if you want to view the source, please visit the github repository of this plugin
*/
varFw=Object.create;var_a=Object.defineProperty;vargw=Object.getOwnPropertyDescriptor;varww=Object.getOwnPropertyNames;varvw=Object.getPrototypeOf,Hw=Object.prototype.hasOwnProperty;varyw=(e,I,l)=>Iine?_a(e,I,{enumerable:!0,configurable:!0,writable:!0,value:l}):e[I]=l;var$p=(e,I)=>()=>(I||e((I={exports:{}}).exports,I),I.exports),uG=(e,I)=>{for(varlinI)_a(e,l,{get:I[l],enumerable:!0})},Io=(e,I,l,G)=>{if(I&&typeofI=="object"||typeofI=="function")for(lettofww(I))!Hw.call(e,t)&&t!==l&&_a(e,t,{get:()=>I[t],enumerable:!(G=gw(I,t))||G.enumerable});returne};varBi=(e,I,l)=>(l=e!=null?Fw(vw(e)):{},Io(I||!e||!e.__esModule?_a(l,"default",{value:e,enumerable:!0}):l,e)),Jw=e=>Io(_a({},"__esModule",{value:!0}),e);var$=(e,I,l)=>yw(e,typeofI!="symbol"?I+"":I,l);varJX=$p(ws=>{"use strict";ws.byteLength=FA;ws.toByteArray=wA;ws.fromByteArray=yA;varit=[],oe=[],LA=typeofUint8Array<"u"?Uint8Array:Array,Mh="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(wd=0,HX=Mh.length;wd<HX;++wd)it[wd]=Mh[wd],oe[Mh.charCodeAt(wd)]=wd;varwd,HX;oe[45]=62;oe[95]=63;functionyX(e){varI=e.length;if(I%4>0)thrownewError("Invalid string. Length must be a multiple of 4");varl=e.indexOf("=");l===-1&&(l=I);varG=l===I?0:4-l%4;return[l,G]}functionFA(e){varI=yX(e),l=I[0],G=I[1];return(l+G)*3/4-G}functiongA(e,I,l){return(I+l)*3/4-l}functionwA(e){varI,l=yX(e),G=l[0],t=l[1],c=newLA(gA(e,G,t)),d=0,b=t>0?G-4:G,a;for(a=0;a<b;a+=4)I=oe[e.charCodeAt(a)]<<18|oe[e.charCodeAt(a+1)]<<12|oe[e.charCodeAt(a+2)]<<6|oe[e.charCodeAt(a+3)],c[d++]=I>>16&255,c[d++]=I>>8&255,c[d++]=I&255;returnt===2&&(I=oe[e.charCodeAt(a)]<<2|oe[e.charCodeAt(a+1)]>>4,c[d++]=I&255),t===1&&(I=oe[e.charCodeAt(a)]<<10|oe[e.charCodeAt(a+1)]<<4|oe[e.charCodeAt(a+2)]>>2,c[d++]=I>>8&255,c[d++]=I&255),c}functionvA(e){returnit[e>>18&63]+it[e>>12&63]+it[e>>6&63]+it[e&63]}functionHA(e,I,l){for(varG,t=[],c=I;c<l;c+=3)G=(e[c]<<16&16711680)+(e[c+1]<<8&65280)+(e[c+2]&255),t.push(vA(G));returnt.join("")}functionyA(e){for(varI,l=e.length,G=l%3,t=[],c=16383,d=0,b=l-G;d<b;d+=c)t.push(HA(e,d,d+c>b?b:d+c));returnG===1?(I=e[l-1],t.push(it[I>>2]+it[I<<4&63]+"==")):G===2&&(I=(e[l-2]<<8)+e[l-1],t.push(it[I>>10]+it[I>>4&63]+it[I<<2&63]+"=")),t.join("")}});varAR=$p(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});require("obsidian");varqt=classextendsError{},b0=classextendsqt{constructor(I){super(`Invalid DateTime: ${I.toMessage()}`)}},a0=classextendsqt{constructor(I){super(`Invalid Interval: ${I.toMessage()}`)}},n0=classextendsqt{constructor(I){super(`Invalid Duration: ${I.toMessage()}`)}},Jd=classextendsqt{},Ds=classextendsqt{constructor(I){super(`Invalid unit ${I}`)}},BG=classextendsqt{},Ct=classextendsqt{constructor(){super("Zone is an abstract class")}},aI="numeric",Se="short",ee="long",fs={year:aI,month:aI,day:aI},AQ={year:aI,month:Se,day:aI},IE={year:aI,month:Se,day:aI,weekday:Se},EQ={year:aI,month:ee,day:aI},kQ={year:aI,month:ee,day:aI,weekday:ee},OQ={hour:aI,minute:aI},KQ={hour:aI,minute:aI,second:aI},xQ={hour:aI,minute:aI,second:aI,timeZoneName:Se},UQ={hour:aI,minute:aI,second:aI,timeZoneName:ee},zQ={hour:aI,minute:aI,hourCycle:"h23"},BQ={hour:aI,minute:aI,second:aI,hourCycle:"h23"},DQ={hour:aI,minute:aI,second:aI,hourCycle:"h23",timeZoneName:Se},fQ={hour:aI,minute:aI,second:aI,hourCycle:"h23",timeZoneName:ee},MQ={year:aI,month:aI,day:aI,hour:aI,minute:aI},jQ={year:aI,month:aI,day:aI,hour:aI,minute:aI,second:aI},SQ={year:aI,month:Se,day:aI,hour:aI,minute:aI},TQ={year:aI,month:Se,day:aI,hour:aI,minute:aI,second:aI},lE={year:aI,month:Se,day:aI,weekday:Se,hour:aI,minute:aI},qQ={year:aI,month:ee,day:aI,hour:aI,minute:aI,timeZoneName:Se},PQ={year:aI,month:ee,day:aI,hour:aI,minute:aI,second:aI,timeZoneName:Se},_Q={year:aI,month:ee,day:aI,weekday:ee,hour:aI,minute:aI,timeZoneName:ee},$Q={year:aI,month:ee,day:aI,weekday:ee,hour:aI,minute:aI,second:aI,timeZoneName:ee},kd=class{gettype(){thrownewCt}getname(){thrownewCt}getianaName(){returnthis.name}getisUniversal(){thrownewCt}offsetName(I,l){thrownewCt}formatOffset(I,l){
`||r.charAt(II)==="\r"&&r.charAt(II+1)!==`
`)&&(lI++,GI===0&&(GI=II+1)),II--}var mI=M+lI,el=v-GI;return O[v]={line:mI,lineStart:GI},{offset:v,line:mI+1,column:el+1}}function x(r){if(!C(r))throw new Error("not a parser: "+r)}function B(r,v){return typeof r=="string"?r.charAt(v):r[v]}function f(r){if(typeof r!="number")throw new Error("not a number: "+r)}function z(r){if(typeof r!="function")throw new Error("not a function: "+r)}function y(r){if(typeof r!="string")throw new Error("not a string: "+r)}var H=2,J=3,_=8,bI=5*_,rI=4*_,QI=" ";function BI(r,v){return new Array(v+1).join(r)}function yI(r,v,O){var M=v-r.length;return M<=0?r:BI(O,M)+r}function hI(r,v,O,M){return{from:r-v>0?r-v:0,to:r+O>M?M:r+O}}function YI(r,v){var O,M,lI,GI,II,mI=v.index,el=mI.offset,Hl=1;if(el===r.length)return"Got the end of the input";if(g(r)){var nl=el-el%_,be=el-nl,Dl=hI(nl,bI,rI+_,r.length),fl=n(function(Kl){return n(function(jd){return yI(jd.toString(16),2,"0")},Kl)},(function(Kl,jd){var Sd=Kl.length,zc=[],Td=0;if(Sd<=jd)return[Kl.slice()];for(var qd=0;qd<Sd;qd++)zc[Td]||zc.push([]),zc[Td].push(Kl[qd]),(qd+1)%jd==0&&Td++;return zc})(r.slice(Dl.from,Dl.to).toJSON().data,_));GI=(function(Kl){return Kl.from===0&&Kl.to===1?{from:Kl.from,to:Kl.to}:{from:Kl.from/_,to:Math.floor(Kl.to/_)}})(Dl),M=nl/_,O=3*be,be>=4&&(O+=1),Hl=2,lI=n(function(Kl){return Kl.length<=4?Kl.join(" "):Kl.slice(0,4).join(" ")+" "+Kl.slice(4).join(" ")},fl),(II=(8*(GI.to>0?GI.to-1:GI.to)).toString(16).length)<2&&(II=2)}else{var Ml=r.split(/\r\n|[\n\r\u2028\u2029]/);O=mI.column-1,M=mI.line-1,GI=hI(M,H,J,Ml.length),lI=Ml.slice(GI.from,GI.to),II=GI.to.toString().length}var Cl=M-GI.from;return g(r)&&(II=(8*(GI.to>0?GI.to-1:GI.to)).toString(16).length)<2&&(II=2),a(function(Kl,jd,Sd){var zc,Td=Sd===Cl,qd=Td?"> ":QI;return zc=g(r)?yI((8*(GI.from+Sd)).toString(16),II,"0"):yI((GI.from+Sd+1).toString(),II," "),[].concat(Kl,[qd+zc+" | "+jd],Td?[QI+BI(" ",II)+" | "+yI("",O," ")+BI("^",Hl)]:[])},[],lI).join(`
`)}function DI(r,v){return[`
`,"-- PARSING FAILED "+BI("-",50),`
`,YI(r,v),`
`,(O=v.expected,O.length===1?`Expected:
`+O[0]:`Expectedoneofthefollowing:
`+O.join(", ")),`
`].join("");var O}function gG(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 kG(){for(var r=[].slice.call(arguments),v=r.length,O=0;O<v;O+=1)x(r[O]);return c(function(M,lI){for(var GI,II=new Array(v),mI=0;mI<v;mI+=1){if(!(GI=R(r[mI]._(M,lI),GI)).status)return GI;II[mI]=GI.value,lI=GI.index}return R(X(lI,II),GI)})}function OG(){var r=[].slice.call(arguments);if(r.length===0)throw new Error("seqMap needs at least one argument");var v=r.pop();return z(v),kG.apply(null,r).map(function(O){return v.apply(null,O)})}function nG(){var r=[].slice.call(arguments),v=r.length;if(v===0)return T("zero alternates");for(var O=0;O<v;O+=1)x(r[O]);return c(function(M,lI){for(var GI,II=0;II<r.length;II+=1)if((GI=R(r[II]._(M,lI),GI)).status)return GI;return GI})}function ye(r,v){return jG(r,v).or(YG([]))}function jG(r,v){return x(r),x(v),OG(r,v.then(r).many(),function(O,M){return[O].concat(M)})}function SG(r){y(r);var v="'"+r+"'";return c(function(O,M){var lI=M+r.length,GI=O.slice(M,lI);return GI===r?X(lI,GI):w(M,v)})}function sG(r,v){(function(lI){if(!(lI instanceof RegExp))throw new Error("not a regexp: "+lI);for(var GI=gG(lI),II=0;II<GI.length;II++){var mI=GI.charAt(II);if(mI!=="i"&&mI!=="m"&&mI!=="u"&&mI!=="s")throw new Error('unsupported regexp flag "'+mI+'": '+lI)}})(r),arguments.length>=2?f(v):v=0;var O=(function(lI){return RegExp("^(?:"+lI.source+")",gG(lI))})(r),M=""+r;return c(function(lI,GI){var II=O.exec(lI.slice(GI));if(II){if(0<=v&&v<=II.length){var mI=II[0],el=II[v];return X(GI+mI.length,el)}return w(GI,"valid match group (0 to "+II.length+") in "+M)}return w(GI,M)})}function YG(r){return c(function(v,O){return X(O,r)})}function T(r){return c(function(v,O){return w(O,r)})}function KI(r){if(C(r))return c(function(v,O){var M=r._(v,O);return M.index=O,M.value="",M});if(typeof r=="string")return KI(SG(r));if(r instanceof RegExp)return KI(sG(r));throw new Error("not a string, regexp, or parser: "+r)}function fI(r){return x(r),c(function(v,O){var M=r._(v,O),lI=v.slice(O,M.index);return M.status?w(O,'not "'+lI+'"'):X(O,null)})}function qI(r){return z(r),c(function(v,O){var M=B(v,O);return O<v.length&&r(M)?X(O+1,M):w(O,"a character/byte matching "+r)})}function ce(r,v){arguments.length<2&&(v=r,r=void 0);var O=c(function(M,lI){return O._=v()._,O._(M,lI)});return r?O.desc(r):O}function iG(){return T("fantasy-land/empty")}d.parse=function(r){if(typeof r!="string"&&!g(r))throw new Error(".parse must be called with a string or Buffer as its argument");var v,O=this.skip(de)._(r,0);return v=O.status?{status:!0,value:O.value}:{status:!1,index:j(r,O.furthest),expected:O.expected},delete A[r],v},d.tryParse=function(r){var v=this.parse(r);if(v.status)return v.value;var O=DI(r,v),M=new Error(O);throw M.type="ParsimmonError",M.result=v,M},d.assert=function(r,v){return this.chain(function(O){return r(O)?YG(O):T(v)})},d.or=function(r){return nG(this,r)},d.trim=function(r){return this.wrap(r,r)},d.wrap=function(r,v){return OG(r,this,v,function(O,M){return M})},d.thru=function(r){return r(this)},d.then=function(r){return x(r),kG(this,r).map(function(v){return v[1]})},d.many=function(){var r=this;return c(function(v,O){for(var M=[],lI=void 0;;){if(!(lI=R(r._(v,O),lI)).status)return R(X(O,M),lI);if(O===lI.index)throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause");O=lI.index,M.push(lI.value)}})},d.tieWith=function(r){return y(r),this.map(function(v){if((function(lI){if(!Q(lI))throw new Error("not an array: "+lI)})(v),v.length){y(v[0]);for(var O=v[0],M=1;M<v.length;M++)y(v[M]),O+=r+v[M];return O}return""})},d.tie=function(){return this.tieWith("")},d.times=function(r,v){var O=this;return arguments.length<2&&(v=r),f(r),f(v),c(function(M,lI){for(var GI=[],II=void 0,mI=void 0,el=0;el<r;el+=1){if(mI=R(II=O._(M,lI),mI),!II.status)return mI;lI=II.index,GI.push(II.value)}for(;el<v&&(mI=R(II=O._(M,lI),mI),II.status);el+=1)lI=II.index,GI.push(II.value);return R(X(lI,GI),mI)})},d
`),Uc=SG(`\r
`),Ee=nG(Uc,Pa,xc).desc("newline"),qW=nG(Ee,de);c.all=yt,c.alt=nG,c.any=Ic,c.cr=xc,c.createLanguage=function(r){varv={};for(varOinr)({}).hasOwnProperty.call(r,O)&&(function(M){v[M]=ce(function(){returnr[M](v)})})(O);returnv},c.crlf=Uc,c.custom=function(r){returnc(r(X,w))},c.digit=lc,c.digits=Kc,c.empty=iG,c.end=qW,c.eof=de,c.fail=T,c.formatError=DI,c.index=TG,c.isParser=C,c.lazy=ce,c.letter=Gc,c.letters=Je,c.lf=Pa,c.lookahead=KI,c.makeFailure=w,c.makeSuccess=X,c.newline=Ee,c.noneOf=function(r){returnqI(function(v){returnr.indexOf(v)<0}).desc("none of '"+r+"'")},c.notFollowedBy=fI,c.of=YG,c.oneOf=function(r){for(varv=r.split(""),O=0;O<v.length;O++)v[O]="'"+v[O]+"'";returnqI(function(M){returnr.indexOf(M)>=0}).desc(v)},c.optWhitespace=TW,c.Parser=c,c.range=function(r,v){returnqI(function(O){returnr<=O&&O<=v}).desc(r+"-"+v)},c.regex=sG,c.regexp=sG,c.sepBy=ye,c.sepBy1=jG,c.seq=kG,c.seqMap=OG,c.seqObj=function(){for(varr,v={},O=0,M=(r=arguments,Array.prototype.slice.call(r)),lI=M.length,GI=0;GI<lI;GI+=1){varII=M[GI];if(!C(II)){if(Q(II)&&II.length===2&&typeofII[0]=="string"&&C(II[1])){varmI=II[0];if(Object.prototype.hasOwnProperty.call(v,mI))thrownewError("seqObj: duplicate key "+mI);v[mI]=!0,O++;continue}thrownewError("seqObj arguments must be parsers or [string, parser] array pairs.")}}if(O===0)thrownewError("seqObj expects at least one named parser, found zero");returnc(function(el,Hl){for(varnl,be={},Dl=0;Dl<lI;Dl+=1){varfl,Ml;if(Q(M[Dl])?(fl=M[Dl][0],Ml=M[Dl][1]):(fl=null,Ml=M[Dl]),!(nl=R(Ml._(el,Hl),nl)).status)returnnl;fl&&(be[fl]=nl.value),Hl=nl.index}returnR(X(Hl,be),nl)})},c.string=SG,c.succeed=YG,c.takeWhile=function(r){returnz(r),c(function(v,O){for(varM=O;M<v.length&&r(B(v,M));)M++;returnX(M,v.slice(O,M))})},c.test=qI,c.whitespace=Ae,c["fantasy-land/empty"]=iG,c["fantasy-land/of"]=YG,c.Binary={bitSeq:N,bitSeqObj:function(r){W();varv={},O=0,M=n(function(GI){if(Q(GI)){varII=GI;if(II.length!==2)thrownewError("["+II.join(", ")+"] should be length 2, got length "+II.length);if(y(II[0]),f(II[1]),Object.prototype.hasOwnProperty.call(v,II[0]))thrownewError("duplicate key in bitSeqObj: "+II[0]);returnv[II[0]]=!0,O++,II}returnf(GI),[null,GI]},r);if(O<1)thrownewError("bitSeqObj expects at least one named pair, got ["+r.join(", ")+"]");varlI=n(function(GI){returnGI[0]},M);returnN(n(function(GI){returnGI[1]},M)).map(function(GI){returna(function(II,mI){returnmI[0]!==null&&(II[mI[0]]=mI[1]),II},{},n(function(II,mI){return[II,GI[mI]]},lI))})},byte:function(r){if(W(),f(r),r>255)thrownewError("Value specified to byte constructor ("+r+"=0x"+r.toString(16)+") is larger in value than a single byte.");varv=(r>15?"0x":"0x0")+r.toString(16);returnc(function(O,M){varlI=B(O,M);returnlI===r?X(M+1,lI):w(M,v)})},buffer:function(r){returns("buffer",r).map(function(v){returnBuffer.from(v)})},encodedString:function(r,v){returns("string",v).map(function(O){returnO.toString(r)})},uintBE:Y,uint8BE:Y(1),uint16BE:Y(2),uint32BE:Y(4),uintLE:p,uint8LE:p(1),uint16LE:p(2),uint32LE:p(4),intBE:u,int8BE:u(1),int16BE:u(2),int32BE:u(4),intLE:o,int8LE:o(1),int16LE:o(2),int32LE:o(4),floatBE:s("floatBE",4).map(function(r){returnr.readFloatBE(0)}),floatLE:s("floatLE",4).map(function(r){returnr.readFloatLE(0)}),doubleBE:s("doubleBE",8).map(function(r){returnr.readDoubleBE(0)}),doubleLE:s("doubleLE",8).map(function(r){returnr.readDoubleLE(0)})},l.exports=c}])})})(Ps,Ps.exports);varF=Ps.exports,J0=()=>/[#*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\u29
`)}functionln(e){letI=Object.entries(e);if(I.length===0)return[];letG=["t","tm","yd"].map(d=>{letb=e[d];returnb?[d,b]:null}).filter(d=>d!==null),t=newSet(G.map(([d])=>d)),c=I.filter(([d])=>!t.has(d)).sort((d,b)=>{leta=d[0].length-b[0].length;returna!==0?a:d[0].localeCompare(b[0])});return[...G,...c]}functioncN(e){returnln(e).map(([I,l])=>`${I}=${l}`).join(", ")}vardN={choices:[],inputPrompt:"single-line",persistInputPromptDrafts:!0,useSelectionAsCaptureValue:!0,devMode:!1,templateFolderPath:"",announceUpdates:"major",version:"0.0.0",globalVariables:{},onePageInputEnabled:!1,disableOnlineFeatures:!0,enableRibbonIcon:!1,showCaptureNotification:!0,showInputCancellationNotification:!1,enableTemplatePropertyTypes:!1,dateAliases:Ib,ai:{defaultModel:"Ask me",defaultSystemPrompt:'As an AI assistant within Obsidian, your primary goal is to help users manage their ideas and knowledge more effectively. Format your responses using Markdown syntax. Please use the [[Obsidian]] link format. You can write aliases for the links by writing [[Obsidian|the alias after the pipe symbol]]. To use mathematical notation, use LaTeX syntax. LaTeX syntax for larger equations should be on separate lines, surrounded with double dollar signs ($$). You can also inline math expressions by wrapping it in $ symbols. For example, use $$w_{ij}^{\\text{new}}:=w_{ij}^{\\text{current}}+\\eta\\cdot\\delta_j\\cdot x_{ij}$$ on a separate line, but you can write "($\\eta$ = learning rate, $\\delta_j$ = error term, $x_{ij}$ = input)" inline.',promptTemplatesFolderPath:"",showAssistant:!0,providers:tN},migrations:{migrateToMacroIDFromEmbeddedMacro:!0,useQuickAddTemplateFolder:!1,incrementFileNameSettingMoveToDefaultBehavior:!1,consolidateFileExistsBehavior:!1,repairTemplateFileExistsBehavior:!1,mutualExclusionInsertAfterAndWriteToBottomOfFile:!1,setVersionAfterUpdateModalRelease:!1,addDefaultAIProviders:!1,removeMacroIndirection:!1,migrateFileOpeningSettings:!1,backfillFileOpeningDefaults:!1,setProviderModelDiscoveryMode:!1,migrateProviderApiKeysToSecretStorage:!1}};functionjI(e){letl=(typeofwindow<"u"?window:globalThis).structuredClone;if(typeofl=="function")try{returnl(e)}catch{}returncc(e,newMap)}functioncc(e,I){if(e===null||typeofe!="object")returne;if(I.has(e))returnI.get(e);if(einstanceofDate){lett=newDate(e.getTime());returnI.set(e,t),t}if(Array.isArray(e)){lett=[];I.set(e,t);for(letcofe)t.push(cc(c,I));returnt}if(einstanceofMap){lett=newMap;I.set(e,t);for(let[c,d]ofe.entries())t.set(cc(c,I),cc(d,I));returnt}if(einstanceofSet){lett=newSet;I.set(e,t);for(letcofe.values())t.add(cc(c,I));returnt}if(einstanceofRegExp){lett=newRegExp(e.source,e.flags);returnt.lastIndex=e.lastIndex,I.set(e,t),t}if(einstanceofArrayBuffer){lett=e.slice(0);returnI.set(e,t),t}if(ArrayBuffer.isView(e)){if(einstanceofDataView){letb=newDataView(cc(e.buffer,I),e.byteOffset,e.byteLength);returnI.set(e,b),b}lett=e,c=cc(t.buffer,I),d=newt.constructor(c,t.byteOffset,t.length);returnI.set(e,d),d}letl=Object.getPrototypeOf(e),G=Object.create(l);I.set(e,G);for(let[t,c]ofObject.entries(e))Object.defineProperty(G,t,{value:cc(c,I),writable:!0,enumerable:!0,configurable:!0});returnG}varS=(()=>{lete=so((t,c)=>({...jI(dN)})),{getState:I,setState:l,subscribe:G}=e;return{getState:I,replaceState:t=>l(t,!0),setState:l,subscribe:G}})();varLI=require("obsidian");varjc="{{value}}",$i="{{date}}",io="{{time}}",Iu="{{name}}",$w="{{value:<variable name>}}",Iv="{{value:<variable name>|<default value>}}",lv="{{value:<variable name>|default:<value>}}",Gv="{{value:<variable name>|label:<helper text>}}",ev="{{value:<items>|text:<display items>}}",tv="{{value|case:kebab}}",cv="{{value:<variable name>|case:kebab}}",dv="{{field:<field name>}}",uo="{{mvalue}}",Co="{{linkcurrent}}",ho="{{filenamecurrent}}",po="{{title}}",oo="{{selected}}",Vo="{{clipboard}}",bv="{{random:<length>}}",av="{{global_var:<name>}}";varro=[$i,"{{date:<dateformat>}}","{{vdate:<variable name>, <date format>}}","{{vdate:<variable name>, <date format>|<default value>}}",av,jc,Iu,t
`+e,{line:d,ch:Z.length}),t.setCursor({line:d+a,ch:n})}}catch{k.logError(`unable to insert '${e}' on new line ${I}.`)}}functionVr(e,I){or(e,"above",I)}functionrr(e,I){or(e,"below",I)}functionv5(e,I,l="replaceSelection",G={}){let{requireActiveView:t=!0}=G,c=e.workspace.getActiveViewOfType(wG.MarkdownView);if(!c){letZ="Cannot append link because no active Markdown view is available.";if(t)thrownewError(Z);k.logMessage(Z);return}letd=c.editor,b=d.listSelections().map(Z=>({anchor:{...Z.anchor},head:{...Z.head}}));if(l==="replaceSelection"){d.replaceSelection(I);return}leta=({line:Z,ch:m})=>d.posToOffset({line:Z,ch:m}),n=b.sort((Z,m)=>a(m.head)-a(Z.head));for(letZofn){letm=a(Z.anchor)>a(Z.head)?Z.anchor:Z.head;switch(l){case"afterSelection":{d.replaceRange(I,m);break}case"endOfLine":{letW=d.getLine(m.line),N={line:m.line,ch:W.length};d.replaceRange(I,N);break}case"newLine":{letW=d.getLine(m.line),N={line:m.line,ch:W.length},i=W.length===0?"":`
`;d.replaceRange(i+I,N);break}}}}functionH5(e){letI=/^\s*!?\[[^\]]*\]\((.+)\)\s*$/,l=e.match(I);if(!l)returnnull;letG=l[1].trim();returnG?(G.startsWith("<")&&G.endsWith(">")&&(G=G.slice(1,-1).trim()),G):null}functiony5(e){letI=e.trim();if(I.startsWith("![[")&&I.includes("]]"))returne;letl=e.indexOf("[["),G=e.indexOf("]]",l+2);if(l!==-1&&G!==-1)return(l>0?e.charAt(l-1):"")==="!"?e:`${e.slice(0,l)}!${e.slice(l)}`;lett=H5(e);returnt?`![[${t}]]`:e.startsWith("!")?e:`!${e}`}functionSN(e,I,l){if(!l?.enabled)return!1;letG=e.workspace.getActiveFile();if(!G&&l.requireActiveFile)thrownewError("Append link is enabled but there's no active file to insert into.");if(!e.workspace.getActiveViewOfType(wG.MarkdownView)){if(l.requireActiveFile)thrownewError("Cannot append link because no active Markdown view is available.");return!1}letc=G?.path??"",d=e.fileManager.generateMarkdownLink(I,c),a=l.linkType==="embed"&&xt(l.placement)?y5(d):d;returnv5(e,a,l.placement,{requireActiveView:!1}),!0}functionJ5(e,I){returne.commands.findCommand(I)}functionXr(e,I){J5(e,I)&&(deletee.commands.commands[I],deletee.commands.editorCommands[I])}functionud(e){returne.vault.getAllLoadedFiles().filter(I=>IinstanceofwG.TFolder).map(I=>I.path)}functionBm(e){letI=e.split("::").map(l=>l.trim()).filter(Boolean);return{basename:I[0],memberAccess:I.slice(1)}}functionQr(e){if(!e)return!1;letI=e,l=I.getViewState?.();return!!I.pinned||!!l?.pinned||!!l?.state?.pinned}functiondh(e){letI=e.workspace;return(I.rootSplit?I.getMostRecentLeaf?.(I.rootSplit):null)??I.getMostRecentLeaf?.()??I.activeLeaf??null}functionA5(e){letI=[];returne.workspace.iterateRootLeaves(l=>{I.includes(l)||I.push(l)}),I}functionir(e){returne.parent?.id??e.parent??null}functionE5(e,I){letl=ir(I),G=e.filter(d=>d===I||Qr(d)?!1:l===null||ir(d)!==l);if(G.length===0)returnnull;lett=e.indexOf(I);return(t===-1?e:[...e.slice(t+1),...e.slice(0,t)]).find(d=>G.includes(d))??G[0]}functionk5(e){returneinstanceofwG.TFile?!0:typeofe=="object"&&e!==null&&"path"ine&&typeofe.path=="string"}functionO5(e,I,l,G){if(G&&(I==="tab"||I==="reuse")&&Qr(G))returnE5(A5(e),G)??e.workspace.getLeaf("tab");switch(I){case"reuse":returne.workspace.getLeaf(!1);case"tab":returne.workspace.getLeaf("tab");case"split":returne.workspace.getLeaf("split",l);case"window":returne.workspace.getLeaf("window");case"left-sidebar":returne.workspace.getLeftLeaf(!0);case"right-sidebar":returne.workspace.getRightLeaf(!0);default:returne.workspace.getLeaf("tab")}}asyncfunctionCd(e,I,l={}){let{location:G="tab",direction:t="vertical",mode:c,focus:d=!0,eState:b,originLeaf:a}=l,n=typeofI=="string"?e.vault.getAbstractFileByPath(I):I;if(!k5(n)){letW=typeofI=="string"?I:I.path;thrownewError(`File not found: ${W}`)}letZ=a??dh(e),m=O5(e,G,t,Z);if(!m)thrownewError("Could not obtain a workspace leaf.");if(awaitm.openFile(n),c&&c!=="default"&&!(typeofc=="object"&&c.mode==="default")){letW=m.getViewState(),N={...W.state??{}};c==="preview"||typeofc=="object"&&c.mode==="preview"?(N.mode="preview",deleteN.source):c==="source"?(N.mode="source",N.source=!0):c==="live"||c==="live-preview"?(N.mode="source",N.source=!1):typeofc=="object"&&c.mode==="source"&&(N.mode="source",N.source=c.source),awaitm.setViewState({...W,state:{...N,...b}})}returnd&&e.workspace.setActiveLeaf(m,{focus:!0}),m}functionur(e){return(0,wG.normalizePath)(e).replace(/\/{2,}/g,"/").replace(/^\/+/,"")}functionK5(e,I){returnur(e)===ur(I)}functionDm(e,I,l=!0){letG;returne.workspace.iterateRootLeaves(t=>{letc=t.view;if(cinstanceofwG.FileView&&c.file&&(c.file===I||K5(I.path,c.file.path))){G=t;return}}),G!==void0?(l&&e.workspace.setActiveLeaf(G,{focus:!0}),G):null}asyncfunctionZt(e,I){letl=I.vault.getAbstractFileByPath(e.path);if(!l){k.logError(`failed to load file ${e.path}.`);return}if(linstanceofwG.TFile){letG=m=>window.require&&window.require(m),t={},c={exports:t},d=awaitI.vault.read(l);window.eval(`(function(require, module, exports) { ${d}
`).filter(Boolean).reduce((G,t)=>{let[c,d,...b]=t.split(""),a=Number.parseInt(d,10);return b.forEach((n,Z)=>G[n]=a+Z),G},{});for(let[G,t]of Object.entries(l)){let c=AX.default.toByteArray(G);this.rankMap.set(c.join(","),t),this.textMap.set(t,c)}this.specialTokens={...e.special_tokens,...I},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((G,[t,c])=>(G[c]=this.textEncoder.encode(t),G),{})}encode(e,I=[],l="all"){let G=new RegExp(this.patStr,"ug"),t=jh.specialTokenRegex(Object.keys(this.specialTokens)),c=[],d=new Set(I==="all"?Object.keys(this.specialTokens):I),b=new Set(l==="all"?Object.keys(this.specialTokens).filter(n=>!d.has(n)):l);if(b.size>0){let n=jh.specialTokenRegex([...b]),Z=e.match(n);if(Z!=null)throw new Error(`The text contains a special token that is not allowed: ${Z[0]}`)}let a=0;for(;;){let n=null,Z=a;for(;t.lastIndex=Z,n=t.exec(e),!(n==null||d.has(n[0]));)Z=n.index+1;let m=n?.index??e.length;for(let N of e.substring(a,m).matchAll(G)){let s=this.textEncoder.encode(N[0]),i=this.rankMap.get(s.join(","));if(i!=null){c.push(i);continue}c.push(...OA(s,this.rankMap))}if(n==null)break;let W=this.specialTokens[n[0]];c.push(W),a=n.index+n[0].length}return c}decode(e){let I=[],l=0;for(let c=0;c<e.length;++c){let d=e[c],b=this.textMap.get(d)??this.inverseSpecialTokens[d];b!=null&&(I.push(b),l+=b.length)}let G=new Uint8Array(l),t=0;for(let c of I)G.set(c,t),t+=c.length;return this.textDecoder.decode(G)}},vs=jh;EA(vs,"specialTokenRegex",e=>new RegExp(e.map(I=>KA(I)).join("|"),"g"));function Sh(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"
${I}`:""}`;functionJs(e){if(e){letI=newBX.Notice(zX("starting",""),1e6);return{setMessage:(l,G)=>{I.setMessage(zX(l,G))},hide:()=>I.hide()}}return{setMessage:()=>{},hide:()=>{}}}varDX={cl100k_base:EX,o200k_base:kX},fX=newMap;functionMA(e){letI=einDX?e:"cl100k_base",l=fX.get(I);if(l)returnl;letG=newvs(DX[I]);returnfX.set(I,G),G}varIe=(e,I)=>{letl="cl100k_base";try{l=Sh(I.name)}catch{l="cl100k_base"}return(l==="p50k_base"||l==="p50k_edit"||l==="r50k_base"||l==="gpt2")&&(l="cl100k_base"),MA(l).encode(e).length},MX=25,Ve=[];functionPh(e){return{...e,modelOptions:{...e.modelOptions},usage:e.usage?{...e.usage}:void0}}functionUX(e){letI=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,l=Date.now();returnVe.push({...e,modelOptions:{...e.modelOptions??{}},id:I,createdAt:l,status:"pending"}),TX(),I}functionTh(e,I){letl=Ve.find(G=>G.id===e);l&&(l.status=I.status,l.durationMs=I.durationMs,l.usage=I.usage,l.errorMessage=I.errorMessage,TX())}functionSX(e=10){Number.isFinite(e)||(e=10);letI=Math.floor(e);returnI<=0?[]:Ve.slice(-I).map(Ph).reverse()}functionTX(){if(Ve.length<=MX)return;lete=Ve.length-MX;for(;e>0;){letI=Ve.findIndex(l=>l.status!=="pending");if(I===-1)break;Ve.splice(I,1),e-=1}}functionqX(e){letI=Ve.find(l=>l.id===e);returnI?Ph(I):null}functionPX(){lete=Ve[Ve.length-1];returne?Ph(e):null}function_X(){Ve.splice(0,Ve.length)}asyncfunctionjA(e,I,l){if(typeofe!="function")thrownewTypeError("Callback must be a function.");if(!(IinstanceofPromise))thrownewTypeError("Promise must be an instance of Promise.");if(typeofl!="number"||l<=0)thrownewTypeError("Interval must be a positive number.");letG=!1;for(I.then(()=>{G=!0},()=>{G=!0});!G;)e(),awaitsleep(l)}functionSA(e){returneinstanceofError?e:newError(String(e))}asyncfunctionTA(e,I,l){letG;if(I.enable)G=l.find(b=>b.path.endsWith(I.name));else{letb=l.map(a=>a.basename);G=awaitVG.Suggest(e,b,l)}$G(G,"Prompt template does not exist");lett=G.path,c=e.vault.getAbstractFileByPath(t);$G(cinstanceofjX.TFile,`${t} is not a file`);letd=awaite.vault.cachedRead(c);return[G.basename,d]}asyncfunction$X(e,I,l){if(S.getState().disableOnlineFeatures)thrownewError("Blocking request to OpenAI: Online features are disabled in settings.");letG=Js(I.showAssistantMessages);try{let{apiKey:t,model:c,outputVariableName:d,promptTemplate:b,systemPrompt:a,promptTemplateFolder:n}=I,Z=sc(e,n),[m,W]=awaitTA(e,b,Z);G.setMessage("waiting","QuickAdd is formatting the prompt template.");letN=awaitl(W),s=["prompting",`Using prompt template "${m}".`];G.setMessage(s[0],s[1]);letY=ys(e,t,c,a,I.modelOptions)(N),u=(await_h(Y,100,Q=>{G.setMessage(s[0],`${s[1]} (${(Q/1e3).toFixed(2)}s)`)},Q=>{G.setMessage("finished",`Took ${(Q/1e3).toFixed(2)}s.`)})).content,o=("> "+u).replace(/\n/g,`
> `),C={[d]:u,[`${d}-quoted`]:o};returnwindow.setTimeout(()=>G.hide(),5e3),C}catch(t){throwG.setMessage("dead",t.message),window.setTimeout(()=>G.hide(),5e3),ol(t)?newvI("Input cancelled by user"):t}}asyncfunction_h(e,I,l,G){lett=Date.now();returnawaitjA(()=>l(Date.now()-t),e,I),G(Date.now()-t),awaite}asyncfunctionIQ(e,I,l){if(S.getState().disableOnlineFeatures)thrownewError("Blocking request to OpenAI: Online features are disabled in settings.");letG=Js(I.showAssistantMessages);try{let{apiKey:t,model:c,outputVariableName:d,systemPrompt:b,prompt:a,modelOptions:n}=I;G.setMessage("waiting","QuickAdd is formatting the prompt template.");letZ=awaitl(a),m=["prompting","Using custom prompt."];G.setMessage(m[0],m[1]);letN=ys(e,t,c,b,n)(Z),i=(await_h(N,100,u=>{G.setMessage(m[0],`${m[1]} (${(u/1e3).toFixed(2)}s)`)},u=>{G.setMessage("finished",`Took ${(u/1e3).toFixed(2)}s.`)})).content,Y=("> "+i).replace(/\n/g,`
> `),p={[d]:i,[`${d}-quoted`]:Y};returnwindow.setTimeout(()=>G.hide(),5e3),p}catch(t){throwG.setMessage("dead",t.message),window.setTimeout(()=>G.hide(),5e3),t}}varqh=class{constructor(I,l){this.maxRequests=I;this.intervalMs=l;this.queue=[];this.pendingPromises=[]}add(I){returnnewPromise((l,G)=>{this.queue.push(async()=>{try{l(awaitI())}catch(t){G(SA(t))}}),this.schedule()})}schedule(){if(this.queue.length===0||this.pendingPromises.length>=this.maxRequests)return;letI=this.queue.shift();if(!I)return;letl=I();this.pendingPromises.push(l),l.then(()=>{this.pendingPromises=this.pendingPromises.filter(G=>G!==l),this.schedule()},()=>{this.pendingPromises=this.pendingPromises.filter(G=>G!==l),this.schedule()}),window.setTimeout(()=>this.schedule(),this.intervalMs)}};asyncfunctionlQ(e,I,l){if(S.getState().disableOnlineFeatures)thrownewError("Blocking request to OpenAI: Online features are disabled in settings.");letG=Js(I.showAssistantMessages);try{let{apiKey:t,model:c,outputVariableName:d,systemPrompt:b,promptTemplate:a,text:n,modelOptions:Z}=I;G.setMessage("chunking","Creating prompt chunks with text and prompt template");letm=I.chunkSeparator||/\n/g,W=n.split(m),N=Ie(b,c),s=awaitl(a,{chunk:" "}),i=Ie(s,c),Y=xX(c.name)/2-N,p=I.shouldMerge??!0,u=[],o=Y-i;if(p){letB=[],f="",z=0;for(letyofW){letH=Ie(y,c)+1;if(H>o)thrownewError(`The chunk "${y.slice(0,25)}..." is too large to fit in a single prompt.`);z+H<o?(f+=y,z+=H):(B.push(f),f=y,z=H)}f!==""&&B.push(f);for(letyofB){letH=awaitl(a,{chunk:y});u.push(H)}}elsefor(letBofW){letf=Ie(B,c);if(f>Y)thrownewError(`Chunk size (${f}) is larger than the maximum chunk size (${Y}). Please check your chunk separator.`);letz=awaitl(a,{chunk:B});u.push(z)}letC=ys(e,t,c,b,Z),Q=["prompting",`${u.length} prompts being sent.`];G.setMessage(Q[0],Q[1]);letg=newqh(5,1e3*30),X=Promise.all(u.map(B=>g.add(()=>C(B)))),A=(await_h(X,100,B=>{G.setMessage(Q[0],`${Q[1]} (${(B/1e3).toFixed(2)}s)`)},B=>{G.setMessage("finished",`Took ${(B/1e3).toFixed(2)}s.`)})).map(B=>B.content).join(I.resultJoiner),j=("> "+A).replace(/\n/g,`
> `),x={[d]:A,[`${d}-quoted`]:j};returnwindow.setTimeout(()=>G.hide(),5e3),x}catch(t){throwG.setMessage("dead",t.message),window.setTimeout(()=>G.hide(),5e3),t}}varqA="quickadd-ai";functionPA(e){returne.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function_A(e){letI=e.name?.trim()||"provider";return`${qA}-${PA(I)}`}asyncfunctionGQ(e,I){if(!e?.secretStorage?.getSecret)returnnull;try{returnawaitPromise.resolve(e.secretStorage.getSecret(I))}catch(l){returnk.logWarning(`Failed to read SecretStorage entry "${I}": ${l.message??l}`),null}}asyncfunctionSt(e,I){letl=I.apiKeyRef?.trim();if(l){letG=awaitGQ(e,l);if(G)returnG}returnI.apiKey??""}asyncfunctioneQ(e,I,l){letG=l?.trim();if(!G||!e?.secretStorage?.getSecret||!e.secretStorage?.setSecret)returnnull;lett=_A(I),c=t,d=1;for(;;){letb=awaitGQ(e,c);if(!b)break;if(b===G)returnc;d+=1,c=`${t}-${d}`}try{returnawaitPromise.resolve(e.secretStorage.setSecret(c,G)),c}catch(b){returnk.logWarning(`Failed to write SecretStorage entry "${c}": ${b.message??b}`),null}}varPb=require("obsidian"),tW=classeextendsPb.Modal{constructor(l,G,t=[]){super(l);this.items=G;this.selectedItems=t;this._selectedItems=[...t],this.promise=newPromise((c,d)=>{this.resolvePromise=c,this.rejectPromise=d}),this.display(),this.open()}staticOpen(l,G,t){returnnewe(l,G,t).promise}display(){this.contentEl.empty(),this.containerEl.addClass("quickAddModal","checkboxPrompt"),this.addCheckboxRows(),this.addSubmitButton()}onClose(){super.onClose(),this.resolved||this.rejectPromise("no input given.")}addCheckboxRows(){letl=this.contentEl.createDiv("checkboxRowContainer");this.items.forEach(G=>this.addCheckboxRow(G,l))}addCheckboxRow(l,G){lett=G.createDiv("checkboxRow");t.createEl("span",{text:l}),newPb.ToggleComponent(t).setTooltip(`Toggle ${l}`).setValue(this._selectedItems.contains(l)).onChange(d=>{if(d)this._selectedItems.push(l);else{letb=this._selectedItems.findIndex(a=>l===a);this._selectedItems.splice(b,1)}})}addSubmitButton(){letl=this.contentEl.createDiv("submitButtonContainer");newPb.ButtonComponent(l).setButtonText("Submit").setCta().onClick(t=>{this.resolved=!0,this.resolvePromise(this._selectedItems),this.close()})}};varAs=require("obsidian"),cW=classeextendsAs.Modal{constructor(l,G,t){super(l);this.header=G;this.text=t;this.waitForClose=newPromise(c=>{this.resolvePromise=c}),this.open(),this.display()}staticShow(l,G,t){returnnewe(l,G,t).waitForClose}display(){this.contentEl.empty(),this.titleEl.textContent=this.header,String.isString(this.text)?this.contentEl.createEl("p",{text:this.text}):Array.isArray(this.text)&&this.text.forEach(t=>this.contentEl.createEl("p",{text:t}));letl=this.contentEl.createDiv(),G=newAs.ButtonComponent(l).setButtonText("OK").onClick(()=>this.close());Object.assign(l.style,{display:"flex",justifyContent:"flex-end"}),G.buttonEl.focus()}onClose(){super.onClose(),this.resolvePromise()}};var_b=require("obsidian");varoc=classeextends_b.Modal{constructor(l,G,t,c,d,b){super(l);this.header=G;this.linkSourcePath=d;this.didSubmit=!1;this.submitClickCallback=l=>this.submit();this.cancelClickCallback=l=>this.cancel();this.submitEnterCallback=l=>{(l.ctrlKey||l.metaKey)&&l.key==="Enter"&&(l.preventDefault(),this.submit())};this.placeholder=t??"",this.description=b?.trim()||void0,this.draftHandler=newSb({kind:"multi",header:this.header,placeholder:this.placeholder,linkSourcePath:this.linkSourcePath}),this.input=this.draftHandler.hydrate(c??""),this.waitForClose=newPromise((a,n)=>{this.resolvePromise=a,this.rejectPromise=n}),this.display(),this.open(),this.fileSuggester=newfb(l,this.inputComponent.inputEl,{sourcePath:this.linkSourcePath}),this.tagSuggester=newMb(l,this.inputComponent.inputEl)}staticPrompt(l,G,t,c,d){returnnewe(l,G,t,c,void0,d).waitForClose}staticPromptWithContext(l,G,t,c,d,b){returnnewe(l,G,t,c,d,b).waitForClose}display(){if(this.containerEl.addClass("quickAddModal","qaWideInputPrompt"),this.contentEl.empty(),this.titleEl.textContent=this.header,this.description){letG=this.contentEl.cr
`,shouldMerge:b?.shouldMerge??!0},(u,o)=>{let C={...a,...o};return m(u,C,!1)});return p?(b?.shouldAssignVariables&&Object.entries(p).forEach(([u,o])=>{G.variables.set(u,o)}),p):(al(new Error("AI Assistant returned null"),"Chunked AI Prompt error"),{})},getModels:()=>ut(),getMaxTokens:t=>{let c=De(t);if(!c)throw new Error(`Model${t}notfound.`);return c.maxTokens},countTokens(t,c){return Ie(t,c)},getRequestLogs(t=10){return SX(t)},getRequestLogById(t){return qX(t)},getLastRequestLog(){return PX()},clearRequestLogs(){_X()}},utility:{getClipboard:async()=>await navigator.clipboard.readText(),setClipboard:async t=>await navigator.clipboard.writeText(t),getSelection:()=>{let t=I.workspace.getActiveViewOfType(E0.MarkdownView);return t?t.editor.getSelection()??"":""},getSelectedText:()=>{let t=I.workspace.getActiveViewOfType(E0.MarkdownView);if(!t){al(new Error("No active view"),"Could not get selected text");return}if(!t.editor.somethingSelected()){al(new Error("No text selected"),"Could not get selected text");return}return t.editor.getSelection()}},date:{now:(t,c)=>Ut({format:t,offset:c}),tomorrow:t=>Ut({format:t,offset:1}),yesterday:t=>Ut({format:t,offset:-1})},fieldSuggestions:{getFieldValues:async(t,c)=>{let d=c?.includeInlineCodeBlocks?.map(Z=>Z.trim().toLowerCase()).filter(Z=>Z.length>0),b={folder:c?.folder,tags:c?.tags,inline:c?.includeInline??!1,inlineCodeBlocks:d},a=I.vault.getMarkdownFiles();a=nY.filterFiles(a,b,Z=>I.metadataCache.getFileCache(Z));let n=new Set;for(let Z of a){let W=I.metadataCache.getFileCache(Z)?.frontmatter?.[t];if(W!=null){if(Array.isArray(W))W.forEach(N=>{let s=N.toString().trim();s&&n.add(s)});else if(typeof W!="object"){let N=W.toString().trim();N&&n.add(N)}}if(b.inline){let N=await I.vault.read(Z);ma.getFieldValues(N,t,{includeCodeBlocks:d}).forEach(i=>n.add(i))}}return Array.from(n).sort()},clearCache:t=>{ot.getInstance().clear(t)}}}}static async inputPrompt(I,l,G,t){try{return await rl.Prompt(I,l,G,t)}catch(c){Lc(c);return}}static async datePrompt(I,l,G){try{let t=await gd.Prompt(I,l,G?.placeholder,G?.defaultValue,G?.dateFormat);if(t&&t.startsWith("@date:")){let c=t.slice(6);return(G?.dateFormat?pc(c,G.dateFormat):null)??c}return t}catch(t){Lc(t);return}}static async wideInputPrompt(I,l,G,t){try{return await oc.Prompt(I,l,G,t)}catch(c){Lc(c);return}}static async yesNoPrompt(I,l,G){try{return await re.Prompt(I,l,G)}catch(t){Lc(t);return}}static async infoDialog(I,l,G){try{return await cW.Show(I,l,G)}catch(t){Lc(t);return}}static async suggester(I,l,G,t,c=!1,d){try{let b;return typeof l=="function"?b=G.map((a,n,Z)=>oG(l(a,n,Z))):b=l.map(a=>oG(a)),c?await mG.Suggest(I,b,G,{...t?{placeholder:t}:{},...d?.renderItem?{renderItem:d.renderItem}:{}}):await VG.Suggest(I,b,G,t,d?.renderItem)}catch(b){Lc(b);return}}static async checkboxPrompt(I,l,G){try{return await tW.Open(I,l,G)}catch(t){Lc(t);return}}};function Lc(e){if(e instanceof vI)throw e;if(ol(e))throw new vI("Input cancelled by user")}var sa=class extends Ob{};var WG=[];for(let e=0;e<256;++e)WG.push((e+256).toString(16).slice(1));function xR(e,I=0){return(WG[e[I+0]]+WG[e[I+1]]+WG[e[I+2]]+WG[e[I+3]]+"-"+WG[e[I+4]]+WG[e[I+5]]+"-"+WG[e[I+6]]+WG[e[I+7]]+"-"+WG[e[I+8]]+WG[e[I+9]]+"-"+WG[e[I+10]]+WG[e[I+11]]+WG[e[I+12]]+WG[e[I+13]]+WG[e[I+14]]+WG[e[I+15]]).toLowerCase()}var k0,aO=new Uint8Array(16);function O0(){if(!k0){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");k0=crypto.getRandomValues.bind(crypto)}return k0(aO)}var nO=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),K0={randomUUID:nO};function ZO(e,I,l){if(K0.randomUUID&&!I&&!e)return K0.randomUUID();e=e||{};let G=e.random??e.rng?.()??O0();if(G.length<16)throw new Error("Random bytes length must be >= 16");if(G[6]=G[6]&15|64,G[8]=G[8]&63|128,I){if(l=l||0,l<0||l+16>I.length)throw new RangeError(`UUIDbyterange${l}:${l+15}isoutofbufferbounds`);for(let t=0;t<16;++t)I[l+t]=G[t];return I}return xR(G)}var rG=ZO;var eG=class{constructor(I,l){this.n
`)}var_R=require("obsidian");functionQa(e,I){if(I.options)for(letlinI.options){letG=e[l]===void0,t="defaultValue"inI.options[l]&&I.options[l].defaultValue!==void0;G&&t&&(e[l]=I.options[l].defaultValue)}}asyncfunctionfR(e,I){returne.mode==="script"?awaitI.evaluateScriptCondition(e):mO(e,I.variables)}functionmO(e,I){letl=e.variableName?.trim();if(!l)returnk.logWarning("Conditional command skipped: No variable name configured."),!1;if(!(linI))returnk.logWarning(`Conditional command skipped: Variable '${l}' is not defined.`),!1;letG=I[l];switch(e.operator){case"isTruthy":return!!G;case"isFalsy":return!G}if(uc(e.operator)){lett=fr(e);returnt===void0?(k.logWarning(`Conditional command: Operator '${e.operator}' requires a comparison value.`),!1):e.operator==="contains"?DR(G,t,e):e.operator==="notContains"?!DR(G,t,e):WO(G,t,e)}return!1}functionDR(e,I,l){if(e==null)return!1;if(typeofI=="string"&&I.length===0)returnk.logWarning("Conditional command: 'contains' operator requires a non-empty comparison value."),!1;if(Array.isArray(e))returne.map(c=>mh(c,l.valueType)).some(c=>c===I);if(typeofe=="string")returne.includes(ic(I));if(typeofe=="number"&&typeofI=="number")returne===I;letG=ic(e),t=ic(I);returntypeofG=="string"&&G.includes(t)}functionWO(e,I,l){letG=mh(e,l.valueType);switch(l.operator){case"equals":returnG===I;case"notEquals":returnG!==I;case"lessThan":returnZY(G,I,(t,c)=>t<c);case"lessThanOrEqual":returnZY(G,I,(t,c)=>t<=c);case"greaterThan":returnZY(G,I,(t,c)=>t>c);case"greaterThanOrEqual":returnZY(G,I,(t,c)=>t>=c);default:return!1}}functionZY(e,I,l){letG=Number(e),t=Number(I);returnNumber.isNaN(G)||Number.isNaN(t)?(k.logWarning("Conditional command numeric comparison failed: non-numeric value encountered."),!1):l(G,t)}varMR=require("obsidian");functionFc(e,{logPrefix:I,noticePrefix:l=I,defaultReason:G}){if(!(einstanceofvI))return!1;lett=typeofe.message=="string"&&e.message.trim().length>0?e.message:G;returnk.logMessage(`${I}: ${t}`),(!(typeofe.message=="string"&&e.message.toLowerCase().includes("cancelled by user"))||S.getState().showInputCancellationNotification)&&newMR.Notice(`${l}: ${t}`),!0}functionjR(e,I=void0){returne==="horizontal"?"horizontal":e==="vertical"?"vertical":I}functiongc(e,I,l){returnl?{location:e,direction:l,focus:I,mode:"default"}:{location:e,focus:I,mode:"default"}}functionTR(e){letI=e.focus??!0;if(e.location)switch(e.location){case"reuse":returngc("reuse",I);case"tab":returngc("tab",I);case"split":returngc("split",I,jR(e.direction,"vertical"));case"window":returngc("window",I);case"left-sidebar":returngc("left-sidebar",I);case"right-sidebar":returngc("right-sidebar",I);default:break}letl=e.openInNewTab??!1,G=jR(e.direction);returnl?gc("split",I,G??"vertical"):gc("reuse",I)}functionqR(e){letI={hasOwnProperty:l=>e.has(l)};returnnewProxy(I,{get(l,G){if(G==="hasOwnProperty")returnI.hasOwnProperty;if(typeofG=="string")returne.get(G)},set(l,G,t){returntypeofG!="string"||e.set(G,t),!0},deleteProperty(l,G){returntypeofG!="string"||e.delete(G),!0},has(l,G){returntypeofG=="string"&&e.has(G)},ownKeys(){returnArray.from(e.keys())},getOwnPropertyDescriptor(l,G){if(G==="hasOwnProperty")return{value:I.hasOwnProperty,writable:!1,configurable:!1,enumerable:!1};if(!(typeofG!="string"||!e.has(G)))return{value:e.get(G),writable:!0,configurable:!0,enumerable:!0}}})}functionPt(e,I){returnU0(e)&&e.type===I}functionsO(e){returnPt(e,"Obsidian")}functionYO(e){returnPt(e,"UserScript")}functioniO(e){returnPt(e,"Choice")}functionuO(e){returnPt(e,"Wait")}functionCO(e){returnPt(e,"NestedChoice")}functionhO(e){returnPt(e,"EditorCommand")}functionpO(e){returnPt(e,"AIAssistant")}functionoO(e){returnPt(e,"OpenFile")}functionVO(e){returnPt(e,"Conditional")}functionU0(e){returne!==null&&typeofe=="object"}functionrO(e){returntypeofe=="function"}function$R(e){returnU0(e)}functionXO(e){if(!$R(e))return;let{settings:I}=e;returnU0(I)?I:void0}functionPR(e){return`${e.scriptPath}::${e.exportName??"default"}`}varVt=classextends
Suggested values for ${G}: ${n.slice(0,3).join(", ")}`)}returnawaitrl.PromptWithContext(this.app,`Enter value for ${G}`,a,void0,this.getLinkSourcePath()??void0)}letb=`Enter value for ${G}`;returnd&&(b=`Enter value for ${G} (default: ${t.defaultValue})`),awaitmG.Suggest(this.app,c,c,{placeholder:b})}catch(G){throwol(G)?newvI("Input cancelled by user"):G}}generateCacheKey(l){returncY(l)}asyncgetMacroValue(l,G){lett=newWY(this.app,this.plugin,this.plugin.settings.choices,this.choiceExecutor,this.variables),c=awaitt.runAndGetOutput(l,G)??"";returnt.getVariables().forEach((d,b)=>{this.variables.set(b,d)}),c}asyncgetTemplateContent(l){returnawaitnewvc(this.app,this.plugin,l,this.choiceExecutor).run()}asyncgetSelectedText(){letl=this.app.workspace.getActiveViewOfType(GL.MarkdownView);returnl?l.editor.getSelection():""}asyncgetClipboardContent(){try{returnawaitnavigator.clipboard.readText()}catch{return""}}isTemplatePropertyTypesEnabled(){returnthis.plugin.settings.enableTemplatePropertyTypes}asyncreplaceInlineJavascriptInString(l){letG=l;for(;cn.test(G);){letc=cn.exec(G)?.at(1)?.trim();if(c){letd=newmY(this.app,this.plugin,this.choiceExecutor,this.variables),b=awaitd.runAndGetOutput(c);for(letaind.params.variables)this.variables.set(a,d.params.variables[a]);G=typeofb=="string"?this.replacer(G,cn,b):this.replacer(G,cn,"")}}returnG}asynccollectValuesManually(l,G){returnawaitdY(this.app,l,G)}};varLa=require("obsidian");vareL=require("obsidian");functionpW(e){return((0,eL.normalizePath)(e).split("/").pop()??"").replace(/\.(md|canvas|base)$/i,"")}varrt=classextendsError{constructor(I){super(I),this.name="InvalidFolderPathError"}};functionz0(e){returneinstanceofvI||!!e&&typeofe=="object"&&"name"ine&&e.name==="MacroAbortError"}varFa=classextendsOb{constructor(l,G,t){super(l);this.plugin=G;this.templater=ch(l),this.formatter=newTe(l,G,t)}asyncgetOrCreateFolder(l,G={}){lett=this.buildFolderSelectionContext(l,G);if(!this.shouldPromptForFolder(t))returnawaitthis.handleSingleSelection(t);letc=awaitthis.promptUntilAllowed(t);returnc.isEmpty?"":c.resolved}buildFolderSelectionContext(l,G){lett=G.allowCreate??!1,c=G.allowedRoots?.map(m=>this.normalizeFolderPath(m))??[],{items:d,displayItems:b,normalizedItems:a,canonicalByNormalized:n,displayByNormalized:Z}=this.buildFolderSuggestions(l,G.topItems??[],c.length>0?c:void0);return{items:d,displayItems:b,normalizedItems:a,canonicalByNormalized:n,displayByNormalized:Z,existingSet:newSet(a),allowCreate:t,allowedRoots:c,placeholder:G.placeholder}}shouldPromptForFolder(l){returnl.items.length>1||l.allowCreate&&l.items.length===0}asyncpromptForFolder(l){try{returnl.allowCreate?awaitmG.Suggest(this.app,l.displayItems,l.items,{placeholder:l.placeholder??"Choose a folder or type to create one",renderItem:(G,t)=>{this.renderFolderSuggestion(G,t,l.existingSet,l.displayByNormalized)}}):awaitVG.Suggest(this.app,l.displayItems,l.items,l.placeholder)}catch(G){throwol(G)?newvI("Input cancelled by user"):G}}asyncresolveSelection(l,G){lett=this.normalizeFolderPath(l),c=t.length===0,d=G.canonicalByNormalized.get(t),b=d??t,a=c?!1:d!==void0||awaitthis.app.vault.adapter.exists(b),n=G.allowedRoots.length===0?!0:this.isPathAllowed(c?"":b,G.allowedRoots);return{raw:l,normalized:t,resolved:b,exists:a,isAllowed:n,isEmpty:c}}asyncpromptUntilAllowed(l){for(;;){letG=awaitthis.promptForFolder(l),t=awaitthis.resolveSelection(G,l);if(t.isEmpty){if(!t.isAllowed){this.showFolderNotAllowedNotice(l.allowedRoots);continue}returnt}if(!t.isAllowed){this.showFolderNotAllowedNotice(l.allowedRoots);continue}try{this.validateFolderPath(t.resolved)}catch(c){if(cinstanceofrt){newLa.Notice(c.message);continue}throwc}returnawaitthis.ensureFolderExists(t),t}}asyncensureFolderExists(l){l.isEmpty||l.exists||awaitthis.createFolder(l.resolved)}asynchandleSingleSelection(l){letG=l.items[0]??"",t=awaitthis.resolveSelection(G,l);if(t.isEmpty)return"";if(!t.isAllowed)throwthis.showFolderNotAllowedNotice(l.allowedRoots),newvI("Selected folder not allowed.");if
`).map(o=>o.trim()).filter(o=>o.length>0),Y=this.truncatePickerText(i[0]??"(empty text card)",90),p=[`${i.length} line${i.length===1?"":"s"}`];Z&&p.push(Z);letu=p.join(" \xB7 ");return{id:a.id,type:n,title:Y,subtitle:u,searchText:`${a.id}${Y}${u}`.toLowerCase(),capturable:!0,capturableReason:""}}if(n==="file"){lets=this.getCanvasNodeFilePath(a.file),i=CG.test(s),Y=i?"":"Canvas file cards must link to markdown files (.md).",p=this.truncatePickerText(s.split("/").pop()??s,90),u=[this.truncatePickerText(s,120)];Z&&u.push(Z),i||u.push("Not capturable in this version");leto=u.join(" \xB7 ");return{id:a.id,type:n,title:p,subtitle:o,searchText:`${a.id}${p}${o}`.toLowerCase(),capturable:i,capturableReason:Y}}letW=`Unsupported node (${typeofa.type=="string"&&a.type.length>0?a.type:"unknown"})`,N=Z||"Type is not currently capturable";return{id:a.id,type:n,title:W,subtitle:N,searchText:`${a.id}${W}${N}`.toLowerCase(),capturable:!1,capturableReason:"This Canvas node type is not capturable."}}),b={text:0,file:1,other:2};returnd.sort((a,n)=>{letZ=b[a.type]-b[n.type];returnZ!==0?Z:a.title.localeCompare(n.title)})}catch{return[]}}getCanvasNodeFilePath(l){returntypeofl=="string"?l:l&&typeofl=="object"&&"path"inl&&typeofl.path=="string"?l.path:"(missing file path)"}describeCanvasNodeCoordinates(l){returntypeofl.x!="number"||typeofl.y!="number"||typeofl.width!="number"||typeofl.height!="number"?"":`${Math.round(l.x)},${Math.round(l.y)} \xB7 ${Math.round(l.width)}x${Math.round(l.height)}`}truncatePickerText(l,G){returnl.length<=G?l:l.slice(0,G-1)+"\u2026"}addTaskSetting(){newLI.Setting(this.contentEl).setName("Task").setDesc("Formats the value as a task.").addToggle(G=>{G.setValue(this.choice.task),G.onChange(t=>this.choice.task=t)})}addAppendLinkSetting(){letl=Nc(this.choice.appendLink),G=l.linkType??"link",t=l.enabled?l.requireActiveFile?"required":"optional":"disabled";newLI.Setting(this.contentEl).setName("Link to captured file").setDesc("Choose how QuickAdd should insert a link to the captured file in the current note.").addDropdown(d=>{d.addOption("required","Enabled (requires active file)"),d.addOption("optional","Enabled (skip if no active file)"),d.addOption("disabled","Disabled"),d.setValue(t),d.onChange(b=>{switch(b){case"disabled":this.choice.appendLink=!1;break;case"required":this.choice.appendLink={enabled:!0,placement:l.placement,requireActiveFile:!0,linkType:G};break;case"optional":this.choice.appendLink={enabled:!0,placement:l.placement,requireActiveFile:!1,linkType:G};break}this.reload()})}),t!=="disabled"&&(newLI.Setting(this.contentEl).setName("Link placement").setDesc("Where to place the link when appending").addDropdown(b=>{b.addOption("replaceSelection","Replace selection"),b.addOption("afterSelection","After selection"),b.addOption("endOfLine","End of line"),b.addOption("newLine","New line"),b.setValue(l.placement),b.onChange(a=>{letn=this.choice.appendLink,Z=typeofn=="boolean"?l.requireActiveFile:n.requireActiveFile,m=typeofn=="boolean"?G:n.linkType??G,W=xt(a)?m:"link";this.choice.appendLink={enabled:!0,placement:a,requireActiveFile:Z,linkType:W},this.reload()})}),xt(l.placement)&&newLI.Setting(this.contentEl).setName("Link type").setDesc("Choose whether to insert a regular link or an embed when replacing the selection.").addDropdown(a=>{a.addOption("link","Link"),a.addOption("embed","Embed"),a.setValue(G),a.onChange(n=>{letZ=this.choice.appendLink,m=typeofZ=="boolean"?l.requireActiveFile:Z.requireActiveFile,W=typeofZ=="boolean"?l.placement:Z.placement;this.choice.appendLink={enabled:!0,placement:W,requireActiveFile:m,linkType:n}})}))}addWritePositionSetting(){letl=newLI.Setting(this.contentEl),G=!!this.choice?.captureToActiveFile;this.choice.activeFileWritePosition||(this.choice.activeFileWritePosition="cursor"),l.setName("Write position").setDesc(G?"Where to place the capture in the current file.":"Where to place the capture in the target file.").addDropdown(t=>{letc=this.choice.insertAfter?.enabled?"after":this.choice.newLineCapture?.enabled?this.choice.newLineCapture.direc
Inordertobeiterable,non-arrayobjectsmusthavea[Symbol.iterator]()method.`)}function I3(){throw new TypeError(`Invalidattempttodestructurenon-iterableinstance.
Inordertobeiterable,non-arrayobjectsmusthavea[Symbol.iterator]()method.`)}function gW(e,I){var l=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!l){if(Array.isArray(e)||(l=lp(e))||I&&e&&typeof e.length=="number"){l&&(e=l);var G=0,t=function(){};return{s:t,n:function(){return G>=e.length?{done:!0}:{done:!1,value:e[G++]}},e:function(a){throw a},f:t}}throw new TypeError(`Invalidattempttoiteratenon-iterableinstance.
${l?"Deleting this choice will delete all ("+e.choices.length+") choices inside it!":""}
${G?"Deleting this choice will delete its macro commands!":""}
`)}asyncfunctionWF(e,I,l){if(e.type==="Multi")try{returnawaitnew_Y(I,e).waitForClose}catch{return}letG=E9(e,I,l);if(!G)thrownewError("Invalid choice type");returnawaitG.waitForClose}functionNF(e){return{...e,command:!e.command}}varIi=class{constructor(I){this.plugin=I}enableCommand(I){this.plugin.addCommandForChoice(I)}disableCommand(I){this.plugin.removeCommandForChoice(I)}updateCommand(I,l){this.plugin.removeCommandForChoice(I),this.plugin.addCommandForChoice(l)}};functionsF(e,I,l){if(!I||!l)returne;letG=ip(e,I),t=ip(e,l);if(!G||!t||t.type!=="Multi"||G.type==="Multi"&&(G.id===t.id||k9(G).has(t.id)))returne;let{updated:c,removed:d}=YF(e,I);returnd?iF(c,l,d)??e:e}functionip(e,I){for(letlofe){if(l.id===I)returnl;if(l.type==="Multi"){letG=ip(l.choices,I);if(G)returnG}}}functionk9(e){letI=newSet,l=G=>{I.add(G.id),G.type==="Multi"&&G.choices.forEach(l)};return(e.choices??[]).forEach(l),I}functionYF(e,I){letl;return{updated:e.map(t=>{if(t.id===I){l=t;return}if(t.type!=="Multi")returnt;letc=YF(t.choices,I);returnc.removed&&(l=c.removed),c.removed?{...t,choices:c.updated}:t}).filter(Boolean),removed:l}}functioniF(e,I,l){letG=!1,t=e.map(c=>{if(c.id===I&&c.type==="Multi"){G=!0;letb=c;return{...b,choices:[...b.choices,l]}}if(c.type!=="Multi")returnc;letd=iF(c.choices,I,l);returnd?(G=!0,{...c,choices:d}):c});returnG?t:void0}varwt=require("obsidian");varFl=require("obsidian");varuF=require("obsidian");varli=null,O9=1440*60*1e3;asyncfunctionCF(){if(li&&Date.now()-li.fetchedAt<O9)returnli.data;if(S.getState().disableOnlineFeatures)thrownewError("Fetching models directory is disabled: Online features are turned off.");letI=await(await(0,uF.requestUrl)({url:"https://models.dev/api.json",method:"GET"})).json;returnli={data:I,fetchedAt:Date.now()},I}functionhp(e){letI=e.toLowerCase();returnI.includes("openai.com")?"openai":I.includes("openrouter.ai")?"openrouter":I.includes("generativelanguage.googleapis.com")?"google":I.includes("anthropic.com")||I.includes("anthropic")?"anthropic":I.includes("groq.com")?"groq":I.includes("together.ai")?"togetherai":I.includes("huggingface.co")||I.includes("huggingface")?"huggingface":I.includes("github")&&I.includes("models")?"github-models":I.includes("bedrock")||I.includes("aws")?"amazon-bedrock":I.includes("modelscope")?"modelscope":I.includes("dashscope")?"alibaba":I.includes("fireworks.ai")?"fireworks-ai":I.includes("vercel")?"vercel":I.includes("inference.net")?"inference":I.includes("z.ai")||I.includes("zhipu")?"zhipuai":I.includes("deepseek.com")?"deepseek":I.includes("cerebras")?"cerebras":I.includes("venice.ai")?"venice":I.includes("upstage.ai")?"upstage":I.includes("llama.com")||I.includes("api.llama.com")?"llama":I.includes("morphllm")?"morph":I.includes("inceptionlabs.ai")?"inception":I.includes("deepinfra")?"deepinfra":I.includes("gateway.opencode.ai")?"opencode":I.includes("router.huggingface.co")?"huggingface":I.includes("inference.wandb.ai")?"wandb":I.includes("api.githubcopilot.com")?"github-copilot":I.includes("api.openai.com")?"openai":null}functionhF(e){returne.map(I=>({name:I.id,maxTokens:Math.max(1,Math.floor(I.limit?.context??128e3))}))}functionpp(e,I){letl=newSet(e.map(t=>t.name)),G=I.filter(t=>!l.has(t.name));returne.concat(G)}varVF=require("obsidian");varK9=128e3;asyncfunctionGi(e,I){letl=e.modelSource??"providerApi";if(l==="modelsDev")returnpF(e);if(l==="providerApi")returnoF(e,I);try{returnawaitoF(e,I)}catch(G){if(!hp(e.endpoint))throwG;returnpF(e,G)}}asyncfunctionpF(e,I){try{letl=awaitCF(),G=hp(e.endpoint);if(!G||!(Ginl))thrownewError(`models.dev does not list a provider that matches ${e.endpoint}.`);lett=Object.values(l[G].models);returnhF(t)}catch(l){throwI?newError(`Provider API failed (${I.message}). Fallback to models.dev also failed: ${l.message}`):l}}asyncfunctionoF(e,I){let{disableOnlineFeatures:l}=S.getState();if(l)thrownewError("Online features are disabled \u2014 enable them to browse provider models.");if(!e.endpoint)thrownewError("Provider is missing an endpoin
yd=yesterday`).setValue(_i(S.getState().dateAliases)).onChange(d=>{S.setState({dateAliases:Yo(d)})}),c.inputEl.addClass("qa-date-alias-input")}),G.addButton(c=>{c.setButtonText("Reset to defaults").onClick(()=>{S.setState({dateAliases:Ib}),t&&t.setValue(_i(Ib))}),c.buttonEl.addClass("qa-date-alias-reset")})})}addDisableOnlineFeaturesSetting(l){l.addSetting(G=>{G.setName("Disable AI & Online features").setDesc("This prevents the plugin from making requests to external providers like OpenAI. You can still use User Scripts to execute arbitrary code, including contacting external providers. However, this setting disables plugin features like the AI Assistant from doing so. You need to disable this setting to use the AI Assistant.").addToggle(t=>t.setValue(S.getState().disableOnlineFeatures).onChange(c=>{S.setState({disableOnlineFeatures:c}),this.display()}))})}addEnableRibbonIconSetting(l){l.addSetting(G=>{G.setName("Show icon in sidebar").setDesc("Add QuickAdd icon to the sidebar ribbon. Requires a reload.").addToggle(t=>{t.setValue(S.getState().enableRibbonIcon).onChange(c=>{S.setState({enableRibbonIcon:c}),this.display()})})})}};var fa=class{formatOutputString(I){return`QuickAdd:(${I.level})${I.message}`}getQuickAddError(I,l,G,t){return{message:I,level:l,time:Date.now(),stack:G,originalError:t}}};var xW=class extends fa{constructor(){super(...arguments);this.ErrorLog=[]}logError(l,G,t){let c=this.getQuickAddError(l,"ERROR",G,t);this.addMessageToErrorLog(c);let d=t||new Error(l);console.error(this.formatOutputString(c),d)}logWarning(l,G,t){let c=this.getQuickAddError(l,"WARNING",G,t);this.addMessageToErrorLog(c);let d=t||new Error(l);console.warn(this.formatOutputString(c),d)}logMessage(l,G,t){let c=this.getQuickAddError(l,"LOG",G,t);this.addMessageToErrorLog(c),t?console.log(this.formatOutputString(c),t):console.log(this.formatOutputString(c))}addMessageToErrorLog(l){this.ErrorLog.push(l),this.ErrorLog.length>lh&&(this.ErrorLog=this.ErrorLog.slice(-lh))}clearErrorLog(){this.ErrorLog=[]}};var kp=require("obsidian");var ri=class extends fa{constructor(l){super();this.plugin=l}logError(l,G,t){let c=this.getQuickAddError(l,"ERROR",G,t);new kp.Notice(this.formatOutputString(c),15e3)}logWarning(l,G,t){let c=this.getQuickAddError(l,"WARNING",G,t);new kp.Notice(this.formatOutputString(c))}logMessage(l,G,t){}};var Xi=class{constructor(I,l,G,t){this.app=I;this.plugin=l;this.choices=G;this.choiceExecutor=t}async run(){let I=Pe(this.choices).filter(l=>l.type==="Macro"&&l.runOnStartup);for(let l of I)await new Vt(this.app,this.plugin,l,this.choiceExecutor,new Map).run()}};var Op=require("obsidian"),Kg=require("obsidian");var Qi=class extends Fa{constructor(l,G,t,c,d=null){super(l,G,c);this.originLeaf=d;this.choiceExecutor=c,this.choice=t}async run(){try{$G(this.choice.templatePath,()=>`Invalidtemplatepathfor${this.choice.name}.${this.choice.templatePath.length===0?"Template path is empty.":`Template path is not valid: ${this.choice.templatePath}`}`);let l=Nc(this.choice.appendLink);this.setLinkToCurrentFileBehavior(l.enabled&&!l.requireActiveFile?"optional":"required");let G="";if(this.choice.folder.enabled)G=await this.getFolderPath();else{let W=this.app.fileManager.getNewFileParent(this.app.workspace.getActiveFile()?.path??"");G=W===this.app.vault.getRoot()?"":W.path}let t=this.choice.fileNameFormat.enabled?this.choice.fileNameFormat.format:jc,c=await this.formatter.formatFileName(t,this.choice.name),{fileName:d,strippedPrefix:b}=this.stripDuplicateFolderPrefix(c,G),a=this.shouldTreatFormattedNameAsVaultRelativePath(c,b),n=this.normalizeTemplateFilePath(a?"":G,d,this.choice.templatePath),Z,m=!1;if(await this.app.vault.adapter.exists(n)){let W=await this.getSelectedFileExistsMode(),N=va(W),s=N.requiresExistingFile?this.findExistingFile(n):null;if(N.requiresExistingFile&&(!(s instanceof Op.TFile)||s.extension!=="md"&&s.extension!=="canvas"&&s.extension!=="base")){k.logError(`'${n}'alreadyexistsbutcouldnotberesolvedasamarkdown,canvas,orbasefile.`);return}({createdFile:Z,shouldAutoOpen:m}=await this.applyFileExis
`)}}).join(`
`)}}varUg=e=>e.join(""),ex=e=>e.split(/\b/),tx=xg("<<<<<<< YOUR CHANGES","=======",">>>>>>> APP AUTHORS CHANGES",Ug),cx={splitFunction:ex,joinFunction:Ug,conflictFunction:tx};functionDp(e,I,l,G={}){G=Object.assign({},cx,G);let[t,c,d]=[e,I,l].map(n=>G.splitFunction.call(G,n)),b=BW.merge(t,c,d);returnDW.collateMerge(b,G.joinFunction,G.conflictFunction)}varzg=Dp;varfp=require("obsidian");varMI=classextendsvI{};functionBg(e,I){returne.line===I.line}functiondx(e){letI=[];returne.forEach((l,G)=>{lett=l.match(/^(#+)[\s]+(.*)$/);t&&I.push({level:t[1].length,text:t[2],line:G})}),I}functionwi(e,I,l=!1){letG=dx(e),t=G.find(n=>n.line===I),c=!!t;if(!c&&l)thrownewError(`Target line ${I} is not a heading, but we are trying to find the end of its section.`);if(!c&&!l){letn=Dg(e,I,Z=>Z.trim()==="");returnn!==null&&n>I?n-1:I}letd=e.length-1,b=bx(t,G,e,l),a=Zx(e,b,n=>n.trim()!=="");if(a!==null){if(a<I)returnI;letn=e[a+1].trim()==="";returna+1===d&&!n?b:a===0?a+1:a}returnb}functionbx(e,I,l,G){lett=I.findIndex(Z=>Bg(Z,e)),c=t===I.length-1,d=l.length-1;if(c)returnd;let[b,a]=ax(e,I);if(a&&b===I.length)returnd;if(a&&G)returnI[b].line-1;if(a&&!G)returnI[t+1].line;if(!G&&!a){letZ=nx(e.line,I);returnZ===null?d:Z}returnd}functionax(e,I){letl=I.findIndex(t=>Bg(t,e)),G=Dg(I,l,t=>t.level<=e.level);returnG===null?[-1,!1]:[G,!0]}functionnx(e,I){letl=I.find(G=>G.line>e);returnl?l.line:null}functionZx(e,I,l){for(letG=I-1;G>=0;G--)if(l(e[G]))returnG;returnnull}functionDg(e,I,l){for(letG=I+1;G<e.length;G++)if(l(e[G]))returnG;returnnull}varvi=classextendsTe{constructor(){super(...arguments);this.file=null;this.fileContent="";this.sourcePath=null;this.useSelectionAsCaptureValue=!0;this.templaterProcessed=!1}setDestinationFile(l){this.file=l,this.sourcePath=l.path}setDestinationSourcePath(l){this.sourcePath=l,this.file=null}setUseSelectionAsCaptureValue(l){this.useSelectionAsCaptureValue=l}shouldUseSelectionForValue(){returnthis.useSelectionAsCaptureValue}asyncgetSelectedTextForValue(){letl=awaitthis.getSelectedText();returnl.trim().length>0?l:""}getLinkSourcePath(){returnthis.sourcePath??this.file?.path??null}getCurrentFileLink(){letl=this.app.workspace.getActiveFile();if(!l)returnnull;letG=this.sourcePath??this.file?.path??"";returnthis.app.fileManager.generateMarkdownLink(l,G)}asyncformatContentWithFile(l,G,t,c){if(this.choice=G,this.file=c,this.fileContent=t,!G||!c||t===null)returnl;letd=G.insertAfter.enabled||G.prepend||!G.captureToActiveFile||G.activeFileWritePosition==="top"||G.activeFileWritePosition==="bottom";returnawaitthis.formatFileContent(l,d)}asyncformatContent(l,G){returnthis.choice=G,G?awaitthis.formatFileContent(l):l}asyncformatFileContent(l,G=!0){lett=awaitsuper.formatFileContent(l);if(t=this.replaceLinebreakInString(t),G&&this.file&&!this.templaterProcessed){leta=awaitAb(this.app,t,this.file);a&&(t=a),this.templaterProcessed=!0}if(t.trim()==="")returnthis.fileContent;if(this.choice.prepend||this.choice.captureToActiveFile&&this.choice.activeFileWritePosition==="bottom"){leta=!this.choice.task,n=this.fileContent.length>0&&!this.fileContent.endsWith(`
`)?Math.max(G,d-1):d}asyncinsertAfterHandler(l){letG=awaitthis.formatLocationString(this.choice.insertAfter.after);if(this.choice.insertAfter?.inline)returnawaitthis.insertAfterInlineHandler(l,G);lett=x0(this.fileContent),c=this.findInsertAfterIndex(t,G);if(c===-1){if(this.choice.insertAfter?.createIfNotFound)returnawaitthis.createInsertAfterIfNotFound(l);thrownewMI(`Insert-after target not found: '${G}'.`)}if(this.choice.insertAfter?.insertAtEnd){if(!this.file)thrownewError("Tried to get sections without file.");letb=wi(t,c,!!this.choice.insertAfter.considerSubsections);c=this.findInsertAfterPositionAtSectionEnd(t,b??t.length-1,this.fileContent,l)}else{letb=this.choice.insertAfter?.blankLineAfterMatchMode??"auto";c=this.findInsertAfterPositionWithBlankLines(t,c,this.fileContent,b)}returnthis.insertTextAfterPositionInBody(l,this.fileContent,c)}hasInlineTargetLinebreak(l){returnl.includes(`
`,l);returnG===-1?this.fileContent.length:G>0&&this.fileContent[G-1]==="\r"?G-1:G}asyncinsertAfterInlineHandler(l,G){if(this.hasInlineTargetLinebreak(G))returnal(newError("Inline insert after target must be a single line."),"Insert After Inline Error"),this.fileContent;lett=this.fileContent.indexOf(G);if(t===-1){if(this.choice.insertAfter?.createIfNotFound)returnawaitthis.createInlineInsertAfterIfNotFound(l,G);thrownewMI(`Inline insert-after target not found: '${G}'.`)}letc=t+G.length;if(this.choice.insertAfter?.replaceExisting){letd=this.getInlineEndOfLine(c);returnthis.fileContent.slice(0,c)+l+this.fileContent.slice(d)}returnthis.fileContent.slice(0,c)+l+this.fileContent.slice(c)}asynccreateInsertAfterIfNotFound(l){lett=`${this.replaceLinebreakInString(awaitthis.formatLocationString(this.choice.insertAfter.after))}
${t}`;if(this.choice.insertAfter?.createIfNotFoundLocation===en)try{letc=this.app.workspace.getActiveViewOfType(fp.MarkdownView);if(!c)thrownewError("No active view.");letb=c.editor.getCursor().line;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)thrownewError("Tried to get sections without file.");letn=x0(this.fileContent),Z=wi(n,b,!!this.choice.insertAfter.considerSubsections);b=this.findInsertAfterPositionAtSectionEnd(n,Z??n.length-1,this.fileContent,t)}returnthis.insertTextAfterPositionInBody(t,this.fileContent,b)}catch{thrownewMI(`Unable to insert line '${this.choice.insertAfter.after}' at cursor position.`)}thrownewMI(`Unknown createIfNotFoundLocation: ${this.choice.insertAfter?.createIfNotFoundLocation}`)}asynccreateInlineInsertAfterIfNotFound(l,G){lett=`${G}${l}`;if(this.choice.insertAfter?.createIfNotFoundLocation===lb){letc=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):-1;returnthis.insertTextAfterPositionInBody(t,this.fileContent,c)}if(this.choice.insertAfter?.createIfNotFoundLocation===Gn)return`${this.fileContent}
${t}`;if(this.choice.insertAfter?.createIfNotFoundLocation===en)try{letc=this.app.workspace.getActiveViewOfType(fp.MarkdownView);if(!c)thrownewError("No active view.");letb=c.editor.getCursor().line;returnthis.insertTextAfterPositionInBody(t,this.fileContent,b)}catch{thrownewMI(`Unable to insert line '${this.choice.insertAfter.after}' at cursor position.`)}thrownewMI(`Unknown createIfNotFoundLocation: ${this.choice.insertAfter?.createIfNotFoundLocation}`)}getFrontmatterEndPosition(l,G){lett=this.app.metadataCache.getFileCache(l);if(t?.frontmatterPosition)returnt.frontmatterPosition.end.line;if(G){letc=this.inferFrontmatterEndLineFromContent(G);if(c!==null)returnc}returnk.logMessage("could not get frontmatter. Maybe there isn't any."),-1}inferFrontmatterEndLineFromContent(l){letG=PN(l);if(!G)returnnull;lett=l.slice(0,G[1]),c=t.split(/\r?\n/);returnc.length===0?null:t.endsWith(`
${l}${b}`}};functionfg(e){returne.captureToActiveFile&&!e.insertAfter.enabled&&e.newLineCapture?.enabled?e.newLineCapture.direction==="above"?"newLineAbove":"newLineBelow":e.captureToActiveFile&&!e.insertAfter.enabled?e.activeFileWritePosition==="top"?"activeFileTop":e.activeFileWritePosition==="bottom"||e.prepend?"append":"currentLine":e.insertAfter.enabled?"insertAfter":e.prepend?"prepend":"append"}functionMp(e){returne?.type==="text"?"text":e?.type==="file"||e?.file?"file":typeofe?.text=="string"?"text":"unsupported"}functionmx(e,I){letl=I.id;if(!l)returnnull;letG=e.getData?.();returnG?.nodes?.length?G.nodes.find(t=>t.id===l)??null:null}functionMg(e,I){if(e==="text"){if(I==="currentLine")return"Canvas capture does not support 'At cursor' for text cards. Use top, bottom, or insert-after placement.";if(I==="newLineAbove"||I==="newLineBelow")return"Canvas capture does not support 'New line above/below cursor' for text cards. Use top, bottom, or insert-after placement."}returne==="file"&&(I==="currentLine"||I==="newLineAbove"||I==="newLineBelow")?"Canvas file cards do not support cursor-based capture modes. Use top, bottom, or insert-after modes.":null}functionWx(e){letI=e.file;returnI?typeofI=="string"?I:typeofI=="object"&&"path"inI&&typeofI.path=="string"?I.path:null:null}functionjp(e){return!!e&&"path"ine&&"extension"ine}functionNx(e){letl=(e.workspace.activeLeaf??e.workspace.getMostRecentLeaf?.()??null)?.view;return!l||l.getViewType?.()!=="canvas"?null:l}functionsx(e,I){letl=I.file??e.workspace.getActiveFile?.();if(!l)thrownewMI("Cannot capture to Canvas because no active Canvas file is available.");returnl}functionYx(e){letI=e.selection?Array.from(e.selection):[];if(I.length!==1)thrownewMI("Canvas capture requires exactly one selected node.");returnI[0]}functionjg(e){letI=Wx(e);if(!I)thrownewMI("Selected Canvas file card does not have a valid linked file path.");if(!CG.test(I))thrownewMI("Canvas file card targets markdown files only in this version.");returnI}functionix(e,I){letl=jg(I),G=e.vault.getAbstractFileByPath(l);if(!jp(G))thrownewMI(`Selected Canvas file card target not found: ${l}`);returnG}functionux(e,I){letl=jg(I),G=e.vault.getAbstractFileByPath(l);if(!G)return{targetPath:l};if(!jp(G))thrownewMI(`Selected Canvas file card target not found: ${l}`);return{targetPath:l,targetFile:G}}functionCx(e,I){letl;try{l=JSON.parse(e)}catch{thrownewMI(`Canvas file is not valid JSON: ${I}`)}if(!l||typeofl!="object")thrownewMI(`Canvas file has invalid structure: ${I}`);if(!Array.isArray(l.nodes))thrownewMI(`Canvas file has no nodes array: ${I}`);returnl}functionSg(e,I){letl=e,G=Nx(l);if(!G)returnnull;lett=G.canvas;if(!t)thrownewMI("Canvas capture is unavailable in this Obsidian version.");letc=sx(l,G),d=Yx(t),b=mx(t,d),a=Mp(d);if(a==="unsupported"&&b&&(a=Mp(b)),a==="unsupported")thrownewMI("Canvas capture currently supports only text and file cards.");letn=Mg(a,I);if(n)thrownewMI(n);if(a==="text")return{kind:"text",source:"active",canvas:t,canvasFile:c,node:d,nodeData:b};letZ=d.file||!b?.file?d:{...d,file:b.file};return{kind:"file",source:"active",canvasFile:c,node:Z,targetFile:ix(l,Z)}}asyncfunctionTg(e,I,l,G){lett=l.trim();if(!t)thrownewMI("Canvas node id is required for Canvas node capture.");letc=e.vault.getAbstractFileByPath(I);if(!jp(c))thrownewMI(`Canvas target not found: ${I}`);if(!hG.test(c.path))thrownewMI("Canvas node capture requires the target path to be a .canvas file.");letd=awaite.vault.read(c),b=Cx(d,c.path),a=b.nodes.findIndex(i=>i.id===t);if(a===-1)thrownewMI(`Canvas node id '${t}' was not found in ${c.path}.`);letn=b.nodes[a],Z=Mp(n);if(Z==="unsupported")thrownewMI("Canvas capture currently supports only text and file cards.");letm=Mg(Z,G);if(m)thrownewMI(m);if(Z==="text")return{kind:"text",source:"configured",canvasFile:c,rawCanvas:d,canvasData:b,nodeData:n,nodeIndex:a};letW=e,{targetPath:N,targetFile:s}=ux(W,n);return{kind:"file",source:"configured",canvasFile:c,nodeData:n,targetPath:N,targetFile:s}}functio
`),l}async getFormattedPathToCaptureTo(l){let G=this.choiceExecutor?.variables?.get(dn);if(!l&&G&&typeof G=="string"&&G.length>0)return this.normalizeCaptureFilePath(G);if(l){let b=this.app.workspace.getActiveFile();return $G(b,"Cannot capture to active file - no active file."),b.path}let t=this.choice.captureTo,c=await this.formatter.formatFileName(t,this.choice.name),d=this.resolveCaptureTarget(c);switch(d.kind){case"vault":return this.selectFileInFolder("",!0);case"tag":return this.selectFileWithTag(d.tag);case"folder":return this.selectFileInFolder(d.folder,!1);case"file":return this.normalizeCaptureFilePath(d.path)}}resolveCaptureTarget(l){let G=this.stripLeadingSlash(l.trim());if(G==="")return{kind:"vault"};if(G.startsWith("#"))return{kind:"tag",tag:G.replace(/\.md$/,"")};if(ae.test(G))throw new MI(`Captureto'.base'filesisnotsupported(${G}).UseaTemplatechoiceinstead.`);let t=G.endsWith("/"),c=G.replace(/\/+$/,"");if(t)return{kind:"folder",folder:c};if(CG.test(G)||hG.test(G))return{kind:"file",path:G};let d=this.normalizeMarkdownFilePath("",c),a=!!this.app.vault.getAbstractFileByPath(d);return TN(this.app,c)&&!a?{kind:"folder",folder:c}:{kind:"file",path:G}}async selectFileInFolder(l,G){let t=l.endsWith("/")||G?l:`${l}/`,c=sc(this.app,t);$G(c.length>0,`Folder${t}isempty.`);let d=c.map(n=>n.path),b;try{b=await mG.Suggest(this.app,d.map(n=>n.replace(t,"")),d)}catch(n){throw ol(n)?new vI("Input cancelled by user"):n}$G(!!b&&b.length>0,"No file selected for capture.");let a=b.startsWith(`${t}`)?b:`${t}/${b}`;return await this.formatFilePath(a)}async selectFileWithTag(l){let G=l.startsWith("#")?l:`#${l}`,t=qN(this.app,G);$G(t.length>0,`Nofileswithtag${l}.`);let c=t.map(b=>b.path),d;try{d=await mG.Suggest(this.app,c,c)}catch(b){throw ol(b)?new vI("Input cancelled by user"):b}return $G(!!d&&d.length>0,"No file selected for capture."),await this.formatFilePath(d)}async onFileExists(l,G){let t=this.getFileByPath(l);if(!t)throw new Error("File not found");this.formatter.setTitle(t.basename),this.formatter.setDestinationFile(t);let c=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.formatContentOnly(G));this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let d=await this.app.vault.read(t),b=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.formatContentWithFile(c,this.choice,d,t));this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let a=await this.app.vault.read(t),n=b;if(a!==d){let Z=zg(a,d,b);$G(!Z.isSuccess,()=>`Thefile${l}hasbeenmodifiedsincethelastread.
QuickAdd will now revert to backup.`),e.settings=G,S.replaceState(jI(e.settings))}}e.saveSettings()}varYw=Dx;varOc=require("obsidian");asyncfunctionfx(e,I,l){letG=await(0,Oc.requestUrl)({url:`https://api.github.com/repos/${e}/${I}/releases`,throw:!1}),t=G.json;if(G.status>=400&&"message"int||!Array.isArray(t))thrownewError(`Failed to fetch releases: ${t.message??"Unknown error"}`);letc=t.findIndex(d=>d.tag_name===l);if(c===-1)thrownewError(`Could not find release with tag ${l}`);returnt.slice(0,c).filter(d=>!d.draft&&!d.prerelease)}functionMx(e,I=1){letl=e.split(`
`)}varUi=classextendsOc.Modal{constructor(I,l){super(I),this.previousVersion=l,this.releaseNotesPromise=fx("chhoumann","quickadd",l),this.releaseNotesPromise.then(G=>{if(this.releases=G,this.releases.length===0){this.close();return}this.display()}).catch(G=>{k.logError(`Failed to fetch release notes: ${G}`)})}onOpen(){let{contentEl:I}=this;I.empty(),I.createEl("h1",{text:"Fetching release notes..."})}onClose(){let{contentEl:I}=this;I.empty()}display(){let{contentEl:I}=this;I.empty(),I.classList.add("quickadd-update-modal-container");letl=`### New in QuickAdd v${this.releases[0].tag_name}
`,G="Thank you for using QuickAdd! If you like the plugin, please consider supporting me by buying me a coffee. With your sponsorship, I'll be able to contribute more to my existing projects, start new ones, and be more responsive to issues & feature requests.",t='<div class="quickadd-bmac-container"><a href="https://www.buymeacoffee.com/chhoumann" target="_blank"><img src="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"),d=this.releases.map(Z=>Z.body).join(`
---
`),b=`And now, here is everything new in QuickAdd since your last update (v${this.previousVersion}):`,n=`${l}
${G}
${t}
I'd love to get your feedback on QuickAdd! Please fill out this <a href="https://forms.gle/WRq1ewcKK8qmkqps6">feedback form</a> to let me know what you think.
${b}
---
${Mx(d)}`;Oc.MarkdownRenderer.render(this.app,n,c,this.app.vault.getRoot().path,newOc.Component)}};varBl=require("obsidian");varzi=classextendsBl.Modal{constructor(l,G){super(l);this.showAdvancedSettings=!1;this.settings=G,this.waitForClose=newPromise((t,c)=>{this.rejectPromise=c,this.resolvePromise=t}),this.open(),this.display()}getsystemPromptTokenLength(){letl=De(this.settings.model);returnl?Ie(this.settings.systemPrompt,l):Number.POSITIVE_INFINITY}display(){this.contentEl.empty();letl=this.contentEl.createEl("h2",{text:`${this.settings.name} Settings`});l.addClass("qa-clickable-modal-title"),l.addEventListener("click",async()=>{try{letG=awaitrl.Prompt(this.app,"New name",this.settings.name,this.settings.name);G&&G!==this.settings.name&&(this.settings.name=G,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(l){newBl.Setting(l).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(G=>{lett=ut();for(letcoft)G.addOption(c,c);G.addOption("Ask me","Ask me"),G.setValue(this.settings.model),G.onChange(c=>{this.settings.model=c,this.reload()})})}addOutputVariableNameSetting(l){newBl.Setting(l).setName("Output variable name").setDesc("The name of the variable used to store the AI Assistant output, i.e. {{value:output}}.").addText(G=>{G.setValue(this.settings.outputVariableName).onChange(t=>{this.settings.outputVariableName=t})})}addSystemPromptSetting(l){newBl.Setting(l).setName("System Prompt").setDesc("The system prompt for the AI Assistant");letG=this.contentEl.createEl("div"),t=G.createEl("span",{cls:"qa-ai-token-count"}),c=G.createEl("div",{text:"Exact for OpenAI models; estimates for others.",cls:"qa-ai-token-note"});G.appendChild(t),G.appendChild(c);letd=newBl.TextAreaComponent(l);d.setValue(this.settings.systemPrompt).onChange(asyncZ=>{this.settings.systemPrompt=Z,a.innerText=awaitb.format(Z),n()}),newcG(this.app,d.inputEl,Il.instance);letb=newyG(this.app,Il.instance);d.inputEl.addClass("qa-ai-prompt-textarea");leta=this.contentEl.createEl("span"),n=(0,Bl.debounce)(()=>{t.innerText=`Token count: ${this.systemPromptTokenLength}`},50);n(),(async()=>a.innerText=awaitb.format(this.settings.systemPrompt??""))()}addShowAdvancedSettingsToggle(l){newBl.Setting(l).setName("Show advanced settings").setDesc("Show advanced settings such as temperature, top p, and frequency penalty.").addToggle(G=>{G.setValue(this.showAdvancedSettings),G.onChange(t=>{this.showAdvancedSettings=t,this.reload()})})}addTemperatureSetting(l){newBl.Setting(l).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(G=>{G.setLimits(0,1,.1),G.setDynamicTooltip(),G.setValue(this.settings.modelParameters.temperature??1),G.onChange(t=>{this.settings.modelParameters.temperature=t})})}addTopPSetting(l){newBl.Setting(l).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(G=>{G.setLimits(0,1,.1),G.setDynamicTooltip(),G.setValue(this.settings.modelParameters.top_p??1),G.onChange(t=>{this.settings.modelParameters.top_p=t})})}addFrequencyPenaltySetting(l){newBl.Setting(l).setName("Frequency