Files
BlueRoseNote/.obsidian/plugins/quickadd/main.js

118 lines
4.1 MiB
JavaScript
Raw Normal View History

2025-08-02 12:09:34 +08:00
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
2026-05-06 17:32:44 +08:00
var pw=Object.create;var fZ=Object.defineProperty;var Vw=Object.getOwnPropertyDescriptor;var ow=Object.getOwnPropertyNames;var rw=Object.getPrototypeOf,Xw=Object.prototype.hasOwnProperty;var Qw=(e,I,l)=>I in e?fZ(e,I,{enumerable:!0,configurable:!0,writable:!0,value:l}):e[I]=l;var pW=(e,I)=>()=>(I||e((I={exports:{}}).exports,I),I.exports),yG=(e,I)=>{for(var l in I)fZ(e,l,{get:I[l],enumerable:!0})},mp=(e,I,l,G)=>{if(I&&typeof I=="object"||typeof I=="function")for(let t of ow(I))!Xw.call(e,t)&&t!==l&&fZ(e,t,{get:()=>I[t],enumerable:!(G=Vw(I,t))||G.enumerable});return e};var UI=(e,I,l)=>(l=e!=null?pw(rw(e)):{},mp(I||!e||!e.__esModule?fZ(l,"default",{value:e,enumerable:!0}):l,e)),Rw=e=>mp(fZ({},"__esModule",{value:!0}),e);var GI=(e,I,l)=>Qw(e,typeof I!="symbol"?I+"":I,l);var lV=pW((Ri,Li)=>{(function(e,I){typeof Ri=="object"&&typeof Li<"u"?Li.exports=I():typeof define=="function"&&define.amd?define(I):(e=typeof globalThis<"u"?globalThis:e||self).dayjs_plugin_quarterOfYear=I()})(Ri,function(){"use strict";var e="month",I="quarter";return function(l,G){var t=G.prototype;t.quarter=function(d){return this.$utils().u(d)?Math.ceil((this.month()+1)/3):this.month(this.month()%3+3*(d-1))};var c=t.add;t.add=function(d,Z){return d=Number(d),this.$utils().p(Z)===I?this.add(3*d,e):c.bind(this)(d,Z)};var b=t.startOf;t.startOf=function(d,Z){var a=this.$utils(),m=!!a.u(Z)||Z;if(a.p(d)===I){var n=this.quarter()-1;return m?this.month(3*n).startOf(e).startOf("day"):this.month(3*n+2).endOf(e).endOf("day")}return b.bind(this)(d,Z)}}})});var MI=pW((Fi,wi)=>{(function(e,I){typeof Fi=="object"&&typeof wi<"u"?wi.exports=I():typeof define=="function"&&define.amd?define(I):(e=typeof globalThis<"u"?globalThis:e||self).dayjs=I()})(Fi,function(){"use strict";var e=1e3,I=6e4,l=36e5,G="millisecond",t="second",c="minute",b="hour",d="day",Z="week",a="month",m="quarter",n="year",W="date",N="Invalid Date",Y=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,s=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,u={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(k){var O=["th","st","nd","rd"],K=k%100;return"["+k+(O[(K-20)%10]||O[K]||O[0])+"]"}},V=function(k,O,K){var J=String(k);return!J||J.length>=O?k:""+Array(O+1-J.length).join(K)+k},C={s:V,z:function(k){var O=-k.utcOffset(),K=Math.abs(O),J=Math.floor(K/60),H=K%60;return(O<=0?"+":"-")+V(J,2,"0")+":"+V(H,2,"0")},m:function k(O,K){if(O.date()<K.date())return-k(K,O);var J=12*(K.year()-O.year())+(K.month()-O.month()),H=O.clone().add(J,a),v=K-H<0,A=O.clone().add(J+(v?-1:1),a);return+(-(J+(K-H)/(v?H-A:A-H))||0)},a:function(k){return k<0?Math.ceil(k)||0:Math.floor(k)},p:function(k){return{M:a,y:n,w:Z,d,D:W,h:b,m:c,s:t,ms:G,Q:m}[k]||String(k||"").toLowerCase().replace(/s$/,"")},u:function(k){return k===void 0}},r="en",i={};i[r]=u;var Q="$isDayjsObject",R=function(k){return k instanceof E||!(!k||!k[Q])},h=function k(O,K,J){var H;if(!O)return r;if(typeof O=="string"){var v=O.toLowerCase();i[v]&&(H=v),K&&(i[v]=K,H=v);var A=O.split("-");if(!H&&A.length>1)return k(A[0])}else{var B=O.name;i[B]=O,H=B}return!J&&H&&(r=H),H||!J&&r},F=function(k,O){if(R(k))return k.clone();var K=typeof O=="object"?O:{};return K.date=k,K.args=arguments,new E(K)},w=C;w.l=h,w.i=R,w.w=function(k,O){return F(k,{locale:O.$L,utc:O.$u,x:O.$x,$offset:O.$offset})};var E=function(){function k(K){this.$L=h(K.locale,null,!0),this.parse(K),this.$x=this.$x||K.x||{},this[Q]=!0}var O=k.prototype;return O.parse=function(K){this.$d=function(J){var H=J.date,v=J.utc;if(H===null)return new Date(NaN);if(w.u(H))return new Date;if(H instanceof Date)return new Date(H);if(typeof H=="string"&&!/Z$/i.test(H)){var A=H.match(Y);if(A){var B=A[2]-1||0,q=(A[7]||"0").substring(0,3);return v?new Date(Date.UTC(A[1],B,A[3]||1,A[4]||0,A[5]||0,A[6]||0,q)):new Date(A[1],B,A[3]||1,A[4]||0,A[5]||0,A[6]||0,q)}}return new Date(H)}(K),this.init()},O.init=f
`||X.charAt($)==="\r"&&X.charAt($+1)!==`
`)&&(II++,lI===0&&(lI=$+1)),$--}var NI=f+II,Gl=y-lI;return U[y]={line:NI,lineStart:lI},{offset:y,line:NI+1,column:Gl+1}}function k(X){if(!i(X))throw new Error("not a parser: "+X)}function O(X,y){return typeof X=="string"?X.charAt(y):X[y]}function K(X){if(typeof X!="number")throw new Error("not a number: "+X)}function J(X){if(typeof X!="function")throw new Error("not a function: "+X)}function H(X){if(typeof X!="string")throw new Error("not a string: "+X)}var v=2,A=3,B=8,q=5*B,mI=4*B,nI=" ";function VI(X,y){return new Array(y+1).join(X)}function RI(X,y,U){var f=y-X.length;return f<=0?X:VI(U,f)+X}function uI(X,y,U,f){return{from:X-y>0?X-y:0,to:X+U>f?f:X+U}}function WI(X,y){var U,f,II,lI,$,NI=y.index,Gl=NI.offset,Hl=1;if(Gl===X.length)return"Got the end of the input";if(R(X)){var bl=Gl-Gl%B,be=Gl-bl,Dl=uI(bl,q,mI+B,X.length),Ml=a(function(Ol){return a(function(xb){return RI(xb.toString(16),2,"0")},Ol)},function(Ol,xb){var Ub=Ol.length,Jc=[],zb=0;if(Ub<=xb)return[Ol.slice()];for(var Bb=0;Bb<Ub;Bb++)Jc[zb]||Jc.push([]),Jc[zb].push(Ol[Bb]),(Bb+1)%xb==0&&zb++;return Jc}(X.slice(Dl.from,Dl.to).toJSON().data,B));lI=function(Ol){return Ol.from===0&&Ol.to===1?{from:Ol.from,to:Ol.to}:{from:Ol.from/B,to:Math.floor(Ol.to/B)}}(Dl),f=bl/B,U=3*be,be>=4&&(U+=1),Hl=2,II=a(function(Ol){return Ol.length<=4?Ol.join(" "):Ol.slice(0,4).join(" ")+" "+Ol.slice(4).join(" ")},Ml),($=(8*(lI.to>0?lI.to-1:lI.to)).toString(16).length)<2&&($=2)}else{var fl=X.split(/\r\n|[\n\r\u2028\u2029]/);U=NI.column-1,f=NI.line-1,lI=uI(f,v,A,fl.length),II=fl.slice(lI.from,lI.to),$=lI.to.toString().length}var Cl=f-lI.from;return R(X)&&($=(8*(lI.to>0?lI.to-1:lI.to)).toString(16).length)<2&&($=2),Z(function(Ol,xb,Ub){var Jc,zb=Ub===Cl,Bb=zb?"> ":nI;return Jc=R(X)?RI((8*(lI.from+Ub)).toString(16),$,"0"):RI((lI.from+Ub+1).toString(),$," "),[].concat(Ol,[Bb+Jc+" | "+xb],zb?[nI+VI(" ",$)+" | "+RI("",U," ")+VI("^",Hl)]:[])},[],II).join(`
`)}function LI(X,y){return[`
`,"-- PARSING FAILED "+VI("-",50),`
`,WI(X,y),`
`,(U=y.expected,U.length===1?`Expected:
`+U[0]:`Expected one of the following:
`+U.join(", ")),`
`].join("");var U}function ll(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 ul(){for(var X=[].slice.call(arguments),y=X.length,U=0;U<y;U+=1)k(X[U]);return c(function(f,II){for(var lI,$=new Array(y),NI=0;NI<y;NI+=1){if(!(lI=w(X[NI]._(f,II),lI)).status)return lI;$[NI]=lI.value,II=lI.index}return w(h(II,$),lI)})}function vl(){var X=[].slice.call(arguments);if(X.length===0)throw new Error("seqMap needs at least one argument");var y=X.pop();return J(y),ul.apply(null,X).map(function(U){return y.apply(null,U)})}function hl(){var X=[].slice.call(arguments),y=X.length;if(y===0)return j("zero alternates");for(var U=0;U<y;U+=1)k(X[U]);return c(function(f,II){for(var lI,$=0;$<X.length;$+=1)if((lI=w(X[$]._(f,II),lI)).status)return lI;return lI})}function ge(X,y){return fG(X,y).or(NG([]))}function fG(X,y){return k(X),k(y),vl(X,y.then(X).many(),function(U,f){return[U].concat(f)})}function jG(X){H(X);var y="'"+X+"'";return c(function(U,f){var II=f+X.length,lI=U.slice(f,II);return lI===X?h(II,lI):F(f,y)})}function WG(X,y){(function(II){if(!(II instanceof RegExp))throw new Error("not a regexp: "+II);for(var lI=ll(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?K(y):y=0;var U=function(II){return RegExp("^(?:"+II.source+")",ll(II))}(X),f=""+X;return c(function(II,lI){var $=U.exec(II.slice(lI));if($){if(0<=y&&y<=$.length){var NI=$[0],Gl=$[y];return h(lI+NI.length,Gl)}return F(lI,"valid match group (0 to "+$.length+") in "+f)}return F(lI,f)})}function NG(X){return c(function(y,U){return h(U,X)})}function j(X){return c(function(y,U){return F(U,X)})}function kI(X){if(i(X))return c(function(y,U){var f=X._(y,U);return f.index=U,f.value="",f});if(typeof X=="string")return kI(jG(X));if(X instanceof RegExp)return kI(WG(X));throw new Error("not a string, regexp, or parser: "+X)}function xI(X){return k(X),c(function(y,U){var f=X._(y,U),II=y.slice(U,f.index);return f.status?F(U,'not "'+II+'"'):h(U,null)})}function SI(X){return J(X),c(function(y,U){var f=O(y,U);return U<y.length&&X(f)?h(U+1,f):F(U,"a character/byte matching "+X)})}function te(X,y){arguments.length<2&&(y=X,X=void 0);var U=c(function(f,II){return U._=y()._,U._(f,II)});return X?U.desc(X):U}function YG(){return j("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 y,U=this.skip(ce)._(X,0);return y=U.status?{status:!0,value:U.value}:{status:!1,index:T(X,U.furthest),expected:U.expected},delete E[X],y},b.tryParse=function(X){var y=this.parse(X);if(y.status)return y.value;var U=LI(X,y),f=new Error(U);throw f.type="ParsimmonError",f.result=y,f},b.assert=function(X,y){return this.chain(function(U){return X(U)?NG(U):j(y)})},b.or=function(X){return hl(this,X)},b.trim=function(X){return this.wrap(X,X)},b.wrap=function(X,y){return vl(X,this,y,function(U,f){return f})},b.thru=function(X){return X(this)},b.then=function(X){return k(X),ul(this,X).map(function(y){return y[1]})},b.many=function(){var X=this;return c(function(y,U){for(var f=[],II=void 0;;){if(!(II=w(X._(y,U),II)).status)return w(h(U,f),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,f.push(II.value)}})},b.tieWith=function(X){return H(X),this.map(function(y){if(function(II){if(!Q(II))throw new Error("not an array: "+II)}(y),y.length){H(y[0]);for(var U=y[0],f=1;f<y.length;f++)H(y[f]),U+=X+y[f];return U}return""})},b.tie=function(){return this.tieWith("")},b.times=function(X,y){var U=this;return arguments.length<2&&(y=X),K(X),K(y),c(function(f,II){for(var lI=[],$=void 0,NI=void 0,Gl=0;Gl<X;Gl+=1){if(NI=w($=U._(f,II),NI),!$.status)return NI;II=$.index,lI.push($.value)}for(;Gl<y&&(NI=w($=U._(f,II),NI),$.status);Gl+=1)II=$.index,lI.push($.value);return w(h(II,lI),NI)})},b.result=function(X){return thi
`),yc=jG(`\r
`),ye=hl(yc,MZ,Hc).desc("newline"),hW=hl(ye,ce);c.all=Ft,c.alt=hl,c.any=St,c.cr=Hc,c.createLanguage=function(X){var y={};for(var U in X)({}).hasOwnProperty.call(X,U)&&function(f){y[f]=te(function(){return X[f](y)})}(U);return y},c.crlf=yc,c.custom=function(X){return c(X(h,F))},c.digit=Tt,c.digits=vc,c.empty=YG,c.end=hW,c.eof=ce,c.fail=j,c.formatError=LI,c.index=SG,c.isParser=i,c.lazy=te,c.letter=qt,c.letters=ve,c.lf=MZ,c.lookahead=kI,c.makeFailure=F,c.makeSuccess=h,c.newline=ye,c.noneOf=function(X){return SI(function(y){return X.indexOf(y)<0}).desc("none of '"+X+"'")},c.notFollowedBy=xI,c.of=NG,c.oneOf=function(X){for(var y=X.split(""),U=0;U<y.length;U++)y[U]="'"+y[U]+"'";return SI(function(f){return X.indexOf(f)>=0}).desc(y)},c.optWhitespace=CW,c.Parser=c,c.range=function(X,y){return SI(function(U){return X<=U&&U<=y}).desc(X+"-"+y)},c.regex=WG,c.regexp=WG,c.sepBy=ge,c.sepBy1=fG,c.seq=ul,c.seqMap=vl,c.seqObj=function(){for(var X,y={},U=0,f=(X=arguments,Array.prototype.slice.call(X)),II=f.length,lI=0;lI<II;lI+=1){var $=f[lI];if(!i($)){if(Q($)&&$.length===2&&typeof $[0]=="string"&&i($[1])){var NI=$[0];if(Object.prototype.hasOwnProperty.call(y,NI))throw new Error("seqObj: duplicate key "+NI);y[NI]=!0,U++;continue}throw new Error("seqObj arguments must be parsers or [string, parser] array pairs.")}}if(U===0)throw new Error("seqObj expects at least one named parser, found zero");return c(function(Gl,Hl){for(var bl,be={},Dl=0;Dl<II;Dl+=1){var Ml,fl;if(Q(f[Dl])?(Ml=f[Dl][0],fl=f[Dl][1]):(Ml=null,fl=f[Dl]),!(bl=w(fl._(Gl,Hl),bl)).status)return bl;Ml&&(be[Ml]=bl.value),Hl=bl.index}return w(h(Hl,be),bl)})},c.string=jG,c.succeed=NG,c.takeWhile=function(X){return J(X),c(function(y,U){for(var f=U;f<y.length&&X(O(y,f));)f++;return h(f,y.slice(U,f))})},c.test=SI,c.whitespace=He,c["fantasy-land/empty"]=YG,c["fantasy-land/of"]=NG,c.Binary={bitSeq:N,bitSeqObj:function(X){W();var y={},U=0,f=a(function(lI){if(Q(lI)){var $=lI;if($.length!==2)throw new Error("["+$.join(", ")+"] should be length 2, got length "+$.length);if(H($[0]),K($[1]),Object.prototype.hasOwnProperty.call(y,$[0]))throw new Error("duplicate key in bitSeqObj: "+$[0]);return y[$[0]]=!0,U++,$}return K(lI),[null,lI]},X);if(U<1)throw new Error("bitSeqObj expects at least one named pair, got ["+X.join(", ")+"]");var II=a(function(lI){return lI[0]},f);return N(a(function(lI){return lI[1]},f)).map(function(lI){return Z(function($,NI){return NI[0]!==null&&($[NI[0]]=NI[1]),$},{},a(function($,NI){return[$,lI[NI]]},II))})},byte:function(X){if(W(),K(X),X>255)throw new Error("Value specified to byte constructor ("+X+"=0x"+X.toString(16)+") is larger in value than a single byte.");var y=(X>15?"0x":"0x0")+X.toString(16);return c(function(U,f){var II=O(U,f);return II===X?h(f+1,II):F(f,y)})},buffer:function(X){return Y("buffer",X).map(function(y){return Buffer.from(y)})},encodedString:function(X,y){return Y("string",y).map(function(U){return U.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:C,int8BE:C(1),int16BE:C(2),int32BE:C(4),intLE:r,int8LE:r(1),int16LE:r(2),int32LE:r(4),floatBE:Y("floatBE",4).map(function(X){return X.readFloatBE(0)}),floatLE:Y("floatLE",4).map(function(X){return X.readFloatLE(0)}),doubleBE:Y("doubleBE",8).map(function(X){return X.readDoubleBE(0)}),doubleLE:Y("doubleLE",8).map(function(X){return X.readDoubleLE(0)})},l.exports=c}])})})(VY,VY.exports);var g=VY.exports,fh=()=>/[#*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
`)[0];let G=l.substring(2).trim();return g.makeSuccess(I+l.length,G)}),namedField:e=>g.alt(e.explicitNamedField,LA(Be.field).map(([I,l])=>rY.named(FA(l),I))),sortField:e=>g.seqMap(Be.field.skip(g.optWhitespace),g.regexp(/ASCENDING|DESCENDING|ASC|DESC/i).atMost(1),(I,l)=>{let G=l.length==0?"ascending":l[0].toLowerCase();return G=="desc"&&(G="descending"),G=="asc"&&(G="ascending"),{field:I,direction:G}}),headerClause:e=>e.queryType.chain(I=>{switch(I){case"table":return SX(()=>({type:I,fields:[],showId:!0}),g.seqMap(g.regexp(/WITHOUT\s+ID/i).skip(g.optWhitespace).atMost(1),g.sepBy(e.namedField,g.string(",").trim(g.optWhitespace)),(l,G)=>({type:I,fields:G,showId:l.length==0})));case"list":return SX(()=>({type:I,format:void 0,showId:!0}),g.seqMap(g.regexp(/WITHOUT\s+ID/i).skip(g.optWhitespace).atMost(1),Be.field.atMost(1),(l,G)=>({type:I,format:G.length==1?G[0]:void 0,showId:l.length==0})));case"task":return g.succeed({type:I});case"calendar":return g.whitespace.then(g.seqMap(e.namedField,l=>({type:I,showId:!0,field:l})));default:return g.fail(`Unrecognized query type '${I}'`)}}).desc("TABLE or LIST or TASK or CALENDAR"),fromClause:e=>g.seqMap(g.regexp(/FROM/i),g.whitespace,Be.source,(I,l,G)=>G),whereClause:e=>g.seqMap(g.regexp(/WHERE/i),g.whitespace,Be.field,(I,l,G)=>({type:"where",clause:G})).desc("WHERE <expression>"),sortByClause:e=>g.seqMap(g.regexp(/SORT/i),g.whitespace,e.sortField.sepBy1(g.string(",").trim(g.optWhitespace)),(I,l,G)=>({type:"sort",fields:G})).desc("SORT field [ASC/DESC]"),limitClause:e=>g.seqMap(g.regexp(/LIMIT/i),g.whitespace,Be.field,(I,l,G)=>({type:"limit",amount:G})).desc("LIMIT <value>"),flattenClause:e=>g.seqMap(g.regexp(/FLATTEN/i).skip(g.whitespace),e.namedField,(I,l)=>({type:"flatten",field:l})).desc("FLATTEN <value> [AS <name>]"),groupByClause:e=>g.seqMap(g.regexp(/GROUP BY/i).skip(g.whitespace),e.namedField,(I,l)=>({type:"group",field:l})).desc("GROUP BY <value> [AS <name>]"),clause:e=>g.alt(e.fromClause,e.whereClause,e.sortByClause,e.limitClause,e.groupByClause,e.flattenClause),query:e=>g.seqMap(e.headerClause.trim(Ch),e.fromClause.trim(Ch).atMost(1),e.clause.trim(Ch).many(),(I,l,G)=>({header:I,source:l.length==0?Yt.folder(""):l[0],operations:G,settings:Mh}))}),Ch=g.alt(g.whitespace,SQ.comment).many().map(e=>e.join("")),wA=e=>e?e.plugins.plugins.dataview?.api:window.DataviewAPI,gA=e=>e.plugins.enabledPlugins.has("dataview");st.DATE_SHORTHANDS=kh;st.DURATION_TYPES=Eh;st.EXPRESSION=Be;st.KEYWORDS=Oh;st.QUERY_LANGUAGE=SQ;st.getAPI=wA;st.isPluginEnabled=gA;st.parseField=RA});var Y9={};yG(Y9,{default:()=>$I});module.exports=Rw(Y9);var hw=require("obsidian");var Re=require("obsidian");function _I(){}function Zi(e){return e()}function VW(){return Object.create(null)}function rI(e){e.forEach(Zi)}function yI(e){return typeof e=="function"}function OI(e,I){return e!=e?I==I:e!==I||e&&typeof e=="object"||typeof e=="function"}function np(e){return Object.keys(e).length===0}function ai(e){return e??""}function Ac(e){return e&&yI(e.destroy)?e.destroy:_I}var jZ=typeof window<"u"?window:typeof globalThis<"u"?globalThis:global;var oW=class e{constructor(I){GI(this,"_listeners","WeakMap"in jZ?new WeakMap:void 0);GI(this,"_observer");GI(this,"options");this.options=I}observe(I,l){return this._listeners.set(I,l),this._getObserver().observe(I,this.options),()=>{this._listeners.delete(I),this._observer.unobserve(I)}}_getObserver(){return this._observer??(this._observer=new ResizeObserver(I=>{for(let l of I)e.entries.set(l.target,l),this._listeners.get(l.target)?.(l)}))}};oW.entries="WeakMap"in jZ?new WeakMap:void 0;var Wp=!1;function Np(){Wp=!0}function Yp(){Wp=!1}function p(e,I){e.appendChild(I)}function dl(e,I,l){let G=sp(e);if(!G.getElementById(I)){let t=L("style");t.id=I,t.textContent=l,ww(G,t)}}function sp(e){if(!e)return document;let I=e.getRootNode?e.getRootNode():e.ownerDocument;return I&&I.host?I:e.ownerDocument}function ww(e,I){return p(e.head||e,I),I.sheet}function cI(e,I,l){e.insertBefore(I,l||null)}function eI(e){e.parentNode&&e.parentNode.removeChild(e)}function wt(e,I){for(let l=0;l<e.length;l+=1)
`)}function TZ(e){let I=Object.entries(e);if(I.length===0)return[];let G=["t","tm","yd"].map(b=>{let d=e[b];return d?[b,d]:null}).filter(b=>b!==null),t=new Set(G.map(([b])=>b)),c=I.filter(([b])=>!t.has(b)).sort((b,d)=>{let Z=b[0].length-d[0].length;return Z!==0?Z:b[0].localeCompare(d[0])});return[...G,...c]}function wW(e){return TZ(e).map(([I,l])=>`${I}=${l}`).join(", ")}var gW={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:jb,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:FW},migrations:{migrateToMacroIDFromEmbeddedMacro:!0,useQuickAddTemplateFolder:!1,incrementFileNameSettingMoveToDefaultBehavior:!1,mutualExclusionInsertAfterAndWriteToBottomOfFile:!1,setVersionAfterUpdateModalRelease:!1,addDefaultAIProviders:!1,removeMacroIndirection:!1,migrateFileOpeningSettings:!1,backfillFileOpeningDefaults:!1,setProviderModelDiscoveryMode:!1,migrateProviderApiKeysToSecretStorage:!1}};function el(e){let I=globalThis.structuredClone;if(typeof I=="function")try{return I(e)}catch{}return $t(e,new Map)}function $t(e,I){if(e===null||typeof e!="object")return e;if(I.has(e))return I.get(e);if(e instanceof Date){let t=new Date(e.getTime());return I.set(e,t),t}if(Array.isArray(e)){let t=[];I.set(e,t);for(let c of e)t.push($t(c,I));return t}if(e instanceof Map){let t=new Map;I.set(e,t);for(let[c,b]of e.entries())t.set($t(c,I),$t(b,I));return t}if(e instanceof Set){let t=new Set;I.set(e,t);for(let c of e.values())t.add($t(c,I));return t}if(e instanceof RegExp){let t=new RegExp(e.source,e.flags);return t.lastIndex=e.lastIndex,I.set(e,t),t}if(e instanceof ArrayBuffer){let t=e.slice(0);return I.set(e,t),t}if(ArrayBuffer.isView(e)){if(e instanceof DataView){let d=new DataView($t(e.buffer,I),e.byteOffset,e.byteLength);return I.set(e,d),d}let t=e,c=$t(t.buffer,I),b=new t.constructor(c,t.byteOffset,t.length);return I.set(e,b),b}let l=Object.getPrototypeOf(e),G=Object.create(l);I.set(e,G);for(let[t,c]of Object.entries(e))Object.defineProperty(G,t,{value:$t(c,I),writable:!0,enumerable:!0,configurable:!0});return G}var P=(()=>{let e=Xp((t,c)=>({...el(gW)})),{getState:I,setState:l,subscribe:G}=e;return{getState:I,setState:l,subscribe:G}})();var EI=require("obsidian");var Kc="{{value}}",Ci="{{date}}",Rp="{{time}}",hi="{{name}}",Dw="{{value:<variable name>}}",Mw="{{value:<variable name>|<default value>}}",fw="{{value:<variable name>|default:<value>}}",jw="{{value:<variable name>|label:<helper text>}}",Sw="{{value:<items>|text:<display items>}}",Tw="{{value|case:kebab}}",qw="{{value:<variable name>|case:kebab}}",Pw="{{field:<field name>}}",Lp="{{mvalue}}",Fp="{{linkcurrent}}",wp="{{filenamecurrent}}",gp="{{title}}",vp="{{selected}}",Hp="{{clipboard}}",_w="{{random:<length>}}",$w="{{global_var:<name>}}";var yp=[Ci,"{{date:<dateformat>}}","{{vdate:<variable name>, <date format>}}","{{vdate:<variable name>, <date format>|<default value>}}",$w,Kc,hi,Tw,qw,Dw,Mw,fw,jw,Sw,Pw,_w];var pi=new RegExp(/^-?[0-9]*$/),Sb="top",qZ="bottom",PZ="cursor",vW=new RegExp(/{{DATE(\+-?[0-9]+)?}}/i),Tb=n
tags: ${JSON.stringify(Array.from(this._tags).sort())},
knownValues: ${JSON.stringify(this.knownValues)},
impliedValues: ${JSON.stringify(this.impliedValues)}},
reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,vi.default)(this.dateWithoutTimezoneAdjustment())}date(){let I=this.dateWithoutTimezoneAdjustment(),l=this.reference.getSystemTimezoneAdjustmentMinute(I,this.get("timezoneOffset"));return new Date(I.getTime()+l*6e4)}addTag(I){return this._tags.add(I),this}addTags(I){for(let l of I)this._tags.add(l);return this}tags(){return new Set(this._tags)}dateWithoutTimezoneAdjustment(){let I=new Date(this.get("year"),this.get("month")-1,this.get("day"),this.get("hour"),this.get("minute"),this.get("second"),this.get("millisecond"));return I.setFullYear(this.get("year")),I}static createRelativeFromReference(I,l){let G=bV(I.getDateWithAdjustedTimezone(),l),t=new e(I);return t.addTag("result/relativeDate"),l.hour||l.minute||l.second?(t.addTag("result/relativeDateAndTime"),eV(t,G),GV(t,G),t.assign("timezoneOffset",I.getTimezoneOffset())):(tV(t,G),t.imply("timezoneOffset",I.getTimezoneOffset()),l.day?(t.assign("day",G.getDate()),t.assign("month",G.getMonth()+1),t.assign("year",G.getFullYear()),t.assign("weekday",G.getDay())):l.week?(t.assign("day",G.getDate()),t.assign("month",G.getMonth()+1),t.assign("year",G.getFullYear()),t.imply("weekday",G.getDay())):(t.imply("day",G.getDate()),l.month?(t.assign("month",G.getMonth()+1),t.assign("year",G.getFullYear())):(t.imply("month",G.getMonth()+1),l.year?t.assign("year",G.getFullYear()):t.imply("year",G.getFullYear())))),t}},BI=class e{constructor(I,l,G,t,c){GI(this,"refDate");GI(this,"index");GI(this,"text");GI(this,"reference");GI(this,"start");GI(this,"end");this.reference=I,this.refDate=I.instant,this.index=l,this.text=G,this.start=t||new _(I),this.end=c}clone(){let I=new e(this.reference,this.index,this.text);return I.start=this.start?this.start.clone():null,I.end=this.end?this.end.clone():null,I}date(){return this.start.date()}addTag(I){return this.start.addTag(I),this.end&&this.end.addTag(I),this}addTags(I){return this.start.addTags(I),this.end&&this.end.addTags(I),this}tags(){let I=new Set(this.start.tags());if(this.end)for(let l of this.end.tags())I.add(l);return I}toString(){let I=Array.from(this.tags()).sort();return`[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(I)} ...}]`}};function QG(e,I,l="\\s{0,5},?\\s{0,5}"){let G=I.replace(/\((?!\?)/g,"(?:");return`${e}${G}(?:${l}${G}){0,10}`}function Gg(e){let I;return e instanceof Array?I=[...e]:e instanceof Map?I=Array.from(e.keys()):I=Object.keys(e),I}function bI(e){return`(?:${Gg(e).sort((l,G)=>G.length-l.length).join("|").replace(/\./g,"\\.")})`}var ZV=UI(MI(),1);function EG(e){return e<100&&(e>50?e=e+1900:e=e+2e3),e}function PI(e,I,l){let G=(0,ZV.default)(e),t=G;t=t.month(l-1),t=t.date(I),t=t.year(G.year());let c=t.add(1,"y"),b=t.add(-1,"y");return Math.abs(c.diff(G))<Math.abs(t.diff(G))?t=c:Math.abs(b.diff(G))<Math.abs(t.diff(G))&&(t=b),t.year()}var OW={sunday:0,sun:0,"sun.":0,monday:1,mon:1,"mon.":1,tuesday:2,tue:2,"tue.":2,wednesday:3,wed:3,"wed.":3,thursday:4,thurs:4,"thurs.":4,thur:4,"thur.":4,thu:4,"thu.":4,friday:5,fri:5,"fri.":5,saturday:6,sat:6,"sat.":6},Ji={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},de={...Ji,jan:1,"jan.":1,feb:2,"feb.":2,mar:3,"mar.":3,apr:4,"apr.":4,jun:6,"jun.":6,jul:7,"jul.":7,aug:8,"aug.":8,sep:9,"sep.":9,sept:9,"sept.":9,oct:10,"oct.":10,nov:11,"nov.":11,dec:12,"dec.":12},Hi={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},yi={first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,twentieth:20,"twenty first":21,"twenty-first":21,"twenty second":22,"twenty-second":22,"twenty third":23,"twenty-third":23,"twenty fourth":24,"twenty-fourth":24,"twenty fifth":25,"twenty-fifth":25,"twenty sixth":26,"twenty-sixth":26,"twenty seventh":27,"twenty-seventh":27,"twenty eighth":28,"twenty-eighth":28,"twenty ninth":29,"twenty-ninth":29,thirtieth:30
`),Z=d.length,a=d[Z-1]?.length??0;if(I==="above")t.replaceRange(e+`
`,{line:b,ch:0}),t.setCursor({line:b+Z-1,ch:a});else{let m=t.getLine(b);t.replaceRange(`
`+e,{line:b,ch:m.length}),t.setCursor({line:b+Z,ch:a})}}catch{x.logError(`unable to insert '${e}' on new line ${I}.`)}}function B2(e,I){z2(e,"above",I)}function D2(e,I){z2(e,"below",I)}function uy(e,I,l="replaceSelection",G={}){let{requireActiveView:t=!0}=G,c=e.workspace.getActiveViewOfType(xG.MarkdownView);if(!c){let m="Cannot append link because no active Markdown view is available.";if(t)throw new Error(m);x.logMessage(m);return}let b=c.editor,d=b.listSelections().map(m=>({anchor:{...m.anchor},head:{...m.head}}));if(l==="replaceSelection"){b.replaceSelection(I);return}let Z=({line:m,ch:n})=>b.posToOffset({line:m,ch:n}),a=d.sort((m,n)=>Z(n.head)-Z(m.head));for(let m of a){let n=Z(m.anchor)>Z(m.head)?m.anchor:m.head;switch(l){case"afterSelection":{b.replaceRange(I,n);break}case"endOfLine":{let W=b.getLine(n.line),N={line:n.line,ch:W.length};b.replaceRange(I,N);break}case"newLine":{let W=b.getLine(n.line),N={line:n.line,ch:W.length},s=W.length===0?"":`
`;b.replaceRange(s+I,N);break}}}}function Cy(e){let I=/^\s*!?\[[^\]]*\]\((.+)\)\s*$/,l=e.match(I);if(!l)return null;let G=l[1].trim();return G?(G.startsWith("<")&&G.endsWith(">")&&(G=G.slice(1,-1).trim()),G):null}function hy(e){let I=e.trim();if(I.startsWith("![[")&&I.includes("]]"))return e;let l=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)}`;let t=Cy(e);return t?`![[${t}]]`:e.startsWith("!")?e:`!${e}`}function hN(e,I,l){if(!l?.enabled)return!1;let G=e.workspace.getActiveFile();if(!G&&l.requireActiveFile)throw new Error("Append link is enabled but there's no active file to insert into.");if(!e.workspace.getActiveViewOfType(xG.MarkdownView)){if(l.requireActiveFile)throw new Error("Cannot append link because no active Markdown view is available.");return!1}let c=G?.path??"",b=e.fileManager.generateMarkdownLink(I,c),Z=l.linkType==="embed"&&At(l.placement)?hy(b):b;return uy(e,Z,l.placement,{requireActiveView:!1}),!0}function py(e,I){return e.commands.findCommand(I)}function M2(e,I){py(e,I)&&(delete e.commands.commands[I],delete e.commands.editorCommands[I])}function nb(e){return e.vault.getAllLoadedFiles().filter(I=>I instanceof xG.TFolder).map(I=>I.path)}function Nn(e){let I=e.split("::").map(l=>l.trim()).filter(Boolean);return{basename:I[0],memberAccess:I.slice(1)}}async function Wb(e,I,l={}){let{location:G="tab",direction:t="vertical",mode:c,focus:b=!0,eState:d}=l,Z=typeof I=="string"?e.vault.getAbstractFileByPath(I):I;if(!Z)throw new Error(`File not found: ${String(I)}`);let a;switch(G){case"reuse":a=e.workspace.getLeaf(!1);break;case"tab":a=e.workspace.getLeaf("tab");break;case"split":a=e.workspace.getLeaf("split",t);break;case"window":a=e.workspace.getLeaf("window");break;case"left-sidebar":a=e.workspace.getLeftLeaf(!0);break;case"right-sidebar":a=e.workspace.getRightLeaf(!0);break;default:a=e.workspace.getLeaf("tab")}if(!a)throw new Error("Could not obtain a workspace leaf.");if(await a.openFile(Z),c&&c!=="default"&&!(typeof c=="object"&&c.mode==="default")){let m=a.getViewState(),n={...m.state??{}};c==="preview"||typeof c=="object"&&c.mode==="preview"?(n.mode="preview",delete n.source):c==="source"?(n.mode="source",n.source=!0):c==="live"||c==="live-preview"?(n.mode="source",n.source=!1):typeof c=="object"&&c.mode==="source"&&(n.mode="source",n.source=c.source),await a.setViewState({...m,state:{...n,...d}})}return b&&e.workspace.setActiveLeaf(a,{focus:!0}),a}function O2(e){return(0,xG.normalizePath)(e).replace(/\/{2,}/g,"/").replace(/^\/+/,"")}function Vy(e,I){return O2(e)===O2(I)}function Yn(e,I,l=!0){let G;return e.workspace.iterateRootLeaves(t=>{let c=t.view;if(c instanceof xG.FileView&&c.file&&(c.file===I||Vy(I.path,c.file.path))){G=t;return}}),G!==void 0?(l&&e.workspace.setActiveLeaf(G,{focus:!0}),G):null}async function kt(e,I){let l=I.vault.getAbstractFileByPath(e.path);if(!l){x.logError(`failed to load file ${e.path}.`);return}if(l instanceof xG.TFile){let G=n=>window.require&&window.require(n),t={},c={exports:t},b=await I.vault.read(l);window.eval(`(function(require, module, exports) { ${b}
})`)(G,c,t);let Z=t.default||c.exports;if(!Z)return;let a=Z,{memberAccess:m}=Nn(e.name);if(m&&m.length>0){let n;for(;n=m.shift();)a=a[n]}return a}}function f2(e,I){let l=el(e);for(let G of I)delete l[G];return l}function pN(e,I){let l=e.vault.getAbstractFileByPath(I);return!!l&&l instanceof xG.TFolder}function mc(e,I){return e.vault.getMarkdownFiles().filter(l=>l.path.startsWith(I))}function oy(e){let I=e.frontmatter;if(!I)return[];let l=Object.entries(I);if(!l.length)return[];let G=l.filter(([c,b])=>{let d=c.toLowerCase();return d==="tags"||d==="tag"});return G?G.flatMap(([c,b])=>{if(typeof b=="string")return b.split(/,|\s+/).map(d=>d.trim());if(Array.isArray(b))return b}).filter(c=>!!c):[]}function ry(e,I){let l=e.metadataCache.getFileCache(I);if(!l)return[];let G=[];return l.frontmatter&&G.push(...oy(l)),l.tags&&Array.isArray(l.tags)&&G.push(...l.tags.map(t=>t.tag.replace(/^\#/,""))),G}function VN(e,I){let l=I.replace(/^\#/,"");return e.vault.getMarkdownFiles().filter(G=>ry(e,G).includes(l))}function oN(e){let l=/^(\s*---\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)\s*(?:\r?\n|$))/.exec(e);return l?[0,l[0].length]:null}function j2(e,I,l,G){if(!(G!==null&&I>=G[0]&&I<=G[1]))return{isInYaml:!1,isQuoted:!1,lineStart:0,lineEnd:0,baseIndent:"",isKeyValuePosition:!1};let c=e.lastIndexOf(`
`,I-1)+1,b=e.indexOf(`
`,I),d=b===-1?e.length:b,Z=e.slice(c,I),a=e.slice(l,d),m=(Z.match(/^\s*/)||[""])[0],n=e[I-1]==='"'&&e[l]==='"'||e[I-1]==="'"&&e[l]==="'",W=Z.replace(/["']$/,""),N=a.replace(/^["']/,""),Y=/:\s*$/.test(W)&&N.trim().length===0;return{isInYaml:!0,isQuoted:n,lineStart:c,lineEnd:d,baseIndent:m,isKeyValuePosition:Y}}var S2={"[":"]","(":")","{":"}","<":">"};function Xy(e,I=","){let l=[],G="",t=[],c=null;for(let d=0;d<e.length;d++){let Z=e[d];if(c){if(G+=Z,Z===c){let a=0;for(let m=d-1;m>=0&&e[m]==="\\";m--)a++;a%2===0&&(c=null)}continue}if(Z==='"'||Z==="'"){c=Z,G+=Z;continue}if(Z in S2){t.push(S2[Z]),G+=Z;continue}if(t.length>0){let a=t[t.length-1];Z===a&&t.pop(),G+=Z;continue}if(Z===I){let a=G.trim();a.length>0&&l.push(a),G="";continue}G+=Z}let b=G.trim();return b.length>0&&l.push(b),l}function Qy(e){return e.includes(`
`)?e.replace(/\r?\n/g,`
`):e.includes("\\n")?e.replace(/\\n/g,`
`):e}function Ry(e,I){if(!e||!I)return null;let l=e.metadataCache,G=e.metadataTypeManager??l?.app?.metadataTypeManager;if(!G||typeof G.getTypeInfo!="function")return null;let t=G.getTypeInfo(I),c=t?.expected?.type??t?.inferred?.type;return typeof c=="string"?c:null}function Ly(e){if(!e)return!1;let I=e.toLowerCase();return I==="list"||I==="tags"||I==="multitext"}function T2(e,I){let l=e.trim();if(!l)return;let G=Qy(l),t=I?.propertyType??Ry(I?.app,I?.propertyKey),c=Ly(t),d=c||t===null,a=G.split(/\n/).map(m=>m.trim()).filter(m=>m.length>0);if(d&&a.length>0&&a.every(m=>/^-\s+/.test(m)))return a.map(m=>m.replace(/^-[\s]*/,"").trim());if(G.startsWith("[")&&G.endsWith("]")||G.startsWith("{")&&G.endsWith("}")){if(t&&!c&&t!=="list")return;try{return JSON.parse(G)}catch{}}if(G.includes(",")&&d){let m=Xy(G);if(m.length>1)return m}}var q2="\0",nc=class{constructor(I){this.app=I;this.map=new Map;this.propertyTypeCache=new Map}maybeCollect(I){let{input:l,matchStart:G,matchEnd:t,rawValue:c,fallbackKey:b,featureEnabled:d}=I;if(!d)return;let Z=oN(l),a=j2(l,G,t,Z);if(!a.isInYaml)return;let m=l.slice(a.lineStart,a.lineEnd),n=m.trim(),W=m.match(/^\s*([^:]+):/),N=W?W[1].trim():b,Y=/^-\s*['"]?\{\{VALUE:[^}]+\}\}['"]?\s*$/i,s=null;if(a.isKeyValuePosition?s=[N]:Y.test(n)&&(s=this.findListParentPath(l,a.lineStart,a.baseIndent??"")),!s||s.length===0)return;let u=s[s.length-1],V=c;if(typeof c=="string"){let i=T2(c,this.buildParseOptions(u));i!==void 0&&(V=i)}if(!(typeof V!="string"&&(Array.isArray(V)||typeof V=="object"&&V!==null||typeof V=="number"||typeof V=="boolean"||V===null)))return;let r=s.join(q2);this.map.set(r,V)}drain(){let I=new Map(this.map);return this.map.clear(),I}buildParseOptions(I){return{propertyKey:I,propertyType:this.resolvePropertyType(I),app:this.app}}findListParentPath(I,l,G){let t=l-1,c=[],b=G.length;for(;t>=0;){let d=I.lastIndexOf(`
`,t),Z=d===-1?0:d+1,a=I.slice(Z,t+1),m=a.trim();if(m.length===0){t=Z-2;continue}if(m==="---"||m==="...")break;if(m.startsWith("-")){t=Z-2;continue}let n=a.match(/^(\s*)([^:\n]+):/);if(n){let N=(n[1]??"").length;if(N<b&&(c.unshift(n[2].trim()),b=N,b===0))break}t=Z-2}return c.length>0?c:null}resolvePropertyType(I){if(!this.app)return null;if(this.propertyTypeCache.has(I))return this.propertyTypeCache.get(I)??null;let l=this.app,G=l.metadataTypeManager??l.metadataCache?.app?.metadataTypeManager;if(!G||typeof G.getTypeInfo!="function")return this.propertyTypeCache.set(I,null),null;let t=G.getTypeInfo(I),c=t?.expected?.type??t?.inferred?.type??null,b=typeof c=="string"?c:null;return this.propertyTypeCache.set(I,b),b}};nc.PATH_SEPARATOR=q2;var P2=/[\u0000-\u001F]/u,_2=/[\\/:*?"<>|]/u,$2=/[. ]$/u,Fy=new Set(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]);function rN(e){return Fy.has(e.toUpperCase())}function wy(e){if(!e)return null;let I=e.trim().toLowerCase();switch(I){case"kebab":case"snake":case"camel":case"pascal":case"title":case"lower":case"upper":case"slug":return I;default:return null}}function pC(e){if(!e)return e;let I=e.toLowerCase();return I.slice(0,1).toUpperCase()+I.slice(1)}function VC(e){return/\p{L}/u.test(e)?/\p{Lu}/u.test(e)&&!/\p{Ll}/u.test(e):!1}function XN(e){return/\p{Lu}/u.test(e)&&/\p{Ll}/u.test(e)}function gy(e){return/^\p{Ll}/u.test(e)&&XN(e)}function vy(e){if(!e)return[];{let l=e.match(/^([\p{Ll}][\p{Lu}]{2,})([\p{N}]+)?$/u);if(l){let G=[l[1]];return l[2]&&G.push(l[2]),G}}if(/^[\p{Ll}][\p{Lu}][\p{Ll}]+(?:[\p{Lu}][\p{Ll}]+)*$/u.test(e))return[e];let I=e;return I=I.replace(/([\p{Lu}]+)([\p{Lu}][\p{Ll}])/gu,"$1 $2"),I=I.replace(/([\p{Ll}\p{N}])([\p{Lu}])/gu,"$1 $2"),I=I.replace(/([\p{L}])([\p{N}])/gu,"$1 $2"),I=I.replace(/([\p{N}])([\p{L}])/gu,"$1 $2"),I.trim().split(/\s+/u).map(l=>l.trim()).filter(Boolean)}function Hy(e){return e.split(/[^\p{L}\p{N}\p{M}]+/gu).filter(Boolean).flatMap(vy).filter(Boolean)}function QN(e,I){let l=wy(I);if(!l)return e;if(l==="lower")return e.toLowerCase();if(l==="upper")return e.toUpperCase();let G=Hy(e);if(G.length===0)return"";switch(l){case"kebab":return G.map(t=>t.toLowerCase()).join("-");case"snake":return G.map(t=>t.toLowerCase()).join("_");case"camel":{let[t,...c]=G,b=t?gy(t)?t:t.toLowerCase():"",d=c.map(Z=>VC(Z)||XN(Z)?Z:pC(Z));return[b,...d].join("")}case"pascal":return G.map(t=>VC(t)||XN(t)?t:pC(t)).join("");case"title":return G.map(t=>VC(t)||XN(t)?t:pC(t)).join(" ");case"slug":{let t=G.map(c=>c.toLowerCase()).join("-");return rN(t)?`${t}-`:t}default:return e}}function sn(e){return e.split("|")}function Ir(e){return e.startsWith("|")?e.slice(1):e}function un(e){let I=e.indexOf(":");if(I===-1)return null;let l=e.slice(0,I).trim().toLowerCase();if(!l)return null;let G=e.slice(I+1).trim();return{key:l,value:G}}var lr="",Gr=new Set(["label","default","custom","type","case","text"]);function yy(e,I,l){return l&&I?`${e}${lr}${I}`:e}function Cn(e){let I=e.indexOf(lr);return I===-1?e:e.slice(0,I)}function Jy(e,I){let l=I.toLowerCase(),G=null;for(let t of e.keys())if(t.toLowerCase()===l&&e.get(t)!==void 0){if(G)return null;G=t}return G}function RN(e,I){if(!I)return null;let l=[I],G=Cn(I);G!==I&&l.push(G);for(let t of l){if(e.has(t)&&e.get(t)!==void 0)return t;let c=Jy(e,t);if(c)return c}return null}function Ay(e){if(!e)return!0;let I=e.trim().toLowerCase();return!["false","no","0","off"].includes(I)}function Ey(e){let I=e.trim();if(!I)return!1;let l=un(I);return l?Gr.has(l.key):!1}function er(e,I){if(e.length===0)return{defaultValue:"",allowCustomInput:!1,usesOptions:!1};let l=e.some(Ey),G=I&&e.some(n=>n.trim().toLowerCase()==="custom");if(!(l||G))return{defaultValue:e.join("|").trim(),allowCustomInput:!1,usesOptions:!1};let c,b,d="",Z=!1,a,m;for(let n of e){let W=n.trim();if(!W)continue;if(I&&W.toLowerCase()==="custom"){Z=!0;continue}let N=un(W);if(!N)continue;let{key:Y,value:s}=N;if(Gr.has(Y))switch(Y){case"label":s&&(c=s);break;case"case":s&&(b=s);break;case"defaul
`,G++):c=="\\"?(l+="\\",G++):l+="\\":l+=t}return l}replaceRandomInString(I){let l=I;for(;Xi.test(l);){let G=Xi.exec(l);if(!G||!G[1])continue;let t=parseInt(G[1]);if(t<=0||t>100)throw new Error(`Random string length must be between 1 and 100. Got: ${t}`);let c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",b="";for(let d=0;d<t;d++)b+=c.charAt(Math.floor(Math.random()*c.length));l=l.replace(G[0],b)}return l}replaceTitleInString(I){let l=I,G=this.getVariableValue("title");for(;Vi.test(l);)l=this.replacer(l,Vi,G);return l}};FN.FIELD_VARIABLE_PREFIX="FIELD:";var dt=FN;var ky={title:"My Document Title",name:"Document Name",project:"Project Alpha",category:"Notes",author:"Your Name",status:"Draft",priority:"High",tag:"important",type:"meeting",client:"Acme Corp"},Oy={clipboard:"clipboard_content",date:"formatted_date",time:"current_time",random:"random_value",uuid:"unique_id"},Ky=[{pattern:/date|time/i,example:"2024-01-15"},{pattern:/title|name/i,example:"Example Title"},{pattern:/tag/i,example:"important"},{pattern:/category|type/i,example:"Notes"},{pattern:/author|user/i,example:"Your Name"},{pattern:/project/i,example:"Project Alpha"},{pattern:/status/i,example:"In Progress"},{pattern:/priority/i,example:"High"},{pattern:/number|count|id/i,example:"001"}];function wN(e){let I=e.toLowerCase(),l=ky[I];return l||`${e}_example`}function gN(e){return Oy[e.toLowerCase()]||`${e}_output`}function vN(e){for(let{pattern:I,example:l}of Ky)if(I.test(e))return l;return`${e}_value`}function HN(e){return e.length>0?`${e[0]} (${e.length} options)`:"suggestion_list"}function yN(e){return e?.path?e.basename:"current_file"}function JN(e){return e?.basename||"current_filename"}var Zt=class{static generate(I,l=new Date){let G=l.getFullYear(),t=(l.getMonth()+1).toString().padStart(2,"0"),c=l.getDate().toString().padStart(2,"0"),b=l.getHours().toString().padStart(2,"0"),d=l.getMinutes().toString().padStart(2,"0"),Z=l.getSeconds().toString().padStart(2,"0");return I.replace(/YYYY/g,G.toString()).replace(/YY/g,G.toString().slice(-2)).replace(/MMMM/g,this.MONTH_NAMES[l.getMonth()]).replace(/MMM/g,this.MONTH_NAMES_SHORT[l.getMonth()]).replace(/MM/g,t).replace(/M/g,(l.getMonth()+1).toString()).replace(/dddd/g,this.DAY_NAMES[l.getDay()]).replace(/ddd/g,this.DAY_NAMES_SHORT[l.getDay()]).replace(/DD/g,c).replace(/D/g,l.getDate().toString()).replace(/HH/g,b).replace(/H/g,l.getHours().toString()).replace(/mm/g,d).replace(/m/g,l.getMinutes().toString()).replace(/ss/g,Z).replace(/s/g,l.getSeconds().toString()).replace(/ww/g,this.getWeekNumber(l).toString().padStart(2,"0")).replace(/w/g,this.getWeekNumber(l).toString())}static getWeekNumber(I){let l=new Date(I.getFullYear(),0,1),G=(I.getTime()-l.getTime())/864e5;return Math.ceil((G+l.getDay()+1)/7)}};Zt.MONTH_NAMES=["January","February","March","April","May","June","July","August","September","October","November","December"],Zt.MONTH_NAMES_SHORT=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Zt.DAY_NAMES=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Zt.DAY_NAMES_SHORT=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];var gd=class extends dt{constructor(l,G,t){super(l);this.plugin=G;this.dateParser=t||Ee}async format(l){let G=l;try{G=await this.replaceGlobalVarInString(G),G=await this.replaceMacrosInString(G),G=this.replaceDateInString(G),G=this.replaceTimeInString(G),G=await this.replaceValueInString(G),G=await this.replaceSelectedInString(G),G=await this.replaceClipboardInString(G),G=await this.replaceDateVariableInString(G),G=await this.replaceVariableInString(G),G=await this.replaceFieldVarInString(G),G=await this.replaceCurrentFileNameInString(G),G=this.replaceRandomInString(G)}catch{return l}return G}async replaceGlobalVarInString(l){let G=l,t=0,c=new RegExp(Ic.source,"gi");for(;c.test(G)&&!(++t>5);)G=G.replace(c,(b,d)=>{let Z=String(d??"").trim();if(!Z)return b;let a=this.plugin?.settings?.globalVariables?.[Z];return typeof a=="string"?a:""});return G}promptForValue(l){return l||"user input"}getVariableValue(l){let G=this.variables.get(l)
<div class="qa-suggestion-content">
<span class="suggestion-main-text">${d}</span>
${a}
</div>
<span class="suggestion-sub-text">${Z}</span>
`,this.addHoverTooltip(G,t)}addHoverTooltip(l,G){let t,c=()=>{clearTimeout(t),document.querySelector(".qa-file-tooltip")?.remove()};l.addEventListener("mouseenter",()=>{c(),t=setTimeout(async()=>{let d=this.createTooltip(G);d&&(document.body.appendChild(d),this.positionTooltip(d,l))},200)}),l.addEventListener("mouseleave",c),l.addEventListener("blur",c);let b=()=>c();document.addEventListener("scroll",b,{passive:!0}),l._tooltipCleanup=()=>{c(),document.removeEventListener("scroll",b)}}createTooltip(l){let G=this.app.vault.getAbstractFileByPath(l.path);if(!G||!(G instanceof Gh.TFile))return null;let t=document.createElement("div");return t.className="qa-file-tooltip",t.innerHTML=`
<div class="qa-tooltip-header">${G.basename}</div>
<div class="qa-tooltip-content">
<div>Path: ${G.path}</div>
<div>Modified: ${new Date(G.stat.mtime).toLocaleDateString()}</div>
</div>
`,t}positionTooltip(l,G){let t=G.getBoundingClientRect();l.style.position="fixed",l.style.left=`${t.right+10}px`,l.style.top=`${t.top}px`,l.style.zIndex="1000"}close(){document.querySelectorAll(".qaFileSuggestionItem").forEach(t=>{let c=t;c._tooltipCleanup&&c._tooltipCleanup()}),document.querySelectorAll(".qa-file-tooltip").forEach(t=>t.remove()),super.close()}async selectSuggestion(l){if(this.inputEl.selectionStart===null)return;let G=this.inputEl.selectionStart,t=this.lastInput.length,c=this.inputEl.value,b=0,d=this.inputEl.value.slice(G-this.lastInput.length-3,G-this.lastInput.length)==="![[";if(l.matchType==="unresolved")b=this.makeLinkManually(c,l.displayText.replace(/.md$/,""),G,t);else if(l.matchType==="heading"||l.matchType==="block"){let Z=l.displayText;b=this.makeLinkManually(c,Z,G,t)}else if(d)b=this.makeLinkManually(c,l.displayText,G,t);else{let Z=this.app.vault.getAbstractFileByPath(l.file.path);if(Z instanceof Gh.TFile){let a=l.matchType==="alias"?l.displayText:void 0;b=this.makeLinkObsidianMethod(Z,c,G,t,a)}else b=this.makeLinkManually(c,l.displayText,G,t)}this.inputEl.trigger("input"),this.close(),this.inputEl.setSelectionRange(b,b)}makeLinkObsidianMethod(l,G,t,c,b){let d=this.app.vault.getAbstractFileByPath(l.path),Z=this.app.fileManager.generateMarkdownLink(d,this.getSourcePath(),"",b??"");return this.inputEl.value=this.getNewInputValueForFileLink(G,Z,t,c),t-c+Z.length+2}makeLinkManually(l,G,t,c){return this.inputEl.value=this.getNewInputValueForFileName(l,G,t,c),t-c+G.length+2}getNewInputValueForFileLink(l,G,t,c){return`${l.substr(0,t-c-2)}${G}${l.substr(t)}`}getNewInputValueForFileName(l,G,t,c){return`${l.substr(0,t-c)}${G}]]${l.substr(t)}`}};var Kd=class extends lG{constructor(l,G){super(l,G);this.app=l;this.inputEl=G;this.lastInput="";this.lastInputStart=0;this.lastInputLength=0;this.refreshTagIndex(),$I.instance.registerEvent(this.app.metadataCache.on("resolved",()=>this.refreshTagIndex()))}refreshTagIndex(){let l=this.app.metadataCache.getTags(),G=Object.keys(l);this.tagSet=new Set(G),this.sortedTags=G.sort((t,c)=>t.length!==c.length?t.length-c.length:t.localeCompare(c)),this.fuse=new UG(this.sortedTags,{threshold:.4,includeScore:!0,keys:[""]})}getSuggestions(l){if(this.inputEl.selectionStart===null)return[];let G=this.inputEl.selectionStart,t=l.slice(0,G),c=Ep.exec(t);if(!c)return[];let b=t.lastIndexOf("[[");if(c.index===void 0)return[];if(b!==-1&&b<c.index)return[];let d=c[1];this.lastInput=d,this.lastInputStart=c.index,this.lastInputLength=c[0].length;let Z=this.sortedTags.filter(W=>W.toLowerCase().startsWith(d.toLowerCase())).slice(0,5),a=this.fuse.search(d).filter(W=>W.score!==void 0&&W.score<.8).map(W=>W.item).slice(0,10),m=new Set(Z),n=[...Z];for(let W of a)!m.has(W)&&n.length<15&&(n.push(W),m.add(W));return n}renderSuggestion(l,G){this.renderMatch(G,l,this.lastInput)}selectSuggestion(l){let G=this.inputEl;if(G.selectionStart===null)return;let t=this.lastInputStart,c=t+this.lastInputLength,b=l.startsWith("#")?l:`#${l}`;zN(G,t,c,b,{fromCompletion:!0}),this.close()}};var xd=class e{constructor(){this.drafts=new Map;this.MAX_ENTRIES=100}static getInstance(){return e.instance||(e.instance=new e),e.instance}makeKey(I){return JSON.stringify({v:1,kind:I.kind,header:I.header,placeholder:I.placeholder??"",linkSourcePath:I.linkSourcePath??""})}get(I){let l=this.drafts.get(I);if(l)return l.timestamp=Date.now(),l.value}set(I,l){this.drafts.size>=this.MAX_ENTRIES&&!this.drafts.has(I)&&this.evictOldest(1),this.drafts.set(I,{value:l,timestamp:Date.now()})}clear(I){this.drafts.delete(I)}clearAll(){this.drafts.clear()}evictOldest(I){let l=Array.from(this.drafts.entries()).sort(([,G],[,t])=>G.timestamp-t.timestamp).slice(0,I);for(let[G]of l)this.drafts.delete(G)}};var Ud=class{constructor(I,l){this.store=xd.getInstance();this.initialValue="";this.didChange=!1;this.draftKey=this.store.makeKey(I),this.shouldPersist=l??(()=>P.getState().persistInputPromptDrafts)}hydrate(I){return this.initialValue=I,this.shouldPersist()?this.store.get(this.draftKey)??I:I}markChanged(){this.didChange=!0}persist(I,l){if(this.s
`).filter(Boolean).reduce((G,t)=>{let[c,b,...d]=t.split(" "),Z=Number.parseInt(b,10);return d.forEach((a,m)=>G[a]=Z+m),G},{});for(let[G,t]of Object.entries(l)){let c=qr.default.toByteArray(G);this.rankMap.set(c.join(","),t),this.textMap.set(t,c)}this.specialTokens={...e.special_tokens,...I},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((G,[t,c])=>(G[c]=this.textEncoder.encode(t),G),{})}encode(e,I=[],l="all"){let G=new RegExp(this.patStr,"ug"),t=ch.specialTokenRegex(Object.keys(this.specialTokens)),c=[],b=new Set(I==="all"?Object.keys(this.specialTokens):I),d=new Set(l==="all"?Object.keys(this.specialTokens).filter(a=>!b.has(a)):l);if(d.size>0){let a=ch.specialTokenRegex([...d]),m=e.match(a);if(m!=null)throw new Error(`The text contains a special token that is not allowed: ${m[0]}`)}let Z=0;for(;;){let a=null,m=Z;for(;t.lastIndex=m,a=t.exec(e),!(a==null||b.has(a[0]));)m=a.index+1;let n=a?.index??e.length;for(let N of e.substring(Z,n).matchAll(G)){let Y=this.textEncoder.encode(N[0]),s=this.rankMap.get(Y.join(","));if(s!=null){c.push(s);continue}c.push(...Y5(Y,this.rankMap))}if(a==null)break;let W=this.specialTokens[a[0]];c.push(W),Z=a.index+a[0].length}return c}decode(e){let I=[],l=0;for(let c=0;c<e.length;++c){let b=e[c],d=this.textMap.get(b)??this.inverseSpecialTokens[b];d!=null&&(I.push(d),l+=d.length)}let G=new Uint8Array(l),t=0;for(let c of I)G.set(c,t),t+=c.length;return this.textDecoder.decode(G)}},lY=ch;W5(lY,"specialTokenRegex",e=>new RegExp(e.map(I=>s5(I)).join("|"),"g"));function bh(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 tY(e){if(e){let I=new tX.Notice(eX("starting",""),1e6);return{setMessage:(l,G)=>{I.setMessage(eX(l,G))},hide:()=>I.hide()}}return{setMessage:()=>{},hide:()=>{}}}var cX={cl100k_base:Pr,o200k_base:_r},bX=new Map;function o5(e){let I=e in cX?e:"cl100k_base",l=bX.get(I);if(l)return l;let G=new lY(cX[I]);return bX.set(I,G),G}var $G=(e,I)=>{let l="cl100k_base";try{l=bh(I.name)}catch{l="cl100k_base"}return(l==="p50k_base"||l==="p50k_edit"||l==="r50k_base"||l==="gpt2")&&(l="cl100k_base"),o5(l).encode(e).length},dX=25,he=[];function ah(e){return{...e,modelOptions:{...e.modelOptions},usage:e.usage?{...e.usage}:void 0}}function GX(e){let I=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,l=Date.now();return he.push({...e,modelOptions:{...e.modelOptions??{}},id:I,createdAt:l,status:"pending"}),mX(),I}function dh(e,I){let l=he.find(G=>G.id===e);l&&(l.status=I.status,l.durationMs=I.durationMs,l.usage=I.usage,l.errorMessage=I.errorMessage,mX())}function aX(e=10){Number.isFinite(e)||(e=10);let I=Math.floor(e);return I<=0?[]:he.slice(-I).map(ah).reverse()}function mX(){if(he.length<=dX)return;let e=he.length-dX;for(;e>0;){let I=he.findIndex(l=>l.status!=="pending");if(I===-1)break;he.splice(I,1),e-=1}}function nX(e){let I=he.find(l=>l.id===e);return I?ah(I):null}function WX(){let e=he[he.length-1];return e?ah(e):null}function NX(){he.splice(0,he.length)}async function r5(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 X5(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)}_G(G,"Prompt template does not exist");let t=G.path,c=e.vault.getAbstractFileByPath(t);_G(c instanceof ZX.TFile,`${t} is not a file`);let b=await e.vault.cachedRead(c);return[G.basename,b]}async function YX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=tY(I.showAssistantMessages);try{let{apiKey:t,model:c,outputVariableName:b,promptTemplate:d,systemPrompt:Z,promptTemplateFolder:a}=I,m=mc(e,a),[n,W]=await X5(e,d,m);G.setMessage("waiting","QuickAdd is formatting the prompt template.");let N=await l(W),Y=["prompting",`Using prompt template "${n}".`];G.setMessage(Y[0],Y[1]);let u=eY(e,t,c,Z,I.modelOptions)(N),C=(await mh(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=("> "+C).replace(/\n/g,`
> `),i={[b]:C,[`${b}-quoted`]:r};return setTimeout(()=>G.hide(),5e3),i}catch(t){throw G.setMessage("dead",t.message),setTimeout(()=>G.hide(),5e3),pl(t)?new jI("Input cancelled by user"):t}}async function mh(e,I,l,G){let t=Date.now();return await r5(()=>l(Date.now()-t),e,I),G(Date.now()-t),await e}async function sX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=tY(I.showAssistantMessages);try{let{apiKey:t,model:c,outputVariableName:b,systemPrompt:d,prompt:Z,modelOptions:a}=I;G.setMessage("waiting","QuickAdd is formatting the prompt template.");let m=await l(Z),n=["prompting","Using custom prompt."];G.setMessage(n[0],n[1]);let N=eY(e,t,c,d,a)(m),s=(await mh(N,100,C=>{G.setMessage(n[0],`${n[1]} (${(C/1e3).toFixed(2)}s)`)},C=>{G.setMessage("finished",`Took ${(C/1e3).toFixed(2)}s.`)})).content,u=("> "+s).replace(/\n/g,`
> `),V={[b]:s,[`${b}-quoted`]:u};return setTimeout(()=>G.hide(),5e3),V}catch(t){throw G.setMessage("dead",t.message),setTimeout(()=>G.hide(),5e3),t}}var Zh=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(t){G(t)}}),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 iX(e,I,l){if(P.getState().disableOnlineFeatures)throw new Error("Blocking request to OpenAI: Online features are disabled in settings.");let G=tY(I.showAssistantMessages);try{let{apiKey:t,model:c,outputVariableName:b,systemPrompt:d,promptTemplate:Z,text:a,modelOptions:m}=I;G.setMessage("chunking","Creating prompt chunks with text and prompt template");let n=I.chunkSeparator||/\n/g,W=a.split(n),N=$G(d,c),Y=await l(Z,{chunk:" "}),s=$G(Y,c),u=lX(c.name)/2-N,V=I.shouldMerge??!0,C=[],r=u-s;if(V){let O=[],K="",J=0;for(let H of W){let v=$G(H,c)+1;if(v>r)throw new Error(`The chunk "${H.slice(0,25)}..." is too large to fit in a single prompt.`);J+v<r?(K+=H,J+=v):(O.push(K),K=H,J=v)}K!==""&&O.push(K);for(let H of O){let v=await l(Z,{chunk:H});C.push(v)}}else for(let O of W){let K=$G(O,c);if(K>u)throw new Error(`Chunk size (${K}) is larger than the maximum chunk size (${u}). Please check your chunk separator.`);let J=await l(Z,{chunk:O});C.push(J)}let i=eY(e,t,c,d,m),Q=["prompting",`${C.length} prompts being sent.`];G.setMessage(Q[0],Q[1]);let R=new Zh(5,1e3*30),h=Promise.all(C.map(O=>R.add(()=>i(O)))),E=(await mh(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(t){throw G.setMessage("dead",t.message),setTimeout(()=>G.hide(),5e3),t}}var Q5="quickadd-ai";function R5(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function L5(e){let I=e.name?.trim()||"provider";return`${Q5}-${R5(I)}`}async function Bt(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(`Failed to read SecretStorage entry "${l}": ${G.message??G}`)}return I.apiKey??""}async function uX(e,I,l){let G=l?.trim();if(!G||!e?.secretStorage?.getSecret||!e.secretStorage?.setSecret)return null;let t=L5(I),c=t,b=1;for(;;){let d=null;try{d=await Promise.resolve(e.secretStorage.getSecret(c))}catch(Z){x.logWarning(`Failed to read SecretStorage entry "${c}": ${Z.message??Z}`)}if(!d)break;if(d===G)return c;b+=1,c=`${t}-${b}`}try{return await Promise.resolve(e.secretStorage.setSecret(c,G)),c}catch(d){return x.logWarning(`Failed to write SecretStorage entry "${c}": ${d.message??d}`),null}}var Dd=require("obsidian"),Fn=class e extends Dd.Modal{constructor(l,G,t=[]){super(l);this.items=G;this.selectedItems=t;this._selectedItems=[...t],this.promise=new Promise((c,b)=>{this.resolvePromise=c,this.rejectPromise=b}),this.display(),this.open()}static Open(l,G,t){return new e(l,G,t).promise}display(){this.contentEl.empty(),this.containerEl.addClass("quickAddModal","checkboxPrompt"),this.addCheckboxRows(),this.addSubmitButton()}onClose(){super.onClose(),this.resolved||this.rejectPromise("no input given.")}addCheckboxRows(){let l=this.contentEl.createDiv("checkboxRowContainer");this.items.forEach(G=>this.addCheckboxRow(G,l))}addCheckboxRow(l,G){let t=G.createDiv("checkboxRow");t.createEl("span",{text:l}),new Dd.ToggleComponent(t).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 Dd.ButtonComponent(l).setButtonText("Submit").setCta().onClick(t=>{this.resolved=!0,this.resolvePromise(this._selectedItems),this.close()})}};var cY=require("obsidian"),wn=class e extends cY.Modal{constructor(l,G,t){super(l);this.header=G;this.text=t;this.waitForClose=new Promise(c=>{this.resolvePromise=c}),this.open(),this.display()}static Show(l,G,t){return new e(l,G,t).waitForClose}display(){this.contentEl.empty(),this.titleEl.textContent=this.header,String.isString(this.text)?this.contentEl.createEl("p",{text:this.text}):Array.isArray(this.text)&&this.text.forEach(t=>this.contentEl.createEl("p",{text:t}));let l=this.contentEl.createDiv(),G=new cY.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 Md=require("obsidian");var sc=class e extends Md.Modal{constructor(l,G,t,c,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=t??"",this.description=d?.trim()||void 0,this.draftHandler=new Ud({kind:"multi",header:this.header,placeholder:this.placeholder,linkSourcePath:this.linkSourcePath}),this.input=this.draftHandler.hydrate(c??""),this.waitForClose=new Promise((Z,a)=>{this.resolvePromise=Z,this.rejectPromise=a}),this.display(),this.open(),this.fileSuggester=new Od(l,this.inputComponent.inputEl,{sourcePath:this.linkSourcePath}),this.tagSuggester=new Kd(l,this.inputComponent.inputEl)}static Prompt(l,G,t,c,b){return new e(l,G,t,c,void 0,b).waitForClose}static PromptWithContext(l,G,t,c,b,d){return new e(l,G,t,c,b,d).waitForClose}display(){if(this.containerEl.addClass("quickAddModal","qaWideInputPrompt"),this.contentEl.empty(),this.titleEl.textContent=this.he
`,shouldMerge:d?.shouldMerge??!0},(C,r)=>{let i={...Z,...r};return n(C,i,!1)});return V?(d?.shouldAssignVariables&&Object.entries(V).forEach(([C,r])=>{G.variables.set(C,r)}),V):(cl(new Error("AI Assistant returned null"),"Chunked AI Prompt error"),{})},getModels:()=>Wt(),getMaxTokens:t=>{let c=xe(t);if(!c)throw new Error(`Model ${t} not found.`);return c.maxTokens},countTokens(t,c){return $G(t,c)},getRequestLogs(t=10){return aX(t)},getRequestLogById(t){return nX(t)},getLastRequestLog(){return WX()},clearRequestLogs(){NX()}},utility:{getClipboard:async()=>await navigator.clipboard.readText(),setClipboard:async t=>await navigator.clipboard.writeText(t),getSelection:()=>{let t=I.workspace.getActiveViewOfType(Sh.MarkdownView);return t?t.editor.getSelection()??"":""},getSelectedText:()=>{let t=I.workspace.getActiveViewOfType(Sh.MarkdownView);if(!t){cl(new Error("No active view"),"Could not get selected text");return}if(!t.editor.somethingSelected()){cl(new Error("No text selected"),"Could not get selected text");return}return t.editor.getSelection()}},date:{now:(t,c)=>Et({format:t,offset:c}),tomorrow:t=>Et({format:t,offset:1}),yesterday:t=>Et({format:t,offset:-1})},fieldSuggestions:{getFieldValues:async(t,c)=>{let b=c?.includeInlineCodeBlocks?.map(m=>m.trim().toLowerCase()).filter(m=>m.length>0),d={folder:c?.folder,tags:c?.tags,inline:c?.includeInline??!1,inlineCodeBlocks:b},Z=I.vault.getMarkdownFiles();Z=HY.filterFiles(Z,d,m=>I.metadataCache.getFileCache(m));let a=new Set;for(let m of Z){let W=I.metadataCache.getFileCache(m)?.frontmatter?.[t];if(W!=null){if(Array.isArray(W))W.forEach(N=>{let Y=N.toString().trim();Y&&a.add(Y)});else if(typeof W!="object"){let N=W.toString().trim();N&&a.add(N)}}if(d.inline){let N=await I.vault.read(m);tZ.getFieldValues(N,t,{includeCodeBlocks:b}).forEach(s=>a.add(s))}}return Array.from(a).sort()},clearCache:t=>{it.getInstance().clear(t)}}}}static async inputPrompt(I,l,G,t){try{return await ol.Prompt(I,l,G,t)}catch(c){Vc(c);return}}static async datePrompt(I,l,G){try{let t=await rb.Prompt(I,l,G?.placeholder,G?.defaultValue,G?.dateFormat);if(t&&t.startsWith("@date:")){let c=t.slice(6);return(G?.dateFormat?Yc(c,G.dateFormat):null)??c}return t}catch(t){Vc(t);return}}static async wideInputPrompt(I,l,G,t){try{return await sc.Prompt(I,l,G,t)}catch(c){Vc(c);return}}static async yesNoPrompt(I,l,G){try{return await pe.Prompt(I,l,G)}catch(t){Vc(t);return}}static async infoDialog(I,l,G){try{return await wn.Show(I,l,G)}catch(t){Vc(t);return}}static async suggester(I,l,G,t,c=!1,b){try{let d;return typeof l=="function"?d=G.map(l):d=l,d=d.map(Z=>FG(Z)),c?await aG.Suggest(I,d,G,{...t?{placeholder:t}:{},...b?.renderItem?{renderItem:b.renderItem}:{}}):await CG.Suggest(I,d,G,t,b?.renderItem)}catch(d){Vc(d);return}}static async checkboxPrompt(I,l,G){try{return await Fn.Open(I,l,G)}catch(t){Vc(t);return}}};function Vc(e){if(e instanceof jI)throw e;if(pl(e))throw new jI("Input cancelled by user")}var dZ=class extends vd{};var mG=[];for(let e=0;e<256;++e)mG.push((e+256).toString(16).slice(1));function $Q(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 Th,kA=new Uint8Array(16);function qh(){if(!Th){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Th=crypto.getRandomValues.bind(crypto)}return Th(kA)}var OA=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ph={randomUUID:OA};function KA(e,I,l){if(Ph.randomUUID&&!I&&!e)return Ph.randomUUID();e=e||{};let G=e.random??e.rng?.()??qh();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 t=0;t<16;++t)I[l+t]=G[t];return I}return $Q(G)}var hG=KA;var GG=class{constructor(I,l){this.name=I,this.type=
`)}var NR=require("obsidian");function CZ(e,I){if(I.options)for(let l in I.options){let G=e[l]===void 0,t="defaultValue"in I.options[l]&&I.options[l].defaultValue!==void 0;G&&t&&(e[l]=I.options[l].defaultValue)}}var xA=["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","contains","notContains"],eR=new Set(["true","1","yes","on"]),tR=new Set(["false","0","no","off"]);function oc(e){return xA.includes(e)}function cR(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 bR(e){if(!oc(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 eR.has(l)?!0:tR.has(l)?!1:!!I}case"string":default:return I}}function $h(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(eR.has(l))return!0;if(tR.has(l))return!1}return!!e;case"string":default:return e==null?"":String(e)}}function UA(e){if(!oc(e.operator))return"";let I=e.expectedValue??"";return I.length===0?"(empty)":e.valueType==="string"?`"${I}"`:I}function zA(e){let I=e.variableName?`$${e.variableName}`:"(missing variable)",l=DA(e.operator),G=oc(e.operator)?` ${UA(e)}`:"";return`${I} ${l}${G}`.trim()}function BA(e){let I=e.exportName?`::${e.exportName}`:"";return`script ${e.scriptPath}${I}`}function hZ(e){return e.mode==="variable"?zA(e):BA(e)}function DA(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 ZR(e,I){return e.mode==="script"?await I.evaluateScriptCondition(e):MA(e,I.variables)}function MA(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(`Conditional command skipped: Variable '${l}' is not defined.`),!1;let G=I[l];switch(e.operator){case"isTruthy":return!!G;case"isFalsy":return!G}if(oc(e.operator)){let t=bR(e);return t===void 0?(x.logWarning(`Conditional command: Operator '${e.operator}' requires a comparison value.`),!1):e.operator==="contains"?dR(G,t,e):e.operator==="notContains"?!dR(G,t,e):fA(G,t,e)}return!1}function dR(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=>$h(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 fA(e,I,l){let G=$h(e,l.valueType);switch(l.operator){case"equals":return G===I;case"notEquals":return G!==I;case"lessThan":return yY(G,I,(t,c)=>t<c);case"lessThanOrEqual":return yY(G,I,(t,c)=>t<=c);case"greaterThan":return yY(G,I,(t,c)=>t>c);case"greaterThanOrEqual":return yY(G,I,(t,c)=>t>=c);default:return!1}}function yY(e,I,l){let G=Number(e),t=Number(I);return Number.isNaN(G)||Number.isNaN(t)?(x.logWarning("Conditional command numeric comparison failed: non-numeric value encountered."),!1):l(G,t)}var aR=require("obsidian");function rc(e,{logPrefix:I,noticePrefix:l=I,defaultReason:G}){if(!(e instanceof jI))return!1;let t=typeof e.message=="string"&&e.message.trim().length>0?e.message:G;return x.logMessage(`${I}: ${t}`),(!(typeof e.message=="string"&&e.message.toLowerCase().includes("cancelled by user"))||P.getState().showInputCancellationNotification)&&new aR.Notice(`${l}: ${t}`
${AI}
\\end{${e}}${AI}`}var YR=[...TA,...qA.map(PA)];var sR=require("obsidian");var _A=new RegExp(/\\([a-z{}A-Z0-9]*)$/),EY=class extends lG{constructor(l){super($I.instance.app,l);this.inputEl=l;this.lastInput="";this.symbols=Object.assign([],YR),this.elementsRendered=this.symbols.reduce((G,t)=>{try{G[t.toString()]=(0,sR.renderMath)(t,!0)}catch{}return G},{})}getSuggestions(l){if(this.inputEl.selectionStart===null)return[];let G=this.inputEl.selectionStart,t=l.substr(0,G),c=t.lastIndexOf("\\"),b=t.substr(c),d=_A.exec(b),Z=[];return d&&(this.lastInput=d[1],Z=this.symbols.filter(n=>n.toLowerCase().contains(this.lastInput))),new UG(Z,{findAllMatches:!0,threshold:.8}).search(this.lastInput).map(n=>n.item)}renderSuggestion(l,G){l&&(G.setText(l),G.append(this.elementsRendered[l]))}selectSuggestion(l){if(this.inputEl.selectionStart===null)return;let G=this.inputEl.selectionStart,t=this.lastInput.length,c=this.inputEl.value,b=0,d=l.replace(/\\\\/g,"\\");if(this.inputEl.value=`${c.substr(0,G-t-1)}${d}${c.substr(G)}`,b=G-t+l.length-1,this.inputEl.trigger("input"),this.close(),l.contains(AI)){let Z=this.inputEl.value.indexOf(AI);this.inputEl.value=this.inputEl.value.replace(AI,""),this.inputEl.setSelectionRange(Z,Z)}else this.inputEl.setSelectionRange(b,b)}};var kY=class e extends BG.Modal{constructor(){super($I.instance.app);this.didSubmit=!1;this.keybindListener=l=>{l.ctrlKey&&l.key==="Enter"&&this.submit(),l.key==="Tab"&&(l.preventDefault(),this.cursorToGoTo())};this.submitClickCallback=l=>this.submit();this.cancelClickCallback=l=>this.cancel();this.open(),this.display(),this.waitForClose=new Promise((l,G)=>{this.resolvePromise=l,this.rejectPromise=G}),new EY(this.inputEl),this.inputEl.focus(),this.inputEl.select()}static Prompt(){return new e().waitForClose}display(){this.containerEl.addClass("quickAddModal","qaMathModal"),this.contentEl.empty();let l=this.contentEl.createDiv();l.className="math math-block is-loaded";let G=new BG.TextAreaComponent(this.contentEl);G.inputEl.style.width="100%",G.inputEl.style.height="10rem",this.inputEl=G.inputEl,G.onChange((0,BG.debounce)(async t=>await this.mathjaxLoop(l,t),50)),G.inputEl.addEventListener("keydown",this.keybindListener),this.createButtonBar(this.contentEl.createDiv())}async onOpen(){super.onOpen(),await(0,BG.loadMathJax)()}async mathjaxLoop(l,G){let t=(0,BG.renderMath)(G,!0);await(0,BG.finishRenderMath)(),l.empty(),l.append(t)}cursorToGoTo(){if(this.inputEl.value.contains(AI)){let l=this.inputEl.value.indexOf(AI);this.inputEl.value=this.inputEl.value.replace(AI,""),this.inputEl.setSelectionRange(l,l)}}createButton(l,G,t){let c=new BG.ButtonComponent(l);return c.setButtonText(G).onClick(t),c}createButtonBar(l){let G=l.createDiv();this.createButton(G,"Ok",this.submitClickCallback).setCta().buttonEl.style.marginRight="0",this.createButton(G,"Cancel",this.cancelClickCallback),G.style.display="flex",G.style.flexDirection="row-reverse",G.style.justifyContent="flex-start",G.style.marginTop="1rem",G.style.gap="0.5rem"}removeInputListeners(){this.inputEl.removeEventListener("keydown",this.keybindListener)}resolveInput(){let l=this.inputEl.value.replace("\\n","\\\\n").replace(new RegExp(AI,"g"),"");this.didSubmit?this.resolvePromise(l):this.rejectPromise("No input given.")}submit(){this.didSubmit=!0,this.close()}cancel(){this.close()}onClose(){super.onClose(),this.resolveInput(),this.removeInputListeners()}};var Me=class extends dt{constructor(l,G,t,c){super(l);this.app=l;this.plugin=G;this.choiceExecutor=t;this.dateParser=c||Ee,t&&(this.variables=t?.variables)}async format(l){let G=l;return G=await this.replaceInlineJavascriptInString(G),G=await this.replaceMacrosInString(G),G=await this.replaceTemplateInString(G),G=await this.replaceGlobalVarInString(G),G=this.replaceDateInString(G),G=this.replaceTimeInString(G),G=await this.replaceValueInString(G),G=await this.replaceSelectedInString(G),G=await this.replaceClipboardInString(G),G=await this.replaceDateVariableInString(G),G=await this.replaceVariableInString(G),G=await this.replaceFieldVarInString(G),G=await this.replaceMathValueInString(G)
Suggested values for ${G}: ${a.slice(0,3).join(", ")}`)}return await ol.PromptWithContext(this.app,`Enter value for ${G}`,Z,void 0,this.getLinkSourcePath()??void 0)}let d=`Enter value for ${G}`;return b&&(d=`Enter value for ${G} (default: ${t.defaultValue})`),await aG.Suggest(this.app,c,c,{placeholder:d})}catch(G){throw pl(G)?new jI("Input cancelled by user"):G}}generateCacheKey(l){return FY(l)}async getMacroValue(l,G){let t=new AY(this.app,this.plugin,this.plugin.settings.choices,this.choiceExecutor,this.variables),c=await t.runAndGetOutput(l,G)??"";return t.getVariables().forEach((b,d)=>{this.variables.set(d,b)}),c}async getTemplateContent(l){return await new Xc(this.app,this.plugin,l,this.choiceExecutor).run()}async getSelectedText(){let l=this.app.workspace.getActiveViewOfType(iR.MarkdownView);return l?l.editor.getSelection():""}async getClipboardContent(){try{return await navigator.clipboard.readText()}catch{return""}}isTemplatePropertyTypesEnabled(){return this.plugin.settings.enableTemplatePropertyTypes}async replaceInlineJavascriptInString(l){let G=l;for(;$Z.test(G);){let c=$Z.exec(G)?.at(1)?.trim();if(c){let b=new JY(this.app,this.plugin,this.choiceExecutor,this.variables),d=await b.runAndGetOutput(c);for(let Z in b.params.variables)this.variables.set(Z,b.params.variables[Z]);G=typeof d=="string"?this.replacer(G,$Z,d):this.replacer(G,$Z,"")}}return G}async collectValuesManually(l,G){return await wY(this.app,l,G)}};var VZ=require("obsidian");var uR=require("obsidian");function Dn(e){return((0,uR.normalizePath)(e).split("/").pop()??"").replace(/\.(md|canvas|base)$/i,"")}var Ct=class extends Error{constructor(I){super(I),this.name="InvalidFolderPathError"}};function I0(e){return e instanceof jI||!!e&&typeof e=="object"&&"name"in e&&e.name==="MacroAbortError"}var oZ=class extends vd{constructor(l,G,t){super(l);this.plugin=G;this.templater=hC(l),this.formatter=new Me(l,G,t)}async getOrCreateFolder(l,G={}){let t=this.buildFolderSelectionContext(l,G);if(!this.shouldPromptForFolder(t))return await this.handleSingleSelection(t);let c=await this.promptUntilAllowed(t);return c.isEmpty?"":c.resolved}buildFolderSelectionContext(l,G){let t=G.allowCreate??!1,c=G.allowedRoots?.map(n=>this.normalizeFolderPath(n))??[],{items:b,displayItems:d,normalizedItems:Z,canonicalByNormalized:a,displayByNormalized:m}=this.buildFolderSuggestions(l,G.topItems??[],c.length>0?c:void 0);return{items:b,displayItems:d,normalizedItems:Z,canonicalByNormalized:a,displayByNormalized:m,existingSet:new Set(Z),allowCreate:t,allowedRoots:c,placeholder:G.placeholder}}shouldPromptForFolder(l){return l.items.length>1||l.allowCreate&&l.items.length===0}async promptForFolder(l){try{return l.allowCreate?await aG.Suggest(this.app,l.displayItems,l.items,{placeholder:l.placeholder??"Choose a folder or type to create one",renderItem:(G,t)=>{this.renderFolderSuggestion(G,t,l.existingSet,l.displayByNormalized)}}):await CG.Suggest(this.app,l.displayItems,l.items,l.placeholder)}catch(G){throw pl(G)?new jI("Input cancelled by user"):G}}async resolveSelection(l,G){let t=this.normalizeFolderPath(l),c=t.length===0,b=G.canonicalByNormalized.get(t),d=b??t,Z=c?!1:b!==void 0||await this.app.vault.adapter.exists(d),a=G.allowedRoots.length===0?!0:this.isPathAllowed(c?"":d,G.allowedRoots);return{raw:l,normalized:t,resolved:d,exists:Z,isAllowed:a,isEmpty:c}}async promptUntilAllowed(l){for(;;){let G=await this.promptForFolder(l),t=await this.resolveSelection(G,l);if(t.isEmpty){if(!t.isAllowed){this.showFolderNotAllowedNotice(l.allowedRoots);continue}return t}if(!t.isAllowed){this.showFolderNotAllowedNotice(l.allowedRoots);continue}try{this.validateFolderPath(t.resolved)}catch(c){if(c instanceof Ct){new VZ.Notice(c.message);continue}throw c}return await this.ensureFolderExists(t),t}}async ensureFolderExists(l){l.isEmpty||l.exists||await this.createFolder(l.resolved)}async handleSingleSelection(l){let G=l.items[0]??"",t=await this.resolveSelection(G,l);if(t.isEmpty)return"";if(!t.isAllowed)throw this.showFolderNotAllowedNotice(l.allowedRoots),new jI("Selected folder not allowed.");if
${Z}`:`${Z}
${d}`;return await this.app.vault.modify(l,a),l}catch(c){if(I0(c))throw c;return cl(c,"Could not append to file with template"),null}}async getTemplateContent(l){let G=this.stripLeadingSlash(l);!JG.test(l)&&!AG.test(l)&&!Gt.test(l)&&(G+=".md");let t=this.app.vault.getAbstractFileByPath(G);if(!(t instanceof VZ.TFile))throw new Error(`Template file not found at path "${G}".`);return await this.app.vault.cachedRead(t)}};var Xc=class extends oZ{constructor(l,G,t,c){super(l,G,c);this.templatePath=t}async run(){let l=await this.getTemplateContent(this.templatePath);return l||x.logError(`Template ${this.templatePath} not found.`),l=await this.formatter.formatFileContent(l),l}getAndClearTemplatePropertyVars(){return this.formatter.getAndClearTemplatePropertyVars()}};var wG=class extends dt{constructor(l,G,t){super(l);this.plugin=G;this.dateParser=t||Ee}async format(l){let G=l;try{G=await this.replaceGlobalVarInString(G),G=this.replaceDateInString(G),G=this.replaceTimeInString(G),G=await this.replaceValueInString(G),G=await this.replaceSelectedInString(G),G=await this.replaceClipboardInString(G),G=await this.replaceDateVariableInString(G),G=await this.replaceVariableInString(G),G=await this.replaceLinkToCurrentFileInString(G),G=await this.replaceCurrentFileNameInString(G),G=await this.replaceMacrosInString(G),G=await this.replaceTemplateInString(G),G=await this.replaceFieldVarInString(G),G=this.replaceRandomInString(G),G=this.replaceLinebreakInString(G)}catch{return l}return G}async replaceGlobalVarInString(l){let G=l,t=0,c=new RegExp(Ic.source,"gi");for(;c.test(G)&&!(++t>5);)G=G.replace(c,(b,d)=>{let Z=String(d??"").trim();if(!Z)return b;let a=this.plugin?.settings?.globalVariables?.[Z];return typeof a=="string"?a:""});return G}promptForValue(l){return l||"user input"}getVariableValue(l){let G=this.variables.get(l);if(typeof G=="string")return G;let t=Cn(l);return wN(t)}getCurrentFileLink(){return this.app?yN(this.app.workspace.getActiveFile()):null}getCurrentFileName(){return this.app?JN(this.app.workspace.getActiveFile()):"current_filename"}suggestForValue(l,G=!1,t){return HN(t?.displayValues??l)}getMacroValue(l,G){return gN(l)}promptForMathValue(){return Promise.resolve("calculation_result")}promptForVariable(l,G){return Promise.resolve(vN(l))}async getTemplateContent(l){let G=this.app;if(!G)return`Template (app unavailable): ${l}`;try{return await new Xc(G,this.plugin,l,void 0).run()}catch{return`Template (not found): ${l}`}}async getSelectedText(){return"selected_text"}async getClipboardContent(){return"clipboard_content"}async suggestForField(l){return Promise.resolve(`${l}_field_value`)}async replaceDateVariableInString(l){let G=l;return G=G.replace(new RegExp(xc.source,"gi"),(t,c,b,d)=>{let Z=c?.trim(),a=b?.trim(),m=d?.trim();if(!Z||!a)return t;let n=new Date,W;try{W=Zt.generate(a,n)}catch{W=`[${a} format]`}return m&&(W+=` (default: ${m})`),W}),G}replaceRandomInString(l){let G=l;return G=G.replace(/{{RANDOM:(\d+)}}/gi,(t,c)=>{let b=parseInt(c);if(b<=0||b>100)return t;let d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Z="";for(let a=0;a<Math.min(b,8);a++)Z+=d.charAt(Math.floor(Math.random()*d.length));return b>8&&(Z+=`... (${b} chars)`),Z}),G}isTemplatePropertyTypesEnabled(){return!1}};var OY=require("obsidian");var pG=class extends lG{constructor(l,G,t,c=1/0){super(l,G);this.app=l;this.inputEl=G;this.items=t;this.maxSuggestions=c;this.items=t.map(b=>FG(b))}getSuggestions(l){let G=Ut(l).toLowerCase(),t=this.items.filter(b=>b.toLowerCase().includes(G));return t.length===0&&this.close(),t.slice(0,this.maxSuggestions)}selectSuggestion(l){this.inputEl.value=l,this.inputEl.trigger("input"),this.close()}renderSuggestion(l,G){if(!l)return;let t=OC(l),c=OC(this.getCurrentQuery());l.toLowerCase().endsWith(".md")&&c.toLowerCase().startsWith(`${t.toLowerCase()}.`)&&(c=t),this.renderMatch(G,t,c)}getCurrentQuery(){return this.inputEl.value}};function yb(e){let{app:I,parent:l,initialValue:G="",placeholder:t,required:c=!1,requiredMessage:b="This field is required",validator:d,suggestions:Z,maxSuggestions:a=1/0,attac
`).map(r=>r.trim()).filter(r=>r.length>0),u=this.truncatePickerText(s[0]??"(empty text card)",90),V=[`${s.length} line${s.length===1?"":"s"}`];m&&V.push(m);let C=V.join(" \xB7 ");return{id:Z.id,type:a,title:u,subtitle:C,searchText:`${Z.id} ${u} ${C}`.toLowerCase(),capturable:!0,capturableReason:""}}if(a==="file"){let Y=this.getCanvasNodeFilePath(Z.file),s=JG.test(Y),u=s?"":"Canvas file cards must link to markdown files (.md).",V=this.truncatePickerText(Y.split("/").pop()??Y,90),C=[this.truncatePickerText(Y,120)];m&&C.push(m),s||C.push("Not capturable in this version");let r=C.join(" \xB7 ");return{id:Z.id,type:a,title:V,subtitle:r,searchText:`${Z.id} ${V} ${r}`.toLowerCase(),capturable:s,capturableReason:u}}let W=`Unsupported node (${typeof Z.type=="string"&&Z.type.length>0?Z.type:"unknown"})`,N=m||"Type is not currently capturable";return{id:Z.id,type:a,title:W,subtitle:N,searchText:`${Z.id} ${W} ${N}`.toLowerCase(),capturable:!1,capturableReason:"This Canvas node type is not capturable."}}),d={text:0,file:1,other:2};return b.sort((Z,a)=>{let m=d[Z.type]-d[a.type];return m!==0?m:Z.title.localeCompare(a.title)})}catch{return[]}}getCanvasNodeFilePath(l){return typeof l=="string"?l:l&&typeof l=="object"&&"path"in l&&typeof l.path=="string"?l.path:"(missing file path)"}describeCanvasNodeCoordinates(l){return typeof l.x!="number"||typeof l.y!="number"||typeof l.width!="number"||typeof l.height!="number"?"":`${Math.round(l.x)},${Math.round(l.y)} \xB7 ${Math.round(l.width)}x${Math.round(l.height)}`}truncatePickerText(l,G){return l.length<=G?l:l.slice(0,G-1)+"\u2026"}addTaskSetting(){new EI.Setting(this.contentEl).setName("Task").setDesc("Formats the value as a task.").addToggle(G=>{G.setValue(this.choice.task),G.onChange(t=>this.choice.task=t)})}addAppendLinkSetting(){let l=ac(this.choice.appendLink),G=l.linkType??"link",t=l.enabled?l.requireActiveFile?"required":"optional":"disabled";new EI.Setting(this.contentEl).setName("Link to captured file").setDesc("Choose how QuickAdd should insert a link to the captured file in the current note.").addDropdown(b=>{b.addOption("required","Enabled (requires active file)"),b.addOption("optional","Enabled (skip if no active file)"),b.addOption("disabled","Disabled"),b.setValue(t),b.onChange(d=>{switch(d){case"disabled":this.choice.appendLink=!1;break;case"required":this.choice.appendLink={enabled:!0,placement:l.placement,requireActiveFile:!0,linkType:G};break;case"optional":this.choice.appendLink={enabled:!0,placement:l.placement,requireActiveFile:!1,linkType:G};break}this.reload()})}),t!=="disabled"&&(new EI.Setting(this.contentEl).setName("Link placement").setDesc("Where to place the link when appending").addDropdown(d=>{d.addOption("replaceSelection","Replace selection"),d.addOption("afterSelection","After selection"),d.addOption("endOfLine","End of line"),d.addOption("newLine","New line"),d.setValue(l.placement),d.onChange(Z=>{let a=this.choice.appendLink,m=typeof a=="boolean"?l.requireActiveFile:a.requireActiveFile,n=typeof a=="boolean"?G:a.linkType??G,W=At(Z)?n:"link";this.choice.appendLink={enabled:!0,placement:Z,requireActiveFile:m,linkType:W},this.reload()})}),At(l.placement)&&new EI.Setting(this.contentEl).setName("Link type").setDesc("Choose whether to insert a regular link or an embed when replacing the selection.").addDropdown(Z=>{Z.addOption("link","Link"),Z.addOption("embed","Embed"),Z.setValue(G),Z.onChange(a=>{let m=this.choice.appendLink,n=typeof m=="boolean"?l.requireActiveFile:m.requireActiveFile,W=typeof m=="boolean"?l.placement:m.placement;this.choice.appendLink={enabled:!0,placement:W,requireActiveFile:n,linkType:a}})}))}addWritePositionSetting(){let l=new EI.Setting(this.contentEl),G=!!this.choice?.captureToActiveFile;this.choice.activeFileWritePosition||(this.choice.activeFileWritePosition="cursor"),l.setName("Write position").setDesc(G?"Where to place the capture in the current file.":"Where to place the capture in the target file.").addDropdown(t=>{let c=this.choice.insertAfter?.enabled?"after":this.choice.newLineCapture?.enabled?this.choice.newLineCapture.direc
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function NE(){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 $n(e,I){var l=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!l){if(Array.isArray(e)||(l=W0(e))||I&&e&&typeof e.length=="number"){l&&(e=l);var G=0,t=function(){};return{s:t,n:function(){return G>=e.length?{done:!0}:{done:!1,value:e[G++]}},e:function(Z){throw Z},f:t}}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 c=!0,b=!1,d;return{s:function(){l=l.call(e)},n:function(){var Z=l.next();return c=Z.done,Z},e:function(Z){b=!0,d=Z},f:function(){try{!c&&l.return!=null&&l.return()}finally{if(b)throw d}}}}var YE="finalize",sE="consider";function gZ(e,I,l){e.dispatchEvent(new CustomEvent(YE,{detail:{items:I,info:l}}))}function Fc(e,I,l){e.dispatchEvent(new CustomEvent(sE,{detail:{items:I,info:l}}))}var PY="draggedEntered",IW="draggedLeft",_Y="draggedOverIndex",N0="draggedLeftDocument",MY={LEFT_FOR_ANOTHER:"leftForAnother",OUTSIDE_OF_ANY:"outsideOfAny"};function iE(e,I,l){e.dispatchEvent(new CustomEvent(PY,{detail:{indexObj:I,draggedEl:l}}))}function uE(e,I,l){e.dispatchEvent(new CustomEvent(IW,{detail:{draggedEl:I,type:MY.LEFT_FOR_ANOTHER,theOtherDz:l}}))}function CE(e,I){e.dispatchEvent(new CustomEvent(IW,{detail:{draggedEl:I,type:MY.OUTSIDE_OF_ANY}}))}function hE(e,I,l){e.dispatchEvent(new CustomEvent(_Y,{detail:{indexObj:I,draggedEl:l}}))}function pE(e){window.dispatchEvent(new CustomEvent(N0,{detail:{draggedEl:e}}))}var HG={DRAG_STARTED:"dragStarted",DRAGGED_ENTERED:PY,DRAGGED_ENTERED_ANOTHER:"dragEnteredAnother",DRAGGED_OVER_INDEX:_Y,DRAGGED_LEFT:IW,DRAGGED_LEFT_ALL:"draggedLeftAll",DROPPED_INTO_ZONE:"droppedIntoZone",DROPPED_INTO_ANOTHER:"droppedIntoAnother",DROPPED_OUTSIDE_OF_ANY:"droppedOutsideOfAny",DRAG_STOPPED:"dragStopped"},rG={POINTER:"pointer",KEYBOARD:"keyboard"},$Y="isDndShadowItem",Is="data-is-dnd-shadow-item-internal",VE="data-is-dnd-shadow-item-hint",kb="id:dnd-shadow-placeholder-0000",oE="dnd-action-dragged-el",dG="id",c0=0;function JR(){c0++}function AR(){if(c0===0)throw new Error("Bug! trying to decrement when there are no dropzones");c0--}var Y0=typeof window>"u",vI=function(){};function b0(e){var I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,l,G=I?RE(e):e.getBoundingClientRect(),t=getComputedStyle(e),c=t.transform;if(c){var b,d,Z,a;if(c.startsWith("matrix3d("))l=c.slice(9,-1).split(/, /),b=+l[0],d=+l[5],Z=+l[12],a=+l[13];else if(c.startsWith("matrix("))l=c.slice(7,-1).split(/, /),b=+l[0],d=+l[3],Z=+l[4],a=+l[5];else return G;var m=t.transformOrigin,n=G.x-Z-(1-b)*parseFloat(m),W=G.y-a-(1-d)*parseFloat(m.slice(m.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 ER(e){var I=b0(e);return{top:I.top+window.scrollY,bottom:I.bottom+window.scrollY,left:I.left+window.scrollX,right:I.right+window.scrollX}}function kR(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 OR(e){return{x:(e.left+e.right)/2,y:(e.top+e.bottom)/2}}function rE(e,I){return Math.sqrt(Math.pow(e.x-I.x,2)+Math.pow(e.y-I.y,2))}function ls(e,I){return e.y<=I.bottom&&e.y>=I.top&&e.x>=I.left&&e.x<=I.right}function qn(e){return OR(kR(e))}function rR(e,I){var l=qn(e),G=ER(I);return ls(l,G)}function XE(e,I){var l=qn(e),G=qn(I);return rE(l,G)}function QE(e){var I=kR(e);return I.right<0||I.left>document.documentElement.scrollWidth||I.bottom<0||I.top>document.documentElement.scrollHeight}function RE(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 t=G.getBoundingClientRect(),c=window.getComputedStyle(G).overflowY,b=window.getComputedStyle(G).overflowX,d=c==="scroll"||c==="auto",Z=b==="scroll"||b==="auto";d&&(l.top=Math.max(l.top,t.top),l.bottom=Math.min(l.bottom,t.bottom)),Z&&(l.left=Math.max(l.left,t.left),l.right=Math.min(l.right,t.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 LZ;function s0(){vI(function(){return"resetting indexes cache"}),LZ=new Map}s0();function LE(e){var I=Array.from(e.children).f
${l?"Deleting this choice will delete all ("+e.choices.length+") choices inside it!":""}
${G?"Deleting this choice will delete its macro commands!":""}
`)}async function NL(e,I,l){if(e.type==="Multi")try{return await new ps(I,e).waitForClose}catch{return}let G=qk(e,I,l);if(!G)throw new Error("Invalid choice type");return await G.waitForClose}function YL(e){return{...e,command:!e.command}}var os=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 sL(e,I,l){if(!I||!l)return e;let G=L0(e,I),t=L0(e,l);if(!G||!t||t.type!=="Multi"||G.type==="Multi"&&(G.id===t.id||Pk(G).has(t.id)))return e;let{updated:c,removed:b}=iL(e,I);return b?uL(c,l,b)??e:e}function L0(e,I){for(let l of e){if(l.id===I)return l;if(l.type==="Multi"){let G=L0(l.choices,I);if(G)return G}}}function Pk(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 iL(e,I){let l;return{updated:e.map(t=>{if(t.id===I){l=t;return}if(t.type!=="Multi")return t;let c=iL(t.choices,I);return c.removed&&(l=c.removed),c.removed?{...t,choices:c.updated}:t}).filter(Boolean),removed:l}}function uL(e,I,l){let G=!1,t=e.map(c=>{if(c.id===I&&c.type==="Multi"){G=!0;let d=c;return{...d,choices:[...d.choices,l]}}if(c.type!=="Multi")return c;let b=uL(c.choices,I,l);return b?(G=!0,{...c,choices:b}):c});return G?t:void 0}var Qt=require("obsidian");var Rl=require("obsidian");var CL=require("obsidian");var rs=null,_k=24*60*60*1e3;async function hL(){if(rs&&Date.now()-rs.fetchedAt<_k)return rs.data;if(P.getState().disableOnlineFeatures)throw new Error("Fetching models directory is disabled: Online features are turned off.");let I=await(await(0,CL.requestUrl)({url:"https://models.dev/api.json",method:"GET"})).json;return rs={data:I,fetchedAt:Date.now()},I}function g0(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 pL(e){return e.map(I=>({name:I.id,maxTokens:Math.max(1,Math.floor(I.limit?.context??128e3))}))}function v0(e,I){let l=new Set(e.map(t=>t.name)),G=I.filter(t=>!l.has(t.name));return e.concat(G)}var rL=require("obsidian");var $k=128e3;async function Xs(e,I){let l=e.modelSource??"providerApi";if(l==="modelsDev")return VL(e);if(l==="providerApi")return oL(e,I);try{return await oL(e,I)}catch(G){if(!g0(e.endpoint))throw G;return VL(e,G)}}async function VL(e,I){try{let l=await hL(),G=g0(e.endpoint);if(!G||!(G in l))throw new Error(`models.dev does not list a provider that matches ${e.endpoint}.`);let t=Object.values(l[G].models);return pL(t)}catch(l){throw I?new Error(`Provider API failed (${I.message}). Fallback to models.dev also failed: ${l.message}`):l}}async function oL(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
`),d=aI(b),o(I,"class","warning svelte-iqd8ho")},m(Z,a){cI(Z,I,a),p(I,l),p(I,G),p(I,t),p(t,c),p(t,d)},p(Z,a){a[0]&256&&b!==(b=Z[8].missingChoiceIds.join(", ")+"")&&XI(d,b)},d(Z){Z&&eI(I)}}}function ZF(e){let I,l,G,t,c=e[4].missingChoices.length>0&&aF(e),b=e[4].missingAssets.length>0&&mF(e);return{c(){I=L("section"),l=L("h4"),l.textContent="Warnings",G=M(),c&&c.c(),t=M(),b&&b.c(),o(I,"class","warning svelte-iqd8ho")},m(d,Z){cI(d,I,Z),p(I,l),p(I,G),c&&c.m(I,null),p(I,t),b&&b.m(I,null)},p(d,Z){d[4].missingChoices.length>0?c?c.p(d,Z):(c=aF(d),c.c(),c.m(I,t)):c&&(c.d(1),c=null),d[4].missingAssets.length>0?b?b.p(d,Z):(b=mF(d),b.c(),b.m(I,null)):b&&(b.d(1),b=null)},d(d){d&&eI(I),c&&c.d(),b&&b.d()}}}function aF(e){let I,l,G=e[4].missingChoices.map(e[23]).join(", ")+"",t;return{c(){I=L("p"),l=aI(`Missing choices:
`),t=aI(G)},m(c,b){cI(c,I,b),p(I,l),p(I,t)},p(c,b){b[0]&144&&G!==(G=c[4].missingChoices.map(c[23]).join(", ")+"")&&XI(t,G)},d(c){c&&eI(I)}}}function mF(e){let I,l,G,t,c=Wl(e[4].missingAssets),b=[];for(let d=0;d<c.length;d+=1)b[d]=nF(eF(e,c,d));return{c(){I=L("div"),l=L("p"),l.textContent="Missing assets:",G=M(),t=L("ul");for(let d=0;d<b.length;d+=1)b[d].c();o(t,"class","svelte-iqd8ho")},m(d,Z){cI(d,I,Z),p(I,l),p(I,G),p(I,t);for(let a=0;a<b.length;a+=1)b[a]&&b[a].m(t,null)},p(d,Z){if(Z[0]&528){c=Wl(d[4].missingAssets);let a;for(a=0;a<c.length;a+=1){let m=eF(d,c,a);b[a]?b[a].p(m,Z):(b[a]=nF(m),b[a].c(),b[a].m(t,null))}for(;a<b.length;a+=1)b[a].d(1);b.length=c.length}},d(d){d&&eI(I),wt(b,d)}}}function nF(e){let I,l=e[28].path+"",G,t,c,b,d=e[9][e[28].kind]+"",Z,a;return{c(){I=L("li"),G=aI(l),t=M(),c=L("span"),b=aI("("),Z=aI(d),a=aI(")"),o(c,"class","assetKind svelte-iqd8ho")},m(m,n){cI(m,I,n),p(I,G),p(I,t),p(I,c),p(c,b),p(c,Z),p(c,a)},p(m,n){n[0]&16&&l!==(l=m[28].path+"")&&XI(G,l),n[0]&16&&d!==(d=m[9][m[28].kind]+"")&&XI(Z,d)},d(m){m&&eI(I)}}}function jO(e){let I;return{c(){I=aI("Copy JSON")},m(l,G){cI(l,I,G)},d(l){l&&eI(I)}}}function SO(e){let I;return{c(){I=aI("Copying\u2026")},m(l,G){cI(l,I,G)},d(l){l&&eI(I)}}}function TO(e){let I;return{c(){I=aI("Save to file")},m(l,G){cI(l,I,G)},d(l){l&&eI(I)}}}function qO(e){let I;return{c(){I=aI("Saving\u2026")},m(l,G){cI(l,I,G)},d(l){l&&eI(I)}}}function PO(e){let I,l,G,t,c,b,d,Z,a,m,n,W,N,Y,s,u,V,C,r,i,Q=e[8].rootCount+"",R,h,F,w,E,T,k=e[8].totalChoices+"",O,K,J,H,v,A,B=e[8].dependencyCount+"",q,mI,nI,VI,RI,uI,WI=e[8].userScripts+e[8].conditionalScripts+"",LI,ll,ul,vl,hl,ge,fG=e[8].templateFiles+e[8].captureTemplates+"",jG,WG,NG,j,kI,xI,SI,te,YG,SG,St,Ft,ce,Tt,vc,qt,ve,CW,He,Hc,MZ,yc,ye,hW,X,y,U;function f(fl,Cl){return fl[6].length===0?fO:MO}let II=f(e,[-1,-1]),lI=II(e),$=e[8].missingChoiceIds.length>0&&dF(e),NI=e[4]&&ZF(e);function Gl(fl,Cl){return fl[5]==="copy"?SO:jO}let Hl=Gl(e,[-1,-1]),bl=Hl(e);function be(fl,Cl){return fl[5]==="save"?qO:TO}let Dl=be(e,[-1,-1]),Ml=Dl(e);return{c(){I=L("div"),l=L("header"),l.innerHTML='<h2>Export QuickAdd Package</h2> <p class="svelte-iqd8ho">Select choices to bundle. Dependencies are added automatically.</p>',G=M(),t=L("section"),c=L("input"),d=M(),Z=L("div"),a=L("button"),a.textContent="Select visible",m=M(),n=L("button"),n.textContent="Clear selection",W=M(),N=L("section"),lI.c(),Y=M(),s=L("section"),u=L("h3"),u.textContent="Package summary",V=M(),C=L("div"),r=L("div"),i=L("strong"),R=aI(Q),h=M(),F=L("span"),F.textContent="Selected choices",w=M(),E=L("div"),T=L("strong"),O=aI(k),K=M(),J=L("span"),J.textContent="Total packaged",H=M(),v=L("div"),A=L("strong"),q=aI(B),mI=M(),nI=L("span"),nI.textContent="Auto-included",VI=M(),RI=L("div"),uI=L("strong"),LI=aI(WI),ll=M(),ul=L("span"),ul.textContent="Scripts embedded",vl=M(),hl=L("div"),ge=L("strong"),jG=aI(fG),WG=M(),NG=L("span"),NG.textContent="Templates embedded",j=M(),$&&$.c(),kI=M(),NI&&NI.c(),xI=M(),SI=L("section"),te=L("div"),YG=L("button"),bl.c(),St=M(),Ft=L("div"),ce=L("label"),Tt=L("span"),Tt.textContent="Save to file",vc=M(),qt=L("div"),ve=L("input"),CW=M(),He=L("button"),Ml.c(),MZ=M(),yc=L("section"),ye=L("button"),hW=aI("Cancel"),o(l,"class","svelte-iqd8ho"),o(c,"type","text"),o(c,"placeholder","Filter choices"),o(c,"autocapitalize","off"),o(c,"autocorrect","off"),o(c,"spellcheck",b=!1),o(c,"class","svelte-iqd8ho"),o(a,"type","button"),o(a,"class","svelte-iqd8ho"),o(n,"type","button"),o(n,"class","svelte-iqd8ho"),o(Z,"class","controlButtons svelte-iqd8ho"),o(t,"class","controls svelte-iqd8ho"),o(N,"class","choiceList svelte-iqd8ho"),o(u,"class","svelte-iqd8ho"),o(i,"class","svelte-iqd8ho"),o(r,"class","svelte-iqd8ho"),o(T,"class","svelte-iqd8ho"),o(E,"class","svelte-iqd8ho"),o(A,"class","svelte-iqd8ho"),o(v,"class","svelte-iqd8ho"),o(uI,"class","svelte-iqd8ho"),o(RI,"class","svelte-iqd8ho"),o(ge,"class","svelte-iqd8ho"),o(hl,"class","svelte-iqd8ho"),o(C,"class","summaryGrid svelte-iqd8ho"),o(s,"class","summary svelte-iqd8ho"),o(YG,"type","button"),o(YG,"class","secondary svelte-iq
tm = tomorrow
yd = yesterday`).setValue(ui(P.getState().dateAliases)).onChange(b=>{P.setState({dateAliases:Qp(b)})}),c.inputEl.style.width="100%",c.inputEl.style.minHeight="6rem",c.inputEl.style.flex="1 1 280px",c.inputEl.style.maxWidth="100%",c.inputEl.style.boxSizing="border-box"}),G.addButton(c=>{c.setButtonText("Reset to defaults").onClick(()=>{P.setState({dateAliases:jb}),t&&t.setValue(ui(jb))}),c.buttonEl.style.alignSelf="flex-start",c.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(t=>t.setValue(P.getState().disableOnlineFeatures).onChange(c=>{P.setState({disableOnlineFeatures:c}),this.display()}))})}addEnableRibbonIconSetting(l){l.addSetting(G=>{G.setName("Show icon in sidebar").setDesc("Add QuickAdd icon to the sidebar ribbon. Requires a reload.").addToggle(t=>{t.setValue(P.getState().enableRibbonIcon).onChange(c=>{P.setState({enableRibbonIcon:c}),this.display()})})})}};var KZ=class{formatOutputString(I){return`QuickAdd: (${I.level}) ${I.message}`}getQuickAddError(I,l,G,t){return{message:I,level:l,time:Date.now(),stack:G,originalError:t}}};var mW=class extends KZ{constructor(){super(...arguments);this.ErrorLog=[]}logError(l,G,t){let c=this.getQuickAddError(l,"ERROR",G,t);this.addMessageToErrorLog(c);let b=t||new Error(l);console.error(this.formatOutputString(c),b)}logWarning(l,G,t){let c=this.getQuickAddError(l,"WARNING",G,t);this.addMessageToErrorLog(c);let b=t||new Error(l);console.warn(this.formatOutputString(c),b)}logMessage(l,G,t){let c=this.getQuickAddError(l,"LOG",G,t);this.addMessageToErrorLog(c),t?console.log(this.formatOutputString(c),t):console.log(this.formatOutputString(c))}addMessageToErrorLog(l){this.ErrorLog.push(l),this.ErrorLog.length>sC&&(this.ErrorLog=this.ErrorLog.slice(-sC))}clearErrorLog(){this.ErrorLog=[]}};var j0=require("obsidian");var zs=class extends KZ{constructor(l){super();this.plugin=l}logError(l,G,t){let c=this.getQuickAddError(l,"ERROR",G,t);new j0.Notice(this.formatOutputString(c),15e3)}logWarning(l,G,t){let c=this.getQuickAddError(l,"WARNING",G,t);new j0.Notice(this.formatOutputString(c))}logMessage(l,G,t){}};var Bs=class{constructor(I,l,G,t){this.app=I;this.plugin=l;this.choices=G;this.choiceExecutor=t}async run(){let I=je(this.choices).filter(l=>l.type==="Macro"&&l.runOnStartup);for(let l of I)await new ut(this.app,this.plugin,l,this.choiceExecutor,new Map).run()}};var S0=require("obsidian"),AF=require("obsidian");var Ds=class extends oZ{constructor(I,l,G,t){super(I,l,t),this.choiceExecutor=t,this.choice=G}async run(){try{_G(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}`}`);let I=ac(this.choice.appendLink);this.setLinkToCurrentFileBehavior(I.enabled&&!I.requireActiveFile?"optional":"required");let l="";if(this.choice.folder.enabled)l=await this.getFolderPath();else{let n=this.app.fileManager.getNewFileParent(this.app.workspace.getActiveFile()?.path??"");l=n===this.app.vault.getRoot()?"":n.path}let G=this.choice.fileNameFormat.enabled?this.choice.fileNameFormat.format:Kc,t=await this.formatter.formatFileName(G,this.choice.name),{fileName:c,strippedPrefix:b}=this.stripDuplicateFolderPrefix(t,l),d=this.shouldTreatFormattedNameAsVaultRelativePath(t,b),Z=this.normalizeTemplateFilePath(d?"":l,c,this.choice.templatePath);this.choice.fileExistsMode===Uc&&(Z=await this.incrementFileName(Z));let a,m=!1;if(await this.app.vault.adapter.exists(Z)){let n=this.findExistingFile(Z);if(!(n instanceof S0.TFile)||n.extension!=="md"&&n.extension!=="canvas"&&n.extension!=="base"){x.logError(`'${Z}' already exists but could not be resolved a
`)}}).join(`
`)}}var kF=e=>e.join(""),h3=e=>e.split(/\b/),p3=EF("<<<<<<< YOUR CHANGES","=======",">>>>>>> APP AUTHORS CHANGES",kF),V3={splitFunction:h3,joinFunction:kF,conflictFunction:p3};function Ip(e,I,l,G={}){G=Object.assign({},V3,G);let[t,c,b]=[e,I,l].map(a=>G.splitFunction.call(G,a)),d=NW.merge(t,c,b);return YW.collateMerge(d,G.joinFunction,G.conflictFunction)}var OF=Ip;var lp=require("obsidian");var zI=class extends jI{};function KF(e,I){return e.line===I.line}function o3(e){let I=[];return e.forEach((l,G)=>{let t=l.match(/^(#+)[\s]+(.*)$/);t&&I.push({level:t[1].length,text:t[2],line:G})}),I}function Ts(e,I,l=!1){let G=o3(e),t=G.find(a=>a.line===I),c=!!t;if(!c&&l)throw new Error(`Target line ${I} is not a heading, but we are trying to find the end of its section.`);if(!c&&!l){let a=xF(e,I,m=>m.trim()==="");return a!==null&&a>I?a-1:I}let b=e.length-1,d=r3(t,G,e,l),Z=R3(e,d,a=>a.trim()!=="");if(Z!==null){if(Z<I)return I;let a=e[Z+1].trim()==="";return Z+1===b&&!a?d:Z===0?Z+1:Z}return d}function r3(e,I,l,G){let t=I.findIndex(m=>KF(m,e)),c=t===I.length-1,b=l.length-1;if(c)return b;let[d,Z]=X3(e,I);if(Z&&d===I.length)return b;if(Z&&G)return I[d].line-1;if(Z&&!G)return I[t+1].line;if(!G&&!Z){let m=Q3(e.line,I);return m===null?b:m}return b}function X3(e,I){let l=I.findIndex(t=>KF(t,e)),G=xF(I,l,t=>t.level<=e.level);return G===null?[-1,!1]:[G,!0]}function Q3(e,I){let l=I.find(G=>G.line>e);return l?l.line:null}function R3(e,I,l){for(let G=I-1;G>=0;G--)if(l(e[G]))return G;return null}function xF(e,I,l){for(let G=I+1;G<e.length;G++)if(l(e[G]))return G;return null}var qs=class extends Me{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(){return this.useSelectionAsCaptureValue}async getSelectedTextForValue(){let l=await this.getSelectedText();return l.trim().length>0?l:""}getLinkSourcePath(){return this.sourcePath??this.file?.path??null}getCurrentFileLink(){let l=this.app.workspace.getActiveFile();if(!l)return null;let G=this.sourcePath??this.file?.path??"";return this.app.fileManager.generateMarkdownLink(l,G)}async formatContentWithFile(l,G,t,c){if(this.choice=G,this.file=c,this.fileContent=t,!G||!c||t===null)return l;let b=G.insertAfter.enabled||G.prepend||!G.captureToActiveFile||G.activeFileWritePosition==="top"||G.activeFileWritePosition==="bottom";return await this.formatFileContent(l,b)}async formatContent(l,G){return this.choice=G,G?await this.formatFileContent(l):l}async formatFileContent(l,G=!0){let t=await super.formatFileContent(l);if(t=this.replaceLinebreakInString(t),G&&this.file&&!this.templaterProcessed){let Z=await wd(this.app,t,this.file);Z&&(t=Z),this.templaterProcessed=!0}if(t.trim()==="")return this.fileContent;if(this.choice.prepend||this.choice.captureToActiveFile&&this.choice.activeFileWritePosition==="bottom"){let Z=!this.choice.task,a=this.fileContent.length>0&&!this.fileContent.endsWith(`
`)&&!t.startsWith(`
`),m=Z||a?`
`:"";return`${this.fileContent}${m}${t}`}if(this.choice.insertAfter.enabled)return await this.insertAfterHandler(t);let d=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):null;return d==null||d<0?`${t}${this.fileContent}`:this.insertTextAfterPositionInBody(t,this.fileContent,d)}async formatContentOnly(l){let G=await super.formatFileContent(l);return G=this.replaceLinebreakInString(G),G.trim()===""?this.fileContent:G}normalizeTarget(l){return l.replace("\\n","").trimEnd()}findInsertAfterIndex(l,G){let t=this.normalizeTarget(G),c=-1;for(let b=0;b<l.length;b++){let d=l[b].trimStart();if(d===t)return b;if(d.startsWith(t)){let a=d.slice(t.length);if(/^\s*$/.test(a))return b;c===-1&&(c=b);continue}let Z=d.indexOf(t);if(Z!==-1){let a=d.slice(Z+t.length);if(/^\s*$/.test(a))return b;c===-1&&(c=b)}}return c}shouldSkipBlankLinesAfterMatch(l,G){return l==="skip"?!0:l==="none"?!1:this.isAtxHeading(G)}isAtxHeading(l){return/^\s{0,3}#{1,6}\s+\S/.test(l)}findInsertAfterPositionWithBlankLines(l,G,t,c){if(G<0)return G;let b=l[G]??"";if(!this.shouldSkipBlankLinesAfterMatch(c,b))return G;let Z=t.endsWith(`
`)?Math.max(l.length-1,0):l.length,a=G;for(let m=G+1;m<Z;m++){if(l[m].trim().length===0){a=m;continue}break}return a}findInsertAfterPositionAtSectionEnd(l,G,t,c){if(G<0)return G;let b=G,d=G+1;for(;d<l.length&&l[d].trim().length===0;)b=d,d++;return b===G||d!==l.length||!c.endsWith(`
`)?G:t.endsWith(`
`)?Math.max(G,b-1):b}async insertAfterHandler(l){let G=await this.formatLocationString(this.choice.insertAfter.after);if(this.choice.insertAfter?.inline)return await this.insertAfterInlineHandler(l,G);let t=_h(this.fileContent),c=this.findInsertAfterIndex(t,G);if(c===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInsertAfterIfNotFound(l);throw new zI(`Insert-after target not found: '${G}'.`)}if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let d=Ts(t,c,!!this.choice.insertAfter.considerSubsections);c=this.findInsertAfterPositionAtSectionEnd(t,d??t.length-1,this.fileContent,l)}else{let d=this.choice.insertAfter?.blankLineAfterMatchMode??"auto";c=this.findInsertAfterPositionWithBlankLines(t,c,this.fileContent,d)}return this.insertTextAfterPositionInBody(l,this.fileContent,c)}hasInlineTargetLinebreak(l){return l.includes(`
`)||l.includes("\r")}getInlineEndOfLine(l){let G=this.fileContent.indexOf(`
`,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 cl(new Error("Inline insert after target must be a single line."),"Insert After Inline Error"),this.fileContent;let t=this.fileContent.indexOf(G);if(t===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInlineInsertAfterIfNotFound(l,G);throw new zI(`Inline insert-after target not found: '${G}'.`)}let c=t+G.length;if(this.choice.insertAfter?.replaceExisting){let b=this.getInlineEndOfLine(c);return this.fileContent.slice(0,c)+l+this.fileContent.slice(b)}return this.fileContent.slice(0,c)+l+this.fileContent.slice(c)}async createInsertAfterIfNotFound(l){let t=`${this.replaceLinebreakInString(await this.formatLocationString(this.choice.insertAfter.after))}
${l}`;if(this.choice.insertAfter?.createIfNotFoundLocation===Sb){let c=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):-1;return this.insertTextAfterPositionInBody(t,this.fileContent,c)}if(this.choice.insertAfter?.createIfNotFoundLocation===qZ)return`${this.fileContent}
${t}`;if(this.choice.insertAfter?.createIfNotFoundLocation===PZ)try{let c=this.app.workspace.getActiveViewOfType(lp.MarkdownView);if(!c)throw new Error("No active view.");let d=c.editor.getCursor().line;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let a=_h(this.fileContent),m=Ts(a,d,!!this.choice.insertAfter.considerSubsections);d=this.findInsertAfterPositionAtSectionEnd(a,m??a.length-1,this.fileContent,t)}return this.insertTextAfterPositionInBody(t,this.fileContent,d)}catch{throw new zI(`Unable to insert line '${this.choice.insertAfter.after}' at cursor position.`)}throw new zI(`Unknown createIfNotFoundLocation: ${this.choice.insertAfter?.createIfNotFoundLocation}`)}async createInlineInsertAfterIfNotFound(l,G){let t=`${G}${l}`;if(this.choice.insertAfter?.createIfNotFoundLocation===Sb){let c=this.file?this.getFrontmatterEndPosition(this.file,this.fileContent):-1;return this.insertTextAfterPositionInBody(t,this.fileContent,c)}if(this.choice.insertAfter?.createIfNotFoundLocation===qZ)return`${this.fileContent}
${t}`;if(this.choice.insertAfter?.createIfNotFoundLocation===PZ)try{let c=this.app.workspace.getActiveViewOfType(lp.MarkdownView);if(!c)throw new Error("No active view.");let d=c.editor.getCursor().line;return this.insertTextAfterPositionInBody(t,this.fileContent,d)}catch{throw new zI(`Unable to insert line '${this.choice.insertAfter.after}' at cursor position.`)}throw new zI(`Unknown createIfNotFoundLocation: ${this.choice.insertAfter?.createIfNotFoundLocation}`)}getFrontmatterEndPosition(l,G){let t=this.app.metadataCache.getFileCache(l);if(t?.frontmatterPosition)return t.frontmatterPosition.end.line;if(G){let c=this.inferFrontmatterEndLineFromContent(G);if(c!==null)return c}return x.logMessage("could not get frontmatter. Maybe there isn't any."),-1}inferFrontmatterEndLineFromContent(l){let G=oN(l);if(!G)return null;let t=l.slice(0,G[1]),c=t.split(/\r?\n/);return c.length===0?null:t.endsWith(`
`)?c.length-2:c.length-1}insertTextAfterPositionInBody(l,G,t){if(t===-1){let Z=!this.choice.task;return`${l}${Z?`
`:""}${G}`}let c=G.split(`
`),b=c.slice(0,t+1).join(`
`),d=c.slice(t+1).join(`
`);return`${b}
${l}${d}`}};function UF(e){return e.captureToActiveFile&&!e.insertAfter.enabled&&e.newLineCapture?.enabled?e.newLineCapture.direction==="above"?"newLineAbove":"newLineBelow":e.captureToActiveFile&&!e.insertAfter.enabled?e.activeFileWritePosition==="top"?"activeFileTop":e.activeFileWritePosition==="bottom"||e.prepend?"append":"currentLine":e.insertAfter.enabled?"insertAfter":e.prepend?"prepend":"append"}function Gp(e){return e?.type==="text"?"text":e?.type==="file"||e?.file?"file":typeof e?.text=="string"?"text":"unsupported"}function L3(e,I){let l=I.id;if(!l)return null;let G=e.getData?.();return G?.nodes?.length?G.nodes.find(t=>t.id===l)??null:null}function zF(e,I){if(e==="text"){if(I==="currentLine")return"Canvas capture does not support 'At cursor' for text cards. Use top, bottom, or insert-after placement.";if(I==="newLineAbove"||I==="newLineBelow")return"Canvas capture does not support 'New line above/below cursor' for text cards. Use top, bottom, or insert-after placement."}return e==="file"&&(I==="currentLine"||I==="newLineAbove"||I==="newLineBelow")?"Canvas file cards do not support cursor-based capture modes. Use top, bottom, or insert-after modes.":null}function F3(e){let I=e.file;return I?typeof I=="string"?I:typeof I=="object"&&"path"in I&&typeof I.path=="string"?I.path:null:null}function ep(e){return!!e&&"path"in e&&"extension"in e}function w3(e){let l=(e.workspace.activeLeaf??e.workspace.getMostRecentLeaf?.()??null)?.view;return!l||l.getViewType?.()!=="canvas"?null:l}function g3(e,I){let l=I.file??e.workspace.getActiveFile?.();if(!l)throw new zI("Cannot capture to Canvas because no active Canvas file is available.");return l}function v3(e){let I=e.selection?Array.from(e.selection):[];if(I.length!==1)throw new zI("Canvas capture requires exactly one selected node.");return I[0]}function BF(e){let I=F3(e);if(!I)throw new zI("Selected Canvas file card does not have a valid linked file path.");if(!JG.test(I))throw new zI("Canvas file card targets markdown files only in this version.");return I}function H3(e,I){let l=BF(I),G=e.vault.getAbstractFileByPath(l);if(!ep(G))throw new zI(`Selected Canvas file card target not found: ${l}`);return G}function y3(e,I){let l=BF(I),G=e.vault.getAbstractFileByPath(l);if(!G)return{targetPath:l};if(!ep(G))throw new zI(`Selected Canvas file card target not found: ${l}`);return{targetPath:l,targetFile:G}}function J3(e,I){let l;try{l=JSON.parse(e)}catch{throw new zI(`Canvas file is not valid JSON: ${I}`)}if(!l||typeof l!="object")throw new zI(`Canvas file has invalid structure: ${I}`);let G=l;if(!Array.isArray(G.nodes))throw new zI(`Canvas file has no nodes array: ${I}`);return l}function DF(e,I){let l=e,G=w3(l);if(!G)return null;let t=G.canvas;if(!t)throw new zI("Canvas capture is unavailable in this Obsidian version.");let c=g3(l,G),b=v3(t),d=L3(t,b),Z=Gp(b);if(Z==="unsupported"&&d&&(Z=Gp(d)),Z==="unsupported")throw new zI("Canvas capture currently supports only text and file cards.");let a=zF(Z,I);if(a)throw new zI(a);if(Z==="text")return{kind:"text",source:"active",canvas:t,canvasFile:c,node:b,nodeData:d};let m=b.file||!d?.file?b:{...b,file:d.file};return{kind:"file",source:"active",canvasFile:c,node:m,targetFile:H3(l,m)}}async function MF(e,I,l,G){let t=l.trim();if(!t)throw new zI("Canvas node id is required for Canvas node capture.");let c=e.vault.getAbstractFileByPath(I);if(!ep(c))throw new zI(`Canvas target not found: ${I}`);if(!AG.test(c.path))throw new zI("Canvas node capture requires the target path to be a .canvas file.");let b=await e.vault.read(c),d=J3(b,c.path),Z=d.nodes.findIndex(s=>s.id===t);if(Z===-1)throw new zI(`Canvas node id '${t}' was not found in ${c.path}.`);let a=d.nodes[Z],m=Gp(a);if(m==="unsupported")throw new zI("Canvas capture currently supports only text and file cards.");let n=zF(m,G);if(n)throw new zI(n);if(m==="text")return{kind:"text",source:"configured",canvasFile:c,rawCanvas:b,canvasData:d,nodeData:a,nodeIndex:Z};let W=e,{targetPath:N,targetFile:Y}=y3(W,a);return{kind:"file",source:"configured",canvasFile:c,nodeData:a,targetPath:N,targetFile:Y}
`),l}async getFormattedPathToCaptureTo(l){let G=this.choiceExecutor?.variables?.get(Ia);if(!l&&G&&typeof G=="string"&&G.length>0)return this.normalizeCaptureFilePath(G);if(l){let d=this.app.workspace.getActiveFile();return _G(d,"Cannot capture to active file - no active file."),d.path}let t=this.choice.captureTo,c=await this.formatter.formatFileName(t,this.choice.name),b=this.resolveCaptureTarget(c);switch(b.kind){case"vault":return this.selectFileInFolder("",!0);case"tag":return this.selectFileWithTag(b.tag);case"folder":return this.selectFileInFolder(b.folder,!1);case"file":return this.normalizeCaptureFilePath(b.path)}}resolveCaptureTarget(l){let G=this.stripLeadingSlash(l.trim());if(G==="")return{kind:"vault"};if(G.startsWith("#"))return{kind:"tag",tag:G.replace(/\.md$/,"")};if(Gt.test(G))throw new zI(`Capture to '.base' files is not supported (${G}). Use a Template choice instead.`);let t=G.endsWith("/"),c=G.replace(/\/+$/,"");if(t)return{kind:"folder",folder:c};if(JG.test(G)||AG.test(G))return{kind:"file",path:G};let b=this.normalizeMarkdownFilePath("",c),Z=!!this.app.vault.getAbstractFileByPath(b);return pN(this.app,c)&&!Z?{kind:"folder",folder:c}:{kind:"file",path:G}}async selectFileInFolder(l,G){let t=l.endsWith("/")||G?l:`${l}/`,c=mc(this.app,t);_G(c.length>0,`Folder ${t} is empty.`);let b=c.map(a=>a.path),d;try{d=await aG.Suggest(this.app,b.map(a=>a.replace(t,"")),b)}catch(a){throw pl(a)?new jI("Input cancelled by user"):a}_G(!!d&&d.length>0,"No file selected for capture.");let Z=d.startsWith(`${t}`)?d:`${t}/${d}`;return await this.formatFilePath(Z)}async selectFileWithTag(l){let G=l.startsWith("#")?l:`#${l}`,t=VN(this.app,G);_G(t.length>0,`No files with tag ${l}.`);let c=t.map(d=>d.path),b;try{b=await aG.Suggest(this.app,c,c)}catch(d){throw pl(d)?new jI("Input cancelled by user"):d}return _G(!!b&&b.length>0,"No file selected for capture."),await this.formatFilePath(b)}async onFileExists(l,G){let t=this.getFileByPath(l);if(!t)throw new Error("File not found");this.formatter.setTitle(t.basename),this.formatter.setDestinationFile(t);let c=await this.formatter.formatContentOnly(G);this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let b=await this.app.vault.read(t),d=await this.formatter.formatContentWithFile(c,this.choice,b,t);this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let Z=await this.app.vault.read(t),a=d;if(Z!==b){let m=OF(Z,b,d);_G(!m.isSuccess,()=>`The file ${l} has been modified since the last read.
2025-08-02 12:09:34 +08:00
QuickAdd could not merge the versions two without conflicts, and will not modify the file.
2026-05-06 17:32:44 +08:00
This is in order to prevent data loss.`),a=m.joinedResults()}return{file:t,newFileContent:a,captureContent:c}}async onCreateFileIfItDoesntExist(l,G,t){let c=Dn(l);this.formatter.setTitle(c),this.formatter.setDestinationSourcePath(l);let b=await this.formatter.formatContentOnly(G);this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let d="";if(this.choice.createFileIfItDoesntExist.createWithTemplate){let n=new Xc(this.app,this.plugin,this.choice.createFileIfItDoesntExist.template,this.choiceExecutor);t?.enabled&&!t.requireActiveFile&&n.setLinkToCurrentFileBehavior("optional"),d=await n.run();let W=n.getAndClearTemplatePropertyVars();x.logMessage(`CaptureChoiceEngine: Collected ${W.size} template property variables`),W.size>0&&x.logMessage(`Variables: ${Array.from(W.keys()).join(", ")}`),this.templatePropertyVars=W}let Z=await this.createFileWithInput(l,d,{suppressTemplaterOnCreate:this.choice.createFileIfItDoesntExist.createWithTemplate});this.choice.createFileIfItDoesntExist.createWithTemplate&&this.templatePropertyVars&&this.shouldPostProcessFrontMatter(Z,this.templatePropertyVars)&&await this.postProcessFrontMatter(Z,this.templatePropertyVars),this.choice.createFileIfItDoesntExist.createWithTemplate&&d?await Fd(this.app,Z):CN(this.app)&&await K2(this.app,Z);let a=await this.app.vault.read(Z),m=await this.formatter.formatContentWithFile(b,this.choice,a,Z);return this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars()),{file:Z,newFileContent:m,captureContent:b}}async formatFilePath(l){let G=await this.formatter.formatFileName(l,this.choice.name);return this.normalizeCaptureFilePath(G)}normalizeCaptureFilePath(l){let G=this.stripLeadingSlash(l);if(Gt.test(G))throw new zI(`Capture to '.base' files is not supported (${G}). Use a Template choice instead.`);return JG.test(G)||AG.test(G)?G:this.normalizeMarkdownFilePath("",G)}mergeCapturePropertyVars(l){if(!(!l||l.size===0)){for(let[G,t]of l)this.capturePropertyVars.set(G,t);x.logMessage(`CaptureChoiceEngine: Accumulated ${this.capturePropertyVars.size} structured capture variables`)}}async applyCapturePropertyVars(l){if(this.capturePropertyVars.size!==0){if(!this.shouldPostProcessFrontMatter(l,this.capturePropertyVars)){this.capturePropertyVars.clear();return}x.logMessage(`CaptureChoiceEngine: Post-processing front matter with ${this.capturePropertyVars.size} capture variables`),await this.postProcessFrontMatter(l,this.capturePropertyVars),this.capturePropertyVars.clear()}}};var _s=require("obsidian");var cp="\u2190 Back",gc=class e extends _s.FuzzySuggestModal{constructor(l,G,t){super(l.app);this.plugin=l;this.choices=G;this.choiceExecutor=new Fe(this.app,this.plugin);this.placeholderStack=[];t?.choiceExecutor&&(this.choiceExecutor=t.choiceExecutor),this.placeholderStack=t?.placeholderStack??[],this.currentPlaceholder=t?.placeholder?.trim()||void 0,this.currentPlaceholder&&this.setPlaceholder(this.currentPlaceholder)}static Open(l,G,t){new e(l,G,t).open()}renderSuggestion(l,G){G.empty(),_s.MarkdownRenderer.renderMarkdown(l.item.name,G,"",this.plugin),G.classList.add("quickadd-choice-suggestion"),l.item.name===cp&&G.classList.add("quickadd-choice-suggestion-back")}getItemText(l){return l.name}getItems(){return this.choices}async onChooseItem(l,G){l.type==="Multi"?this.onChooseMultiType(l):await this.choiceExecutor.execute(l)}onChooseMultiType(l){let G=[...l.choices],t=l.name===cp;t||G.push(new EZ(cp).addChoices(this.choices));let c=t?this.placeholderStack[this.placeholderStack.length-1]:l.placeholder?.trim()||l.name,b=t?this.placeholderStack.slice(0,-1):[...this.placeholderStack,this.currentPlaceholder];e.Open(this.plugin,G,{choiceExecutor:this.choiceExecutor,placeholder:c,placeholderStack:b})}};var $s=require("obsidian");var sW=class extends dt{constructor(l,G,t){super(l);this.app=l;this.plugin=G;this.choiceExecutor=t;this.requirements=new Map;this.templatesToScan=new Set;this.dateParser=Ee,t&&(this.variables=new Map(t.variables))}async scanString(l){let G=await this.replaceGlobalVarInString(l);this.scanVariableTokens(G),aw
2025-08-02 12:09:34 +08:00
2026-05-06 17:32:44 +08:00
${t}
2025-08-02 12:09:34 +08:00
2026-05-06 17:32:44 +08:00
QuickAdd will now revert to backup.`),e.settings=G}}e.saveSettings()}var dw=e9;var BZ=require("obsidian");async function t9(e,I,l){let G=await fetch(`https://api.github.com/repos/${e}/${I}/releases`),t=await G.json();if(!G.ok&&"message"in t||!Array.isArray(t))throw new Error(`Failed to fetch releases: ${t.message??"Unknown error"}`);let c=t.findIndex(b=>b.tag_name===l);if(c===-1)throw new Error(`Could not find release with tag ${l}`);return t.slice(0,c).filter(b=>!b.draft&&!b.prerelease)}function c9(e,I=1){let l=e.split(`
`);for(let G=0;G<l.length;G++)l[G].startsWith("#")&&(l[G]="#".repeat(I)+l[G]);return l.join(`
`)}var bi=class extends BZ.Modal{constructor(I,l){super(I),this.previousVersion=l,this.releaseNotesPromise=t9("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");let l=`### New in QuickAdd v${this.releases[0].tag_name}
`,G="Thank you for using QuickAdd! If you like the plugin, please consider supporting me by buying me a coffee. With your sponsorship, I'll be able to contribute more to my existing projects, start new ones, and be more responsive to issues & feature requests.",t='<div class="quickadd-bmac-container"><a href="https://www.buymeacoffee.com/chhoumann" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 40px !important;width: 144px !important;" ></a></div>',c=I.createDiv("quickadd-update-modal"),b=this.releases.map(m=>m.body).join(`
---
`),d=`And now, here is everything new in QuickAdd since your last update (v${this.previousVersion}):`,a=`${l}
${G}
${t}
I'd love to get your feedback on QuickAdd! Please fill out this <a href="https://forms.gle/WRq1ewcKK8qmkqps6">feedback form</a> to let me know what you think.
2025-08-02 12:09:34 +08:00
2026-05-06 17:32:44 +08:00
${d}
2025-08-02 12:09:34 +08:00
---
2026-05-06 17:32:44 +08:00
${c9(b)}`;BZ.MarkdownRenderer.renderMarkdown(a,c,this.app.vault.getRoot().path,new BZ.Component)}};var Bl=require("obsidian");var di=class extends Bl.Modal{constructor(l,G){super(l);this.showAdvancedSettings=!1;this.settings=G,this.waitForClose=new Promise((t,c)=>{this.rejectPromise=c,this.resolvePromise=t}),this.open(),this.display()}get systemPromptTokenLength(){let l=xe(this.settings.model);return l?$G(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 ol.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 Bl.Setting(l).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(G=>{let t=Wt();for(let c of t)G.addOption(c,c);G.addOption("Ask me","Ask me"),G.setValue(this.settings.model),G.onChange(c=>{this.settings.model=c,this.reload()})})}addOutputVariableNameSetting(l){new Bl.Setting(l).setName("Output variable name").setDesc("The name of the variable used to store the AI Assistant output, i.e. {{value:output}}.").addText(G=>{G.setValue(this.settings.outputVariableName).onChange(t=>{this.settings.outputVariableName=t})})}addSystemPromptSetting(l){new Bl.Setting(l).setName("System Prompt").setDesc("The system prompt for the AI Assistant");let G=this.contentEl.createEl("div"),t=G.createEl("span");t.style.color="var(--text-muted-color)";let c=G.createEl("div",{text:"Exact for OpenAI models; estimates for others."});c.style.color="var(--text-muted-color)",c.style.fontSize="var(--font-ui-smaller)",G.appendChild(t),G.appendChild(c);let b=new Bl.TextAreaComponent(l);b.setValue(this.settings.systemPrompt).onChange(async m=>{this.settings.systemPrompt=m,Z.innerText=await d.format(m),a()}),new tG(this.app,b.inputEl,$I.instance);let d=new wG(this.app,$I.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"),a=(0,Bl.debounce)(()=>{t.innerText=`Token count: ${this.systemPromptTokenLength}`},50);a(),(async()=>Z.innerText=await d.format(this.settings.systemPrompt??""))()}addShowAdvancedSettingsToggle(l){new Bl.Setting(l).setName("Show advanced settings").setDesc("Show advanced settings such as temperature, top p, and frequency penalty.").addToggle(G=>{G.setValue(this.showAdvancedSettings),G.onChange(t=>{this.showAdvancedSettings=t,this.reload()})})}addTemperatureSetting(l){new Bl.Setting(l).setName("Temperature").setDesc("Sampling temperature. Higher values like 0.8 makes the output more random, whereas lower values like 0.2 will make it more focused and deterministic. The default is 1.").addSlider(G=>{G.setLimits(0,1,.1),G.setDynamicTooltip(),G.setValue(this.settings.modelParameters.temperature??1),G.onChange(t=>{this.settings.modelParameters.temperature=t})})}addTopPSetting(l){new Bl.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,
2025-08-02 12:09:34 +08:00
2026-05-06 17:32:44 +08:00
/* nosourcemap */