`].join("");var U}function $I(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 sl(){for(var X=[].slice.call(arguments),J=X.length,U=0;U<J;U+=1)k(X[U]);return t(function(j,II){for(var lI,_=new Array(J),NI=0;NI<J;NI+=1){if(!(lI=H(X[NI]._(j,II),lI)).status)return lI;_[NI]=lI.value,II=lI.index}return H(V(II,_),lI)})}function wl(){var X=[].slice.call(arguments);if(X.length===0)throw new Error("seqMap needs at least one argument");var J=X.pop();return L(J),sl.apply(null,X).map(function(U){return J.apply(null,U)})}function Cl(){var X=[].slice.call(arguments),J=X.length;if(J===0)return S("zero alternates");for(var U=0;U<J;U+=1)k(X[U]);return t(function(j,II){for(var lI,_=0;_<X.length;_+=1)if((lI=H(X[_]._(j,II),lI)).status)return lI;return lI})}function Qe(X,J){return zG(X,J).or(WG([]))}function zG(X,J){return k(X),k(J),wl(X,J.then(X).many(),function(U,j){return[U].concat(j)})}function BG(X){y(X);var J="'"+X+"'";return t(function(U,j){var II=j+X.length,lI=U.slice(j,II);return lI===X?V(II,lI):w(j,J)})}function nG(X,J){(function(II){if(!(II instanceof RegExp))throw new Error("not a regexp: "+II);for(var lI=$I(II),_=0;_<lI.length;_++){var NI=lI.charAt(_);if(NI!=="i"&&NI!=="m"&&NI!=="u"&&NI!=="s")throw new Error('unsupported regexp flag "'+NI+'": '+II)}})(X),arguments.length>=2?E(J):J=0;var U=function(II){return RegExp("^(?:"+II.source+")",$I(II))}(X),j=""+X;return t(function(II,lI){var _=U.exec(II.slice(lI));if(_){if(0<=J&&J<=_.length){var NI=_[0],Il=_[J];return V(lI+NI.length,Il)}return w(lI,"valid match group (0 to "+_.length+") in "+j)}return w(lI,j)})}function WG(X){return t(function(J,U){return V(U,X)})}function S(X){return t(function(J,U){return w(U,X)})}function EI(X){if(s(X))return t(function(J,U){var j=X._(J,U);return j.index=U,j.value="",j});if(typeof X=="string")return EI(BG(X));if(X instanceof RegExp)return EI(nG(X));throw new Error("not a string, regexp, or parser: "+X)}function KI(X){return k(X),t(function(J,U){var j=X._(J,U),II=J.slice(U,j.index);return j.status?w(U,'not "'+II+'"'):V(U,null)})}function MI(X){return L(X),t(function(J,U){var j=A(J,U);return U<J.length&&X(j)?V(U+1,j):w(U,"a character/byte matching "+X)})}function Ie(X,J){arguments.length<2&&(J=X,X=void 0);var U=t(function(j,II){return U._=J()._,U._(j,II)});return X?U.desc(X):U}function NG(){return S("fantasy-land/empty")}b.parse=function(X){if(typeof X!="string"&&!r(X))throw new Error(".parse must be called with a string or Buffer as its argument");var J,U=this.skip(le)._(X,0);return J=U.status?{status:!0,value:U.value}:{status:!1,index:f(X,U.furthest),expected:U.expected},delete O[X],J},b.tryParse=function(X){var J=this.parse(X);if(J.status)return J.value;var U=LI(X,J),j=new Error(U);throw j.type="ParsimmonError",j.result=J,j},b.assert=function(X,J){return this.chain(function(U){return X(U)?WG(U):S(J)})},b.or=function(X){return Cl(this,X)},b.trim=function(X){return this.wrap(X,X)},b.wrap=function(X,J){return wl(X,this,J,function(U,j){return j})},b.thru=function(X){return X(this)},b.then=function(X){return k(X),sl(this,X).map(function(J){return J[1]})},b.many=function(){var X=this;return t(function(J,U){for(var j=[],II=void 0;;){if(!(II=H(X._(J,U),II)).status)return H(V(U,j),II);if(U===II.index)throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause");U=II.index,j.push(II.value)}})},b.tieWith=function(X){return y(X),this.map(function(J){if(function(II){if(!Q(II))throw new Error("not an array: "+II)}(J),J.length){y(J[0]);for(var U=J[0],j=1;j<J.length;j++)y(J[j]),U+=X+J[j];return U}return""})},b.tie=function(){return this.tieWith("")},b.times=function(X,J){var U=this;return arguments.length<2&&(J=X),E(X),E(J),t(function(j,II){for(var lI=[],_=void 0,NI=void 0,Il=0;Il<X;Il+=1){if(NI=H(_=U._(j,II),NI),!_.status)return NI;II=_.index,lI.push(_.value)}for(;Il<J&&(NI=H(_=U._(j,II),NI),_.status);Il+=1)II=_.index,lI.push(_.value);return H(V(II,lI),NI)})},b.result=function(X){return thi
`),Qt=BG(`\r
`),Le=Cl(Qt,HZ,Xt).desc("newline"),IW=Cl(Le,le);t.all=ic,t.alt=Cl,t.any=Uc,t.cr=Xt,t.createLanguage=function(X){varJ={};for(varUinX)({}).hasOwnProperty.call(X,U)&&function(j){J[j]=Ie(function(){returnX[j](J)})}(U);returnJ},t.crlf=Qt,t.custom=function(X){returnt(X(V,w))},t.digit=xc,t.digits=ot,t.empty=NG,t.end=IW,t.eof=le,t.fail=S,t.formatError=LI,t.index=DG,t.isParser=s,t.lazy=Ie,t.letter=zc,t.letters=Re,t.lf=HZ,t.lookahead=EI,t.makeFailure=w,t.makeSuccess=V,t.newline=Le,t.noneOf=function(X){returnMI(function(J){returnX.indexOf(J)<0}).desc("none of '"+X+"'")},t.notFollowedBy=KI,t.of=WG,t.oneOf=function(X){for(varJ=X.split(""),U=0;U<J.length;U++)J[U]="'"+J[U]+"'";returnMI(function(j){returnX.indexOf(j)>=0}).desc(J)},t.optWhitespace=$n,t.Parser=t,t.range=function(X,J){returnMI(function(U){returnX<=U&&U<=J}).desc(X+"-"+J)},t.regex=nG,t.regexp=nG,t.sepBy=Qe,t.sepBy1=zG,t.seq=sl,t.seqMap=wl,t.seqObj=function(){for(varX,J={},U=0,j=(X=arguments,Array.prototype.slice.call(X)),II=j.length,lI=0;lI<II;lI+=1){var_=j[lI];if(!s(_)){if(Q(_)&&_.length===2&&typeof_[0]=="string"&&s(_[1])){varNI=_[0];if(Object.prototype.hasOwnProperty.call(J,NI))thrownewError("seqObj: duplicate key "+NI);J[NI]=!0,U++;continue}thrownewError("seqObj arguments must be parsers or [string, parser] array pairs.")}}if(U===0)thrownewError("seqObj expects at least one named parser, found zero");returnt(function(Il,gl){for(varcl,Ge={},zl=0;zl<II;zl+=1){varBl,Dl;if(Q(j[zl])?(Bl=j[zl][0],Dl=j[zl][1]):(Bl=null,Dl=j[zl]),!(cl=H(Dl._(Il,gl),cl)).status)returncl;Bl&&(Ge[Bl]=cl.value),gl=cl.index}returnH(V(gl,Ge),cl)})},t.string=BG,t.succeed=WG,t.takeWhile=function(X){returnL(X),t(function(J,U){for(varj=U;j<J.length&&X(A(J,j));)j++;returnV(j,J.slice(U,j))})},t.test=MI,t.whitespace=re,t["fantasy-land/empty"]=NG,t["fantasy-land/of"]=WG,t.Binary={bitSeq:N,bitSeqObj:function(X){W();varJ={},U=0,j=m(function(lI){if(Q(lI)){var_=lI;if(_.length!==2)thrownewError("["+_.join(", ")+"] should be length 2, got length "+_.length);if(y(_[0]),E(_[1]),Object.prototype.hasOwnProperty.call(J,_[0]))thrownewError("duplicate key in bitSeqObj: "+_[0]);returnJ[_[0]]=!0,U++,_}returnE(lI),[null,lI]},X);if(U<1)thrownewError("bitSeqObj expects at least one named pair, got ["+X.join(", ")+"]");varII=m(function(lI){returnlI[0]},j);returnN(m(function(lI){returnlI[1]},j)).map(function(lI){returnZ(function(_,NI){returnNI[0]!==null&&(_[NI[0]]=NI[1]),_},{},m(function(_,NI){return[_,lI[NI]]},II))})},byte:function(X){if(W(),E(X),X>255)thrownewError("Value specified to byte constructor ("+X+"=0x"+X.toString(16)+") is larger in value than a single byte.");varJ=(X>15?"0x":"0x0")+X.toString(16);returnt(function(U,j){varII=A(U,j);returnII===X?V(j+1,II):w(j,J)})},buffer:function(X){returnY("buffer",X).map(function(J){returnBuffer.from(J)})},encodedString:function(X,J){returnY("string",J).map(function(U){returnU.toString(X)})},uintBE:C,uint8BE:C(1),uint16BE:C(2),uint32BE:C(4),uintLE:p,uint8LE:p(1),uint16LE:p(2),uint32LE:p(4),intBE:o,int8BE:o(1),int16BE:o(2),int32BE:o(4),intLE:R,int8LE:R(1),int16LE:R(2),int32LE:R(4),floatBE:Y("floatBE",4).map(function(X){returnX.readFloatBE(0)}),floatLE:Y("floatLE",4).map(function(X){returnX.readFloatLE(0)}),doubleBE:Y("doubleBE",8).map(function(X){returnX.readDoubleBE(0)}),doubleLE:Y("doubleLE",8).map(function(X){returnX.readDoubleLE(0)})},l.exports=t}])})})(GY,GY.exports);varg=GY.exports,hh=()=>/[#*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\u2
`)}functionJZ(e){letI=Object.entries(e);if(I.length===0)return[];letG=["t","tm","yd"].map(b=>{letd=e[b];returnd?[b,d]:null}).filter(b=>b!==null),c=newSet(G.map(([b])=>b)),t=I.filter(([b])=>!c.has(b)).sort((b,d)=>{letZ=b[0].length-d[0].length;returnZ!==0?Z:b[0].localeCompare(d[0])});return[...G,...t]}functionnW(e){returnJZ(e).map(([I,l])=>`${I}=${l}`).join(", ")}varWW={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:Ob,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}^{ ext{new}}:=w_{ij}^{ ext{current}}+etacdotdelta_jcdot 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:mW},migrations:{migrateToMacroIDFromEmbeddedMacro:!0,useQuickAddTemplateFolder:!1,incrementFileNameSettingMoveToDefaultBehavior:!1,mutualExclusionInsertAfterAndWriteToBottomOfFile:!1,setVersionAfterUpdateModalRelease:!1,addDefaultAIProviders:!1,removeMacroIndirection:!1,migrateFileOpeningSettings:!1,backfillFileOpeningDefaults:!1,setProviderModelDiscoveryMode:!1,migrateProviderApiKeysToSecretStorage:!1}};functionGl(e){letI=globalThis.structuredClone;if(typeofI=="function")try{returnI(e)}catch{}returnMc(e,newMap)}functionMc(e,I){if(e===null||typeofe!="object")returne;if(I.has(e))returnI.get(e);if(einstanceofDate){letc=newDate(e.getTime());returnI.set(e,c),c}if(Array.isArray(e)){letc=[];I.set(e,c);for(lettofe)c.push(Mc(t,I));returnc}if(einstanceofMap){letc=newMap;I.set(e,c);for(let[t,b]ofe.entries())c.set(Mc(t,I),Mc(b,I));returnc}if(einstanceofSet){letc=newSet;I.set(e,c);for(lettofe.values())c.add(Mc(t,I));returnc}if(einstanceofRegExp){letc=newRegExp(e.source,e.flags);returnc.lastIndex=e.lastIndex,I.set(e,c),c}if(einstanceofArrayBuffer){letc=e.slice(0);returnI.set(e,c),c}if(ArrayBuffer.isView(e)){if(einstanceofDataView){letd=newDataView(Mc(e.buffer,I),e.byteOffset,e.byteLength);returnI.set(e,d),d}letc=e,t=Mc(c.buffer,I),b=newc.constructor(t,c.byteOffset,c.length);returnI.set(e,b),b}letl=Object.getPrototypeOf(e),G=Object.create(l);I.set(e,G);for(let[c,t]ofObject.entries(e))Object.defineProperty(G,c,{value:Mc(t,I),writable:!0,enumerable:!0,configurable:!0});returnG}varP=(()=>{lete=q0((c,t)=>({...Gl(WW)})),{getState:I,setState:l,subscribe:G}=e;return{getState:I,setState:l,subscribe:G}})();varll=require("obsidian");vargt="{{value}}",Ps="{{date}}",_0="{{time}}",_s="{{name}}",SF="{{value:<variable name>}}",TF="{{value:<variable name>|<default value>}}",qF="{{value:<variable name>|default:<value>}}",PF="{{value:<variable name>|label:<helper text>}}",_F="{{field:<field name>}}",$0="{{mvalue}}",Ip="{{linkcurrent}}",lp="{{filenamecurrent}}",Gp="{{title}}",ep="{{selected}}",cp="{{clipboard}}",$F="{{random:<length>}}",Iw="{{global_var:<name>}}";vartp=[Ps,"{{date:<dateformat>}}","{{vdate:<variable name>, <date format>}}","{{vdate:<variable name>, <date format>|<default value>}}",Iw,gt,_s,SF,TF,qF,PF,_F,$F];var$s=newRegExp(/^-?[0-9]*$/),Kb="top",AZ="bottom",EZ="cursor",NW=newRegExp(/{{DATE(\+-?[0-9]+)?}}/i),Ub=newRegExp(/{{DATE:([^}\n\r+]*)(\+-?[0-9]+)?}}/i),xb=newRegExp(/{{TIME}}/i),zb=newRegExp(/{{TIME:([^}\n\r+]*)}}/i),YW=ne
`+e,{line:b,ch:d.length}),c.setCursor({line:b+1,ch:e.length})}}catch{K.logError(`unable to insert '${e}' on new line ${I}.`)}}functionYo(e,I){No(e,"above",I)}functionso(e,I){No(e,"below",I)}functioni4(e,I,l="replaceSelection",G={}){let{requireActiveView:c=!0}=G,t=e.workspace.getActiveViewOfType(ne.MarkdownView);if(!t){leta="Cannot append link because no active Markdown view is available.";if(c)thrownewError(a);K.logMessage(a);return}letb=t.editor,d=b.listSelections().map(a=>({anchor:{...a.anchor},head:{...a.head}}));if(l==="replaceSelection"){b.replaceSelection(I);return}letZ=({line:a,ch:n})=>b.posToOffset({line:a,ch:n}),m=d.sort((a,n)=>Z(n.head)-Z(a.head));for(letaofm){letn=Z(a.anchor)>Z(a.head)?a.anchor:a.head;switch(l){case"afterSelection":{b.replaceRange(I,n);break}case"endOfLine":{letW=b.getLine(n.line),N={line:n.line,ch:W.length};b.replaceRange(I,N);break}case"newLine":{letW=b.getLine(n.line),N={line:n.line,ch:W.length},u=W.length===0?"":`
`;b.replaceRange(u+I,N);break}}}}functionh4(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}functionp4(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)}`;letc=h4(e);returnc?`![[${c}]]`:e.startsWith("!")?e:`!${e}`}functionGN(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(ne.MarkdownView)){if(l.requireActiveFile)thrownewError("Cannot append link because no active Markdown view is available.");return!1}lett=G?.path??"",b=e.fileManager.generateMarkdownLink(I,t),Z=l.linkType==="embed"&&Rc(l.placement)?p4(b):b;returni4(e,Z,l.placement,{requireActiveView:!1}),!0}functionV4(e,I){returne.commands.findCommand(I)}functionuo(e,I){V4(e,I)&&(deletee.commands.commands[I],deletee.commands.editorCommands[I])}function_a(e){returne.vault.getAllLoadedFiles().filter(I=>Iinstanceofne.TFolder).map(I=>I.path)}function$a(e){letI=e.split("::").map(l=>l.trim()).filter(Boolean);return{basename:I[0],memberAccess:I.slice(1)}}asyncfunctionVd(e,I,l={}){let{location:G="tab",direction:c="vertical",mode:t,focus:b=!0,eState:d}=l,Z=typeofI=="string"?e.vault.getAbstractFileByPath(I):I;if(!Z)thrownewError(`File not found: ${String(I)}`);letm;switch(G){case"reuse":m=e.workspace.getLeaf(!1);break;case"tab":m=e.workspace.getLeaf("tab");break;case"split":m=e.workspace.getLeaf("split",c);break;case"window":m=e.workspace.getLeaf("window");break;case"left-sidebar":m=e.workspace.getLeftLeaf(!0);break;case"right-sidebar":m=e.workspace.getRightLeaf(!0);break;default:m=e.workspace.getLeaf("tab")}if(!m)thrownewError("Could not obtain a workspace leaf.");if(awaitm.openFile(Z),t&&t!=="default"&&!(typeoft=="object"&&t.mode==="default")){leta=m.getViewState(),n={...a.state??{}};t==="preview"||typeoft=="object"&&t.mode==="preview"?(n.mode="preview",deleten.source):t==="source"?(n.mode="source",n.source=!0):t==="live"||t==="live-preview"?(n.mode="source",n.source=!1):typeoft=="object"&&t.mode==="source"&&(n.mode="source",n.source=t.source),awaitm.setViewState({...a,state:{...n,...d}})}returnb&&e.workspace.setActiveLeaf(m,{focus:!0}),m}functioneN(e,I,l=!0){letG;returne.workspace.iterateRootLeaves(c=>{lett=c.view;if(tinstanceofne.FileView&&t.file&&I.path===t.file.path){G=c;return}}),G!==void0?(l&&e.workspace.setActiveLeaf(G,{focus:!0}),G):null}asyncfunctionLc(e,I){letl=I.vault.getAbstractFileByPath(e.path);if(!l){K.logError(`failed to load file ${e.path}.`);return}if(linstanceofne.TFile){letG=n=>window.require&&window.require(n),c={},t={exports:c},b=awaitI.vault.read(l);window.eval(`(function(require, module, exports) { ${b}
`).filter(Boolean).reduce((G,c)=>{let[t,b,...d]=c.split(""),Z=Number.parseInt(b,10);return d.forEach((m,a)=>G[m]=Z+a),G},{});for(let[G,c]of Object.entries(l)){let t=iX.default.toByteArray(G);this.rankMap.set(t.join(","),c),this.textMap.set(c,t)}this.specialTokens={...e.special_tokens,...I},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((G,[c,t])=>(G[t]=this.textEncoder.encode(c),G),{})}encode(e,I=[],l="all"){let G=new RegExp(this.patStr,"ug"),c=Ji.specialTokenRegex(Object.keys(this.specialTokens)),t=[],b=new Set(I==="all"?Object.keys(this.specialTokens):I),d=new Set(l==="all"?Object.keys(this.specialTokens).filter(m=>!b.has(m)):l);if(d.size>0){let m=Ji.specialTokenRegex([...d]),a=e.match(m);if(a!=null)throw new Error(`The text contains a special token that is not allowed: ${a[0]}`)}let Z=0;for(;;){let m=null,a=Z;for(;c.lastIndex=a,m=c.exec(e),!(m==null||b.has(m[0]));)a=m.index+1;let n=m?.index??e.length;for(let N of e.substring(Z,n).matchAll(G)){let Y=this.textEncoder.encode(N[0]),u=this.rankMap.get(Y.join(","));if(u!=null){t.push(u);continue}t.push(...my(Y,this.rankMap))}if(m==null)break;let W=this.specialTokens[m[0]];t.push(W),Z=m.index+m[0].length}return t}decode(e){let I=[],l=0;for(let t=0;t<e.length;++t){let b=e[t],d=this.textMap.get(b)??this.inverseSpecialTokens[b];d!=null&&(I.push(d),l+=d.length)}let G=new Uint8Array(l),c=0;for(let t of I)G.set(t,c),c+=t.length;return this.textDecoder.decode(G)}},EN=Ji;dy(EN,"specialTokenRegex",e=>new RegExp(e.map(I=>ay(I)).join("|"),"g"));function Ai(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":retur
${I}`:""}`;function KN(e){if(e){let I=new RX.Notice(QX("starting",""),1e6);return{setMessage:(l,G)=>{I.setMessage(QX(l,G))},hide:()=>I.hide()}}return{setMessage:(I,l)=>{K.logMessage(`(${I}) ${l}`)},hide:()=>{}}}var rX={cl100k_base:hX,o200k_base:pX},LX=new Map;function Cy(e){let I=e in rX?e:"cl100k_base",l=LX.get(I);if(l)return l;let G=new EN(rX[I]);return LX.set(I,G),G}var TG=(e,I)=>{let l="cl100k_base";try{l=Ai(I.name)}catch{l="cl100k_base"}return(l==="p50k_base"||l==="p50k_edit"||l==="r50k_base"||l==="gpt2")&&(l="cl100k_base"),Cy(l).encode(e).length};async function iy(e,I,l){if(typeof e!="function")throw new TypeError("Callbackmustbeafunction.");if(!(I instanceof Promise))throw new TypeError("PromisemustbeaninstanceofPromise.");if(typeof l!="number"||l<=0)throw new TypeError("Intervalmustbeapositivenumber.");let G=!1;for(I.finally(()=>{G=!0});!G;)e(),await sleep(l)}async function hy(e,I,l){let G;if(I.enable)G=l.find(d=>d.path.endsWith(I.name));else{let d=l.map(Z=>Z.basename);G=await CG.Suggest(e,d,l)}SG(G,"Prompttemplatedoesnotexist");let c=G.path,t=e.vault.getAbstractFileByPath(c);SG(t instanceof FX.TFile,`${c} is not a file`);let b=await e.vault.cachedRead(t);return[G.basename,b]}async function wX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("BlockingrequesttoOpenAI:Onlinefeaturesaredisabledinsettings.");let G=KN(I.showAssistantMessages);try{let{apiKey:c,model:t,outputVariableName:b,promptTemplate:d,systemPrompt:Z,promptTemplateFolder:m}=I,a=Gt(e,m),[n,W]=await hy(e,d,a);G.setMessage("waiting","QuickAddisformattingtheprompttemplate.");let N=await l(W),Y=["prompting",`Using prompt template "${n}".`];G.setMessage(Y[0],Y[1]);let C=ON(e,c,t,Z,I.modelOptions)(N),o=(await ki(C,100,Q=>{G.setMessage(Y[0],`${Y[1]} (${(Q/1e3).toFixed(2)}s)`)},Q=>{G.setMessage("finished",`Took ${(Q/1e3).toFixed(2)}s.`)})).content,R=(">"+o).replace(/\n/g,`
> `),s={[b]:o,[`${b}-quoted`]:R};return setTimeout(()=>G.hide(),5e3),s}catch(c){throw G.setMessage("dead",c.message),setTimeout(()=>G.hide(),5e3),il(c)?new SI("Inputcancelledbyuser"):c}}async function ki(e,I,l,G){let c=Date.now();return await iy(()=>l(Date.now()-c),e,I),G(Date.now()-c),await e}async function gX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("BlockingrequesttoOpenAI:Onlinefeaturesaredisabledinsettings.");let G=KN(I.showAssistantMessages);try{let{apiKey:c,model:t,outputVariableName:b,systemPrompt:d,prompt:Z,modelOptions:m}=I;G.setMessage("waiting","QuickAddisformattingtheprompttemplate.");let a=await l(Z),n=["prompting","Usingcustomprompt."];G.setMessage(n[0],n[1]);let N=ON(e,c,t,d,m)(a),u=(await ki(N,100,o=>{G.setMessage(n[0],`${n[1]} (${(o/1e3).toFixed(2)}s)`)},o=>{G.setMessage("finished",`Took ${(o/1e3).toFixed(2)}s.`)})).content,C=(">"+u).replace(/\n/g,`
> `),p={[b]:u,[`${b}-quoted`]:C};return setTimeout(()=>G.hide(),5e3),p}catch(c){throw G.setMessage("dead",c.message),setTimeout(()=>G.hide(),5e3),c}}var Ei=class{constructor(I,l){this.maxRequests=I;this.intervalMs=l;this.queue=[];this.pendingPromises=[]}add(I){return new Promise((l,G)=>{this.queue.push(async()=>{try{l(await I())}catch(c){G(c)}}),this.schedule()})}schedule(){if(this.queue.length===0||this.pendingPromises.length>=this.maxRequests)return;let I=this.queue.shift();if(!I)return;let l=I();this.pendingPromises.push(l),l.finally(()=>{this.pendingPromises=this.pendingPromises.filter(G=>G!==l),this.schedule()}),setTimeout(()=>this.schedule(),this.intervalMs)}};async function HX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("BlockingrequesttoOpenAI:Onlinefeaturesaredisabledinsettings.");let G=KN(I.showAssistantMessages);try{let{apiKey:c,model:t,outputVariableName:b,systemPrompt:d,promptTemplate:Z,text:m,modelOptions:a}=I;G.setMessage("chunking","Creatingpromptchunkswithtextandprompttemplate");let n=I.chunkSeparator||/\n/g,W=m.split(n),N=TG(d,t),Y=await l(Z,{chunk:""}),u=TG(Y,t),C=XX(t.name)/2-N,p=I.shouldMerge??!0,o=[],R=C-u;if(p){let A=[],E="",L=0;for(let y of W){let v=TG(y,t)+1;if(v>R)throw new Error(`The chunk "${y.slice(0,25)}..." is too large to fit in a single prompt.`);L+v<R?(E+=y,L+=v):(A.push(E),E=y,L=v)}E!==""&&A.push(E);for(let y of A){let v=await l(Z,{chunk:y});o.push(v)}}else for(let A of W){let E=TG(A,t);if(E>C)throw new Error(`Chunk size (${E}) is larger than the maximum chunk size (${C}). Please check your chunk separator.`);let L=await l(Z,{chunk:A});o.push(L)}let s=ON(e,c,t,d,a),Q=["prompting",`${o.length} prompts being sent.`];G.setMessage(Q[0],Q[1]);let r=new Ei(5,1e3*30),V=Promise.all(o.map(A=>r.add(()=>s(A)))),O=(await ki(V,100,A=>{G.setMessage(Q[0],`${Q[1]} (${(A/1e3).toFixed(2)}s)`)},A=>{G.setMessage("finished",`Took ${(A/1e3).toFixed(2)}s.`)})).map(A=>A.content).join(I.resultJoiner),f=(">"+O).replace(/\n/g,`
> `),k={[b]:O,[`${b}-quoted`]:f};return setTimeout(()=>G.hide(),5e3),k}catch(c){throw G.setMessage("dead",c.message),setTimeout(()=>G.hide(),5e3),c}}var py="quickadd-ai";function Vy(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function oy(e){let I=e.name?.trim()||"provider";return`${py}-${Vy(I)}`}async function yc(e,I){let l=I.apiKeyRef?.trim();if(l&&e?.secretStorage?.getSecret)try{let G=await Promise.resolve(e.secretStorage.getSecret(l));if(G)return G}catch(G){K.logWarning(`Failed to read SecretStorage entry "${l}": ${G.message??G}`)}return I.apiKey??""}async function vX(e,I,l){let G=l?.trim();if(!G||!e?.secretStorage?.getSecret||!e.secretStorage?.setSecret)return null;let c=oy(I),t=c,b=1;for(;;){let d=null;try{d=await Promise.resolve(e.secretStorage.getSecret(t))}catch(Z){K.logWarning(`Failed to read SecretStorage entry "${t}": ${Z.message??Z}`)}if(!d)break;if(d===G)return t;b+=1,t=`${c}-${b}`}try{return await Promise.resolve(e.secretStorage.setSecret(t,G)),t}catch(d){return K.logWarning(`Failed to write SecretStorage entry "${t}": ${d.message??d}`),null}}var Ed=require("obsidian"),an=class e extends Ed.Modal{constructor(l,G,c=[]){super(l);this.items=G;this.selectedItems=c;this._selectedItems=[...c],this.promise=new Promise((t,b)=>{this.resolvePromise=t,this.rejectPromise=b}),this.display(),this.open()}static Open(l,G,c){return new e(l,G,c).promise}display(){this.contentEl.empty(),this.containerEl.addClass("quickAddModal","checkboxPrompt"),this.addCheckboxRows(),this.addSubmitButton()}onClose(){super.onClose(),this.resolved||this.rejectPromise("noinputgiven.")}addCheckboxRows(){let l=this.contentEl.createDiv("checkboxRowContainer");this.items.forEach(G=>this.addCheckboxRow(G,l))}addCheckboxRow(l,G){let c=G.createDiv("checkboxRow");c.createEl("span",{text:l}),new Ed.ToggleComponent(c).setTooltip(`Toggle ${l}`).setValue(this._selectedItems.contains(l)).onChange(b=>{if(b)this._selectedItems.push(l);else{let d=this._selectedItems.findIndex(Z=>l===Z);this._selectedItems.splice(d,1)}})}addSubmitButton(){let l=this.contentEl.createDiv("submitButtonContainer");new Ed.ButtonComponent(l).setButtonText("Submit").setCta().onClick(c=>{this.resolved=!0,this.resolvePromise(this._selectedItems),this.close()})}};var UN=require("obsidian"),nn=class e extends UN.Modal{constructor(l,G,c){super(l);this.header=G;this.text=c;this.waitForClose=new Promise(t=>{this.resolvePromise=t}),this.open(),this.display()}static Show(l,G,c){return new e(l,G,c).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(c=>this.contentEl.createEl("p",{text:c}));let l=this.contentEl.createDiv(),G=new UN.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 kd=require("obsidian");var dt=class e extends kd.Modal{constructor(l,G,c,t,b,d){super(l);this.header=G;this.linkSourcePath=b;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=c??"",this.description=d?.trim()||void 0,this.draftHandler=new yd({kind:"multi",header:this.header,placeholder:this.placeholder,linkSourcePath:this.linkSourcePath}),this.input=this.draftHandler.hydrate(t??""),this.waitForClose=new Promise((Z,m)=>{this.resolvePromise=Z,this.rejectPromise=m}),this.display(),this.open(),this.fileSuggester=new gd(l,this.inputComponent.inputEl,{sourcePath:this.linkSourcePath}),this.tagSuggester=new Hd(l,this.inputComponent.inputEl)}static Prompt(l,G,c,t,b){return new e(l,G,c,t,void 0,b).waitForClose}static PromptWithContext(l,G,c,t,b,d){return new e(l,G,c,t,b,d).waitForClose}display(){if(this.containerEl.addClass("quickAddModal","qaWideInputPrompt"),this.contentEl.empty(),this.titleEl.textContent=this.he
`,shouldMerge:d?.shouldMerge??!0},(o,R)=>{let s={...Z,...R};return n(o,s,!1)});return p?(d?.shouldAssignVariables&&Object.entries(p).forEach(([o,R])=>{G.variables.set(o,R)}),p):(qI(new Error("AIAssistantreturnednull"),"ChunkedAIPrompterror"),{})},getModels:()=>Gc(),getMaxTokens:c=>{let t=Je(c);if(!t)throw new Error(`Model ${c} not found.`);return t.maxTokens},countTokens(c,t){return TG(c,t)}},utility:{getClipboard:async()=>await navigator.clipboard.readText(),setClipboard:async c=>await navigator.clipboard.writeText(c),getSelection:()=>{let c=I.workspace.getActiveViewOfType(Vh.MarkdownView);return c?c.editor.getSelection()??"":""},getSelectedText:()=>{let c=I.workspace.getActiveViewOfType(Vh.MarkdownView);if(!c){qI(new Error("Noactiveview"),"Couldnotgetselectedtext");return}if(!c.editor.somethingSelected()){qI(new Error("Notextselected"),"Couldnotgetselectedtext");return}return c.editor.getSelection()}},date:{now:(c,t)=>rc({format:c,offset:t}),tomorrow:c=>rc({format:c,offset:1}),yesterday:c=>rc({format:c,offset:-1})},fieldSuggestions:{getFieldValues:async(c,t)=>{let b={folder:t?.folder,tags:t?.tags,inline:t?.includeInline??!1},d=I.vault.getMarkdownFiles();d=NY.filterFiles(d,b,m=>I.metadataCache.getFileCache(m));let Z=new Set;for(let m of d){let n=I.metadataCache.getFileCache(m)?.frontmatter?.[c];if(n!=null){if(Array.isArray(n))n.forEach(W=>{let N=W.toString().trim();N&&Z.add(N)});else if(typeof n!="object"){let W=n.toString().trim();W&&Z.add(W)}}if(b.inline){let W=await I.vault.read(m);qd.getFieldValues(W,c).forEach(Y=>Z.add(Y))}}return Array.from(Z).sort()},clearCache:c=>{bc.getInstance().clear(c)}}}}static async inputPrompt(I,l,G,c){try{return await pl.Prompt(I,l,G,c)}catch(t){Wt(t);return}}static async datePrompt(I,l,G){try{let c=await Nb.Prompt(I,l,G?.placeholder,G?.defaultValue,G?.dateFormat);if(c&&c.startsWith("@date:")){let t=c.slice(6);return(G?.dateFormat?bt(t,G.dateFormat):null)??t}return c}catch(c){Wt(c);return}}static async wideInputPrompt(I,l,G,c){try{return await dt.Prompt(I,l,G,c)}catch(t){Wt(t);return}}static async yesNoPrompt(I,l,G){try{return await ue.Prompt(I,l,G)}catch(c){Wt(c);return}}static async infoDialog(I,l,G){try{return await nn.Show(I,l,G)}catch(c){Wt(c);return}}static async suggester(I,l,G,c,t=!1,b){try{let d;return typeof l=="function"?d=G.map(l):d=l,d=d.map(Z=>LG(Z)),t?await ZG.Suggest(I,d,G,{...c?{placeholder:c}:{},...b?.renderItem?{renderItem:b.renderItem}:{}}):await CG.Suggest(I,d,G,c,b?.renderItem)}catch(d){Wt(d);return}}static async checkboxPrompt(I,l,G){try{return await an.Open(I,l,G)}catch(c){Wt(c);return}}};function Wt(e){if(e instanceof SI)throw e;if(il(e))throw new SI("Inputcancelledbyuser")}var $d=class extends Xd{};var mG=[];for(let e=0;e<256;++e)mG.push((e+256).toString(16).slice(1));function NR(e,I=0){return(mG[e[I+0]]+mG[e[I+1]]+mG[e[I+2]]+mG[e[I+3]]+"-"+mG[e[I+4]]+mG[e[I+5]]+"-"+mG[e[I+6]]+mG[e[I+7]]+"-"+mG[e[I+8]]+mG[e[I+9]]+"-"+mG[e[I+10]]+mG[e[I+11]]+mG[e[I+12]]+mG[e[I+13]]+mG[e[I+14]]+mG[e[I+15]]).toLowerCase()}var oh,vJ=new Uint8Array(16);function Xh(){if(!oh){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues()notsupported.Seehttps://github.com/uuidjs/uuid#getrandomvalues-not-supported");oh=crypto.getRandomValues.bind(crypto)}return oh(vJ)}var yJ=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Qh={randomUUID:yJ};function JJ(e,I,l){if(Qh.randomUUID&&!I&&!e)return Qh.randomUUID();e=e||{};let G=e.random??e.rng?.()??Xh();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(`UUID byte range ${l}:${l+15} is out of buffer bounds`);for(let c=0;c<16;++c)I[l+c]=G[c];return I}return NR(G)}var iG=JJ;var lG=class{constructor(I,l){this.name=I,this.type=l,this.id=iG()}};var YR=require("obsidian");var rl=class extends lG{constructor(I){super(I,"EditorCommand"),this.editorCommandType=I}static getSelectedText(I){return this.getActiveMarkdownView(I).editor.getSelection()}static getActiveMarkdownView(I){le
`)}var LR=require("obsidian");function bZ(e,I){if(I.options)for(let l in I.options){let G=e[l]===void 0,c="defaultValue"in I.options[l]&&I.options[l].defaultValue!==void 0;G&&c&&(e[l]=I.options[l].defaultValue)}}var AJ=["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","contains","notContains"],CR=new Set(["true","1","yes","on"]),iR=new Set(["false","0","no","off"]);function Nt(e){return AJ.includes(e)}function hR(e){switch(e){case"lessThan":case"lessThanOrEqual":case"greaterThan":case"greaterThanOrEqual":return"number";case"equals":case"notEquals":return"string";case"contains":case"notContains":return"string";case"isTruthy":case"isFalsy":default:return"boolean"}}function pR(e){if(!Nt(e.operator)||e.expectedValue===void 0||e.expectedValue===null)return;let I=e.expectedValue.trim();switch(e.valueType){case"number":{let l=Number(I);return Number.isNaN(l)?NaN:l}case"boolean":{let l=I.toLowerCase();return CR.has(l)?!0:iR.has(l)?!1:!!I}case"string":default:return I}}function rh(e,I){switch(I){case"number":return typeof e=="number"?e:typeof e=="boolean"?e?1:0:Number(e);case"boolean":if(typeof e=="boolean")return e;if(typeof e=="string"){let l=e.trim().toLowerCase();if(CR.has(l))return!0;if(iR.has(l))return!1}return!!e;case"string":default:return e==null?"":String(e)}}function EJ(e){if(!Nt(e.operator))return"";let I=e.expectedValue??"";return I.length===0?"(empty)":e.valueType==="string"?`"${I}"`:I}function kJ(e){let I=e.variableName?`$${e.variableName}`:"(missing variable)",l=KJ(e.operator),G=Nt(e.operator)?`${EJ(e)}`:"";return`${I}${l}${G}`.trim()}function OJ(e){let I=e.exportName?`::${e.exportName}`:"";return`script${e.scriptPath}${I}`}function dZ(e){return e.mode==="variable"?kJ(e):OJ(e)}function KJ(e){switch(e){case"equals":return"equals";case"notEquals":return"does not equal";case"lessThan":return"is less than";case"lessThanOrEqual":return"is less than or equal to";case"greaterThan":return"is greater than";case"greaterThanOrEqual":return"is greater than or equal to";case"contains":return"contains";case"notContains":return"does not contain";case"isTruthy":return"is truthy";case"isFalsy":return"is falsy";default:return e}}async function oR(e,I){return e.mode==="script"?await I.evaluateScriptCondition(e):UJ(e,I.variables)}function UJ(e,I){let l=e.variableName?.trim();if(!l)return K.logWarning("Conditional command skipped: No variable name configured."),!1;if(!(l in I))return K.logWarning(`Conditionalcommandskipped:Variable'${l}'isnotdefined.`),!1;let G=I[l];switch(e.operator){case"isTruthy":return!!G;case"isFalsy":return!G}if(Nt(e.operator)){let c=pR(e);return c===void 0?(K.logWarning(`Conditionalcommand:Operator'${e.operator}'requiresacomparisonvalue.`),!1):e.operator==="contains"?VR(G,c,e):e.operator==="notContains"?!VR(G,c,e):xJ(G,c,e)}return!1}function VR(e,I,l){return e==null?!1:typeof I=="string"&&I.length===0?(K.logWarning("Conditional command: 'contains' operator requires a non-empty comparison value."),!1):Array.isArray(e)?e.map(G=>rh(G,l.valueType)).some(G=>G===I):typeof e=="string"?e.includes(String(I)):typeof e=="number"&&typeof I=="number"?e===I:String(e).includes(String(I))}function xJ(e,I,l){let G=rh(e,l.valueType);switch(l.operator){case"equals":return G===I;case"notEquals":return G!==I;case"lessThan":return YY(G,I,(c,t)=>c<t);case"lessThanOrEqual":return YY(G,I,(c,t)=>c<=t);case"greaterThan":return YY(G,I,(c,t)=>c>t);case"greaterThanOrEqual":return YY(G,I,(c,t)=>c>=t);default:return!1}}function YY(e,I,l){let G=Number(e),c=Number(I);return Number.isNaN(G)||Number.isNaN(c)?(K.logWarning("Conditional command numeric comparison failed: non-numeric value encountered."),!1):l(G,c)}var XR=require("obsidian");function Yt(e,{logPrefix:I,noticePrefix:l=I,defaultReason:G}){if(!(e instanceof SI))return!1;let c=typeof e.message=="string"&&e.message.trim().length>0?e.message:G;return K.logMessage(`${I}:${c}`),(!(typeof e.message=="string"&&e.message.toLowerCase().includes("cancelled by user"))||P.getState().showInputCancellationNotification)&&new XR.Notice(`${l}:${c}`
${d}`;returnawaitthis.app.vault.modify(l,m),l}catch(t){if(Lh(t))throwt;returnqI(t,"Could not append to file with template"),null}}asyncgetTemplateContent(l){letG=this.stripLeadingSlash(l);!vt.test(l)&&!kZ.test(l)&&(G+=".md");letc=this.app.vault.getAbstractFileByPath(G);if(!(cinstanceofmZ.TFile))thrownewError(`Template file not found at path "${G}".`);returnawaitthis.app.vault.cachedRead(c)}};varst=classextendsaZ{constructor(l,G,c,t){super(l,G,t);this.templatePath=c}asyncrun(){letl=awaitthis.getTemplateContent(this.templatePath);returnl||K.logError(`Template ${this.templatePath} not found.`),l=awaitthis.formatter.formatFileContent(l),l}getAndClearTemplatePropertyVars(){returnthis.formatter.getAndClearTemplatePropertyVars()}};varFG=classextendsPe{constructor(l,G,c){super(l);this.plugin=G;this.dateParser=c||ge}asyncformat(l){letG=l;try{G=awaitthis.replaceGlobalVarInString(G),G=this.replaceDateInString(G),G=this.replaceTimeInString(G),G=awaitthis.replaceValueInString(G),G=awaitthis.replaceSelectedInString(G),G=awaitthis.replaceClipboardInString(G),G=awaitthis.replaceDateVariableInString(G),G=awaitthis.replaceVariableInString(G),G=awaitthis.replaceLinkToCurrentFileInString(G),G=awaitthis.replaceCurrentFileNameInString(G),G=awaitthis.replaceMacrosInString(G),G=awaitthis.replaceTemplateInString(G),G=awaitthis.replaceFieldVarInString(G),G=this.replaceRandomInString(G),G=this.replaceLinebreakInString(G)}catch{returnl}returnG}asyncreplaceGlobalVarInString(l){letG=l,c=0,t=newRegExp(jc.source,"gi");for(;t.test(G)&&!(++c>5);)G=G.replace(t,(b,d)=>{letZ=String(d??"").trim();if(!Z)returnb;letm=this.plugin?.settings?.globalVariables?.[Z];returntypeofm=="string"?m:""});returnG}promptForValue(l){returnl||"user input"}getVariableValue(l){letG=this.variables.get(l);if(typeofG=="string")returnG;letc=In(l);returnaN(c)}getCurrentFileLink(){returnthis.app?YN(this.app.workspace.getActiveFile()):null}getCurrentFileName(){returnthis.app?sN(this.app.workspace.getActiveFile()):"current_filename"}suggestForValue(l,G=!1,c){returnNN(l)}getMacroValue(l,G){returnnN(l)}promptForMathValue(){returnPromise.resolve("calculation_result")}promptForVariable(l,G){returnPromise.resolve(WN(l))}asyncgetTemplateContent(l){letG=this.app;if(!G)return`Template (app unavailable): ${l}`;try{returnawaitnewst(G,this.plugin,l,void0).run()}catch{return`Template (not found): ${l}`}}asyncgetSelectedText(){return"selected_text"}asyncgetClipboardContent(){return"clipboard_content"}asyncsuggestForField(l){returnPromise.resolve(`${l}_field_value`)}asyncreplaceDateVariableInString(l){letG=l;returnG=G.replace(newRegExp(Ht.source,"gi"),(c,t,b,d)=>{letZ=t?.trim(),m=b?.trim(),a=d?.trim();if(!Z||!m)returnc;letn=newDate,W;try{W=_e.generate(m,n)}catch{W=`[${m} format]`}returna&&(W+=` (default: ${a})`),W}),G}replaceRandomInString(l){letG=l;returnG=G.replace(/{{RANDOM:(\d+)}}/gi,(c,t)=>{letb=parseInt(t);if(b<=0||b>100)returnc;letd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Z="";for(letm=0;m<Math.min(b,8);m++)Z+=d.charAt(Math.floor(Math.random()*d.length));returnb>8&&(Z+=`... (${b} chars)`),Z}),G}isTemplatePropertyTypesEnabled(){return!1}};varhY=require("obsidian");varhG=classextendsIG{constructor(l,G,c,t=1/0){super(l,G);this.app=l;this.inputEl=G;this.items=c;this.maxSuggestions=t;this.items=c.map(b=>LG(b))}getSuggestions(l){letG=Hc(l).toLowerCase(),c=this.items.filter(b=>b.toLowerCase().includes(G));returnc.length===0&&this.close(),c.slice(0,this.maxSuggestions)}selectSuggestion(l){this.inputEl.value=l,this.inputEl.trigger("input"),this.close()}renderSuggestion(l,G){l&&this.renderMatch(G,l,this.getCurrentQuery())}getCurrentQuery(){returnthis.inputEl.value}};functionQb(e){let{app:I,parent:l,initialValue:G="",placeholder:c,required:t=!1,requiredMessage:b="This field is required",validator:d,suggestions:Z,maxSuggestions:m=1/0,attachSuggesters:a=[],inputKind:n="text",debounceMs:W=0,trim:N=!0,ariaHintId:Y,fullWidth:u=!0,marginBottomPx:C=8,onChange:p}=e,o=n==="textarea"?newhY.TextA
Inordertobeiterable,non-arrayobjectsmusthavea[Symbol.iterator]()method.`)}function mA(){throw new TypeError(`Invalidattempttodestructurenon-iterableinstance.
Inordertobeiterable,non-arrayobjectsmusthavea[Symbol.iterator]()method.`)}function En(e,I){var l=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!l){if(Array.isArray(e)||(l=Kh(e))||I&&e&&typeof e.length=="number"){l&&(e=l);var G=0,c=function(){};return{s:c,n:function(){return G>=e.length?{done:!0}:{done:!1,value:e[G++]}},e:function(Z){throw Z},f:c}}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!":""}
`)}asyncfunctionvr(e,I,l){if(e.type==="Multi")try{returnawaitnewIs(I,e).waitForClose}catch{return}letG=jE(e,I,l);if(!G)thrownewError("Invalid choice type");returnawaitG.waitForClose}functionyr(e){return{...e,command:!e.command}}varGs=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)}};functionJr(e,I,l){if(!I||!l)returne;letG=I0(e,I),c=I0(e,l);if(!G||!c||c.type!=="Multi"||G.type==="Multi"&&(G.id===c.id||fE(G).has(c.id)))returne;let{updated:t,removed:b}=Ar(e,I);returnb?Er(t,l,b)??e:e}functionI0(e,I){for(letlofe){if(l.id===I)returnl;if(l.type==="Multi"){letG=I0(l.choices,I);if(G)returnG}}}functionfE(e){letI=newSet,l=G=>{I.add(G.id),G.type==="Multi"&&G.choices.forEach(l)};return(e.choices??[]).forEach(l),I}functionAr(e,I){letl;return{updated:e.map(c=>{if(c.id===I){l=c;return}if(c.type!=="Multi")returnc;lett=Ar(c.choices,I);returnt.removed&&(l=t.removed),t.removed?{...c,choices:t.updated}:c}).filter(Boolean),removed:l}}functionEr(e,I,l){letG=!1,c=e.map(t=>{if(t.id===I&&t.type==="Multi"){G=!0;letd=t;return{...d,choices:[...d.choices,l]}}if(t.type!=="Multi")returnt;letb=Er(t.choices,I,l);returnb?(G=!0,{...t,choices:b}):t});returnG?c:void0}varsc=require("obsidian");varQl=require("obsidian");varkr=require("obsidian");vares=null,SE=24*60*60*1e3;asyncfunctionOr(){if(es&&Date.now()-es.fetchedAt<SE)returnes.data;if(P.getState().disableOnlineFeatures)thrownewError("Fetching models directory is disabled: Online features are turned off.");letI=await(await(0,kr.requestUrl)({url:"https://models.dev/api.json",method:"GET"})).json;returnes={data:I,fetchedAt:Date.now()},I}functione0(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}functionKr(e){returne.map(I=>({name:I.id,maxTokens:Math.max(1,Math.floor(I.limit?.context??128e3))}))}functionc0(e,I){letl=newSet(e.map(c=>c.name)),G=I.filter(c=>!l.has(c.name));returne.concat(G)}varzr=require("obsidian");varTE=128e3;asyncfunctioncs(e,I){letl=e.modelSource??"providerApi";if(l==="modelsDev")returnUr(e);if(l==="providerApi")returnxr(e,I);try{returnawaitxr(e,I)}catch(G){if(!e0(e.endpoint))throwG;returnUr(e,G)}}asyncfunctionUr(e,I){try{letl=awaitOr(),G=e0(e.endpoint);if(!G||!(Ginl))thrownewError(`models.dev does not list a provider that matches ${e.endpoint}.`);letc=Object.values(l[G].models);returnKr(c)}catch(l){throwI?newError(`Provider API failed (${I.message}). Fallback to models.dev also failed: ${l.message}`):l}}asyncfunctionxr(e,I){let{disableOnlineFeatures:l}=P.getState();if(l)thrownewError("Online features are disabled \u2014 enable them to browse provider models.");if(!e.endpoint)thrownewError("Provider is missing an endpoi
yd=yesterday`).setValue(qs(P.getState().dateAliases)).onChange(b=>{P.setState({dateAliases:P0(b)})}),t.inputEl.style.width="100%",t.inputEl.style.minHeight="6rem",t.inputEl.style.flex="1 1 280px",t.inputEl.style.maxWidth="100%",t.inputEl.style.boxSizing="border-box"}),G.addButton(t=>{t.setButtonText("Reset to defaults").onClick(()=>{P.setState({dateAliases:Ob}),c&&c.setValue(qs(Ob))}),t.buttonEl.style.alignSelf="flex-start",t.buttonEl.style.whiteSpace="nowrap"})})}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(c=>c.setValue(P.getState().disableOnlineFeatures).onChange(t=>{P.setState({disableOnlineFeatures:t}),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(c=>{c.setValue(P.getState().enableRibbonIcon).onChange(t=>{P.setState({enableRibbonIcon:t}),this.display()})})})}};var LZ=class{formatOutputString(I){return`QuickAdd:(${I.level})${I.message}`}getQuickAddError(I,l,G,c){return{message:I,level:l,time:Date.now(),stack:G,originalError:c}}};var fn=class extends LZ{constructor(){super(...arguments);this.ErrorLog=[]}logError(l,G,c){let t=this.getQuickAddError(l,"ERROR",G,c);this.addMessageToErrorLog(t);let b=c||new Error(l);console.error(this.formatOutputString(t),b)}logWarning(l,G,c){let t=this.getQuickAddError(l,"WARNING",G,c);this.addMessageToErrorLog(t);let b=c||new Error(l);console.warn(this.formatOutputString(t),b)}logMessage(l,G,c){let t=this.getQuickAddError(l,"LOG",G,c);this.addMessageToErrorLog(t),c?console.log(this.formatOutputString(t),c):console.log(this.formatOutputString(t))}addMessageToErrorLog(l){this.ErrorLog.push(l),this.ErrorLog.length>SC&&(this.ErrorLog=this.ErrorLog.slice(-SC))}clearErrorLog(){this.ErrorLog=[]}};var V0=require("obsidian");var Vs=class extends LZ{constructor(l){super();this.plugin=l}logError(l,G,c){let t=this.getQuickAddError(l,"ERROR",G,c);new V0.Notice(this.formatOutputString(t),15e3)}logWarning(l,G,c){let t=this.getQuickAddError(l,"WARNING",G,c);new V0.Notice(this.formatOutputString(t))}logMessage(l,G,c){}};var os=class{constructor(I,l,G,c){this.app=I;this.plugin=l;this.choices=G;this.choiceExecutor=c}async run(){let I=Ue(this.choices).filter(l=>l.type==="Macro"&&l.runOnStartup);for(let l of I)await new dc(this.app,this.plugin,l,this.choiceExecutor,new Map).run()}};var o0=require("obsidian");var Xs=class extends aZ{constructor(I,l,G,c){super(I,l,c),this.choiceExecutor=c,this.choice=G}async run(){try{SG(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 I=lt(this.choice.appendLink);this.setLinkToCurrentFileBehavior(I.enabled&&!I.requireActiveFile?"optional":"required");let l="";if(this.choice.folder.enabled)l=await this.getFolderPath();else{let Z=this.app.fileManager.getNewFileParent(this.app.workspace.getActiveFile()?.path??"");l=Z===this.app.vault.getRoot()?"":Z.path}let G=this.choice.fileNameFormat.enabled?this.choice.fileNameFormat.format:gt,c=await this.formatter.formatFileName(G,this.choice.name),t=this.normalizeTemplateFilePath(l,c,this.choice.templatePath);this.choice.fileExistsMode===yt&&(t=await this.incrementFileName(t));let b,d=!1;if(await this.app.vault.adapter.exists(t)){let Z=this.findExistingFile(t);if(!(Z instanceof o0.TFile)||Z.extension!=="md"&&Z.extension!=="canvas"){K.logError(`'${t}'alreadyexistsbutcouldnotberesolvedasamarkdownorcanvasfile.`);return}let m=this.choice.fileExistsMode;if(!this.choice.setFileExistsBehavior)try{m=await CG.Suggest(this.app,[...cu],[...cu])}catch(a){throw
`)}}varlF=e=>e.join(""),sO=e=>e.split(/\b/),uO=IF("<<<<<<< YOUR CHANGES","=======",">>>>>>> APP AUTHORS CHANGES",lF),CO={splitFunction:sO,joinFunction:lF,conflictFunction:uO};functionF0(e,I,l,G={}){G=Object.assign({},CO,G);let[c,t,b]=[e,I,l].map(m=>G.splitFunction.call(G,m)),d=qn.merge(c,t,b);returnPn.collateMerge(d,G.joinFunction,G.conflictFunction)}varGF=F0;varw0=require("obsidian");functioneF(e,I){returne.line===I.line}functioniO(e){letI=[];returne.forEach((l,G)=>{letc=l.match(/^(#+)[\s]+(.*)$/);c&&I.push({level:c[1].length,text:c[2],line:G})}),I}functionFs(e,I,l=!1){letG=iO(e),c=G.find(m=>m.line===I),t=!!c;if(!t&&l)thrownewError(`Target line ${I} is not a heading, but we are trying to find the end of its section.`);if(!t&&!l){letm=cF(e,I,a=>a.trim()==="");returnm!==null&&m>I?m-1:I}letb=e.length-1,d=hO(c,G,e,l),Z=oO(e,d,m=>m.trim()!=="");if(Z!==null){if(Z<I)returnI;letm=e[Z+1].trim()==="";returnZ+1===b&&!m?d:Z===0?Z+1:Z}returnd}functionhO(e,I,l,G){letc=I.findIndex(a=>eF(a,e)),t=c===I.length-1,b=l.length-1;if(t)returnb;let[d,Z]=pO(e,I);if(Z&&d===I.length)returnb;if(Z&&G)returnI[d].line-1;if(Z&&!G)returnI[c+1].line;if(!G&&!Z){leta=VO(e.line,I);returna===null?b:a}returnb}functionpO(e,I){letl=I.findIndex(c=>eF(c,e)),G=cF(I,l,c=>c.level<=e.level);returnG===null?[-1,!1]:[G,!0]}functionVO(e,I){letl=I.findIndex(G=>G.line>e);returnl===-1?null:l}functionoO(e,I,l){for(letG=I-1;G>=0;G--)if(l(e[G]))returnG;returnnull}functioncF(e,I,l){for(letG=I+1;G<e.length;G++)if(l(e[G]))returnG;returnnull}varws=classextendsKe{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,c,t){if(this.choice=G,this.file=t,this.fileContent=c,!G||!t||c===null)returnl;letb=G.insertAfter.enabled||G.prepend||!G.captureToActiveFile||G.activeFileWritePosition==="top";returnawaitthis.formatFileContent(l,b)}asyncformatContent(l,G){returnthis.choice=G,G?awaitthis.formatFileContent(l):l}asyncformatFileContent(l,G=!0){letc=awaitsuper.formatFileContent(l);if(c=this.replaceLinebreakInString(c),G&&this.file&&!this.templaterProcessed){letd=awaitpd(this.app,c,this.file);d&&(c=d),this.templaterProcessed=!0}if(c.trim()==="")returnthis.fileContent;if(this.choice.prepend){letd=!this.choice.task;return`${this.fileContent}${d?`
`)?Math.max(l.length-1,0):l.length,m=G;for(leta=G+1;a<Z;a++){if(l[a].trim().length===0){m=a;continue}break}returnm}asyncinsertAfterHandler(l){letG=awaitthis.formatLocationString(this.choice.insertAfter.after);if(this.choice.insertAfter?.inline)returnawaitthis.insertAfterInlineHandler(l,G);letc=Rh(this.fileContent),t=this.findInsertAfterIndex(c,G);if(t===-1){if(this.choice.insertAfter?.createIfNotFound)returnawaitthis.createInsertAfterIfNotFound(l);qI(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.");t=Fs(c,t,!!this.choice.insertAfter.considerSubsections)??c.length-1}else{letd=this.choice.insertAfter?.blankLineAfterMatchMode??"auto";t=this.findInsertAfterPositionWithBlankLines(c,t,this.fileContent,d)}returnthis.insertTextAfterPositionInBody(l,this.fileContent,t)}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))returnqI(newError("Inline insert after target must be a single line."),"Insert After Inline Error"),this.fileContent;letc=this.fileContent.indexOf(G);if(c===-1)returnthis.choice.insertAfter?.createIfNotFound?awaitthis.createInlineInsertAfterIfNotFound(l,G):(qI(newError("Unable to find insert after text in file."),"Insert After Inline Error"),this.fileContent);lett=c+G.length;if(this.choice.insertAfter?.replaceExisting){letb=this.getInlineEndOfLine(t);returnthis.fileContent.slice(0,t)+l+this.fileContent.slice(b)}returnthis.fileContent.slice(0,t)+l+this.fileContent.slice(t)}asynccreateInsertAfterIfNotFound(l){letc=`${this.replaceLinebreakInString(awaitthis.formatLocationString(this.choice.insertAfter.after))}
${c}`;if(this.choice.insertAfter?.createIfNotFoundLocation===EZ)try{lett=this.app.workspace.getActiveViewOfType(w0.MarkdownView);if(!t)thrownewError("No active view.");letd=t.editor.getCursor().line;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)thrownewError("Tried to get sections without file.");letm=Rh(this.fileContent);d=Fs(m,d,!!this.choice.insertAfter.considerSubsections)??m.length-1}returnthis.insertTextAfterPositionInBody(c,this.fileContent,d)}catch(t){qI(t,`Unable to insert line '${this.choice.insertAfter.after}' at cursor position`)}}asynccreateInlineInsertAfterIfNotFound(l,G){letc=`${G}${l}`;if(this.choice.insertAfter?.createIfNotFoundLocation===Kb){lett=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):-1;returnthis.insertTextAfterPositionInBody(c,this.fileContent,t)}if(this.choice.insertAfter?.createIfNotFoundLocation===AZ)return`${this.fileContent}
${c}`;if(this.choice.insertAfter?.createIfNotFoundLocation===EZ)try{lett=this.app.workspace.getActiveViewOfType(w0.MarkdownView);if(!t)thrownewError("No active view.");letd=t.editor.getCursor().line;returnthis.insertTextAfterPositionInBody(c,this.fileContent,d)}catch(t){qI(t,`Unable to insert line '${this.choice.insertAfter.after}' at cursor position`)}returnK.logWarning(`Unknown createIfNotFoundLocation: ${this.choice.insertAfter?.createIfNotFoundLocation}`),this.fileContent}getFrontmatterEndPosition(l,G){letc=this.app.metadataCache.getFileCache(l);if(c?.frontmatterPosition)returnc.frontmatterPosition.end.line;if(G){lett=this.inferFrontmatterEndLineFromContent(G);if(t!==null)returnt}returnK.logMessage("could not get frontmatter. Maybe there isn't any."),-1}inferFrontmatterEndLineFromContent(l){letG=bN(l);if(!G)returnnull;letc=l.slice(0,G[1]),t=c.split(/\r?\n/);returnt.length===0?null:c.endsWith(`
${l}${d}`}};functiontF(e){returne.captureToActiveFile&&e.newLineCapture?.enabled?e.newLineCapture.direction==="above"?"newLineAbove":"newLineBelow":e.captureToActiveFile&&!e.prepend&&!e.insertAfter.enabled?e.activeFileWritePosition==="top"?"activeFileTop":"currentLine":e.insertAfter.enabled?"insertAfter":e.prepend?"prepend":"append"}varbF=4e3,gs=classextends$d{constructor(l,G,c,t){super(l);this.choiceExecutor=t;this.capturePropertyVars=newMap;this.choice=c,this.plugin=G,this.formatter=newws(l,G,t)}showSuccessNotice(l,{wasNewFile:G,action:c}){lett=`'${l.basename}'`;if(G){newg0.Notice(`Created and captured to ${t}`,bF);return}letb="";switch(c){case"currentLine":b=`Captured to current line in ${t}`;break;case"prepend":case"activeFileTop":b=`Captured to top of ${t}`;break;case"append":b=`Captured to ${t}`;break;case"insertAfter":{letd=this.choice.insertAfter.after;b=d?`Captured to ${t} under '${d}'`:`Captured to ${t}`;break}}newg0.Notice(b,bF)}asyncrun(){try{this.capturePropertyVars.clear();letl=lt(this.choice.appendLink);this.formatter.setLinkToCurrentFileBehavior(l.enabled&&!l.requireActiveFile?"optional":"required");letG=this.choice.useSelectionAsCaptureValue,c=this.plugin.settings.useSelectionAsCaptureValue??!0,t=typeofG=="boolean"?G:c;this.formatter.setUseSelectionAsCaptureValue(t);letb=awaitthis.getFormattedPathToCaptureTo(this.choice.captureToActiveFile),d=this.getCaptureContent(),Z,m=awaitthis.fileExists(b);if(m)Z=this.onFileExists.bind(this);elseif(this.choice?.createFileIfItDoesntExist?.enabled)Z=(u,C,p)=>this.onCreateFileIfItDoesntExist(u,C,l);else{K.logWarning(`The file ${b} does not exist and "Create file if it doesn't exist" is disabled.`);return}let{file:a,newFileContent:n,captureContent:W}=awaitZ(b,d),N=tF(this.choice);if(N==="currentLine"||N==="newLineAbove"||N==="newLineBelow"){letu=awaitpd(this.app,W,a);switch(N){case"currentLine":Wo(u,this.app);break;case"newLineAbove":Yo(u,this.app);break;case"newLineBelow":so(u,this.app);break}}elseawaitthis.app.vault.modify(a,n),this.choice.templater?.afterCapture==="wholeFile"&&awaithd(this.app,a),awaitthis.applyCapturePropertyVars(a);if(this.plugin.settings.showCaptureNotification&&this.showSuccessNotice(a,{wasNewFile:!m,action:N}),l.enabled&&GN(this.app,a,l),this.choice.openFile&&a){letu=KG(this.choice.fileOpening),C=u.focus??!0;eN(this.app,a,C)||awaitVd(this.app,a,u),awaitlN(this.app,a)}}catch(l){if(Yt(l,{logPrefix:"Capture execution aborted",noticePrefix:"Capture execution aborted",defaultReason:"Capture aborted"})){this.choiceExecutor.signalAbort?.(l);return}qI(l,`Error running capture choice "${this.choice.name}"`)}}getCaptureContent(){letl;returnthis.choice.format.enabled?l=this.choice.format.format:l=gt,this.choice.task&&(l=`- [ ] ${l}
`),l}asyncgetFormattedPathToCaptureTo(l){letG=this.choiceExecutor?.variables?.get(UZ);if(!l&&G&&typeofG=="string"&&G.length>0)returnG;if(l){leta=this.app.workspace.getActiveFile();returnSG(a,"Cannot capture to active file - no active file."),a.path}letc=this.choice.captureTo,t=awaitthis.formatFilePath(c),b=t.replace(/^\/$|\/\.md$|^\.md$/,""),d=b==="",Z=d||cN(this.app,b),m=t.startsWith("#");if(Z)returnthis.selectFileInFolder(b,d);if(m){leta=t.replace(/\.md$/,"");returnthis.selectFileWithTag(a)}returnt}asyncselectFileInFolder(l,G){letc=l.endsWith("/")||G?l:`${l}/`,t=Gt(this.app,c);SG(t.length>0,`Folder ${c} is empty.`);letb=t.map(m=>m.path),d;try{d=awaitZG.Suggest(this.app,b.map(m=>m.replace(c,"")),b)}catch(m){throwil(m)?newSI("Input cancelled by user"):m}SG(!!d&&d.length>0,"No file selected for capture.");letZ=d.startsWith(`${c}`)?d:`${c}/${d}`;returnawaitthis.formatFilePath(Z)}asyncselectFileWithTag(l){letG=l.startsWith("#")?l:`#${l}`,c=tN(this.app,G);SG(c.length>0,`No files with tag ${l}.`);lett=c.map(d=>d.path),b;try{b=awaitZG.Suggest(this.app,t,t)}catch(d){throwil(d)?newSI("Input cancelled by user"):d}returnSG(!!b&&b.length>0,"No file selected for capture."),awaitthis.formatFilePath(b)}asynconFileExists(l,G){letc=this.getFileByPath(l);if(!c)thrownewError("File not found");this.formatter.setTitle(c.basename),this.formatter.setDestinationFile(c);lett=awaitthis.formatter.formatContentOnly(G);this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());letb=awaitthis.app.vault.read(c),d=awaitthis.formatter.formatContentWithFile(t,this.choice,b,c);this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());letZ=awaitthis.app.vault.read(c),m=d;if(Z!==b){leta=GF(Z,b,d);SG(!a.isSuccess,()=>`The file ${l} has been modified since the last read.
This is in order to prevent data loss.`),m=a.joinedResults()}return{file:c,newFileContent:m,captureContent:t}}asynconCreateFileIfItDoesntExist(l,G,c){lett=l.split("/").pop()?.replace(/\.md$/,"")||"";this.formatter.setTitle(t),this.formatter.setDestinationSourcePath(l);letb=awaitthis.formatter.formatContentOnly(G);this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());letd="";if(this.choice.createFileIfItDoesntExist.createWithTemplate){letn=newst(this.app,this.plugin,this.choice.createFileIfItDoesntExist.template,this.choiceExecutor);c?.enabled&&!c.requireActiveFile&&n.setLinkToCurrentFileBehavior("optional"),d=awaitn.run();letW=n.getAndClearTemplatePropertyVars();K.logMessage(`CaptureChoiceEngine: Collected ${W.size} template property variables`),W.size>0&&K.logMessage(`Variables: ${Array.from(W.keys()).join(", ")}`),this.templatePropertyVars=W}letZ=awaitthis.createFileWithInput(l,d,{suppressTemplaterOnCreate:this.choice.createFileIfItDoesntExist.createWithTemplate});this.choice.createFileIfItDoesntExist.createWithTemplate&&this.templatePropertyVars&&this.shouldPostProcessFrontMatter(Z,this.templatePropertyVars)&&awaitthis.postProcessFrontMatter(Z,this.templatePropertyVars),this.choice.createFileIfItDoesntExist.createWithTemplate&&d?awaithd(this.app,Z):IN(this.app)&&awaitao(this.app,Z);letm=awaitthis.app.vault.read(Z),a=awaitthis.formatter.formatContentWithFile(b,this.choice,m,Z);returnthis.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars()),{file:Z,newFileContent:a,captureContent:b}}asyncformatFilePath(l){letG=awaitthis.formatter.formatFileName(l,this.choice.name);returnthis.normalizeMarkdownFilePath("",G)}mergeCapturePropertyVars(l){if(!(!l||l.size===0)){for(let[G,c]ofl)this.capturePropertyVars.set(G,c);K.logMessage(`CaptureChoiceEngine: Accumulated ${this.capturePropertyVars.size} structured capture variables`)}}asyncapplyCapturePropertyVars(l){if(this.capturePropertyVars.size!==0){if(!this.shouldPostProcessFrontMatter(l,this.capturePropertyVars)){this.capturePropertyVars.clear();return}K.logMessage(`CaptureChoiceEngine: Post-processing front matter with ${this.capturePropertyVars.size} capture variables`),awaitthis.postProcessFrontMatter(l,this.capturePropertyVars),this.capturePropertyVars.clear()}}};varHs=require("obsidian");varH0="\u2190 Back",Vt=classeextendsHs.FuzzySuggestModal{constructor(l,G,c){super(l.app);this.plugin=l;this.choices=G;this.choiceExecutor=newKc(this.app,this.plugin);this.placeholderStack=[];c?.choiceExecutor&&(this.choiceExecutor=c.choiceExecutor),this.placeholderStack=c?.placeholderStack??[],this.currentPlaceholder=c?.placeholder?.trim()||void0,this.currentPlaceholder&&this.setPlaceholder(this.currentPlaceholder)}staticOpen(l,G,c){newe(l,G,c).open()}renderSuggestion(l,G){G.empty(),Hs.MarkdownRenderer.renderMarkdown(l.item.name,G,"",this.plugin),G.classList.add("quickadd-choice-suggestion"),l.item.name===H0&&G.classList.add("quickadd-choice-suggestion-back")}getItemText(l){returnl.name}getItems(){returnthis.choices}asynconChooseItem(l,G){l.type==="Multi"?this.onChooseMultiType(l):awaitthis.choiceExecutor.execute(l)}onChooseMultiType(l){letG=[...l.choices],c=l.name===H0;c||G.push(newQZ(H0).addChoices(this.choices));lett=c?this.placeholderStack[this.placeholderStack.length-1]:l.placeholder?.trim()||l.name,b=c?this.placeholderStack.slice(0,-1):[...this.placeholderStack,this.currentPlaceholder];e.Open(this.plugin,G,{choiceExecutor:this.choiceExecutor,placeholder:t,placeholderStack:b})}};varvs=require("obsidian");var_n=classextendsPe{constructor(l,G,c){super(l);this.app=l;this.plugin=G;this.choiceExecutor=c;this.requirements=newMap;this.templatesToScan=newSet;this.dateParser=ge,c&&(this.variables=newMap(c.variables))}asyncscanString(l){letG=awaitthis.replaceGlobalVarInString(l);this.scanVariableTokens(G),awaitthis.format(G)}asyncformat(l){letG=l;G=awaitthis.replaceGlobalVarInString(G),G=this.replaceDateInString(G),G=this.replaceTimeInString(G),G=awaitthis.replaceValueInString(G),G=awaitthis.repl
QuickAddwillnowreverttobackup.`),e.settings=G}}e.saveSettings()}var pF=UO;var gZ=require("obsidian");async function xO(e,I,l){let G=await fetch(`https://api.github.com/repos/${e}/${I}/releases`),c=await G.json();if(!G.ok&&"message"in c||!Array.isArray(c))throw new Error(`Failed to fetch releases: ${c.message??"Unknown error"}`);let t=c.findIndex(b=>b.tag_name===l);if(t===-1)throw new Error(`Could not find release with tag ${l}`);return c.slice(0,t).filter(b=>!b.draft&&!b.prerelease)}function zO(e,I=1){let l=e.split(`
`,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.",c='<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>',t=I.createDiv("quickadd-update-modal"),b=this.releases.map(a=>a.body).join(`
${zO(b)}`;gZ.MarkdownRenderer.renderMarkdown(m,t,this.app.vault.getRoot().path,new gZ.Component)}};var xl=require("obsidian");var Us=class extends xl.Modal{constructor(l,G){super(l);this.showAdvancedSettings=!1;this.settings=G,this.waitForClose=new Promise((c,t)=>{this.rejectPromise=t,this.resolvePromise=c}),this.open(),this.display()}get systemPromptTokenLength(){let l=Je(this.settings.model);return l?TG(this.settings.systemPrompt,l):Number.POSITIVE_INFINITY}display(){this.contentEl.empty();let l=this.contentEl.createEl("h2",{text:`${this.settings.name}Settings`});l.style.textAlign="center",l.style.cursor="pointer",l.style.userSelect="none",l.addEventListener("click",async()=>{try{let G=await pl.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){new xl.Setting(l).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(G=>{let c=Gc();for(let t of c)G.addOption(t,t);G.addOption("Ask me","Ask me"),G.setValue(this.settings.model),G.onChange(t=>{this.settings.model=t,this.reload()})})}addOutputVariableNameSetting(l){new xl.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(c=>{this.settings.outputVariableName=c})})}addSystemPromptSetting(l){new xl.Setting(l).setName("System Prompt").setDesc("The system prompt for the AI Assistant");let G=this.contentEl.createEl("div"),c=G.createEl("span");c.style.color="var(--text-muted-color)";let t=G.createEl("div",{text:"Exact for OpenAI models; estimates for others."});t.style.color="var(--text-muted-color)",t.style.fontSize="var(--font-ui-smaller)",G.appendChild(c),G.appendChild(t);let b=new xl.TextAreaComponent(l);b.setValue(this.settings.systemPrompt).onChange(async a=>{this.settings.systemPrompt=a,Z.innerText=await d.format(a),m()}),new eG(this.app,b.inputEl,PI.instance);let d=new FG(this.app,PI.instance);b.inputEl.style.width="100%",b.inputEl.style.height="100px",b.inputEl.style.minHeight="100px",b.inputEl.style.marginBottom="1em";let Z=this.contentEl.createEl("span"),m=(0,xl.debounce)(()=>{c.innerText=`Tokencount:${this.systemPromptTokenLength}`},50);m(),(async()=>Z.innerText=await d.format(this.settings.systemPrompt??""))()}addShowAdvancedSettingsToggle(l){new xl.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(c=>{this.showAdvancedSettings=c,this.reload()})})}addTemperatureSetting(l){new xl.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(c=>{this.settings.modelParameters.temperature=c})})}addTopPSetting(l){new xl.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,