`),Le=Cl(Qt,vZ,Xt).desc("newline"),eW=Cl(Le,le);t.all=hc,t.alt=Cl,t.any=Uc,t.cr=Xt,t.createLanguage=function(X){vary={};for(varUinX)({}).hasOwnProperty.call(X,U)&&function(j){y[j]=Ie(function(){returnX[j](y)})}(U);returny},t.crlf=Qt,t.custom=function(X){returnt(X(h,w))},t.digit=xc,t.digits=ot,t.empty=NG,t.end=eW,t.eof=le,t.fail=f,t.formatError=LI,t.index=DG,t.isParser=s,t.lazy=Ie,t.letter=zc,t.letters=Re,t.lf=vZ,t.lookahead=EI,t.makeFailure=w,t.makeSuccess=h,t.newline=Le,t.noneOf=function(X){returnjI(function(y){returnX.indexOf(y)<0}).desc("none of '"+X+"'")},t.notFollowedBy=KI,t.of=WG,t.oneOf=function(X){for(vary=X.split(""),U=0;U<y.length;U++)y[U]="'"+y[U]+"'";returnjI(function(j){returnX.indexOf(j)>=0}).desc(y)},t.optWhitespace=GW,t.Parser=t,t.range=function(X,y){returnjI(function(U){returnX<=U&&U<=y}).desc(X+"-"+y)},t.regex=nG,t.regexp=nG,t.sepBy=Qe,t.sepBy1=zG,t.seq=sl,t.seqMap=gl,t.seqObj=function(){for(varX,y={},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(y,NI))thrownewError("seqObj: duplicate key "+NI);y[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,Hl){for(varcl,Ge={},Bl=0;Bl<II;Bl+=1){varDl,Ml;if(Q(j[Bl])?(Dl=j[Bl][0],Ml=j[Bl][1]):(Dl=null,Ml=j[Bl]),!(cl=F(Ml._(Il,Hl),cl)).status)returncl;Dl&&(Ge[Dl]=cl.value),Hl=cl.index}returnF(h(Hl,Ge),cl)})},t.string=BG,t.succeed=WG,t.takeWhile=function(X){returnJ(X),t(function(y,U){for(varj=U;j<y.length&&X(O(y,j));)j++;returnh(j,y.slice(U,j))})},t.test=jI,t.whitespace=re,t["fantasy-land/empty"]=NG,t["fantasy-land/of"]=WG,t.Binary={bitSeq:N,bitSeqObj:function(X){W();vary={},U=0,j=m(function(lI){if(Q(lI)){var$=lI;if($.length!==2)thrownewError("["+$.join(", ")+"] should be length 2, got length "+$.length);if(v($[0]),K($[1]),Object.prototype.hasOwnProperty.call(y,$[0]))thrownewError("duplicate key in bitSeqObj: "+$[0]);returny[$[0]]=!0,U++,$}returnK(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(),K(X),X>255)thrownewError("Value specified to byte constructor ("+X+"=0x"+X.toString(16)+") is larger in value than a single byte.");vary=(X>15?"0x":"0x0")+X.toString(16);returnt(function(U,j){varII=O(U,j);returnII===X?h(j+1,II):w(j,y)})},buffer:function(X){returnY("buffer",X).map(function(y){returnBuffer.from(y)})},encodedString:function(X,y){returnY("string",y).map(function(U){returnU.toString(X)})},uintBE:u,uint8BE:u(1),uint16BE:u(2),uint32BE:u(4),uintLE:V,uint8LE:V(1),uint16LE:V(2),uint32LE:V(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}])})})(dY,dY.exports);varg=dY.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
`)}functionEZ(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){returnEZ(e).map(([I,l])=>`${I}=${l}`).join(", ")}varYW={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:Kb,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:WW},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=dp((c,t)=>({...Gl(YW)})),{getState:I,setState:l,subscribe:G}=e;return{getState:I,setState:l,subscribe:G}})();varll=require("obsidian");vargt="{{value}}",tu="{{date}}",mp="{{time}}",bu="{{name}}",cw="{{value:<variable name>}}",tw="{{value:<variable name>|<default value>}}",bw="{{value:<variable name>|default:<value>}}",dw="{{value:<variable name>|label:<helper text>}}",Zw="{{value|case:kebab}}",mw="{{value:<variable name>|case:kebab}}",aw="{{field:<field name>}}",ap="{{mvalue}}",np="{{linkcurrent}}",Wp="{{filenamecurrent}}",Np="{{title}}",Yp="{{selected}}",sp="{{clipboard}}",nw="{{random:<length>}}",Ww="{{global_var:<name>}}";varup=[tu,"{{date:<dateformat>}}","{{vdate:<variable name>, <date format>}}","{{vdate:<variable name>, <date format>|<default value>}}",Ww,gt,bu,Zw,mw,cw,tw,bw,dw,aw,nw];vardu=newRegExp(/^-?[0-9]*$/),Ub="top",kZ="bottom",OZ="cursor",sW=newRegExp(/{{DATE(\+-?[0-9]+)?}}/i),xb=newRegExp(/{{DATE:([^}\n\r+]*)(\+-?[0-9]+)?}}/i
`+e,{line:b,ch:d.length}),c.setCursor({line:b+1,ch:e.length})}}catch{x.logError(`unable to insert '${e}' on new line ${I}.`)}}functionRo(e,I){Qo(e,"above",I)}functionro(e,I){Qo(e,"below",I)}functiong4(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);x.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},C=W.length===0?"":`
`;b.replaceRange(C+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}functionv4(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}`}functioncN(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)?v4(b):b;returng4(e,Z,l.placement,{requireActiveView:!1}),!0}functiony4(e,I){returne.commands.findCommand(I)}functionLo(e,I){y4(e,I)&&(deletee.commands.commands[I],deletee.commands.editorCommands[I])}functioneb(e){returne.vault.getAllLoadedFiles().filter(I=>Iinstanceofne.TFolder).map(I=>I.path)}functionIn(e){letI=e.split("::").map(l=>l.trim()).filter(Boolean);return{basename:I[0],memberAccess:I.slice(1)}}asyncfunctionod(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}functiontN(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}asyncfunctionFc(e,I){letl=I.vault.getAbstractFileByPath(e.path);if(!l){x.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}
${I}`:""}`;function DN(e){if(e){let I=new KX.Notice(OX("starting",""),1e6);return{setMessage:(l,G)=>{I.setMessage(OX(l,G))},hide:()=>I.hide()}}return{setMessage:(I,l)=>{x.logMessage(`(${I})${l}`)},hide:()=>{}}}var UX={cl100k_base:yX,o200k_base:JX},xX=new Map;function Jy(e){let I=e in UX?e:"cl100k_base",l=xX.get(I);if(l)return l;let G=new xN(UX[I]);return xX.set(I,G),G}var TG=(e,I)=>{let l="cl100k_base";try{l=fi(I.name)}catch{l="cl100k_base"}return(l==="p50k_base"||l==="p50k_edit"||l==="r50k_base"||l==="gpt2")&&(l="cl100k_base"),Jy(l).encode(e).length};async function Ay(e,I,l){if(typeof e!="function")throw new TypeError("Callback must be a function.");if(!(I instanceof Promise))throw new TypeError("Promise must be an instance of Promise.");if(typeof l!="number"||l<=0)throw new TypeError("Interval must be a positive number.");let G=!1;for(I.finally(()=>{G=!0});!G;)e(),await sleep(l)}async function Ey(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,"Prompt template does not exist");let c=G.path,t=e.vault.getAbstractFileByPath(c);SG(t instanceof zX.TFile,`${c}isnotafile`);let b=await e.vault.cachedRead(t);return[G.basename,b]}async function BX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=DN(I.showAssistantMessages);try{let{apiKey:c,model:t,outputVariableName:b,promptTemplate:d,systemPrompt:Z,promptTemplateFolder:m}=I,a=Gt(e,m),[n,W]=await Ey(e,d,a);G.setMessage("waiting","QuickAdd is formatting the prompt template.");let N=await l(W),Y=["prompting",`Usingprompttemplate"${n}".`];G.setMessage(Y[0],Y[1]);let u=BN(e,c,t,Z,I.modelOptions)(N),o=(await Ti(u,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 MI("Input cancelled by user"):c}}async function Ti(e,I,l,G){let c=Date.now();return await Ay(()=>l(Date.now()-c),e,I),G(Date.now()-c),await e}async function DX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=DN(I.showAssistantMessages);try{let{apiKey:c,model:t,outputVariableName:b,systemPrompt:d,prompt:Z,modelOptions:m}=I;G.setMessage("waiting","QuickAdd is formatting the prompt template.");let a=await l(Z),n=["prompting","Using custom prompt."];G.setMessage(n[0],n[1]);let N=BN(e,c,t,d,m)(a),C=(await Ti(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,u=("> "+C).replace(/\n/g,`
>`),V={[b]:C,[`${b}-quoted`]:u};return setTimeout(()=>G.hide(),5e3),V}catch(c){throw G.setMessage("dead",c.message),setTimeout(()=>G.hide(),5e3),c}}var Si=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 MX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=DN(I.showAssistantMessages);try{let{apiKey:c,model:t,outputVariableName:b,systemPrompt:d,promptTemplate:Z,text:m,modelOptions:a}=I;G.setMessage("chunking","Creating prompt chunks with text and prompt template");let n=I.chunkSeparator||/\n/g,W=m.split(n),N=TG(d,t),Y=await l(Z,{chunk:" "}),C=TG(Y,t),u=kX(t.name)/2-N,V=I.shouldMerge??!0,o=[],R=u-C;if(V){let O=[],K="",J=0;for(let v of W){let H=TG(v,t)+1;if(H>R)throw new Error(`Thechunk"${v.slice(0,25)}..."istoolargetofitinasingleprompt.`);J+H<R?(K+=v,J+=H):(O.push(K),K=v,J=H)}K!==""&&O.push(K);for(let v of O){let H=await l(Z,{chunk:v});o.push(H)}}else for(let O of W){let K=TG(O,t);if(K>u)throw new Error(`Chunksize(${K})islargerthanthemaximumchunksize(${u}).Pleasecheckyourchunkseparator.`);let J=await l(Z,{chunk:O});o.push(J)}let s=BN(e,c,t,d,a),Q=["prompting",`${o.length}promptsbeingsent.`];G.setMessage(Q[0],Q[1]);let L=new Si(5,1e3*30),h=Promise.all(o.map(O=>L.add(()=>s(O)))),E=(await Ti(h,100,O=>{G.setMessage(Q[0],`${Q[1]}(${(O/1e3).toFixed(2)}s)`)},O=>{G.setMessage("finished",`Took${(O/1e3).toFixed(2)}s.`)})).map(O=>O.content).join(I.resultJoiner),T=("> "+E).replace(/\n/g,`
>`),k={[b]:E,[`${b}-quoted`]:T};return setTimeout(()=>G.hide(),5e3),k}catch(c){throw G.setMessage("dead",c.message),setTimeout(()=>G.hide(),5e3),c}}var ky="quickadd-ai";function Oy(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function Ky(e){let I=e.name?.trim()||"provider";return`${ky}-${Oy(I)}`}async function Jc(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){x.logWarning(`FailedtoreadSecretStorageentry"${l}":${G.message??G}`)}return I.apiKey??""}async function jX(e,I,l){let G=l?.trim();if(!G||!e?.secretStorage?.getSecret||!e.secretStorage?.setSecret)return null;let c=Ky(I),t=c,b=1;for(;;){let d=null;try{d=await Promise.resolve(e.secretStorage.getSecret(t))}catch(Z){x.logWarning(`FailedtoreadSecretStorageentry"${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 x.logWarning(`FailedtowriteSecretStorageentry"${t}":${d.message??d}`),null}}var kd=require("obsidian"),Nn=class e extends kd.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("no input given.")}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 kd.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 kd.ButtonComponent(l).setButtonText("Submit").setCta().onClick(c=>{this.resolved=!0,this.resolvePromise(this._selectedItems),this.close()})}};var MN=require("obsidian"),Yn=class e extends MN.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 MN.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 Od=require("obsidian");var dt=class e extends Od.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 Jd({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 Hd(l,this.inputComponent.inputEl,{sourcePath:this.linkSourcePath}),this.tagSuggester=new vd(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)=>{lets={...Z,...R};returnn(o,s,!1)});returnV?(d?.shouldAssignVariables&&Object.entries(V).forEach(([o,R])=>{G.variables.set(o,R)}),V):(qI(newError("AI Assistant returned null"),"Chunked AI Prompt error"),{})},getModels:()=>ec(),getMaxTokens:c=>{lett=Je(c);if(!t)thrownewError(`Model ${c} not found.`);returnt.maxTokens},countTokens(c,t){returnTG(c,t)}},utility:{getClipboard:async()=>awaitnavigator.clipboard.readText(),setClipboard:asyncc=>awaitnavigator.clipboard.writeText(c),getSelection:()=>{letc=I.workspace.getActiveViewOfType(yh.MarkdownView);returnc?c.editor.getSelection()??"":""},getSelectedText:()=>{letc=I.workspace.getActiveViewOfType(yh.MarkdownView);if(!c){qI(newError("No active view"),"Could not get selected text");return}if(!c.editor.somethingSelected()){qI(newError("No text selected"),"Could not get selected text");return}returnc.editor.getSelection()}},date:{now:(c,t)=>Lc({format:c,offset:t}),tomorrow:c=>Lc({format:c,offset:1}),yesterday:c=>Lc({format:c,offset:-1})},fieldSuggestions:{getFieldValues:async(c,t)=>{letb={folder:t?.folder,tags:t?.tags,inline:t?.includeInline??!1},d=I.vault.getMarkdownFiles();d=iY.filterFiles(d,b,m=>I.metadataCache.getFileCache(m));letZ=newSet;for(letmofd){letn=I.metadataCache.getFileCache(m)?.frontmatter?.[c];if(n!=null){if(Array.isArray(n))n.forEach(W=>{letN=W.toString().trim();N&&Z.add(N)});elseif(typeofn!="object"){letW=n.toString().trim();W&&Z.add(W)}}if(b.inline){letW=awaitI.vault.read(m);Pd.getFieldValues(W,c).forEach(Y=>Z.add(Y))}}returnArray.from(Z).sort()},clearCache:c=>{dc.getInstance().clear(c)}}}}staticasyncinputPrompt(I,l,G,c){try{returnawaitpl.Prompt(I,l,G,c)}catch(t){Wt(t);return}}staticasyncdatePrompt(I,l,G){try{letc=awaitYb.Prompt(I,l,G?.placeholder,G?.defaultValue,G?.dateFormat);if(c&&c.startsWith("@date:")){lett=c.slice(6);return(G?.dateFormat?bt(t,G.dateFormat):null)??t}returnc}catch(c){Wt(c);return}}staticasyncwideInputPrompt(I,l,G,c){try{returnawaitdt.Prompt(I,l,G,c)}catch(t){Wt(t);return}}staticasyncyesNoPrompt(I,l,G){try{returnawaitue.Prompt(I,l,G)}catch(c){Wt(c);return}}staticasyncinfoDialog(I,l,G){try{returnawaitYn.Show(I,l,G)}catch(c){Wt(c);return}}staticasyncsuggester(I,l,G,c,t=!1,b){try{letd;returntypeofl=="function"?d=G.map(l):d=l,d=d.map(Z=>LG(Z)),t?awaitZG.Suggest(I,d,G,{...c?{placeholder:c}:{},...b?.renderItem?{renderItem:b.renderItem}:{}}):awaitCG.Suggest(I,d,G,c,b?.renderItem)}catch(d){Wt(d);return}}staticasynccheckboxPrompt(I,l,G){try{returnawaitNn.Open(I,l,G)}catch(c){Wt(c);return}}};functionWt(e){if(einstanceofMI)throwe;if(il(e))thrownewMI("Input cancelled by user")}varIZ=classextendsQd{};varmG=[];for(lete=0;e<256;++e)mG.push((e+256).toString(16).slice(1));functionLR(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()}varJh,TJ=newUint8Array(16);functionAh(){if(!Jh){if(typeofcrypto>"u"||!crypto.getRandomValues)thrownewError("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Jh=crypto.getRandomValues.bind(crypto)}returnJh(TJ)}varqJ=typeofcrypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Eh={randomUUID:qJ};functionPJ(e,I,l){if(Eh.randomUUID&&!I&&!e)returnEh.randomUUID();e=e||{};letG=e.random??e.rng?.()??Ah();if(G.length<16)thrownewError("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)thrownewRangeError(`UUID byte range ${l}:${l+15} is out of buffer bounds`);for(letc=0;c<16;++c)I[l+c]=G[c];returnI}returnLR(G)}variG=PJ;varlG=class{constructor(I,l){this.name=I,this.type=l,this.id=iG()}};varFR=require("obsidian");varLl=classextendslG{constructor(I){super(I,"EditorCommand"),this.editorCommandType=I}staticgetSelectedText(I){returnthis.getActiveMarkdownView(I).editor.getSelection()}staticgetActiveMarkdownView(I){le
`)}var xR=require("obsidian");function dZ(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 _J=["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","contains","notContains"],HR=new Set(["true","1","yes","on"]),vR=new Set(["false","0","no","off"]);function Nt(e){return _J.includes(e)}function yR(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 JR(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 HR.has(l)?!0:vR.has(l)?!1:!!I}case"string":default:return I}}function Oh(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(HR.has(l))return!0;if(vR.has(l))return!1}return!!e;case"string":default:return e==null?"":String(e)}}function $J(e){if(!Nt(e.operator))return"";let I=e.expectedValue??"";return I.length===0?"(empty)":e.valueType==="string"?`"${I}"`:I}function IA(e){let I=e.variableName?`$${e.variableName}`:"(missing variable)",l=GA(e.operator),G=Nt(e.operator)?`${$J(e)}`:"";return`${I}${l}${G}`.trim()}function lA(e){let I=e.exportName?`::${e.exportName}`:"";return`script${e.scriptPath}${I}`}function ZZ(e){return e.mode==="variable"?IA(e):lA(e)}function GA(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 ER(e,I){return e.mode==="script"?await I.evaluateScriptCondition(e):eA(e,I.variables)}function eA(e,I){let l=e.variableName?.trim();if(!l)return x.logWarning("Conditional command skipped: No variable name configured."),!1;if(!(l in I))return x.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=JR(e);return c===void 0?(x.logWarning(`Conditionalcommand:Operator'${e.operator}'requiresacomparisonvalue.`),!1):e.operator==="contains"?AR(G,c,e):e.operator==="notContains"?!AR(G,c,e):cA(G,c,e)}return!1}function AR(e,I,l){return e==null?!1:typeof I=="string"&&I.length===0?(x.logWarning("Conditional command: 'contains' operator requires a non-empty comparison value."),!1):Array.isArray(e)?e.map(G=>Oh(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 cA(e,I,l){let G=Oh(e,l.valueType);switch(l.operator){case"equals":return G===I;case"notEquals":return G!==I;case"lessThan":return hY(G,I,(c,t)=>c<t);case"lessThanOrEqual":return hY(G,I,(c,t)=>c<=t);case"greaterThan":return hY(G,I,(c,t)=>c>t);case"greaterThanOrEqual":return hY(G,I,(c,t)=>c>=t);default:return!1}}function hY(e,I,l){let G=Number(e),c=Number(I);return Number.isNaN(G)||Number.isNaN(c)?(x.logWarning("Conditional command numeric comparison failed: non-numeric value encountered."),!1):l(G,c)}var kR=require("obsidian");function Yt(e,{logPrefix:I,noticePrefix:l=I,defaultReason:G}){if(!(e instanceof MI))return!1;let c=typeof e.message=="string"&&e.message.trim().length>0?e.message:G;return x.logMessage(`${I}:${c}`),(!(typeof e.message=="string"&&e.message.toLowerCase().includes("cancelled by user"))||P.getState().showInputCancellationNotification)&&new kR.Notice(`${l}:${c}`
${d}`;returnawaitthis.app.vault.modify(l,m),l}catch(t){if(Kh(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(!(cinstanceofaZ.TFile))thrownewError(`Template file not found at path "${G}".`);returnawaitthis.app.vault.cachedRead(c)}};varst=classextendsnZ{constructor(l,G,c,t){super(l,G,t);this.templatePath=c}asyncrun(){letl=awaitthis.getTemplateContent(this.templatePath);returnl||x.logError(`Template ${this.templatePath} not found.`),l=awaitthis.formatter.formatFileContent(l),l}getAndClearTemplatePropertyVars(){returnthis.formatter.getAndClearTemplatePropertyVars()}};varFG=classextends_e{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=en(l);returnsN(c)}getCurrentFileLink(){returnthis.app?hN(this.app.workspace.getActiveFile()):null}getCurrentFileName(){returnthis.app?pN(this.app.workspace.getActiveFile()):"current_filename"}suggestForValue(l,G=!1,c){returniN(l)}getMacroValue(l,G){returnuN(l)}promptForMathValue(){returnPromise.resolve("calculation_result")}promptForVariable(l,G){returnPromise.resolve(CN(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}};varQY=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=vc(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){if(!l)return;letc=Ri(l),t=Ri(this.getCurrentQuery());l.toLowerCase().endsWith(".md")&&t.toLowerCase().startsWith(`${c.toLowerCase()}.`)&&(t=c),this.renderMatch(G,c,t)}getCurrentQuery(){returnthis.inputEl.value}};functionRb(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="t
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function RA(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Kn(e,I){var l=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!l){if(Array.isArray(e)||(l=Ph(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(`Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var t=!0,b=!1,d;return{s:function(){l=l.call(e)},n:function(){var Z=l.next();return t=Z.done,Z},e:function(Z){b=!0,d=Z},f:function(){try{!t&&l.return!=null&&l.return()}finally{if(b)throw d}}}}var rA="finalize",LA="consider";function hZ(e,I,l){e.dispatchEvent(new CustomEvent(rA,{detail:{items:I,info:l}}))}function ht(e,I,l){e.dispatchEvent(new CustomEvent(LA,{detail:{items:I,info:l}}))}var kY="draggedEntered",Un="draggedLeft",OY="draggedOverIndex",_h="draggedLeftDocument",HY={LEFT_FOR_ANOTHER:"leftForAnother",OUTSIDE_OF_ANY:"outsideOfAny"};function FA(e,I,l){e.dispatchEvent(new CustomEvent(kY,{detail:{indexObj:I,draggedEl:l}}))}function wA(e,I,l){e.dispatchEvent(new CustomEvent(Un,{detail:{draggedEl:I,type:HY.LEFT_FOR_ANOTHER,theOtherDz:l}}))}function gA(e,I){e.dispatchEvent(new CustomEvent(Un,{detail:{draggedEl:I,type:HY.OUTSIDE_OF_ANY}}))}function HA(e,I,l){e.dispatchEvent(new CustomEvent(OY,{detail:{indexObj:I,draggedEl:l}}))}function vA(e){window.dispatchEvent(new CustomEvent(_h,{detail:{draggedEl:e}}))}var gG={DRAG_STARTED:"dragStarted",DRAGGED_ENTERED:kY,DRAGGED_ENTERED_ANOTHER:"dragEnteredAnother",DRAGGED_OVER_INDEX:OY,DRAGGED_LEFT:Un,DRAGGED_LEFT_ALL:"draggedLeftAll",DROPPED_INTO_ZONE:"droppedIntoZone",DROPPED_INTO_ANOTHER:"droppedIntoAnother",DROPPED_OUTSIDE_OF_ANY:"droppedOutsideOfAny",DRAG_STOPPED:"dragStopped"},oG={POINTER:"pointer",KEYBOARD:"keyboard"},KY="isDndShadowItem",UY="data-is-dnd-shadow-item-internal",yA="data-is-dnd-shadow-item-hint",wb="id:dnd-shadow-placeholder-0000",JA="dnd-action-dragged-el",bG="id",Dh=0;function mr(){Dh++}function ar(){if(Dh===0)throw new Error("Bug!tryingtodecrementwhentherearenodropzones");Dh--}var $h=typeof window>"u",HI=function(){};function Mh(e){var I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,l,G=I?OA(e):e.getBoundingClientRect(),c=getComputedStyle(e),t=c.transform;if(t){var b,d,Z,m;if(t.startsWith("matrix3d("))l=t.slice(9,-1).split(/, /),b=+l[0],d=+l[5],Z=+l[12],m=+l[13];else if(t.startsWith("matrix("))l=t.slice(7,-1).split(/, /),b=+l[0],d=+l[3],Z=+l[4],m=+l[5];else return G;var a=c.transformOrigin,n=G.x-Z-(1-b)*parseFloat(a),W=G.y-m-(1-d)*parseFloat(a.slice(a.indexOf("")+1)),N=b?G.width/b:e.offsetWidth,Y=d?G.height/d:e.offsetHeight;return{x:n,y:W,width:N,height:Y,top:W,right:n+N,bottom:W+Y,left:n}}else return G}function nr(e){var I=Mh(e);return{top:I.top+window.scrollY,bottom:I.bottom+window.scrollY,left:I.left+window.scrollX,right:I.right+window.scrollX}}function Wr(e){var I=e.getBoundingClientRect();return{top:I.top+window.scrollY,bottom:I.bottom+window.scrollY,left:I.left+window.scrollX,right:I.right+window.scrollX}}function Nr(e){return{x:(e.left+e.right)/2,y:(e.top+e.bottom)/2}}function AA(e,I){return Math.sqrt(Math.pow(e.x-I.x,2)+Math.pow(e.y-I.y,2))}function xY(e,I){return e.y<=I.bottom&&e.y>=I.top&&e.x>=I.left&&e.x<=I.right}function En(e){return Nr(Wr(e))}function _R(e,I){var l=En(e),G=nr(I);return xY(l,G)}function EA(e,I){var l=En(e),G=En(I);return AA(l,G)}function kA(e){var I=Wr(e);return I.right<0||I.left>document.documentElement.scrollWidth||I.bottom<0||I.top>document.documentElement.scrollHeight}function OA(e){for(var I=e.getBoundingClientRect(),l={top:I.top,bottom:I.bottom,left:I.left,right:I.right},G=e.parentElement;G&&G!==document.body;){var c=G.getBoundingClientRect(),t=window.getComputedStyle(G).overflowY,b=window.getComputedStyle(G).overflowX,d=t==="scroll"||t==="auto",Z=b==="scroll"||b==="auto";d&&(l.top=Math.max(l.top,c.top),l.bottom=Math.min(l.bottom,c.bottom)),Z&&(l.left=Math.max(l.left,c.left),l.right=Math.min(l.right,c.right)),G=G.parentElement}return l.top=Math.max(l.top,0),l.bottom=Math.min(l.bottom,window.innerHeight),l.left=Math.max(l.left,0),l.right=Math.min(l.right,window.innerWidth),{top:l.top,bottom:l.bottom,left:l.left,right:l.right,width:Math.max(0,l.right-l.left),height:Math.max(0,l.bottom-l.top)}}var uZ;function I0(){HI(function(){return"resettingindexescache"}),uZ=new Map}I0();function KA(e){var I=Array.from(e.children).f
`)}async function zr(e,I,l){if(e.type==="Multi")try{return await new bs(I,e).waitForClose}catch{return}let G=Zk(e,I,l);if(!G)throw new Error("Invalidchoicetype");return await G.waitForClose}function Br(e){return{...e,command:!e.command}}var Zs=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)}};function Dr(e,I,l){if(!I||!l)return e;let G=W0(e,I),c=W0(e,l);if(!G||!c||c.type!=="Multi"||G.type==="Multi"&&(G.id===c.id||mk(G).has(c.id)))return e;let{updated:t,removed:b}=Mr(e,I);return b?jr(t,l,b)??e:e}function W0(e,I){for(let l of e){if(l.id===I)return l;if(l.type==="Multi"){let G=W0(l.choices,I);if(G)return G}}}function mk(e){let I=new Set,l=G=>{I.add(G.id),G.type==="Multi"&&G.choices.forEach(l)};return(e.choices??[]).forEach(l),I}function Mr(e,I){let l;return{updated:e.map(c=>{if(c.id===I){l=c;return}if(c.type!=="Multi")return c;let t=Mr(c.choices,I);return t.removed&&(l=t.removed),t.removed?{...c,choices:t.updated}:c}).filter(Boolean),removed:l}}function jr(e,I,l){let G=!1,c=e.map(t=>{if(t.id===I&&t.type==="Multi"){G=!0;let d=t;return{...d,choices:[...d.choices,l]}}if(t.type!=="Multi")return t;let b=jr(t.choices,I,l);return b?(G=!0,{...t,choices:b}):t});return G?c:void 0}var uc=require("obsidian");var Ql=require("obsidian");var fr=require("obsidian");var ms=null,ak=24*60*60*1e3;async function Sr(){if(ms&&Date.now()-ms.fetchedAt<ak)return ms.data;if(P.getState().disableOnlineFeatures)throw new Error("Fetchingmodelsdirectoryisdisabled:Onlinefeaturesareturnedoff.");let I=await(await(0,fr.requestUrl)({url:"https://models.dev/api.json",method:"GET"})).json;return ms={data:I,fetchedAt:Date.now()},I}function s0(e){let I=e.toLowerCase();return I.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}function Tr(e){return e.map(I=>({name:I.id,maxTokens:Math.max(1,Math.floor(I.limit?.context??128e3))}))}function u0(e,I){let l=new Set(e.map(c=>c.name)),G=I.filter(c=>!l.has(c.name));return e.concat(G)}var _r=require("obsidian");var nk=128e3;async function as(e,I){let l=e.modelSource??"providerApi";if(l==="modelsDev")return qr(e);if(l==="providerApi")return Pr(e,I);try{return await Pr(e,I)}catch(G){if(!s0(e.endpoint))throw G;return qr(e,G)}}async function qr(e,I){try{let l=await Sr(),G=s0(e.endpoint);if(!G||!(G in l))throw new Error(`models.dev does not list a provider that matches ${e.endpoint}.`);let c=Object.values(l[G].models);return Tr(c)}catch(l){throw I?new Error(`Provider API failed (${I.message}). Fallback to models.dev also failed: ${l.message}`):l}}async function Pr(e,I){let{disableOnlineFeatures:l}=P.getState();if(l)throw new Error("Online features are disabled \u2014 enable them to browse provider models.");if(!e.endpoint)throw new Error("Provider is missing an endpoi
yd = yesterday`).setValue(cu(P.getState().dateAliases)).onChange(b=>{P.setState({dateAliases:Zp(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:Kb}),c&&c.setValue(cu(Kb))}),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()})})})}};varFZ=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}}};varqn=classextendsFZ{constructor(){super(...arguments);this.ErrorLog=[]}logError(l,G,c){lett=this.getQuickAddError(l,"ERROR",G,c);this.addMessageToErrorLog(t);letb=c||newError(l);console.error(this.formatOutputString(t),b)}logWarning(l,G,c){lett=this.getQuickAddError(l,"WARNING",G,c);this.addMessageToErrorLog(t);letb=c||newError(l);console.warn(this.formatOutputString(t),b)}logMessage(l,G,c){lett=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>Gi&&(this.ErrorLog=this.ErrorLog.slice(-Gi))}clearErrorLog(){this.ErrorLog=[]}};varv0=require("obsidian");varFs=classextendsFZ{constructor(l){super();this.plugin=l}logError(l,G,c){lett=this.getQuickAddError(l,"ERROR",G,c);newv0.Notice(this.formatOutputString(t),15e3)}logWarning(l,G,c){lett=this.getQuickAddError(l,"WARNING",G,c);newv0.Notice(this.formatOutputString(t))}logMessage(l,G,c){}};varws=class{constructor(I,l,G,c){this.app=I;this.plugin=l;this.choices=G;this.choiceExecutor=c}asyncrun(){letI=Ue(this.choices).filter(l=>l.type==="Macro"&&l.runOnStartup);for(letlofI)awaitnewZc(this.app,this.plugin,l,this.choiceExecutor,newMap).run()}};vary0=require("obsidian");vargs=classextendsnZ{constructor(I,l,G,c){super(I,l,c),this.choiceExecutor=c,this.choice=G}asyncrun(){try{SG(this.choice.templatePath,()=>`Invalid template path for ${this.choice.name}. ${this.choice.templatePath.length===0?"Template path is empty.":`Template path is not valid: ${this.choice.templatePath}`}`);letI=lt(this.choice.appendLink);this.setLinkToCurrentFileBehavior(I.enabled&&!I.requireActiveFile?"optional":"required");letl="";if(this.choice.folder.enabled)l=awaitthis.getFolderPath();else{letZ=this.app.fileManager.getNewFileParent(this.app.workspace.getActiveFile()?.path??"");l=Z===this.app.vault.getRoot()?"":Z.path}letG=this.choice.fileNameFormat.enabled?this.choice.fileNameFormat.format:gt,c=awaitthis.formatter.formatFileName(G,this.choice.name),t=this.normalizeTemplateFilePath(l,c,this.choice.templatePath);this.choice.fileExistsMode===yt&&(t=awaitthis.incrementFileName(t));letb,d=!1;if(awaitthis.app.vault.adapter.exists(t)){letZ=this.findExistingFile(t);if(!(Zinstanceofy0.TFile)||Z.extension!=="md"&&Z.extension!=="canvas"){x.logError(`'${t}' already exists but could not be resolved as a markdown or canvas file.`);return}letm=this.choice.fileExistsMode;if(!this.choice.setFileExistsBehavior)try{m=awaitCG.Suggest(this.app,[...Wu],[...Wu])}catch(a){throw
`)?Math.max(l.length-1,0):l.length,m=G;for(let a=G+1;a<Z;a++){if(l[a].trim().length===0){m=a;continue}break}return m}async insertAfterHandler(l){let G=await this.formatLocationString(this.choice.insertAfter.after);if(this.choice.insertAfter?.inline)return await this.insertAfterInlineHandler(l,G);let c=kh(this.fileContent),t=this.findInsertAfterIndex(c,G);if(t===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInsertAfterIfNotFound(l);qI(new Error("Unable to find insert after line in file"),"Insert After Error")}if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");t=As(c,t,!!this.choice.insertAfter.considerSubsections)??c.length-1}else{let d=this.choice.insertAfter?.blankLineAfterMatchMode??"auto";t=this.findInsertAfterPositionWithBlankLines(c,t,this.fileContent,d)}return this.insertTextAfterPositionInBody(l,this.fileContent,t)}hasInlineTargetLinebreak(l){return l.includes(`
`,l);return G===-1?this.fileContent.length:G>0&&this.fileContent[G-1]==="\r"?G-1:G}async insertAfterInlineHandler(l,G){if(this.hasInlineTargetLinebreak(G))return qI(new Error("Inline insert after target must be a single line."),"Insert After Inline Error"),this.fileContent;let c=this.fileContent.indexOf(G);if(c===-1)return this.choice.insertAfter?.createIfNotFound?await this.createInlineInsertAfterIfNotFound(l,G):(qI(new Error("Unable to find insert after text in file."),"Insert After Inline Error"),this.fileContent);let t=c+G.length;if(this.choice.insertAfter?.replaceExisting){let b=this.getInlineEndOfLine(t);return this.fileContent.slice(0,t)+l+this.fileContent.slice(b)}return this.fileContent.slice(0,t)+l+this.fileContent.slice(t)}async createInsertAfterIfNotFound(l){let c=`${this.replaceLinebreakInString(awaitthis.formatLocationString(this.choice.insertAfter.after))}
${c}`;if(this.choice.insertAfter?.createIfNotFoundLocation===OZ)try{let t=this.app.workspace.getActiveViewOfType(U0.MarkdownView);if(!t)throw new Error("No active view.");let d=t.editor.getCursor().line;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let m=kh(this.fileContent);d=As(m,d,!!this.choice.insertAfter.considerSubsections)??m.length-1}return this.insertTextAfterPositionInBody(c,this.fileContent,d)}catch(t){qI(t,`Unabletoinsertline'${this.choice.insertAfter.after}'atcursorposition`)}}async createInlineInsertAfterIfNotFound(l,G){let c=`${G}${l}`;if(this.choice.insertAfter?.createIfNotFoundLocation===Ub){let t=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):-1;return this.insertTextAfterPositionInBody(c,this.fileContent,t)}if(this.choice.insertAfter?.createIfNotFoundLocation===kZ)return`${this.fileContent}
${c}`;if(this.choice.insertAfter?.createIfNotFoundLocation===OZ)try{let t=this.app.workspace.getActiveViewOfType(U0.MarkdownView);if(!t)throw new Error("No active view.");let d=t.editor.getCursor().line;return this.insertTextAfterPositionInBody(c,this.fileContent,d)}catch(t){qI(t,`Unabletoinsertline'${this.choice.insertAfter.after}'atcursorposition`)}return x.logWarning(`UnknowncreateIfNotFoundLocation:${this.choice.insertAfter?.createIfNotFoundLocation}`),this.fileContent}getFrontmatterEndPosition(l,G){let c=this.app.metadataCache.getFileCache(l);if(c?.frontmatterPosition)return c.frontmatterPosition.end.line;if(G){let t=this.inferFrontmatterEndLineFromContent(G);if(t!==null)return t}return x.logMessage("could not get frontmatter. Maybe there isn't any."),-1}inferFrontmatterEndLineFromContent(l){let G=ZN(l);if(!G)return null;let c=l.slice(0,G[1]),t=c.split(/\r?\n/);return t.length===0?null:c.endsWith(`
QuickAdd will now revert to backup.`),e.settings=G}}e.saveSettings()}vargF=G3;varHZ=require("obsidian");asyncfunctione3(e,I,l){letG=awaitfetch(`https://api.github.com/repos/${e}/${I}/releases`),c=awaitG.json();if(!G.ok&&"message"inc||!Array.isArray(c))thrownewError(`Failed to fetch releases: ${c.message??"Unknown error"}`);lett=c.findIndex(b=>b.tag_name===l);if(t===-1)thrownewError(`Could not find release with tag ${l}`);returnc.slice(0,t).filter(b=>!b.draft&&!b.prerelease)}functionc3(e,I=1){letl=e.split(`
`)}varfs=classextendsHZ.Modal{constructor(I,l){super(I),this.previousVersion=l,this.releaseNotesPromise=e3("chhoumann","quickadd",l),this.releaseNotesPromise.then(G=>{if(this.releases=G,this.releases.length===0){this.close();return}this.display()}).catch(G=>{x.logError(`Failed to fetch release notes: ${G}`)})}onOpen(){let{contentEl:I}=this;I.empty(),I.createEl("h1",{text:"Fetching release notes..."})}onClose(){let{contentEl:I}=this;I.empty()}display(){let{contentEl:I}=this;I.empty(),I.classList.add("quickadd-update-modal-container");letl=`### New in QuickAdd v${this.releases[0].tag_name}
`,G="Thank you for using QuickAdd! If you like the plugin, please consider supporting me by buying me a coffee. With your sponsorship, I'll be able to contribute more to my existing projects, start new ones, and be more responsive to issues & feature requests.",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(`
I'd love to get your feedback on QuickAdd! Please fill out this <a href="https://forms.gle/WRq1ewcKK8qmkqps6">feedback form</a> to let me know what you think.
${c3(b)}`;HZ.MarkdownRenderer.renderMarkdown(m,t,this.app.vault.getRoot().path,newHZ.Component)}};varzl=require("obsidian");varSs=classextendszl.Modal{constructor(l,G){super(l);this.showAdvancedSettings=!1;this.settings=G,this.waitForClose=newPromise((c,t)=>{this.rejectPromise=t,this.resolvePromise=c}),this.open(),this.display()}getsystemPromptTokenLength(){letl=Je(this.settings.model);returnl?TG(this.settings.systemPrompt,l):Number.POSITIVE_INFINITY}display(){this.contentEl.empty();letl=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{letG=awaitpl.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){newzl.Setting(l).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(G=>{letc=ec();for(lettofc)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){newzl.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){newzl.Setting(l).setName("System Prompt").setDesc("The system prompt for the AI Assistant");letG=this.contentEl.createEl("div"),c=G.createEl("span");c.style.color="var(--text-muted-color)";lett=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);letb=newzl.TextAreaComponent(l);b.setValue(this.settings.systemPrompt).onChange(asynca=>{this.settings.systemPrompt=a,Z.innerText=awaitd.format(a),m()}),neweG(this.app,b.inputEl,PI.instance);letd=newFG(this.app,PI.instance);b.inputEl.style.width="100%",b.inputEl.style.height="100px",b.inputEl.style.minHeight="100px",b.inputEl.style.marginBottom="1em";letZ=this.contentEl.createEl("span"),m=(0,zl.debounce)(()=>{c.innerText=`Token count: ${this.systemPromptTokenLength}`},50);m(),(async()=>Z.innerText=awaitd.format(this.settings.systemPrompt??""))()}addShowAdvancedSettingsToggle(l){newzl.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){newzl.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){newzl.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,