vareV=Object.create;varIc=Object.defineProperty;vartV=Object.getOwnPropertyDescriptor;varwV=Object.getOwnPropertyNames;varuV=Object.getPrototypeOf,yV=Object.prototype.hasOwnProperty;varoV=(c,G,I)=>Ginc?Ic(c,G,{enumerable:!0,configurable:!0,writable:!0,value:I}):c[G]=I;varAV=(c,G)=>()=>(G||c((G={exports:{}}).exports,G),G.exports),zV=(c,G)=>{for(varIinG)Ic(c,I,{get:G[I],enumerable:!0})},AW=(c,G,I,l)=>{if(G&&typeofG=="object"||typeofG=="function")for(letbofwV(G))!yV.call(c,b)&&b!==I&&Ic(c,b,{get:()=>G[b],enumerable:!(l=tV(G,b))||l.enumerable});returnc};varzW=(c,G,I)=>(I=c!=null?eV(uV(c)):{},AW(G||!c||!c.__esModule?Ic(I,"default",{value:c,enumerable:!0}):I,c)),gV=c=>AW(Ic({},"__esModule",{value:!0}),c);varG2=(c,G,I)=>(oV(c,typeofG!="symbol"?G+"":G,I),I);varv0=AV(T1=>{"use strict";T1.byteLength=nN;T1.toByteArray=EN;T1.fromByteArray=vN;varUl=[],pl=[],pN=typeofUint8Array<"u"?Uint8Array:Array,PZ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(K2=0,Q0=PZ.length;K2<Q0;++K2)Ul[K2]=PZ[K2],pl[PZ.charCodeAt(K2)]=K2;varK2,Q0;pl["-".charCodeAt(0)]=62;pl["_".charCodeAt(0)]=63;functionJ0(c){varG=c.length;if(G%4>0)thrownewError("Invalid string. Length must be a multiple of 4");varI=c.indexOf("=");I===-1&&(I=G);varl=I===G?0:4-I%4;return[I,l]}functionnN(c){varG=J0(c),I=G[0],l=G[1];return(I+l)*3/4-l}functionsN(c,G,I){return(G+I)*3/4-I}functionEN(c){varG,I=J0(c),l=I[0],b=I[1],Z=newpN(sN(c,l,b)),W=0,d=b>0?l-4:l,V;for(V=0;V<d;V+=4)G=pl[c.charCodeAt(V)]<<18|pl[c.charCodeAt(V+1)]<<12|pl[c.charCodeAt(V+2)]<<6|pl[c.charCodeAt(V+3)],Z[W++]=G>>16&255,Z[W++]=G>>8&255,Z[W++]=G&255;returnb===2&&(G=pl[c.charCodeAt(V)]<<2|pl[c.charCodeAt(V+1)]>>4,Z[W++]=G&255),b===1&&(G=pl[c.charCodeAt(V)]<<10|pl[c.charCodeAt(V+1)]<<4|pl[c.charCodeAt(V+2)]>>2,Z[W++]=G>>8&255,Z[W++]=G&255),Z}functionQN(c){returnUl[c>>18&63]+Ul[c>>12&63]+Ul[c>>6&63]+Ul[c&63]}functionJN(c,G,I){for(varl,b=[],Z=G;Z<I;Z+=3)l=(c[Z]<<16&16711680)+(c[Z+1]<<8&65280)+(c[Z+2]&255),b.push(QN(l));returnb.join("")}functionvN(c){for(varG,I=c.length,l=I%3,b=[],Z=16383,W=0,d=I-l;W<d;W+=Z)b.push(JN(c,W,W+Z>d?d:W+Z));returnl===1?(G=c[I-1],b.push(Ul[G>>2]+Ul[G<<4&63]+"==")):l===2&&(G=(c[I-2]<<8)+c[I-1],b.push(Ul[G>>10]+Ul[G>>4&63]+Ul[G<<2&63]+"=")),b.join("")}});varx5={};zV(x5,{default:()=>GI});module.exports=gV(x5);varpV=require("obsidian");varAl=require("obsidian");functionDI(){}functionEl(c,G){for(letIinG)c[I]=G[I];returnc}functionzb(c){returnc()}functiongW(){returnObject.create(null)}functionWI(c){c.forEach(zb)}functionVI(c){returntypeofc=="function"}function_(c,G){returnc!=c?G==G:c!==G||c&&typeofc=="object"||typeofc=="function"}functioniW(c){returnObject.keys(c).length===0}functionUc(c,G,I,l){if(c){letb=rW(c,G,I,l);returnc[0](b)}}functionrW(c,G,I,l){returnc[1]&&l?El(I.ctx.slice(),c[1](l(G))):I.ctx}functionMc(c,G,I,l){if(c[2]&&l){letb=c[2](l(I));if(G.dirty===void0)returnb;if(typeofb=="object"){letZ=[],W=Math.max(G.dirty.length,b.length);for(letd=0;d<W;d+=1)Z[d]=G.dirty[d]|b[d];returnZ}returnG.dirty|b}returnG.dirty}functionBc(c,G,I,l,b,Z){if(b){letW=rW(G,I,l,Z);c.p(W,b)}}functionLc(c){if(c.ctx.length>32){letG=[],I=c.ctx.length/32;for(letl=0;l<I;l++)G[l]=-1;returnG}return-1}functionjc(c){letG={};for(letIinc)I[0]!=="$"&&(G[I]=c[I]);returnG}functionZG(c,G){letI={};G=newSet(G);for(letlinc)!G.has(l)&&l[0]!=="$"&&(I[l]=c[l]);returnI}functionfc(c){returnc&&VI(c.destroy)?c.destroy:DI}varkW=typeofwindow<"u"?window:typeofglobalThis<"u"?globalThis:global,Gc=class{constructor(G){this.options=G,this._listeners="WeakMap"inkW?newWeakMap:void0}observe(G,I){returnthis._listeners.set(G,I),this._getObserver().observe(G,this.options),()=>{this._listeners.delete(G),this._observer.unobserve(G)}}_getObserver(){varG;return(G=this._observer)!==null&&G!==void0?G:this._observer=newResizeObserver(I=>{varl;for(letbofI)Gc.entries.set(b.target,b),(l=this._listeners.get(b.target))===null||l===void0||l(b)})}};Gc.entries="WeakMap"inkW?newWeakMap:void0;varxW=!1;functioniV(){xW=!0}functionrV(){x
${G}`:""}`;functionS1(c){if(c){letG=newo0.Notice(y0("starting",""),1e6);return{setMessage:(I,l)=>{G.setMessage(y0(I,l))},hide:()=>G.hide()}}return{setMessage:(G,I)=>{u.logMessage(`(${G}) ${I}`)},hide:()=>{}}}vardl=(c,G)=>{letI=G.name==="gpt-3.5-turbo-16k"?"gpt-3.5-turbo":G.name;I=I==="gpt-4-1106-preview"?"gpt-4":I,I=I==="gpt-3.5-turbo-1106"?"gpt-3.5-turbo":I;try{returnt0(I).encode(c).length}catch{return_Z("cl100k_base").encode(c).length}};asyncfunctionBN(c,G,I){if(typeofc!="function")thrownewTypeError("Callback must be a function.");if(!(GinstanceofPromise))thrownewTypeError("Promise must be an instance of Promise.");if(typeofI!="number"||I<=0)thrownewTypeError("Interval must be a positive number.");letl=!1;for(G.finally(()=>{l=!0});!l;)c(),awaitsleep(I)}asyncfunctionLN(c,G){letI;if(c.enable)I=G.find(W=>W.path.endsWith(c.name));else{letW=G.map(d=>d.basename);I=awaitAI.Suggest(app,W,G)}Wl(I,"Prompt template does not exist");letl=I.path,b=app.vault.getAbstractFileByPath(l);Wl(binstanceofA0.TFile,`${l} is not a file`);letZ=awaitapp.vault.cachedRead(b);return[I.basename,Z]}asyncfunctionz0(c,G){if(i.getState().disableOnlineFeatures)thrownewError("Blocking request to OpenAI: Online features are disabled in settings.");letI=S1(c.showAssistantMessages);try{let{apiKey:l,model:b,outputVariableName:Z,promptTemplate:W,systemPrompt:d,promptTemplateFolder:V}=c,a=AG(V),[m,N]=awaitLN(W,a);I.setMessage("waiting","QuickAdd is formatting the prompt template.");letF=awaitG(N),h=["prompting",`Using prompt template "${m}".`];I.setMessage(h[0],h[1]);letX=C1(l,b,d,c.modelOptions)(F),R=(awaitlW(X,100,Y=>{I.setMessage(h[0],`${h[1]} (${(Y/1e3).toFixed(2)}s)`)},Y=>{I.setMessage("finished",`Took ${(Y/1e3).toFixed(2)}s.`)})).content,J=("> "+R).replace(/\n/g,`
>`),t={[Z]:R,[`${Z}-quoted`]:J};return setTimeout(()=>I.hide(),5e3),t}catch(l){I.setMessage("dead",l.message),setTimeout(()=>I.hide(),5e3)}}async function lW(c,G,I,l){let b=Date.now();return await BN(()=>I(Date.now()-b),c,G),l(Date.now()-b),await c}async function g0(c,G){if(i.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let I=S1(c.showAssistantMessages);try{let{apiKey:l,model:b,outputVariableName:Z,systemPrompt:W,prompt:d,modelOptions:V}=c;I.setMessage("waiting","QuickAdd is formatting the prompt template.");let a=await G(d),m=["prompting","Using custom prompt."];I.setMessage(m[0],m[1]);let F=C1(l,b,W,V)(a),H=(await lW(F,100,R=>{I.setMessage(m[0],`${m[1]}(${(R/1e3).toFixed(2)}s)`)},R=>{I.setMessage("finished",`Took${(R/1e3).toFixed(2)}s.`)})).content,X=("> "+H).replace(/\n/g,`
>`),n={[Z]:H,[`${Z}-quoted`]:X};return setTimeout(()=>I.hide(),5e3),n}catch(l){I.setMessage("dead",l.message),setTimeout(()=>I.hide(),5e3)}}var IW=class{constructor(G,I){this.maxRequests=G;this.intervalMs=I;this.queue=[];this.pendingPromises=[]}add(G){return new Promise((I,l)=>{this.queue.push(async()=>{try{I(await G())}catch(b){l(b)}}),this.schedule()})}schedule(){if(this.queue.length===0||this.pendingPromises.length>=this.maxRequests)return;let G=this.queue.shift();if(!G)return;let I=G();this.pendingPromises.push(I),I.finally(()=>{this.pendingPromises=this.pendingPromises.filter(l=>l!==I),this.schedule()}),setTimeout(()=>this.schedule(),this.intervalMs)}};async function i0(c,G){if(i.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let I=S1(c.showAssistantMessages);try{let{apiKey:l,model:b,outputVariableName:Z,systemPrompt:W,promptTemplate:d,text:V,modelOptions:a}=c;I.setMessage("chunking","Creating prompt chunks with text and prompt template");let m=c.chunkSeparator||/\n/g,N=V.split(m),F=dl(W,b),h=await G(d,{chunk:" "}),H=dl(h,b),X=u0(b.name)/2-F,n=c.shouldMerge??!0,R=[],J=X-H;if(n){let Q=[],II="",cI=0;for(let hI of N){let ZI=dl(hI,b)+1;if(ZI>J)throw new Error(`Thechunk"${hI.slice(0,25)}..."istoolargetofitinasingleprompt.`);cI+ZI<J?(II+=hI,cI+=ZI):(Q.push(II),II=hI,cI=ZI)}II!==""&&Q.push(II);for(let hI of Q){let ZI=await G(d,{chunk:hI});R.push(ZI)}}else for(let Q of N){let II=dl(Q,b);if(II>X)throw new Error(`Chunksize(${II})islargerthanthemaximumchunksize(${X}).Pleasecheckyourchunkseparator.`);let cI=await G(d,{chunk:Q});R.push(cI)}let t=C1(l,b,W,a),Y=["prompting",`${R.length}promptsbeingsent.`];I.setMessage(Y[0],Y[1]);let p=new IW(5,1e3*30),E=Promise.all(R.map(Q=>p.add(()=>t(Q)))),v=(await lW(E,100,Q=>{I.setMessage(Y[0],`${Y[1]}(${(Q/1e3).toFixed(2)}s)`)},Q=>{I.setMessage("finished",`Took${(Q/1e3).toFixed(2)}s.`)})).map(Q=>Q.content).join(c.resultJoiner),x=("> "+v).replace(/\n/g,`
>`),P={[Z]:v,[`${Z}-quoted`]:x};return setTimeout(()=>I.hide(),5e3),P}catch(l){I.setMessage("dead",l.message),setTimeout(()=>I.hide(),5e3)}}var xG=class{static GetApi(G,I,l){return{inputPrompt:(b,Z,W)=>this.inputPrompt(G,b,Z,W),wideInputPrompt:(b,Z,W)=>this.wideInputPrompt(G,b,Z,W),yesNoPrompt:(b,Z)=>this.yesNoPrompt(G,b,Z),infoDialog:(b,Z)=>this.infoDialog(G,b,Z),suggester:(b,Z)=>this.suggester(G,b,Z),checkboxPrompt:(b,Z)=>this.checkboxPrompt(G,b,Z),executeChoice:async(b,Z)=>{let W=I.getChoiceByName(b);W||u.logError(`choicenamed'${b}'notfound`),Z&&Object.keys(Z).forEach(d=>{l.variables.set(d,Z[d])}),await l.execute(W),l.variables.clear()},format:async(b,Z,W=!0)=>{Z&&Object.keys(Z).forEach(V=>{l.variables.set(V,Z[V])});let d=await new Bl(G,I,l).formatFileContent(b);return W&&l.variables.clear(),d},ai:{prompt:async(b,Z,W)=>{let d=i.getState(),V=d.ai;if(d.disableOnlineFeatures)throw new Error("Rejecting request to `prompt` via API AI module. Online features are disabled in settings.");let a=this.GetApi(G,I,l).format,m;if(typeof Z=="string"){let h=yl(Z);if(!h)throw new Error(`Model'${Z}'notfound.`);m=h}else m=Z;let N=P2(m.name);if(!N)throw new Error(`Model'${m.name}'notfoundinanyprovider`);let F=await g0({model:m,prompt:b,apiKey:N.apiKey,modelOptions:W?.modelOptions??{},outputVariableName:W?.variableName??"output",showAssistantMessages:W?.showAssistantMessages??!0,systemPrompt:W?.systemPrompt??V.defaultSystemPrompt},(h,H)=>a(h,H,!1));return F?(W?.shouldAssignVariables&&Object.assign(l.variables,F),F):(u.logError("AI Assistant returned null"),{})},chunkedPrompt:async(b,Z,W,d,V)=>{let a=i.getState(),m=a.ai;if(a.disableOnlineFeatures)throw new Error("Rejecting request to `prompt` via API AI module. Online features are disabled in settings.");let N=this.GetApi(G,I,l).format,F;if(typeof W=="string"){let X=yl(W);if(!X)throw new Error(`Model${W}notfound.`);F=X}else F=W;let h=P2(F.name);if(!h)throw new Error(`Model'${F.name}'notfoundinanyprovider`);let H=await i0({model:F,text:b,promptTemplate:Z,chunkSeparator:d?.chunkSeparator??/\n/,apiKey:h.apiKey,modelOptions:d?.modelOptions??{},outputVariableName:d?.variableName??"output",showAssistantMessages:d?.showAssistantMessages??!0,systemPrompt:d?.systemPrompt??m.defaultSystemPrompt,resultJoiner:d?.chunkJoiner??`
`,shouldMerge:d?.shouldMerge??!0},(X,n)=>{let R={...V,...n};return N(X,R,!1)});return H?(d?.shouldAssignVariables&&Object.assign(l.variables,H),H):(u.logError("AI Assistant returned null"),{})},getModels:()=>Ml(),getMaxTokens:b=>{let Z=yl(b);if(!Z)throw new Error(`Model${b}notfound.`);return Z.maxTokens},countTokens(b,Z){return dl(b,Z)}},utility:{getClipboard:async()=>await navigator.clipboard.readText(),setClipboard:async b=>await navigator.clipboard.writeText(b),getSelectedText:()=>{let b=G.workspace.getActiveViewOfType(r0.MarkdownView);if(!b){u.logError("no active view - could not get selected text.");return}if(!b.editor.somethingSelected()){u.logError("no text selected.");return}return b.editor.getSelection()}},date:{now:(b,Z)=>ql({format:b,offset:Z}),tomorrow:b=>ql({format:b,offset:1}),yesterday:b=>ql({format:b,offset:-1})}}}static async inputPrompt(G,I,l,b){try{return await dI.Prompt(G,I,l,b)}catch{return}}static async wideInputPrompt(G,I,l,b){try{return await _l.Prompt(G,I,l,b)}catch{return}}static async yesNoPrompt(G,I,l){try{return await OI.Prompt(G,I,l)}catch{return}}static async infoDialog(G,I,l){try{return await S2.Show(G,I,l)}catch{return}}static async suggester(G,I,l){try{let b;return typeof I=="function"?b=l.map(I):b=I,await AI.Suggest(G,b,l)}catch{return}}static async checkboxPrompt(G,I,l){try{return await D2.Open(G,I,l)}catch{return}}};var UG=class extends iG{};var jI=class{constructor(G,I){this.name=G,this.type=I,this.id=Sl()}};var k0=require("obsidian");var zI=class extends jI{constructor(I){super(I,"EditorCommand");this.editorCommandType=I}static getSelectedText(I){return this.getActiveMarkdownView(I).editor.getSelection()}static getActiveMarkdownView(I){let l=I.workspace.getActiveViewOfType(k0.MarkdownView);if(!l)throw u.logError("no active markdown view."),new Error("no active markdown view.");return l}};var MG=class extends zI{constructor(){super("Cut")}static async run(G){let I=zI.getSelectedText(G),l=zI.getActiveMarkdownView(G);if(!I){u.logError("nothing selected.");return}await navigator.clipboard.writeText(I),l.editor.replaceSelection("")}};var LG=class extends zI{constructor(){super("Copy")}static async run(G){let I=zI.getSelectedText(G);await navigator.clipboard.writeText(I)}};var jG=class extends zI{constructor(){super("Paste")}static async run(G){let I=await navigator.clipboard.readText(),l=zI.getActiveMarkdownView(G);if(!l){u.logError("no active markdown view.");return}l.editor.replaceSelection(I)}};var fG=class extends zI{constructor(){super("Select active line")}static run(G){let I=zI.getActiveMarkdownView(G),{line:l}=I.editor.getCursor(),Z=I.editor.getLine(l).length;I.editor.setSelection({line:l,ch:0},{line:l,ch:Z})}};var TG=class extends zI{constructor(){super("Select link on active line")}static run(G){let I=zI.getActiveMarkdownView(G),{line:l}=I.editor.getCursor(),b=I.editor.getLine(l),Z=qd.exec(b);if(!Z){u.logError(`nointernallinkfoundonline${l}.`);return}let W=Z.index,d=Z[0].length+W;I.editor.setSelection({line:l,ch:W},{line:l,ch:d})}};function x0(c){return new Promise(G=>setTimeout(G,c))}function GW(c){return c.split(`
${W}`;return await this.app.vault.modify(I,V),await yG(this.app,I,!0),I}catch(Z){return u.logError(Z),null}}async getTemplateContent(I){let l=I;t1.test(I)||(l+=".md");let b=this.app.vault.getAbstractFileByPath(l);if(!(b instanceof f0.TFile))throw new Error(`Templatefilenotfoundatpath"${l}".`);return await this.app.vault.cachedRead(b)}};var Y2=class extends DG{constructor(I,l,b,Z){super(I,l,Z);this.templatePath=b}async run(){let I=await this.getTemplateContent(this.templatePath);return I||u.logError(`Template${this.templatePath}notfound.`),I=await this.formatter.formatFileContent(I),I}};var Vl=class extends F2{constructor(I,l){super();this.app=I;this.plugin=l}async format(I){let l=I;return l=this.replaceDateInString(l),l=this.replaceTimeInString(l),l=await this.replaceValueInString(l),l=await this.replaceDateVariableInString(l),l=await this.replaceVariableInString(l),l=await this.replaceLinkToCurrentFileInString(l),l=await this.replaceMacrosInString(l),l=await this.replaceTemplateInString(l),l=await this.replaceFieldVarInString(l),l=this.replaceLinebreakInString(l),l}promptForValue(I){return"_value_"}getVariableValue(I){return I}getCurrentFileLink(){return this.app.workspace.getActiveFile()?.path??"_noPageOpen_"}getNaturalLanguageDates(){return oG(this.app)}suggestForValue(I){return"_suggest_"}getMacroValue(I){return`_macro:${I}_`}promptForMathValue(){return Promise.resolve("_math_")}promptForVariable(I){return Promise.resolve(`${I}_`)}async getTemplateContent(I){try{return await new Y2(this.app,this.plugin,I,void 0).run()}catch{return`Template(notfound):${I}`}}async getSelectedText(){return"_selected_"}async suggestForField(I){return Promise.resolve(`_field:${I}_`)}};var KG=class extends N2{constructor(I,l,b){super(I);this.plugin=b;this.choice=l,this.display()}display(){this.containerEl.addClass("captureChoiceBuilder"),this.contentEl.empty(),this.addCenteredChoiceNameHeader(this.choice),this.addCapturedToSetting(),this.choice?.captureToActiveFile||(this.addCreateIfNotExistsSetting(),this.choice?.createFileIfItDoesntExist?.enabled&&this.addCreateWithTemplateSetting()),this.addTaskSetting(),this.addPrependSetting(),this.addAppendLinkSetting(),this.addInsertAfterSetting(),this.choice.captureToActiveFile||(this.addOpenFileSetting(),this.choice.openFile&&this.addOpenFileInNewTabSetting()),this.addFormatSetting()}addCapturedToSetting(){let I;new aI.Setting(this.contentEl).setName("Capture To").setDesc("File to capture to. Supports some format syntax.");let l=this.contentEl.createDiv("captureToContainer"),b=l.createDiv("captureToActiveFileContainer"),Z=b.createEl("span");Z.textContent="Capture to active file";let W=new aI.ToggleComponent(b);if(W.setValue(this.choice?.captureToActiveFile),W.onChange(d=>{this.choice.captureToActiveFile=d,this.reload()}),!this.choice?.captureToActiveFile){let d=l.createDiv("captureToFileContainer"),V=d.createEl("span"),a=new zG(this.app);(async()=>V.textContent=await a.format(this.choice.captureTo))();let m=new aI.TextComponent(d);m.setPlaceholder("File name format"),I=m,m.inputEl.style.width="100%",m.inputEl.style.marginBottom="8px",m.setValue(this.choice.captureTo).setDisabled(this.choice?.captureToActiveFile).onChange(async F=>{this.choice.captureTo=F,V.textContent=await a.format(F)});let N=[...this.app.vault.getMarkdownFiles().map(F=>F.path),...rd];new MI(this.app,I.inputEl,N,50)}}addPrependSetting(){new aI.Setting(this.contentEl).setName("Write to bottom of file").setDesc(`Putvalueatthebottomofthefile-otherwiseatthe${this.choice?.captureToActiveFile?"active cursor location":"top"}.`).addToggle(l=>{l.setValue(this.choice.prepend),l.onChange(b=>{this.choice.prepend=b,this.choice.prepend&&this.choice.insertAfter.enabled&&(this.choice.insertAfter.enabled=!1,this.reload())})})}addTaskSetting(){new aI.Setting(this.contentEl).setName("Task").setDesc("Formats the value as a task.").addToggle(l=>{l.setValue(this.choice.task),l.onChange(b=>this.choice.task=b)})}addAppendLinkSetting(){new aI.Setting(this.contentEl).setName("Append link").setDesc("Add a link on your current cur
${s?"Deleting this choice will delete all ("+p.choices.length+") choices inside it!":""}
${E?"Deleting this choice will delete the macro associated with it!":""}
`)&&(E&&(I(9,b=b.filter(v=>v.id!==p.macroId)),W(b)),I(0,l=l.filter(v=>$0(p.id,v))),V.removeCommandForChoice(p),Z(l))}async function N(Y){let{choice:p}=Y.detail,E;if(p.type==="Multi"){E=p;let s=await dI.Prompt(d,`Rename${p.name}`,"",p.name);if(!s)return;E.name=s}else{let s=X(p);if(!s)throw new Error("Invalid choice type");E=await s.waitForClose}E&&(I(0,l=l.map(s=>aW(s,E))),V.removeCommandForChoice(p),V.addCommandForChoice(E),Z(l))}async function F(Y){let{choice:p}=Y.detail,E={...p,command:!p.command};E.command?V.addCommandForChoice(E):V.removeCommandForChoice(E),I(0,l=l.map(s=>aW(s,E))),Z(l)}async function h(Y){let{choice:p}=Y.detail,E=H(p);I(0,l=[...l,E]),Z(l)}function H(Y){if(!H0(Y))throw new Error("Invalid choice type");let p;switch(Y.type){case"Template":p=new o2(`${Y.name}(copy)`);break;case"Capture":p=new A2(`${Y.name}(copy)`);break;case"Macro":p=new Hc(`${Y.name}(copy)`);break;case"Multi":p=new z2(`${Y.name}(copy)`);break}return Y.type!=="Multi"?Object.assign(p,Y0(Y,["id","name"])):p.choices=Y.choices.map(E=>H(E)),p}function X(Y){switch(Y.type){case"Template":return new gG(d,Y,V);case"Capture":return new KG(d,Y,V);case"Macro":return new bb(d,Y,b,i.getState().choices);case"Multi":default:break}}async function n(){let Y=await new Zb(d,V,b,l).waitForClose;Y&&(W(Y),I(9,b=Y))}async function R(){let Y=await new db(i.getState().ai).waitForClose;Y&&i.setState(p=>({...p,ai:Y}))}function J(Y){l=Y,I(0,l)}let t=Y=>Z(Y.detail.choices);return c.$$set=Y=>{"choices"in Y&&I(0,l=Y.choices),"macros"in Y&&I(9,b=Y.macros),"saveChoices"in Y&&I(1,Z=Y.saveChoices),"saveMacros"in Y&&I(10,W=Y.saveMacros),"app"in Y&&I(11,d=Y.app),"plugin"in Y&&I(12,V=Y.plugin)},[l,Z,a,m,N,F,h,n,R,b,W,d,V,J,t]}var NW=class extends O{constructor(G){super(),$(this,G,X5,R5,_,{choices:0,macros:9,saveChoices:1,saveMacros:10,app:11,plugin:12},Y5)}},IV=NW;var p5={name:"OpenAI",endpoint:"https://api.openai.com/v1",apiKey:"",models:[{name:"text-davinci-003",maxTokens:4096},{name:"gpt-3.5-turbo",maxTokens:4096},{name:"gpt-3.5-turbo-16k",maxTokens:16384},{name:"gpt-3.5-turbo-1106",maxTokens:16385},{name:"gpt-4",maxTokens:8192},{name:"gpt-4-32k",maxTokens:32768},{name:"gpt-4-1106-preview",maxTokens:128e3},{name:"gpt-4-turbo",maxTokens:128e3},{name:"gpt-4o",maxTokens:128e3},{name:"gpt-4o-mini",maxTokens:128e3}]},Vb=[p5];var f1={choices:[],macros:[],inputPrompt:"single-line",devMode:!1,templateFolderPath:"",announceUpdates:!0,version:"0.0.0",disableOnlineFeatures:!0,enableRibbonIcon:!1,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:Vb},migrations:{migrateToMacroIDFromEmbeddedMacro:!1,useQuickAddTemplateFolder:!1,incrementFileNameSettingMoveToDefaultBehavior:!1,mutualExclusionInsertAfterAndWriteToBottomOfFile:!1,setVersionAfterUpdateModalRelease:!1,addDefaultAIProviders:!1}},mb=class extends Al.PluginSettingTab{constructor(I,l){super(I,l);this.plugin=l}display(){let{containerEl:I}=this;I.empty(),I.createEl("h2",{text:"QuickAdd Settings"}),this.addChoicesSetting(),this.addUseMultiLineInputPromptSetting(),this.addTemplateFolderPathSetting(),this.addAnnounceUpdatesSetting(),this.addDisableOnlineFeaturesSetting(),this.addEnableRibbonIconSetting()}addAnnounceUpdatesSetting(){let I=new Al.Setting(this.containerEl);I.setName("Announce Updates"),I.setDesc("Display release notes when a new version i
`:""}${l}`}if(this.choice.insertAfter.enabled)returnawaitthis.insertAfterHandler(l);letZ=this.file?this.getFrontmatterEndPosition(this.file):null;returnZ?this.insertTextAfterPositionInBody(l,this.fileContent,Z):`${l}${this.fileContent}`}asyncformatContentOnly(I){letl=awaitsuper.formatFileContent(I);returnl=this.replaceLinebreakInString(l),l.trim()===""?this.fileContent:l}asyncinsertAfterHandler(I){letl=awaitthis.format(this.choice.insertAfter.after),b=newRegExp(`\\s*${U0(l.replace("\\n",""))}\\s*`),Z=GW(this.fileContent),W=Z.findIndex(V=>b.test(V));if(W===-1){if(this.choice.insertAfter?.createIfNotFound)returnawaitthis.createInsertAfterIfNotFound(I);u.logError("unable to find insert after line in file.")}if(this.choice.insertAfter?.insertAtEnd){if(!this.file)thrownewError("Tried to get sections without file.");W=Yb(Z,W,!!this.choice.insertAfter.considerSubsections)??Z.length-1}returnthis.insertTextAfterPositionInBody(I,this.fileContent,W)}asynccreateInsertAfterIfNotFound(I){letb=`${this.replaceLinebreakInString(awaitthis.format(this.choice.insertAfter.after))}
${b}`;if(this.choice.insertAfter?.createIfNotFoundLocation===X1)try{let Z=this.app.workspace.getActiveViewOfType(bV.MarkdownView);if(!Z)throw new Error("No active view.");let d=Z.editor.getCursor().line;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let a=GW(this.fileContent);d=Yb(a,d,!!this.choice.insertAfter.considerSubsections)??a.length-1}return this.insertTextAfterPositionInBody(b,this.fileContent,d)}catch(Z){u.logError(`unabletoinsertline'${this.choice.insertAfter.after}'onyourcursor.
${Z}`)}}getFrontmatterEndPosition(I){let l=this.app.metadataCache.getFileCache(I);return!l||!l.frontmatter?(u.logMessage("could not get frontmatter. Maybe there isn't any."),-1):l.frontmatterPosition?l.frontmatterPosition.end.line:-1}insertTextAfterPositionInBody(I,l,b){if(b===-1){let V=!this.choice.task;return`${I}${V?`
QuickAddwillnowreverttobackup.`),c.settings=l}}c.saveSettings()}var RV=i5;var XV=require("obsidian"),vb=require("obsidian");async function r5(c,G,I){let l=await fetch(`https://api.github.com/repos/${c}/${G}/releases`),b=await l.json();if(!l.ok&&"message"in b||!Array.isArray(b))throw new Error(`Failed to fetch releases: ${b.message??"Unknown error"}`);let Z=b.findIndex(W=>W.tag_name===I);if(Z===-1)throw new Error(`Could not find release with tag ${I}`);return b.slice(0,Z).filter(W=>!W.draft&&!W.prerelease)}function k5(c,G=1){let I=c.split(`
`,b="Thank you for using QuickAdd! If you like the plugin, please consider supporting me by buying me a coffee. With your sponsorship, I'll be able to contribute more to my existing projects, start new ones, and be more responsive to issues & feature requests.",Z='<div class="quickadd-bmac-container"><a href="https://www.buymeacoffee.com/chhoumann" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 40px !important;width: 144px !important;" ></a></div>',W=I.createDiv("quickadd-update-modal"),d=this.releases.map(N=>N.body).join(`
${k5(d)}`;vb.MarkdownRenderer.renderMarkdown(m,W,app.vault.getRoot().path,new XV.Component)}};var eI=require("obsidian");var eb=class extends eI.Modal{constructor(I){super(app);this.showAdvancedSettings=!1;this.settings=I,this.waitForClose=new Promise((l,b)=>{this.rejectPromise=b,this.resolvePromise=l}),this.open(),this.display()}get systemPromptTokenLength(){let I=yl(this.settings.model);return I?dl(this.settings.systemPrompt,I):Number.POSITIVE_INFINITY}display(){this.contentEl.empty();let I=this.contentEl.createEl("h2",{text:`${this.settings.name}Settings`});I.style.textAlign="center",I.style.cursor="pointer",I.style.userSelect="none",I.addEventListener("click",async()=>{try{let l=await dI.Prompt(app,"New name",this.settings.name,this.settings.name);l&&l!==this.settings.name&&(this.settings.name=l,this.reload())}catch{}}),this.addResultJoinerSetting(this.contentEl),this.addChunkSeparatorSetting(this.contentEl),this.addMaxTokensSetting(this.contentEl),this.addMergeChunksSetting(this.contentEl),this.addModelSetting(this.contentEl),this.addOutputVariableNameSetting(this.contentEl),this.addShowAdvancedSettingsToggle(this.contentEl),this.showAdvancedSettings&&(this.settings.modelParameters||(this.settings.modelParameters={}),this.addTemperatureSetting(this.contentEl),this.addTopPSetting(this.contentEl),this.addFrequencyPenaltySetting(this.contentEl),this.addPresencePenaltySetting(this.contentEl)),this.addSystemPromptSetting(this.contentEl)}reload(){this.contentEl.empty(),this.display()}addModelSetting(I){new eI.Setting(I).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(l=>{let b=Ml();for(let Z of b)l.addOption(Z,Z);l.addOption("Ask me","Ask me"),l.setValue(this.settings.model),l.onChange(Z=>{this.settings.model=Z,this.reload()})})}addOutputVariableNameSetting(I){new eI.Setting(I).setName("Output variable name").setDesc("The name of the variable used to store the AI Assistant output, i.e. {{value:output}}.").addText(l=>{l.setValue(this.settings.outputVariableName).onChange(b=>{this.settings.outputVariableName=b})})}addSystemPromptSetting(I){new eI.Setting(I).setName("System Prompt").setDesc("The system prompt for the AI Assistant");let l=this.contentEl.createEl("div"),b=l.createEl("span");b.style.color="var(--text-muted-color)",l.appendChild(b);let Z=new eI.TextAreaComponent(I);Z.setValue(this.settings.systemPrompt).onChange(async a=>{this.settings.systemPrompt=a,d.innerText=await W.format(a),V()}),new CI(this.app,Z.inputEl,GI.instance);let W=new Vl(this.app,GI.instance);Z.inputEl.style.width="100%",Z.inputEl.style.height="100px",Z.inputEl.style.minHeight="100px",Z.inputEl.style.marginBottom="1em";let d=this.contentEl.createEl("span"),V=(0,eI.debounce)(()=>{b.innerText=`Tokencount:${this.systemPromptTokenLength}`},50);V(),(async()=>d.innerText=await W.format(this.settings.systemPrompt??""))()}addShowAdvancedSettingsToggle(I){new eI.Setting(I).setName("Show advanced settings").setDesc("Show advanced settings such as temperature, top p, and frequency penalty.").addToggle(l=>{l.setValue(this.showAdvancedSettings),l.onChange(b=>{this.showAdvancedSettings=b,this.reload()})})}addTemperatureSetting(I){new eI.Setting(I).setName("Temperature").setDesc("Sampling temperature. Higher values like 0.8 makes the output more random, whereas lower values like 0.2 will make it more focused and deterministic. The default is 1.").addSlider(l=>{l.setLimits(0,1,.1),l.setDynamicTooltip(),l.setValue(this.settings.modelParameters.temperature??1),l.onChange(b=>{this.settings.modelParameters.temperature=b})})}addTopPSetting(I){new eI.Setting(I).setName("Top P").setDesc("Nucleus sampling - consider this an alternative to temperature. The model considers the results of the tokens with top_p probability mass. 0.1 means only tokens compromising the top 10% probability mass are considered. The default is 1.").addSlider(l=>{l.setLimits(0,1,.1),l.setDynamicTooltip(),l.setValue(this.settings.modelParameters.top_p??1),l.onChange(b=>{this.settings.modelParameters.top_p=b})})}addFrequencyPenaltySetting(I){new eI.Setting(I).setName