`].join("");var g}function MI(X){return X.flags!==void 0?X.flags:[X.global?"g":"",X.ignoreCase?"i":"",X.multiline?"m":"",X.unicode?"u":"",X.sticky?"y":""].join("")}function U(){for(var X=[].slice.call(arguments),t=X.length,g=0;g<t;g+=1)O(X[g]);return c(function(r,T){for(var S,f=new Array(t),XI=0;XI<t;XI+=1){if(!(S=C(X[XI]._(r,T),S)).status)return S;f[XI]=S.value,T=S.index}return C(w(T,f),S)})}function pI(){var X=[].slice.call(arguments);if(X.length===0)throw new Error("seqMap needs at least one argument");var t=X.pop();return B(t),U.apply(null,X).map(function(g){return t.apply(null,g)})}function uI(){var X=[].slice.call(arguments),t=X.length;if(t===0)return xZ("zero alternates");for(var g=0;g<t;g+=1)O(X[g]);return c(function(r,T){for(var S,f=0;f<X.length;f+=1)if((S=C(X[f]._(r,T),S)).status)return S;return S})}function TG(X,t){return Kc(X,t).or(ub([]))}function Kc(X,t){return O(X),O(t),pI(X,t.then(X).many(),function(g,r){return[g].concat(r)})}function zZ(X){y(X);var t="'"+X+"'";return c(function(g,r){var T=r+X.length,S=g.slice(r,T);return S===X?w(T,S):i(r,t)})}function lb(X,t){(function(T){if(!(T instanceof RegExp))throw new Error("not a regexp: "+T);for(var S=MI(T),f=0;f<S.length;f++){var XI=S.charAt(f);if(XI!=="i"&&XI!=="m"&&XI!=="u"&&XI!=="s")throw new Error('unsupported regexp flag "'+XI+'": '+T)}})(X),arguments.length>=2?E(t):t=0;var g=function(T){return RegExp("^(?:"+T.source+")",MI(T))}(X),r=""+X;return c(function(T,S){var f=g.exec(T.slice(S));if(f){if(0<=t&&t<=f.length){var XI=f[0],SI=f[t];return w(S+XI.length,SI)}return i(S,"valid match group (0 to "+f.length+") in "+r)}return i(S,r)})}function ub(X){return c(function(t,g){return w(g,X)})}function xZ(X){return c(function(t,g){return i(g,X)})}function Dc(X){if(R(X))return c(function(t,g){var r=X._(t,g);return r.index=g,r.value="",r});if(typeof X=="string")return Dc(zZ(X));if(X instanceof RegExp)return Dc(lb(X));throw new Error("not a string, regexp, or parser: "+X)}function _Y(X){return O(X),c(function(t,g){var r=X._(t,g),T=t.slice(g,r.index);return r.status?i(g,'not "'+T+'"'):w(g,null)})}function il(X){return B(X),c(function(t,g){var r=k(t,g);return g<t.length&&X(r)?w(g+1,r):i(g,"a character/byte matching "+X)})}function UZ(X,t){arguments.length<2&&(t=X,X=void 0);var g=c(function(r,T){return g._=t()._,g._(r,T)});return X?g.desc(X):g}function Tc(){return xZ("fantasy-land/empty")}W.parse=function(X){if(typeof X!="string"&&!v(X))throw new Error(".parse must be called with a string or Buffer as its argument");var t,g=this.skip(Sc)._(X,0);return t=g.status?{status:!0,value:g.value}:{status:!1,index:GI(X,g.furthest),expected:g.expected},delete K[X],t},W.tryParse=function(X){var t=this.parse(X);if(t.status)return t.value;var g=aG(X,t),r=new Error(g);throw r.type="ParsimmonError",r.result=t,r},W.assert=function(X,t){return this.chain(function(g){return X(g)?ub(g):xZ(t)})},W.or=function(X){return uI(this,X)},W.trim=function(X){return this.wrap(X,X)},W.wrap=function(X,t){return pI(X,this,t,function(g,r){return r})},W.thru=function(X){return X(this)},W.then=function(X){return O(X),U(this,X).map(function(t){return t[1]})},W.many=function(){var X=this;return c(function(t,g){for(var r=[],T=void 0;;){if(!(T=C(X._(t,g),T)).status)return C(w(g,r),T);if(g===T.index)throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause");g=T.index,r.push(T.value)}})},W.tieWith=function(X){return y(X),this.map(function(t){if(function(T){if(!J(T))throw new Error("not an array: "+T)}(t),t.length){y(t[0]);for(var g=t[0],r=1;r<t.length;r++)y(t[r]),g+=X+t[r];return g}return""})},W.tie=function(){return this.tieWith("")},W.times=function(X,t){var g=this;return arguments.length<2&&(t=X),E(X),E(t),c(function(r,T){for(var S=[],f=void 0,XI=void 0,SI=0;SI<X;SI+=1){if(XI=C(f=g._(r,T),XI),!f.status)return XI;T=f.index,S.push(f.value)}for(;SI<t&&(XI=C(f=g._(r,T),XI),f.status);SI+=1)T=f.index,S.push(f.value);return C(w(T,S),XI)})},W.result=function(X){return this.map(function(){return X})},W.atMost=function(X){return this.ti
`),Dp=zZ(`\r
`),Tp=uI(Dp,Kp,jp).desc("newline"),Iw=uI(Tp,Sc);c.all=$Y,c.alt=uI,c.any=zd,c.cr=jp,c.createLanguage=function(X){vart={};for(varginX)({}).hasOwnProperty.call(X,g)&&function(r){t[r]=UZ(function(){returnX[r](t)})}(g);returnt},c.crlf=Dp,c.custom=function(X){returnc(X(w,i))},c.digit=IV,c.digits=GV,c.empty=Tc,c.end=Iw,c.eof=Sc,c.fail=xZ,c.formatError=aG,c.index=VZ,c.isParser=R,c.lazy=UZ,c.letter=fs,c.letters=Ps,c.lf=Kp,c.lookahead=Dc,c.makeFailure=i,c.makeSuccess=w,c.newline=Tp,c.noneOf=function(X){returnil(function(t){returnX.indexOf(t)<0}).desc("none of '"+X+"'")},c.notFollowedBy=_Y,c.of=ub,c.oneOf=function(X){for(vart=X.split(""),g=0;g<t.length;g++)t[g]="'"+t[g]+"'";returnil(function(r){returnX.indexOf(r)>=0}).desc(t)},c.optWhitespace=_s,c.Parser=c,c.range=function(X,t){returnil(function(g){returnX<=g&&g<=t}).desc(X+"-"+t)},c.regex=lb,c.regexp=lb,c.sepBy=TG,c.sepBy1=Kc,c.seq=U,c.seqMap=pI,c.seqObj=function(){for(varX,t={},g=0,r=(X=arguments,Array.prototype.slice.call(X)),T=r.length,S=0;S<T;S+=1){varf=r[S];if(!R(f)){if(J(f)&&f.length===2&&typeoff[0]=="string"&&R(f[1])){varXI=f[0];if(Object.prototype.hasOwnProperty.call(t,XI))thrownewError("seqObj: duplicate key "+XI);t[XI]=!0,g++;continue}thrownewError("seqObj arguments must be parsers or [string, parser] array pairs.")}}if(g===0)thrownewError("seqObj expects at least one named parser, found zero");returnc(function(SI,Zl){for(varBG,Mb={},el=0;el<T;el+=1){varjb,qc;if(J(r[el])?(jb=r[el][0],qc=r[el][1]):(jb=null,qc=r[el]),!(BG=C(qc._(SI,Zl),BG)).status)returnBG;jb&&(Mb[jb]=BG.value),Zl=BG.index}returnC(w(Zl,Mb),BG)})},c.string=zZ,c.succeed=ub,c.takeWhile=function(X){returnB(X),c(function(t,g){for(varr=g;r<t.length&&X(k(t,r));)r++;returnw(r,t.slice(g,r))})},c.test=il,c.whitespace=$s,c["fantasy-land/empty"]=Tc,c["fantasy-land/of"]=ub,c.Binary={bitSeq:h,bitSeqObj:function(X){a();vart={},g=0,r=N(function(S){if(J(S)){varf=S;if(f.length!==2)thrownewError("["+f.join(", ")+"] should be length 2, got length "+f.length);if(y(f[0]),E(f[1]),Object.prototype.hasOwnProperty.call(t,f[0]))thrownewError("duplicate key in bitSeqObj: "+f[0]);returnt[f[0]]=!0,g++,f}returnE(S),[null,S]},X);if(g<1)thrownewError("bitSeqObj expects at least one named pair, got ["+X.join(", ")+"]");varT=N(function(S){returnS[0]},r);returnh(N(function(S){returnS[1]},r)).map(function(S){returnm(function(f,XI){returnXI[0]!==null&&(f[XI[0]]=XI[1]),f},{},N(function(f,XI){return[f,S[XI]]},T))})},byte:function(X){if(a(),E(X),X>255)thrownewError("Value specified to byte constructor ("+X+"=0x"+X.toString(16)+") is larger in value than a single byte.");vart=(X>15?"0x":"0x0")+X.toString(16);returnc(function(g,r){varT=k(g,r);returnT===X?w(r+1,T):i(r,t)})},buffer:function(X){returnF("buffer",X).map(function(t){returnBuffer.from(t)})},encodedString:function(X,t){returnF("string",t).map(function(g){returng.toString(X)})},uintBE:p,uint8BE:p(1),uint16BE:p(2),uint32BE:p(4),uintLE:Q,uint8LE:Q(1),uint16LE:Q(2),uint32LE:Q(4),intBE:u,int8BE:u(1),int16BE:u(2),int32BE:u(4),intLE:s,int8LE:s(1),int16LE:s(2),int32LE:s(4),floatBE:F("floatBE",4).map(function(X){returnX.readFloatBE(0)}),floatLE:F("floatLE",4).map(function(X){returnX.readFloatLE(0)}),doubleBE:F("doubleBE",8).map(function(X){returnX.readDoubleBE(0)}),doubleLE:F("doubleLE",8).map(function(X){returnX.readDoubleLE(0)})},G.exports=c}])})})(Ta,Ta.exports);varn=Ta.exports,OX=()=>/[#*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\u
`+b,{line:W,ch:d.length}),Z.setCursor({line:W+1,ch:b.length})}}catch{M.logError(`unable to insert '${b}' on new line ${I}.`)}}function n0(b,I){Q0(b,"above",I)}function H0(b,I){Q0(b,"below",I)}function Ga(b,I,G="replaceSelection"){let l=b.workspace.getActiveViewOfType(Wb.MarkdownView);if(!l){M.logError("insertLinkWithPlacement:noactiveMarkdownview.");return}let Z=l.editor,c=Z.listSelections().map(m=>({anchor:{...m.anchor},head:{...m.head}}));if(G==="replaceSelection"){Z.replaceSelection(I);return}let W=({line:m,ch:N})=>Z.posToOffset({line:m,ch:N}),d=c.sort((m,N)=>W(N.head)-W(m.head));for(let m of d){let N=W(m.anchor)>W(m.head)?m.anchor:m.head;switch(G){case"afterSelection":{Z.replaceRange(I,N);break}case"endOfLine":{let Y=Z.getLine(N.line),V={line:N.line,ch:Y.length};Z.replaceRange(I,V);break}case"newLine":{let Y=Z.getLine(N.line),V={line:N.line,ch:Y.length},a=Y.endsWith(`
${I}`:""}`;function Ca(b){if(b){let I=new Xu.Notice(Fu("starting",""),1e6);return{setMessage:(G,l)=>{I.setMessage(Fu(G,l))},hide:()=>I.hide()}}return{setMessage:(I,G)=>{M.logMessage(`(${I}) ${G}`)},hide:()=>{}}}var Jl=(b,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 au(G).encode(b).length}catch{return ZX("cl100k_base").encode(b).length}};async function o5(b,I,G){if(typeof b!="function")throw new TypeError("Callbackmustbeafunction.");if(!(I instanceof Promise))throw new TypeError("PromisemustbeaninstanceofPromise.");if(typeof G!="number"||G<=0)throw new TypeError("Intervalmustbeapositivenumber.");let l=!1;for(I.finally(()=>{l=!0});!l;)b(),await sleep(G)}async function i5(b,I,G){let l;if(I.enable)l=G.find(d=>d.path.endsWith(I.name));else{let d=G.map(m=>m.basename);l=await _G.Suggest(b,d,G)}El(l,"Prompttemplatedoesnotexist");let Z=l.path,c=b.vault.getAbstractFileByPath(Z);El(c instanceof pu.TFile,`${Z} is not a file`);let W=await b.vault.cachedRead(c);return[l.basename,W]}async function Qu(b,I,G){if(lI.getState().disableOnlineFeatures)throw new Error("BlockingrequesttoOpenAI:Onlinefeaturesaredisabledinsettings.");let l=Ca(I.showAssistantMessages);try{let{apiKey:Z,model:c,outputVariableName:W,promptTemplate:d,systemPrompt:m,promptTemplateFolder:N}=I,Y=sZ(b,N),[V,a]=await i5(b,d,Y);l.setMessage("waiting","QuickAddisformattingtheprompttemplate.");let h=await G(a),F=["prompting",`Using prompt template "${V}".`];l.setMessage(F[0],F[1]);let p=ya(b,Z,c,m,I.modelOptions)(h),u=(await WX(p,100,J=>{l.setMessage(F[0],`${F[1]} (${(J/1e3).toFixed(2)}s)`)},J=>{l.setMessage("finished",`Took ${(J/1e3).toFixed(2)}s.`)})).content,s=(">"+u).replace(/\n/g,`
> `),R={[W]:u,[`${W}-quoted`]:s};return setTimeout(()=>l.hide(),5e3),R}catch(Z){l.setMessage("dead",Z.message),setTimeout(()=>l.hide(),5e3)}}async function WX(b,I,G,l){let Z=Date.now();return await o5(()=>G(Date.now()-Z),b,I),l(Date.now()-Z),await b}async function nu(b,I,G){if(lI.getState().disableOnlineFeatures)throw new Error("BlockingrequesttoOpenAI:Onlinefeaturesaredisabledinsettings.");let l=Ca(I.showAssistantMessages);try{let{apiKey:Z,model:c,outputVariableName:W,systemPrompt:d,prompt:m,modelOptions:N}=I;l.setMessage("waiting","QuickAddisformattingtheprompttemplate.");let Y=await G(m),V=["prompting","Usingcustomprompt."];l.setMessage(V[0],V[1]);let h=ya(b,Z,c,d,N)(Y),H=(await WX(h,100,u=>{l.setMessage(V[0],`${V[1]} (${(u/1e3).toFixed(2)}s)`)},u=>{l.setMessage("finished",`Took ${(u/1e3).toFixed(2)}s.`)})).content,p=(">"+H).replace(/\n/g,`
> `),Q={[W]:H,[`${W}-quoted`]:p};return setTimeout(()=>l.hide(),5e3),Q}catch(Z){l.setMessage("dead",Z.message),setTimeout(()=>l.hide(),5e3)}}var cX=class{constructor(I,G){this.maxRequests=I;this.intervalMs=G;this.queue=[];this.pendingPromises=[]}add(I){return new Promise((G,l)=>{this.queue.push(async()=>{try{G(await I())}catch(Z){l(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(l=>l!==G),this.schedule()}),setTimeout(()=>this.schedule(),this.intervalMs)}};async function Hu(b,I,G){if(lI.getState().disableOnlineFeatures)throw new Error("BlockingrequesttoOpenAI:Onlinefeaturesaredisabledinsettings.");let l=Ca(I.showAssistantMessages);try{let{apiKey:Z,model:c,outputVariableName:W,systemPrompt:d,promptTemplate:m,text:N,modelOptions:Y}=I;l.setMessage("chunking","Creatingpromptchunkswithtextandprompttemplate");let V=I.chunkSeparator||/\n/g,a=N.split(V),h=Jl(d,c),F=await G(m,{chunk:""}),H=Jl(F,c),p=Ru(c.name)/2-h,Q=I.shouldMerge??!0,u=[],s=p-H;if(Q){let k=[],E="",B=0;for(let y of a){let D=Jl(y,c)+1;if(D>s)throw new Error(`The chunk "${y.slice(0,25)}..." is too large to fit in a single prompt.`);B+D<s?(E+=y,B+=D):(k.push(E),E=y,B=D)}E!==""&&k.push(E);for(let y of k){let D=await G(m,{chunk:y});u.push(D)}}else for(let k of a){let E=Jl(k,c);if(E>p)throw new Error(`Chunk size (${E}) is larger than the maximum chunk size (${p}). Please check your chunk separator.`);let B=await G(m,{chunk:k});u.push(B)}let R=ya(b,Z,c,d,Y),J=["prompting",`${u.length} prompts being sent.`];l.setMessage(J[0],J[1]);let v=new cX(5,1e3*30),w=Promise.all(u.map(k=>v.add(()=>R(k)))),K=(await WX(w,100,k=>{l.setMessage(J[0],`${J[1]} (${(k/1e3).toFixed(2)}s)`)},k=>{l.setMessage("finished",`Took ${(k/1e3).toFixed(2)}s.`)})).map(k=>k.content).join(I.resultJoiner),GI=(">"+K).replace(/\n/g,`
> `),O={[W]:K,[`${W}-quoted`]:GI};return setTimeout(()=>l.hide(),5e3),O}catch(Z){l.setMessage("dead",Z.message),setTimeout(()=>l.hide(),5e3)}}var TW=require("obsidian"),aY=class b extends TW.Modal{constructor(G,l,Z=[]){super(G);this.items=l;this.selectedItems=Z;this._selectedItems=[...Z],this.promise=new Promise((c,W)=>{this.resolvePromise=c,this.rejectPromise=W}),this.display(),this.open()}static Open(G,l,Z){return new b(G,l,Z).promise}display(){this.contentEl.empty(),this.containerEl.addClass("quickAddModal","checkboxPrompt"),this.addCheckboxRows(),this.addSubmitButton()}onClose(){super.onClose(),this.resolved||this.rejectPromise("noinputgiven.")}addCheckboxRows(){let G=this.contentEl.createDiv("checkboxRowContainer");this.items.forEach(l=>this.addCheckboxRow(l,G))}addCheckboxRow(G,l){let Z=l.createDiv("checkboxRow");Z.createEl("span",{text:G}),new TW.ToggleComponent(Z).setTooltip(`Toggle ${G}`).setValue(this._selectedItems.contains(G)).onChange(W=>{if(W)this._selectedItems.push(G);else{let d=this._selectedItems.findIndex(m=>G===m);this._selectedItems.splice(d,1)}})}addSubmitButton(){let G=this.contentEl.createDiv("submitButtonContainer");new TW.ButtonComponent(G).setButtonText("Submit").setCta().onClick(Z=>{this.resolved=!0,this.resolvePromise(this._selectedItems),this.close()})}};var ga=require("obsidian"),hY=class b extends ga.Modal{constructor(G,l,Z){super(G);this.header=l;this.text=Z;this.waitForClose=new Promise(c=>{this.resolvePromise=c}),this.open(),this.display()}static Show(G,l,Z){return new b(G,l,Z).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(Z=>this.contentEl.createEl("p",{text:Z}));let G=this.contentEl.createDiv(),l=new ga.ButtonComponent(G).setButtonText("OK").onClick(()=>this.close());Object.assign(G.style,{display:"flex",justifyContent:"flex-end"}),l.buttonEl.focus()}onClose(){super.onClose(),this.resolvePromise()}};var SW=require("obsidian");var gc=class b extends SW.Modal{constructor(G,l,Z,c){super(G);this.header=l;this.didSubmit=!1;this.submitClickCallback=G=>this.submit();this.cancelClickCallback=G=>this.cancel();this.submitEnterCallback=G=>{(G.ctrlKey||G.metaKey)&&G.key==="Enter"&&(G.preventDefault(),this.submit())};this.placeholder=Z??"",this.input=c??"",this.waitForClose=new Promise((W,d)=>{this.resolvePromise=W,this.rejectPromise=d}),this.display(),this.open(),this.fileSuggester=new MW(G,this.inputComponent.inputEl),this.tagSuggester=new jW(G,this.inputComponent.inputEl)}static Prompt(G,l,Z,c){return new b(G,l,Z,c).waitForClose}display(){this.containerEl.addClass("quickAddModal","qaWideInputPrompt"),this.contentEl.empty(),this.titleEl.textContent=this.header;let G=this.contentEl.createDiv();this.inputComponent=this.createInputField(G,this.placeholder,this.input),this.createButtonBar(G)}createInputField(G,l,Z){let c=new SW.TextAreaComponent(G);return c.inputEl.classList.add("wideInputPromptInputEl"),c.inputEl.setAttribute("dir","auto"),c.setPlaceholder(l??"").setValue(Z??"").onChange(W=>this.input=W).inputEl.addEventListener("keydown",this.submitEnterCallback),c}createButton(G,l,Z){let c=new SW.ButtonComponent(G);return c.setButtonText(l).onClick(Z),c}createButtonBar(G){let l=G.createDiv();this.createButton(l,"Ok",this.submitClickCallback).setCta().buttonEl.style.marginRight="0",this.createButton(l,"Cancel",this.cancelClickCallback),l.style.display="flex",l.style.flexDirection="row-reverse",l.style.justifyContent="flex-start",l.style.marginTop="1rem",l.style.gap="0.5rem"}submit(){this.didSubmit=!0,this.close()}cancel(){this.close()}resolveInput(){this.didSubmit?this.resolvePromise(this.input):this.rejectPromise("Noinputgiven.")}removeInputListener(){this.inputComponent.inputEl.removeEventListener("keydown",this.submitEnterCallback)}onOpen(){super.onOpen(),this.inputComponent.inputEl.focus(),this.inputComponent.inputEl.select()}onClose(){super.onClose(),this.resolveInput(),this.removeInputListener()}};var RY=require("obsidian"),Tl=class b
`,shouldMerge:d?.shouldMerge??!0},(H,p)=>{let Q={...m,...p};return V(H,Q,!1)});return F?(d?.shouldAssignVariables&&Object.assign(l.variables,F),F):(jI(new Error("AIAssistantreturnednull"),"ChunkedAIPrompterror"),{})},getModels:()=>gb(),getMaxTokens:Z=>{let c=Yb(Z);if(!c)throw new Error(`Model ${Z} not found.`);return c.maxTokens},countTokens(Z,c){return Jl(Z,c)}},utility:{getClipboard:async()=>await navigator.clipboard.readText(),setClipboard:async Z=>await navigator.clipboard.writeText(Z),getSelectedText:()=>{let Z=I.workspace.getActiveViewOfType(Ge.MarkdownView);if(!Z){jI(new Error("Noactiveview"),"Couldnotgetselectedtext");return}if(!Z.editor.somethingSelected()){jI(new Error("Notextselected"),"Couldnotgetselectedtext");return}return Z.editor.getSelection()}},date:{now:(Z,c)=>fb({format:Z,offset:c}),tomorrow:Z=>fb({format:Z,offset:1}),yesterday:Z=>fb({format:Z,offset:-1})},fieldSuggestions:{getFieldValues:async(Z,c)=>{let W={folder:c?.folder,tags:c?.tags,inline:c?.includeInline??!1},d=I.vault.getMarkdownFiles();d=Zh.filterFiles(d,W,N=>I.metadataCache.getFileCache(N));let m=new Set;for(let N of d){let V=I.metadataCache.getFileCache(N)?.frontmatter?.[Z];if(V!=null){if(Array.isArray(V))V.forEach(a=>{let h=a.toString().trim();h&&m.add(h)});else if(typeof V!="object"){let a=V.toString().trim();a&&m.add(a)}}if(W.inline){let a=await I.vault.read(N);dd.getFieldValues(a,Z).forEach(F=>m.add(F))}}return Array.from(m).sort()},clearCache:Z=>{Lb.getInstance().clear(Z)}}}}static async inputPrompt(I,G,l,Z){try{return await IG.Prompt(I,G,l,Z)}catch{return}}static async wideInputPrompt(I,G,l,Z){try{return await gc.Prompt(I,G,l,Z)}catch{return}}static async yesNoPrompt(I,G,l){try{return await Tl.Prompt(I,G,l)}catch{return}}static async infoDialog(I,G,l){try{return await hY.Show(I,G,l)}catch{return}}static async suggester(I,G,l,Z,c=!1,W){try{let d;return typeof G=="function"?d=l.map(G):d=G,c?await Kl.Suggest(I,d,l,{...Z?{placeholder:Z}:{},...W?.renderItem?{renderItem:W.renderItem}:{}}):await _G.Suggest(I,d,l,Z,W?.renderItem)}catch{return}}static async checkboxPrompt(I,G,l){try{return await aY.Open(I,G,l)}catch{return}}};var Yd=class extends kW{};var jG=[];for(let b=0;b<256;++b)jG.push((b+256).toString(16).slice(1));function le(b,I=0){return(jG[b[I+0]]+jG[b[I+1]]+jG[b[I+2]]+jG[b[I+3]]+"-"+jG[b[I+4]]+jG[b[I+5]]+"-"+jG[b[I+6]]+jG[b[I+7]]+"-"+jG[b[I+8]]+jG[b[I+9]]+"-"+jG[b[I+10]]+jG[b[I+11]]+jG[b[I+12]]+jG[b[I+13]]+jG[b[I+14]]+jG[b[I+15]]).toLowerCase()}var jX,zg=new Uint8Array(16);function KX(){if(!jX){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues()notsupported.Seehttps://github.com/uuidjs/uuid#getrandomvalues-not-supported");jX=crypto.getRandomValues.bind(crypto)}return jX(zg)}var xg=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),DX={randomUUID:xg};function Ug(b,I,G){if(DX.randomUUID&&!I&&!b)return DX.randomUUID();b=b||{};let l=b.random??b.rng?.()??KX();if(l.length<16)throw new Error("Random bytes length must be >= 16");if(l[6]=l[6]&15|64,l[8]=l[8]&63|128,I){if(G=G||0,G<0||G+16>I.length)throw new RangeError(`UUID byte range ${G}:${G+15} is out of buffer bounds`);for(let Z=0;Z<16;++Z)I[G+Z]=l[Z];return I}return le(l)}var Pl=Ug;var $G=class{constructor(I,G){this.name=I,this.type=G,this.id=Pl()}};var be=require("obsidian");var YG=class extends $G{constructor(I){super(I,"EditorCommand"),this.editorCommandType=I}static getSelectedText(I){return this.getActiveMarkdownView(I).editor.getSelection()}static getActiveMarkdownView(I){let G=I.workspace.getActiveViewOfType(be.MarkdownView);if(!G)throw M.logError("no active markdown view."),new Error("no active markdown view.");return G}};var Vd=class extends YG{constructor(){super("Cut")}static async run(I){let G=YG.getSelectedText(I),l=YG.getActiveMarkdownView(I);if(!G){M.logError("nothing selected.");return}await navigator.clipboard.writeText(G),l.editor.replaceSelection("")}};var ad=class extends YG{constructor(){super("Copy")}static async run(I){let G=YG.getSelectedText(I);await navigator.clipboard.writeText(G)}};va
`)}var We=require("obsidian"),kb=class extends Yd{constructor(I,G,l,Z,c){super(I),this.choice=l,this.plugin=G,this.macro=l?.macro,this.choiceExecutor=Z,this.params={app:this.app,quickAddApi:Nd.GetApi(I,G,Z),variables:{},obsidian:Bg},c?.forEach((W,d)=>{this.params.variables[d]=W})}async run(){if(!this.macro||!this.macro.commands){M.logError(`Nocommandsinthemacroforchoice'${this.choice.name}'`);return}await this.executeCommands(this.macro.commands)}getOutput(){return this.output}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 ce(G.time),G?.type==="NestedChoice"&&await this.executeNestedChoice(G),G?.type==="EditorCommand"&&await this.executeEditorCommand(G),G?.type==="AIAssistant"&&await this.executeAIAssistant(G),G?.type==="OpenFile"&&await this.executeOpenFile(G),Object.keys(this.params.variables).forEach(l=>{this.choiceExecutor.variables.set(l,this.params.variables[l])})}async executeUserScript(I){let G=await AW(I,this.app);if(!G){M.logError(`failedtoloaduserscript${I.path}.`);return}G.settings&&(this.userScriptCommand=I);try{await this.userScriptDelegator(G)}catch(l){jI(l,`Failedtorunuserscript${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:M.logError(`userscriptinmacrofor'${this.choice.name}'isinvalid`)}}async onExportIsFunction(I,G){this.output=await I(this.params,G||{})}async onExportIsObject(I){if(Object.keys(I).length===0)throw new Error(`userscriptinmacrofor'${this.choice.name}'isanemptyobject`);if(this.userScriptCommand&&I.entry!==null){await this.runScriptWithSettings(I,this.userScriptCommand);return}try{let G=Object.keys(I),l=await _G.Suggest(this.app,G,G);await this.userScriptDelegator(I[l])}catch(G){jI(G,"Error in script object handling","LOG")}}executeObsidianCommand(I){this.app.commands.executeCommandById(I.commandId)}async executeChoice(I){let G=this.plugin.getChoiceById(I.choiceId);if(!G){M.logError("choice could not be found.");return}await this.choiceExecutor.execute(G)}async executeNestedChoice(I){let G=I.choice;if(!G){M.logError(`choicein${I.name}isinvalid`);return}await this.choiceExecutor.execute(G)}async executeEditorCommand(I){switch(I.editorCommandType){case"Cut":await Vd.run(this.app);break;case"Copy":await ad.run(this.app);break;case"Paste":await hd.run(this.app);break;case"Paste with format":await Rd.run(this.app);break;case"Select active line":Fd.run(this.app);break;case"Select link on active line":Xd.run(this.app);break}}async executeAIAssistant(I){if(lI.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=lI.getState().ai,l=gb(),Z=I.model==="Ask me"?await _G.Suggest(this.app,l,l):I.model,c=Yb(Z);if(!c)throw new Error(`Model${Z}notfoundwithanyprovider.`);let W=new Fb(this.app,UI.instance,this.choiceExecutor),d=Cc(c.name);if(!d)throw new Error(`Model${c.name}notfoundintheAIproviderssettings.`);let m=await Qu(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 N=>W.formatFileContent(N));for(let N in m)this.choiceExecutor.variables.set(N,m[N])}async executeOpenFile(I){try{let Z=(await new Fb(this.app,UI.instance,this.choiceExecutor).formatF
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}functionNo(){thrownewTypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}functionrY(b,I){varG=typeofSymbol<"u"&&b[Symbol.iterator]||b["@@iterator"];if(!G){if(Array.isArray(b)||(G=cp(b))||I&&b&&typeofb.length=="number"){G&&(b=G);varl=0,Z=function(){};return{s:Z,n:function(){returnl>=b.length?{done:!0}:{done:!1,value:b[l++]}},e:function(m){throwm},f:Z}}thrownewTypeError(`Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}varc=!0,W=!1,d;return{s:function(){G=G.call(b)},n:function(){varm=G.next();returnc=m.done,m},e:function(m){W=!0,d=m},f:function(){try{!c&&G.return!=null&&G.return()}finally{if(W)throwd}}}}varYo="finalize",Vo="consider";functionvd(b,I,G){b.dispatchEvent(newCustomEvent(Yo,{detail:{items:I,info:G}}))}functionkZ(b,I,G){b.dispatchEvent(newCustomEvent(Vo,{detail:{items:I,info:G}}))}varHh="draggedEntered",zY="draggedLeft",uh="draggedOverIndex",Wp="draggedLeftDocument",Rh={LEFT_FOR_ANOTHER:"leftForAnother",OUTSIDE_OF_ANY:"outsideOfAny"};functionao(b,I,G){b.dispatchEvent(newCustomEvent(Hh,{detail:{indexObj:I,draggedEl:G}}))}functionho(b,I,G){b.dispatchEvent(newCustomEvent(zY,{detail:{draggedEl:I,type:Rh.LEFT_FOR_ANOTHER,theOtherDz:G}}))}functionRo(b,I){b.dispatchEvent(newCustomEvent(zY,{detail:{draggedEl:I,type:Rh.OUTSIDE_OF_ANY}}))}functionFo(b,I,G){b.dispatchEvent(newCustomEvent(uh,{detail:{indexObj:I,draggedEl:G}}))}functionXo(b){window.dispatchEvent(newCustomEvent(Wp,{detail:{draggedEl:b}}))}varYl={DRAG_STARTED:"dragStarted",DRAGGED_ENTERED:Hh,DRAGGED_ENTERED_ANOTHER:"dragEnteredAnother",DRAGGED_OVER_INDEX:uh,DRAGGED_LEFT:zY,DRAGGED_LEFT_ALL:"draggedLeftAll",DROPPED_INTO_ZONE:"droppedIntoZone",DROPPED_INTO_ANOTHER:"droppedIntoAnother",DROPPED_OUTSIDE_OF_ANY:"droppedOutsideOfAny",DRAG_STOPPED:"dragStopped"},ll={POINTER:"pointer",KEYBOARD:"keyboard"},th="isDndShadowItem",eh="data-is-dnd-shadow-item-internal",po="data-is-dnd-shadow-item-hint",Mc="id:dnd-shadow-placeholder-0000",Qo="dnd-action-dragged-el",UG="id",_X=0;functionye(){_X++}functionCe(){if(_X===0)thrownewError("Bug! trying to decrement when there are no dropzones");_X--}vardp=typeofwindow>"u",nI=function(){};function$X(b){varI=arguments.length>1&&arguments[1]!==void0?arguments[1]:!0,G,l=I?to(b):b.getBoundingClientRect(),Z=getComputedStyle(b),c=Z.transform;if(c){varW,d,m,N;if(c.startsWith("matrix3d("))G=c.slice(9,-1).split(/, /),W=+G[0],d=+G[5],m=+G[12],N=+G[13];elseif(c.startsWith("matrix("))G=c.slice(7,-1).split(/, /),W=+G[0],d=+G[3],m=+G[4],N=+G[5];elsereturnl;varY=Z.transformOrigin,V=l.x-m-(1-W)*parseFloat(Y),a=l.y-N-(1-d)*parseFloat(Y.slice(Y.indexOf(" ")+1)),h=W?l.width/W:b.offsetWidth,F=d?l.height/d:b.offsetHeight;return{x:V,y:a,width:h,height:F,top:a,right:V+h,bottom:a+F,left:V}}elsereturnl}functionge(b){varI=$X(b);return{top:I.top+window.scrollY,bottom:I.bottom+window.scrollY,left:I.left+window.scrollX,right:I.right+window.scrollX}}functionoe(b){varI=b.getBoundingClientRect();return{top:I.top+window.scrollY,bottom:I.bottom+window.scrollY,left:I.left+window.scrollX,right:I.right+window.scrollX}}functionie(b){return{x:(b.left+b.right)/2,y:(b.top+b.bottom)/2}}functionno(b,I){returnMath.sqrt(Math.pow(b.x-I.x,2)+Math.pow(b.y-I.y,2))}functionsh(b,I){returnb.y<=I.bottom&&b.y>=I.top&&b.x>=I.left&&b.x<=I.right}functionAY(b){returnie(oe(b))}functionQe(b,I){varG=AY(b),l=ge(I);returnsh(G,l)}functionHo(b,I){varG=AY(b),l=AY(I);returnno(G,l)}functionuo(b){varI=oe(b);returnI.right<0||I.left>document.documentElement.scrollWidth||I.bottom<0||I.top>document.documentElement.scrollHeight}functionto(b){for(varI=b.getBoundingClientRect(),G={top:I.top,bottom:I.bottom,left:I.left,right:I.right},l=b.parentElement;l&&l!==document.body;){varZ=l.getBoundingClientRect(),c=window.getComputedStyle(l).overflowY,W=window.getComputedStyle(l).overflowX,d=c==="scroll"||c==="auto",m=W==="scroll"||W==="auto";d&&(G.top=Math.max(G.top,Z.top),G.bottom=Math.min(G.bottom,Z.bottom)),m&&(G.left=Math.max(G.left,Z.left),G.right=Math.min(G.right,Z.right)),l=l.parentElement}returnG.top=Math.max(G.top,0),G.bottom=Math.min(G.bottom,window.innerHeight),G.left=Math.max(G.left,0),G.right=Math.min(G.right,window.innerWidth),{top:G.top,bottom:G.bottom,left:G.left,right:G.right,width:Math.max(0,G.right-G.left),height:Math.max(0,G.bottom-G.top)}}vared;functionmp(){nI(function(){return"resetting indexes cache"}),ed=newMap}mp();functioneo(b){varI=Array.from(b.children).f
`)}}vargs=b=>b.join(""),QA=b=>b.split(/\b/),nA=Cs("<<<<<<< YOUR CHANGES","=======",">>>>>>> APP AUTHORS CHANGES",gs),HA={splitFunction:QA,joinFunction:gs,conflictFunction:nA};functionrp(b,I,G,l={}){l=Object.assign({},HA,l);let[Z,c,W]=[b,I,G].map(N=>l.splitFunction.call(l,N)),d=qY.merge(Z,c,W);returnfY.collateMerge(d,l.joinFunction,l.conflictFunction)}varos=rp;varLs=require("obsidian");functionis(b,I){returnb.line===I.line}functionuA(b){letI=[];returnb.forEach((G,l)=>{letZ=G.match(/^(#+)[\s]+(.*)$/);Z&&I.push({level:Z[1].length,text:Z[2],line:l})}),I}functionc2(b,I,G=!1){letl=uA(b),Z=l.find(N=>N.line===I),c=!!Z;if(!c&&G)thrownewError(`Target line ${I} is not a heading, but we are trying to find the end of its section.`);if(!c&&!G){letN=As(b,I,Y=>Y.trim()==="");returnN!==null&&N>I?N-1:I}letW=b.length-1,d=tA(Z,l,b,G),m=wA(b,d,N=>N.trim()!=="");if(m!==null){if(m<I)returnI;letN=b[m+1].trim()==="";returnm+1===W&&!N?d:m===0?m+1:m}returnd}functiontA(b,I,G,l){letZ=I.findIndex(Y=>is(Y,b)),c=Z===I.length-1,W=G.length-1;if(c)returnW;let[d,m]=eA(b,I);if(m&&d===I.length)returnW;if(m&&l)returnI[d].line-1;if(m&&!l)returnI[Z+1].line;if(!l&&!m){letY=sA(b.line,I);returnY===null?W:Y}returnW}functioneA(b,I){letG=I.findIndex(Z=>is(Z,b)),l=As(I,G,Z=>Z.level<=b.level);returnl===null?[-1,!1]:[l,!0]}functionsA(b,I){letG=I.findIndex(l=>l.line>b);returnG===-1?null:G}functionwA(b,I,G){for(letl=I-1;l>=0;l--)if(G(b[l]))returnl;returnnull}functionAs(b,I,G){for(letl=I+1;l<b.length;l++)if(G(b[l]))returnl;returnnull}varW2=classextendsFb{constructor(){super(...arguments);this.file=null;this.fileContent="";this.templaterProcessed=!1}asyncformatContentWithFile(G,l,Z,c){if(this.choice=l,this.file=c,this.fileContent=Z,!l||!c||Z===null)returnG;letW=l.insertAfter.enabled||l.prepend||!l.captureToActiveFile;returnawaitthis.formatFileContent(G,W)}asyncformatContent(G,l){returnthis.choice=l,l?awaitthis.formatFileContent(G):G}asyncformatFileContent(G,l=!0){letZ=awaitsuper.formatFileContent(G);if(Z=this.replaceLinebreakInString(Z),l&&this.file&&!this.templaterProcessed){letd=awaitIa(this.app,Z,this.file);d&&(Z=d),this.templaterProcessed=!0}if(Z.trim()==="")returnthis.fileContent;if(this.choice.prepend){letd=!this.choice.task;return`${this.fileContent}${d?`
`:""}${Z}`}if(this.choice.insertAfter.enabled)returnawaitthis.insertAfterHandler(Z);letW=this.file?this.getFrontmatterEndPosition(this.file):null;returnW?this.insertTextAfterPositionInBody(Z,this.fileContent,W):`${Z}${this.fileContent}`}asyncformatContentOnly(G){letl=awaitsuper.formatFileContent(G);returnl=this.replaceLinebreakInString(l),l.trim()===""?this.fileContent:l}normalizeTarget(G){returnG.replace("\\n","").trimEnd()}findInsertAfterIndex(G,l){letZ=this.normalizeTarget(l),c=-1;for(letW=0;W<G.length;W++){letd=G[W].trimStart();if(d===Z)returnW;if(d.startsWith(Z)){letm=d.slice(Z.length);if(/^\s*$/.test(m))returnW;c===-1&&(c=W)}}returnc}asyncinsertAfterHandler(G){letl=awaitthis.formatLocationString(this.choice.insertAfter.after),Z=TX(this.fileContent),c=this.findInsertAfterIndex(Z,l);if(c===-1){if(this.choice.insertAfter?.createIfNotFound)returnawaitthis.createInsertAfterIfNotFound(G);jI(newError("Unable to find insert after line in file"),"Insert After Error")}if(this.choice.insertAfter?.insertAtEnd){if(!this.file)thrownewError("Tried to get sections without file.");c=c2(Z,c,!!this.choice.insertAfter.considerSubsections)??Z.length-1}returnthis.insertTextAfterPositionInBody(G,this.fileContent,c)}asynccreateInsertAfterIfNotFound(G){letZ=`${this.replaceLinebreakInString(awaitthis.formatLocationString(this.choice.insertAfter.after))}
${Z}`;if(this.choice.insertAfter?.createIfNotFoundLocation===RV)try{letc=this.app.workspace.getActiveViewOfType(Ls.MarkdownView);if(!c)thrownewError("No active view.");letd=c.editor.getCursor().line;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)thrownewError("Tried to get sections without file.");letN=TX(this.fileContent);d=c2(N,d,!!this.choice.insertAfter.considerSubsections)??N.length-1}returnthis.insertTextAfterPositionInBody(Z,this.fileContent,d)}catch(c){jI(c,`Unable to insert line '${this.choice.insertAfter.after}' at cursor position`)}}getFrontmatterEndPosition(G){letl=this.app.metadataCache.getFileCache(G);return!l||!l.frontmatter?(M.logMessage("could not get frontmatter. Maybe there isn't any."),-1):l.frontmatterPosition?l.frontmatterPosition.end.line:-1}insertTextAfterPositionInBody(G,l,Z){if(Z===-1){letm=!this.choice.task;return`${G}${m?`
${G}${d}`}};functionzp(b){returnb.captureToActiveFile&&b.newLineCapture?.enabled?b.newLineCapture.direction==="above"?"newLineAbove":"newLineBelow":b.captureToActiveFile&&!b.prepend&&!b.insertAfter.enabled?"currentLine":b.insertAfter.enabled?"insertAfter":b.prepend?"prepend":"append"}varks=4e3,d2=classextendsYd{constructor(G,l,Z,c){super(G);this.choiceExecutor=c;this.choice=Z,this.plugin=l,this.formatter=newW2(G,l,c)}showSuccessNotice(G,{wasNewFile:l,action:Z}){letc=`'${G.basename}'`;if(l){newxp.Notice(`Created and captured to ${c}`,ks);return}letW="";switch(Z){case"currentLine":W=`Captured to current line in ${c}`;break;case"prepend":W=`Captured to top of ${c}`;break;case"append":W=`Captured to ${c}`;break;case"insertAfter":{letd=this.choice.insertAfter.after;W=d?`Captured to ${c} under '${d}'`:`Captured to ${c}`;break}}newxp.Notice(W,ks)}asyncrun(){try{letG=awaitthis.getFormattedPathToCaptureTo(this.choice.captureToActiveFile),l=this.getCaptureContent(),Z,c=awaitthis.fileExists(G);if(c)Z=this.onFileExists.bind(this);elseif(this.choice?.createFileIfItDoesntExist?.enabled)Z=this.onCreateFileIfItDoesntExist.bind(this);else{M.logWarning(`The file ${G} does not exist and "Create file if it doesn't exist" is disabled.`);return}let{file:W,newFileContent:d,captureContent:m}=awaitZ(G,l),N=zp(this.choice);if(N==="currentLine"||N==="newLineAbove"||N==="newLineBelow"){letV=awaitIa(this.app,m,W);switch(N){case"currentLine":p0(V,this.app);break;case"newLineAbove":n0(V,this.app);break;case"newLineBelow":H0(V,this.app);break}}elseawaitthis.app.vault.modify(W,d),awaitnc(this.app,W);if(this.plugin.settings.showCaptureNotification){letV=zp(this.choice);this.showSuccessNotice(W,{wasNewFile:!c,action:V})}letY=oZ(this.choice.appendLink);Y.enabled&&Ga(this.app,this.app.fileManager.generateMarkdownLink(W,""),Y.placement),this.choice.openFile&&W&&(la(this.app,W)||awaitiW(this.app,W,this.choice.fileOpening))}catch(G){jI(G,`Error running capture choice "${this.choice.name}"`)}}getCaptureContent(){letG;returnthis.choice.format.enabled?G=this.choice.format.format:G=DZ,this.choice.task&&(G=`- [ ] ${G}
`),G}asyncgetFormattedPathToCaptureTo(G){letl=this.choiceExecutor?.variables?.get(Md);if(!G&&l&&typeofl=="string"&&l.length>0)returnl;if(G){letY=this.app.workspace.getActiveFile();returnEl(Y,"Cannot capture to active file - no active file."),Y.path}letZ=this.choice.captureTo,c=awaitthis.formatFilePath(Z),W=c.replace(/^\/$|\/\.md$|^\.md$/,""),d=W==="",m=d||ba(this.app,W),N=c.startsWith("#");if(m)returnthis.selectFileInFolder(W,d);if(N){letY=c.replace(/\.md$/,"");returnthis.selectFileWithTag(Y)}returnc}asyncselectFileInFolder(G,l){letZ=G.endsWith("/")||l?G:`${G}/`,c=sZ(this.app,Z);El(c.length>0,`Folder ${Z} is empty.`);letW=c.map(N=>N.path),d=awaitKl.Suggest(this.app,W.map(N=>N.replace(Z,"")),W);El(!!d&&d.length>0,"No file selected for capture.");letm=d.startsWith(`${Z}`)?d:`${Z}/${d}`;returnawaitthis.formatFilePath(m)}asyncselectFileWithTag(G){letl=G.startsWith("#")?G:`#${G}`,Z=Za(this.app,l);El(Z.length>0,`No files with tag ${G}.`);letc=Z.map(d=>d.path),W=awaitKl.Suggest(this.app,c,c);returnEl(!!W&&W.length>0,"No file selected for capture."),awaitthis.formatFilePath(W)}asynconFileExists(G,l){letZ=this.getFileByPath(G);if(!Z)thrownewError("File not found");this.formatter.setTitle(Z.basename);letc=awaitthis.formatter.formatContentOnly(l),W=awaitthis.app.vault.read(Z),d=awaitthis.formatter.formatContentWithFile(c,this.choice,W,Z),m=awaitthis.app.vault.read(Z),N=d;if(m!==W){letY=os(m,W,d);El(!Y.isSuccess,()=>`The file ${G} has been modified since the last read.
This is in order to prevent data loss.`),N=Y.joinedResults()}return{file:Z,newFileContent:N,captureContent:c}}asynconCreateFileIfItDoesntExist(G,l){letZ=G.split("/").pop()?.replace(/\.md$/,"")||"";this.formatter.setTitle(Z);letc=awaitthis.formatter.formatContentOnly(l),W="";this.choice.createFileIfItDoesntExist.createWithTemplate&&(W=awaitnewgZ(this.app,this.plugin,this.choice.createFileIfItDoesntExist.template,this.choiceExecutor).run());letd=awaitthis.createFileWithInput(G,W);this.choice.createFileIfItDoesntExist.createWithTemplate&&W&&awaitnc(this.app,d);letm=awaitthis.app.vault.read(d),N=awaitthis.formatter.formatContentWithFile(c,this.choice,m,d);return{file:d,newFileContent:N,captureContent:c}}asyncformatFilePath(G){letl=awaitthis.formatter.formatFileName(G,this.choice.name);returnthis.normalizeMarkdownFilePath("",l)}};varm2=require("obsidian");varrZ=classbextendsm2.FuzzySuggestModal{constructor(G,l,Z){super(G.app);this.plugin=G;this.choices=l;this.choiceExecutor=newYZ(this.app,this.plugin);Z&&(this.choiceExecutor=Z)}staticOpen(G,l,Z){newb(G,l,Z).open()}renderSuggestion(G,l){l.empty(),m2.MarkdownRenderer.renderMarkdown(G.item.name,l,"",this.plugin),l.classList.add("quickadd-choice-suggestion")}getItemText(G){returnG.name}getItems(){returnthis.choices}asynconChooseItem(G,l){G.type==="Multi"?this.onChooseMultiType(G):awaitthis.choiceExecutor.execute(G)}onChooseMultiType(G){letl=[...G.choices];G.name!="\u2190 Back"&&l.push(newgd("\u2190 Back").addChoices(this.choices)),b.Open(this.plugin,l)}};varrs=require("obsidian");varPY=classextendsvb{constructor(G,l,Z){super();this.app=G;this.plugin=l;this.choiceExecutor=Z;this.requirements=newMap;this.templatesToScan=newSet;this.dateParser=cb,Z&&(this.variables=newMap(Z.variables))}asyncscanString(G){letl=awaitthis.replaceGlobalVarInString(G);this.scanVariableTokens(l),awaitthis.format(l)}asyncformat(G){letl=G;l=awaitthis.replaceGlobalVarInString(l),l=this.replaceDateInString(l),l=this.replaceTimeInString(l),l=awaitthis.replaceValueInString(l),l=awaitthis.replaceSelectedInString(l),l=awaitthis.replaceClipboardInString(l),l=awaitthis.replaceDateVariableInString(l),l=awaitthis.replaceVariableInString(l),l=awaitthis.replaceFieldVarInString(l),l=awaitthis.replaceMathValueInString(l),l=this.replaceRandomInString(l);{letZ=newRegExp(dW.source,"gi"),c;for(;(c=Z.exec(l))!==null;){letW=c[1];W&&this.templatesToScan.add(W)}}returnl}asyncreplaceGlobalVarInString(G){letl=G,Z=0,c=newRegExp(FZ.source,"gi");for(;c.test(l)&&!(++Z>5);)l=l.replace(c,(W,d)=>{letm=String(d??"").trim();if(!m)returnW;letN=this.plugin?.settings?.globalVariables?.[m];returntypeofN=="string"?N:""});returnl}scanVariableTokens(G){letl=newRegExp(RZ.source,"gi"),Z;for(;(Z=l.exec(G))!==null;){letc=(Z[1]??"").trim();if(!c)continue;letW=c.indexOf("|"),d=c,m;if(W!==-1&&(m=c.substring(W+1).trim(),d=c.substring(0,W).trim()),!d)continue;letN=W===-1&&d.includes(",");if(this.requirements.has(d)){if(m){letY=this.requirements.get(d);Y.defaultValue===void0&&(Y.defaultValue=m)}}else{letY={id:d,label:d,type:N?"dropdown":"text"};N&&(Y.options=d.split(",").map(V=>V.trim()).filter(Boolean)),m&&(Y.defaultValue=m),this.requirements.set(d,Y)}}}asyncpromptForValue(G){letl="value";returnthis.requirements.has(l)||this.requirements.set(l,{id:l,label:G||"Enter value",type:this.plugin.settings.inputPrompt==="multi-line"?"textarea":"text",source:"collected"}),""}asyncpromptForVariable(G,l){if(!G)return"";if(l?.type==="VDATE"&&l.dateFormat)returnthis.requirements.has(G)||this.requirements.set(G,{id:G,label:G,type:"date",defaultValue:l.defaultValue,dateFormat:l.dateFormat,source:"collected"}),l.defaultValue??"";if(!this.requirements.has(G)){letZ=G.includes(","),c={id:G,label:G,type:Z?"dropdown":"text",source:"collected"};Z&&(c.options=G.split(",").map(W=>W.trim()).filter(Boolean)),l?.defaultValue&&(c.defaultValue=l.defaultValue),this.requirements.set(G,c)}returnl?.defaultValue??""}asyncpromptForMathValue(){letG="mvalue";returnthis.requirements.has(G)||this.requirements.set
QuickAddwillnowreverttobackup.`),b.settings=l}}b.saveSettings()}var Ss=UA;var rd=require("obsidian");async function BA(b,I,G){let l=await fetch(`https://api.github.com/repos/${b}/${I}/releases`),Z=await l.json();if(!l.ok&&"message"in Z||!Array.isArray(Z))throw new Error(`Failed to fetch releases: ${Z.message??"Unknown error"}`);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 OA(b,I=1){let G=b.split(`
`,l="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.",Z='<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"),W=this.releases.map(Y=>Y.body).join(`
${OA(W)}`;rd.MarkdownRenderer.renderMarkdown(N,c,this.app.vault.getRoot().path,new rd.Component)}};var vG=require("obsidian");var a2=class extends vG.Modal{constructor(G,l){super(G);this.showAdvancedSettings=!1;this.settings=l,this.waitForClose=new Promise((Z,c)=>{this.rejectPromise=c,this.resolvePromise=Z}),this.open(),this.display()}get systemPromptTokenLength(){let G=Yb(this.settings.model);return G?Jl(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 l=await IG.Prompt(this.app,"New name",this.settings.name,this.settings.name);l&&l!==this.settings.name&&(this.settings.name=l,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 vG.Setting(G).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(l=>{let Z=gb();for(let c of Z)l.addOption(c,c);l.addOption("Ask me","Ask me"),l.setValue(this.settings.model),l.onChange(c=>{this.settings.model=c,this.reload()})})}addOutputVariableNameSetting(G){new vG.Setting(G).setName("Output variable name").setDesc("The name of the variable used to store the AI Assistant output, i.e. {{value:output}}.").addText(l=>{l.setValue(this.settings.outputVariableName).onChange(Z=>{this.settings.outputVariableName=Z})})}addSystemPromptSetting(G){new vG.Setting(G).setName("System Prompt").setDesc("The system prompt for the AI Assistant");let l=this.contentEl.createEl("div"),Z=l.createEl("span");Z.style.color="var(--text-muted-color)",l.appendChild(Z);let c=new vG.TextAreaComponent(G);c.setValue(this.settings.systemPrompt).onChange(async N=>{this.settings.systemPrompt=N,d.innerText=await W.format(N),m()}),new rG(this.app,c.inputEl,UI.instance);let W=new ml(this.app,UI.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"),m=(0,vG.debounce)(()=>{Z.innerText=`Tokencount:${this.systemPromptTokenLength}`},50);m(),(async()=>d.innerText=await W.format(this.settings.systemPrompt??""))()}addShowAdvancedSettingsToggle(G){new vG.Setting(G).setName("Show advanced settings").setDesc("Show advanced settings such as temperature, top p, and frequency penalty.").addToggle(l=>{l.setValue(this.showAdvancedSettings),l.onChange(Z=>{this.showAdvancedSettings=Z,this.reload()})})}addTemperatureSetting(G){new vG.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(l=>{l.setLimits(0,1,.1),l.setDynamicTooltip(),l.setValue(this.settings.modelParameters.temperature??1),l.onChange(Z=>{this.settings.modelParameters.temperature=Z})})}addTopPSetting(G){new vG.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(l=>{l.setLimits(0,1,.1),l.setDynamicTooltip(),l.setValue(this.settings.modelParameters.top_p??1),l.onChange(Z=>{this.settings.modelParameters.top_p=Z})})}addFrequencyPenaltySetting(G){new vG.Setting(