392 lines
1.1 MiB
Executable File
392 lines
1.1 MiB
Executable File
/*
|
||
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
|
||
if you want to view the source, please visit the github repository of this plugin
|
||
*/
|
||
|
||
var rY=Object.create;var Yf=Object.defineProperty;var nY=Object.getOwnPropertyDescriptor;var iY=Object.getOwnPropertyNames;var oY=Object.getPrototypeOf,sY=Object.prototype.hasOwnProperty;var vR=r=>{throw TypeError(r)};var aY=(r,t,e)=>t in r?Yf(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var x=(r,t,e)=>()=>{if(e)throw e[0];try{return r&&(t=r(r=0)),t}catch(n){throw e=[n],n}};var cb=(r,t)=>{for(var e in t)Yf(r,e,{get:t[e],enumerable:!0})},yR=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of iY(t))!sY.call(r,i)&&i!==e&&Yf(r,i,{get:()=>t[i],enumerable:!(n=nY(t,i))||n.enumerable});return r};var lY=(r,t,e)=>(e=r!=null?rY(oY(r)):{},yR(t||!r||!r.__esModule?Yf(e,"default",{value:r,enumerable:!0}):e,r)),cY=r=>yR(Yf({},"__esModule",{value:!0}),r);var fe=(r,t,e)=>aY(r,typeof t!="symbol"?t+"":t,e),fk=(r,t,e)=>t.has(r)||vR("Cannot "+e);var L=(r,t,e)=>(fk(r,t,"read from private field"),e?e.call(r):t.get(r)),qe=(r,t,e)=>t.has(r)?vR("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(r):t.set(r,e),Oe=(r,t,e,n)=>(fk(r,t,"write to private field"),n?n.call(r,e):t.set(r,e),e),tt=(r,t,e)=>(fk(r,t,"access private method"),e);var oD,sD,aD=x(()=>{oD=r=>{let t,e=new Set,n=(c,d)=>{let u=typeof c=="function"?c(t):c;if(!Object.is(u,t)){let p=t;t=d??(typeof u!="object"||u===null)?u:Object.assign({},t,u),e.forEach(m=>m(t,p))}},i=()=>t,a={setState:n,getState:i,getInitialState:()=>l,subscribe:c=>(e.add(c),()=>e.delete(c))},l=t=r(n,i,a);return a},sD=(r=>r?oD(r):oD)});function Sh(r){if(r.kind)return r.kind;let t=(r.name??"").toLowerCase(),e=cD(r.endpoint),n=i=>e===i||e.endsWith(`.${i}`);return t==="anthropic"||n("api.anthropic.com")?"anthropic":t==="gemini"||n("generativelanguage.googleapis.com")?"gemini":"openai"}function lD(r){let t=Sh(r);return t==="openai"&&cD(r.endpoint)==="api.openai.com"?"openai-responses":t}function cD(r){let t=(r??"").trim();if(!t)return"";for(let e of[t,`https://${t}`])try{return new URL(e).hostname.toLowerCase()}catch{}return""}function $K(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function Qb(r,t){let e=$K(r),n=new Set(t.map(o=>o.id).filter(o=>!!o)),i=e;for(let o=2;n.has(i);o++)i=`${e}-${o}`;return i}function Xb(r){let t=!1,e=new Set;for(let n of r){if(n.id&&!e.has(n.id)){e.add(n.id);continue}n.id=Qb(n.id??n.name,r),e.add(n.id),t=!0}return t}function Nl(r,t){return t&&t.name===r?t:void 0}function lp(r){return r.map((t,e)=>({model:t,index:e})).sort((t,e)=>{let n=+!!t.model.deprecated-+!!e.model.deprecated;if(n!==0)return n;let i=t.model.releaseDate??"",o=e.model.releaseDate??"";return i!==o?i?o&&i<o?1:-1:1:t.index-e.index}).map(({model:t})=>t)}function Jb(r){return Ah[r].map(t=>({...t}))}var Ah,dD,FK,MK,Zb,gi=x(()=>{Ah={openai:[{name:"gpt-6-sol",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-6-luna",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-6-astra",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.6-sol",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.6-luna",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.6-terra",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.5",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.4",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!0},{name:"gpt-5.4-mini",maxTokens:4e5,maxOutputTokens:128e3,supportsTemperature:!0},{name:"gpt-5.4-nano",maxTokens:4e5,maxOutputTokens:128e3,supportsTemperature:!0},{name:"gpt-4.1",maxTokens:1047576,maxOutputTokens:32768,supportsTemperature:!0},{name:"gpt-4.1-mini",maxTokens:1047576,maxOutputTokens:32768,supportsTemperature:!0},{name:"gpt-4o",maxTokens:128e3,maxOutputTokens:16384,supportsTemperature:!0},{name:"gpt-4o-mini",maxTokens:128e3,maxOutputTokens:16384,supportsTemperature:!0},{name:"o3",maxTokens:2e5,maxOutputTokens:1e5,supportsTemperature:!1},{name:"o4-mini",maxTokens:2e5,maxOutputTokens:1e5,supportsTemperature:!1}],google:[{name:"gemini-3.8-flash",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-3.7-flash",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-3.6-flash",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-3.5-flash",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-3.5-flash-lite",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-3.1-pro-preview",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-3.1-flash-lite",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-3-flash-preview",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-2.5-pro",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-2.5-flash",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0},{name:"gemini-2.5-flash-lite",maxTokens:1048576,maxOutputTokens:65536,supportsTemperature:!0}],anthropic:[{name:"claude-opus-5-5",maxTokens:1e6,maxOutputTokens:128e3,supportsTemperature:!1},{name:"claude-fable-5-1",maxTokens:1e6,maxOutputTokens:128e3,supportsTemperature:!1},{name:"claude-fable-5",maxTokens:1e6,maxOutputTokens:128e3,supportsTemperature:!1},{name:"claude-sonnet-5",maxTokens:1e6,maxOutputTokens:128e3,supportsTemperature:!1},{name:"claude-opus-4-8",maxTokens:1e6,maxOutputTokens:128e3,supportsTemperature:!1},{name:"claude-opus-4-5",maxTokens:2e5,maxOutputTokens:64e3,supportsTemperature:!0},{name:"claude-haiku-4-5",maxTokens:2e5,maxOutputTokens:64e3,supportsTemperature:!0}]},dD={openai:["gpt-4-32k","gpt-4-1106-preview"],google:["gemini-1.5-pro","gemini-1.5-flash","gemini-1.5-flash-8b"]};FK={id:"openai",name:"OpenAI",endpoint:"https://api.openai.com/v1",kind:"openai",apiKey:"",models:Jb("openai"),autoSyncModels:!0,modelSource:"modelsDev"},MK={id:"gemini",name:"Gemini",endpoint:"https://generativelanguage.googleapis.com",kind:"gemini",apiKey:"",models:Jb("google"),autoSyncModels:!0,modelSource:"modelsDev"},Zb=[FK,MK]});function uD(r,t){return Object.prototype.hasOwnProperty.call(r,t)?r[t]:void 0}function Ih(r,t=cp){let e=r.trim();if(!e)return r;let n=uD(t,e.toLowerCase());if(n)return n;let[i,...o]=e.split(/\s+/),s=uD(t,i.toLowerCase());return s?[s,...o].join(" "):r}function pD(r){let t={},e=r.split(/\r?\n/);for(let n of e){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.indexOf("=");if(o===-1)continue;let s=i.slice(0,o).trim().toLowerCase(),a=i.slice(o+1).trim();!s||!a||Object.defineProperty(t,s,{value:a,enumerable:!0,writable:!0,configurable:!0})}return t}function yS(r){return Object.entries(r).filter(([t,e])=>t&&e).map(([t,e])=>`${t} = ${e}`).join(`
|
||
`)}function Ph(r){let t=Object.entries(r);if(t.length===0)return[];let n=["t","tm","yd"].map(s=>{let a=r[s];return a?[s,a]:null}).filter(s=>s!==null),i=new Set(n.map(([s])=>s)),o=t.filter(([s])=>!i.has(s)).sort((s,a)=>{let l=s[0].length-a[0].length;return l!==0?l:s[0].localeCompare(a[0])});return[...n,...o]}function ew(r){return Ph(r).map(([t,e])=>`${t}=${e}`).join(", ")}var cp,wd=x(()=>{cp={t:"today",tm:"tomorrow",yd:"yesterday",nw:"next week",nm:"next month",ny:"next year",lw:"last week",lm:"last month",ly:"last year"}});var tw,bS=x(()=>{gi();wd();tw={choices:[],inputPrompt:"single-line",persistInputPromptDrafts:!0,useSelectionAsCaptureValue:!0,namePastedImagesAfterNoteTitle:!1,searchNestedChoices:!0,templateFolderLauncherRow:"bottom",devMode:!1,templateFolderPaths:[],announceUpdates:"major",version:"0.0.0",globalVariables:{},onePageInputEnabled:!1,disableOnlineFeatures:!0,enableUriCallbacks:!1,enableRibbonIcon:!1,showCaptureNotification:!0,showInputCancellationNotification:!1,enableTemplatePropertyTypes:!1,dateAliases:cp,showDateCalendar:!0,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}^{\\text{new}}:=w_{ij}^{\\text{current}}+\\eta\\cdot\\delta_j\\cdot 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:Zb,confirmToolCalls:"destructive"},migrations:{useQuickAddTemplateFolder:!1,incrementFileNameSettingMoveToDefaultBehavior:!1,consolidateFileExistsBehavior:!1,repairTemplateFileExistsBehavior:!1,mutualExclusionInsertAfterAndWriteToBottomOfFile:!1,setVersionAfterUpdateModalRelease:!1,addDefaultAIProviders:!1,removeMacroIndirection:!1,migrateFileOpeningSettings:!1,backfillFileOpeningDefaults:!1,setProviderModelDiscoveryMode:!1,migrateProviderApiKeysToSecretStorage:!1,migrateToMultipleTemplateFolders:!1,refreshStaleDefaultModelSeeds:!1,pinAiModelRefs:!1}}});function ke(r){if(typeof structuredClone=="function")try{return structuredClone(r)}catch{}return Vl(r,new Map)}function Vl(r,t){if(r===null||typeof r!="object")return r;if(t.has(r))return t.get(r);if(r instanceof Date){let i=new Date(r.getTime());return t.set(r,i),i}if(Array.isArray(r)){let i=[];t.set(r,i);for(let o of r)i.push(Vl(o,t));return i}if(r instanceof Map){let i=new Map;t.set(r,i);for(let[o,s]of r.entries())i.set(Vl(o,t),Vl(s,t));return i}if(r instanceof Set){let i=new Set;t.set(r,i);for(let o of r.values())i.add(Vl(o,t));return i}if(r instanceof RegExp){let i=new RegExp(r.source,r.flags);return i.lastIndex=r.lastIndex,t.set(r,i),i}if(r instanceof ArrayBuffer){let i=r.slice(0);return t.set(r,i),i}if(ArrayBuffer.isView(r)){if(r instanceof DataView){let a=new DataView(Vl(r.buffer,t),r.byteOffset,r.byteLength);return t.set(r,a),a}let i=r,o=Vl(i.buffer,t),s=new i.constructor(o,i.byteOffset,i.length);return t.set(r,s),s}let e=Object.getPrototypeOf(r),n=Object.create(e);t.set(r,n);for(let[i,o]of Object.entries(r))Object.defineProperty(n,i,{value:Vl(o,t),writable:!0,enumerable:!0,configurable:!0});return n}var tn=x(()=>{});var U,je=x(()=>{aD();bS();tn();U=(()=>{let r=sD((i,o)=>({...ke(tw)})),{getState:t,setState:e,subscribe:n}=r;return{getState:t,replaceState:i=>e(i,!0),setState:e,subscribe:n}})()});var Cd,$h,S,ye=x(()=>{Cd=class Cd{register(t){return Cd.loggers.push(t),this}logError(t){let e=t instanceof Error?t.message:t,n=t instanceof Error?t.stack:void 0,i=t instanceof Error?t:void 0;Cd.loggers.forEach(o=>o.logError(e,n,i))}logWarning(t){let e=t instanceof Error?t.message:t,n=t instanceof Error?t.stack:void 0,i=t instanceof Error?t:void 0;Cd.loggers.forEach(o=>o.logWarning(e,n,i))}logMessage(t){let e=t instanceof Error?t.message:t,n=t instanceof Error?t.stack:void 0,i=t instanceof Error?t:void 0;Cd.loggers.forEach(o=>o.logMessage(e,n,i))}};Cd.loggers=[];$h=Cd,S=new $h});var xr,mD,fD,Vi,xd,Ed,Yo,hD,wS,gD,CS,fo,Td,Bl,dp,rw,Ss,xS,ES,xt,lr,Rn,Fh,nw,As,iw,Mh,ho,Rh,Oh,TS,_S,vD,yD,bD,wD,CD,xD,ED,TD,_D,kD,SD,kS,AD,ID,PD,$D,FD,MD,RD,OD,DD,LD,ND,SS,AS,IS,PS,$S,VD,BD,UD,qD,ow,Dh,Sa,zD,Le=x(()=>{xr="{{value}}",mD="{{name}}",fD=new RegExp(/^-?[0-9]*$/),Vi="top",xd="bottom",Ed="cursor",Yo="ordered",hD=new RegExp(/{{DATE(\+-?[0-9]+)?(?:\|((?:startof|endof):[a-z]+))?(?:\|case:([a-z-]+))?}}/i),wS=new RegExp(/{{DATE:((?:\[[^\]\n\r]*\]|\[(?![^\]\n\r]*\])|[^}\n\r+|[]|\|(?!(?:startof|endof):[a-z])(?!(?:case):[a-z-]+}}))*)(\+-?[0-9]+)?(?:\|((?:startof|endof):[a-z]+))?(?:\|case:([a-z-]+))?}}/i),gD=new RegExp(/{{TIME(?:\|case:([a-z-]+))?}}/i),CS=new RegExp(/{{TIME:((?:\[[^\]\n\r]*\]|\[(?![^\]\n\r]*\])|[^}\n\r+|[]|\|(?!(?:case):[a-z-]+}}))*)(?:\|case:([a-z-]+))?}}/i),fo=new RegExp(/{{(?:NAME|VALUE)(?!:)(?:\|[^\n\r}]*)?}}/i),Td=new RegExp(/{{VALUE:([^\n\r}]*)}}/i),Bl="FIELD:",dp=new RegExp(/{{FIELD:([^\n\r}|{]*)(\|[^\n\r}{]*)?}}/i),rw=new RegExp(/{{FILE:([^\n\r{}]*)}}/i),Ss=new RegExp(/{{VDATE:([^\n\r},|{]*)(?:,([^\n\r}|{]*))?(?:\|([^\n\r}{]*))?}}/i),xS=new RegExp(/{{LINKCURRENT}}/i),ES=new RegExp(/{{LINKSECTION}}/i),xt=new RegExp(/\.md$/i),lr=new RegExp(/\.canvas$/i),Rn=new RegExp(/\.base$/i),Fh=new RegExp(/\.js$/i),nw=new RegExp(/{{MACRO:([^\n\r}]*)}}/i),As=new RegExp(/{{TEMPLATE:([^\n\r}]*\.(?:md|canvas|base))}}/i),iw=new RegExp(/{{GLOBAL_VAR:([^\n\r}]*)}}/i),Mh=new RegExp(/{{MVALUE}}/i),ho=new RegExp(/{{TITLE}}/i),Rh=new RegExp(/{{PROPERTY}}/i),Oh=new RegExp(/{{SELECTED}}/i),TS=new RegExp(/{{CLIPBOARD}}/i),_S=new RegExp(/{{RANDOM:(\d+)}}/i),vD=new RegExp(/\[\[([^\]]*)$/),yD=new RegExp(/#([^ ]*)$/),bD=new RegExp(/{{[D]?[A]?[T]?[E]?[}]?[}]?$/i),wD=new RegExp(/{{[D]?[A]?[T]?[E]?[:]?$|{{DATE:[^\n\r}]*}}$/i),CD=new RegExp(/{{[N]?[A]?[M]?[E]?[}]?[}]?$/i),xD=new RegExp(/{{[V]?[A]?[L]?[U]?[E]?[}]?[}]?$/i),ED=new RegExp(/{{[V]?[A]?[L]?[U]?[E]?[:]?$|{{VALUE:[^\n\r}]*}}$/i),TD=new RegExp(/{{[V]?[D]?[A]?[T]?[E]?[:]?$|{{VDATE:[^\n\r}]*}}$/i),_D=new RegExp(/{{[L]?[I]?[N]?[K]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),kD=new RegExp(/^\{\{(?:l(?:i(?:n(?:k(?:s(?:e(?:c(?:t(?:i(?:o(?:n(?:\}\}?)?)?)?)?)?)?)?)?)?)?)?)?$/i),SD=new RegExp(/{{[F]?[I]?[L]?[E]?[N]?[A]?[M]?[E]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),kS=new RegExp(/{{[F]?[O]?[L]?[D]?[E]?[R]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),AD=new RegExp(/{{[F]?[O]?[L]?[D]?[E]?[R]?[}]?[}]?$/i),ID=new RegExp(/{{[F]?[I]?[L]?[E]?[:]?$/i),PD=new RegExp(/{{[F]?[I]?[E]?[L]?[D]?[:]?$/i),$D=new RegExp(/{{[T]?[E]?[M]?[P]?[L]?[A]?[T]?[E]?[:]?$|{{TEMPLATE:[^\n\r}]*[}]?[}]?$/i),FD=new RegExp(/{{[M]?[A]?[C]?[R]?[O]?[:]?$|{{MACRO:[^\n\r}]*}}$/i),MD=new RegExp(/{{[M]?[V]?[A]?[L]?[U]?[E]?[}]?[}]?/i),RD=new RegExp(/{{[T]?[I]?[T]?[L]?[E]?[}]?[}]?/i),OD=new RegExp(/{{[P]?[R]?[O]?[P]?[E]?[R]?[T]?[Y]?[}]?[}]?$/i),DD=/{{(?:C(?:U(?:R(?:S(?:O(?:R)?)?)?)?)?)?[}]?[}]?$/i,LD=new RegExp(/{{[S]?[E]?[L]?[E]?[C]?[T]?[E]?[D]?[}]?[}]?/i),ND=new RegExp(/{{[C]?[L]?[I]?[P]?[B]?[O]?[A]?[R]?[D]?[}]?[}]?$/i),SS=new RegExp(/{{[D]?[A]?[I]?[L]?[Y]?[}]?[}]?$|{{DAILY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),AS=new RegExp(/{{[W]?[E]?[E]?[K]?[L]?[Y]?[}]?[}]?$|{{WEEKLY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),IS=new RegExp(/{{[M]?[O]?[N]?[T]?[H]?[L]?[Y]?[}]?[}]?$|{{MONTHLY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),PS=new RegExp(/{{[Q]?[U]?[A]?[R]?[T]?[E]?[R]?[L]?[Y]?[}]?[}]?$|{{QUARTERLY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),$S=new RegExp(/{{[Y]?[E]?[A]?[R]?[L]?[Y]?[}]?[}]?$|{{YEARLY\|[l]?[i]?[n]?[k]?[}]?[}]?$/i),VD=new RegExp(/{{[R]?[A]?[N]?[D]?[O]?[M]?[:]?$|{{RANDOM:[^\n\r}]*}}$/i),BD=new RegExp(/{{[G]?[L]?[O]?[B]?[A]?[L]?[_]?[V]?[A]?[R]?[:]?$|{{GLOBAL_VAR:[^\n\r}]*}}$/i),UD=new RegExp(/{{[T]?[I]?[M]?[E]?[}]?[}]?/i),qD=new RegExp(/{{[T]?[I]?[M]?[E]?[:]?$|{{TIME:[^\n\r}]*}}$/i),ow="__qa.",Dh=`${ow}captureTargetFilePath`,Sa=`${ow}dateOrigin`,zD=new RegExp(/\[\[([^\]]*)\]\]/)});function jD(r){return typeof r=="string"?r:""}function go(r){return jD(r).replace(/^\s+(?=[\\/])/,"").replace(/[\\/]+/g,"/").replace(/^\/|\/$/g,"").trimEnd().replace(/\/$/,"").normalize("NFC")}function cr(r){return jD(r).trim().replace(/[\\/]+/g,"/").replace(/^\/|\/$/g,"").normalize("NFC")}function Is(r){return((0,RS.normalizePath)(r).split("/").pop()??"").replace(/\.(md|canvas|base)$/i,"")}function ei(r){let t=(0,RS.normalizePath)(r),e=t.lastIndexOf("/");return e===-1?"":t.slice(0,e)}var RS,Dr=x(()=>{RS=require("obsidian")});function Ps(r){return xt.test(r)||lr.test(r)||Rn.test(r)}function nn(r,t){let e=En(t);if(!e)return null;let n=r.vault.getAbstractFileByPath(e);return n instanceof YD.TFile?n:null}function En(r){let t=cr(r);return t?Ps(t)?t:`${t}.md`:""}function ti(r){if(!Array.isArray(r))return[];let t=new Set,e=[];for(let n of r){if(typeof n!="string")continue;let i=cr(n);!i||t.has(i)||(t.add(i),e.push(i))}return e}function KD(r,t){return t.length===0?!0:t.some(e=>r===e||r.startsWith(`${e}/`))}var YD,Jt=x(()=>{YD=require("obsidian");Le();Dr()});function Aa(r){return/\{\{[^}]*\}\}/.test(r)}var Nh=x(()=>{});function Bi(r){if(r.nodeType===Node.DOCUMENT_NODE)return r;let t=r.ownerDocument;if(!t)throw new Error("Unable to resolve owner document for DOM node.");return t}function Vh(r){let t=Bi(r).defaultView;if(!t)throw new Error("Unable to resolve owner window for DOM node.");return t}function At(r,t){return Bi(r).win.createEl(t)}function _d(r,t){return Bi(r).createTextNode(t)}var Ko=x(()=>{});var sw=x(()=>{});var at,ri=x(()=>{at=class extends Error{constructor(t){super(t||"Macro execution aborted"),this.name="MacroAbortError"}}});function on(){return new et(ql)}var et,ql,rr=x(()=>{ri();et=class extends at{},ql="Input cancelled by user"});function Ia(r,t){if(r instanceof Error){if(!t)return r;let n=new Error(`${t}: ${r.message}`);return n.name=r.name,n.stack=r.stack,n}let e=t?`${t}: ${String(r)}`:String(r);return new Error(e)}function Be(r){return r instanceof et?!0:typeof r=="string"&&DK.has(r)}function LS(r){return typeof r=="object"&&r!==null||typeof r=="function"}function VK(r,t){let e=r;for(let n=0;n<NK&&LS(e);n++){let i=DS.get(e);if(i!==void 0&&t-i<LK)return!0;e=e.cause}return!1}function Me(r,t,e="ERROR"){let n=Date.now();if(VK(r,n))return!1;LS(r)&&DS.set(r,n);let i=Ia(r,t);switch(e){case"ERROR":S.logError(i);break;case"WARNING":S.logWarning(i);break;case"LOG":S.logMessage(i);break;default:S.logError(i)}return!0}function XD(r){LS(r)&&DS.set(r,Date.now())}function kd(r,t,e="ERROR"){return Be(r)?!1:Me(r,t,e)}function JD(r,t,e="ERROR"){try{return r()}catch(n){Me(n,t,e);return}}function $s(r,t){let e=n=>{kd(n,r)};return(...n)=>{try{let i=t(...n);typeof i?.then=="function"&&Promise.resolve(i).catch(e)}catch(i){e(i)}}}function ZD(r){let t=r.then(void 0,e=>{throw Be(e)&&t.catch(()=>{}),e});return t}var OS,DK,DS,LK,NK,nt=x(()=>{ye();sw();rr();OS=100;DK=new Set(["no input given.","No input given.","cancelled"]),DS=new WeakMap,LK=1e4,NK=8});function e0(r,t){return BK.test(r[t])}function UK(r){if(!r.includes("![["))return r;let t="",e=0,n=0,i=0;for(;n<r.length;){if(r.charCodeAt(n)===33&&r.charCodeAt(n+1)===91&&r.charCodeAt(n+2)===91){for(i<n+3&&(i=n+3);i<r.length&&r.charCodeAt(i)!==93;)i++;if(i<r.length&&r.charCodeAt(i+1)===93){t+=r.slice(e,n),n=i+2,e=n;continue}}n++}return t+r.slice(e)}function qK(r){if(!r.includes("[["))return r;let t="",e=0,n=0,i=0,o=0;for(;n<r.length;){if(r.charCodeAt(n)===91&&r.charCodeAt(n+1)===91){for(i<n+2&&(i=n+2);i<r.length;){let s=r.charCodeAt(i);if(s===93||s===124)break;i++}if(i<r.length&&r.charCodeAt(i)===93){if(r.charCodeAt(i+1)===93){t+=r.slice(e,n)+r.slice(n+2,i),n=i+2,e=n;continue}}else if(i<r.length){for(o<i+1&&(o=i+1);o<r.length&&r.charCodeAt(o)!==93;)o++;if(o<r.length&&r.charCodeAt(o+1)===93){t+=r.slice(e,n)+r.slice(i+1,o),n=o+2,e=n;continue}}}n++}return t+r.slice(e)}function zK(r){let t=0;if(r.charCodeAt(0)===35){for(;r.charCodeAt(t)===35;)t++;for(;t<r.length&&e0(r,t);)t++}let e=r.length;if(e>t&&r.charCodeAt(e-1)===35){for(;e>t&&r.charCodeAt(e-1)===35;)e--;for(;e>t&&e0(r,e-1);)e--}return r.slice(t,e)}function HK(r){if(!r.includes("[[")&&!r.includes("]]"))return r;let t="",e=0,n=0;for(;n<r.length;){let i=r.charCodeAt(n);if(i===91&&r.charCodeAt(n+1)===91||i===93&&r.charCodeAt(n+1)===93){t+=r.slice(e,n),n+=2,e=n;continue}n++}return t+r.slice(e)}function NS(r){return HK(zK(qK(UK(r)).replace(WK,""))).trim()}var BK,WK,t0=x(()=>{BK=/^\s$/;WK=/[*_`~]/g});function sn(r){return typeof r=="string"?r:r==null?"":String(r)}function r0(r,t){r.scope?.register(["Mod","Shift"],"Enter",()=>(t(),!1)),typeof r.setInstructions=="function"&&r.setInstructions([{command:"\u2191\u2193",purpose:"to navigate"},{command:"\u21B5",purpose:"to choose"},{command:"ctrl/cmd+shift+\u21B5",purpose:"to skip (leave empty)"},{command:"esc",purpose:"to cancel"}]);let e=r.modalEl;if(e&&typeof e.createDiv=="function"){let i=e.createDiv({cls:"qa-suggester-skip-bar"}).createEl("button",{text:"Skip (leave empty)",cls:"qa-suggester-skip-button"});i.type="button",i.setAttribute("aria-label","Skip and leave empty"),i.addEventListener("click",o=>{o.preventDefault(),t()})}}function pp(r){let t=!1;return e=>{t||(t=!0,S.logWarning(Ia(e,r)))}}function zl(r){return sn(r)}function Ht(r){return r.normalize("NFC").toLowerCase()}function aw(r){return r.toLowerCase().endsWith(".md")?r.slice(0,-3):r}function lw(r,t,e,n,i={}){let o=r.value;r.value=o.slice(0,t)+n+o.slice(e),r.setSelectionRange(t+n.length,t+n.length);let s=new Event("input",{bubbles:!0});i.fromCompletion&&(s.fromCompletion=!0),r.dispatchEvent(s)}function n0(r,t,e){if(r.replaceChildren(),!e){r.textContent=t;return}let n="",i=[],o=[],s=0;for(let u of t){let p=u.toLowerCase(),m=s,h=s+u.length;for(let g=0;g<p.length;g++)i.push(m),o.push(h);n+=p,s=h}let a="";for(let u of e)a+=u.toLowerCase();let l=0,c=0,d=n.indexOf(a,c);for(;d!==-1;){let u=Math.max(l,i[d]),p=o[d+a.length-1];if(p>u){u>l&&r.append(_d(r,t.slice(l,u)));let m=At(r,"mark");m.className="qa-highlight",m.textContent=t.slice(u,p),r.append(m),l=p}c=d+a.length,d=n.indexOf(a,c)}l<t.length&&r.append(_d(r,t.slice(l)))}function Fs(r,t,e,n=0){r.replaceChildren();let i=0;for(let[o,s]of e){let a=Math.max(i,o-n),l=Math.min(t.length,s-n);if(l<=a)continue;a>i&&r.append(_d(r,t.slice(i,a)));let c=At(r,"mark");c.className="qa-highlight",c.textContent=t.slice(a,l),r.append(c),i=l}i<t.length&&r.append(_d(r,t.slice(i)))}function Pa(r,t=!1){let e=Object.assign(new Event("input",{bubbles:!0}),{fromCompletion:!0,...t?{keepOpen:!0}:{}});r.dispatchEvent(e)}var an=x(()=>{ye();Ko();nt();t0()});function YK(r,t,e){let n=r.closest(".modal")?.querySelector(".qa-prompt-actions");if(!n)return!1;let i=n.getBoundingClientRect(),o=i.height>0&&i.top>=t.bottom,s=t.bottom+Uh+e>i.top;return o&&s}function KK(r,t){let e=r.getBoundingClientRect(),n=r.ownerDocument,i=n.defaultView?.visualViewport??{offsetLeft:0,offsetTop:0,width:n.documentElement.clientWidth,height:n.documentElement.clientHeight},o=Math.max(e.width,Math.min(jK,i.width));t.setCssStyles({maxHeight:"",width:`${o}px`,left:"0px",top:"0px"});let s=t.getBoundingClientRect(),a=parseFloat(getComputedStyle(n.documentElement).getPropertyValue("--keyboard-height"))||0,l=Math.min(i.offsetTop+i.height,n.documentElement.clientHeight-a),c=parseFloat(getComputedStyle(n.body).getPropertyValue("--safe-area-inset-top"))||0,d=r.closest(".modal.mod-settings")?.querySelector(".modal-header"),u=Math.max(i.offsetTop+c,d?.getBoundingClientRect().bottom??0),p=l-e.bottom-Uh,m=e.top-Uh-u,h=s.height<=p,v=s.height<=m?!h||YK(r,e,s.height):!h&&m>p,b=Math.min(s.height,v?m:p),y=v?e.top-Uh-b:e.bottom+Uh,C=Math.max(i.offsetLeft,Math.min(e.left,i.offsetLeft+i.width-o));t.setCssStyles({maxHeight:b<s.height?`${b}px`:"",left:`${C-s.left}px`,top:`${y-s.top}px`})}function QK(r){let t=Array.from(r.childNodes).flatMap(e=>e.nodeName==="MARK"?Array.from(e.childNodes):[e]).filter(e=>e.nodeType===Node.TEXT_NODE&&!!e.nodeValue?.includes("/"));for(let e of t){let n=(e.nodeValue??"").match(/[^/]*\/|[^/]+$/g)??[];e.replaceWith(...n.flatMap(i=>i.endsWith("/")?[i,At(r,"wbr")]:[i]))}}var cw,GK,Uh,jK,XK,VS,Bh,Er,Ms=x(()=>{cw=require("obsidian");ye();Ko();an();GK=(r,t)=>(r%t+t)%t,Uh=4,jK=300;XK=0,VS=class{constructor(t,e,n,i,o){this.isOpen=!1;this.owner=t,this.containerEl=e,this.optionIdPrefix=i,this.onActiveOptionChange=o,this.clickListener=a=>{let l=this.findSuggestionItem(a.target);l&&this.onSuggestionClick(a,l)},this.mousemoveListener=a=>{let l=this.findSuggestionItem(a.target);l&&this.onSuggestionMouseover(a,l)},e.addEventListener("click",this.clickListener),e.addEventListener("mousemove",this.mousemoveListener);let s={ArrowUp:()=>this.selectedItem-1,ArrowDown:()=>this.selectedItem+1,PageUp:()=>Math.max(0,this.selectedItem-5),PageDown:()=>Math.min(this.suggestions.length-1,this.selectedItem+5)};for(let[a,l]of Object.entries(s))n.register([],a,c=>{if(!c.isComposing&&this.isOpen)return this.setSelectedItem(l(),!0),!1})}findSuggestionItem(t){let e=this.containerEl.ownerDocument.defaultView;if(!e||!(t instanceof e.Element))return null;let n=t.closest(".suggestion-item");return n&&this.containerEl.contains(n)?n:null}onSuggestionClick(t,e){t.preventDefault();let n=this.suggestions.indexOf(e);this.setSelectedItem(n,!1),this.useSelectedItem(t)}onSuggestionMouseover(t,e){let n=this.suggestions.indexOf(e);this.setSelectedItem(n,!1)}setSuggestions(t){this.containerEl.replaceChildren();let e=[];if(t.forEach((n,i)=>{let o=this.containerEl.createDiv({cls:"suggestion-item"});o.setAttribute("role","option"),o.setAttribute("aria-selected","false"),o.setAttribute("id",`${this.optionIdPrefix}-option-${i}`),this.owner.renderSuggestion(n,o),QK(o),e.push(o)}),this.values=t,this.suggestions=e,t.length===0){this.isOpen=!1,this.onActiveOptionChange(null);return}this.setSelectedItem(0,!1),this.isOpen=!0}useSelectedItem(t){let e=this.values[this.selectedItem];e&&this.owner.selectSuggestion(e,t)}setSelectedItem(t,e){if(!this.suggestions?.length)return;let n=GK(t,this.suggestions.length),i=this.suggestions[this.selectedItem],o=this.suggestions[n];i?.classList.remove("is-selected"),o?.classList.add("is-selected"),i?.setAttribute("aria-selected","false"),o?.setAttribute("aria-selected","true"),this.onActiveOptionChange(o?.id??null),this.selectedItem=n,e&&o.scrollIntoView(!1)}close(){this.isOpen=!1,this.onActiveOptionChange(null)}getIsOpen(){return this.isOpen}},Bh=new WeakMap,Er=class{constructor(t,e,n){this.currentRequestId=0;this.isOpen=!1;this.destroyed=!1;this.currentQuery="";this.listQuery=null;this.renderMatch=n0;let i=this.constructor.name,o=Bh.get(e);o||(o=new Map,Bh.set(e,o));let s=o.get(i);s&&s.destroy(),Bh.set(e,o),o.set(i,this),this.app=t,this.inputEl=e,this.scope=new cw.Scope(n),this.suggestEl=this.inputEl.ownerDocument.win.createDiv(),this.suggestEl.classList.add("suggestion-container","qa-text-input-suggest");let a=this.suggestEl.createDiv({cls:"suggestion"});this.listboxId=`qa-suggest-listbox-${++XK}`,a.id=this.listboxId,a.setAttribute("role","listbox"),a.setAttribute("aria-label","Suggestions"),this.suggest=new VS(this,a,this.scope,this.listboxId,l=>this.setActiveDescendant(l)),this.scope.register([],"Escape",this.close.bind(this)),this.scope.register([],"Enter",l=>{if(!(l.isComposing||!this.suggest.getIsOpen()))return this.useSelectedItem(l),!1}),this.debouncedOnInputChanged=(0,cw.debounce)(this.onInputChanged.bind(this),50),this.inputEventListener=l=>this.debouncedOnInputChanged(l),this.focusEventListener=()=>this.debouncedOnInputChanged(),this.inputBlurListener=this.close.bind(this),this.inputEl.addEventListener("input",this.inputEventListener),this.inputEl.addEventListener("focus",this.focusEventListener),this.inputEl.addEventListener("blur",this.inputBlurListener),this.inputEl.setAttribute("role","combobox"),this.inputEl.setAttribute("aria-autocomplete","list"),this.inputEl.setAttribute("aria-expanded","false"),this.inputEl.setAttribute("aria-controls",this.listboxId),this.inputEl.setAttribute("aria-haspopup","listbox"),this.suggestEl.addEventListener("mousedown",l=>{l.preventDefault()}),this.globalClickListener=this.onGlobalClick.bind(this),this.globalWheelListener=this.onGlobalWheel.bind(this),this.globalScrollListener=l=>{this.suggestEl.contains(l.target)||this.reposition()},this.globalResizeListener=this.close.bind(this),this.globalKeyboardListener=this.reposition.bind(this),this.globalBlurListener=this.close.bind(this)}onGlobalClick(t){if(!this.isOpen)return;let e=t.target;!this.suggestEl.contains(e)&&!this.inputEl.contains(e)&&this.close()}onGlobalWheel(t){if(!this.isOpen)return;let e=t.target;this.suggestEl.contains(e)||this.close()}async onInputChanged(t){if(this.destroyed||this.inputEl.closest("[hidden]")||this.inputEl.ownerDocument.activeElement!==this.inputEl)return;let e=!!(t?.fromCompletion&&t.keepOpen);if(t?.fromCompletion&&!e)return;let n=this.inputEl.value,i=++this.currentRequestId;this.currentQuery=n;try{let o=await this.getSuggestions(n);if(i!==this.currentRequestId)return;if(!o?.length){(e||this.isOpen)&&this.close();return}this.suggest.setSuggestions(o),this.listQuery=n,e&&this.isOpen?this.reposition():this.open(this.app.dom.appContainerEl,this.inputEl)}catch(o){S.logError(o),e||this.close()}}async useSelectedItem(t){this.inputEl.value!==this.listQuery&&(this.debouncedOnInputChanged.cancel(),await this.onInputChanged(),this.inputEl.value!==this.listQuery||!this.suggest.getIsOpen())||this.suggest.useSelectedItem(t)}open(t,e){if(this.destroyed||e.closest("[hidden]"))return;let n=!this.isOpen;n&&this.app.keymap.pushScope(this.scope),this.isOpen=!0,this.inputEl.setAttribute("aria-expanded","true"),this.inputEl.setAttribute("aria-controls",this.listboxId);let i=Bi(e);if((Bi(t)===i?t:i.body).appendChild(this.suggestEl),this.reposition(),!n)return;let a=Vh(e);i.addEventListener("pointerdown",this.globalClickListener,!0),i.addEventListener("wheel",this.globalWheelListener,!0),i.addEventListener("scroll",this.globalScrollListener,!0),a.addEventListener("resize",this.globalResizeListener),a.addEventListener("keyboardDidShow",this.globalKeyboardListener),a.addEventListener("blur",this.globalBlurListener)}reposition(){KK(this.inputEl,this.suggestEl)}close(){if(this.currentRequestId++,!this.isOpen)return;this.app.keymap.popScope(this.scope),this.isOpen=!1,this.inputEl.setAttribute("aria-expanded","false"),this.setActiveDescendant(null),this.suggest.close(),this.suggest.setSuggestions([]),this.suggestEl.remove();let t=Bi(this.inputEl),e=Vh(this.inputEl);t.removeEventListener("pointerdown",this.globalClickListener,!0),t.removeEventListener("wheel",this.globalWheelListener,!0),t.removeEventListener("scroll",this.globalScrollListener,!0),e.removeEventListener("resize",this.globalResizeListener),e.removeEventListener("keyboardDidShow",this.globalKeyboardListener),e.removeEventListener("blur",this.globalBlurListener)}destroy(){this.destroyed=!0,this.close(),this.inputEl.removeEventListener("input",this.inputEventListener),this.inputEl.removeEventListener("focus",this.focusEventListener),this.inputEl.removeEventListener("blur",this.inputBlurListener);let t=this.constructor.name,e=Bh.get(this.inputEl);e&&(e.delete(t),e.size===0&&Bh.delete(this.inputEl))}setActiveDescendant(t){if(t){this.inputEl.setAttribute("aria-activedescendant",t);return}this.inputEl.removeAttribute("aria-activedescendant")}getCurrentQuery(){return this.currentQuery}}});function Wt(r){return Array.isArray(r)||r==null?!1:typeof r=="object"?Object.keys(r).length>0:!!r}var qh=x(()=>{});function Vt(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let r=crypto.getRandomValues(new Uint8Array(16));r[6]=r[6]&15|64,r[8]=r[8]&63|128;let t=Array.from(r,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Qo=x(()=>{});function dw(r){return Ee(r)&&r.type==="Multi"}function Ee(r){return typeof r=="object"&&r!==null}function Ne(r){return dw(r)?Array.isArray(r.choices)?r.choices:[]:[]}function $a(r){return dw(r)&&Array.isArray(r.choices)}function mp(r){if(!Array.isArray(r))return!0;let t=e=>e.some(n=>{if(Array.isArray(n))return!0;if(!Ee(n)||n.type!=="Multi")return!1;let i=n.choices;return Array.isArray(i)?t(i):Wt(i)});return t(r)}function mr(r){return Array.isArray(r)?r:[]}function vo(r){return dw(r)?Wt(r.choices):!1}function fp(r){switch(r){case"Template":return"file-text";case"Capture":return"pencil";case"Macro":return"terminal";case"Multi":return"folder";default:return"file-plus"}}function Sd(r){return(typeof r.icon=="string"?r.icon.trim():"")||fp(r.type)}function Zt(r){let t=[],e=n=>{Ee(n)&&(t.push(n),Ne(n).forEach(e))};return mr(r).forEach(e),t}function i0(r){let t=new Map,e=n=>{let i=[];for(let o of n){if(!Ee(o)){i.push(o);continue}let s=o,a=t.get(s.id);if(a){if(JSON.stringify(s)===JSON.stringify(a))continue;s={...s,id:Vt()}}t.set(s.id,s),dw(s)&&Array.isArray(s.choices)&&(s={...s,choices:e(s.choices)}),i.push(s)}return i};return e(r)}function uw(r){let t=r.type==="Capture"?r.format:r.type==="Template"?r.fileNameFormat:void 0;if(!t||typeof t!="object")return;let e=t,n=typeof e.format=="string"?e.format:"";e.enabled===!0&&n.trim()===""&&(e.enabled=!1)}function o0(r){if(!Array.isArray(r))return{choices:[],changed:!1,repaired:[]};let t=new Set,e=[],n=o=>{let s=!1,a=[];for(let l of o){if(Array.isArray(l)){s=!0,a.push(...n(l));continue}if(!Ee(l)){s=!0;continue}let c=l;if($a(c)){let p=c.choices,m=n(p);m!==p&&(c={...c,choices:m},s=!0)}let d=c.id;if(typeof d=="string"&&d!==""&&!t.has(d)){t.add(d),a.push(c);continue}let u={...c,id:Vt()};t.add(u.id),e.push({previousId:d,choice:u}),a.push(u),s=!0}return s?a:o},i=n(r);return{choices:i,changed:i!==r,repaired:e}}function Ad(r,t=[],e=0,n=null){let i=[];for(let o of mr(r)){if(!Ee(o))continue;let s=[...t,o.name];i.push({choice:o,id:o.id,path:s,depth:e,parentId:n}),i.push(...Ad(Ne(o),s,e+1,o.id))}return i}var lt=x(()=>{qh();Qo();qh()});function BS(r,t,e=[]){let n=r(t),i;for(let o of e){let s=r(o);s&&(!n||s.score>n.score)&&(n=s,i=o)}return n?i===void 0?{result:n}:{result:n,alias:i}:null}function Hl(r,t,e,n){let i=r.trim();if(!i)return t.slice(0,n.limit).map(a=>({item:a,matches:[]}));let o=(0,u0.prepareFuzzySearch)(i),s=[];for(let a of t){let l=e(a),c=BS(o,l,n.aliases?.(a));if(!c)continue;let{result:d,alias:u}=c,p=d.matches;if(n.caseSensitive){let m=l.indexOf(i);if(m<0)continue;p=[[m,m+i.length]]}s.push({item:a,matches:p,score:d.score,...u!==void 0?{alias:u}:{}})}return s.sort((a,l)=>l.score-a.score).slice(0,n.limit).map(({score:a,...l})=>l)}var u0,hp=x(()=>{u0=require("obsidian")});function vQ(r,t,e,n={}){let i=n.tab??" ";if(t===e){let u=t+i.length;return{regionStart:t,regionEnd:t,replacement:i,selectionStart:u,selectionEnd:u}}let o=t===0?0:r.lastIndexOf(`
|
||
`,t-1)+1,a=r.slice(o,e).split(`
|
||
`),l=a.length-1,c=0,d=a.map((u,p)=>p===l&&u===""?u:(c+=i.length,i+u));return{regionStart:o,regionEnd:e,replacement:d.join(`
|
||
`),selectionStart:t+i.length,selectionEnd:e+c}}function yQ(r,t){r.setSelectionRange(t.regionStart,t.regionEnd);let e=r.ownerDocument,n=!1;try{n=typeof e.execCommand=="function"&&e.execCommand("insertText",!1,t.replacement)}catch{n=!1}if(!n){let i=r.value;r.value=i.slice(0,t.regionStart)+t.replacement+i.slice(t.regionEnd),r.setSelectionRange(t.selectionStart,t.selectionEnd),r.dispatchEvent(new Event("input",{bubbles:!0}));return}r.setSelectionRange(t.selectionStart,t.selectionEnd)}function zh(r,t={}){let e=t.passThroughUntilUsed??!1,n=!e,i=()=>{n=!e},o=()=>{n=!0},s=l=>{if(l.key!=="Tab"){gQ.has(l.key)||(n=!0);return}if(!n||l.shiftKey||l.ctrlKey||l.metaKey||l.altKey||l.isComposing||l.defaultPrevented)return;l.preventDefault();let c=r.selectionStart??r.value.length,d=r.selectionEnd??c;yQ(r,vQ(r.value,c,d,t))};r.addEventListener("keydown",s),r.addEventListener("focus",i),r.addEventListener("pointerup",o),r.addEventListener("input",o);let a=!1;return()=>{a||(a=!0,r.removeEventListener("keydown",s),r.removeEventListener("focus",i),r.removeEventListener("pointerup",o),r.removeEventListener("input",o))}}function pw(r){return{destroy:zh(r,{passThroughUntilUsed:!0})}}var gQ,Hh=x(()=>{gQ=new Set(["Shift","Control","Alt","Meta"])});function On(r){return r.replace(/\{\{CURSOR\}\}/gi,"")}function gp(r){let t=/\{\{CURSOR\}\}/i.exec(r);return r=On(r),{content:r,cursor:/^[ \t\r\n\f\v]*$/.test(r)?{kind:"none"}:{kind:"offset",value:t?.index??r.length,source:t?"marker":"defaultEnd"}}}function Fa(r,t,e=""){return{content:t+r.content+e,cursor:r.cursor.kind==="none"?r.cursor:{...r.cursor,value:t.length+r.cursor.value}}}function Wl(r,t,e){return{content:t,cursor:r.cursor.kind==="none"||e===null?{kind:"none"}:{...r.cursor,value:e}}}var Ma=x(()=>{});function SQ(r){return TQ.test(r.trim())}function AQ(r){let t=r.replace(_Q,"");return t===r?!1:!kQ.test(t)}function mw(r,t){return xQ.has(r)?AQ(t):SQ(t)}function fw(r){return r==="noteTitle"||r==="captureTarget"||r==="propertyName"||r==="propertyValue"||r==="folder"||r==="templatePath"||r==="lineTarget"||r==="filePath"}function hw(r){return r!=="templatePath"&&r!=="generic"}function gw(r,t){if(r==="generic")return{};let e=EQ[r];return t?{title:e.ask,placeholder:e.hint}:{placeholder:e.partOf}}function IQ(r,t=44){if(r.length<=t)return r;let e=r.split("/");if(e.length===1)return r;let n=e[e.length-1];if(e.length===2){let s=`${p0}/${n}`;return s.length<r.length?s:r}let o=`${e[0]}/${p0}/${n}`;return o.length<r.length?o:r}function vp(r,t,e){if(!r)return;let n=[],i=r.choiceName?.trim();i&&i!==t?.trim()&&n.push(i);let o=e?.showDestination===!1?void 0:r.destination?.trim();if(o){let s=e?.elide===!1?o:IQ(o);n.push(`\u2192 ${r.destinationKind==="folder"?`${s}/`:s}`)}return n.length?n.join(" "):void 0}var xQ,EQ,TQ,_Q,kQ,p0,yp=x(()=>{Le();xQ=new Set(["captureText"]),EQ={noteTitle:{ask:"Note title",hint:"Title for the new note",partOf:"Part of the new note's title"},captureTarget:{ask:"Capture target",hint:"Where to capture to",partOf:"Part of the capture destination"},captureText:{ask:"Text to capture",hint:"Text to add to the note",partOf:"Part of the text added to the note"},propertyName:{ask:"Property",hint:"Property name",partOf:"Part of the property name"},propertyValue:{ask:"Property value",hint:"Value to capture",partOf:"Part of the property value"},noteBody:{ask:"Note content",hint:"Text inserted into the note",partOf:"Part of the text inserted into the note"},folder:{ask:"Folder",hint:"Folder for the new note",partOf:"Part of the folder path"},templatePath:{ask:"Template",hint:"Path to the template file",partOf:"Part of the template path"},lineTarget:{ask:"Line to find",hint:"Existing line to anchor the capture to",partOf:"Part of the line to find"},filePath:{ask:"File to open",hint:"Path to the file to open",partOf:"Part of the file path"}},TQ=new RegExp(`^(?:${fo.source})$`,"i"),_Q=new RegExp(fo.source,"gi"),kQ=/\{\{[^}\n\r]*\}\}/;p0="\u2026"});function Wh(r){let e=/^(\s*---\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)\s*(?:\r?\n|$))/.exec(r);return e?[0,e[0].length]:null}function Gh(r,t,e,n){let[i,o]=n??[Number.NaN,Number.NaN];if(!(n!==null&&t>=i&&t<o))return{isInYaml:!1,isQuoted:!1,lineStart:0,lineEnd:0,baseIndent:"",isKeyValuePosition:!1,isListItemPosition:!1};let a=r.lastIndexOf(`
|
||
`,t-1)+1,l=r.indexOf(`
|
||
`,Math.max(t,e)),c=l===-1?r.length:l,d=r.slice(a,t),u=r.slice(e,c),p=(d.match(/^\s*/)||[""])[0],m=r[t-1]==='"'&&r[e]==='"'||r[t-1]==="'"&&r[e]==="'",h=d.replace(/["']$/,""),v=u.replace(/^["']/,"").replace(/\s+#.*$/,"").trim().length===0,b=/:\s*$/.test(h)&&v,y=/^\s*-\s*$/.test(h)&&v;return{isInYaml:!0,isQuoted:m,lineStart:a,lineEnd:c,baseIndent:p,isKeyValuePosition:b,isListItemPosition:y}}var US=x(()=>{});function Rs(r,t,e={}){if(!r||!t)return null;let n=r,i=n.metadataTypeManager??n.metadataCache?.app?.metadataTypeManager;if(!i||typeof i.getTypeInfo!="function")return null;if(e.registeredOnly){let a=i.getAllProperties?.();if(!a||typeof a!="object"||!Object.keys(a).some(l=>l.toLowerCase()===t.toLowerCase()))return null}let o=i.getTypeInfo(t),s=o?.expected?.type??o?.inferred?.type;return typeof s=="string"?s:null}function FQ(r){return r!==null&&PQ.has(r.toLowerCase())}function m0(r,t){return $Q.has(t.toLowerCase())||FQ(Rs(r,t))}var PQ,$Q,bp=x(()=>{PQ=new Set(["aliases","list","multitext","tags"]),$Q=new Set(["aliases","cssclasses","tags"])});function MQ(r,t=","){let e=[],n="",i=[],o=null;for(let a=0;a<r.length;a++){let l=r[a];if(o){if(n+=l,l===o){let c=0;for(let d=a-1;d>=0&&r[d]==="\\";d--)c++;c%2===0&&(o=null)}continue}if(l==='"'){o=l,n+=l;continue}if(l in f0){i.push(f0[l]),n+=l;continue}if(i.length>0){let c=i[i.length-1];l===c&&i.pop(),n+=l;continue}if(l===t){let c=n.trim();c.length>0&&e.push(c),n="";continue}n+=l}let s=n.trim();return s.length>0&&e.push(s),e}function RQ(r){return r.includes(`
|
||
`)?r.replace(/\r?\n/g,`
|
||
`):r.includes("\\n")?r.replace(/\\n/g,`
|
||
`):r}function OQ(r){if(!r)return!1;let t=r.toLowerCase();return t==="list"||t==="tags"||t==="multitext"}function h0(r,t){let e=r.trim();if(!e)return;let n=RQ(e),i=t?.propertyType??Rs(t?.app,t?.propertyKey),o=OQ(i),a=o||i===null,c=n.split(/\n/).map(d=>d.trim()).filter(d=>d.length>0);if(a&&c.length>0&&c.every(d=>/^-\s+/.test(d)))return c.map(d=>d.replace(/^-[\s]*/,"").trim());if(n.startsWith("[")&&n.endsWith("]")||n.startsWith("{")&&n.endsWith("}")){if(i&&!o&&i!=="list")return;try{return JSON.parse(n)}catch{}}if(n.includes(",")&&a){let d=MQ(n);if(d.length>1)return d}}var f0,g0=x(()=>{bp();f0={"[":"]","(":")","{":"}","<":">"}});function wp(r){if(typeof r=="string"&&r.startsWith("@date:")){let t=r.substring(6),e=new Date(t);if(!Number.isNaN(e.getTime()))return e}return r}function qS(r){return typeof r!="string"&&(Array.isArray(r)||typeof r=="object"&&r!==null||typeof r=="number"||typeof r=="boolean"||r===null)}function v0(r){return Array.isArray(r)||typeof r=="object"&&r!==null}function y0(r){if(qS(r))return Array.isArray(r)?"[]":r===null?"null":typeof r=="object"?"{}":String(r)}var Cp=x(()=>{});var b0,Ui,jh=x(()=>{US();g0();Cp();bp();b0="\0",Ui=class{constructor(t){this.app=t;this.map=new Map;this.propertyTypeCache=new Map}maybeCollect(t){let{input:e,matchStart:n,matchEnd:i,rawValue:o,fallbackKey:s,collectionActive:a,heuristicEnabled:l}=t;if(!a)return;let c=Wh(e),d=Gh(e,n,i,c);if(!d.isInYaml)return;let u=e.slice(d.lineStart,d.lineEnd),p=u.trim(),m=u.match(/^\s*([^:]+):/),h=m?m[1].trim():s,g=/^-\s*['"]?\{\{(?:VALUE|FIELD|FILE):[^}]+\}\}['"]?\s*$/i,v=null;if(d.isKeyValuePosition?v=[h]:g.test(p)&&(v=this.findListParentPath(e,d.lineStart,d.baseIndent??"")),!v||v.length===0)return;let b=v[v.length-1],y=o;if(l&&typeof o=="string"){let w=h0(o,this.buildParseOptions(b));w!==void 0&&(y=w)}if(!qS(y)||Array.isArray(y)&&y.length===0||!l&&!v0(y))return;let C=v.join(b0);return this.map.set(C,y),y}drain(){let t=new Map(this.map);return this.map.clear(),t}merge(t){for(let[e,n]of t)this.map.set(e,n)}buildParseOptions(t){return{propertyKey:t,propertyType:this.resolvePropertyType(t),app:this.app}}findListParentPath(t,e,n){let i=e-1,o=[],s=n.length;for(;i>=0;){let a=t.lastIndexOf(`
|
||
`,i),l=a===-1?0:a+1,c=t.slice(l,i+1),d=c.trim();if(d.length===0){i=l-2;continue}if(d==="---"||d==="...")break;if(d.startsWith("-")){i=l-2;continue}let u=c.match(/^(\s*)([^:\n]+):/);if(u){let m=(u[1]??"").length;if(m<s&&(o.unshift(u[2].trim()),s=m,s===0))break}i=l-2}return o.length>0?o:null}resolvePropertyType(t){if(!this.app)return null;if(this.propertyTypeCache.has(t))return this.propertyTypeCache.get(t)??null;let e=Rs(this.app,t);return this.propertyTypeCache.set(t,e),e}};Ui.PATH_SEPARATOR=b0});function Pd(r){return DQ.has(r.toUpperCase())}function zS(r){if(r.length===0||r==="."||r===".."||r.startsWith(".")||Yh.test(r)||Kh.test(r)||Qh.test(r))return!1;let t=r.split(".")[0]??"";return t.length===0||!Pd(t)}var Yh,Kh,Qh,DQ,Xh=x(()=>{Yh=new RegExp("[\0-]","u"),Kh=/[\\/:*?"<>|]/u,Qh=/[. ]$/u,DQ=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 w0(r){if(!r)return null;let t=r.trim().toLowerCase();switch(t){case"kebab":case"snake":case"camel":case"pascal":case"title":case"lower":case"upper":case"slug":return t;default:return null}}function bw(r){return w0(r)!==null}function HS(r){if(!r)return r;let t=r.toLowerCase();return t.slice(0,1).toUpperCase()+t.slice(1)}function WS(r){return/\p{L}/u.test(r)?/\p{Lu}/u.test(r)&&!/\p{Ll}/u.test(r):!1}function vw(r){return/\p{Lu}/u.test(r)&&/\p{Ll}/u.test(r)}function LQ(r){return/^\p{Ll}/u.test(r)&&vw(r)}function NQ(r){if(!r)return[];{let e=r.match(/^([\p{Ll}][\p{Lu}]{2,})([\p{N}]+)?$/u);if(e){let n=[e[1]];return e[2]&&n.push(e[2]),n}}if(/^[\p{Ll}][\p{Lu}][\p{Ll}]+(?:[\p{Lu}][\p{Ll}]+)*$/u.test(r))return[r];let t=r;return t=t.replace(/([\p{Lu}])([\p{Lu}][\p{Ll}])/gu,"$1 $2"),t=t.replace(/([\p{Ll}\p{N}])([\p{Lu}])/gu,"$1 $2"),t=t.replace(/([\p{L}])([\p{N}])/gu,"$1 $2"),t=t.replace(/([\p{N}])([\p{L}])/gu,"$1 $2"),t.trim().split(/\s+/u).map(e=>e.trim()).filter(Boolean)}function VQ(r){return r.split(/[^\p{L}\p{N}\p{M}]+/gu).filter(Boolean).flatMap(NQ).filter(Boolean)}function Jh(r,t){let e=w0(t);if(!e)return r;if(e==="lower")return r.toLowerCase();if(e==="upper")return r.toUpperCase();let n=VQ(r);if(n.length===0)return"";switch(e){case"kebab":return n.map(i=>i.toLowerCase()).join("-");case"snake":return n.map(i=>i.toLowerCase()).join("_");case"camel":{let[i,...o]=n,s=i?LQ(i)?i:i.toLowerCase():"",a=o.map(l=>WS(l)||vw(l)?l:HS(l));return[s,...a].join("")}case"pascal":return n.map(i=>WS(i)||vw(i)?i:HS(i)).join("");case"title":return n.map(i=>WS(i)||vw(i)?i:HS(i)).join(" ");case"slug":{let i=n.map(o=>o.toLowerCase()).join("-");return Pd(i)?`${i}-`:i}default:return r}}var yw,ww=x(()=>{Xh();yw=["kebab","snake","camel","pascal","title","lower","upper","slug"]});function C0(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(BQ,t=>`\\x${t.charCodeAt(0).toString(16).padStart(2,"0")}`)}function Zh(r){return`"${C0(r)}"`}function GS(r,t,e){let n=Gh(r,t,e,Wh(r));return!n.isInYaml||!n.isQuoted?!1:n.isKeyValuePosition||n.isListItemPosition}function $d(r,t,e,n){return GS(r,t,e)?r[t-1]==='"'?C0(n):n.replace(/'/g,"''"):n}function jS(r,t,e){let n=Gh(r,t,e,Wh(r));return!n.isInYaml||n.isQuoted?!1:n.isKeyValuePosition||n.isListItemPosition}var BQ,Cw=x(()=>{US();BQ=new RegExp("[\0-\x7F]","g")});function xw(r,t,e){let n=r.trim().toLowerCase();if(UQ.has(n))return n;e?.(`QuickAdd: Unsupported multi-select format "${r}" in "${t}". Supported formats: auto, inline, spaced, yaml, markdown.`)}function qQ(r,t){let e=r.lastIndexOf(`
|
||
`,t-1)+1;return r.slice(e,t).match(/^\s*/)?.[0]??""}function x0(r){if(r.format==="inline"||r.format==="spaced")return!1;let t=r.input.lastIndexOf(`
|
||
`,r.matchStart-1)+1,e=r.input.indexOf(`
|
||
`,r.matchEnd);return r.input.slice(t,r.matchStart).trim()===""&&r.input.slice(r.matchEnd,e===-1?void 0:e).trim()===""}function zQ(r){return`- ${r.replace(/\r\n?|\n/g,`
|
||
`)}`}function E0(r){let{input:t,matchStart:e,values:n,format:i}=r,o=n.map(s=>String(s));switch(i){case"auto":return;case"inline":return o.join(",");case"spaced":return o.join(", ");case"yaml":return`[${o.map(Zh).join(", ")}]`;case"markdown":{if(o.length===0)return"";let s=qQ(t,e);return o.map(zQ).join(`
|
||
${s}`)}default:return i}}var UQ,Ew=x(()=>{Cw();UQ=new Set(["auto","inline","spaced","yaml","markdown"])});function Tw(r){let t=r.trim();return t&&(/^\[\[.*\]\]$/.test(t)?t:`[[${t}]]`)}var YS=x(()=>{});function bo(r){return r.split("|")}function T0(r){return r.startsWith("|")?r.slice(1):r}function wo(r){let t=r.indexOf(":");if(t===-1)return null;let e=r.slice(0,t).trim().toLowerCase();if(!e)return null;let n=r.slice(t+1).trim();return{key:e,value:n}}function Gl(r){if(!r)return!0;let t=r.trim().toLowerCase();return!["false","no","0","off"].includes(t)}function Xo(r,t){let e=!1;return{remaining:r.filter(i=>i.trim().toLowerCase()===t?(e=!0,!1):!0),found:e}}var jl=x(()=>{});function KS(r){let{remaining:t,found:e}=Xo(r,"optional"),{remaining:n,found:i}=Xo(t,"trim");return{remaining:n,optional:e,trim:i}}function QS(r,t,e,n,i){let o=r.map(u=>{let p=u.trim();return{raw:p,option:wo(p)}}),s=e?WQ:_0,a=o.some(({option:u})=>u?.key==="type"&&["number","slider"].includes(u.value.toLowerCase())),l=u=>s.has(u)||a&&HQ.has(u);if(!o.some(({raw:u,option:p})=>p&&l(p.key)||t&&["custom","multi"].includes(u.toLowerCase())))return{defaultValue:r.join("|").trim(),allowCustomInput:!1,usesOptions:!1};let d={defaultValue:"",allowCustomInput:!1,usesOptions:!0,multiSelect:!1};for(let{raw:u,option:p}of o){if(t&&u.toLowerCase()==="custom"){d.allowCustomInput=!0;continue}if(t&&u.toLowerCase()==="multi"){d.multiSelect=!0;continue}if(!p||!l(p.key))continue;let{key:m,value:h}=p;switch(m){case"label":h&&(d.label=h);break;case"case":h&&(d.caseStyle=h);break;case"default":d.defaultValue=h;break;case"custom":d.allowCustomInput=Gl(h);break;case"type":h&&(d.inputTypeOverride=h);break;case"min":d.minRaw=h;break;case"max":d.maxRaw=h;break;case"step":d.stepRaw=h;break;case"text":d.displayValuesRaw=h;break;case"optional":d.optionalExplicit=Gl(h);break;case"trim":d.trimExplicit=Gl(h);break;case"multi":d.multiSelect=!0,d.multiEmit=h.trim().toLowerCase()==="linklist"?"linklist":"text";break;case"format":d.multiFormat=xw(h,n,i);break;case"name":h?d.name=h:i(`QuickAdd: empty |name: ignored in "${n}"; provide a variable name, e.g. {{VALUE:a,b|name:category}}.`);break;default:break}}return d}var HQ,_0,WQ,k0=x(()=>{jl();Ew();HQ=new Set(["min","max","step"]),_0=new Set(["label","default","custom","type","case","text","optional","trim","multi","format"]),WQ=new Set([..._0,"name"])});var xp,eg,tg=x(()=>{ye();xp=r=>{S.logWarning(r)},eg=()=>{}});function Ep(r){if(r===void 0)return;let t=r.trim();if(!t)return;let e=Number(t);return Number.isFinite(e)?e:void 0}function GQ(r){return r.minRaw!==void 0||r.maxRaw!==void 0||r.stepRaw!==void 0}function S0(r,t,e){let n=Ep(r.minRaw),i=Ep(r.maxRaw),o=Ep(r.stepRaw),s={};for(let[a,l,c]of[["min",r.minRaw,n],["max",r.maxRaw,i]])l!==void 0&&(c===void 0?e(`QuickAdd: Ignoring invalid ${a} in VALUE token "${t}".`):s[a]=c);return s.min!==void 0&&s.max!==void 0&&s.max<s.min&&(e(`QuickAdd: Ignoring invalid numeric range in VALUE token "${t}"; max must be greater than or equal to min.`),delete s.min,delete s.max),r.stepRaw!==void 0&&(o===void 0||o<=0?e(`QuickAdd: Ignoring invalid step in VALUE token "${t}"; step must be greater than 0.`):s.step=o),Object.keys(s).length>0?s:void 0}function XS(r,t,e,n){if(e!=="number"&&e!=="slider")return GQ(r)&&n(`QuickAdd: Ignoring numeric range options in "${t}" because type is not number or slider.`),{inputTypeOverride:e};if(e!=="slider"){let c=S0(r,t,n);return{inputTypeOverride:e,numericConfig:c}}let i=Ep(r.minRaw),o=Ep(r.maxRaw),s=r.stepRaw===void 0?1:Ep(r.stepRaw),a=i===void 0||o===void 0?"slider requires finite min and max values":o<=i?"max must be greater than min":s===void 0||s<=0?"step must be greater than 0":void 0;if(a)return n(`QuickAdd: Invalid slider configuration in "${t}" (${a}); falling back to type:number.`),{inputTypeOverride:"number",numericConfig:S0(r,t,eg)};let l={min:i,max:o,step:s};return{inputTypeOverride:e,numericConfig:l,sliderConfig:l}}function A0(r){let t=String(r),e=/e-(\d+)$/i.exec(t);if(e)return Number(e[1]);let n=t.indexOf(".");return n===-1?0:t.length-n-1}function jQ(r,t){return String(Number(r.toFixed(t)))}function Co(r,t){let e=r?.trim()??"";if(!e)return"";let n=Number(e);if(!Number.isFinite(n))return"";let i=t?.min,o=t?.max,s=n;if(i!==void 0&&(s=Math.max(i,s)),o!==void 0&&(s=Math.min(o,s)),t?.step!==void 0&&t.step>0){let a=i??0,l=Math.round((s-a)/t.step);s=a+l*t.step,i!==void 0&&(s=Math.max(i,s)),o!==void 0&&(s=Math.min(o,s));let c=Math.max(A0(a),A0(t.step));return jQ(s,c)}return String(s)}function Tp(r,t){return Co(r,t)||String(t.min)}var JS=x(()=>{tg()});function _w(r){return r!==void 0&&YQ.has(r)}function Fd(r){let t=[],e="",n=!1;for(let i=0;i<r.length;i++){let o=r[i];if(n){if(_w(o)){if(_w(r[i+1])){e+='"',i++;continue}let s=i+1;for(;s<r.length&&KQ.test(r[s]);)s++;if(s>=r.length||r[s]===","){n=!1,i=s-1;continue}return r.split(",")}e+=o;continue}if(o===","){t.push(e),e="";continue}if(_w(o)&&e.trim()===""){n=!0,e="";continue}e+=o}return n?r.split(","):(t.push(e),t)}function rg(r){let t=r.trim();if(!_w(t[0]))return r;let e=Fd(t);return e.length===1&&e[0]!==t?e[0].trim():r}var YQ,KQ,ZS=x(()=>{YQ=new Set(['"',"\u201C","\u201D"]);KQ=/[^\S\r\n]/});function JQ(r,t,e){return e&&t?`${r}${eA}${t}`:r}function tA(r){let t=r.indexOf(eA);return t===-1?r:r.slice(0,t)}function ZQ(r,t){let e=t.toLowerCase(),n=null;for(let i of r.keys())if(i.toLowerCase()===e&&r.get(i)!==void 0){if(n)return null;n=i}return n}function Yl(r,t){if(!t)return null;let e=[t],n=tA(t);n!==t&&e.push(n);for(let i of e){if(r.has(i)&&r.get(i)!==void 0)return i;let o=ZQ(r,i);if(o)return o}return null}function I0(r,t,e){if(r&&!bw(r)){e(`QuickAdd: Unsupported |case style "${r}" in token "${t}". Supported styles: ${yw.join(", ")}.`);return}return r}function P0(r,{tokenDisplay:t,hasOptions:e,allowCustomInput:n},i){if(!r)return;let o=r.trim().toLowerCase(),s=o==="boolean"?"checkbox":o;if(!QQ.has(s)){i(`QuickAdd: Unsupported VALUE type "${r}" in token "${t}". Supported types: multiline, number, slider, checkbox, text.`);return}if(e||n){i(`QuickAdd: Ignoring type:${s} for option-list VALUE token "${t}".`);return}return s}function Md(r,t){if(!r)return null;let e=t?.warn??xp,n=bo(r),i=(n.shift()??"").trim();if(!i)return null;let o=Fd(i).map(N=>N.trim()).filter(Boolean),s=o.length>1,{remaining:a,optional:l,trim:c}=KS(n),d=`{{VALUE:${r}}}`,u=QS(a,s,!0,d,e),{label:p,caseStyle:m,defaultValue:h,allowCustomInput:g}=u,v=u.multiSelect??!1,b=u.multiEmit??"text",y=u.multiFormat??"auto",C=u.optionalExplicit??l,w=u.trimExplicit??c;if(!u.usesOptions){let N=h;g=s&&N.toLowerCase()==="custom",h=g?"":N}s&&h&&(h=rg(h));let T=P0(u.inputTypeOverride,{tokenDisplay:d,hasOptions:s,allowCustomInput:g},e),P=XS(u,d,T,e),_;if(u.displayValuesRaw!==void 0){if(!s)throw new Error(`QuickAdd: VALUE option "text" is only supported for option-list tokens in "${d}".`);if(_=Fd(u.displayValuesRaw).map(N=>N.trim()).filter(Boolean),_.length!==o.length)throw new Error(`QuickAdd: VALUE token "${d}" must define the same number of text entries and item entries. To include a comma inside one entry, wrap it in double quotes, e.g. "a, b".`);if(new Set(_).size!==_.length)throw new Error(`QuickAdd: VALUE token "${d}" has duplicate text entries. Text entries must be unique.`)}let I=u.name?.trim()||void 0;I&&I.includes(eA)&&(e(`QuickAdd: |name in "${d}" contains a reserved control character and was ignored.`),I=void 0),I&&XQ.has(I.toLowerCase())&&(e(`QuickAdd: |name:${I} is reserved and was ignored in "${d}". Choose a different name.`),I=void 0),I&&!s&&e(`QuickAdd: |name on a single value in "${d}" is redundant \u2014 use {{VALUE:${I}}} directly.`),m=I0(m,d,e),v&&!s&&(e(`QuickAdd: |multi needs an option list (2+ comma-separated values) in "${d}"; ignoring.`),v=!1),v&&m&&(e(`QuickAdd: |case is ignored with |multi in "${d}" \u2014 a list is not case-transformed.`),m=void 0),!v&&u.multiFormat!==void 0&&(e(`QuickAdd: |format: needs |multi in "${d}"; ignoring.`),y="auto"),!s&&!u.usesOptions&&a.some(N=>N.trim().toLowerCase()==="custom")&&(e(`QuickAdd: |custom needs an option list (2+ comma-separated values) in "${d}"; ignoring.`),h.toLowerCase()==="custom"&&(h=""));let D=I||JQ(i,p,s);return{raw:r,variableName:i,aliasName:I,variableKey:D,label:p,caseStyle:m,defaultValue:h,allowCustomInput:g,suggestedValues:o,displayValues:_,hasOptions:s,inputTypeOverride:P.inputTypeOverride,numericConfig:P.numericConfig,sliderConfig:P.sliderConfig,optional:C,trim:w,multiSelect:v,multiEmit:b,multiFormat:y}}function ng(r,t){let e=t?.warn??xp,n=T0(r),i=bo(n).map(g=>g.trim()).filter(Boolean),{remaining:o,optional:s,trim:a}=KS(i);if(o.length===0)return{defaultValue:"",optional:s,trim:a};let l=`{{VALUE${r}}}`,c=QS(o,!1,!1,l,e);if(c.displayValuesRaw!==void 0)throw new Error(`QuickAdd: VALUE option "text" is only supported for option-list tokens in "${l}".`);let{label:d,caseStyle:u,defaultValue:p}=c;c.usesOptions||(p=p.trim()),u=I0(u,l,e);let m=P0(c.inputTypeOverride,{tokenDisplay:l,hasOptions:!1,allowCustomInput:c.allowCustomInput},e),h=XS(c,l,m,e);return{label:d,caseStyle:u,defaultValue:p,inputTypeOverride:h.inputTypeOverride,numericConfig:h.numericConfig,sliderConfig:h.sliderConfig,optional:c.optionalExplicit??s,trim:c.trimExplicit??a}}var eA,QQ,XQ,xo=x(()=>{k0();JS();ZS();JS();ZS();jl();ww();tg();eA="",QQ=new Set(["multiline","number","slider","checkbox","text"]),XQ=new Set(["value","title"])});function Os(r){if(r==null)return"";if(typeof r=="string")return r;if(typeof r=="number"||typeof r=="boolean")return String(r);if(typeof r=="bigint"||typeof r=="symbol")return r.toString();if(r instanceof Error)return r.message;try{return JSON.stringify(r)??Object.prototype.toString.call(r)}catch{return Object.prototype.toString.call(r)}}function Kl(r){return e3.includes(r)}function M0(r){switch(r){case"lessThan":case"lessThanOrEqual":case"greaterThan":case"greaterThanOrEqual":return"number";case"equals":case"notEquals":return"string";case"contains":case"notContains":return"string";default:return"boolean"}}function R0(r){if(!Kl(r.operator)||r.expectedValue===void 0||r.expectedValue===null)return;let t=r.expectedValue.trim();switch(r.valueType){case"number":{let e=Number(t);return Number.isNaN(e)?NaN:e}case"boolean":{let e=t.toLowerCase();return $0.has(e)?!0:F0.has(e)?!1:!!t}default:return t}}function rA(r,t){switch(t){case"number":return typeof r=="number"?r:typeof r=="boolean"?r?1:0:Number(r);case"boolean":if(typeof r=="boolean")return r;if(typeof r=="string"){let e=r.trim().toLowerCase();if($0.has(e))return!0;if(F0.has(e))return!1}return!!r;default:return r==null?"":Os(r)}}function t3(r){if(!Kl(r.operator))return"";let t=r.expectedValue??"";return t.length===0?"(empty)":r.valueType==="string"?`"${t}"`:t}function r3(r){let t=r.variableName?`$${r.variableName}`:"(missing variable)",e=i3(r.operator),n=Kl(r.operator)?` ${t3(r)}`:"";return`${t} ${e}${n}`.trim()}function n3(r){let t=r.exportName?`::${r.exportName}`:"";return`script ${r.scriptPath}${t}`}function Ql(r){return r.mode==="variable"?r3(r):n3(r)}function i3(r){switch(r){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 r}}var e3,$0,F0,Xl=x(()=>{e3=["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","contains","notContains"],$0=new Set(["true","1","yes","on"]),F0=new Set(["false","0","no","off"])});var o3,kw,nA=x(()=>{Le();yp();ye();jh();ww();Cp();Cw();Ew();YS();xo();tg();Xl();o3=new Set(["number","slider","checkbox"]),kw=class{constructor(t){this.app=t;this.variables=new Map;this.promptScope="generic";this.promptScopeSoleValue=!1;this.templatePropertyCollectionDepth=0;this.listPicksAsLines=!1;this.namedSuggesterOptionSigs=new Map;this.namedSuggesterConflictsWarned=new Set;this.warnSink=t=>this.warn(t);this.propertyCollector=new Ui(t)}writesListPicksAsLines(){return this.listPicksAsLines}async preserveSingleTokenValue(t,e){let n=this.singleTokenValue,i=/^(?:\{\{(?:VALUE|NAME)(?::[^{}]+|\|[^{}]+)?\}\}|\{\{(?:FIELD|FILE):[^{}]+\}\}|\{\{PROPERTY\}\}|`{3,}js quickadd[\s\S]*`{3,})$/i.test(t)?{input:t}:void 0;this.singleTokenValue=i;try{let o=await e();return i?.result&&typeof i.result.value!="string"?i.result.value:o}finally{this.singleTokenValue=n}}retainSingleTokenValue(t,e,n,i){return this.singleTokenValue?.input===t&&e===0&&n===t.length?(this.singleTokenValue.result={value:i},!0):!1}propertyTokenValue(t,e){if(e==="text")return Os(t);if(e==="checkbox"){if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1;throw new Error("A checkbox property value must be true or false.")}if(e==="number"||e==="slider"){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t!="string"||!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(t.trim())||!Number.isFinite(Number(t)))throw new Error("A number property value must be a finite number.");return Number(t)}return t}warn(t){S.logWarning(t)}reportProblem(t){S.logError(t)}setPromptRunContext(t){this.promptRunContext={...this.promptRunContext,...t}}getPromptRunContext(){return this.promptRunContext}async withPromptScope(t,e,n){let i=this.promptScope,o=this.promptScopeSoleValue;this.promptScope=t,this.promptScopeSoleValue=mw(t,e);try{return await n()}finally{this.promptScope=i,this.promptScopeSoleValue=o}}hasConcreteVariable(t){return this.variables.has(t)?this.variables.get(t)!==void 0:!1}setTitle(t){this.hasConcreteVariable("title")||this.variables.set("title",t)}getAnonymousValue(){return this.value}userText(t){return t}replacer(t,e,n){return t.replace(e,function(){return n})}applyCaseOption(t,e,n){return e?bw(e)?Jh(t,e):(this.warn(`QuickAdd: Unsupported |case style "${e}" in token "${n}". Supported styles: ${yw.join(", ")}.`),t):t}async resolveValue(t){if(this.valuePromptContext=this.getValuePromptContext(t),this.hasConcreteVariable("value")){let e=this.variables.get("value");this.value=Os(e)}return this.value===void 0&&(this.value=await this.promptForValue()),this.value}async replaceValueInString(t){let e=t;if(!fo.test(e))return e;await this.resolveValue(e);let n=new RegExp(fo.source,"gi");return e=e.replace(n,(...i)=>{let o=i[0],s=i[i.length-2],a=i[i.length-1],l=o.slice(2,-2),c=l.indexOf("|");if(c===-1)return this.retainSingleTokenValue(a,s,s+o.length,this.hasConcreteVariable("value")?this.variables.get("value"):this.value),this.userText($d(a,s,s+o.length,this.value));let d=l.slice(c),u=ng(d,{warn:this.warnSink}),p=this.value===""&&u.defaultValue&&!u.optional?u.defaultValue:this.value,m=this.applyValueTextOptions(p,u);if(this.singleTokenValue){let h=this.value===""&&u.defaultValue&&!u.optional?u.defaultValue:this.hasConcreteVariable("value")?this.variables.get("value"):this.value;this.retainSingleTokenValue(a,s,s+o.length,this.propertyTokenValue(this.applyValueTokenOptions(h,u),u.inputTypeOverride))}return u.inputTypeOverride==="text"&&m!==""&&jS(a,s,s+o.length)?this.userText(Zh(m)):this.userText($d(a,s,s+o.length,m))}),e}applyValueTextOptions(t,e){let n=String(t??""),i=e.trim?n.trim():n;return Jh(i,e.caseStyle)}applyValueTokenOptions(t,e){return Array.isArray(t)?e.trim?t.map(n=>typeof n=="string"?n.trim():n):t:typeof t=="string"?this.applyValueTextOptions(t,e):t}getValuePromptContext(t){let e=new RegExp(fo.source,"gi"),n,i;for(;(n=e.exec(t))!==null;){let s=n[0].slice(2,-2),a=s.indexOf("|");if(a===-1)continue;let l=s.slice(a),c=ng(l,{warn:eg});i||(i={}),!i.label&&c.label&&(i.label=c.label),!i.defaultValue&&c.defaultValue&&(i.defaultValue=c.defaultValue),c.inputTypeOverride&&!i.inputTypeOverride&&(i.inputTypeOverride=c.inputTypeOverride),c.numericConfig&&!i.numericConfig&&(i.numericConfig=c.numericConfig),c.sliderConfig&&!i.sliderConfig&&(i.sliderConfig=c.sliderConfig),c.optional&&(i.optional=!0)}return i}getAndClearTemplatePropertyVars(){return this.propertyCollector.drain()}mergeTemplatePropertyVars(t){this.propertyCollector.merge(t)}renderCollectedOrArrayValue(t){if(this.writesListPicksAsLines()&&Array.isArray(t.rawValue)&&x0({...t,format:t.multiFormat})){let i=t.rawValue.map(String);if(!this.retainSingleTokenValue(t.input,t.matchStart,t.matchEnd,t.rawValue)&&i.some(s=>/[\r\n]/.test(s)))throw new Error("A list item that contains a line break can only be written when its token is the whole Capture format.");return i.join(`
|
||
`)}if((!t.multiFormat||t.multiFormat==="auto")&&this.retainSingleTokenValue(t.input,t.matchStart,t.matchEnd,t.rawValue),Array.isArray(t.rawValue)&&t.multiFormat){let i=E0({input:t.input,matchStart:t.matchStart,values:t.rawValue,format:t.multiFormat});if(i!==void 0)return i}let e=this.propertyCollector.maybeCollect({...t,collectionActive:this.templatePropertyCollectionDepth>0}),n=y0(e);if(n!==void 0)return n;if(Array.isArray(t.rawValue))return $d(t.input,t.matchStart,t.matchEnd,t.rawValue.join(","))}async withTemplatePropertyCollection(t){this.templatePropertyCollectionDepth+=1;try{return await t()}finally{this.templatePropertyCollectionDepth-=1}}warnOnNamedOptionConflict(t){if(!t.aliasName||!t.hasOptions)return;let e=t.variableKey.toLowerCase(),n=JSON.stringify([t.suggestedValues,t.allowCustomInput,t.displayValues??null,t.multiSelect,t.multiEmit]),i=this.namedSuggesterOptionSigs.get(e);if(i===void 0){this.namedSuggesterOptionSigs.set(e,n);return}i!==n&&!this.namedSuggesterConflictsWarned.has(e)&&(this.namedSuggesterConflictsWarned.add(e),this.warn(`QuickAdd: named value "${t.variableKey}" is defined with different option lists; the first definition's value is reused.`))}async ensureValueVariableResolved(t){let{variableName:e,variableKey:n,label:i,defaultValue:o,allowCustomInput:s,suggestedValues:a,displayValues:l,hasOptions:c}=t;this.warnOnNamedOptionConflict(t),await this.resolveIncludingTextDate(n);let d=Yl(this.variables,n);if(d)return d;let u=this.promptScope==="propertyValue"?this.variables.get("propertyKey"):void 0,p=c?i||(typeof u=="string"?u:void 0):void 0;if(c&&t.multiSelect){let h=await this.suggestForValueMulti(a,s,{placeholder:p,variableKey:n,displayValues:l,optional:t.optional});return this.variables.set(n,t.multiEmit==="linklist"?h.map(Tw):h),n}let m="";return c?m=await this.suggestForValue(a,s,{placeholder:p,variableKey:n,displayValues:l,optional:t.optional}):m=await this.promptForVariable(e,{defaultValue:o,label:i,inputTypeOverride:t.inputTypeOverride,numericConfig:t.numericConfig,sliderConfig:t.sliderConfig,variableKey:n,optional:t.optional}),!m&&o&&!t.optional&&(m=o),this.variables.set(n,m),n}async resolveNamedSuggesterDefinitions(t){if(!/\|\s*name\s*:/i.test(t))return;let e=new RegExp(Td.source,"gi"),n=[],i;for(;(i=e.exec(t))!==null;){if(!i[1])continue;let a;try{a=Md(i[1],{warn:eg})}catch{return}a&&n.push({parsed:a,index:i.index})}let o=new Map;for(let{parsed:a,index:l}of n){if(a.hasOptions&&a.aliasName)continue;let c=a.variableKey.toLowerCase();o.has(c)||o.set(c,l)}let s=new Set;for(let{parsed:a,index:l}of n){if(!a.hasOptions||!a.aliasName)continue;let c=a.variableKey.toLowerCase();(o.get(c)??l)>=l||s.has(c)||(s.add(c),await this.ensureValueVariableResolved(a))}}async replaceVariableInString(t){let e=t;await this.resolveNamedSuggesterDefinitions(e);let n=new RegExp(Td.source,"gi"),i=this.isTemplatePropertyTypesEnabled(),o;for(;(o=n.exec(e))!==null;){if(!o[1])throw new Error(`Unable to parse variable. Invalid syntax in: "${e.substring(Math.max(0,o.index-10),Math.min(e.length,o.index+30))}..."`);let s=Md(o[1],{warn:this.warnSink});if(!s)throw new Error(`Unable to parse variable. Invalid syntax in: "${e.substring(Math.max(0,o.index-10),Math.min(e.length,o.index+30))}..."`);let{variableName:a}=s,l=await this.ensureValueVariableResolved(s),c=this.variables.get(l),d=this.applyValueTokenOptions(c,s);this.singleTokenValue&&(!s.multiFormat||s.multiFormat==="auto")&&this.retainSingleTokenValue(e,o.index,o.index+o[0].length,this.propertyTokenValue(d,s.inputTypeOverride));let u=this.renderCollectedOrArrayValue({input:e,matchStart:o.index,matchEnd:o.index+o[0].length,rawValue:this.singleTokenValue?.result?this.singleTokenValue.result.value:d,fallbackKey:a,heuristicEnabled:i&&this.templatePropertyCollectionDepth>0&&s.inputTypeOverride!=="text",multiFormat:s.multiFormat}),p,m=!1;if(u!==void 0)p=u;else{let v=String(this.applyValueTextOptions(this.getValueTokenText(l),s)??"");s.inputTypeOverride==="text"&&v!==""&&jS(e,o.index,o.index+o[0].length)?p=Zh(v):o3.has(s.inputTypeOverride??"")&&GS(e,o.index,o.index+o[0].length)?(m=!0,p=v):p=$d(e,o.index,o.index+o[0].length,v)}p=this.userText(p);let h=m?o.index-1:o.index,g=o.index+o[0].length+(m?1:0);e=e.slice(0,h)+p+e.slice(g),n.lastIndex=h+p.length}return e}async resolveIncludingTextDate(t){}getValueTokenText(t){return this.getVariableValue(t)}suggestForValueMulti(t,e,n){return[]}}});function Sw(r){let t=r.trim().toLowerCase(),e=s3[t];if(!e)throw new Error(`Unknown date unit "${r.trim()}". Valid units: ${a3}.`);return e}function O0(r){let t=wo(r);return t?t.key==="startof"?{boundary:"start",unit:Sw(t.value)}:t.key==="endof"?{boundary:"end",unit:Sw(t.value)}:null:null}function _p(r,t){return t?t.boundary==="start"?r.startOf(t.unit):r.endOf(t.unit):r}var s3,a3,ig=x(()=>{jl();s3={year:"year",years:"year",y:"year",quarter:"quarter",quarters:"quarter",q:"quarter",month:"month",months:"month",week:"week",weeks:"week",w:"week",isoweek:"isoWeek",isoweeks:"isoWeek",day:"day",days:"day",d:"day"},a3="year, quarter, month, week, isoweek, day"});function l3(r){return r===void 0?window.moment():window.moment(r)}function c3(r){let t=l3(r?.now);return r?.origin?window.moment(r.origin).hour(t.hour()).minute(t.minute()).second(t.second()).millisecond(t.millisecond()):t}function Ra(r){let t;return r?.offset!==null&&r?.offset!==void 0&&typeof r.offset=="number"&&(t=window.moment.duration(r.offset,"days")),_p(c3(r).add(t),r?.snap).format(r?.format??"YYYY-MM-DD")}var Aw=x(()=>{ig()});function og(r){if(!r)return{optional:!1,withTime:!1};let{remaining:t,found:e}=Xo(bo(r),"optional"),{remaining:n,found:i}=Xo(t,"time"),{remaining:o,found:s}=Xo(n,"datetime"),a,l=!1,c,d,u,p=[];for(let h of o){let g=wo(h.trim());if(g?.key==="optional"){a=Gl(g.value);continue}if(g?.key==="type"){g.value.trim().toLowerCase()==="datetime"&&(l=!0);continue}if(g?.key==="startof"||g?.key==="endof"){c||(c={boundary:g.key==="startof"?"start":"end",unit:Sw(g.value)});continue}if(g?.key==="case"){d=g.value.trim()||void 0;continue}if(g?.key==="label"){u=g.value||void 0;continue}p.push(h)}return{defaultValue:p.join("|").trim()||void 0,optional:a??e,withTime:i||s||l,snap:c,...d?{caseStyle:d}:{},...u?{label:u}:{}}}function Iw(r){try{return{options:og(r)}}catch(t){return{options:{optional:!1,withTime:!1},error:t instanceof Error?t.message:String(t)}}}var sg=x(()=>{jl();ig()});function D0(r,t,e){return r.replace(t,()=>e)}function ag(r){return r?"YYYY-MM-DD HH:mm":"YYYY-MM-DD"}function iA(r,t,e,n=!1){let i=kp.get(r);i||(i=new Map,kp.set(r,i));let o=r.get(t),s=i.get(t);(n||!s||s.answer!==o)&&i.set(t,{answer:o,dateFormat:e})}function Pw(r,t){let e=kp.get(r)?.get(t);return e&&e.answer===r.get(t)?e.dateFormat:void 0}function lg(r,t){let e=Pw(r,t);if(e!==void 0)return e;let n=t.toLowerCase(),i=[...kp.get(r)?.keys()??[]].filter(o=>o.toLowerCase()===n);return i.length===1?Pw(r,i[0]):void 0}function L0(r){return new Map(kp.get(r))}function cg(r,t){kp.set(r,new Map(t))}function dg(r,t,e,n){if(r===void 0)return null;let i=r,o;if(typeof i=="string"&&i&&!i.startsWith("@date:")){if(n){let s=U.getState().dateAliases,a=n.parseDate(Ih(i,s));a&&(o=`@date:${a.moment.toISOString()}`,i=o)}}else i instanceof Date&&(Number.isNaN(i.getTime())||(o=`@date:${i.toISOString()}`,i=o));if(typeof i=="string"&&i.startsWith("@date:")){let s=i.substring(6);if(n&&window.moment){let a=window.moment(s);if(a?.isValid())return{text:_p(a,e).format(t),...o!==void 0?{normalized:o}:{}}}return{text:"",...o!==void 0?{normalized:o}:{}}}return typeof i=="string"&&i?{text:i}:i!=null?{text:Os(i)}:{text:""}}function N0(r,t){let e=r;for(let n of[hD,wS]){let i=n===wS;for(;n.test(e);){let o=n.exec(e);if(i&&!o)throw B0("date",e,n);let s=o?.[i?2:1]?.replace("+","").trim(),a=s&&fD.test(s)?parseInt(s):void 0,l=o?.[i?3:2],c=t.clocks(),d=Ra({...i?{format:o?.[1]}:{},offset:a,snap:l?O0(l)??void 0:void 0,origin:c?.date,now:c?.now});e=D0(e,n,t.applyCase(d,o?.[i?4:3],o?.[0]??"{{DATE}}"))}}return e}function V0(r,t){let e=r;for(let n of[gD,CS]){let i=n===CS;for(;n.test(e);){let o=n.exec(e);if(!o)throw B0("time",e,n);let s=Ra({format:i?o[1]:"HH:mm",now:t.clocks()?.now});e=D0(e,n,t.applyCase(s,o[i?2:1],o[0]))}}return e}function B0(r,t,e){let n=t.search(e);return new Error(`Unable to parse ${r} format. Invalid syntax in: "${t.substring(Math.max(0,n-10),Math.min(t.length,n+30))}..."`)}async function U0(r,t){let e=new RegExp(Ss.source,"gi"),n="",i=0,o;for(;(o=e.exec(r))!==null;){n+=r.slice(i,o.index),i=o.index+o[0].length;let s=o[1]?.trim();if(!s){n+=o[0];continue}let{defaultValue:a,optional:l,withTime:c,snap:d,caseStyle:u,label:p}=og(o[3]),m=o[2]?.trim()||ag(c),h=t.variables.get(s);if(h===void 0){let v=await t.prompt(s,{type:"VDATE",dateFormat:m,defaultValue:a,optional:l,withTime:c,label:p});if(l&&!v?.trim())t.variables.set(s,"");else if(v?.startsWith("@date:"))t.variables.set(s,v);else{if(!t.dateParser)throw new Error("Date parser is not available");let b=U.getState().dateAliases,y=Ih(v,b),C=t.dateParser.parseDate(y);if(C)t.variables.set(s,`@date:${C.moment.toISOString()}`);else throw new Error(`unable to parse date variable ${v}${l?"":". Tip: add |optional inside the {{VDATE}} token to allow leaving this date empty"}`)}}let g=dg(t.variables.get(s),m,d,t.dateParser);g?.normalized!==void 0&&t.variables.set(s,g.normalized),iA(t.variables,s,m,h===void 0||g?.normalized!==void 0),n+=t.applyCase(g?.text??"",u,o[0])}return n+r.slice(i)}var kp,Rd=x(()=>{Le();Aw();je();wd();ig();sg();Xl();kp=new WeakMap});function pg(r,t=0){let e=r.length,n=t;for(;n<e;){let i=r.indexOf("`",n);if(i===-1)break;let o=i;for(;o<e&&r[o]==="`";)o++;if(o-i<3||!r.startsWith(ug,o)){n=o;continue}let s=o+ug.length,a=s;for(;a<e;){let l=r.indexOf("`",a);if(l===-1)break;let c=l;for(;c<e&&r[c]==="`";)c++;if(c-l>=3)return{start:i,end:c,code:r.slice(s,l).trim()};a=c}break}}function yi(r){let t=[],e=pg(r);for(;e;)t.push(e),e=pg(r,e.end);return t}function q0(r,t){let e=Math.max(3,t-ug.length+1);for(let n=e;n<t;n++)if(r.startsWith("```",n-3)&&r.startsWith(ug,n)){let i=n-3;for(;i>0&&r[i-1]==="`";)i--;return i}return t}function oA(r){let t=yi(r),e=r.length,n=t.length>0?t[t.length-1].end:0;for(;n<e;){let i=r.indexOf("`",n);if(i===-1)return!1;let o=i;for(;o<e&&r[o]==="`";)o++;if(o-i>=3&&r.startsWith(ug,o))return!0;n=o}return!1}function $w(r){return yi(r).map(({code:t})=>t).filter(t=>t!=="")}var ug,Oa=x(()=>{ug="js quickadd"});function W0(r,t,e,n){let i=new Map,o=new Set,s={LINKCURRENT:t.links,LINKSECTION:t.links,FILENAMECURRENT:t.fileName,FOLDER:t.folder,FOLDERCURRENT:t.activeFolder,TITLE:t.title},a=r.replace(/{{(?:(LINKCURRENT|LINKSECTION|FILENAMECURRENT|TITLE)|(FOLDERCURRENT|FOLDER)(\|name)?)}}/gi,(c,d,u,p)=>{let m=(d??u??"").toUpperCase();if(!(m in e))return c;let h=m;if(!s[h])return c;i.has(h)||i.set(h,e[h]());let g=i.get(h)??null;return(h==="FOLDERCURRENT"?g===null:(h==="LINKCURRENT"||h==="LINKSECTION"||h==="FILENAMECURRENT")&&!g)&&o.add(h),p&&g!==null?g.slice(g.lastIndexOf("/")+1):g??""}),l="Unable to get the active file's folder. Make sure you have a file open in the editor.";if(o.has("FOLDERCURRENT")&&t.activeFolder==="path")throw new Error(l);if(o.size>0){if(n==="required")throw new Error(o.has("LINKCURRENT")||o.has("LINKSECTION")?"Unable to get current file path. Make sure you have a file open in the editor.":o.has("FILENAMECURRENT")?"Unable to get current file name. Make sure you have a file open in the editor.":l);S.logMessage("Skipping current-file token replacement because no active file is available.")}return a}var z0,H0,sA=x(()=>{ye();z0=/{{(?:LINKCURRENT|LINKSECTION|FILENAMECURRENT|FOLDERCURRENT(?:\|name)?)}}/i,H0=/{{FOLDERCURRENT(?:\|name)?}}/i});function d3(r,t){let e=Math.min(r.length,t.length),n=0;for(;n<e&&r[n]===t[n];)n++;return n}function G0(r,t,e){if(r===t)return 0;if(Math.abs(r.length-t.length)>e||r.length>64||t.length>64)return e+1;let n=[],i=Array.from({length:t.length+1},(s,a)=>a),o=[];for(let s=1;s<=r.length;s++){o=new Array(t.length+1),o[0]=s;let a=o[0];for(let l=1;l<=t.length;l++){let c=r[s-1]===t[l-1]?0:1,d=Math.min(i[l]+1,o[l-1]+1,i[l-1]+c);s>1&&l>1&&r[s-1]===t[l-2]&&r[s-2]===t[l-1]&&(d=Math.min(d,n[l-2]+1)),o[l]=d,d<a&&(a=d)}if(a>e)return e+1;n=i,i=o}return i[t.length]}function j0(r,t,e=3){let n=r.trim().toLowerCase();if(!n)return[];let i=t.map((a,l)=>({candidate:a,index:l})).filter(a=>a.candidate!==n),o=i.map(a=>({...a,distance:G0(n,a.candidate,2)})).filter(a=>a.distance<=1).sort((a,l)=>a.distance-l.distance||a.index-l.index);if(o.length>0)return o.slice(0,e).map(a=>a.candidate);if(n.length>=2){let a=i.map(l=>({...l,shared:d3(n,l.candidate)})).filter(l=>l.shared>=2).sort((l,c)=>c.shared-l.shared||l.index-c.index);if(a.length>0)return a.slice(0,e).map(l=>l.candidate)}return i.map(a=>({...a,distance:G0(n,a.candidate,2)})).filter(a=>a.distance<=2&&a.candidate.length>=10).sort((a,l)=>a.distance-l.distance||a.index-l.index).slice(0,e).map(a=>a.candidate)}var Y0=x(()=>{});function Mw(r,t){return r.length<=t?r:`${r.slice(0,t)}\u2026`}function p3(r){let t=r.map(e=>`"${e}"`);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} or ${t[t.length-1]}`}function K0(r,t){let e=Mw(r,32),n=`{{FIELD:${Mw(t,48)}}}`,i=u3.get(r);if(i)return`Unknown FIELD filter "${e}" - ${i}. Ignored in ${n}.`;let o=j0(r,Fw);return o.length>0?`Unknown FIELD filter "${e}" - did you mean ${p3(o)}? Ignored in ${n}.`:`Unknown FIELD filter "${e}" in ${n} was ignored. Supported filters: ${Fw.join(", ")}.`}function m3(r,t){let e=Mw(r,32);return`FIELD filter "${e}" needs a value - write "${e}:value". Ignored in {{FIELD:${Mw(t,48)}}}.`}function f3(r,t,e){(e.warn??xp)(K0(r,t))}var Fw,u3,Dn,Da=x(()=>{tg();jl();Y0();Ew();Fw=["folder","tag","inline","inline-code-blocks","exclude-folder","exclude-tag","exclude-file","default","default-from","default-empty","default-always","case-sensitive","multi","format","label"],u3=new Map([["case-insensitive",'matching is already case-insensitive; use "case-sensitive:true" to match exactly']]);Dn=class{static parse(t,e){let n=bo(t).map(d=>d.trim()),i=n[0],o={},s=!1,a="auto",l=!1,c;for(let d=1;d<n.length;d++){let u=n[d];if(u.toLowerCase()==="multi"){s=!0;continue}let p=wo(u);if(!p){let g=u.toLowerCase();e?.warnUnknown&&g&&(e.warn??xp)(Fw.includes(g)?m3(g,t):K0(g,t));continue}let m=p.key,h=p.value;if(!Fw.includes(m)){e?.warnUnknown&&f3(m,t,e);continue}switch(m){case"label":c=h||void 0;break;case"multi":s=Gl(h);break;case"format":l=!0,a=xw(h,`{{FIELD:${t}}}`,e?.warn)??"auto";break;case"folder":o.folders??(o.folders=[]),o.folders.push(h),o.folder||(o.folder=h);break;case"tag":{o.tags??(o.tags=[]);let g=h.startsWith("#")?h.substring(1):h;o.tags.push(g);break}case"inline":o.inline=h.toLowerCase()==="true";break;case"inline-code-blocks":o.inlineCodeBlocks??(o.inlineCodeBlocks=[]),o.inlineCodeBlocks.push(...h.split(",").map(g=>g.trim().toLowerCase()).filter(g=>g.length>0));break;case"default":o.defaultValue=h;break;case"default-from":o.defaultFrom=h.toLowerCase();break;case"default-empty":o.defaultEmpty=h.toLowerCase()==="true";break;case"default-always":o.defaultAlways=h.toLowerCase()==="true";break;case"case-sensitive":o.caseSensitive=h.toLowerCase()==="true";break;case"exclude-folder":o.excludeFolders??(o.excludeFolders=[]),o.excludeFolders.push(h);break;case"exclude-tag":{o.excludeTags??(o.excludeTags=[]);let g=h.startsWith("#")?h.substring(1):h;o.excludeTags.push(g);break}case"exclude-file":o.excludeFiles??(o.excludeFiles=[]),o.excludeFiles.push(h);break}}return!s&&l&&(e?.warn?.(`QuickAdd: |format: needs |multi in "{{FIELD:${t}}}"; ignoring.`),a="auto"),{fieldName:i,filters:o,...s?{multiSelect:s}:{},...a!=="auto"?{multiFormat:a}:{},...c?{label:c}:{}}}}});function v3(r){return r.split(",").map(t=>t.trim().toLowerCase().replace(/^\./,"")).filter(Boolean)}function y3(r){if(r.length!==0)return r.includes("any")?"any":new Set(r.flatMap(t=>g3.get(t)??[t]))}function aA(r){return r.replace(/^\/+|\/+$/g,"")}function Sp(r,t=e=>e){return JSON.stringify([...r].map(t).sort())}function X0(r,t,e){let n=[`folder=${aA(r)}`];return e&&n.push(`types=${e==="any"?"any":Sp([...e])}`),t.folders?.length&&n.push(`folders=${Sp(t.folders,aA)}`),t.tags?.length&&n.push(`tags=${Sp(t.tags)}`),t.excludeFolders?.length&&n.push(`xfolder=${Sp(t.excludeFolders,aA)}`),t.excludeTags?.length&&n.push(`xtag=${Sp(t.excludeTags)}`),t.excludeFiles?.length&&n.push(`xfile=${Sp(t.excludeFiles)}`),n.join("|")}function b3(r){let{folderPath:t,mode:e,label:n,optional:i,allowCustomInput:o,multiSelect:s,filter:a,extensions:l}=r,c=[X0(t,a,l),`mode=${e}`];return n&&c.push(`label=${n}`),i&&c.push("optional"),o&&c.push("custom"),s&&c.push("multi"),c.join("|")}function Rw(r,t){if(!r)return null;let e=bo(r),n=(e.shift()??"").trim();if(!n)return null;let i=e,o=Xo(i,"optional");i=o.remaining;let s=o.found,a=Xo(i,"custom");i=a.remaining;let l=a.found,c=Xo(i,"multi");i=c.remaining;let d=c.found,u="name",p=[];for(let P of i){let _=P.trim().toLowerCase();if(h3.has(_)){u=_;continue}p.push(P)}let m,h,g=[];for(let P of p){let _=wo(P);if(_){if(_.key==="label"&&_.value)m=_.value;else if(_.key==="name"&&_.value)h=_.value;else if(_.key==="type")for(let I of v3(_.value))g.includes(I)||g.push(I)}}let v=y3(g),b=Dn.parse(r,{warn:t?.warn}),y=d||(b.multiSelect??!1),C=b.multiFormat??"auto",w={folder:n,tags:b.filters.tags,excludeFolders:b.filters.excludeFolders,excludeTags:b.filters.excludeTags,excludeFiles:b.filters.excludeFiles},T=h?`${mg}name=${h}|${X0(n,w,v)}${y?"|multi":""}`:`${mg}${b3({folderPath:n,mode:u,label:m,optional:s,allowCustomInput:l,multiSelect:y,filter:w,extensions:v})}`;return{raw:r,folderPath:n,mode:u,label:m,aliasName:h,optional:s,allowCustomInput:l,filter:w,multiSelect:y,multiFormat:C,types:g,extensions:v,variableKey:T}}function J0(r,t){if(!r)return r;for(let e of t)if(r===e)return r;return`${Jo}${r}`}function Od(r){return typeof r!="string"||r===""?{kind:"empty"}:r.startsWith(Jo)?{kind:"custom",text:r.slice(Jo.length)}:r.startsWith(Jl)?{kind:"file",path:r.slice(Jl.length)}:{kind:"raw",value:r}}function Ap(r){return(r.split("/").pop()??r).replace(/\.(md|canvas|base)$/i,"")}function Ip(r){return(r.split("/").pop()??r).replace(/\.md$/i,"")}function Z0(r){return typeof r=="string"&&r.trim().length>0?r.trim():void 0}function w3(r){if(!r)return;let t=Object.entries(r).find(([e])=>e.toLowerCase()==="title");return t?Z0(t[1]):void 0}function C3(r){let t=r?.headings?.find(e=>e.level===1);return Z0(t?.heading)}function E3(r,t){let e=w3(t?.frontmatter);return e||(Object.values(x3).some(i=>i.test(r))?C3(t)??r:r)}function T3(r){let t=r.parent?.path;return t&&t!=="/"?t:r.path.includes("/")?r.path.slice(0,r.path.lastIndexOf("/")):"vault root"}function _3(r){return r.extension&&r.extension!=="md"?r.name:r.basename||Ip(r.path)}function Dd(r,t,e){let n=e.trim().toLowerCase(),i=t.findIndex(o=>o.some(s=>s.toLowerCase()===n));return i>=0?r[i]:void 0}function Ds(r,t){let e=r.map(i=>{let o=t?.(i)??null,s=_3(i),a=E3(s,o),l=a===s?s:`${a} (${s})`,c=(0,Q0.parseFrontMatterAliases)(o?.frontmatter)??[];return{file:i,primary:a,label:l,aliases:c}}),n=new Map;for(let{label:i}of e)n.set(i,(n.get(i)??0)+1);return e.map(({file:i,primary:o,label:s,aliases:a})=>{let l=(n.get(s)??0)<=1?s:`${s} - ${T3(i)}`;return{primary:o,secondary:i.path,label:l,aliases:a}})}var Q0,mg,Jl,Jo,h3,g3,x3,Ln=x(()=>{Q0=require("obsidian");Da();jl();mg="FILE:",Jl="@file:",Jo="@filecustom:",h3=new Set(["name","link","path"]),g3=new Map([["note",["md"]],["image",["avif","bmp","gif","jpeg","jpg","png","svg","webp"]],["audio",["3gp","flac","m4a","mp3","ogg","wav","webm"]],["video",["mkv","mov","mp4","ogv","webm"]],["pdf",["pdf"]]]);x3={timestamp:/^\d{12,}$/,compactUuid:/^[0-9a-f]{32}$/i,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ulid:/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i}});function tL(r,t,e){return Array.isArray(r)?r.map(n=>eL(n,t,e)):eL(r,t,e)}function eL(r,t,e){if(t==="link")return e(r);let n=Od(r);switch(n.kind){case"empty":return"";case"file":return t==="path"?n.path:Ip(n.path);case"custom":case"raw":return n.kind==="custom"?n.text:n.value}}var rL=x(()=>{Ln()});function Ow(r){return new Promise(t=>window.setTimeout(t,r))}function Zl(r){return r.split(`
|
||
`)}var Pp=x(()=>{});var Dw,fg,Eo,lA=x(()=>{Dw=class{isResolved(){return!this.hasConflicts}isConflicted(){return this.hasConflicts}},fg=class r extends Dw{constructor(t,e,n){super(),this.left=t,this.base=e,this.right=n,this.hasConflicts=!0}static create(t){return new r(t.left,t.base,t.right)}apply(t){return r.create({left:t(this.left),base:t(this.base),right:t(this.right)})}},Eo=class r extends Dw{constructor(t){super(),this.hasConflicts=!1,this.result=t}combine(t){this.result=this.result.concat(t.result)}apply(t){return new r(t(this.result))}}});var La,cA,$p,dA,uA,Ls,hg,Lw,Nw=x(()=>{La=class r{constructor(t,e){this.left=t,this.right=e}static executeDiff(t,e){if(!t.push)throw new Error("Argument is not an array");let n=r.diff(t,e);return new dA(t,e,n).convertToTypedOutput()}static diff(t,e){return new r(t,e).performDiff()}performDiff(){let t=this.identifyUniquePositions();t.sort((o,s)=>s[0]-o[0]);let[e,n]=this.findNextChange(),i=new Lw(e,n,[]);return t.forEach(o=>{i=this.getDifferences(i,o)}),i.changeRanges}getDifferences(t,e){let[n,i]=[t.leftChangePos,t.rightChangePos],[o,s]=e;if(o<n||s<i)return t;{let[a,l,c,d]=this.findPrevChange(n,i,o-1,s-1),[u,p]=this.findNextChange(o+1,s+1),m=this.appendChangeRange(t.changeRanges,a,l,c,d);return new Lw(u,p,m)}}findNextChange(t=0,e=0){let n=this.left.slice(t)||[],i=this.right.slice(e)||[],o=this.mismatchOffset(n,i);return[t+o,e+o]}findPrevChange(t,e,n,i){if(t>n||e>i)return[t,n,e,i];{let o=this.left.slice(t,n+1).reverse()||[],s=this.right.slice(e,i+1).reverse()||[],a=this.mismatchOffset(o,s);return[t,n-a,e,i-a]}}mismatchOffset(t,e){let n=Math.max(t.length,e.length);for(let i=0;i<n;i++)if(t[i]!==e[i])return i;return Math.min(t.length,e.length)}identifyUniquePositions(){let t=this.findUnique(this.left),e=this.findUnique(this.right),n=new Set(...t.keys()),i=new Set(...e.keys()),s=[...new Set([...n].filter(a=>i.has(a)))].map(a=>[t.get(a),e.get(a)]);return s.unshift([this.left.length,this.right.length]),s}findUnique(t){let e=new Map;t.forEach((i,o)=>{e.set(i,new cA(o,!e.has(i)))});let n=new Map;for(let[i,o]of e.entries())o.unique&&n.set(i,o.pos);return n}appendChangeRange(t,e,n,i,o){return e<=n&&i<=o?t.push(new hg(Ls.change,e+1,n+1,i+1,o+1)):e<=n?t.push(new hg(Ls.remove,e+1,n+1,i+1,i)):i<=o&&t.push(new hg(Ls.add,e+1,e,i+1,o+1)),t}},cA=class{constructor(t,e){this.pos=t,this.unique=e}},$p=class{constructor(t,e){this.text=t,this.low=e}},dA=class{constructor(t,e,n){this.oldTextArray=t,this.newTextArray=e,this.chunks=n,this.oldText=[],this.newText=[]}convertToTypedOutput(){let t=new uA(0,0);return this.chunks.forEach(e=>{let[n,i]=this.setTextNodeIndexes(e,t.oldIndex,t.newIndex),[o,s]=this.appendChanges(e,t.oldIndex+n,t.newIndex+i);t.oldIndex=o,t.newIndex=s}),this.setTheRemainingTextNodeIndexes(t.oldIndex,t.newIndex),{oldText:this.oldText,newText:this.newText}}setTextNodeIndexes(t,e,n){let i=0;for(;e+i<t.leftLo-1;)this.oldText.push(new $p(this.oldTextArray[e+i],n+i)),i+=1;let o=0;for(;n+o<t.rightLo-1;)this.newText.push(new $p(this.newTextArray[n+o],e+o)),o+=1;return[i,o]}appendChanges(t,e,n){for(;e<=t.leftHi-1;)this.oldText.push(this.oldTextArray[e]),e+=1;for(;n<=t.rightHi-1;)this.newText.push(this.newTextArray[n]),n+=1;return[e,n]}setTheRemainingTextNodeIndexes(t,e){let n=0;for(;t+n<this.oldTextArray.length;)this.oldText.push(new $p(this.oldTextArray[t+n],e+n)),n+=1;for(;e+n<this.newTextArray.length;)this.newText.push(new $p(this.newTextArray[e+n],t+n)),n+=1}},uA=class{constructor(t,e){this.oldIndex=t,this.newIndex=e}};(function(r){r.change="change",r.add="add",r.remove="remove"})(Ls||(Ls={}));hg=class{constructor(t,e,n,i,o){this.action=t,this.leftLo=e,this.leftHi=n,this.rightLo=i,this.rightHi=o}},Lw=class{constructor(t,e,n){this.leftChangePos=t,this.rightChangePos=e,this.changeRanges=n}}});var Vw,Fp,pA,Na,Nr,Bw,mA=x(()=>{Nw();Vw=class r{constructor(t,e,n,i,o){this.code=t,this.baseLo=e,this.baseHi=n,this.sideLo=i,this.sideHi=o}static fromChangeRange(t){return new r(t.action,t.leftLo,t.leftHi,t.rightLo,t.rightHi)}},Fp=class r{constructor(t,e,n){this.left=t,this.base=e,this.right=n}static executeDiff(t,e,n){return new r(t,e,n).getDifferences()}getDifferences(){let t=La.diff(this.base,this.left).map(n=>Vw.fromChangeRange(n)),e=La.diff(this.base,this.right).map(n=>Vw.fromChangeRange(n));return this.collapseDifferences(new Bw(t,e))}collapseDifferences(t,e=[]){if(t.isFinished())return e;{let n=new Bw,i=t.chooseSide(),o=t.dequeue();return n.enqueue(i,o),t.switchSides(),this.buildResultQueue(t,o.baseHi,n),e.push(this.determineDifference(n,i,t.switchSides())),this.collapseDifferences(t,e)}}buildResultQueue(t,e,n){if(this.queueIsFinished(t.peek(),e))return n;{let i=t.dequeue();return n.enqueue(t.currentSide,i),e<i.baseHi?(t.switchSides(),this.buildResultQueue(t,i.baseHi,n)):this.buildResultQueue(t,e,n)}}queueIsFinished(t,e){return t.length===0||t[0].baseLo>e+1}determineDifference(t,e,n){let i=t.get(e)[0].baseLo,o=t.get(n),s=o[o.length-1].baseHi,[a,l]=this.diffableEndpoints(t.get(Nr.left),i,s),[c,d]=this.diffableEndpoints(t.get(Nr.right),i,s),u=this.left.slice(a-1,l),p=this.right.slice(c-1,d),m=this.decideAction(t,u,p);return new pA(m,a,l,c,d,i,s)}diffableEndpoints(t,e,n){if(t.length){let i=t[0],o=t[t.length-1],s=i.sideLo-i.baseLo+e,a=o.sideHi-o.baseHi+n;return[s,a]}else return[e,n]}decideAction(t,e,n){return t.isEmpty(Nr.left)?Na.chooseRight:t.isEmpty(Nr.right)?Na.chooseLeft:e.every((i,o)=>n[o]===i)?Na.noConflictFound:Na.possibleConflict}},pA=class{constructor(t,e,n,i,o,s,a){this.changeType=t,this.leftLo=e,this.leftHi=n,this.rightLo=i,this.rightHi=o,this.baseLo=s,this.baseHi=a}};(function(r){r.chooseRight="choose_right",r.chooseLeft="choose_left",r.possibleConflict="possible_conflict",r.noConflictFound="no_conflict_found"})(Na||(Na={}));(function(r){r.left="left",r.right="right"})(Nr||(Nr={}));Bw=class{constructor(t=[],e=[]){this.diffs={left:t,right:e}}dequeue(t=this.currentSide){return this.diffs[t].shift()}peek(t=this.currentSide){return this.diffs[t]}isFinished(){return this.isEmpty(Nr.left)&&this.isEmpty(Nr.right)}enqueue(t=this.currentSide,e){return this.diffs[t].push(e)}get(t=this.currentSide){return this.diffs[t]}isEmpty(t=this.currentSide){return this.diffs[t].length===0}switchSides(t=this.currentSide){return this.currentSide=t===Nr.left?Nr.right:Nr.left}chooseSide(){return this.isEmpty(Nr.left)?this.currentSide=Nr.right:this.isEmpty(Nr.right)?this.currentSide=Nr.left:this.currentSide=this.get(Nr.left)[0].baseLo<=this.get(Nr.right)[0].baseLo?Nr.left:Nr.right,this.currentSide}}});var gg,fA,nL=x(()=>{lA();mA();Nw();gg=class r{static merge(t,e,n){let i=new r(t,e,n);return i.executeThreeWayMerge(),i.result}constructor(t,e,n){this.result=[],this.text3=new fA(t,n,e)}executeThreeWayMerge(){let t=Fp.executeDiff(this.text3.left,this.text3.base,this.text3.right),e=1;t.forEach(i=>{let o=[];for(let s=e;s<i.baseLo;s++)o.push(this.text3.base[s-1]);o.length&&this.result.push(new Eo(o)),this.interpretChunk(i),e=i.baseHi+1});let n=this.accumulateLines(e,this.text3.base.length,this.text3.base);n.length&&this.result.push(new Eo(n))}setConflict(t){let e=fg.create({left:this.accumulateLines(t.leftLo,t.leftHi,this.text3.left),base:this.accumulateLines(t.baseLo,t.baseHi,this.text3.base),right:this.accumulateLines(t.rightLo,t.rightHi,this.text3.right)});this.result.push(e)}determineConflict(t,e,n){let i=1;t.forEach(s=>{for(let l=i;l<=s.leftLo;l++)this.result.push(new Eo(this.accumulateLines(i,l,n)));let a=this.determineOutcome(s,e,n);i=s.rightHi+1,a&&this.result.push(a)});let o=this.accumulateLines(i,n.length+1,n);o.length&&this.result.push(new Eo(o))}determineOutcome(t,e,n){return t.action===Ls.change?fg.create({left:this.accumulateLines(t.rightLo,t.rightHi,e),right:this.accumulateLines(t.leftLo,t.leftHi,n),base:[]}):t.action===Ls.add?new Eo(this.accumulateLines(t.rightLo,t.rightHi,e)):null}setText(t,e,n){let i=[];for(let o=e;o<=n;o++)i.push(t[o-1]);return i}_conflictRange(t){let e=this.setText(this.text3.right,t.rightLo,t.rightHi),n=this.setText(this.text3.left,t.leftLo,t.leftHi),i=La.diff(e,n);(this._assocRange(i,Ls.change)||this._assocRange(i,Ls.remove))&&t.baseLo<=t.baseHi?this.setConflict(t):this.determineConflict(i,n,e)}interpretChunk(t){if(t.changeType==Na.chooseLeft){let e=this.accumulateLines(t.leftLo,t.leftHi,this.text3.left);e.length&&this.result.push(new Eo(e))}else if(t.changeType!==Na.possibleConflict){let e=this.accumulateLines(t.rightLo,t.rightHi,this.text3.right);e.length&&this.result.push(new Eo(e))}else this._conflictRange(t)}_assocRange(t,e){for(let n=0;n<t.length;n++){let i=t[n];if(i.action===e)return i}return null}accumulateLines(t,e,n){let i=[];for(let o=t;o<=e;o++)n[o-1]&&i.push(n[o-1]);return i}},fA=class{constructor(t,e,n){this.left=t,this.right=e,this.base=n}}});var Ld,iL=x(()=>{Ld=class{constructor(t,e,n={}){this.results=t,this.joinFunction=e,this.conflictHandler=n.conflictHandler,this.conflict=n.conflict||!1}isSuccess(){return!this.conflict}isConflict(){return!!this.conflict}joinedResults(){if(this.isConflict())return this.conflictHandler?this.conflictHandler(this.results):this.results;{let[t,e]=[this.results[0],this.results.slice(1)],n=t;return e.forEach(i=>n.combine(i)),n.apply(this.joinFunction).result}}}});var vg,oL=x(()=>{lA();iL();vg=class r{static collateMerge(t,e,n){return t.length?(t=r.combineNonConflicts(t),t.length===1&&t[0].isResolved()?new Ld(t,e):new Ld(t,e,{conflict:!0,conflictHandler:n})):new Ld([new Eo([])],e)}static combineNonConflicts(t){let e=[];return t.forEach(n=>{e.length&&e[e.length-1].isResolved()&&n.isResolved()?e[e.length-1].combine(n):e.push(n)}),e}}});function sL(r,t,e,n){return function(o){return o.map(s=>{if(s.isResolved())return s.apply(n).result;{let a=s.apply(n),{left:l,right:c}=a;return[r,l,t,c,e].join(`
|
||
`)}}).join(`
|
||
`)}}var aL=x(()=>{});function hA(r,t,e,n={}){n=Object.assign({},A3,n);let[i,o,s]=[r,t,e].map(c=>n.splitFunction.call(n,c)),a=gg.merge(i,o,s);return vg.collateMerge(a,n.joinFunction,n.conflictFunction)}var lL,k3,S3,A3,cL=x(()=>{nL();oL();aL();lL=r=>r.join(""),k3=r=>r.split(/\b/),S3=sL("<<<<<<< YOUR CHANGES","=======",">>>>>>> APP AUTHORS CHANGES",lL),A3={splitFunction:k3,joinFunction:lL,conflictFunction:S3}});var dL,uL=x(()=>{cL();mA();Nw();dL=hA});function Vr(r,t){if(!r)throw new Error(typeof t=="function"?t():t)}var Nd=x(()=>{});function vA(r,t){let e=i=>i instanceof gA.MarkdownView&&i.file===t&&!!i.editor&&i.getMode()==="source",n=r.workspace.getActiveViewOfType(gA.MarkdownView);return e(n)?n:r.workspace.getLeavesOfType("markdown").map(i=>i.view).find(e)??null}async function pL(r,t){let e=vA(r,t);e&&await yA(e)}async function Bd(r,t){return await pL(r,t),r.vault.read(t)}async function To(r,t,e){let n=vA(r,t);if(n){await yA(n);let i=await r.vault.read(t),{editor:o}=n,s=o.getValue();if(vA(r,t)===n&&s===Vd(i)){let a=Vd(e(s)),l=P3(s,a);return l&&(o.transaction({changes:[{from:o.offsetToPos(l.from),to:o.offsetToPos(l.to),text:l.text}]}),await yA(n).catch(c=>S.logWarning(`Could not save '${t.path}' yet: ${String(c)}`))),a}}return r.vault.process(t,e)}async function mL(r,t,e,n){let i=!1;return{content:await To(r,t,s=>{if(Vd(s)===Vd(e))return n;let a=dL(Vd(s),Vd(e),Vd(n));return Vr(a.isSuccess(),()=>`The file ${t.path} has been modified since the last read.
|
||
QuickAdd could not merge the two versions without conflicts, and will not modify the file.
|
||
This is in order to prevent data loss.`),i=!0,a.joinedResults()}),merged:i}}async function Va(r,t,e){await pL(r,t),await r.fileManager.processFrontMatter(t,e)}async function yA(r){await r.save();let t=()=>r.saving===!0;for(let e=0;t();e+=10){if(e>=I3)throw new Error(`Obsidian is still saving '${r.file?.path}'. Try again once it has saved.`);await Ow(10)}}function P3(r,t){if(r===t)return null;let e=Math.min(r.length,t.length),n=0;for(;n<e&&r.charCodeAt(n)===t.charCodeAt(n);)n++;let i=0;for(;i<e-n&&r.charCodeAt(r.length-1-i)===t.charCodeAt(t.length-1-i);)i++;return{from:n,to:r.length-i,text:t.slice(n,t.length-i)}}function Vd(r){return r.includes("\r")?r.replace(/\r\n?/g,`
|
||
`):r}var gA,I3,Ns=x(()=>{gA=require("obsidian");Pp();uL();Nd();ye();I3=1e4});function Mp(r){return $3.has(r)}function Ba(r){return r==="inFrontmatter"}function Uw(r){return F3.has(r)}function M3(r,t,e){return r==="embed"&&e.type==="activeFile"&&Mp(t)?"embed":"link"}function R3(r,t,e,n){return r==="selection"&&e.type==="activeFile"&&Uw(t)&&n==="link"?"selection":"none"}function O3(r){return r?.type==="specifiedFile"?{type:"specifiedFile",path:typeof r.path=="string"?r.path.trim():""}:{type:"activeFile"}}function D3(r){return typeof r=="object"&&r!==null&&"enabled"in r&&"placement"in r}function Zo(r){if(D3(r)){let t=r.placement??"replaceSelection",e=O3(r.destination),n=M3(r.linkType,t,e);return{enabled:r.enabled,placement:t,requireActiveFile:r.requireActiveFile??!0,linkType:n,displayText:R3(r.displayText,t,e,n),destination:e,frontmatterProperty:r.frontmatterProperty,frontmatterHandling:Ba(t)?r.frontmatterHandling??Ud:r.frontmatterHandling}}return{enabled:r,placement:"replaceSelection",requireActiveFile:!!r,linkType:"link",displayText:"none",destination:{type:"activeFile"}}}var Ud,$3,F3,Ua=x(()=>{Ud="alwaysAppend",$3=new Set(["replaceSelection","afterSelection","endOfLine","newLine"]);F3=new Set(["replaceSelection","afterSelection"])});function bA(r){return r.vault.getConfig?.("useMarkdownLinks")===!0}function L3(r,t){let e=t.replace(/\s+/g,n=>/[\r\n]/.test(n)?" ":n).trim();if(e){if(bA(r))return e.replace(/\\/g,"\\\\").replace(/\[/g,"\\[").replace(/\]/g,"\\]");if(!(e.includes("]]")||e.includes("[[")||e.endsWith("]")))return e}}function N3(r){return`[[${r.path.replace(/\.md$/i,"")}]]`}function qw(r,t,e={}){let n=e.sourcePath??"";if(e.linkType==="embed"&&(!e.placement||Mp(e.placement)))return`![[${r.metadataCache.fileToLinktext(t,n)}]]`;let o=e.alias===void 0?void 0:L3(r,e.alias);return o===void 0?r.fileManager.generateMarkdownLink(t,n):r.fileManager.generateMarkdownLink(t,n,void 0,o)}function wA(r){let t=r.trim().replace(/^\/+/,"");return t?/\.md$/i.test(t)?t:`${t}.md`:""}function bg(r,t){if(t.type!=="specifiedFile")return null;let e=wA(t.path);if(!e)return null;let n=r.vault.getAbstractFileByPath(e);return!(n instanceof yg.TFile)||n.extension!=="md"?null:n}function V3(r,t){return r.length===0?t:r.endsWith(`
|
||
`)?`${r}${t}`:`${r}
|
||
${t}`}async function hL(r,t,e,n){let i=e.destination;if(i?.type!=="specifiedFile")return!1;let o=bg(r,i);if(!o)throw new Error(`Append link target file not found or is not a Markdown file: ${i.path}`);return await CA(r,o,qw(r,t,{sourcePath:o.path,linkType:"link"}),n),!0}async function CA(r,t,e,n){let i;await To(r,t,o=>{let s=V3(o,e);return i={filePath:t.path,before:o,after:s,edits:[{from:o.length,to:o.length,text:s.slice(o.length)}]},s}),i&&n?.(i)}async function B3(r){let t=window.navigator?.clipboard;if(!t?.writeText)return S.logMessage("QuickAdd: Clipboard API is unavailable."),!1;try{return await t.writeText(r),!0}catch(e){return S.logMessage(`QuickAdd: Could not copy link to clipboard: ${e instanceof Error?e.message:String(e)}`),!1}}async function gL(r){let t=N3(r);return await B3(t)?(new yg.Notice(`Copied link to '${r.basename}' to clipboard.`,fL),!0):(new yg.Notice(`Created '${r.basename}', but QuickAdd could not copy its link to the clipboard.`,fL),!1)}var yg,fL,qd=x(()=>{yg=require("obsidian");Ns();ye();Ua();fL=4e3});function Rp(r){return r&&typeof r=="object"?r:void 0}function xA(r){return typeof r=="string"?r.trim():""}function vL(r){return r.replace(/[\\/]+/g,"/").replace(/^\/|\/$/g,"")}function yL(r){return`{{${r.toUpperCase()}}}`}function bL(r,t,e){return{source:r,folder:vL(xA(e.folder)),format:xA(e.format)||U3[t],template:vL(xA(e.template))}}function Hw(r,t){let e=Rp(Rp(r?.plugins?.plugins?.["periodic-notes"])?.settings);if(e&&"calendarSets"in e)throw new Error(`${yL(t)} can't read the settings of Periodic Notes 1.0. Use Periodic Notes 0.0.17, or turn it off and use the Daily notes core plugin.`);let n=Rp(e?.[t]);if(n?.enabled===!0)return bL("periodic-notes",t,n);if(t!=="daily")throw new Error(`${yL(t)} needs the Periodic Notes plugin with ${t} notes turned on.`);let i=Rp(r?.internalPlugins?.plugins?.["daily-notes"]);if(i?.enabled===!0)return bL("daily-notes",t,Rp(Rp(i.instance)?.options)??{});throw new Error("{{DAILY}} needs the Daily notes core plugin, or Periodic Notes with daily notes, turned on.")}function wL(r,t){return t.clone().startOf(q3[r])}function CL(r,t,e){let n=wL(t,e).format(r.format).trim().replace(/\.md$/i,"");if(!n)throw new Error(`The ${t} note format "${r.format}" gives an empty file name.`);return r.folder?`${r.folder}/${n}`:n}function xL(r,t,e){let n=r.vault.getAbstractFileByPath(`${t}.md`);if(n instanceof zw.TFile)return r.fileManager.generateMarkdownLink(n,e);if(!bA(r))return`[[${t}]]`;let i=encodeURI(`${t}.md`).replace(/\(/g,"%28").replace(/\)/g,"%29");return`[${(t.split("/").pop()??t).replace(/[\\[\]]/g,"\\$&")}](${i})`}async function EL(r,t,e){let{template:n}=t;if(!n)return null;let i=r.vault.getAbstractFileByPath(n),o=t.source==="periodic-notes"?r.metadataCache.getFirstLinkpathDest(n,""):i instanceof zw.TFile?i:r.vault.getAbstractFileByPath(`${n}.md`);if(!(o instanceof zw.TFile)){let s=t.source==="daily-notes"?"Daily notes":"Periodic Notes";throw new Error(`The ${e} note template "${n}" doesn't exist. Fix it in Settings \u2192 ${s}.`)}return r.vault.cachedRead(o)}function EA(r,t,e,n){return r.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(i,o,s,a,l,c)=>{let d=t.clone().set({hour:e.hour(),minute:e.minute(),second:e.second()});return s&&a&&l&&d.add(parseInt(a,10),l),c?d.format(c.substring(1).trim()):d.format(n)})}function TL(r,t,e,n,i){let{format:o}=t,s=wL(e,n);if(t.source==="daily-notes"){let c=s.format(o).trim();return r.replace(/{{(date|time|title)(?::([^}]*))?}}/gi,(d,u,p)=>{let m=u.toLowerCase();return m==="title"?p===void 0?c:d:i.format(p||(m==="date"?"YYYY-MM-DD":"HH:mm"))})}let a=s.format(o),l=i.format("HH:mm");if(e==="daily")return EA(r.replace(/{{\s*date\s*}}/gi,a).replace(/{{\s*time\s*}}/gi,l).replace(/{{\s*title\s*}}/gi,a),s,i,o).replace(/{{\s*yesterday\s*}}/gi,s.clone().subtract(1,"day").format(o)).replace(/{{\s*tomorrow\s*}}/gi,s.clone().add(1,"d").format(o));if(e==="weekly"){let c=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],d=s.localeData().firstDayOfWeek(),u=[...c.slice(d),...c.slice(0,d)];return EA(r,s,i,o).replace(/{{\s*title\s*}}/gi,a).replace(/{{\s*time\s*}}/gi,l).replace(/{{\s*(sunday|monday|tuesday|wednesday|thursday|friday|saturday)\s*:(.*?)}}/gi,(p,m,h)=>s.clone().weekday(u.indexOf(m.toLowerCase())).format(h.trim()))}return EA(r,s,i,o).replace(/{{\s*date\s*}}/gi,a).replace(/{{\s*time\s*}}/gi,l).replace(/{{\s*title\s*}}/gi,a)}var zw,TA,U3,q3,_A=x(()=>{zw=require("obsidian");qd();TA=/{{(DAILY|WEEKLY|MONTHLY|QUARTERLY|YEARLY)(\|link)?}}/i,U3={daily:"YYYY-MM-DD",weekly:"gggg-[W]ww",monthly:"YYYY-MM",quarterly:"YYYY-[Q]Q",yearly:"YYYY"},q3={daily:"day",weekly:"week",monthly:"month",quarterly:"quarter",yearly:"year"}});function _L(r){if(!r)return null;let t=r.indexOf("|");if(t===-1){let o=r.trim();return o?{macroName:o}:null}let e=r.slice(0,t).trim();if(!e)return null;let n=r.slice(t+1).trim();if(!n)return{macroName:e};if(!n.toLowerCase().startsWith("label:"))return null;let i=n.slice(6).trim();return{macroName:e,label:i||void 0}}var kL=x(()=>{});function AL(r){let t=r.trim();if(!t||/[\r\n\0]/.test(t)||t==="__proto__")throw new Error("Property name must be nonempty and contain no line breaks or unsafe keys.");return t}function IL(r){return Rh.test(r)}function PL(r){if(r==null)return"";if(Array.isArray(r)){if(!r.every(t=>typeof t=="string"))throw new Error("{{PROPERTY}} only expands lists of text.");if(r.some(t=>/[\r\n]/.test(t)))throw new Error("{{PROPERTY}} cannot expand a list item that contains a line break. Return a rewritten array from an inline script instead.");return r.join(`
|
||
`)}if(typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r))return String(r);throw new Error("{{PROPERTY}} only expands text, finite numbers, checkboxes, and lists of text.")}function FL(r){return $L.map(t=>({key:t,present:r.has(t),value:r.get(t)}))}function ML(r,t){for(let e of t)e.present?r.set(e.key,e.value):r.delete(e.key)}function RL(r,t,e){for(let i of $L)if(!(!r.has(i)||r.get(i)===void 0))throw new Error(`Property Capture cannot seed '${i}' because that variable is already set. Rename your {{VALUE:${i}}} prompt (or other writer of this key) so it does not collide with the property snapshot.`);let n;e!=null&&(n=z3(e,t)),r.set("propertyKey",t),r.set("propertyValue",n),r.set("list",Array.isArray(n)?[...n]:[])}function z3(r,t){if(typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r))return r;if(Array.isArray(r)&&r.every(e=>typeof e=="string"))return[...r];throw new Error(`Property '${t}' supports text, finite numbers, checkboxes, and lists of text only.`)}function wg(r,t){if(Object.prototype.hasOwnProperty.call(r,t))return t;let e=Object.keys(r).filter(n=>n.trim().toLowerCase()===t.trim().toLowerCase());if(e.length>1)throw new Error(`Property '${t}' matches multiple properties in the target note.`);return e[0]??t}function OL(r){return r.split(/\r?\n/).map(t=>t.trim()).filter(t=>t!=="")}function DL(r){return typeof r=="string"?OL(r).length===0:Array.isArray(r)&&r.length===0}function SL(r,t){if(typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r))return r;if(Array.isArray(r)&&r.every(e=>typeof e=="string"))return[...r];throw new Error(`Property '${t}' supports text, finite numbers, checkboxes, and lists of text only.`)}function LL(r,t){if(r===null&&["tags","aliases","cssclasses"].includes(t.toLowerCase()))return"list";if(r===null)return null;switch(r.toLowerCase()){case"text":return"text";case"number":return"number";case"checkbox":case"boolean":return"checkbox";case"list":case"multitext":case"tags":case"aliases":return"list";case"date":return"date";case"datetime":return"datetime";default:throw new Error(`Property '${t}' has unsupported type '${r}'.`)}}function NL(r){if(r.action==="addToList")return!0;let t=LL(r.registeredType,r.key);return t==="list"||t===null&&Array.isArray(r.existing)}function Ww(r){return Array.isArray(r)?"list":typeof r=="boolean"?"checkbox":typeof r=="number"?"number":"text"}function H3(r,t,e){let n=Ww(r);if(t==="date"||t==="datetime"){if(typeof r=="string"&&(r===""||(t==="date"?/^\d{4}-\d{2}-\d{2}$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})?$/).test(r)&&Number.isFinite(Date.parse(r))&&new Date(r.slice(0,10)).toISOString().slice(0,10)===r.slice(0,10)))return}else if(n===t)return;throw new Error(`Property '${e}' requires ${t}; the capture is ${n}. Use a matching typed VALUE token or value.`)}function VL(r){let{frontmatter:t,config:e}=r,n=wg(t,r.key),i=Object.prototype.hasOwnProperty.call(t,n);if(!i&&!e.createIfMissing)throw new Error(`Property '${n}' is missing. Enable 'Create property if missing' to add it.`);let o=i?t[n]:void 0,s=SL(r.value,n),a=o==null?null:SL(o,n),l=LL(r.registeredType,n)??(a===null?null:Ww(a)),c=typeof s=="string"?OL(s):null;if(e.action==="addToList"){if(a!==null&&!Array.isArray(a))throw new Error(`Property '${n}' is ${Ww(a)}. 'Add to list' requires a list.`);if(l!==null&&l!=="list")throw new Error(`Property '${n}' is ${l}. 'Add to list' requires a list.`);let u=c??s;if(!Array.isArray(u))throw new Error(`Property '${n}' requires text or a list of text to add.`);return u.length===0?a??[]:r.compose?[...new Set(u)]:[...new Set([...a??[],...u])]}if(l==="list"&&a!==null&&!Array.isArray(a))throw new Error(`Property '${n}' contains ${Ww(a)}. Set a list only after correcting the existing property to a list.`);if(l===null&&c!==null&&c.length>1)throw new Error(`Property '${n}' has no type yet, so ${c.length} lines could be one text value or a list. Use 'Add to list' to write them as list items, or set the property's type in Obsidian first - Text keeps the lines as one value.`);let d=l==="list"?c??s:s;return l!==null&&H3(d,l,n),Array.isArray(d)?[...new Set(d)]:d}function BL(r){let t=(0,zd.getFrontMatterInfo)(r);if(!t.exists||!t.frontmatter.trim())return{};let e=(0,zd.parseYaml)(t.frontmatter);if(e===null)return{};if(!e||typeof e!="object"||Array.isArray(e))throw new Error("The capture target's frontmatter must be a property mapping.");return Object.fromEntries(Object.entries(e))}function UL(r,t){let e=(0,zd.getFrontMatterInfo)(r),n=e.exists?r.slice(e.contentStart):r;return`---
|
||
${(0,zd.stringifyYaml)(t)}---
|
||
${n}`}var zd,$L,kA=x(()=>{zd=require("obsidian");Le();$L=["propertyKey","propertyValue","list"]});var qL,Gw,ec,Op=x(()=>{nA();Rd();Rd();Oa();sA();qL=require("obsidian");Le();Ln();rL();_A();ye();Cw();Da();kL();kA();nA();Oa();Gw=10,ec=class extends kw{constructor(){super(...arguments);this.linkToCurrentFileBehavior="required";this.targetFolderPath=null;this.periodicNoteTarget=null;this.propertyTokenExpanded=!1}runClocks(){return this.clocks}setTemplateInclusionState(e){this.templateInclusion=e}replaceDateInString(e){let n=N0(e,{clocks:()=>this.runClocks(),applyCase:(i,o,s)=>this.applyCaseOption(i,o,s)});return TA.test(n)?this.replacePeriodicNotesInString(n):n}outermostIncluder(){return this.templateInclusion?.includer?.outermostIncluder()??this}replacePeriodicNotesInString(e){let n=this.runClocks(),i=window.moment(n?.date??n?.now),o=new RegExp(TA.source,"gi");return e.replace(o,(s,a,l)=>{let c=a.toLowerCase(),d=CL(Hw(this.app,c),c,i);return l&&this.app?xL(this.app,d,this.getLinkSourcePath()??""):(this.promptScope==="captureTarget"&&(this.outermostIncluder().periodicNoteTarget={path:d,period:c}),d)})}replaceTimeInString(e){return V0(e,{clocks:()=>this.runClocks(),applyCase:(n,i,o)=>this.applyCaseOption(n,i,o)})}async replaceSelectedInString(e){if(!Oh.test(e))return e;let n=await this.getSelectedText(),i=new RegExp(Oh.source,"gi"),o=this.userText(n);return e.replace(i,()=>o)}async replaceClipboardInString(e){if(!TS.test(e))return e;let n=await this.getClipboardContent(),i=new RegExp(TS.source,"gi"),o=this.userText(n);return e.replace(i,()=>o)}async replaceLinkToCurrentFileInString(e){if(!xS.test(e))return e;let n=this.getCurrentFileLink();if(!n){if(this.linkToCurrentFileBehavior==="required")throw new Error("Unable to get current file path. Make sure you have a file open in the editor.");S.logMessage("Skipping {{LINKCURRENT}} replacement because no active file is available.")}let i=new RegExp(xS.source,"gi");return e.replace(i,()=>n??"")}replaceLinkToCurrentSectionInString(e){if(!ES.test(e))return e;let n=this.getCurrentFileLinkToSection();if(!n){if(this.linkToCurrentFileBehavior==="required")throw new Error("Unable to get current file path. Make sure you have a file open in the editor.");S.logMessage("Skipping {{LINKSECTION}} replacement because no active file is available.")}let i=new RegExp(ES.source,"gi");return e.replace(i,()=>n??"")}replaceCurrentFileLinksInString(e){return this.replaceCurrentFileTokensInString(e,{links:!0})}replaceCurrentFileTokensInString(e,n){return W0(e,n,{LINKCURRENT:()=>this.getCurrentFileLink(),LINKSECTION:()=>this.getCurrentFileLinkToSection(),FILENAMECURRENT:()=>this.getCurrentFileName(),FOLDER:()=>this.targetFolderPath??"",FOLDERCURRENT:()=>this.getCurrentFolderPath(),TITLE:()=>this.getVariableValue("title")},this.linkToCurrentFileBehavior)}async replaceCurrentFileNameInString(e){return this.replaceCurrentFileTokensInString(e,{fileName:!0})}setLinkToCurrentFileBehavior(e){this.linkToCurrentFileBehavior=e}setTargetFolderPath(e){if(e==null){this.targetFolderPath=null;return}let n=e.trim();this.targetFolderPath=n==="/"?"":n.replace(/^\/+/,"").replace(/\/+$/,"")}replaceTargetFolderInString(e){return this.replaceCurrentFileTokensInString(e,{folder:!0})}getCurrentFileLinkToSection(){return null}getCurrentFolderPath(){return null}async replaceFieldVarInString(e){let n=new RegExp(dp.source,"gi"),i="",o=0,s;for(;(s=n.exec(e))!==null;){i+=e.slice(o,s.index);let a=s[1]+(s[2]||"");if(a){let l=this.getFieldVariableKey(a),c=Dn.parse(a,{warnUnknown:!0,warn:this.warnSink});this.hasConcreteVariable(l)||this.variables.set(l,await this.suggestForField(a,c));let d=this.hasConcreteVariable(l)?this.variables.get(l):this.getVariableValue(l);(!c.multiFormat||c.multiFormat==="auto")&&this.retainSingleTokenValue(e,s.index,s.index+s[0].length,d);let u;Array.isArray(d)?u=this.renderCollectedOrArrayValue({input:e,matchStart:s.index,matchEnd:s.index+s[0].length,rawValue:d,fallbackKey:c.fieldName,heuristicEnabled:!1,multiFormat:c.multiFormat??"auto"})??d.join(","):u=$d(e,s.index,s.index+s[0].length,String(d??"")),i+=this.userText(u)}else i+=s[0];o=n.lastIndex}return i+e.slice(o)}getFieldVariableKey(e){return`${Bl}${e}`}async replaceFileInString(e){let n=new RegExp(rw.source,"gi"),i="",o=0,s;for(;(s=n.exec(e))!==null;){i+=e.slice(o,s.index);let a=Rw(s[1]??"",{warn:this.warnSink});if(!a){i+=s[0],o=n.lastIndex;continue}let l=a.variableKey;this.hasConcreteVariable(l)||this.variables.set(l,await this.suggestForFile(a));let c=tL(this.variables.get(l),a.mode,d=>this.getFileLinkForStoredValue(d));if(Array.isArray(c)){let d=this.renderCollectedOrArrayValue({input:e,matchStart:s.index,matchEnd:s.index+s[0].length,rawValue:c,fallbackKey:a.aliasName??a.folderPath,heuristicEnabled:!1,multiFormat:a.multiFormat});i+=this.userText(d??c.join(","))}else i+=this.userText(c);o=n.lastIndex}return i+e.slice(o)}getFileLinkForStoredValue(e){let n=Od(e);if(n.kind==="empty")return"";if(n.kind!=="file"){let s=n.kind==="custom"?n.text:n.value;return s?`[[${s}]]`:""}let i=n.path;if(!i)return"";let o=this.app?.vault.getAbstractFileByPath(i);return o instanceof qL.TFile?this.app?.fileManager.generateMarkdownLink(o,this.getLinkSourcePath()??"")??`[[${Ip(i)}]]`:`[[${Ip(i)}]]`}getLinkSourcePath(){return null}async replaceMathValueInString(e){let n=new RegExp(Mh.source,"gi"),i=this.variables.get("mvalue"),o=typeof i=="string"&&i.trim()?i:null,s="",a=0,l;for(;(l=n.exec(e))!==null;)s+=e.slice(a,l.index),s+=this.userText(o??await this.promptForMathValue()),a=l.index+l[0].length;return s+=e.slice(a),s}async replaceMacrosInString(e){let n=new RegExp(nw.source,"gi"),i="",o=0,s;for(;(s=n.exec(e))!==null;){i+=e.slice(o,s.index),o=s.index+s[0].length;let a=s[1]?_L(s[1]):null;if(!a)continue;let l=await this.getMacroValue(a.macroName,a.label?{label:a.label}:void 0);i+=l?l.toString():""}return i+=e.slice(o),i}async replaceDateVariableInString(e){return U0(e,{variables:this.variables,dateParser:this.dateParser,prompt:(n,i)=>this.promptForVariable(n,i),applyCase:(n,i,o)=>this.applyCaseOption(n,i,o)})}getValueTokenText(e){let n=this.variables.get(e);if(typeof n=="string"&&n.startsWith("@date:")&&window.moment?.(n.slice(6)).isValid()){let i=Pw(this.variables,e)??ag(!1);return dg(n,i,void 0,this.dateParser)?.text??""}return super.getValueTokenText(e)}async replaceTemplateInString(e){let n=e;for(;As.test(n);){let i=As.exec(n);if(!i||!i[1])continue;let o=i[1];if(this.templateInclusion??(this.templateInclusion={visited:new Set,depth:0}),this.templateInclusion.visited.has(o)){let a=`[QuickAdd: template inclusion cycle detected at "${o}"]`;this.reportProblem(a),n=this.replacer(n,As,a);continue}if(this.templateInclusion.depth>=Gw){let a=`[QuickAdd: max template inclusion depth (${Gw}) exceeded at "${o}"]`;this.reportProblem(a),n=this.replacer(n,As,a);continue}this.templateInclusion.visited.add(o);let s;try{s=await this.getTemplateContent(o)}finally{this.templateInclusion.visited.delete(o)}n=this.replacer(n,As,s)}return n}replaceLinebreakInString(e){let n="";for(let i=0;i<e.length;i++){let o=e[i],s=e[i+1];o=="\\"?s=="n"?(n+=`
|
||
`,i++):s=="\\"?(n+="\\",i++):n+="\\":n+=o}return n}expandLinebreakEscapesOutsideTokens(e){let n=yi(e),i="",o=0,s=0;for(;o<e.length;){for(;s<n.length&&n[s].end<=o;)s++;let a=n[s];if(a&&a.start===o){i+=e.slice(a.start,a.end),o=a.end;continue}if(e[o]==="{"&&e[o+1]==="{"){let d=e.indexOf("}}",o+2),u=!1;if(d!==-1){let p=d+2;for(let m=s;m<n.length;m++){let h=n[m];if(h.start>=p)break;if(p<h.end&&p>h.start){u=!0;break}}}if(d!==-1&&!u){i+=e.slice(o,d+2),o=d+2;continue}}let l=e[o],c=e[o+1];l==="\\"?c==="n"?(i+=`
|
||
`,o+=2):c==="\\"?(i+="\\",o+=2):(i+="\\",o+=1):(i+=l,o+=1)}return i}replaceRandomInString(e){let n=e;for(;_S.test(n);){let i=_S.exec(n);if(!i||!i[1])continue;let o=parseInt(i[1]);if(o<=0||o>100)throw new Error(`Random string length must be between 1 and 100. Got: ${o}`);let s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a="";for(let l=0;l<o;l++)a+=s.charAt(Math.floor(Math.random()*s.length));n=n.replace(i[0],a)}return n}replaceTitleInString(e){return this.replaceCurrentFileTokensInString(e,{title:!0})}consumePropertyTokenExpanded(){let e=this.propertyTokenExpanded;return this.propertyTokenExpanded=!1,e}replacePropertyInString(e){if(!Rh.test(e))return e;if(this.promptScope!=="propertyValue")throw new Error("{{PROPERTY}} can only be used in a property Capture format.");this.propertyTokenExpanded=!0;let n=this.variables.get("propertyValue");/^{{PROPERTY}}$/i.test(e.trim())&&e.trim()===e&&this.retainSingleTokenValue(e,0,e.length,n===void 0?"":n);let i=this.userText(PL(n));return e.replace(new RegExp(Rh.source,"gi"),()=>i)}}});function HL(r){return r<=31||r===127||r===8232||r===8233}function j3(r){let t="",e=0;for(;e<r.length;){let n=e;for(;n<r.length&&r.charCodeAt(n)===32;)n++;if(n<r.length&&HL(r.charCodeAt(n))){for(;n<r.length&&HL(r.charCodeAt(n));)n++;for(;n<r.length&&r.charCodeAt(n)===32;)n++;t+=" ",e=n;continue}t+=r.slice(e,Math.min(n+1,r.length)),e=n+1}return t}function WL(r,t){let e=r.length;for(;e>0&&t.includes(r[e-1]);)e--;return r.slice(0,e)}function Hd(r){return Y3.filter(t=>r.includes(t))}function jL(r){return`A file or folder name cannot contain ${QL(r)}, so this choice would fail at run time. ${KL}`}function YL(r,t){return`Cannot create "${t}": a file or folder name cannot contain ${QL(r)}. ${KL}`}function QL(r){return r.map(t=>`"${t}"`).join(", ")}function Br(r,t="File path"){let{path:e,problems:n}=JL(r,t);if(n.length>0)throw new Error(n[0]);return e}function XL(r,t="File path"){return JL(r,t)}function JL(r,t){let e=[],n=r.replace(/\\/g,"/").split("/");return{path:n.map((o,s)=>o.length===0&&s!==0&&s!==n.length-1?(e.push(`${t} contains an empty path segment after formatting.`),o):K3(o,t,e)).join("/"),problems:e}}function K3(r,t,e){if(r.length===0)return r;let n=W3.test(r),i=G3.test(r),o=j3(r);n&&(o=o.replace(/^ /u,"")),i&&(o=o.replace(/ $/u,""));let s=WL(o," ");return s==="."||s===".."?(e.push(`${t} cannot contain "." or ".." path segments.`),s):(o=WL(o,". "),o||e.push(`${t} contains an empty path segment after formatting.`),o)}var GL,W3,G3,Y3,KL,es=x(()=>{GL="\0-\x7F\u2028\u2029",W3=new RegExp(`^ *[${GL}]`,"u"),G3=new RegExp(`[${GL}] *$`,"u");Y3=[":"];KL="Check your own text and tokens like {{TIME}}, which is HH:mm."});function Np(r){if(r==null||typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")return"";let t=String(r).trim();return t.startsWith("#")?t.substring(1).trim():t}function xg(r){return r==null?[]:(Array.isArray(r)?r:typeof r=="string"?r.split(/,|\s+/):[r]).map(Np).filter(Boolean)}var IA=x(()=>{});var Vs,jw=x(()=>{IA();Vs=class{static filterFiles(t,e,n){let i=this.applyInclusionFilters(t,e,n);return this.applyExclusionFilters(i,e,n)}static applyInclusionFilters(t,e,n){let i=t,o=this.getIncludeFolders(e);return o.length>0&&(i=i.filter(s=>o.some(a=>this.matchesFolder(s,a)))),e.tags&&e.tags.length>0&&(i=i.filter(s=>this.matchesTags(s,e.tags??[],n,"all"))),i}static applyExclusionFilters(t,e,n){return t.filter(i=>!(e.excludeFolders?.length&&e.excludeFolders.some(o=>this.matchesFolder(i,o)))&&!(e.excludeTags?.length&&this.matchesTags(i,e.excludeTags,n,"any"))&&!(e.excludeFiles?.length&&e.excludeFiles.some(o=>this.matchesFile(i,o))))}static getIncludeFolders(t){let e=t.folders?.length?t.folders:t.folder?[t.folder]:[];return[...new Set(e.map(n=>this.normalizePath(n)).filter(Boolean))]}static matchesFolder(t,e){let n=this.normalizePath(e),i=this.normalizePath(t.path);return i.startsWith(n+"/")||i.substring(0,i.lastIndexOf("/"))===n}static matchesTags(t,e,n,i){let o=n(t);if(!o)return!1;let s=this.getAllTags(o),a=e.map(Np).filter(Boolean),l=c=>s.some(d=>d===c||d.startsWith(c+"/"));return i==="all"?a.every(l):a.some(l)}static matchesFile(t,e){return t.name===e||t.path===e}static getAllTags(t){let e=[];return t.frontmatter?.tags&&e.push(...xg(t.frontmatter.tags)),t.frontmatter?.tag&&e.push(...xg(t.frontmatter.tag)),t.tags&&e.push(...t.tags.map(n=>Np(n.tag))),e.filter(Boolean)}static normalizePath(t){return t.replace(/^\/+|\/+$/g,"")}}});function za(r){return r.vault.getAllLoadedFiles().filter(t=>t instanceof PA.TFolder).map(t=>t.path)}function Eg(r,t){let e=r.vault.getAbstractFileByPath(t);return!!e&&e instanceof PA.TFolder}function ts(r,t){let e=t.replace(/\/+$/,"");if(e==="")return r.vault.getMarkdownFiles();let n=`${e}/`;return r.vault.getMarkdownFiles().filter(i=>i.path===e||i.path.startsWith(n))}function Z3(r){return Object.entries(r.frontmatter??{}).filter(([t])=>["tag","tags"].includes(t.toLowerCase())).flatMap(([,t])=>xg(t)).filter(Boolean)}function e4(r,t){let e=r.metadataCache.getFileCache(t);if(!e)return[];let n=[];return e.frontmatter&&n.push(...Z3(e)),e.tags&&Array.isArray(e.tags)&&n.push(...e.tags.map(i=>Np(i.tag))),n}function lN(r,t){let e=t.replace(/^#/,"");return r.vault.getMarkdownFiles().filter(n=>e4(r,n).includes(e))}function Yw(r,t){return Vs.filterFiles(r.vault.getMarkdownFiles(),t,e=>r.metadataCache.getFileCache(e))}function t4(r,t){let e=t.trim().toLowerCase();return r==null?!1:Array.isArray(r)?r.some(n=>n!=null&&typeof n!="object"&&String(n).trim().toLowerCase()===e):typeof r=="object"?!1:String(r).trim().toLowerCase()===e}function Kw(r,t,e,n){let i=t.trim().toLowerCase();if(!i)return[];let o=r.vault.getMarkdownFiles().filter(a=>{let l=r.metadataCache.getFileCache(a)?.frontmatter;if(!l)return!1;let c=Object.entries(l).find(([d])=>d.toLowerCase()===i);return c?e===void 0?!0:t4(c[1],e):!1});return n&&(n.folder||n.tags?.length||n.excludeFolders?.length||n.excludeTags?.length||n.excludeFiles?.length)&&(o=Vs.filterFiles(o,n,a=>r.metadataCache.getFileCache(a))),o}function Vp(r,t){let{extensions:e}=t,n=e?e==="any"?r.vault.getFiles():r.vault.getFiles().filter(i=>e.has(i.extension.toLowerCase())):r.vault.getMarkdownFiles();return Vs.filterFiles(n,t.filter,i=>r.metadataCache.getFileCache(i))}var PA,bi=x(()=>{PA=require("obsidian");jw();IA()});function qi(r){if(!r.includes("\\|"))return r;let t="",e=0;for(let n of yi(r))t+=cN(r.slice(e,n.start)),t+=r.slice(n.start,n.end),e=n.end;return t+cN(r.slice(e))}var r4,cN,Wd=x(()=>{Oa();r4=/{{[^{}\n\r]*}}/g,cN=r=>r.replace(r4,t=>t.split("\\|").join("|"))});function rc(r,t){let e=r,n=new RegExp(iw.source,"gi"),i=0;for(;n.test(e)&&!(++i>5);)e=e.replace(n,(o,s)=>{let a=String(s??"").trim();if(!a)return o;let l=t?.[a];return typeof l=="string"?qi(l):""});return e}var Tg=x(()=>{Le();Wd()});var dt,Lt,zi,Ha=x(()=>{(function(r){r[r.AM=0]="AM",r[r.PM=1]="PM"})(dt||(dt={}));(function(r){r[r.SUNDAY=0]="SUNDAY",r[r.MONDAY=1]="MONDAY",r[r.TUESDAY=2]="TUESDAY",r[r.WEDNESDAY=3]="WEDNESDAY",r[r.THURSDAY=4]="THURSDAY",r[r.FRIDAY=5]="FRIDAY",r[r.SATURDAY=6]="SATURDAY"})(Lt||(Lt={}));(function(r){r[r.JANUARY=1]="JANUARY",r[r.FEBRUARY=2]="FEBRUARY",r[r.MARCH=3]="MARCH",r[r.APRIL=4]="APRIL",r[r.MAY=5]="MAY",r[r.JUNE=6]="JUNE",r[r.JULY=7]="JULY",r[r.AUGUST=8]="AUGUST",r[r.SEPTEMBER=9]="SEPTEMBER",r[r.OCTOBER=10]="OCTOBER",r[r.NOVEMBER=11]="NOVEMBER",r[r.DECEMBER=12]="DECEMBER"})(zi||(zi={}))});function rs(r,t){r.assign("day",t.getDate()),r.assign("month",t.getMonth()+1),r.assign("year",t.getFullYear())}function Qw(r,t){r.assign("hour",t.getHours()),r.assign("minute",t.getMinutes()),r.assign("second",t.getSeconds()),r.assign("millisecond",t.getMilliseconds()),r.assign("meridiem",t.getHours()<12?dt.AM:dt.PM)}function Wa(r,t){r.imply("day",t.getDate()),r.imply("month",t.getMonth()+1),r.imply("year",t.getFullYear())}function _g(r,t){r.imply("hour",t.getHours()),r.imply("minute",t.getMinutes()),r.imply("second",t.getSeconds()),r.imply("millisecond",t.getMilliseconds()),r.imply("meridiem",t.getHours()<12?dt.AM:dt.PM)}var Gd=x(()=>{Ha()});function nc(r,t,e,n,i=0){let o=0,s=0;for(;s<n;)o++,new Date(r,t-1,o).getDay()===e&&s++;return new Date(r,t-1,o,i)}function dN(r,t,e,n=0){let i=e===0?7:e,o=new Date(r,t-1+1,1,12),s=o.getDay()===0?7:o.getDay(),a;return s===i?a=7:s<i?a=7+s-i:a=s-i,o.setDate(o.getDate()-a),new Date(r,t-1,o.getDate(),n)}function Xw(r,t,e={}){if(r==null)return null;if(typeof r=="number")return r;let n=e[r]??i4[r];return n==null?null:typeof n=="number"?n:t==null?null:t>n.dstStart(t.getFullYear())&&!(t>n.dstEnd(t.getFullYear()))?n.timezoneOffsetDuringDst:n.timezoneOffsetNonDst}var i4,$A=x(()=>{Ha();i4={ACDT:630,ACST:570,ADT:-180,AEDT:660,AEST:600,AFT:270,AKDT:-480,AKST:-540,ALMT:360,AMST:-180,AMT:-240,ANAST:720,ANAT:720,AQTT:300,ART:-180,AST:-240,AWDT:540,AWST:480,AZOST:0,AZOT:-60,AZST:300,AZT:240,BNT:480,BOT:-240,BRST:-120,BRT:-180,BST:60,BTT:360,CAST:480,CAT:120,CCT:390,CDT:-300,CEST:120,CET:{timezoneOffsetDuringDst:120,timezoneOffsetNonDst:60,dstStart:r=>dN(r,zi.MARCH,Lt.SUNDAY,2),dstEnd:r=>dN(r,zi.OCTOBER,Lt.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-300,timezoneOffsetNonDst:-360,dstStart:r=>nc(r,zi.MARCH,Lt.SUNDAY,2,2),dstEnd:r=>nc(r,zi.NOVEMBER,Lt.SUNDAY,1,2)},CVT:-60,CXT:420,ChST:600,DAVT:420,EASST:-300,EAST:-360,EAT:180,ECT:-300,EDT:-240,EEST:180,EET:120,EGST:0,EGT:-60,EST:-300,ET:{timezoneOffsetDuringDst:-240,timezoneOffsetNonDst:-300,dstStart:r=>nc(r,zi.MARCH,Lt.SUNDAY,2,2),dstEnd:r=>nc(r,zi.NOVEMBER,Lt.SUNDAY,1,2)},FJST:780,FJT:720,FKST:-180,FKT:-240,FNT:-120,GALT:-360,GAMT:-540,GET:240,GFT:-180,GILT:720,GMT:0,GST:240,GYT:-240,HAA:-180,HAC:-300,HADT:-540,HAE:-240,HAP:-420,HAR:-360,HAST:-600,HAT:-90,HAY:-480,HKT:480,HLV:-210,HNA:-240,HNC:-360,HNE:-300,HNP:-480,HNR:-420,HNT:-150,HNY:-540,HOVT:420,ICT:420,IDT:180,IOT:360,IRDT:270,IRKST:540,IRKT:540,IRST:210,IST:330,JST:540,KGT:360,KRAST:480,KRAT:480,KST:540,KUYT:240,LHDT:660,LHST:630,LINT:840,MAGST:720,MAGT:720,MART:-510,MAWT:300,MDT:-360,MESZ:120,MEZ:60,MHT:720,MMT:390,MSD:240,MSK:180,MST:-420,MT:{timezoneOffsetDuringDst:-360,timezoneOffsetNonDst:-420,dstStart:r=>nc(r,zi.MARCH,Lt.SUNDAY,2,2),dstEnd:r=>nc(r,zi.NOVEMBER,Lt.SUNDAY,1,2)},MUT:240,MVT:300,MYT:480,NCT:660,NDT:-90,NFT:690,NOVST:420,NOVT:360,NPT:345,NST:-150,NUT:-660,NZDT:780,NZST:720,OMSST:420,OMST:420,PDT:-420,PET:-300,PETST:720,PETT:720,PGT:600,PHOT:780,PHT:480,PKT:300,PMDT:-120,PMST:-180,PONT:660,PST:-480,PT:{timezoneOffsetDuringDst:-420,timezoneOffsetNonDst:-480,dstStart:r=>nc(r,zi.MARCH,Lt.SUNDAY,2,2),dstEnd:r=>nc(r,zi.NOVEMBER,Lt.SUNDAY,1,2)},PWT:540,PYST:-180,PYT:-240,RET:240,SAMT:240,SAST:120,SBT:660,SCT:240,SGT:480,SRT:-180,SST:-660,TAHT:-600,TFT:300,TJT:300,TKT:780,TLT:540,TMT:300,TVT:720,ULAT:480,UTC:0,UYST:-120,UYT:-180,UZT:300,VET:-210,VLAST:660,VLAT:660,VUT:660,WAST:120,WAT:60,WEST:60,WESZ:60,WET:0,WEZ:0,WFT:720,WGST:-120,WGT:-180,WIB:420,WIT:540,WITA:480,WST:780,WT:0,YAKST:600,YAKT:600,YAPT:600,YEKST:360,YEKT:360}});function cn(r,t){let e=new Date(r);if(t.y&&(t.year=t.y,delete t.y),t.mo&&(t.month=t.mo,delete t.mo),t.M&&(t.month=t.M,delete t.M),t.w&&(t.week=t.w,delete t.w),t.d&&(t.day=t.d,delete t.d),t.h&&(t.hour=t.h,delete t.h),t.m&&(t.minute=t.m,delete t.m),t.s&&(t.second=t.s,delete t.s),t.ms&&(t.millisecond=t.ms,delete t.ms),"year"in t){let n=Math.floor(t.year);e.setFullYear(e.getFullYear()+n);let i=t.year-n;i>0&&(t.month=t?.month??0,t.month+=i*12)}if("quarter"in t){let n=Math.floor(t.quarter);e.setMonth(e.getMonth()+n*3)}if("month"in t){let n=Math.floor(t.month);e.setMonth(e.getMonth()+n);let i=t.month-n;i>0&&(t.week=t?.week??0,t.week+=i*4)}if("week"in t){let n=Math.floor(t.week);e.setDate(e.getDate()+n*7);let i=t.week-n;i>0&&(t.day=t?.day??0,t.day+=Math.round(i*7))}if("day"in t){let n=Math.floor(t.day);e.setDate(e.getDate()+n);let i=t.day-n;i>0&&(t.hour=t?.hour??0,t.hour+=Math.round(i*24))}if("hour"in t){let n=Math.floor(t.hour);e.setHours(e.getHours()+n);let i=t.hour-n;i>0&&(t.minute=t?.minute??0,t.minute+=Math.round(i*60))}if("minute"in t){let n=Math.floor(t.minute);e.setMinutes(e.getMinutes()+n);let i=t.minute-n;i>0&&(t.second=t?.second??0,t.second+=Math.round(i*60))}if("second"in t){let n=Math.floor(t.second);e.setSeconds(e.getSeconds()+n);let i=t.second-n;i>0&&(t.millisecond=t?.millisecond??0,t.millisecond+=Math.round(i*1e3))}if("millisecond"in t){let n=Math.floor(t.millisecond);e.setMilliseconds(e.getMilliseconds()+n)}return e}function ic(r){let t={};for(let e in r)t[e]=-r[e];return t}var uN,Ga=x(()=>{uN={day:0,second:0,millisecond:0}});var oc,mt,ja,ns=x(()=>{Gd();$A();Ga();oc=class r{constructor(t,e){fe(this,"instant");fe(this,"timezoneOffset");this.instant=t??new Date,this.timezoneOffset=e??null}static fromDate(t){return new r(t)}static fromInput(t,e){if(t instanceof Date)return r.fromDate(t);let n=t?.instant??new Date,i=Xw(t?.timezone,n,e);return new r(n,i)}getDateWithAdjustedTimezone(){let t=new Date(this.instant);return this.timezoneOffset!==null&&t.setMinutes(t.getMinutes()-this.getSystemTimezoneAdjustmentMinute(this.instant)),t}getSystemTimezoneAdjustmentMinute(t,e){t||(t=new Date);let n=-t.getTimezoneOffset(),i=e??this.timezoneOffset??n;return n-i}getTimezoneOffset(){return this.timezoneOffset??-this.instant.getTimezoneOffset()}},mt=class r{constructor(t,e){fe(this,"knownValues");fe(this,"impliedValues");fe(this,"reference");fe(this,"_tags",new Set);if(this.reference=t,this.knownValues={},this.impliedValues={},e)for(let i in e)this.knownValues[i]=e[i];let n=t.getDateWithAdjustedTimezone();this.imply("day",n.getDate()),this.imply("month",n.getMonth()+1),this.imply("year",n.getFullYear()),this.imply("hour",12),this.imply("minute",0),this.imply("second",0),this.imply("millisecond",0)}static createRelativeFromReference(t,e=uN){let n=cn(t.getDateWithAdjustedTimezone(),e),i=new r(t);return i.addTag("result/relativeDate"),"hour"in e||"minute"in e||"second"in e||"millisecond"in e?(i.addTag("result/relativeDateAndTime"),Qw(i,n),rs(i,n),i.assign("timezoneOffset",t.getTimezoneOffset())):(_g(i,n),i.imply("timezoneOffset",t.getTimezoneOffset()),"day"in e?(i.assign("day",n.getDate()),i.assign("month",n.getMonth()+1),i.assign("year",n.getFullYear()),i.assign("weekday",n.getDay())):"week"in e?(i.assign("day",n.getDate()),i.assign("month",n.getMonth()+1),i.assign("year",n.getFullYear()),i.imply("weekday",n.getDay())):(i.imply("day",n.getDate()),"month"in e?(i.assign("month",n.getMonth()+1),i.assign("year",n.getFullYear())):(i.imply("month",n.getMonth()+1),"year"in e?i.assign("year",n.getFullYear()):i.imply("year",n.getFullYear())))),i}get(t){return t in this.knownValues?this.knownValues[t]:t in this.impliedValues?this.impliedValues[t]:null}isCertain(t){return t in this.knownValues}getCertainComponents(){return Object.keys(this.knownValues)}imply(t,e){return t in this.knownValues?this:(this.impliedValues[t]=e,this)}assign(t,e){return this.knownValues[t]=e,delete this.impliedValues[t],this}addDurationAsImplied(t){let e=this.dateWithoutTimezoneAdjustment(),n=cn(e,t);return("day"in t||"week"in t||"month"in t||"year"in t)&&(this.delete(["day","weekday","month","year"]),this.imply("day",n.getDate()),this.imply("weekday",n.getDay()),this.imply("month",n.getMonth()+1),this.imply("year",n.getFullYear())),("second"in t||"minute"in t||"hour"in t)&&(this.delete(["second","minute","hour"]),this.imply("second",n.getSeconds()),this.imply("minute",n.getMinutes()),this.imply("hour",n.getHours())),this}delete(t){typeof t=="string"&&(t=[t]);for(let e of t)delete this.knownValues[e],delete this.impliedValues[e]}clone(){let t=new r(this.reference);t.knownValues={},t.impliedValues={};for(let e in this.knownValues)t.knownValues[e]=this.knownValues[e];for(let e in this.impliedValues)t.impliedValues[e]=this.impliedValues[e];return t}isOnlyDate(){return!this.isCertain("hour")&&!this.isCertain("minute")&&!this.isCertain("second")}isOnlyTime(){return!this.isCertain("weekday")&&!this.isCertain("day")&&!this.isCertain("month")&&!this.isCertain("year")}isOnlyWeekdayComponent(){return this.isCertain("weekday")&&!this.isCertain("day")&&!this.isCertain("month")}isDateWithUnknownYear(){return this.isCertain("month")&&!this.isCertain("year")}isValidDate(){let t=new Date(Date.UTC(this.get("year"),this.get("month")-1,this.get("day"),this.get("hour"),this.get("minute"),this.get("second"),this.get("millisecond")));return t.setUTCFullYear(this.get("year")),!(t.getUTCFullYear()!==this.get("year")||t.getUTCMonth()!==this.get("month")-1||t.getUTCDate()!==this.get("day")||this.get("hour")!=null&&t.getUTCHours()!=this.get("hour")||this.get("minute")!=null&&t.getUTCMinutes()!=this.get("minute"))}toString(){return`[ParsingComponents {
|
||
tags: ${JSON.stringify(Array.from(this._tags).sort())},
|
||
knownValues: ${JSON.stringify(this.knownValues)},
|
||
impliedValues: ${JSON.stringify(this.impliedValues)}},
|
||
reference: ${JSON.stringify(this.reference)}]`}date(){let t=this.get("timezoneOffset")??this.reference.timezoneOffset;if(t==null)return this.dateWithoutTimezoneAdjustment();let e=new Date(Date.UTC(this.get("year"),this.get("month")-1,this.get("day"),this.get("hour"),this.get("minute"),this.get("second"),this.get("millisecond")));return e.setUTCFullYear(this.get("year")),new Date(e.getTime()-t*6e4)}addTag(t){return this._tags.add(t),this}addTags(t){for(let e of t)this._tags.add(e);return this}tags(){return new Set(this._tags)}dateWithoutTimezoneAdjustment(){let t=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 t.setFullYear(this.get("year")),t}},ja=class r{constructor(t,e,n,i,o){fe(this,"refDate");fe(this,"index");fe(this,"text");fe(this,"reference");fe(this,"start");fe(this,"end");this.reference=t,this.refDate=t.instant,this.index=e,this.text=n,this.start=i||new mt(t),this.end=o}clone(){let t=new r(this.reference,this.index,this.text);return t.start=this.start?this.start.clone():null,t.end=this.end?this.end.clone():null,t}date(){return this.start.date()}addTag(t){return this.start.addTag(t),this.end&&this.end.addTag(t),this}addTags(t){return this.start.addTags(t),this.end&&this.end.addTags(t),this}tags(){let t=new Set(this.start.tags());if(this.end)for(let e of this.end.tags())t.add(e);return t}toString(){let t=Array.from(this.tags()).sort();return`[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(t)} ...}]`}}});function FA(r,t,e="\\s{0,5},?\\s{0,5}"){let n=t.replace(/\((?!\?)/g,"(?:");return`${r}${n}(?:${e}${n}){0,10}`}function o4(r){let t;return r instanceof Array?t=[...r]:r instanceof Map?t=Array.from(r.keys()):t=Object.keys(r),t}function Ur(r){return`(?:${o4(r).sort((e,n)=>n.length-e.length).join("|").replace(/\./g,"\\.")})`}var Ya=x(()=>{});function Jw(r){return r<100&&(r>50?r=r+1900:r=r+2e3),r}function sc(r,t,e){let n=new Date(r);n.setMonth(e-1),n.setDate(t);let i=cn(n,{year:1}),o=cn(n,{year:-1});return Math.abs(i.getTime()-r.getTime())<Math.abs(n.getTime()-r.getTime())?n=i:Math.abs(o.getTime()-r.getTime())<Math.abs(n.getTime()-r.getTime())&&(n=o),n.getFullYear()}var Up=x(()=>{Ga()});function s4(r){let t=r.toLowerCase();return MA[t]!==void 0?MA[t]:t==="a"||t==="an"||t=="the"?1:t.match(/few/)?3:t.match(/half/)?.5:t.match(/couple/)?2:t.match(/several/)?7:parseFloat(t)}function zp(r){let t=r.toLowerCase();return RA[t]!==void 0?RA[t]:(t=t.replace(/(?:st|nd|rd|th)$/i,""),parseInt(t))}function Bs(r){if(/BE/i.test(r))return r=r.replace(/BE/i,""),parseInt(r)-543;if(/BCE?/i.test(r))return r=r.replace(/BCE?/i,""),-parseInt(r);if(/(AD|CE)/i.test(r))return r=r.replace(/(AD|CE)/i,""),parseInt(r);let t=parseInt(r);return Jw(t)}function _o(r){let t={},e=r,n=pN.exec(e);for(;n;)l4(t,n),e=e.substring(n[0].length).trim(),n=pN.exec(e);return Object.keys(t).length==0?null:t}function l4(r,t){if(t[0].match(/^[a-zA-Z]+$/))return;let e=s4(t[1]),n=kg[t[2].toLowerCase()];r[n]=e}var Zw,OA,ii,MA,RA,mN,kg,fN,qp,ac,hN,pN,a4,gN,Ka,lc,fr=x(()=>{Ya();Up();Zw={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},OA={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},ii={...OA,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},MA={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},RA={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,"thirty first":31,"thirty-first":31},mN={second:"second",seconds:"second",minute:"minute",minutes:"minute",hour:"hour",hours:"hour",day:"day",days:"day",week:"week",weeks:"week",month:"month",months:"month",quarter:"quarter",quarters:"quarter",year:"year",years:"year"},kg={s:"second",sec:"second",second:"second",seconds:"second",m:"minute",min:"minute",mins:"minute",minute:"minute",minutes:"minute",h:"hour",hr:"hour",hrs:"hour",hour:"hour",hours:"hour",d:"day",day:"day",days:"day",w:"week",week:"week",weeks:"week",mo:"month",mon:"month",mos:"month",month:"month",months:"month",qtr:"quarter",quarter:"quarter",quarters:"quarter",y:"year",yr:"year",year:"year",years:"year",...mN},fN=`(?:${Ur(MA)}|[0-9]+|[0-9]+\\.[0-9]+|half(?:\\s{0,2}an?)?|an?\\b(?:\\s{0,2}few)?|few|several|the|a?\\s{0,2}couple\\s{0,2}(?:of)?)`;qp=`(?:${Ur(RA)}|[0-9]{1,2}(?:st|nd|rd|th)?)`;ac="(?:[1-9][0-9]{0,3}\\s{0,2}(?:BE|AD|BC|BCE|CE)|[1-9][0-9]{3}|[0-9]{2}(?!\\w|:\\d|\\s+(?:am|pm|o\\s*clock|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)))";hN=`(${fN})\\s{0,3}(${Ur(kg)})`,pN=new RegExp(hN,"i"),a4=`(${fN})\\s{0,3}(${Ur(mN)})`,gN="\\s{0,5},?(?:\\s*and)?\\s{0,5}",Ka=FA("(?:(?:about|around)\\s{0,3})?",hN,gN),lc=FA("(?:(?:about|around)\\s{0,3})?",a4,gN)});var yt,Nn=x(()=>{yt=class{constructor(){fe(this,"cachedInnerPattern",null);fe(this,"cachedPattern",null)}innerPatternHasChange(t,e){return this.innerPattern(t)!==e}patternLeftBoundary(){return"(\\W|^)"}pattern(t){return this.cachedInnerPattern&&!this.innerPatternHasChange(t,this.cachedInnerPattern)?this.cachedPattern:(this.cachedInnerPattern=this.innerPattern(t),this.cachedPattern=new RegExp(`${this.patternLeftBoundary()}${this.cachedInnerPattern.source}`,this.cachedInnerPattern.flags),this.cachedPattern)}extract(t,e){let n=e[1]??"";e.index=e.index+n.length,e[0]=e[0].substring(n.length);for(let i=2;i<e.length;i++)e[i-1]=e[i];return this.innerExtract(t,e)}}});var c4,d4,u4,Sg,vN=x(()=>{fr();ns();Nn();c4=new RegExp(`(?:(?:within|in|for)\\s*)?(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${Ka})(?=\\W|$)`,"i"),d4=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${Ka})(?=\\W|$)`,"i"),u4=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${lc})(?=\\W|$)`,"i"),Sg=class extends yt{constructor(e){super();fe(this,"strictMode");this.strictMode=e}innerPattern(e){return this.strictMode?u4:e.option.forwardDate?c4:d4}innerExtract(e,n){if(n[0].match(/^for\s*the\s*\w+/))return null;let i=_o(n[1]);return i?mt.createRelativeFromReference(e.reference,i):null}}});var p4,yN,bN,m4,wN,Ag,CN=x(()=>{Up();fr();fr();fr();Ya();Nn();p4=new RegExp(`(?:on\\s{0,3})?(${qp})(?:\\s{0,3}(?:to|\\-|\\\u2013|until|through|till)\\s{0,3}(${qp}))?(?:-|/|\\s{0,3}(?:of)?\\s{0,3})(${Ur(ii)})(?:(?:-|/|,?\\s{0,3})(${ac}(?!\\w)))?(?=\\W|$)`,"i"),yN=1,bN=2,m4=3,wN=4,Ag=class extends yt{innerPattern(){return p4}innerExtract(t,e){let n=t.createParsingResult(e.index,e[0]),i=ii[e[m4].toLowerCase()],o=zp(e[yN]);if(o>31)return e.index=e.index+e[yN].length,null;if(n.start.assign("month",i),n.start.assign("day",o),e[wN]){let s=Bs(e[wN]);n.start.assign("year",s)}else{let s=sc(t.refDate,o,i);n.start.imply("year",s)}if(e[bN]){let s=zp(e[bN]);n.end=n.start.clone(),n.end.assign("day",s)}return n}}});var f4,h4,xN,DA,LA,Ig,EN=x(()=>{Up();fr();fr();fr();Ya();Nn();f4=new RegExp(`(${Ur(ii)})(?:-|/|\\s*,?\\s*)(${qp})(?!\\s*(?:am|pm))\\s*(?:(?:to|\\-)\\s*(${qp})\\s*)?(?:(?:-|/|\\s*,\\s*|\\s+)(${ac}))?(?=\\W|$)(?!\\:\\d)`,"i"),h4=1,xN=2,DA=3,LA=4,Ig=class extends yt{constructor(e){super();fe(this,"shouldSkipYearLikeDate");this.shouldSkipYearLikeDate=e}innerPattern(){return f4}innerExtract(e,n){let i=ii[n[h4].toLowerCase()],o=zp(n[xN]);if(o>31||this.shouldSkipYearLikeDate&&!n[DA]&&!n[LA]&&n[xN].match(/^\d{2}$/))return null;let s=e.createParsingComponents({day:o,month:i}).addTag("parser/ENMonthNameMiddleEndianParser");if(n[LA]){let c=Bs(n[LA]);s.assign("year",c)}else{let c=sc(e.refDate,o,i);s.imply("year",c)}if(!n[DA])return s;let a=zp(n[DA]),l=e.createParsingResult(n.index,n[0]);return l.start=s,l.end=s.clone(),l.end.assign("day",a),l}}});var g4,v4,y4,TN,Pg,_N=x(()=>{fr();Up();Ya();fr();Nn();g4=new RegExp(`((?:in)\\s*)?(${Ur(ii)})\\s*(?:(?:,|-|of)?\\s*(${ac})?)?(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`,"i"),v4=1,y4=2,TN=3,Pg=class extends yt{innerPattern(){return g4}innerExtract(t,e){let n=e[y4].toLowerCase();if(e[0].length<=3&&!OA[n])return null;let i=t.createParsingResult(e.index+(e[v4]||"").length,e.index+e[0].length);i.start.imply("day",1),i.start.addTag("parser/ENMonthNameParser");let o=ii[n];if(i.start.assign("month",o),e[TN]){let s=Bs(e[TN]);i.start.assign("year",s)}else{let s=sc(t.refDate,1,o);i.start.imply("year",s)}return i}}});var b4,w4,C4,kN,x4,$g,SN=x(()=>{fr();Ya();Nn();b4=new RegExp(`([0-9]{4})[-\\.\\/\\s](?:(${Ur(ii)})|([0-9]{1,2}))[-\\.\\/\\s]([0-9]{1,2})(?=\\W|$)`,"i"),w4=1,C4=2,kN=3,x4=4,$g=class extends yt{constructor(e){super();fe(this,"strictMonthDateOrder");this.strictMonthDateOrder=e}innerPattern(){return b4}innerExtract(e,n){let i=parseInt(n[w4]),o=parseInt(n[x4]),s=n[kN]?parseInt(n[kN]):ii[n[C4].toLowerCase()];if(s<1||s>12){if(this.strictMonthDateOrder)return null;o>=1&&o<=12&&([s,o]=[o,s])}return o<1||o>31?null:{day:o,month:s,year:i}}}});var E4,T4,_4,k4,Fg,AN=x(()=>{fr();Ya();fr();Nn();E4="(?:[1-9][0-9]{0,3}\\s{0,2}(?:BE|AD|BC|BCE|CE)|[1-9][0-9]{3})",T4=new RegExp(`(${E4})(?:\\s*[-.\\/,]?\\s*|\\s+of\\s+)(${Ur(ii)})(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`,"i"),_4=1,k4=2,Fg=class extends yt{innerPattern(){return T4}innerExtract(t,e){let n=Bs(e[_4]),i=e[k4].toLowerCase(),o=ii[i],s=t.createParsingResult(e.index,e[0]);return s.start.imply("day",1),s.start.assign("month",o),s.start.assign("year",n),s.start.addTag("parser/ENYearMonthNameParser"),s}}});var S4,A4,I4,Mg,IN=x(()=>{Nn();S4=new RegExp("([0-9]|0[1-9]|1[012])/([0-9]{4})","i"),A4=1,I4=2,Mg=class extends yt{innerPattern(){return S4}innerExtract(t,e){let n=parseInt(e[I4]),i=parseInt(e[A4]);return t.createParsingComponents().imply("day",1).assign("month",i).assign("year",n)}}});function P4(r,t,e,n){return new RegExp(`${r}${t}(\\d{1,4})(?:(?:\\.|:|\uFF1A)(\\d{1,2})(?:(?::|\uFF1A)(\\d{2})(?:\\.(\\d{1,6}))?)?)?(?:\\s*(a\\.m\\.|p\\.m\\.|am?|pm?))?${e}`,n)}function $4(r,t){return new RegExp(`^(${r})(\\d{1,4})(?:(?:\\.|\\:|\\\uFF1A)(\\d{1,2})(?:(?:\\.|\\:|\\\uFF1A)(\\d{1,2})(?:\\.(\\d{1,6}))?)?)?(?:\\s*(a\\.m\\.|p\\.m\\.|am?|pm?))?${t}`,"i")}var NA,jd,eC,tC,Hp,rC,PN=x(()=>{Ha();NA=2,jd=3,eC=4,tC=5,Hp=6,rC=class{constructor(t=!1){fe(this,"strictMode");fe(this,"cachedPrimaryPrefix",null);fe(this,"cachedPrimarySuffix",null);fe(this,"cachedPrimaryTimePattern",null);fe(this,"cachedFollowingPhase",null);fe(this,"cachedFollowingSuffix",null);fe(this,"cachedFollowingTimePatten",null);this.strictMode=t}patternFlags(){return"i"}primaryPatternLeftBoundary(){return"(^|\\s|T|\\b)"}primarySuffix(){return"(?!/)(?=\\W|$)"}followingSuffix(){return"(?!/)(?=\\W|$)"}pattern(t){return this.getPrimaryTimePatternThroughCache()}extract(t,e){let n=this.extractPrimaryTimeComponents(t,e);if(!n)return e[0].match(/^\d{4}/)?(e.index+=4,null):(e.index+=e[0].length,null);let i=e.index+e[1].length,o=e[0].substring(e[1].length),s=t.createParsingResult(i,o,n);e.index+=e[0].length;let a=t.text.substring(e.index),c=this.getFollowingTimePatternThroughCache().exec(a);return o.match(/^\d{3,4}/)&&c&&(c[0].match(/^\s*([+-])\s*\d{2,4}$/)||c[0].match(/^\s*([+-])\s*\d{2}\W\d{2}/))?null:!c||c[0].match(/^\s*([+-])\s*\d{3,4}$/)?this.checkAndReturnWithoutFollowingPattern(s):(s.end=this.extractFollowingTimeComponents(t,c,s),s.end&&(s.text+=c[0]),this.checkAndReturnWithFollowingPattern(s))}extractPrimaryTimeComponents(t,e,n=!1){let i=t.createParsingComponents(),o=0,s=null,a=parseInt(e[NA]);if(a>100){if(e[NA].length==4&&e[jd]==null&&!e[Hp]||this.strictMode||e[jd]!=null)return null;o=a%100,a=Math.floor(a/100)}if(a>24)return null;if(e[jd]!=null){if(e[jd].length==1&&!e[Hp])return null;o=parseInt(e[jd])}if(o>=60)return null;if(a>12&&(s=dt.PM),e[Hp]!=null){if(a>12)return null;let l=e[Hp][0].toLowerCase();l=="a"&&(s=dt.AM,a==12&&(a=0)),l=="p"&&(s=dt.PM,a!=12&&(a+=12))}if(i.assign("hour",a),i.assign("minute",o),s!==null?i.assign("meridiem",s):a<12?i.imply("meridiem",dt.AM):i.imply("meridiem",dt.PM),e[tC]!=null){let l=parseInt(e[tC].substring(0,3));if(l>=1e3)return null;i.assign("millisecond",l)}if(e[eC]!=null){let l=parseInt(e[eC]);if(l>=60)return null;i.assign("second",l)}return i}extractFollowingTimeComponents(t,e,n){let i=t.createParsingComponents();if(e[tC]!=null){let l=parseInt(e[tC].substring(0,3));if(l>=1e3)return null;i.assign("millisecond",l)}if(e[eC]!=null){let l=parseInt(e[eC]);if(l>=60)return null;i.assign("second",l)}let o=parseInt(e[NA]),s=0,a=-1;if(e[jd]!=null?s=parseInt(e[jd]):o>100&&(s=o%100,o=Math.floor(o/100)),s>=60||o>24)return null;if(o>=12&&(a=dt.PM),e[Hp]!=null){if(o>12)return null;let l=e[Hp][0].toLowerCase();l=="a"&&(a=dt.AM,o==12&&(o=0,i.isCertain("day")||i.imply("day",i.get("day")+1))),l=="p"&&(a=dt.PM,o!=12&&(o+=12)),n.start.isCertain("meridiem")||(a==dt.AM?(n.start.imply("meridiem",dt.AM),n.start.get("hour")==12&&n.start.assign("hour",0)):(n.start.imply("meridiem",dt.PM),n.start.get("hour")!=12&&n.start.assign("hour",n.start.get("hour")+12)))}return i.assign("hour",o),i.assign("minute",s),a>=0?i.assign("meridiem",a):n.start.isCertain("meridiem")&&n.start.get("hour")>12?n.start.get("hour")-12>o?i.imply("meridiem",dt.AM):o<=12&&(i.assign("hour",o+12),i.assign("meridiem",dt.PM)):o>12?i.imply("meridiem",dt.PM):o<=12&&i.imply("meridiem",dt.AM),i.date().getTime()<n.start.date().getTime()&&i.imply("day",i.get("day")+1),i}checkAndReturnWithoutFollowingPattern(t){if(t.text.match(/^\d$/)||t.text.match(/^\d\d\d+$/)||t.text.match(/\d[apAP]$/))return null;let e=t.text.match(/[^\d:.](\d[\d.]+)$/);if(e){let n=e[1];if(this.strictMode||n.includes(".")&&!n.match(/\d(\.\d{2})+$/)||parseInt(n)>24)return null}return t}checkAndReturnWithFollowingPattern(t){if(t.text.match(/^\d+-\d+$/))return null;let e=t.text.match(/[^\d:.](\d[\d.]+)\s*-\s*(\d[\d.]+)$/);if(e){if(this.strictMode)return null;let n=e[1],i=e[2];if(i.includes(".")&&!i.match(/\d(\.\d{2})+$/))return null;let o=parseInt(i),s=parseInt(n);if(o>24||s>24)return null}return t}getPrimaryTimePatternThroughCache(){let t=this.primaryPrefix(),e=this.primarySuffix();return this.cachedPrimaryPrefix===t&&this.cachedPrimarySuffix===e?this.cachedPrimaryTimePattern:(this.cachedPrimaryTimePattern=P4(this.primaryPatternLeftBoundary(),t,e,this.patternFlags()),this.cachedPrimaryPrefix=t,this.cachedPrimarySuffix=e,this.cachedPrimaryTimePattern)}getFollowingTimePatternThroughCache(){let t=this.followingPhase(),e=this.followingSuffix();return this.cachedFollowingPhase===t&&this.cachedFollowingSuffix===e?this.cachedFollowingTimePatten:(this.cachedFollowingTimePatten=$4(t,e),this.cachedFollowingPhase=t,this.cachedFollowingSuffix=e,this.cachedFollowingTimePatten)}}});var Rg,$N=x(()=>{Ha();PN();Rg=class extends rC{constructor(t){super(t)}followingPhase(){return"\\s*(?:\\-|\\\u2013|\\~|\\\u301C|to|until|through|till|\\?)\\s*"}primaryPrefix(){return"(?:(?:at|from)\\s*)??"}primarySuffix(){return"(?:\\s*(?:o\\W*clock|at\\s*night|in\\s*the\\s*(?:morning|afternoon)))?(?!/)(?=\\W|$)"}extractPrimaryTimeComponents(t,e){let n=super.extractPrimaryTimeComponents(t,e);if(!n)return n;if(e[0].endsWith("night")){let i=n.get("hour");i>=6&&i<12?(n.assign("hour",n.get("hour")+12),n.assign("meridiem",dt.PM)):i<6&&n.assign("meridiem",dt.AM)}if(e[0].endsWith("afternoon")){n.assign("meridiem",dt.PM);let i=n.get("hour");i>=0&&i<=6&&n.assign("hour",n.get("hour")+12)}return e[0].endsWith("morning")&&(n.assign("meridiem",dt.AM),n.get("hour")<12&&n.assign("hour",n.get("hour"))),n.addTag("parser/ENTimeExpressionParser")}extractFollowingTimeComponents(t,e,n){let i=super.extractFollowingTimeComponents(t,e,n);return i&&i.addTag("parser/ENTimeExpressionParser"),i}}});var F4,M4,Og,FN=x(()=>{fr();ns();Nn();Ga();F4=new RegExp(`(${Ka})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),M4=new RegExp(`(${lc})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),Og=class extends yt{constructor(e){super();fe(this,"strictMode");this.strictMode=e}innerPattern(){return this.strictMode?M4:F4}innerExtract(e,n){let i=_o(n[1]);return i?mt.createRelativeFromReference(e.reference,ic(i)):null}}});var R4,O4,D4,Dg,MN=x(()=>{fr();ns();Nn();R4=new RegExp(`(${Ka})\\s{0,5}(?:later|after|from now|henceforth|forward|out)(?=(?:\\W|$))`,"i"),O4=new RegExp(`(${lc})\\s{0,5}(later|after|from now)(?=\\W|$)`,"i"),D4=1,Dg=class extends yt{constructor(e){super();fe(this,"strictMode");this.strictMode=e}innerPattern(){return this.strictMode?O4:R4}innerExtract(e,n){let i=_o(n[D4]);return i?mt.createRelativeFromReference(e.reference,i):null}}});var Wp,ko,cc=x(()=>{Wp=class{refine(t,e){return e.filter(n=>this.isValid(t,n))}},ko=class{refine(t,e){if(e.length<2)return e;let n=[],i=e[0],o=null;for(let s=1;s<e.length;s++){o=e[s];let a=t.text.substring(i.index+i.text.length,o.index);if(!this.shouldMergeResults(a,i,o,t))n.push(i),i=o;else{let l=i,c=o,d=this.mergeResults(a,l,c,t);t.debug(()=>{console.log(`${this.constructor.name} merged ${l} and ${c} into ${d}`)}),i=d}}return i!=null&&n.push(i),n}}});var Lg,RN=x(()=>{cc();Ga();Lg=class extends ko{shouldMergeResults(t,e,n){return!e.end&&!n.end&&t.match(this.patternBetween())!=null}mergeResults(t,e,n){if(!e.start.isOnlyWeekdayComponent()&&!n.start.isOnlyWeekdayComponent()&&(n.start.getCertainComponents().forEach(o=>{e.start.isCertain(o)||e.start.imply(o,n.start.get(o))}),e.start.getCertainComponents().forEach(o=>{n.start.isCertain(o)||n.start.imply(o,e.start.get(o))})),e.start.date()>n.start.date()){let o=e.start.date(),s=n.start.date();n.start.isOnlyWeekdayComponent()&&cn(s,{day:7})>o?(s=cn(s,{day:7}),n.start.imply("day",s.getDate()),n.start.imply("month",s.getMonth()+1),n.start.imply("year",s.getFullYear())):e.start.isOnlyWeekdayComponent()&&cn(o,{day:-7})<s?(o=cn(o,{day:-7}),e.start.imply("day",o.getDate()),e.start.imply("month",o.getMonth()+1),e.start.imply("year",o.getFullYear())):n.start.isDateWithUnknownYear()&&cn(s,{year:1})>o?(s=cn(s,{year:1}),n.start.imply("year",s.getFullYear())):e.start.isDateWithUnknownYear()&&cn(o,{year:-1})<s?(o=cn(o,{year:-1}),e.start.imply("year",o.getFullYear())):[n,e]=[e,n]}let i=e.clone();return i.start=e.start,i.end=n.start,i.index=Math.min(e.index,n.index),e.index<n.index?i.text=e.text+t+n.text:i.text=n.text+t+e.text,i}}});var Ng,ON=x(()=>{RN();Ng=class extends Lg{patternBetween(){return/^\s*(to|-|–|until|through|till)\s*$/i}}});function VA(r,t){let e=r.clone(),n=r.start,i=t.start;if(e.start=DN(n,i),r.end!=null||t.end!=null){let o=r.end==null?r.start:r.end,s=t.end==null?t.start:t.end,a=DN(o,s);if(r.end==null&&a.date().getTime()<e.start.date().getTime()){let l=new Date(a.date().getTime());l.setDate(l.getDate()+1),a.isCertain("day")?rs(a,l):Wa(a,l)}e.end=a}return e}function DN(r,t){let e=r.clone();t.isCertain("hour")?(e.assign("hour",t.get("hour")),e.assign("minute",t.get("minute")),t.isCertain("second")?(e.assign("second",t.get("second")),t.isCertain("millisecond")?e.assign("millisecond",t.get("millisecond")):e.imply("millisecond",t.get("millisecond"))):(e.imply("second",t.get("second")),e.imply("millisecond",t.get("millisecond")))):(e.imply("hour",t.get("hour")),e.imply("minute",t.get("minute")),e.imply("second",t.get("second")),e.imply("millisecond",t.get("millisecond"))),t.isCertain("timezoneOffset")&&e.assign("timezoneOffset",t.get("timezoneOffset"));let n=r.get("meridiem")!=null&&(r.isCertain("meridiem")||Array.from(r.tags()).some(i=>i.startsWith("casualReference/")));return t.isCertain("meridiem")?e.assign("meridiem",t.get("meridiem")):t.get("meridiem")!=null&&!n&&e.imply("meridiem",t.get("meridiem")),e.get("meridiem")==dt.PM&&e.get("hour")<12&&(t.isCertain("hour")?e.assign("hour",e.get("hour")+12):e.imply("hour",e.get("hour")+12)),e.addTags(r.tags()),e.addTags(t.tags()),e}var LN=x(()=>{Ha();Gd()});var Vg,NN=x(()=>{cc();LN();Vg=class extends ko{shouldMergeResults(t,e,n){return(e.start.isOnlyDate()&&n.start.isOnlyTime()||n.start.isOnlyDate()&&e.start.isOnlyTime())&&t.match(this.patternBetween())!=null}mergeResults(t,e,n){let i=e.start.isOnlyDate()?VA(e,n):VA(n,e);return i.index=e.index,i.text=e.text+t+n.text,i}}});var Gp,VN=x(()=>{NN();Gp=class extends Vg{patternBetween(){return new RegExp("^\\s*(T|at|after|before|on|of|,|-|\\.|\u2219|:)?\\s*$")}}});var L4,Bg,BN=x(()=>{$A();L4=new RegExp("^\\s*,?\\s*\\(?([A-Z]{2,4})\\)?(?=\\W|$)","i"),Bg=class{constructor(t){fe(this,"timezoneOverrides");this.timezoneOverrides=t}refine(t,e){let n=t.option.timezones??{};return e.forEach(i=>{let o=t.text.substring(i.index+i.text.length),s=L4.exec(o);if(!s)return;let a=s[1].toUpperCase(),l=i.start.date()??i.refDate??new Date,c={...this.timezoneOverrides,...n},d=Xw(a,l,c);if(d==null)return;t.debug(()=>{console.log(`Extracting timezone: '${a}' into: ${d} for: ${i.start}`)});let u=i.start.get("timezoneOffset");u!==null&&d!=u&&(i.start.isCertain("timezoneOffset")||a!=s[1])||i.start.isOnlyDate()&&a!=s[1]||(i.text+=s[0],i.start.isCertain("timezoneOffset")||i.start.assign("timezoneOffset",d),i.end!=null&&!i.end.isCertain("timezoneOffset")&&i.end.assign("timezoneOffset",d))}),e}}});var N4,V4,B4,U4,Ug,UN=x(()=>{N4=new RegExp("^\\s*(?:\\(?(?:GMT|UTC)\\s?)?([+-])(\\d{1,2})(?::?(\\d{2}))?\\)?","i"),V4=1,B4=2,U4=3,Ug=class{refine(t,e){return e.forEach(function(n){if(n.start.isCertain("timezoneOffset"))return;let i=t.text.substring(n.index+n.text.length),o=N4.exec(i);if(!o)return;t.debug(()=>{console.log(`Extracting timezone: '${o[0]}' into : ${n}`)});let s=parseInt(o[B4]),a=parseInt(o[U4]||"0"),l=s*60+a;l>840||(o[V4]==="-"&&(l=-l),n.end!=null&&n.end.assign("timezoneOffset",l),n.start.assign("timezoneOffset",l),n.text+=o[0])}),e}}});var dc,BA=x(()=>{dc=class{refine(t,e){if(e.length<2)return e;let n=[],i=e[0];for(let o=1;o<e.length;o++){let s=e[o];if(s.index>=i.index+i.text.length){n.push(i),i=s;continue}let a=null,l=null;s.text.length>i.text.length?(a=s,l=i):(a=i,l=s),t.debug(()=>{console.log(`${this.constructor.name} remove ${l} by ${a}`)}),i=a}return i!=null&&n.push(i),n}}});function qN(r,t,e){let n=r.getDateWithAdjustedTimezone(),i=q4(n,t,e),o=new mt(r);return o=o.addDurationAsImplied({day:i}),o.assign("weekday",t),o}function q4(r,t,e){let n=r.getDay();switch(e){case"this":return Yd(r,t);case"last":return zN(r,t);case"next":return n==Lt.SUNDAY?t==Lt.SUNDAY?7:t:n==Lt.SATURDAY?t==Lt.SATURDAY?7:t==Lt.SUNDAY?8:1+t:t<n&&t!=Lt.SUNDAY?Yd(r,t):Yd(r,t)+7}return z4(r,t)}function z4(r,t){let e=zN(r,t),n=Yd(r,t);return n<-e?n:e}function Yd(r,t){let e=r.getDay(),n=t-e;return n<0&&(n+=7),n}function zN(r,t){let e=r.getDay(),n=t-e;return n>=0&&(n-=7),n}var UA=x(()=>{Ha();ns()});var qg,HN=x(()=>{Gd();Gd();Ga();UA();qg=class{refine(t,e){return t.option.forwardDate&&e.forEach(n=>{let i=t.reference.getDateWithAdjustedTimezone();if(n.start.isOnlyTime()&&t.reference.instant>n.start.date()){let o=t.reference.getDateWithAdjustedTimezone(),s=new Date(o);s.setDate(s.getDate()+1),Wa(n.start,s),t.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} time from the ref date (${o}) to the following day (${s})`)}),n.end&&n.end.isOnlyTime()&&(Wa(n.end,s),n.start.date()>n.end.date()&&(s.setDate(s.getDate()+1),Wa(n.end,s)))}if(n.start.isOnlyWeekdayComponent()&&i>n.start.date()){let o=Yd(i,n.start.get("weekday"))||7,s=cn(i,{day:o});if(Wa(n.start,s),t.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} weekday (${n.start})`)}),n.end&&n.start.date()>n.end.date()){let a=Yd(i,n.start.get("weekday"))||7,l=cn(i,{day:a});Wa(n.end,l),t.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} weekday (${n.end})`)})}}if(n.start.isDateWithUnknownYear()&&i>n.start.date())for(let o=0;o<3&&i>n.start.date();o++)n.start.imply("year",n.start.get("year")+1),t.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} year (${n.start})`)}),n.end&&!n.end.isCertain("year")&&(n.end.imply("year",n.end.get("year")+1),t.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} month (${n.start})`)}))}),e}}});var zg,WN=x(()=>{cc();zg=class extends Wp{constructor(e){super();fe(this,"strictMode");this.strictMode=e}isValid(e,n){return n.text.replace(" ","").match(/^\d*(\.\d*)?$/)?(e.debug(()=>{console.log(`Removing unlikely result '${n.text}'`)}),!1):n.start.isValidDate()?n.end&&!n.end.isValidDate()?(e.debug(()=>{console.log(`Removing invalid result: ${n} (${n.end})`)}),!1):this.strictMode?this.isStrictModeValid(e,n):!0:(e.debug(()=>{console.log(`Removing invalid result: ${n} (${n.start})`)}),!1)}isStrictModeValid(e,n){return n.start.isOnlyWeekdayComponent()?(e.debug(()=>{console.log(`(Strict) Removing weekday only component: ${n} (${n.end})`)}),!1):!0}}});var H4,W4,G4,j4,GN,Y4,jN,YN,K4,KN,QN,Hg,XN=x(()=>{Nn();H4=new RegExp("([0-9]{4})\\-([0-9]{1,2})\\-([0-9]{1,2})(?:T([0-9]{1,2}):([0-9]{1,2})(?::([0-9]{1,2})(?:\\.(\\d{1,4}))?)?(Z|([+-]\\d{2}):?(\\d{2})?)?)?(?=\\W|$)","i"),W4=1,G4=2,j4=3,GN=4,Y4=5,jN=6,YN=7,K4=8,KN=9,QN=10,Hg=class extends yt{innerPattern(){return H4}innerExtract(t,e){let n=t.createParsingComponents({year:parseInt(e[W4]),month:parseInt(e[G4]),day:parseInt(e[j4])});if(e[GN]!=null&&(n.assign("hour",parseInt(e[GN])),n.assign("minute",parseInt(e[Y4])),e[jN]!=null&&n.assign("second",parseInt(e[jN])),e[YN]!=null&&n.assign("millisecond",parseInt(e[YN])),e[K4]!=null)){let i=0;if(e[KN]){let o=parseInt(e[KN]),s=0;e[QN]!=null&&(s=parseInt(e[QN])),i=o*60,i<0?i-=s:i+=s}n.assign("timezoneOffset",i)}return n.addTag("parser/ISOFormatParser")}}});var Wg,JN=x(()=>{cc();Wg=class extends ko{mergeResults(t,e,n){let i=n.clone();return i.index=e.index,i.text=e.text+t+i.text,i.start.assign("weekday",e.start.get("weekday")),i.end&&i.end.assign("weekday",e.start.get("weekday")),i}shouldMergeResults(t,e,n){return e.start.isOnlyWeekdayComponent()&&!e.start.isCertain("hour")&&n.start.isCertain("day")&&t.match(/^,?\s*$/)!=null}}});function ZN(r,t=!1){return r.parsers.unshift(new Hg),r.refiners.unshift(new Wg),r.refiners.unshift(new Ug),r.refiners.unshift(new dc),r.refiners.push(new Bg),r.refiners.push(new dc),r.refiners.push(new qg),r.refiners.push(new zg(t)),r}var e1=x(()=>{BN();UN();BA();HN();WN();XN();JN()});function t1(r){let t=r.getDateWithAdjustedTimezone(),e=new mt(r,{});return rs(e,t),Qw(e,t),e.assign("timezoneOffset",r.getTimezoneOffset()),e.addTag("casualReference/now"),e}function r1(r){let t=r.getDateWithAdjustedTimezone(),e=new mt(r,{});return rs(e,t),_g(e,t),e.delete("meridiem"),e.addTag("casualReference/today"),e}function n1(r){return Q4(r,1).addTag("casualReference/yesterday")}function i1(r){return nC(r,1).addTag("casualReference/tomorrow")}function Q4(r,t){return nC(r,-t)}function nC(r,t){let e=r.getDateWithAdjustedTimezone(),n=new mt(r,{}),i=new Date(e.getTime());return i.setDate(i.getDate()+t),rs(n,i),_g(n,i),n.delete("meridiem"),n}function o1(r,t=22){let e=r.getDateWithAdjustedTimezone(),n=new mt(r,{});return rs(n,e),n.imply("hour",t),n.imply("meridiem",dt.PM),n.addTag("casualReference/tonight"),n}function s1(r,t=20){let e=new mt(r,{});return e.imply("meridiem",dt.PM),e.imply("hour",t),e.addTag("casualReference/evening"),e}function a1(r){let t=new mt(r,{});return r.getDateWithAdjustedTimezone().getHours()>2&&t.addDurationAsImplied({day:1}),t.assign("hour",0),t.imply("minute",0),t.imply("second",0),t.imply("millisecond",0),t.addTag("casualReference/midnight"),t}function l1(r,t=6){let e=new mt(r,{});return e.imply("meridiem",dt.AM),e.imply("hour",t),e.imply("minute",0),e.imply("second",0),e.imply("millisecond",0),e.addTag("casualReference/morning"),e}function c1(r,t=15){let e=new mt(r,{});return e.imply("meridiem",dt.PM),e.imply("hour",t),e.imply("minute",0),e.imply("second",0),e.imply("millisecond",0),e.addTag("casualReference/afternoon"),e}function d1(r){let t=new mt(r,{});return t.imply("meridiem",dt.AM),t.assign("hour",12),t.imply("minute",0),t.imply("second",0),t.imply("millisecond",0),t.addTag("casualReference/noon"),t}var qA=x(()=>{ns();Gd();Ha()});var X4,Gg,p1=x(()=>{Nn();Gd();qA();X4=/(now|today|tonight|tomorrow|overmorrow|tmr|tmrw|yesterday|last\s*night)(?=\W|$)/i,Gg=class extends yt{innerPattern(t){return X4}innerExtract(t,e){let n=t.refDate,i=e[0].toLowerCase(),o=t.createParsingComponents();switch(i){case"now":o=t1(t.reference);break;case"today":o=r1(t.reference);break;case"yesterday":o=n1(t.reference);break;case"tomorrow":case"tmr":case"tmrw":o=i1(t.reference);break;case"tonight":o=o1(t.reference);break;case"overmorrow":o=nC(t.reference,2);break;default:if(i.match(/last\s*night/)){if(n.getHours()>6){let s=new Date(n.getTime());s.setDate(s.getDate()-1),n=s}rs(o,n),o.imply("hour",0)}break}return o.addTag("parser/ENCasualDateParser"),o}}});var J4,jg,m1=x(()=>{Nn();qA();J4=/(?:this)?\s{0,3}(morning|afternoon|evening|night|midnight|midday|noon)(?=\W|$)/i,jg=class extends yt{innerPattern(){return J4}innerExtract(t,e){let n=null;switch(e[1].toLowerCase()){case"afternoon":n=c1(t.reference);break;case"evening":case"night":n=s1(t.reference);break;case"midnight":n=a1(t.reference);break;case"morning":n=l1(t.reference);break;case"noon":case"midday":n=d1(t.reference);break}return n&&n.addTag("parser/ENCasualTimeParser"),n}}});var Z4,e6,t6,r6,Yg,f1=x(()=>{fr();Ya();Nn();UA();Ha();Z4=new RegExp(`(?:(?:\\,|\\(|\\\uFF08)\\s*)?(?:on\\s*?)?(?:(this|last|past|next)\\s*)?(${Ur(Zw)}|weekend|weekday)(?:\\s*(?:\\,|\\)|\\\uFF09))?(?:\\s*(?:of\\s*)?(this|last|past|next)\\s*week)?(?=\\W|$)`,"i"),e6=1,t6=2,r6=3,Yg=class extends yt{innerPattern(){return Z4}innerExtract(t,e){let n=e[e6],i=e[r6],o=n||i;o=o||"",o=o.toLowerCase();let s=null;o=="last"||o=="past"?s="last":o=="next"?s="next":o=="this"&&(s="this");let a=e[t6].toLowerCase(),l;if(Zw[a]!==void 0)l=Zw[a];else if(a=="weekend")l=s=="last"?Lt.SUNDAY:Lt.SATURDAY;else if(a=="weekday"){let c=t.reference.getDateWithAdjustedTimezone().getDay();c==Lt.SUNDAY||c==Lt.SATURDAY?l=s=="last"?Lt.FRIDAY:Lt.MONDAY:(l=c-1,l=s=="last"?l-1:l+1,l=l%5+1)}else return null;return qN(t.reference,l,s)}}});var n6,i6,o6,Kg,h1=x(()=>{fr();ns();Nn();Ya();n6=new RegExp(`(this|last|past|next|after\\s*this)\\s*(${Ur(kg)})(?=\\s*)(?=\\W|$)`,"i"),i6=1,o6=2,Kg=class extends yt{innerPattern(){return n6}innerExtract(t,e){let n=e[i6].toLowerCase(),i=e[o6].toLowerCase(),o=kg[i];if(n=="next"||n.startsWith("after")){let l={};return l[o]=1,mt.createRelativeFromReference(t.reference,l)}if(n=="last"||n=="past"){let l={};return l[o]=-1,mt.createRelativeFromReference(t.reference,l)}let s=t.createParsingComponents(),a=new Date(t.reference.instant.getTime());return i.match(/week/i)?(a.setDate(a.getDate()-a.getDay()),s.imply("day",a.getDate()),s.imply("month",a.getMonth()+1),s.imply("year",a.getFullYear())):i.match(/month/i)?(a.setDate(1),s.imply("day",a.getDate()),s.assign("year",a.getFullYear()),s.assign("month",a.getMonth()+1)):i.match(/year/i)&&(a.setDate(1),a.setMonth(0),s.imply("day",a.getDate()),s.imply("month",a.getMonth()+1),s.assign("year",a.getFullYear())),s}}});var s6,a6,l6,g1,v1,zA,Qg,y1=x(()=>{Up();s6=new RegExp("([^\\d]|^)([0-3]{0,1}[0-9]{1})[\\/\\.\\-]([0-3]{0,1}[0-9]{1})(?:[\\/\\.\\-]([0-9]{4}|[0-9]{2}))?(\\W|$)","i"),a6=1,l6=5,g1=2,v1=3,zA=4,Qg=class{constructor(t){fe(this,"groupNumberMonth");fe(this,"groupNumberDay");this.groupNumberMonth=t?v1:g1,this.groupNumberDay=t?g1:v1}pattern(){return s6}extract(t,e){let n=e.index+e[a6].length,i=e.index+e[0].length-e[l6].length;if(n>0&&t.text.substring(0,n).match("\\d/?$")||i<t.text.length&&t.text.substring(i).match("^/?\\d"))return;let o=t.text.substring(n,i);if(o.match(/^\d\.\d$/)||o.match(/^\d\.\d{1,2}\.\d{1,2}\s*$/)||!e[zA]&&o.indexOf("/")<0)return;let s=t.createParsingResult(n,o),a=parseInt(e[this.groupNumberMonth]),l=parseInt(e[this.groupNumberDay]);if((a<1||a>12)&&a>12)if(l>=1&&l<=12&&a<=31)[l,a]=[a,l];else return null;if(l<1||l>31)return null;if(s.start.assign("day",l),s.start.assign("month",a),e[zA]){let c=parseInt(e[zA]),d=Jw(c);s.start.assign("year",d)}else{let c=sc(t.refDate,l,a);s.start.imply("year",c)}return s.addTag("parser/SlashDateFormatParser")}}});var c6,d6,Xg,b1=x(()=>{fr();ns();Nn();Ga();c6=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${Ka})(?=\\W|$)`,"i"),d6=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${lc})(?=\\W|$)`,"i"),Xg=class extends yt{constructor(e=!0){super();fe(this,"allowAbbreviations");this.allowAbbreviations=e}innerPattern(){return this.allowAbbreviations?c6:d6}innerExtract(e,n){let i=n[1].toLowerCase(),o=_o(n[2]);if(!o)return null;switch(i){case"last":case"past":case"-":o=ic(o);break}return mt.createRelativeFromReference(e.reference,o)}}});function u6(r){return r.text.match(/^[+-]/i)!=null}function w1(r){return r.text.match(/^-/i)!=null}var Jg,C1=x(()=>{cc();ns();fr();Ga();Jg=class extends ko{shouldMergeResults(t,e,n){return t.match(/^\s*$/i)?u6(n)||w1(n):!1}mergeResults(t,e,n,i){let o=_o(n.text);w1(n)&&(o=ic(o));let s=mt.createRelativeFromReference(oc.fromDate(e.start.date()),o);return new ja(e.reference,e.index,`${e.text}${t}${n.text}`,s)}}});function x1(r){return r.text.match(/\s+(before|from)$/i)!=null}function p6(r){return r.text.match(/\s+(after|since)$/i)!=null}var Zg,E1=x(()=>{cc();ns();fr();Ga();Zg=class extends ko{patternBetween(){return/^\s*$/i}shouldMergeResults(t,e,n){return!t.match(this.patternBetween())||!x1(e)&&!p6(e)?!1:!!n.start.get("day")&&!!n.start.get("month")&&!!n.start.get("year")}mergeResults(t,e,n){let i=_o(e.text);x1(e)&&(i=ic(i));let o=mt.createRelativeFromReference(oc.fromDate(n.start.date()),i);return new ja(n.reference,e.index,`${e.text}${t}${n.text}`,o)}}});var m6,f6,ev,T1=x(()=>{fr();m6=new RegExp(`^\\s*(${ac})`,"i"),f6=1,ev=class{refine(t,e){return e.forEach(function(n){if(!n.start.isDateWithUnknownYear())return;let i=t.text.substring(n.index+n.text.length),o=m6.exec(i);if(!o||o[0].trim().length<=3)return;t.debug(()=>{console.log(`Extracting year: '${o[0]}' into : ${n}`)});let s=Bs(o[f6]);n.end!=null&&n.end.assign("year",s),n.start.assign("year",s),n.text+=o[0]}),e}}});var tv,_1=x(()=>{cc();tv=class extends Wp{constructor(){super()}isValid(t,e){let n=e.text.trim();return n===t.text.trim()?!0:n.toLowerCase()==="may"&&!t.text.substring(0,e.index).trim().match(/\b(in)$/i)?(t.debug(()=>{console.log(`Removing unlikely result: ${e}`)}),!1):n.toLowerCase().endsWith("the second")?(t.text.substring(e.index+e.text.length).trim().length>0&&t.debug(()=>{console.log(`Removing unlikely result: ${e}`)}),!1):!0}}});var Kd,HA=x(()=>{vN();CN();EN();_N();SN();AN();IN();$N();FN();MN();ON();VN();e1();p1();m1();f1();h1();y1();b1();C1();E1();BA();T1();_1();Kd=class{createCasualConfiguration(t=!1){let e=this.createConfiguration(!1,t);return e.parsers.push(new Gg),e.parsers.push(new jg),e.parsers.push(new Pg),e.parsers.push(new Kg),e.parsers.push(new Xg),e.refiners.push(new tv),e}createConfiguration(t=!0,e=!1){let n=ZN({parsers:[new Qg(e),new Sg(t),new Ag,new Ig(e),new Yg,new Mg,new Rg(t),new Og(t),new Dg(t),new Fg],refiners:[new Gp]},t);return n.parsers.unshift(new $g(t)),n.refiners.unshift(new Zg),n.refiners.unshift(new Jg),n.refiners.unshift(new dc),n.refiners.push(new Gp),n.refiners.push(new ev),n.refiners.push(new Ng),n}}});var jp,WA,k1=x(()=>{ns();HA();jp=class r{constructor(t){fe(this,"parsers");fe(this,"refiners");fe(this,"defaultConfig",new Kd);t=t||this.defaultConfig.createCasualConfiguration(),this.parsers=[...t.parsers],this.refiners=[...t.refiners]}clone(){return new r({parsers:[...this.parsers],refiners:[...this.refiners]})}parseDate(t,e,n){let i=this.parse(t,e,n);return i.length>0?i[0].start.date():null}parse(t,e,n){let i=new WA(t,e,n),o=[];return this.parsers.forEach(s=>{let a=r.executeParser(i,s);o=o.concat(a)}),o.sort((s,a)=>s.index-a.index),this.refiners.forEach(function(s){o=s.refine(i,o)}),o}static executeParser(t,e){let n=[],i=e.pattern(t),o=t.text,s=t.text,a=i.exec(s);for(;a;){let l=a.index+o.length-s.length;a.index=l;let c=e.extract(t,a);if(!c){s=o.substring(a.index+1),a=i.exec(s);continue}let d=null;c instanceof ja?d=c:c instanceof mt?(d=t.createParsingResult(a.index,a[0]),d.start=c):d=t.createParsingResult(a.index,a[0],c);let u=d.index,p=d.text;t.debug(()=>console.log(`${e.constructor.name} extracted (at index=${u}) '${p}'`)),n.push(d),s=o.substring(u+p.length),a=i.exec(s)}return n}},WA=class{constructor(t,e,n){fe(this,"text");fe(this,"option");fe(this,"reference");fe(this,"refDate");this.text=t,this.option=n??{},this.reference=oc.fromInput(e,this.option.timezones),this.refDate=this.reference.instant}createParsingComponents(t){return t instanceof mt?t:new mt(this.reference,t)}createParsingResult(t,e,n,i){let o=typeof e=="string"?e:this.text.substring(t,e),s=n?this.createParsingComponents(n):null,a=i?this.createParsingComponents(i):null;return new ja(this.reference,t,o,s,a)}debug(t){this.option.debug&&(this.option.debug instanceof Function?this.option.debug(t):this.option.debug.debug(t))}}});var GA,S1,h6,TIe,A1=x(()=>{k1();HA();GA=new Kd,S1=new jp(GA.createCasualConfiguration(!1)),h6=new jp(GA.createConfiguration(!0,!1)),TIe=new jp(GA.createCasualConfiguration(!0))});function I1(r,t,e){return v6.parseDate(r,t,e)}var v6,P1=x(()=>{A1();v6=S1});function C6(r){return!b6.test(r)}var b6,w6,jA,So,Qd=x(()=>{P1();b6=/\b(?:last|previous)\b|\bpast\s+(?:few\s+)?(?:\w*day|weekend|week|month|year|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\w*\b/i,w6=/\bprevious\b/gi;jA=class{getParsedDate(t,e=new Date){let n=t.replace(w6,"last");return I1(n,e,{forwardDate:C6(n)})}parseDate(t){if(!t||!t.trim())return null;try{let e=this.getParsedDate(t);return e?window.moment?{moment:window.moment(e)}:(console.warn("Moment.js is not available"),null):null}catch(e){return console.warn("Failed to parse date:",t,e),null}}},So=new jA});function lv(r){return typeof r=="string"&&av.includes(r)}function Qa(r){if(!r||typeof r!="object")return;let t=r;switch(t.kind){case"now":return{kind:"now"};case"ask":{let e=typeof t.defaultValue=="string"?t.defaultValue.trim():"";return e?{kind:"ask",defaultValue:e}:{kind:"ask"}}case"relative":return typeof t.offset!="number"||!Number.isInteger(t.offset)||!lv(t.unit)?void 0:{kind:"relative",offset:t.offset,unit:t.unit};case"variable":return typeof t.name!="string"||!t.name.trim()?void 0:{kind:"variable",name:t.name.trim()};default:return}}var av,Xp=x(()=>{av=["days","weeks","months","years"]});function mC(r){return F6.has(r)}function Xa(r){if(!r||r.kind==="now")return"today";if(r.kind==="ask")return"ask";if(r.kind==="variable")return"variable";for(let t of KA)if(r.offset===t.offset&&r.unit===t.unit)return t.id;return"custom"}function fC(r){let{preset:t,previous:e}=r;if(t!=="today"){if(t==="ask")return e?.kind==="ask"?e:R1(Xa(e));if(t==="variable")return e?.kind==="variable"?e:{kind:"variable",name:""};if(t==="custom")return e?.kind==="relative"&&Xa(e)==="custom"?e:{kind:"relative",offset:-2,unit:"days"};for(let n of KA)if(n.id===t)return{kind:"relative",offset:n.offset,unit:n.unit}}}function R1(r){for(let t of pC)if(t.id===r&&t.defaultValue)return{kind:"ask",defaultValue:t.defaultValue};return{kind:"ask"}}function uv(r){let t=(r??"").trim().toLowerCase();for(let e of pC)if(e.aliases.some(n=>n===t))return e.id;return"kept"}function hC(r){let t=pC.map(e=>({value:e.id,label:e.label}));if(uv(r)==="kept"){let e=r?.trim();e&&t.push({value:"kept",label:e})}return t}function gC(r,t){if(r==="kept"){let e=t?.trim();return e||void 0}for(let e of pC)if(e.id===r)return e.defaultValue}function O1(r){return typeof r=="string"&&r.trim().toLowerCase()==="ask"}function Jp(r){return r?.kind==="ask"?r:R1(Xa(r))}var $6,oC,sC,aC,lC,cv,cC,dv,dC,KA,uC,pC,F6,uc=x(()=>{$6=["today","ask","yesterday","last-week","next-week","last-month","custom","variable"],oC="Which day",sC="The day {{DATE}} writes. The clock stays now. Hold Shift in the QuickAdd menu to pick a different day.",aC="Picker starts on",lC="The date the picker suggests first. You can still pick a different day.",cv="How far from today",cC="How many days, weeks, months, or years from today. Negative is the past.",dv="Variable name",dC="A VDATE or script value that already has the day.",KA=[{id:"yesterday",label:"Yesterday",offset:-1,unit:"days"},{id:"last-week",label:"Last week",offset:-1,unit:"weeks"},{id:"next-week",label:"Next week",offset:1,unit:"weeks"},{id:"last-month",label:"Last month",offset:-1,unit:"months"}],uC=[{value:"today",label:"Today"},{value:"ask",label:"Ask each time"},...KA.map(r=>({value:r.id,label:r.label})),{value:"custom",label:"Custom\u2026"},{value:"variable",label:"A variable\u2026"}],pC=[{id:"today",label:"Today",defaultValue:void 0,aliases:["","today"]},{id:"yesterday",label:"Yesterday",defaultValue:"yesterday",aliases:["yesterday","yd"]},{id:"last-week",label:"Last week",defaultValue:"last week",aliases:["last week","lw"]},{id:"next-week",label:"Next week",defaultValue:"next week",aliases:["next week","nw"]},{id:"last-month",label:"Last month",defaultValue:"last month",aliases:["last month","lm"]}],F6=new Set($6)});function Y6(r,t){let e=[r,...t??[]].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);return e.length>0?e:void 0}function N1(r){let t=Dn.parse(`__capture_scope|${r}`);return{filter:t.filters,multiSelect:t.multiSelect??!1}}function K6(r){return!!(r.folder||r.folders?.length||r.tags?.length||r.excludeFolders?.length||r.excludeTags?.length||r.excludeFiles?.length)}function em(r){let t=r.trim();if(!t)return null;if(t.startsWith("#")){let o=bo(t),s=(o.shift()??"").replace(/^#/,"").replace(/\.md$/i,"").trim();if(!s)return null;let a=o.length>0?N1(o.join("|")):{filter:{},multiSelect:!1};return{filter:{...a.filter,tags:Y6(s,a.filter.tags)},multiSelect:a.multiSelect}}let e=bo(t)[0]??"",n=wo(e);if(!n||!j6.has(n.key))return null;let i=N1(t);return K6(i.filter)?i:null}var j6,CC=x(()=>{Da();jl();j6=new Set(["folder","tag","exclude-folder","exclude-tag","exclude-file"])});function tm(r){let t=r.trim();if(!V1.test(t))return null;let e=t.replace(V1,""),{fieldName:n,filters:i}=Dn.parse(e),o=n.indexOf("="),s=(o>=0?n.slice(0,o):n).trim(),a=o>=0?n.slice(o+1).trim():"",l=a.length>0?a:void 0;return{field:s,value:l,filter:i}}var V1,xC=x(()=>{Da();V1=/^property:/i});function nV(r){let t=SC.find(e=>e.id===(r===void 0?"open":r));if(!t)throw new Error(`Unknown existing-note action: ${String(r)}`);return t}function AC(r){return nV(r).id}function fc(r){return nV(r).verb}function am(r){let t=_X.get(r);if(!t)throw new Error(`Unknown file exists mode: ${r}`);return t}function iV(r){return cI.filter(t=>t.category===r)}function oV(r){return am(r).category}function sV(){return[...cI]}function aV(r){return r.kind==="prompt"?"prompt":oV(r.mode)}function lV(r,t){return r==="prompt"?{kind:"prompt"}:t?.kind==="apply"&&oV(t.mode)===r?t:{kind:"apply",mode:kX[r]}}function cV(r){return typeof r!="string"||!Object.prototype.hasOwnProperty.call(tV,r)?null:tV[r]??null}async function dV(r,t,e){return await SX[t](r,e)}async function AX(r,t){let e=r;for(;await t(e);){let{basename:n,extension:i}=uV(e),o=n.match(/^(.*?)(\d+)$/);e=`${o?`${o[1]}${String(BigInt(o[2])+1n).padStart(o[2].length,"0")}`:`${n}1`}${i}`}return e}async function IX(r,t){let e=r;for(;await t(e);){let{basename:n,extension:i}=uV(e),o=n.match(/^(.*) \((\d+)\)$/);e=`${o?`${o[1]} (${String(BigInt(o[2])+1n)})`:`${n} (1)`}${i}`}return e}function uV(r){return lr.test(r)?{basename:r.replace(lr,""),extension:".canvas"}:Rn.test(r)?{basename:r.replace(Rn,""),extension:".base"}:{basename:r.replace(xt,""),extension:".md"}}var rV,cI,SC,_X,kX,tV,SX,Za=x(()=>{Le();rV=[{id:"prompt",label:"Ask every time"},{id:"update",label:"Update existing file"},{id:"create",label:"Create another file"},{id:"keep",label:"Keep existing file"}],cI=[{id:"appendBottom",category:"update",label:"Append to bottom",description:"Adds the template content to the end of the existing file.",requiresExistingFile:!0,resolutionKind:"modifyExisting"},{id:"appendTop",category:"update",label:"Append to top",description:"Adds the template content to the beginning of the existing file.",requiresExistingFile:!0,resolutionKind:"modifyExisting"},{id:"overwrite",category:"update",label:"Overwrite file",description:"Replaces the existing file content with the template.",requiresExistingFile:!0,resolutionKind:"modifyExisting"},{id:"increment",category:"create",label:"Increment trailing number",description:"Changes trailing digits only. Example: Draft009.md -> Draft010.md.",requiresExistingFile:!1,resolutionKind:"createNew"},{id:"duplicateSuffix",category:"create",label:"Append duplicate suffix",description:"Keeps the original name and adds a duplicate marker. Example: Project Plan.md -> Project Plan (1).md.",requiresExistingFile:!1,resolutionKind:"createNew"},{id:"doNothing",category:"keep",label:"Do nothing",description:"Leaves the file unchanged and opens the existing file.",requiresExistingFile:!0,resolutionKind:"reuseExisting"}],SC=[{id:"open",label:"Open note",verb:"Open"},{id:"appendBottom",label:"Append template to bottom",verb:"Append to"},{id:"appendTop",label:"Insert template at top",verb:"Insert into"},{id:"overwrite",label:"Replace entire note",verb:"Replace"}];_X=new Map(cI.map(r=>[r.id,r])),kX={update:"appendBottom",create:"duplicateSuffix",keep:"doNothing"},tV={"Append to the bottom of the file":"appendBottom","Append to the top of the file":"appendTop","Overwrite the file":"overwrite","Increment the file name":"increment","Append duplicate suffix":"duplicateSuffix",Nothing:"doNothing",appendBottom:"appendBottom",appendTop:"appendTop",overwrite:"overwrite",increment:"increment",duplicateSuffix:"duplicateSuffix",doNothing:"doNothing"},SX={increment:AX,duplicateSuffix:IX}});function RI(r,t){if(!r.fileNameFormat?.enabled)return!0;let e=t.trim().toLowerCase();return e===xr.toLowerCase()||e===mD.toLowerCase()}function OI(r,t){return r.discoverExistingNotesBeforeCreate===!0&&RI(r,t)}function xc(r,t,e){return!(!OI(r,t)||e!=null)}var ou=x(()=>{Le()});function Ei(r,{title:t,message:e,action:n,destructive:i=!0}){return new Promise(o=>{let s=!1,a=new ZV.ConfirmationModal(r);a.setTitle(t),e&&a.setContent(e),a.addCancelButton().addButton(l=>{l.setButtonText(n).setCta().setInitialFocus().onClick(()=>{s=!0}),i&&l.setDestructive()}),a.buttonContainerEl.querySelectorAll("button").forEach(KC),a.setCloseCallback(()=>o(s)),a.open()})}function KC(r){let t=e=>{e.preventDefault(),e.stopPropagation()};r.addEventListener("pointerdown",t),r.addEventListener("mousedown",t)}function QC(r){r.forEach(t=>{t.addEventListener("keydown",e=>{if(e.key==="ArrowRight"||e.key==="ArrowLeft"){let i=(r.indexOf(t)+(e.key==="ArrowRight"?1:-1)+r.length)%r.length;r[i].focus(),e.preventDefault()}})})}var ZV,tl=x(()=>{ZV=require("obsidian")});function eB(r){NI=r}function Wr(){if(!NI)throw new Error("QuickAdd plugin instance accessed before it was initialised.");return NI}var NI,ss=x(()=>{});var jt,er=x(()=>{jt=(c=>(c.Obsidian="Obsidian",c.UserScript="UserScript",c.Choice="Choice",c.Wait="Wait",c.NestedChoice="NestedChoice",c.EditorCommand="EditorCommand",c.AIAssistant="AIAssistant",c.OpenFile="OpenFile",c.Conditional="Conditional",c))(jt||{})});function Ws(r){let t=0,e=0,n=!1,i=0,o=0,s=0;for(;t<=r.length;){let a=r.indexOf(`
|
||
`,t),l=a===-1?r.length:a,c=r.slice(t,l).replace(/\r$/,""),d=a===-1?r.length+1:a+1,u=h8.exec(c);if(n){if(u&&u[1].length>=i&&u[2].trim().length===0)return nB(r.slice(o,t),s)}else if(u){let p=u[2].trim().split(/\s+/)[0]?.toLowerCase();(p==="js"||p==="javascript")&&(n=!0,i=u[1].length,o=d,s=e+1)}if(t=d,e++,a===-1)break}return n?nB(r.slice(o),s):{code:null,error:g8}}function nB(r,t){return r.trim().length===0?{code:"",error:v8}:{code:`
|
||
`.repeat(t)+r}}var h8,g8,v8,_m=x(()=>{h8=/^ {0,3}(`{3,})(.*)$/,g8="No ```js (or ```javascript) code block found in the note.",v8="The ```js code block is empty."});function as(r,t){let e=t;for(;e<r.length;){let n=r[e],i=r[e+1];if(/\s/.test(n)){e+=1;continue}if(n==="/"&&i==="/"){let o=r.indexOf(`
|
||
`,e+2);e=o===-1?r.length:o+1;continue}if(n==="/"&&i==="*"){let o=r.indexOf("*/",e+2);e=o===-1?r.length:o+2;continue}return e}return e}function Ov(r,t){let e=r[t];if(e!=='"'&&e!=="'"&&e!=="`")return null;let n="";for(let i=t+1;i<r.length;i++){let o=r[i];if(o==="\\"){let s=r[i+1];if(s===void 0)return null;n+=s,i+=1;continue}if(o===e)return{value:n,end:i+1};n+=o}return null}function iB(r,t){let e=/^[A-Za-z_$][\w$]*/.exec(r.slice(t));return e?{value:e[0],end:t+e[0].length}:null}function XC(r,t,e,n){let i=0;for(let o=t;o<r.length;o++){let s=r[o],a=r[o+1];if(s==='"'||s==="'"||s==="`"){let l=Ov(r,o);if(!l)return-1;o=l.end-1;continue}if(s==="/"&&a==="/"){let l=r.indexOf(`
|
||
`,o+2);o=l===-1?r.length:l;continue}if(s==="/"&&a==="*"){let l=r.indexOf("*/",o+2);if(l===-1)return-1;o=l+1;continue}if(s===e){i+=1;continue}if(s===n&&(i-=1,i===0))return o}return-1}function oB(r){let t=new Map,e=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(["'`])/g,n;for(;(n=e.exec(r))!==null;){let i=Ov(r,e.lastIndex-1);i&&(t.set(n[1],i.value),e.lastIndex=i.end)}return t}function b8(r){let t=[],e=oB(r),n=0;for(;n<r.length;){n=as(r,n);let i=r[n];if(i==='"'||i==="'"||i==="`"){let a=Ov(r,n);n=a?a.end:n+1;continue}let o=zI(r,n,e);if(!o){n+=1;continue}if(n=as(r,o.end),r[n]!==":"){n=o.end;continue}if(n=as(r,n+1),o.name!=="options"||r[n]!=="{")continue;let s=XC(r,n,"{","}");if(s===-1)break;t.push({start:n+1,end:s}),n=s+1}return t}function zI(r,t,e){if(r[t]==='"'||r[t]==="'"||r[t]==="`"){let i=Ov(r,t);return i?{name:i.value,end:i.end}:null}if(r[t]==="["){let i=as(r,t+1),o=iB(r,i),s=XC(r,t,"[","]");if(s===-1)return null;let a=o?as(r,o.end):i;return{name:o&&a===s?e.get(o.value)??null:null,end:s+1}}let n=iB(r,t);return n?{name:n.value,end:n.end}:null}function w8(r){let t=new Map,e=0;for(;e<r.length;){if(e=as(r,e),r[e]===","){e+=1;continue}if(e>=r.length)break;let n=zI(r,e,new Map);if(!n?.name){e+=1;continue}if(e=as(r,n.end),r[e]!==":"){e+=1;continue}if(e=as(r,e+1),r[e]==='"'||r[e]==="'"||r[e]==="`"){let o=Ov(r,e);if(!o)break;t.set(n.name,o.value),e=o.end;continue}if(r.slice(e,e+4)==="true"){t.set(n.name,!0),e+=4;continue}if(r.slice(e,e+5)==="false"){t.set(n.name,!1),e+=5;continue}let i=r[e];if(i==="{"||i==="["){let o=XC(r,e,i,i==="{"?"}":"]");if(o===-1)break;e=o+1;continue}for(;e<r.length&&r[e]!==",";)e+=1}return t}function C8(r){let t=w8(r),e=t.get("type"),n=t.get("secret");return e==="secret"||(e==="text"||e==="input")&&n===!0}function Dv(r,t){let e=t&&y8.test(t)?Ws(r).code??"":r,n=new Set,i=!1,o=oB(e);for(let{start:s,end:a}of b8(e)){let l=s;for(;l<a;){if(l=as(e,l),e[l]===","){l+=1;continue}if(l>=a)break;let c=zI(e,l,o);if(!c){l+=1;continue}if(l=as(e,c.end),e[l]!==":"){l+=1;continue}if(l=as(e,l+1),e[l]!=="{"){l+=1;continue}let d=XC(e,l,"{","}");if(d===-1||d>a)break;let u=e.slice(l+1,d);C8(u)&&(i=!0,c.name&&n.add(c.name)),l=d+1}}return{names:n,foundSecretOptions:i}}var y8,sB=x(()=>{_m();y8=/\.md$/i});function Tr(r){return typeof r=="object"&&r!==null}function rl(r){return Tr(r)&&!Array.isArray(r)}function x8(r){return rl(r)?!1:Array.isArray(r)?r.length>0:Wt(r)}function ur(r){return rl(r)?r.commands:x8(r)?r:void 0}function Mt(r){return Array.isArray(r)?r:[]}function km(r){return Array.isArray(r)?r:[]}function Lv(r){return Array.isArray(r)}function HI(r){let t=Mt(r),e=new Set,n=!1,i=[];for(let o of t){if(Array.isArray(o)){let l=HI(o);for(let c of l.commands){let d=c.id;if(typeof d=="string"&&d!==""&&!e.has(d)){e.add(d),i.push(c);continue}let u={...c,id:Vt()};e.add(u.id),i.push(u)}n=!0;continue}if(!Tr(o)){n=!0;continue}let s=o.id;if(typeof s=="string"&&s!==""&&!e.has(s)){e.add(s),i.push(o);continue}let a={...o,id:Vt()};e.add(a.id),i.push(a),n=!0}return n?{commands:i,changed:n}:{commands:t,changed:!1}}function aB(r){lB(r,new Set)}function lB(r,t){Tr(r)&&(t.has(r)||(t.add(r),rl(r)&&(r.id=Vt()),JC(ur(r),t)))}function JC(r,t){if(Lv(r))for(let e of r){if(Array.isArray(e)){JC(e,t);continue}if(!Tr(e)||t.has(e))continue;t.add(e),e.id=Vt();let n=e;JC(n.thenCommands,t),JC(n.elseCommands,t),cB(n.choice,t)}}function cB(r,t){if(!Tr(r)||t.has(r))return;t.add(r);let e=r;if(e.id=Vt(),e.type==="Macro"&&lB(e.macro,t),e.type==="Multi"&&Array.isArray(e.choices))for(let n of e.choices)cB(n,t)}var Gr=x(()=>{qh();Qo();qh()});function Am(r){return r!==null&&typeof r=="object"}function nx(r){return r?.secretStorage}function ex(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"setting"}function T8(r){let t=5381;for(let e=0;e<r.length;e+=1)t=t*33^r.charCodeAt(e);return(t>>>0).toString(36).slice(0,E8)}function uB(r,t){return r.length<=t?r:r.slice(0,t).replace(/-+$/g,"")||"setting"}function mB(r,t){let e=t?.id;return typeof e=="string"&&e.trim().length>0?e:r}function WI(r,t,e){let i=(e?[ZC,r,t,e]:[ZC,r,t]).join("-");if(i.length<=dB)return i;let o=T8([r,t,e].filter(Boolean).join(":")),s=e?4:3,a=dB-ZC.length-o.length-(e?.length??0)-s,l=Math.max(8,Math.floor(a*.6)),c=Math.max(8,a-l);return[ZC,uB(r,l),uB(t,c),...e?[e]:[],o].join("-")}function GI(r){return r?.message??String(r)}function Im(r){return Am(r)?r.type==="secret"||(r.type==="text"||r.type==="input")&&r.secret===!0:!1}function Sm(r){return Am(r)&&r[pB]===!0&&typeof r.secretRef=="string"&&r.secretRef.trim().length>0}function tx(r){return{[pB]:!0,secretRef:r}}function _8(r,t,e){let n=r.id?.trim()||r.path||r.name||"script";return WI(ex(n),ex(mB(t,e)))}function k8(r){let t=r?.options;return t?Object.entries(t).filter(([,e])=>Im(e)).map(([e])=>e):[]}function S8(r){let t=r?.options;return t?Object.entries(t).filter(([,e])=>Im(e)):[]}function A8(r){return typeof r.id=="string"&&r.id.trim().length>0}async function jI(r,t){let e=nx(r);if(!e?.getSecret)return null;try{return await Promise.resolve(e.getSecret(t))}catch(n){return S.logWarning(`Failed to read user script SecretStorage entry "${t}": ${GI(n)}`),null}}async function I8(r,t,e){let n=nx(r);if(!n?.setSecret)return!1;try{return await Promise.resolve(n.setSecret(t,e)),!0}catch(i){return S.logWarning(`Failed to write user script SecretStorage entry "${t}": ${GI(i)}`),!1}}async function P8(r,t,e,n,i){let o=t.id?.trim()||t.path||t.name||"script",s=ex(o),a=ex(mB(e,i)),l=WI(s,a),c=1;for(;;){let d=await jI(r,l);if(!d||d===n)return l;c+=1,l=WI(s,a,String(c))}}async function YI(r,t,e,n,i,o){if(n.length===0)return null;let s=i?.trim()||await P8(r,t,e,n,o);return await I8(r,s,n)?s:null}async function KI(r,t){let e=t?.trim();if(!e)return!0;let n=nx(r);if(!n)return!0;let i=n.deleteSecret??n.removeSecret??n.delete;try{if(i)return await Promise.resolve(i.call(n,e)),!0;if(n.setSecret)return await Promise.resolve(n.setSecret(e,"")),!0}catch(o){S.logWarning(`Failed to clear user script SecretStorage entry "${e}": ${GI(o)}`)}return!1}async function fB(r,t,e){let n=t.settings??{},i={...n},o=new Set(k8(e));for(let[s,a]of Object.entries(n)){if(Sm(a)){let l=await jI(r,a.secretRef);if(l){i[s]=l;continue}throw new Error(`Secret setting "${s}" for user script "${t.name}" is unavailable. Re-enter it on this device.`)}o.has(s)&&(i[s]=typeof a=="string"?a:"")}return i}async function ix(r,t,e){let n=S8(e);if(n.length===0)return!1;let i=nx(r);if(!i?.getSecret||!i?.setSecret)return n.some(([a])=>{let l=t.settings?.[a];return typeof l=="string"&&l.length>0})&&S.logWarning(`SecretStorage unavailable; leaving plaintext user script secret settings for "${t.name}" unchanged.`),!1;let o=!1;for(let[s,a]of n){let l=t.settings?.[s];if(Sm(l))continue;if(typeof l!="string"||l.length===0){if(!A8(a))continue;let d=_8(t,s,a);if(!await jI(r,d))continue;t.settings[s]=tx(d);for(let[p,m]of Object.entries(t.settings))p!==s&&Sm(m)&&m.secretRef===d&&delete t.settings[p];o=!0;continue}let c=await YI(r,t,s,l,void 0,a);c&&(t.settings[s]=tx(c),o=!0)}return o}function ox(r,t){let e=r.settings?.[t];return Sm(e)?e.secretRef:void 0}async function $8(r,t){if(!Am(t))return!0;let e=Object.values(t).filter(Sm).map(i=>i.secretRef);return(await Promise.all(e.map(i=>KI(r,i)))).every(Boolean)}function*QI(r){if(Am(r)&&(r.type==="Macro"&&(yield*rx(ur(r.macro))),r.type==="Multi"&&Array.isArray(r.choices)))for(let t of r.choices)yield*QI(t)}function*XI(r){Am(r)&&(r.type==="UserScript"&&(yield r),yield*rx(r.thenCommands),yield*rx(r.elseCommands),yield*QI(r.choice))}function*rx(r){if(Array.isArray(r))for(let t of r)yield*Array.isArray(t)?rx(t):XI(t)}async function F8(r,t){let e=!0;for(let n of t)e=await $8(r,n.settings)&&e;return e}async function sx(r,t){return F8(r,XI(t))}function M8(r,t){let e=r.path;if(typeof e=="string")return t?.secretOptionNamesByPath?.get(e)}function R8(r,t,e){if(Am(r))for(let[n,i]of Object.entries(r)){if(Sm(i)){delete r[n];continue}typeof i=="string"&&(t===null||t?.has(n)||t===void 0&&e?.stripUnknownStringSettings===!0)&&delete r[n]}}function hB(r,t){for(let e of r)R8(e.settings,M8(e,t),t)}function gB(r,t){hB(XI(r),t)}function ax(r,t){hB(QI(r),t)}var ZC,pB,dB,E8,nl=x(()=>{ye();sB();Gr();ZC="quickadd-user-script",pB="__quickaddSecret",dB=64,E8=8});function Pm(r,t){if(t.options)for(let e in t.options){let n=r[e]===void 0,i="defaultValue"in t.options[e]&&t.options[e].defaultValue!==void 0;n&&i&&!Im(t.options[e])&&(r[e]=t.options[e].defaultValue)}}var lx=x(()=>{nl()});function px(r){return r instanceof dx}function L8(r){return r.charCodeAt(0)===65279?r.slice(1):r}function N8(r){return L8(r).trimStart().slice(0,D8).toLowerCase()}function V8(r){return/^<(?:!doctype\s+html|html\b|head\b|body\b|script\b|meta\b|title\b|div\b)/.test(N8(r))}function $m(r,t){let e=new dx(r);throw t.reportLoadErrors!==!1&&Me(e),e}function B8(r){return`QuickAdd could not run ${r}. A user script must be a .js file or a note with a \`\`\`js code block. Rename the file so it ends in .js.`}function U8(r){return`QuickAdd could not find ${r}. If you moved or renamed the script, update its path in the macro.`}function q8(r){return`QuickAdd could not load ${r}. This file looks like a saved webpage, not a JavaScript file. Open the script on GitHub, use the Raw button, then download the .js file and select that file in QuickAdd.`}function z8(r){return`QuickAdd loaded ${r}, but its default export is not a function. Change it to module.exports = async (params) => { ... } or exports.default = async (params) => { ... }. If you meant to export several functions, use module.exports = { run } and select Script::run.`}function H8(r,t){let e=t?`the required module "${t}"`:"a required module";return`QuickAdd could not load ${r} because it could not find ${e}. Check that the required file or package exists, and that the capitalization in require(...) matches the file name exactly.`}function W8(r,t,e){let n=e===void 0?"":` on line ${e}`;return`QuickAdd could not load ${r} because it has a syntax error${n}: ${t}. Fix the script and run it again.`}function G8(r,t){if(r.startsWith("#!"))return;let e=window.require?.("vm");try{e?.compileFunction(r,bB,{filename:"user-script"})}catch(n){if(!(n instanceof Error)||n.message!==t)return;let i=n.stack?.match(/^user-script:(\d+)\n/)?.[1];if(i)return Number(i)}}function j8(r){return wB(r)?(r instanceof Error?r.message:String(r)).match(/Cannot find module ['"]([^'"]+)['"]/)?.[1]:void 0}function wB(r){return!r||typeof r!="object"?!1:r.code==="MODULE_NOT_FOUND"?!0:(r instanceof Error?r.message:String(r)).includes("Cannot find module")}function JI(r){return r!==null&&typeof r=="object"}function Y8(r){return typeof r.entry=="function"?!0:Object.entries(r).some(([t,e])=>t!=="settings"&&t!=="quickadd"&&typeof e=="function")}function K8(r){return typeof r=="function"?!0:JI(r)?Y8(r):!1}function Fm(r){let t=r.split("::").map(e=>e.trim()).filter(Boolean);return{basename:t[0],memberAccess:t.slice(1)}}function mx(r){let t=r.path??r.id;if(t===void 0)return;let{memberAccess:e}=Fm(r.name??"");return e&&e.length>0?`${t}::${e.join("::")}`:t}function yB(r){if(!JI(r)&&typeof r!="function")return;let t=r.settings;return JI(t)?t:void 0}function Q8(r,t){let e=r,n=yB(e);for(let i of t)e=e[i],n=yB(e)??n;return{script:e,settings:n}}async function Nv(r,t,e={}){return(await su(r,t,e))?.script}async function su(r,t,e={}){let n=t.vault.getAbstractFileByPath(r.path);if(n||$m(U8(r.path),e),n instanceof ux.TFile){let i=xt.test(n.path);!i&&!Fh.test(n.path)&&$m(B8(r.path),e);let o=g=>window.require&&window.require(g),s={},a={exports:s},l=await t.vault.read(n),c=l;if(i){let{code:g,error:v}=Ws(l);if(g===null||g.length===0){e.reportLoadErrors!==!1&&new ux.Notice(`QuickAdd: ${v} (${r.path})`);return}c=g}V8(c)&&$m(q8(r.path),e);let d;try{d=new Function(...bB,c)}catch(g){throw g instanceof SyntaxError&&$m(W8(r.path,g.message,G8(c,g.message)),e),g}try{d(o,a,s)}catch(g){throw wB(g)&&$m(H8(r.path,j8(g)),e),g}let u=s.default||a.exports;if(!u)return;let p=!!s.default,m=Fm(r.name).memberAccess??[],h=Q8(u,m);return p&&m.length===0&&!K8(h.script)&&$m(z8(r.path),e),h}}var ux,D8,dx,bB,au=x(()=>{ux=require("obsidian");Le();_m();nt();D8=1024,dx=class extends Error{constructor(t){super(t),this.name="UserScriptLoadError"}};bB=["require","module","exports"]});function Tc(r){return Array.isArray?Array.isArray(r):IB(r)==="[object Array]"}function e9(r){if(typeof r=="string")return r;if(typeof r=="bigint")return r.toString();let t=r+"";return t=="0"&&1/r==-1/0?"-0":t}function tP(r){return r==null?"":e9(r)}function Vn(r){return typeof r=="string"}function gx(r){return typeof r=="number"}function t9(r){return r===!0||r===!1||r9(r)&&IB(r)=="[object Boolean]"}function AB(r){return typeof r=="object"}function r9(r){return AB(r)&&r!==null}function ji(r){return r!=null}function hx(r){return!r.trim().length}function IB(r){return r==null?r===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(r)}function PB(r){let t=null,e=null,n=null,i=1,o=null;if(Vn(r)||Tc(r))n=r,t=xB(r),e=vx(r);else{if(!CB.call(r,"name"))throw new Error(s9("name"));let s=r.name;if(n=s,CB.call(r,"weight")&&r.weight!==void 0&&(i=r.weight,i<=0))throw new Error(a9(vx(s)));t=xB(s),e=vx(s),o=r.getFn??null}return{path:t,id:e,weight:i,src:n,getFn:o}}function xB(r){return Tc(r)?r:r.split(".")}function vx(r){return Tc(r)?r.join("."):r}function d9(r,t){let e=[],n=!1,i=(o,s,a,l)=>{if(ji(o))if(!s[a])e.push(l!==void 0?{v:o,i:l}:o);else{let c=o[s[a]];if(!ji(c))return;if(a===s.length-1&&(Vn(c)||gx(c)||t9(c)||typeof c=="bigint"))e.push(l!==void 0?{v:tP(c),i:l}:tP(c));else if(Tc(c)){n=!0;for(let d=0,u=c.length;d<u;d+=1)i(c[d],s,a+1,d)}else s.length&&i(c,s,a+1,l)}};return i(r,Vn(t)?t.split("."):t,0),n?e:e[0]}function h9(r){return r>=9&&r<=13||r===32||r===160}function g9(r=1,t=3){let e=new Map,n=Math.pow(10,t);return{get(i){let o=0,s=!1;for(let l=0;l<i.length;l++)h9(i.charCodeAt(l))?s=!1:s||(o++,s=!0);if(o===0&&(o=1),e.has(o))return e.get(o);let a=Math.round(n/Math.pow(o,.5*r))/n;return e.set(o,a),a},clear(){e.clear()}}}function $B(r,t,{getFn:e=Ue.getFn,fieldNormWeight:n=Ue.fieldNormWeight}={}){let i=new cP({getFn:e,fieldNormWeight:n});return i.setKeys(r.map(PB)),i.setSources(t),i.create(),i}function v9(r,{getFn:t=Ue.getFn,fieldNormWeight:e=Ue.fieldNormWeight}={}){let{keys:n,records:i}=r,o=new cP({getFn:t,fieldNormWeight:e});return o.setKeys(n),o.setIndexRecords(i),o}function y9(r=[],t=Ue.minMatchCharLength){let e=[],n=-1,i=-1,o=0;for(let s=r.length;o<s;o+=1){let a=r[o];a&&n===-1?n=o:!a&&n!==-1&&(i=o-1,i-n+1>=t&&e.push([n,i]),n=-1)}return r[o-1]&&o-n>=t&&e.push([n,o-1]),e}function b9(r,t,e,{location:n=Ue.location,distance:i=Ue.distance,threshold:o=Ue.threshold,findAllMatches:s=Ue.findAllMatches,minMatchCharLength:a=Ue.minMatchCharLength,includeMatches:l=Ue.includeMatches,ignoreLocation:c=Ue.ignoreLocation}={}){if(t.length>32)throw new Error(o9(32));let d=t.length,u=r.length,p=Math.max(0,Math.min(n,u)),m=o,h=p,g=(D,N)=>{let K=D/d;if(c)return K;let ne=Math.abs(p-N);return i?K+ne/i:ne?1:K},v=a>1||l,b=v?Array(u):[],y;for(;(y=r.indexOf(t,h))>-1;){let D=g(0,y);if(m=Math.min(D,m),h=y+d,v){let N=0;for(;N<d;)b[y+N]=1,N+=1}}h=-1;let C=[],w=1,T=0,P=d+u,_=1<<d-1;for(let D=0;D<d;D+=1){let N=0,K=P;for(;N<K;)g(D,p+K)<=m?N=K:P=K,K=Math.floor((P-N)/2+N);P=K;let ne=Math.max(1,p-K+1),H=s?u:Math.min(p+K,u)+d,O=Array(H+2);O[H+1]=(1<<D)-1;for(let G=H;G>=ne;G-=1){let V=G-1,M=e[r[V]];if(O[G]=(O[G+1]<<1|1)&M,D&&(O[G]|=(C[G+1]|C[G])<<1|1|C[G+1]),O[G]&_&&(w=g(D,V),w<=m)){if(m=w,h=V,T=D,h<=p)break;ne=Math.max(1,2*p-h)}}if(g(D+1,p)>m)break;C=O}if(v&&h>=0){let D=Math.min(u-1,h+d-1+T);for(let N=h;N<=D;N+=1)e[r[N]]&&(b[N]=1)}let I={isMatch:h>=0,score:Math.max(.001,w)};if(v){let D=y9(b,a);D.length?l&&(I.indices=D):I.isMatch=!1}return I}function w9(r){let t={};for(let e=0,n=r.length;e<n;e+=1){let i=r.charAt(e);t[i]=(t[i]||0)|1<<n-e-1}return t}function dP(r){if(r.length<=1)return r;r.sort((e,n)=>e[0]-n[0]||e[1]-n[1]);let t=[r[0]];for(let e=1,n=r.length;e<n;e+=1){let i=t[t.length-1],o=r[e];o[0]<=i[1]+1?i[1]=Math.max(i[1],o[1]):t.push(o)}return t}function E9(r){return r.startsWith("inverse")}function k9(r){let t=[],e=r.length,n=0;for(;n<e;){for(;n<e&&r[n]===" ";)n++;if(n>=e)break;let i=n;for(;i<e&&r[i]!==" "&&r[i]!=='"';)i++;if(i<e&&r[i]==='"'){for(i++;i<e;){if(r[i]==='"'){let o=i+1;if(o>=e||r[o]===" "){i++;break}if(r[o]==="$"&&(o+1>=e||r[o+1]===" ")){i+=2;break}}i++}t.push(r.substring(n,i)),n=i}else{for(;i<e&&r[i]!==" ";)i++;t.push(r.substring(n,i)),n=i}}return t}function TB(r,t){let e=r.match(t);return e?e[1]:null}function S9(r,t={}){return r.replace(/\\\|/g,T9).split(_9).map(e=>{let n=k9(e.replace(/\u0000/g,"|").trim()).filter(o=>o&&!!o.trim()),i=[];for(let o=0,s=n.length;o<s;o+=1){let a=n[o],l=!1,c=-1;for(;!l&&++c<EB;){let d=nP[c],u=TB(a,d.multiRegex);u&&(i.push(d.create(u,t)),l=!0)}if(!l)for(c=-1;++c<EB;){let d=nP[c],u=TB(a,d.singleRegex);if(u){i.push(d.create(u,t));break}}}return i})}function pP(...r){iP.push(...r)}function yx(r,t){for(let e=0,n=iP.length;e<n;e+=1){let i=iP[e];if(i.condition(r,t))return new i(r,t)}return new uP(r,t)}function MB(r,t,{auto:e=!0}={}){let n=i=>{if(Vn(i)){let l={keyId:null,pattern:i};return e&&(l.searcher=yx(i,t)),l}let o=Object.keys(i),s=I9(i);if(!s&&o.length>1&&!sP(i))return n(_B(i));if(P9(i)){let l=s?i[oP.PATH]:o[0],c=s?i[oP.PATTERN]:i[l];if(!Vn(c))throw new Error(i9(l));let d={keyId:vx(l),pattern:c};return e&&(d.searcher=yx(c,t)),d}let a={children:[],operator:o[0]};return o.forEach(l=>{let c=i[l];Tc(c)&&c.forEach(d=>{a.children.push(n(d))})}),a};return sP(r)||(r=_B(r)),n(r)}function aP(r,{ignoreFieldNorm:t=Ue.ignoreFieldNorm}){let e=1;return r.forEach(({key:n,norm:i,score:o})=>{let s=n?n.weight:null;e*=Math.pow(o===0&&s?Number.EPSILON:o,(s||1)*(t?1:i))}),e}function $9(r,{ignoreFieldNorm:t=Ue.ignoreFieldNorm}){r.forEach(e=>{e.score=aP(e.matches,{ignoreFieldNorm:t})})}function M9(r){let t=[];return r.matches.forEach(e=>{if(!ji(e.indices)||!e.indices.length)return;let n={indices:e.indices,value:e.value};e.key&&(n.key=e.key.id),e.idx>-1&&(n.refIndex=e.idx),t.push(n)}),t}function R9(r,t,{includeMatches:e=Ue.includeMatches,includeScore:n=Ue.includeScore}={}){return r.map(i=>{let{idx:o}=i,s={item:t[o],refIndex:o};return e&&(s.matches=M9(i)),n&&(s.score=i.score),s})}function D9(r){kB.has(r)||(kB.add(r),console.warn(`[Fuse] tokenize regex ${r} lacks the global flag; only the first match per text will be returned. Add the 'g' flag.`))}function L9(r){if(typeof r=="function"){let t=!1;return e=>{let n=r(e);if(!t&&(t=!0,!Array.isArray(n)||n.some(i=>typeof i!="string")))throw new Error(`[Fuse] tokenize function must return string[]; received ${Array.isArray(n)?"array containing non-strings":typeof n}.`);return n}}return r instanceof RegExp?(r.global||D9(r),t=>t.match(r)||[]):t=>t.match(O9)||[]}function lP({isCaseSensitive:r=!1,ignoreDiacritics:t=!1,tokenize:e}={}){let n=L9(e);return{tokenize(i){return r||(i=i.toLowerCase()),t&&(i=Vv(i)),n(i)}}}function eP(r,t,e,n){let i=n.tokenize(t);if(!i.length)return;r.fieldCount++,r.docFieldCount.set(e,(r.docFieldCount.get(e)||0)+1);let o=new Set(i),s=r.docTermFieldHits.get(e);s||(s=new Map,r.docTermFieldHits.set(e,s));for(let a of o)s.set(a,(s.get(a)||0)+1),r.df.set(a,(r.df.get(a)||0)+1)}function RB(r,t,e,n){let{i,v:o,$:s}=t;if(o!==void 0){eP(r,o,i,n);return}if(s)for(let a=0;a<e;a++){let l=s[a];if(l)if(Array.isArray(l))for(let c of l)eP(r,c.v,i,n);else eP(r,l.v,i,n)}}function V9(r,t,e){let n={fieldCount:0,df:new Map,docFieldCount:new Map,docTermFieldHits:new Map};for(let i of r)RB(n,i,t,e);return n}function B9(r,t,e,n){RB(r,t,e,n)}function U9(r,t){let e=r.docFieldCount.get(t);if(e===void 0)return;r.fieldCount-=e,r.docFieldCount.delete(t);let n=r.docTermFieldHits.get(t);if(n){for(let[i,o]of n){let s=(r.df.get(i)||0)-o;s<=0?r.df.delete(i):r.df.set(i,s)}r.docTermFieldHits.delete(t)}}function SB(r,t){if(t.length===0)return;let e=Array.from(new Set(t)).sort((a,l)=>a-l);for(let a of e)U9(r,a);let n=a=>{let l=0,c=e.length;for(;l<c;){let d=l+c>>>1;e[d]<a?l=d+1:c=d}return a-l},i=e[0],o=new Map;for(let[a,l]of r.docFieldCount)o.set(a>i?n(a):a,l);r.docFieldCount=o;let s=new Map;for(let[a,l]of r.docTermFieldHits)s.set(a>i?n(a):a,l);r.docTermFieldHits=s}var n9,rP,i9,o9,s9,a9,l9,CB,c9,u9,p9,m9,f9,Ue,cP,FB,C9,Vv,uP,x9,nP,EB,T9,_9,A9,iP,bx,oP,sP,I9,P9,_B,F9,O9,kB,N9,_c,kc,wx=x(()=>{n9="Incorrect 'index' type",rP="Invalid doc index: must be a non-negative integer within the bounds of the docs array",i9=r=>`Invalid value for key ${r}`,o9=r=>`Pattern length exceeds max of ${r}.`,s9=r=>`Missing ${r} property in key`,a9=r=>`Property 'weight' in key '${r}' must be a positive integer`,l9="Fuse.match does not support useTokenSearch: token search requires corpus-level statistics (df, fieldCount) that a one-off string comparison does not have. Use new Fuse(...).search(...) instead.",CB=Object.prototype.hasOwnProperty,c9=class{constructor(r){this._keys=[],this._keyMap={};let t=0;r.forEach(e=>{let n=PB(e);this._keys.push(n),this._keyMap[n.id]=n,t+=n.weight}),this._keys.forEach(e=>{e.weight/=t})}get(r){return this._keyMap[r]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};u9={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},p9={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(r,t)=>r.score===t.score?r.idx<t.idx?-1:1:r.score<t.score?-1:1},m9={location:0,threshold:.6,distance:100},f9={useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:"any",getFn:d9,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1},Ue=Object.freeze({...p9,...u9,...m9,...f9});cP=class{constructor({getFn:r=Ue.getFn,fieldNormWeight:t=Ue.fieldNormWeight}={}){this.norm=g9(t,3),this.getFn=r,this.isCreated=!1,this.docs=[],this.keys=[],this._keysMap={},this.setIndexRecords()}setSources(r=[]){this.docs=r}setIndexRecords(r=[]){this.records=r}setKeys(r=[]){this.keys=r,this._keysMap={},r.forEach((t,e)=>{this._keysMap[t.id]=e})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;let r=this.docs.length;this.records=new Array(r);let t=0;if(Vn(this.docs[0]))for(let e=0;e<r;e++){let n=this._createStringRecord(this.docs[e],e);n&&(this.records[t++]=n)}else for(let e=0;e<r;e++)this.records[t++]=this._createObjectRecord(this.docs[e],e);this.records.length=t,this.norm.clear()}add(r,t){if(!Number.isInteger(t)||t<0)throw new Error(rP);if(Vn(r)){let n=this._createStringRecord(r,t);return n&&this.records.push(n),n}let e=this._createObjectRecord(r,t);return this.records.push(e),e}removeAt(r){if(!Number.isInteger(r)||r<0)throw new Error(rP);for(let t=0,e=this.records.length;t<e;t+=1)if(this.records[t].i===r){this.records.splice(t,1);break}for(let t=0,e=this.records.length;t<e;t+=1)this.records[t].i>r&&(this.records[t].i-=1)}removeAll(r){let t=new Set;for(let n of r)Number.isInteger(n)&&n>=0&&t.add(n);if(t.size===0)return;this.records=this.records.filter(n=>!t.has(n.i));let e=Array.from(t).sort((n,i)=>n-i);for(let n of this.records){let i=0,o=e.length;for(;i<o;){let s=i+o>>>1;e[s]<n.i?i=s+1:o=s}n.i-=i}}getValueForItemAtKeyId(r,t){return r[this._keysMap[t]]}size(){return this.records.length}_createStringRecord(r,t){return!ji(r)||hx(r)?null:{v:r,i:t,n:this.norm.get(r)}}_createObjectRecord(r,t){let e={i:t,$:{}};for(let n=0,i=this.keys.length;n<i;n++){let o=this.keys[n],s=o.getFn?o.getFn(r):this.getFn(r,o.path);if(ji(s)){if(Tc(s)){let a=[];for(let l=0,c=s.length;l<c;l+=1){let d=s[l];if(ji(d)){if(Vn(d)){if(!hx(d)){let u={v:d,i:l,n:this.norm.get(d)};a.push(u)}}else if(ji(d.v)){let u=Vn(d.v)?d.v:tP(d.v);if(!hx(u)){let p={v:u,i:d.i,n:this.norm.get(u)};a.push(p)}}}}e.$[n]=a}else if(Vn(s)&&!hx(s)){let a={v:s,n:this.norm.get(s)};e.$[n]=a}}}return e}toJSON(){return{keys:this.keys.map(({getFn:r,...t})=>t),records:this.records}}};FB={\u0142:"l",\u0141:"L",\u0111:"d",\u0110:"D",\u00F8:"o",\u00D8:"O",\u0127:"h",\u0126:"H",\u0167:"t",\u0166:"T",\u0131:"i",\u00DF:"ss"},C9=new RegExp("["+Object.keys(FB).join("")+"]","g"),Vv=typeof String.prototype.normalize=="function"?r=>r.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,"").replace(C9,t=>FB[t]):r=>r,uP=class{constructor(r,{location:t=Ue.location,threshold:e=Ue.threshold,distance:n=Ue.distance,includeMatches:i=Ue.includeMatches,findAllMatches:o=Ue.findAllMatches,minMatchCharLength:s=Ue.minMatchCharLength,isCaseSensitive:a=Ue.isCaseSensitive,ignoreDiacritics:l=Ue.ignoreDiacritics,ignoreLocation:c=Ue.ignoreLocation}={}){if(this.options={location:t,threshold:e,distance:n,includeMatches:i,findAllMatches:o,minMatchCharLength:s,isCaseSensitive:a,ignoreDiacritics:l,ignoreLocation:c},r=a?r:r.toLowerCase(),r=l?Vv(r):r,this.pattern=r,this.chunks=[],!this.pattern.length)return;let d=(p,m)=>{this.chunks.push({pattern:p,alphabet:w9(p),startIndex:m})},u=this.pattern.length;if(u>32){let p=0,m=u%32,h=u-m;for(;p<h;)d(this.pattern.substr(p,32),p),p+=32;if(m){let g=u-32;d(this.pattern.substr(g),g)}}else d(this.pattern,0)}searchIn(r){let{isCaseSensitive:t,ignoreDiacritics:e,includeMatches:n}=this.options;if(r=t?r:r.toLowerCase(),r=e?Vv(r):r,this.pattern===r){if(r.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};let h={isMatch:!0,score:0};return n&&(h.indices=[[0,r.length-1]]),h}let{location:i,distance:o,threshold:s,findAllMatches:a,minMatchCharLength:l,ignoreLocation:c}=this.options,d=[],u=0,p=!1;this.chunks.forEach(({pattern:h,alphabet:g,startIndex:v})=>{let{isMatch:b,score:y,indices:C}=b9(r,h,g,{location:i+v,distance:o,threshold:s,findAllMatches:a,minMatchCharLength:l,includeMatches:n,ignoreLocation:c});b&&(p=!0),u+=y,b&&C&&d.push(...C)});let m={isMatch:p,score:p?u/this.chunks.length:1};return p&&n&&(m.indices=dP(d)),m}},x9=new Set(["fuzzy","include"]);nP=[{type:"exact",multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:r=>({type:"exact",search(t){let e=t===r;return{isMatch:e,score:e?0:1,indices:[0,r.length-1]}}})},{type:"include",multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:r=>({type:"include",search(t){let e=0,n,i=[],o=r.length;for(;(n=t.indexOf(r,e))>-1;)e=n+o,i.push([n,e-1]);let s=!!i.length;return{isMatch:s,score:s?0:1,indices:i}}})},{type:"prefix-exact",multiRegex:/^\^"(.*)"$/,singleRegex:/^\^(.*)$/,create:r=>({type:"prefix-exact",search(t){let e=t.startsWith(r);return{isMatch:e,score:e?0:1,indices:[0,r.length-1]}}})},{type:"inverse-prefix-exact",multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:r=>({type:"inverse-prefix-exact",search(t){let e=!t.startsWith(r);return{isMatch:e,score:e?0:1,indices:[0,t.length-1]}}})},{type:"inverse-suffix-exact",multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:r=>({type:"inverse-suffix-exact",search(t){let e=!t.endsWith(r);return{isMatch:e,score:e?0:1,indices:[0,t.length-1]}}})},{type:"suffix-exact",multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:r=>({type:"suffix-exact",search(t){let e=t.endsWith(r);return{isMatch:e,score:e?0:1,indices:[t.length-r.length,t.length-1]}}})},{type:"inverse-exact",multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:r=>({type:"inverse-exact",search(t){let e=t.indexOf(r)===-1;return{isMatch:e,score:e?0:1,indices:[0,t.length-1]}}})},{type:"fuzzy",multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(r,t={})=>{let e=new uP(r,{location:t.location??Ue.location,threshold:t.threshold??Ue.threshold,distance:t.distance??Ue.distance,includeMatches:t.includeMatches??Ue.includeMatches,findAllMatches:t.findAllMatches??Ue.findAllMatches,minMatchCharLength:t.minMatchCharLength??Ue.minMatchCharLength,isCaseSensitive:t.isCaseSensitive??Ue.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics??Ue.ignoreDiacritics,ignoreLocation:t.ignoreLocation??Ue.ignoreLocation});return{type:"fuzzy",search(n){return e.searchIn(n)}}}}],EB=nP.length,T9="\0",_9="|";A9=class{constructor(r,{isCaseSensitive:t=Ue.isCaseSensitive,ignoreDiacritics:e=Ue.ignoreDiacritics,includeMatches:n=Ue.includeMatches,minMatchCharLength:i=Ue.minMatchCharLength,ignoreLocation:o=Ue.ignoreLocation,findAllMatches:s=Ue.findAllMatches,location:a=Ue.location,threshold:l=Ue.threshold,distance:c=Ue.distance}={}){this.query=null,this.options={isCaseSensitive:t,ignoreDiacritics:e,includeMatches:n,minMatchCharLength:i,findAllMatches:s,ignoreLocation:o,location:a,threshold:l,distance:c},r=t?r:r.toLowerCase(),r=e?Vv(r):r,this.pattern=r,this.query=S9(this.pattern,this.options)}static condition(r,t){return t.useExtendedSearch}searchIn(r){let t=this.query;if(!t)return{isMatch:!1,score:1};let{includeMatches:e,isCaseSensitive:n,ignoreDiacritics:i}=this.options;r=n?r:r.toLowerCase(),r=i?Vv(r):r;let o=0,s=[],a=0,l=!1;for(let c=0,d=t.length;c<d;c+=1){let u=t[c];s.length=0,o=0,l=!1;for(let p=0,m=u.length;p<m;p+=1){let h=u[p],{isMatch:g,indices:v,score:b}=h.search(r);if(g)o+=1,a+=b,E9(h.type)&&(l=!0),e&&(x9.has(h.type)?s.push(...v):s.push(v));else{a=0,o=0,s.length=0,l=!1;break}}if(o){let p={isMatch:!0,score:a/o};return l&&(p.hasInverse=!0),e&&(p.indices=dP(s)),p}}return{isMatch:!1,score:1}}},iP=[];bx={AND:"$and",OR:"$or"},oP={PATH:"$path",PATTERN:"$val"},sP=r=>!!(r[bx.AND]||r[bx.OR]),I9=r=>!!r[oP.PATH],P9=r=>!Tc(r)&&AB(r)&&!sP(r),_B=r=>({[bx.AND]:Object.keys(r).map(t=>({[t]:r[t]}))});F9=class{constructor(r,t){this.limit=r,this.heap=[],this.comparator=t}get size(){return this.heap.length}insert(r){this.size<this.limit?(this.heap.push(r),this._bubbleUp(this.size-1)):this.comparator(r,this.heap[0])<0&&(this.heap[0]=r,this._sinkDown(0))}extractSorted(){return this.heap.sort(this.comparator)}_bubbleUp(r){let t=this.heap;for(;r>0;){let e=r-1>>1;if(this.comparator(t[r],t[e])<=0)break;let n=t[r];t[r]=t[e],t[e]=n,r=e}}_sinkDown(r){let t=this.heap,e=t.length,n=r;do{r=n;let i=2*r+1,o=2*r+2;if(i<e&&this.comparator(t[i],t[n])>0&&(n=i),o<e&&this.comparator(t[o],t[n])>0&&(n=o),n!==r){let s=t[r];t[r]=t[n],t[n]=s}}while(n!==r)}};O9=/[\p{L}\p{M}\p{N}_]+/gu,kB=new WeakSet;N9=class{static condition(r,t){return t.useTokenSearch}constructor(r,t){this.options=t,this.analyzer=lP({isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,tokenize:t.tokenize});let e=this.analyzer.tokenize(r),{df:n,fieldCount:i}=t._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(let o of e){this.termSearchers.push(new uP(o,{location:t.location,threshold:t.threshold,distance:t.distance,includeMatches:t.includeMatches,findAllMatches:t.findAllMatches,minMatchCharLength:t.minMatchCharLength,isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,ignoreLocation:!0}));let s=n.get(o)||0,a=Math.log(1+(i-s+.5)/(s+.5));this.idfWeights.push(a)}this.combineAll=t.tokenMatch==="all",this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(r){if(!this.termSearchers.length)return{isMatch:!1,score:1};let t=[],e=0,n=0,i=0,o=0,s=this.combineAll&&!this.useMask?new Set:null;for(let c=0;c<this.termSearchers.length;c++){let d=this.termSearchers[c].searchIn(r),u=this.idfWeights[c];n+=u,d.isMatch&&(i++,e+=u*(1-d.score),d.indices&&t.push(...d.indices),this.combineAll&&(this.useMask?o|=1<<c:s.add(c)))}if(i===0)return{isMatch:!1,score:1};let a=n>0?1-e/n:0,l={isMatch:!0,score:Math.max(.001,a)};return this.options.includeMatches&&t.length&&(l.indices=dP(t)),this.combineAll&&(this.useMask?l.matchedMask=o:l.matchedTerms=s,l.termCount=this.numTerms),l}};_c=class{constructor(r,t,e){this.options={...Ue,...t},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new c9(this.options.keys),this._docs=r,this._myIndex=null,this._invertedIndex=null,this.setCollection(r,e),this._lastQuery=null,this._lastSearcher=null}_getSearcher(r){if(this._lastQuery===r)return this._lastSearcher;let t=yx(r,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=r,this._lastSearcher=t,t}setCollection(r,t){if(this._docs=r,t&&!(t instanceof cP))throw new Error(n9);if(this._myIndex=t||$B(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){let e=lP({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=V9(this._myIndex.records,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}add(r){if(!ji(r))return;this._docs.push(r);let t=this._myIndex.add(r,this._docs.length-1);if(this._invertedIndex&&t){let e=lP({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});B9(this._invertedIndex,t,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}remove(r=()=>!1){let t=[],e=[];for(let n=0,i=this._docs.length;n<i;n+=1)r(this._docs[n],n)&&(t.push(this._docs[n]),e.push(n));if(e.length){this._invertedIndex&&SB(this._invertedIndex,e);let n=new Set(e);this._docs=this._docs.filter((i,o)=>!n.has(o)),this._myIndex.removeAll(e),this._invalidateSearcherCache()}return t}removeAt(r){if(!Number.isInteger(r)||r<0||r>=this._docs.length)throw new Error(rP);this._invertedIndex&&SB(this._invertedIndex,[r]);let t=this._docs.splice(r,1)[0];return this._myIndex.removeAt(r),this._invalidateSearcherCache(),t}_invalidateSearcherCache(){this._lastQuery=null,this._lastSearcher=null}getIndex(){return this._myIndex}_normalizedKeys(){return this._myIndex.keys.map(r=>this._keyStore.get(r.id)||r)}search(r,t){let{limit:e=-1}=t||{},{includeMatches:n,includeScore:i,shouldSort:o,sortFn:s,ignoreFieldNorm:a}=this.options;if(Vn(r)&&!r.trim()){let p=this._docs.map((m,h)=>({item:m,refIndex:h}));return gx(e)&&e>-1&&(p=p.slice(0,e)),p}let l=o&&gx(e)&&e>0&&Vn(r),c=s,d=(p,m)=>c(p,m)||p.idx-m.idx,u;if(l){let p=new F9(e,d);Vn(this._docs[0])?this._searchStringList(r,{heap:p,ignoreFieldNorm:a}):this._searchObjectList(r,{heap:p,ignoreFieldNorm:a}),u=p.extractSorted()}else u=Vn(r)?Vn(this._docs[0])?this._searchStringList(r):this._searchObjectList(r):this._searchLogical(r),$9(u,{ignoreFieldNorm:a}),o&&u.sort(Vn(r)?d:c),gx(e)&&e>-1&&(u=u.slice(0,e));return R9(u,this._docs,{includeMatches:n,includeScore:i})}_searchStringList(r,{heap:t,ignoreFieldNorm:e}={}){let n=this._getSearcher(r),i=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:o}=this._myIndex,s=t?null:[];return o.forEach(({v:a,i:l,n:c})=>{if(!ji(a))return;let d=n.searchIn(a);if(d.isMatch){let u={score:d.score,value:a,norm:c,indices:d.indices};i&&(u.matchedMask=d.matchedMask,u.matchedTerms=d.matchedTerms,u.termCount=d.termCount);let p=[u];if(!i||this._coversAllTokens(p)){let m={item:a,idx:l,matches:p};t?(m.score=aP(m.matches,{ignoreFieldNorm:e}),t.insert(m)):s.push(m)}}}),s}_searchLogical(r){let t=MB(r,this.options),e=this._normalizedKeys(),n=(a,l,c)=>{if(!("children"in a)){let{keyId:m,searcher:h}=a,g;return m===null?(g=[],e.forEach((v,b)=>{g.push(...this._findMatches({key:v,value:l[b],searcher:h}))})):g=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(l,m),searcher:h}),g&&g.length?[{idx:c,item:l,matches:g}]:[]}let{children:d,operator:u}=a,p=[];for(let m=0,h=d.length;m<h;m+=1){let g=d[m],v=n(g,l,c);if(v.length)p.push(...v);else if(u===bx.AND)return[]}return p},i=this._myIndex.records,o=new Map,s=[];return i.forEach(({$:a,i:l})=>{if(ji(a)){let c=n(t,a,l);c.length&&(o.has(l)||(o.set(l,{idx:l,item:a,matches:[]}),s.push(o.get(l))),c.forEach(({matches:d})=>{o.get(l).matches.push(...d)}))}}),s}_searchObjectList(r,{heap:t,ignoreFieldNorm:e}={}){let n=this._getSearcher(r),i=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:o}=this._myIndex,s=this._normalizedKeys(),a=t?null:[];return o.forEach(({$:l,i:c})=>{if(!ji(l))return;let d=[],u=!1,p=!1;if(s.forEach((m,h)=>{let g=this._findMatches({key:m,value:l[h],searcher:n});g.length?(d.push(...g),g[0].hasInverse&&(p=!0)):u=!0}),!(p&&u)&&d.length&&(!i||this._coversAllTokens(d))){let m={idx:c,item:l,matches:d};t?(m.score=aP(m.matches,{ignoreFieldNorm:e}),t.insert(m)):a.push(m)}}),a}_findMatches({key:r,value:t,searcher:e}){if(!ji(t))return[];let n=[];if(Tc(t))t.forEach(({v:i,i:o,n:s})=>{if(!ji(i))return;let a=e.searchIn(i);if(a.isMatch){let l={score:a.score,key:r,value:i,idx:o,norm:s,indices:a.indices,hasInverse:a.hasInverse};a.termCount!==void 0&&(l.matchedMask=a.matchedMask,l.matchedTerms=a.matchedTerms,l.termCount=a.termCount),n.push(l)}});else{let{v:i,n:o}=t,s=e.searchIn(i);if(s.isMatch){let a={score:s.score,key:r,value:i,norm:o,indices:s.indices,hasInverse:s.hasInverse};s.termCount!==void 0&&(a.matchedMask=s.matchedMask,a.matchedTerms=s.matchedTerms,a.termCount=s.termCount),n.push(a)}}return n}_coversAllTokens(r){let t=r.length?r[0].termCount:void 0;if(t===void 0)return!0;if(t<=31){let n=0;for(let i=0;i<r.length;i++)n|=r[i].matchedMask||0;return n===2**t-1}let e=new Set;for(let n=0;n<r.length;n++){let i=r[n].matchedTerms;if(i)for(let o of i)e.add(o)}return e.size===t}};_c.version="7.5.0";_c.createIndex=$B;_c.parseIndex=v9;_c.config=Ue;_c.match=function(r,t,e){if(e&&e.useTokenSearch)throw new Error(l9);return yx(r,{...Ue,...e}).searchIn(t)};_c.parseQuery=MB;pP(A9);pP(N9);_c.use=function(...r){r.forEach(t=>pP(t))};kc=_c});function q9(r){if(!r)return[];let t=[];for(let[e,n]of Object.entries(r)){let i=e.toLowerCase();if(i!=="alias"&&i!=="aliases")continue;let o=typeof n=="string"?n.split(","):n;Array.isArray(o)&&t.push(...o.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean))}return t}function OB(r,t,e){let n=r.metadataCache.getFileCache(t),i=n?.frontmatter,o=q9(i),s=o.map(d=>Ht(d)),a=(n?.headings??[]).map(d=>NS(d.heading)),l=[];if(n?.blocks)for(let d of Object.values(n.blocks))d.id&&l.push(d.id);let c=n?.tags?.map(d=>d.tag)??[];if(i?.tags){let d=Array.isArray(i.tags)?i.tags:[i.tags];c.push(...d.filter(u=>typeof u=="string"))}return{path:t.path,pathNormalized:Ht(t.path),basename:t.basename,basenameNormalized:Ht(t.basename),aliases:o,aliasesNormalized:s,headings:a,blockIds:l,tags:c,modified:t.stat.mtime,openedAt:e,folder:t.parent?.path??""}}var DB=x(()=>{an()});function LB(r,t,e,n,i,o,s){let a=n;if(e.currentFolder&&r.folder===e.currentFolder&&(a+=i.boosts.sameFolder),r.openedAt&&(Date.now()-r.openedAt)/864e5<i.thresholds.recencyDays&&(a+=i.boosts.recency),e.currentFile&&o){let m=r.tags.filter(h=>o.tags.includes(h));m.length>0&&(a+=i.boosts.tagOverlap*Math.min(m.length,Math.abs(i.boosts.tagOverlapMax/i.boosts.tagOverlap)))}let l=Ht(t),c=s==="alias"&&r.aliases.length>0?r.aliasesNormalized.findIndex(m=>m.includes(l)):-1,d=c>=0?r.aliases[c].length:r.basename.length;if(s==="alias"){let m=Math.max(0,(d-i.penalties.titleLengthThreshold)*i.penalties.aliasLengthMultiplier),h=Math.min(i.penalties.aliasMaxPenalty,i.penalties.aliasMinPenalty+m);a+=h}d>i.penalties.titleLengthThreshold&&(a+=(d-i.penalties.titleLengthThreshold)*i.penalties.titleLengthMultiplier);let p=(c>=0?r.aliasesNormalized[c]:r.basenameNormalized).indexOf(l);return p>=0&&(a+=p*i.penalties.positionMultiplier),a}var Cx,mP=x(()=>{an();Cx={base:{basenameExact:-1e3,aliasExact:-900,basenamePrefix:-500,aliasPrefix:-500,substringBasename:-300,fuzzyMatch:0},boosts:{sameFolder:-.15,recency:-.1,tagOverlap:-.05,tagOverlapMax:-.2},penalties:{titleLengthThreshold:15,titleLengthMultiplier:.02,aliasMinPenalty:.05,aliasMaxPenalty:.6,aliasLengthMultiplier:.04,positionMultiplier:.05},thresholds:{recencyDays:1,fuzzyRelaxCount:5}}});var Bv,fP,z9,H9,NB,Mm,hP=x(()=>{Bv=require("obsidian");wx();DB();mP();mP();an();fP=class{constructor(t=100){this.cache=new Map;this.maxSize=t}peek(t){return this.cache.get(t)}set(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;this.cache.delete(n)}this.cache.set(t,e)}clear(){this.cache.clear()}},z9=20,H9=100,NB=/\w/,Mm=class r{constructor(t,e){this.fileMap=new Map;this.recentFiles=new fP;this.unresolvedLinks=[];this.unresolvedLinksDirty=!0;this.isIndexing=!1;this.indexPromise=null;this.reindexTimeout=null;this.fuseUpdateTimeout=null;this.pendingFuseUpdates=new Map;this.reindexBuffer=null;this.effectiveWeights=Cx;this.app=t,this.plugin=e;let n={keys:[{name:"basenameNormalized",weight:.8},{name:"aliasesNormalized",weight:.6},{name:"pathNormalized",weight:.2}],ignoreLocation:!0,findAllMatches:!0,shouldSort:!1,includeScore:!0,includeMatches:!0};this.fuseStrict=new kc([],{...n,threshold:.2}),this.fuseRelaxed=new kc([],{...n,threshold:.4}),this.setupEventListeners(),this.effectiveWeights=Cx}static getInstance(t,e){return r.instance||(r.instance=new r(t,e)),r.instance}static getInstanceIfExists(){return r.instance??void 0}getLastOpenedAt(t){return this.recentFiles.peek(t)}setupEventListeners(){this.plugin.registerEvent(this.app.workspace.on("file-open",t=>{if(t){this.recentFiles.set(t.path,Date.now());let e=this.fileMap.get(t.path);e&&(e.openedAt=Date.now())}})),this.plugin.registerEvent(this.app.metadataCache.on("changed",t=>{t instanceof Bv.TFile&&t.extension==="md"&&this.updateFile(t)})),this.plugin.registerEvent(this.app.metadataCache.on("resolved",()=>{this.unresolvedLinksDirty=!0,this.fileMap.size===0&&this.scheduleReindex()})),this.plugin.registerEvent(this.app.vault.on("create",t=>{t instanceof Bv.TFile&&t.extension==="md"&&this.addFile(t)})),this.plugin.registerEvent(this.app.vault.on("delete",t=>{t instanceof Bv.TFile&&this.removeFile(t)})),this.plugin.registerEvent(this.app.vault.on("rename",(t,e)=>{t instanceof Bv.TFile&&t.extension==="md"&&(this.removeFileByPath(e),this.addFile(t))}))}async ensureIndexed(){if(this.isIndexing&&this.indexPromise)return this.indexPromise;if(this.fileMap.size===0)return this.reindex()}scheduleReindex(){this.reindexTimeout!==null&&window.clearTimeout(this.reindexTimeout),this.reindexTimeout=window.setTimeout(()=>{this.reindex()},500)}async reindex(){if(this.isIndexing&&this.indexPromise)return this.indexPromise;this.isIndexing=!0,this.indexPromise=this.performReindex();try{await this.indexPromise}finally{this.isIndexing=!1,this.indexPromise=null}}async performReindex(){let t=new Map;this.reindexBuffer=t;try{let e=this.app.vault.getMarkdownFiles(),n=new Map;await(async(o,s=50)=>{for(let a=0;a<o.length;a+=s){let l=o.slice(a,a+s);for(let c of l){let d=this.createIndexedFile(c);n.set(c.path,d)}await new Promise(c=>window.setTimeout(c,0))}})(e),this.fileMap=n;for(let[o,s]of t)s.op==="remove"?this.fileMap.delete(o):s.file&&this.fileMap.set(o,this.createIndexedFile(s.file));this.updateFuseIndex(),this.updateUnresolvedLinks()}catch(e){try{this.updateFuseIndex()}catch{}throw e}finally{this.reindexBuffer=null}}createIndexedFile(t){return OB(this.app,t,this.recentFiles.peek(t.path))}addFile(t){this.upsertFile(t,"add")}updateFile(t){this.upsertFile(t,"update"),this.unresolvedLinksDirty=!0}upsertFile(t,e){this.fileMap.set(t.path,this.createIndexedFile(t)),this.scheduleFuseUpdate(t.path,e),this.reindexBuffer?.set(t.path,{op:"upsert",file:t})}removeFile(t){this.removeFileByPath(t.path)}removeFileByPath(t){this.fileMap.delete(t),this.scheduleFuseUpdate(t,"remove"),this.reindexBuffer?.set(t,{op:"remove"})}updateFuseIndex(){let t=Array.from(this.fileMap.values());this.fuseStrict.setCollection(t),this.fuseRelaxed.setCollection(t)}scheduleFuseUpdate(t,e){if(this.isIndexing)return;let n=this.pendingFuseUpdates.get(t);if(n==="add"&&e==="remove"){this.pendingFuseUpdates.delete(t);return}this.pendingFuseUpdates.set(t,n==="remove"&&e==="add"?"update":e),this.fuseUpdateTimeout!==null&&window.clearTimeout(this.fuseUpdateTimeout),this.fuseUpdateTimeout=window.setTimeout(()=>{this.processPendingFuseUpdates()},H9)}processPendingFuseUpdates(){if(this.pendingFuseUpdates.size!==0){if(this.isIndexing){this.pendingFuseUpdates.clear();return}if(this.pendingFuseUpdates.size>z9){this.updateFuseIndex(),this.pendingFuseUpdates.clear();return}for(let[t,e]of this.pendingFuseUpdates)for(let n of[this.fuseStrict,this.fuseRelaxed]){n.remove(o=>o.path===t);let i=e!=="remove"&&this.fileMap.get(t);i&&n.add(i)}this.pendingFuseUpdates.clear()}}updateUnresolvedLinks(){let t=this.app.metadataCache.unresolvedLinks,e=new Set;for(let n in t)for(let i in t[n])e.add(i);this.unresolvedLinks=Array.from(e,n=>{let i=n.lastIndexOf("/"),o=n.slice(i+1);return{path:n,pathNormalized:Ht(n),basename:o,basenameNormalized:Ht(o),aliases:[],aliasesNormalized:[],headings:[],blockIds:[],tags:[],modified:0,folder:i===-1?"":n.slice(0,i)}}),this.unresolvedLinksDirty=!1}search(t,e={},n=50){if(this.unresolvedLinksDirty&&this.updateUnresolvedLinks(),t.includes("#"))return this.searchWithHeadings(t,e,n);let i=Ht(t),o=this.matchFiles(t,e,n);if(t.length>=2){let s=this.effectiveWeights.base;for(let a of this.unresolvedLinks){if(!a.pathNormalized.includes(i))continue;let l=i.includes("/")?a.pathNormalized:a.basenameNormalized,c=l.indexOf(i),d=c===0?l===i?s.basenameExact:s.basenamePrefix:c>0&&!NB.test(l[c-1])?s.substringBasename:s.fuzzyMatch;o.push({file:a,score:this.calculateScore(a,t,e,d),matchType:"unresolved",displayText:a.path})}}return o.sort((s,a)=>s.score-a.score).slice(0,n)}calculateScore(t,e,n,i,o){return LB(t,e,n,i,this.effectiveWeights,n.currentFile?this.fileMap.get(n.currentFile.path):void 0,o)}searchWithHeadings(t,e,n){let[i,o]=t.split("#"),s=Ht(o??""),a=[];if(i===""){let l=0,c=200,d=Array.from(this.fileMap.values());for(let u of d){if(l>=c)break;for(let p of u.headings){if(l>=c)break;Ht(p).includes(s)&&(a.push({file:u,score:this.calculateScore(u,t,e,.1),matchType:"heading",displayText:`${u.basename}#${p}`}),l++)}}}else{let l=this.searchFiles(i,e,n);if(l.length===0)return[];for(let c of l)for(let d of c.file.headings)Ht(d).includes(s)&&a.push({file:c.file,score:c.score+.05,matchType:"heading",displayText:`${c.file.basename}#${d}`})}return a.sort((l,c)=>l.score-c.score).slice(0,n)}searchFiles(t,e,n){return this.matchFiles(t,e,n,{...this.effectiveWeights.base,basenameExact:-1e3,basenamePrefix:-500,aliasPrefix:-500,substringBasename:-300}).sort((i,o)=>i.score-o.score).slice(0,n)}matchFiles(t,e,n,i=this.effectiveWeights.base){let o=[],s=Ht(t),a=new Set,l=Array.from(this.fileMap.values()),c=(u,p,m,h)=>{a.has(u.path)||(o.push({file:u,score:this.calculateScore(u,t,e,p,m),matchType:m,displayText:h}),a.add(u.path))};for(let u of l)u.basenameNormalized===s&&c(u,i.basenameExact,"exact",u.basename);for(let u of l){let p=u.aliasesNormalized.indexOf(s);p!==-1&&c(u,i.aliasExact,"alias",u.aliases[p])}for(let u of l)u.basenameNormalized.startsWith(s)&&c(u,i.basenamePrefix,"fuzzy",u.basename);for(let u of l){let p=u.aliasesNormalized.findIndex(m=>m.startsWith(s));p!==-1&&c(u,i.aliasPrefix,"alias",u.aliases[p])}for(let u of l){let p=u.basenameNormalized.indexOf(s);p>0&&!NB.test(u.basenameNormalized[p-1])&&c(u,i.substringBasename,"fuzzy",u.basename)}let d=this.fuseStrict.search(s,{limit:n*2});d.length<this.effectiveWeights.thresholds.fuzzyRelaxCount&&(d=this.fuseRelaxed.search(s,{limit:n*2}));for(let u of d){if(!u||!u.item||!u.item.path||a.has(u.item.path))continue;let p=(u.matches??[]).find(v=>v.key==="aliasesNormalized"),m=!!p,h=m?"alias":"fuzzy",g=u.item.basename;if(m){let v=typeof p?.value=="string"?p.value:void 0,b=v?u.item.aliasesNormalized.findIndex(y=>y===v):u.item.aliasesNormalized.findIndex(y=>y.includes(s));b>=0&&(g=u.item.aliases[b])}c(u.item,(u.score??.5)+i.fuzzyMatch,h,g)}return o}getFile(t){return this.fileMap.get(t)}getHeadings(t){return t.headings}getBlockIds(t){return t.blockIds}getIndexedFileCount(){return this.fileMap.size}}});function W9(r,t){let e=At(r,"span");switch(e.classList.add("qa-suggestion-pill"),t){case"alias":return e.classList.add("qa-alias-pill"),e.textContent="alias",e;case"heading":return e.classList.add("qa-heading-pill"),e.textContent="H",e;case"block":return e.classList.add("qa-block-pill"),e.textContent="^",e;case"unresolved":return e.classList.add("qa-unresolved-pill"),e.textContent="unresolved",e;default:return null}}var xx,Rm,gP=x(()=>{Ms();xx=require("obsidian");Le();hP();an();ss();Ko();Rm=class extends Er{constructor(e,n,i){super(e,n);this.app=e;this.inputEl=n;this.lastInput="";this.sourcePathOverride=i?.sourcePath,this.fileIndex=Mm.getInstance(e,Wr()),this.fileIndex.ensureIndexed()}normalizeFolderPath(e){return!e||e==="/"?"":e.replace(/\/+$/,"")}getSourcePath(){return this.sourcePathOverride??this.app.workspace.getActiveFile()?.path??""}getSourceFolder(){let e=this.getSourcePath();if(!e)return"";let n=this.app.fileManager.getNewFileParent(e);return this.normalizeFolderPath(n?.path)}resolveRelative(e,n){let i=this.normalizeFolderPath(e),o=n;for(o.startsWith("./")&&(o=o.slice(2));o.startsWith("../");){let s=i.split("/");if(!i||s.length===0||s.length===1&&s[0]==="")break;s.pop(),i=s.join("/"),o=o.slice(3)}return{folder:this.normalizeFolderPath(i),query:o}}getSuggestions(e){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=e.slice(0,n),o=vD.exec(i);if(!o)return[];let s=o[1];if(this.lastInput=s,s.includes("#^"))return this.getBlockSuggestions(s);if(s.indexOf("#")>0)return this.getHeadingSuggestions(s);if(s.startsWith("./")||s.startsWith("../"))return this.getRelativePathSuggestions(s);if(i.includes("![["))return this.getAttachmentSuggestions(s);let c=this.getSourceFolder(),d=this.app.workspace.getActiveFile(),u={currentFile:this.sourcePathOverride?void 0:d??void 0,currentFolder:c};return this.fileIndex.search(s,u,50)}getHeadingSuggestions(e){let[n,i]=e.split("#"),o=n.trim()==="",s=Ht(i??""),a=[];if(o){let c=this.app.workspace.getActiveFile();if(c){let d=this.fileIndex.getFile(c.path);d&&(a=[d])}}else a=this.fileIndex.searchFiles(n,{},1).map(c=>c.file);if(a.length===0)return[];let l=[];for(let c of a){let u=this.fileIndex.getHeadings(c).filter(p=>i===""||Ht(p).includes(s)).slice(0,20);for(let p of u)l.push({file:c,score:0,matchType:"heading",displayText:o?`#${p}`:`${c.basename}#${p}`})}return l}getBlockSuggestions(e){let[n,i]=e.split("#^"),o=Ht(i??""),s=this.fileIndex.searchFiles(n,{},1);if(s.length===0)return[];let a=s[0].file;return this.fileIndex.getBlockIds(a).filter(c=>i===""||Ht(c).includes(o)).slice(0,20).map(c=>({file:a,score:0,matchType:"block",displayText:`${a.basename}#^${c}`}))}getRelativePathSuggestions(e){let n=this.getSourceFolder(),{folder:i,query:o}=this.resolveRelative(n,e);if(o)return this.fileIndex.search(o,{currentFolder:i},20);let s=this.fileIndex.search("",{currentFolder:i},50),a=l=>this.normalizeFolderPath(l||"");return s.filter(l=>a(l.file.folder)===a(i))}getAttachmentSuggestions(e){let n=this.app.vault.getFiles(),i=["png","jpg","jpeg","gif","svg","pdf","mp4","webm","mov","canvas"],o=Ht(e);return n.filter(a=>i.includes(a.extension.toLowerCase())&&(e===""||Ht(a.basename).includes(o))).slice(0,20).map(a=>({file:{path:a.path,pathNormalized:Ht(a.path),basename:a.basename,basenameNormalized:Ht(a.basename),aliases:[],aliasesNormalized:[],headings:[],blockIds:[],tags:[],modified:a.stat.mtime,folder:this.normalizeFolderPath(a.parent?.path||"")},score:0,matchType:"exact",displayText:a.name}))}renderSuggestion(e,n){let{file:i,matchType:o,displayText:s}=e;n.classList.add("qaFileSuggestionItem"),n.classList.add(`qa-suggest-${o}`);let a=s,l="",c=!1,d="";switch(o){case"exact":case"fuzzy":a=i.basename,l=i.path;break;case"alias":a=s,l=i.path;break;case"heading":{let[g,v]=s.split("#"),b=this.lastInput.includes("#")?this.lastInput.split("#")[1]:"",y=Ht(b??"");b&&Ht(v).includes(y)?(a=v,c=!0,d=b):a=v,l=g;break}case"block":{let[g,v]=s.split("#^");a=v,l=g;break}case"unresolved":a=s,l="Unresolved link";break}let u=At(n,"div");u.className="qa-suggestion-content";let p=At(n,"span");p.className="suggestion-main-text",c?this.renderMatch(p,a,d):p.textContent=a,u.appendChild(p);let m=W9(n,o);m&&u.appendChild(m);let h=At(n,"span");h.className="suggestion-sub-text",h.textContent=l,n.replaceChildren(u,h),this.addHoverTooltip(n,i)}open(e,n){if(super.open(e,n),!this.scrollListener){let i=Bi(this.inputEl),o=()=>this.hideTooltip();i.addEventListener("scroll",o,{passive:!0}),this.scrollListener=o,this.scrollListenerDocument=i}}hideTooltip(){let e=Bi(this.inputEl);this.tooltipTimeout!==void 0&&(window.clearTimeout(this.tooltipTimeout),this.tooltipTimeout=void 0),e.querySelector(".qa-file-tooltip")?.remove()}addHoverTooltip(e,n){let i=Bi(e);e.addEventListener("mouseenter",()=>{this.hideTooltip(),this.tooltipTimeout=window.setTimeout(()=>{let o=this.createTooltip(n);o&&(i.body.appendChild(o),this.positionTooltip(o,e))},200)}),e.addEventListener("mouseleave",()=>this.hideTooltip()),e.addEventListener("blur",()=>this.hideTooltip())}createTooltip(e){let n=this.app.vault.getAbstractFileByPath(e.path);if(!n||!(n instanceof xx.TFile))return null;let i=this.inputEl,o=At(i,"div");o.className="qa-file-tooltip";let s=At(i,"div");s.className="qa-tooltip-header",s.textContent=n.basename;let a=At(i,"div");a.className="qa-tooltip-content";let l=At(i,"div");l.textContent=`Path: ${n.path}`;let c=At(i,"div");return c.textContent=`Modified: ${new Date(n.stat.mtime).toLocaleDateString()}`,a.append(l,c),o.append(s,a),o}positionTooltip(e,n){let i=n.getBoundingClientRect();e.style.left=`${i.right+10}px`,e.style.top=`${i.top}px`}close(){this.hideTooltip(),this.scrollListener&&this.scrollListenerDocument&&(this.scrollListenerDocument.removeEventListener("scroll",this.scrollListener),this.scrollListener=void 0,this.scrollListenerDocument=void 0),super.close()}selectSuggestion(e){if(this.inputEl.selectionStart===null)return;let n=this.inputEl.selectionStart,i=this.lastInput.length,o=this.inputEl.value,s=0,c=this.inputEl.value.slice(n-this.lastInput.length-3,n-this.lastInput.length)==="![["||e.matchType==="unresolved"||e.matchType==="heading"||e.matchType==="block"?void 0:this.app.vault.getAbstractFileByPath(e.file.path);c instanceof xx.TFile?s=this.makeLinkObsidianMethod(c,o,n,i,e.matchType==="alias"?e.displayText:void 0):s=this.makeLinkManually(o,e.matchType==="unresolved"?e.displayText.replace(/.md$/,""):e.displayText,n,i),this.inputEl.trigger("input"),this.close(),this.inputEl.setSelectionRange(s,s)}makeLinkObsidianMethod(e,n,i,o,s){let a=this.app.vault.getAbstractFileByPath(e.path);if(!(a instanceof xx.TFile))return this.makeLinkManually(n,e.path,i,o);let l=this.app.fileManager.generateMarkdownLink(a,this.getSourcePath(),"",s??"");return this.inputEl.value=this.getNewInputValueForFileLink(n,l,i,o),i-o+l.length+2}makeLinkManually(e,n,i,o){return this.inputEl.value=this.getNewInputValueForFileName(e,n,i,o),i-o+n.length+2}getNewInputValueForFileLink(e,n,i,o){return`${e.slice(0,i-o-2)}${n}${e.slice(i)}`}getNewInputValueForFileName(e,n,i,o){return`${e.slice(0,i-o)}${n}]]${e.slice(i)}`}}});var VB,Ex,BB=x(()=>{wx();VB={threshold:.4,includeScore:!0,keys:[""]},Ex=class r{constructor(t,e){this.sortedTags=[];this.fuse=new kc([],VB);this.app=t,this.refresh(),e.registerEvent(this.app.metadataCache.on("resolved",()=>this.refresh()))}static getInstance(t,e){return r.instance||(r.instance=new r(t,e)),r.instance}refresh(){let t=this.app.metadataCache.getTags(),e=Object.keys(t);this.sortedTags=e.sort((n,i)=>n.length!==i.length?n.length-i.length:n.localeCompare(i)),this.fuse=new kc(this.sortedTags,VB)}getSortedTags(){return this.sortedTags}search(t){return this.fuse.search(t)}}});function G9(r,t){let e=r.slice(0,t),n=e.lastIndexOf("[[");return n===-1?!1:e.lastIndexOf("]]")<n}var Om,vP=x(()=>{Le();Ms();an();ss();BB();Om=class extends Er{constructor(e,n,i){super(e,n);this.app=e;this.inputEl=n;this.lastInput="";this.lastInputStart=0;this.lastInputLength=0;this.tagIndex=Ex.getInstance(e,Wr()),i?.refreshIndex!==!1&&this.tagIndex.refresh()}getSuggestions(e){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=e.slice(0,n),o=yD.exec(i);if(!o)return[];if(o.index===void 0)return[];if(G9(i,o.index))return[];let s=o[1];this.lastInput=s,this.lastInputStart=o.index,this.lastInputLength=o[0].length;let a=this.tagIndex.getSortedTags(),l=s.toLowerCase(),c=a.filter(m=>m.replace(/^#/,"").toLowerCase().startsWith(l)).slice(0,5),d=this.tagIndex.search(s).filter(m=>m.score!==void 0&&m.score<.8).map(m=>m.item).slice(0,10),u=new Set(c),p=[...c];for(let m of d)!u.has(m)&&p.length<15&&(p.push(m),u.add(m));return p}renderSuggestion(e,n){this.renderMatch(n,e,this.lastInput)}selectSuggestion(e){let n=this.inputEl;if(n.selectionStart===null)return;let i=this.lastInputStart,o=i+this.lastInputLength,s=e.startsWith("#")?e:`#${e}`;lw(n,i,o,s,{fromCompletion:!0}),this.close()}}});var Bn,Dm=x(()=>{Bn=class r{constructor(){this.drafts=new Map;this.executionScopes=[];this.MAX_ENTRIES=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}makeKey(t){return JSON.stringify({v:1,kind:t.kind,header:t.header,placeholder:t.placeholder??"",linkSourcePath:t.linkSourcePath??"",scopeId:t.scopeId??""})}get(t){let e=this.drafts.get(t);if(e)return e.timestamp=Date.now(),e.value}takeDraftForPrompt(t){if(this.executionScopes.some(e=>e.submittedDraftKeys.has(t))){this.clear(t);return}return this.get(t)}set(t,e){this.drafts.size>=this.MAX_ENTRIES&&!this.drafts.has(t)&&this.evictOldest(1),this.drafts.set(t,{value:e,timestamp:Date.now()})}handleSubmittedDraft(t,e){let n=this.executionScopes.at(-1);if(!n){this.clear(t);return}this.set(t,e),n.submittedDraftKeys.add(t)}beginExecutionScope(){let t={submittedDraftKeys:new Set,failed:!1};return this.executionScopes.push(t),t}commitExecutionScope(t){if(!(!this.endExecutionScope(t)||t.failed))for(let e of t.submittedDraftKeys)this.clear(e)}rollbackExecutionScope(t){this.endExecutionScope(t)&&this.markExecutionScopeFailed()}markExecutionScopeFailed(){for(let t of this.executionScopes)t.failed=!0}hasActiveExecutionScope(){return this.executionScopes.length>0}clear(t){this.drafts.delete(t);for(let e of this.executionScopes)e.submittedDraftKeys.delete(t)}clearAll(){this.drafts.clear(),this.executionScopes=[]}endExecutionScope(t){let e=this.executionScopes.indexOf(t);return e===-1?!1:(this.executionScopes.splice(e,1),!0)}evictOldest(t){let e=Array.from(this.drafts.entries()).sort(([,n],[,i])=>n.timestamp-i.timestamp).slice(0,t);for(let[n]of e)this.clear(n)}}});var Tx,UB=x(()=>{je();Dm();Tx=class{constructor(t,e){this.store=Bn.getInstance();this.initialValue="";this.didChange=!1;this.draftKey=this.store.makeKey(t),this.shouldPersist=e??(()=>U.getState().persistInputPromptDrafts)}hydrate(t){return this.initialValue=t,this.shouldPersist()?this.store.takeDraftForPrompt(this.draftKey)??t:t}markChanged(){this.didChange=!0}persist(t,e){if(this.shouldPersist()){if(e){this.store.handleSubmittedDraft(this.draftKey,t);return}if(this.didChange){if(!t.trim()||t===this.initialValue){this.store.clear(this.draftKey);return}this.store.set(this.draftKey,t)}}}}});function _x(r,t){if(r.focus(),t?.cursorAtEnd){let e=r.value.length;r.setSelectionRange(e,e);return}r.select()}var yP=x(()=>{});function qB(r,t,e){let n=t?.trim();if(!n)return;let i=r.createDiv({text:n,cls:"qa-prompt-context"});return i.setAttr("title",e?.trim()||n),i}var zB=x(()=>{});function HB(r){return(r??"").trim().replace(/\\/g,"/")}function j9(r){return r.startsWith("/")||/^[a-zA-Z]:/.test(r)}function Y9(r){return r.split("/").some(t=>/^\.\.[. ]*$/u.test(t))}function Ut(r){let t=HB(r);return t?j9(t)||Y9(t):!1}function kx(r){let t=HB(r);return!t||Ut(t)?!1:!t.split("/").some(e=>e.startsWith(".")&&!e.startsWith("..%"))}var Yi=x(()=>{});function ol(r){return Object.hasOwn(il,r)}function WB(r){let t=r.toLowerCase();return t==="jpeg"||Object.values(il).includes(t)}function K9(r){let t=e=>String(e).padStart(2,"0");return`${r.getFullYear()}-${t(r.getMonth()+1)}-${t(r.getDate())} ${t(r.getHours())}.${t(r.getMinutes())}.${t(r.getSeconds())}`}function X9(r){return r.replace(Q9,"").replace(/\s+/g," ").replace(/[. ]+$/g,"").trim()}function Sx(r){if(r.nameAfterNoteTitle){let t=X9(Ap(r.sourcePath));if(t.length>0&&zS(t))return`${t}.${r.extension}`}return`Clipboard image ${K9(r.now)}.${r.extension}`}function GB(r,t){if(!ol(r))throw new Error(`Unsupported clipboard image type: ${r}`);return Sx({extension:il[r],sourcePath:"",now:t,nameAfterNoteTitle:!1})}function jB(r){let t=r.split(/[\\/]/u).at(-1)??"",e=t.lastIndexOf("."),n=e>=0?t.slice(0,e):t;return zS(n)?n:null}async function bP(r,t,e,n,i){if(!ol(e))throw new Error(`Unsupported image type: ${e}`);let o=await r.fileManager.getAvailablePathForAttachment(i,n||void 0);if(Ut(o))throw new Error(`Refusing to save image outside the vault: '${o}'`);return r.vault.createBinary(o,t)}async function Ax(r,t,e,n,i){if(!ol(e))throw new Error(`Unsupported clipboard image type: ${e}`);let o=i?.nameAfterNoteTitle??U.getState().namePastedImagesAfterNoteTitle;return bP(r,t,e,n,Sx({extension:il[e],sourcePath:n,now:i?.now??new Date,nameAfterNoteTitle:o}))}function Ix(r,t,e){let n=r.fileManager.generateMarkdownLink(t,e);return n.startsWith("!")?n:`!${n}`}var il,Q9,Px=x(()=>{je();Ln();Xh();Yi();il=Object.assign(Object.create(null),{"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg"});Q9=/[/\\:*?"<>|#^[\]]/g});function J9(){let r=$x.filter(e=>e.inputEl.isConnected);return r.find(e=>document.activeElement!==null&&e.inputEl.contains(document.activeElement))??r.at(-1)??null}function Mx(r,t,e={}){let n=e.sourcePath??"",i=null,o=!1,s=!1,a=()=>{s=!0},l=()=>{s=!1},c=(b,y,C,w)=>{switch(C.kind){case"stand-down":return;case"take":if(y.preventDefault(),i){new Uv.Notice(b==="paste"?"QuickAdd: an image is still being saved \u2014 paste again in a moment.":"QuickAdd: an image is still being saved \u2014 drop again in a moment.");return}i=h(C.images,w).then(()=>{}).finally(()=>{i=null});return;default:return Fx(C)}},d=b=>{let y=b.clipboardData;if(!y||s)return;let C=new Date;c("paste",b,YB("paste",y,r),C)},u=b=>{if(s)return;let y=b.dataTransfer;!y||!QB(y)||(b.preventDefault(),y.dropEffect="copy",t.classList.add("qa-image-drop-target"))},p=()=>{t.classList.remove("qa-image-drop-target")},m=b=>{if(p(),s)return;let y=b.dataTransfer;if(!y||!QB(y))return;let C=new Date;c("drop",b,YB("drop",y,r),C)};async function h(b,y){let C=t.readOnly;t.readOnly=!0,t.setAttribute("aria-busy","true"),t.classList.add("qa-image-paste-busy");let w=[];try{for(let P of b){let _;switch(P.origin){case"vault":_=P.file;break;case"bytes":{let I=await P.file.arrayBuffer(),D=r7(P,y,n);_=await n7(()=>bP(r,I,P.mimeType,n,D));break}default:return Fx(P)}w.push(Ix(r,_,n))}}catch(P){S.logError(`Failed to save image: ${P instanceof Error?P.message:String(P)}`),new Uv.Notice("QuickAdd: failed to save image.")}finally{t.readOnly=C,t.removeAttribute("aria-busy"),t.classList.remove("qa-image-paste-busy")}if(w.length===0||o)return"";let T=w.join(t.tagName==="TEXTAREA"?`
|
||
`:" ");try{return i7(t,T),T}catch(P){return S.logError(`Failed to insert image link: ${P instanceof Error?P.message:String(P)}`),new Uv.Notice("QuickAdd: saved the image but could not insert its link."),""}}async function g(b){let y=new Date,C=t7(b);if(C.length===0)return S.logMessage("QuickAdd: image ingest skipped (no-images)."),"";if(i)return new Uv.Notice("QuickAdd: an image is still being saved \u2014 drop again in a moment."),S.logMessage("QuickAdd: image ingest skipped (busy)."),"";let w="";return i=(async()=>{w=await h(C,y)})().finally(()=>{i=null}),await i,w.length>0&&S.logMessage(`QuickAdd: ingested ${C.length} image(s) into the active prompt.`),w}t.addEventListener("paste",d),t.addEventListener("dragenter",u),t.addEventListener("dragover",u),t.addEventListener("dragleave",p),t.addEventListener("drop",m),t.addEventListener("compositionstart",a),t.addEventListener("compositionend",l);let v={isBusy:()=>i!==null,whenIdle:()=>i??Promise.resolve(),ingestFiles:g,detach:()=>{o=!0,p(),t.removeEventListener("paste",d),t.removeEventListener("dragenter",u),t.removeEventListener("dragover",u),t.removeEventListener("dragleave",p),t.removeEventListener("drop",m),t.removeEventListener("compositionstart",a),t.removeEventListener("compositionend",l);let b=$x.findIndex(y=>y.handle===v);b>=0&&$x.splice(b,1)}};return $x.push({handle:v,inputEl:t}),v}async function JB(r){let t=J9();if(!t)return S.logMessage("QuickAdd: image ingest skipped (no-active-prompt)."),{ok:!1,reason:"no-active-prompt"};if(t.handle.isBusy())return S.logMessage("QuickAdd: image ingest skipped (busy)."),{ok:!1,reason:"busy"};let e=await t.handle.ingestFiles(r);return e.length===0?{ok:!1,reason:"no-images"}:{ok:!0,inserted:e}}function YB(r,t,e){switch(r){case"paste":{if(t.getData("text/plain").length>0)return{kind:"stand-down"};let n=KB(t).map(i=>({origin:"bytes",...i,naming:{kind:"paste-name"}}));return n.length>0?{kind:"take",images:n}:{kind:"stand-down"}}case"drop":{let n=Z9(t,e);if(n.length>0)return{kind:"take",images:n};let i=KB(t).map(o=>({origin:"bytes",...o,naming:ZB(o)}));return i.length>0?{kind:"take",images:i}:{kind:"stand-down"}}default:return Fx(r)}}function Z9(r,t){let e=[];for(let n of r.getData("text/plain").split(/\r?\n/u)){let i=n.trim();if(i.length===0||i.toLowerCase().startsWith("file://")||Ut(i))continue;let o=t.vault.getAbstractFileByPath(i);e7(o)&&e.push({origin:"vault",file:o})}return e}function e7(r){return r!==null&&"extension"in r&&typeof r.extension=="string"&&WB(r.extension)}function KB(r){let t=[],e=0;for(let o of Array.from(r.items??[])){if(o.kind!=="file"||(e++,!ol(o.type)))continue;let s=o.getAsFile();s&&t.push({file:s,mimeType:o.type})}if(e>0&&t.length===e)return t;if(t.length===0){let o=[];for(let s of Array.from(r.files??[]))ol(s.type)&&o.push({file:s,mimeType:s.type});return o}let n=[...t],i=new Set(t.map(({file:o,mimeType:s})=>`${o.name}\0${o.size}\0${s}\0${o.lastModified}`));for(let o of Array.from(r.files??[])){if(!ol(o.type))continue;let s=`${o.name}\0${o.size}\0${o.type}\0${o.lastModified}`;i.has(s)||(i.add(s),n.push({file:o,mimeType:o.type}))}return n}function t7(r){return r.flatMap(t=>{if(!ol(t.type))return[];let e={file:t,mimeType:t.type};return[{origin:"bytes",...e,naming:ZB(e)}]})}function ZB(r){let t=jB(r.file.name);return t===null?{kind:"clipboard-stamp"}:{kind:"original-stem",stem:t}}function r7(r,t,e){switch(r.naming.kind){case"clipboard-stamp":return GB(r.mimeType,t);case"paste-name":return Sx({extension:il[r.mimeType],sourcePath:e,now:t,nameAfterNoteTitle:U.getState().namePastedImagesAfterNoteTitle});case"original-stem":return`${r.naming.stem}.${il[r.mimeType]}`;default:return Fx(r.naming)}}function QB(r){return Array.from(r.types??[]).some(t=>t==="Files"||ol(t))}function Fx(r){throw new Error(`Unexpected image intake value: ${String(r)}`)}function n7(r){let t=XB.then(r,r);return XB=t.catch(()=>{}),t}function i7(r,t){r.focus();let e=!1;try{e=r.ownerDocument.execCommand("insertText",!1,t)}catch{e=!1}if(e)return;let n=r.selectionStart??r.value.length,i=r.selectionEnd??n;r.setRangeText(t,n,i,"end"),r.dispatchEvent(new Event("input",{bubbles:!0}))}var Uv,$x,XB,Rx=x(()=>{Uv=require("obsidian");ye();Px();je();Yi();$x=[];XB=Promise.resolve()});function Un(r){let t=r.workspace.getActiveViewOfType(eU.MarkdownView);return t?.editor?t:null}function qv(r){return Un(r)?.editor.getSelection()??""}var eU,sl=x(()=>{eU=require("obsidian")});function tU(r,t){return!r.isComposing&&r.key.toLowerCase()===t.toLowerCase()&&r.shiftKey&&(r.ctrlKey||r.metaKey)}function rU(r){return tU(r,"Enter")}function iU(r){return tU(r,zv)}function oU(r){return r?`Look at the note without losing this draft. ${nU}`:"Look at the note without losing this draft."}function sU(){return`${nU} returns to the prompt`}var zv,nU,Hv=x(()=>{zv="E",nU="Ctrl/Cmd+Shift+E"});function aU(r,t,e,n){let i=Math.max(0,Math.min(t,r.length)),o=Math.max(i,Math.min(e,r.length));return{text:r.slice(0,i)+n+r.slice(o),cursor:i+n.length}}function lU(r,t=42){let e=r.slice(0,t*4),n=e.replace(/\s+/g," ").trim();return n.length<=t?e.length<r.length?`${n}\u2026`:n:`${n.slice(0,Math.max(0,t-1))}\u2026`}var wP=x(()=>{});function xP(r){CP.add(r)}function EP(r){CP.delete(r)}function cU(){return CP.size>0}var CP,TP=x(()=>{CP=new Set});function o7(r,t){let e=new Set([t]);return r.workspace.iterateAllLeaves?.(i=>{let o=i.view?.containerEl?.ownerDocument;o&&e.add(o)}),[...e]}var kn,ls,al,Ox=x(()=>{kn=require("obsidian");sl();Ko();Hv();wP();TP();ls=class ls{constructor(t,e){this.app=t;this.handle=e;this.chipEl=null;this.insertButton=null;this.compactChrome=!1;this.returnScope=null;this.selectionDocuments=[];this.selectionListener=null;this.chipKeyListener=null;this.hasSelection=null;this.selectionPreview=""}static isPeeking(){return ls.active!==null}static getActive(){return ls.active}static activate(t,e){let n=ls.active;if(n){let o=n.handle.title;n.cancel(),new kn.Notice(`QuickAdd: cancelled the peeked prompt "${o}".`)}let i=new ls(t,e);return ls.active=i,i.mount(),i}static discard(){ls.active?.destroy()}discard(){this.destroy()}resume(){if(!this.canReturnNow())return;let t=this.handle;this.destroy(),t.resume()}cancel(){let t=this.handle;this.destroy(),t.cancel()}insertSelectionAndResume(){if(!this.canReturnNow())return;let t=qv(this.app);if(!t){this.resume();return}let e=this.handle;this.destroy(),e.insertSelectionAndResume(t)}canReturnNow(){return cU()?(new kn.Notice("QuickAdd: close the open prompt before returning to the peeked one."),!1):!0}mount(){let n=(this.app.workspace.containerEl?.ownerDocument??document).body;this.compactChrome=kn.Platform.isPhone;let i=n.createDiv({cls:"qa-peek-chip"});i.setAttribute("role","status"),i.setAttribute("aria-live","polite"),this.compactChrome&&i.addClass("qa-peek-chip--compact","qa-peek-chip--top");let o=i.createDiv({cls:"qa-peek-chip-header"}),s=o.createSpan({cls:"qa-peek-chip-icon"});s.setAttribute("aria-hidden","true"),(0,kn.setIcon)(s,"eye");let a=o.createDiv({cls:"qa-peek-chip-titles"});a.createDiv({cls:"qa-peek-chip-title",text:this.compactChrome?this.handle.title:"QuickAdd is waiting"}),this.compactChrome||(a.createDiv({cls:"qa-peek-chip-subtitle",text:this.handle.title}),i.createEl("p",{cls:"qa-peek-chip-hint",text:"Look at the note, copy or select text, then come back. Your draft is still there."}));let l=i.createDiv({cls:"qa-peek-chip-actions"});this.insertButton=new kn.ButtonComponent(l).setButtonText(this.compactChrome?"Insert":"Insert selection").setCta().setTooltip("Drop the selected text into your draft and return").onClick(()=>this.insertSelectionAndResume()),this.insertButton.buttonEl.setAttribute("aria-label","Insert the selected text and return to QuickAdd"),new kn.ButtonComponent(l).setButtonText("Return").setTooltip("Go back to the prompt without inserting").onClick(()=>this.resume());let c=new kn.ButtonComponent(l).setTooltip("Discard this run").onClick(()=>this.cancel());if(c.buttonEl.addClass("qa-peek-chip-cancel"),c.buttonEl.setAttribute("aria-label","Cancel this run"),this.compactChrome){let d=At(c.buttonEl,"span");d.className="qa-peek-chip-cancel-icon",d.setAttribute("aria-hidden","true"),(0,kn.setIcon)(d,"x"),c.buttonEl.replaceChildren(d)}else c.setButtonText("Cancel");kn.Platform.isMobile||i.createEl("p",{cls:"qa-peek-chip-keys",text:sU()}),this.chipEl=i,this.refreshInsertButton(),this.listenForSelection(),this.listenForChipEscape(),this.pushReturnShortcut()}listenForSelection(){let t=(0,kn.debounce)(()=>this.refreshInsertButton(),100,!0);this.selectionListener=t,this.selectionDocuments=o7(this.app,this.chipEl?.ownerDocument??document);for(let e of this.selectionDocuments)e.addEventListener("selectionchange",t)}refreshInsertButton(){let t=this.insertButton;if(!t)return;let e=qv(this.app),n=e.length>0,i=n&&!this.compactChrome?lU(e):"";n===this.hasSelection&&i===this.selectionPreview||(this.hasSelection=n,this.selectionPreview=i,t.setDisabled(!n),t.buttonEl.classList.toggle("qa-peek-insert-ready",n),this.compactChrome||t.setButtonText(n?`Insert \u201C${i}\u201D`:"Insert selection"))}listenForChipEscape(){let t=this.chipEl;t&&(this.chipKeyListener=e=>{if(e.isComposing||e.key!=="Escape")return;let n=e.target;!(n instanceof Node)||!t.contains(n)||(e.preventDefault(),this.resume())},t.addEventListener("keydown",this.chipKeyListener))}pushReturnShortcut(){this.returnScope=new kn.Scope(this.app.scope),this.returnScope.register(["Mod","Shift"],zv,()=>(this.resume(),!1)),this.app.keymap.pushScope(this.returnScope)}destroy(){if(ls.active===this&&(ls.active=null),this.returnScope&&(this.app.keymap.popScope(this.returnScope),this.returnScope=null),this.chipKeyListener&&this.chipEl&&(this.chipEl.removeEventListener("keydown",this.chipKeyListener),this.chipKeyListener=null),this.selectionListener){for(let t of this.selectionDocuments)t.removeEventListener("selectionchange",this.selectionListener);this.selectionListener.cancel?.(),this.selectionListener=null}this.selectionDocuments=[],this.chipEl?.remove(),this.chipEl=null,this.insertButton=null}};ls.active=null;al=ls});function s7(r){Un(r)?.editor?.focus?.()}var dU,Lm,_P=x(()=>{sl();Ox();wP();TP();dU="qa-prompt-peek-hidden",Lm=class{constructor(t){this.host=t;this.peeking=!1;this.session=null}peek(){if(this.peeking)return;let t=this.host.getField();t&&this.host.setValue(t.value),this.host.persistDraft(),this.peeking=!0,this.hideModal(),this.session=al.activate(this.host.app,{title:this.host.title,resume:()=>this.resume(),cancel:()=>this.cancel(),insertSelectionAndResume:e=>this.insertSelectionAndResume(e)})}onHostOpened(){xP(this.host)}onHostClosed(){EP(this.host),this.peeking&&(this.peeking=!1,this.session?.discard(),this.session=null)}hideModal(){EP(this.host),this.host.containerEl.addClass(dU),this.host.app.keymap.popScope(this.host.scope),s7(this.host.app)}showModal(){this.host.app.keymap.pushScope(this.host.scope),this.host.containerEl.removeClass(dU),xP(this.host),this.host.getField()?.focus()}resume(){this.peeking&&(this.peeking=!1,this.session=null,this.showModal())}insertSelectionAndResume(t){if(!this.peeking)return;let e=this.host.getField();if(e){let n=e.selectionStart??e.value.length,i=e.selectionEnd??n,o=aU(e.value,n,i,t);e.value=o.text,e.setSelectionRange(o.cursor,o.cursor),this.host.setValue(o.text)}else this.host.setValue(this.host.getValue()+t);this.host.markDraftChanged(),this.host.persistDraft(),this.resume()}cancel(){this.peeking&&(this.peeking=!1,this.session=null,this.host.app.keymap.pushScope(this.host.scope),this.host.close())}}});function uU(r){return Wv.Platform.isPhone||(r?.innerWidth??Number.POSITIVE_INFINITY)<=540}function Dx(r){let t=uU(r.ownerDocument.defaultView);return r.classList.toggle("qa-prompt-compact",t),t}function Lx(r){let t=uU(r.buttonEl.ownerDocument.defaultView);r.setButtonText(t?l7:a7),r.setTooltip(oU(!Wv.Platform.isMobile)),r.buttonEl.setAttribute("aria-label","Peek at the note. Your draft stays."),r.buttonEl.classList.add("qa-peek-button");let e=At(r.buttonEl,"span");return e.className="qa-peek-button-icon",e.setAttribute("aria-hidden","true"),(0,Wv.setIcon)(e,"eye"),r.buttonEl.prepend(e),r}var Wv,a7,l7,kP=x(()=>{Wv=require("obsidian");Ko();Hv();a7="Peek at note",l7="Peek"});var Nx,Nm,SP=x(()=>{Nx=require("obsidian");gP();vP();UB();yP();zB();Rx();rr();_P();Hv();kP();Nm=class extends Nx.Modal{constructor(e,n,i,o,s,a){super(e);this.header=n;this.options=a;this.didSubmit=!1;this.didClose=!1;this.submitClickCallback=e=>this.submit();this.cancelClickCallback=e=>this.cancel();this.skipClickCallback=e=>this.skip();this.submitEnterCallback=e=>{if(this.supportsPeek()&&iU(e)){e.preventDefault(),this.peek.peek();return}if(this.isOptionalPrompt&&rU(e)){e.preventDefault(),this.skip();return}this.shouldSubmit(e)&&(e.preventDefault(),this.submit())};this.placeholder=i??"",this.description=s?.trim()||void 0,this.draftHandler=new Tx({kind:this.getPromptKind(),header:this.header,placeholder:this.placeholder,linkSourcePath:a?.linkSourcePath,scopeId:a?.draftScopeId}),this.input=this.draftHandler.hydrate(o??""),this.waitForClose=new Promise((l,c)=>{this.resolvePromise=l,this.rejectPromise=c}),this.peek=new Lm({app:e,title:this.header,containerEl:this.containerEl,scope:this.scope,getField:()=>this.inputComponent?.inputEl,getValue:()=>this.input,setValue:l=>{this.input=l},markDraftChanged:()=>this.draftHandler.markChanged(),persistDraft:()=>this.persistDraft(),close:()=>this.close()}),this.display(),this.open(),this.attachSuggesters()}display(){this.containerEl.addClass("quickAddModal",this.getPromptKind()==="single"?"qaInputPrompt":"qaWideInputPrompt"),Dx(this.containerEl),this.contentEl.empty(),this.titleEl.textContent=this.header,qB(this.contentEl,this.options?.contextLine,this.options?.contextLineFull),this.description&&this.contentEl.createDiv({text:this.description,cls:"setting-item-description"}).setCssStyles({marginBottom:"0.75rem"}),this.isOptionalPrompt&&this.contentEl.createDiv({text:"Optional \u2014 leave empty, press Skip, or ctrl/cmd+shift+\u21B5.",cls:"setting-item-description"}).setCssStyles({marginBottom:"0.75rem"});let e=this.contentEl.createDiv();this.inputComponent=this.createInputField(e,this.placeholder,this.input),this.createButtonBar(e)}get isOptionalPrompt(){return this.options?.optional===!0}supportsPeek(){return this.options?.allowPeek===!0}configureInput(e,n,i){return e.setPlaceholder(n??"").setValue(i??"").onChange(o=>this.onInputChanged(o)),e.inputEl.addEventListener("keydown",this.submitEnterCallback),this.options?.imagePaste&&(this.imagePasteHandle=Mx(this.app,e.inputEl,this.options.imagePaste)),e}disposeInput(){}createButton(e,n,i){let o=new Nx.ButtonComponent(e);return o.setButtonText(n).onClick(i),o}createButtonBar(e){let n=e.createDiv({cls:"qa-prompt-actions"}),i=n.createDiv({cls:"qa-prompt-actions-primary"});if(this.createButton(i,"Ok",this.submitClickCallback).setCta().buttonEl.setCssStyles({marginRight:"0"}),this.createButton(i,"Cancel",this.cancelClickCallback),this.isOptionalPrompt){let o=this.createButton(i,"Skip",this.skipClickCallback);o.setTooltip("Leave this field empty"),o.buttonEl.setAttribute("aria-label","Skip and leave empty")}if(this.supportsPeek()){let o=n.createDiv({cls:"qa-prompt-actions-secondary"});Lx(this.createButton(o,"Peek at note",()=>this.peek.peek()))}}transformInputOnSubmit(e){return e}submit(){if(this.didSubmit||this.didClose)return;if(this.imagePasteHandle?.isBusy()){this.imagePasteHandle.whenIdle().then(()=>this.submit());return}let e=this.inputComponent?.inputEl?.value??this.input;this.input=this.transformInputOnSubmit(e),this.didSubmit=!0,this.close()}skip(){this.getPromptKind()==="multi"&&this.didSubmit||(this.input="",this.didSubmit=!0,this.close())}cancel(){this.close()}resolveInput(){this.didSubmit?this.resolvePromise(this.input):this.rejectPromise(on())}onInputChanged(e){this.draftHandler.markChanged(),this.input=e}syncInputFromEl(){this.inputComponent?.inputEl&&(this.input=this.inputComponent.inputEl.value)}persistDraft(){this.draftHandler.persist(this.input,this.didSubmit)}attachSuggesters(){this.fileSuggester=new Rm(this.app,this.inputComponent.inputEl,{sourcePath:this.options?.linkSourcePath}),this.tagSuggester=new Om(this.app,this.inputComponent.inputEl)}removeInputListener(){this.inputComponent.inputEl.removeEventListener("keydown",this.submitEnterCallback),this.disposeInput(),this.imagePasteHandle?.detach()}onOpen(){super.onOpen(),this.peek.onHostOpened(),_x(this.inputComponent.inputEl,this.options)}onClose(){this.didClose=!0,this.didSubmit||this.syncInputFromEl(),this.persistDraft(),this.peek.onHostClosed(),this.resolveInput(),this.removeInputListener(),this.fileSuggester?.destroy(),this.tagSuggester?.destroy(),super.onClose()}}});var pU,ir,Gs=x(()=>{pU=require("obsidian");SP();ir=class r extends Nm{static Prompt(t,e,n,i,o,s){return new r(t,e,n,i,o,s).waitForClose}getPromptKind(){return"single"}createInputField(t,e,n){let i=new pU.TextComponent(t);return i.inputEl.setCssStyles({width:"100%"}),this.configureInput(i,e,n)}shouldSubmit(t){return!t.isComposing&&t.key==="Enter"}}});function Ti(r){if(r.length===0)return 0;let t=new TextEncoder().encode(r).length,e=!1;for(let i=0;i<r.length;i++)if(r.charCodeAt(i)>127){e=!0;break}return Math.max(1,Math.ceil(t/(e?3:4)))}function mU(r){return!Number.isFinite(r)||r<=0?1:Math.max(1,Math.floor(r*.45))}var Gv=x(()=>{});function vU(){return U.getState().ai.providers.flatMap(t=>t.models).map(t=>t.name)}function IP(){return U.getState().ai.providers}function fU(r,t){for(let e of r){let n=e.models.find(i=>i.name===t);if(n)return{provider:e,model:n}}}function AP(r){let t=IP();return t.filter(e=>e.models.some(n=>n.name===r)).map(e=>{let n=`${e.id??e.name}/${r}`;return t.some(o=>o.models.some(s=>s.name===n))?`{ name: "${r}", provider: "${e.id??e.name}" } (the string "${n}" is itself a model id on another provider)`:n})}function gU(r,t){hU.has(r)||(hU.add(r),S.logWarning(t))}function lu(r,t){let e=IP(),n=t?.silent===!0;if(r==null)return;if(typeof r!="string"){let s=e.find(c=>c.id===r.providerId),a=s?.models.find(c=>c.name===r.name);if(s&&a)return{provider:s,model:a};let l=fU(e,r.name);return l?(n||gU(`pin:${r.providerId}/${r.name}\u2192${l.provider.id??l.provider.name}`,`Model "${r.name}" is pinned to provider "${r.providerId}", which no longer serves it. Using "${l.provider.name}" instead \u2014 re-select the model in the command's settings to pin it again.`),l):void 0}let i=fU(e,r);if(i){let s=AP(r);return s.length>1&&!n&&gU(`ambiguous:${r}\u2192${i.provider.id??i.provider.name}`,`Model "${r}" is served by ${s.length} providers; using "${i.provider.name}". Qualify it to choose explicitly: ${s.join(", ")}.`),i}let o=r.indexOf("/");if(!(o<=0||o===r.length-1))return yU(r.slice(0,o),r.slice(o+1))}function yU(r,t){let e=IP(),n=r.trim().toLowerCase(),i=e.find(s=>s.id?.toLowerCase()===n)??e.find(s=>s.name.trim().toLowerCase()===n),o=i?.models.find(s=>s.name===t);if(i&&o)return{provider:i,model:o}}function jv(r){let t=typeof r=="string"?r:r?.name;if(!t)throw new Error('Invalid model parameter. Expected a string (e.g., "gpt-4o" or "openai/gpt-4o") or an object with a name property (e.g., {name: "gpt-4o", provider: "openai"})');let e=typeof r!="string"&&r.provider?yU(r.provider,t):lu(t);if(!e){let n=t.includes("/")?t.slice(t.indexOf("/")+1):t,i=[...AP(t),...n!==t?AP(n):[]],o=i.length?` Did you mean ${i.join(" or ")}?`:" Add it in Settings \u2192 QuickAdd \u2192 AI Assistant \u2192 your provider, or turn on Auto-sync models for that provider.";throw new Error(`Model '${typeof r=="string"?r:`${r.provider??""}/${t}`}' not found in configured providers.${o}`)}return e}var hU,Vm=x(()=>{ye();je();hU=new Set});var qx=x(()=>{});var Ki=x(()=>{});var hn,ll=x(()=>{Qo();hn=class{constructor(t,e){this.name=t,this.type=e,this.id=Vt()}}});var ht,cs=x(()=>{er();ll();sl();ye();ht=class extends hn{constructor(t){super(t,"EditorCommand"),this.editorCommandType=t}static getSelectedText(t){return this.getActiveMarkdownView(t).editor.getSelection()}static getActiveMarkdownView(t){let e=Un(t);if(!e)throw S.logError("no active markdown editor."),new Error("no active markdown editor.");return e}}});var Um,MP=x(()=>{Ki();cs();Um=class extends ht{constructor(){super("Copy")}static async run(t){let e=ht.getSelectedText(t);await navigator.clipboard.writeText(e)}}});var qm,RP=x(()=>{Ki();cs();ye();qm=class extends ht{constructor(){super("Cut")}static async run(t){let e=ht.getSelectedText(t),n=ht.getActiveMarkdownView(t);if(!e){S.logError("nothing selected.");return}await navigator.clipboard.writeText(e),n.editor.replaceSelection("")}}});var zm,OP=x(()=>{Ki();ye();cs();zm=class extends ht{constructor(){super("Paste")}static async run(t){let e=await navigator.clipboard.readText(),n=ht.getActiveMarkdownView(t);if(!n){S.logError("no active markdown view.");return}n.editor.replaceSelection(e)}}});var EU,Hm,DP=x(()=>{EU=require("obsidian");ye();cs();Ki();Hm=class extends ht{constructor(){super("Paste with format")}static async run(t){let e=ht.getActiveMarkdownView(t);if(!e){S.logError("no active markdown view.");return}let n="";try{if("read"in navigator.clipboard&&navigator.clipboard.read){let i=await navigator.clipboard.read(),o=!1;for(let s of i)if(s.types.includes("text/html")){let l=await(await s.getType("text/html")).text();n=(0,EU.htmlToMarkdown)(l),o=!0;break}o||(n=await navigator.clipboard.readText())}else n=await navigator.clipboard.readText();e.editor.replaceSelection(n)}catch(i){S.logWarning(`Formatted paste failed. Falling back to plain text: ${i}`);try{let o=await navigator.clipboard.readText();e.editor.replaceSelection(o)}catch(o){S.logError(`Failed to read clipboard text: ${o}`)}}}}});var Wm,LP=x(()=>{Ki();cs();Wm=class extends ht{constructor(){super("Select active line")}static run(t){let e=ht.getActiveMarkdownView(t),{line:n}=e.editor.getCursor(),o=e.editor.getLine(n).length;e.editor.setSelection({line:n,ch:0},{line:n,ch:o})}}});var Gm,NP=x(()=>{cs();Ki();Le();ye();Gm=class extends ht{constructor(){super("Select link on active line")}static run(t){let e=ht.getActiveMarkdownView(t),{line:n}=e.editor.getCursor(),i=e.editor.getLine(n),o=zD.exec(i);if(!o){S.logError(`no internal link found on line ${n}.`);return}let s=o.index,a=o[0].length+s;e.editor.setSelection({line:n,ch:s},{line:n,ch:a})}}});var jm,VP=x(()=>{cs();Ki();jm=class extends ht{constructor(){super("Move cursor to file start")}static run(t){ht.getActiveMarkdownView(t).editor.setCursor({line:0,ch:0})}}});var Ym,BP=x(()=>{cs();Ki();Ym=class extends ht{constructor(){super("Move cursor to file end")}static run(t){let e=ht.getActiveMarkdownView(t),n=e.editor.lastLine(),i=e.editor.getLine(n).length;e.editor.setCursor({line:n,ch:i})}}});var Km,UP=x(()=>{cs();Ki();Km=class extends ht{constructor(){super("Move cursor to line start")}static run(t){let e=ht.getActiveMarkdownView(t),{line:n}=e.editor.getCursor();e.editor.setCursor({line:n,ch:0})}}});var Qm,qP=x(()=>{cs();Ki();Qm=class extends ht{constructor(){super("Move cursor to line end")}static run(t){let e=ht.getActiveMarkdownView(t),{line:n}=e.editor.getCursor(),i=e.editor.getLine(n).length;e.editor.setCursor({line:n,ch:i})}}});var Qs,Xm,WP=x(()=>{Qs=require("obsidian");ye();an();rr();hp();Xm=class extends Qs.FuzzySuggestModal{constructor(e,n,i,o,s){super(e);this.indexByItem=new Map;this.aliasByMatch=new WeakMap;this.warnedOnEmptyDisplay=!1;this.warnRenderItemFailure=pp("Custom renderItem threw an error; falling back to default rendering");this.modalEl.addClass("qa-suggester"),this.renderItem=o,this.items=i,this.displayItems=n.map(a=>sn(a)),this.promise=new Promise((a,l)=>{this.resolvePromise=a,this.rejectPromise=l}),s?.skippable&&r0(this,()=>this.skip()),this.inputEl.addEventListener("keydown",a=>{if(a.code!=="Tab"||!("chooser"in this))return;let{values:l,selectedItem:c}=this.chooser,{value:d}=this.inputEl;this.inputEl.value=l[c]?.item??d}),this.displayItems.length!==this.items.length&&(this.displayItems=this.items.map((a,l)=>{let c=this.displayItems[l];return sn(c??a)})),this.items.forEach((a,l)=>{this.indexByItem.has(a)||this.indexByItem.set(a,l)}),this.aliases=s?.aliases}indexOfItem(e){return this.indexByItem.get(e)??-1}getItemText(e){let n=this.indexOfItem(e),i=n>=0?this.displayItems[n]:void 0;return sn(i??e)}getItems(){return this.items}getSuggestions(e){let n=zl(e);if(!this.aliases||!n.trim())return super.getSuggestions(n);let i=(0,Qs.prepareFuzzySearch)(n.trim()),o=[];return this.items.forEach((s,a)=>{let l=BS(i,this.getItemText(s),this.aliases?.[a]);if(!l)return;let c={item:s,match:l.result};l.alias!==void 0&&this.aliasByMatch.set(c,l.alias),o.push(c)}),(0,Qs.sortSearchResults)(o),o}selectSuggestion(e,n){this.resolved=!0,super.selectSuggestion(e,n)}renderSuggestion(e,n){let i=this.aliasByMatch.get(e);if(i!==void 0){this.renderAliasSuggestion(e,i,n);return}if(!this.renderItem){super.renderSuggestion(e,n);return}try{n.empty(),this.renderItem(e.item,n,e.match.matches)}catch(o){this.warnRenderItemFailure(o),n.empty(),super.renderSuggestion(e,n)}}renderAliasSuggestion(e,n,i){i.empty(),i.addClass("mod-complex");let o=i.createDiv({cls:"suggestion-content"});(0,Qs.renderMatches)(o.createDiv({cls:"suggestion-title"}),n,e.match.matches);let s=this.indexOfItem(e.item);o.createDiv({cls:"suggestion-note",text:this.displayItems[s]??""});let a=i.createDiv({cls:"suggestion-aux"}).createSpan({cls:"suggestion-flair"});a.setAttribute("aria-label","Alias"),(0,Qs.setIcon)(a,"forward")}renderDefaultSuggestion(e,n){super.renderSuggestion(e,n)}onChooseItem(e,n){this.resolved=!0,this.resolvePromise(e)}skip(){this.resolved=!0,this.resolvePromise(""),this.close()}onClose(){super.onClose(),this.resolved||this.rejectPromise(on())}warnIfEmptyDisplay(){if(this.warnedOnEmptyDisplay)return;this.displayItems.some(n=>n.length===0)&&(this.warnedOnEmptyDisplay=!0,S.logWarning("QuickAdd suggester received empty display values. Check your displayItems mapping."))}}});var AU,vr,cl=x(()=>{AU=require("obsidian");an();WP();vr=class r extends Xm{constructor(e,n,i,o={}){super(e,n,i,o.renderItem,o);this.warnCustomValueFailure=pp("Custom create-row rendering threw an error; falling back to default rendering");this.allowCustomValue=!0;this.searchItems=o.searchItems?.map(s=>sn(s))??[],this.allowCustomValue=o.allowCustomValue??!0,this.customValueLabel=o.customValueLabel,this.valueExists=o.valueExists,o.placeholder&&this.setPlaceholder(o.placeholder),typeof o.limit=="number"&&(this.limit=o.limit),o.emptyStateText&&(this.emptyStateText=o.emptyStateText),this.searchItems.length!==this.items.length&&(this.searchItems=this.items.map((s,a)=>sn(this.searchItems[a]??this.displayItems[a]??s))),this.warnIfEmptyDisplay(),this.open()}static Suggest(e,n,i,o={}){return new r(e,n,i,o).promise}getItemText(e){if(e===this.inputEl.value)return e;let n=this.indexOfItem(e),i=n>=0?this.searchItems[n]:void 0;return sn(i??e)}getSuggestions(e){let n=super.getSuggestions(e);if(!this.allowCustomValue)return n;let i=zl(this.inputEl.value);if(!i||this.items.includes(i)||this.valueExists?.(i)||n.some(a=>a.item===i))return n;let s={item:i,match:{score:Number.NEGATIVE_INFINITY,matches:[]}};return this.customValueLabel?n.unshift(s):n.push(s),n}renderSuggestion(e,n){if(this.customValueLabel&&e.match.score===Number.NEGATIVE_INFINITY){this.renderCustomValue(e.item,n);return}super.renderSuggestion(e,n)}renderCustomValue(e,n){try{n.empty(),n.addClass("mod-complex"),n.createDiv({cls:"suggestion-content"}).createDiv({cls:"suggestion-title",text:this.customValueLabel?.(e)??e});let o=n.createDiv({cls:"suggestion-aux"});(0,AU.setIcon)(o.createSpan({cls:"suggestion-flair"}),"file-plus")}catch(i){this.warnCustomValueFailure(i),n.empty(),this.renderDefaultSuggestion({item:e,match:{score:0,matches:[]}},n)}}}});var It,Qi=x(()=>{WP();It=class r extends Xm{static Suggest(t,e,n,i,o,s){let a=new r(t,e,n,o,s);return i&&a.setPlaceholder(i),a.promise}constructor(t,e,n,i,o){super(t,e,n,i,o),this.warnIfEmptyDisplay(),this.open()}}});function qn(r){return r.type==="Template"}function pl(r){return r.type==="Capture"}function Xi(r){return r.type==="Macro"}function uu(r){return r.type==="Multi"}var ml=x(()=>{});function sq(r){let t=[],e=new RegExp(kJ.source,"gi"),n=0;for(;n<r.length;){e.lastIndex=n;let i=e.exec(r);if(!i)break;let o=i.index,s=o+oq.length,a=s;for(;a<r.length;){let d=r[a];if(d==="}"||d===`
|
||
`||d==="\r")break;a++}let l=r.slice(s,a);r[a]==="}"&&r[a+1]==="}"&&SJ.test(l)?(t.push({start:o,end:a+2,path:cr(l)}),n=a+2):n=a}return t}function Xs(r){let t=new Set;if(!r)return t;for(let e of sq(r))e.path&&t.add(e.path);return t}function hE(r,t){if(!r||t.size===0)return r;let e=sq(r);if(e.length===0)return r;let n="",i=0;for(let o of e){let s=t.get(o.path);s&&(n+=r.slice(i,o.start),n+=`${oq}${s}}}`,i=o.end)}return i===0?r:n+r.slice(i)}var oq,kJ,SJ,Ac=x(()=>{Dr();oq="{{TEMPLATE:",kJ=/{{TEMPLATE:/gi,SJ=/\.(?:md|canvas|base)$/i});function Aq(r){try{let t=window.require;return t?t(r):null}catch{return null}}async function cf(r,t){let e=r.vault.adapter;if(typeof h$.FileSystemAdapter!="function"||!(e instanceof h$.FileSystemAdapter))return;let n=Aq("fs"),i=Aq("path");if(!n?.promises||!i)return;let o=await n.promises.realpath(e.getBasePath()),a=e.getFullPath(t);for(;!QJ(n,a);){let p=i.dirname(a);if(p===a)break;a=p}let l;try{l=await n.promises.realpath(a)}catch{throw new ty(`Refusing to write to "${t}": it resolves through an unresolvable (dangling) symlink.`)}let c=i.relative(o,l);if(c===".."||c.startsWith(`..${i.sep}`)||i.isAbsolute(c))throw new ty(`Refusing to write to "${t}": it resolves (via a symlink) outside the vault.`);if(c.split(i.sep).some(p=>p.startsWith(".")))throw new ty(`Refusing to write to "${t}": it resolves (via a symlink) into a config/hidden directory.`)}function QJ(r,t){try{return r.lstatSync(t),!0}catch{return!1}}var h$,ty,g$=x(()=>{h$=require("obsidian"),ty=class extends Error{constructor(t){super(t),this.name="VaultWriteEscapeError"}}});function Q$(r,t=new Set){if(r==null||t.has(r))return[];if(t.add(r),typeof r=="string")return[r];if(typeof r!="object")return[String(r)];let e=r,n=[];for(let i of Ree){let o=e[i];o!==void 0&&n.push(...Q$(o,t))}return n}function QE(r){return Number(r.replace(/,/g,""))}function Oee(r){let t=r.match(/context (?:length|window)(?:\s+is)?(?:\s+of)?\s*(\d[\d,]*)/i);return t?QE(t[1]):null}function Dee(r){let t=r.match(/(\d[\d,]*)\s*(?:tokens?\s+)?in the completion\b/i);if(t){let n=QE(t[1]),i=Oee(r);return i===null?"input":n>=i?"output":"input"}let e=r.match(/input length and max_tokens exceed context limit:?\s*(\d[\d,]*)\s*\+\s*(\d[\d,]*)(?:\s*>\s*(\d[\d,]*))?/i);if(e){let n=QE(e[2]),i=e[3]?QE(e[3]):null;return i===null?"input":n>=i?"output":"input"}return null}function cy(r){let t=Q$(r).join(" "),e=Dee(t);return e==="output"?"output_budget":e==="input"?"input_context":Mee.some(n=>n.test(t))?"output_budget":Fee.some(n=>n.test(t))?"input_context":"other"}function dz(r){return cy(r)==="input_context"}function uz(r){return Lee.test(Q$(r).join(" "))}function XE(r,t){let e="",n="",i;try{i=t.json}catch{i=void 0}if(i&&typeof i=="object"){let s=i,a=s.error??s;e=String(a.message??s.message??""),n=String(a.code??a.type??a.status??"")}e||(e=typeof t.text=="string"&&t.text.length>0?t.text:`HTTP ${t.status}`);let o=new Error(`${r} request failed (HTTP ${t.status})${n?` [${n}]`:""}: ${e}`);return o.status=t.status,n&&(o.providerCode=n),o}var Fee,Mee,Ree,Lee,ff=x(()=>{Fee=[/context[_ -]?length[_ -]?exceeded/i,/context[_ -]?window[_ -]?exceeded/i,/maximum context length/i,/context window/i,/too many input tokens/i,/input(?: is)? too long/i,/prompt(?: is)? too long/i,/input token count/i,/reduce the length of (?:the |your )?(?:messages|prompt|input)/i,/exceed(?:s|ed|ing)? (?:the )?(?:maximum |allowed )?(?:input |prompt )?(?:token|context)/i],Mee=[/max_tokens/i,/max_completion_tokens/i,/max(?:imum)? output tokens/i,/output token limit/i],Ree=["message","code","type","status","statusText","providerCode","error","response","json","cause"];Lee=/tool_choice:\s*type\s*"tool"\s*and\s*"any"\s*are not supported/i});function Yee(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function Kee(r){let t=r.name?.trim()||"provider";return`${jee}-${Yee(t)}`}async function hz(r,t){if(!r?.secretStorage?.getSecret)return null;try{return await Promise.resolve(r.secretStorage.getSecret(t))}catch(e){return S.logWarning(`Failed to read SecretStorage entry "${t}": ${e.message??e}`),null}}async function Po(r,t){let e=t.apiKeyRef?.trim();if(e){let n=await hz(r,e);if(n)return n}return t.apiKey??""}async function gz(r,t,e){let n=e?.trim();if(!n||!r?.secretStorage?.getSecret||!r.secretStorage?.setSecret)return null;let i=Kee(t),o=i,s=1;for(;;){let a=await hz(r,o);if(!a)break;if(a===n)return o;s+=1,o=`${i}-${s}`}try{return await Promise.resolve(r.secretStorage.setSecret(o,n)),o}catch(a){return S.logWarning(`Failed to write SecretStorage entry "${o}": ${a.message??a}`),null}}var jee,Ic=x(()=>{ye();jee="quickadd-ai"});async function my(r,t,e){let n=Date.now();if(!(r instanceof Promise))throw new TypeError("Promise must be an instance of Promise.");let i=!1,o=()=>{i=!0};for(r.then(o,o);!i;)t.setMessage(e[0],`${e[1]} (${((Date.now()-n)/1e3).toFixed(2)}s)`),await sleep(100);return t.setMessage("finished",`Took ${((Date.now()-n)/1e3).toFixed(2)}s.`),await r}function fy(r,t){return{[r]:t,[`${r}-quoted`]:("> "+t).replace(/\n/g,`
|
||
> `)}}var nF=x(()=>{});var de,Sn=x(()=>{ri();de=class extends at{}});function gf(r){return iF.filter(t=>typeof r[t]=="number")}function pT(r){let t={...r};for(let e of iF)delete t[e];return t}function oF(r,t){return r.supportsTemperature===!1&&gf(t).length>0?pT(t):t}function Mz(r,t){return t.length===0?!1:ute.some(e=>e.test(r))}function sF(r){let t=r.map(e=>dte[e]);return t.length<=1?t.join(""):t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[t.length-1]}`}function hy(r,t){let e={};return typeof t.temperature=="number"&&(e.temperature=t.temperature),typeof t.top_p=="number"&&(e[r==="gemini"?"topP":"top_p"]=t.top_p),e}var iF,dte,uT,ute,mT=x(()=>{iF=["temperature","top_p","frequency_penalty","presence_penalty"],dte={temperature:"Temperature",top_p:"Top P",frequency_penalty:"Frequency penalty",presence_penalty:"Presence penalty"};uT=iF.join("|"),ute=[new RegExp(`unsupported (?:parameter|value)[^.]{0,40}['\`"]?(?:${uT})['\`"]?`,"i"),new RegExp(`['\`"]?(?:${uT})['\`"]?[^.]{0,40}(?:is deprecated|is not supported|not supported|does not support)`,"i"),new RegExp(`unrecognized request argument[^.]{0,40}(?:${uT})`,"i"),new RegExp(`(?:${uT})[^.]{0,40}extra inputs are not permitted`,"i")]});function aF(r){return{...r,modelOptions:{...r.modelOptions},usage:r.usage?{...r.usage}:void 0}}function lF(r){let t=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,e=Date.now();return Fo.push({...r,modelOptions:{...r.modelOptions??{}},id:t,createdAt:e,status:"pending"}),Oz(),t}function gy(r,t){let e=Fo.find(n=>n.id===r);e&&(e.status=t.status,e.durationMs=t.durationMs,e.usage=t.usage,e.errorMessage=t.errorMessage,Oz())}function Rz(r=10){Number.isFinite(r)||(r=10);let t=Math.floor(r);return t<=0?[]:Fo.slice(-t).map(aF).reverse()}function Oz(){if(Fo.length<=25)return;let r=Fo.length-25;for(;r>0;){let t=Fo.findIndex(e=>e.status!=="pending");if(t===-1)break;Fo.splice(t,1),r-=1}}function Dz(r){let t=Fo.find(e=>e.id===r);return t?aF(t):null}function Lz(){let r=Fo[Fo.length-1];return r?aF(r):null}function Nz(){Fo.splice(0,Fo.length)}var Fo,cF=x(()=>{Fo=[]});function fT(r){let t=r.workspace.activeEditor?.editor?.getCursor(),e=r.workspace.activeEditor?.editor?.listSelections();return()=>{t&&r.workspace.activeEditor?.editor?.setCursor(t),e&&r.workspace.activeEditor?.editor?.setSelections(e)}}var dF=x(()=>{});function mu(r){let t=Array.isArray(r)?r:{...r},e=t.type==="object"||Array.isArray(t.type)&&t.type.includes("object")||t.properties!==void 0;if(t.properties){let n={};for(let[i,o]of Object.entries(t.properties))n[i]=mu(o);t.properties=n}return t.items&&!Array.isArray(t.items)&&(t.items=mu(t.items)),e&&(t.additionalProperties=!1,t.required=t.properties?Object.keys(t.properties):[]),t}function pte(r){let t=[];for(let e of r)if(e.role==="system")t.push({role:"system",content:e.content});else if(e.role==="user")t.push({role:"user",content:e.content});else if(e.role==="assistant"){let n={role:"assistant",content:e.content??""};e.toolCalls&&e.toolCalls.length>0&&(n.tool_calls=e.toolCalls.map(i=>({id:i.id,type:"function",function:{name:i.name,arguments:i.rawArgs??JSON.stringify(i.args??{})}}))),t.push(n)}else for(let n of e.results)t.push({role:"tool",tool_call_id:n.toolCallId,content:n.isError?`ERROR: ${n.content}`:n.content});return t}function mte(r){return r.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.strict?mu(t.parameters):t.parameters,...t.strict?{strict:!0}:{}}}))}function fte(r){return typeof r=="string"?r:{type:"function",function:{name:r.name}}}function gte(r,t){let e={model:r,...t.modelParams??{},messages:pte(t.messages)};return t.tools&&t.tools.length>0&&(e.tools=mte(t.tools),t.toolChoice&&(e.tool_choice=fte(t.toolChoice)),t.disableParallel&&(e.parallel_tool_calls=!1)),t.maxOutputTokens!==void 0&&(hte.test(r)?e.max_completion_tokens=t.maxOutputTokens:e.max_tokens=t.maxOutputTokens),t.responseFormat&&(e.response_format=t.responseFormat.schema?{type:"json_schema",json_schema:{name:t.responseFormat.name??"response",strict:t.responseFormat.strict??!0,schema:t.responseFormat.strict??!0?mu(t.responseFormat.schema):t.responseFormat.schema}}:{type:"json_object"}),e}function vte(r){let t=r.choices?.[0]??{},e=t.message??{},i=(e.tool_calls??[]).map(d=>Bz(d)),o=String(t.finish_reason??""),s=r.usage??{},a=typeof e.content=="string"?e.content:"",l=typeof e.refusal=="string"?e.refusal:"",c=!a&&l.length>0&&i.length===0;return{content:c?l:a,toolCalls:i,normalizedStopReason:i.length>0||o==="tool_calls"?"tool_calls":o==="length"?"length":o==="stop"&&!c?"stop":"other",rawStopReason:c?"refusal":o,usage:{promptTokens:s.prompt_tokens??0,completionTokens:s.completion_tokens??0,totalTokens:s.total_tokens??0}}}function Vz(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function Bz(r){let t=r.function.arguments;if(typeof t=="string")try{let n=Vz(JSON.parse(t||"{}"));if(!n)throw new Error("tool arguments are not a JSON object");return{id:r.id,name:r.function.name,args:n,rawArgs:t}}catch{return{id:r.id,name:r.function.name,args:null,rawArgs:t,parseError:!0}}let e=Vz(t);return e?{id:r.id,name:r.function.name,args:e}:{id:r.id,name:r.function.name,args:null,rawArgs:typeof t=="string"?t:JSON.stringify(t??{}),parseError:!0}}function yte(r){let t=[];for(let e of r)if(e.role==="system"||e.role==="user")t.push({role:e.role,content:e.content});else if(e.role==="assistant"){if(Array.isArray(e.providerRaw)){t.push(...e.providerRaw);continue}e.content&&t.push({role:"assistant",content:e.content});for(let n of e.toolCalls??[])t.push({type:"function_call",call_id:n.id,name:n.name,arguments:n.rawArgs??JSON.stringify(n.args??{})})}else for(let n of e.results)t.push({type:"function_call_output",call_id:n.toolCallId,output:n.isError?`ERROR: ${n.content}`:n.content});return t}function bte(r){return typeof r=="string"?r:{type:"function",name:r.name}}function wte(r,t){let{reasoning_effort:e,max_tokens:n,max_completion_tokens:i,...o}=t.modelParams??{},s={model:r,...o,input:yte(t.messages),store:!1,include:["reasoning.encrypted_content"]};e!==void 0&&(s.reasoning={effort:e});let a=t.maxOutputTokens??i??n;if(a!==void 0&&(s.max_output_tokens=a),t.tools&&t.tools.length>0&&(s.tools=t.tools.map(l=>({type:"function",name:l.name,description:l.description,parameters:l.strict?mu(l.parameters):l.parameters,strict:l.strict===!0})),t.toolChoice&&(s.tool_choice=bte(t.toolChoice)),t.disableParallel&&(s.parallel_tool_calls=!1)),t.responseFormat){let l=t.responseFormat.strict??!0;s.text={format:t.responseFormat.schema?{type:"json_schema",name:t.responseFormat.name??"response",strict:l,schema:l?mu(t.responseFormat.schema):t.responseFormat.schema}:{type:"json_object"}}}return s}function Cte(r){let t=r.output??[],e=t.filter(d=>d.type==="function_call").map(d=>Bz({id:d.call_id??"",function:{name:d.name??"",arguments:d.arguments}})),n=t.filter(d=>d.type==="message").flatMap(d=>d.content??[]),i=n.filter(d=>d.type==="output_text").map(d=>d.text??"").join(""),o=n.filter(d=>d.type==="refusal").map(d=>d.refusal??"").join(""),s=!i&&o.length>0,a=String(r.status??""),l=String(r.incomplete_details?.reason??""),c=r.usage??{};return{content:s?o:i,toolCalls:e,normalizedStopReason:e.length>0?"tool_calls":l==="max_output_tokens"?"length":a==="completed"&&!s?"stop":"other",rawStopReason:s?"refusal":l||a,usage:{promptTokens:c.input_tokens??0,completionTokens:c.output_tokens??0,totalTokens:c.total_tokens??0},providerRaw:t}}function xte(r,t,e){let n=[],i=[];for(let s of t.messages)if(s.role==="system")s.content&&n.push(s.content);else if(s.role==="user")i.push({role:"user",content:s.content});else if(s.role==="assistant"){let a=[];s.content&&a.push({type:"text",text:s.content});for(let l of s.toolCalls??[])a.push({type:"tool_use",id:l.id,name:l.name,input:l.args??{}});i.push({role:"assistant",content:a})}else i.push({role:"user",content:s.results.map(a=>({type:"tool_result",tool_use_id:a.toolCallId,content:a.content,...a.isError?{is_error:!0}:{}}))});let o={model:r,max_tokens:t.maxOutputTokens??e,messages:i};return n.length>0&&(o.system=n.join(`
|
||
|
||
`)),Object.assign(o,hy("anthropic",t.modelParams??{})),t.tools&&t.tools.length>0&&(o.tools=t.tools.map(s=>({name:s.name,description:s.description,input_schema:s.parameters})),t.toolChoice?o.tool_choice=Ete(t.toolChoice,t.disableParallel):t.disableParallel&&(o.tool_choice={type:"auto",disable_parallel_tool_use:!0})),t.responseFormat?.schema&&(o.output_config={format:{type:"json_schema",schema:mu(t.responseFormat.schema)}}),o}function Ete(r,t){let e=t?{disable_parallel_tool_use:!0}:{};return typeof r=="string"?r==="required"?{type:"any",...e}:r==="none"?{type:"none"}:{type:"auto",...e}:{type:"tool",name:r.name,...e}}function Tte(r){let t=r.content??[],e=t.filter(a=>a.type==="tool_use").map(a=>({id:a.id??"",name:a.name??"",args:a.input??{}})),n=String(r.stop_reason??""),i=r.usage??{},o=i.input_tokens??0,s=i.output_tokens??0;return{content:t.filter(a=>a.type==="text").map(a=>a.text??"").join(""),toolCalls:e,normalizedStopReason:n==="tool_use"||e.length>0?"tool_calls":n==="max_tokens"?"length":n==="end_turn"||n==="stop_sequence"?"stop":"other",rawStopReason:n,usage:{promptTokens:o,completionTokens:s,totalTokens:o+s}}}function _te(r,t){let e=[],n=[];for(let s of t.messages)if(s.role==="system")s.content&&e.push(s.content);else if(s.role==="user")n.push({role:"user",parts:[{text:s.content}]});else if(s.role==="assistant")if(Array.isArray(s.providerRaw))n.push({role:"model",parts:s.providerRaw});else{let a=[];s.content&&a.push({text:s.content});for(let l of s.toolCalls??[])a.push({functionCall:{name:l.name,args:l.args??{}}});n.push({role:"model",parts:a})}else n.push({role:"user",parts:s.results.map(a=>({functionResponse:{name:a.name,response:a.isError?{error:a.content}:{result:a.content}}}))});let i={contents:n};e.length>0&&(i.systemInstruction={role:"system",parts:[{text:e.join(`
|
||
|
||
`)}]}),t.tools&&t.tools.length>0&&(i.tools=[{functionDeclarations:t.tools.map(s=>({name:s.name,description:s.description,parameters:s.parameters}))}],t.toolChoice&&(i.toolConfig=kte(t.toolChoice)));let o=hy("gemini",t.modelParams??{});return t.maxOutputTokens!==void 0&&(o.maxOutputTokens=t.maxOutputTokens),t.responseFormat?.schema&&(o.responseMimeType="application/json",o.responseSchema=t.responseFormat.schema),Object.keys(o).length>0&&(i.generationConfig=o),i}function kte(r){return typeof r=="string"?{functionCallingConfig:{mode:r==="required"?"ANY":r==="none"?"NONE":"AUTO"}}:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[r.name]}}}function Ste(r){let t=r.candidates?.[0]??{},n=(t.content??{}).parts??[],i=n.filter(a=>a.functionCall).map((a,l)=>({id:a.functionCall?.id??`gemini-call-${l}`,name:a.functionCall?.name??"",args:a.functionCall?.args??{}})),o=String(t.finishReason??""),s=r.usageMetadata??{};return{content:n.filter(a=>typeof a.text=="string").map(a=>a.text??"").join(""),toolCalls:i,normalizedStopReason:i.length>0?"tool_calls":o==="MAX_TOKENS"?"length":o==="STOP"?"stop":"other",rawStopReason:o,usage:{promptTokens:s.promptTokenCount??0,completionTokens:s.candidatesTokenCount??0,totalTokens:s.totalTokenCount??0},providerRaw:n}}function uF(r,t,e,n=8192){switch(r){case"anthropic":return xte(t,e,n);case"gemini":return _te(t,e);case"openai-responses":return wte(t,e);default:return gte(t,e)}}function Uz(r,t){switch(r){case"anthropic":return Tte(t);case"gemini":return Ste(t);case"openai-responses":return Cte(t);default:return vte(t)}}var hte,qz=x(()=>{mT();hte=/^(?:o[1-9]|gpt-(?:[5-9]|\d\d))/i});async function vy({kind:r,apiKey:t,provider:e,model:n,body:i,afterRequest:o}){let s={"Content-Type":"application/json"},a;switch(r){case"anthropic":a="/v1/messages",s["x-api-key"]=t,s["anthropic-version"]="2023-06-01";break;case"gemini":a=`/v1beta/models/${encodeURIComponent(n.name)}:generateContent`,s["x-goog-api-key"]=t;break;case"openai-responses":a="/responses",s.Authorization=`Bearer ${t}`;break;default:a="/chat/completions",s.Authorization=`Bearer ${t}`}let l=(0,zz.requestUrl)({url:e.endpoint+a,method:"POST",headers:s,body:JSON.stringify(i),throw:!1});o?.();let c=await l;if(c.status>=400)throw XE(e.name,c);return c.json}function Ate(r){return{id:r.id,model:r.model,content:r.choices[0].message.content,usage:{promptTokens:r.usage.prompt_tokens,completionTokens:r.usage.completion_tokens,totalTokens:r.usage.total_tokens},stopReason:r.choices[0].finish_reason,stopSequence:null,created:r.created}}function Ite(r){return{id:r.id,model:r.model,content:r.content.filter(t=>t.type==="text").map(t=>t.text??"").join(""),usage:{promptTokens:r.usage.input_tokens,completionTokens:r.usage.output_tokens,totalTokens:r.usage.input_tokens+r.usage.output_tokens},stopReason:r.stop_reason,stopSequence:r.stop_sequence,created:Date.now()}}function yy(r){if(typeof r.maxOutputTokens=="number"&&Number.isFinite(r.maxOutputTokens)&&r.maxOutputTokens>0)return Math.floor(r.maxOutputTokens);let t=4096;return Number.isFinite(r.maxTokens)&&r.maxTokens>0?Math.min(t,r.maxTokens):t}function Pte(r,t,e,n,i){if(r!=="anthropic"&&r!=="gemini")return{model:t.name,...n,messages:[{role:"system",content:e},{role:"user",content:i}]};let o=hy(r,n);return r==="anthropic"?{model:t.name,max_tokens:yy(t),messages:[{role:"user",content:i}],...e&&e.trim().length>0?{system:e}:{},...o}:{contents:[{role:"user",parts:[{text:i}]}],...e&&e.trim().length>0?{systemInstruction:{role:"system",parts:[{text:e}]}}:{},...Object.keys(o).length?{generationConfig:o}:{}}}async function Hz({kind:r,systemPrompt:t,params:e,prompt:n,...i}){let o=Pte(r,i.model,t,e,n),s={...i,kind:r,body:o};switch(r){case"anthropic":return Ite(await vy(s));case"gemini":return $te(await vy(s));default:return Ate(await vy(s))}}function $te(r){let t=r.candidates?.[0],n=(t?.content?.parts??[]).map(i=>typeof i.text=="string"?i.text:"").join("");return{id:`${Date.now()}`,model:r.modelVersion??"gemini",content:n,usage:{promptTokens:r.usageMetadata?.promptTokenCount??0,completionTokens:r.usageMetadata?.candidatesTokenCount??0,totalTokens:r.usageMetadata?.totalTokenCount??0},stopReason:t?.finishReason??"",stopSequence:null,created:Date.now()}}var zz,pF=x(()=>{zz=require("obsidian");ff();mT()});function by(r,t,e,n,i,o={},s=!0){return async function(l){if(U.getState().disableOnlineFeatures)throw new Error("Blocking request: Online features are disabled in settings.");let c=Ti(l)+Ti(i),d=Date.now(),u=lF({provider:n.name,endpoint:n.endpoint,model:e.name,systemPrompt:i,prompt:l,modelOptions:o});S.logMessage(`[AI Request ${u}] Started ${n.name}/${e.name}`),Number.isFinite(e.maxTokens)&&e.maxTokens>0&&c>e.maxTokens&&S.logMessage(`[AI Request ${u}] Estimated prompt size is ${c} tokens, above the configured ${e.maxTokens} token context. Sending anyway; the provider will enforce the exact limit.`);try{let p=fT(r),m=Sh(n),h=C=>Hz({kind:m,apiKey:t,model:e,provider:n,systemPrompt:i,params:C,prompt:l,afterRequest:p}),g=oF(e,o),v=gf(g);v.length===0&&gf(o).length>0&&S.logMessage(`[AI Request ${u}] ${e.name} uses fixed sampling; not sending ${sF(gf(o))}.`);let b=await Gz(()=>h(g),()=>h(pT(g)),{sentKeys:v,model:e,provider:n,logPrefix:`AI Request ${u}`,advancedSettings:!0}),y=Date.now()-d;return gy(u,{status:"success",durationMs:y,usage:b.usage}),S.logMessage(`[AI Request ${u}] Success in ${y}ms`),b}catch(p){let m=p.message??String(p),h=Date.now()-d;gy(u,{status:"error",durationMs:h,errorMessage:m}),S.logMessage(`[AI Request ${u}] Failed in ${h}ms: ${m}`);let g=cy(p)==="input_context"?" The prompt likely exceeds the model's context window \u2014 shorten it, choose a model with a larger context, or use the chunked AI prompt API.":"",v=new Error(`Error while making request to ${n.name}: ${m}${g}`,{cause:p});throw s&&Me(v),v}}}async function mF(r,t,e,n,i,o,s=!0){if(U.getState().disableOnlineFeatures)throw new Error("Blocking request: Online features are disabled in settings.");let a=lD(n),l={...i,modelParams:oF(e,i.modelParams??{})},c=gf(l.modelParams??{}),d=uF(a,e.name,l,yy(e)),u=i.messages.find(g=>g.role==="system"),p=[...i.messages].reverse().find(g=>g.role==="user"),m=Date.now(),h=lF({provider:n.name,endpoint:n.endpoint,model:e.name,systemPrompt:u&&u.role==="system"?u.content:"",prompt:p&&p.role==="user"?p.content:"[tool-calling turn]",modelOptions:i.modelParams??{}});try{let g=w=>vy({kind:a,apiKey:t,provider:n,model:e,body:w,afterRequest:o}),v=async w=>{try{return await g(w)}catch(T){let P=Mte(a,w,T.message??String(T));if(!P)throw T;return S.logMessage(`[AI Chat ${h}] ${e.name} rejected function tools while reasoning; retrying with reasoning_effort "none".`),g(P)}},b=await Gz(()=>v(d),()=>v(uF(a,e.name,{...l,modelParams:pT(l.modelParams??{})},yy(e))),{sentKeys:c,model:e,provider:n,logPrefix:`AI Chat ${h}`}),y=Uz(a,b),C=Date.now()-m;return gy(h,{status:"success",durationMs:C,usage:y.usage}),S.logMessage(`[AI Chat ${h}] Success in ${C}ms`),{id:b.id??`${Date.now()}`,model:e.name,content:y.content,usage:y.usage,stopReason:y.rawStopReason,stopSequence:null,created:Date.now(),toolCalls:y.toolCalls,normalizedStopReason:y.normalizedStopReason,providerRaw:y.providerRaw}}catch(g){let v=g.message??String(g),b=Date.now()-m;gy(h,{status:"error",durationMs:b,errorMessage:v});let y=uz(g)?` ${e.name} can't be forced to call a tool, so toolChoice "required" and named tools don't work with it. Use toolChoice "auto" (the default) and say in the prompt when to call the tool, or pass a schema to get a fixed JSON shape.`:"",C=new Error(`Error while making request to ${n.name}: ${v}${y}`,{cause:g});throw s&&Me(C),C}}function Mte(r,t,e){return r!=="openai"||!Array.isArray(t.tools)||t.tools.length===0||t.reasoning_effort!==void 0||!Fte.test(e)?null:{...t,reasoning_effort:"none"}}async function Gz(r,t,e){try{return await r()}catch(n){let i=n.message??String(n),{sentKeys:o,model:s,provider:a,logPrefix:l,advancedSettings:c}=e;if(!Mz(i,o))throw n;let d=sF(o),u=o.length>1?"them":"it";return S.logMessage(`[${l}] ${a.name} rejected ${d}; retrying without sampling parameters.`),new Wz.Notice(`${s.name} doesn't accept the ${d} setting${o.length>1?"s":""}, so QuickAdd retried without ${u}.`+(c?` You can remove ${u} from this command's advanced settings.`:"")),t()}}var Wz,Fte,hT=x(()=>{Wz=require("obsidian");mT();je();cF();dF();nt();gi();qz();ye();Gv();ff();pF();pF();Fte=/function tools with reasoning_effort are not supported[\s\S]*reasoning_effort to 'none'/i});function fu(r){if(r){let t=new jz.Notice(fF("starting",""),1e6);return{setMessage:(e,n)=>{t.setMessage(fF(e,n))},hide:()=>t.hide(),fail:e=>{if(Be(e)){t.hide();return}t.setMessage(fF("dead",e?.message??String(e))),XD(e),window.setTimeout(()=>t.hide(),5e3)}}}return{setMessage:()=>{},hide:()=>{},fail:()=>{}}}var jz,fF,gT=x(()=>{jz=require("obsidian");nt();fF=(r,t)=>`${r==="dead"?"AI request failed.":`Assistant is ${r}.`}${t?`
|
||
|
||
${t}`:""}`});function Ote(){return Array.from(new Set([hF,...["kebab","snake","camel","pascal","title","lower","upper","slug"].map(r=>Jh(hF,r))])).filter(Boolean)}function Kz(r){if(r.length<=1)return null;let t=Math.floor(r.length/2),e=[`
|
||
|
||
`,`
|
||
`,". "," "],n=-1,i=Number.POSITIVE_INFINITY;for(let a of e){let l=r.lastIndexOf(a,t),c=r.indexOf(a,t),d=[l,c].filter(u=>u>0);for(let u of d){let p=u+a.length;if(p<=0||p>=r.length)continue;let m=Math.abs(p-t);m<i&&(i=m,n=p)}}if(n>0&&n<r.length)return[r.slice(0,n),r.slice(n)];let o=t,s=r.charCodeAt(o);return s>=56320&&s<=57343&&(o+=1),o<=0||o>=r.length?null:[r.slice(0,o),r.slice(o)]}function Dte(r){let t=new RegExp(Td.source,"gi"),e=qi(r),n;for(;(n=t.exec(e))!==null;)if(n[1].split("|")[0].trim().toLowerCase()==="chunk")return!0;return!1}function Lte(r){return As.test(r)||nw.test(r)||iw.test(r)||yi(r).length>0}function Nte(r){return Yz.some(t=>r.includes(t))}function Vte(r){return Yz.slice().sort((t,e)=>e.length-t.length).reduce((t,e)=>t.split(e).join(" "),r)}function Qz(r){if(r>yT)throw new Error(`This chunked AI request would split into more than ${yT} prompts, which exceeds the safety limit. Increase the chunk size, use a larger chunk separator, or reduce the input text.`)}function Bte(r,t,e){let n=Math.max(1,Math.floor(t)),i=[r],o=0;for(;i.length>0;){let s=i.pop(),l=Ti(s)<=n?null:Kz(s);if(!l){e.push(s),o+=1,Qz(o);continue}i.push(l[1],l[0])}}function Ute(r){let t=r.flags.replace(/[gy]/g,"");return new RegExp(r.source+"|",t).exec("").length-1}function zte(r,t){if(typeof t=="string"){let s=r.split(t);return{chunks:s,separators:new Array(Math.max(0,s.length-1)).fill(t)}}if(Ute(t)>0||qte.test(t.source))return{chunks:r.split(t),separators:null};let e=new RegExp(`(${t.source})`,t.flags),n=r.split(e),i=[],o=[];for(let s=0;s<n.length;s++)s%2===0?i.push(n[s]):o.push(n[s]);return{chunks:i,separators:o}}function Hte(r,t,e,n){let i=[];if(r.forEach((l,c)=>{let d=[];Bte(l,e,d),d.forEach((u,p)=>{i.push({text:u,joiner:p===0&&c>0?t?.[c-1]??"":""})})}),!n)return i.map(l=>l.text);let o=[],s="",a=0;for(let l of i){let c=Ti(l.text)+Math.max(1,Ti(l.joiner));s!==""&&a+c>=e&&(o.push(s),s="",a=0),s+=s===""?l.text:l.joiner+l.text,a+=c}return s!==""&&o.push(s),o}function Wte(r,t){let e=Math.max(1,Math.floor(r));if(t!==void 0&&Number.isFinite(t)&&t>0){let n=Math.floor(t);return{budget:Math.min(e,n),clamped:n>e}}return{budget:e,clamped:!1}}async function gF(r,t,e){if(U.getState().disableOnlineFeatures)throw new Error("Online features are disabled in settings. Enable them to use the AI Assistant.");let n=fu(t.showAssistantMessages);try{let{apiKey:i,model:o,provider:s,outputVariableName:a,systemPrompt:l,promptTemplate:c,text:d,modelOptions:u}=t;n.setMessage("chunking","Creating prompt chunks with text and prompt template");let p=t.chunkSeparator||/\n/g,{chunks:m,separators:h}=zte(d,p),g=await e(c,{chunk:hF});if(!(Dte(c)||Lte(c)&&Nte(g)))throw new Error("The chunked prompt template does not reference the chunk text. Add {{VALUE:chunk}} to your prompt template so each chunk is inserted.");let b=o.maxTokens,y=mU(b),C=Vte(g),w=Ti(l)+Ti(C);if(w>=b)throw new Error(`The estimated prompt overhead (${w} tokens) exceeds the model's entire context window (${b} tokens). Shorten the system prompt or prompt template, or use a model with a larger context window.`);let{budget:T,clamped:P}=Wte(y-w,t.maxChunkTokens);P&&S.logMessage(`[ChunkedPrompt] Requested max chunk tokens (${t.maxChunkTokens}) exceeds this model's estimated input budget; using ${T} estimated tokens per chunk instead.`);let _=t.shouldMerge??!0,I=Hte(m,h,T,_);Qz(I.length);let D=by(r,i,o,s,l,u,!t.showAssistantMessages),N=["prompting",`${I.length} prompts being sent.`];n.setMessage(N[0],N[1]);let K=new vT(5,1e3*30),ne=!1,H=0,O=Promise.resolve(),G=W=>{let Z=O.then(()=>{if(ne)throw new Error("Chunked prompt stopped after an earlier failure.");return e(c,{chunk:W})});return O=Z.then(()=>{},()=>{}),Z},V=async(W,Z=0)=>{if(ne)throw new Error("Chunked prompt stopped after an earlier failure.");let se;try{se=await G(W)}catch(ce){throw ne=!0,ce}try{return[(await K.add(()=>{if(ne)throw new Error("Chunked prompt stopped after an earlier failure.");if(H+=1,H>yT)throw new Error(`Chunked AI request exceeded the safety limit of ${yT} provider requests.`);return D(se)})).content]}catch(ce){let $e=Kz(W);if(Z>=Rte||!$e||!dz(ce))throw ne=!0,ce;n.setMessage("prompting","Provider rejected a prompt for context length. Retrying with smaller chunks.");let[Xe,Ye]=$e,he=await V(Xe,Z+1),Re=await V(Ye,Z+1);return[...he,...Re]}},M=Promise.all(I.map(W=>V(W))),te=(await my(M,n,N)).flat().join(t.resultJoiner);return window.setTimeout(()=>n.hide(),5e3),fy(a,te)}catch(i){throw n.fail(i),i}}var vT,Rte,yT,hF,Yz,qte,Xz=x(()=>{je();hT();ff();gT();Gv();ye();Le();Oa();Wd();ww();nF();vT=class{constructor(t,e){this.maxRequests=t;this.intervalMs=e;this.queue=[];this.startTimes=[]}add(t){return new Promise((e,n)=>{this.queue.push(async()=>{try{e(await t())}catch(i){n(i instanceof Error?i:new Error(String(i)))}}),this.schedule()})}schedule(){if(this.queue.length===0)return;let t=Date.now();if(this.startTimes=this.startTimes.filter(i=>t-i<this.intervalMs),this.startTimes.length>=this.maxRequests){let i=this.startTimes[0],o=Math.max(0,this.intervalMs-(t-i));window.setTimeout(()=>this.schedule(),o+1);return}let e=this.queue.shift();if(!e)return;this.startTimes.push(t);let n=e();window.setTimeout(()=>this.schedule(),this.intervalMs),this.schedule()}},Rte=12,yT=500,hF="quickadd_chunk_probe_123456789";Yz=Ote();qte=/(?:^|[^\\])(?:\\\\)*\\[1-9]/});async function Gte(r,t,e,n=!0,i){let o;if(t.enable)o=e.find(c=>c.path.endsWith(t.name));else{let c=e.map(d=>d.basename);if(i)o=await i.suggester(c,e,"Select a prompt template");else if(n)o=await It.Suggest(r,c,e,"Select a prompt template");else throw new de("This AI command asks which prompt template to use, but this run is non-interactive. Enable a specific prompt template in the command, or re-run with the ui flag.")}Vr(o,"Prompt template does not exist");let s=o.path,a=r.vault.getAbstractFileByPath(s);Vr(a instanceof Jz.TFile,`${s} is not a file`);let l=await r.vault.cachedRead(a);return[o.basename,l]}async function Zz(r,t,e){if(U.getState().disableOnlineFeatures)throw new Error("Online features are disabled in settings. Enable them to use the AI Assistant.");let n=fu(t.showAssistantMessages);try{let{apiKey:i,model:o,provider:s,outputVariableName:a,promptTemplate:l,systemPrompt:c,promptTemplateFolder:d}=t,u=ts(r,d),[p,m]=await Gte(r,l,u,t.interactive??!0,t.promptProvider);n.setMessage("waiting","QuickAdd is formatting the prompt template.");let h=await e(m),g=["prompting",`Using prompt template "${p}".`];n.setMessage(g[0],g[1]);let b=by(r,i,o,s,c,t.modelOptions,!t.showAssistantMessages)(h),C=(await my(b,n,g)).content;return window.setTimeout(()=>n.hide(),5e3),fy(a,C)}catch(i){throw n.fail(i),Be(i)?new et("Input cancelled by user"):i}}async function e2(r,t,e){if(U.getState().disableOnlineFeatures)throw new Error("Online features are disabled in settings. Enable them to use the AI Assistant.");let n=fu(t.showAssistantMessages);try{let{apiKey:i,model:o,provider:s,outputVariableName:a,systemPrompt:l,prompt:c,modelOptions:d}=t;n.setMessage("waiting","QuickAdd is formatting the prompt template.");let u=await e(c),p=["prompting","Using custom prompt."];n.setMessage(p[0],p[1]);let h=by(r,i,o,s,l,d,!t.showAssistantMessages)(u),v=(await my(h,n,p)).content;return window.setTimeout(()=>n.hide(),5e3),fy(a,v)}catch(i){throw n.fail(i),i}}var Jz,vF=x(()=>{nF();Jz=require("obsidian");rr();Sn();Qi();je();bi();Nd();nt();hT();gT();cF();Xz()});function t2(r){return r.replace(jte,t=>t+"\uFDD0")}function An(r){return r.includes("\uFDD0")?r.replace(Yte,"$1"):r}function wy(r,t){if(!r.includes("\uFDD0"))return{content:r,offsets:t};let e=n=>An(r.slice(0,n)).length;return{content:An(r),offsets:typeof t=="number"?e(t):t.map(e)}}function bT(r){let{cursor:t}=r,e=wy(r.content,t.kind==="offset"?t.value:0);return{content:e.content,cursor:t.kind==="offset"?{...t,value:e.offsets}:t}}var jte,Yte,vf=x(()=>{jte=/\{(?=\{)|<(?=%)|%(?=>)/g,Yte=/([{<%])\uFDD0(?=[{%>])/g});var r2,Pc,yF=x(()=>{r2=require("obsidian");SP();Hh();Pc=class r extends Nm{static Prompt(t,e,n,i,o,s){return new r(t,e,n,i,o,s).waitForClose}getPromptKind(){return"multi"}createInputField(t,e,n){let i=new r2.TextAreaComponent(t);return i.inputEl.classList.add("wideInputPromptInputEl"),i.inputEl.setAttribute("dir","auto"),this.disposeIndent=zh(i.inputEl),this.configureInput(i,e,n)}shouldSubmit(t){return(t.ctrlKey||t.metaKey)&&t.key==="Enter"}disposeInput(){this.disposeIndent?.()}}});var Cy,n2=x(()=>{Gs();xo();Cy=class r extends ir{supportsPeek(){return!1}static Prompt(t,e,n,i,o,s){return new r(t,e,n,i,o,s).waitForClose}createInputField(t,e,n){let i=super.createInputField(t,e,n);i.inputEl.type="number",i.inputEl.inputMode="decimal";let o=this.options?.numeric;return o?.min!==void 0&&(i.inputEl.min=String(o.min)),o?.max!==void 0&&(i.inputEl.max=String(o.max)),i.inputEl.setAttr("step",o?.step!==void 0?String(o.step):"any"),i}transformInputOnSubmit(t){return this.options?.numeric?t===""&&this.isOptionalPrompt?"":Co(t,this.options.numeric):t}}});var bF,xy,i2=x(()=>{Gs();xo();bF={min:0,max:100,step:1},xy=class r extends ir{supportsPeek(){return!1}static Prompt(t,e,n,i,o,s){return new r(t,e,n,i,o,s).waitForClose}createInputField(t,e,n){let i=this.options?.slider??bF,o=this.isOptionalPrompt&&!n,s=Tp(n,i);this.sliderEl=t.createEl("input"),this.sliderEl.type="range",this.sliderEl.min=String(i.min),this.sliderEl.max=String(i.max),this.sliderEl.step=String(i.step),this.sliderEl.value=s,this.sliderEl.setCssStyles({width:"100%"});let a=super.createInputField(t,void 0,s);return this.numberEl=a.inputEl,this.numberEl.type="number",this.numberEl.inputMode="decimal",this.numberEl.min=String(i.min),this.numberEl.max=String(i.max),this.numberEl.step=String(i.step),o&&(this.numberEl.value=""),this.sliderEl.addEventListener("input",()=>this.syncFromSlider()),this.numberEl.addEventListener("input",()=>this.syncFromNumber()),a}syncFromSlider(){!this.sliderEl||!this.numberEl||(this.numberEl.value=this.sliderEl.value,this.onInputChanged(this.sliderEl.value))}syncFromNumber(){if(!this.sliderEl||!this.numberEl)return;let t=this.numberEl.value;if(t===""&&this.isOptionalPrompt){this.onInputChanged("");return}let e=Co(t,this.options?.slider??bF);e!==""&&(this.sliderEl.value=e),this.onInputChanged(t)}transformInputOnSubmit(t){return t===""&&this.isOptionalPrompt?"":Tp(t,this.options?.slider??bF)}}});var hu,wF=x(()=>{yF();Gs();n2();i2();ss();hu=class{factory(t){return t==="multiline"?Pc:t==="number"?Cy:t==="slider"?xy:Wr().settings.inputPrompt==="multi-line"?Pc:ir}}});function CF(r){return r.normalize("NFKD").toLowerCase()}var s2,o2,Kte,gu,xF=x(()=>{s2=require("obsidian"),o2=200,Kte=0;gu=class{constructor(t,e){this.options=e;this.instanceId=++Kte;this.indexedItems=[];this.renderedRows=[];this.query="";this.rootEl=t.createDiv({cls:"qa-searchable-multi-select"});let n=this.rootEl.createDiv({cls:"search-input-container qa-searchable-multi-select__search-container"});this.searchInputEl=n.createEl("input",{cls:"qa-searchable-multi-select__search",type:"search",placeholder:e.searchPlaceholder??"Search options..."}),this.searchInputEl.name=`qa-multi-select-search-${this.instanceId}`,this.searchInputEl.setAttribute("aria-label",this.searchInputEl.placeholder),this.searchInputEl.setAttribute("autocomplete","off"),this.searchInputEl.setAttribute("spellcheck","false"),this.summaryEl=this.rootEl.createDiv({cls:"qa-searchable-multi-select__summary"}),this.summaryEl.setAttribute("aria-live","polite"),this.listEl=this.rootEl.createDiv({cls:"qa-searchable-multi-select__list"}),this.listEl.setAttribute("role","group"),this.listEl.setAttribute("aria-label","Options"),this.searchInputEl.addEventListener("input",()=>{this.query=this.searchInputEl.value,this.renderList()}),this.searchInputEl.addEventListener("keydown",i=>{if(i.key==="ArrowDown"){i.preventDefault(),this.renderedRows[0]?.input.focus();return}i.key==="ArrowUp"&&(i.preventDefault(),this.renderedRows.at(-1)?.input.focus())}),this.setItems(e.items)}setItems(t){this.indexedItems=t.map((e,n)=>({item:e,index:n,searchableText:CF(`${e.label} ${e.searchText??""}`),searchableAliases:(e.aliases??[]).map(CF)})),this.searchInputEl.disabled=t.length===0,this.renderList()}clearSearch(){return this.query?(this.query="",this.searchInputEl.value="",this.renderList(),this.searchInputEl.focus(),!0):!1}focusSearchOnOpen(){document.body.classList.contains("is-mobile")||this.searchInputEl.focus()}refreshSelection(){for(let{item:t,input:e}of this.renderedRows)e.checked=this.options.isSelected(t),e.closest("label")?.classList.toggle("is-selected",e.checked);this.updateSummary()}getMatchingItems(){let t=CF(this.query.trim()).split(/\s+/).filter(Boolean);if(t.length===0)return this.indexedItems;let e=i=>t.every(o=>i.includes(o)),n=[];for(let i of this.indexedItems){if(e(i.searchableText)){n.push(i);continue}let o=i.searchableAliases.findIndex(e);o>=0&&n.push({...i,alias:i.item.aliases?.[o]})}return n}getVisibleItems(t){if(t.length<=o2)return t;let e=[],n=[];for(let i of t)(this.options.isSelected(i.item)?e:n).push(i);return[...e,...n].slice(0,o2)}renderList(){this.listEl.replaceChildren(),this.renderedRows=[];let t=this.getMatchingItems(),e=this.getVisibleItems(t);if(e.length===0){let n=this.listEl.createDiv({cls:"qa-searchable-multi-select__empty"});n.setAttribute("role","status"),n.textContent=this.indexedItems.length?`No options match \u201C${this.query.trim()}\u201D`:this.options.emptyText??"No options available"}for(let n of e)this.renderRow(n);if(t.length>e.length){let n=this.listEl.createDiv({cls:"qa-searchable-multi-select__limit"});n.setAttribute("role","status"),n.textContent=`Showing ${e.length} of ${t.length} options. Refine your search to see the rest.`}this.updateSummary(t.length)}renderRow(t){let{item:e,index:n,alias:i}=t,o=this.listEl.createEl("label",{cls:"qa-searchable-multi-select__option"}),s=o.createSpan({cls:"qa-searchable-multi-select__option-text"});if(s.createSpan({cls:"qa-searchable-multi-select__option-label",text:i??e.label}),i!==void 0){s.createSpan({cls:"qa-searchable-multi-select__option-note",text:e.label});let l=o.createSpan({cls:"qa-searchable-multi-select__option-flair"});l.setAttribute("aria-label","Alias"),(0,s2.setIcon)(l,"forward")}let a=o.createEl("input",{type:"checkbox"});a.name=`qa-multi-select-${this.instanceId}`,a.id=`qa-multi-select-${this.instanceId}-${n}`,a.checked=this.options.isSelected(e),o.htmlFor=a.id,o.classList.toggle("is-selected",a.checked),a.addEventListener("change",()=>{this.options.onToggle(e,a.checked),this.refreshSelection()}),a.addEventListener("keydown",l=>{this.handleOptionKeydown(l,a)}),this.renderedRows.push({item:e,input:a})}handleOptionKeydown(t,e){let n=this.renderedRows.findIndex(i=>i.input===e);if(t.key==="ArrowDown"){t.preventDefault(),this.renderedRows[n+1]?.input.focus();return}if(t.key==="ArrowUp"){t.preventDefault(),n===0?this.searchInputEl.focus():this.renderedRows[n-1]?.input.focus();return}if(t.key==="Home"){t.preventDefault(),this.renderedRows[0]?.input.focus();return}if(t.key==="End"){t.preventDefault(),this.renderedRows.at(-1)?.input.focus();return}if(t.key==="Enter"||t.key===" "){t.preventDefault(),e.checked=!e.checked,e.dispatchEvent(new Event("change",{bubbles:!0}));return}t.key==="/"&&!t.metaKey&&!t.ctrlKey&&!t.altKey&&(t.preventDefault(),this.searchInputEl.focus())}updateSummary(t=this.getMatchingItems().length){let n=`${this.options.getSelectedCount?.()??new Set(this.indexedItems.filter(({item:i})=>this.options.isSelected(i)).map(({item:i})=>i.key)).size} selected`;if(!this.query.trim()){let i=this.indexedItems.length;this.summaryEl.textContent=`${n} \xB7 ${i} ${i===1?"option":"options"}`;return}this.summaryEl.textContent=`${n} \xB7 ${t} ${t===1?"match":"matches"}`}}});var $c,Fc,EF=x(()=>{$c=require("obsidian");an();rr();Ln();xF();Fc=class r extends $c.Modal{constructor(e,n,i,o={}){super(e);this.didSubmit=!1;this.skipped=!1;this.selected=new Set;this.customValues=[];this.draft="";this.items=i,this.displayItems=n.length===i.length?n:i,this.opts=o,this.seedPreselection(o.preselected),this.waitForClose=new Promise((s,a)=>{this.resolvePromise=s,this.rejectPromise=a}),this.render(),this.open(),this.picker.focusSearchOnOpen()}static Suggest(e,n,i,o={}){return new r(e,n,i,o).waitForClose}onEscapeKey(e){if(this.picker.clearSearch()){e.preventDefault();return}super.onEscapeKey(e)}selectValue(e){!this.items.includes(e)&&!this.customValues.includes(e)&&this.customValues.push(e),this.selected.add(e)}seedPreselection(e){if(e?.length)for(let n of e){let i=n?.trim();i&&this.selectValue(i)}}render(){this.containerEl.addClass("quickAddModal","qaSearchableMultiSelectModal","qaMultiSuggester"),this.titleEl.setText(this.opts.placeholder??"Select one or more");let{contentEl:e}=this;e.empty();let n=e.createDiv({cls:"qa-multi-list"});this.picker=new gu(n,{items:this.getSearchableItems(),isSelected:({value:o})=>this.selected.has(o),onToggle:({value:o},s)=>{s?this.selected.add(o):this.selected.delete(o)},getSelectedCount:()=>this.selected.size}),this.opts.allowCustomValue&&new $c.Setting(e).setName("Add a custom value").addText(s=>{s.setPlaceholder("Not in the list\u2026").setValue(this.draft).onChange(a=>this.draft=a),s.inputEl.addClass("qa-multi-custom-input"),s.inputEl.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.commitDraft())})}).addButton(s=>s.setButtonText("Add").onClick(()=>this.commitDraft())).settingEl.addClass("qa-multi-custom");let i=new $c.Setting(e);i.settingEl.addClass("qa-multi-actions"),this.opts.skippable&&i.addButton(o=>o.setButtonText("Skip").setTooltip("Leave empty").onClick(()=>{this.skipped=!0,this.didSubmit=!0,this.close()})),i.addButton(o=>o.setButtonText("Cancel").onClick(()=>this.close())),i.addButton(o=>o.setButtonText("Done").setCta().onClick(()=>this.submit()))}getSearchableItems(){return[...this.items.map((e,n)=>({key:e,value:e,label:sn(this.displayItems[n]??e),searchText:e,aliases:this.opts.aliases?.[n]})),...this.customValues.map(e=>({key:e,value:e,label:e}))]}commitDraft(){let e=this.draft.trim();if(!e)return new $c.Notice("Enter a value to add."),!1;let n=this.typedValue(e);return(this.items.includes(n)||this.customValues.includes(n))&&this.selected.has(n)?(new $c.Notice(`"${e}" is already added.`),!1):(this.selectValue(n),this.draft="",this.render(),this.focusCustomInput(),!0)}typedValue(e){return Dd(this.items,this.opts.aliases??[],e)??e}focusCustomInput(){this.contentEl.querySelector(".qa-multi-custom-input")?.focus()}submit(){this.opts.allowCustomValue&&this.draft.trim()&&(this.selectValue(this.typedValue(this.draft.trim())),this.draft=""),this.didSubmit=!0,this.close()}collectResult(){return[...this.items,...this.customValues].filter(e=>this.selected.has(e))}onClose(){super.onClose(),this.didSubmit?this.resolvePromise(this.skipped?[]:this.collectResult()):this.rejectPromise(on())}}});var wT,Mc,Qte,Xte,Jte,l2,TF,Ey,_F,a2,CT,xT,kF=x(()=>{wT=require("obsidian");je();Mc=r=>r.toString().padStart(2,"0"),Qte=r=>{if(typeof r=="number"&&r>=0&&r<=6)return r;let e=window.moment?.localeData?.()?.firstDayOfWeek?.();return typeof e=="number"&&e>=0&&e<=6?e:0},Xte=r=>{let t=new Intl.DateTimeFormat(void 0,{weekday:"short"}),e=new Date(2021,7,1),n=Array.from({length:7},(i,o)=>{let s=new Date(e.getFullYear(),e.getMonth(),e.getDate()+o);return t.format(s)});return n.slice(r).concat(n.slice(0,r))},Jte=(r,t)=>new Intl.DateTimeFormat(void 0,{month:"long",year:"numeric"}).format(new Date(r,t,1)),l2=(r,t,e)=>`${r}-${Mc(t+1)}-${Mc(e)}`,TF=r=>l2(r.getFullYear(),r.getMonth(),r.getDate()),Ey=r=>{if(!r)return null;let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(t){let[,n,i,o]=t;return new Date(Number.parseInt(n,10),Number.parseInt(i,10)-1,Number.parseInt(o,10))}let e=new Date(r);return Number.isNaN(e.getTime())?null:e},_F=(r,t,e,n)=>{let i=l2(r,t,e);return n?`${i}T${Mc(n.hour)}:${Mc(n.minute)}:00`:i},a2=r=>{if(!r)return null;let t=/[T ](\d{2}):(\d{2})/.exec(r);if(!t)return null;if(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(r)){let i=new Date(r);return Number.isNaN(i.getTime())?null:{hour:i.getHours(),minute:i.getMinutes()}}let e=Number.parseInt(t[1],10),n=Number.parseInt(t[2],10);return Number.isNaN(e)||Number.isNaN(n)||e<0||e>23||n<0||n>59?null:{hour:e,minute:n}},CT=r=>{let t=Qte(r.weekStartsOn),e=Xte(t),n=Ey(r.initialIso)??new Date,i=n.getFullYear(),o=n.getMonth(),s=r.initialIso,a=r.withTime===!0,l=a?a2(r.initialIso)??{hour:0,minute:0}:null,c=r.container.createDiv({cls:"qa-date-picker"}),d=c.createDiv({cls:"qa-date-picker__header"}),u=d.createEl("button",{cls:"qa-date-picker__nav clickable-icon"});(0,wT.setIcon)(u,"chevron-left"),u.type="button",u.tabIndex=-1,u.setAttr("aria-label","Previous month");let p=d.createDiv({cls:"qa-date-picker__label"}),m=d.createEl("button",{cls:"qa-date-picker__nav clickable-icon"});(0,wT.setIcon)(m,"chevron-right"),m.type="button",m.tabIndex=-1,m.setAttr("aria-label","Next month");let h=c.createDiv({cls:"qa-date-picker__weekdays"});e.forEach(I=>{let D=h.createDiv({cls:"qa-date-picker__weekday"});D.textContent=I});let g=c.createDiv({cls:"qa-date-picker__grid"}),v=c.createDiv({cls:"qa-date-picker__actions"}),b=v.createEl("button",{cls:"qa-date-picker__action",text:"Today"});b.type="button",b.tabIndex=-1;let y=v.createEl("button",{cls:"qa-date-picker__action",text:"Clear"});y.type="button",y.tabIndex=-1;let C;if(a){let I=c.createDiv({cls:"qa-date-picker__time"});I.createEl("label",{cls:"qa-date-picker__time-label",text:"Time"}),C=I.createEl("input",{cls:"qa-date-picker__time-input",attr:{"aria-label":"Time"}}),C.type="time",C.tabIndex=-1,l&&(C.value=`${Mc(l.hour)}:${Mc(l.minute)}`)}let w=I=>{o+=I,o>11?(o=0,i+=1):o<0&&(o=11,i-=1),_()},T=(I,D)=>{s=I,r.onSelect(I,D),_()},P=I=>{s=void 0,r.onSelect(null,I),_()};u.addEventListener("click",()=>w(-1)),m.addEventListener("click",()=>w(1)),b.addEventListener("click",()=>{let I=new Date,D=_F(I.getFullYear(),I.getMonth(),I.getDate(),l);i=I.getFullYear(),o=I.getMonth(),T(D,"action")}),y.addEventListener("click",()=>P("action")),C&&C.addEventListener("change",()=>{if(C.value.trim()==="")l={hour:0,minute:0};else{let[I,D]=C.value.split(":").map(N=>Number.parseInt(N,10));if(Number.isNaN(I)||Number.isNaN(D))return;l={hour:I,minute:D}}if(s){let I=Ey(s);I&&T(_F(I.getFullYear(),I.getMonth(),I.getDate(),l),"picker")}});let _=()=>{p.textContent=Jte(i,o),g.empty();let D=(new Date(i,o,1).getDay()-t+7)%7,N=new Date(i,o,1-D),K=TF(new Date),ne=s?Ey(s):null,H=ne?TF(ne):void 0,O=new Intl.DateTimeFormat(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric"});for(let G=0;G<42;G+=1){let V=new Date(N);V.setDate(N.getDate()+G);let M=TF(V),B=V.getMonth()!==o,J=M===K,te=H&&M===H,W=g.createEl("button",{cls:"qa-date-picker__day",text:String(V.getDate())});W.type="button",W.tabIndex=-1,W.setAttr("aria-label",O.format(V)),B&&W.addClass("is-outside"),J&&W.addClass("is-today"),te&&(W.addClass("is-selected"),W.setAttr("aria-pressed","true")),W.addEventListener("click",()=>{let Z=_F(V.getFullYear(),V.getMonth(),V.getDate(),l);T(Z,"picker")})}};return _(),{setSelectedIso:(I,{updateView:D}={})=>{if(s=I,I&&D!==!1){let N=Ey(I);N&&(i=N.getFullYear(),o=N.getMonth())}if(a&&I){let N=a2(I);N&&(l=N,C&&(C.value=`${Mc(N.hour)}:${Mc(N.minute)}`))}_()},setViewFromIso:I=>{let D=Ey(I);D&&(i=D.getFullYear(),o=D.getMonth(),_())},destroy:()=>{c.remove()}}},xT=(r,t)=>{let e=r.createEl("button",{cls:"qa-date-field__calendar clickable-icon"});e.type="button",e.tabIndex=-1,(0,wT.setIcon)(e,"calendar"),e.addEventListener("mousedown",i=>i.preventDefault()),e.addEventListener("click",()=>{U.setState({showDateCalendar:!U.getState().showDateCalendar})});let n=i=>{t.toggle(i),e.toggleClass("is-shown",i),e.setAttr("aria-label",i?"Hide calendar":"Show calendar")};return n(U.getState().showDateCalendar),U.subscribe(i=>n(i.showDateCalendar))}});function Rc(r,t,e=So,n){if(!r||!r.trim())return{isValid:!1,error:"Empty input"};try{let i=n??U.getState().dateAliases,o=Ih(r,i),s=e.parseDate(o);if(s?.moment?.isValid()){let a=s.moment.toISOString(),l=t?s.moment.format(t):s.moment.format("YYYY-MM-DD");return{isValid:!0,isoString:a,formatted:l}}else return{isValid:!1,error:"Unable to parse date"}}catch(i){return{isValid:!1,error:`Parse error: ${i instanceof Error?i.message:"Unknown error"}`}}}function Mo(r,t){if(!window.moment)return null;try{let e=window.moment(r);if(e.isValid())return e.format(t)}catch{}return null}var vu=x(()=>{Qd();je();wd()});var bf,yf,fl,ET=x(()=>{bf=require("obsidian");Gs();kF();vu();yP();je();wd();yf=class yf extends ir{constructor(e,n,i,o,s,a,l){super(e,n,i,o??"",void 0,a);this.isOpen=!0;if(this.containerEl.addClass("qaDatePrompt"),this.withTime=l===!0,this.dateFormat=s||(this.withTime?"YYYY-MM-DD HH:mm":"YYYY-MM-DD"),this.defaultValue=o,this.currentInput=this.inputComponent?.inputEl?.value??o??"",this.mountDatePicker(),this.currentInput.startsWith("@date:")){let c=this.currentInput.slice(6).trim();c&&Mo(c,this.dateFormat)!==null&&(this.applyPickerSelection(c,!1),_x(this.inputComponent.inputEl,a))}this.updatePreviewDebounced=(0,bf.debounce)(this.updatePreview.bind(this),250,!0),this.updatePreview()}supportsPeek(){return!1}static Prompt(e,n,i,o,s,a,l){return new yf(e,n,i,o,s,a,l).waitForClose}createInputField(e,n,i){e.addClass("qa-date-input"),this.dateFieldEl=e.createDiv({cls:"qa-date-field"});let o=new bf.TextComponent(this.dateFieldEl);return o.inputEl.addClass("qa-vdate-input"),o.setPlaceholder(n??"").setValue(i??"").onChange(s=>{this.lastPickerDisplayValue=void 0,this.onInputChanged(s),this.currentInput=s,this.updatePreviewDebounced()}).inputEl.addEventListener("keydown",this.submitEnterCallback),this.currentInput=i??"",this.pickerHostEl=e.createDiv({cls:"qa-date-picker-container"}),this.createPreviewElement(e),o}mountDatePicker(){this.datePicker=CT({container:this.pickerHostEl,initialIso:this.selectedIso,withTime:this.withTime,onSelect:e=>{e?this.applyPickerSelection(e):this.clearPickerSelection()}}),this.unsubscribeCalendarToggle=xT(this.dateFieldEl,this.pickerHostEl)}createPreviewElement(e){let n=e.createDiv("vdate-preview-container");n.createDiv({text:"Preview:",cls:"vdate-preview-label"}),this.previewEl=n.createDiv({cls:"vdate-preview-text"}),this.previewEl.textContent=yf.PREVIEW_PLACEHOLDER;let i=Ph(U.getState().dateAliases);if(i.length>0){let o=n.createEl("details",{cls:"vdate-alias-details"});o.createEl("summary",{text:`Aliases (${i.length})`}).addClass("vdate-alias-summary");let a=o.createDiv({cls:"vdate-alias-list"});a.textContent=ew(U.getState().dateAliases)}}updatePreview(){if(!this.isOpen)return;let e=this.currentInput.trim();if(!e&&this.defaultValue&&!this.isOptionalPrompt){this.renderPreviewFromInput(this.defaultValue);return}if(!e){this.selectedIso=void 0,this.lastPickerDisplayValue=void 0,this.syncPickerSelection(),this.setPreviewText(this.isOptionalPrompt?"Will be left empty":yf.PREVIEW_PLACEHOLDER,!1);return}if(e.startsWith("@date:")){let n=e.slice(6).trim();if(n){this.selectedIso=n,this.lastPickerDisplayValue=void 0,this.syncPickerSelection(n),this.renderPreviewFromIso(n);return}}if(this.selectedIso&&this.lastPickerDisplayValue&&e===this.lastPickerDisplayValue){this.syncPickerSelection(this.selectedIso,!1),this.renderPreviewFromIso(this.selectedIso);return}this.renderPreviewFromInput(e)}formatIsoForInput(e){let n=Mo(e,this.dateFormat);return n||(e.length>=10?e.slice(0,10):e)}syncPickerSelection(e,n=!0){this.datePicker?.setSelectedIso(e,{updateView:n})}applyPickerSelection(e,n=!0){let i=this.formatIsoForInput(e);this.selectedIso=e,this.lastPickerDisplayValue=i,this.inputComponent?.inputEl&&(this.inputComponent.inputEl.value=i),n?this.onInputChanged(i):this.input=i,this.currentInput=i,this.syncPickerSelection(e),this.renderPreviewFromIso(e)}clearPickerSelection(){this.inputComponent?.inputEl&&(this.inputComponent.inputEl.value=""),this.onInputChanged(""),this.currentInput="",this.selectedIso=void 0,this.lastPickerDisplayValue=void 0,this.syncPickerSelection(),this.updatePreview()}renderPreviewFromIso(e){this.setPreviewText(this.formatIsoForInput(e),!1)}renderPreviewFromInput(e){let n=Rc(e,this.dateFormat);if(n.isValid&&n.isoString){this.selectedIso=n.isoString,this.lastPickerDisplayValue=void 0,this.syncPickerSelection(n.isoString);let i=n.formatted??this.formatIsoForInput(n.isoString);this.setPreviewText(i,!1)}else{this.selectedIso=void 0,this.lastPickerDisplayValue=void 0,this.syncPickerSelection();let i=n.error||"Unable to parse date";this.setPreviewText(i,!0)}}setPreviewText(e,n){this.previewEl.textContent=e,this.previewEl.toggleClass("is-error",n)}onOpen(){super.onOpen()}transformInputOnSubmit(e){let n=e.trim();if(n.startsWith("@date:"))return n;if(this.selectedIso&&this.lastPickerDisplayValue&&n===this.lastPickerDisplayValue)return`@date:${this.selectedIso}`;if(!n&&this.defaultValue&&!this.isOptionalPrompt){let i=Rc(this.defaultValue,this.dateFormat);if(i.isValid&&i.isoString)return`@date:${i.isoString}`}if(n){let i=Rc(n,this.dateFormat);if(i.isValid&&i.isoString)return`@date:${i.isoString}`;new bf.Notice(`QuickAdd: "${n}" could not be parsed as a date; using it as-is.`)}return e}onClose(){this.isOpen=!1,this.updatePreviewDebounced.cancel(),this.unsubscribeCalendarToggle?.(),!this.input.trim()&&this.defaultValue&&!this.isOptionalPrompt&&(this.input=this.defaultValue),super.onClose()}};yf.PREVIEW_PLACEHOLDER="Preview will appear here";fl=yf});async function c2(r,t,e){let n=r.executor?.promptProvider;if(n)return e?.type==="VDATE"?await n.datePrompt(e.label??t??"Enter date",{defaultValue:e.defaultValue,dateFormat:e.dateFormat??"YYYY-MM-DD",withTime:e.withTime}):e?.inputTypeOverride==="checkbox"?String(await n.suggester(["true","false"],["true","false"],e.label??t??"Choose value",!1)):await n.inputPrompt(e?.label??t??"Enter value",e?.placeholder,e?.defaultValue);r.assertInteractivePrompt(t?`{{VALUE:${t}}}`:"a template variable");try{let i=e?.label??t??"Enter value",o=hw(r.scope),s=vp(r.runContext,i,{showDestination:o}),a=vp(r.runContext,i,{elide:!1,showDestination:o});return e?.type==="VDATE"?await fl.Prompt(r.app,i,e.withTime?"Enter a date & time (e.g., 'tomorrow at 3pm', '2025-12-25 14:30')":"Enter a date (e.g., 'tomorrow', 'next friday', '2025-12-25')",e.defaultValue,e.dateFormat??"YYYY-MM-DD",{optional:e.optional,contextLine:s,contextLineFull:a,draftScopeId:r.runContext?.draftScopeId},e.withTime):e?.inputTypeOverride==="checkbox"?await It.Suggest(r.app,["true","false"],["true","false"],e.label??t??"Choose value",void 0,e.optional?{skippable:!0}:void 0):await new hu().factory(e?.inputTypeOverride).Prompt(r.app,i,e?.placeholder??(e?.defaultValue?e.defaultValue:void 0),e?.defaultValue,void 0,r.buildInputPromptOptions(e,s,a))}catch(i){throw Be(i)?new et("Input cancelled by user"):i}}async function d2(r,t,e=!1,n){let i=r.executor?.promptProvider;if(i)return String(await i.suggester(n?.displayValues??t,t,n?.placeholder,e));r.assertInteractivePrompt(n?.variableKey?`{{VALUE:${n.variableKey}}}`:"a value choice");try{let o=n?.displayValues??t;return e?await vr.Suggest(r.app,o,t,{...n?.placeholder?{placeholder:n.placeholder}:{},...n?.optional?{skippable:!0}:{}}):await It.Suggest(r.app,o,t,n?.placeholder,void 0,n?.optional?{skippable:!0}:void 0)}catch(o){throw Be(o)?new et("Input cancelled by user"):o}}async function u2(r,t,e=!1,n){let i=n?.displayValues??t,o=r.executor?.promptProvider;if(o)return await o.suggesterMulti(i,t,{placeholder:n?.placeholder,allowCustomInput:e});r.assertInteractivePrompt(n?.variableKey?`{{VALUE:${n.variableKey}}}`:"a multi-select value");try{return await Fc.Suggest(r.app,i,t,{...n?.placeholder?{placeholder:n.placeholder}:{},allowCustomValue:e,...n?.optional?{skippable:!0}:{}})}catch(s){throw Be(s)?new et("Input cancelled by user"):s}}var p2=x(()=>{yp();wF();cl();Qi();EF();ET();rr();nt()});var hl,TT=x(()=>{hl=class r{constructor(){this.cache=new Map;this.TTL=300*1e3;this.MAX_CACHE_ENTRIES=100;this.cleanupInterval=null;this.revision=0}static getInstance(){return r.instance||(r.instance=new r),r.instance}startAutomaticCleanup(t){if(this.cleanupInterval===null&&typeof window<"u"){let e=window.setInterval(()=>{this.cleanExpired()},6e4);this.cleanupInterval=t(e)}}registerInvalidationListeners(t,e){let n=()=>this.clear();e(t.metadataCache.on("changed",n)),e(t.metadataCache.on("deleted",n)),e(t.vault.on("rename",n))}get(t,e){let n=this.makeKey(t,e),i=this.cache.get(n);return i?Date.now()-i.timestamp>this.TTL?(this.cache.delete(n),null):new Set(i.values):null}set(t,e,n){let i=this.makeKey(t,n);this.cache.size>=this.MAX_CACHE_ENTRIES&&!this.cache.has(i)&&this.evictOldestEntries(1),this.cache.set(i,{fieldName:t,values:new Set(e),timestamp:Date.now()})}getRevision(){return this.revision}setIfRevision(t,e,n,i){return this.revision!==i?!1:(this.set(t,e,n),!0)}evictOldestEntries(t){let e=Array.from(this.cache.entries()).sort(([,n],[,i])=>n.timestamp-i.timestamp).slice(0,t);for(let[n]of e)this.cache.delete(n)}clear(t){if(this.revision++,!t){this.cache.clear();return}for(let[e,n]of this.cache)n.fieldName===t&&this.cache.delete(e)}cleanExpired(){let t=Date.now();for(let[e,n]of this.cache)t-n.timestamp>this.TTL&&this.cache.delete(e)}getStats(){return{size:this.cache.size,maxSize:this.MAX_CACHE_ENTRIES,cleanupInterval:this.cleanupInterval}}destroy(){this.cleanupInterval=null,this.clear()}makeKey(t,e){return JSON.stringify([t,e||null])}}});var _T,m2=x(()=>{_T=class{static deduplicate(t,e=!1){let n=new Map;for(let o of t){let s=e?o:o.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase();n.has(s)||n.set(s,o)}let i=Array.from(n.values());return i.sort((o,s)=>e?o.localeCompare(s):o.toLowerCase().localeCompare(s.toLowerCase())),{values:i,duplicatesRemoved:t.length-i.length}}}});var ea,SF=x(()=>{Le();m2();ea=class{static processValues(t,e){let n=t.size,i=Array.from(t).filter(l=>!this.isUnresolvedFieldToken(l)),o=_T.deduplicate(i,e.caseSensitive);i=o.values;let{processedValues:s,hasDefault:a}=this.applyDefaultValues(i,e);return i=s,{values:i,hasDefaultValue:a,duplicatesRemoved:o.duplicatesRemoved,totalProcessed:n}}static isUnresolvedFieldToken(t){return this.unresolvedFieldTokenRegex.test(t.trim())}static applyDefaultValues(t,e){if(!e.defaultValue)return{processedValues:t,hasDefault:!1};let n=e.defaultValue,i=[...t],o=!1,s=a=>e.caseSensitive?a===n:this.normalizeForComparison(a)===this.normalizeForComparison(n);return e.defaultAlways?(i=i.filter(a=>!s(a)),i.unshift(n),o=!0):e.defaultEmpty&&t.length===0?(i=[n],o=!0):!e.defaultEmpty&&!e.defaultAlways&&(i.some(s)||(i.unshift(n),o=!0)),{processedValues:i,hasDefault:o}}static promoteValueToFront(t,e,n=!1){let i=o=>n?o===e:this.normalizeForComparison(o)===this.normalizeForComparison(e);return[e,...t.filter(o=>!i(o))]}static canonicalizeAgainst(t,e,n=!1){if(n)return e;let i=this.normalizeForComparison(e);return t.find(o=>this.normalizeForComparison(o)===i)??e}static normalizeForComparison(t){return t.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}static getSmartDefaults(t,e){let n={status:["To Do","In Progress","Done","Cancelled"],priority:["High","Medium","Low"],type:["Note","Task","Project","Reference"],category:["Personal","Work","Study"],mood:["\u{1F60A} Good","\u{1F610} Neutral","\u{1F614} Bad"],rating:["\u2B50","\u2B50\u2B50","\u2B50\u2B50\u2B50","\u2B50\u2B50\u2B50\u2B50","\u2B50\u2B50\u2B50\u2B50\u2B50"],progress:["0%","25%","50%","75%","100%"],difficulty:["Easy","Medium","Hard"],size:["Small","Medium","Large"]},i=t.toLowerCase();if(Object.prototype.hasOwnProperty.call(n,i))return n[i];for(let[o,s]of Object.entries(n))if(i.includes(o)||o.includes(i))return s;if(e.length>0){let o=new Map;for(let s of e)o.set(s,(o.get(s)||0)+1);return Array.from(o.entries()).sort((s,a)=>a[1]-s[1]).slice(0,5).map(([s])=>s)}return[]}};ea.unresolvedFieldTokenRegex=new RegExp(`^${dp.source}$`,"i")});function f2(r){if(!r.includes(",")){let o=r.trim();return o?[o]:[]}let t=[],e="",n=!1;for(let o=0;o<r.length;o++){let s=r[o],a=r[o+1];if(s==="["&&a==="["){n=!0,e+=s;continue}if(s==="]"&&a==="]"){n=!1,e+=s;continue}if(s===","&&!n){let l=e.trim();l&&t.push(l),e="";continue}e+=s}let i=e.trim();return i&&t.push(i),t}var h2=x(()=>{});var gl,wf,AF=x(()=>{h2();gl=class gl{static parseInlineFields(t,e){let n=new Map,i=this.removeCodeBlocksAndFrontmatter(t,e),o;for(;(o=gl.INLINE_FIELD_REGEX.exec(i))!==null;){let s=o[1].trim(),a=o[2].trim();if(a){n.has(s)||n.set(s,new Set);for(let l of f2(a))n.get(s)?.add(l)}}return gl.INLINE_FIELD_REGEX.lastIndex=0,n}static removeCodeBlocksAndFrontmatter(t,e){return t=t.replace(this.FRONTMATTER_REGEX,""),t=this.filterFencedCodeBlocks(t,e?.includeCodeBlocks),t.replace(this.INLINE_CODE_SPAN_REGEX,"")}static filterFencedCodeBlocks(t,e){if(!t.includes("```"))return t;let n=new Set((e??[]).map(a=>a.trim().toLowerCase()).filter(a=>a.length>0)),i=t.split(`
|
||
`),o=[],s=null;for(let a of i){if(!s){let l=this.matchFenceOpen(a);l?s={...l,lines:[a]}:o.push(a);continue}if(this.matchFenceClose(a,s.length)){let l=s.info.trim().split(/\s+/)[0]?.toLowerCase();if(n.size>0&&l!==void 0&&l.length>0&&n.has(l))for(let d=1;d<s.lines.length;d++)o.push(s.lines[d]);s=null}else s.lines.push(a)}if(s)for(let a of s.lines)o.push(a);return o.join(`
|
||
`)}static matchFenceOpen(t){let e=this.FENCE_OPEN_REGEX.exec(this.stripTrailingCarriage(t));return e?{length:e[1].length,info:e[2]}:null}static matchFenceClose(t,e){let n=this.FENCE_CLOSE_REGEX.exec(this.stripTrailingCarriage(t));return n!==null&&n[1].length>=e}static stripTrailingCarriage(t){return t.endsWith("\r")?t.slice(0,-1):t}static getFieldValues(t,e,n){return this.parseInlineFields(t,n).get(e)||new Set}};gl.INLINE_FIELD_REGEX=/(?:^|[\n\r])(?![ \t]*[-*+][ \t]+\[[ xX]\])([^:\n\r]+?)::[ \t]*(.*)$/gmu,gl.FRONTMATTER_REGEX=/^---\r?\n[\s\S]*?\r?\n---\r?\n/,gl.INLINE_CODE_SPAN_REGEX=/`[^`]*`/g,gl.FENCE_OPEN_REGEX=/^[ \t]*(`{3,})([^`]*)$/,gl.FENCE_CLOSE_REGEX=/^[ \t]*(`{3,})[ \t]*$/;wf=gl});function IF(r){let t=[];return r.folder&&t.push(`folder:${r.folder}`),r.folders?.length&&t.push(`folders:${r.folders.join(",")}`),r.tags&&t.push(`tags:${r.tags.join(",")}`),r.inline&&t.push("inline:true"),r.inlineCodeBlocks?.length&&t.push(`inline-code-blocks:${r.inlineCodeBlocks.join(",")}`),r.caseSensitive&&t.push("case-sensitive:true"),r.excludeFolders&&t.push(`exclude-folders:${r.excludeFolders.join(",")}`),r.excludeTags&&t.push(`exclude-tags:${r.excludeTags.join(",")}`),r.excludeFiles&&t.push(`exclude-files:${r.excludeFiles.join(",")}`),r.defaultValue&&t.push(`default:${r.defaultValue}`),r.defaultEmpty&&t.push("default-empty:true"),r.defaultAlways&&t.push("default-always:true"),t.join("|")}async function g2(r,t,e){return(await PF(r,t,e)).values}async function PF(r,t,e){let n=await Zte(r,t,e),i=ea.processValues(n,e);return{values:i.values,hasDefaultValue:i.hasDefaultValue}}async function Zte(r,t,e){let n=hl.getInstance(),i=IF(e),o=n.get(t,i);if(o)return o;let s=n.getRevision(),a=await $F(r,t,e);return n.setIfRevision(t,a,i,s),a}async function $F(r,t,e){let n=t.trim().toLowerCase();if(n==="tags"||n==="tag"){let i=await ere(r,e);if(i.size>0)return i}return await nre(r,t,e)}async function ere(r,t){if(!(!!t.folder||!!t.folders?.length||!!t.tags?.length||!!t.excludeFolders?.length||!!t.excludeTags?.length||!!t.excludeFiles?.length)){let n=tre(r);if(n.size>0)return n}return await rre(r,t)}function tre(r){let t=new Set;try{let e=r.metadataCache.getTags?.();if(!e)return t;for(let n of Object.keys(e)){let o=(n.startsWith("#")?n.substring(1):n).trim();o&&t.add(o)}}catch{}return t}function Ty(r,t){if(t!=null)for(let e of Array.isArray(t)?t:[t]){let n=String(e).trim();n&&r.add(n)}}async function v2(r,t,e){let n=new Set,i=Vs.filterFiles(r.vault.getMarkdownFiles(),t,o=>r.metadataCache.getFileCache(o));for(let o=0;o<i.length;o+=50){let s=await Promise.all(i.slice(o,o+50).map(async a=>{let l=new Set;try{await e(a,l)}catch{}return l}));for(let a of s)for(let l of a)n.add(l)}return n}async function rre(r,t){return v2(r,t,(e,n)=>{let i=r.metadataCache.getFileCache(e);Ty(n,i?.frontmatter?.tags),Ty(n,i?.frontmatter?.tag);for(let o of i?.tags??[]){let s=String(o.tag??"").trim().replace(/^#/,"");s&&n.add(s)}})}async function nre(r,t,e){return v2(r,e,async(n,i)=>{let o=r.metadataCache.getFileCache(n)?.frontmatter?.[t];if(Array.isArray(o)?o.forEach(s=>Ty(i,[s])):typeof o!="object"&&Ty(i,o),e.inline){let s=await r.vault.cachedRead(n);Ty(i,[...wf.getFieldValues(s,t,{includeCodeBlocks:e.inlineCodeBlocks})])}})}var kT=x(()=>{jw();TT();SF();AF()});function ire(r,t){let e=t.trim();if(!e||!r)return null;let n=r[e];if(n===void 0){let i=e.toLowerCase(),o=Object.keys(r).find(s=>s.toLowerCase()===i);o!==void 0&&(n=r[o])}if(n==null)return null;if(Array.isArray(n)){let i=[];for(let o of n){let s=y2(o);s!==null&&i.push(s)}return i.length>0?i:null}return y2(n)}function ST(r,t,e){if(!t||t.extension!=="md")return null;let n=r.metadataCache.getFileCache(t)?.frontmatter;return ire(n,e)}function y2(r){if(r==null)return null;let t=typeof r;if(t==="string"||t==="number"||t==="boolean"){let e=String(r).trim();return e.length>0?e:null}return null}var FF=x(()=>{});async function b2({app:r,executor:t,getSourcePath:e},n){let i=t?.promptProvider;try{let{fieldName:o,filters:s,multiSelect:a,label:l}=Dn.parse(n),c=s.defaultFrom==="active"?ST(r,t?.triggerContext?.activeFile??null,o):null,{values:d,hasDefaultValue:u}=await PF(r,o,s),p=d,m=u,h=s.defaultValue;!a&&typeof c=="string"?(p=ea.promoteValueToFront(p,c,s.caseSensitive),h=c,m=!0):!a&&Array.isArray(c)&&c.length>0&&S.logMessage(`{{FIELD:${o}|default-from:active}}: the active note's "${o}" is a list value, which applies only to |multi FIELD prompts, so no default was prefilled.`);let g=l??`Enter value for ${o}`,v=a&&!l?`Select values for ${o}`:g;if(m&&h&&(v=`${v} (default: ${h})`),a){let b=p;if(p.length===0&&!s.defaultValue){let C=ea.getSmartDefaults(o,[]);C.length>0&&(b=C)}let y=c===null?void 0:(Array.isArray(c)?c:[c]).map(C=>ea.canonicalizeAgainst(b,C,s.caseSensitive));return i?await i.suggesterMulti(b,b,{placeholder:v,allowCustomInput:!0,preselected:y&&y.length>0?y:void 0}):await Fc.Suggest(r,b,b,{placeholder:v,allowCustomValue:!0,...y&&y.length>0?{preselected:y}:{}})}if(p.length===0){let b="No existing values were found in your vault.";if(!s.defaultValue){let y=ea.getSmartDefaults(o,[]);y.length>0&&(b+=`
|
||
|
||
Suggested values for ${o}: ${y.slice(0,3).join(", ")}`)}return i?await i.inputPrompt(g,b):await ir.Prompt(r,g,b,void 0,void 0,{allowPeek:!0,linkSourcePath:e()??void 0})}return i?String(await i.suggester(p,p,v,!0)):await vr.Suggest(r,p,p,{placeholder:v})}catch(o){throw Be(o)?new et("Input cancelled by user"):o}}async function w2({app:r,executor:t,getSourcePath:e},n){let i=t?.promptProvider;try{let o=Vp(r,n),s=n.label??`Select a file from ${n.folderPath}`;if(o.length===0){let p=`No matching files found in "${n.folderPath}". Type a value or leave empty.`,m=i?await i.inputPrompt(s,p):await ir.Prompt(r,s,p,void 0,void 0,{optional:n.optional||void 0,allowPeek:!0});return n.multiSelect?m?[`${Jo}${m}`]:[]:m?`${Jo}${m}`:""}let a=Ds(o,p=>r.metadataCache.getFileCache(p)),l=a.map(p=>p.label),c=a.map(p=>p.aliases),d=o.map(p=>`${Jl}${p.path}`);if(n.multiSelect)return(i?(await i.suggesterMulti(l,d,{placeholder:s,allowCustomInput:n.allowCustomInput})).map(m=>d.includes(m)?m:Dd(d,c,m)??m):await Fc.Suggest(r,l,d,{placeholder:s,allowCustomValue:n.allowCustomInput,aliases:c,...n.optional?{skippable:!0}:{}})).map(m=>d.includes(m)?m:`${Jo}${m}`);if(i){let p=String(await i.suggester(l,d,s,n.allowCustomInput));return p?d.includes(p)?p:Dd(d,c,p)??`${Jo}${p}`:""}if(n.allowCustomInput){let p=new Set(o.map(g=>g.basename.toLowerCase())),m=new Set([...l,...c.flat()].map(g=>g.toLowerCase())),h=await vr.Suggest(r,l,d,{placeholder:s,aliases:c,valueExists:g=>p.has(g.toLowerCase())||m.has(g.toLowerCase()),...n.optional?{skippable:!0}:{}});return h?d.includes(h)?h:`${Jo}${h}`:""}return await It.Suggest(r,l,d,s,void 0,{aliases:c,...n.optional?{skippable:!0}:{}})??""}catch(o){throw Be(o)?new et("Input cancelled by user"):o}}var C2=x(()=>{Gs();cl();EF();Qi();Da();kT();SF();FF();Ln();rr();nt();ye();bi()});function are(r){return`\\begin{${r}}
|
||
\u261A
|
||
\\end{${r}}\u261A`}var ore,sre,x2,MF=x(()=>{ore=["\\!","\\,","\\:","\\>","\\;","\\#","\\$","\\%","\\&","\\","_","{ }","|","^{\u261A}\u261A","[\u261A]\u261A","\\above","\\abovewithdelims","\\acute","\\aleph","\\alpha","\\amalg","\\And","\\angle","\\approx","\\approxeq","\\arccos","\\arcsin","\\arctan","\\arg","\\array","\\arrowvert","\\Arrowvert","\\ast","\\asymp","\\atop","\\atopwithdelims","\\backepsilon","\\backprime","\\backsim","\\backsimeq","\\backslash","\\bar","\\barwedge","\\Bbb","\\Bbbk","\\because","\\begin","\\beta","\\beth","\\between","\\bf","\\Bigg","\\bigg","\\Big","\\big","\\Biggl","\\Biggm","\\Biggr","\\biggl","\\biggm","\\biggr","\\Bigl","\\Bigm","\\Bigl","\\bigl","\\bigm","\\bigr","\\bigcap","\\bigcirc","\\bigcup","\\bigodot","\\bigoplus","\\bigotimes","\\bigsqcup","\\bigstar","\\bigtriangledown","\\bigtriangleup","\\biguplus","\\bigvee","\\bigwedge","\\binom","\\blacklozenge","\\blacksquare","\\blacktriangle","\\blacktriangledown","\\blacktriangleleft","\\blacktriangleright","\\bmod","\\boldsymbol","\\bot","\\bowtie","\\Box","\\boxdot","\\boxed","\\boxminus","\\boxplus","\\boxtimes","\\brace","\\bracevert","\\brack","\\breve","\\bullet","\\Bumpeq","\\bumpeq","\\cal","\\cancel","\\Cap","\\cap","\\cases","\\cdot","\\cdotp","\\cdots","\\centerdot","\\cfrac{\u261A}{\u261A}\u261A","\\check","\\checkmark","\\chi","\\choose","\\circ","\\circeq","\\circlearrowleft","\\circlearrowright","\\circledast","\\circledcirc","\\circleddash","\\circledR","\\circledS","\\class","\\clubsuit","\\colon","\\color","\\complement","\\cong","\\coprod","\\cos","\\cosh","\\cot","\\coth","\\cr","\\csc","\\cssId","\\Cup","\\cup","\\curlyeqprec","\\curlyeqsucc","\\curlyvee","\\curlywedge","\\curvearrowleft","\\curvearrowright","\\dagger","\\ddagger","\\daleth","\\dashleftarrow","\\dashrightarrow","\\dashv","\\dbinom","\\dot","\\ddot","\\dddot","\\ddddot","\\ddots","\\DeclareMathOperator","\\def","\\deg","\\Delta","\\delta","\\det","\\dfrac{\u261A}{\u261A}\u261A","\\diagdown","\\diagup","\\Diamond","\\diamond","\\diamondsuit","\\digamma","\\dim","\\displaylines","\\displaystyle","\\div","\\divideontimes","\\Doteq","\\doteq","\\dotplus","\\dots","\\dotsb","\\dotsc","\\dotsi","\\dotsm","\\dotso","\\doublebarwedge","\\doublecap","\\doublecup","\\downarrow","\\Downarrow","\\downdownarrows","\\downharpoonleft","\\downharpoonright","\\ell","\\emptyset","\\end","\\enspace","\\epsilon","\\eqalign","\\eqalignno","\\eqcirc","\\eqsim","\\eqslantgtr","\\eqslantless","\\equiv","\\eta","\\eth","\\exists","\\exp","\\fallingdotseq","\\fbox","\\Finv","\\flat","\\forall","\\frac{\u261A}{\u261A}\u261A","\\frak","\\frown","\\Game","\\Gamma","\\gamma","\\gcd","\\ge","\\geq","\\geqq","\\geqslant","\\genfrac","\\gets","\\gg","\\ggg","\\gggtr","\\gimel","\\gtrapprox","\\gnapprox","\\gneq","\\gneqq","\\gvertneqq","\\gtrsim","\\gnsim","\\grave","\\gt","\\gtrdot","\\gtreqless","\\gtreqqless","\\gtrless","\\hat","\\hbar","\\hbox","\\hdashline","\\hline","\\heartsuit","\\hfil","\\hfill","\\hom","\\hookleftarrow","\\hookrightarrow","\\hphantom","\\href","\\hskip","\\hslash","\\hspace","\\Huge","\\huge","\\iddots","\\idotsint","\\iff","\\iiiint","\\iiint","\\iint","\\int","\\intop","\\Im","\\imath","\\impliedby","\\implies","\\in","\\inf","\\infty","\\injlim","\\intercal","\\iota","\\it","\\jmath","\\Join","\\kappa","\\ker","\\kern","\\Lambda","\\lambda","\\land","\\langle","\\LARGE","\\Large","\\large","\\LaTeX","\\lbrace","\\lbrack","\\lceil","\\ldotp","\\ldots","\\le","\\leq","\\leqq","\\leqslant","\\leadsto","\\left","\\leftarrow","\\Leftarrow","\\leftarrowtail","\\leftharpoondown","\\leftharpoonup","\\leftleftarrows","\\leftrightarrow","\\Leftrightarrow","\\leftrightarrows","\\leftrightharpoons","\\leftrightsquigarrow","\\leftroot","\\leftthreetimes","\\leqalignno","\\lessapprox","\\lessdot","\\lesseqgtr","\\lesseqqgtr","\\lessgtr","\\lesssim","\\lfloor","\\lg","\\lgroup","\\lhd","\\lim","\\liminf","\\limits","\\limsup","\\ll","\\llap","\\llcorner","\\lrcorner","\\Lleftarrow","\\lll","\\llless","\\lmoustache","\\ln","\\lnapprox","\\lneq","\\lneqq","\\lnot","\\lnsim","\\log","\\longleftarrow","\\Longleftarrow","\\longrightarrow","\\Longrightarrow","\\longleftrightarrow","\\Longleftrightarrow","\\longmapsto","\\looparrowleft","\\looparrowright","\\lor","\\lower","\\lozenge","\\Lsh","\\lt","\\ltimes","\\lvert","\\lVert","\\lvertneqq","\\maltese","\\mapsto","\\mathbb","\\mathbf","\\mathbin","\\mathcal","\\mathchoice","\\mathclose","\\mathfrak","\\mathinner","\\mathit","\\mathop","\\mathopen","\\mathord","\\mathpunct","\\mathrel","\\mathring","\\mathrm","\\mathscr","\\mathsf","\\mathstrut","\\mathtt","\\matrix","\\max","\\mbox","\\measuredangle","\\mho","\\mid","\\min","\\mit","\\mod","\\models","\\moveleft","\\moveright","\\mp","\\mskip","\\mspace","\\mu","\\multimap","\\nabla","\\natural","\\ncong","\\ne","\\nearrow","\\neg","\\negthinspace","\\negmedspace","\\negthickspace","\\neq","\\newcommand","\\newenvironment","\\newline","\\nexists","\\ngeq","\\ngeqq","\\ngeqslant","\\ngtr","\\ni","\\nleftarrow","\\nLeftarrow","\\nleftrightarrow","\\nLeftrightarrow","\\nleq","\\nleqq","\\nleqslant","\\nless","\\nmid","\\nobreakspace","\\nolimits","\\normalsize","\\not","\\notag","\\notin","\\nparallel","\\nprec","\\npreceq","\\nrightarrow","\\nRightarrow","\\nshortmid","\\nshortparallel","\\nsim","\\nsubseteq","\\nsubseteqq","\\nsucc","\\nsucceq","\\nsupseteq","\\nsupseteqq","\\ntriangleleft","\\ntrianglelefteq","\\ntriangleright","\\ntrianglerighteq","\\nu","\\nVDash","\\nVdash","\\nvDash","\\nvdash","\\nwarrow","\\odot","\\ominus","\\oplus","\\oslash","\\otimes","\\oint","\\oldstyle","\\omega","\\Omega","\\omicron","\\operatorname","\\over","\\overbrace","\\overleftarrow","\\overrightarrow","\\overleftrightarrow","\\overline","\\overparen","\\overset","\\overwithdelims","\\owns","\\parallel","\\partial","\\perp","\\phantom","\\phi","\\Phi","\\pi","\\Pi","\\pitchfork","\\pm","\\pmatrix","\\pmb","\\pmod","\\pod","\\Pr","\\prec","\\precapprox","\\precnapprox","\\preccurlyeq","\\preceq","\\precneqq","\\precsim","\\precnsim","\\prime","\\prod","\\projlim","\\propto","\\psi","\\Psi","\\quad","\\qquad","\\raise","\\rangle","\\rbrace","\\rbrack","\\rceil","\\Re","\\renewcommand","\\require (non-standard)","\\restriction","\\rfloor","\\rgroup","\\rhd","\\rho","\\right","\\rightarrow","\\Rightarrow","\\rightarrowtail","\\rightharpoondown","\\rightharpoonup","\\rightleftarrows","\\rightleftharpoons","\\rightrightarrows","\\rightsquigarrow","\\rightthreetimes","\\risingdotseq","\\rlap","\\rm","\\rmoustache","\\Rrightarrow","\\Rsh","\\rtimes","\\Rule (non-standard)","\\rvert","\\rVert","\\S","\\scr","\\scriptscriptstyle","\\scriptsize","\\scriptstyle","\\searrow","\\sec","\\setminus","\\sf","\\sharp","\\shortmid","\\shortparallel","\\shoveleft","\\shoveright","\\sideset","\\sigma","\\Sigma","\\sim","\\simeq","\\sin","\\sinh","\\skew","\\small","\\smallfrown","\\smallint","\\smallsetminus","\\smallsmile","\\smash","\\smile","\\space","\\Space (non-standard)","\\spadesuit","\\sphericalangle","\\sqcap","\\sqcup","\\sqrt","\\sqsubset","\\sqsupset","\\sqsubseteq","\\sqsupseteq","\\square","\\stackrel","\\star","\\strut","\\style","\\subset","\\Subset","\\subseteq","\\subsetneq","\\subseteqq","\\subsetneqq","\\substack","\\succ","\\succapprox","\\succnapprox","\\succcurlyeq","\\succeq","\\succneqq","\\succsim","\\succnsim","\\sum","\\sup","\\supset","\\Supset","\\supseteq","\\supsetneq","\\supseteqq","\\supsetneqq","\\surd","\\swarrow","\\tag","\\tan","\\tanh","\\tau","\\tbinom","\\TeX","\\text{\u261A}\u261A","\\textbf{\u261A}\u261A","\\textit{\u261A}\u261A","\\textrm{\u261A}\u261A","\\textsf{\u261A}\u261A","\\texttt{\u261A}\u261A","\\textstyle","\\tfrac{\u261A}{\u261A}\u261A","\\therefore","\\theta","\\Theta","\\thickapprox","\\thicksim","\\thinspace","\\tilde","\\times","\\tiny","\\Tiny","\\to","\\top","\\triangle","\\triangledown","\\triangleleft","\\triangleright","\\trianglelefteq","\\trianglerighteq","\\triangleq","\\tt","\\twoheadleftarrow","\\twoheadrightarrow","\\ulcorner","\\urcorner","\\underbrace","\\underleftarrow","\\underrightarrow","\\underleftrightarrow","\\underline","\\underparen","\\underset","\\unicode","\\unlhd","\\unrhd","\\uparrow","\\Uparrow","\\updownarrow","\\Updownarrow","\\upharpoonleft","\\upharpoonright","\\uplus","\\uproot","\\upsilon","\\Upsilon","\\upuparrows","\\varDelta","\\varepsilon","\\varGamma","\\varinjlim","\\varkappa","\\varLambda","\\varlimsup","\\varliminf","\\varnothing","\\varOmega","\\varphi","\\varPhi","\\varpi","\\varPi","\\varprojlim","\\varpropto","\\varPsi","\\varrho","\\varsigma","\\varSigma","\\varsubsetneq","\\varsubsetneqq","\\varsupsetneq","\\varsupsetneqq","\\vartheta","\\varTheta","\\vartriangle","\\vartriangleleft","\\vartriangleright","\\varUpsilon","\\varXi","\\vcenter","\\vdash","\\Vdash","\\vDash","\\vdots","\\vec","\\vee","\\veebar","\\verb","\\vert","\\Vert","\\vphantom","\\Vvdash","\\wedge","\\widehat","\\widetilde","\\wp","\\wr","\\Xi","\\xi","\\xleftarrow","\\xrightarrow","\\yen","\\zeta","\\{%C\\}%C","\\langle %C \\rangle%C"],sre=["align","align*","alignat","alignat*","array","Bmatrix","bmatrix","cases","eqnarray","eqnarray*","equation","equation*","gather","gather*","matrix","pmatrix","smallmatrix","subarray","Vmatrix","vmatrix"];x2=[...ore,...sre.map(are)]});function cre(r){if(RF.has(r))return RF.get(r)??null;let t=null;try{t=(0,E2.renderMath)(r,!0)}catch{t=null}return RF.set(r,t),t}function dre(r){return OF===null&&(OF=new kc(r,{findAllMatches:!0,threshold:.8})),OF}var E2,lre,RF,OF,AT,T2=x(()=>{Ms();wx();E2=require("obsidian");MF();ss();lre=new RegExp(/\\([a-z{}A-Z0-9]*)$/),RF=new Map,OF=null;AT=class extends Er{constructor(e){super(Wr().app,e);this.inputEl=e;this.lastInput="";this.symbols=Object.assign([],x2)}getSuggestions(e){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=e.slice(0,n),o=i.lastIndexOf("\\"),s=i.slice(o),a=lre.exec(s),l=[];a&&(this.lastInput=a[1],l=this.symbols.filter(u=>u.toLowerCase().contains(this.lastInput)));let c=new Set(l);return dre(this.symbols).search(this.lastInput).map(u=>u.item).filter(u=>c.has(u))}renderSuggestion(e,n){if(e){n.setText(e);let i=cre(e);i&&n.append(i.cloneNode(!0))}}selectSuggestion(e){if(this.inputEl.selectionStart===null)return;let n=this.inputEl.selectionStart,i=this.lastInput.length,o=this.inputEl.value,s=0,a=e.replace(/\\\\/g,"\\");if(this.inputEl.value=`${o.slice(0,n-i-1)}${a}${o.slice(n)}`,s=n-i+e.length-1,this.inputEl.trigger("input"),this.close(),e.contains("\u261A")){let l=this.inputEl.value.indexOf("\u261A");this.inputEl.value=this.inputEl.value.replace("\u261A",""),this.inputEl.setSelectionRange(l,l)}else this.inputEl.setSelectionRange(s,s)}}});var Si,IT,_2=x(()=>{Si=require("obsidian");ss();MF();T2();rr();IT=class r extends Si.Modal{constructor(){super(Wr().app);this.didSubmit=!1;this.keybindListener=e=>{(e.ctrlKey||e.metaKey)&&e.key==="Enter"&&this.submit(),e.key==="Tab"&&(e.preventDefault(),this.cursorToGoTo())};this.submitClickCallback=e=>this.submit();this.cancelClickCallback=e=>this.cancel();this.open(),this.display(),this.waitForClose=new Promise((e,n)=>{this.resolvePromise=e,this.rejectPromise=n}),new AT(this.inputEl),this.inputEl.focus(),this.inputEl.select()}static Prompt(){return new r().waitForClose}display(){this.containerEl.addClass("quickAddModal","qaMathModal"),this.contentEl.empty();let e=this.contentEl.createDiv();e.className="math math-block is-loaded";let n=new Si.TextAreaComponent(this.contentEl);n.inputEl.setCssStyles({width:"100%",height:"10rem"}),this.inputEl=n.inputEl,n.onChange((0,Si.debounce)(async o=>await this.mathjaxLoop(e,o),50)),n.inputEl.addEventListener("keydown",this.keybindListener),this.contentEl.createDiv({text:"Ctrl/Cmd+Enter to submit \xB7 Tab to jump to the cursor marker",cls:"setting-item-description"}).setCssStyles({marginTop:"0.5rem"}),this.createButtonBar(this.contentEl.createDiv())}async onOpen(){super.onOpen(),await(0,Si.loadMathJax)()}async mathjaxLoop(e,n){let i=(0,Si.renderMath)(n,!0);await(0,Si.finishRenderMath)(),e.empty(),e.append(i)}cursorToGoTo(){if(this.inputEl.value.contains("\u261A")){let e=this.inputEl.value.indexOf("\u261A");this.inputEl.value=this.inputEl.value.replace("\u261A",""),this.inputEl.setSelectionRange(e,e)}}createButton(e,n,i){let o=new Si.ButtonComponent(e);return o.setButtonText(n).onClick(i),o}createButtonBar(e){let n=e.createDiv();this.createButton(n,"Ok",this.submitClickCallback).setCta().buttonEl.setCssStyles({marginRight:"0"}),this.createButton(n,"Cancel",this.cancelClickCallback),n.setCssStyles({display:"flex",flexDirection:"row-reverse",justifyContent:"flex-start",marginTop:"1rem",gap:"0.5rem"})}removeInputListeners(){this.inputEl.removeEventListener("keydown",this.keybindListener)}resolveInput(){let e=this.inputEl.value.replace(/\\n/g,"\\\\n").replace(new RegExp("\u261A","g"),"");this.didSubmit?this.resolvePromise(e):this.rejectPromise(on())}submit(){this.didSubmit=!0,this.close()}cancel(){this.close()}onClose(){super.onClose(),this.resolveInput(),this.removeInputListeners()}}});function PT(r){return r?.triggerContext?.named===!0}function kr(r,t){let e=t?.triggerContext;return e?.named?e.activeFile:r.workspace.getActiveFile()}function DF(r,t){let e=Un(r),n=t?.triggerContext;return n?.named?n.activeFile&&e?.file?.path===n.activeFile.path?e:null:e}function Cf(r,t){return DF(r,t)?.editor.getSelection()??""}var vl=x(()=>{sl()});function yu(r){return r.replace(ure," ").replace(/\s+/g," ").trim()}function k2(r){return!(r.trim()===""||/^( {4,}|\t)/.test(r)||/^ {0,3}#{1,6}[ \t]/.test(r)||/^ {0,3}(`{3,}|~{3,})/.test(r)||/^ {0,3}>/.test(r)||/^ {0,3}([-*+]|\d{1,9}[.)])[ \t]/.test(r)||/^ {0,3}(=+|-+)\s*$/.test(r)||/^ {0,3}([*_-])([ \t]*\1){2,}[ \t]*$/.test(r))}function S2(r,t){return r[t.line]?.trim()===t.heading?t.line+1:t.line}function LF(r){let t=r.map(()=>!1),e=r.map(s=>s.replace(/\r$/,"")),n=0;if(e.length>0&&/^---\s*$/.test(e[0])){let s=1;for(;s<e.length&&!/^---\s*$/.test(e[s]);)s++;if(s<e.length){for(let a=0;a<=s;a++)t[a]=!0;n=s+1}}let i=null,o=null;for(;n<e.length;n++){let s=e[n];if(o){t[n]=!0,pre(o,s)&&(o=null);continue}if(i){t[n]=!0;let d=s.match(/^ {0,3}(`{3,}|~{3,})\s*$/);d&&d[1][0]===i.char&&d[1].length>=i.length&&(i=null);continue}let a=s.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);if(a&&!(a[1][0]==="`"&&a[2].includes("`"))){t[n]=!0,i={char:a[1][0],length:a[1].length};continue}let l=s.match(/^ {0,3}(%%|\$\$)(.*)$/),c=n>0&&/^\s*([-*+]|\d{1,9}[.)])[ \t]/.test(e[n-1]);if(l&&!(l[1]==="$$"&&c)){let d=l[1],u=l[2];(d==="%%"?u.includes("%%"):u.trimEnd().length>2&&u.trimEnd().endsWith("$$"))||(t[n]=!0,o=d)}}return t}function pre(r,t){return r==="%%"?t.includes("%%"):t.trimEnd().endsWith("$$")}function si(r){let t=[],e=LF(r);for(let n=0;n<r.length;n++){let i=r[n].replace(/\r$/,"");if(e[n])continue;let o=i.match(/^ {0,3}(#{1,6})[ \t]+(.*)$/);if(o){t.push({heading:o[2],level:o[1].length,line:n});continue}let s=i.match(/^ {0,3}(=+|-+)\s*$/);if(s&&n>0){let a=r[n-1],l=t.length>0&&t[t.length-1].line===n-1,c=n<2||e[n-2]||!k2(r[n-2]);!l&&!e[n-1]&&c&&k2(a)&&t.push({heading:a.trim(),level:s[1][0]==="="?1:2,line:n-1});continue}}return t}function mre(r,t){let e=[],n=yu(r[t].heading);n&&e.push(n);let i=r[t].level;for(let o=t-1;o>=0&&i>1;o--)if(r[o].level<i){i=r[o].level;let s=yu(r[o].heading);s&&e.unshift(s)}return e}function NF(r,t){if(r.length===0)return null;let e=-1;for(let d=0;d<r.length&&r[d].line<=t;d++)e=d;if(e===-1)return null;let n=yu(r[e].heading);if(!n)return null;let i=n.toLowerCase();if(!r.some((d,u)=>u!==e&&yu(d.heading).toLowerCase()===i))return`#${n}`;let s=mre(r,e);if(s.length<2)return null;let a=s.join("#"),l=a.toLowerCase();return fre(r).some((d,u)=>u!==e&&d===l)?null:`#${a}`}function fre(r){let t=new Array(r.length),e=[];for(let n=0;n<r.length;n++){for(;e.length>0&&r[e[e.length-1]].level>=r[n].level;)e.pop();let i=e.length>0?t[e[e.length-1]]:[],o=yu(r[n].heading);t[n]=o?[...i,o]:i,e.push(n)}return t.map(n=>n.join("#").toLowerCase())}var ure,bu=x(()=>{ure=/[!"#$%&()*+,.:;<=>?@^`{|}~/[\]\\\r\n]/g});async function $T(r,t,e,n){return await ix(r,e,n)&&await t.saveSettings?.(),fB(r,e,n)}var VF=x(()=>{nl()});function _y(r,t){let e=t.findIndex(n=>n.id===r.id);if(e!==-1){let n=[...t.slice(e),r].map(i=>i.name).join(" -> ");throw new Error(`${r.type} "${r.name}" calls itself: ${n}`)}return[...t,r]}function A2(){return FT}function I2(r,t){let e=FT;FT=r;try{return t()}finally{FT=e}}var FT,MT=x(()=>{FT=[]});function Dc(r,{logPrefix:t,noticePrefix:e=t,defaultReason:n}){if(!(r instanceof at))return!1;if(P2.has(r))return!0;P2.add(r);let i=typeof r.message=="string"&&r.message.trim().length>0?r.message:n,o=a=>i===a?a:`${a}: ${i}`;return S.logMessage(o(t)),(!(r instanceof et||typeof r.message=="string"&&r.message.toLowerCase().includes("cancelled by user"))||U.getState().showInputCancellationNotification)&&new $2.Notice(o(e)),!0}var $2,P2,ky=x(()=>{$2=require("obsidian");ri();rr();je();ye();P2=new WeakSet});var F2={};cb(F2,{SingleMacroEngine:()=>BF});function gre(r){if(r==null)return"";if(typeof r=="string")return r;if(typeof r=="number"||typeof r=="boolean")return String(r);if(typeof r=="bigint"||typeof r=="symbol")return r.toString();if(r instanceof Error)return r.message;try{return JSON.stringify(r)}catch{return Object.prototype.toString.call(r)}}var hre,BF,M2=x(()=>{ye();er();au();lt();lx();VF();Sy();MT();ky();Gr();ri();hre=new Set(["settings","entry","quickadd"]);BF=class{constructor(t,e,n,i,o){this.app=t;this.plugin=e;this.choices=n;this.emittedConflictNotice=!1;this.choiceExecutor=i,o?(this.variables=o,this.choiceExecutor.variables=o):i.variables?this.variables=i.variables:(this.variables=new Map,this.choiceExecutor.variables=this.variables)}async runAndGetOutput(t,e,n=[]){this.emittedConflictNotice=!1;let{basename:i,memberAccess:o}=Fm(t),s=d=>(d??"").trim(),a=Zt(this.choices).find(d=>d.type==="Macro"&&s(d.name)===s(i));if(!a){let d=p=>s(p).toLowerCase(),u=Zt(this.choices).filter(p=>p.type==="Macro"&&d(p.name)===d(i));if(u.length>1)throw S.logError(`Ambiguous macro reference '${t}'. Multiple choices match when ignoring case.`),new Error(`Ambiguous macro reference '${t}'. Please disambiguate by renaming macros.`);a=u[0]}if(!a)throw S.logError(`macro '${t}' does not exist.`),new Error(`macro '${t}' does not exist.`);let l=new ta(this.app,this.plugin,a,this.choiceExecutor,this.variables,void 0,e?.label,null,_y(a,n));if(o?.length){let d=await this.tryExecuteExport(l,a,o);if(this.ensureNotAborted(),d.executed)return this.formatResult(d.result)}await l.run(),this.ensureNotAborted();let c=l.getOutput();if(o?.length){let d=this.resolveMemberAccess(c,o);d.found||S.logWarning(`Macro '${a.name}' was asked for member '${o.join("::")}', but it has no user script exporting it; the result is empty.`),c=d.value}return typeof c=="function"?c=await c():c&&typeof c=="object"&&(c=JSON.stringify(c)),gre(c)}getVariables(){return this.variables}async tryExecuteExport(t,e,n){let i=Mt(e.macro?.commands);if(!i.length)return{executed:!1};let o=i.map((c,d)=>({command:c,index:d})).filter(c=>Tr(c.command)&&c.command.type==="UserScript");if(o.length===0)return{executed:!1};let s=await this.selectUserScriptCandidate(e,o,n),a=s.candidate.command.id,l=i.slice(0,s.candidate.index);try{l.length&&(await t.runSubset(l),this.ensureNotAborted());let c=e.macro?.commands,d=Lv(c)?c:i,u;a!==void 0?u=d.findIndex(w=>Tr(w)&&w.id===a&&w.type==="UserScript"):u=s.candidate.index;let p=u>=0?d[u]:void 0;if(!p||p.type!=="UserScript")throw new at(`Could not resolve the member-access script for '${e.name}'.`);let m=p;m.settings||(m.settings={});let h=s.candidate.exportsRef!==void 0?s.candidate.exportsRef:await Nv(m,this.app);if(h==null)throw new at(`Macro '${e.name}' could not load '${m.name}' for member access.`);let g=typeof h=="object"||typeof h=="function"?h.settings:void 0;g&&typeof g=="object"&&Pm(m.settings,g);let v=s.candidate.resolvedMember??this.resolveMemberAccess(h,s.memberAccess);if(!v.found)throw new at(`Macro '${e.name}' routes member access to '${m.name}', but that script does not export '${s.memberAccess.join("::")}'.`);let b=d.slice(u+1),y=m.settings;typeof v.value=="function"&&(y=await $T(this.app,this.plugin,m,g&&typeof g=="object"?g:void 0));let C=await this.executeResolvedMember(v.value,t,y);return this.ensureNotAborted(),t.setOutput(C),this.syncVariablesFromParams(t),b.length&&(await t.runSubset(b),this.ensureNotAborted()),{executed:!0,result:C}}catch(c){throw Dc(c,{logPrefix:"Macro execution aborted",noticePrefix:"Macro execution aborted",defaultReason:"Macro execution aborted"})&&this.choiceExecutor.signalAbort?.(c),c}}resolveMemberAccess(t,e){let n=t;for(let i of e){if(n==null||typeof n!="object"&&typeof n!="function")return{found:!1};let o=n;if(!(i in o))return{found:!1};n=o[i]}return{found:!0,value:n}}async executeResolvedMember(t,e,n){return typeof t=="function"?await t(e.params,n):t}async selectUserScriptCandidate(t,e,n){if(e.length===1)return{candidate:{command:e[0].command,index:e[0].index},memberAccess:n};let i=this.resolveScriptSelector(t,e,n);if(i)return{candidate:{command:i.command,index:i.index},memberAccess:i.memberAccess};let o=[];for(let l of e){let c=await Nv(l.command,this.app);o.push({command:l.command,index:l.index,exportsRef:c,resolvedMember:this.resolveMemberAccess(c,n)})}let s=o.filter(l=>l.resolvedMember.found);if(s.length===1)return{candidate:s[0],memberAccess:n};if(s.length===0)throw new at(`Macro '${t.name}' could not find '${n.join("::")}' in any user script.`);if(hre.has(n[0])){let l=s[0];return this.warnReservedKeyConflict(t,n,l,s),{candidate:l,memberAccess:n}}let a=s.map(l=>`'${l.command.name}'`).join(", ");throw new at(`Macro '${t.name}' has multiple user scripts exporting '${n.join("::")}': ${a}. Disambiguate with '{{MACRO:${t.name}::<Script Name>::${n.join("::")}}}'.`)}warnReservedKeyConflict(t,e,n,i){if(this.emittedConflictNotice)return;this.emittedConflictNotice=!0;let o=i.map(s=>`'${s.command.name}'`).join(", ");S.logWarning(`Macro '${t.name}': multiple user scripts export '${e.join("::")}' (${o}); using '${n.command.name}'. Disambiguate with '{{MACRO:${t.name}::<Script Name>::${e.join("::")}}}'.`)}resolveScriptSelector(t,e,n){if(n.length<2)return null;let i=n[0]?.trim(),o=e.filter(s=>s.command.name.trim()===i);if(o.length===0)return null;if(o.length>1)throw new at(`Macro '${t.name}' has multiple user scripts named '${i}'. Rename one of them before using '{{MACRO:${t.name}::${i}::${n.slice(1).join("::")}}}'.`);return{command:o[0].command,index:o[0].index,memberAccess:n.slice(1)}}syncVariablesFromParams(t){Object.keys(t.params.variables).forEach(e=>{this.choiceExecutor.variables.set(e,t.params.variables[e])})}formatResult(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return t.toString();if(typeof t=="object")try{return JSON.stringify(t)}catch{return Object.prototype.toString.call(t)}return String(t)}ensureNotAborted(){let t=this.choiceExecutor.consumeAbortSignal?.();if(t)throw t}}});function UF(r,t){let e=r.replace(/\n$/,"").split(`
|
||
`).pop()??"",n=t.split(`
|
||
`,1)[0];return O2.test(e)&&O2.test(n)?`
|
||
`:""}function yl(r){let t=(0,D2.getFrontMatterInfo)(r);return t.exists?t.contentStart:0}function yre(r,t){let e=yl(r);if(e===0)return 0;if(R2.test(t))return e;let n=R2.exec(r.slice(e));return n?e+n[0].length:e}function wu(r,t,{separateBlockquotes:e=!1}={}){if(t.length===0)return{content:r,insertedStartOffset:null,insertedEndOffset:null};let n=yre(r,t),i=r.slice(0,n),o=r.slice(n),s=i.length>0&&!i.endsWith(`
|
||
`)&&!vre.test(t)?`
|
||
`:"",a=o.length>0&&!t.endsWith(`
|
||
`)?`
|
||
`:"",l=e?UF(t,o):"",c=i.length+s.length,d=c+t.length;return{content:`${i}${s}${t}${a}${l}${o}`,insertedStartOffset:c,insertedEndOffset:d}}function L2(r,t){return wu(r,t).content}var D2,R2,vre,O2,Lc=x(()=>{D2=require("obsidian"),R2=/^[^\S\r\n]*\r?\n/,vre=/^\r?\n/,O2=/^ {0,3}>/});function RT(r){let t=yl(r),e=/\{\{CURSOR\}\}/i.exec(r.slice(t));return{content:On(r),offsets:e?[On(r.slice(0,t)).length+e.index]:[]}}function qF(r,t){if(r.content===t)return r;r.content.includes("\r")&&!t.includes("\r")&&(r=bre(r));let e=yl(r.content),n=yl(t);return r.offsets.some(i=>i<e)||r.content.slice(e)!==t.slice(n)?null:{content:t,offsets:r.offsets.map(i=>i+n-e)}}function bre(r){let t=e=>e.replace(/\r\n?/g,`
|
||
`);return{content:t(r.content),offsets:r.offsets.map(e=>t(r.content.slice(0,e)).length)}}var zF=x(()=>{Ma();Lc()});function OT(r){for(let t of r.workspace.getLeavesOfType("markdown")){let e=t.view;if(!(!e.containerEl||!e.file||e.file.extension!=="md"))try{let n=Bi(e.containerEl).activeElement;if(!n||!e.containerEl.contains(n)||!n.closest(".metadata-property-value")||n.matches(wre))continue;let o=n.closest(".metadata-property")?.getAttribute("data-property-key");if(!o)continue;return{file:e.file,key:o}}catch{continue}}return null}function Cre(r,t,e){let n=B2(r,t),i=r[n];if(Array.isArray(i)){i.push(e);return}if(i==null||i===""){r[n]=e;return}if(typeof i=="string"){r[n]=`${i} ${e}`;return}throw new Error(`Cannot append link to frontmatter property '${n}' because it contains a ${typeof i} value.`)}function HF(r,t,e,n=Ud){let i=B2(r,t),o=r[i];if(Array.isArray(o)){o.push(e);return}if(o===null||o===""){r[i]=[e];return}if(o===void 0){if(n==="error")throw new Error(`Cannot append link to frontmatter property '${i}' because it does not exist.`);r[i]=[e];return}if(typeof o=="object")throw new Error(`Cannot append link to frontmatter property '${i}' because it contains an object value.`);if(n!=="alwaysAppend")throw new Error(`Cannot append link to frontmatter property '${i}' because it is not a list and the link-handling mode is '${N2[n]}'. Choose '${N2.alwaysAppend}' to convert it into a list and append.`);r[i]=[o,e]}function B2(r,t){if(t=t.trim(),!t)throw new Error("Cannot append link to an empty frontmatter property key.");let e=V2(t),n=Object.keys(r).filter(i=>V2(i)===e);if(n.length>1)throw new Error(`Cannot append link to frontmatter property '${t}' because the note has multiple properties that normalize to that key.`);return n[0]??t}function V2(r){return r.trim().toLowerCase()}async function U2(r,t,e){let n=r.fileManager.generateMarkdownLink(e,t.file.path);try{return await Va(r,t.file,i=>{Cre(i,t.key,n)}),!0}catch(i){return S.logError(`QuickAdd: created the file but could not append the link to frontmatter property '${t.key}' in '${t.file.path}': ${i instanceof Error?i.message:String(i)}`),!1}}var N2,wre,Ay=x(()=>{Ns();ye();Ua();Ko();N2={alwaysAppend:"Create or convert",createProperty:"Create if missing",error:"Require list"},wre=['input[type="number"]','input[type="date"]','input[type="datetime-local"]','input[type="time"]','input[type="month"]','input[type="checkbox"]'].join(", ")});function q2(r,t,e,n){let i=ai(t,e);return i?GF(r,i.editor,n):null}function GF(r,t,e){if(r.cursor.kind==="none")return null;let n=r.content.replace(/\r\n?/g,`
|
||
`),i=r.content.slice(0,r.cursor.value).replace(/\r\n?/g,`
|
||
`).length,o=u=>t.posToOffset(u),s=t.getCursor(),a;if(e==="currentLine")a=t.listSelections().map(({anchor:u,head:p})=>({from:o(u)<=o(p)?u:p,to:o(u)<=o(p)?p:u,text:n,cursor:i}));else if(e==="newLineAbove"||e==="newLineBelow"){let u=e==="newLineAbove";a=[{from:{line:s.line,ch:u?0:t.getLine(s.line).length},text:u?n+`
|
||
`:`
|
||
`+n,cursor:i+(u?0:1)}]}else return null;let l=[],c=[],d=0;a.sort((u,p)=>o(u.from)-o(p.from));for(let u of a)l.push(o(u.from)+d+u.cursor),c.push(o(u.from)+d+u.text.length-(e==="newLineAbove"?1:0)),d+=u.text.length-(o(u.to??u.from)-o(u.from));return t.transaction({changes:a.map(({from:u,to:p,text:m})=>({from:u,to:p,text:m}))}),t.setSelections(c.map(u=>({anchor:t.offsetToPos(u)}))),{offsets:l,content:t.getValue()}}function ai(r,t){let e=Un(r);return e?.file?.path===t.path?e:null}function z2(r,t,e){try{let n=ai(t,e);return n?(n.editor.replaceSelection(r),!0):(S.logError(`unable to append '${r}' to current line.`),!1)}catch{return S.logError(`unable to append '${r}' to current line.`),!1}}function H2(r,t,e,n){try{let i=ai(e,n);if(!i)return S.logError(`unable to insert '${r}' on new line ${t}.`),!1;let o=i.editor,a=o.getCursor().line,l=r.split(`
|
||
`),c=l.length,d=l[c-1]?.length??0;if(t==="above")o.replaceRange(r+`
|
||
`,{line:a,ch:0}),o.setCursor({line:a+c-1,ch:d});else{let u=o.getLine(a);o.replaceRange(`
|
||
`+r,{line:a,ch:u.length}),o.setCursor({line:a+c,ch:d})}return!0}catch{return S.logError(`unable to insert '${r}' on new line ${t}.`),!1}}function W2(r,t,e){return H2(r,"above",t,e)}function G2(r,t,e){return H2(r,"below",t,e)}function xre(r,t,e,n,i){let o=c=>r.posToOffset(c),s=t.map(c=>{let[d,u]=o(c.anchor)<=o(c.head)?[c.anchor,c.head]:[c.head,c.anchor];return{from:d,to:u,text:n(r.getRange(d,u))}}).sort((c,d)=>o(c.from)-o(d.from)),a=s.map(({from:c,to:d,text:u})=>e==="replaceSelection"?{from:c,to:d,text:u}:{from:d,text:u}),l=[];if(e==="replaceSelection"){let c=0;for(let{from:d,to:u,text:p}of s)l.push(o(d)+c+p.length),c+=p.length-(o(u)-o(d))}i(a,()=>r.transaction({changes:a})),e==="replaceSelection"&&r.setSelections(l.map(c=>({anchor:r.offsetToPos(c)})))}async function Ere(r,t,e="replaceSelection",n={}){let{requireActiveView:i=!0,frontmatterProperty:o,frontmatterHandling:s=Ud,textForSelection:a,onEditorTextMutation:l}=n,c=r.workspace.getActiveViewOfType(WF.MarkdownView);if(!c){let g="Cannot append link because no active Markdown view is available.";if(i)throw new Error(g);S.logMessage(g);return}if(e==="inFrontmatter"){let g=c.file;if(!g)throw new Error("Cannot append link because the active Markdown view has no file.");await Va(r,g,v=>{HF(v,o??"",t,s)});return}let d=c.editor;if(!d){let g="Cannot append link because the active Markdown view has no editor.";if(i)throw new Error(g);S.logMessage(g);return}let u=(g,v)=>{if(!l){v();return}let b=d.getValue(),y=g.map(C=>({from:d.posToOffset(C.from),to:d.posToOffset(C.to??C.from),text:C.text}));v(),l({filePath:c.file?.path??null,before:b,after:d.getValue(),edits:y})},p=d.listSelections().map(g=>({anchor:{...g.anchor},head:{...g.head}}));if(a&&p.length>0&&(e==="replaceSelection"||e==="afterSelection")){xre(d,p,e,a,u);return}if(e==="replaceSelection"){let g=p.map(({anchor:v,head:b})=>({from:d.posToOffset(v)<=d.posToOffset(b)?v:b,to:d.posToOffset(v)<=d.posToOffset(b)?b:v,text:t}));u(g,()=>d.replaceSelection(t));return}let m=({line:g,ch:v})=>d.posToOffset({line:g,ch:v}),h=p.sort((g,v)=>m(v.head)-m(g.head));for(let g of h){let v=m(g.anchor)>m(g.head)?g.anchor:g.head;switch(e){case"afterSelection":{u([{from:v,text:t}],()=>d.replaceRange(t,v));break}case"endOfLine":case"newLine":{let b=d.getLine(v.line).length,y=e==="newLine"&&b>0?`
|
||
`:"",C={line:v.line,ch:b};u([{from:C,text:y+t}],()=>d.replaceRange(y+t,C));break}}}}async function j2(r,t,e,n,i,o=!1){if(!n?.enabled)return!1;let s=Zo(n);if(!e||e.extension!=="md"){if(n.requireActiveFile)throw new Error("Cannot append link because no active Markdown view is available.");return!1}let a=e.path,l=qw(r,t,{sourcePath:a,linkType:s.linkType,placement:s.placement});if(!ai(r,e)){if(s.placement==="inFrontmatter")await Va(r,e,d=>{HF(d,s.frontmatterProperty??"",l,s.frontmatterHandling)});else if(o)await CA(r,e,l,i);else{if(n.requireActiveFile)throw new Error("Cannot append link because no active Markdown view is available.");return!1}return!0}let c=s.displayText==="selection"?d=>qw(r,t,{sourcePath:a,linkType:s.linkType,placement:s.placement,alias:d}):void 0;return await Ere(r,l,s.placement,{requireActiveView:!1,frontmatterProperty:s.frontmatterProperty,frontmatterHandling:s.frontmatterHandling,textForSelection:c,onEditorTextMutation:i}),!0}function Y2(r,t,e,n){return Iy(r,t,[e],n)}function Iy(r,t,e,n){try{if(t.extension!=="md"||!e.length||e.some(c=>!Number.isSafeInteger(c)||c<0||c>n.length))return!1;let i=r.workspace.getActiveViewOfType(WF.MarkdownView);if(!i||i.file?.path!==t.path||i.getMode()==="preview")return!1;let o=i.editor;if(!o)return!1;let s=o.getValue(),a=e;if(s!==n){if(s!==n.replace(/\r\n?/g,`
|
||
`))return!1;a=e.map(c=>n.slice(0,c).replace(/\r\n?/g,`
|
||
`).length)}a.length===1?o.setCursor(o.offsetToPos(a[0])):o.setSelections(a.map(c=>({anchor:o.offsetToPos(c)})));let l=i.containerEl?.ownerDocument;return l&&l.activeElement===l.body&&o.focus(),!0}catch{return S.logMessage(`Unable to place cursor after capture in '${t.path}'.`),!1}}var WF,Nc=x(()=>{WF=require("obsidian");sl();ye();Ua();qd();Ay();Ns();qd()});function LT(r,t){try{let e=r.workspace.getActiveViewOfType(NT.MarkdownView);if(!e||e.file?.path!==t.path)return{cursor:null,value:null};let n=e.editor,i=n?.getCursor?.(),o=i&&typeof i.line=="number"&&typeof i.ch=="number"?{line:i.line,ch:i.ch}:null,s=typeof n?.getValue=="function"?n.getValue():null;return{cursor:o,value:s}}catch{return{cursor:null,value:null}}}function _re(r,t){return r!==null&&t!==null&&(r.line!==t.line||r.ch!==t.ch)}function K2(r){return typeof r!="string"?null:[...r.matchAll(Tre)].length}function J2(r,t){let e=K2(r),n=K2(t);return e!==null&&n!==null&&e>n}function Q2(r,t){return _re(r.cursor,t.cursor)||J2(r.value,t.value)}async function YF(r,t,e=500){try{let n=r.vault.adapter;if(!("stat"in n)||typeof n.stat!="function")return;let i=await n.stat(t.path);if(!i)return;let o=i.mtime,s=Date.now(),a=30;for(;Date.now()-s<e;){await $y(a);let l=await n.stat(t.path);if(!l||l.mtime===o)return;o=l.mtime,a=Math.min(a*2,200)}}catch(n){S.logWarning(`waitForFileSettle: fallback due to adapter/stat failure \u2013 ${n.message}`)}}function QF(r){return r.plugins.plugins["templater-obsidian"]}function xu(r){let t=QF(r);return t||null}function Fy(r){let t=xu(r);if(!t)return!1;let e=t.settings?.trigger_on_file_creation;if(typeof e=="boolean")return e;let n=r.loadLocalStorage?.("templater-local-settings");return typeof n=="object"&&n!==null&&!Array.isArray(n)&&"trigger_on_file_creation"in n&&n.trigger_on_file_creation===!0}function $y(r){return new Promise(t=>window.setTimeout(t,r))}function kre(r,t){if(Vc)return;let e=function(...n){let i=t.apply(this,n),o=n[n.length-1]?.path;return typeof o=="string"&&Cu.has(o)&&Cu.set(o,Promise.resolve(i)),i};r.on_file_creation=e,Vc={owner:r,original:t,wrapper:e}}function Sre(){!Vc||Cu.size>0||(Vc.owner.on_file_creation===Vc.wrapper&&(Vc.owner.on_file_creation=Vc.original),Vc=null)}async function XF(r,t,e){let n=(0,NT.normalizePath)(t),i,o;try{i=Fy(r)?xu(r)?.templater?.constructor:void 0,o=i?.on_file_creation}catch{i=void 0}if(!(!!i&&typeof o=="function"&&!Cu.has(n))){let d=await e();return await X2(r,d),d}Cu.set(n,null),kre(i,o);let a,l;try{a=await e()}finally{l=Cu.get(n)??null,Cu.delete(n),Sre()}if(!l||a.path!==n)return await X2(r,a),a;let c;try{await Promise.race([l,new Promise(d=>{c=window.setTimeout(d,Are)})])}catch(d){S.logWarning(`Templater failed on new note ${a.path}: ${d.message}`)}finally{window.clearTimeout(c)}return a}async function X2(r,t,e={}){if(t.extension!=="md"||!Fy(r))return;let i=xu(r)?.templater?.files_with_pending_templates;if(!(i instanceof Set)){await $re(r,t,{timeoutMs:e.timeoutMs??5e3,gracePeriodMs:e.appearTimeoutMs??2500,quietPeriodMs:200});return}let{timeoutMs:o=5e3,appearTimeoutMs:s=2500}=e,a=Date.now();for(;Date.now()-a<s&&!i.has(t.path);)await $y(50);for(;Date.now()-a<o&&i.has(t.path);)await $y(50);await YF(r,t,800)}async function Pre(r,t,e){if(!(KF>0)&&e.size===0){if(Py){await Py;return}Py=(async()=>{try{r.workspace.trigger("templater:all-templates-executed"),await t.templater?.functions_generator?.teardown?.()}catch(n){S.logWarning(`withTemplaterFileCreationSuppressed: teardown failed \u2013 ${n.message}`)}})();try{await Py}finally{Py=null}}}async function Z2(r,t,e){let n=xu(r),i=n?.templater?.files_with_pending_templates;if(!n||!Fy(r)||!(i instanceof Set))return await e();KF++;let o=jF.get(t);o||(o={count:0,hadPathInitially:i.has(t)},jF.set(t,o),o.hadPathInitially||i.add(t)),o.count++;let s=!1;try{let a=await e();return s=!0,a}finally{o.count--,KF--,o.count<=0&&(jF.delete(t),o.hadPathInitially||(s&&await $y(Ire),i.delete(t),await Pre(r,n,i)))}}async function $re(r,t,e={}){let{timeoutMs:n=2e3,quietPeriodMs:i=150,gracePeriodMs:o=800}=e;try{let s=r.vault.adapter;if(!("stat"in s)||typeof s.stat!="function")return;let a=await s.stat(t.path);if(!a)return;let l=a.mtime,c=Date.now(),d=!1,u=c,p=50;for(;Date.now()-u<n;){await $y(p);let m=await s.stat(t.path);if(!m)return;let h=Date.now();if(m.mtime!==l){d=!0,l=m.mtime,c=h,p=50;continue}if(d){if(h-c>=i)return}else if(h-u>=o)return;p=Math.min(Math.floor(p*1.5),200)}}catch(s){S.logWarning(`waitForFileToStopChanging: fallback due to adapter/stat failure \u2013 ${s.message}`)}}async function Fre(r,t){let e=DT.get(r)??Promise.resolve(),n,i=new Promise(s=>{n=()=>s()}),o=e.catch(()=>{}).then(()=>i);DT.set(r,o),o.finally(()=>{DT.get(r)===o&&DT.delete(r)}).catch(()=>{}),await e.catch(()=>{});try{return await t()}finally{n()}}async function Eu(r,t,e={}){if(t.extension!=="md")return!1;let n=xu(r),i=n?.templater,o=i?.overwrite_file_commands;if(!n||!i||typeof o!="function")return!1;let{skipIfNoTags:s=!0,postWait:a=!0}=e;return await Fre(t.path,async()=>{await YF(r,t);let l;try{l=await r.vault.read(t)}catch(u){return Me(u,`overwriteTemplaterOnce: failed to read ${t.path} before render`),!1}if(s&&!l.includes("<%"))return!1;let c=null,d=r.workspace.on("templater:overwrite-file",u=>{u.file.path===t.path&&(c=u.content)});try{await o.call(i,t);let u=J2(c,LT(r,t).value);return a&&await YF(r,t,800),u}catch(u){return Me(u,`Templater failed on ${t.path}`),!1}finally{r.workspace.offref(d)}})}async function Bc(r,t,e){if(e.extension!=="md")return t;let n=xu(r),i=n?.templater,o=i?.parse_template;if(!n||!i||typeof o!="function")return t;let s=i.create_running_config,a=typeof s=="function"?s.call(i,void 0,e,4):{target_file:e,run_mode:4,frontmatter:{}};return await o.call(i,a,t)}async function Tu(r,t){if(t.extension!=="md"||r.workspace.getActiveFile()?.path!==t.path)return!1;let e=xu(r),n=!!e?.settings?.auto_jump_to_cursor,i=e?.editor_handler,o=i?.jump_to_next_cursor_location;if(!n)return!1;let s=LT(r,t);if(typeof o=="function")try{return await o.call(i,t,!0),Q2(s,LT(r,t))}catch(a){S.logWarning(`jumpToNextTemplaterCursorIfPossible: API failed \u2013 ${a.message}`)}try{return!r.commands.executeCommandById?.("templater-obsidian:jump-to-next-cursor-location")?!1:Q2(s,LT(r,t))}catch{}return!1}var NT,Tre,Cu,Vc,Are,jF,KF,Py,Ire,DT,Uc=x(()=>{NT=require("obsidian");ye();nt();Tre=/<%\s*tp\.file\.cursor\((?:-?[0-9]+(?:\.[0-9]+)?)?\)\s*%>/g;Cu=new Map,Vc=null;Are=5e3;jF=new Map,KF=0,Py=null,Ire=350;DT=new Map});var My,xf,JF=x(()=>{My=require("obsidian");Le();ye();Uc();Yi();xf=class{constructor(t){this.app=t}async createFolder(t){await this.app.vault.adapter.exists(t)||await this.app.vault.createFolder(t)}stripLeadingSlash(t){return t.replace(/^\/+/,"")}normalizeMarkdownFilePath(t,e){let n=this.stripLeadingSlash(t),i=n?`${n}/`:"",o=this.stripLeadingSlash(e).replace(xt,"");return`${i}${o}.md`}async fileExists(t){return await this.app.vault.adapter.exists(t)}getFileByPath(t){let e=this.app.vault.getAbstractFileByPath(t);if(!e)throw S.logError(`${t} not found`),new Error(`${t} not found`);if(e instanceof My.TFolder)throw S.logError(`${t} found but it's a folder`),new Error(`${t} found but it's a folder`);if(!(e instanceof My.TFile))throw new Error(`${t} is not a file`);return e}async createFileWithInput(t,e,n={}){if(Ut(t))throw new Error(`Refusing to create a file outside the vault: "${t}".`);let i=t.match(/(.*)[/\\]/),o="";i&&(o=i[1]);let s=this.app.vault.getAbstractFileByPath(o);(!s||!(s instanceof My.TFolder))&&await this.createFolder(o);let a=()=>this.app.vault.create(t,e);return n.suppressTemplaterOnCreate&&t.toLowerCase().endsWith(".md")?await Z2(this.app,t,a):await a()}}});async function Zi(r,t){try{return r.promptProvider?await t.remote(r.promptProvider):r.interactive===!1?await t.headless():await t.app()}catch(e){throw Be(e)?new et("Input cancelled by user"):e}}var _u=x(()=>{rr();nt()});async function eo(r,t){let e=t.items.map((s,a)=>`${Mre}${a}`),n=await r.suggester(t.items.map(s=>s.title),e,t.placeholder,t.allowCustomInput??!1),i=n==null?"":String(n),o=e.indexOf(i);if(o!==-1)return t.items[o].value;if(i==="")throw new et("Input cancelled by user");if(t.allowCustomInput)return i;throw new Error(`A reply to ${t.what} has to be one of the offered options, and "${i.slice(0,60)}" is not. Reply with the item's \`value\` token exactly as it was sent, or \`{"cancelled": true}\` to dismiss it.`)}var Mre,ku=x(()=>{rr();Mre="\0qa-eng:"});function ZF(r){let t=r.map(n=>n||"/");return`Folder must be under: ${t.length>3?`${t.slice(0,3).join(", ")}...`:t.join(", ")}`}var VT,Rre,ra,BT,eH=x(()=>{VT=require("obsidian");JF();Qi();cl();Xh();Dr();ri();Sn();_u();ku();Rre=3,ra=class extends Error{constructor(t){super(t),this.name="InvalidFolderPathError"}},BT=class extends xf{async getOrCreateFolder(t,e){let n=this.buildFolderSelectionContext(t,{...e,topItems:t.length>0?[]:e.topItems??[]});if(!this.shouldPromptForFolder(n))return await this.handleSingleSelection(n);let i=this.buildFolderSelectionContext(t,e),o=await this.promptUntilAllowed(i,e.executor);return o.isEmpty?"":o.normalized}buildFolderSelectionContext(t,e){let n=e.allowCreate??!1,i=e.allowedRoots?.map(s=>go(s))??[];return{...this.buildFolderSuggestions(t,e.topItems??[],i.length>0?i:void 0),allowCreate:n,allowedRoots:i,placeholder:e.placeholder}}shouldPromptForFolder(t){return t.items.length>1||t.allowCreate&&t.items.length===0}async promptForFolder(t,e){let n=t.placeholder??"Choose a folder or type to create one";return String(await Zi(e,{remote:i=>eo(i,{items:t.items.map((o,s)=>({value:o,title:t.displayItems[s]??o})),placeholder:n,allowCustomInput:t.allowCreate,what:"the folder chooser"}),headless:()=>{throw new de("This choice needs to ask which folder to create the note in, but this run is non-interactive. Configure a single target folder, or re-run with the ui flag.")},app:()=>t.allowCreate?vr.Suggest(this.app,t.displayItems,t.items,{placeholder:n,renderItem:(i,o)=>{this.renderFolderSuggestion(i,o,t.canonicalByNormalized,t.displayByNormalized)}}):It.Suggest(this.app,t.displayItems,t.items,t.placeholder)}))}async resolveSelection(t,e){let n=cr(t),i=n.length===0,o=e.canonicalByNormalized.get(n)??go(t),s=i?!1:e.canonicalByNormalized.has(n)||await this.app.vault.adapter.exists(o),a=e.allowedRoots.length===0?!0:this.isPathAllowed(o,e.allowedRoots);return{raw:t,normalized:o,exists:s,isAllowed:a,isEmpty:i}}async promptUntilAllowed(t,e){let n=e.promptProvider?Rre:0,i=null;for(;;){if(e.promptProvider&&n--<=0)throw new de(i??ZF(t.allowedRoots));let o=await this.promptForFolder(t,e),s=await this.resolveSelection(o,t);if(!s.isAllowed){i=ZF(t.allowedRoots),this.showFolderNotAllowedNotice(t.allowedRoots);continue}if(s.isEmpty)return s;try{this.validateFolderPath(s.normalized)}catch(a){if(a instanceof ra){i=a.message,new VT.Notice(a.message);continue}throw a}return await this.ensureFolderExists(s),s}}async ensureFolderExists(t){t.isEmpty||t.exists||await this.createFolder(t.normalized)}async handleSingleSelection(t){let e=t.items[0]??"",n=await this.resolveSelection(e,t);if(n.isEmpty)return"";if(!n.isAllowed)throw this.showFolderNotAllowedNotice(t.allowedRoots),new at("Selected folder not allowed.");try{this.validateFolderPath(n.normalized)}catch(i){if(i instanceof ra)return new VT.Notice(i.message),"";throw i}return await this.ensureFolderExists(n),n.normalized}validateFolderPath(t){if(!t)return;let e=t.split("/");for(let n of e)this.validateFolderSegment(n)}validateFolderSegment(t){if(!t)throw new ra("Folder name cannot be empty.");if(t==="."||t==="..")throw new ra("Folder name cannot be '.' or '..'.");if(Yh.test(t))throw new ra("Folder name cannot contain control characters.");if(Kh.test(t))throw new ra('Folder name cannot contain any of the following characters: \\ / : * ? " < > |');if(Qh.test(t))throw new ra("Folder name cannot end with a space or a period.");let e=t.split(".")[0]??"";if(e&&Pd(e))throw new ra("Folder name cannot be a reserved name like CON, PRN, AUX, NUL, COM1-9, or LPT1-9.")}isPathAllowed(t,e){let n=go(t);for(let i of e)if(!i||n===i||n.startsWith(`${i}/`))return!0;return!1}showFolderNotAllowedNotice(t){new VT.Notice(ZF(t))}canonicalFolderPath(t){return go(t)}buildFolderSuggestions(t,e,n){let i=[],o=[],s=new Map,a=new Map,l=(c,d)=>{let u=cr(c);s.has(u)||n&&n.length>0&&!this.isPathAllowed(c,n)||(i.push(c),o.push(d??c),s.set(u,this.canonicalFolderPath(c)),d&&a.set(u,d))};for(let c of e)l(c.path,c.label);for(let c of t)l(c);return{items:i,displayItems:o,canonicalByNormalized:s,displayByNormalized:a}}renderFolderSuggestion(t,e,n,i){e.empty(),e.classList.add("mod-complex");let o=cr(t),s=i.get(o),a=t||"/",l=n.has(o),c="";s==="<current folder>"?c="Current folder":l||(c="Create folder"),e.createDiv("suggestion-content").createDiv("suggestion-title").createSpan({text:a}),c&&e.createDiv("suggestion-aux").createEl("kbd",{cls:"suggestion-hotkey",text:c})}}});function Dre(r){let t=[],e=[];for(let[n,i]of r){let o=tM(n,i,new Set,0);t.push(...o.warnings),e.push(...o.errors)}return{isValid:e.length===0,warnings:t,errors:e}}function tM(r,t,e,n){let i=[],o=[];if(typeof t=="function")return o.push(`Variable "${r}" contains a function, which cannot be serialized to YAML`),{warnings:i,errors:o};if(typeof t=="symbol")return o.push(`Variable "${r}" contains a symbol, which cannot be serialized to YAML`),{warnings:i,errors:o};if(typeof t=="bigint")return i.push(`Variable "${r}" contains a BigInt, which will be converted to a string`),{warnings:i,errors:o};if(t==null)return{warnings:i,errors:o};if(typeof t!="object")return{warnings:i,errors:o};if(e.has(t))return o.push(`Variable "${r}" contains a circular reference`),{warnings:i,errors:o};if(n>=eM.MAX_NESTING_DEPTH)return o.push(`Variable "${r}" exceeds maximum nesting depth of ${eM.MAX_NESTING_DEPTH}`),{warnings:i,errors:o};e.add(t);try{if(Array.isArray(t))for(let s=0;s<t.length;s++){let a=tM(`${r}[${s}]`,t[s],e,n+1);i.push(...a.warnings),o.push(...a.errors)}else for(let[s,a]of Object.entries(t)){let l=tM(`${r}.${s}`,a,e,n+1);i.push(...l.warnings),o.push(...l.errors)}}finally{e.delete(t)}return{warnings:i,errors:o}}function Ef(r,t){return Ore.includes(r.extension)&&t.size>0}async function Tf(r,t,e){let n=Dre(e);if(n.warnings.length>0)for(let i of n.warnings)S.logWarning(`Structured variable validation warning: ${i}`);if(!n.isValid){let i=n.errors.join("; ");S.logError(`Cannot post-process front matter for file ${t.path} due to validation errors: ${i}. The file was created successfully, but some structured variables may not be properly formatted. Please check the variable values and ensure they don't contain circular references, exceed nesting depth of ${eM.MAX_NESTING_DEPTH}, or contain unsupported types (functions, symbols).`);return}try{S.logMessage(`Post-processing front matter for ${t.path} with ${e.size} structured variables`),S.logMessage(`Variable types: ${Array.from(e.entries()).map(([i,o])=>`${i}:${typeof o}`).join(", ")}`),await Va(r,t,i=>{for(let[o,s]of e){let a=o.includes(Ui.PATH_SEPARATOR)?o.split(Ui.PATH_SEPARATOR):[o],l=wp(s);Ry(i,a,l)}}),S.logMessage(`Successfully post-processed front matter for ${t.path}`)}catch(i){S.logError(`Failed to post-process front matter for file ${t.path}: ${i}. The file was created successfully, but structured variables may not be properly formatted. This usually happens when variable values contain unexpected types or when Obsidian's YAML processor encounters an issue. Check the console for more details about which variables caused the problem.`)}}function rM(r){return r.some((t,e)=>t==="__proto__"?!0:!(e===r.length-1)&&Lre.has(t))}function Ry(r,t,e){if(t.length===0)return;if(rM(t)){S.logWarning(`Skipping front matter assignment for unsafe key path "${t.join(".")}" to avoid prototype pollution.`);return}let n=r;for(let i=0;i<t.length-1;i++){let o=t[i],s=n[o];(typeof s!="object"||s===null||Array.isArray(s))&&(n[o]={}),n=n[o]}n[t[t.length-1]]=e}var eM,Ore,Lre,UT=x(()=>{Ns();ye();Cp();jh();eM={MAX_NESTING_DEPTH:10},Ore=["md"];Lre=new Set(["prototype","constructor"])});function Oy(r){let t=Hd(r);if(t.length!==0)throw new de(YL(t,r))}function tH(r){return Hd(r).length===0}var qT=x(()=>{Sn();es()});function nM(r){return r instanceof at||!!r&&typeof r=="object"&&"name"in r&&r.name==="MacroAbortError"}var rH,qc,zT=x(()=>{zF();Ma();Lc();Nc();Ns();eH();UT();Su();rH=require("obsidian");Jt();Uc();Le();nt();es();Yi();Dr();ri();ye();qT();vf();qc=class extends BT{constructor(e,n,i,o){super(e);this.plugin=n;this.cursorPlacement=null;this.templaterCursorHandled=!1;this.lastTemplateFileFailure=null;this.templater=QF(e),this.formatter=new Ai(e,n,i),o&&this.formatter.setTemplateInclusionState(o)}hasTemplaterHandledCursor(){return this.templaterCursorHandled}async finishTemplateContent(e){if(this.cursorPlacement=null,e.extension!=="md")return;let n=null;await To(this.app,e,i=>{let o=RT(i);return n=wy(o.content,o.offsets),n.content}),this.cursorPlacement=n,this.cursorPlacement?.offsets.length===0&&(this.cursorPlacement=null)}getCursorPlacement(){return this.cursorPlacement}placeCursor(e,n){let i=ai(this.app,e)?.editor;if(this.cursorPlacement&&i)for(let o of[this.cursorPlacement,n]){if(!o)continue;let s=qF(o,i.getValue())??o;if(Iy(this.app,e,s.offsets,s.content))return}}async rebaseCursorAfterFileChanges(e){if(this.cursorPlacement)try{this.cursorPlacement=qF(this.cursorPlacement,await this.app.vault.read(e))}catch{this.cursorPlacement=null,S.logMessage(`Unable to verify cursor position in '${e.path}'.`)}}stripDuplicateFolderPrefix(e,n){let i=this.stripLeadingSlash(n),o=this.stripLeadingSlash(e);return i?o.startsWith(`${i}/`)?{fileName:o.slice(i.length+1),strippedPrefix:!0}:{fileName:o,strippedPrefix:!1}:{fileName:o,strippedPrefix:!1}}shouldTreatFormattedNameAsVaultRelativePath(e,n,i){if(i||n)return!1;let o=e.trim();if(!o.includes("/")||o.startsWith("./"))return!1;if(o.startsWith("/"))return!0;let[s]=this.stripLeadingSlash(o).split("/");return s?this.app.vault.getAbstractFileByPath(s)instanceof rH.TFolder:!1}getTemplateExtension(e){return e=En(e),lr.test(e)?".canvas":Rn.test(e)?".base":".md"}normalizeTemplateFilePath(e,n,i){let o=this.stripLeadingSlash(e),s=o?`${o}/`:"",a=this.getTemplateExtension(i),l=Br(this.stripLeadingSlash(n),"File name"),c=Br(l.replace(xt,"").replace(lr,"").replace(Rn,""),"File name");if(!c.slice(c.lastIndexOf("/")+1).trim())throw new Error("File name is empty after formatting. Make sure the tokens in the file name format produce a value (an optional token left empty can cause this).");let u=`${s}${c}${a}`;if(Ut(u))throw new Error(`Refusing to build a file path outside the vault: "${u}".`);return u}noteTemplateFileFailure(e,n){this.lastTemplateFileFailure=e instanceof Error&&e.message?e.message:n}setTemplateDestination(e,n){this.formatter.setTitle(n),this.formatter.setTargetFolderPath(ei(e)),this.formatter.setPromptRunContext({destination:e,destinationKind:"file"})}async prepareTemplateBody(e,n,i,o){this.setTemplateDestination(n,i);let s=n.toLowerCase().endsWith(".md"),a=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.withPromptScope("noteBody",e,()=>s?this.formatter.withUserTextProtected(()=>this.formatter.formatTemplateContent(e)):this.formatter.formatFileContent(e))),l=this.formatter.getAndClearTemplatePropertyVars();S.logMessage(`TemplateEngine.${o}: Collected ${l.size} template property variables for ${n}`),l.size>0&&S.logMessage(`Variables: ${Array.from(l.keys()).join(", ")}`),this.cursorPlacement=null,this.templaterCursorHandled=!1;let c=yl(a);return{content:n.toLowerCase().endsWith(".md")?On(a.slice(0,c))+a.slice(c):On(a),variables:l}}async createFileWithTemplate(e,n){this.lastTemplateFileFailure=null,Oy(e);try{let i=await this.getTemplateContent(n),{content:o,variables:s}=await this.prepareTemplateBody(i,e,Is(e),"createFileWithTemplate"),a=e.toLowerCase().endsWith(".md"),l=await this.createFileWithInput(e,o,{suppressTemplaterOnCreate:a}),c=!1;try{Ef(l,s)&&await Tf(this.app,l,s),this.templaterCursorHandled=await Eu(this.app,l),c=!0}finally{await this.finishTemplateContent(l).catch(d=>{if(c)throw d;S.logWarning(`Unable to clean cursor markers in '${l.path}': ${String(d)}`)})}return l}catch(i){if(nM(i))throw i;return this.noteTemplateFileFailure(i,`Could not create file with template at ${e}`),Me(i,`Could not create file with template at ${e}`),null}}setLinkToCurrentFileBehavior(e){this.formatter.setLinkToCurrentFileBehavior(e)}setTargetFolderPath(e){this.formatter.setTargetFolderPath(e)}setPromptRunContext(e){this.formatter.setPromptRunContext(e)}get choiceChain(){return this.formatter.choiceChain}set choiceChain(e){this.formatter.choiceChain=e}async resolveTemplateSourcePath(e){return this.formatter.formatTemplateFilePath(e)}async overwriteFileWithTemplate(e,n){this.lastTemplateFileFailure=null;try{let i=await this.getTemplateContent(n),{content:o,variables:s}=await this.prepareTemplateBody(i,e.path,e.basename,"overwriteFileWithTemplate");await To(this.app,e,()=>o);let a=!1;try{Ef(e,s)&&await Tf(this.app,e,s),this.templaterCursorHandled=await Eu(this.app,e),a=!0}finally{await this.finishTemplateContent(e).catch(l=>{if(a)throw l;S.logWarning(`Unable to clean cursor markers in '${e.path}': ${String(l)}`)})}return e}catch(i){if(nM(i))throw i;return this.noteTemplateFileFailure(i,"Could not overwrite file with template"),Me(i,"Could not overwrite file with template"),null}}async appendToFileWithTemplate(e,n,i){this.lastTemplateFileFailure=null;try{let o=await this.getTemplateContent(n);this.setTemplateDestination(e.path,e.basename);let s=await this.formatter.withPromptScope("noteBody",o,()=>this.formatter.withUserTextProtected(()=>this.formatter.formatFileContent(o)));e.extension==="md"&&(s=await Bc(this.app,s,e)),s=An(s);let a=await this.app.vault.cachedRead(e),l=i==="top"?`${s}
|
||
${a}`:`${a}
|
||
${s}`;return await this.app.vault.modify(e,l),e}catch(o){if(nM(o))throw o;return this.noteTemplateFileFailure(o,"Could not append to file with template"),Me(o,"Could not append to file with template"),null}}async getTemplateContent(e){let n=nn(this.app,e);if(!n)throw new Error(`Template file not found at path "${e}".`);return await this.app.vault.cachedRead(n)}}});var nH={};cb(nH,{SingleTemplateEngine:()=>_f});var _f,iM=x(()=>{zT();ye();Dr();_f=class extends qc{constructor(e,n,i,o,s){super(e,n,o,s);this.templatePath=i;this.promptScope="noteBody";this.preserveCursorMarkers=!1;this.keepUserTextProtected=!1}setPreserveCursorMarkers(e){this.preserveCursorMarkers=e}setKeepUserTextProtected(e){this.keepUserTextProtected=e}setPromptScope(e){this.promptScope=e}setDestinationPath(e){this.formatter.setTitle(Is(e)),this.formatter.setTargetFolderPath(ei(e))}async run(){let e=await this.resolveTemplateSourcePath(this.templatePath),n=await this.getTemplateContent(e);n||S.logError(`Template ${e} not found.`);let i=()=>this.preserveCursorMarkers?this.formatter.formatTemplateContent(n):this.formatter.formatFileContent(n);return n=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.withPromptScope(this.promptScope,n,()=>this.keepUserTextProtected?this.formatter.withUserTextProtected(i):i())),n}getAndClearTemplatePropertyVars(){return this.formatter.getAndClearTemplatePropertyVars()}}});var iH={};cb(iH,{SingleInlineScriptEngine:()=>oM});var oM,oH=x(()=>{Sy();oM=class extends ta{constructor(t,e,n,i,o){super(t,e,null,n,i,void 0,void 0,null,o)}async runAndGetOutput(t){let e=Object.getPrototypeOf(async function(){}).constructor;return await new e(t).bind(this.params,this).call()}}});var sH,Ai,Su=x(()=>{Ma();vf();p2();C2();Tg();Wd();Oa();sH=require("obsidian");Le();Rd();Qi();wF();_2();Qd();Da();Ln();xo();kT();vl();Op();yp();bu();rr();Sn();nt();Ai=class extends ec{constructor(e,n,i,o){super(e);this.app=e;this.plugin=n;this.choiceExecutor=i;this.contentValuePromptsAcceptImagePaste=!1;this.preserveTemplateCursorMarkers=!1;this.keepUserTextProtected=!1;this.choiceChain=[];this.skipPropertyExpansion=!1;this.includingText=null;this.dateParser=o||So,i&&(this.variables=i?.variables)}userText(e){return t2(e)}async withUserTextProtected(e){let n=this.keepUserTextProtected;this.keepUserTextProtected=!0;try{return await e()}finally{this.keepUserTextProtected=n}}runClocks(){return this.choiceExecutor?.clocks??this.clocks}async format(e){return this.formatScalarTokens(await this.expandCodeAndIncludes(e))}async expandCodeAndIncludes(e){let n=qi(e);n=await this.replaceInlineJavascriptInString(n),n=await this.replaceMacrosInString(n);let i=this.includingText;this.includingText=await this.replaceGlobalVarInString(n);try{n=await this.replaceTemplateInString(n)}finally{this.includingText=i}return this.replaceGlobalVarInString(n)}async formatScalarTokens(e){let n=e;return n=this.replaceDateInString(n),n=this.replaceTimeInString(n),n=await this.replaceValueInString(n),n=await this.replaceSelectedInString(n),n=await this.replaceClipboardInString(n),n=await this.replaceDateVariableInString(n),n=await this.replaceVariableInString(n),n=await this.replaceFieldVarInString(n),n=await this.replaceFileInString(n),n=await this.replaceMathValueInString(n),n=this.replaceRandomInString(n),this.defersPropertyExpansion()||(n=this.replacePropertyInString(n)),this.promptScope==="captureText"||this.promptScope==="noteBody"&&this.preserveTemplateCursorMarkers?n:On(n)}async replaceGlobalVarInString(e){return rc(e,this.plugin?.settings?.globalVariables)}async formatFileName(e,n="generic"){if(ho.test(e))throw new Error("{{title}} cannot be used in file names as it would create a circular dependency. The title is derived from the filename itself.");let i=await this.withPromptScope(n,e,()=>this.format(e));if(ho.test(i))throw new Error("{{title}} cannot be used in file names as it would create a circular dependency. The title is derived from the filename itself.");return i=this.replaceCurrentFileTokensInString(i,{fileName:!0,folder:!0,activeFolder:"path"}),An(i)}get includer(){return this.templateInclusion?.includer}async resolveIncludingTextDate(e){if(!(!this.includer||lg(this.variables,e)!==void 0))for(let n=this.includer;n;n=n.includer){let i=[...(n.includingText??"").matchAll(new RegExp(Ss.source,"gi"))].filter(o=>o[1]?.trim().toLowerCase()===e.toLowerCase());if(i.length>0){await n.replaceDateVariableInString(i.map(o=>o[0]).join(""));return}}}defersPropertyExpansion(){return this.includer?.defersPropertyExpansion()??this.skipPropertyExpansion}writesListPicksAsLines(){return this.includer?.writesListPicksAsLines()??super.writesListPicksAsLines()}async formatPropertyName(e){return await this.withPromptScope("propertyName",e,async()=>An(this.replaceCurrentFileTokensInString(await this.format(e),{links:!0,fileName:!0,folder:!0,activeFolder:"content",title:!0})))}async formatPropertyValue(e,n={}){let i=await this.preserveSingleTokenValue(e,()=>this.withPromptScope("propertyValue",e,async()=>{this.skipPropertyExpansion=!0,this.listPicksAsLines=n.listItems??!1;let o;try{o=await this.format(e)}finally{this.skipPropertyExpansion=!1,this.listPicksAsLines=!1}return o=this.replaceCurrentFileTokensInString(o,{links:!0,fileName:!0,folder:!0,activeFolder:"content",title:!0}),this.replacePropertyInString(o)}));return typeof i=="string"?An(On(i)):i}async formatTemplateContent(e){return this.formatContentWithCursorMarkers(e,!0)}async formatFileContent(e){return this.formatContentWithCursorMarkers(e,!1)}async formatContentWithCursorMarkers(e,n){let i=e,o=this.preserveTemplateCursorMarkers;this.preserveTemplateCursorMarkers=n;let s=this.contentValuePromptsAcceptImagePaste;this.contentValuePromptsAcceptImagePaste=!fw(this.promptScope);try{i=await this.format(i)}finally{this.contentValuePromptsAcceptImagePaste=s,this.preserveTemplateCursorMarkers=o}return i=this.replaceCurrentFileTokensInString(i,{links:!0,fileName:!0,folder:!0,activeFolder:"content",title:!0}),this.keepUserTextProtected||this.includer?i:An(i)}async formatFolderPath(e){if(ho.test(e))throw new Error("{{title}} cannot be used in folder paths as it would create a circular dependency. The title is derived from the filename itself.");let n=await this.withPromptScope("folder",e,()=>this.format(e));if(ho.test(n))throw new Error("{{title}} cannot be used in folder paths as it would create a circular dependency. The title is derived from the filename itself.");let i=this.replaceCurrentFileTokensInString(n,{folder:!0,activeFolder:"path"});return An(i).replace(/^\/+/,"")}async formatTemplateFilePath(e){if(ho.test(e))throw new Error("{{title}} cannot be used in a template path \u2014 the title is derived from the created file, not the source template.");let n=qi(e);if(n=await this.replaceGlobalVarInString(n),ho.test(n))throw new Error("{{title}} cannot be used in a template path \u2014 the title is derived from the created file, not the source template.");return n=await this.withPromptScope("templatePath",e,()=>this.formatScalarTokens(n)),An(n).trim()}async formatLocationString(e){let n=await this.withPromptScope("lineTarget",e,()=>this.format(e));return n=this.replaceCurrentFileTokensInString(n,{links:!0,fileName:!0,title:!0}),An(n)}getLinkSourcePath(){return this.includer?.getLinkSourcePath()??null}getCurrentFileLink(){if(this.includer)return this.includer.getCurrentFileLink();let e=kr(this.app,this.choiceExecutor);return e?this.app.fileManager.generateMarkdownLink(e,""):null}getCurrentFileName(){return kr(this.app,this.choiceExecutor)?.basename??null}getCurrentFolderPath(){let e=kr(this.app,this.choiceExecutor);if(!e)return null;let n=e.parent?.path??"";return n==="/"?"":n}getCurrentFileLinkToSection(){let e=kr(this.app,this.choiceExecutor);if(!e)return null;let n=this.getLinkSourcePath()??"",i=null;try{i=this.getActiveHeadingSubpath(e)}catch{i=null}return i?this.app.fileManager.generateMarkdownLink(e,n,i):this.app.fileManager.generateMarkdownLink(e,n)}getActiveHeadingSubpath(e){let n=this.app.workspace.getActiveViewOfType(sH.MarkdownView);if(!n||n.file?.path!==e.path||n.getMode()==="preview")return null;let i=n.editor,o=i?.getCursor();if(!i||!o)return null;let s=i.getValue(),a=si(s.split(/\r?\n/)),c=n.data.replace(/\r\n/g,`
|
||
`)===s?this.app.metadataCache.getFileCache(e):null,d=(c?.headings??[]).map(y=>({heading:y.heading,level:y.level,line:y.position.start.line})),u=y=>`${y.level}:${yu(y.heading)}`,p=new Map(a.map(y=>[y.line,u(y)]));if(!(c&&d.every(y=>p.get(y.line)===u(y))))return NF(a,o.line);let h=new Set(d.map(y=>y.line)),g=(c.sections??[]).filter(y=>y.type==="html"||y.type==="comment"||y.type==="math"),v=a.filter(y=>!h.has(y.line)&&!g.some(C=>C.position.start.line<=y.line&&y.line<=C.position.end.line)),b=[...d,...v].sort((y,C)=>y.line-C.line);return NF(b,o.line)}getVariableValue(e){return this.variables.get(e)??""}shouldUseSelectionForValue(){return this.includer?.shouldUseSelectionForValue()??!0}async getSelectedTextForValue(){return this.includer?await this.includer.getSelectedTextForValue():await this.getSelectedText()}assertInteractivePrompt(e){if(this.choiceExecutor?.interactive===!1)throw new de(`This run is non-interactive but a value for ${e} was not provided up front. Pass it (e.g. a value- flag) or re-run with the ui flag.`)}describeAnonymousValuePrompt(){let e=gw(this.promptScope,this.promptScopeSoleValue),n=this.valuePromptContext?.label??e.title??(this.promptRunContext?.choiceName?.trim()||"Enter value"),i=hw(this.promptScope);return{title:n,placeholder:e.placeholder,contextLine:vp(this.promptRunContext,n,{showDestination:i}),contextLineFull:vp(this.promptRunContext,n,{elide:!1,showDestination:i})}}async promptForValue(e){if(this.value===void 0){if(this.shouldUseSelectionForValue()){let o=await this.getSelectedTextForValue();if(o){let s=this.normalizeSelectedTextForPrompt(o);if(s!==void 0)return this.value=s,this.value}}if(this.assertInteractivePrompt("{{VALUE}}"),this.valuePromptContext?.inputTypeOverride==="checkbox"){let o=this.choiceExecutor?.promptProvider;if(o)return this.value=String(await o.suggester(["true","false"],["true","false"],this.describeAnonymousValuePrompt().title,!1)),this.value;try{return this.value=await It.Suggest(this.app,["true","false"],["true","false"],this.describeAnonymousValuePrompt().title,void 0,this.valuePromptContext.optional?{skippable:!0}:void 0),this.value}catch(s){throw Be(s)?new et("Input cancelled by user"):s}}let n=this.describeAnonymousValuePrompt(),i=this.choiceExecutor?.promptProvider;if(i)return this.value=await i.inputPrompt(n.contextLine?`${n.title} (${n.contextLine})`:n.title,this.valuePromptContext?.placeholder??n.placeholder,this.valuePromptContext?.defaultValue),this.value;try{let o=this.getLinkSourcePath(),s=new hu().factory(this.valuePromptContext?.inputTypeOverride??this.defaultValueInputType),a=this.valuePromptContext?.defaultValue,l=this.buildInputPromptOptions(this.valuePromptContext,n.contextLine,n.contextLineFull),c=this.valuePromptContext?.placeholder??n.placeholder;this.value=await s.Prompt(this.app,n.title,c,a,void 0,{...l,linkSourcePath:o||void 0})}catch(o){throw Be(o)?new et("Input cancelled by user"):o}}return this.value}normalizeSelectedTextForPrompt(e){let n=this.valuePromptContext;if(n?.inputTypeOverride==="checkbox"){let s=e.trim().toLowerCase();return s==="true"||s==="false"?s:void 0}if(n?.inputTypeOverride!=="number"&&n?.inputTypeOverride!=="slider")return e;let i=n.sliderConfig??n.numericConfig,o=Co(e,i);return o===""?void 0:o}buildInputPromptOptions(e,n,i){let o=this.contentValuePromptsAcceptImagePaste&&e?.inputTypeOverride!=="number"&&e?.inputTypeOverride!=="slider"?{sourcePath:this.getLinkSourcePath()??""}:void 0,s=this.promptRunContext?.draftScopeId;return{optional:e?.optional,numeric:e?.numericConfig,slider:e?.sliderConfig,imagePaste:o,contextLine:n,contextLineFull:i,draftScopeId:s,allowPeek:!0}}promptRuntime(){return{app:this.app,executor:this.choiceExecutor,scope:this.promptScope,runContext:this.promptRunContext,assertInteractivePrompt:e=>this.assertInteractivePrompt(e),buildInputPromptOptions:(e,n,i)=>this.buildInputPromptOptions(e,n,i)}}async promptForVariable(e,n){return c2(this.promptRuntime(),e,n)}async promptForMathValue(){let e=this.choiceExecutor?.promptProvider;if(e)return await e.inputPrompt("Enter a math expression");this.assertInteractivePrompt("a {{MVALUE}} math expression");try{return await IT.Prompt()}catch(n){throw Be(n)?new et("Input cancelled by user"):n}}async suggestForValue(e,n=!1,i){return d2(this.promptRuntime(),e,n,i)}async suggestForValueMulti(e,n=!1,i){return u2(this.promptRuntime(),e,n,i)}async suggestForField(e){return this.assertInteractivePrompt(`{{FIELD:${e}}}`),b2({app:this.app,executor:this.choiceExecutor,getSourcePath:()=>this.getLinkSourcePath()},e)}generateCacheKey(e){return IF(e)}async suggestForFile(e){return this.assertInteractivePrompt(`{{FILE}} (pick a file from ${e.folderPath})`),w2({app:this.app,executor:this.choiceExecutor,getSourcePath:()=>this.getLinkSourcePath()},e)}async getMacroValue(e,n){let{SingleMacroEngine:i}=await Promise.resolve().then(()=>(M2(),F2)),o=new i(this.app,this.plugin,this.plugin.settings.choices,this.choiceExecutor,this.variables),s=await o.runAndGetOutput(e,n,this.choiceChain)??"";return o.getVariables().forEach((a,l)=>{this.variables.set(l,a)}),s}async getTemplateContent(e){let{SingleTemplateEngine:n}=await Promise.resolve().then(()=>(iM(),nH));this.templateInclusion??(this.templateInclusion={visited:new Set,depth:0});let i={visited:this.templateInclusion.visited,depth:this.templateInclusion.depth+1,includer:this},o=new n(this.app,this.plugin,e,this.choiceExecutor,i);o.setTargetFolderPath(this.targetFolderPath),o.choiceChain=this.choiceChain,this.preserveTemplateCursorMarkers&&this.promptScope==="noteBody"&&o.setPreserveCursorMarkers(!0),this.promptScope!=="generic"&&o.setPromptScope(this.promptScope),this.promptRunContext&&o.setPromptRunContext({...this.promptRunContext,draftScopeId:`${this.promptRunContext.draftScopeId??""}#${e}`});let s=await o.run();return this.mergeTemplatePropertyVars(o.getAndClearTemplatePropertyVars()),s}async getSelectedText(){return Cf(this.app,this.choiceExecutor)}async getClipboardContent(){if(this.includer)return this.includer.getClipboardContent();try{return await navigator.clipboard.readText()}catch{return""}}isTemplatePropertyTypesEnabled(){return this.plugin.settings.enableTemplatePropertyTypes}async replaceInlineJavascriptInString(e){let n=e,i=pg(n);for(;i;){let{start:o,end:s,code:a}=i,l="";if(a){let{SingleInlineScriptEngine:c}=await Promise.resolve().then(()=>(oH(),iH)),d=new c(this.app,this.plugin,this.choiceExecutor,this.variables,this.choiceChain),u=await d.runAndGetOutput(a);for(let p in d.params.variables)this.variables.set(p,d.params.variables[p]);typeof u=="string"?l=u:(typeof u=="number"||typeof u=="boolean"||Array.isArray(u))&&(l=this.renderCollectedOrArrayValue({input:n,matchStart:o,matchEnd:s,rawValue:u,fallbackKey:"inlineScript",heuristicEnabled:this.isTemplatePropertyTypesEnabled()})??String(u))}n=n.slice(0,o)+l+n.slice(s),i=pg(n,q0(n,o))}return n}async collectValuesManually(e,n){return await $F(this.app,e,n)}}});async function aH(r,t,e,n,i,o){if(U.getState().disableOnlineFeatures)throw new Error("Blocking request: Online features are disabled in settings.");let s=U.getState().ai,a;if(i.model==="Ask me")a=await o();else if(a=lu(Nl(i.model,i.modelRef)??i.model),!a)throw new Error(`Model ${i.model} not found with any provider.`);let{model:l,provider:c}=a,d=new Ai(r,Wr(),e);d.setPromptRunContext({choiceName:t?.name,draftScopeId:`${t?.id??"macro"}#aiAssistant:${i.id}`}),d.choiceChain=n;let u=await Po(r,c),p=await Zz(r,{apiKey:u,model:l,provider:c,outputVariableName:i.outputVariableName,promptTemplate:i.promptTemplate,promptTemplateFolder:s.promptTemplatesFolderPath,systemPrompt:i.systemPrompt,showAssistantMessages:s.showAssistant,modelOptions:i.modelParameters,interactive:e.interactive,promptProvider:e.promptProvider},async m=>d.formatFileContent(m));for(let m in p)e.variables.set(m,p[m])}async function lH(r,t){let n=U.getState().ai.providers.flatMap(o=>lp(o.models).map(s=>({label:`${s.name} (${o.name}${s.deprecated?", retired":""})`,qualified:`${o.id??o.name}/${s.name}`,resolved:{provider:o,model:s}})));if(n.length===0)throw new Error("No AI models are configured. Add a provider with models in the AI Assistant settings.");let i=t.promptProvider;if(i){let o=String(await i.suggester(n.map(a=>a.label),n.map(a=>a.qualified),"Select a model")),s=n.find(a=>a.qualified===o);if(!s)throw new Error(`Model ${o} not found with any provider.`);return s.resolved}if(t.interactive===!1)throw new de('This AI command is set to "Ask me" for the model, but this run is non-interactive. Pick a specific model in the command, or re-run with the ui flag.');try{return await It.Suggest(r,n.map(o=>o.label),n.map(o=>o.resolved),"Select a model")}catch(o){throw Be(o)?new et("Input cancelled by user"):o}}var cH=x(()=>{vF();Ic();je();Su();ss();Vm();gi();nt();Sn();rr();Qi()});function zc(r,t){try{return r.getChoiceById(t)}catch{return null}}var HT=x(()=>{});function WT(r,t){dH.has(r)||(dH.add(r),S.logWarning(t))}function Vre(r,t){return r.type==="NestedChoice"?r.choice??null:r.type==="Choice"?t(r.choiceId):null}function uH(r,t,e){if(!r||t.type!=="Obsidian"||t.commandId!==Nre)return null;let n=Vre(r,e);return n&&(n.type==="Template"||n.type==="Capture")?n.name:null}var Nre,dH,sM=x(()=>{ye();er();Nre="templater-obsidian:replace-in-file-templater",dH=new Set});function hH(r){return Dy.some(t=>t.id===r)}function pH(r){let t=(0,GT.getFrontMatterInfo)(r);return t.exists?{frontmatterYaml:t.frontmatter,body:r.slice(t.contentStart)}:{frontmatterYaml:null,body:r}}function qre(r,t,e){if(e==="bottom"){let n=r.replace(Bre,""),i=n.trim()?`${n}
|
||
|
||
`:"",o=i+t;return{content:o,insertedStartOffset:i.length,insertedEndOffset:o.length}}return wu(r,`${t}
|
||
`)}function zre(r){return r==null||r===""||Array.isArray(r)&&r.length===0}function mH(r){return typeof r=="string"?r.length>0?[r]:[]:!Array.isArray(r)||!r.every(t=>typeof t=="string")?null:r}function fH(r,t){let e=mH(r),n=mH(t);if(e===null||n===null)return;let i=[],o=new Set(e);for(let s of n)s.length===0||o.has(s)||(o.add(s),i.push(s));if(i.length!==0)return[...e,...i]}var GT,Dy,Bre,Ure,kf,jT=x(()=>{GT=require("obsidian");ye();Nc();Uc();UT();Nd();jh();Cp();Dr();Lc();Ns();zF();zT();es();bp();vf();Dy=[{id:"cursor",label:"Insert at cursor",description:"Inserts the template at the cursor position in the editor."},{id:"top",label:"Insert at top",description:"Inserts the template below the note's frontmatter, or at the very top."},{id:"bottom",label:"Append to bottom",description:"Adds the template content to the end of the note."},{id:"replace",label:"Replace note content",description:"Replaces the entire note content with the template."}];Bre=/(?:\r?\n[^\S\r\n]*)+$/,Ure=/^(?:[^\S\r\n]*\r?\n)+/;kf=class extends qc{constructor(e,n,i,o,s,a,l){super(e,n,a);this.targetFile=i;this.templatePath=o;this.mode=s;this.cursorView=null;this.resolvedTemplatePath=l??null}placeCursor(e){this.mode==="cursor"&&ai(this.app,e)!==this.cursorView||super.placeCursor(e)}async run(){await this.apply()}async getResolvedTemplatePath(){return this.resolvedTemplatePath===null&&(this.resolvedTemplatePath=await this.resolveTemplateSourcePath(this.templatePath)),this.resolvedTemplatePath}async apply(){switch(this.cursorPlacement=null,Vr(this.templatePath,"Cannot apply template: no template path given."),this.mode){case"replace":return await this.overwriteFileWithTemplate(this.targetFile,await this.getResolvedTemplatePath());case"top":case"bottom":return await this.insertTemplateIntoFile(this.mode);case"cursor":return await this.insertTemplateAtCursor()}}async computeChoiceTargetPath(e){let n=e.folder,i;if(this.formatter.setTargetFolderPath(null),n?.enabled){if(n.chooseWhenCreatingNote)return null;if(n.createInSameFolderAsActiveFile)i=this.targetFile.parent?.path??"";else{if(n.chooseFromSubfolders)return null;if(n.folders.length===1)i=await this.formatter.formatFolderPath(n.folders[0]);else return null}}else i=this.targetFile.parent?.path??"";i==="/"&&(i="");let o=this.targetFile.basename,s=!1;if(e.fileNameFormat?.enabled&&e.fileNameFormat.format){this.formatter.setTargetFolderPath(i);let a=await this.formatter.formatFileName(e.fileNameFormat.format,"generic"),l=Br(a,"File name"),c=this.stripDuplicateFolderPrefix(l,i);o=c.fileName,s=this.shouldTreatFormattedNameAsVaultRelativePath(l,c.strippedPrefix,n?.enabled??!1)}return o.slice(o.lastIndexOf("/")+1).trim()?this.normalizeTemplateFilePath(s?"":i,o,await this.getResolvedTemplatePath()):null}async insertTemplateIntoFile(e){let{formatted:n,templatePropertyVars:i}=await this.formatTemplateForTargetFile(),o=pH(n),{frontmatterYaml:s}=o,a=e==="bottom"?o.body.replace(Ure,""):o.body,l=this.cursorPlacement;return(a.trim().length>0||l)&&await To(this.app,this.targetFile,c=>{let d=qre(c,a,e);if(l&&d.insertedStartOffset!==null){let u=d.insertedStartOffset,p=u-(n.length-a.length);this.cursorPlacement={content:d.content,offsets:l.offsets.map(m=>Math.max(u,p+m))}}return d.content}),await this.mergeFrontmatterProperties(s,i),await this.rebaseCursorAfterFileChanges(this.targetFile),this.targetFile}async insertTemplateAtCursor(){let e=ai(this.app,this.targetFile);Vr(e,"Cannot insert at cursor: the note is not open in the active editor."),this.cursorView=e;let n=e.editor,{formatted:i,templatePropertyVars:o}=await this.formatTemplateForTargetFile();Vr(e.file===this.targetFile&&e.editor===n&&this.app.workspace.getLeavesOfType("markdown").some(c=>c.view===e),"Cannot insert at cursor: the original editor was closed or changed notes.");let{frontmatterYaml:s,body:a}=pH(i),l=this.cursorPlacement?.offsets[0];return l!==void 0?this.cursorPlacement=GF({content:a,cursor:{kind:"offset",value:l-(i.length-a.length),source:"marker"}},n,"currentLine"):a.trim().length>0&&n.replaceSelection(a),this.cursorPlacement&&s&&await e.save(),await this.mergeFrontmatterProperties(s,o),s&&await this.rebaseCursorAfterFileChanges(this.targetFile),this.targetFile}async formatTemplateForTargetFile(){let e=await this.getTemplateContent(await this.getResolvedTemplatePath());this.formatter.setTitle(this.targetFile.basename),this.formatter.setTargetFolderPath(ei(this.targetFile.path));let n=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.withPromptScope("noteBody",e,()=>this.formatter.withUserTextProtected(()=>this.targetFile.extension==="md"?this.formatter.formatTemplateContent(e):this.formatter.formatFileContent(e)))),i=this.formatter.getAndClearTemplatePropertyVars();this.targetFile.extension==="md"&&(n=await Bc(this.app,n,this.targetFile));let o=RT(n),s=wy(o.content,o.offsets);return this.cursorPlacement=this.targetFile.extension==="md"&&s.offsets.length>0?s:null,{formatted:s.content,templatePropertyVars:i}}async mergeFrontmatterProperties(e,n){if(!e||this.targetFile.extension!=="md")return;let i;try{i=(0,GT.parseYaml)(e)}catch(o){S.logWarning(`Could not parse template frontmatter for merging: ${o}`);return}if(!(!i||typeof i!="object"||Array.isArray(i))){if(n&&n.size>0)for(let[o,s]of n){let a=o.includes(Ui.PATH_SEPARATOR)?o.split(Ui.PATH_SEPARATOR):[o];Ry(i,a,wp(s))}await Va(this.app,this.targetFile,o=>{for(let[s,a]of Object.entries(i)){if(rM([s])){S.logWarning(`Skipping front matter merge for unsafe key "${s}" to avoid prototype pollution.`);continue}let l=Object.hasOwn(o,s)?o[s]:void 0,c=m0(this.app,s);if(zre(l)){c&&Array.isArray(a)?o[s]=fH([],a)??[]:o[s]=a;continue}if(c){let d=fH(l,a);d!==void 0&&(o[s]=d)}}})}}}});function Hre(r){return r.trim().length===0}function Hc(r){return r=En(r),!lr.test(r)&&!Rn.test(r)}function Wre(r){return r.kind==="choice"?`Choice: ${r.choice.name}`:`Template: ${r.path}`}function Gre(r){return En(r).toLowerCase()}function jre(r){return r.toLowerCase()}function Yre(r,t){let e=Zt(r).filter(o=>o.type==="Template"&&!!o.templatePath&&Hc(o.templatePath)),n=new Set(e.map(o=>Gre(o.templatePath))),i=e.map(o=>({kind:"choice",choice:o}));for(let o of t)Hc(o)&&(n.has(jre(o))||i.push({kind:"file",path:o}));return i}async function Ly(r,t,e){let n=e.file??r.workspace.getActiveFile();if(!n||n.extension!=="md")return new Sf.Notice("QuickAdd: No active markdown note to apply a template to."),null;let i=e.choiceExecutor.triggerContext;i==null&&(e.choiceExecutor.triggerContext={activeFile:n});try{let o=!e.templatePath,s;if(e.templatePath)s={kind:"file",path:e.templatePath};else{let h=await Kre(r,t);if(!h)return null;s=h}let a=s.kind==="choice"?s.choice.templatePath:s.path;if(!Hc(a))return new Sf.Notice("QuickAdd: Only markdown templates can be applied to a note. Canvas and base templates create their own file types."),null;let l=await Bd(r,n),c=Hre(l),d;if(e.mode)d=e.mode;else if(c)d="replace";else if(!o)d="bottom";else{let h=await Qre(r,n);if(!h)return null;d=h}e.choiceExecutor.variables.has("value")||e.choiceExecutor.variables.set("value",n.basename);let u=new kf(r,t,n,a,d,e.choiceExecutor);e.chain&&(u.choiceChain=e.chain),u.setPromptRunContext({choiceName:s.kind==="choice"?s.choice.name:void 0,draftScopeId:s.kind==="choice"?s.choice.id:`template-insert#${a}`,destination:n.path,destinationKind:"file"});let p=await u.getResolvedTemplatePath();return Hc(p)?await u.apply()?(o&&s.kind==="choice"&&(u.setPromptRunContext({destination:void 0,destinationKind:void 0}),await Xre(r,u,s.choice,n)),!u.hasTemplaterHandledCursor()&&!await Tu(r,n)&&u.placeCursor(n),new Sf.Notice(`Applied template to '${n.basename}'.`),n):null:(new Sf.Notice("QuickAdd: Only markdown templates can be applied to a note. Canvas and base templates create their own file types."),null)}catch(o){return Be(o)||gH(o)||Me(o,"Error applying template to note"),null}finally{e.choiceExecutor.triggerContext=i}}function gH(r){return!!r&&typeof r=="object"&&r.name==="MacroAbortError"}async function Kre(r,t){let e=Yre(t.settings.choices,t.getTemplateFiles().map(n=>n.path));if(e.length===0)return new Sf.Notice("QuickAdd: No Template choices or template files found. Create a Template choice or set the template folder path in settings."),null;try{return await It.Suggest(r,e.map(Wre),e,"Apply template to note")}catch(n){if(Be(n))return null;throw n}}async function Qre(r,t){let e=!!ai(r,t),n=Dy.filter(i=>i.id!=="cursor"||e);try{return await It.Suggest(r,n.map(i=>i.label),n.map(i=>i.id),"How should the template be applied?")}catch(i){if(Be(i))return null;throw i}}async function Xre(r,t,e,n){try{let i=await t.computeChoiceTargetPath(e);if(!i||i===n.path||await r.vault.adapter.exists(i)||!tH(i)||!await Ei(r,{title:"Move note to match choice settings?",message:`'${e.name}' creates notes at '${i}'. Move '${n.path}' there? Links to the note will be updated.`,action:"Move",destructive:!1}))return;let s=i.lastIndexOf("/"),a=s===-1?"":i.slice(0,s);a&&!await r.vault.adapter.exists(a)&&await r.vault.createFolder(a),await r.fileManager.renameFile(n,i)}catch(i){if(Be(i)||gH(i))return;S.logWarning(`Could not move note to match choice settings: ${i}`)}}var Sf,YT=x(()=>{Jt();Sf=require("obsidian");Le();Qi();tl();ye();Nc();Uc();lt();qT();nt();Ns();jT()});function Jre(r,t,e){return window.moment(r).add(t,e).startOf("day").toDate()}function Ny(r){if(r instanceof Date&&!Number.isNaN(r.getTime()))return r;if(typeof r!="string")return;let t=r.trim();if(!t)return;if(t.toLowerCase().startsWith("@date:")){let n=t.slice(6),i=window.moment(n);return i.isValid()?i.toDate():void 0}let e=Rc(t,void 0,So);if(e.isValid&&e.isoString){let n=window.moment(e.isoString);return n.isValid()?n.toDate():void 0}}function KT(r){if(r.clocks?.date)return{status:"inherit"};if(r.reservedSeed!==void 0){let o=Ny(r.reservedSeed);return o?{status:"set",date:o}:{status:"error",message:"Could not parse the seeded date origin."}}let t=r.setting;if(!t||t.kind==="now")return{status:"inherit"};if(t.kind==="ask")return{status:"ask",defaultValue:t.defaultValue};if(t.kind==="relative"){let o=r.clocks?.now??new Date;return{status:"set",date:Jre(o,t.offset,t.unit)}}let e=r.variables;if(!e)return{status:"error",message:`Date origin variable "${t.name}" is not available.`};let n=Yl(e,t.name);if(!n)return{status:"error",message:`Date origin variable "${t.name}" is not set.`};let i=Ny(e.get(n));return i?{status:"set",date:i}:{status:"error",message:`Date origin variable "${t.name}" is not a date.`}}function Af(r,t){if(t==null||typeof t=="string"&&!t.trim())return!0;if(O1(t))return r.pickDate=!0,!0;let e=Ny(t);return e?(r.clocks={now:r.clocks?.now??new Date,date:e},!0):!1}var If=x(()=>{Qd();uc();vu();xo()});var Vy,By,vH=x(()=>{Vy=require("obsidian");tl();By=class r extends Vy.Modal{constructor(e,n,i){super(e);this.header=n;this.text=i;this.input=null;this.waitForClose=new Promise(o=>{this.resolvePromise=o}),this.open(),this.display()}static Ask(e,n,i){return new r(e,n,i).waitForClose}display(){this.containerEl.addClass("quickAddModal","qaYesNoPrompt"),this.contentEl.empty(),this.titleEl.textContent=this.header,this.contentEl.createEl("p",{text:this.text});let e=this.contentEl.createDiv({cls:"yesNoPromptButtonContainer"}),n=new Vy.ButtonComponent(e).setButtonText("No").onClick(()=>this.submit(!1));KC(n.buttonEl);let i=new Vy.ButtonComponent(e).setButtonText("Yes").onClick(()=>this.submit(!0)).setDestructive();KC(i.buttonEl),i.buttonEl.focus(),QC([n.buttonEl,i.buttonEl])}submit(e){this.input=e,this.close()}onClose(){super.onClose(),this.resolvePromise(this.input)}}});var QT,Uy,yH=x(()=>{QT=require("obsidian"),Uy=class r extends QT.Modal{constructor(e,n,i){super(e);this.header=n;this.text=i;this.waitForClose=new Promise(o=>{this.resolvePromise=o}),this.open(),this.display()}static Show(e,n,i){return new r(e,n,i).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(i=>this.contentEl.createEl("p",{text:i}));let e=this.contentEl.createDiv(),n=new QT.ButtonComponent(e).setButtonText("OK").onClick(()=>this.close());Object.assign(e.style,{display:"flex",justifyContent:"flex-end"}),n.buttonEl.focus()}onClose(){super.onClose(),this.resolvePromise()}}});var qy,Pf,bH=x(()=>{qy=require("obsidian");rr();xF();Pf=class r extends qy.Modal{constructor(e,n,i=[],o){super(e);this.items=n;this.selectedItems=i;this.header=o;this._selectedItems=[...i],this.promise=new Promise((s,a)=>{this.resolvePromise=s,this.rejectPromise=a}),this.display(),this.open(),this.picker.focusSearchOnOpen()}static Open(e,n,i,o){return new r(e,n,i,o).promise}onEscapeKey(e){if(this.picker.clearSearch()){e.preventDefault();return}super.onEscapeKey(e)}display(){this.contentEl.empty(),this.containerEl.addClass("quickAddModal","qaSearchableMultiSelectModal","checkboxPrompt"),this.header&&(this.titleEl.textContent=this.header),this.addSearchableOptions(),this.addSubmitButton()}onClose(){super.onClose(),this.resolved||this.rejectPromise(on())}addSearchableOptions(){this.picker=new gu(this.contentEl,{items:this.items.map(e=>({key:e,value:e,label:e})),isSelected:({value:e})=>this._selectedItems.includes(e),onToggle:({value:e},n)=>{if(n){this._selectedItems.includes(e)||this._selectedItems.push(e);return}this._selectedItems=this._selectedItems.filter(i=>i!==e)},getSelectedCount:()=>new Set(this._selectedItems).size})}addSubmitButton(){let e=this.contentEl.createDiv("submitButtonContainer");new qy.ButtonComponent(e).setButtonText("Cancel").onClick(()=>{this.close()}),new qy.ButtonComponent(e).setButtonText("Submit").setCta().onClick(()=>{this.resolved=!0,this.resolvePromise(this._selectedItems),this.close()})}}});function na(r){throw r instanceof at?r:Be(r)?new et(ql):r}var ia,aM=x(()=>{Gs();yF();vH();yH();Qi();bH();cl();ET();an();ri();rr();nt();vu();ia=class{static async inputPrompt(t,e,n,i,o){try{return await ir.Prompt(t,e,n,i,void 0,{allowPeek:!0,...o})}catch(s){na(s)}}static async datePrompt(t,e,n){try{let i=await fl.Prompt(t,e,n?.placeholder,n?.defaultValue,n?.dateFormat);if(i&&i.startsWith("@date:")){let o=i.slice(6);return(n?.dateFormat?Mo(o,n.dateFormat):null)??o}return i}catch(i){na(i)}}static async wideInputPrompt(t,e,n,i,o){try{return await Pc.Prompt(t,e,n,i,void 0,{allowPeek:!0,...o})}catch(s){na(s)}}static async yesNoPrompt(t,e,n){let i;try{i=await By.Ask(t,e,n)}catch(o){na(o)}if(i===null)throw new et(ql);return i}static async infoDialog(t,e,n){try{return await Uy.Show(t,e,n)}catch(i){na(i)}}static async suggester(t,e,n,i,o=!1,s){try{let a;return typeof e=="function"?a=n.map((l,c,d)=>sn(e(l,c,d))):a=e.map(l=>sn(l)),o?await vr.Suggest(t,a,n,{...i?{placeholder:i}:{},...s?.renderItem?{renderItem:s.renderItem}:{}}):await It.Suggest(t,a,n,i,s?.renderItem)}catch(a){na(a)}}static async checkboxPrompt(t,e,n,i){try{return await(i===void 0?Pf.Open(t,e,n):Pf.Open(t,e,n,i))}catch(o){na(o)}}}});var Zre,XT,wH=x(()=>{Da();kT();hp();Ms();an();Zre=200,XT=class extends Er{constructor(e,n,i){super(e,n);this.matchesByItem=new Map;this.lookupSequence=0;this.dropValues=()=>{this.values=void 0};this.fieldInput=i;let o=Dn.parse(i);this.fieldName=o.fieldName,this.filters=o.filters,n.addEventListener("blur",this.dropValues)}destroy(){this.inputEl.removeEventListener("blur",this.dropValues),super.destroy()}async getSuggestions(e){let n=++this.lookupSequence;this.values??(this.values=g2(this.app,this.fieldName,this.filters));let i=await this.values;if(n!==this.lookupSequence)return[];let o=Hl(e,i,s=>s,{limit:Zre});return this.matchesByItem=new Map(o.map(({item:s,matches:a})=>[s,a])),o.map(({item:s})=>s)}renderSuggestion(e,n){Fs(n,e,this.matchesByItem.get(e)??[])}selectSuggestion(e){this.inputEl.value=e,Pa(this.inputEl),this.close()}}});var lM,CH,JT,xH=x(()=>{lM=require("obsidian");hp();Ms();an();Ln();CH=200,JT=class extends Er{constructor(e,n,i,o,s,a,l,c){super(e,n);this.getOptions=i;this.isSelected=o;this.onSelect=s;this.multiSelect=a;this.allowCustomInput=l;this.newNoteExists=c;this.matchesByOption=new Map;this.aliasByOption=new Map;this.namesByOption=new WeakMap;a&&n.setAttribute("aria-multiselectable","true")}getSuggestions(e){let n=e.trim(),i=this.getOptions().filter(d=>!this.isSelected(d.value)),o=Hl(n,i,d=>`${d.label} ${d.path}`,{limit:CH,aliases:d=>d.aliases});this.matchesByOption=new Map(o.map(({item:d,matches:u})=>[d,u])),this.aliasByOption=new Map(o.flatMap(({item:d,alias:u})=>u!==void 0?[[d,u]]:[]));let s=o.map(({item:d})=>d);if(!n||!this.allowCustomInput)return s;let a=n.toLocaleLowerCase(),l=this.getOptions().some(d=>this.namesOf(d).includes(a)),c=this.isSelected(n);return l||c||this.newNoteExists?.(n)?s:[this.newNoteExists?{value:n,label:`Create new note: ${n}`,path:"",isCustom:!0}:{value:n,label:`Use \u201C${n}\u201D`,path:"Custom value",isCustom:!0},...s].slice(0,CH)}namesOf(e){let n=this.namesByOption.get(e);return n||(n=[e.label,e.path,...e.isCustom?[]:[Ap(e.path)],...e.aliases??[]].map(i=>i.toLocaleLowerCase()),this.namesByOption.set(e,n)),n}renderSuggestion(e,n){n.addClass("qa-onepage-file-suggestion");let i=n.createDiv({cls:"qa-onepage-file-suggestion__text"}),o=i.createDiv({cls:"qa-onepage-file-suggestion__label"});if(e.isCustom&&this.newNoteExists){o.setText(`Create new note: ${e.value}`),n.addClass("mod-complex"),i.addClass("suggestion-content"),(0,lM.setIcon)(n.createDiv({cls:"suggestion-aux"}).createSpan({cls:"suggestion-flair"}),"file-plus");return}let s=i.createDiv({cls:"qa-onepage-file-suggestion__path"});if(e.isCustom){o.setText(e.label),s.setText(e.path);return}let a=this.matchesByOption.get(e)??[],l=this.aliasByOption.get(e);if(l!==void 0){Fs(o,l,a),s.setText(e.label),n.addClass("mod-complex"),i.addClass("suggestion-content");let c=n.createDiv({cls:"suggestion-aux"}).createSpan({cls:"suggestion-flair"});c.setAttribute("aria-label","Alias"),(0,lM.setIcon)(c,"forward");return}Fs(o,e.label,a),Fs(s,e.path,a,e.label.length+1)}selectSuggestion(e){if(this.onSelect(e),this.inputEl.value="",!this.multiSelect){this.close();return}Pa(this.inputEl,!0),this.inputEl.focus()}}});var ene,ZT,EH=x(()=>{hp();Ms();an();ene=200,ZT=class extends Er{constructor(e,n,i,o=!1,s=!1,a){super(e,n);this.matchesByItem=new Map;this.options=i.map(l=>sn(l)),this.caseSensitive=o,this.multiSelect=s,this.onSelect=a,this.multiSelect&&this.inputEl.setAttribute("aria-multiselectable","true")}parseMultiSelectInput(e){if(!this.multiSelect)return{alreadySelected:[],activeTerm:e};let n=e.split(",").map(i=>i.trim());return{alreadySelected:n.slice(0,-1).filter(Boolean),activeTerm:n[n.length-1]||""}}getRemainingOptions(e){return this.options.filter(n=>!e.includes(n))}getSuggestions(e){let n=zl(e),{alreadySelected:i,activeTerm:o}=this.parseMultiSelectInput(n),s=this.getRemainingOptions(i),a=Hl(o,s,l=>l,{limit:ene,caseSensitive:this.caseSensitive});return this.matchesByItem=new Map(a.map(({item:l,matches:c})=>[l,c])),a.map(({item:l})=>l)}renderSuggestion(e,n){Fs(n,e,this.matchesByItem.get(e)??[])}selectSuggestion(e){this.multiSelect?this.selectMultipleItem(e):this.selectSingleItem(e)}selectSingleItem(e){this.inputEl.value=e,Pa(this.inputEl),this.close()}selectMultipleItem(e){let{alreadySelected:n}=this.parseMultiSelectInput(this.inputEl.value);n.push(e),this.onSelect?.(e);let i=this.getRemainingOptions(n).length>0;this.inputEl.value=i?n.join(", ")+", ":n.join(", "),this.inputEl.setSelectionRange(this.inputEl.value.length,this.inputEl.value.length),Pa(this.inputEl,i),i?this.inputEl.focus():this.close()}}});function TH(r,t,e){return e?t.get(r)??r:r}function _H(r,t){return t.length===0?r:r===""?t[0]??"":t.includes(r)?r:t[0]??""}var kH=x(()=>{});function SH(r){return`qa-onepage-label-${encodeURIComponent(r.id)}`}var li,e_,AH=x(()=>{li=require("obsidian");Le();kF();wH();xH();EH();vu();wd();je();xo();Ln();es();kH();e_=class{constructor(t,e,n){this.app=t;this.contentEl=e;this.host=n}setting(t,e=!0){let n=new li.Setting(this.contentEl).setName(this.host.decorateLabel(t));return n.nameEl.id=SH(t),e&&t.description&&n.setDesc(t.description),this.fieldSetting=n,n}labelControls(t){this.fieldSetting?.controlEl.querySelectorAll("input:not([aria-label]), textarea:not([aria-label]), select:not([aria-label])").forEach(e=>e.setAttribute("aria-labelledby",SH(t))),this.fieldSetting=void 0}render(t){let e=this.host.controlFor(t),n=(o,s)=>{e.value=s,this.host.publish(e),this.host.updatePreview()},i=this.host.initialValue(t.id)??t.defaultValue??"";switch(e.value=i,t.type){case"textarea":case"text":{let o=this.setting(t),s=t.type==="textarea"?new li.TextAreaComponent(o.controlEl):new li.TextComponent(o.controlEl);s.setPlaceholder(t.placeholder??"").setValue(i).onChange(a=>n(t.id,a)),t.type==="textarea"&&s.inputEl.addClass("qa-onepage-textarea"),this.host.attachFreeText(t,s.inputEl);break}case"number":{let o=this.setting(t),s=new li.TextComponent(o.controlEl);s.inputEl.type="number",s.inputEl.inputMode="decimal",t.numericConfig?.min!==void 0&&(s.inputEl.min=String(t.numericConfig.min)),t.numericConfig?.max!==void 0&&(s.inputEl.max=String(t.numericConfig.max)),s.inputEl.step=t.numericConfig?.step!==void 0?String(t.numericConfig.step):"any";let a=t.numericConfig?Co(i,t.numericConfig):i;s.setPlaceholder(t.placeholder??"").setValue(a).onChange(l=>n(t.id,t.numericConfig?Co(l,t.numericConfig):l)),n(t.id,a);break}case"slider":{let o=this.setting(t);o.controlEl.parentElement?.addClass("qa-onepage-slider-setting");let s=t.sliderConfig??{min:0,max:100,step:1},a=t.optional&&i==="",l=Tp(i,s),c=o.controlEl.createDiv({cls:"qa-onepage-slider"}),d=c.createEl("input");d.type="range",d.min=String(s.min),d.max=String(s.max),d.step=String(s.step),d.value=l;let u=new li.TextComponent(c);u.inputEl.type="number",u.inputEl.inputMode="decimal",u.inputEl.min=String(s.min),u.inputEl.max=String(s.max),u.inputEl.step=String(s.step),u.setValue(a?"":l),n(t.id,a?"":l),d.addEventListener("input",()=>{u.inputEl.value=d.value,n(t.id,d.value)}),u.onChange(p=>{if(p===""&&t.optional){n(t.id,"");return}let m=Co(p,s);m!==""&&(d.value=m,u.inputEl.value=m,n(t.id,m))});break}case"dropdown":{let o=this.setting(t),s=new li.DropdownComponent(o.controlEl),a=t.options??[],l=t.displayOptions??a;if(a.length>0){t.optional&&s.addOption("","Skip (leave empty)"),a.forEach((d,u)=>{let p=l[u]??d;s.addOption(d,p)});let c=_H(i,a);s.setValue(c),n(t.id,c),s.onChange(d=>n(t.id,d))}else s.setDisabled(!0),o.controlEl.createDiv({text:t.placeholder||"No options available"}).addClass("qa-onepage-dropdown-note");break}case"date":{let o=this.setting(t);o.settingEl.addClass("qa-onepage-date-setting");let s=o.controlEl.createDiv({cls:"qa-date-input"}),a=s.createDiv({cls:"qa-date-field"}),l=new li.TextComponent(a),c="Enter a date (e.g., 'today', 'next friday', '2025-12-25')",d,u=i;i?.startsWith("@date:")&&(d=i.slice(6),u=(t.dateFormat?Mo(d,t.dateFormat):void 0)??(d.length>=10?d.slice(0,10):d)),l.setPlaceholder(c).setValue(u??"");let p=s.createDiv();p.addClass("qa-date-preview-text");let m=s.createDiv({cls:"qa-date-picker-container"}),h=CT({container:m,initialIso:d,withTime:t.withTime===!0,onSelect:_=>{_?C(_):w()}});e.dispose.push(()=>h.destroy()),e.dispose.push(xT(a,m));let g=Ph(U.getState().dateAliases);if(g.length>0){let _=s.createEl("details");_.addClass("qa-date-alias-details"),_.createEl("summary",{text:`Aliases (${g.length})`}).addClass("qa-date-alias-summary");let D=_.createDiv();D.textContent=ew(U.getState().dateAliases),D.addClass("qa-date-alias-list")}let v=_=>{if(t.dateFormat){let I=Mo(_,t.dateFormat);if(I)return I}return _.length>=10?_.slice(0,10):_},b=(_,I)=>{p.setText(_),p.toggleClass("is-error",I)},y=_=>{h.setSelectedIso(_)},C=_=>{e.dateParseError=!1;let I=v(_);l.inputEl.value=I,n(t.id,`@date:${_}`),b(I,!1),y(_)},w=()=>{l.inputEl.value="",P("")},T=_=>{let I=Rc(_,t.dateFormat),D=I.isValid?I.isoString:void 0;e.dateParseError=!D,n(t.id,D?`@date:${D}`:""),y(D),b(D?I.formatted??v(D):I.error||"Unable to parse date",!D)},P=_=>{let I=(_??"").trim();if(!I&&t.defaultValue&&!t.optional){T(t.defaultValue);return}if(!I){e.dateParseError=!1,n(t.id,""),y(),b(t.optional?"Will be left empty":"Preview will appear here",!1);return}if(I.startsWith("@date:")){let D=I.slice(6).trim();if(D){C(D);return}}T(I)};l.onChange(_=>P(_)),d?C(d):P(u??"");break}case"field-suggest":{let o=this.setting(t),s=new li.TextComponent(o.controlEl);s.setPlaceholder(t.placeholder??"").setValue(i).onChange(l=>n(t.id,l));let a=t.id.startsWith(Bl)?t.id.slice(Bl.length):t.id;try{e.suggesters.push(new XT(this.app,s.inputEl,a))}catch{}break}case"suggester":{let o=this.setting(t),s=t.options??[],a=t.displayOptions??s,l=new Map,c=new Map;s.forEach((p,m)=>{let h=a[m]??p;l.set(h,p),c.has(p)||c.set(p,h)});let d=c.get(i)??i,u=new li.TextComponent(o.controlEl);if(u.setPlaceholder(t.placeholder??"Type to search...").setValue(d).onChange(p=>n(t.id,p)),u.inputEl.addEventListener("input",p=>{let m=!!p.fromCompletion,h=u.inputEl.value,g=TH(h,l,m);(g!==h||m)&&n(t.id,g)}),a.length>0)try{let p=t.suggesterConfig?.caseSensitive??!1,m=t.suggesterConfig?.multiSelect??!1;e.suggesters.push(new ZT(this.app,u.inputEl,a,p,m,m?h=>{let g=e.multiSelections??[];g.push(h),e.multiSelections=g,this.host.publish(e)}:void 0))}catch{}break}case"file-picker":{this.renderFilePickerField(t,i,n);break}default:{let o=this.setting(t,!1),s=new li.TextComponent(o.controlEl);s.setPlaceholder(t.placeholder??"").setValue(i).onChange(a=>n(t.id,a)),this.host.attachFreeText(t,s.inputEl)}}this.labelControls(t),this.host.publish(e)}noteNameExists(t,e){let n=t==="vault"?this.app.vault.getMarkdownFiles().map(o=>o.path):e,i=new Set(n.map(o=>Ap(o).toLowerCase()));return o=>{let s;try{s=Br(o,"Capture target file path")}catch{return!1}let a=s.replace(/\.(md|canvas)$/i,"");return i.has(a.slice(a.lastIndexOf("/")+1).toLowerCase())?!0:t==="vault"&&[s,`${a}.md`,`${a}.canvas`].some(l=>!!this.app.vault.getAbstractFileByPath(l))}}renderFilePickerField(t,e,n){let i=this.setting(t);i.settingEl.addClass("qa-onepage-file-picker-setting");let o=t.options??[],s=t.displayOptions??o,a=o.map((w,T)=>{let P=Od(w);return{value:w,label:s[T]??w,path:P.kind==="file"?P.path:w,aliases:t.optionAliases?.[T]}}),l=new Map(a.map(w=>[w.value,w])),c=t.suggesterConfig?.multiSelect??!1,d=t.suggesterConfig?.allowCustomInput??!1,u=new Set,p=new Map,m=w=>{let T=p.get(w);if(T)return T;let P={value:w,label:w,path:t.newNoteName?"New note":"Custom value",isCustom:!0};return p.set(w,P),P};if(e&&l.has(e))u.add(e);else if(e&&d){let w=Od(e),T=w.kind==="custom"?w.text:e;m(T),u.add(T)}let h=i.controlEl.createDiv({cls:"qa-onepage-file-picker"}),g=h.createDiv({cls:"qa-onepage-file-picker__selection"});g.setAttribute("aria-live","polite");let v=new li.TextComponent(h);v.inputEl.addClass("qa-onepage-file-picker__input"),v.setPlaceholder(t.placeholder??(c?"Search and add files...":"Search files...")),v.inputEl.setAttribute("aria-label",c?`Add files for ${t.label}`:`Choose file for ${t.label}`);let b=()=>{let w=a.filter(T=>u.has(T.value));for(let T of p.values())u.has(T.value)&&w.push(T);return w},y=()=>{let w=b(),T=w.map(P=>P.value);this.host.controlFor(t).fileSelections=T,n(t.id,c?T.join(", "):T[0]??""),g.empty(),g.toggleClass("qa-hidden",w.length===0);for(let P of w){let _=g.createDiv({cls:"qa-onepage-file-picker__chip"});_.setAttribute("title",P.path),_.createSpan({cls:"qa-onepage-file-picker__chip-label",text:P.label});let I=_.createEl("button",{cls:"qa-onepage-file-picker__remove",text:"\xD7"});I.type="button",I.setAttribute("aria-label",`Remove ${P.label}`),I.addEventListener("click",()=>{u.delete(P.value),y(),v.inputEl.focus()})}},C=w=>{let T=w.isCustom?m(w.value):w;c||u.clear(),u.add(T.value),y()};v.inputEl.addEventListener("keydown",w=>{if(w.key==="Backspace"&&v.inputEl.value===""&&u.size>0){let T=b().at(-1);if(!T)return;w.preventDefault(),u.delete(T.value),y()}});try{let w=new JT(this.app,v.inputEl,()=>[...a,...p.values()],T=>u.has(T),C,c,d,t.newNoteName?this.noteNameExists(t.newNoteName,a.map(T=>T.path)):void 0);this.host.controlFor(t).suggesters.push(w)}catch{v.setDisabled(!0)}y()}}});function IH(r,t){r.empty(),r.toggleClass("qa-hidden",t.length===0);for(let e of t){let n=e.diagnostics.filter(l=>l.severity==="error"),o=n.some(l=>l.kind!=="path")?"Unresolved":n.length>0?"Won't be created":e.label,s=r.createDiv({cls:"qa-onepage-preview-row"});s.createDiv({text:`${o}:`,cls:"qa-preview-key"}),s.createDiv({text:e.text,cls:"qa-preview-val"}).setAttribute("title",e.text);for(let l of e.diagnostics){let c=r.createDiv({cls:"qa-preview-issue"});c.toggleClass("qa-preview-issue--error",l.severity==="error"),c.createSpan({cls:"qa-visually-hidden",text:l.severity==="error"?"Error: ":"Warning: "}),c.appendText(l.message),c.setAttribute("title",l.message)}}}var PH=x(()=>{});function t_(r,t={}){let{openedAtOf:e,recentRankOf:n,isExcluded:i}=t;return r.map(o=>({file:o,name:o.basename||o.path,excluded:i?.(o.path)??!1,openedAt:e?.(o.path),recentRank:n?.(o.path)})).sort((o,s)=>{if(o.excluded!==s.excluded)return o.excluded?1:-1;let a=o.openedAt!=null,l=s.openedAt!=null;if(a!==l)return a?-1:1;if(a&&l&&o.openedAt!==s.openedAt)return s.openedAt-o.openedAt;let c=o.recentRank??Number.POSITIVE_INFINITY,d=s.recentRank??Number.POSITIVE_INFINITY;return c!==d?c-d:o.name.localeCompare(s.name)}).map(o=>o.file)}var cM=x(()=>{});function r_(r){let t=r.workspace?.getLastOpenFiles?.(),e=Array.isArray(t)?t:[],n=new Map;e.forEach((s,a)=>{n.has(s)||n.set(s,a)});let i;try{i=Mm.getInstanceIfExists()}catch{i=void 0}let o=r.metadataCache;return{openedAtOf:s=>i?.getLastOpenedAt(s),recentRankOf:s=>n.get(s),isExcluded:s=>o?.isUserIgnored?.(s)??!1}}var dM=x(()=>{hP()});function tne(r){return`${uM}${r}`}function rne(r){return`${pM}${r}`}function nne(r){return r.startsWith(uM)}function ine(r){return r.startsWith(pM)}function one(r){return r.slice(uM.length)}function sne(r){return r.slice(pM.length)}function to(r){return r.trim().replace(/\.md$/i,"").toLowerCase()}function ane(r){return r.trim().replace(/^\/+/,"")}function lne(r){return r.trim().length>0&&!r.includes("{{")}function cne(r){return lne(r.templatePath)?new Set([En(r.templatePath).toLowerCase()]):new Set}function dne(r,t,e){let n=t.replace(/\.md$/i,"");r.add(to(t)),r.add(to(n)),r.add(to(e))}function une(r,t){let e=r.metadataCache.getFileCache(t)?.frontmatter;if(!e)return[];let n=[];for(let[i,o]of Object.entries(e)){let s=i.toLowerCase();s!=="alias"&&s!=="aliases"||(typeof o=="string"?n.push(...o.split(",").map(a=>a.trim()).filter(Boolean)):Array.isArray(o)&&n.push(...o.filter(a=>typeof a=="string").map(a=>a.trim()).filter(Boolean)))}return n}function pne(r){let n=((r.split("|")[0]?.trim()??"").split("#")[0]?.trim()??"").replace(/\.md$/i,"").trim();return!n||n==="/"||Ut(n)?null:n}function mne(r){let t=r.metadataCache.unresolvedLinks??{},e=new Map;for(let n of Object.values(t))for(let i of Object.keys(n)){let o=pne(i);if(!o)continue;let s=to(o);e.has(s)||e.set(s,o)}return[...e.values()].sort((n,i)=>n.localeCompare(i))}function n_(r,t){let e=new Set,n=cne(t),i=t_(r.vault.getMarkdownFiles(),r_(r)),o=[];for(let s of i){if(n.has(ane(s.path).toLowerCase()))continue;dne(e,s.path,s.basename);let a=une(r,s);for(let c of a)e.add(to(c));let l=[s.basename,s.path,...a].join(" ");o.push({item:tne(s.path),exactKeys:[s.basename,s.path,...a].map(to),display:l,title:a[0]?`${s.basename} (${s.path})`:s.path,renderPath:s.path,renderAlias:a[0]})}for(let s of mne(r)){let a=to(s);e.has(a)||o.push({item:rne(s),exactKeys:[to(s)],display:s,title:`${s} (unresolved link)`,unresolvedTitle:s})}return{candidates:o,existingKeys:e}}function zy(r){return nne(r)?{kind:"existing",path:one(r)}:oa(ine(r)?sne(r):r)}function oa(r){let t=Br(r,"Note title");return{kind:"create",title:t,...t.includes("/")?{vaultRelativePath:t}:{}}}function mM(r,t){let e=zy(t);return Hy(r,e),e}function Hy(r,t){if(t.kind==="existing"){let n=r.vault.getAbstractFileByPath(t.path);if(!(n instanceof $H.TFile))throw new Error("Selected note no longer exists. Please run QuickAdd again.");if(n.extension.toLowerCase()!=="md")throw new Error("Select a Markdown note to use with this Template choice.");return{kind:"existing",file:n}}let e=Br(t.title,"Note title");return{kind:"create",title:e,...e.includes("/")?{vaultRelativePath:e}:{}}}var $H,uM,pM,$f=x(()=>{$H=require("obsidian");cM();dM();es();Yi();Jt();uM="@quickadd-existing-note:",pM="@quickadd-unresolved-note:"});var o_,i_,FH=x(()=>{o_=require("obsidian");Za();$f();Ms();i_=class extends Er{constructor(e,n,i,o,s){let{candidates:a,existingKeys:l}=n_(e,i);super(e,n,s);this.obsidianApp=e;this.onSelect=o;this.existingKeys=l;let c=fc(i.existingNoteAction);this.options=a.map(d=>({item:d.item,exactKeys:d.exactKeys,label:d.renderPath?`${c==="Open"?"":`${c}: `}${d.renderPath.split("/").at(-1)?.replace(/\.md$/i,"")}`:d.unresolvedTitle??d.title,detail:d.renderPath??"Unresolved link",search:d.display}))}getSuggestions(e){let n=e.trim();if(!n)return this.options.slice(0,100);let i=to(n),o=(0,o_.prepareFuzzySearch)(n),s=this.options.map(a=>({option:a,match:o(a.search)})).filter(a=>a.match!==null).sort((a,l)=>Number(l.option.exactKeys.includes(i))-Number(a.option.exactKeys.includes(i))||(l.match?.score??0)-(a.match?.score??0)).slice(0,99).map(({option:a})=>a);return!this.existingKeys.has(i)&&!this.options.some(a=>a.exactKeys.includes(i))&&s.unshift({item:n,exactKeys:[i],label:`Create new note: ${n}`,detail:"",search:n}),s}resolveInput(e){let n=to(e),i=this.options.find(o=>o.exactKeys.includes(n));return i?mM(this.obsidianApp,i.item):oa(e)}renderSuggestion(e,n){n.addClass("qa-onepage-file-suggestion");let i=n.createDiv({cls:"qa-onepage-file-suggestion__text"});i.createDiv({cls:"qa-onepage-file-suggestion__label",text:e.label}),e.detail&&i.createDiv({cls:"qa-onepage-file-suggestion__path",text:e.detail})}selectSuggestion(e){try{let n=this.options.includes(e)?mM(this.obsidianApp,e.item):oa(e.item);this.inputEl.value="",this.close(),this.onSelect(n)}catch(n){new o_.Notice(n instanceof Error?n.message:"Could not select this note."),this.inputEl.focus()}}}});function s_(r=null){return{collect:{kind:"none"},opaque:null,deferred:r}}function fM(r){return{collect:{kind:"none"},opaque:r,deferred:r}}function RH(r,t=null){return s_(t)}function MH(r){if(!r)return s_("unresolvableChoice");switch(r.type){case"Template":case"Capture":return qn(r)||pl(r)?{collect:{kind:"scanChoice",choice:r},opaque:null,deferred:null}:s_("unresolvableChoice");case"Macro":return fM("nestedMacroGroup");case"Multi":return fM("interactivePicker");default:return RH(r.type,"unresolvableChoice")}}function Ff(r,t){switch(r.type){case"NestedChoice":return MH(r.choice??null);case"Choice":return MH(t(r.choiceId));case"UserScript":return{collect:{kind:"scriptInputs",command:r},opaque:"runsUserCode",deferred:null};case"AIAssistant":return{collect:{kind:"none"},opaque:"runsUserCode",deferred:null};case"Conditional":return fM("conditionalBranch");case"Obsidian":case"EditorCommand":case"Wait":case"OpenFile":return s_();default:return RH(r.type)}}var a_=x(()=>{ml();er()});function hM(r,t){return r.onePageInput==="never"&&qn(r)&&xc(r,r.fileNameFormat.enabled?r.fileNameFormat.format:xr,t)}function fne(r){return{id:r.id,label:r.name}}function hne(r){return{id:r.id,label:r.name}}function Wy(r,t,e){let n=[],i=[],o=!1,s=!1;for(let a of Mt(t.macro?.commands)){if(!Tr(a))continue;let l=Ff(a,r);if(s){i.push({label:a.name,reason:"afterOpaqueStep"});continue}if(l.collect.kind==="scanChoice"){let c=l.collect.choice;s=hM(c,e),c.onePageInput==="never"?i.push({label:c.name,reason:"choiceOptedOut"}):o?i.push({label:c.name,reason:"afterOpaqueStep"}):n.push({kind:"choice",occurrenceId:a.id,choice:c,group:fne(c)})}else l.collect.kind==="scriptInputs"?n.push({kind:"script",occurrenceId:a.id,command:l.collect.command,group:hne(l.collect.command)}):l.deferred&&i.push({label:a.name,reason:l.deferred});l.opaque&&(o=!0)}return{members:n,deferred:i}}var l_=x(()=>{Gr();Le();ou();ml();a_()});function c_(r,t){switch(t.kind){case"filter":return Yw(r,t.filter);case"property":return Kw(r,t.field,t.value,t.filter);case"tag":return lN(r,t.tag);case"folder":return ts(r,t.folderPathSlash)}}function d_(r,t){let e=t_(t,r_(r)),n=e.map(l=>l.path),i=Ds(e,l=>r.metadataCache.getFileCache(l)),o=i.map(l=>l.label),s=i.map(l=>l.aliases),a=n.map((l,c)=>`${i[c]?.primary??l} ${l}`);return{paths:n,labels:o,aliases:s,search:a}}var gM=x(()=>{bi();cM();dM();Ln()});function vne(r){return typeof r=="string"&&gne.includes(r)}function OH(r){if(!r||typeof r!="object")return null;let t=r,e=t.id,n=t.type;if(typeof e!="string"||!vne(n))return null;let i=yne(t.numericConfig),o=bne(t.sliderConfig),s=n==="slider"&&!o?"number":n;return{id:e,label:typeof t.label=="string"?t.label:e,type:s,placeholder:typeof t.placeholder=="string"?t.placeholder:void 0,defaultValue:typeof t.defaultValue=="string"?t.defaultValue:void 0,numericConfig:o??i,sliderConfig:o,options:Array.isArray(t.options)?t.options.filter(a=>typeof a=="string"):void 0,dateFormat:typeof t.dateFormat=="string"?t.dateFormat:void 0,description:typeof t.description=="string"?t.description:void 0,optional:typeof t.optional=="boolean"?t.optional:void 0,source:"script"}}function yne(r){if(!r||typeof r!="object")return;let t=r,e=typeof t.min=="number"&&Number.isFinite(t.min)?t.min:void 0,n=typeof t.max=="number"&&Number.isFinite(t.max)?t.max:void 0,i=typeof t.step=="number"&&Number.isFinite(t.step)&&t.step>0?t.step:void 0;if(e!==void 0&&n!==void 0&&n<e)return i===void 0?void 0:{step:i};let o={};return e!==void 0&&(o.min=e),n!==void 0&&(o.max=n),i!==void 0&&(o.step=i),Object.keys(o).length>0?o:void 0}function bne(r){if(!r||typeof r!="object")return;let t=r,e=typeof t.min=="number"?t.min:void 0,n=typeof t.max=="number"?t.max:void 0,i=t.step===void 0?1:typeof t.step=="number"?t.step:void 0;if(!(e===void 0||n===void 0||i===void 0||!Number.isFinite(e)||!Number.isFinite(n)||!Number.isFinite(i)||n<=e||i<=0))return{min:e,max:n,step:i}}function DH(r){if(!r||typeof r!="object"&&typeof r!="function")return[];let t=r.quickadd;if(!t||typeof t!="object")return[];let e=t.inputs;return Array.isArray(e)?e:[]}var gne,LH=x(()=>{gne=["text","number","textarea","dropdown","slider","date","field-suggest","file-picker","suggester"]});function u_(r){return`${r.replace(/^\/+/,"").replace(xt,"")}.md`}function p_(r,t,e){if(e)return null;let n=(t??"").trim().replace(/^\/+/,"");if(Aa(n))return null;let i=tm(n),o=!!i&&!!i.field,s=o?null:em(n),a=!!s&&!s.multiSelect,l=!o&&!s&&n.startsWith("#"),c=n.endsWith("/"),d=!l&&!o&&!a&&!c&&(xt.test(n)||lr.test(n)||Rn.test(n)),u=n.replace(/\/+$/,""),p=!l&&!o&&!a&&!d&&(n===""||r.isFolder(u)&&!r.markdownFileExists(u)),m=!o&&!a&&c;if(o&&i)return{kind:"property",field:i.field,value:i.value,filter:i.filter};if(a&&s)return{kind:"filter",filter:s.filter};if(l)return{kind:"tag",tag:n};if(p||m){let h=u;return{kind:"folder",folderPathSlash:h===""?"":`${h}/`}}return null}var vM=x(()=>{Le();Nh();xC();CC()});function yM(r){let t=/^\{\{VALUE:([^{}]+)\}\}$/i.exec(r);if(t){let i=Md(t[1]);return i&&!i.inputTypeOverride&&!i.hasOptions&&!i.caseStyle?i.variableKey:null}let e=/^\{\{(?:VALUE|NAME)(\|[^{}]+)?\}\}$/i.exec(r);if(!e)return null;let n=ng(e[1]??"");return!n.inputTypeOverride&&!n.caseStyle?"value":null}function m_(r,t){let e=t==="boolean"?"checkbox":t;return e!=="number"&&e!=="checkbox"||yM(r)===null?r:`${r.slice(0,-2)}|type:${e}}}`}var bM=x(()=>{xo()});function Cne(r){let t=r[0];for(let e of r.slice(1)){let n=`${t} / ${e}`;if(n.length>wne)return`${t}\u2026`;t=n}return t}var wne,Gy,NH=x(()=>{Tg();Wd();Dr();Le();Op();yp();Qd();xo();sg();Da();FF();Ln();bi();wne=30;Gy=class extends ec{constructor(e,n,i){super(e);this.app=e;this.plugin=n;this.choiceExecutor=i;this.requirements=new Map;this.templatesToScan=new Set;this.scannedTemplateRefDepths=new Map;this.scanningPathContext=!1;this.scanningScope="generic";this.valueTakesLines=!1;this.scanningSoleValue=!1;this.scanPositions=new Map;this.dateParser=So,i&&(this.variables=new Map(i.variables))}warn(){}reportProblem(){}async scanString(e,n=!1,i="generic"){let o=this.scanningPathContext,s=this.scanningScope,a=this.scanningSoleValue;this.scanningPathContext=n,this.scanningScope=i,this.scanningSoleValue=mw(i,e);let l=new Set(this.requirements.keys());this.scanPositions=new Map;try{let c=qi(await this.replaceGlobalVarInString(e));if(this.scanDateTokens(c),this.scanVariableTokens(c),this.scanFileTokens(c),n){if(new RegExp(fo.source,"i").test(c)){let d=this.requirements.get("value");d&&(d.pathContext=!0)}if(new RegExp(Mh.source,"i").test(c)){let d=this.requirements.get("mvalue");d&&(d.pathContext=!0)}}await this.format(c),this.orderNewFieldsByPosition(l,c)}finally{this.scanningPathContext=o,this.scanningScope=s,this.scanningSoleValue=a}}orderNewFieldsByPosition(e,n){this.notePosition("value",n.search(fo)),this.notePosition("mvalue",n.search(Mh));let i=new RegExp(dp.source,"gi");for(let a of n.matchAll(i))this.notePosition(`${Bl}${a[1]}${a[2]??""}`,a.index);let o=[...this.requirements].filter(([a])=>!e.has(a)),s=a=>this.scanPositions.get(a)??Number.MAX_SAFE_INTEGER;o.sort(([a],[l])=>s(a)-s(l));for(let[a]of o)this.requirements.delete(a);for(let[a,l]of o)this.requirements.set(a,l)}notePosition(e,n){if(n<0)return;let i=this.scanPositions.get(e);(i===void 0||n<i)&&this.scanPositions.set(e,n)}markScanContext(e){this.scanningPathContext&&(e.pathContext=!0)}async format(e){let n=e;n=await this.replaceGlobalVarInString(n),n=this.replaceDateInString(n),n=this.replaceTimeInString(n),n=await this.replaceValueInString(n),n=await this.replaceSelectedInString(n),n=await this.replaceClipboardInString(n),n=await this.replaceDateVariableInString(n),n=await this.replaceVariableInString(n),n=await this.replaceFieldVarInString(n),n=await this.replaceFileInString(n),n=await this.replaceMathValueInString(n),n=this.replaceRandomInString(n);{let i=new RegExp(As.source,"gi"),o;for(;(o=i.exec(n))!==null;){let s=o[1];s&&this.templatesToScan.add(cr(s))}}return n}async replaceGlobalVarInString(e){return rc(e,this.plugin?.settings?.globalVariables)}scanVariableTokens(e){let n=new RegExp(Td.source,"gi"),i;for(;(i=n.exec(e))!==null;){let o=(i[1]??"").trim();if(!o)continue;let s=Md(o,{warn:this.warnSink});if(!s)continue;let{variableName:a,variableKey:l,label:c,defaultValue:d,displayValues:u,hasOptions:p}=s;if(!a)continue;let m=c??(p?s.aliasName??Cne(u??s.suggestedValues):a),h=l,g=this.findRequirementIgnoringCase(h,"date");if(this.notePosition(g?.id??h,i.index),g){this.markScanContext(g);continue}if(this.requirements.has(h)){let v=this.requirements.get(h);if(this.markScanContext(v),p&&!this.hasOptionList(v)&&(v.type=this.optionFieldType(s),v.label=m,this.applyOptionFields(v,s),v.defaultValue!==void 0&&!s.allowCustomInput)){let b=rg(v.defaultValue);v.defaultValue=s.suggestedValues.includes(b)?b:void 0}d&&v.defaultValue===void 0&&(v.defaultValue=d),!v.displayOptions&&u&&(v.displayOptions=u),v.optional=(v.optional??!1)&&s.optional}else{let v=this.inputFieldType(s),b={id:h,label:m,type:p?this.optionFieldType(s):v,optional:s.optional};p?this.applyOptionFields(b,s):v==="dropdown"?b.options=["true","false"]:v==="number"?b.numericConfig=s.numericConfig:v==="slider"&&(b.numericConfig=s.numericConfig,b.sliderConfig=s.sliderConfig),d&&(b.defaultValue=d),this.markScanContext(b),this.requirements.set(h,b)}}}findRequirementIgnoringCase(e,n){let i=this.requirements.get(e);if(i)return i.type===n?i:void 0;let o=e.toLowerCase(),s=[...this.requirements.values()].filter(a=>a.id.toLowerCase()===o);return s.length===1&&s[0].type===n?s[0]:void 0}inputFieldType(e){switch(e?.inputTypeOverride){case"checkbox":return"dropdown";case"number":return"number";case"slider":return"slider";case"multiline":return"textarea";default:return this.plugin.settings.inputPrompt==="multi-line"?"textarea":"text"}}optionFieldType(e){return e.allowCustomInput||e.multiSelect?"suggester":"dropdown"}hasOptionList(e){return Array.isArray(e.options)&&e.options.length>0}applyOptionFields(e,n){e.options=n.suggestedValues,n.displayValues&&(e.displayOptions=n.displayValues),n.multiSelect?e.multiEmit=n.multiEmit??"text":delete e.multiEmit,n.allowCustomInput||n.multiSelect?e.suggesterConfig={allowCustomInput:n.allowCustomInput,caseSensitive:!1,multiSelect:n.multiSelect??!1}:delete e.suggesterConfig}scanDateTokens(e){let n=new RegExp(Ss.source,"gi"),i;for(;(i=n.exec(e))!==null;){let o=i[1]?.trim();if(!o)continue;this.notePosition(o,i.index);let{defaultValue:s,optional:a,withTime:l,label:c}=og(i[3]),d=i[2]?.trim()||(l?"YYYY-MM-DD HH:mm":"YYYY-MM-DD"),u=this.requirements.get(o);u?((u.type==="text"||u.type==="textarea")&&!this.hasOptionList(u)&&(u.type="date",u.dateFormat=d,u.withTime=l,c&&(u.label=c)),u.type==="date"&&s&&u.defaultValue===void 0&&(u.defaultValue=s),u.optional=(u.optional??!1)&&a,u.type==="date"&&l&&!u.withTime&&(u.withTime=!0,i[2]?.trim()||(u.dateFormat="YYYY-MM-DD HH:mm"))):this.requirements.set(o,{id:o,label:c??o,type:"date",defaultValue:s,dateFormat:d,withTime:l,optional:a,source:"collected"})}}async promptForValue(e){let n="value";if(!this.requirements.has(n)){let i=this.valueTakesLines&&!this.valuePromptContext?.inputTypeOverride?"textarea":this.inputFieldType(this.valuePromptContext),o=gw(this.scanningScope,this.scanningSoleValue);this.requirements.set(n,{id:n,label:this.valuePromptContext?.label||o.title||e||"Enter value",type:i,placeholder:o.placeholder,defaultValue:this.valuePromptContext?.defaultValue,numericConfig:this.valuePromptContext?.numericConfig,sliderConfig:this.valuePromptContext?.sliderConfig,options:i==="dropdown"?["true","false"]:void 0,source:"collected",optional:this.valuePromptContext?.optional})}return this.markScanContext(this.requirements.get(n)),""}async promptForVariable(e,n){if(!e)return"";let i=n?.variableKey??e;if(n?.type==="VDATE")return n.defaultValue??"@date:1970-01-01T00:00:00.000Z";if(!this.requirements.has(i)){let o=Fd(e).map(c=>c.trim()).filter(Boolean),s=o.length>1,a=s?"dropdown":this.inputFieldType(n),l={id:i,label:n?.label??e,type:a,numericConfig:n?.numericConfig,sliderConfig:n?.sliderConfig,source:"collected"};s?l.options=o:a==="dropdown"&&(l.options=["true","false"]),n?.defaultValue&&(l.defaultValue=n.defaultValue),this.requirements.set(i,l)}return this.markScanContext(this.requirements.get(i)),n?.defaultValue??""}async promptForMathValue(){let e="mvalue";return this.requirements.has(e)||this.requirements.set(e,{id:e,label:"Math expression",type:"text",placeholder:"e.g., 2+2*3"}),this.markScanContext(this.requirements.get(e)),""}async suggestForField(e){let n=Dn.parse(e),i=`${Bl}${e}`;if(!this.requirements.has(i)){let o={id:i,label:n.label??(n.fieldName||e),type:"field-suggest",source:"collected",runtimeOnly:n.multiSelect};if(!n.multiSelect&&n.filters.defaultFrom==="active"){let s=ST(this.app,this.choiceExecutor?.triggerContext?.activeFile??null,n.fieldName),a=(typeof s=="string"?s:void 0)??n.filters.defaultValue;a!==void 0&&(o.defaultValue=a)}this.requirements.set(i,o)}return""}scanFileTokens(e){let n=new RegExp(rw.source,"gi"),i;for(;(i=n.exec(e))!==null;){let o=Rw(i[1]??"");o&&(this.notePosition(o.variableKey,i.index),this.recordFileRequirement(o))}}recordFileRequirement(e){let n=e.variableKey,i=this.requirements.get(n);if(i){i.optional=(i.optional??!1)&&e.optional,i.type="file-picker",i.suggesterConfig={allowCustomInput:(i.suggesterConfig?.allowCustomInput??!1)||e.allowCustomInput,caseSensitive:!1,multiSelect:(i.suggesterConfig?.multiSelect??!1)||e.multiSelect};return}let o=Vp(this.app,e),s=o.map(p=>`${Jl}${p.path}`),a=Ds(o,p=>this.app.metadataCache.getFileCache(p)),l=a.map(p=>p.label),c=e.allowCustomInput||s.length===0,d=[...e.types];e.mode!=="name"&&d.push(e.mode);let u=d.length?`File from ${e.folderPath} (${d.join(", ")})`:`File from ${e.folderPath}`;this.requirements.set(n,{id:n,label:e.label??u,type:"file-picker",source:"collected",options:s,displayOptions:l,optionAliases:a.map(p=>p.aliases),optional:e.optional,suggesterConfig:{allowCustomInput:c,caseSensitive:!1,multiSelect:e.multiSelect}})}suggestForFile(e){return""}async suggestForValue(e,n,i){return""}getVariableValue(e){return""}async getTemplateContent(e){return""}async getSelectedText(){return""}async getClipboardContent(){return""}getCurrentFileLink(){return null}getCurrentFileName(){return null}async getMacroValue(e,n){return""}isTemplatePropertyTypesEnabled(){return!1}}});function CM(r){return`${wM}${r}`}function Mf(r){return r.startsWith(wM)&&r.length>wM.length}function xM(r){return r===Dh||Mf(r)}function VH(r,t){let e=Yl(r,t);return e?r.get(e)==null?null:e:null}function xne(r){let t=0;for(let e of r.keys())Mf(e)&&t++;return t}function BH(r,t){if(!r)return;let e=r.get(CM(t));if(typeof e=="string"&&e.length>0)return e;if(xne(r)>1)return;let n=r.get(Dh);if(typeof n=="string"&&n.length>0)return n}function UH(r,t){return xM(t)?VH(r,t):null}function qH(r,t,e){return e!==1||!Mf(t)?!1:VH(r,Dh)!==null}var wM,EM=x(()=>{Le();xo();wM=`${Dh}.`});async function HH(r,t){let e=nn(r,t);return e?await r.vault.cachedRead(e):""}async function bl(r,t,e,n="generic",i=new Set,o=0){let s=fw(n),a=Xs(e);t.templatesToScan.clear(),await t.scanString(e,s,n);let l=[...t.templatesToScan].filter(c=>a.has(c));if(t.templatesToScan.clear(),!(o>=Gw))for(let c of l){if(i.has(c))continue;let d=`${s?"path":"content"}:${c}`,u=t.scannedTemplateRefDepths.get(d);if(!(u!==void 0&&u<=o)){t.scannedTemplateRefDepths.set(d,o),i.add(c);try{await bl(r,t,await HH(r,c),n,i,o+1)}finally{i.delete(c)}}}}async function Ene(r,t,e){await t.scanString(e,!0,"templatePath"),await WH(r,t,e)}async function WH(r,t,e){if(Aa(e)){S.logMessage(`Preflight: template path "${e}" uses format syntax; its body's prompts are collected at run time, not in the one-page form.`);return}await bl(r,t,await HH(r,e),"noteBody",new Set([e]))}async function GH(r,t,e,n){let i=new Gy(r,t,e);if(n.templatePath&&await i.scanString(n.templatePath,!0,"templatePath"),n.folder?.enabled)for(let s of n.folder.folders??[])await bl(r,i,s,"folder");n.fileNameFormat?.enabled&&await bl(r,i,n.fileNameFormat.format,"noteTitle"),n.templatePath&&await WH(r,i,n.templatePath);let o=n.fileNameFormat?.enabled?n.fileNameFormat.format:xr;if(OI(n,o)){let s=i.requirements.get("value");s&&(s.runtimeOnly=!0)}return i}async function jH(r,t,e,n,i){let o=new Gy(r,t,e);await bl(r,o,n.captureTo,"captureTarget"),n.propertyCapture?.property.kind==="named"&&await bl(r,o,n.propertyCapture.property.format,"propertyName");let s=n.format?.enabled?n.format.format:xr,a=n.propertyCapture?.property.kind==="named"?n.propertyCapture.property.format.trim():null,l=a&&!Aa(a)?Rs(r,a,{registeredOnly:!0}):null;if((n.format?.enabled||n.propertyCapture)&&(o.valueTakesLines=!!n.eachLine&&!n.propertyCapture,await bl(r,o,n.propertyCapture?m_(s,l):s,n.propertyCapture?"propertyValue":"captureText"),o.valueTakesLines=!1),n.propertyCapture&&l===null){let u=yM(s),p=u===null?void 0:o.requirements.get(u);p&&(p.runtimeOnly=!0)}!n.propertyCapture&&n.insertAfter?.enabled&&!n.insertAfter.promptHeading&&await bl(r,o,n.insertAfter.after,"lineTarget"),!n.propertyCapture&&n.insertBefore?.enabled&&await bl(r,o,n.insertBefore.before,"lineTarget");let c=n.createFileIfItDoesntExist;c?.enabled&&c.createWithTemplate&&c.template&&await Ene(r,o,c.template);let d=p_({isFolder:u=>Eg(r,u),markdownFileExists:u=>r.vault.getAbstractFileByPath(u_(u))instanceof zH.TFile},n.captureTo??"",n.captureToActiveFile);if(d){let{paths:u,labels:p,aliases:m}=d_(r,c_(r,d)),h=n.createFileIfItDoesntExist?.enabled??!1,g=CM(n.id);u.length===0&&h?o.requirements.set(g,{id:g,label:"Select capture target file",type:"file-picker",source:"collected",options:u,displayOptions:p,runtimeOnly:!0,placeholder:"Type a new note name in the capture target picker"}):u.length===0?o.requirements.set(g,{id:g,label:"Select capture target file",type:"dropdown",options:u,displayOptions:p,placeholder:"No files found in target scope"}):o.requirements.set(g,{id:g,label:"Select capture target file",type:"file-picker",options:u,displayOptions:p,optionAliases:m,...h?{suggesterConfig:{allowCustomInput:!0},newNoteName:d.kind==="folder"?"scope":"vault"}:{}});for(let[v,b]of[...o.requirements])v!==g&&(o.requirements.delete(v),o.requirements.set(v,b))}if(i){let u=n.useSelectionAsCaptureValue,p=t.settings.useSelectionAsCaptureValue??!0;if(typeof u=="boolean"?u:p){let h=e.variables.get("value");if(h==null){let g=Cf(r,e);g.trim().length>0&&e.variables.set("value",g)}}}return o}async function Tne(r,t,e){let n=[];try{let i=mx(t),o=i!==void 0?e?.get(i):void 0;o===void 0&&(o=await su(t,r,{reportLoadErrors:!1}),i!==void 0&&o!==void 0&&e?.set(i,o));let s=DH(o?.script);for(let a of s){let l=OH(a);l&&n.push(l)}}catch(i){let o=t.path??t.id,s=i instanceof Error?i.message:String(i);if(px(i))return S.logMessage(`QuickAdd preflight could not inspect user script '${o}': ${s}`),n;S.logWarning(`Preflight could not inspect user script '${o}': ${s}`)}return n}async function _ne(r,t,e,n,i){let o=Wy(l=>zc(t,l),n,e.variables.get("value")),s=new Map,a=i?.seedCaptureSelectionAsValue??!1;for(let l of o.members){let c=l.kind==="script"?await Tne(r,l.command,i?.preloadedUserScripts):qn(l.choice)?Array.from((await GH(r,t,e,l.choice)).requirements.values()):Array.from((await jH(r,t,e,l.choice,a)).requirements.values());for(let d of c){let u=s.get(d.id);if(u){u.optional=(u.optional??!1)&&(d.optional??!1),d.pathContext&&(u.pathContext=!0),d.runtimeOnly&&(u.runtimeOnly=!0),u.type==="text"&&d.type==="textarea"&&(u.type="textarea");continue}s.set(d.id,{...d,group:l.group})}}return kne(e.variables,s),Array.from(s.values())}function kne(r,t){let e=[];for(let n of t.values())Mf(n.id)&&e.push(n.id);if(!(e.length<2))for(let n of e)r.has(n)||r.set(n,null)}function Sne(r,t){let e=t.pickDate?Jp(Qa(r.dateOrigin)):Qa(r.dateOrigin);if(!(e?.kind!=="ask"||t.clocks?.date))return{id:Sa,label:`Date for ${r.name}`,type:"date",dateFormat:"YYYY-MM-DD",defaultValue:e.defaultValue,source:"collected"}}function Ane(r,t,e){let n=Sne(r,t);return n?[n,...e.filter(i=>i.id!==Sa)]:e}async function sa(r,t,e,n,i){let o;if(Xi(n))o=await _ne(r,t,e,n,i);else if(qn(n))o=[...(await GH(r,t,e,n)).requirements.values()];else if(n.type==="Capture")o=[...(await jH(r,t,e,n,i?.seedCaptureSelectionAsValue??!1)).requirements.values()];else return[];return Ane(n,e,o)}function YH(r,t,e){return Wy(n=>zc(r,n),t,e).deferred}function wl(r,t){let e=r.filter(n=>Mf(n.id)).length;return r.filter(n=>{if(xM(n.id))return UH(t,n.id)!==null?!1:!qH(t,n.id,e);let i=Yl(t,n.id);return i?t.get(i)==null:!0})}var zH,jy=x(()=>{gM();LH();HT();zH=require("obsidian");vl();Op();Le();Xp();uc();ml();ou();Ac();Jt();bi();ye();au();Nh();vM();xo();bM();bp();NH();yp();EM();l_()});function KH(){return{pending:new Map,active:null,discoveryMacros:new Set}}function QH(r,t){r.preparedInputs.discoveryMacros.add(t)}function XH(r,t){return r.preparedInputs.discoveryMacros.has(t)}function JH(r,t,e){r.preparedInputs.pending.set(t,e)}function ZH(r,t){return r.preparedInputs.active?.choiceId===t}function eW(r,t){let e=r.preparedInputs.active;return e?.choiceId===t?e.discovery:null}function tW(r){r.preparedInputs.pending.clear(),r.preparedInputs.discoveryMacros.clear(),r.preparedInputs.active=null}async function Yy(r,t,e){let n=r.preparedInputs,i=n.pending.get(t);if(!i)return e();n.pending.delete(t);let o=n.active;n.active=i;let s=r.variables.has("value"),a=r.variables.get("value"),l=!1;for(let[c,d]of i.values)r.variables.get(c)==null&&(r.variables.set(c,d),c==="value"&&(l=!0));try{return await e()}finally{l&&r.variables.get("value")===i.values.get("value")&&(s?r.variables.set("value",a):r.variables.delete("value")),n.active=o}}var Rf=x(()=>{});function rW(r,t){let e=r.flatMap(n=>{if(n.kind==="always")return[n.metadata];let i=t.get(n.noteId);return i?.kind==="create"?[n.create]:i?.kind==="existing"&&n.existing?[n.existing]:[]});return e.length===0?null:{...e[0],optional:e.length>0&&e.every(n=>n.optional),pathContext:e.some(n=>n.pathContext),runtimeOnly:e.some(n=>n.runtimeOnly)}}function f_(r){return{...r}}function _M(r,t){let e=t.get(r.noteId);return e?.kind==="create"||r.includeExisting&&e?.kind==="existing"}function TM(r,t){return qn(r)&&xc(r,r.fileNameFormat.enabled?r.fileNameFormat.format:xr,t.variables.get("value"))}async function nW(r,t,e,n){let i=d=>zc(t,d),o;if(Xi(n)){for(let d of Mt(n.macro?.commands)){if(!Tr(d))continue;let u=Ff(d,i);u.collect.kind==="scanChoice"&&TM(u.collect.choice,e)&&QH(e,n.id)}if(!XH(e,n.id))return null;o=Wy(i,n,e.variables.get("value")).members}else if(TM(n,e))o=[{kind:"choice",choice:n,occurrenceId:n.id,group:{id:n.id,label:n.name}}];else return null;let s=new Map,a=new Map,l={notes:[],visibleForNotes:new Map,fieldUsages:new Map},c=[];if(Xi(n)){let d={...n,macro:{...n.macro,commands:[]}},u=wl(await sa(r,t,e,d),e.variables);if(u.length>0){let p=new Map;for(let m of u)s.set(m.id,m),p.set(m.id,{variable:m.id,condition:null}),a.set(m.id,[null]),l.fieldUsages.set(m.id,[{kind:"always",metadata:f_(m)}]);c.push({occurrenceId:n.id,choiceId:n.id,noteId:null,bindings:p})}}for(let d of o){let u={...d.group,id:d.occurrenceId},p=d.kind==="choice"?d.choice:null,m=p!==null&&TM(p,e)?p:null,h=m?`__qa.note.${d.occurrenceId}`:null,g={occurrenceId:d.occurrenceId,choiceId:p?.id??d.occurrenceId,noteId:h,bindings:new Map};c.push(g),m&&h&&(l.notes.push({id:h,choice:m,group:u}),s.set(h,{id:h,label:"Note",type:"text",pathContext:!0,group:u}));let v=p??(Xi(n)&&d.kind==="script"?{...n,macro:{...n.macro,commands:[d.command]}}:null);if(!v)continue;let b=wl(await sa(r,t,e,v,{preloadedUserScripts:e.preloadedUserScripts}),e.variables),y=new Map;if(m&&AC(m.existingNoteAction)!=="open"){let w={...m,fileNameFormat:{enabled:!1,format:""},folder:{...m.folder,enabled:!1}};for(let T of await sa(r,t,e,w))y.set(T.id,T)}let C=p&&pl(p)&&(p.useSelectionAsCaptureValue??t.settings.useSelectionAsCaptureValue??!0)?Cf(r,e):"";for(let w of b){if(m&&w.id==="value")continue;let T=w.id==="value"?`__qa.value.${d.occurrenceId}`:w.id,P=h?{noteId:h,includeExisting:y.has(w.id)}:null;g.bindings.set(T,{variable:w.id,condition:P});let _=l.fieldUsages.get(T)??[],I=y.get(w.id),D={...w,id:T,group:u,...w.id==="value"&&C.trim()?{defaultValue:C}:{}};_.push(h?{kind:"note",noteId:h,create:f_(D),existing:I?f_(I):null}:{kind:"always",metadata:f_(D)}),l.fieldUsages.set(T,_);let N=s.get(T);N?(N.optional=!!(N.optional&&w.optional),w.pathContext&&(N.pathContext=!0),w.runtimeOnly&&(N.runtimeOnly=!0)):s.set(T,D);let K=a.get(T)??[];K.push(P),a.set(T,K)}}for(let[d,u]of a)u.includes(null)||l.visibleForNotes.set(d,u.filter(p=>p!==null));return{requirements:[...s.values()],config:l,steps:c}}function iW(r,t,e,n){for(let i of t.steps){let o=i.noteId?n.get(i.noteId)??null:null,s=new Map;for(let[a,{variable:l,condition:c}]of i.bindings)(!c||_M(c,n))&&e.has(a)&&s.set(l,e.get(a));JH(r,i.occurrenceId,{choiceId:i.choiceId,values:s,discovery:o})}}var kM=x(()=>{HT();ml();Le();ou();Za();Gr();vl();a_();l_();jy();Rf()});function Ine(r){let t=[];for(let e of r){let n=t.at(-1);n&&n.group?.id===e.group?.id?n.fields.push(e):t.push({group:e.group,fields:[e]})}return t}function Pne(r){let t=new Set;for(let e of r)e.group&&t.add(e.group.id);return t.size>=2}function h_(r){return JSON.stringify(Object.entries(r).filter(([t,e])=>e!==void 0&&!["id","group","optional","pathContext","runtimeOnly"].includes(t)).sort(([t],[e])=>t.localeCompare(e)))}var Sr,Of,SM=x(()=>{AH();Sr=require("obsidian");_P();kP();Hv();gP();vP();Rx();rr();PH();FH();$f();kM();Za();Of=class extends Sr.Modal{constructor(e,n,i,o,s){super(e);this.discoveryForm=s;this.result=new Map;this.multiSelections=new Map;this.fileSelections=new Map;this.discoverySelections=new Map;this.discoverySuggesters=[];this.fieldElements=new Map;this.fieldAnchors=new Map;this.fieldControls=new Map;this.discoveryInputs=new Map;this.dateParseErrors=new Set;this.previewContainerEl=null;this.previewToken=0;this.settled=!1;this.imagePasteHandles=new Map;this.imagePasteInputs=new Map;this.freeTextFields=[];this.requirements=n.map(a=>({...a})),this.updateFieldMetadata(),this.initialValues=new Map,this.computePreview=o,i?.forEach((a,l)=>{typeof a=="string"&&this.initialValues.set(l,a)}),this.updatePreviewDebounced=(0,Sr.debounce)(this.updatePreviews.bind(this),150,!0),this.peek=new Lm({app:e,title:"Provide inputs",containerEl:this.containerEl,scope:this.scope,getField:()=>this.insertTarget()?.el,getValue:()=>this.insertTarget()?.el.value??"",setValue:a=>{let l=this.insertTarget();l&&(this.result.set(l.id,a),this.updatePreviewDebounced())},persistDraft:()=>{},markDraftChanged:()=>{let a=this.insertTarget();a&&(this.result.set(a.id,a.el.value),this.updatePreviewDebounced())},close:()=>this.close()}),this.waitForClose=new Promise((a,l)=>{this.resolvePromise=a,this.rejectPromise=l}),this.display(),this.open()}display(){if(this.containerEl.addClass("quickAddModal","onePageInputModal"),Dx(this.containerEl),this.discoveryForm&&this.containerEl.addClass("qa-discovery-form"),this.contentEl.empty(),this.contentEl.createEl("h2",{text:"Provide inputs"}).addClass("qa-onepage-title"),this.computePreview&&(this.previewContainerEl=this.contentEl.createDiv(),this.previewContainerEl.addClass("qa-onepage-preview","qa-hidden")),Pne(this.requirements))for(let s of Ine(this.requirements)){s.group&&!(this.discoveryForm&&s.fields.length===1&&s.fields[0].label===s.group.label)&&this.contentEl.createEl("h3",{text:s.group.label,cls:"qa-onepage-section"});for(let a of s.fields)this.renderField(a)}else this.requirements.forEach(s=>this.renderField(s));this.updateFieldVisibility(!1),this.computePreview&&this.updatePreviews(),this.modalEl.addClass("qa-has-modal-footer");let n=this.modalEl.createDiv({cls:"qa-prompt-actions qa-modal-footer"}),i=n.createDiv({cls:"qa-prompt-actions-primary"});new Sr.ButtonComponent(i).setButtonText("Submit").setCta().onClick(()=>this.submit()),new Sr.ButtonComponent(i).setButtonText("Cancel").onClick(()=>this.cancel());let o=n.createDiv({cls:"qa-prompt-actions-secondary"});Lx(new Sr.ButtonComponent(o).setButtonText("Peek at note").onClick(()=>this.peek.peek()))}open(){if(super.open(),!this.modalEl.ownerDocument.activeElement?.matches(".qa-onepage-file-picker__remove"))return;let e=Array.from(this.contentEl.querySelectorAll("input, textarea, select")).filter(i=>!i.closest("[hidden]")&&!i.matches(":disabled"));(e.find(i=>!i.closest(".qa-onepage-file-picker")?.querySelector(".qa-onepage-file-picker__chip"))??e[0])?.focus()}onOpen(){this.peek.onHostOpened();let e=this.scope;typeof e?.register=="function"&&(e.register(["Mod"],"Enter",()=>(this.submit(),!1)),e.register(["Mod","Shift"],zv,()=>(this.peek.peek(),!1)))}renderField(e){let n=new Set(this.contentEl.children),i=this.discoveryForm?.notes.find(s=>s.id===e.id);i?this.renderNoteField(i):this.renderFieldControl(e);let o=Array.from(this.contentEl.children).filter(s=>s.instanceOf(HTMLElement)&&!n.has(s));if(this.fieldElements.set(e.id,o),!i){this.controlFor(e).elements=o;let s=this.fieldAnchors.get(e.id);s||(s=this.contentEl.ownerDocument.createComment(e.id),this.contentEl.append(s),this.fieldAnchors.set(e.id,s));for(let a of o)this.contentEl.insertBefore(a,s)}}controlFor(e){let n=this.fieldControls.get(e);return n||(n={requirement:e,elements:[],value:"",dateParseError:!1,suggesters:[],dispose:[]},this.fieldControls.set(e,n)),n}publishControl(e){let n=e.requirement;this.settled||!this.requirements.includes(n)||(this.result.set(n.id,e.value),e.multiSelections?this.multiSelections.set(n.id,e.multiSelections):this.multiSelections.delete(n.id),e.fileSelections?this.fileSelections.set(n.id,e.fileSelections):this.fileSelections.delete(n.id),e.dateParseError?this.dateParseErrors.add(n.id):this.dateParseErrors.delete(n.id))}get activeRequirements(){return this.requirements.filter(e=>this.isFieldVisible(e.id))}isFieldVisible(e){if(this.requirements.find(i=>i.id===e)?.runtimeOnly)return!1;let n=this.discoveryForm?.visibleForNotes.get(e);return!n||n.some(i=>_M(i,this.discoverySelections))}updateFieldVisibility(e=!0){this.updateFieldMetadata();for(let[n,i]of this.fieldElements)for(let o of i)o.hidden=!this.isFieldVisible(n);for(let n of this.fieldControls.values())if(!(this.requirements.includes(n.requirement)&&this.isFieldVisible(n.requirement.id)))for(let i of n.suggesters)i.close();for(let[n,i]of this.imagePasteInputs)this.syncImagePaste(n,i);e&&this.updatePreviewDebounced()}updateFieldMetadata(){for(let e=0;e<this.requirements.length;e++){let n=this.requirements[e],i=this.discoveryForm?.fieldUsages.get(n.id);if(!i)continue;let o=rW(i,this.discoverySelections);if(!o)continue;let s={...o,id:n.id,group:n.group};if(!this.fieldElements.has(n.id)){this.requirements[e]=s;continue}if(h_(n)!==h_(s)){let a=this.controlFor(n);a.value=this.result.get(n.id)??a.value;for(let c of a.suggesters)c.close();for(let c of a.elements)c.hidden=!0,c.remove();let l=Array.from(this.fieldControls.values()).find(c=>c.requirement.id===n.id&&h_(c.requirement)===h_(s));if(n=l?.requirement??s,this.requirements[e]=n,l){for(let c of l.elements)this.contentEl.insertBefore(c,this.fieldAnchors.get(n.id)??null);this.fieldElements.set(n.id,l.elements),this.publishControl(l)}else this.renderField(n)}Object.assign(n,{optional:s.optional,pathContext:s.pathContext,runtimeOnly:s.runtimeOnly});for(let a of this.fieldElements.get(n.id)??[]){if(a.querySelector(".setting-item-name")?.replaceChildren(this.decorateLabel(n)),n.type!=="dropdown")continue;let l=a.querySelector("select");if(!l||n.options?.includes(""))continue;let c=Array.from(l.options).find(d=>d.value==="");if(n.optional&&!c)l.createEl("option",{value:"",text:"Skip (leave empty)",prepend:!0});else if(!n.optional&&c){c.remove();let d=this.controlFor(n);d.value=l.value,this.publishControl(d)}}}}renderNoteField(e){let n=new Sr.Setting(this.contentEl).setName("Note");n.settingEl.addClass("qa-onepage-file-picker-setting");let i=n.controlEl.createDiv({cls:"qa-onepage-file-picker"}),o=i.createDiv({cls:"qa-onepage-file-picker__selection"});o.setAttribute("aria-live","polite");let s=new Sr.TextComponent(i).setPlaceholder("Search notes or create new note");s.inputEl.addClass("qa-onepage-file-picker__input"),s.inputEl.setAttribute("aria-label",`Note for ${e.choice.name}`);let a,l=c=>{a?.close(),this.discoverySelections.set(e.id,c),o.empty();let d=fc(e.choice.existingNoteAction),u=c.kind==="existing"?`${d==="Open"?"":`${d}: `}${c.path.replace(/\.md$/i,"")}`:`Create: ${c.title}`,p=o.createDiv({cls:"qa-onepage-file-picker__chip"});p.createSpan({cls:"qa-onepage-file-picker__chip-label",text:u});let m=p.createEl("button",{cls:"qa-onepage-file-picker__remove",text:"\xD7"});m.type="button",m.setAttribute("aria-label","Change note"),m.addEventListener("click",()=>{this.discoverySelections.delete(e.id),o.empty(),s.inputEl.hidden=!1,this.updateFieldVisibility(),s.inputEl.focus()}),s.inputEl.hidden=!0,this.updateFieldVisibility(),m.focus()};try{a=new i_(this.app,s.inputEl,e.choice,l,this.scope),this.discoverySuggesters.push(a)}catch{new Sr.Notice("Note search is unavailable. Type a new note title.")}this.discoveryInputs.set(e.id,{input:s.inputEl,select:l,resolve:()=>a?a.resolveInput(s.inputEl.value):oa(s.inputEl.value)})}renderFieldControl(e){new e_(this.app,this.contentEl,{controlFor:n=>this.controlFor(n),initialValue:n=>this.initialValues.get(n),publish:n=>this.publishControl(n),updatePreview:()=>this.updatePreviewDebounced(),decorateLabel:n=>this.decorateLabel(n),attachFreeText:(n,i)=>{this.enableImagePaste(n,i),this.attachFreeTextBehaviors(n,i)}}).render(e)}attachFreeTextBehaviors(e,n){let o={id:e.id,el:n,fileSuggester:new Rm(this.app,n),tagSuggester:new Om(this.app,n,{refreshIndex:this.freeTextFields.length===0})};this.freeTextFields.push(o),this.controlFor(e).suggesters.push(o.fileSuggester,o.tagSuggester),n.addEventListener("focus",()=>{this.lastFocusedFreeText=o})}insertTarget(){return this.lastFocusedFreeText&&this.contentEl.contains(this.lastFocusedFreeText.el)&&this.isFieldVisible(this.lastFocusedFreeText.id)?this.lastFocusedFreeText:this.freeTextFields.find(e=>this.contentEl.contains(e.el)&&this.isFieldVisible(e.id))}enableImagePaste(e,n){this.imagePasteInputs.set(e,n),this.syncImagePaste(e,n)}syncImagePaste(e,n){let i=this.imagePasteHandles.get(e);if(this.settled||e.pathContext||!this.requirements.includes(e)||!this.isFieldVisible(e.id)){if(!this.settled&&!e.pathContext&&i?.isBusy()){i.whenIdle().then(()=>this.syncImagePaste(e,n));return}i?.detach(),this.imagePasteHandles.delete(e)}else i||this.imagePasteHandles.set(e,Mx(this.app,n,{}))}decorateLabel(e){if(!e.optional)return e.label;let n=this.contentEl.ownerDocument,i=n.win.createFragment();return i.appendChild(n.createTextNode(e.label)),i.createSpan({text:" (optional)",cls:"qa-onepage-optional-badge"}),i}submit(){if(this.settled)return;let e=new Set(this.requirements.filter(c=>!this.isFieldVisible(c.id)).map(c=>c.id));for(let c of this.discoveryForm?.notes??[]){if(this.discoverySelections.has(c.id))continue;let d=this.discoveryInputs.get(c.id);if(d){if(!d.input.value.trim()){new Sr.Notice("Enter a note title or choose an existing note."),d.input.focus();return}try{d.select(d.resolve())}catch(u){new Sr.Notice(u instanceof Error?u.message:"Could not select this note."),d.input.focus();return}}}let n=c=>c.type==="file-picker"&&!c.optional&&!c.suggesterConfig?.multiSelect,i=this.requirements.find(c=>e.has(c.id)&&this.isFieldVisible(c.id)&&!c.optional&&!n(c)&&!(this.result.get(c.id)??this.initialValues.get(c.id)??c.defaultValue));if(i){this.focusField(i.id);return}let o=this.requirements.find(c=>this.isFieldVisible(c.id)&&n(c)&&!this.result.get(c.id));if(o){new Sr.Notice(`QuickAdd: Choose a file for "${o.label}".`),this.focusField(o.id);return}let s=Array.from(this.imagePasteHandles.values()).find(c=>c.isBusy());if(s){s.whenIdle().then(()=>this.submit());return}let a={},l=this.requirements.find(c=>this.isFieldVisible(c.id)&&c.type==="date"&&!c.optional&&this.dateParseErrors.has(c.id));if(l){new Sr.Notice(`QuickAdd: "${l.label}" is not a valid date. Fix it or clear it before submitting.`),this.focusField(l.id);return}for(let[c,d]of this.multiSelections){let u=(this.result.get(c)??"").replace(/,\s*$/,"").trim();d.join(", ")!==u&&this.multiSelections.delete(c)}Object.assign(a,this.collectAnswers()),this.settled=!0,this.close(),this.resolvePromise(a)}focusField(e){let n=this.fieldElements.get(e)?.[0];Sr.Platform.isPhone?n?.scrollIntoView({block:"nearest"}):n?.querySelector("input, textarea, select")?.focus()}collectAnswers(){let e=new Map(this.requirements.map(i=>[i.id,i])),n={};return this.result.forEach((i,o)=>{if(!this.isFieldVisible(o))return;let s=e.get(o);if(s?.type==="date"&&i===""){let a=this.dateParseErrors.has(o);if(!s.optional||a)return}n[o]=i}),n}collectPreviewAnswers(){let e=this.collectAnswers(),n=new Map(this.requirements.map(i=>[i.id,i]));for(let[i,o]of this.fileSelections)this.isFieldVisible(i)&&(e[i]=n.get(i)?.suggesterConfig?.multiSelect?[...o]:o[0]??"");return e}cancel(){this.settled=!0,this.close(),this.rejectPromise(on())}onClose(){this.peek.onHostClosed();for(let e of this.imagePasteHandles.values())e.detach();this.imagePasteHandles.clear(),this.imagePasteInputs.clear();for(let e of this.fieldControls.values()){for(let n of e.suggesters)n.destroy();for(let n of e.dispose)n()}this.freeTextFields.length=0,this.lastFocusedFreeText=void 0;for(let e of this.discoverySuggesters)e.destroy();this.discoverySuggesters.length=0,this.settled||(this.settled=!0,this.rejectPromise(on()))}async updatePreviews(){if(!this.computePreview||!this.previewContainerEl)return;let e=++this.previewToken;try{let n=await this.computePreview(this.collectPreviewAnswers());if(e!==this.previewToken||!this.previewContainerEl)return;IH(this.previewContainerEl,n)}catch{}}}});function $ne(r){if(!r||typeof r!="object")return;let t={};return typeof r.min=="number"&&Number.isFinite(r.min)&&(t.min=r.min),typeof r.max=="number"&&Number.isFinite(r.max)&&(t.max=r.max),t.min!==void 0&&t.max!==void 0&&t.max<t.min&&(delete t.min,delete t.max),typeof r.step=="number"&&Number.isFinite(r.step)&&r.step>0&&(t.step=r.step),Object.keys(t).length>0?t:void 0}function Fne(r){if(!r||typeof r!="object")return;let{min:t,max:e}=r,n=r.step??1;if(!(typeof t!="number"||typeof e!="number"||typeof n!="number"||!Number.isFinite(t)||!Number.isFinite(e)||!Number.isFinite(n)||e<=t||n<=0))return{min:t,max:e,step:n}}async function oW(r,t,e){let n={},i=[];for(let l of e){let c=t.variables.get(l.id);if(c!=null){n[l.id]=String(c);continue}let d=Fne(l.sliderConfig),u=d??$ne(l.numericConfig),p=l.type==="slider"&&!d?"number":l.type;i.push({id:l.id,label:l.label??l.id,type:p,placeholder:l.placeholder,defaultValue:l.defaultValue,numericConfig:u,sliderConfig:d,options:l.options,dateFormat:l.dateFormat,description:l.description,optional:l.optional,suggesterConfig:l.suggesterConfig,source:"script"})}let o={};if(i.length>0){let l=t?.promptProvider;if(l)try{let c=await l.requestInputs(i);o=Object.fromEntries(Object.entries(c).map(([d,u])=>[d,Array.isArray(u)?u.join(", "):u]))}catch(c){na(c)}else{let c=new Of(r,i,t.variables);try{o=await c.waitForClose}catch(d){na(d)}}}for(let l of e){let c=o[l.id];l.type==="suggester"&&l.suggesterConfig?.multiSelect&&typeof c=="string"&&(o[l.id]=c.replace(/,\s*$/,""))}let s={...n,...o};for(let l of e)s[l.id]===void 0&&(s[l.id]="");Object.entries(s).forEach(([l,c])=>t.variables.set(l,c));let a={};for(let l of e){let c=s[l.id];if(c===void 0)continue;let d=c;if(l.type==="date"&&l.dateFormat&&typeof c=="string"&&c.startsWith("@date:")){let u=c.slice(6),p=Mo(u,l.dateFormat);p&&(d=p)}a[l.id]=d}return a}var sW=x(()=>{SM();vu();aM()});function Au(r){return new TextEncoder().encode(r).length}function Mne(r){let t=0;for(let e of r){if(e.role==="tool"){for(let n of e.results)t+=Au(n.content);continue}if(t+=Au(e.content),e.role==="assistant"&&e.toolCalls){for(let n of e.toolCalls)if(typeof n.rawArgs=="string")t+=Au(n.rawArgs);else if(n.args)try{t+=Au(JSON.stringify(n.args))}catch{}}}return t}function Rne(r,t){let e;if(typeof r=="string")e=r;else if(r==null)e='{"ok":true}';else try{e=JSON.stringify(r)}catch{return{content:"tool returned a value that could not be serialized",isError:!0}}if(Au(e)>t){let n=" \u2026[truncated]",i=Math.max(0,t-Au(n)),o=Math.min(e.length,i);for(;o>0&&Au(e.slice(0,o))>i;)o=Math.floor(o*.9)||o-1;e=e.slice(0,o)+n}return{content:e,isError:!1}}async function aW(r){let t=r.maxResultBytes??32768,e=r.maxTranscriptBytes??524288,n=Math.max(1,r.maxSteps),i=[...r.request.messages],o=[],s={promptTokens:0,completionTokens:0,totalTokens:0},a=0,l=!1,c=null;for(let m=0;m<n;m++){if(m>0&&r.isOnlineDisabled?.())return d("aborted");let h=m===n-1,g=l||h,v={...r.request,messages:i,...g?{toolChoice:"none"}:{}};a+=Mne(i);let b;try{b=await r.dispatch(v,{isFinalStep:g})}catch(C){if(r.isContextOverflow?.(C))return d("context-overflow");throw C}if(c=b,s.promptTokens+=b.usage.promptTokens,s.completionTokens+=b.usage.completionTokens,s.totalTokens+=b.usage.totalTokens,b.normalizedStopReason!=="tool_calls"||b.toolCalls.length===0||g){o.push({stepNumber:m,text:b.content,toolCalls:b.toolCalls,toolResults:[],finishReason:b.rawStopReason,usage:b.usage}),await r.onStepFinish?.(o[o.length-1]);let C=b.normalizedStopReason==="length"?"length":h&&!l&&m>0?"max-steps":"stop";return d(C)}i.push({role:"assistant",content:b.content,toolCalls:b.toolCalls,providerRaw:b.providerRaw});let y=[];for(let C of b.toolCalls)y.push(await u(C));i.push({role:"tool",results:y}),o.push({stepNumber:m,text:b.content,toolCalls:b.toolCalls,toolResults:y,finishReason:b.rawStopReason,usage:b.usage}),await r.onStepFinish?.(o[o.length-1]),a>e&&(l=!0),r.shouldStop?.({steps:o})&&(l=!0)}return d("max-steps");function d(m){return{text:c?.content??"",steps:o,finishReason:m,usage:s,messages:i,finalTurn:c??{content:"",toolCalls:[],normalizedStopReason:"stop",rawStopReason:"",usage:{promptTokens:0,completionTokens:0,totalTokens:0}}}}async function u(m){if(m.parseError)return p(m,"could not parse the tool arguments as JSON");let h=r.getTool(m.name);if(!h)return p(m,`unknown tool "${m.name}"`);let g=m.args??{},v=r.validateArgs(h,g);if(v)return p(m,`invalid arguments: ${v}`);if(!await r.confirm(m,h))return p(m,"tool call denied by user");let y;try{y=await h.execute(g,{toolCallId:m.id,toolName:m.name})}catch(T){if(r.isAbortError(T))throw T;return p(m,`tool execution failed: ${T instanceof Error?T.message:String(T)}`)}let{content:C,isError:w}=Rne(y,t);return{toolCallId:m.id,name:m.name,content:C,isError:w}}function p(m,h){return{toolCallId:m.id,name:m.name,content:h,isError:!0}}}var lW=x(()=>{});function v_(r,t="schema"){if(r===null||typeof r!="object"||Array.isArray(r))throw new Cl(`${t} must be a JSON Schema object.`);for(let e of Object.keys(r))if(!cW.has(e))throw new Cl(`${t} uses unsupported JSON Schema keyword "${e}". QuickAdd tool schemas support only: ${[...cW].join(", ")}. (Constraints like pattern/minLength/additionalProperties/$ref/allOf/anyOf/format are rejected because at least one provider would silently drop them.)`);if(r.type!==void 0){let e=Array.isArray(r.type)?r.type:[r.type];for(let n of e)if(!One.has(n))throw new Cl(`${t} has invalid type "${String(n)}".`)}if(r.properties!==void 0){if(r.properties===null||typeof r.properties!="object"||Array.isArray(r.properties))throw new Cl(`${t}.properties must be an object.`);for(let[e,n]of Object.entries(r.properties))v_(n,`${t}.properties.${e}`)}if(r.required!==void 0&&(!Array.isArray(r.required)||r.required.some(e=>typeof e!="string")))throw new Cl(`${t}.required must be an array of strings.`);if(r.items!==void 0){if(Array.isArray(r.items))throw new Cl(`${t}.items as an array (tuple validation) is not supported in QuickAdd's schema subset.`);v_(r.items,`${t}.items`)}if(r.enum!==void 0&&!Array.isArray(r.enum))throw new Cl(`${t}.enum must be an array.`)}function g_(r){return r===null?"null":Array.isArray(r)?"array":typeof r=="number"?Number.isInteger(r)?"integer":"number":typeof r=="boolean"?"boolean":typeof r=="string"?"string":"object"}function Dne(r,t){let e=g_(r);return e===t||t==="number"&&e==="integer"}function Ky(r,t,e="$"){if(t.type!==void 0){let n=Array.isArray(t.type)?t.type:[t.type];if(!n.some(i=>Dne(r,i)))return`${e}: expected ${n.join(" | ")}, got ${g_(r)}`}if(Array.isArray(t.enum)&&!t.enum.some(i=>y_(i,r)))return`${e}: value is not one of the allowed enum values`;if("const"in t&&!y_(t.const,r))return`${e}: value does not equal the required const`;if(g_(r)==="object"){let n=r;if(Array.isArray(t.required)){for(let i of t.required)if(!Object.prototype.hasOwnProperty.call(n,i))return`${e}.${i}: required property is missing`}if(t.properties){for(let[i,o]of Object.entries(t.properties))if(i in n){let s=Ky(n[i],o,`${e}.${i}`);if(s)return s}}}if(g_(r)==="array"&&t.items&&!Array.isArray(t.items)){let n=r;for(let i=0;i<n.length;i++){let o=Ky(n[i],t.items,`${e}[${i}]`);if(o)return o}}return null}function y_(r,t){if(r===t)return!0;if(typeof r!=typeof t)return!1;if(r===null||t===null)return r===t;if(Array.isArray(r)&&Array.isArray(t))return r.length===t.length&&r.every((e,n)=>y_(e,t[n]));if(typeof r=="object"&&typeof t=="object"){let e=Object.keys(r),n=Object.keys(t);return e.length!==n.length?!1:e.every(i=>y_(r[i],t[i]))}return!1}var cW,One,Cl,dW=x(()=>{cW=new Set(["type","properties","required","items","enum","const","description","title"]),One=new Set(["object","array","string","number","integer","boolean","null"]),Cl=class extends Error{constructor(t){super(t),this.name="ToolSchemaError"}}});function b_(r){return r.toLowerCase().startsWith(ow)}var AM=x(()=>{Le()});function w_(r){let t=r.trim();if(!t)throw new Error("assignToVariable cannot be empty.");if(new Set(["value","title","text","meta"]).has(t.toLowerCase()))throw new Error(`assignToVariable "${t}" is reserved (it would hijack a built-in formatter token).`);if(t.toLowerCase().endsWith("-quoted"))throw new Error(`assignToVariable "${t}" cannot end with "-quoted" (collides with the quoted output variable).`);if(b_(t))throw new Error(`assignToVariable "${t}" uses the reserved "__qa." prefix for QuickAdd internal variables.`);if(/[|,]/.test(t))throw new Error(`assignToVariable "${t}" contains characters unreachable by {{VALUE:name}}.`)}var IM=x(()=>{AM()});function Lne(r,t){if(!t||typeof t!="object")return"";let e=t,n=typeof e.path=="string"?e.path.trim():"",i=typeof e.heading=="string"?e.heading.trim():"";if(!n&&!i)return"";let o=[];return n&&o.push(`Target: ${n}`),i&&o.push(`Heading: ${i}`),o.join(" \xB7 ")}function Nne(r){try{return JSON.stringify(r,null,2)??String(r)}catch{return String(r)}}var Iu,Qy,uW=x(()=>{Iu=require("obsidian");tl();Qy=class r extends Iu.Modal{constructor(e,n,i){super(e);this.toolName=n;this.args=i;this.outcome=null;this.waitForClose=new Promise(o=>{this.resolvePromise=o}),this.open(),this.display()}static Prompt(e,n,i){return new r(e,n,i).waitForClose}display(){this.containerEl.addClass("quickAddModal","qaAIToolConfirm"),this.contentEl.empty(),this.titleEl.textContent=`Run AI tool: ${this.toolName}?`,this.contentEl.createEl("p",{text:"The AI requested this tool call with the arguments below."});let e=Lne(this.toolName,this.args);e&&this.contentEl.createEl("p",{cls:"qaAIToolSummary",text:e});let n=this.contentEl.createEl("pre",{cls:"qaAIToolArgs"});n.textContent=Nne(this.args),n.setCssStyles({whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:"16rem",overflowY:"auto"});let i=this.contentEl.createDiv({cls:"yesNoPromptButtonContainer"}),o=new Iu.ButtonComponent(i).setButtonText("Abort run").onClick(()=>this.submit("abort")),s=new Iu.ButtonComponent(i).setButtonText("Deny").onClick(()=>this.submit("deny")),a=new Iu.ButtonComponent(i).setButtonText("Approve all this run").onClick(()=>this.submit("allow-all")),l=new Iu.ButtonComponent(i).setButtonText("Approve").onClick(()=>this.submit("allow"));s.buttonEl.focus(),QC([o.buttonEl,s.buttonEl,a.buttonEl,l.buttonEl])}submit(e){this.outcome=e,this.close()}onClose(){super.onClose(),this.resolvePromise(this.outcome??"deny")}}});function Une(r){return r instanceof at}function mW(r){return cy(r)==="input_context"}function qne(r){return{content:r.content,toolCalls:r.toolCalls??[],normalizedStopReason:r.normalizedStopReason??"stop",rawStopReason:r.stopReason,usage:r.usage,providerRaw:r.providerRaw}}function zne(r){if(r)return typeof r=="string"?r:{name:r.toolName}}function Hne(r){return{toolCallId:r.id,toolName:r.name,input:r.args}}function Wne(r){return{toolCallId:r.toolCallId,toolName:r.name,output:r.content,isError:r.isError??!1}}function fW(r,t){let e;try{e=JSON.parse(Gne(r))}catch(i){return{ok:!1,error:`not valid JSON (${i instanceof Error?i.message:String(i)})`}}let n=Ky(e,t);return n?{ok:!1,error:n}:{ok:!0,value:e}}function Gne(r){let t=r.trim(),e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);return e?e[1]:t}var pW,Vne,Bne,PM,C_,hW=x(()=>{je();Su();gT();Sn();ri();Vm();Ic();ff();dF();nt();hT();lW();dW();IM();uW();pW=/^[a-zA-Z0-9_-]{1,64}$/,Vne=20,Bne=100,PM=new WeakSet;C_=class{constructor(t,e,n,i){this.app=t;this.plugin=e;this.choiceExecutor=n;this.config=i;this.running=!1;this.approveAllThisRun=!1;let o=new Set;for(let[s,a]of Object.entries(i.tools??{})){if(!pW.test(s))throw new Error(`Invalid tool name "${s}". Tool names must match ${pW}.`);if(o.has(s))throw new Error(`Duplicate tool name "${s}".`);o.add(s),v_(a.inputSchema,`tool "${s}".inputSchema`)}}async generate(t={}){if(this.running)throw new Error("This agent is already running a generate() call. Await it, or create a separate agent for concurrent runs.");let e=typeof t.assignToVariable=="string"&&t.assignToVariable.length>0;if(e&&(this.assertAssignableName(t.assignToVariable),PM.has(this.choiceExecutor)))throw new Error("Another AI run with assignToVariable is already in flight in this context \u2014 they would race the shared variables. Run them sequentially.");this.running=!0,e&&PM.add(this.choiceExecutor);let n=fT(this.app);try{return await this.run(t,n)}finally{this.running=!1,e&&PM.delete(this.choiceExecutor);try{n()}catch{}}}async run(t,e){this.approveAllThisRun=!1;let n=U.getState();if(n.disableOnlineFeatures)throw new Error("Rejecting AI request: Online features are disabled in settings.");let{model:i,provider:o}=jv(this.config.model),s=await Po(this.app,o),a=await this.buildSeedMessages(t),l=this.buildToolDefinitions(),c=this.buildRegistry(),d=t.schema?{schema:t.schema,name:"response",strict:!0}:void 0,u={messages:a,...l.length>0?{tools:l}:{},toolChoice:zne(t.toolChoice??this.config.toolChoice)??"auto",maxOutputTokens:t.maxOutputTokens??this.config.maxOutputTokens,modelParams:this.config.modelOptions},p=Math.max(1,Math.min(this.config.maxSteps??Vne,Bne)),m=fu(n.ai.showAssistant);m.setMessage("starting","QuickAdd is running the AI agent.");try{let h=await aW({request:u,maxSteps:p,dispatch:async(v,b)=>{let y=this.buildTurnRequest(v,b.isFinalStep,d);try{let C=await mF(this.app,s,i,o,y,e,!n.ai.showAssistant);return qne(C)}catch(C){throw mW(C)&&Me(C),C}},getTool:v=>c.get(v),confirm:(v,b)=>this.confirm(v,b),validateArgs:(v,b)=>Ky(b,v.definition.parameters),isAbortError:Une,isContextOverflow:mW,isOnlineDisabled:()=>U.getState().disableOnlineFeatures,shouldStop:this.buildShouldStop(),onStepFinish:v=>this.reportStep(m,v)}),g=this.toGenerateResult(h);return t.schema&&(g.object=await this.resolveStructuredObject(h,u,i,o,s,t.schema,e)),typeof t.assignToVariable=="string"&&t.assignToVariable&&this.assignVariable(t.assignToVariable,g.text),m.setMessage("finished",`Ran ${g.steps.length} step${g.steps.length===1?"":"s"}.`),window.setTimeout(()=>m.hide(),5e3),g}catch(h){throw m.fail(h),h}}reportStep(t,e){let n=e.toolCalls.map(o=>o.name),i=n.length>0?`Step ${e.stepNumber+1}: running ${n.join(", ")}.`:`Step ${e.stepNumber+1}: generating a response.`;t.setMessage("thinking",i)}async buildSeedMessages(t){let e=[],n=t.system??this.config.system??U.getState().ai.defaultSystemPrompt;n&&n.trim().length>0&&e.push({role:"system",content:n});let i=t.prompt??"",o=i?await new Ai(this.app,this.plugin,this.choiceExecutor).formatFileContent(i):"";return e.push({role:"user",content:o}),e}buildToolDefinitions(){return Object.entries(this.config.tools??{}).map(([t,e])=>({name:t,description:e.description,parameters:e.inputSchema,...e.strict?{strict:!0}:{}}))}buildRegistry(){let t=new Map;for(let[e,n]of Object.entries(this.config.tools??{}))t.set(e,{definition:{name:e,description:n.description,parameters:n.inputSchema,strict:n.strict},execute:(i,o)=>n.execute(i,o),readOnly:n.readOnly});return t}buildShouldStop(){let t=this.config.stopWhen?Array.isArray(this.config.stopWhen)?this.config.stopWhen:[this.config.stopWhen]:[];if(t.length!==0)return({steps:e})=>{let n=e.flatMap(i=>i.toolCalls.map(o=>o.name));return t.some(i=>i({stepNumber:e.length,toolCallNames:n}))}}buildTurnRequest(t,e,n){return!!(t.tools&&t.tools.length>0)&&!e?{...t,responseFormat:void 0}:{...t,tools:void 0,toolChoice:e?"none":t.toolChoice,responseFormat:n}}async confirm(t,e){let n=t.args??{},i=await this.resolvePerToolApproval(e,n);if(!(i||this.needsGlobalConfirmation(e))||this.approveAllThisRun&&!i)return!0;if(this.choiceExecutor.interactive===!1)throw new de(`'${t.name}' needs approval before it runs, but this run is non-interactive. Set the AI assistant's tool-confirmation to "never", mark the tool readOnly, or re-run with the ui flag.`);let s=await Qy.Prompt(this.app,t.name,t.args??{});if(s==="abort")throw new at("AI tool run aborted by user");return s==="allow-all"?(this.approveAllThisRun=!0,!0):s==="allow"}async resolvePerToolApproval(t,e){let i=this.config.tools?.[t.definition.name]?.needsApproval;return typeof i=="function"?await i({args:e}):i===!0}needsGlobalConfirmation(t){let e=U.getState().ai.confirmToolCalls??"destructive";return e==="always"?!0:e==="destructive"?t.readOnly!==!0:!1}async resolveStructuredObject(t,e,n,i,o,s,a){if(t.finalTurn.rawStopReason==="refusal")return;let l=fW(t.finalTurn.content,s);if(l.ok)return l.value;if(t.finishReason==="aborted"||t.finishReason==="context-overflow"||U.getState().disableOnlineFeatures)return;let c=[...t.messages,{role:"assistant",content:t.finalTurn.content},{role:"user",content:`Your previous reply was not valid JSON matching the required schema (${l.error}). Reply with ONLY a JSON object that matches the schema \u2014 no prose, no code fences.`}],d={...e,messages:c,tools:void 0,toolChoice:"none",responseFormat:{schema:s,name:"response",strict:!0}};try{let u=await mF(this.app,o,n,i,d,a),p=fW(u.content,s);return p.ok?p.value:void 0}catch{return}}toGenerateResult(t){let e=t.steps.map(i=>({stepNumber:i.stepNumber,text:i.text,toolCalls:i.toolCalls.map(Hne),toolResults:i.toolResults.map(Wne),finishReason:i.finishReason})),n=e[e.length-1];return{text:t.text,steps:e,toolCalls:n?.toolCalls??[],toolResults:n?.toolResults??[],usage:{inputTokens:t.usage.promptTokens,outputTokens:t.usage.completionTokens,totalTokens:t.usage.totalTokens},finishReason:t.finishReason}}assignVariable(t,e){let n=t.trim(),i=("> "+e).replace(/\n/g,`
|
||
> `);this.choiceExecutor.variables.set(n,e),this.choiceExecutor.variables.set(`${n}-quoted`,i)}assertAssignableName(t){w_(t)}}});function xl(r,t,e=!1){let n=si(r),i=n.find(u=>u.line===t),o=!!i;if(!o&&e)throw new Error(`Target line ${t} is not a heading, but we are trying to find the end of its section.`);if(!o&&!e){let u=n.find(h=>h.line>t)?.line??null,p=jne(r,t,h=>h.trim()===""),m=[u,p].filter(h=>h!==null);return m.length>0?Math.min(...m)-1:r.length-1}let s=i,l=n.find(u=>u.line>s.line&&(!e||u.level<=s.level))?.line??r.length,c=S2(r,s),d=l-1;for(;d>c&&r[d].trim()==="";)d--;return d===0&&r[1]?.trim()===""?1:Math.max(d,c)}function jne(r,t,e){for(let n=t+1;n<r.length;n++)if(e(r[n]))return n;return null}var x_=x(()=>{bu()});function Xy(r){let t=LF(r);return r.map((e,n)=>t[n]?e.replace(/^(\s*)#+(\s)/,`$1${Yne}$2`):e)}function Kne(r){let t=r.match(/^\[?v?(\d+)\.(\d+)\.(\d+)(?:[-+\]].*)?$/i)??r.match(/^\[?v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/i);if(!t)return{value:0,parsed:!1};let e=n=>Math.min(Number(n??"0"),999999);return{value:e(t[1])*1e12+e(t[2])*1e6+e(t[3]),parsed:!0}}function gW(r,t,e){switch(t.by){case"lexical":return{value:r.toLocaleLowerCase(),parsed:!0};case"numeric":{let n=r.match(/^-?\d+(?:\.\d+)?/);return n?{value:Number(n[0]),parsed:!0}:{value:0,parsed:!1}}case"date":{let n=e?e(r,t.dateFormat||void 0,!1):null;return n&&n.isValid()?{value:n.valueOf(),parsed:!0}:{value:0,parsed:!1}}case"semver":return Kne(r);default:return{value:0,parsed:!0}}}function Qne(r,t){if(typeof r.value=="string"&&typeof t.value=="string")return r.value<t.value?-1:r.value>t.value?1:0;let e=r.value,n=t.value;return e<n?-1:e>n?1:0}function vW(r,t,e,n,i,o=0){let s=Xy(r),a=si(s).filter(p=>p.line>=o),l=a.filter(p=>p.level===e),c=gW(si([t])[0]?.heading.trim()??"",n,i);if(l.length===0){let p=a.filter(m=>m.level<e).pop();return p?{mode:"after",line:xl(s,p.line,!0)}:{mode:"bodyStart"}}let d=()=>{let p=l[l.length-1];return{mode:"after",line:xl(s,p.line,!0)}};if(n.by==="insertion")return n.direction==="desc"?{mode:"before",line:l[0].line}:d();if(!c.parsed)return d();let u=n.unparseable??"bottom";for(let p of l){let m=gW(p.heading.trim(),n,i),h;if(!m.parsed)h=u==="bottom";else{let g=Qne(c,m);h=n.direction==="desc"?g>0:g<0}if(h)return{mode:"before",line:p.line}}return d()}var Yne,$M=x(()=>{x_();bu();Yne="\u200B"});function FM(r){let t=r.split(`
|
||
`);for(;t.length>1&&t[t.length-1].trim()==="";)t.pop();return t}function MM(r){return r.length===0||r.length===1&&r[0].trim()===""}function RM(r,t){if(t.length<=1){let e=Xne(r,t[0]??"");return{start:e,end:e}}return Jne(r,t)}function Xne(r,t){let e=t.trimEnd(),n=-1;for(let i=0;i<r.length;i++){let o=r[i].trimStart();if(o===e)return i;if(o.startsWith(e)){let a=o.slice(e.length);if(/^\s*$/.test(a))return i;n===-1&&(n=i);continue}let s=o.indexOf(e);if(s!==-1){let a=o.slice(s+e.length);if(/^\s*$/.test(a))return i;n===-1&&(n=i)}}return n}function Jne(r,t){let e=t.length,n=t.map(i=>yW(i));for(let i=0;i+e<=r.length;i++){let o=!0;for(let s=0;s<e;s++)if(yW(r[i+s])!==n[s]){o=!1;break}if(o)return{start:i,end:i+e-1}}return{start:-1,end:-1}}function yW(r){return r.trimEnd()}function E_(r,t,e){return r?si(t).some(n=>n.line===e):!1}function Zne(r,t){return r==="skip"?!0:r==="none"?!1:eie(t)}function eie(r){return/^\s{0,3}#{1,6}\s+\S/.test(r)}function T_(r,t,e,n){if(t<0)return t;let i=r[t]??"";if(!Zne(n,i))return t;let s=e.endsWith(`
|
||
`)?Math.max(r.length-1,0):r.length,a=t;for(let l=t+1;l<s;l++){if(r[l].trim().length===0){a=l;continue}break}return a}function Jy(r,t,e,n){if(t<0)return t;let i=t,o=t+1;for(;o<r.length&&r[o].trim().length===0;)i=o,o++;return i===t||o!==r.length||!n.endsWith(`
|
||
`)?t:e.endsWith(`
|
||
`)?Math.max(t,i-1):i}function bW(r){return r.includes(`
|
||
`)||r.includes("\r")}function wW(r,t){let e=r.indexOf(`
|
||
`,t);return e===-1?r.length:e>0&&r[e-1]==="\r"?e-1:e}function OM(r){let t=yl(r);return t>0?r.slice(0,t).split(`
|
||
`).length-1:0}function CW(r){return si([r.replace(/\r$/,"")]).length>0}function xW(r){let t=new Set(si(r.map(e=>e.replace(/\r$/,""))).map(e=>e.line));return r.map((e,n)=>t.has(n)?e:"")}function EW(r,t){let e=OM(t),n=r.map((i,o)=>o<e?"":i);return Xy(n).map(i=>i.replace(/\r$/,""))}function Df(r,t,e,n,i=r.length){let o=t.split(`
|
||
`),s=o.slice(0,e+1).join(`
|
||
`),a=o.slice(e+1).join(`
|
||
`),c=(o[e+1]??"").trim(),d=t.endsWith(`
|
||
`)&&e+1===o.length-1,u=e+1<o.length&&!d&&c==="",p=n&&r.endsWith(`
|
||
`)&&u?r.slice(0,-1):r,m=!r.endsWith(`
|
||
`)&&a.length>0?`
|
||
`:"";return{content:`${s}
|
||
${p}${m}${a}`,insertedEndOffset:s.length+1+Math.min(i,p.length)}}function TW(r,t,e,n=r.length){let i=t.length>0&&!r.endsWith(`
|
||
`)?`
|
||
`:"",o=Math.max(0,Math.min(n,r.length));if(e<=0)return{content:`${r}${i}${t}`,insertedEndOffset:o};let s=t.split(`
|
||
`),a=s.slice(0,e).join(`
|
||
`),l=s.slice(e).join(`
|
||
`);return{content:`${a}
|
||
${r}${i}${l}`,insertedEndOffset:a.length+1+o}}function _W(r,t,e,n,i){let o=n,s=o.includes(`\r
|
||
`)?`\r
|
||
`:`
|
||
`,a=t.mode==="before"?t.line:t.line+1,l=0;for(let C=0;C<a&&C<r.length;C++)l+=r[C].length+1;l>o.length&&(l=o.length);let c=o.slice(0,l),d=o.slice(l),u=a>0?(r[a-1]??"").replace(/\r$/,""):"",p=a<r.length?(r[a]??"").replace(/\r$/,""):"",m=e.split(`
|
||
`).map(C=>C.replace(/\r$/,""));m.length>1&&m[m.length-1]===""&&m.pop();let h=[];a>0&&u.trim()!==""&&h.push(""),h.push(...m),a<r.length&&p.trim()!==""&&h.push("");let g=h.join(s),v=c.length>0&&!/\n$/.test(c)?s:"",b=d.length>0||/\n$/.test(o)?s:"",y=c.length+v.length;return{content:`${c}${v}${g}${b}${d}`,insertedEndOffset:y+(i===void 0?g.length:(a>0&&u.trim()!==""?s.length:0)+Math.min(e.slice(0,i).split(`
|
||
`).map(C=>C.replace(/\r$/,"")).join(s).length,m.join(s).length))}}var __=x(()=>{bu();$M();Lc()});function DM(r){return cr(r)}function LM(r,t){return t.some(e=>r===e||r.startsWith(`${e}/`))}function Pu(r,t){let e=(t??[]).map(n=>DM(n)).filter(n=>n.length>0);return e.length===0?!0:r?LM(r.normalize("NFC"),e):!1}var k_=x(()=>{Dr()});function $u(r,t={}){let e=(r??"").trim();if(!e)throw new Ro("Path is empty.");let n=e.replace(/\\/g,"/").normalize("NFC");if(n.startsWith("/")||/^[a-zA-Z]:/.test(n))throw new Ro(`Refusing to write to an absolute path outside the vault: "${n}".`);let i=n.replace(/\/+/g,"/").replace(/^\/+|\/+$/g,""),o=i.split("/").filter(a=>a.length>0);if(o.length===0)throw new Ro("Path is empty after normalization.");for(let a of o){if(a==="."||a==="..")throw new Ro(`Refusing path with a traversal segment ("${a}"): "${i}".`);if(a.startsWith("."))throw new Ro(`Refusing to write into a dot/config path segment ("${a}"): "${i}".`);tie(a,i)}let s=(t.allowedRoots??[]).map(a=>DM(a)).filter(a=>a.length>0);if(s.length>0&&!LM(i,s))throw new Ro(`Path "${i}" is not under an allowed root (${s.join(", ")}).`);return i}function tie(r,t){if(Yh.test(r))throw new Ro(`Path segment "${r}" contains control characters: "${t}".`);if(Kh.test(r))throw new Ro(`Path segment "${r}" contains an illegal character (\\ : * ? " < > |): "${t}".`);if(Qh.test(r))throw new Ro(`Path segment "${r}" cannot end with a space or a period: "${t}".`);let e=r.split(".")[0]??"";if(e&&Pd(e))throw new Ro(`Path segment "${r}" is a reserved device name: "${t}".`)}var Ro,SW=x(()=>{Xh();k_();Ro=class extends Error{constructor(t){super(t),this.name="UnsafeVaultPathError"}}});function Lf(r,t){let e=Object.entries(r),n=new Set(e.map(([o])=>o));if(AW(t.only,n,"only"),AW(t.exclude,n,"exclude"),t.only){let o=new Set(t.only);e=e.filter(([s])=>o.has(s))}if(t.exclude){let o=new Set(t.exclude);e=e.filter(([s])=>!o.has(s))}let i=t.prefix??"";return Object.fromEntries(e.map(([o,s])=>[i+o,s]))}function Zy(r){return{...r,__qaTool:!0}}function AW(r,t,e){if(!r)return;let n=r.filter(i=>!t.has(i));n.length!==0&&S.logWarning(`AI tools: ${e} listed unknown tool name(s) ${n.map(i=>`"${i}"`).join(", ")}. Valid names: ${[...t].join(", ")}.`)}var S_=x(()=>{ye()});function OW(r,t={}){let e=t.allowedRoots,n={read_note:Fu({description:"Read a note's full markdown content by vault path.",inputSchema:Mu({path:Oo("Vault path to the note, e.g. Notes/Foo.md")},["path"]),readOnly:!0,execute:async({path:i})=>{let o=$u(String(i),{allowedRoots:e}),s=r.vault.getAbstractFileByPath(o);if(!(s instanceof VM.TFile))return{found:!1,path:o};let a=await r.vault.cachedRead(s);return{found:!0,path:o,content:a.length>IW?a.slice(0,IW)+`
|
||
\u2026[truncated]`:a}}}),list_notes:Fu({description:"List markdown notes, optionally within a folder.",inputSchema:Mu({folder:Oo("Folder to list (omit for the whole vault)."),limit:PW("Max results (default 100, capped at 200).")},[]),readOnly:!0,execute:async({folder:i,limit:o})=>{let s=i?$u(String(i),{allowedRoots:e}):"",a=MW(FW(o,rie),1,nie),l=ts(r,s).filter(c=>Pu(c.path,e));return{total:l.length,notes:l.slice(0,a).map(c=>({path:c.path,basename:c.basename}))}}}),search_notes:Fu({description:"Search notes by name and/or content. Returns matching paths with a short snippet.",inputSchema:Mu({query:Oo("Text to search for."),in:$W(["name","content","both"],"Where to search (default both)."),limit:PW("Max results (default 25, capped at 50).")},["query"]),readOnly:!0,execute:async({query:i,in:o,limit:s})=>{let a=String(i).toLowerCase(),l=o??"both",c=MW(FW(s,iie),1,oie),d=r.vault.getMarkdownFiles().filter(h=>Pu(h.path,e)),u=[],p=0,m=!1;for(let h of d){if(u.length>=c)break;if(l!=="content"&&h.basename.toLowerCase().includes(a)){u.push({path:h.path});continue}if(l!=="name"){if(p>=sie){m=!0;continue}p++;let v=await r.vault.cachedRead(h),b=v.toLowerCase().indexOf(a);b>=0&&u.push({path:h.path,snippet:lie(v,b)})}}return{results:u,scannedFiles:p,truncated:u.length>=c||m}}}),get_property_values:Fu({description:"List the distinct values a frontmatter property takes across the vault (e.g. existing tags or statuses).",inputSchema:Mu({field:Oo("Frontmatter property name."),folder:Oo("Optional folder scope.")},["field"]),readOnly:!0,execute:async({field:i,folder:o})=>{let s=o?$u(String(o),{allowedRoots:e}):"",a=(o?ts(r,s):r.vault.getMarkdownFiles()).filter(c=>Pu(c.path,e)),l=new Set;for(let c of a){let u=r.metadataCache.getFileCache(c)?.frontmatter?.[String(i)];if(u!=null){for(let p of Array.isArray(u)?u:[u])if(typeof p!="object"){let m=String(p).trim();m&&l.add(m)}}}return{field:String(i),values:[...l].sort().slice(0,200)}}}),create_note:Fu({description:"Create a new markdown note. Fails if the path already exists.",inputSchema:Mu({path:Oo("Vault path for the new note."),content:Oo("Initial markdown content.")},["path"]),needsApproval:!0,execute:async({path:i,content:o})=>{let s=$u(NM(String(i)),{allowedRoots:e});return await cf(r,s),await aie(r,s),{created:!0,path:(await r.vault.create(s,String(o??""))).path}}}),append_to_note:Fu({description:"Append text to an existing note (frontmatter-aware for top inserts).",inputSchema:Mu({path:Oo("Vault path to the existing note."),content:Oo("Markdown to append."),position:$W(["top","bottom"],"Where to add it (default bottom).")},["path","content"]),needsApproval:!0,execute:async({path:i,content:o,position:s})=>{let a=$u(NM(String(i)),{allowedRoots:e}),l=RW(r,a);await cf(r,a);let c=String(o);return await To(r,l,d=>s==="top"?L2(d,c.endsWith(`
|
||
`)?c:c+`
|
||
`):`${d}${d.endsWith(`
|
||
`)||d.length===0?"":`
|
||
`}${c}`),{appended:!0,path:a}}}),insert_under_heading:Fu({description:"Insert markdown under an existing heading (matched exactly). Errors if the heading is not found.",inputSchema:Mu({path:Oo("Vault path to the existing note."),heading:Oo("Exact heading text (without the # markers)."),content:Oo("Markdown to insert under the heading.")},["path","heading","content"]),needsApproval:!0,execute:async({path:i,heading:o,content:s})=>{let a=$u(NM(String(i)),{allowedRoots:e}),l=RW(r,a);await cf(r,a);let c=r.metadataCache.getFileCache(l)?.headings??[],d=c.find(b=>b.heading===String(o));if(!d)throw new Error(`Heading "${o}" not found in ${a}`);let u=await r.vault.read(l),p=u.split(`
|
||
`),m=d.position.start.line,g=(c.find(b=>b.position.start.line>m&&b.level<=d.level)?.position.start.line??p.length)-1;for(;g>m&&p[g].trim()==="";)g--;let v=Df(String(s),u,g,!1);return await r.vault.modify(l,v.content),{inserted:!0,path:a,heading:String(o)}}})};return Lf(n,t)}function Fu(r){return{...r,__qaTool:!0}}function Mu(r,t){return{type:"object",properties:r,required:t}}function Oo(r){return{type:"string",description:r}}function PW(r){return{type:"integer",description:r}}function $W(r,t){return{type:"string",enum:r,description:t}}function FW(r,t){let e=Number(r);return Number.isFinite(e)?Math.floor(e):t}function MW(r,t,e){return Math.max(t,Math.min(e,r))}function NM(r){if(/\.md$/i.test(r))return r;if(/\.[a-z0-9]+$/i.test(r))throw new Error(`This tool only operates on markdown notes (.md); refused path: "${r}".`);return`${r}.md`}function RW(r,t){let e=r.vault.getAbstractFileByPath(t);if(!(e instanceof VM.TFile))throw new Error(`Note not found: ${t}`);return e}async function aie(r,t){let e=t.lastIndexOf("/");if(e<=0)return;let n=t.slice(0,e);if(!r.vault.getAbstractFileByPath(n))try{await r.vault.createFolder(n)}catch{}}function lie(r,t){let e=Math.max(0,t-40);return r.slice(e,t+80).replace(/\s+/g," ").trim()}var VM,IW,rie,nie,iie,oie,sie,DW=x(()=>{VM=require("obsidian");bi();__();Lc();Ns();k_();SW();g$();S_();IW=16e3,rie=100,nie=200,iie=25,oie=50,sie=400});function NW(r,t={}){let e=t.allowedRoots,n=()=>{let s=r.workspace.getActiveFile();return!(s instanceof A_.TFile)||s.extension!=="md"?null:Pu(s.path,e)?s:null},i=()=>{let s=r.workspace.getActiveViewOfType(A_.MarkdownView);return s&&Pu(s.file?.path,e)?s:null},o={get_active_note:Zy({description:"Get the currently active note (path, basename, and content). Returns active:null if there is none.",inputSchema:{type:"object",properties:{}},readOnly:!0,execute:async()=>{let s=n();if(!s)return{active:null};let a=await r.vault.cachedRead(s);return{active:{path:s.path,basename:s.basename,content:a.length>LW?a.slice(0,LW)+`
|
||
\u2026[truncated]`:a}}}}),get_selection:Zy({description:"Get the text currently selected in the active editor (empty string if none).",inputSchema:{type:"object",properties:{}},readOnly:!0,execute:async()=>({selection:i()?.editor?.getSelection()??""})})};return Lf(o,t)}var A_,LW,VW=x(()=>{A_=require("obsidian");k_();S_();LW=16e3});function BW(r={}){let t={get_date:Zy({description:"Get the current date/time. Optionally pass a moment.js format and a day offset.",inputSchema:{type:"object",properties:{format:{type:"string",description:"moment.js format, e.g. YYYY-MM-DD"},offset:{type:"integer",description:"Day offset from today (e.g. 1 = tomorrow)."}}},readOnly:!0,execute:async({format:e,offset:n})=>({date:Ra({format:e!=null?String(e):void 0,offset:n!=null?Number(n):void 0})})})};return Lf(t,r)}var UW=x(()=>{Aw();S_()});function zW(r,t,e,n){async function i(s,a){let l=U.getState();if(l.disableOnlineFeatures)throw new Error("Rejecting request to `prompt` via API AI module. Online features are disabled in settings.");let{model:c,provider:d}=jv(s),u=await Po(r,d);return a?.assignToVariable&&w_(a.assignToVariable),{model:c,provider:d,apiKey:u,modelOptions:a?.modelOptions??{},outputVariableName:a?.assignToVariable||a?.variableName||"output",showAssistantMessages:a?.showAssistantMessages??!0,systemPrompt:a?.systemPrompt??l.ai.defaultSystemPrompt}}function o(s,a,l){if(!s)return Me(new Error("AI Assistant returned null"),l),{};if(a?.shouldAssignVariables||a?.assignToVariable)for(let[c,d]of Object.entries(s))e.variables.set(c,d);return s}return{prompt:async(s,a,l)=>{let c=await e2(r,{...await i(a,l),prompt:s},(d,u)=>n(d,u,!1));return o(c,l,"AI Prompt error")},chunkedPrompt:async(s,a,l,c,d)=>{let u=await gF(r,{...await i(l,c),text:s,promptTemplate:a,chunkSeparator:c?.chunkSeparator??/\n/,resultJoiner:c?.chunkJoiner??`
|
||
`,shouldMerge:c?.shouldMerge??!0,maxChunkTokens:c?.maxChunkTokens},(p,m)=>n(p,{...d,...m},!1));return o(u,c,"Chunked AI Prompt error")},getModels:()=>vU(),getMaxTokens:s=>jv(s).model.maxTokens,estimateTokens(s){return Ti(s)},countTokens(s,a){return qW||(qW=!0,S.logMessage("quickAddApi.ai.countTokens is deprecated and now returns a provider-agnostic estimate (the model argument is ignored). Use estimateTokens(text) instead.")),Ti(s)},getRequestLogs(s=10){return Rz(s)},getRequestLogById(s){return Dz(s)},getLastRequestLog(){return Lz()},clearRequestLogs(){Nz()},agent:s=>new C_(r,t,e,s),tool:s=>({...s,__qaTool:!0}),stepCountIs:s=>({stepNumber:a})=>a>=s,hasToolCall:s=>({toolCallNames:a})=>a.includes(s),tools:{vault:s=>OW(r,s),workspace:s=>NW(r,s),system:s=>BW(s)}}}var qW,HW=x(()=>{vF();Vm();Ic();Gv();hW();IM();DW();VW();UW();je();nt();ye();qW=!1});function WW(r){return{getFieldValues:async(t,e)=>{let n=e?.includeInlineCodeBlocks?.map(a=>a.trim().toLowerCase()).filter(a=>a.length>0),i={folder:e?.folder,folders:e?.folders,tags:e?.tags,inline:e?.includeInline??!1,inlineCodeBlocks:n},o=r.vault.getMarkdownFiles();o=Vs.filterFiles(o,i,a=>r.metadataCache.getFileCache(a));let s=new Set;for(let a of o){let c=r.metadataCache.getFileCache(a)?.frontmatter?.[t];if(c!=null){if(Array.isArray(c))c.forEach(d=>{if(d==null||typeof d=="object")return;let u=String(d).trim();u&&s.add(u)});else if(typeof c!="object"){let d=String(c).trim();d&&s.add(d)}}if(i.inline)try{let d=await r.vault.cachedRead(a);wf.getFieldValues(d,t,{includeCodeBlocks:n}).forEach(p=>s.add(p))}catch{}}return Array.from(s).sort()},clearCache:t=>{hl.getInstance().clear(t)}}}var GW=x(()=>{TT();jw();AF()});function jW(r){return{entries:Array.from(r.entries()),dateFormats:L0(r)}}function YW(r,t){r.clear();for(let[e,n]of t.entries)r.set(e,n);cg(r,t.dateFormats)}var zn,Nf,BM=x(()=>{Su();Rd();YT();jT();sl();If();nt();Aw();aM();sW();HW();GW();zn=class zn{static GetApi(t,e,n,i){let o=async(a,l,c=!0)=>{let d=c?jW(n.variables):null;l&&Object.keys(l).forEach(u=>{n.variables.set(u,l[u])});try{let u=new Ai(t,e,n);return i&&(u.choiceChain=i),await u.formatFileContent(a)}finally{d&&YW(n.variables,d)}},s=async(a,l,c)=>{let d;try{d=e.getChoiceByName(a)}catch{d=void 0}if(!d){Me(new Error(`Choice named '${a}' not found`),"API executeChoice error");return}if(!Af(n,c?.date)){Me(new Error(`Could not parse date origin '${String(c?.date)}'`),"API executeChoice error");return}l&&Object.keys(l).forEach(p=>{n.variables.set(p,l[p])}),await n.execute(d,i);let u=n.consumeAbortSignal?.();if(n.variables.clear(),cg(n.variables,new Map),u)throw u};return{requestInputs:a=>oW(t,n,a),inputPrompt:(a,l,c,d)=>{let u=n?.promptProvider;return u?u.inputPrompt(a,l,c):zn.inputPrompt(t,a,l,c,d)},datePrompt:(a,l)=>{let c=n?.promptProvider;return c?c.datePrompt(a,l):zn.datePrompt(t,a,l)},wideInputPrompt:(a,l,c,d)=>{let u=n?.promptProvider;return u?u.wideInputPrompt(a,l,c):zn.wideInputPrompt(t,a,l,c,d)},yesNoPrompt:(a,l)=>{let c=n?.promptProvider;return c?c.yesNoPrompt(a,l):zn.yesNoPrompt(t,a,l)},infoDialog:(a,l)=>{let c=n?.promptProvider;return c?c.infoDialog(a,l):zn.infoDialog(t,a,l)},suggester:(a,l,c,d=!1,u)=>{let p=n?.promptProvider;return p?p.suggester(a,l,c,d):zn.suggester(t,a,l,c,d,u)},checkboxPrompt:(a,l,c)=>{let d=n?.promptProvider;return d?d.checkboxPrompt(a,l,c):zn.checkboxPrompt(t,a,l,c)},executeChoice:(...a)=>ZD(s(...a)),applyTemplateToActiveFile:async(a,l)=>{if(!a)throw new Error("applyTemplateToActiveFile requires a template path.");if(!Hc(a))throw new Error("applyTemplateToActiveFile only supports markdown templates. Canvas and base templates cannot be applied to a markdown note.");if(l?.mode!==void 0&&!hH(l.mode))throw new Error(`Invalid mode '${String(l.mode)}'. Valid modes: ${Dy.map(d=>d.id).join(", ")}.`);let c=jW(n.variables);try{return await Ly(t,e,{templatePath:a,mode:l?.mode,choiceExecutor:n,chain:i})}finally{YW(n.variables,c)}},format:o,ai:zW(t,e,n,o),utility:{getClipboard:async()=>await navigator.clipboard.readText(),setClipboard:async a=>await navigator.clipboard.writeText(a),getSelection:()=>qv(t),getSelectedText:()=>{let a=Un(t);return a?a.editor.somethingSelected()?a.editor.getSelection():(Me(new Error("No text selected"),"Could not get selected text"),""):(Me(new Error("No active Markdown editor"),"Could not get selected text"),"")}},date:{now:(a,l)=>Ra({format:a,offset:l}),tomorrow:a=>Ra({format:a,offset:1}),yesterday:a=>Ra({format:a,offset:-1})},fieldSuggestions:WW(t)}}};zn.inputPrompt=ia.inputPrompt,zn.datePrompt=ia.datePrompt,zn.wideInputPrompt=ia.wideInputPrompt,zn.yesNoPrompt=ia.yesNoPrompt,zn.infoDialog=ia.infoDialog,zn.suggester=ia.suggester,zn.checkboxPrompt=ia.checkboxPrompt;Nf=zn});function cie(r){return r!==null&&typeof r=="object"}function KW(r){return typeof r=="function"}async function QW(r,t){let{app:e,plugin:n,choiceName:i,params:o,executor:s,preloadedUserScripts:a,promptLabel:l}=t,c=mx(r),d=c===void 0?void 0:a.get(c);c!==void 0&&d!==void 0&&a.delete(c),d===void 0&&(d=await su(r,e));let u=d?.script;if(!u){S.logError(`failed to load user script ${r.path}.`);return}r.settings||(r.settings={});let p=d?.settings;p&&Pm(r.settings,p);async function m(g){let v=await $T(e,n,r,p);return{output:await g(o,v)}}async function h(g){if(KW(g))return m(g);if(cie(g)){if(Object.keys(g).length===0)throw new Error(`user script in macro for '${i}' is an empty object`);if(KW(g.entry))return m(g.entry);let v=Object.keys(g);try{let b=String(await Zi(s,{remote:y=>eo(y,{items:v.map(C=>({value:C,title:C})),placeholder:l,what:"the user-script member picker"}),headless:()=>{if(v.length===1)return Promise.resolve(v[0]);throw new de("This macro's user script exports multiple members and needs to ask which one to run, but this run is non-interactive. Reference a single member (e.g. myScript::start), or re-run with the ui flag.")},app:()=>It.Suggest(e,v,v,l)}));if(!Object.hasOwn(g,b))throw new Error(`This macro's user script does not export a member named "${b}".`);return await h(g[b])}catch(b){throw b instanceof at?b:Be(b)?new et("Input cancelled by user"):b}}switch(typeof g){case"bigint":case"boolean":case"number":case"string":return{output:g.toString()};case"object":return;default:S.logError(`user script in macro for '${i}' is invalid`)}}try{return await h(u)}catch(g){throw g instanceof at||Me(g,`Failed to run user script ${r.name} in "${i}"`),g}}var XW=x(()=>{au();lx();VF();ye();nt();ri();Sn();rr();Qi();_u();ku()});var Vf,UM=x(()=>{JF();Vf=class extends xf{}});function eG(r){if(!r)return!1;let t=r,e=t.getViewState?.();return!!t.pinned||!!e?.pinned||!!e?.state?.pinned}function I_(r){let t=r.workspace;return(t.rootSplit?t.getMostRecentLeaf?.(t.rootSplit):null)??t.getMostRecentLeaf?.()??null}function qM(r){return r.workspace.getActiveViewOfType(Wc.View)?.leaf??null}function die(r){let t=[];return r.workspace.iterateRootLeaves(e=>{t.includes(e)||t.push(e)}),t}function JW(r){return r.parent?.id??r.parent??null}function uie(r,t){let e=JW(t),n=r.filter(s=>s===t||eG(s)?!1:e===null||JW(s)!==e);if(n.length===0)return null;let i=r.indexOf(t);return(i===-1?r:[...r.slice(i+1),...r.slice(0,i)]).find(s=>n.includes(s))??n[0]}function pie(r){return r instanceof Wc.TFile?!0:typeof r=="object"&&r!==null&&"path"in r&&typeof r.path=="string"&&"extension"in r&&typeof r.extension=="string"}function mie(r,t,e,n){if(n&&(t==="tab"||t==="reuse")&&eG(n))return uie(die(r),n)??r.workspace.getLeaf("tab");switch(t){case"reuse":return r.workspace.getLeaf(!1);case"tab":return r.workspace.getLeaf("tab");case"split":return r.workspace.getLeaf("split",e);case"window":return r.workspace.getLeaf("window");case"left-sidebar":return r.workspace.getLeftLeaf(!0);case"right-sidebar":return r.workspace.getRightLeaf(!0);default:return r.workspace.getLeaf("tab")}}async function P_(r,t,e={}){let{location:n="tab",direction:i="vertical",mode:o,focus:s=!0,eState:a,originLeaf:l}=e,c=typeof t=="string"?r.vault.getAbstractFileByPath(t):t;if(!pie(c)){let m=typeof t=="string"?t:t.path;throw new Error(`File not found: ${m}`)}let d=l??I_(r),u=s?null:qM(r),p=mie(r,n,i,d);if(!p)throw new Error("Could not obtain a workspace leaf.");if(u&&qM(r)!==u&&r.workspace.setActiveLeaf(u,{focus:!1}),s?await p.openFile(c):await p.openFile(c,{active:!1}),o&&o!=="default"&&!(typeof o=="object"&&o.mode==="default")){let m=p.getViewState(),h={...m.state??{}};o==="preview"||typeof o=="object"&&o.mode==="preview"?(h.mode="preview",delete h.source):o==="source"?(h.mode="source",h.source=!0):o==="live"||o==="live-preview"?(h.mode="source",h.source=!1):typeof o=="object"&&o.mode==="source"&&(h.mode="source",h.source=o.source),await p.setViewState({...m,...!s&&{active:!1},state:{...h,...a}})}return s&&r.workspace.setActiveLeaf(p,{focus:!0}),p}function ZW(r){return(0,Wc.normalizePath)(r).replace(/\/{2,}/g,"/").replace(/^\/+/,"")}function fie(r,t){return ZW(r)===ZW(t)}function tG(r,t,e=!0){let n,i=qM(r);return r.workspace.iterateRootLeaves(o=>{if(n&&n===i)return;let s=o.view;if(s instanceof Wc.FileView&&s.file&&(s.file===t||fie(t.path,s.file.path))){n=o;return}}),n!==void 0?(e&&r.workspace.setActiveLeaf(n,{focus:!0}),n):null}var Wc,$_=x(()=>{Wc=require("obsidian")});async function nG(r,t){return r.mode==="script"?await t.evaluateScriptCondition(r):hie(r,t.variables)}function hie(r,t){let e=r.variableName?.trim();if(!e)return S.logWarning("Conditional command skipped: No variable name configured."),!1;if(!(e in t))return r.operator==="isFalsy";let n=t[e];switch(r.operator){case"isTruthy":return!!n;case"isFalsy":return!n}if(Kl(r.operator)){let i=R0(r);return i===void 0?(S.logWarning(`Conditional command: Operator '${r.operator}' requires a comparison value.`),!1):r.operator==="contains"?rG(n,i,r):r.operator==="notContains"?!rG(n,i,r):gie(n,i,r)}return!1}function rG(r,t,e){if(r==null)return!1;if(typeof t=="string"&&t.length===0)return S.logWarning("Conditional command: 'contains' operator requires a non-empty comparison value."),!1;if(Array.isArray(r))return r.map(o=>rA(o,e.valueType)).some(o=>o===t);if(typeof r=="string")return r.includes(Os(t));if(typeof r=="number"&&typeof t=="number")return r===t;let n=Os(r),i=Os(t);return typeof n=="string"&&n.includes(i)}function gie(r,t,e){let n=rA(r,e.valueType);switch(e.operator){case"equals":return n===t;case"notEquals":return n!==t;case"lessThan":return F_(n,t,(i,o)=>i<o);case"lessThanOrEqual":return F_(n,t,(i,o)=>i<=o);case"greaterThan":return F_(n,t,(i,o)=>i>o);case"greaterThanOrEqual":return F_(n,t,(i,o)=>i>=o);default:return!1}}function F_(r,t,e){let n=Number(r),i=Number(t);return Number.isNaN(n)||Number.isNaN(i)?(S.logWarning("Conditional command numeric comparison failed: non-numeric value encountered."),!1):e(n,i)}var iG=x(()=>{ye();Xl()});function oG(r,t=void 0){return r==="horizontal"?"horizontal":r==="vertical"?"vertical":t}function Gc(r,t,e){return e?{location:r,direction:e,focus:t,mode:"default"}:{location:r,focus:t,mode:"default"}}function sG(r){let t=r.focus??!0;if(r.location)switch(r.location){case"reuse":return Gc("reuse",t);case"tab":return Gc("tab",t);case"split":return Gc("split",t,oG(r.direction,"vertical"));case"window":return Gc("window",t);case"left-sidebar":return Gc("left-sidebar",t);case"right-sidebar":return Gc("right-sidebar",t);default:break}let e=r.openInNewTab??!1,n=oG(r.direction);return e?Gc("split",t,n??"vertical"):Gc("reuse",t)}var aG=x(()=>{qx()});function lG(r){let t={hasOwnProperty:e=>r.has(e)};return new Proxy(t,{get(e,n){if(n==="hasOwnProperty")return t.hasOwnProperty;if(typeof n=="string")return r.get(n)},set(e,n,i){return typeof n!="string"||r.set(n,i),!0},deleteProperty(e,n){return typeof n!="string"||r.delete(n),!0},has(e,n){return typeof n=="string"&&r.has(n)},ownKeys(){return Array.from(r.keys())},getOwnPropertyDescriptor(e,n){if(n==="hasOwnProperty")return{value:t.hasOwnProperty,writable:!0,configurable:!0,enumerable:!1};if(!(typeof n!="string"||!r.has(n)))return{value:r.get(n),writable:!0,configurable:!0,enumerable:!0}}})}var cG=x(()=>{});function dG(r,t="command"){if(typeof r!="string"||!r.trim())return`the saved entry has no ${t} type, so QuickAdd cannot tell what it was meant to do. It is in .obsidian/plugins/quickadd/data.json.`;let e=t==="command"?yie.get(r):void 0;return e||`QuickAdd does not recognise the ${t} type '${r}'. It can come from a newer version of QuickAdd, an imported package, or a hand-edited .obsidian/plugins/quickadd/data.json.`}function uG(r){return`${r.scriptPath}::${r.exportName??"default"}`}var vie,pG,yie,ta,Sy=x(()=>{cH();MT();HT();sM();vie=lY(require("obsidian"));ye();nt();er();BM();Rd();XW();UM();ss();au();Ki();RP();MP();OP();DP();LP();NP();VP();BP();UP();qP();Pp();Su();$_();pG=require("obsidian");ri();iG();ky();aG();cG();Gr();a_();l_();Rf();yie=new Map([["InfiniteAIAssistant",'The "Infinite AI Assistant" command type was removed - no released version could ever run one. Delete the step from the macro. For chunked AI prompts, use quickAddApi.ai.chunkedPrompt() in a user script.']]);ta=class extends Vf{constructor(e,n,i,o,s,a,l,c=null,d=[i]){super(e);this.originLeaf=c;this.chain=d;this.conditionalScriptCache=new Map;this.choice=i,this.plugin=n,this.macro=i?.macro,this.choiceExecutor=o,this.preloadedUserScripts=a??new Map,this.promptLabel=l;let u=this.initSharedVariables(o,s);this.choiceExecutor.variables=u,this.params=this.buildParams(e,n,o,u)}buildParams(e,n,i,o){let s=lG(o),a={app:e,quickAddApi:Nf.GetApi(e,n,i,this.chain),obsidian:vie,abort:l=>{throw new at(l)}};return Object.defineProperty(a,"variables",{get:()=>s,set:l=>{if(l===o||l===s)return;let c=l instanceof Map?Array.from(l.entries()).filter(([d])=>typeof d=="string"):l&&typeof l=="object"?Object.entries(l):null;c&&(o.clear(),cg(o,new Map),c?.forEach(([d,u])=>o.set(d,u)))},enumerable:!0,configurable:!1}),a}initSharedVariables(e,n){let i=e.variables;return n?(i&&n!==i&&i.forEach((o,s)=>{n.has(s)||n.set(s,o)}),n):i??new Map}async run(){if(Wt(this.macro?.commands))throw new Error(`Could not read the commands for macro '${this.choice.name}'. The saved value is not a list of commands - QuickAdd has not changed it. It is in .obsidian/plugins/quickadd/data.json.`);let e=Mt(this.macro?.commands);if(e.length===0){Lv(this.macro?.commands)||S.logError(`No commands in the macro for choice '${this.choice.name}'`);return}this.previousStep=void 0,await this.executeCommands(e)}getOutput(){return this.output}async executeCommands(e){try{for(let[n,i]of e.entries()){if(!i)continue;let o=i.type==="Choice"||i.type==="NestedChoice"?Ff(i,l=>zc(this.plugin,l)):null,s=uH(this.previousStep,i,l=>zc(this.plugin,l));s&&WT(`templater-rerun:${this.choice.id}:${i.id}`,`Macro '${this.choice.name}' runs "Templater: Replace templates in the active file" after '${s}'. QuickAdd already runs Templater in the notes it creates and captures, so this step is deprecated and can run template code twice. Remove it from the macro.`),i.type!=="Wait"&&i.type!=="Conditional"&&(this.previousStep=i);let a=o?.collect.kind==="scanChoice"&&hM(o.collect.choice,this.choiceExecutor.variables.get("value"));await Yy(this.choiceExecutor,i.id,async()=>{switch(i.type){case"Obsidian":this.executeObsidianCommand(i);break;case"UserScript":await this.executeUserScript(i);break;case"Choice":await this.executeChoice(i);break;case"Wait":await Ow(i.time);break;case"NestedChoice":await this.executeNestedChoice(i);break;case"EditorCommand":await this.executeEditorCommand(i);break;case"AIAssistant":await this.executeAIAssistant(i);break;case"OpenFile":await this.executeOpenFile(i);break;case"Conditional":await this.executeConditional(i);break;default:{let l=i.type;this.reportUnrunnableCommand(i,dG(l));break}}}),a&&await this.choiceExecutor.prepareMacroInputs(this.choice,e.slice(n+1))}}catch(n){if(Dc(n,{logPrefix:"Macro execution aborted",noticePrefix:"Macro execution aborted",defaultReason:"Macro execution aborted"})){this.choiceExecutor.signalAbort?.(n);return}throw n}}reportUnrunnableCommand(e,n){let i=typeof e?.name=="string"&&e.name.trim()?`'${e.name}'`:"an unnamed command";S.logError(`Skipped ${i} in the macro for '${this.choice.name}': ${n} QuickAdd did not stop the macro, so its result may be incomplete.`)}async executeUserScript(e){let n=await QW(e,{app:this.app,plugin:this.plugin,choiceName:this.choice.name,params:this.params,executor:this.choiceExecutor,preloadedUserScripts:this.preloadedUserScripts,promptLabel:this.promptLabel});n&&(this.output=n.output)}executeObsidianCommand(e){let n=this.app.commands.commands;if(n&&!n[e.commandId]){S.logError(`Obsidian command '${e.name}' is no longer available.`);return}I2(this.chain,()=>this.app.commands.executeCommandById(e.commandId))}async executeChoice(e){let n;try{n=this.plugin.getChoiceById(e.choiceId)}catch(o){let s=o instanceof Error?o.message:String(o);if(!/not found/i.test(s))throw o;S.logError(`choice '${e.name}' could not be found.`);return}await this.choiceExecutor.execute(n,this.chain);let i=this.choiceExecutor.consumeAbortSignal?.();if(i)throw i}async executeNestedChoice(e){let n=e.choice;if(!n){S.logError(`choice in ${e.name} is invalid`);return}await this.choiceExecutor.execute(n,this.chain);let i=this.choiceExecutor.consumeAbortSignal?.();if(i)throw i}async executeEditorCommand(e){switch(e.editorCommandType){case"Cut":await qm.run(this.app);break;case"Copy":await Um.run(this.app);break;case"Paste":await zm.run(this.app);break;case"Paste with format":await Hm.run(this.app);break;case"Select active line":Wm.run(this.app);break;case"Select link on active line":Gm.run(this.app);break;case"Move cursor to file start":jm.run(this.app);break;case"Move cursor to file end":Ym.run(this.app);break;case"Move cursor to line start":Km.run(this.app);break;case"Move cursor to line end":Qm.run(this.app);break;default:{let n=e.editorCommandType;this.reportUnrunnableCommand(e,dG(n,"editor command"))}}}async executeAIAssistant(e){return aH(this.app,this.choice,this.choiceExecutor,this.chain,e,()=>this.pickModelInteractively())}async pickModelInteractively(){return lH(this.app,this.choiceExecutor)}async executeConditional(e){let n=await nG(e.condition,{variables:this.params.variables,evaluateScriptCondition:async s=>await this.evaluateScriptCondition(s)}),i=n?e.thenCommands:e.elseCommands;if(Wt(i))throw new Error(`Could not read the ${n?"then":"else"} commands for '${e.name}'. The saved value is not a list of commands - QuickAdd has not changed it. It is in .obsidian/plugins/quickadd/data.json.`);if(!Array.isArray(i)||i.length===0)return;await this.executeCommands(i);let o=this.choiceExecutor.consumeAbortSignal?.();if(o)throw o}async runSubset(e){e?.length&&await this.executeCommands(e)}setOutput(e){this.output=e}async evaluateScriptCondition(e){let n=uG(e),i=this.conditionalScriptCache.get(n);if(!i){if(i=await this.loadConditionalScript(e),!i)return!1;this.conditionalScriptCache.set(n,i)}let o;try{o=await i()}catch(s){throw Me(s,`Failed to evaluate conditional script '${e.scriptPath}'.`),s}return typeof o!="boolean"?(S.logWarning(`Conditional script '${e.scriptPath}' must return a boolean result.`),!1):o}async loadConditionalScript(e){try{let n=await Nv(this.buildConditionalUserScript(e),this.app);return n==null?void 0:typeof n=="function"?async()=>await n(this.params):async()=>n}catch(n){throw Me(n,`Failed to load conditional script '${e.scriptPath}'.`),n}}buildConditionalUserScript(e){return{id:`conditional-script-${uG(e)}`,name:e.exportName?`${e.scriptPath}::${e.exportName}`:e.scriptPath,type:"UserScript",path:e.scriptPath,settings:{}}}async executeOpenFile(e){try{let n=new Ai(this.app,Wr(),this.choiceExecutor);n.setPromptRunContext({choiceName:this.choice?.name,draftScopeId:`${this.choice?.id??"macro"}#openFile:${e.id}`}),n.choiceChain=this.chain;let o=(await n.formatFileName(e.filePath,"filePath")).replace(/\\/g,"/"),s=o.split("/");if(s.some((d,u)=>d===".."||d===""&&u!==0&&u!==s.length-1)){S.logError(`OpenFile: Path traversal not allowed in '${o}'`);return}let l=this.app.vault.getAbstractFileByPath(o);if(!l||!(l instanceof pG.TFile)){S.logError(`OpenFile: '${o}' does not exist or is not a file`);return}let c=sG(e);await P_(this.app,l,{...c,originLeaf:this.originLeaf})}catch(n){S.logError(`OpenFile: Failed to open file '${e.filePath}': ${n.message}`)}}}});var joe={};cb(joe,{default:()=>ok});module.exports=cY(joe);var Gj=require("obsidian");var uy=require("obsidian");var bR;typeof window<"u"&&((bR=window.__svelte??(window.__svelte={})).v??(bR.v=new Set)).add("5");var fa={};var Rt=Symbol("uninitialized"),no=Symbol("filename");var db="http://www.w3.org/1999/xhtml";var wR=globalThis.process?.env?.NODE_ENV,j=wR&&!wR.toLowerCase().startsWith("prod");var io=Array.isArray,CR=Array.prototype.indexOf,_l=Array.prototype.includes,Du=Array.from,hk=Object.keys,jr=Object.defineProperty,di=Object.getOwnPropertyDescriptor,ub=Object.getOwnPropertyDescriptors,pb=Object.prototype,xR=Array.prototype,kl=Object.getPrototypeOf,gk=Object.isExtensible;var $t=()=>{};function mb(r){for(var t=0;t<r.length;t++)r[t]()}function fb(){var r,t,e=new Promise((n,i)=>{r=n,t=i});return{promise:e,resolve:r,reject:t}}function vk(r,t){if(Array.isArray(r))return r;if(t===void 0||!(Symbol.iterator in r))return Array.from(r);let e=[];for(let n of r)if(e.push(n),e.length===t)break;return e}var yn=Symbol("$state"),hb=Symbol("component"),Kf=Symbol("legacy props"),ER=Symbol(""),gb=Symbol("proxy path"),vb=Symbol("attributes"),Qf=Symbol("class"),Xf=Symbol("style"),Jf=Symbol("text"),Sl=Symbol("form reset"),yk=Symbol("hmr anchor"),ha=new class extends Error{constructor(){super(...arguments);fe(this,"name","StaleReactionError");fe(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}},yb=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml");var Kc=3,Ii=8;var ga="font-weight: bold",va="font-weight: normal";function TR(r){j?console.warn(`%c[svelte] await_reactivity_loss
|
||
%cDetected reactivity loss when reading \`${r}\`. This happens when state is read in an async function after an earlier \`await\`
|
||
https://svelte.dev/e/await_reactivity_loss`,ga,va):console.warn("https://svelte.dev/e/await_reactivity_loss")}function _R(r,t){j?console.warn(`%c[svelte] await_waterfall
|
||
%cAn async derived, \`${r}\` (${t}) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app
|
||
https://svelte.dev/e/await_waterfall`,ga,va):console.warn("https://svelte.dev/e/await_waterfall")}function kR(){j?console.warn(`%c[svelte] derived_inert
|
||
%cReading a derived belonging to a now-destroyed effect may result in stale values
|
||
https://svelte.dev/e/derived_inert`,ga,va):console.warn("https://svelte.dev/e/derived_inert")}function SR(r,t,e){j?console.warn(`%c[svelte] hydration_attribute_changed
|
||
%cThe \`${r}\` attribute on \`${t}\` changed its value between server and client renders. The client value, \`${e}\`, will be ignored in favour of the server value
|
||
https://svelte.dev/e/hydration_attribute_changed`,ga,va):console.warn("https://svelte.dev/e/hydration_attribute_changed")}function Qc(r){j?console.warn(`%c[svelte] hydration_mismatch
|
||
%c${r?`Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${r}`:"Hydration failed because the initial UI does not match what was rendered on the server"}
|
||
https://svelte.dev/e/hydration_mismatch`,ga,va):console.warn("https://svelte.dev/e/hydration_mismatch")}function AR(){j?console.warn(`%c[svelte] lifecycle_double_unmount
|
||
%cTried to unmount a component that was not mounted
|
||
https://svelte.dev/e/lifecycle_double_unmount`,ga,va):console.warn("https://svelte.dev/e/lifecycle_double_unmount")}function IR(){j?console.warn("%c[svelte] select_multiple_invalid_value\n%cThe `value` property of a `<select multiple>` element should be an array, but it received a non-array value. The selection will be kept as is.\nhttps://svelte.dev/e/select_multiple_invalid_value",ga,va):console.warn("https://svelte.dev/e/select_multiple_invalid_value")}function bb(r){j?console.warn(`%c[svelte] state_proxy_equality_mismatch
|
||
%cReactive \`$state(...)\` proxies and the values they proxy have different identities. Because of this, comparisons with \`${r}\` will produce unexpected results
|
||
https://svelte.dev/e/state_proxy_equality_mismatch`,ga,va):console.warn("https://svelte.dev/e/state_proxy_equality_mismatch")}function PR(){j?console.warn("%c[svelte] svelte_boundary_reset_noop\n%cA `<svelte:boundary>` `reset` function only resets the boundary the first time it is called\nhttps://svelte.dev/e/svelte_boundary_reset_noop",ga,va):console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}var xe=!1;function Pr(r){xe=r}var De;function Tt(r){if(r===null)throw Qc(),fa;return De=r}function Yr(){return Tt(wn(De))}function $(r){if(xe){if(wn(De)!==null)throw Qc(),fa;De=r}}function Xt(r=1){if(xe){for(var t=r,e=De;t--;)e=wn(e);De=e}}function fs(r=!0){for(var t=0,e=De;;){if(e.nodeType===Ii){var n=e.data;if(n==="]"){if(t===0)return e;t-=1}else(n==="["||n==="[!"||n[0]==="["&&!isNaN(Number(n.slice(1))))&&(t+=1)}var i=wn(e);r&&e.remove(),e=i}}function eh(r){if(!r||r.nodeType!==Ii)throw Qc(),fa;return r.data}function wb(r){return r===this.v}function Cb(r,t){return r!=r?t==t:r!==t||r!==null&&typeof r=="object"||typeof r=="function"}function xb(r){return!Cb(r,this.v)}function $R(r){if(j){let t=new Error(`invariant_violation
|
||
An invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app \u2014 please open an issue at https://github.com/sveltejs/svelte, citing the following message: "${r}"
|
||
https://svelte.dev/e/invariant_violation`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/invariant_violation")}function th(r){if(j){let t=new Error(`lifecycle_outside_component
|
||
\`${r}(...)\` can only be used during component initialisation
|
||
https://svelte.dev/e/lifecycle_outside_component`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function MR(){if(j){let r=new Error("async_derived_orphan\nCannot create a `$derived(...)` with an `await` expression outside of an effect tree\nhttps://svelte.dev/e/async_derived_orphan");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/async_derived_orphan")}function bk(){if(j){let r=new Error("bind_invalid_checkbox_value\nUsing `bind:value` together with a checkbox input is not allowed. Use `bind:checked` instead\nhttps://svelte.dev/e/bind_invalid_checkbox_value");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/bind_invalid_checkbox_value")}function RR(){if(j){let r=new Error(`derived_references_self
|
||
A derived value cannot reference itself recursively
|
||
https://svelte.dev/e/derived_references_self`);throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/derived_references_self")}function wk(r,t,e){if(j){let n=new Error(`each_key_duplicate
|
||
${e?`Keyed each block has duplicate key \`${e}\` at indexes ${r} and ${t}`:`Keyed each block has duplicate key at indexes ${r} and ${t}`}
|
||
https://svelte.dev/e/each_key_duplicate`);throw n.name="Svelte error",n}else throw new Error("https://svelte.dev/e/each_key_duplicate")}function OR(r,t,e){if(j){let n=new Error(`each_key_volatile
|
||
Keyed each block has key that is not idempotent \u2014 the key for item at index ${r} was \`${t}\` but is now \`${e}\`. Keys must be the same each time for a given item
|
||
https://svelte.dev/e/each_key_volatile`);throw n.name="Svelte error",n}else throw new Error("https://svelte.dev/e/each_key_volatile")}function DR(r){if(j){let t=new Error(`effect_in_teardown
|
||
\`${r}\` cannot be used inside an effect cleanup function
|
||
https://svelte.dev/e/effect_in_teardown`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/effect_in_teardown")}function LR(){if(j){let r=new Error("effect_in_unowned_derived\nEffect cannot be created inside a `$derived` value that was not itself created inside an effect\nhttps://svelte.dev/e/effect_in_unowned_derived");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function NR(r){if(j){let t=new Error(`effect_orphan
|
||
\`${r}\` can only be used inside an effect (e.g. during component initialisation)
|
||
https://svelte.dev/e/effect_orphan`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/effect_orphan")}function VR(){if(j){let r=new Error(`effect_update_depth_exceeded
|
||
Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state
|
||
https://svelte.dev/e/effect_update_depth_exceeded`);throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function BR(){if(j){let r=new Error(`hydration_failed
|
||
Failed to hydrate the application
|
||
https://svelte.dev/e/hydration_failed`);throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/hydration_failed")}function UR(){if(j){let r=new Error("invalid_snippet\nCould not `{@render}` snippet due to the expression being `null` or `undefined`. Consider using optional chaining `{@render snippet?.()}`\nhttps://svelte.dev/e/invalid_snippet");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/invalid_snippet")}function qR(r){if(j){let t=new Error(`props_invalid_value
|
||
Cannot do \`bind:${r}={undefined}\` when \`${r}\` has a fallback value
|
||
https://svelte.dev/e/props_invalid_value`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/props_invalid_value")}function zR(r){if(j){let t=new Error(`rune_outside_svelte
|
||
The \`${r}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files
|
||
https://svelte.dev/e/rune_outside_svelte`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/rune_outside_svelte")}function HR(){if(j){let r=new Error("state_descriptors_fixed\nProperty descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`.\nhttps://svelte.dev/e/state_descriptors_fixed");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function WR(){if(j){let r=new Error("state_prototype_fixed\nCannot set prototype of `$state` object\nhttps://svelte.dev/e/state_prototype_fixed");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/state_prototype_fixed")}function GR(){if(j){let r=new Error("state_unsafe_mutation\nUpdating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state`\nhttps://svelte.dev/e/state_unsafe_mutation");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function jR(){if(j){let r=new Error("svelte_boundary_reset_onerror\nA `<svelte:boundary>` `reset` function cannot be called while an error is still being handled\nhttps://svelte.dev/e/svelte_boundary_reset_onerror");throw r.name="Svelte error",r}else throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}var pr=!1,ya=!1,No=!1;var pY="font-weight: bold",mY="font-weight: normal";function Ck(r){j?console.warn(`%c[svelte] state_snapshot_uncloneable
|
||
%c${r?`The following properties cannot be cloned with \`$state.snapshot\` \u2014 the return value contains the originals:
|
||
|
||
${r}`:"Value cannot be cloned with `$state.snapshot` \u2014 the original value was returned"}
|
||
https://svelte.dev/e/state_snapshot_uncloneable`,pY,mY):console.warn("https://svelte.dev/e/state_snapshot_uncloneable")}var fY=[];function Xc(r,t=!1,e=!1){if(j&&!t){let n=[],i=rh(r,new Map,"",n,null,e);if(n.length===1&&n[0]==="")Ck();else if(n.length>0){let o=n.length>10?n.slice(0,7):n.slice(0,10),s=n.length-o.length,a=o.map(l=>`- <value>${l}`).join(`
|
||
`);s>0&&(a+=`
|
||
- ...and ${s} more`),Ck(a)}return i}return rh(r,new Map,"",fY,null,e)}function rh(r,t,e,n,i=null,o=!1){if(typeof r=="object"&&r!==null){var s=t.get(r);if(s!==void 0)return s;if(r instanceof Map)return new Map(r);if(r instanceof Set)return new Set(r);if(io(r)){var a=Array(r.length);t.set(r,a),i!==null&&t.set(i,a);for(var l=0;l<r.length;l+=1){var c=r[l];l in r&&(a[l]=rh(c,t,j?`${e}[${l}]`:e,n,null,o))}return a}if(kl(r)===pb){a={},t.set(r,a),i!==null&&t.set(i,a);for(var d of Object.keys(r))a[d]=rh(r[d],t,j?`${e}.${d}`:e,n,null,o);return a}if(r instanceof Date)return r.getTime(),structuredClone(r);if(typeof r.toJSON=="function"&&!o)return rh(r.toJSON(),t,j?`${e}.toJSON()`:e,n,r)}if(r instanceof EventTarget)return r;try{return structuredClone(r)}catch{return j&&n.push(e),r}}var nh=null;function Pn(r,t){return r.label=t,Eb(r.v,t),r}function Eb(r,t){return r?.[gb]?.(t),r}function Vo(r){let t=new Error,e=hY();return e.length===0?null:(e.unshift(`
|
||
`),jr(t,"stack",{value:e.join(`
|
||
`)}),jr(t,"name",{value:r}),t)}function hY(){let r=Error.stackTraceLimit;Error.stackTraceLimit=1/0;let t=new Error().stack;if(Error.stackTraceLimit=r,!t)return[];let e=t.split(`
|
||
`),n=[];for(let i=0;i<e.length;i++){let o=e[i],s=o.replaceAll("\\","/");if(o.trim()!=="Error"){if(o.includes("validate_each_keys"))return[];s.includes("svelte/src/internal")||s.includes("node_modules/.vite")||n.push(o)}}return n}function KR(r,t){if(!j)throw new Error("invariant(...) was not guarded by if (DEV)");r||$R(t)}var rt=null;function ba(r){rt=r}var hs=null;function Vu(r){hs=r}var Bo=null;function Tb(r){Bo=r}function ie(r,t=!1,e){rt={p:rt,i:!1,c:null,e:null,s:r,x:null,r:we,l:ya&&!t?{s:null,u:null,$:[]}:null},j&&(rt.function=e,Bo=e)}function oe(r){var t=rt,e=t.e;if(e!==null){t.e=null;for(var n of e)xk(n)}return r!==void 0&&(t.x=r),t.i=!0,rt=t.p,j&&(Bo=rt?.function??null),ih(r)}function ih(r={}){return jr(r,hb,{value:!0}),r}function Uo(){return!ya||rt!==null&&rt.l===null}var Jc=[];function QR(){var r=Jc;Jc=[],mb(r)}function wr(r){if(Jc.length===0&&!Zc){var t=Jc;queueMicrotask(()=>{t===Jc&&QR()})}Jc.push(r)}function XR(){for(;Jc.length>0;)QR()}var gY=-7169;function _t(r,t){r.f=r.f&gY|t}function Bu(r){(r.f&512)!==0||r.deps===null?_t(r,1024):_t(r,4096)}function JR(r){if(r!==null)for(let t of r)(t.f&2)===0||(t.f&65536)===0||(t.f^=65536,JR(t.deps))}function _b(r,t,e){(r.f&2048)!==0?t.add(r):(r.f&4096)!==0&&e.add(r),JR(r.deps),_t(r,1024)}var ZR=!1,kb=!1;function Ek(r){var t=kb;try{return kb=!1,[r(),kb]}finally{kb=t}}function rd(r){xe&&Xr(r)!==null&&qu(r)}var eO=!1;function Sb(){eO||(eO=!0,document.addEventListener("reset",r=>{Promise.resolve().then(()=>{if(!r.defaultPrevented)for(let t of r.target.elements)t[Sl]?.()})},{capture:!0}))}function ao(r){var t=Pe,e=we;Mr(null),Rr(null);try{return r()}finally{Mr(t),Rr(e)}}function Ab(r,t,e,n=e){r.addEventListener(t,()=>ao(e));let i=r[Sl];i?r[Sl]=()=>{i(),n(!0)}:r[Sl]=()=>n(!0),Sb()}function Ib(r,t,e,n){let i=Uo()?Il:nd;var o=r.filter(m=>!m.settled),s=t.map(i);if(j&&s.forEach((m,h)=>{m.label=t[h].toString().replace("() => ","").replaceAll("$.eager(() => ","$state.eager(").replace(/\$\.get\((.+?)\)/g,(g,v)=>v)}),e.length===0&&o.length===0){n(s);return}var a=we,l=tO(),c=o.length===1?o[0].promise:o.length>1?Promise.all(o.map(m=>m.promise)):null;function d(m){if((a.f&16384)===0){l();try{n([...s,...m])}catch(h){pi(h,a)}zu()}}var u=Tk();if(e.length===0){c.then(()=>d([])).finally(u);return}function p(){Promise.all(e.map(m=>kk(m))).then(d).catch(m=>pi(m,a)).finally(u)}c?c.then(()=>{l(),p(),zu()}):p()}function tO(){var r=we,t=Pe,e=rt,n=_e;if(j)var i=hs;return function(s=!0){Rr(r),Mr(t),ba(e),s&&(r.f&16384)===0&&(n?.activate(),n?.apply()),j&&(_k(null),Vu(i))}}var yY=!1;function zu(r=!0){yY=!1,Rr(null),Mr(null),ba(null),r&&_e?.deactivate(),j&&(_k(null),Vu(null))}function Tk(){var r=we,t=r.b,e=_e,n=!!t?.is_rendered();return t?.update_pending_count(1,e),e.increment(n,r),()=>{t?.update_pending_count(-1,e),e.decrement(n,r)}}var mi=null;function _k(r){mi=r}var sh=new Set;function Il(r){var t=2050;we!==null&&(we.f|=524288);let e={ctx:rt,deps:null,effects:null,equals:wb,f:t,fn:r,reactions:null,rv:0,v:Rt,wv:0,parent:we,ac:null};return j&&No&&(e.created=Vo("created at")),e}var Hu=Symbol("obsolete");function kk(r,t,e){let n=we;n===null&&MR();var i=void 0,o=Mn(Rt);j&&(o.label=t??r.toString());var s=!Pe,a=new Set;return iO(()=>{var l=we;j&&(mi={effect:l,effect_deps:new Set,warned:!1});var c=fb();i=c.promise;try{Promise.resolve(r()).then(c.resolve,m=>{m!==ha&&c.reject(m)}).finally(zu)}catch(m){c.reject(m),zu()}if(j){if(mi){if(l.deps!==null)for(let m=0;m<Wn;m+=1)mi.effect_deps.add(l.deps[m]);if(Jr!==null)for(let m=0;m<Jr.length;m+=1)mi.effect_deps.add(Jr[m])}mi=null}var d=_e;if(s){if((l.f&32768)!==0)var u=Tk();if(n.b?.is_rendered())d.async_deriveds.get(l)?.reject(Hu);else for(let m of a.values())m.reject(Hu);a.add(c),d.async_deriveds.set(l,c)}let p=(m,h=void 0)=>{j&&(mi=null),u?.(),a.delete(c),h!==Hu&&(d.activate(),h?(o.f|=8388608,zo(o,h)):((o.f&8388608)!==0&&(o.f^=8388608),j&&e!==void 0&&!o.equals(m)&&(sh.add(o),setTimeout(()=>{sh.has(o)&&(l.f&16384)===0&&(_R(o.label,e),sh.delete(o))})),zo(o,m)),d.deactivate())};c.promise.then(p,m=>p(null,m||"unknown"))}),Qr(()=>{for(let l of a)l.reject(Hu)}),j&&(o.f|=4194304),new Promise(l=>{function c(d){function u(){d===i?l(o):c(i)}d.then(u,u)}c(i)})}function k(r){let t=Il(r);return pr||Fb(t),t}function nd(r){let t=Il(r);return t.equals=xb,t}function rO(r){var t=r.effects;if(t!==null){r.effects=null;for(var e=0;e<t.length;e+=1)sr(t[e])}}var Sk=[];function ah(r){var t,e=we,n=r.parent;if(!Pi&&n!==null&&r.v!==Rt&&(n.f&24576)!==0)return kR(),r.v;if(Rr(n),j){let i=id;Pb(new Set);try{_l.call(Sk,r)&&RR(),Sk.push(r),r.f&=-65537,rO(r),t=$b(r)}finally{Rr(e),Pb(i),Sk.pop()}}else try{r.f&=-65537,rO(r),t=$b(r)}finally{Rr(e)}return t}function Ak(r){var t=ah(r);if(!r.equals(t)&&(r.wv=Wu(),(!_e?.is_fork||r.deps===null)&&(_e!==null?(_e.capture(r,t,!0),gs?.capture(r,t,!0)):r.v=t,r.deps===null))){_t(r,1024);return}Pi||(Zr!==null?(Al()||_e?.is_fork)&&Zr.set(r,t):Bu(r))}function nO(r){if(r.effects!==null)for(let t of r.effects)(t.teardown||t.ac)&&(t.teardown?.(),t.ac!==null&&ao(()=>{t.ac.abort(ha),t.ac=null}),t.fn!==null&&(t.teardown=$t),od(t,0),lh(t))}function Ik(r){if(r.effects!==null)for(let t of r.effects)t.teardown&&t.fn!==null&&vs(t)}var Mb=null,Gu=null,_e=null,gs=null,Zr=null,Fk=null,Zc=!1,Pk=!1,sd=null,uh=null,oO=0,$k=new Set,CY=1,Yu,xa,Ea,Ku,Qu,Xu,Ta,Ju,Gn,ph,_a,Ho,ys,Zu,Pl,wt,Mk,ch,Rk,aO,lO,ju,cO,dh,Rb=class Rb{constructor(){qe(this,wt);fe(this,"id",CY++);qe(this,Yu,!1);fe(this,"linked",!0);qe(this,xa,null);qe(this,Ea,null);fe(this,"async_deriveds",new Map);fe(this,"current",new Map);fe(this,"previous",new Map);qe(this,Ku,new Set);qe(this,Qu,new Set);qe(this,Xu,0);qe(this,Ta,new Map);qe(this,Ju,null);qe(this,Gn,[]);qe(this,ph,[]);qe(this,_a,new Set);qe(this,Ho,new Set);qe(this,ys,new Map);qe(this,Zu,new Set);fe(this,"is_fork",!1);qe(this,Pl,!1);Gu===null?Mb=Gu=this:(Oe(Gu,Ea,this),Oe(this,xa,Gu)),Gu=this}skip_effect(t){L(this,ys).has(t)||L(this,ys).set(t,{d:[],m:[]}),L(this,Zu).delete(t)}unskip_effect(t,e=n=>this.schedule(n)){var n=L(this,ys).get(t);if(n){L(this,ys).delete(t);for(var i of n.d)_t(i,2048),e(i);for(i of n.m)_t(i,4096),e(i)}L(this,Zu).add(t)}capture(t,e,n=!1){t.v!==Rt&&!this.previous.has(t)&&this.previous.set(t,t.v),(t.f&8388608)===0&&(this.current.set(t,[e,n]),Zr?.set(t,e)),this.is_fork||(t.v=e)}activate(){_e=this}deactivate(){_e=null,Zr=null}flush(){try{j&&$k.clear(),Pk=!0,_e=this,tt(this,wt,ch).call(this)}finally{if(oO=0,Fk=null,sd=null,uh=null,Pk=!1,_e=null,Zr=null,co.clear(),j)for(let t of $k)t.updated=null}}discard(){for(let t of L(this,Qu))t(this);L(this,Qu).clear();for(let t of this.async_deriveds.values())t.reject(Hu);tt(this,wt,dh).call(this),L(this,Ju)?.resolve()}register_created_effect(t){L(this,ph).push(t)}increment(t,e){if(Oe(this,Xu,L(this,Xu)+1),t){let n=L(this,Ta).get(e)??0;L(this,Ta).set(e,n+1)}}decrement(t,e){if(Oe(this,Xu,L(this,Xu)-1),t){let n=L(this,Ta).get(e)??0;n===1?L(this,Ta).delete(e):L(this,Ta).set(e,n-1)}L(this,Pl)||(Oe(this,Pl,!0),wr(()=>{Oe(this,Pl,!1),this.linked&&this.flush()}))}transfer_effects(t,e){for(let n of t)L(this,_a).add(n);for(let n of e)L(this,Ho).add(n);t.clear(),e.clear()}oncommit(t){L(this,Ku).add(t)}ondiscard(t){L(this,Qu).add(t)}settled(){return(L(this,Ju)??Oe(this,Ju,fb())).promise}static ensure(){if(_e===null){let t=_e=new Rb;!Pk&&!Zc&&wr(()=>{L(t,Yu)||t.flush()})}return _e}apply(){if(!pr||!this.is_fork&&L(this,xa)===null&&L(this,Ea)===null){Zr=null;return}Zr=new Map;for(let[e,[n]]of this.current)Zr.set(e,n);for(let e=Mb;e!==null;e=L(e,Ea))if(!(e===this||e.is_fork)){var t=!1;if(e.id<this.id){for(let[n,[,i]]of e.current)if(!i&&this.current.has(n)){t=!0;break}}if(!t)for(let[n,i]of e.previous)Zr.has(n)||Zr.set(n,i)}}schedule(t){if(Fk=t,t.b?.is_pending&&(t.f&16777228)!==0&&(t.f&32768)===0){t.b.defer_effect(t);return}for(var e=t;e.parent!==null;){e=e.parent;var n=e.f;if(sd!==null&&e===we&&(pr||(Pe===null||(Pe.f&2)===0)&&!ZR))return;if((n&96)!==0){if((n&1024)===0)return;e.f^=1024}}L(this,Gn).push(e)}};Yu=new WeakMap,xa=new WeakMap,Ea=new WeakMap,Ku=new WeakMap,Qu=new WeakMap,Xu=new WeakMap,Ta=new WeakMap,Ju=new WeakMap,Gn=new WeakMap,ph=new WeakMap,_a=new WeakMap,Ho=new WeakMap,ys=new WeakMap,Zu=new WeakMap,Pl=new WeakMap,wt=new WeakSet,Mk=function(){if(this.is_fork)return!0;for(let n of L(this,Ta).keys()){for(var t=n,e=!1;t.parent!==null;){if(L(this,ys).has(t)){e=!0;break}t=t.parent}if(!e)return!0}return!1},ch=function(){var l,c,d;if(Oe(this,Yu,!0),oO++>1e3&&(tt(this,wt,dh).call(this),xY()),j)for(let u of this.current.keys())$k.add(u);for(let u of L(this,_a))L(this,Ho).delete(u),_t(u,2048),this.schedule(u);for(let u of L(this,Ho))_t(u,4096),this.schedule(u);let t=L(this,Gn);Oe(this,Gn,[]),this.apply();var e=sd=[],n=[],i=uh=[];for(let u of t)try{tt(this,wt,Rk).call(this,u,e,n)}catch(p){throw pO(u),tt(this,wt,Mk).call(this)||this.discard(),p}if(_e=null,i.length>0){var o=Rb.ensure();for(let u of i)o.schedule(u)}if(sd=null,uh=null,tt(this,wt,Mk).call(this)){tt(this,wt,ju).call(this,n),tt(this,wt,ju).call(this,e);for(let[u,p]of L(this,ys))uO(u,p);i.length>0&&tt(l=_e,wt,ch).call(l);return}let s=tt(this,wt,aO).call(this);if(s){tt(this,wt,ju).call(this,n),tt(this,wt,ju).call(this,e),tt(c=s,wt,lO).call(c,this);return}L(this,_a).clear(),L(this,Ho).clear();for(let u of L(this,Ku))u(this);L(this,Ku).clear(),gs=this,sO(n),sO(e),gs=null,L(this,Ju)?.resolve();var a=_e;if(L(this,Xu)===0&&(L(this,Gn).length===0||a!==null)&&(tt(this,wt,dh).call(this),pr&&(tt(this,wt,cO).call(this),_e=a)),L(this,Gn).length>0)if(a!==null){let u=a;L(u,Gn).push(...L(this,Gn).filter(p=>!L(u,Gn).includes(p)))}else a=this;a!==null&&(co.clear(),tt(d=a,wt,ch).call(d))},Rk=function(t,e,n){t.f^=1024;for(var i=t.first;i!==null;){var o=i.f,s=(o&96)!==0,a=s&&(o&1024)!==0,l=a||(o&8192)!==0||L(this,ys).has(i);if(!l&&i.fn!==null){s?i.f^=1024:(o&4)!==0?e.push(i):pr&&(o&16777224)!==0?n.push(i):$l(i)&&((o&16)!==0&&L(this,Ho).add(i),vs(i));var c=i.first;if(c!==null){i=c;continue}}for(;i!==null;){var d=i.next;if(d!==null){i=d;break}i=i.parent}}},aO=function(){for(var t=L(this,xa);t!==null;){if(!t.is_fork){for(let[e,[,n]]of this.current)if(t.current.has(e)&&!n)return t}t=L(t,xa)}return null},lO=function(t){var n;for(let[i,o]of t.current)!this.previous.has(i)&&t.previous.has(i)&&this.previous.set(i,t.previous.get(i)),this.current.set(i,o);for(let[i,o]of t.async_deriveds){let s=this.async_deriveds.get(i);s&&o.promise.then(s.resolve).catch(s.reject)}t.async_deriveds.clear(),this.transfer_effects(L(t,_a),L(t,Ho));let e=i=>{var o=i.reactions;if(o!==null&&!((i.f&2)!==0&&(i.f&6144)===0))for(let l of o){var s=l.f;if((s&2)!==0)e(l);else{var a=l;s&4194320&&!this.async_deriveds.has(a)&&(L(this,Ho).delete(a),_t(a,2048),this.schedule(a))}}};for(let i of this.current.keys())e(i);this.oncommit(()=>t.discard()),tt(n=t,wt,dh).call(n),_e=this,tt(this,wt,ch).call(this)},ju=function(t){for(var e=0;e<t.length;e+=1)_b(t[e],L(this,_a),L(this,Ho))},cO=function(){var u;for(let p=Mb;p!==null;p=L(p,Ea)){var t=p.id<this.id,e=[];for(let[m,[h,g]]of this.current){if(p.current.has(m)){var n=p.current.get(m)[0];if(t&&h!==n)p.current.set(m,[h,g]);else continue}e.push(m)}if(t)for(let[m,h]of this.async_deriveds){let g=p.async_deriveds.get(m);g&&h.promise.then(g.resolve).catch(g.reject)}var i=[...p.current.keys()].filter(m=>!p.current.get(m)[1]);if(!(!L(p,Yu)||i.length===0)){var o=i.filter(m=>!this.current.has(m));if(o.length===0)t&&p.discard();else if(e.length>0){if(j&&!L(p,Pl)&&KR(L(p,Gn).length===0,"Batch has scheduled roots"),t)for(let m of L(this,Zu))p.unskip_effect(m,h=>{var g;(h.f&4194320)!==0?p.schedule(h):tt(g=p,wt,ju).call(g,[h])});p.activate();var s=new Set,a=new Map;for(var l of e)dO(l,o,s,a);a=new Map;var c=[...p.current].filter(([m,h])=>{let g=this.current.get(m);return g?g[0]!==h[0]||g[1]!==h[1]:!0}).map(([m])=>m);if(c.length>0)for(let m of L(this,ph))(m.f&155648)===0&&Ok(m,c,a)&&((m.f&4194320)!==0?(_t(m,2048),p.schedule(m)):L(p,_a).add(m));if(L(p,Gn).length>0&&!L(p,Pl)){p.apply();for(var d of L(p,Gn))tt(u=p,wt,Rk).call(u,d,[],[]);Oe(p,Gn,[])}p.deactivate()}}}},dh=function(){if(this.linked){var t=L(this,xa),e=L(this,Ea);t===null?Mb=e:Oe(t,Ea,e),e===null?Gu=t:Oe(e,xa,t),this.linked=!1}};var $i=Rb;function cd(r){var t=Zc;Zc=!0;try{var e;for(r&&(_e!==null&&!_e.is_fork&&_e.flush(),e=r());;){if(XR(),_e===null)return e;_e.flush()}}finally{Zc=t}}function xY(){if(j){var r=new Map;for(let e of _e.current.keys())for(let[n,i]of e.updated??[]){var t=r.get(n);t||(t={error:i.error,count:0},r.set(n,t)),t.count+=i.count}for(let e of r.values())e.error&&console.error(e.error)}try{VR()}catch(e){j&&jr(e,"stack",{value:""}),pi(e,Fk)}}var lo=null;function sO(r){var t=r.length;if(t!==0){for(var e=0;e<t;){var n=r[e++];if((n.f&24576)===0&&$l(n)&&(lo=new Set,vs(n),n.deps===null&&n.first===null&&n.nodes===null&&n.teardown===null&&n.ac===null&&Dk(n),lo?.size>0)){co.clear();for(let i of lo){if((i.f&24576)!==0)continue;let o=[i],s=i.parent;for(;s!==null;)lo.has(s)&&(lo.delete(s),o.push(s)),s=s.parent;for(let a=o.length-1;a>=0;a--){let l=o[a];(l.f&24576)===0&&vs(l)}}lo.clear()}}lo=null}}function dO(r,t,e,n){if(!e.has(r)&&(e.add(r),r.reactions!==null))for(let i of r.reactions){let o=i.f;(o&2)!==0?dO(i,t,e,n):(o&4194320)!==0&&(o&2048)===0&&Ok(i,t,n)&&(_t(i,2048),mh(i))}}function Ok(r,t,e){let n=e.get(r);if(n!==void 0)return n;if(r.deps!==null)for(let i of r.deps){if(_l.call(t,i))return!0;if((i.f&2)!==0&&Ok(i,t,e))return e.set(i,!0),!0}return e.set(r,!1),!1}function mh(r){_e.schedule(r)}function uO(r,t){if(!((r.f&32)!==0&&(r.f&1024)!==0)){(r.f&2048)!==0?t.d.push(r):(r.f&4096)!==0&&t.m.push(r),_t(r,1024);for(var e=r.first;e!==null;)uO(e,t),e=e.next}}function pO(r){_t(r,1024);for(var t=r.first;t!==null;)pO(t),t=t.next}var id=new Set,co=new Map;function Pb(r){id=r}var Lk=!1;function fO(){Lk=!0}function Mn(r,t){var e={f:0,v:r,reactions:null,equals:wb,rv:0,wv:0};return j&&No&&(e.created=t??Vo("created at"),e.updated=null,e.set_during_effect=!1,e.trace=null),e}function pe(r,t){let e=Mn(r,t);return Fb(e),e}function ed(r,t=!1,e=!0){var i;let n=Mn(r);return t||(n.equals=xb),ya&&e&&rt!==null&&rt.l!==null&&((i=rt.l).s??(i.s=[])).push(n),n}function q(r,t,e=!1){Pe!==null&&(!jn||(Pe.f&131072)!==0)&&Uo()&&(Pe.f&4325394)!==0&&(uo===null||!uo.has(r))&&GR();let n=e?Ze(t):t;return j&&Eb(n,r.label),zo(r,n,uh)}function zo(r,t,e=null){if(!r.equals(t)){Pi?co.set(r,t):co.has(r)||co.set(r,r.v);var n=$i.ensure();if(n.capture(r,t),j){if(No||we!==null){r.updated??(r.updated=new Map);let i=(r.updated.get("")?.count??0)+1;if(r.updated.set("",{error:null,count:i}),No||i>5){let o=Vo("updated at");if(o!==null){let s=r.updated.get(o.stack);s||(s={error:o,count:0},r.updated.set(o.stack,s)),s.count++}}}we!==null&&(r.set_during_effect=!0)}if((r.f&2)!==0){let i=r;(r.f&2048)!==0&&ah(i),Zr===null&&Bu(i)}r.wv=Wu(),hO(r,2048,e),Uo()&&we!==null&&(we.f&1024)!==0&&(we.f&96)===0&&(Fi===null?gO([r]):Fi.push(r)),!n.is_fork&&id.size>0&&!Lk&&Ob()}return t}function Ob(){Lk=!1;for(let r of id){(r.f&1024)!==0&&_t(r,4096);let t;try{t=$l(r)}catch{t=!0}t&&vs(r)}id.clear()}function Nk(r,t=1){var e=f(r);return q(r,t===1?++e:--e)}function dd(r){q(r,r.v+1)}function hO(r,t,e){var n=r.reactions;if(n!==null)for(var i=Uo(),o=n.length,s=0;s<o;s++){var a=n[s],l=a.f;if(!(!i&&a===we)){var c=(l&2048)===0;if(c&&_t(a,t),(l&131072)!==0)id.add(a);else if((l&2)!==0){var d=a;Zr?.delete(d),(l&65536)===0&&(l&512&&(we===null||(we.f&2097152)===0)&&(a.f|=65536),hO(d,4096,e))}else if(c){var u=a;(l&16)!==0&&lo!==null&&lo.add(u),e!==null?e.push(u):mh(u)}}}}var TY=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;function Ze(r){if(typeof r!="object"||r===null||yn in r||hb in r)return r;let t=kl(r);if(t!==pb&&t!==xR)return r;var e=new Map,n=io(r),i=pe(0),o=j&&No?Vo("created at"):null,s=Fl,a=u=>{if(Fl===s)return u();var p=Pe,m=Fl;Mr(null),Vk(s);var h=u();return Mr(p),Vk(m),h};n&&(e.set("length",pe(r.length,o)),j&&(r=kY(r)));var l="";let c=!1;function d(u){if(!c){c=!0,l=u,Pn(i,`${l} version`);for(let[p,m]of e)Pn(m,ud(l,p));c=!1}}return new Proxy(r,{defineProperty(u,p,m){(!("value"in m)||m.configurable===!1||m.enumerable===!1||m.writable===!1)&&HR();var h=e.get(p);return h===void 0?a(()=>{var g=pe(m.value,o);return e.set(p,g),j&&typeof p=="string"&&Pn(g,ud(l,p)),g}):q(h,m.value,!0),!0},deleteProperty(u,p){var m=e.get(p);if(m===void 0){if(p in u){let h=a(()=>pe(Rt,o));e.set(p,h),dd(i),j&&Pn(h,ud(l,p))}}else q(m,Rt),dd(i);return!0},get(u,p,m){if(p===yn)return r;if(j&&p===gb)return d;var h=e.get(p),g=p in u;if(h===void 0&&(!g||di(u,p)?.writable)&&(h=a(()=>{var b=Ze(g?u[p]:Rt),y=pe(b,o);return j&&Pn(y,ud(l,p)),y}),e.set(p,h)),h!==void 0){var v=f(h);return v===Rt?void 0:v}return Reflect.get(u,p,m)},getOwnPropertyDescriptor(u,p){var m=Reflect.getOwnPropertyDescriptor(u,p);if(m&&"value"in m){var h=e.get(p);h&&(m.value=f(h))}else if(m===void 0){var g=e.get(p),v=g?.v;if(g!==void 0&&v!==Rt)return{enumerable:!0,configurable:!0,value:v,writable:!0}}return m},has(u,p){if(p===yn)return!0;var m=e.get(p),h=m!==void 0&&m.v!==Rt||Reflect.has(u,p);if(m!==void 0||we!==null&&(!h||di(u,p)?.writable)){m===void 0&&(m=a(()=>{var v=h?Ze(u[p]):Rt,b=pe(v,o);return j&&Pn(b,ud(l,p)),b}),e.set(p,m));var g=f(m);if(g===Rt)return!1}return h},set(u,p,m,h){var g=e.get(p),v=p in u;if(n&&p==="length")for(var b=m;b<g.v;b+=1){var y=e.get(b+"");y!==void 0?q(y,Rt):b in u&&(y=a(()=>pe(Rt,o)),e.set(b+"",y),j&&Pn(y,ud(l,b)))}if(g===void 0)(!v||di(u,p)?.writable)&&(g=a(()=>pe(void 0,o)),j&&Pn(g,ud(l,p)),q(g,Ze(m)),e.set(p,g));else{v=g.v!==Rt;var C=a(()=>Ze(m));q(g,C)}var w=Reflect.getOwnPropertyDescriptor(u,p);if(w?.set&&w.set.call(h,m),!v){if(n&&typeof p=="string"){var T=e.get("length"),P=Number(p);Number.isInteger(P)&&P>=T.v&&q(T,P+1)}dd(i)}return!0},ownKeys(u){f(i);var p=Reflect.ownKeys(u).filter(g=>{var v=e.get(g);return v===void 0||v.v!==Rt});for(var[m,h]of e)h.v!==Rt&&!(m in u)&&p.push(m);return p},setPrototypeOf(){WR()}})}function ud(r,t){return typeof t=="symbol"?`${r}[Symbol(${t.description??""})]`:TY.test(t)?`${r}.${t}`:/^\d+$/.test(t)?`${r}[${t}]`:`${r}['${t}']`}function tp(r){try{if(r!==null&&typeof r=="object"&&yn in r)return r[yn]}catch{}return r}function Db(r,t){return Object.is(tp(r),tp(t))}var _Y=new Set(["copyWithin","fill","pop","push","reverse","shift","sort","splice","unshift"]);function kY(r){return new Proxy(r,{get(t,e,n){var i=Reflect.get(t,e,n);return _Y.has(e)?function(...o){fO();var s=i.apply(this,o);return Ob(),s}:i}})}function vO(){let r=Array.prototype,t=Array.__svelte_cleanup;t&&t();let{indexOf:e,lastIndexOf:n,includes:i}=r;r.indexOf=function(o,s){let a=e.call(this,o,s);if(a===-1){for(let l=s??0;l<this.length;l+=1)if(tp(this[l])===o){bb("array.indexOf(...)");break}}return a},r.lastIndexOf=function(o,s){let a=n.call(this,o,s??this.length-1);if(a===-1){for(let l=0;l<=(s??this.length-1);l+=1)if(tp(this[l])===o){bb("array.lastIndexOf(...)");break}}return a},r.includes=function(o,s){let a=i.call(this,o,s);if(!a){for(let l=0;l<this.length;l+=1)if(tp(this[l])===o){bb("array.includes(...)");break}}return a},Array.__svelte_cleanup=()=>{r.indexOf=e,r.lastIndexOf=n,r.includes=i}}var Bk,yO,fh,bO,wO;function Lb(){if(Bk===void 0){Bk=window,yO=document,fh=/Firefox/.test(navigator.userAgent);var r=Element.prototype,t=Node.prototype,e=Text.prototype;bO=di(t,"firstChild").get,wO=di(t,"nextSibling").get,gk(r)&&(r[Qf]=void 0,r[vb]=null,r[Xf]=void 0,r.__e=void 0),gk(e)&&(e[Jf]=void 0),j&&(r.__svelte_meta=null,vO())}}function ar(r=""){return document.createTextNode(r)}function Xr(r){return bO.call(r)}function wn(r){return wO.call(r)}function R(r,t){if(!xe)return Xr(r);var e=Xr(De);if(e===null)e=De.appendChild(ar());else if(t&&e.nodeType!==Kc){var n=ar();return e?.before(n),Tt(n),n}return t&&hh(e),Tt(e),e}function ae(r,t=!1){if(!xe){var e=Xr(r);return e instanceof Comment&&e.data===""?wn(e):e}if(t){if(De?.nodeType!==Kc){var n=ar();return De?.before(n),Tt(n),n}hh(De)}return De}function re(r,t=!1){if(!xe)return Xr(r);var e=R(r,t);return $(r),e}function E(r,t=1,e=!1){let n=xe?De:r;for(var i;t--;)i=n,n=wn(n);if(!xe)return n;if(e){if(n?.nodeType!==Kc){var o=ar();return n===null?i?.after(o):n.before(o),Tt(o),o}hh(n)}return Tt(n),n}function qu(r){r.textContent=""}function Nb(){if(!pr||lo!==null)return!1;var r=we.f;return(r&32768)!==0}function Wo(r,t,e){return t==null||t===db?e?document.createElement(r,{is:e}):document.createElement(r):e?document.createElementNS(t,r,{is:e}):document.createElementNS(t,r)}function hh(r){if(r.nodeValue.length<65536)return;let t=r.nextSibling;for(;t!==null&&t.nodeType===Kc;)t.remove(),r.nodeValue+=t.nodeValue,t=r.nextSibling}var Uk=new WeakMap;function CO(r){var t=we;if(t===null)return Pe.f|=8388608,r;if(j&&r instanceof Error&&!Uk.has(r)&&Uk.set(r,SY(r,t)),(t.f&32768)===0&&(t.f&4)===0)throw j&&!t.parent&&r instanceof Error&&xO(r),r;pi(r,t)}function pi(r,t){if(!(t!==null&&(t.f&16384)!==0)){for(;t!==null;){if((t.f&128)!==0&&(t.f&33570816)===0){if((t.f&32768)===0)throw r;try{t.b.error(r);return}catch(e){r=e}}t=t.parent}throw j&&r instanceof Error&&xO(r),r}}function SY(r,t){let e=di(r,"message");if(!(e&&!e.configurable)){for(var n=fh?" ":" ",i=`
|
||
${n}in ${t.fn?.name||"<unknown>"}`,o=t.ctx;o!==null;)i+=`
|
||
${n}in ${o.function?.[no].split("/").pop()}`,o=o.p;return{message:r.message+`
|
||
${i}
|
||
`,stack:r.stack?.split(`
|
||
`).filter(s=>!s.includes("svelte/src/internal")).join(`
|
||
`)}}}function xO(r){let t=Uk.get(r);t&&(jr(r,"message",{value:t.message}),jr(r,"stack",{value:t.stack}))}function TO(r){we===null&&(Pe===null&&NR(r),LR()),Pi&&DR(r)}function IY(r,t){var e=t.last;e===null?t.last=t.first=r:(e.next=r,r.prev=e,t.last=r)}function bs(r,t){var e=we;if(j)for(;e!==null&&(e.f&131072)!==0;)e=e.parent;e!==null&&(e.f&8192)!==0&&(r|=8192);var n={ctx:rt,deps:null,nodes:null,f:r|2048|512,first:null,fn:t,last:null,next:null,parent:e,b:e&&e.b,prev:null,teardown:null,wv:0,ac:null};j&&(n.component_function=Bo),_e?.register_created_effect(n);var i=n;if((r&4)!==0)sd!==null?sd.push(n):$i.ensure().schedule(n);else if(t!==null){try{vs(n)}catch(s){throw sr(n),s}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&(i.f&524288)===0&&(i=i.first,(r&16)!==0&&(r&65536)!==0&&i!==null&&(i.f|=65536))}if(i!==null&&(i.parent=e,e!==null&&IY(i,e),Pe!==null&&(Pe.f&2)!==0&&(r&64)===0)){var o=Pe;(o.effects??(o.effects=[])).push(i)}return n}function Al(){return Pe!==null&&!jn}function Qr(r){let t=bs(8,null);return _t(t,1024),t.teardown=r,t}function Dt(r){TO("$effect"),j&&jr(r,"name",{value:"$effect"});var t=we.f,e=!Pe&&(t&32)!==0&&rt!==null&&!rt.i;if(e){var n=rt;(n.e??(n.e=[])).push(r)}else return xk(r)}function xk(r){return bs(1048580,r)}function Hk(r){$i.ensure();let t=bs(524352,r);return()=>{sr(t)}}function _O(r){$i.ensure();let t=bs(524352,r);return(e={})=>new Promise(n=>{e.outro?ws(t,()=>{sr(t),n(void 0)}):(sr(t),n(void 0))})}function Cr(r){return bs(4,r)}function iO(r){return bs(4718592,r)}function en(r,t=0){return bs(8|t,r)}function Q(r,t=[],e=[],n=[]){Ib(n,t,e,i=>{bs(8,()=>{r(...i.map(f))})})}function Yn(r,t=0){var e=bs(16|t,r);return j&&(e.dev_stack=hs),e}function Or(r){return bs(524320,r)}function Wk(r){var t=r.teardown;if(t!==null){let e=Pi,n=Pe;qk(!0),Mr(null);try{t.call(null)}catch(i){pi(i,r.parent)}finally{qk(e),Mr(n)}}}function lh(r,t=!1){var e=r.first;for(r.first=r.last=null;e!==null;){let i=e.ac;i!==null&&ao(()=>{i.abort(ha)});var n=e.next;(e.f&64)!==0?e.parent=null:sr(e,t),e=n}}function kO(r){for(var t=r.first;t!==null;){var e=t.next;(t.f&32)===0&&sr(t),t=e}}function sr(r,t=!0){var e=!1;(t||(r.f&262144)!==0)&&r.nodes!==null&&r.nodes.end!==null&&(SO(r.nodes.start,r.nodes.end),e=!0),r.f|=33554432,lh(r,t&&!e),od(r,0);var n=r.nodes&&r.nodes.t;if(n!==null)for(let o of n)o.stop();Wk(r),r.f^=33554432,r.f|=16384;var i=r.parent;i!==null&&i.first!==null&&Dk(r),j&&(r.component_function=null),r.next=r.prev=r.teardown=r.ctx=r.deps=r.fn=r.nodes=r.ac=r.b=null}function SO(r,t){for(;r!==null;){var e=r===t?null:wn(r);r.remove(),r=e}}function Dk(r){var t=r.parent,e=r.prev,n=r.next;e!==null&&(e.next=n),n!==null&&(n.prev=e),t!==null&&(t.first===r&&(t.first=n),t.last===r&&(t.last=e))}function ws(r,t,e=!0){var n=[];r.f|=256,AO(r,n,!0);var i=()=>{e&&sr(r),t&&t()},o=n.length;if(o>0){var s=()=>--o||i();for(var a of n)a.out(s)}else i()}function AO(r,t,e){if((r.f&8192)===0){r.f^=8192;var n=r.nodes&&r.nodes.t;if(n!==null)for(let a of n)(a.is_global||e)&&t.push(a);for(var i=r.first;i!==null;){var o=i.next;if((i.f&64)===0){var s=(i.f&65536)!==0||(i.f&32)!==0&&(r.f&16)!==0;AO(i,t,s?e:!1)}i=o}}}function rp(r){r.f&=-257,IO(r,!0)}function IO(r,t){if((r.f&256)===0&&(r.f&8192)!==0){r.f^=8192,(r.f&1024)===0&&(_t(r,2048),$i.ensure().schedule(r));for(var e=r.first;e!==null;){var n=e.next,i=(e.f&65536)!==0||(e.f&32)!==0;IO(e,i?t:!1),e=n}var o=r.nodes&&r.nodes.t;if(o!==null)for(let s of o)(s.is_global||t)&&s.in()}}function np(r,t){if(r.nodes)for(var e=r.nodes.start,n=r.nodes.end;e!==null;){var i=e===n?null:wn(e);t.append(e),e=i}}var PO=null;var Vb=!1,Pi=!1;function qk(r){Pi=r}var Pe=null,jn=!1;function Mr(r){Pe=r}var we=null;function Rr(r){we=r}var uo=null;function Fb(r){Pe!==null&&(!pr||(Pe.f&2)!==0)&&(uo??(uo=new Set)).add(r)}var Jr=null,Wn=0,Fi=null;function gO(r){Fi=r}var FO=1,pd=0,Fl=pd;function Vk(r){Fl=r}function Wu(){return++FO}function $l(r){var t=r.f;if((t&2048)!==0)return!0;if(t&2&&(r.f&=-65537),(t&4096)!==0){for(var e=r.deps,n=e.length,i=0;i<n;i++){var o=e[i];if($l(o)&&Ak(o),o.wv>r.wv)return!0}(t&512)!==0&&Zr===null&&_t(r,1024)}return!1}function MO(r,t,e=!0){var n=r.reactions;if(n!==null&&!(!pr&&uo!==null&&uo.has(r)))for(var i=0;i<n.length;i++){var o=n[i];(o.f&2)!==0?MO(o,t,!1):t===o&&(e?_t(o,2048):(o.f&1024)!==0&&_t(o,4096),mh(o))}}function $b(r){var t=Jr,e=Wn,n=Fi,i=Pe,o=uo,s=rt,a=jn,l=Fl,c=r.f;Jr=null,Wn=0,Fi=null,Pe=(c&96)===0?r:null,uo=null,ba(r.ctx),jn=!1,Fl=++pd,r.ac!==null&&(ao(()=>{r.ac.abort(ha)}),r.ac=null);try{r.f|=2097152;var d=r.fn,u=d();r.f|=32768;var p=$O(r);if(Uo()&&Fi!==null&&!jn&&p!==null&&(r.f&6146)===0)for(var m=0;m<Fi.length;m++)MO(Fi[m],r);if(i!==null&&i!==r){if(pd++,i.deps!==null)for(let h=0;h<e;h+=1)i.deps[h].rv=pd;if(t!==null)for(let h of t)h.rv=pd;Fi!==null&&(n===null?n=Fi:n.push(...Fi))}return(r.f&8388608)!==0&&(r.f^=8388608),u}catch(h){return $O(r),CO(h)}finally{r.f^=2097152,Jr=t,Wn=e,Fi=n,Pe=i,uo=o,ba(s),jn=a,Fl=l}}function $O(r){var i;var t=r.deps,e=_e?.is_fork;if(Jr!==null){var n;if(e||od(r,Wn),t!==null&&Wn>0)for(t.length=Wn+Jr.length,n=0;n<Jr.length;n++)t[Wn+n]=Jr[n];else r.deps=t=Jr;if(Al()&&(r.f&512)!==0)for(n=Wn;n<t.length;n++)((i=t[n]).reactions??(i.reactions=[])).push(r)}else!e&&t!==null&&Wn<t.length&&(od(r,Wn),t.length=Wn);return t}function PY(r,t){let e=t.reactions;if(e!==null){var n=CR.call(e,r);if(n!==-1){var i=e.length-1;i===0?e=t.reactions=null:(e[n]=e[i],e.pop())}}if(e===null&&(t.f&2)!==0&&(Jr===null||!_l.call(Jr,t))){var o=t;(o.f&512)!==0&&(o.f^=512,o.f&=-65537),o.v!==Rt&&Bu(o),o.ac!==null&&ao(()=>{o.ac.abort(ha),o.ac=null,_t(o,2048)}),nO(o),od(o,0)}}function od(r,t){var e=r.deps;if(e!==null)for(var n=t;n<e.length;n++)PY(r,e[n])}function vs(r){var t=r.f;if((t&16384)===0){_t(r,1024);var e=we,n=Vb;if(we=r,Vb=(t&96)===0,j){var i=Bo;Tb(r.component_function);var o=hs;Vu(r.dev_stack??hs)}try{(t&16777232)!==0?kO(r):lh(r),Wk(r);var s=$b(r);if(r.teardown=typeof s=="function"?s:null,r.wv=FO,j&&No&&(r.f&2048)!==0&&r.deps!==null)for(var a of r.deps)a.set_during_effect&&(a.wv=Wu(),a.set_during_effect=!1)}finally{Vb=n,we=e,j&&(Tb(i),Vu(o))}}}async function Cs(){if(pr)return new Promise(r=>{requestAnimationFrame(()=>r()),setTimeout(()=>r())});await Promise.resolve(),cd()}function f(r){var t=r.f,e=(t&2)!==0;if(PO?.add(r),Pe!==null&&!jn){var n=we!==null&&(we.f&16384)!==0;if(!n&&(uo===null||!uo.has(r))){var i=Pe.deps;if((Pe.f&2097152)!==0)r.rv<pd&&(r.rv=pd,Jr===null&&i!==null&&i[Wn]===r?Wn++:Jr===null?Jr=[r]:Jr.push(r));else{Pe.deps??(Pe.deps=[]),_l.call(Pe.deps,r)||Pe.deps.push(r);var o=r.reactions;o===null?r.reactions=[Pe]:_l.call(o,Pe)||o.push(Pe)}}}if(j){if(!jn&&mi&&_e===null&&gs===null&&!mi.warned&&(mi.effect.f&2097152)===0&&!mi.effect_deps.has(r)){mi.warned=!0,TR(r.label);var s=Vo("traced at");s&&console.warn(s)}if(sh.delete(r),No&&!jn&&nh!==null&&Pe!==null&&nh.reaction===Pe){if(r.trace)r.trace();else if(s=Vo("traced at"),s){var a=nh.entries.get(r);a===void 0&&(a={traces:[]},nh.entries.set(r,a));var l=a.traces[a.traces.length-1];s.stack!==l?.stack&&a.traces.push(s)}}}if(Pi&&co.has(r))return co.get(r);if(e){var c=r;if(Pi){var d=c.v;return((c.f&1024)===0&&c.reactions!==null||OO(c))&&(d=ah(c)),co.set(c,d),d}var u=(c.f&512)===0&&!jn&&Pe!==null&&(Vb||(Pe.f&512)!==0),p=(c.f&32768)===0;$l(c)&&(u&&(c.f|=512),Ak(c)),u&&!p&&(Ik(c),RO(c))}if(Zr?.has(r))return Zr.get(r);if((r.f&8388608)!==0)throw r.v;return r.v}function RO(r){if(r.f|=512,r.deps!==null)for(let t of r.deps)(t.reactions??(t.reactions=[])).push(r),(t.f&2)!==0&&(t.f&512)===0&&(Ik(t),RO(t))}function OO(r){if(r.v===Rt)return!0;if(r.deps===null)return!1;for(let t of r.deps)if(co.has(t)||(t.f&2)!==0&&OO(t))return!0;return!1}function pt(r){var t=jn;try{return jn=!0,r()}finally{jn=t}}function Ub(r){if(!(typeof r!="object"||!r||r instanceof EventTarget)){if(yn in r)Bb(r);else if(!Array.isArray(r))for(let t in r){let e=r[t];typeof e=="object"&&e&&yn in e&&Bb(e)}}}function Bb(r,t=new Set){if(typeof r=="object"&&r!==null&&!(r instanceof EventTarget)&&!t.has(r)){t.add(r),r instanceof Date&&r.getTime();for(let n in r)try{Bb(r[n],t)}catch{}let e=kl(r);if(e!==Object.prototype&&e!==Array.prototype&&e!==Map.prototype&&e!==Set.prototype&&e!==Date.prototype){let n=ub(e);for(let i in n){let o=n[i].get;if(o)try{o.call(r)}catch{}}}}}var md=Symbol("events"),Yk=new Set,qb=new Set;function DO(r,t,e,n={}){function i(o){if(n.capture||zb.call(t,o),!o.cancelBubble)return ao(()=>e?.call(this,o))}return r.startsWith("pointer")||r.startsWith("touch")||r==="wheel"?wr(()=>{t.addEventListener(r,i,n)}):t.addEventListener(r,i,n),i}function Kn(r,t,e,n,i){var o={capture:n,passive:i},s=DO(r,t,e,o);(t===document.body||t===window||t===document||t instanceof HTMLMediaElement)&&Qr(()=>{t.removeEventListener(r,s,o)})}function ge(r,t,e){(t[md]??(t[md]={}))[r]=e}function He(r){for(var t=0;t<r.length;t++)Yk.add(r[t]);for(var e of qb)e(r)}var Gk=null,jk=!1;function zb(r){var t=this,e=t.ownerDocument,n=r.type,i=r.composedPath?.()||[],o=i[0]||r.target;Gk=r,jk||(jk=!0,setTimeout(()=>{jk=!1,Gk=null}));var s=0,a=Gk===r&&r[md];if(a){var l=i.indexOf(a);if(l!==-1&&(t===document||t===window)){r[md]=t;return}var c=i.indexOf(t);if(c===-1)return;l<=c&&(s=l)}if(o=i[s]||r.target,o!==t){jr(r,"currentTarget",{configurable:!0,get(){return o||e}});var d=Pe,u=we;Mr(null),Rr(null);try{for(var p,m=[];o!==null&&o!==t;){try{var h=o[md]?.[n];h!=null&&(!o.disabled||r.target===o)&&h.call(o,r)}catch(g){p?m.push(g):p=g}if(r.cancelBubble)break;s++,o=s<i.length?i[s]:null}if(p){for(let g of m)queueMicrotask(()=>{throw g});throw p}}finally{r[md]=t,delete r.currentTarget,Mr(d),Rr(u)}}}var $Y=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:r=>r});function LO(r){return $Y?.createHTML(r)??r}function Kk(r){var t=Wo("template");return t.innerHTML=LO(r.replaceAll("<!>","<!---->")),t.content}function Mi(r,t){var e=we;e.nodes===null&&(e.nodes={start:r,end:t,a:null,t:null})}function F(r,t){var e=(t&1)!==0,n=(t&2)!==0,i,o=!r.startsWith("<!>");return()=>{if(xe)return Mi(De,null),De;i===void 0&&(i=Kk(o?r:"<!>"+r),e||(i=Xr(i)));var s=n||fh?document.importNode(i,!0):i.cloneNode(!0);if(e){var a=Xr(s),l=s.lastChild;Mi(a,l)}else Mi(s,s);return s}}function xs(r=""){if(!xe){var t=ar(r+"");return Mi(t,t),t}var e=De;return e.nodeType!==Kc?(e.before(e=ar()),Tt(e)):hh(e),Mi(e,e),e}function bt(){if(xe)return Mi(De,null),De;var r=document.createDocumentFragment(),t=document.createComment(""),e=ar();return r.append(t,e),Mi(t,e),r}function A(r,t){if(xe){var e=we;((e.f&32768)===0||e.nodes.end===null)&&(e.nodes.end=De),Yr();return}r!==null&&r.before(t)}function Ri(){var r;if(xe&&De&&De.nodeType===Ii&&De.textContent?.startsWith("$")){let t=De.textContent.substring(1);return Yr(),t}return(r=window.__svelte??(window.__svelte={})).uid??(r.uid=1),`c${window.__svelte.uid++}`}var LY=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","disabled","formnovalidate","indeterminate","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","seamless","selected","webkitdirectory","defer","disablepictureinpicture","disableremoteplayback"];var wde=[...LY,"formNoValidate","isMap","noModule","playsInline","readOnly","value","volume","defaultValue","defaultChecked","srcObject","noValidate","allowFullscreen","disablePictureInPicture","disableRemotePlayback"];var NY=["touchstart","touchmove"];function NO(r){return NY.includes(r)}var VY=["$state","$state.raw","$derived","$derived.by"],Cde=[...VY,"$state.eager","$state.snapshot","$props","$props.id","$bindable","$effect","$effect.pre","$effect.tracking","$effect.root","$effect.pending","$inspect","$inspect().with","$inspect.trace","$host"];function VO(r){let t=0,e=Mn(0),n;return j&&Pn(e,"createSubscriber version"),()=>{Al()&&(f(e),en(()=>(t===0&&(n=pt(()=>r(()=>dd(e)))),t+=1,()=>{wr(()=>{t-=1,t===0&&(n?.(),n=void 0,dd(e))})})))}}var BY=589824;function wh(r,t,e,n){new Xk(r,t,e,n)}var Oi,vh,po,fd,Qn,Di,Xn,Li,Es,hd,Ml,ip,yh,bh,Ts,Wb,St,UO,qO,Jk,zO,Zk,gh,Hb,eS,tS,Xk=class{constructor(t,e,n,i){qe(this,St);fe(this,"parent");fe(this,"is_pending",!1);fe(this,"transform_error");qe(this,Oi);qe(this,vh,xe?De:null);qe(this,po);qe(this,fd);qe(this,Qn);qe(this,Di,null);qe(this,Xn,null);qe(this,Li,null);qe(this,Es,null);qe(this,hd,0);qe(this,Ml,0);qe(this,ip,!1);qe(this,yh,new Set);qe(this,bh,new Set);qe(this,Ts,null);qe(this,Wb,VO(()=>(Oe(this,Ts,Mn(L(this,hd))),j&&Pn(L(this,Ts),"$effect.pending()"),()=>{Oe(this,Ts,null)})));Oe(this,Oi,t),Oe(this,po,e),Oe(this,fd,o=>{var s=we;s.b=this,s.f|=128,n(o)}),this.parent=we.b,this.transform_error=i??this.parent?.transform_error??(o=>o),Oe(this,Qn,Yn(()=>{if(xe){let o=L(this,vh);Yr();let s=o.data==="[!";if(o.data.startsWith("[?")){let l=JSON.parse(o.data.slice("[?".length));tt(this,St,qO).call(this,l)}else s?tt(this,St,zO).call(this):tt(this,St,UO).call(this)}else tt(this,St,Zk).call(this)},BY)),xe&&Oe(this,Oi,De)}defer_effect(t){_b(t,L(this,yh),L(this,bh))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!L(this,po).pending}update_pending_count(t,e){tt(this,St,eS).call(this,t,e),Oe(this,hd,L(this,hd)+t),!(!L(this,Ts)||L(this,ip))&&(Oe(this,ip,!0),wr(()=>{Oe(this,ip,!1),L(this,Ts)&&zo(L(this,Ts),L(this,hd))}))}get_effect_pending(){return L(this,Wb).call(this),f(L(this,Ts))}error(t){if(!L(this,po).onerror&&!L(this,po).failed)throw t;_e?.is_fork?(L(this,Di)&&_e.skip_effect(L(this,Di)),L(this,Xn)&&_e.skip_effect(L(this,Xn)),L(this,Li)&&_e.skip_effect(L(this,Li)),_e.oncommit(()=>{tt(this,St,tS).call(this,t)})):tt(this,St,tS).call(this,t)}};Oi=new WeakMap,vh=new WeakMap,po=new WeakMap,fd=new WeakMap,Qn=new WeakMap,Di=new WeakMap,Xn=new WeakMap,Li=new WeakMap,Es=new WeakMap,hd=new WeakMap,Ml=new WeakMap,ip=new WeakMap,yh=new WeakMap,bh=new WeakMap,Ts=new WeakMap,Wb=new WeakMap,St=new WeakSet,UO=function(){try{Oe(this,Di,Or(()=>L(this,fd).call(this,L(this,Oi))))}catch(t){this.error(t)}},qO=function(t){let e=L(this,po).failed,{reset:n,invoke_onerror:i}=tt(this,St,Jk).call(this,t);wr(i),e&&Oe(this,Li,Or(()=>{e(L(this,Oi),()=>t,()=>n)}))},Jk=function(t){var e=!1,n=!1;let i=()=>{if(e){PR();return}e=!0,n&&jR(),L(this,Li)!==null&&ws(L(this,Li),()=>{Oe(this,Li,null)}),tt(this,St,Hb).call(this,()=>{tt(this,St,Zk).call(this)})};return{reset:i,invoke_onerror:()=>{try{n=!0,L(this,po).onerror?.(t,i),n=!1}catch(s){pi(s,L(this,Qn)&&L(this,Qn).parent)}}}},zO=function(){let t=L(this,po).pending;t&&(this.is_pending=!0,Oe(this,Xn,Or(()=>t(L(this,Oi)))),wr(()=>{var e=Oe(this,Es,document.createDocumentFragment()),n=ar(),i=!1;if(e.append(n),Oe(this,Di,tt(this,St,Hb).call(this,()=>{try{return Or(()=>L(this,fd).call(this,n))}catch(o){try{this.error(o),i=!0}catch(s){pi(s,L(this,Qn).parent)}return null}})),L(this,Di)===null){Oe(this,Es,null),i&&tt(this,St,gh).call(this,_e);return}L(this,Ml)===0&&(L(this,Oi).before(e),Oe(this,Es,null),ws(L(this,Xn),()=>{Oe(this,Xn,null)}),tt(this,St,gh).call(this,_e))}))},Zk=function(){try{if(this.is_pending=this.has_pending_snippet(),Oe(this,Ml,0),Oe(this,hd,0),Oe(this,Di,Or(()=>{L(this,fd).call(this,L(this,Oi))})),L(this,Ml)>0){var t=Oe(this,Es,document.createDocumentFragment());np(L(this,Di),t);let e=L(this,po).pending;Oe(this,Xn,Or(()=>e(L(this,Oi))))}else tt(this,St,gh).call(this,_e)}catch(e){this.error(e)}},gh=function(t){this.is_pending=!1,t.transfer_effects(L(this,yh),L(this,bh))},Hb=function(t){var e=we,n=Pe,i=rt;Rr(L(this,Qn)),Mr(L(this,Qn)),ba(L(this,Qn).ctx);try{return $i.ensure(),t()}finally{Rr(e),Mr(n),ba(i)}},eS=function(t,e){var n;if(!this.has_pending_snippet()){this.parent&&tt(n=this.parent,St,eS).call(n,t,e);return}Oe(this,Ml,L(this,Ml)+t),L(this,Ml)===0&&(tt(this,St,gh).call(this,e),L(this,Xn)&&ws(L(this,Xn),()=>{Oe(this,Xn,null)}),L(this,Es)&&(L(this,Oi).before(L(this,Es)),Oe(this,Es,null)))},tS=function(t){L(this,Di)&&(sr(L(this,Di)),Oe(this,Di,null)),L(this,Xn)&&(sr(L(this,Xn)),Oe(this,Xn,null)),L(this,Li)&&(sr(L(this,Li)),Oe(this,Li,null)),xe&&(Tt(L(this,vh)),Xt(),Tt(fs()));let e=L(this,po).failed,n=i=>{let{reset:o,invoke_onerror:s}=tt(this,St,Jk).call(this,i);s(),e&&Oe(this,Li,tt(this,St,Hb).call(this,()=>{try{return Or(()=>{var a=we;a.b=this,a.f|=128,e(L(this,Oi),()=>i,()=>o)})}catch(a){return pi(a,L(this,Qn).parent),null}}))};wr(()=>{var i;try{i=this.transform_error(t)}catch(o){pi(o,L(this,Qn)&&L(this,Qn).parent);return}i!==null&&typeof i=="object"&&typeof i.then=="function"?i.then(n,o=>pi(o,L(this,Qn)&&L(this,Qn).parent)):n(i)})};var rS=!0;function ee(r,t){var n;var e=t==null?"":typeof t=="object"?`${t}`:t;e!==(r[n=Jf]??(r[n]=r.nodeValue))&&(r[Jf]=e,r.nodeValue=`${e}`)}function gd(r,t){return HO(r,t)}function iS(r,t){Lb(),t.intro=t.intro??!1;let e=t.target,n=xe,i=De;try{for(var o=Xr(e);o&&(o.nodeType!==Ii||o.data!=="[");)o=wn(o);if(!o)throw fa;Pr(!0),Tt(o);let s=HO(r,{...t,anchor:o});return Pr(!1),s}catch(s){if(s instanceof Error&&s.message.split(`
|
||
`).some(a=>a.startsWith("https://svelte.dev/e/")))throw s;return s!==fa&&console.warn("Failed to hydrate: ",s),t.recover===!1&&BR(),Lb(),qu(e),Pr(!1),gd(r,t)}finally{Pr(n),Tt(i)}}var Gb=new Map;function HO(r,{target:t,anchor:e,props:n={},events:i,context:o,intro:s=!0,transformError:a}){Lb();var l=void 0,c=_O(()=>{var d=e??t.appendChild(ar());wh(d,{pending:()=>{}},m=>{ie({});var h=rt;if(o&&(h.c=o),i&&(n.$$events=i),xe&&Mi(m,null),rS=s,l=r(m,n)||ih(),rS=!0,xe&&(we.nodes.end=De,De===null||De.nodeType!==Ii||De.data!=="]"))throw Qc(),fa;oe()},a);var u=new Set,p=m=>{for(var h=0;h<m.length;h++){var g=m[h];if(!u.has(g)){u.add(g);var v=NO(g);for(let C of[t,document]){var b=Gb.get(C);b===void 0&&(b=new Map,Gb.set(C,b));var y=b.get(g);y===void 0?(C.addEventListener(g,zb,{passive:v}),b.set(g,1)):b.set(g,y+1)}}}};return p(Du(Yk)),qb.add(p),()=>{for(var m of u)for(let v of[t,document]){var h=Gb.get(v),g=h.get(m);--g==0?(v.removeEventListener(m,zb),h.delete(m),h.size===0&&Gb.delete(v)):h.set(m,g)}qb.delete(p),d!==e&&d.parentNode?.removeChild(d)}});return nS.set(l,c),l}var nS=new WeakMap;function op(r,t){let e=nS.get(r);return e?(nS.delete(r),e(t)):(j&&AR(),Promise.resolve())}var Go,_s,Ni,vd,Ch,xh,jb,jo=class{constructor(t,e=!0){fe(this,"anchor");qe(this,Go,new Map);qe(this,_s,new Map);qe(this,Ni,new Map);qe(this,vd,new Set);qe(this,Ch,!0);qe(this,xh,t=>{if(L(this,Go).has(t)){var e=L(this,Go).get(t),n=L(this,_s).get(e);if(n)rp(n),L(this,vd).delete(e);else{var i=L(this,Ni).get(e);i&&(rp(i.effect),L(this,_s).set(e,i.effect),L(this,Ni).delete(e),j&&(i.fragment.lastChild[yk]=this.anchor),i.fragment.lastChild.remove(),this.anchor.before(i.fragment),n=i.effect)}for(let[o,s]of L(this,Go)){if(L(this,Go).delete(o),o===t)break;let a=L(this,Ni).get(s);a&&(sr(a.effect),L(this,Ni).delete(s))}for(let[o,s]of L(this,_s)){if(o===e||L(this,vd).has(o))continue;let a=()=>{if(Array.from(L(this,Go).values()).includes(o)){var c=document.createDocumentFragment();np(s,c),c.append(ar()),L(this,Ni).set(o,{effect:s,fragment:c})}else sr(s);L(this,vd).delete(o),L(this,_s).delete(o)};L(this,Ch)||!n?(L(this,vd).add(o),ws(s,a,!1)):a()}}});qe(this,jb,t=>{L(this,Go).delete(t);let e=Array.from(L(this,Go).values());for(let[n,i]of L(this,Ni))e.includes(n)||(sr(i.effect),L(this,Ni).delete(n))});this.anchor=t,Oe(this,Ch,e)}ensure(t,e){var n=_e,i=Nb();if(e&&!L(this,_s).has(t)&&!L(this,Ni).has(t))if(i){var o=document.createDocumentFragment(),s=ar();o.append(s),L(this,Ni).set(t,{effect:Or(()=>e(s)),fragment:o})}else L(this,_s).set(t,Or(()=>e(this.anchor)));if(L(this,Go).set(n,t),i){for(let[a,l]of L(this,_s))a===t?n.unskip_effect(l):n.skip_effect(l);for(let[a,l]of L(this,Ni))a===t?n.unskip_effect(l.effect):n.skip_effect(l.effect);n.oncommit(L(this,xh)),n.ondiscard(L(this,jb))}else xe&&(this.anchor=De),L(this,xh).call(this,n)}};Go=new WeakMap,_s=new WeakMap,Ni=new WeakMap,vd=new WeakMap,Ch=new WeakMap,xh=new WeakMap,jb=new WeakMap;function Rl(r,t,...e){var n=new jo(r);Yn(()=>{let i=t()??null;j&&i==null&&UR(),n.ensure(i,i&&(o=>i(o,...e)))},65536)}if(j){let r=function(t){if(!(t in globalThis)){let e;Object.defineProperty(globalThis,t,{configurable:!0,get:()=>{if(e!==void 0)return e;zR(t)},set:n=>{e=n}})}};r("$state"),r("$effect"),r("$derived"),r("$inspect"),r("$props"),r("$bindable")}function Eh(r){rt===null&&th("onMount"),ya&&rt.l!==null?zY(rt).m.push(r):Dt(()=>{let t=pt(r);if(typeof t=="function")return t})}function GO(r){rt===null&&th("onDestroy"),Eh(()=>()=>pt(r))}function zY(r){var t=r.l;return t.u??(t.u={a:[],b:[],m:[]})}var YO=new Map;function KO(r,t){var e=YO.get(r);e||(e=new Set,YO.set(r,e)),e.add(t)}function z(r,t,e=!1){var n;xe&&(n=De,Yr());var i=new jo(r),o=e?65536:0;function s(a,l){if(xe){var c=eh(n);if(a!==parseInt(c.substring(1))){var d=fs();Tt(d),i.anchor=d,Pr(!1),i.ensure(a,l),Pr(!0);return}}i.ensure(a,l)}Yn(()=>{var a=!1;t((l,c=0)=>{a=!0,s(c,l)}),a||s(-1,null)},o)}var jY=Symbol("NaN");function Th(r,t,e){xe&&Yr();var n=new jo(r),i=!Uo();Yn(()=>{var o=t();o!==o&&(o=jY),i&&o!==null&&typeof o=="object"&&(o={}),n.ensure(o,e)})}function yd(r,t){return t}function JY(r,t,e){for(var n=[],i=t.length,o,s=t.length,a=0;a<i;a++){let u=t[a];ws(u,()=>{if(o){if(o.pending.delete(u),o.done.add(u),o.pending.size===0){var p=r.outrogroups;oS(r,Du(o.done)),p.delete(o),p.size===0&&(r.outrogroups=null)}}else s-=1},!1)}if(s===0){var l=n.length===0&&e!==null&&r.pending.size===0;if(l){var c=e,d=c.parentNode;qu(d),d.append(c),r.items.clear()}oS(r,t,!l)}else o={pending:new Set(t),done:new Set},(r.outrogroups??(r.outrogroups=new Set)).add(o)}function oS(r,t,e=!0){var n;if(r.pending.size>0){n=new Set;for(let s of r.pending.values())for(let a of s)n.add(r.items.get(a).e)}for(var i=0;i<t.length;i++){var o=t[i];if(n?.has(o)){o.f|=33554432;let s=document.createDocumentFragment();np(o,s)}else sr(t[i],e)}}var Yb;function gt(r,t,e,n,i,o=null){var s=r,a=new Map,l=(t&4)!==0;if(l){var c=r;s=xe?Tt(Xr(c)):c.appendChild(ar())}xe&&Yr();var d=null,u=nd(()=>{var C=e();return io(C)?C:C==null?[]:Du(C)});j&&Pn(u,"{#each ...}");var p,m=new Map,h=!0;function g(C){(y.effect.f&16384)===0&&(y.pending.delete(C),y.fallback=d,ZY(y,p,s,t,n),d!==null&&(p.length===0?(d.f&33554432)===0?rp(d):(d.f^=33554432,kh(d,null,s)):ws(d,()=>{d=null})))}function v(C){y.pending.delete(C)}var b=Yn(()=>{p=f(u);var C=p.length;let w=!1;if(xe){var T=eh(s)==="[!";T!==(C===0)&&(s=fs(),Tt(s),Pr(!1),w=!0)}for(var P=new Set,_=_e,I=Nb(),D=0;D<C;D+=1){xe&&De.nodeType===Ii&&De.data==="]"&&(s=De,w=!0,Pr(!1));var N=p[D],K=n(N,D);if(j){var ne=n(N,D);K!==ne&&OR(String(D),String(K),String(ne))}var H=h?null:a.get(K);H?(H.v&&zo(H.v,N),H.i&&zo(H.i,D),I&&_.unskip_effect(H.e)):(H=eK(a,h?s:Yb??(Yb=ar()),N,K,D,i,t,e),h||(H.e.f|=33554432),a.set(K,H)),P.add(K)}if(C===0&&o&&!d&&(h?d=Or(()=>o(s)):(d=Or(()=>o(Yb??(Yb=ar()))),d.f|=33554432)),C>P.size&&(j?tK(p,n):wk("","","")),xe&&C>0&&Tt(fs()),!h)if(m.set(_,P),I){for(let[O,G]of a)P.has(O)||_.skip_effect(G.e);_.oncommit(g),_.ondiscard(v)}else g(_);w&&Pr(!0),f(u)}),y={effect:b,flags:t,items:a,pending:m,outrogroups:null,fallback:d};h=!1,xe&&(s=De)}function _h(r){for(;r!==null&&(r.f&32)===0;)r=r.next;return r}function ZY(r,t,e,n,i){var o=(n&8)!==0,s=t.length,a=r.items,l=_h(r.effect.first),c,d=null,u,p=[],m=[],h,g,v,b;if(o)for(b=0;b<s;b+=1)h=t[b],g=i(h,b),v=a.get(g).e,(v.f&33554432)===0&&(v.nodes?.a?.measure(),(u??(u=new Set)).add(v));for(b=0;b<s;b+=1){if(h=t[b],g=i(h,b),v=a.get(g).e,r.outrogroups!==null)for(let N of r.outrogroups)N.pending.delete(v),N.done.delete(v);if((v.f&8192)!==0&&(rp(v),o&&(v.nodes?.a?.unfix(),(u??(u=new Set)).delete(v))),(v.f&33554432)!==0)if(v.f^=33554432,v===l)kh(v,null,e);else{var y=d?d.next:l;v===r.effect.last&&(r.effect.last=v.prev),v.prev&&(v.prev.next=v.next),v.next&&(v.next.prev=v.prev),Ol(r,d,v),Ol(r,v,y),kh(v,y,e),d=v,p=[],m=[],l=_h(d.next);continue}if(v!==l){if(c!==void 0&&c.has(v)){if(p.length<m.length){var C=m[0],w;d=C.prev;var T=p[0],P=p[p.length-1];for(w=0;w<p.length;w+=1)kh(p[w],C,e);for(w=0;w<m.length;w+=1)c.delete(m[w]);Ol(r,T.prev,P.next),Ol(r,d,T),Ol(r,P,C),l=C,d=P,b-=1,p=[],m=[]}else c.delete(v),kh(v,l,e),Ol(r,v.prev,v.next),Ol(r,v,d===null?r.effect.first:d.next),Ol(r,d,v),d=v;continue}for(p=[],m=[];l!==null&&l!==v;)(c??(c=new Set)).add(l),m.push(l),l=_h(l.next);if(l===null)continue}(v.f&33554432)===0&&p.push(v),d=v,l=_h(v.next)}if(r.outrogroups!==null){for(let N of r.outrogroups)N.pending.size===0&&(oS(r,Du(N.done)),r.outrogroups?.delete(N));r.outrogroups.size===0&&(r.outrogroups=null)}if(l!==null||c!==void 0){var _=[];if(c!==void 0)for(v of c)(v.f&8192)===0&&_.push(v);for(;l!==null;)(l.f&8192)===0&&l!==r.fallback&&_.push(l),l=_h(l.next);var I=_.length;if(I>0){var D=(n&4)!==0&&s===0?e:null;if(o){for(b=0;b<I;b+=1)_[b].nodes?.a?.measure();for(b=0;b<I;b+=1)_[b].nodes?.a?.fix()}JY(r,_,D)}}o&&wr(()=>{if(u!==void 0)for(v of u)v.nodes?.a?.apply()})}function eK(r,t,e,n,i,o,s,a){var l=(s&1)!==0?(s&16)===0?ed(e,!1,!1):Mn(e):null,c=(s&2)!==0?Mn(i):null;return j&&l&&(l.trace=()=>{a()[c?.v??i]}),{v:l,i:c,e:Or(()=>(o(t,l??e,c??i,a),()=>{r.delete(n)}))}}function kh(r,t,e){if(r.nodes)for(var n=r.nodes.start,i=r.nodes.end,o=t&&(t.f&33554432)===0?t.nodes.start:e;n!==null;){var s=wn(n);if(o.before(n),n===i)return;n=s}}function Ol(r,t,e){t===null?r.effect.first=e:t.next=e,e===null?r.effect.last=t:e.prev=t}function tK(r,t){let e=new Map,n=r.length;for(let i=0;i<n;i++){let o=t(r[i],i);if(e.has(o)){let s=String(e.get(o)),a=String(i),l=String(o);l.startsWith("[object ")&&(l=null),wk(s,a,l)}e.set(o,i)}}function Ae(r,t){Cr(()=>{r=we?.parent?.nodes?.start??r;var e=r.getRootNode(),n=e.host?e:e.head??e.ownerDocument.head;if(!n.querySelector("#"+t.hash)){let i=Wo("style");i.id=t.hash,i.textContent=t.code,n.appendChild(i),j&&KO(t.hash,i)}})}function Ft(r,t,e){Cr(()=>{var n=pt(()=>t(r,e?.())||{});if(e&&n?.update){var i=!1,o={};en(()=>{var s=e();Ub(s),i&&Cb(o,s)&&(o=s,n.update(s))}),i=!0}if(n?.destroy)return()=>n.destroy()})}var XO=[...`
|
||
\r\f\xA0\v\uFEFF`];function ZO(r,t,e){var n=r==null?"":""+r;if(t&&(n=n?n+" "+t:t),e){for(var i of Object.keys(e))if(e[i])n=n?n+" "+i:i;else if(n.length)for(var o=i.length,s=0;(s=n.indexOf(i,s))>=0;){var a=s+o;(s===0||XO.includes(n[s-1]))&&(a===n.length||XO.includes(n[a]))?n=(s===0?"":n.substring(0,s))+n.substring(a+1):s=a}}return n===""?null:n}function JO(r,t=!1){var e=t?" !important;":";",n="";for(var i of Object.keys(r)){var o=r[i];o!=null&&o!==""&&(n+=" "+i+": "+o+e)}return n}function sS(r){return r[0]!=="-"||r[1]!=="-"?r.toLowerCase():r}function eD(r,t){if(t){var e="",n,i;if(Array.isArray(t)?(n=t[0],i=t[1]):n=t,r){r=String(r).replaceAll(/\/\*.*?\*\//g,"").trim();var o=!1,s=0,a=!1,l=[];n&&l.push(...Object.keys(n).map(sS)),i&&l.push(...Object.keys(i).map(sS));var c=0,d=-1;let g=r.length;for(var u=0;u<g;u++){var p=r[u];if(a?p==="/"&&r[u-1]==="*"&&(a=!1):o?o===p&&(o=!1):p==="/"&&r[u+1]==="*"?a=!0:p==='"'||p==="'"?o=p:p==="("?s++:p===")"&&s--,!a&&o===!1&&s===0){if(p===":"&&d===-1)d=u;else if(p===";"||u===g-1){if(d!==-1){var m=sS(r.substring(c,d).trim());if(!l.includes(m)){p!==";"&&u++;var h=r.substring(c,u).trim();e+=" "+h+";"}}c=u+1,d=-1}}}}return n&&(e+=JO(n)),i&&(e+=JO(i,!0)),e=e.trim(),e===""?null:e}return r==null?null:String(r)}function Ge(r,t,e,n,i,o){var s=r[Qf];if(xe||s!==e||s===void 0){var a=ZO(e,n,o);(!xe||a!==r.getAttribute("class"))&&(a==null?r.removeAttribute("class"):t?r.className=a:r.setAttribute("class",a)),r[Qf]=e}else if(o&&i!==o)for(var l in o){var c=!!o[l];(i==null||c!==!!i[l])&&r.classList.toggle(l,c)}return o}function aS(r,t={},e,n){for(var i in e){var o=e[i];t[i]!==o&&(e[i]==null?r.style.removeProperty(i):r.style.setProperty(i,o,n))}}function sp(r,t,e,n){var i=r[Xf];if(xe||i!==t){var o=eD(t,n);(!xe||o!==r.getAttribute("style"))&&(o==null?r.removeAttribute("style"):r.style.cssText=o),r[Xf]=t}else n&&(Array.isArray(n)?(aS(r,e?.[0],n[0]),aS(r,e?.[1],n[1],"important")):aS(r,e,n));return n}function lS(r,t){t?r.hasAttribute("selected")||r.setAttribute("selected",""):r.removeAttribute("selected")}function oK(r,t){var e=r.__defaultValue,n=r.multiple,i=n?e??[]:null;if(!(n&&!io(i))){var o=r.selectedIndex,s=t&&n?new Set(r.selectedOptions):null;for(var a of r.options){var l=ap(a);lS(a,n?i.includes(l):Db(l,e))}if(t)if(s!==null)for(a of r.options){var c=s.has(a);a.selected!==c&&(a.selected=c)}else r.selectedIndex!==o&&(r.selectedIndex=o)}}function Dl(r,t,e=!1){if(r.multiple){if(t==null)return;if(!io(t))return IR();for(var n of r.options)n.selected=t.includes(ap(n));return}for(n of r.options){var i=ap(n);if(Db(i,t)){n.selected=!0;return}}(!e||t!==void 0)&&(r.selectedIndex=-1)}function Ll(r){var t=new MutationObserver(e=>{e.every(sK)||("__defaultValue"in r&&oK(r,!1),"__value"in r&&Dl(r,r.__value))});t.observe(r,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]}),Qr(()=>{t.disconnect()})}function cS(r,t,e=t){var n=new WeakSet,i=!0;Ab(r,"change",o=>{var s=o?"[selected]":":checked",a;if(r.multiple)a=[].map.call(r.querySelectorAll(s),ap);else{var l=r.querySelector(s)??r.querySelector("option:not([disabled])");a=l&&ap(l)}e(a),r.__value=a,_e!==null&&n.add(_e)}),Cr(()=>{var o=t();if(r===document.activeElement){var s=pr?gs:_e;if(n.has(s))return}if(Dl(r,o,i),i&&o===void 0){var a=r.querySelector(":checked");a!==null&&(o=ap(a),e(o))}r.__value=o,i=!1})}function ap(r){return"__value"in r?r.__value:r.value}function sK(r){if(r.target.closest("selectedcontent")!==null)return!0;if(r.type==="childList"){var t=[...r.addedNodes,...r.removedNodes];return t.length>0&&t.every(e=>e.nodeName==="SELECTEDCONTENT")}return!1}var dK=Symbol("is custom element"),uK=Symbol("is html"),pK=yb?"link":"LINK";var mK=yb?"progress":"PROGRESS";function Ct(r){if(xe){var t=!1,e=()=>{if(!t){if(t=!0,r.hasAttribute("value")){var n=r.value;le(r,"value",null),r.value=n}if(r.hasAttribute("checked")){var i=r.checked;le(r,"checked",null),r.checked=i}}};r[Sl]=e,wr(e),Sb()}}function Jn(r,t){var e=uS(r);e.value===(e.value=t??void 0)||r.value===t&&(t!==0||r.nodeName!==mK)||(r.value=t??"")}function bd(r,t){var e=uS(r);e.checked!==(e.checked=t??void 0)&&(r.checked=t)}function le(r,t,e,n){var i=uS(r);if(xe&&(i[t]=r.getAttribute(t),t==="src"||t==="srcset"||t==="href"&&r.nodeName===pK)){n||hK(r,t,e??"");return}i[t]!==(i[t]=e)&&(t==="loading"&&(r[ER]=e),e==null?r.removeAttribute(t):typeof e!="string"&&fK(r).has(t)?r[t]=e:r.setAttribute(t,e))}function uS(r){var t;return r[t=vb]??(r[t]={[dK]:r.nodeName.includes("-"),[uK]:r.namespaceURI===db})}var tD=new Map;function fK(r){var t=r.getAttribute("is")||r.nodeName,e=tD.get(t);if(e)return e;tD.set(t,e=new Set);for(var n,i=r,o=Element.prototype;o!==i;){n=ub(i);for(var s in n)n[s].set&&s!=="innerHTML"&&s!=="textContent"&&s!=="innerText"&&e.add(s);i=kl(i)}return e}function hK(r,t,e){j&&(t==="srcset"&&gK(r,e)||dS(r.getAttribute(t)??"",e)||SR(t,r.outerHTML.replace(r.innerHTML,r.innerHTML&&"..."),String(e)))}function dS(r,t){return r===t?!0:new URL(r,document.baseURI).href===new URL(t,document.baseURI).href}function rD(r){return r.split(",").map(t=>t.trim().split(" ").filter(Boolean))}function gK(r,t){var e=rD(r.srcset),n=rD(t);return n.length===e.length&&n.every(([i,o],s)=>o===e[s][1]&&(dS(e[s][0],i)||dS(i,e[s][0])))}function Zn(r,t,e=t){var n=new WeakSet;Ab(r,"input",async i=>{j&&r.type==="checkbox"&&bk();var o=i?r.defaultValue:r.value;if(o=pS(r)?mS(o):o,e(o),_e!==null&&n.add(_e),await Cs(),o!==(o=t())){var s=r.selectionStart,a=r.selectionEnd,l=r.value.length;if(r.value=o??"",a!==null){var c=r.value.length;s===a&&a===l&&c>l?(r.selectionStart=c,r.selectionEnd=c):(r.selectionStart=s,r.selectionEnd=Math.min(a,c))}}}),(xe&&r.defaultValue!==r.value||pt(t)==null&&r.value)&&(e(pS(r)?mS(r.value):r.value),_e!==null&&n.add(_e)),en(()=>{j&&r.type==="checkbox"&&bk();var i=t();if(r===document.activeElement){var o=pr?gs:_e;if(n.has(o))return}pS(r)&&i===mS(r.value)||r.type==="date"&&!i&&!r.value||i!==r.value&&(r.value=i??"")})}function pS(r){var t=r.type;return t==="number"||t==="range"}function mS(r){return r===""?null:+r}function fS(r,t){return r===t||r?.[yn]===t}function xn(r=ih(),t,e,n){var i=rt.r,o=we;return Cr(()=>{var s,a;return en(()=>{s=a,a=n?.()||[],pt(()=>{fS(e(...a),r)||(t(r,...a),s&&fS(e(...s),r)&&t(null,...s))})}),()=>{let l=o;for(;l!==i&&l.parent!==null&&l.parent.f&33554432;)l=l.parent;let c=()=>{a&&fS(e(...a),r)&&t(null,...a)},d=l.teardown;l.teardown=()=>{c(),d?.()}}}),r}function X(r,t,e,n){var i=!ya||(e&2)!==0,o=(e&8)!==0,s=(e&16)!==0,a=n,l=!0,c=void 0,d=()=>s&&i?(c??(c=Il(n)),f(c)):(l&&(l=!1,a=s?pt(n):n),a);let u;if(o){var p=yn in r||Kf in r;u=di(r,t)?.set??(p&&t in r?w=>r[t]=w:void 0)}var m,h=!1;o?[m,h]=Ek(()=>r[t]):m=r[t],m===void 0&&n!==void 0&&(m=d(),u&&(i&&qR(t),u(m)));var g;if(i?g=()=>{var w=r[t];return w===void 0?d():(l=!0,w)}:g=()=>{var w=r[t];return w!==void 0&&(a=void 0),w===void 0?a:w},i&&(e&4)===0)return g;if(u){var v=r.$$legacy;return(function(w,T){return arguments.length>0?((!i||!T||v||h)&&u(T?g():w),w):g()})}var b=!1,y=((e&1)!==0?Il:nd)(()=>(b=!1,g()));j&&(y.label=t),o&&f(y);var C=we;return(function(w,T){if(arguments.length>0){let P=T?f(y):i&&o?Ze(w):w;return q(y,P),b=!0,a!==void 0&&(a=P),w}return Pi&&b||(C.f&16384)!==0?y.v:f(y)})}function iD(r){return new gS(r)}var ka,mo,gS=class{constructor(t){qe(this,ka);qe(this,mo);var e=new Map,n=(o,s)=>{var a=ed(s,!1,!1);return e.set(o,a),a};let i=new Proxy({...t.props||{},$$events:{}},{get(o,s){return f(e.get(s)??n(s,Reflect.get(o,s)))},has(o,s){return s===Kf?!0:(f(e.get(s)??n(s,Reflect.get(o,s))),Reflect.has(o,s))},set(o,s,a){return q(e.get(s)??n(s,a),a),Reflect.set(o,s,a)}});Oe(this,mo,(t.hydrate?iS:gd)(t.component,{target:t.target,anchor:t.anchor,props:i,context:t.context,intro:t.intro??!1,recover:t.recover,transformError:t.transformError})),!pr&&(!t?.props?.$$host||t.sync===!1)&&cd(),Oe(this,ka,i.$$events);for(let o of Object.keys(L(this,mo)))o==="$set"||o==="$destroy"||o==="$on"||jr(this,o,{get(){return L(this,mo)[o]},set(s){L(this,mo)[o]=s},enumerable:!0});L(this,mo).$set=o=>{Object.assign(i,o)},L(this,mo).$destroy=()=>{op(L(this,mo))}}$set(t){L(this,mo).$set(t)}$on(t,e){L(this,ka)[t]=L(this,ka)[t]||[];let n=(...i)=>e.call(this,...i);return L(this,ka)[t].push(n),()=>{L(this,ka)[t]=L(this,ka)[t].filter(i=>i!==n)}}$destroy(){L(this,mo).$destroy()}};ka=new WeakMap,mo=new WeakMap;var IK;typeof HTMLElement=="function"&&(IK=class extends HTMLElement{constructor(t,e,n){super();fe(this,"$$ctor");fe(this,"$$s");fe(this,"$$c");fe(this,"$$cn",!1);fe(this,"$$d",{});fe(this,"$$r",!1);fe(this,"$$p_d",{});fe(this,"$$l",{});fe(this,"$$l_u",new Map);fe(this,"$$me");fe(this,"$$shadowRoot",null);this.$$ctor=t,this.$$s=e,n&&(this.$$shadowRoot=this.attachShadow(n))}addEventListener(t,e,n){if(this.$$l[t]=this.$$l[t]||[],this.$$l[t].push(e),this.$$c){let i=this.$$c.$on(t,e);this.$$l_u.set(e,i)}super.addEventListener(t,e,n)}removeEventListener(t,e,n){if(super.removeEventListener(t,e,n),this.$$c){let i=this.$$l_u.get(e);i&&(i(),this.$$l_u.delete(e))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let t=function(i){return o=>{let s=Wo("slot");i!=="default"&&(s.name=i),A(o,s)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;let e={},n=PK(this);for(let i of this.$$s)i in n&&(i==="default"&&!this.$$d.children?(this.$$d.children=t(i),e.default=!0):e[i]=t(i));for(let i of this.attributes){let o=this.$$g_p(i.name);o in this.$$d||(this.$$d[o]=vS(o,i.value,this.$$p_d,"toProp"))}for(let i in this.$$p_d)!(i in this.$$d)&&this[i]!==void 0&&(this.$$d[i]=this[i],delete this[i]);this.$$c=iD({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:e,$$host:this}}),this.$$me=Hk(()=>{en(()=>{this.$$r=!0;for(let i of hk(this.$$c)){if(!this.$$p_d[i]?.reflect)continue;this.$$d[i]=this.$$c[i];let o=vS(i,this.$$d[i],this.$$p_d,"toAttribute");o==null?this.removeAttribute(this.$$p_d[i].attribute||i):this.setAttribute(this.$$p_d[i].attribute||i,o)}this.$$r=!1})});for(let i in this.$$l)for(let o of this.$$l[i]){let s=this.$$c.$on(i,o);this.$$l_u.set(o,s)}this.$$l={}}}attributeChangedCallback(t,e,n){this.$$r||(t=this.$$g_p(t),this.$$d[t]=vS(t,n,this.$$p_d,"toProp"),this.$$c?.$set({[t]:this.$$d[t]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{!this.$$cn&&this.$$c&&(this.$$c.$destroy(),this.$$me(),this.$$c=void 0)})}$$g_p(t){return hk(this.$$p_d).find(e=>this.$$p_d[e].attribute===t||!this.$$p_d[e].attribute&&e.toLowerCase()===t)||t}});function vS(r,t,e,n){let i=e[r]?.type;if(t=i==="Boolean"&&typeof t!="boolean"?t!=null:t,!n||!e[r])return t;if(n==="toAttribute")switch(i){case"Object":case"Array":return t==null?null:JSON.stringify(t);case"Boolean":return t?"":null;case"Number":return t??null;default:return t}else switch(i){case"Object":case"Array":return t&&JSON.parse(t);case"Boolean":return t;case"Number":return t!=null?+t:t;default:return t}}function PK(r){let t={};return r.childNodes.forEach(e=>{t[e.slot||"default"]=!0}),t}var iq=require("obsidian");je();ye();var FU=require("obsidian");Le();var Lh={location:"tab",direction:"vertical",mode:"default",focus:!0};function rn(r,t){if(!(t?.fillMissingOnly??!0))return{...Lh,...r??{}};let n={...r??{}};return n.location==null&&(n.location=Lh.location),n.direction==null&&(n.direction=Lh.direction),n.mode==null&&(n.mode=Lh.mode),n.focus==null&&(n.focus=Lh.focus),n}var HD=require("obsidian");Le();function up(r){return r.trim().replace(/^\/+/,"")}function Ul(r){return r.trim().toLowerCase().endsWith(".canvas")}function MS(r,t){let e=up(t);if(!e||e.includes("{{"))return null;let n=r.vault.getAbstractFileByPath(e);return!n||!(n instanceof HD.TFile)||n.extension!=="canvas"?null:n}function WD(r,t){let n=r.workspace.getMostRecentLeaf?.()?.view;if(!n||n.getViewType?.()!=="canvas")return null;let i=up(t),o=up(n.file?.path??r.workspace.getActiveFile()?.path??"");if(!i||i!==o)return null;let s=n.canvas?.selection?Array.from(n.canvas.selection):[];if(s.length!==1)return null;let a=s[0]?.id;return typeof a=="string"&&a.length>0?a:null}function RK(r){return typeof r=="string"?r:r&&typeof r=="object"&&"path"in r&&typeof r.path=="string"?r.path:"(missing file path)"}function OK(r){return typeof r.x!="number"||typeof r.y!="number"||typeof r.width!="number"||typeof r.height!="number"?"":`${Math.round(r.x)},${Math.round(r.y)} \xB7 ${Math.round(r.width)}x${Math.round(r.height)}`}function FS(r,t){return r.length<=t?r:r.slice(0,t-1)+"\u2026"}async function GD(r,t){try{let e=await r.vault.cachedRead(t),n=JSON.parse(e);if(!n||typeof n!="object")return[];let i=n.nodes;if(!Array.isArray(i))return[];let o=i.filter(a=>!!a&&typeof a=="object"&&typeof a.id=="string").map(a=>{let l=a.type==="text"?"text":a.type==="file"?"file":"other",c=OK(a);if(l==="text"){let h=(typeof a.text=="string"?a.text:"").split(`
|
||
`).map(y=>y.trim()).filter(y=>y.length>0),g=FS(h[0]??"(empty text card)",90),v=[`${h.length} line${h.length===1?"":"s"}`];c&&v.push(c);let b=v.join(" \xB7 ");return{id:a.id,type:l,title:g,subtitle:b,searchText:`${a.id} ${g} ${b}`.toLowerCase(),capturable:!0,capturableReason:""}}if(l==="file"){let m=RK(a.file),h=xt.test(m),g=h?"":"Canvas file cards must link to markdown files (.md).",v=FS(m.split("/").pop()??m,90),b=[FS(m,120)];c&&b.push(c),h||b.push("Not capturable in this version");let y=b.join(" \xB7 ");return{id:a.id,type:l,title:v,subtitle:y,searchText:`${a.id} ${v} ${y}`.toLowerCase(),capturable:h,capturableReason:g}}let u=`Unsupported node (${typeof a.type=="string"&&a.type.length>0?a.type:"unknown"})`,p=c||"Type is not currently capturable";return{id:a.id,type:l,title:u,subtitle:p,searchText:`${a.id} ${u} ${p}`.toLowerCase(),capturable:!1,capturableReason:"This Canvas node type is not capturable."}}),s={text:0,file:1,other:2};return o.sort((a,l)=>{let c=s[a.type]-s[l.type];return c!==0?c:a.title.localeCompare(l.title)})}catch{return[]}}Jt();Nh();Ms();an();lt();Le();var JK=["noteContent","propertyValue","captureTarget","fileName","lineTarget"],ZK=["captureTarget","fileName"],dr=JK,s0=3;function Ce(r,t,e=r.endsWith(":}}")?2:0){return{insert:r,description:t,caretOffset:e}}var eQ=[{regex:xD,contexts:dr,suggestion:Ce("{{VALUE}}","Asks you for text when the choice runs")},{regex:ED,contexts:dr,suggestion:Ce("{{VALUE:}}","Asks once and reuses the answer by name, or lists options to pick from"),expansions:()=>[Ce("{{VALUE:title}}",'Asks once, then reuses the answer as "title"'),Ce("{{VALUE:option1,option2,option3}}","Asks you to pick one of these options"),Ce("{{VALUE:option1,option2,option3|custom}}","Same, but you can also type your own"),Ce("{{VALUE:title|label:Note title}}","Words the prompt yourself"),Ce("{{VALUE:option1,option2|label:Pick one}}","A list with your own prompt text"),Ce("{{VALUE:title|label:Note title|default:Untitled}}","Opens the prompt with an answer already filled in"),Ce("{{VALUE:<items>|text:<display items>}}","Shows one label in the list and inserts another"),Ce("{{VALUE:option1,option2|name:category}}","Names the pick, so {{VALUE:category}} reuses it"),Ce("{{VALUE:title|case:kebab}}","Reshapes the answer; type |case: for every style"),Ce("{{VALUE:title|trim}}","Trims whitespace off the answer"),Ce("{{VALUE:title|optional}}","Lets the prompt be skipped, leaving it empty")]},{regex:CD,contexts:dr,suggestion:Ce("{{NAME}}","Another name for {{VALUE}}; they do the same thing")},{regex:TD,contexts:dr,suggestion:Ce("{{VDATE:}}",'Asks you for a date; "tomorrow" works'),expansions:()=>[Ce("{{VDATE:date,YYYY-MM-DD}}",'Asks for a date, reused by name as "date"'),Ce("{{VDATE:date,YYYY-MM-DD|today}}","Same, with today filled in"),Ce("{{VDATE:dueDate,YYYY-MM-DD|next monday}}","Same, starting at next Monday"),Ce("{{VDATE:dueDate,YYYY-MM-DD|optional}}","Same, but skippable"),Ce("{{VDATE:date,dddd, MMMM Do, YYYY|case:lower}}","Lowercases the picked date after formatting")]},{regex:PD,contexts:dr,suggestion:Ce("{{FIELD:}}","Suggests values a property already has in your vault, like {{FIELD:project}}")},{regex:OD,contexts:["noteContent","propertyValue"],suggestion:Ce("{{PROPERTY}}","Inserts the property's current value (property Captures only)")},{regex:DD,contexts:["noteContent"],suggestion:Ce("{{CURSOR}}","Places the cursor here (Capture and Template bodies)")},{regex:ID,contexts:dr,suggestion:Ce("{{FILE:}}","Picks a note from a folder"),expansions:({context:r})=>{let t=[Ce("{{FILE:<folder>}}","Picks a note from that folder and inserts its name")];return ZK.includes(r)||t.push(Ce("{{FILE:<folder>|link}}","Same, but inserts a link to the note"),Ce("{{FILE:<folder>|path}}","Same, but inserts its full path"),Ce("{{FILE:<folder>|type:image|link}}","Same, but links an image instead of a note"),Ce("{{FILE:<folder>|optional}}","Same, but skippable")),t.push(Ce("{{FILE:<folder>|custom}}","Same, but you can also type a name that is not there yet")),t}},{regex:MD,contexts:dr,suggestion:Ce("{{MVALUE}}","Asks you for a math formula (LaTeX), with a live preview")},{regex:bD,contexts:dr,suggestion:Ce("{{DATE}}","Today's date, as YYYY-MM-DD")},{regex:wD,contexts:dr,suggestion:Ce("{{DATE:}}","Today's date in a format you choose, like {{DATE:MMMM Do}}"),expansions:({formatDate:r})=>[...["YYYY-MM-DD","MMMM Do, YYYY","ddd D MMM","gggg-[W]ww"].map(t=>Ce(`{{DATE:${t}}}`,r(t))),Ce("{{DATE+7}}","Seven days from today"),Ce("{{DATE:YYYY-MM-DD|startof:week}}","Snapped to the start of the week, month, quarter or year"),Ce("{{DATE:dddd, MMMM Do, YYYY|case:lower}}","Lowercases the formatted date")]},{regex:UD,contexts:dr,suggestion:Ce("{{TIME}}","The current time, as HH:mm")},{regex:qD,contexts:dr,suggestion:Ce("{{TIME:}}","The current time in a format you choose, like {{TIME:HH.mm}}"),expansions:()=>[Ce("{{TIME:A|case:lower}}","Lowercases formatted text, such as AM to am")]},{regex:SS,contexts:dr,suggestion:Ce("{{DAILY}}","The daily note's path, from your Daily notes settings")},{regex:SS,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{DAILY|link}}","A link to the daily note")},{regex:AS,contexts:dr,suggestion:Ce("{{WEEKLY}}","This week's note, from your Periodic Notes settings")},{regex:AS,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{WEEKLY|link}}","A link to this week's note")},{regex:IS,contexts:dr,suggestion:Ce("{{MONTHLY}}","This month's note, from your Periodic Notes settings")},{regex:IS,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{MONTHLY|link}}","A link to this month's note")},{regex:PS,contexts:dr,suggestion:Ce("{{QUARTERLY}}","This quarter's note, from your Periodic Notes settings")},{regex:PS,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{QUARTERLY|link}}","A link to this quarter's note")},{regex:$S,contexts:dr,suggestion:Ce("{{YEARLY}}","This year's note, from your Periodic Notes settings")},{regex:$S,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{YEARLY|link}}","A link to this year's note")},{regex:_D,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{LINKCURRENT}}","A link to that note: [[That note]]")},{regex:kD,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{LINKSECTION}}","A link to the section your cursor is in")},{regex:SD,contexts:["noteContent","propertyValue","captureTarget","fileName","lineTarget"],suggestion:Ce("{{FILENAMECURRENT}}","That note's file name")},{regex:kS,contexts:["noteContent","propertyValue","captureTarget"],suggestion:Ce("{{FOLDERCURRENT}}","That note's folder")},{regex:kS,contexts:["fileName"],suggestion:Ce("{{FOLDERCURRENT|name}}","That note's folder name, without the path")},{regex:LD,contexts:dr,suggestion:Ce("{{SELECTED}}","The text you had selected in the editor")},{regex:RD,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Ce("{{TITLE}}","The new note's file name")},{regex:AD,contexts:["fileName"],suggestion:Ce("{{FOLDER|name}}","The name of the folder the new note lands in")},{regex:ND,contexts:dr,suggestion:Ce("{{CLIPBOARD}}","Whatever you copied last")},{regex:$D,contexts:dr,suggestion:Ce("{{TEMPLATE:}}","The contents of a template file"),expansions:({templatePaths:r})=>r.map(t=>Ce(`{{TEMPLATE:${t}}}`,"Inserts this template's contents"))},{regex:FD,contexts:dr,suggestion:Ce("{{MACRO:}}","Whatever a macro returns"),expansions:({macroNames:r})=>[...r.map(t=>Ce(`{{MACRO:${t}}}`,`Runs your "${t}" macro`)),Ce("{{MACRO:MyMacro|label:Label}}","Word the macro's own prompt yourself")]},{regex:BD,contexts:dr,suggestion:Ce("{{GLOBAL_VAR:}}","A snippet you defined in QuickAdd's settings"),expansions:({globalVariableNames:r})=>r.map(t=>Ce(`{{GLOBAL_VAR:${t}}}`,`Inserts your "${t}" snippet`))},{regex:VD,contexts:dr,suggestion:Ce("{{RANDOM:}}","A random ID of the length you give, like {{RANDOM:6}}")}],a0=[{insert:"kebab",description:"my-note-title",caretOffset:0,isFragment:!0},{insert:"snake",description:"my_note_title",caretOffset:0,isFragment:!0},{insert:"camel",description:"myNoteTitle",caretOffset:0,isFragment:!0},{insert:"pascal",description:"MyNoteTitle",caretOffset:0,isFragment:!0},{insert:"title",description:"My Note Title",caretOffset:0,isFragment:!0},{insert:"lower",description:"my note title",caretOffset:0,isFragment:!0},{insert:"upper",description:"MY NOTE TITLE",caretOffset:0,isFragment:!0},{insert:"slug",description:"my-note-title, guarded against reserved file names",caretOffset:0,isFragment:!0}];function l0(r){return eQ.filter(t=>t.contexts.includes(r))}var tQ=/^\{\{(VALUE|NAME|DATE|TIME|VDATE)([^\n\r}]*)\|case:([a-z-]*)$/i,c0=/^\{\{GLOBAL_VAR:[ \t]*([^\n\r}]*)$/i,d0="{{GLOBAL_VAR:",rQ=new Set(["DATE","TIME","VDATE"]),nQ=/<[^<>\n\r]+>/,ln=class extends Er{constructor(e,n,i,o="noteContent"){super(e,n);this.app=e;this.inputEl=n;this.plugin=i;this.context=o;this.replaceFrom=0;this.completingGlobalVarName=!1;this.matchedQuery="";this.macroNames=Zt(this.plugin.settings.choices).filter(s=>s.type==="Macro").map(s=>s.name),this.templatePaths=this.plugin.getTemplateFiles().map(s=>s.path)}getSuggestions(e){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=e.lastIndexOf("{{",n-1);if(i===-1)return[];this.completingGlobalVarName=!1;let o=e.slice(i,n);if(o.includes("}}"))return[];let s=o.match(tQ);if(s){let g=s[1]?.toUpperCase()??"",v=s[2]??"";if(rQ.has(g)&&v.lastIndexOf("[")>v.lastIndexOf("]"))return[];let b=s[3]??"";this.matchedQuery=b,this.replaceFrom=n-b.length;let y=b.toLowerCase();return a0.filter(C=>C.insert.startsWith(y)).map(C=>({...C}))}let a=o.match(c0);if(a){let g=a[1]??"";return this.replaceFrom=i,this.matchedQuery=`GLOBAL_VAR:${g}`,this.completingGlobalVarName=!0,Object.keys(this.plugin?.settings?.globalVariables??{}).filter(v=>v.toLowerCase().startsWith(g.toLowerCase())).map(v=>({insert:`${d0}${v}}}`,description:`Inserts your "${v}" snippet`,caretOffset:0}))}if(o.includes(":"))return[];let l=[],c=new Set,d=g=>{c.has(g.insert)||(c.add(g.insert),l.push(g))};this.replaceFrom=i,this.matchedQuery=o.slice(2);let u=l0(this.context).filter(g=>{let v=g.regex.exec(o);return v!==null&&v.index+v[0].length===o.length}),p=this.matchedQuery.toLowerCase(),m=g=>g.suggestion.insert.slice(2).toLowerCase().startsWith(p),h=[...u.filter(m),...u.filter(g=>!m(g))];for(let g of h)if(d(g.suggestion),!!g.expansions&&!(this.matchedQuery.length<s0))for(let v of g.expansions({templatePaths:this.templatePaths,macroNames:this.macroNames,globalVariableNames:Object.keys(this.plugin?.settings?.globalVariables??{}),context:this.context,formatDate:b=>typeof window.moment=="function"?window.moment().format(b):b}))d(v);return l}selectSuggestion(e){if(this.inputEl.selectionStart===null)return;let n=this.inputEl.selectionStart,i=this.replaceFrom,o=n;if(this.completingGlobalVarName){let a=this.inputEl.value,l=a.slice(i,n),c=c0.exec(l)?.[1],d=e.insert.slice(d0.length,-2);if(l.lastIndexOf("{{")!==0||c===void 0||!d.toLowerCase().startsWith(c.toLowerCase())){this.close();return}a.startsWith("}}",n)&&(o+=2)}lw(this.inputEl,i,o,e.insert,{fromCompletion:!0});let s=nQ.exec(e.insert);if(s){let a=i+s.index;this.inputEl.setSelectionRange(a,a+s[0].length)}else if(e.caretOffset>0){let a=i+e.insert.length-e.caretOffset;this.inputEl.setSelectionRange(a,a)}this.close()}renderSuggestion(e,n){if(!e)return;n.classList.add("qa-format-suggestion");let i=n.createSpan({cls:e.isFragment?"qa-format-suggestion-token qa-format-suggestion-token-fragment":"qa-format-suggestion-token"});this.renderMatch(i,e.insert,this.matchedQuery),n.createSpan({cls:"qa-format-suggestion-description",text:e.description})}};var iQ=F('<label class="setting-item-name"> </label>'),oQ=F('<div class="setting-item-name"> </div>'),sQ=F('<div class="setting-item-description"> </div>'),aQ=F('<div class="qa-field-body"><!></div>'),lQ=F('<div><div class="setting-item-info"><!> <!></div> <div class="setting-item-control"><!></div> <!></div>');function be(r,t){let e=X(t,"name",3,void 0),n=X(t,"desc",3,void 0),i=X(t,"heading",3,!1),o=X(t,"labelFor",3,void 0),s=X(t,"control",3,void 0),a=X(t,"children",3,void 0),l=X(t,"body",3,void 0);var c=lQ();let d;var u=R(c),p=R(u);{var m=w=>{var T=bt(),P=ae(T);{var _=D=>{var N=iQ(),K=re(N,!0);Q(()=>{le(N,"for",o()),ee(K,e())}),A(D,N)},I=D=>{var N=oQ(),K=re(N,!0);Q(()=>ee(K,e())),A(D,N)};z(P,D=>{o()?D(_):D(I,-1)})}A(w,T)};z(p,w=>{e()&&w(m)})}var h=E(p,2);{var g=w=>{var T=sQ(),P=re(T,!0);Q(()=>ee(P,n())),A(w,T)};z(h,w=>{n()&&w(g)})}$(u);var v=E(u,2),b=R(v);Rl(b,()=>s()??a()??$t),$(v);var y=E(v,2);{var C=w=>{var T=aQ(),P=R(T);Rl(P,l),$(T),A(w,T)};z(y,w=>{l()&&w(C)})}$(c),Q(()=>{d=Ge(c,1,"setting-item",null,d,{"setting-item-heading":i(),"qa-field":l()!==void 0}),le(c,"tabindex",i()?void 0:-1)}),A(r,c)}var cQ=F('<div class="setting-item setting-item-heading"><div class="setting-item-name"> </div> <div class="setting-item-control"></div></div>'),dQ=F('<div class="setting-group"><!> <div class="setting-items"><!></div></div>');function yo(r,t){let e=X(t,"heading",3,void 0);var n=dQ(),i=R(n);{var o=l=>{var c=cQ(),d=R(c),u=re(d,!0);Xt(2),$(c),Q(()=>ee(u,e())),A(l,c)};z(i,l=>{e()&&l(o)})}var s=E(i,2),a=R(s);Rl(a,()=>t.children),$(s),$(n),A(r,n)}var uQ=F('<div role="switch"><input type="checkbox" tabindex="-1" aria-hidden="true" class="svelte-ecj6o4"/></div>'),pQ={hash:"svelte-ecj6o4",code:`
|
||
/* Let clicks fall through to the container so a single handler owns toggling. */.checkbox-container.svelte-ecj6o4 > input:where(.svelte-ecj6o4) {pointer-events:none;}`};function vt(r,t){ie(t,!0),Ae(r,pQ);let e=X(t,"checked",15),n=X(t,"disabled",3,!1),i=X(t,"ariaLabel",3,void 0),o=X(t,"onchange",3,void 0),s=k(()=>e()??!1);function a(){n()||(e(!f(s)),o()?.(e()))}function l(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),a())}var c=uQ();let d;var u=R(c);Ct(u),$(c),Q(()=>{d=Ge(c,1,"checkbox-container svelte-ecj6o4",null,d,{"is-enabled":f(s),"is-disabled":n()}),le(c,"aria-checked",f(s)),le(c,"aria-label",i()),le(c,"tabindex",n()?-1:0),bd(u,f(s))}),ge("click",c,a),ge("keydown",c,l),A(r,c),oe()}He(["click","keydown"]);var mQ=F("<option> </option>"),fQ=F('<select class="dropdown"></select>');function it(r,t){ie(t,!0);let e=X(t,"value",15,""),n=X(t,"disabled",3,!1),i=X(t,"ariaLabel",3,void 0),o=X(t,"onchange",3,void 0);var s=fQ();gt(s,21,()=>t.options,a=>a.value,(a,l)=>{var c=mQ(),d=re(c,!0),u={};Q(()=>{ee(d,f(l).label),u!==(u=f(l).value)&&(c.value=(c.__value=u)??"")}),A(a,c)}),$(s),Ll(s),Q(()=>{s.disabled=n(),le(s,"aria-label",i())}),ge("change",s,()=>o()?.(e())),cS(s,e),A(r,s),oe()}He(["change"]);hp();Ms();an();var vi=class extends Er{constructor(e,n,i,o=1/0){super(e,n);this.app=e;this.inputEl=n;this.items=i;this.maxSuggestions=o;this.matchesByItem=new Map;this.items=i.map(s=>sn(s))}getSuggestions(e){let n=Hl(zl(e),this.items,i=>i,{limit:this.maxSuggestions});return this.matchesByItem=new Map(n.map(({item:i,matches:o})=>[i,o])),n.map(({item:i})=>i)}selectSuggestion(e){this.inputEl.value=e,Pa(this.inputEl),this.close()}renderSuggestion(e,n){Fs(n,aw(e),this.matchesByItem.get(e)??[])}};function hQ(r){return r?Array.isArray(r)?r:[r]:[]}function Id(r,t){let e=hQ(t(r));return{destroy(){e.forEach(n=>n.destroy())}}}Hh();var bQ=F("<textarea></textarea>"),wQ=F('<input type="text"/>'),CQ=F('<!> <div aria-live="polite"> </div>',1);function Lr(r,t){ie(t,!0);let e=X(t,"value",15,""),n=X(t,"placeholder",3,void 0),i=X(t,"inputKind",3,"text"),o=X(t,"required",3,!1),s=X(t,"requiredMessage",3,"This field is required"),a=X(t,"disabled",3,!1),l=X(t,"validator",3,void 0),c=X(t,"trim",3,!0),d=X(t,"suggestions",3,void 0),u=X(t,"maxSuggestions",3,1/0),p=X(t,"makeSuggesters",19,()=>[]),m=X(t,"app",3,void 0),h=X(t,"id",3,void 0),g=X(t,"ariaLabel",3,void 0),v=X(t,"onChange",3,void 0),b=pe(!1),y=pe(!1),C=pe(""),w=pe("neutral"),T=0,P=!1,_=`qa-hint-${Math.random().toString(36).slice(2)}`,I=te=>c()?te.trim():te;function D(te,W=!1,Z="neutral"){q(b,W,!0),q(C,te??"",!0),q(w,W?"neutral":Z,!0)}async function N(te){if(o()&&I(te).length===0)return D(f(y)?s():void 0,f(y)),!1;if(!l())return D(void 0),!0;let W=++T,Z=await Promise.resolve(l()(te));return W!==T||P?!0:typeof Z=="boolean"?(D(Z?void 0:"Invalid value",!Z),Z):typeof Z=="string"?(D(Z,!0),!1):(D(Z.message??(Z.valid?void 0:"Invalid value"),!Z.valid,Z.valid?Z.variant??"neutral":"neutral"),Z.valid)}function K(te){let W=te.currentTarget.value;q(y,!0),e(W),v()?.(W)}Dt(()=>{o(),f(y);let te=e();N(te)}),Dt(()=>()=>{P=!0});function ne(te){let W=[];m()&&d()&&d().length&&W.push(new vi(m(),te,d(),u()));for(let Z of p()){let se=Z(te);se&&W.push(se)}return W}var H=CQ(),O=ae(H);{var G=te=>{var W=bQ();rd(W);let Z;le(W,"spellcheck",!1),Ft(W,(se,ce)=>Id?.(se,ce),()=>ne),Ft(W,se=>pw?.(se)),Q(()=>{Z=Ge(W,1,"qa-validated-input-full-width qa-validated-input-margin-8 qa-validated-input-textarea",null,Z,{"is-invalid":f(b),"is-valid":!f(b)&&f(w)==="success"&&f(C).length>0}),le(W,"id",h()),le(W,"placeholder",n()),W.disabled=a(),le(W,"aria-label",g()),le(W,"aria-invalid",f(b)),le(W,"aria-describedby",_),Jn(W,e())}),ge("input",W,K),Kn("blur",W,()=>q(y,!0)),A(te,W)},V=te=>{var W=wQ();Ct(W);let Z;le(W,"spellcheck",!1),Ft(W,(se,ce)=>Id?.(se,ce),()=>ne),Q(()=>{Z=Ge(W,1,"qa-validated-input-full-width qa-validated-input-margin-8",null,Z,{"is-invalid":f(b),"is-valid":!f(b)&&f(w)==="success"&&f(C).length>0}),le(W,"id",h()),le(W,"placeholder",n()),W.disabled=a(),le(W,"aria-label",g()),le(W,"aria-invalid",f(b)),le(W,"aria-describedby",_),Jn(W,e())}),ge("input",W,K),Kn("blur",W,()=>q(y,!0)),A(te,W)};z(O,te=>{i()==="textarea"?te(G):te(V,-1)})}var M=E(O,2);let B;var J=re(M,!0);Q(()=>{B=Ge(M,1,"qa-field-hint",null,B,{"qa-field-hint--neutral":!f(b)&&f(w)==="neutral","qa-field-hint--success":!f(b)&&f(w)==="success"}),le(M,"id",_),ee(J,f(C))}),A(r,H),oe()}He(["input"]);function ni(r,t){let e=Ri(),n=a=>{var l=bt(),c=ae(l);Rl(c,()=>t.children,()=>e),A(a,l)},i=X(t,"desc",3,void 0),o=X(t,"control",3,void 0),s=X(t,"bodyVisible",3,!0);{let a=k(()=>s()?e:void 0),l=k(()=>s()?n:void 0);be(r,{get name(){return t.name},get desc(){return i()},get control(){return o()},get labelFor(){return f(a)},get body(){return f(l)}})}}Ma();Op();function SA(r){let t=r.replace(/^\[(QuickAdd:[\s\S]*)\]$/i,"$1");if(/^QuickAdd:/i.test(t))return t.replace(/^QuickAdd:\s*/i,"");let e=t.replace(/^QuickAdd\s+/,"");return e===t?t:e.charAt(0).toUpperCase()+e.slice(1)}var Dp=class{formatOutputString(t){return`QuickAdd: (${t.level}) ${SA(t.message)}`}getQuickAddError(t,e,n,i){return{message:t,level:e,time:Date.now(),stack:n,originalError:i}}};nt();var tc=class{constructor(){this.entries=[];this.seen=new Set}add(t,e,n){let i=SA(e).trim();if(!i)return;let o=`${t} ${i}`;this.seen.has(o)||(this.seen.add(o),this.entries.push({severity:t,message:i,...n?{kind:n}:{}}))}list(){return this.entries}get hasError(){return this.entries.some(t=>t.severity==="error")}};function Lp(r){if(Be(r))return null;if(!(r instanceof Error))return zL;let t=r.message??"";return Be(t)?null:t.startsWith("Unable to parse variable")?"This token is incomplete. {{VALUE:}} needs a name, for example {{VALUE:title}}.":t.trim()?t:zL}var zL="Preview unavailable - this format could not be resolved.";es();var Q3={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"},X3={clipboard:"clipboard_content",date:"formatted_date",time:"current_time",random:"random_value",uuid:"unique_id"},J3=[{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 ZL(r){let t=r.toLowerCase(),e=Q3[t];return e||`${r}_example`}function eN(r){return X3[r.toLowerCase()]||`${r}_output`}function tN(r){for(let{pattern:t,example:e}of J3)if(t.test(r))return e;return`${r}_value`}function Cg(r){return r.length>0?`${r[0]} (${r.length} options)`:"suggestion_list"}function rN(r,t){return Hd(r).length>0?t:r}function nN(r){let t=r.fieldName.trim();return t?`${t}_field_value`:"field_value"}function iN(r){return r?.path?r.basename:"current_file"}function AA(r){return`${r?.path?r.basename:"current_file"}#Section`}function oN(r){return r?.basename||"current_filename"}function sN(r){if(!r)return"current_folder";let t=r.parent?.path??"";return t==="/"?"":t}var qa=class{static generate(t,e=new Date){let n=e.getFullYear(),i=this.getWeekNumber(e),o=e.getDate(),s=[["YYYY",n.toString()],["YY",n.toString().slice(-2)],["MMMM",this.MONTH_NAMES[e.getMonth()]],["MMM",this.MONTH_NAMES_SHORT[e.getMonth()]],["MM",(e.getMonth()+1).toString().padStart(2,"0")],["M",(e.getMonth()+1).toString()],["dddd",this.DAY_NAMES[e.getDay()]],["ddd",this.DAY_NAMES_SHORT[e.getDay()]],["Do",`${o}${this.ordinalSuffix(o)}`],["DD",e.getDate().toString().padStart(2,"0")],["D",o.toString()],["HH",e.getHours().toString().padStart(2,"0")],["H",e.getHours().toString()],["mm",e.getMinutes().toString().padStart(2,"0")],["m",e.getMinutes().toString()],["ss",e.getSeconds().toString().padStart(2,"0")],["s",e.getSeconds().toString()],["ww",i.toString().padStart(2,"0")],["w",i.toString()]],a="",l=0;for(;l<t.length;){let c=!1;for(let[d,u]of s)if(t.startsWith(d,l)){a+=u,l+=d.length,c=!0;break}c||(a+=t[l],l+=1)}return a}static ordinalSuffix(t){let e=t%100;if(e>=11&&e<=13)return"th";switch(t%10){case 1:return"st";case 2:return"nd";case 3:return"rd";default:return"th"}}static getWeekNumber(t){let e=new Date(t.getFullYear(),0,1),n=(t.getTime()-e.getTime())/864e5;return Math.ceil((n+e.getDay()+1)/7)}};qa.MONTH_NAMES=["January","February","March","April","May","June","July","August","September","October","November","December"],qa.MONTH_NAMES_SHORT=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],qa.DAY_NAMES=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],qa.DAY_NAMES_SHORT=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];Rd();ig();function aN(r){let t=new Date;return r?_p(window.moment(t),r).toDate():t}bi();Ln();xo();var Bp=class extends ec{constructor(){super(...arguments);this.diagnostics=new tc}warn(e){this.diagnostics.add("warning",e)}reportProblem(e){this.diagnostics.add("error",e)}standIn(e,n){return e}promptForValue(e){return this.standIn(e||this.valuePromptContext?.label||"user input","user input")}getVariableValue(e){let n=this.variables.get(e);if(typeof n=="string")return n;let i=tA(e);return this.standIn(ZL(i),"user input")}async promptForVariable(e,n){let i=lg(this.variables,n?.variableKey??e);return i?qa.generate(i):this.standIn(tN(e),"user input")}getMacroValue(e,n){return this.standIn(eN(e),"macro_output")}async suggestForField(e,n){return this.standIn(nN(n),"field_value")}getCurrentFileLink(){return this.app?iN(this.app.workspace.getActiveFile()):null}getCurrentFileLinkToSection(){return this.app?AA(this.app.workspace.getActiveFile()):AA(null)}getCurrentFileName(){return this.app?oN(this.app.workspace.getActiveFile()):"current_filename"}getCurrentFolderPath(){return this.app?sN(this.app.workspace.getActiveFile()):"current_folder"}previewDateVariable(e,n,i,o){let{withTime:s,snap:a,caseStyle:l}=o,c=i?.trim()||ag(s);iA(this.variables,n,c);let d=dg(this.variables.get(n),c,a,this.dateParser);if(d)return{format:c,text:this.applyCaseOption(d.text,l,e),answered:!0};try{let u=qa.generate(c,aN(a));return{format:c,text:this.applyCaseOption(u,l,e),answered:!1}}catch{return{format:c,answered:!1}}}promptForMathValue(){return Promise.resolve("calculation_result")}async getSelectedText(){return"selected_text"}async getClipboardContent(){return"clipboard_content"}suggestForFile(e){let n=this.app?Vp(this.app,e):[];return n.length>0?`${Jl}${n[0].path}`:`${Jo}${e.folderPath||"file"}`}isTemplatePropertyTypesEnabled(){return!1}};Tg();Wd();Jt();Le();Qd();sg();var Yp=class extends Bp{constructor(e,n,i,o={}){super(e);this.plugin=n;this.opts=o;this.dateParser=i||So}async format(e){this.diagnostics=new tc;try{return On(await this.formatInternal(e,{expandLinebreakEscapes:!0}))}catch(n){let i=Lp(n);return i&&this.diagnostics.add("error",i),On(e)}}async formatInternal(e,{expandLinebreakEscapes:n}){let i=e;return i=await this.replaceGlobalVarInString(i),i=qi(i),n&&(i=this.expandLinebreakEscapesOutsideTokens(i)),i=this.replaceDateInString(i),i=this.replaceTimeInString(i),i=await this.replaceValueInString(i),i=await this.replaceSelectedInString(i),i=await this.replaceClipboardInString(i),i=await this.replaceDateVariableInString(i),i=await this.replaceVariableInString(i),i=this.replaceCurrentFileTokensInString(i,{links:!0,fileName:!0,folder:!0,...this.opts.resolveActiveFolder===!1?{}:{activeFolder:"content"}}),i=await this.replaceMacrosInString(i),i=await this.replaceTemplateInString(i),i=await this.replaceFieldVarInString(i),i=await this.replaceFileInString(i),i=await this.replaceMathValueInString(i),i=this.replaceRandomInString(i),i}async replaceGlobalVarInString(e){return rc(e,this.plugin?.settings?.globalVariables)}suggestForValue(e,n=!1,i){return Cg(i?.displayValues??e)}suggestForValueMulti(e,n,i){return[Cg(i?.displayValues??e)]}async getTemplateContent(e){let n=this.app;if(!n)return this.reportProblem(`Template preview unavailable: ${e}`),`[QuickAdd: template preview unavailable] ${e}`;let i=nn(n,e);if(!i)return this.reportProblem(`Template not found: ${e}`),`[QuickAdd: template not found] ${e}`;this.templateInclusion??(this.templateInclusion={visited:new Set,depth:0}),this.templateInclusion.depth++;try{return await this.formatInternal(await n.vault.cachedRead(i),{expandLinebreakEscapes:!1})}catch(o){let s=Lp(o);return s&&this.diagnostics.add("error",s),`[QuickAdd: template preview failed] ${e}`}finally{this.templateInclusion.depth--}}async replaceDateVariableInString(e){return e.replace(new RegExp(Ss.source,"gi"),(n,i,o,s)=>{let{options:a,error:l}=Iw(s);l&&this.reportProblem(l);let c=i?.trim();if(!c)return n;let d=this.previewDateVariable(n,c,o,a);if(d.answered)return d.text;let u=d.text??`[${d.format} format]`;return a.defaultValue&&(u+=` (default: ${a.defaultValue})`),a.optional&&(u+=" (optional)"),u})}replaceRandomInString(e){let n=e;return n=n.replace(/{{RANDOM:(\d+)}}/gi,(i,o)=>{let s=parseInt(o);if(s<=0||s>100)return i;let a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",l="";for(let c=0;c<Math.min(s,8);c++)l+=a.charAt(Math.floor(Math.random()*a.length));return s>8&&(l+=`... (${s} chars)`),l}),n}};Ma();Tg();Wd();Op();sg();var Kp=require("obsidian");Le();Qd();es();Jt();var $1=25;function x6(r){let t=r.lastIndexOf("{{");return t===-1?!1:r.indexOf("}}",t+2)===-1}function E6(r){let t=yi(r);if(t.length===0)return r;let e="",n=0;for(let i of t)e+=r.slice(n,i.start),n=i.end;return e+r.slice(n)}var Qp=class extends Bp{constructor(e,n,i){super(e);this.plugin=n;this.templateIncludeBudget=$1;this.dateParser=i||So}setRunClocks(e){this.clocks=e}async format(e){let n=e;this.diagnostics=new tc,this.templateIncludeBudget=$1;try{n=On(await this.formatInternal(e,{included:!1}))}catch(o){let s=Lp(o);return s&&this.diagnostics.add("error",s),On(e)}this.reportCircularTitle(e,n);let i=XL(n);for(let o of i.problems)this.diagnostics.add("error",o,"path");return this.reportIllegalChars(e,n),i.path}reportCircularTitle(e,n){!ho.test(e)&&!ho.test(n)||this.reportProblem("A file name cannot contain {{title}}, because the title is derived from the file name itself - so this choice would fail at run time.")}reportIllegalChars(e,n){if(this.diagnostics.hasError||x6(e)||oA(e))return;let i=Hd(E6(n));i.length!==0&&(this.existsInVault(n)||this.diagnostics.add("error",jL(i),"path"))}existsInVault(e){let n=this.app?.vault;if(typeof n?.getAbstractFileByPath!="function")return!1;let i=e.trim();return i?i.endsWith("/")?n.getAbstractFileByPath(i.slice(0,-1))instanceof Kp.TFolder:n.getAbstractFileByPath(i)instanceof Kp.TFile||n.getAbstractFileByPath(`${i}.md`)instanceof Kp.TFile?!0:n.getAbstractFileByPath(i)instanceof Kp.TFolder:!1}async formatInternal(e,{included:n}){let i=e;return i=await this.replaceTemplateOutsideScripts(i),i=await this.replaceGlobalVarInString(i),i=qi(i),i=await this.replaceMacrosInString(i),i=this.replaceDateInString(i),i=this.replaceTimeInString(i),i=await this.replaceValueInString(i),i=await this.replaceSelectedInString(i),i=await this.replaceClipboardInString(i),i=await this.replaceDateVariableInString(i),i=await this.replaceVariableInString(i),i=await this.replaceFieldVarInString(i),i=await this.replaceFileInString(i),i=await this.replaceMathValueInString(i),i=this.replaceCurrentFileTokensInString(i,n?{links:!0,fileName:!0,folder:!0,activeFolder:"content"}:{fileName:!0,folder:!0,activeFolder:"path"}),i=this.replaceRandomInString(i),i}async replaceGlobalVarInString(e){return rc(e,this.plugin?.settings?.globalVariables)}standIn(e,n){return rN(e,n)}suggestForValue(e,n=!1,i){return e[0]??Cg(e)}async replaceTemplateOutsideScripts(e){let n=yi(e);if(n.length===0)return this.replaceTemplateInString(e);let i="",o=0;for(let s of n)i+=await this.replaceTemplateInString(e.slice(o,s.start)),i+=e.slice(s.start,s.end),o=s.end;return i+await this.replaceTemplateInString(e.slice(o))}async getTemplateContent(e){let n=this.app;if(!n)return this.reportProblem(`Template preview unavailable: ${e}`),`[QuickAdd: template preview unavailable] ${e}`;if(this.templateIncludeBudget<=0){let o="[QuickAdd: too many template includes to preview]";return this.reportProblem(o),o}let i=nn(n,e);if(!i)return this.reportProblem(`Template not found: ${e}`),`[QuickAdd: template not found] ${e}`;this.templateIncludeBudget--,this.templateInclusion??(this.templateInclusion={visited:new Set,depth:0}),this.templateInclusion.depth++;try{let o=await n.vault.cachedRead(i),s=this.resolveTitleInIncludedBody(await this.formatInternal(o,{included:!0}));return this.warnIfJoinedIntoOneLine(e,s),s}catch(o){let s=Lp(o);return s&&this.diagnostics.add("error",s),`[QuickAdd: template preview failed] ${e}`}finally{this.templateInclusion.depth--}}resolveTitleInIncludedBody(e){if(!ho.test(e))return e;let n=this.variables.get("title"),i=typeof n=="string"?n:"";return e.replace(new RegExp(ho.source,"gi"),()=>i)}warnIfJoinedIntoOneLine(e,n){let i=n.split(/\r?\n/).filter(o=>o.trim());i.length<2||this.warn(`Template "${e}" is ${i.length} lines; a file name is one line, so they are joined with spaces.`)}async replaceDateVariableInString(e){return e.replace(new RegExp(Ss.source,"gi"),(n,i,o,s)=>{let a=i?.trim();if(!a)return n;let{options:l,error:c}=Iw(s);c&&this.reportProblem(c);let d=this.previewDateVariable(n,a,o,l);return d.text??`[${d.format}]`})}replaceRandomInString(e){let n=e;return n=n.replace(/{{RANDOM:(\d+)}}/gi,(i,o)=>{let s=parseInt(o);if(s<=0||s>100)return i;let a="ABC123",l="";for(let c=0;c<Math.min(s,6);c++)l+=a.charAt(c%a.length);return s>6&&(l+="..."),l}),n}};var T6=F('<div><span class="qa-visually-hidden"> </span> </div>'),_6=F('<div class="qa-preview-issues"></div>'),k6=F('<div><span class="qa-preview-label"> </span><span class="qa-preview-value" aria-live="polite"> </span></div> <!>',1);function Hi(r,t){ie(t,!0);let e=X(t,"formatterKind",3,"format"),n=500,i=pe(""),o=pe(Ze([])),s=pe(!1),a=0,l=k(()=>t.value.trim().length>0),c=k(()=>t.hideWhen?t.hideWhen(f(i))&&!f(o).some(v=>v.severity==="error"&&v.kind!=="path"):!1),d=k(()=>f(s)?f(o).filter(v=>v.severity==="error"):[]),u=k(()=>f(d).some(v=>v.kind!=="path")),p=k(()=>!f(u)&&f(d).length>0);Dt(()=>{let v=t.value;if(!v.trim()){a++,q(i,""),q(o,[],!0);return}let b=e()==="fileName"?new Qp(t.app,t.plugin):new Yp(t.app,t.plugin,void 0,{resolveActiveFolder:e()!=="lineTarget"});b.setTargetFolderPath(t.targetFolderPath===null?null:t.targetFolderPath?.trim()?t.targetFolderPath:"Folder/Name");let y=++a;(async()=>{try{let C=await b.format(v);if(y!==a)return;q(i,C,!0),q(o,b.diagnostics.list(),!0)}catch{if(y!==a)return;q(i,v,!0),q(o,[{severity:"error",message:"Preview unavailable."}],!0)}})()}),Dt(()=>{t.value,q(s,!1);let v=setTimeout(()=>{q(s,!0)},n);return()=>clearTimeout(v)});var m=bt(),h=ae(m);{var g=v=>{var b=k6(),y=ae(b);let C;var w=R(y),T=re(w,!0),P=E(w),_=re(P,!0);$(y);var I=E(y,2);{var D=N=>{var K=_6();gt(K,21,()=>f(o),ne=>ne.severity+ne.message,(ne,H)=>{var O=T6();let G;var V=R(O),M=re(V,!0),B=E(V,1,!0);$(O),Q(()=>{G=Ge(O,1,"qa-preview-issue",null,G,{"qa-preview-issue--error":f(H).severity==="error"}),le(O,"title",f(H).message),ee(M,f(H).severity==="error"?"Error: ":"Warning: "),ee(B,f(H).message)}),A(ne,O)}),$(K),A(N,K)};z(I,N=>{f(s)&&f(o).length>0&&N(D)})}Q(()=>{C=Ge(y,1,"qa-preview-row",null,C,{"qa-preview-row--one-line":e()==="fileName"}),le(y,"title",e()==="fileName"?f(i):void 0),ee(T,f(u)?"Unresolved: ":f(p)?"Won't be created: ":"Preview: "),ee(_,f(i))}),A(v,b)};z(h,v=>{f(l)&&!f(c)&&v(g)})}A(r,m),oe()}Ko();ye();var rv="https://quickadd.obsidian.guide",is={gettingStarted:`${rv}/docs/`,formatSyntax:`${rv}/docs/FormatSyntax/`,onePageInputs:`${rv}/docs/Advanced/onePageInputs/`,userScripts:`${rv}/docs/Choices/MacroChoice/#user-scripts`,packages:`${rv}/docs/Choices/Packages/`};function F1(r,t){try{(t?Vh(t):window).open(r,"_blank","noopener,noreferrer")}catch(e){S.logError(`QuickAdd: Failed to open documentation (${r}): ${e}`)}}function iC(r,t,e){let n=At(r,"a");return n.textContent=e,n.href=t,n.target="_blank",n.rel="noopener noreferrer",n.classList.add("quickadd-docs-link"),r.append(n),n}var S6=F('<div class="qa-token-hint">Type <code>{{</code> to insert a token · <a class="quickadd-docs-link" target="_blank" rel="noopener noreferrer">Format syntax</a></div>');function Xd(r,t){ie(t,!0);let e=k(()=>!t.value.includes("{{"));var n=bt(),i=ae(n);{var o=s=>{var a=S6(),l=E(R(a),3);$(a),Q(()=>le(l,"href",is.formatSyntax)),A(s,a)};z(i,s=>{f(e)&&s(o)})}A(r,n),oe()}var M1=require("obsidian");Ua();qd();var A6=F('<input type="text" class="text-input" aria-label="Frontmatter property" placeholder="related" required=""/>'),YA=F("<!> <!>",1),I6=F("<!> <!> <!> <!>",1);function nv(r,t){ie(t,!0);let e=X(t,"appendLink",15),n=X(t,"app",3,void 0),i=k(()=>Zo(e())),o=k(()=>f(i).linkType??"link"),s=k(()=>f(i).displayText),a=k(()=>f(i).frontmatterHandling??Ud),l=k(()=>f(i).destination.type==="specifiedFile"?f(i).destination.path:""),c=k(()=>f(i).enabled?f(i).requireActiveFile?"required":"optional":"disabled"),d=k(()=>f(i).destination.type),u=k(()=>n()?n().vault.getMarkdownFiles().map(V=>V.path):[]),p=[{value:"required",label:"Enabled (strict)"},{value:"optional",label:"Enabled (skip if unavailable)"},{value:"disabled",label:"Disabled"}],m=[{value:"activeFile",label:"Current note"},{value:"specifiedFile",label:"Specified note"}],h=[{value:"replaceSelection",label:"Replace selection"},{value:"afterSelection",label:"After selection"},{value:"endOfLine",label:"End of line"},{value:"newLine",label:"New line"},{value:"inFrontmatter",label:"In frontmatter property"}],g=[{value:"link",label:"Link"},{value:"embed",label:"Embed"}],v=[{value:"none",label:"Default"},{value:"selection",label:"Selected text"}],b=[{value:"alwaysAppend",label:"Create or convert"},{value:"createProperty",label:"Create if missing"},{value:"error",label:"Require list"}];function y(V){let M=e(),B=typeof M=="boolean"?f(i):M,J=V.placement??B.placement,te=V.destination??B.destination??f(i).destination,W=te.type==="activeFile"&&Mp(J)?V.linkType??B.linkType??f(o):"link",Z=te.type==="activeFile"&&Uw(J)&&W==="link"?V.displayText??f(s):"none";return{enabled:V.enabled??!0,placement:J,requireActiveFile:V.requireActiveFile??B.requireActiveFile??f(i).requireActiveFile,linkType:W,displayText:Z,destination:te,frontmatterProperty:V.frontmatterProperty??B.frontmatterProperty,frontmatterHandling:V.frontmatterHandling??B.frontmatterHandling}}function C(V){switch(V){case"disabled":e(y({enabled:!1}));break;case"required":e(y({requireActiveFile:!0}));break;case"optional":e(y({requireActiveFile:!1}));break}}function w(V){e(y({placement:V}))}function T(V){e(y({linkType:V}))}function P(V){e(y({displayText:V}))}function _(V){e(y({frontmatterProperty:V.currentTarget.value}))}function I(V){e(y({frontmatterHandling:V}))}function D(V){let M=V==="specifiedFile"?{type:"specifiedFile",path:f(l)}:{type:"activeFile"};e(y({destination:M}))}function N(V){e(y({destination:{type:"specifiedFile",path:V.trim()}}))}function K(V){let M=V.trim();if(!M)return"Destination file is required";if(!n())return!0;let B=n().vault.getAbstractFileByPath(wA(M));return B instanceof M1.TFile&&B.extension==="md"?!0:"Markdown file not found"}var ne=YA(),H=ae(ne);{let V=J=>{it(J,{get value(){return f(c)},get options(){return p},onchange:C})},M=k(()=>`Link to ${t.fileLabel} file`),B=k(()=>`Choose whether QuickAdd should insert a link to the ${t.fileLabel} file.`);be(H,{get name(){return f(M)},get desc(){return f(B)},control:V,$$slots:{control:!0}})}var O=E(H,2);{var G=V=>{var M=YA(),B=ae(M);{let Z=ce=>{it(ce,{get value(){return f(d)},get options(){return m},onchange:D})},se=k(()=>`Where QuickAdd writes the link to the ${t.fileLabel} file.`);be(B,{name:"Link destination",get desc(){return f(se)},control:Z,$$slots:{control:!0}})}var J=E(B,2);{var te=Z=>{var se=I6(),ce=ae(se);be(ce,{name:"Link placement",desc:"Where to place the link when appending",control:ct=>{it(ct,{get value(){return f(i).placement},get options(){return h},onchange:w})},$$slots:{control:!0}});var $e=E(ce,2);{var Xe=ze=>{be(ze,{name:"Link type",desc:"Choose whether to insert a link or an embed. Embeds transclude the note's contents at the placement position.",control:Ke=>{it(Ke,{get value(){return f(o)},get options(){return g},onchange:T})},$$slots:{control:!0}})},Ye=k(()=>Mp(f(i).placement));z($e,ze=>{f(Ye)&&ze(Xe)})}var he=E($e,2);{var Re=ze=>{be(ze,{name:"Link display text",desc:"What the inserted link displays. 'Selected text' keeps the highlighted text as the link's display text; with nothing selected, the plain link is inserted.",control:Ke=>{it(Ke,{get value(){return f(s)},get options(){return v},onchange:P})},$$slots:{control:!0}})},Je=k(()=>Uw(f(i).placement)&&f(o)==="link");z(he,ze=>{f(Je)&&ze(Re)})}var ve=E(he,2);{var Ve=ze=>{var ct=YA(),Ke=ae(ct);be(Ke,{name:"Frontmatter property",desc:"Required property to insert the link into.",control:Ir=>{var Hn=A6();Ct(Hn),Q(me=>{Jn(Hn,f(i).frontmatterProperty??""),le(Hn,"aria-invalid",me)},[()=>!f(i).frontmatterProperty?.trim()]),ge("input",Hn,_),A(Ir,Hn)},$$slots:{control:!0}});var ot=E(Ke,2);be(ot,{name:"Property handling",desc:"Choose how strict QuickAdd should be when the property is missing or not a list.",control:Ir=>{it(Ir,{get value(){return f(a)},get options(){return b},onchange:I})},$$slots:{control:!0}}),A(ze,ct)},Ie=k(()=>Ba(f(i).placement));z(ve,ze=>{f(Ie)&&ze(Ve)})}A(Z,se)},W=Z=>{be(Z,{name:"Destination file",desc:"Existing Markdown note that receives the link at the bottom.",control:ce=>{Lr(ce,{get value(){return f(l)},placeholder:"Index.md",get app(){return n()},get suggestions(){return f(u)},maxSuggestions:50,required:!0,requiredMessage:"Destination file is required",validator:K,ariaLabel:"Append link destination file",onChange:N})},$$slots:{control:!0}})};z(J,Z=>{f(d)==="activeFile"?Z(te):Z(W,-1)})}A(V,M)};z(O,V=>{f(c)!=="disabled"&&V(G)})}A(r,ne),oe()}He(["input"]);function iv(r,t){ie(t,!0);let e=X(t,"openFile",15);be(r,{name:"Open",get desc(){return t.description},control:i=>{vt(i,{get checked(){return e()},set checked(o){e(o)}})},$$slots:{control:!0}}),oe()}var P6=F("<!> <!> <!> <!>",1);function ov(r,t){ie(t,!0);let e=X(t,"fileOpening",15);e(rn(e()));let n=[{value:"reuse",label:"Reuse current tab"},{value:"tab",label:"New tab"},{value:"split",label:"Split pane"},{value:"window",label:"New window"},{value:"left-sidebar",label:"Left sidebar"},{value:"right-sidebar",label:"Right sidebar"}],i=[{value:"vertical",label:"Split right"},{value:"horizontal",label:"Split down"}],o=[{value:"source",label:"Source"},{value:"preview",label:"Preview"},{value:"live",label:"Live Preview"},{value:"default",label:"Default"}],s=k(()=>typeof e().mode=="string"?e().mode:"default");var a=P6(),l=ae(a);{let h=v=>{it(v,{get value(){return e().location},get options(){return n},onchange:b=>e(e().location=b,!0)})},g=k(()=>`Where to open the ${t.contextLabel} file`);be(l,{name:"File opening location",get desc(){return f(g)},control:h,$$slots:{control:!0}})}var c=E(l,2);{var d=h=>{be(h,{name:"Split direction",desc:"How to arrange the new pane relative to the current one",control:v=>{it(v,{get value(){return e().direction},get options(){return i},onchange:b=>e(e().direction=b,!0)})},$$slots:{control:!0}})};z(c,h=>{e().location==="split"&&h(d)})}var u=E(c,2);be(u,{name:"View mode",desc:"How to display the opened file",control:g=>{it(g,{get value(){return f(s)},get options(){return o},onchange:v=>e(e().mode=v,!0)})},$$slots:{control:!0}});var p=E(u,2);{var m=h=>{be(h,{name:"Focus new pane",desc:"Focus the opened tab immediately after opening",control:v=>{vt(v,{get checked(){return e().focus},set checked(b){e(e().focus=b,!0)}})},$$slots:{control:!0}})};z(p,h=>{e().location!=="reuse"&&h(m)})}A(r,a),oe()}function sv(r,t){ie(t,!0);let e=X(t,"onePageInput",15),n=[{value:"",label:"Follow global setting"},{value:"always",label:"Always"},{value:"never",label:"Never"}],i=k(()=>e()??"");function o(s){e(s==="always"||s==="never"?s:void 0)}be(r,{name:"One-page input override",desc:"Override the global setting for this choice. 'Always' forces the one-page modal even if disabled globally; 'Never' disables it even if enabled globally.",control:a=>{it(a,{get value(){return f(i)},get options(){return n},onchange:o})},$$slots:{control:!0}}),oe()}Xp();uc();var M6=F('<input type="text" class="qa-validated-input-full-width" placeholder="-2"/> <!>',1),R6=F('<input type="text" class="qa-validated-input-full-width" placeholder="day"/>'),O6=F("<!> <!> <!> <!>",1);function pv(r,t){ie(t,!0);let e=X(t,"dateOrigin",15),n=av.map(_=>({value:_,label:_})),i=k(()=>Xa(e())),o=k(()=>e()?.kind==="ask"?e():void 0),s=k(()=>f(i)==="custom"&&e()?.kind==="relative"?e():void 0),a=k(()=>e()?.kind==="variable"?e():void 0),l=k(()=>uv(f(o)?.defaultValue)),c=k(()=>hC(f(o)?.defaultValue));function d(_){mC(_)&&e(fC({preset:_,previous:e()}))}function u(_){if(e()?.kind!=="ask")return;let I=gC(_,e().defaultValue);e(I?{kind:"ask",defaultValue:I}:{kind:"ask"})}function p(_){if(e()?.kind!=="relative")return;let I=_.trim();/^[+-]?\d+$/.test(I)&&e({...e(),offset:Number(I)})}function m(_){e()?.kind==="relative"&&lv(_)&&e({...e(),unit:_})}function h(_){e()?.kind==="variable"&&e({kind:"variable",name:_})}var g=O6(),v=ae(g);be(v,{get name(){return oC},get desc(){return sC},control:I=>{it(I,{get value(){return f(i)},get options(){return uC},onchange:d})},$$slots:{control:!0}});var b=E(v,2);{var y=_=>{be(_,{get name(){return aC},get desc(){return lC},control:D=>{it(D,{get value(){return f(l)},get options(){return f(c)},onchange:u})},$$slots:{control:!0}})};z(b,_=>{f(o)&&_(y)})}var C=E(b,2);{var w=_=>{be(_,{get name(){return cv},get desc(){return cC},control:D=>{var N=M6(),K=ae(N);Ct(K);var ne=E(K,2);it(ne,{get value(){return f(s).unit},get options(){return n},onchange:m}),Q(H=>{Jn(K,H),le(K,"aria-label",cv)},[()=>String(f(s).offset)]),ge("input",K,H=>{let O=H.currentTarget;O instanceof HTMLInputElement&&p(O.value)}),A(D,N)},$$slots:{control:!0}})};z(C,_=>{f(s)&&_(w)})}var T=E(C,2);{var P=_=>{be(_,{get name(){return dv},get desc(){return dC},control:D=>{var N=R6();Ct(N),Q(()=>{Jn(N,f(a).name),le(N,"aria-label",dv)}),ge("input",N,K=>{let ne=K.currentTarget;ne instanceof HTMLInputElement&&h(ne.value)}),A(D,N)},$$slots:{control:!0}})};z(T,_=>{f(a)&&_(P)})}A(r,g),oe()}He(["input"]);uc();var mv="Add to command palette",vC="Run this choice from the command palette or a hotkey.",yC="A second command that asks which day first. Your hotkey for the main command still uses Which day.";function Zp(r){return`Also add "${XA(r)}"`}function bC(r){return`choice:${r}`}function QA(r){return`${bC(r)}:pick-day`}function XA(r){return`${r} (pick a day)`}function fv(r){return Xa(r)!=="ask"}function D1(r){return!!r.enabled&&fv(r.origin)}var D6=F("<!> <!>",1);function hv(r,t){ie(t,!0);let e=X(t,"command",15),n=X(t,"pickDayCommand",15),i=k(()=>e()&&fv(t.dateOrigin));var o=D6(),s=ae(o);be(s,{get name(){return mv},get desc(){return vC},control:d=>{vt(d,{get ariaLabel(){return mv},get checked(){return e()},set checked(u){e(u)}})},$$slots:{control:!0}});var a=E(s,2);{var l=c=>{{let d=p=>{{let m=k(()=>Zp(t.name));vt(p,{get ariaLabel(){return f(m)},get checked(){return n()},set checked(h){n(h)}})}},u=k(()=>Zp(t.name));be(c,{get name(){return f(u)},get desc(){return yC},control:d,$$slots:{control:!0}})}};z(a,c=>{f(i)&&c(l)})}A(r,o),oe()}bi();var L6=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),N6=new Intl.Collator(void 0,{numeric:!0,sensitivity:"variant"});function wC(r){return r.trim().replace(/^\/+/,"").replace(/\/+$/,"")}function V6(r,t){let e=wC(r),n=wC(t);if(e===n)return 0;let i=e===""?[]:e.split("/"),o=n===""?[]:n.split("/"),s=Math.min(i.length,o.length);for(let a=0;a<s;a++){let l=L6.compare(i[a],o[a]);if(l!==0)return l;let c=N6.compare(i[a],o[a]);if(c!==0)return c}return i.length-o.length}function Ja(r){return[...r].sort(V6)}function B6(r,t){let e=wC(r),n=wC(t);return n?e===n||e.startsWith(`${n}/`):!0}function L1(r,t){let e=[],n=new Set;for(let i of t)for(let o of r)n.has(o)||B6(o,i)&&(e.push(o),n.add(o));return e}var pc=require("obsidian");var U6=F('<div class="qa-canvas-node-empty"> </div>'),q6=F('<div class="qa-canvas-node-empty">No nodes match the current filter.</div>'),z6=F('<button type="button"> </button>'),H6=F('<button type="button" disabled="">Unavailable</button>'),W6=F('<div><div class="qa-canvas-node-item-header"><span> </span> <span class="qa-canvas-node-title"> </span></div> <div class="qa-canvas-node-subtitle"> </div> <div class="qa-canvas-node-meta"><code> </code></div> <div class="qa-canvas-node-item-actions"><!> <button type="button">Copy ID</button></div></div>'),G6=F('<div class="qa-canvas-node-picker"><div class="qa-canvas-node-actions"><button type="button">Open target canvas</button> <button type="button">Use selected in open canvas</button> <button type="button">Clear</button></div> <div class="qa-canvas-node-filter"><input type="text" placeholder="Filter by card text, file path, or node id\u2026" aria-label="Filter canvas nodes"/></div> <div class="qa-canvas-node-status"> </div> <div class="qa-canvas-node-list"><!></div></div>');function JA(r,t){ie(t,!0);let e=X(t,"nodeId",15),n=pe(Ze([])),i=pe("loading"),o=pe(""),s=pe(""),a=k(()=>{let H=f(s).trim().toLowerCase();return H.length?f(n).filter(O=>O.searchText.includes(H)):f(n)}),l=k(()=>(e()??"").trim()),c=k(()=>f(i)==="ready"?`Showing ${f(a).length} of ${f(n).length} nodes`:f(i)==="empty"?f(o):"Loading canvas nodes\u2026");Eh(()=>{(async()=>{let H=MS(t.app,t.canvasTargetPath);if(!H){q(o,"Node picker works for direct .canvas paths that already exist in your vault. Format syntax paths cannot be listed here."),q(i,"empty");return}if(q(n,await GD(t.app,H),!0),f(n).length===0){q(o,"No selectable nodes found in the target canvas."),q(i,"empty");return}q(i,"ready")})()});function d(H){e(H)}function u(){let H=MS(t.app,t.canvasTargetPath);if(!H){new pc.Notice("Target canvas file was not found.");return}t.app.workspace.getLeaf(!0).openFile(H).catch(()=>new pc.Notice("Could not open target canvas."))}function p(){let H=WD(t.app,t.canvasTargetPath);if(!H){new pc.Notice("Open the target canvas and select exactly one card to use this action.");return}let O=f(n).find(G=>G.id===H);if(!O){new pc.Notice(f(i)==="ready"?"The selected node was not found in the loaded canvas.":"Canvas nodes are still loading. Wait a moment and try again.");return}if(!O.capturable){new pc.Notice(O.capturableReason);return}d(H)}function m(H){(async()=>{try{await navigator.clipboard.writeText(H),new pc.Notice(`Copied node id ${H}`)}catch{new pc.Notice("Could not copy node id automatically.")}})()}function h(H){return H==="text"?"TEXT":H==="file"?"FILE":"NODE"}var g=G6(),v=R(g),b=R(v),y=E(b,2),C=E(y,2);$(v);var w=E(v,2),T=R(w);Ct(T),$(w);var P=E(w,2),_=re(P,!0),I=E(P,2),D=R(I);{var N=H=>{var O=U6(),G=re(O,!0);Q(()=>ee(G,f(o))),A(H,O)},K=H=>{var O=q6();A(H,O)},ne=H=>{var O=bt(),G=ae(O);gt(G,17,()=>f(a),V=>V.id,(V,M)=>{let B=k(()=>f(l)===f(M).id);var J=W6();let te;var W=R(J),Z=R(W),se=re(Z,!0),ce=E(Z,2),$e=re(ce,!0);$(W);var Xe=E(W,2),Ye=re(Xe,!0),he=E(Xe,2),Re=R(he),Je=re(Re,!0);$(he);var ve=E(he,2),Ve=R(ve);{var Ie=Ke=>{var ot=z6();let or;var Ir=re(ot,!0);Q(()=>{or=Ge(ot,1,"",null,or,{"mod-cta":f(B)}),ee(Ir,f(B)?"Selected":"Use node")}),ge("click",ot,()=>d(f(M).id)),A(Ke,ot)},ze=Ke=>{var ot=H6();Q(()=>le(ot,"title",f(M).capturableReason)),A(Ke,ot)};z(Ve,Ke=>{f(M).capturable?Ke(Ie):Ke(ze,-1)})}var ct=E(Ve,2);$(ve),$(J),Q(Ke=>{te=Ge(J,1,"qa-canvas-node-item",null,te,{"is-selected":f(B)}),Ge(Z,1,`qa-canvas-node-type is-${f(M).type??""}`),ee(se,Ke),ee($e,f(M).title),ee(Ye,f(M).subtitle),ee(Je,f(M).id)},[()=>h(f(M).type)]),ge("click",ct,()=>m(f(M).id)),A(V,J)}),A(H,O)};z(D,H=>{f(i)==="empty"?H(N):f(i)==="ready"&&f(a).length===0?H(K,1):H(ne,-1)})}$(I),$(g),Q(()=>ee(_,f(c))),ge("click",b,u),ge("click",y,p),ge("click",C,()=>d("")),Zn(T,()=>f(s),H=>q(s,H)),A(r,g),oe()}He(["click"]);CC();xC();function Q6(r){return r.trim().replace(/^\/+/,"")}function gv(r){return[...new Set((r??[]).map(t=>t.trim()).filter(Boolean))]}function vv(r,t="or"){return r.length<=1?r[0]??"":t==="+"?r.join(" + "):r.length===2?`${r[0]} ${t} ${r[1]}`:`${r.slice(0,-1).join(", ")}, ${t} ${r[r.length-1]}`}function B1(r){let t=gv(r.folders??(r.folder?[r.folder]:[])),e=gv(r.tags),n=gv(r.excludeFolders),i=gv(r.excludeTags),o=gv(r.excludeFiles),s=[];return t.length>0&&s.push(`${t.length===1?"folder":"folders"} ${vv(t)}`),e.length>0&&s.push(`${e.length===1?"tag":"tags"} ${vv(e,"+")}`),n.length>0&&s.push(`excluding ${n.length===1?"folder":"folders"} ${vv(n)}`),i.length>0&&s.push(`excluding ${i.length===1?"tag":"tags"} ${vv(i,"+")}`),o.length>0&&s.push(`excluding ${o.length===1?"file":"files"} ${vv(o)}`),s.length>0?s.join("; "):"all notes"}function yv(r){let t=Q6(r),e=tm(t);if(e){if(!e.field)return{recognized:!0,valid:!1,variant:"error",message:"Property capture target needs a field name, e.g. property:type=draft."};let i=e.value?`frontmatter ${e.field} = ${e.value}`:`frontmatter field ${e.field}`,o=B1(e.filter),s=o==="all notes"?"":`; ${o}`;return{recognized:!0,valid:!0,variant:"success",message:`Recognized property target: ${i}${s}.`}}let n=em(t);return n?n.multiSelect?{recognized:!0,valid:!1,variant:"error",message:"Capture target filters select one destination file. Use {{FILE:...|multi}} in the capture format for multi-value metadata."}:{recognized:!0,valid:!0,variant:"success",message:`Recognized filtered picker: ${B1(n.filter)}.`}:null}var X6=F('<button type="button">Daily note</button>'),J6=F("<!> <!> <!>",1),Z6=F('<!> <div class="qa-canvas-node-helper">Tip: open this canvas and select one card to grab its id instantly.</div> <!>',1),U1=F("<!> <!>",1);function ZA(r,t){ie(t,!0);let e=X(t,"choice",15),n=k(()=>{let y=Ja(za(t.app)).filter(T=>T.length>0).map(T=>T.endsWith("/")?T:T+"/"),C=t.app.vault.getMarkdownFiles().map(T=>T.path),w=t.app.vault.getFiles().filter(T=>T.extension==="canvas").map(T=>T.path);return Array.from(new Set([...y,...C,...w]))}),i=[y=>new ln(t.app,y,t.plugin,"captureTarget")],o=k(()=>yv(e().captureTo??"")),s=k(()=>f(o)!==null),a=y=>yv(y)!==null,l=k(()=>!f(s)&&Ul(e().captureTo));function c(y){let C=!!e().captureToActiveFile&&e().activeFileWritePosition==="bottom";e(e().captureToActiveFile=y,!0),!y&&C&&e(e().prepend=!0,!0),!y&&e().newLineCapture?.enabled&&e(e().newLineCapture.enabled=!1,!0)}function d(y){let C=up(e().captureTo),w=Ul(e().captureTo),T=yv(y)!==null;e(e().captureTo=y,!0);let P=up(y),_=Ul(y);(T||!_||w&&_&&C!==P)&&e(e().captureToCanvasNodeId="",!0)}let u="{{DAILY}}";function p(){d(u),e(e().createFileIfItDoesntExist={...e().createFileIfItDoesntExist,enabled:!0,createWithTemplate:!1},!0)}function m(y){let C=yv(y);return C?{valid:C.valid,message:C.message,variant:C.valid?"success":void 0}:y.trim()?!0:{valid:!0,message:"Leave empty to pick the note each time this choice runs."}}var h=U1(),g=ae(h);be(g,{name:"Capture to active file",desc:"Capture into whichever note is open when the choice runs, instead of a fixed target.",control:C=>{vt(C,{get checked(){return e().captureToActiveFile},onchange:c})},$$slots:{control:!0}});var v=E(g,2);{var b=y=>{var C=U1(),w=ae(C);ni(w,{name:"Capture to",desc:"Vault-relative path to a file or folder, a #tag, or property:field=value. Supports format syntax like {{DATE}}; end with '/' to capture into a folder.",control:D=>{var N=bt(),K=ae(N);{var ne=O=>{var G=X6();ge("click",G,p),A(O,G)},H=k(()=>(e().captureTo??"").trim()!==u);z(K,O=>{f(H)&&O(ne)})}A(D,N)},children:(D,N=$t)=>{var K=J6(),ne=ae(K);Lr(ne,{get id(){return N()},get value(){return e().captureTo},placeholder:"Daily/{{DATE}}.md",get app(){return t.app},get suggestions(){return f(n)},maxSuggestions:50,get makeSuggesters(){return i},validator:m,onChange:d});var H=E(ne,2);Xd(H,{get value(){return e().captureTo}});var O=E(H,2);{var G=V=>{Hi(V,{get value(){return e().captureTo},formatterKind:"fileName",get app(){return t.app},get plugin(){return t.plugin},hideWhen:a})};z(O,V=>{f(s)||V(G)})}A(D,K)},$$slots:{control:!0,default:!0}});var T=E(w,2);{var P=_=>{var I=Z6(),D=ae(I);be(D,{name:"Target canvas node",desc:"Choose a card from the canvas below, or paste an exact node id.",control:ne=>{{let H=k(()=>e().captureToCanvasNodeId??"");Lr(ne,{get value(){return f(H)},placeholder:"Canvas node id",ariaLabel:"Canvas node id",required:!0,requiredMessage:"A canvas capture target requires a node id \u2014 pick a card below or paste an exact node id.",onChange:O=>e(e().captureToCanvasNodeId=O.trim(),!0)})}},$$slots:{control:!0}});var N=E(D,4);Th(N,()=>e().captureTo,K=>{JA(K,{get canvasTargetPath(){return e().captureTo},get app(){return t.app},get nodeId(){return e().captureToCanvasNodeId},set nodeId(ne){e(e().captureToCanvasNodeId=ne,!0)}})}),A(_,I)};z(T,_=>{f(l)&&_(P)})}A(y,C)};z(v,y=>{e().captureToActiveFile||y(b)})}A(r,h),oe()}He(["click"]);var G1=require("obsidian");var H1=require("obsidian");Le();function eI(r){let e=r.match(/\{\{DATE:((?:\[[^\]\n\r]*\]|\[(?![^\]\n\r]*\])|[^}\n\r+|[]|\|(?!(?:startof|endof):[a-z])(?!(?:case):[a-z-]+\}\}))*)(?:\+-?\d+)?(?:\|(?:startof|endof):[a-z]+)?(?:\|case:[a-z-]+)?\}\}/i)?.[1]?.trim();if(e)return e;let i=r.match(/\{\{VDATE:[^,}]+,([^}\n\r]*)\}\}/i)?.[1]?.split("|")[0]?.trim();if(i)return i}var eX=F(`<div class="setting-item-description">You'll pick a heading from the target note when you run this capture, and the
|
||
text is inserted under it. Use the toggles below to control placement within that
|
||
section.</div>`),q1=F("<!> <!>",1),tX=F(`<div class="setting-item-description">Inline insertion needs a single-line target. The line break (\\n) can't be
|
||
matched on the same line \u2014 remove it, or turn off "Inline insertion".</div>`),z1=F("<!> <!> <!>",1),rX=F(`<div class="setting-item-description">No sorting: newest-first prepends the new section above existing ones;
|
||
oldest-first appends it below.</div>`),nX=F(`<div class="setting-item-description">This heading uses a date token QuickAdd can't auto-read for sorting. Pick
|
||
"Date" and enter the format, or sections stay in insertion order.</div>`),iX=F(`<div class="setting-item-description">The "Insert after" heading is created at its sorted position among ALL
|
||
same-level headings in the note (it is not scoped to one parent section). It
|
||
does NOT re-sort headings you already have; only the new one is placed. Use
|
||
"Insert at end of section" above for newest-on-top vs. appended entries within
|
||
each section.</div> <!> <!> <!> <!> <!> <!>`,1),oX=F("<!> <!> <!> <!> <!>",1);function tI(r,t){ie(t,!0);let e=X(t,"insertAfter",15);e().inline===void 0&&e(e().inline=!1,!0),e().replaceExisting===void 0&&e(e().replaceExisting=!1,!0),e().promptHeading===void 0&&e(e().promptHeading=!1,!0),e().insertAtEnd===void 0&&e(e().insertAtEnd=!1,!0),e().considerSubsections===void 0&&e(e().considerSubsections=!1,!0),e().blankLineAfterMatchMode||e(e().blankLineAfterMatchMode="auto",!0),e().createIfNotFound||e(e().createIfNotFound=!1,!0),e().createIfNotFoundLocation||e(e().createIfNotFoundLocation=Vi,!0);let n=[V=>new ln(t.app,V,t.plugin,"lineTarget")],i=[{value:"auto",label:"Auto (headings only)"},{value:"skip",label:"Always skip"},{value:"none",label:"Never skip"}],o=k(()=>e().inline?[{value:Vi,label:"Top"},{value:xd,label:"Bottom"},{value:Ed,label:"Cursor"}]:[{value:Vi,label:"Top"},{value:xd,label:"Bottom"},{value:Ed,label:"Cursor"},{value:Yo,label:"Ordered among siblings"}]),s=[{value:"insertion",label:"Insertion order (no sorting)"},{value:"lexical",label:"Text (A\u2192Z)"},{value:"numeric",label:"Number"},{value:"date",label:"Date"},{value:"semver",label:"Version (semver)"}],a=[{value:"desc",label:"Newest / highest first"},{value:"asc",label:"Oldest / lowest first"}],l=[{value:"bottom",label:"Sort to bottom"},{value:"top",label:"Sort to top"}],c=pe(!!e().orderBy),d=k(()=>e().createIfNotFoundLocation===Yo),u=k(()=>e().createIfNotFound&&f(d)),p=k(()=>new Yp(t.app,t.plugin)),m=pe(!1);Dt(()=>{let V=e().after??"",M=f(p);if(!e().inline||V===""){q(m,!1);return}let B=!1;return M.format(V).then(J=>{B||q(m,/[\n\r]/.test(J),!0)}).catch(()=>{B||q(m,!1)}),()=>{B=!0}});let h=k(()=>e().orderBy??{by:"insertion",direction:"desc",unparseable:"bottom"}),g=k(()=>/\{\{V?DATE\b/i.test(e().after??"")),v=k(()=>f(u)&&e().orderBy?.by==="insertion"&&f(g)&&!eI(e().after??""));Dt(()=>{if(!f(u))return;let V=eI(e().after??"");if(!e().orderBy){e(e().orderBy={by:V?"date":"insertion",direction:"desc",dateFormat:V,unparseable:"bottom"},!0);return}!f(c)&&(e().orderBy.by==="insertion"||e().orderBy.by==="date")&&(e(e().orderBy.by=V?"date":"insertion",!0),e(e().orderBy.dateFormat=V,!0))});function b(V){e(e().createIfNotFoundLocation=V,!0),V===Yo?e(e().inline=!1,!0):(e(e().orderBy=void 0,!0),q(c,!1))}function y(V){q(c,!0),e().orderBy&&e(e().orderBy.by=V,!0)}function C(V){e().promptHeading||V&&!e().after.startsWith("#")&&(e(e().considerSubsections=!1,!0),new H1.Notice("Consider subsections requires the target to be a heading (starts with #)"))}function w(V){V&&(e(e().inline=!1,!0),e(e().replaceExisting=!1,!0))}var T=oX(),P=ae(T);be(P,{name:"Choose heading when capturing",desc:"Instead of typing a target line now, show a dropdown of the target note's headings when you run this capture and insert under the one you pick.",control:M=>{vt(M,{onchange:w,get checked(){return e().promptHeading},set checked(B){e(e().promptHeading=B,!0)}})},$$slots:{control:!0}});var _=E(P,2);{var I=V=>{var M=eX();A(V,M)},D=V=>{var M=z1(),B=ae(M);ni(B,{name:"Insert after",desc:"Insert capture after specified text. Accepts format syntax. Tip: use a heading (starts with #) to target a section. Blank line handling is configurable below.",children:(se,ce=$t)=>{var $e=q1(),Xe=ae($e);Lr(Xe,{get id(){return ce()},placeholder:"Insert after",required:!0,requiredMessage:"Insert after text is required",get makeSuggesters(){return n},get value(){return e().after},set value(he){e(e().after=he,!0)}});var Ye=E(Xe,2);Hi(Ye,{get value(){return e().after},formatterKind:"lineTarget",get app(){return t.app},get plugin(){return t.plugin}}),A(se,$e)},$$slots:{default:!0}});var J=E(B,2);{let Z=ce=>{vt(ce,{get disabled(){return f(d)},get checked(){return e().inline},set checked($e){e(e().inline=$e,!0)}})},se=k(()=>f(d)?"Inline insertion can't be combined with ordered placement.":"Insert captured content on the same line, immediately after the matched text (no newline added).");be(J,{name:"Inline insertion",get desc(){return f(se)},control:Z,$$slots:{control:!0}})}var te=E(J,2);{var W=Z=>{var se=tX();A(Z,se)};z(te,Z=>{f(m)&&Z(W)})}A(V,M)};z(_,V=>{e().promptHeading?V(I):V(D,-1)})}var N=E(_,2);{var K=V=>{be(V,{name:"Replace existing value",desc:"Replace everything after the matched text up to end-of-line.",control:B=>{vt(B,{get checked(){return e().replaceExisting},set checked(J){e(e().replaceExisting=J,!0)}})},$$slots:{control:!0}})},ne=V=>{var M=z1(),B=ae(M);be(B,{name:"Insert at end of section",desc:"Place the text at the end of the matched section instead of the top.",control:Z=>{vt(Z,{get checked(){return e().insertAtEnd},set checked(se){e(e().insertAtEnd=se,!0)}})},$$slots:{control:!0}});var J=E(B,2);{let W=se=>{{let ce=k(()=>e().blankLineAfterMatchMode??"auto");it(se,{get value(){return f(ce)},get options(){return i},get disabled(){return e().insertAtEnd},onchange:$e=>e(e().blankLineAfterMatchMode=$e,!0)})}},Z=k(()=>e().insertAtEnd?"Not used when inserting at end of section.":"Controls whether Insert After skips existing blank lines after the matched line.");be(J,{name:"Blank lines after match",get desc(){return f(Z)},control:W,$$slots:{control:!0}})}var te=E(J,2);{let W=se=>{{let ce=k(()=>!e().insertAtEnd);vt(se,{get disabled(){return f(ce)},onchange:C,get checked(){return e().considerSubsections},set checked($e){e(e().considerSubsections=$e,!0)}})}},Z=k(()=>e().insertAtEnd?e().promptHeading?"Also include the chosen heading\u2019s subsections (nested headings inside its section).":"Also include the section\u2019s subsections (requires target to be a heading starting with #). Subsections are headings inside the section.":"Only affects placement when \u201CInsert at end of section\u201D is on.");be(te,{name:"Consider subsections",get desc(){return f(Z)},control:W,$$slots:{control:!0}})}A(V,M)};z(N,V=>{e().inline?V(K):V(ne,-1)})}var H=E(N,2);be(H,{name:"Create line if not found",desc:"Creates the 'insert after' line if it is not found.",control:M=>{var B=q1(),J=ae(B);vt(J,{get checked(){return e().createIfNotFound},set checked(W){e(e().createIfNotFound=W,!0)}});var te=E(J,2);{let W=k(()=>e().createIfNotFoundLocation||Vi);it(te,{get value(){return f(W)},get options(){return f(o)},ariaLabel:"Where to create the line",onchange:b})}A(M,B)},$$slots:{control:!0}});var O=E(H,2);{var G=V=>{var M=iX(),B=E(ae(M),2);be(B,{name:"Sort sections by",control:Re=>{it(Re,{get value(){return f(h).by},get options(){return s},onchange:y})},$$slots:{control:!0}});var J=E(B,2);be(J,{name:"Section order",control:Re=>{it(Re,{get value(){return f(h).direction},get options(){return a},onchange:Je=>{e().orderBy&&e(e().orderBy.direction=Je,!0)}})},$$slots:{control:!0}});var te=E(J,2);{var W=he=>{be(he,{name:"Date format",desc:"Moment format used to parse existing heading dates for sorting (e.g. YYYY-MM-DD).",control:Je=>{{let ve=k(()=>f(h).dateFormat??"");Lr(Je,{get value(){return f(ve)},placeholder:"YYYY-MM-DD",ariaLabel:"Date format",onChange:Ve=>{q(c,!0),e().orderBy&&e(e().orderBy.dateFormat=Ve,!0)}})}},$$slots:{control:!0}})};z(te,he=>{f(h).by==="date"&&he(W)})}var Z=E(te,2);{var se=he=>{be(he,{name:"Existing unparseable headings",desc:"Where to rank EXISTING headings whose text can't be parsed for this sort. (A new heading that can't be parsed is appended at the end.)",control:Je=>{{let ve=k(()=>f(h).unparseable??"bottom");it(Je,{get value(){return f(ve)},get options(){return l},ariaLabel:"Existing unparseable headings",onchange:Ve=>{e().orderBy&&e(e().orderBy.unparseable=Ve,!0)}})}},$$slots:{control:!0}})};z(Z,he=>{(f(h).by==="date"||f(h).by==="numeric"||f(h).by==="semver")&&he(se)})}var ce=E(Z,2);{var $e=he=>{var Re=rX();A(he,Re)};z(ce,he=>{f(h).by==="insertion"&&he($e)})}var Xe=E(ce,2);{var Ye=he=>{var Re=nX();A(he,Re)};z(Xe,he=>{f(v)&&he(Ye)})}A(V,M)};z(O,V=>{f(u)&&e().orderBy&&V(G)})}A(r,T),oe()}Le();var rI=F("<!> <!>",1);function nI(r,t){ie(t,!0);let e=X(t,"insertBefore",15);e().createIfNotFound===void 0&&e(e().createIfNotFound=!1,!0),e().createIfNotFoundLocation||e(e().createIfNotFoundLocation=Vi,!0);let n=[l=>new ln(t.app,l,t.plugin,"lineTarget")],i=[{value:Vi,label:"Top"},{value:xd,label:"Bottom"},{value:Ed,label:"Cursor"}];var o=rI(),s=ae(o);ni(s,{name:"Insert before",desc:"Insert capture before specified text. Accepts format syntax.",children:(c,d=$t)=>{var u=rI(),p=ae(u);Lr(p,{get id(){return d()},placeholder:"Insert before",required:!0,requiredMessage:"Insert before text is required",get makeSuggesters(){return n},get value(){return e().before},set value(h){e(e().before=h,!0)}});var m=E(p,2);Hi(m,{get value(){return e().before},formatterKind:"lineTarget",get app(){return t.app},get plugin(){return t.plugin}}),A(c,u)},$$slots:{default:!0}});var a=E(s,2);be(a,{name:"Create line if not found",desc:"Creates the 'insert before' line if it is not found.",control:c=>{var d=rI(),u=ae(d);vt(u,{get checked(){return e().createIfNotFound},set checked(m){e(e().createIfNotFound=m,!0)}});var p=E(u,2);{let m=k(()=>e().createIfNotFoundLocation||Vi);it(p,{get value(){return f(m)},get options(){return i},onchange:h=>e(e().createIfNotFoundLocation=h,!0)})}A(c,d)},$$slots:{control:!0}}),A(r,o),oe()}var sX=F("<!> <!> <!>",1);function iI(r,t){ie(t,!0);let e=X(t,"config",15),n=[c=>new ln(t.app,c,t.plugin)],i="";var o=sX(),s=ae(o);{let c=p=>{it(p,{get value(){return e().property.kind},options:[{value:"named",label:"Named property"},{value:"prompt",label:"Choose when capturing"}],onchange:m=>{e().property.kind==="named"&&(i=e().property.format),e(e().property=m==="prompt"?{kind:"prompt"}:{kind:"named",format:i},!0)}})},d=(p,m=$t)=>{var h=bt(),g=ae(h);{var v=b=>{Lr(b,{get id(){return m()},placeholder:"Property name",required:!0,requiredMessage:"Property name is required",get makeSuggesters(){return n},get value(){return e().property.format},set value(y){e(e().property.format=y,!0)}})};z(g,b=>{e().property.kind==="named"&&b(v)})}A(p,h)},u=k(()=>e().property.kind==="named");ni(s,{name:"Property",get bodyVisible(){return f(u)},control:c,children:d,$$slots:{control:!0,default:!0}})}var a=E(s,2);{let c=u=>{it(u,{get value(){return e().action},options:[{value:"set",label:"Set value"},{value:"addToList",label:"Add to list"}],onchange:p=>{e(e().action=p==="addToList"?"addToList":"set",!0)}})},d=k(()=>e().action==="addToList"?"Each line is one item. New items go below the existing ones. Put {{PROPERTY}} on its own line to choose where the existing items go.":"Replaces the value. For a list, each line is one item. Put {{PROPERTY}} where the current value should stay. A Text property keeps all lines as one value. A property with no type yet rejects several lines. Use Add to list, or set the type to Text in Obsidian first.");be(a,{name:"Action",get desc(){return f(d)},control:c,$$slots:{control:!0}})}var l=E(a,2);be(l,{name:"Create property if missing",control:d=>{vt(d,{get checked(){return e().createIfMissing},set checked(u){e(e().createIfMissing=u,!0)}})},$$slots:{control:!0}}),A(r,o),oe()}function oI(r){let t=r.insertAfter.enabled||!!r.insertBefore?.enabled;return r.captureToActiveFile&&!t&&r.newLineCapture?.enabled?r.newLineCapture.direction==="above"?"newLineAbove":"newLineBelow":r.captureToActiveFile&&!t?r.activeFileWritePosition==="top"?"activeFileTop":r.activeFileWritePosition==="bottom"||r.prepend?"append":"currentLine":r.insertAfter.enabled?"insertAfter":r.insertBefore?.enabled?"insertBefore":r.prepend?"prepend":"append"}function EC(r){if(r.propertyCapture)return"property";let t=!!r.insertAfter?.enabled||!!r.insertBefore?.enabled;return r.captureToActiveFile&&!t?r.newLineCapture?.enabled?r.newLineCapture.direction==="above"?"newLineAbove":"newLineBelow":r.activeFileWritePosition==="top"?"activeTop":r.activeFileWritePosition==="bottom"||r.prepend?"bottom":"top":r.prepend||r.captureToActiveFile&&r.activeFileWritePosition==="bottom"?"bottom":r.insertAfter?.enabled?"after":r.insertBefore?.enabled?"before":"top"}function bv(r){return r==="currentLine"||r==="newLineAbove"||r==="newLineBelow"}function W1(r){return{...r,activeFileWritePosition:r.prepend||r.activeFileWritePosition==="bottom"?"bottom":"top",newLineCapture:{...r.newLineCapture,enabled:!1}}}var aX=F(`<div class="setting-item-description">Canvas note: 'At cursor' and 'New line above/below cursor' are not supported
|
||
for Canvas card capture. Use top, bottom, insert-after, or insert-before
|
||
placement.</div>`),lX=F("<!> <!> <!> <!> <!>",1);function sI(r,t){ie(t,!0);let e=X(t,"choice",15),n=k(()=>!!e().captureToActiveFile),i=k(()=>EC(e())),o=k(()=>[{value:"top",label:f(n)?"At cursor":"Top of file"},...f(n)?[{value:"activeTop",label:"Top of file (after frontmatter)"},{value:"newLineAbove",label:"New line above cursor"},{value:"newLineBelow",label:"New line below cursor"}]:[],{value:"after",label:"After line\u2026"},{value:"before",label:"Before line\u2026"},{value:"bottom",label:"Bottom of file"},{value:"property",label:"Property"}]);function s(y){if(y==="property"){e().propertyCapture??e(e().propertyCapture={property:{kind:"named",format:""},action:"set",createIfMissing:!0},!0);return}if(delete e().propertyCapture,e(e().prepend=!1,!0),e(e().insertAfter.enabled=!1,!0),e(e().insertAfter.promptHeading=!1,!0),e(e().insertAfter.inline=!1,!0),e(e().insertAfter.replaceExisting=!1,!0),e().insertBefore||e(e().insertBefore={enabled:!1,before:"",createIfNotFound:!1,createIfNotFoundLocation:"top"},!0),e(e().insertBefore.enabled=!1,!0),e().newLineCapture||e(e().newLineCapture={enabled:!1,direction:"below"},!0),e(e().newLineCapture.enabled=!1,!0),e(e().activeFileWritePosition="cursor",!0),y==="top"){f(n)||e(e().prepend=!1,!0);return}if(y==="activeTop"){f(n)&&e(e().activeFileWritePosition="top",!0);return}if(y==="bottom"){f(n)?e(e().activeFileWritePosition="bottom",!0):e(e().prepend=!0,!0);return}if(y==="newLineAbove"){e(e().newLineCapture.enabled=!0,!0),e(e().newLineCapture.direction="above",!0);return}if(y==="newLineBelow"){e(e().newLineCapture.enabled=!0,!0),e(e().newLineCapture.direction="below",!0);return}if(y==="before"){e(e().insertBefore.enabled=!0,!0);return}e(e().insertAfter.enabled=!0,!0)}let a=k(()=>{if(e().propertyCapture)return!1;let y=typeof e().captureTo=="string"&&Ul(e().captureTo),C=t.app.workspace.getActiveViewOfType(G1.FileView)?.getViewType()==="canvas",w=f(n)&&!e().insertAfter.enabled&&!e().insertBefore?.enabled&&!e().newLineCapture?.enabled&&(e().activeFileWritePosition??"cursor")==="cursor"&&!e().prepend;return!(!(e().newLineCapture?.enabled||w)||(f(n)?!C:!y))});var l=lX(),c=ae(l);{let y=w=>{it(w,{get value(){return f(i)},get options(){return f(o)},onchange:s})},C=k(()=>f(n)?"Where to place the capture in the current file.":"Where to place the capture in the target file.");be(c,{name:"Write position",get desc(){return f(C)},control:y,$$slots:{control:!0}})}var d=E(c,2);{var u=y=>{iI(y,{get app(){return t.app},get plugin(){return t.plugin},get config(){return e().propertyCapture},set config(C){e(e().propertyCapture=C,!0)}})};z(d,y=>{e().propertyCapture&&y(u)})}var p=E(d,2);{var m=y=>{tI(y,{get app(){return t.app},get plugin(){return t.plugin},get insertAfter(){return e().insertAfter},set insertAfter(C){e(e().insertAfter=C,!0)}})};z(p,y=>{!e().propertyCapture&&e().insertAfter.enabled&&y(m)})}var h=E(p,2);{var g=y=>{nI(y,{get app(){return t.app},get plugin(){return t.plugin},get insertBefore(){return e().insertBefore},set insertBefore(C){e(e().insertBefore=C,!0)}})};z(h,y=>{!e().propertyCapture&&e().insertBefore?.enabled&&y(g)})}var v=E(h,2);{var b=y=>{var C=aX();A(y,C)};z(v,y=>{f(a)&&y(b)})}A(r,l),oe()}var cX=new Set(["activity","airplay","alarm-check","alarm-clock-off","alarm-clock","alarm-minus","alarm-plus","album","alert-circle","alert-octagon","alert-triangle","align-center-horizontal","align-center-vertical","align-center","align-end-horizontal","align-end-vertical","align-horizontal-distribute-center","align-horizontal-distribute-end","align-horizontal-distribute-start","align-horizontal-justify-center","align-horizontal-justify-end","align-horizontal-justify-start","align-horizontal-space-around","align-horizontal-space-between","align-justify","align-left","align-right","align-start-horizontal","align-start-vertical","align-vertical-distribute-center","align-vertical-distribute-end","align-vertical-distribute-start","align-vertical-justify-center","align-vertical-justify-end","align-vertical-justify-start","align-vertical-space-around","align-vertical-space-between","anchor","aperture","archive","arrow-big-down","arrow-big-left","arrow-big-right","arrow-big-up","arrow-down-circle","arrow-down-left","arrow-down-right","arrow-down","arrow-left-circle","arrow-left-right","arrow-left","arrow-right-circle","arrow-right","arrow-up-circle","arrow-up-left","arrow-up-right","arrow-up","asterisk","at-sign","award","axe","banknote","bar-chart-2","bar-chart","baseline","battery-charging","battery-full","battery-low","battery-medium","battery","beaker","bell-minus","bell-off","bell-plus","bell-ring","bell","bike","binary","bitcoin","bluetooth-connected","bluetooth-off","bluetooth-searching","bluetooth","bold","book-open","book","bookmark-minus","bookmark-plus","bookmark","bot","box-select","box","briefcase","brush","bug","building-2","building","bus","calculator","calendar","camera-off","camera","car","carrot","cast","check-circle-2","check-circle","check-square","check","chevron-down","chevron-first","chevron-last","chevron-left","chevron-right","chevron-up","chevrons-down-up","chevrons-down","chevrons-left","chevrons-right","chevrons-up-down","chevrons-up","chrome","circle-slashed","circle","clipboard-check","clipboard-copy","clipboard-list","clipboard-x","clipboard","clock-1","clock-10","clock-11","clock-12","clock-2","clock-3","clock-4","clock-5","clock-6","clock-7","clock-8","clock-9","clock","cloud-drizzle","cloud-fog","cloud-hail","cloud-lightning","cloud-moon","cloud-off","cloud-rain-wind","cloud-rain","cloud-snow","cloud-sun","cloud","cloudy","clover","code-2","code","codepen","codesandbox","coffee","coins","columns","command","compass","contact","contrast","cookie","copy","copyleft","copyright","corner-down-left","corner-down-right","corner-left-down","corner-left-up","corner-right-down","corner-right-up","corner-up-left","corner-up-right","cpu","credit-card","crop","cross","crosshair","crown","currency","database","delete","dice-1","dice-2","dice-3","dice-4","dice-5","dice-6","disc","divide-circle","divide-square","divide","dollar-sign","download-cloud","download","dribbble","droplet","droplets","drumstick","edit-2","edit-3","edit","egg","equal-not","equal","eraser","euro","expand","external-link","eye-off","eye","facebook","fast-forward","feather","figma","file-check-2","file-check","file-code","file-digit","file-input","file-minus-2","file-minus","file-output","file-plus-2","file-plus","file-search","file-text","file-x-2","file-x","file","files","film","filter","flag-off","flag-triangle-left","flag-triangle-right","flag","flame","flashlight-off","flashlight","flask-conical","flask-round","folder-minus","folder-open","folder-plus","folder","form-input","forward","frame","framer","frown","function-square","gamepad-2","gamepad","gauge","gavel","gem","ghost","gift","git-branch-plus","git-branch","git-commit","git-fork","git-merge","git-pull-request","github","gitlab","glasses","globe-2","globe","grab","graduation-cap","grid","grip-horizontal","grip-vertical","hammer","hand-metal","hand","hard-drive","hard-hat","hash","haze","headphones","heart","help-circle","hexagon","highlighter","history","home","image-minus","image-off","image-plus","image","import","inbox","indent","indian-rupee","infinity","info","inspect","instagram","italic","japanese-yen","key","keyboard","landmark","languages","laptop-2","laptop","lasso-select","lasso","layers","layout-dashboard","layout-grid","layout-list","layout-template","layout","library","life-buoy","lightbulb-off","lightbulb","link-2-off","link-2","link","linkedin","list-checks","list-minus","list-ordered","list-plus","list-x","list","loader-2","loader","locate-fixed","locate-off","locate","lock","log-in","log-out","mail","map-pin","map","maximize-2","maximize","megaphone","meh","menu","message-circle","message-square","mic-off","mic","minimize-2","minimize","minus-circle","minus-square","minus","monitor-off","monitor-speaker","monitor","moon","more-horizontal","more-vertical","mountain-snow","mountain","mouse-pointer-2","mouse-pointer-click","mouse-pointer","mouse","move-diagonal-2","move-diagonal","move-horizontal","move-vertical","move","music","navigation-2","navigation","network","octagon","option","outdent","package-check","package-minus","package-plus","package-search","package-x","package","palette","palmtree","paperclip","pause-circle","pause-octagon","pause","pen-tool","pencil","percent","person-standing","phone-call","phone-forwarded","phone-incoming","phone-missed","phone-off","phone-outgoing","phone","pie-chart","piggy-bank","pin","pipette","plane","play-circle","play","plug-zap","plus-circle","plus-square","plus","pocket","podcast","pointer","pound-sterling","power-off","power","printer","qr-code","quote","radio-receiver","radio","redo","refresh-ccw","refresh-cw","regex","repeat-1","repeat","reply-all","reply","rewind","rocket","rocking-chair","rotate-ccw","rotate-cw","rss","ruler","russian-ruble","save","scale","scan-line","scan","scissors","screen-share-off","screen-share","search","send","separator-horizontal","separator-vertical","server-crash","server-off","server","settings-2","settings","share-2","share","sheet","shield-alert","shield-check","shield-close","shield-off","shield","shirt","shopping-bag","shopping-cart","shovel","shrink","shuffle","sidebar-close","sidebar-open","sidebar","sigma","signal-high","signal-low","signal-medium","signal-zero","signal","skip-back","skip-forward","skull","slack","slash","sliders","smartphone-charging","smartphone","smile","snowflake","sort-asc","sort-desc","speaker","sprout","square","star-half","star","stop-circle","stretch-horizontal","stretch-vertical","strikethrough","subscript","sun","sunrise","sunset","superscript","swiss-franc","switch-camera","table","tablet","tag","target","tent","terminal-square","terminal","text-cursor-input","text-cursor","thermometer-snowflake","thermometer-sun","thermometer","thumbs-down","thumbs-up","ticket","timer-off","timer-reset","timer","toggle-left","toggle-right","tornado","trash-2","trash","trello","trending-down","trending-up","triangle","truck","tv-2","tv","twitch","twitter","type","umbrella","underline","undo","unlink-2","unlink","unlock","upload-cloud","upload","user-check","user-minus","user-plus","user-x","user","users","verified","vibrate","video-off","video","view","voicemail","volume-1","volume-2","volume-x","volume","wallet","wand","watch","waves","webcam","wifi-off","wifi","wind","wrap-text","wrench","x-circle","x-octagon","x-square","x","youtube","zap-off","zap","zoom-in","zoom-out","search-large","lucide-clock","lucide-cloud","lucide-cross","lucide-folder","lucide-info","lucide-languages","lucide-link","lucide-pencil","lucide-pin","lucide-search","lucide-star","lucide-trash"]),TC=Array.from(cX);lt();var j1=require("obsidian"),dX=F('<span class="quickadd-icon svelte-18szklt"></span>'),uX={hash:"svelte-18szklt",code:".quickadd-icon.svelte-18szklt {display:inline-flex;align-items:center;}.quickadd-icon.svelte-18szklt svg {display:inline-block;vertical-align:middle;}"};function Qe(r,t){ie(t,!0),Ae(r,uX);let e=X(t,"size",3,16),n=pe(void 0);Dt(()=>{if(!f(n)||!t.iconId)return;(0,j1.setIcon)(f(n),t.iconId);let o=f(n).querySelector("svg");o&&(o.setAttribute("width",`${e()}`),o.setAttribute("height",`${e()}`))});var i=dX();xn(i,o=>q(n,o),()=>f(n)),A(r,i),oe()}var pX=F('<div class="qa-choice-icon-setting-control svelte-1267c4j"><span class="qa-choice-icon-setting-preview svelte-1267c4j" aria-hidden="true"><!></span> <input type="text" class="qa-choice-icon-input svelte-1267c4j" aria-label="Choice icon"/></div>'),mX={hash:"svelte-1267c4j",code:".qa-choice-icon-setting-control.svelte-1267c4j {display:flex;align-items:center;gap:8px;min-width:min(18rem, 100%);}.qa-choice-icon-setting-preview.svelte-1267c4j {display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--text-muted);}.qa-choice-icon-input.svelte-1267c4j {width:100%;min-width:0;}"};function wv(r,t){ie(t,!0),Ae(r,mX);let e=X(t,"icon",15),n=k(()=>fp(t.type)),i=k(()=>typeof e()=="string"?e():""),o=k(()=>f(i).trim()||f(n));function s(l){return new vi(t.app,l,TC,50)}function a(l){let c=l.currentTarget.value.trim();e(c||void 0)}{let l=d=>{var u=pX(),p=R(u),m=R(p);Qe(m,{get iconId(){return f(o)},size:18}),$(p);var h=E(p,2);Ct(h),Ft(h,(g,v)=>Id?.(g,v),()=>s),$(u),Q(()=>{Jn(h,f(i)),le(h,"placeholder",f(n))}),ge("input",h,a),A(d,u)},c=k(()=>`Lucide/Obsidian icon id. Leave empty to use ${f(n)}.`);be(r,{name:"Icon",get desc(){return f(c)},control:l,$$slots:{control:!0}})}oe()}He(["input"]);var rm=F("<!> <!>",1),fX=F("<!> <!> <!>",1),hX=F("<!> <!> <!> <!> <!> <!> <!>",1),gX=F("<!> <!> <!> <!> <!>",1);function aI(r,t){ie(t,!0);let e=X(t,"choice",15),n=k(()=>t.plugin.getTemplateFiles().map(y=>y.path)),i=k(()=>e().propertyCapture?"propertyValue":"noteContent"),o=k(()=>{let y=f(i);return[C=>new ln(t.app,C,t.plugin,y)]});function s(y){let C=y.trim();return C?Aa(C)?{valid:!0,message:"Contains format syntax \u2014 resolved at run time."}:nn(t.app,C)!==null||"Template not found":!0}let a=k(()=>e().format.enabled?e().format.format:""),l=[{value:"",label:"Follow global setting"},{value:"enabled",label:"Use selection"},{value:"disabled",label:"Ignore selection"}],c=k(()=>typeof e().useSelectionAsCaptureValue=="boolean"?e().useSelectionAsCaptureValue?"enabled":"disabled":"");function d(y){if(y===""){e(e().useSelectionAsCaptureValue=void 0,!0);return}e(e().useSelectionAsCaptureValue=y==="enabled",!0)}function u(y){e().templater||e(e().templater={},!0),e(e().templater.afterCapture=y?"wholeFile":"none",!0)}var p=gX(),m=ae(p);yo(m,{heading:"Location",children:(y,C)=>{var w=rm(),T=ae(w);ZA(T,{get app(){return t.app},get plugin(){return t.plugin},get choice(){return e()},set choice(I){e(I)}});var P=E(T,2);{var _=I=>{var D=rm(),N=ae(D);be(N,{name:"Create file if it doesn't exist",control:O=>{vt(O,{get checked(){return e().createFileIfItDoesntExist.enabled},set checked(G){e(e().createFileIfItDoesntExist.enabled=G,!0)}})},$$slots:{control:!0}});var K=E(N,2);{var ne=H=>{ni(H,{name:"Create file with a template",desc:"Path to the template QuickAdd applies to the new file.",get bodyVisible(){return e().createFileIfItDoesntExist.createWithTemplate},control:V=>{vt(V,{get checked(){return e().createFileIfItDoesntExist.createWithTemplate},set checked(M){e(e().createFileIfItDoesntExist.createWithTemplate=M,!0)}})},children:(V,M=$t)=>{Lr(V,{get id(){return M()},get value(){return e().createFileIfItDoesntExist.template},placeholder:"Template path",get app(){return t.app},get suggestions(){return f(n)},maxSuggestions:50,validator:s,onChange:B=>e(e().createFileIfItDoesntExist.template=B.trim(),!0)})},$$slots:{control:!0,default:!0}})};z(K,H=>{e().createFileIfItDoesntExist.enabled&&H(ne)})}A(I,D)};z(P,I=>{e().captureToActiveFile||I(_)})}A(y,w)},$$slots:{default:!0}});var h=E(m,2);yo(h,{heading:"Position",children:(y,C)=>{sI(y,{get app(){return t.app},get plugin(){return t.plugin},get choice(){return e()},set choice(w){e(w)}})},$$slots:{default:!0}});var g=E(h,2);yo(g,{heading:"Linking",children:(y,C)=>{var w=rm(),T=ae(w);nv(T,{fileLabel:"captured",get app(){return t.app},get appendLink(){return e().appendLink},set appendLink(_){e(e().appendLink=_,!0)}});var P=E(T,2);be(P,{name:"Copy link to clipboard",desc:"Copy a link to the captured file after the Capture choice runs.",control:I=>{{let D=k(()=>e().copyLinkToClipboard??!1);vt(I,{get checked(){return f(D)},onchange:N=>e(e().copyLinkToClipboard=N,!0)})}},$$slots:{control:!0}}),A(y,w)},$$slots:{default:!0}});var v=E(g,2);yo(v,{heading:"Content",children:(y,C)=>{var w=rm(),T=ae(w);{var P=I=>{var D=rm(),N=ae(D);be(N,{name:"Task",desc:"Formats the value as a task.",control:H=>{vt(H,{get checked(){return e().task},set checked(O){e(e().task=O,!0)}})},$$slots:{control:!0}});var K=E(N,2);be(K,{name:"One entry per line",desc:"Writes the format once for each line of {{VALUE}}.",control:H=>{{let O=k(()=>e().eachLine??!1);vt(H,{get checked(){return f(O)},onchange:G=>e(e().eachLine=G,!0)})}},$$slots:{control:!0}}),A(I,D)};z(T,I=>{e().propertyCapture||I(P)})}var _=E(T,2);ni(_,{name:"Capture format",desc:"Leave empty to capture {{VALUE}} on its own - what you type at the prompt, or the current selection.",children:(D,N=$t)=>{var K=fX(),ne=ae(K);Th(ne,()=>f(i),G=>{var V=()=>f(a),M=B=>e(e().format={enabled:B.trim()!=="",format:B},!0);{let B=k(()=>e().propertyCapture?.action==="addToList"?"One item per line":"{{VALUE}}");Lr(G,{get id(){return N()},inputKind:"textarea",get value(){return V()},set value(J){M(J)},get placeholder(){return f(B)},get makeSuggesters(){return f(o)}})}});var H=E(ne,2);Xd(H,{get value(){return f(a)}});var O=E(H,2);Hi(O,{get value(){return f(a)},get app(){return t.app},get plugin(){return t.plugin}}),A(D,K)},$$slots:{default:!0}}),A(y,w)},$$slots:{default:!0}});var b=E(v,2);yo(b,{heading:"Behavior",children:(y,C)=>{var w=hX(),T=ae(w);{var P=O=>{var G=rm(),V=ae(G);iv(V,{description:"Open the captured file.",get openFile(){return e().openFile},set openFile(J){e(e().openFile=J,!0)}});var M=E(V,2);{var B=J=>{ov(J,{contextLabel:"captured",get fileOpening(){return e().fileOpening},set fileOpening(te){e(e().fileOpening=te,!0)}})};z(M,J=>{e().openFile&&J(B)})}A(O,G)};z(T,O=>{e().captureToActiveFile||O(P)})}var _=E(T,2);be(_,{name:"Use editor selection as default value",desc:"Controls whether this Capture uses the current editor selection as {{VALUE}}. Does not affect {{SELECTED}}.",control:G=>{it(G,{get value(){return f(c)},get options(){return l},onchange:d})},$$slots:{control:!0}});var I=E(_,2);{var D=O=>{be(O,{name:"Run Templater on entire destination file after capture (deprecated)",desc:"Will be removed in a future release. QuickAdd already runs Templater in what it captures. This also runs every <% %> elsewhere in the destination file, including inside code blocks.",control:V=>{{let M=k(()=>e().templater?.afterCapture==="wholeFile");vt(V,{get checked(){return f(M)},onchange:u})}},$$slots:{control:!0}})};z(I,O=>{!e().propertyCapture&&e().templater?.afterCapture==="wholeFile"&&O(D)})}var N=E(I,2);pv(N,{get dateOrigin(){return e().dateOrigin},set dateOrigin(O){e(e().dateOrigin=O,!0)}});var K=E(N,2);sv(K,{get onePageInput(){return e().onePageInput},set onePageInput(O){e(e().onePageInput=O,!0)}});var ne=E(K,2);hv(ne,{get name(){return e().name},get dateOrigin(){return e().dateOrigin},get command(){return e().command},set command(O){e(e().command=O,!0)},get pickDayCommand(){return e().pickDayCommand},set pickDayCommand(O){e(e().pickDayCommand=O,!0)}});var H=E(ne,2);wv(H,{get type(){return e().type},get app(){return t.app},get icon(){return e().icon},set icon(O){e(e().icon=O,!0)}}),A(y,w)},$$slots:{default:!0}}),A(r,p),oe()}nt();var vX=F('<pre class="qaMountFailedDetail svelte-1vm72jj"> </pre>'),yX=F(`<div class="qaMountFailed svelte-1vm72jj"><div class="qaMountFailedHead svelte-1vm72jj"><!> <span class="qaMountFailedTitle svelte-1vm72jj"> </span></div> <p class="qaMountFailedBody svelte-1vm72jj">This part of QuickAdd could not be drawn, so it has been left out. Nothing
|
||
was changed by the error. Include the message below if you report this.</p> <!></div>`),bX={hash:"svelte-1vm72jj",code:".qaMountFailed.svelte-1vm72jj {border:1px solid var(--background-modifier-border);border-radius:var(--radius-m);padding:12px 14px;margin:4px 0 8px;background:var(--background-secondary);}.qaMountFailedHead.svelte-1vm72jj {display:flex;align-items:center;gap:8px;color:var(--text-warning, var(--text-normal));}.qaMountFailedTitle.svelte-1vm72jj {font-weight:var(--font-semibold);color:var(--text-normal);}.qaMountFailedBody.svelte-1vm72jj {margin:8px 0 0;color:var(--text-muted);font-size:var(--font-ui-small, 13px);max-width:68ch;}.qaMountFailedDetail.svelte-1vm72jj {margin:10px 0 0;padding:8px 10px;border-radius:var(--radius-s);background:var(--background-primary);color:var(--text-faint);font-size:var(--font-ui-smaller, 12px);white-space:pre-wrap;word-break:break-word;user-select:text;}"};function lI(r,t){Ae(r,bX);let e=X(t,"detail",3,"");var n=yX(),i=R(n),o=R(i);Qe(o,{iconId:"alert-triangle",size:16});var s=E(o,2),a=re(s);$(i);var l=E(i,4);{var c=d=>{var u=vX(),p=re(u,!0);Q(()=>ee(p,e())),A(d,u)};z(l,d=>{e()&&d(c)})}$(n),Q(()=>ee(a,`QuickAdd couldn't display ${t.what??""}`)),A(r,n)}var wX="this part of QuickAdd";function wi(r,t,e,n={}){let i=new Set(r.childNodes),o;try{o=gd(t,{target:r,props:e})}catch(a){return CX(r,i,Ia(a),n)}let s=!1;return{ok:!0,destroy(){s||(s=!0,op(o))}}}function CX(r,t,e,n){let i=n.what??wX;for(let l of Array.from(r.childNodes))t.has(l)||l.remove();Me(e,`Couldn't display ${i}`);let o=r.createDiv({cls:"qa-mount-failed-host"}),s=null;try{s=gd(n.fallbackComponent??lI,{target:o,props:{what:i,detail:e.message}})}catch{o.textContent=`QuickAdd couldn't display ${i}.`}let a=!1;return{ok:!1,destroy(){a||(a=!0,s&&op(s),o.remove())}}}function Wi(r){return Xc(r)}var nm=require("obsidian");var Y1=require("obsidian");ye();function xX(r,t){try{let e=r.setting;return!e?.open||!e?.openTabById?(S.logMessage("QuickAdd: Obsidian internal settings API is unavailable."),!1):(e.open(),e.openTabById(t),!0)}catch(e){return S.logMessage(`QuickAdd: Failed to open plugin settings automatically: ${e}`),!1}}function K1(r,t,e){try{let n=r.setting;return typeof n?.navigateToSearchResult!="function"?(S.logMessage("QuickAdd: Obsidian's settings page navigation is unavailable."),!1):(n.navigateToSearchResult({tab:t,pagePath:e},null),!0)}catch(n){return S.logMessage(`QuickAdd: Failed to open settings page: ${n}`),!1}}function Q1(r){return r.setting}function X1(r,t){try{let e=Q1(r);return typeof e?.openPage!="function"?(S.logMessage("QuickAdd: Obsidian's settings page navigation is unavailable."),!1):(e.openPage(t),!0)}catch(e){return S.logMessage(`QuickAdd: Failed to open settings page: ${e}`),!1}}function _C(r,t,e){t.title=e,t.titlebarEl.querySelector(".setting-page-title")?.setText(e),Q1(r)?.updatePageTitle?.()}function mc(r,t,e){let n=xX(r,t);return!n&&e?.notice!==!1&&new Y1.Notice("QuickAdd: Unable to open settings automatically. Open Settings \u2192 QuickAdd manually."),n}var Ao=class extends nm.SettingPage{constructor(e,n,i){super();this.app=e;this.onSave=i;this.rendered=!1;this.opener=null;this.title=n,this.rootEl.addClass("quickAddModal","qa-builder-page")}open(){return this.opener=EX(activeDocument.activeElement),X1(this.app,this)?!0:(new nm.Notice(`QuickAdd: Couldn't open the settings for \u201C${this.title}\u201D.`),!1)}display(){this.rendered||(this.rendered=!0,this.render(this.containerEl))}hide(){this.destroy(),super.hide(),this.onSave(this.result()),this.opener&&TX(this.opener)}save(){this.onSave(this.result())}destroy(){}addNameSetting(e,n,i,o){return new nm.SettingGroup(e).addSetting(s=>{s.setName("Name").addText(a=>{a.setValue(n).onChange(l=>{o(l),_C(this.app,this,l.trim()||i)})})})}};function EX(r){return r?.instanceOf(HTMLElement)?{el:r,label:r.closest("[data-choice-id]")?null:r.getAttribute("aria-label"),content:r.closest(".vertical-tab-content-container"),focusVisible:r.matches(":focus-visible")}:null}function TX({el:r,label:t,content:e,focusVisible:n}){window.setTimeout(()=>{let i=r.isConnected?r:t?e?.querySelector(`[aria-label="${CSS.escape(t)}"]`):null,o=r.ownerDocument.activeElement,s=o!==null&&(o===e||o.matches(".setting-item")&&!!i&&o.contains(i));i&&s&&i.focus({focusVisible:n})})}function im(r,t){return r.trim()||t}function J1(r){return r.setting}function Z1(r){let t=J1(r)?.pageStack??[];for(let{page:e}of[...t].reverse())e instanceof Ao&&e.save()}function kC(r){let t=J1(r);t?.pageStack?.some(e=>e.page instanceof Ao)&&t.clearPageStack?.()}function eV(r){return Ze({...r,commitPending:void 0,choice:Wi(r.choice)})}var om=class extends Ao{constructor(e,n,i,o,s,a){super(e,n.name,o);this.choice=n;this.plugin=i;this.form=s;this.what=a;this.handle=null;this.name=n.name}render(e){let n=eV({choice:this.choice,app:this.app,plugin:this.plugin});this.addNameSetting(e,this.name,this.choice.name,i=>{this.name=i,n.choice.name=i}),this.handle=wi(e,this.form,n,{what:this.what}),this.handle.ok&&(this.formProps=n)}result(){return this.formProps?.commitPending?.(),{...Wi(this.formProps?.choice??this.choice),name:im(this.name,this.choice.name)}}destroy(){this.handle?.destroy(),this.handle=null}};var sm=class extends om{constructor(t,e,n,i){super(t,e,n,i,aI,"this capture choice's settings"),this.containerEl.addClass("captureChoiceBuilder"),this.normalizeChoice()}normalizeChoice(){this.choice.insertBefore||(this.choice.insertBefore={enabled:!1,before:"",createIfNotFound:!1,createIfNotFoundLocation:Vi}),this.choice.activeFileWritePosition||(this.choice.activeFileWritePosition="cursor"),this.choice.createFileIfItDoesntExist||(this.choice.createFileIfItDoesntExist={enabled:!1,createWithTemplate:!1,template:""}),!this.choice.captureToActiveFile&&!Ul(this.choice.captureTo)&&(this.choice.captureToCanvasNodeId=""),this.choice.openFile&&(this.choice.fileOpening=rn(this.choice.fileOpening))}};Za();ye();bi();Jt();Nh();var IC=class extends vi{constructor(e,n,i,o){super(e,n,i);this.currentItems=o}updateCurrentItems(e){this.currentItems=e}getSuggestions(e){return super.getSuggestions(e).filter(n=>!this.currentItems.includes(n))}};var KV=require("obsidian");function pV(r,t){var e=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),e.push.apply(e,n)}return e}function Av(r){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?pV(Object(e),!0).forEach(function(n){mm(r,n,e[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(e)):pV(Object(e)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(e,n))})}return r}function lm(r){"@babel/helpers - typeof";return lm=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},lm(r)}function mm(r,t,e){return t in r?Object.defineProperty(r,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):r[t]=e,r}function PX(r,t){if(r==null)return{};var e={},n=Object.keys(r),i,o;for(o=0;o<n.length;o++)i=n[o],!(t.indexOf(i)>=0)&&(e[i]=r[i]);return e}function $X(r,t){if(r==null)return{};var e=PX(r,t),n,i;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(r);for(i=0;i<o.length;i++)n=o[i],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(r,n)&&(e[n]=r[n])}return e}function xI(r,t){return MX(r)||OX(r,t)||EI(r,t)||LX()}function Io(r){return FX(r)||RX(r)||EI(r)||DX()}function FX(r){if(Array.isArray(r))return pI(r)}function MX(r){if(Array.isArray(r))return r}function RX(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function OX(r,t){var e=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(e!=null){var n=[],i=!0,o=!1,s,a;try{for(e=e.call(r);!(i=(s=e.next()).done)&&(n.push(s.value),!(t&&n.length===t));i=!0);}catch(l){o=!0,a=l}finally{try{!i&&e.return!=null&&e.return()}finally{if(o)throw a}}return n}}function EI(r,t){if(r){if(typeof r=="string")return pI(r,t);var e=Object.prototype.toString.call(r).slice(8,-1);if(e==="Object"&&r.constructor&&(e=r.constructor.name),e==="Map"||e==="Set")return Array.from(r);if(e==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e))return pI(r,t)}}function pI(r,t){(t==null||t>r.length)&&(t=r.length);for(var e=0,n=new Array(t);e<t;e++)n[e]=r[e];return n}function DX(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
||
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function LX(){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 ru(r,t){var e=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!e){if(Array.isArray(r)||(e=EI(r))||t&&r&&typeof r.length=="number"){e&&(r=e);var n=0,i=function(){};return{s:i,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(l){throw l},f:i}}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 o=!0,s=!1,a;return{s:function(){e=e.call(r)},n:function(){var l=e.next();return o=l.done,l},e:function(l){s=!0,a=l},f:function(){try{!o&&e.return!=null&&e.return()}finally{if(s)throw a}}}}function Gt(r){return r.ownerDocument.defaultView||window}function MC(r,t,e){return{win:r,id:r.setTimeout(t,e)}}function Iv(r){r&&r.win.clearTimeout(r.id)}function os(r){return JSON.stringify(r,null,2)}function RC(r){if(!r)throw new Error("cannot get depth of a falsy node");return TV(r,0)}function TV(r){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return r.parentElement?TV(r.parentElement,t+1):t-1}function NX(r,t){if(Object.keys(r).length!==Object.keys(t).length)return!1;for(var e in r)if(!{}.hasOwnProperty.call(t,e)||t[e]!==r[e])return!1;return!0}function VX(r,t){if(r.length!==t.length)return!1;for(var e=0;e<r.length;e++)if(r[e]!==t[e])return!1;return!0}var BX="finalize",UX="consider";function fm(r,t,e){r.dispatchEvent(new(Gt(r)).CustomEvent(BX,{detail:{items:t,info:e}}))}function Cc(r,t,e){r.dispatchEvent(new(Gt(r)).CustomEvent(UX,{detail:{items:t,info:e}}))}var qC="draggedEntered",Mv="draggedLeft",zC="draggedOverIndex",TI="draggedLeftDocument",OC={LEFT_FOR_ANOTHER:"leftForAnother",OUTSIDE_OF_ANY:"outsideOfAny"};function qX(r,t,e){r.dispatchEvent(new(Gt(r)).CustomEvent(qC,{detail:{indexObj:t,draggedEl:e}}))}function zX(r,t,e){r.dispatchEvent(new(Gt(r)).CustomEvent(Mv,{detail:{draggedEl:t,type:OC.LEFT_FOR_ANOTHER,theOtherDz:e}}))}function HX(r,t){r.dispatchEvent(new(Gt(r)).CustomEvent(Mv,{detail:{draggedEl:t,type:OC.OUTSIDE_OF_ANY}}))}function WX(r,t,e){r.dispatchEvent(new(Gt(r)).CustomEvent(zC,{detail:{indexObj:t,draggedEl:e}}))}function GX(r){var t=Gt(r);t.dispatchEvent(new t.CustomEvent(TI,{detail:{draggedEl:r}}))}var gr={DRAG_STARTED:"dragStarted",DRAGGED_ENTERED:qC,DRAGGED_ENTERED_ANOTHER:"dragEnteredAnother",DRAGGED_OVER_INDEX:zC,DRAGGED_LEFT:Mv,DRAGGED_LEFT_ALL:"draggedLeftAll",DROPPED_INTO_ZONE:"droppedIntoZone",DROPPED_INTO_ANOTHER:"droppedIntoAnother",DROPPED_OUTSIDE_OF_ANY:"droppedOutsideOfAny",DRAG_STOPPED:"dragStopped"},fn={POINTER:"pointer",KEYBOARD:"keyboard"},jX={space:[" "],enter:["Enter"],space_or_enter:[" ","Enter"]},_V="space_or_enter",YX={space:"space-bar",enter:"enter",space_or_enter:"space-bar or enter"},hm="isDndShadowItem",HC="data-is-dnd-shadow-item-internal",KX="data-is-dnd-shadow-item-hint",gm="id:dnd-shadow-placeholder-0000",QX="dnd-action-dragged-el",nr="id",mI=0;function kV(){mI++}function SV(){if(mI===0)throw new Error("Bug! trying to decrement when there are no dropzones");mI--}var _I=typeof window>"u",We=function(){};function fI(r){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,e,n=t?ZX(r):r.getBoundingClientRect(),i=Gt(r).getComputedStyle(r),o=i.transform;if(o){var s,a,l,c;if(o.startsWith("matrix3d("))e=o.slice(9,-1).split(/, /),s=+e[0],a=+e[5],l=+e[12],c=+e[13];else if(o.startsWith("matrix("))e=o.slice(7,-1).split(/, /),s=+e[0],a=+e[3],l=+e[4],c=+e[5];else return n;var d=i.transformOrigin,u=n.left-l-(1-s)*parseFloat(d),p=n.top-c-(1-a)*parseFloat(d.slice(d.indexOf(" ")+1)),m=s?n.width/s:r.offsetWidth,h=a?n.height/a:r.offsetHeight;return{x:u,y:p,width:m,height:h,top:p,right:u+m,bottom:p+h,left:u}}else return n}function hI(r){var t=fI(r),e=Gt(r);return{top:t.top+e.scrollY,bottom:t.bottom+e.scrollY,left:t.left+e.scrollX,right:t.right+e.scrollX}}function AV(r){var t=r.getBoundingClientRect(),e=Gt(r);return{top:t.top+e.scrollY,bottom:t.bottom+e.scrollY,left:t.left+e.scrollX,right:t.right+e.scrollX}}function IV(r){return{x:(r.left+r.right)/2,y:(r.top+r.bottom)/2}}function XX(r,t){return Math.sqrt(Math.pow(r.x-t.x,2)+Math.pow(r.y-t.y,2))}function Tv(r,t){return r.y<=t.bottom&&r.y>=t.top&&r.x>=t.left&&r.x<=t.right}function PV(r){return IV(AV(r))}function mV(r,t){var e=PV(t);return XX(r,e)}function JX(r){var t=AV(r),e=r.ownerDocument.documentElement;return t.right<0||t.left>e.scrollWidth||t.bottom<0||t.top>e.scrollHeight}function ZX(r){for(var t=r.getBoundingClientRect(),e={top:t.top,bottom:t.bottom,left:t.left,right:t.right},n=!1,i=!1,o=r.parentElement;o&&o!==r.ownerDocument.body;){var s=Gt(o).getComputedStyle(o),a=s.overflowY,l=s.overflowX,c=a==="scroll"||a==="auto",d=l==="scroll"||l==="auto";if(c||d){var u=o.getBoundingClientRect();if(c){var p=Math.max(e.top,u.top),m=Math.min(e.bottom,u.bottom);(p!==e.top||m!==e.bottom)&&(n=!0),e.top=p,e.bottom=m}if(d){var h=Math.max(e.left,u.left),g=Math.min(e.right,u.right);(h!==e.left||g!==e.right)&&(i=!0),e.left=h,e.right=g}}o=o.parentElement}return n||i?{top:e.top,bottom:e.bottom,left:e.left,right:e.right,width:Math.max(0,e.right-e.left),height:Math.max(0,e.bottom-e.top)}:{top:t.top,bottom:t.bottom,left:t.left,right:t.right,width:Math.max(0,t.right-t.left),height:Math.max(0,t.bottom-t.top)}}var dm;function kI(){We(function(){return"resetting indexes cache"}),dm=new Map}kI();function e5(r){var t=Array.from(r.children).findIndex(function(e){return e.getAttribute(HC)});if(t>=0)return dm.has(r)||dm.set(r,new Map),dm.get(r).set(t,hI(r.children[t])),t}function t5(r,t){var e=hI(t);if(!Tv(r,e))return null;var n=t.children;if(n.length===0)return{index:0,isProximityBased:!0};for(var i=e5(t),o=0;o<n.length;o++){var s=hI(n[o]);if(Tv(r,s)){var a=dm.has(t)&&dm.get(t).get(o);return a&&!Tv(r,a)?{index:i,isProximityBased:!1}:{index:o,isProximityBased:!1}}}for(var l=Number.MAX_VALUE,c=void 0,d=0;d<n.length;d++){var u=mV(r,n[d]);u<l&&(l=u,c=d)}if(n.length>0){var p=n.length,m=n[p-1],h=m.cloneNode(!1);h.style.visibility="hidden",h.style.pointerEvents="none",t.appendChild(h);var g=mV(r,h);g<l&&(c=p),t.removeChild(h)}return{index:c,isProximityBased:!0}}var r5=200,fV=10,DC,FC;function n5(r,t){var e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:r5,n=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0,o,s,a=!1,l,c=Gt(r),d={};FC=d;var u=Array.from(t).sort(function(m,h){return RC(h)-RC(m)});function p(){var m=i(),h=n.multiScrollIfNeeded();if(!h&&l&&Math.abs(l.x-m.x)<fV&&Math.abs(l.y-m.y)<fV){DC=MC(c,p,e);return}if(JX(r)){We(function(){return"off document"}),GX(r);return}l=m;var g=!1,v=ru(u),b;try{for(v.s();!(b=v.n()).done;){var y=b.value;h&&kI();var C=t5(m,y);if(C!==null){var w=C.index;if(g=!0,y!==o){if(o&&zX(o,r,y),FC!==d)return;qX(y,C,r),o=y}else w!==s&&(WX(y,C,r),s=w);break}}}catch(T){v.e(T)}finally{v.f()}!g&&a&&o?(HX(o,r),o=void 0,s=void 0,a=!1):a=!0,FC===d&&(DC=MC(c,p,e))}p()}function i5(){We(function(){return"unobserving"}),FC=void 0,Iv(DC),DC=void 0,kI()}var Cv=30;function o5(){var r;function t(){r={directionObj:void 0,stepPx:0}}t();function e(o){var s=r,a=s.directionObj,l=s.stepPx;a&&(o.scrollBy(a.x*l,a.y*l),Gt(o).requestAnimationFrame(function(){return e(o)}))}function n(o){return Cv-o}function i(o,s){if(!s)return!1;var a=s5(o,s),l=!!r.directionObj;if(a===null)return l&&t(),!1;var c=!1,d=!1;return s.scrollHeight>s.clientHeight&&(a.bottom<Cv?(c=!0,r.directionObj={x:0,y:1},r.stepPx=n(a.bottom)):a.top<Cv&&(c=!0,r.directionObj={x:0,y:-1},r.stepPx=n(a.top)),!l&&c)||s.scrollWidth>s.clientWidth&&(a.right<Cv?(d=!0,r.directionObj={x:1,y:0},r.stepPx=n(a.right)):a.left<Cv&&(d=!0,r.directionObj={x:-1,y:0},r.stepPx=n(a.left)),!l&&d)?(e(s),!0):(t(),!1)}return{scrollIfNeeded:i,resetScrolling:t}}function s5(r,t){var e=t===t.ownerDocument.scrollingElement?{top:0,bottom:Gt(t).innerHeight,left:0,right:Gt(t).innerWidth}:t.getBoundingClientRect();return Tv(r,e)?{top:r.y-e.top,bottom:e.bottom-r.y,left:r.x-e.left,right:e.right-r.x}:null}function a5(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0;We(function(){return"creating multi-scroller"});var e=c5(r),n=Array.from(e).sort(function(l,c){return RC(c)-RC(l)}),i=o5(),o=i.scrollIfNeeded,s=i.resetScrolling;function a(){var l=t();if(!l||!n)return!1;for(var c=n.filter(function(p){return Tv(l,p.getBoundingClientRect())||p===p.ownerDocument.scrollingElement}),d=0;d<c.length;d++){var u=o(l,c[d]);if(u)return!0}return!1}return{multiScrollIfNeeded:e.size>0?a:function(){return!1},destroy:function(){return s()}}}function l5(r){if(!r)return[];for(var t=[],e=r;e;){var n=Gt(e).getComputedStyle(e),i=n.overflow;i.split(" ").some(function(o){return o.includes("auto")||o.includes("scroll")})&&t.push(e),e=e.parentElement}return t}function c5(r){var t=new Set,e=ru(r),n;try{for(e.s();!(n=e.n()).done;){var i=n.value;l5(i).forEach(function(s){return t.add(s)});var o=i.ownerDocument.scrollingElement;(o.scrollHeight>o.clientHeight||o.scrollWidth>o.clientHeight)&&t.add(o)}}catch(s){e.e(s)}finally{e.f()}return t}function d5(r){var t=r.cloneNode(!0),e=[],n=r.tagName==="SELECT",i=n?[r]:Io(r.querySelectorAll("select")),o=ru(i),s;try{for(o.s();!(s=o.n()).done;){var a=s.value;e.push(a.value)}}catch(C){o.e(C)}finally{o.f()}if(i.length>0)for(var l=n?[t]:Io(t.querySelectorAll("select")),c=0;c<l.length;c++){var d=l[c],u=e[c],p=d.querySelector('option[value="'.concat(u,'"'));p&&p.setAttribute("selected",!0)}var m=r.tagName==="CANVAS",h=m?[r]:Io(r.querySelectorAll("canvas"));if(h.length>0)for(var g=m?[t]:Io(t.querySelectorAll("canvas")),v=0;v<g.length;v++){var b=h[v],y=g[v];y.width=b.width,y.height=b.height,b.width>0&&b.height>0&&y.getContext("2d").drawImage(b,0,0)}return t}var Pv=Object.freeze({USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT:"USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT"}),u5=mm({},Pv.USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT,!1);function $V(r){if(!Pv[r])throw new Error("Can't get non existing feature flag ".concat(r,"! Supported flags: ").concat(Object.keys(Pv)));return u5[r]}var p5=.2;function Jd(r){return"".concat(r," ").concat(p5,"s ease")}function FV(r){var t=r.style.transitionProperty.split(",").map(function(e){return e.trim()});t.includes("all")||(t.includes("width")||(r.style.transition+=", ".concat(Jd("width"))),t.includes("height")||(r.style.transition+=", ".concat(Jd("height"))))}function m5(r,t){var e=r.getBoundingClientRect(),n=Gt(r),i=d5(r);MV(r,i),i.id=QX,i.style.position="fixed";var o=e.top,s=e.left;if(i.style.top="".concat(o,"px"),i.style.left="".concat(s,"px"),t){var a=IV(e);o-=a.y-t.y,s-=a.x-t.x,n.setTimeout(function(){i.style.top="".concat(o,"px"),i.style.left="".concat(s,"px")},0)}return i.style.margin="0",i.style.boxSizing="border-box",i.style.height="".concat(e.height,"px"),i.style.width="".concat(e.width,"px"),i.style.transition="".concat(Jd("top"),", ").concat(Jd("left"),", ").concat(Jd("background-color"),", ").concat(Jd("opacity"),", ").concat(Jd("color")," "),n.setTimeout(function(){return FV(i)},0),i.style.zIndex="9999",i.style.cursor="grabbing",i}function f5(r){r.style.cursor="grab"}function h5(r,t,e,n){FV(r),MV(t,r);var i=t.getBoundingClientRect(),o=r.getBoundingClientRect(),s=Gt(r).getComputedStyle(r),a=parseFloat(s.left),l=parseFloat(s.top),c=i.width-o.width,d=i.height-o.height;if(c||d){var u={left:o.width?(e-o.left)/o.width:0,top:o.height?(n-o.top)/o.height:0};$V(Pv.USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT)||(r.style.height="".concat(i.height,"px"),r.style.width="".concat(i.width,"px")),r.style.left="".concat(a-u.left*c,"px"),r.style.top="".concat(l-u.top*d,"px")}}function MV(r,t){var e=Gt(r).getComputedStyle(r);Array.from(e).filter(function(n){return n.startsWith("background")||n.startsWith("padding")||n.startsWith("font")||n.startsWith("text")||n.startsWith("align")||n.startsWith("justify")||n.startsWith("display")||n.startsWith("flex")||n.startsWith("border")||n==="opacity"||n==="color"||n==="list-style-type"||$V(Pv.USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT)&&(n==="width"||n==="height")}).forEach(function(n){return t.style.setProperty(n,e.getPropertyValue(n),e.getPropertyPriority(n))})}function g5(r,t){r.draggable=!1,r.ondragstart=function(){return!1},t?(r.style.userSelect="",r.style.WebkitUserSelect="",r.style.cursor=""):(r.style.userSelect="none",r.style.WebkitUserSelect="none",r.style.cursor="grab")}function RV(r){r.style.display="none",r.style.position="fixed",r.style.zIndex="-5"}function v5(r){r.style.visibility="hidden",r.setAttribute(HC,"true")}function y5(r){r.style.visibility="",r.removeAttribute(HC)}function gI(r){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){},e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:function(){return[]};r.forEach(function(n){var i=t(n);Object.keys(i).forEach(function(o){n.style[o]=i[o]}),e(n).forEach(function(o){return n.classList.add(o)})})}function SI(r){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){},e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:function(){return[]};r.forEach(function(n){var i=t(n);Object.keys(i).forEach(function(o){n.style[o]=""}),e(n).forEach(function(o){return n.classList.contains(o)&&n.classList.remove(o)})})}function b5(r){var t=r.style.minHeight,e=Gt(r).getComputedStyle(r);r.style.minHeight=e.getPropertyValue("height");var n=r.style.minWidth;return r.style.minWidth=e.getPropertyValue("width"),function(){r.style.minHeight=t,r.style.minWidth=n}}var w5="--any--",C5=100,x5=20,PC=3,E5=80,hV={outline:"rgba(255, 255, 102, 0.7) solid 2px"},gV="data-is-dnd-original-dragged-item",dn,hr,Ci,_v,Bt,WC,wc,pn,qs,un,zs=!1,$v=!1,AI,Rv=!1,cm=[],kv,hc,Ev=!1,II=!1,Us,gc=new Set,ft,Fv,Zd=new Map,zr=new Map,xv=new WeakMap;function T5(r,t){We(function(){return"registering drop-zone if absent"}),Zd.has(t)||Zd.set(t,new Set),Zd.get(t).has(r)||(Zd.get(t).add(r),kV())}function vV(r,t){var e=Zd.get(t);!e||!e.delete(r)||(SV(),e.size===0&&Zd.delete(t))}function PI(r){return Array.from(Zd.get(r)||[]).filter(function(t){return t.ownerDocument.defaultView===ft})}function _5(){We(function(){return"watching dragged element"});var r=PI(_v);if(r.length!==0){gc.size>0&&vI(),gc=new Set(r);var t=ru(gc),e;try{for(t.s();!(e=t.n()).done;){var n=e.value;n.addEventListener(qC,OV),n.addEventListener(Mv,DV),n.addEventListener(zC,LV)}}catch(a){t.e(a)}finally{t.f()}ft.addEventListener(TI,eu);var i=Math.max.apply(Math,Io(Array.from(gc).map(function(a){return zr.get(a).dropAnimationDurationMs}))),o=i===0?x5:Math.max(i,C5);kv=a5(gc,function(){return un});var s=II?function(){return{x:un.x+ft.scrollX,y:un.y+ft.scrollY}}:function(){return PV(hr)};n5(hr,gc,o*1.07,kv,s)}}function vI(){We(function(){return"unwatching dragged element"});var r=ru(gc),t;try{for(r.s();!(t=r.n()).done;){var e=t.value;e.removeEventListener(qC,OV),e.removeEventListener(Mv,DV),e.removeEventListener(zC,LV)}}catch(n){r.e(n)}finally{r.f()}gc=new Set,ft.removeEventListener(TI,eu),kv&&(kv.destroy(),kv=void 0),i5()}function GC(r){return r.findIndex(function(t){return!!t[hm]})}function k5(r){var t;return Av(Av({},r),{},(t={},mm(t,hm,!0),mm(t,nr,gm),t))}function OV(r){We(function(){return["dragged entered",r.currentTarget,r.detail]});var t=zr.get(r.currentTarget),e=t.items,n=t.dropFromOthersDisabled;if(n&&r.currentTarget!==Bt){We(function(){return"ignoring dragged entered because drop is currently disabled"});return}if(Rv=!1,e=e.filter(function(a){return a[nr]!==wc[nr]&&a[nr]!==gm}),We(function(){return"dragged entered items ".concat(os(e))}),Bt!==r.currentTarget){var i=zr.get(Bt).items,o=i.filter(function(a){return!a[hm]});if(Cc(Bt,o,{trigger:gr.DRAGGED_ENTERED_ANOTHER,id:Ci[nr],source:fn.POINTER}),!zs)return}var s=r.detail.indexObj.index;pn=r.currentTarget,e.splice(s,0,wc),Cc(r.currentTarget,e,{trigger:gr.DRAGGED_ENTERED,id:Ci[nr],source:fn.POINTER})}function DV(r){if(zs){We(function(){return["dragged left",r.currentTarget,r.detail]});var t=zr.get(r.currentTarget),e=t.items,n=t.dropFromOthersDisabled;if(n&&r.currentTarget!==Bt&&r.currentTarget!==pn){We(function(){return"drop is currently disabled"});return}var i=Io(e),o=GC(i);o!==-1&&i.splice(o,1);var s=pn;pn=void 0;var a=r.detail,l=a.type,c=a.theOtherDz;if(l===OC.OUTSIDE_OF_ANY||l===OC.LEFT_FOR_ANOTHER&&c!==Bt&&zr.get(c).dropFromOthersDisabled){We(function(){return"dragged left all, putting shadow element back in the origin dz"}),Rv=!0,pn=Bt;var d=s===Bt?i:Io(zr.get(Bt).items);if(d.splice(WC,0,wc),Cc(Bt,d,{trigger:gr.DRAGGED_LEFT_ALL,id:Ci[nr],source:fn.POINTER}),!zs)return}Cc(r.currentTarget,i,{trigger:gr.DRAGGED_LEFT,id:Ci[nr],source:fn.POINTER})}}function LV(r){We(function(){return["dragged is over index",r.currentTarget,r.detail]});var t=zr.get(r.currentTarget),e=t.items,n=t.dropFromOthersDisabled;if(n&&r.currentTarget!==Bt){We(function(){return"drop is currently disabled"});return}var i=Io(e);Rv=!1;var o=r.detail.indexObj.index,s=GC(i);s!==-1&&i.splice(s,1),i.splice(o,0,wc),Cc(r.currentTarget,i,{trigger:gr.DRAGGED_OVER_INDEX,id:Ci[nr],source:fn.POINTER})}function LC(r){r.preventDefault();var t=r.touches?r.touches[0]:r;un={x:t.clientX,y:t.clientY},hr.style.transform="translate3d(".concat(un.x-qs.x,"px, ").concat(un.y-qs.y,"px, 0)")}function eu(){We(function(){return"dropped"}),$v=!0,ft.removeEventListener("mousemove",LC),ft.removeEventListener("touchmove",LC),ft.removeEventListener("mouseup",eu),ft.removeEventListener("touchend",eu),vI(),f5(hr),pn||(We(function(){return"element was dropped right after it left origin but before entering somewhere else"}),pn=Bt),We(function(){return["dropped in dz",pn]});var r=zr.get(pn),t=r.items,e=r.type;SI(PI(e),function(o){return zr.get(o).dropTargetStyle},function(o){return zr.get(o).dropTargetClasses});var n=GC(t);n===-1&&pn===Bt&&(n=WC),t=t.map(function(o){return o[hm]?Ci:o});function i(){vI(),AI(),fm(pn,t,{trigger:Rv?gr.DROPPED_OUTSIDE_OF_ANY:gr.DROPPED_INTO_ZONE,id:Ci[nr],source:fn.POINTER}),pn!==Bt&&fm(Bt,zr.get(Bt).items,{trigger:gr.DROPPED_INTO_ANOTHER,id:Ci[nr],source:fn.POINTER});var o=Array.from(pn.children).find(function(s){return s.getAttribute(HC)});o&&y5(o),I5()}zr.get(pn).dropAnimationDisabled?i():S5(n,i)}function S5(r,t){var e=r>-1?fI(pn.children[r],!1):fI(pn,!1),n={x:e.left-parseFloat(hr.style.left),y:e.top-parseFloat(hr.style.top)},i=zr.get(pn),o=i.dropAnimationDurationMs,s="transform ".concat(o,"ms ease");hr.style.transition=hr.style.transition?hr.style.transition+","+s:s,hr.style.transform="translate3d(".concat(n.x,"px, ").concat(n.y,"px, 0)"),Fv={timeout:MC(ft,NV,o),finalize:t}}function NV(){var r=Fv,t=r.finalize;Fv=void 0,t()}function VV(){We(function(){return"the drag's window is going away"}),$v||eu(),Fv&&(Iv(Fv.timeout),NV())}function A5(r,t){var e={dz:r,destroy:t};cm.push(e),Gt(r).requestAnimationFrame(function(){cm.includes(e)&&(RV(r),r.ownerDocument.body.appendChild(r))})}function I5(){hr&&hr.remove&&hr.remove(),dn&&dn.remove&&dn.remove(),hr=void 0,dn=void 0,Ci=void 0,_v=void 0,Bt=void 0,WC=void 0,wc=void 0,pn=void 0,qs=void 0,un=void 0,zs=!1,$v=!1,AI=void 0,Rv=!1,ft.removeEventListener("pagehide",VV),ft=void 0,Iv(hc),hc=void 0,Ev=!1,II=!1,Us=void 0,cm.length&&(We(function(){return["will destroy zones that were removed during drag",cm]}),cm.forEach(function(r){var t=r.dz,e=r.destroy;e(),t.remove()}),cm=[])}function P5(r,t){var e=!1,n=!1,i={items:void 0,type:void 0,flipDurationMs:0,dragDisabled:!1,morphDisabled:!1,dropFromOthersDisabled:!1,dropTargetStyle:hV,dropTargetClasses:[],transformDraggedElement:function(){},centreDraggedOnCursor:!1,useCursorForDetection:!1,dropAnimationDisabled:!1,delayTouchStartMs:0};We(function(){return["dndzone good to go options: ".concat(os(t),", config: ").concat(os(i)),{node:r}]});var o=new Map;function s(){ft.addEventListener("mousemove",d,{passive:!1}),ft.addEventListener("touchmove",d,{passive:!1,capture:!1}),ft.addEventListener("mouseup",c,{passive:!1}),ft.addEventListener("touchend",c,{passive:!1}),ft.addEventListener("pagehide",l)}function a(){ft.removeEventListener("mousemove",d),ft.removeEventListener("touchmove",d),ft.removeEventListener("mouseup",c),ft.removeEventListener("touchend",c),ft.removeEventListener("pagehide",l),hc&&(Iv(hc),hc=void 0,Ev=!1)}function l(){Us===r&&(a(),ft=void 0,Us=void 0,dn=void 0,qs=void 0,un=void 0)}function c(h){if(Us===r&&(l(),h.type==="touchend")){var g=new(Gt(h.target)).Event("click",{bubbles:!0,cancelable:!0});h.target.dispatchEvent(g)}}function d(h){if(!(n||Us!==r)){var g=!!h.touches,v=g?h.touches[0]:h;if(g&&i.delayTouchStartMs>0&&!Ev){un={x:v.clientX,y:v.clientY},(Math.abs(un.x-qs.x)>=PC||Math.abs(un.y-qs.y)>=PC)&&(Iv(hc),hc=void 0,c(h));return}h.preventDefault(),un={x:v.clientX,y:v.clientY},(Math.abs(un.x-qs.x)>=PC||Math.abs(un.y-qs.y)>=PC)&&p()}}function u(h){if(h.target!==h.currentTarget&&(h.target.value!==void 0||h.target.isContentEditable)){We(function(){return"won't initiate drag on a nested input element"});return}if(h.button){We(function(){return"ignoring none left click button: ".concat(h.button)});return}if(n||zs||Us){We(function(){return"cannot start a new drag before finalizing the current drag or pending gesture"});return}var g=!!h.touches,v=g&&i.delayTouchStartMs>0;v||h.preventDefault(),h.stopPropagation(),Us=r;var b=g?h.touches[0]:h;if(qs={x:b.clientX,y:b.clientY},un=Av({},qs),dn=h.currentTarget,ft=Gt(dn),v){var y=dn;Ev=!1,hc=MC(ft,function(){n||Us!==r||dn!==y||(Ev=!0,p())},i.delayTouchStartMs)}s()}function p(){var h;if(n||Us!==r||zs||!((h=dn)!==null&&h!==void 0&&h.parentElement)){l();return}a(),Us=void 0,We(function(){return["drag start config: ".concat(os(i)),dn]}),zs=!0;var g=o.get(dn);WC=g,Bt=dn.parentElement;var v=Bt.closest("dialog")||Bt.closest("[popover]")||Bt.getRootNode(),b=v.body||v,y=i.items,C=i.type,w=i.centreDraggedOnCursor,T=i.useCursorForDetection,P=Io(y);Ci=P[g],_v=C,wc=k5(Ci),II=T,hr=m5(dn,w&&un),b.appendChild(hr);function _(){if(!(!hr||$v))if(dn.parentElement)ft.requestAnimationFrame(_);else{if(dn.setAttribute(gV,!0),b.appendChild(dn),_5(),!hr)return;RV(dn),wc[nr]=Ci[nr],hr.focus()}}ft.requestAnimationFrame(_),gI(PI(i.type).filter(function(I){return I===Bt||!zr.get(I).dropFromOthersDisabled}),function(I){return zr.get(I).dropTargetStyle},function(I){return zr.get(I).dropTargetClasses}),P.splice(g,1,wc),AI=b5(Bt),ft.addEventListener("mousemove",LC,{passive:!1}),ft.addEventListener("touchmove",LC,{passive:!1,capture:!1}),ft.addEventListener("mouseup",eu,{passive:!1}),ft.addEventListener("touchend",eu,{passive:!1}),ft.addEventListener("pagehide",VV),Cc(Bt,P,{trigger:gr.DRAG_STARTED,id:Ci[nr],source:fn.POINTER})}function m(h){var g=h.items,v=g===void 0?void 0:g,b=h.flipDurationMs,y=b===void 0?0:b,C=h.type,w=C===void 0?w5:C,T=h.dragDisabled,P=T===void 0?!1:T,_=h.morphDisabled,I=_===void 0?!1:_,D=h.dropFromOthersDisabled,N=D===void 0?!1:D,K=h.dropTargetStyle,ne=K===void 0?hV:K,H=h.dropTargetClasses,O=H===void 0?[]:H,G=h.transformDraggedElement,V=G===void 0?function(){}:G,M=h.centreDraggedOnCursor,B=M===void 0?!1:M,J=h.useCursorForDetection,te=J===void 0?!1:J,W=h.dropAnimationDisabled,Z=W===void 0?!1:W,se=h.delayTouchStart,ce=se===void 0?!1:se,$e=zs&&r.ownerDocument.defaultView===ft,Xe=r===Bt||i.type===_v&&!i.dropFromOthersDisabled,Ye=r===Bt||w===_v&&!N;i.dropAnimationDurationMs=y;var he=0;ce===!0?he=E5:typeof ce=="number"&&isFinite(ce)&&ce>=0&&(he=ce),i.delayTouchStartMs=he,i.type&&w!==i.type&&vV(r,i.type),i.type=w,i.items=Io(v),i.dragDisabled=P,i.morphDisabled=I,i.transformDraggedElement=V,i.centreDraggedOnCursor=B,i.useCursorForDetection=te,i.dropAnimationDisabled=Z,e&&$e&&!$v&&(Xe!==Ye||!NX(ne,i.dropTargetStyle)||!VX(O,i.dropTargetClasses))&&(Xe&&SI([r],function(){return i.dropTargetStyle},function(){return i.dropTargetClasses}),Ye&&gI([r],function(){return ne},function(){return O})),i.dropTargetStyle=ne,i.dropTargetClasses=Io(O),i.dropFromOthersDisabled=N,zr.set(r,i),T5(r,w);for(var Re=zs?GC(i.items):-1,Je=0;Je<r.children.length;Je++){var ve=r.children[Je];if(g5(ve,P),Je===Re){I||h5(hr,ve,un.x,un.y),i.transformDraggedElement(hr,Ci,Je),v5(ve);continue}ve.removeEventListener("mousedown",xv.get(ve)),ve.removeEventListener("touchstart",xv.get(ve)),P||(ve.addEventListener("mousedown",u),ve.addEventListener("touchstart",u),xv.set(ve,u)),o.set(ve,Je)}e=!0}return m(t),{update:function(g){We(function(){return"pointer dndzone will update newOptions: ".concat(os(g))}),m(g)},destroy:function(){if(n)return;n=!0,l();var g=ru(r.children),v;try{for(g.s();!(v=g.n()).done;){var b=v.value;b.removeEventListener("mousedown",xv.get(b)),b.removeEventListener("touchstart",xv.get(b))}}catch(C){g.e(C)}finally{g.f()}function y(){We(function(){return"pointer dndzone will destroy"});var C=zr.get(r);C&&(vV(r,C.type),zr.delete(r))}zs&&!r.closest("[".concat(gV,"]"))?(We(function(){return"pointer dndzone will be scheduled for destruction"}),A5(r,y)):y()}}}var $C,yI={DND_ZONE_ACTIVE:"dnd-zone-active",DND_ZONE_DRAG_DISABLED:"dnd-zone-drag-disabled"},BV=($C={},mm($C,yI.DND_ZONE_ACTIVE,"zoneActiveInstruction"),mm($C,yI.DND_ZONE_DRAG_DISABLED,"zoneDragDisabledInstruction"),$C),UV={dragStarted:function(t){var e=t.itemLabel,n=t.zoneLabel,i=t.canMoveBetweenZones;return"Started dragging item ".concat(e,". Use the arrow keys to move it within its list ").concat(n)+(i?", or tab to another list in order to move the item into it":"")},movedToPosition:function(t){var e=t.itemLabel,n=t.zoneLabel,i=t.position;return"Moved item ".concat(e," to position ").concat(i," in the list ").concat(n)},movedToZoneEnd:function(t){var e=t.itemLabel,n=t.zoneLabel;return"Moved item ".concat(e," to the end of the list ").concat(n)},movedToZoneStart:function(t){var e=t.itemLabel,n=t.zoneLabel;return"Moved item ".concat(e," to the beginning of the list ").concat(n)},dropped:function(t){var e=t.itemLabel;return"Stopped dragging item ".concat(e)},zoneActiveInstruction:function(t){var e=t.keyboardDragTrigger;return"Tab to one the items and press ".concat(YX[e]," to start dragging it")},zoneDragDisabledInstruction:"This is a disabled drag and drop list"};var $5=Av({},UV),F5={keyboardDragTrigger:_V},M5="dnd-action-aria-alert",vc=new Map;function bI(r){if(!vc.has(r)){var t=r.createElement("div");(function(){t.id=M5,t.style.position="fixed",t.style.bottom="0",t.style.left="0",t.style.zIndex="-5",t.style.opacity="0",t.style.height="0",t.style.width="0",t.setAttribute("role","alert")})(),r.body.prepend(t),vc.forEach(function(e,n){return!n.defaultView&&vc.delete(n)}),vc.set(r,t),Object.entries(BV).forEach(function(e){var n=xI(e,2),i=n[0],o=n[1];return r.body.prepend(D5(r,i,qV(o,F5)))})}}function R5(r){return _I?null:(r=r||document,r.readyState==="complete"?bI(r):r.addEventListener("DOMContentLoaded",function(){return bI(r)}),Av({},yI))}function O5(r){if(!_I){r=r||document;var t=vc.get(r);t&&(Object.keys(BV).forEach(function(e){var n;return(n=r.getElementById(e))===null||n===void 0?void 0:n.remove()}),t.remove(),vc.delete(r))}}function D5(r,t,e){var n=r.createElement("div");return n.id=t,L5(n,e),n.style.display="none",n.style.position="fixed",n.style.zIndex="-5",n}function L5(r,t){r.replaceChildren();var e=r.ownerDocument.createElement("p");e.textContent=t,r.appendChild(e)}function nu(r,t){if(!_I){t=t||document,vc.has(t)||bI(t);var e=vc.get(t);e.innerHTML="";var n=t.createTextNode(r);e.appendChild(n),e.style.display="none",e.style.display="inline"}}function yV(r,t,e){var n=r[t];return typeof n=="function"?n(e):n}function qV(r,t){try{return yV($5,r,t)}catch(e){We(function(){return['aria string formatter for "'.concat(r,'" threw, falling back to the default'),e]});try{return yV(UV,r,t)}catch(n){return We(function(){return['default aria string formatter for "'.concat(r,'" also threw'),n]}),""}}}function um(r,t,e){nu(qV(r,t),e)}var N5=_V;function V5(r){return jX[N5].includes(r)}var B5="--any--",bV={outline:"rgba(255, 255, 102, 0.7) solid 2px"},Tn=!1,pm,mn,Hs="",el,Gi,yc="",NC,VC=new WeakSet,dI=new WeakMap,uI=new WeakMap,wI=new Map,qr=new Map,bc=new Map,BC=new Map,UC=new Map,CI;function U5(r){for(var t=[r],e=(n=r.defaultView)===null||n===void 0?void 0:n.frameElement;e&&t[t.length-1]!==document;e=Gt(e).frameElement){var n;t.push(e.ownerDocument)}return t}function q5(r){var t=U5(r.ownerDocument);t.forEach(function(e,n){var i=UC.get(e);if(!i){We(function(){return"adding global keydown and click handlers"});var o={keydown:H5,click:W5,pagehide:G5};i={win:e.defaultView,zoneCount:0,documentCount:0,handlers:{}},Object.entries(o).forEach(function(s){var a,l=xI(s,2),c=l[0],d=l[1];i.handlers[c]=function(u){return d(u)},(a=i.win)===null||a===void 0||a.addEventListener(c,i.handlers[c])}),UC.set(e,i)}i.documentCount++,n===0&&i.zoneCount++===0&&(CI=R5(e))}),BC.set(r,t)}function zV(r){var t=BC.get(r);t&&(BC.delete(r),t.forEach(function(e,n){var i=UC.get(e);n===0&&--i.zoneCount===0&&O5(e),!(--i.documentCount>0)&&(We(function(){return"removing global keydown and click handlers"}),UC.delete(e),Object.entries(i.handlers).forEach(function(o){var s,a=xI(o,2),l=a[0],c=a[1];return(s=i.win)===null||s===void 0?void 0:s.removeEventListener(l,c)}))}))}function z5(r,t){var e;We(function(){return"registering drop-zone if absent"}),bc.has(t)||bc.set(t,new Set),bc.get(t).has(r)||(bc.get(t).add(r),kV()),((e=BC.get(r))===null||e===void 0?void 0:e[0])!==r.ownerDocument&&(zV(r),q5(r))}function wV(r,t){We(function(){return"unregistering drop-zone"}),Tn&&mn===r&&tu();var e=bc.get(t);!e||!e.delete(r)||(SV(),e.size===0&&bc.delete(t),zV(r))}function H5(r){Tn&&r.key==="Escape"&&tu()}function W5(r){Tn&&(VC.has(r.currentTarget.document.activeElement)||(We(function(){return"clicked outside of any draggable"}),tu()))}function G5(r){Tn&&mn&&Gt(mn)===r.currentTarget&&(We(function(){return"the focused zone's window is going away"}),tu())}function Sv(r){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:NC;return r.ownerDocument===t}function j5(r,t){var e=r.getBoundingClientRect(),n=t.getBoundingClientRect();return e.top<n.top||e.left<n.left}function $I(r){var t=qr.get(r);return t.type===pm&&!t.dropFromOthersDisabled&&!el.contains(r)&&Sv(r)}function HV(r){return r!==mn&&$I(r)?0:-1}function Y5(){qr.forEach(function(r,t){t.tabIndex=HV(t)})}function K5(){var r=qr.get(mn);return r!=null&&r.items.some(function(t){return t[nr]===Gi})?!0:(We(function(){return"dragged item is gone, dropping"}),tu(),!1)}function CV(r){if(We(function(){return"zone focus"}),!!Tn){var t=r.currentTarget;if(!(t===mn||!$I(t))&&K5()){var e=mn,n=Gi;Hs=t.getAttribute("aria-label")||"";var i=qr.get(mn),o=i.items,s=o.find(function(p){return p[nr]===Gi}),a=o.indexOf(s),l=o.splice(a,1)[0],c=qr.get(t),d=c.items,u=c.autoAriaDisabled;j5(t,mn)?(d.push(l),u||um("movedToZoneEnd",{itemLabel:yc,zoneLabel:Hs,position:d.length,count:d.length},t.ownerDocument)):(d.unshift(l),u||um("movedToZoneStart",{itemLabel:yc,zoneLabel:Hs,position:1,count:d.length},t.ownerDocument)),Tn&&(mn=t),fm(e,o,{trigger:gr.DROPPED_INTO_ANOTHER,id:n,source:fn.KEYBOARD}),qr.has(t)&&fm(t,d,{trigger:gr.DROPPED_INTO_ZONE,id:n,source:fn.KEYBOARD})}}}function WV(){wI.forEach(function(r,t){var e=r.update;return e(qr.get(t))})}function tu(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;if(!(!Tn||!mn)){We(function(){return"drop"});var t=mn,e=qr.get(t),n=Gi,i=pm;if(e){var o=yc,s=Hs,a=NC;if(el=null,Gi=null,yc="",pm=null,mn=null,Hs="",NC=void 0,Tn=!1,!e.autoAriaDisabled){var l=e.items,c=l.findIndex(function(p){return p[nr]===n});um("dropped",{itemLabel:o,zoneLabel:s,position:(c<0?0:c)+1,count:l.length},t.ownerDocument)}var d=t.ownerDocument.activeElement;VC.has(d)&&d.blur(),r&&Cc(t,e.items,{trigger:gr.DRAG_STOPPED,id:n,source:fn.KEYBOARD});var u=bc.get(i);u&&SI(Array.from(u).filter(function(p){return Sv(p,a)}),function(p){return qr.get(p).dropTargetStyle},function(p){return qr.get(p).dropTargetClasses}),WV()}}}function Q5(r,t){var e=!1,n={items:void 0,type:void 0,dragDisabled:!1,zoneTabIndex:0,zoneItemTabIndex:0,dropFromOthersDisabled:!1,dropTargetStyle:bV,dropTargetClasses:[],autoAriaDisabled:!1};function i(p,m,h){p.length<=1||p.splice(h,1,p.splice(m,1,p[h])[0])}function o(p){return Tn&&r===mn&&Sv(r)&&p.currentTarget===el&&p.target===el}function s(p){switch(We(function(){return["handling key down",p.key]}),p.key){case"Enter":case" ":{if(!V5(p.key)||(p.target.disabled!==void 0||p.target.href||p.target.isContentEditable)&&!VC.has(p.target))return;p.preventDefault(),p.stopPropagation(),Tn?tu():a(p);break}case"ArrowDown":case"ArrowRight":{if(!o(p))return;p.preventDefault(),p.stopPropagation();var m=qr.get(r),h=m.items,g=Array.from(r.children),v=g.indexOf(p.currentTarget);if(We(function(){return["arrow down",v]}),v<g.length-1){if(n.autoAriaDisabled||um("movedToPosition",{itemLabel:yc,zoneLabel:Hs,position:v+2,count:h.length},r.ownerDocument),!o(p))break;i(h,v,v+1),fm(r,h,{trigger:gr.DROPPED_INTO_ZONE,id:Gi,source:fn.KEYBOARD})}break}case"ArrowUp":case"ArrowLeft":{if(!o(p))return;p.preventDefault(),p.stopPropagation();var b=qr.get(r),y=b.items,C=Array.from(r.children),w=C.indexOf(p.currentTarget);if(We(function(){return["arrow up",w]}),w>0){if(n.autoAriaDisabled||um("movedToPosition",{itemLabel:yc,zoneLabel:Hs,position:w,count:y.length},r.ownerDocument),!o(p))break;i(y,w,w-1),fm(r,y,{trigger:gr.DROPPED_INTO_ZONE,id:Gi,source:fn.KEYBOARD})}break}}}function a(p){We(function(){return"drag start"}),c(p.currentTarget),mn=r,Hs=r.getAttribute("aria-label")||"",pm=n.type,Tn=!0,NC=r.ownerDocument;var m=Array.from(bc.get(n.type)).filter(function(v){return v===mn||$I(v)});if(gI(m,function(v){return qr.get(v).dropTargetStyle},function(v){return qr.get(v).dropTargetClasses}),!n.autoAriaDisabled){var h=qr.get(r).items,g=h.findIndex(function(v){return v[nr]===Gi});um("dragStarted",{itemLabel:yc,zoneLabel:Hs,position:(g<0?0:g)+1,count:h.length,canMoveBetweenZones:m.length>1},r.ownerDocument)}Tn&&(Cc(r,qr.get(r).items,{trigger:gr.DRAG_STARTED,id:Gi,source:fn.KEYBOARD}),WV())}function l(p){Tn&&p.currentTarget!==el&&(p.stopPropagation(),tu(!1),a(p))}function c(p){var m=qr.get(r),h=m.items,g=Array.from(r.children),v=g.indexOf(p);el=p,el.tabIndex=n.zoneItemTabIndex,Gi=h[v][nr],yc=g[v].getAttribute("aria-label")||""}function d(p){var m=p.items,h=m===void 0?[]:m,g=p.type,v=g===void 0?B5:g,b=p.dragDisabled,y=b===void 0?!1:b,C=p.zoneTabIndex,w=C===void 0?0:C,T=p.zoneItemTabIndex,P=T===void 0?0:T,_=p.dropFromOthersDisabled,I=_===void 0?!1:_,D=p.dropTargetStyle,N=D===void 0?bV:D,K=p.dropTargetClasses,ne=K===void 0?[]:K,H=p.autoAriaDisabled,O=H===void 0?!1:H;n.items=Io(h),n.dragDisabled=y,n.dropFromOthersDisabled=I,n.zoneTabIndex=w,n.zoneItemTabIndex=P,n.dropTargetStyle=N,n.dropTargetClasses=ne,n.autoAriaDisabled=O,n.type&&v!==n.type&&wV(r,n.type),n.type=v,z5(r,v),O||(r.setAttribute("role","list"),r.setAttribute("aria-describedby",y?CI.DND_ZONE_DRAG_DISABLED:CI.DND_ZONE_ACTIVE)),qr.set(r,n);var G=!1;Tn?(G=Sv(r)&&n.type===pm&&n.items.some(function(B){return B[nr]===Gi})&&r!==mn,G&&(mn=r,Hs=r.getAttribute("aria-label")||""),r.tabIndex=HV(r)):r.tabIndex=n.zoneTabIndex,r.addEventListener("focus",CV);for(var V=function(J){var te,W=r.children[J];VC.add(W),W.tabIndex=Tn?-1:n.zoneItemTabIndex,O||W.setAttribute("role","listitem"),W.removeEventListener("keydown",dI.get(W)),W.removeEventListener("click",uI.get(W)),y||(W.addEventListener("keydown",s),dI.set(W,s),W.addEventListener("click",l),uI.set(W,l)),Tn&&Sv(r)&&n.type===pm&&((te=n.items[J])===null||te===void 0?void 0:te[nr])===Gi&&(We(function(){return["focusing on",{i:J,focusedItemId:Gi}]}),el=W,el.tabIndex=n.zoneItemTabIndex,W.focus())},M=0;M<r.children.length;M++)V(M);G&&Tn&&Y5()}d(t);var u={update:function(m){We(function(){return"keyboard dndzone will update newOptions: ".concat(os(m))}),d(m)},destroy:function(){if(!e){e=!0,We(function(){return"keyboard dndzone will destroy"}),r.removeEventListener("focus",CV);var m=ru(r.children),h;try{for(m.s();!(h=m.n()).done;){var g=h.value;g.removeEventListener("keydown",dI.get(g)),g.removeEventListener("click",uI.get(g))}}catch(v){m.e(v)}finally{m.f()}wV(r,n.type),qr.delete(r),wI.delete(r)}}};return wI.set(r,u),u}var X5=["items","flipDurationMs","type","dragDisabled","morphDisabled","dropFromOthersDisabled","zoneTabIndex","zoneItemTabIndex","dropTargetStyle","dropTargetClasses","transformDraggedElement","autoAriaDisabled","centreDraggedOnCursor","useCursorForDetection","delayTouchStart","dropAnimationDisabled"];function vm(r,t){if(J5(r))return{update:function(){},destroy:function(){}};xV(t);var e=P5(r,t),n=Q5(r,t);return{update:function(o){xV(o),e.update(o),n.update(o)},destroy:function(){e.destroy(),n.destroy()}}}function J5(r){return!!r.closest("[".concat(KX,'="true"]'))}function xV(r){var t=r.items;r.flipDurationMs,r.type,r.dragDisabled,r.morphDisabled,r.dropFromOthersDisabled;var e=r.zoneTabIndex,n=r.zoneItemTabIndex;r.dropTargetStyle;var i=r.dropTargetClasses;r.transformDraggedElement,r.autoAriaDisabled,r.centreDraggedOnCursor,r.useCursorForDetection;var o=r.delayTouchStart;r.dropAnimationDisabled;var s=$X(r,X5);if(Object.keys(s).length>0&&console.warn("dndzone will ignore unknown options",s),!t)throw new Error("no 'items' key provided to dndzone");var a=t.find(function(d){return!{}.hasOwnProperty.call(d,nr)});if(a)throw new Error("missing '".concat(nr,"' property for item ").concat(os(a)));if(i&&!Array.isArray(i))throw new Error("dropTargetClasses should be an array but instead it is a ".concat(lm(i),", ").concat(os(i)));if(e&&!EV(e))throw new Error("zoneTabIndex should be a number but instead it is a ".concat(lm(e),", ").concat(os(e)));if(n&&!EV(n))throw new Error("zoneItemTabIndex should be a number but instead it is a ".concat(lm(n),", ").concat(os(n)));if(o!==void 0&&o!==!1){var l=o===!0,c=typeof o=="number"&&isFinite(o)&&o>=0;if(!l&&!c)throw new Error("delayTouchStart should be a boolean (true/false) or a non-negative number but instead it is a ".concat(lm(o),", ").concat(os(o)))}}function EV(r){return!isNaN(r)&&(function(t){return(t|0)===t})(parseFloat(r))}function GV(r){var t=r,e=new Set;return{get:function(){return t},set:function(i){t=i,Array.from(e).forEach(function(o){return o(t)})},subscribe:function(i){e.add(i),i(t)},unsubscribe:function(i){e.delete(i)}}}var dMe=GV(!0),uMe=GV(!1);var Z5=[[9,5],[9,12],[9,19],[15,5],[15,12],[15,19]];function FI(r,t,e=!1){if(!r)return;r.classList.add("qa-drag-clone"),r.dataset.qaMulti=e?"true":"false";let n=r.querySelector(":scope > .qa-drag-pill");if(!n){n=r.createDiv({cls:"qa-drag-pill"});let s=n.createSpan({cls:"qa-drag-pill-grip"}).createSvg("svg",{attr:{viewBox:"0 0 24 24",width:14,height:14,fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"}});for(let[a,l]of Z5)s.createSvg("circle",{attr:{cx:a,cy:l,r:1}});n.createSpan({cls:"qa-drag-pill-label"})}let i=n.querySelector(".qa-drag-pill-label");i&&i.textContent!==t&&(i.textContent=t)}function xi(r){return r.filter(t=>t.id!==gm)}function ym(r,t){let e=r.findIndex(i=>i.id===gm);if(e===-1)return null;let n={...r[e]};return delete n[hm],{item:{...n,id:t},index:e}}function jV(r,t){return r.map(e=>e.id===t.id?t:e)}function bm(r,t,e){let n=r.findIndex(a=>a.id===t);if(n===-1)return null;let i=n+e;if(i<0||i>=r.length||i===n)return null;let o=[...r],[s]=o.splice(n,1);return o.splice(i,0,s),o}var YV=r=>r.name??"";function wm(r,t=YV){if(r.detail.info.trigger!==gr.DRAG_STARTED)return;let e=r.detail.items.find(o=>o.id===gm),i=r.currentTarget?.ownerDocument.getElementById("dnd-action-dragged-el");!e||!i||FI(i,t(e),e.type==="Multi")}function Cm(r){let t=r.resolveLabel??YV;return{items:r.items,dragDisabled:r.dragDisabled,flipDurationMs:0,morphDisabled:!0,useCursorForDetection:!0,centreDraggedOnCursor:!1,transformDraggedElement:(e,n)=>FI(e,n?t(n):"",n?.type==="Multi"),dropTargetStyle:{},dropTargetClasses:r.dropTargetClasses??[],dropAnimationDisabled:!0,autoAriaDisabled:!0,zoneItemTabIndex:-1,delayTouchStart:200,...r.type?{type:r.type}:{}}}function xm(){let r=pe(!1),t=!1;function e(){q(r,!0),t=!1;let n=()=>{window.removeEventListener("pointerup",n,!0),window.removeEventListener("pointercancel",n,!0),t||q(r,!1)};window.addEventListener("pointerup",n,!0),window.addEventListener("pointercancel",n,!0)}return{get armed(){return f(r)},markStarted(){t=!0},reset(){q(r,!1),t=!1},startDrag:e}}async function Em(r,t){if(await Cs(),!r)return;r.querySelector(`button[aria-label="${CSS.escape(t)}"]`)?.focus()}var e8=F('<button type="button"><!></button>');function Hr(r,t){ie(t,!0);let e=X(t,"size",3,16),n=k(()=>!!(t.onMoveUp||t.onMoveDown));function i(l){l.key==="ArrowUp"&&t.onMoveUp?(l.preventDefault(),l.stopPropagation(),t.onMoveUp()):l.key==="ArrowDown"&&t.onMoveDown&&(l.preventDefault(),l.stopPropagation(),t.onMoveDown())}var o=e8();let s;var a=R(o);Qe(a,{iconId:"grip-vertical",get size(){return e()}}),$(o),Q(()=>{s=Ge(o,1,"qa-icon-button qa-drag-handle",null,s,{"qa-drag-handle-ready":t.dragDisabled,"qa-drag-handle-active":!t.dragDisabled}),le(o,"aria-label",t.label),le(o,"aria-keyshortcuts",f(n)?"ArrowUp ArrowDown":void 0),le(o,"tabindex",t.dragDisabled?0:-1)}),ge("pointerdown",o,()=>t.onDragStart()),ge("keydown",o,i),A(r,o),oe()}He(["pointerdown","keydown"]);function jC(r){let t=e=>e.stopPropagation();return r.addEventListener("mousedown",t),r.addEventListener("touchstart",t,{passive:!0}),{destroy(){r.removeEventListener("mousedown",t),r.removeEventListener("touchstart",t)}}}var t8=F('<button type="button"><!></button>');function Et(r,t){let e=X(t,"size",3,16),n=X(t,"extraClass",3,""),i=X(t,"disabled",3,!1);var o=t8();let s;var a=R(o);Qe(a,{get iconId(){return t.iconId},get size(){return e()}}),$(o),Ft(o,l=>jC?.(l)),Q(()=>{s=Ge(o,1,`qa-icon-button ${n()}`,null,s,{"is-pressed":t.ariaPressed===!0}),le(o,"aria-label",t.label),le(o,"aria-pressed",t.ariaPressed),le(o,"aria-haspopup",t.ariaHasPopup),le(o,"title",t.title),o.disabled=i()}),ge("click",o,function(...l){t.onclick?.apply(this,l)}),A(r,o)}He(["click"]);var r8=F('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!></div></li>'),n8=F('<ol class="qa-folder-list svelte-19gohrx"></ol>'),i8={hash:"svelte-19gohrx",code:".qa-folder-list.svelte-19gohrx {display:grid;grid-template-columns:auto;width:auto;margin:12px 0;padding:0;list-style:none;}"};function MI(r,t){let e=Ri();ie(t,!0),Ae(r,i8);let n=`folder:${e}`,i=KV.Platform.isMobile,o=xm(),s=k(()=>!i&&!o.armed),a=pe(void 0);function l(C){return C.map(w=>({id:w}))}let c=pe(null),d=k(()=>f(c)??l(t.folders)),u=null,p=C=>C.id;function m(C){o.markStarted(),wm(C,p);let w=C.detail.items;u=ym(w,C.detail.info.id)??u,q(c,xi(w),!0)}function h(C){let w=xi(C.detail.items),T=C.detail.info.id;u?.item.id===T&&!w.some(P=>P.id===T)&&(w=[...w],w.splice(Math.min(u.index,w.length),0,u.item)),t.onChange(w.map(P=>P.id)),q(c,null),u=null,C.detail.info.source===fn.POINTER&&o.reset()}function g(C,w){let T=document.activeElement?.getAttribute("aria-label"),P=bm(l(t.folders),C,w);if(!P)return;t.onChange(P.map(I=>I.id));let _=P.findIndex(I=>I.id===C);nu(`Moved ${C} to position ${_+1} of ${P.length}`),T&&Em(f(a),T)}function v(C){t.onChange(t.folders.filter(w=>w!==C))}let b=()=>{o.startDrag()};var y=n8();gt(y,21,()=>xi(f(d)),C=>C.id,(C,w)=>{var T=r8(),P=R(T),_=re(P,!0),I=E(P,2),D=R(I);{let K=k(()=>`Remove folder ${f(w).id}`);Et(D,{iconId:"trash-2",get label(){return f(K)},onclick:()=>v(f(w).id)})}var N=E(D,2);{let K=k(()=>`Reorder ${f(w).id}`);Hr(N,{get label(){return f(K)},get dragDisabled(){return f(s)},onDragStart:b,onMoveUp:()=>g(f(w).id,-1),onMoveDown:()=>g(f(w).id,1)})}$(I),$(T),Q(()=>ee(_,f(w).id)),A(C,T)}),$(y),xn(y,C=>q(a,C),()=>f(a)),Ft(y,(C,w)=>vm?.(C,w),()=>Cm({items:f(d),dragDisabled:f(s),type:n,resolveLabel:p})),Kn("consider",y,m),Kn("finalize",y,h),A(r,y),oe()}function iu(r){return r.enabled?r.chooseWhenCreatingNote?"prompt":r.createInSameFolderAsActiveFile?"active-file":"specified":"obsidian-default"}function QV(r,t){switch(t){case"obsidian-default":return{...r,enabled:!1,chooseWhenCreatingNote:!1,createInSameFolderAsActiveFile:!1};case"specified":return{...r,enabled:!0,chooseWhenCreatingNote:!1,createInSameFolderAsActiveFile:!1};case"active-file":return{...r,enabled:!0,createInSameFolderAsActiveFile:!0,chooseWhenCreatingNote:!1};case"prompt":return{...r,enabled:!0,chooseWhenCreatingNote:!0,createInSameFolderAsActiveFile:!1}}}var XV=[{value:"obsidian-default",label:"Obsidian default"},{value:"specified",label:"In a specific folder"},{value:"active-file",label:"Same folder as current file"},{value:"prompt",label:"Ask for folder each time"}],JV={"obsidian-default":"Use Obsidian's \u201CDefault location for new notes\u201D setting.",specified:"Create the note in the folder(s) below. With multiple folders, you'll be asked which one when the note is created.","active-file":"Create the note next to the currently active file (falls back to the vault root if no file is open).",prompt:"Choose any folder in the vault when the note is created."};Le();ou();Oa();function YC(r){if(!r?.enabled||r.chooseWhenCreatingNote||r.chooseFromSubfolders||r.createInSameFolderAsActiveFile)return;let t=r.folders??[];if(t.length!==1)return;let e=t[0]?.trim();if(e&&!e.includes("{{")&&!(yi(e).length>0))return e}var o8=F(`<div class="qa-folder-mode-warning">Add at least one folder. With none, the note falls back to the active
|
||
file's folder (or you'll be prompted to pick one if no file is open).</div>`),s8=F('<div class="folderSelectionContainer"><div class="folderList"><!></div> <div class="folderInputContainer"><input type="text" class="qa-folder-path-input" placeholder="Folder path" aria-label="Folder path"/> <button type="button" class="mod-cta">Add</button></div></div> <!>',1),a8=F("<!> <!> <!>",1),DI=F("<!> <!>",1),l8=F("<!> <!> <!> <!> <!> <!> <!> <!> <!> <!>",1),c8=F("<!> <!> <!> <!>",1);function LI(r,t){ie(t,!0);let e=M=>{var B=s8(),J=ae(B),te=R(J),W=R(te);MI(W,{get folders(){return n().folder.folders},onChange:Ye=>n(n().folder.folders=Ye,!0)}),$(te);var Z=E(te,2),se=R(Z);Ct(se),Cr(()=>Zn(se,()=>f(v),Ye=>q(v,Ye))),Ft(se,(Ye,he)=>Id?.(Ye,he),()=>y);var ce=E(se,2);$(Z),$(J);var $e=E(J,2);{var Xe=Ye=>{var he=o8();A(Ye,he)};z($e,Ye=>{f(h)&&Ye(Xe)})}Kn("keypress",se,w),ge("click",ce,C),A(M,B)},n=X(t,"choice",15),i=X(t,"commitPending",15),o=k(()=>t.plugin.getTemplateFiles().map(M=>M.path)),s=k(()=>Ja(za(t.app)));function a(M){let B=M.trim();return B?Aa(B)?{valid:!0,message:"Contains format syntax \u2014 resolved at run time."}:nn(t.app,B)!==null||"Template not found":!0}let l=k(()=>n().fileNameFormat.enabled?n().fileNameFormat.format:""),c=[M=>new ln(t.app,M,t.plugin,"fileName")],d=k(()=>RI(n(),n().fileNameFormat.enabled?n().fileNameFormat.format:xr)),u=k(()=>f(d)?"Show matching notes and unresolved links in the note-title prompt.":"Only available when the file name prompt is the default note title: no custom format, {{VALUE}}, or {{NAME}}."),p=k(()=>iu(n().folder)),m=k(()=>JV[f(p)]),h=k(()=>f(p)==="specified"&&n().folder.folders.length===0);function g(M){n(n().folder=QV(n().folder,M),!0)}let v=pe(""),b;function y(M){return b=new IC(t.app,M,f(s),n().folder.folders),b}Dt(()=>{b?.updateCurrentItems(n().folder.folders)});function C(){let M=f(v).trim();if(M){if(n().folder.folders.some(B=>B===M)){S.logWarning("cannot add same folder twice.");return}n().folder.folders.push(M),q(v,"")}}function w(M){M.key==="Enter"&&C()}function T(){f(p)==="specified"&&C()}i(T),GO(T);let P=k(()=>aV(n().fileExistsBehavior)),_=k(()=>f(P)!=="prompt"&&f(P)!=="keep"),I=k(()=>iV(f(P)==="update"?"update":"create")),D=k(()=>n().fileExistsBehavior.kind==="apply"?n().fileExistsBehavior.mode:f(I)[0].id);function N(M){n(n().fileExistsBehavior=lV(M,n().fileExistsBehavior),!0)}function K(M){n(n().fileExistsBehavior={kind:"apply",mode:M},!0)}var ne=c8(),H=ae(ne);yo(H,{heading:"Template",children:(M,B)=>{var J=DI(),te=ae(J);ni(te,{name:"Template path",desc:"Path to the template this choice creates notes from.",children:(se,ce=$t)=>{Lr(se,{get id(){return ce()},get value(){return n().templatePath},placeholder:"Template path",get app(){return t.app},get suggestions(){return f(o)},maxSuggestions:50,validator:a,onChange:$e=>n(n().templatePath=$e.trim(),!0)})},$$slots:{default:!0}});var W=E(te,2);ni(W,{name:"File name",desc:"Leave empty to ask for the note title.",children:(se,ce=$t)=>{var $e=a8(),Xe=ae($e),Ye=()=>f(l),he=ve=>n(n().fileNameFormat={enabled:ve.trim()!=="",format:ve},!0);Lr(Xe,{get id(){return ce()},get value(){return Ye()},set value(ve){he(ve)},placeholder:"{{VALUE}}",get makeSuggesters(){return c}});var Re=E(Xe,2);Xd(Re,{get value(){return f(l)}});var Je=E(Re,2);{let ve=k(()=>YC(n().folder));Hi(Je,{get value(){return f(l)},formatterKind:"fileName",get targetFolderPath(){return f(ve)},get app(){return t.app},get plugin(){return t.plugin}})}A(se,$e)},$$slots:{default:!0}}),A(M,J)},$$slots:{default:!0}});var O=E(H,2);yo(O,{heading:"Location",children:(M,B)=>{var J=DI(),te=ae(J);{let se=$e=>{it($e,{get value(){return f(p)},get options(){return XV},ariaLabel:"New note location",onchange:g})},ce=k(()=>f(p)==="specified"?e:void 0);be(te,{name:"New note location",get desc(){return f(m)},get body(){return f(ce)},control:se,$$slots:{control:!0}})}var W=E(te,2);{var Z=se=>{be(se,{name:"Include subfolders",desc:"Get prompted to choose from both the selected folders and their subfolders when creating the note.",control:$e=>{vt($e,{get checked(){return n().folder.chooseFromSubfolders},set checked(Xe){n(n().folder.chooseFromSubfolders=Xe,!0)}})},$$slots:{control:!0}})};z(W,se=>{f(p)==="specified"&&se(Z)})}A(M,J)},$$slots:{default:!0}});var G=E(O,2);yo(G,{heading:"Linking",children:(M,B)=>{var J=DI(),te=ae(J);nv(te,{fileLabel:"created",get app(){return t.app},get appendLink(){return n().appendLink},set appendLink(Z){n(n().appendLink=Z,!0)}});var W=E(te,2);be(W,{name:"Copy link to clipboard",desc:"Copy a link to the created file after the Template choice runs.",control:se=>{{let ce=k(()=>n().copyLinkToClipboard??!1);vt(se,{get checked(){return f(ce)},onchange:$e=>n(n().copyLinkToClipboard=$e,!0)})}},$$slots:{control:!0}}),A(M,J)},$$slots:{default:!0}});var V=E(G,2);yo(V,{heading:"Behavior",children:(M,B)=>{var J=l8(),te=ae(J);be(te,{name:"Search existing notes before creating",get desc(){return f(u)},control:ze=>{{let ct=k(()=>f(d)?n().discoverExistingNotesBeforeCreate??!1:!1),Ke=k(()=>!f(d));vt(ze,{get checked(){return f(ct)},get disabled(){return f(Ke)},onchange:ot=>n(n().discoverExistingNotesBeforeCreate=ot,!0)})}},$$slots:{control:!0}});var W=E(te,2);{var Z=Ie=>{be(Ie,{name:"When selecting an existing note",control:ct=>{{let Ke=k(()=>n().existingNoteAction??"open"),ot=k(()=>SC.map(or=>({value:or.id,label:or.label})));it(ct,{get value(){return f(Ke)},get options(){return f(ot)},onchange:or=>{let Ir=SC.find(Hn=>Hn.id===or);Ir&&n(n().existingNoteAction=Ir.id,!0)}})}},$$slots:{control:!0}})};z(W,Ie=>{f(d)&&n().discoverExistingNotesBeforeCreate&&Ie(Z)})}var se=E(W,2);{let Ie=ct=>{{let Ke=k(()=>rV.map(ot=>({value:ot.id,label:ot.label})));it(ct,{get value(){return f(P)},get options(){return f(Ke)},onchange:N})}},ze=k(()=>f(d)&&n().discoverExistingNotesBeforeCreate?"If a new note's path already exists":"If the target file already exists");be(se,{get name(){return f(ze)},desc:"Choose whether QuickAdd should ask what to do, update the existing file, create another file, or keep the existing file.",control:Ie,$$slots:{control:!0}})}var ce=E(se,2);{var $e=Ie=>{{let ze=ot=>{{let or=k(()=>f(I).map(Ir=>({value:Ir.id,label:Ir.label})));it(ot,{get value(){return f(D)},get options(){return f(or)},onchange:K})}},ct=k(()=>f(P)==="update"?"Update action":"New file naming"),Ke=k(()=>am(f(D)).description);be(Ie,{get name(){return f(ct)},get desc(){return f(Ke)},control:ze,$$slots:{control:!0}})}};z(ce,Ie=>{f(_)&&Ie($e)})}var Xe=E(ce,2);iv(Xe,{description:"Open the created file.",get openFile(){return n().openFile},set openFile(Ie){n(n().openFile=Ie,!0)}});var Ye=E(Xe,2);{var he=Ie=>{ov(Ie,{contextLabel:"created",get fileOpening(){return n().fileOpening},set fileOpening(ze){n(n().fileOpening=ze,!0)}})};z(Ye,Ie=>{n().openFile&&Ie(he)})}var Re=E(Ye,2);pv(Re,{get dateOrigin(){return n().dateOrigin},set dateOrigin(Ie){n(n().dateOrigin=Ie,!0)}});var Je=E(Re,2);sv(Je,{get onePageInput(){return n().onePageInput},set onePageInput(Ie){n(n().onePageInput=Ie,!0)}});var ve=E(Je,2);hv(ve,{get name(){return n().name},get dateOrigin(){return n().dateOrigin},get command(){return n().command},set command(Ie){n(n().command=Ie,!0)},get pickDayCommand(){return n().pickDayCommand},set pickDayCommand(Ie){n(n().pickDayCommand=Ie,!0)}});var Ve=E(ve,2);wv(Ve,{get type(){return n().type},get app(){return t.app},get icon(){return n().icon},set icon(Ie){n(n().icon=Ie,!0)}}),A(M,J)},$$slots:{default:!0}}),A(r,ne),oe()}He(["click"]);var Tm=class extends om{constructor(t,e,n,i){super(t,e,n,i,LI,"this template choice's settings"),this.containerEl.addClass("templateChoiceBuilder"),this.normalizeChoice()}normalizeChoice(){var t,e,n,i,o,s,a,l,c,d,u;(t=this.choice).fileExistsBehavior??(t.fileExistsBehavior={kind:"prompt"}),this.choice.fileOpening=rn(this.choice.fileOpening),(e=this.choice).templatePath??(e.templatePath=""),(n=this.choice).fileNameFormat??(n.fileNameFormat={enabled:!1,format:""}),(i=this.choice.fileNameFormat).enabled??(i.enabled=!1),(o=this.choice.fileNameFormat).format??(o.format=""),(s=this.choice).folder??(s.folder={enabled:!1,folders:[],chooseWhenCreatingNote:!1,createInSameFolderAsActiveFile:!1,chooseFromSubfolders:!1}),(a=this.choice.folder).enabled??(a.enabled=!1),(l=this.choice.folder).folders??(l.folders=[]),(c=this.choice.folder).chooseWhenCreatingNote??(c.chooseWhenCreatingNote=!1),(d=this.choice.folder).createInSameFolderAsActiveFile??(d.createInSameFolderAsActiveFile=!1),(u=this.choice.folder).chooseFromSubfolders??(u.chooseFromSubfolders=!1)}};tl();var us=require("obsidian");var _i=require("obsidian");var xU=require("obsidian");ss();er();Xl();function Ec(r){if(r.type==="Choice")try{return Wr().getChoiceById(r.choiceId).name}catch{return"(missing choice)"}if(r.type==="Conditional"){let t=r.condition;return`If ${Ql(t)}`}return r.name}var d8=F('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!></div></li>');function VI(r,t){ie(t,!0);var e=d8(),n=R(e),i=re(n,!0),o=E(n,2),s=R(o);{let l=k(()=>`Delete ${Ec(t.command)}`);Et(s,{iconId:"trash-2",get label(){return f(l)},extraClass:"clickable",onclick:()=>t.onDeleteCommand(t.command.id)})}var a=E(s,2);{let l=k(()=>`Reorder ${Ec(t.command)}`);Hr(a,{get label(){return f(l)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.startDrag},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(o),$(e),Q(l=>ee(i,l),[()=>Ec(t.command)]),A(r,e),oe()}er();var u8=F('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> <input type="number" min="0" placeholder=" " class="dotInput svelte-1mt90y0" aria-label="Wait duration in milliseconds"/>ms</span> <div class="quickAddCommandControls"><!> <!></div></li>'),p8={hash:"svelte-1mt90y0",code:".dotInput.svelte-1mt90y0 {border:none;display:inline;font-family:inherit;font-size:inherit;padding:0;width:var(--qa-wait-input-width, 2ch);text-decoration:underline dotted;background-color:transparent;}.dotInput.svelte-1mt90y0:hover {background-color:transparent;}"};function BI(r,t){ie(t,!0),Ae(r,p8);let e=pe(void 0),n=pe(Ze(pt(()=>t.command.time)));function i(){if(!f(e))return;let m=String(f(e).value).length;f(e).style.setProperty("--qa-wait-input-width",`${m===0?2:m}ch`)}function o(m){let h=m.currentTarget.valueAsNumber;q(n,Number.isNaN(h)||h<0?0:h,!0),i(),t.onUpdateCommand({...t.command,time:f(n)})}Eh(i);var s=u8(),a=R(s),l=R(a),c=E(l);Ct(c),xn(c,m=>q(e,m),()=>f(e)),Xt(),$(a);var d=E(a,2),u=R(d);{let m=k(()=>`Delete ${t.command.name}`);Et(u,{iconId:"trash-2",get label(){return f(m)},extraClass:"clickable",onclick:()=>t.onDeleteCommand(t.command.id)})}var p=E(u,2);{let m=k(()=>`Reorder ${t.command.name}`);Hr(p,{get label(){return f(m)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.startDrag},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(d),$(s),Q(()=>{ee(l,`${t.command.name??""} for `),Jn(c,f(n))}),ge("input",c,o),A(r,s),oe()}He(["input"]);var m8=F('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function UI(r,t){ie(t,!0);var e=m8(),n=R(e),i=re(n,!0),o=E(n,2),s=R(o);{let c=k(()=>`Configure ${t.command.name}`);Et(s,{iconId:"settings",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onConfigureChoice(t.command)})}var a=E(s,2);{let c=k(()=>`Delete ${t.command.name}`);Et(a,{iconId:"trash-2",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onDeleteCommand(t.command.id)})}var l=E(a,2);{let c=k(()=>`Reorder ${t.command.name}`);Hr(l,{get label(){return f(c)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.startDrag},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(o),$(e),Q(()=>ee(i,t.command.name)),A(r,e),oe()}var f8=F('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function qI(r,t){ie(t,!0);var e=f8(),n=R(e),i=re(n,!0),o=E(n,2),s=R(o);{let c=k(()=>`Configure ${t.command.name}`);Et(s,{iconId:"settings",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onConfigureScript(t.command)})}var a=E(s,2);{let c=k(()=>`Delete ${t.command.name}`);Et(a,{iconId:"trash-2",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onDeleteCommand(t.command.id)})}var l=E(a,2);{let c=k(()=>`Reorder ${t.command.name}`);Hr(l,{get label(){return f(c)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.startDrag},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(o),$(e),Q(()=>ee(i,t.command.name)),A(r,e),oe()}var _n=require("obsidian");ss();function tB(r,t){let e=r.createDiv({cls:"qa-format-preview-host"}),n=Ze({value:t.value,app:t.app,plugin:t.plugin,targetFolderPath:null}),i=wi(e,Hi,n,{what:"the preview for this field"}),o=!1;return{setValue(s){o||(n.value=s)},destroy(){o||(o=!0,i.destroy(),e.remove())}}}Hh();function rB(r){r.addEventListener("focus",()=>{r.type="text"}),r.addEventListener("blur",()=>{r.type="password"}),r.type="password"}lx();nl();function O8(r){return typeof r=="string"?r:r==null?"":String(r)}function vB(r){if(typeof r=="string")return r;if(r==null)return"";if(typeof r=="number"||typeof r=="boolean")return String(r);try{return JSON.stringify(r)??String(r)}catch{return String(r)}}var cx=class extends _n.Modal{constructor(e,n,i,o){super(e);this.command=n;this.settings=i;this.onCommandChange=o;this.previewHandles=[];this.command.settings||(this.command.settings={}),Pm(this.command.settings,this.settings),this.display(),this.migrateSecretSettings()}display(){this.containerEl.addClass("quickAddModal","userScriptSettingsModal"),this.destroyPreviews(),this.contentEl.empty();let e=vB(this.settings?.name??this.command.name),n=vB(this.settings?.author);this.titleEl.innerText=`${e}${n?` by ${n}`:""}`;let i=this.settings.options;if(i)for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let s=i[o];if(Im(s)){let d=this.addSecretInput(o,"placeholder"in s?s.placeholder:void 0);s.description&&d.setDesc(s.description);continue}let a=s.defaultValue;this.command.settings[o]!==void 0&&(a=this.command.settings[o]);let l,c=s.type;c==="text"||c==="input"?l=this.addInputBox(o,a,s?.placeholder,s.secret):c==="textarea"?l=this.addTextArea(o,a,s?.placeholder):c==="checkbox"||c==="toggle"?l=this.addToggle(o,a):c==="dropdown"||c==="select"?l=this.addDropdown(o,s.options,a):c==="format"&&(l=this.addFormatInput(o,a,s.placeholder)),s.description&&l&&l.setDesc(s.description)}}addInputBox(e,n,i,o){return new _n.Setting(this.contentEl).setName(e).addText(s=>{s.setValue(n).onChange(a=>{this.command.settings[e]=a,this.onCommandChange?.()}).setPlaceholder(i??""),o&&rB(s.inputEl)})}addSecretInput(e,n){let i=new _n.Setting(this.contentEl).setName(e),o="",s,a=()=>{let c=this.command.settings?.[e];return ox(this.command,e)!==void 0||typeof c=="string"&&c.length>0},l=()=>{s&&(s.placeholder=a()?"Secret saved":n??"Paste secret")};return i.addText(c=>{c.setValue("").onChange(d=>{o=d}),c.inputEl.type="password",c.inputEl.addClass("qa-user-script-secret-input"),c.inputEl.setAttribute("aria-label",e),s=c.inputEl,l()}),i.addButton(c=>{c.setIcon("save").setTooltip("Save secret").onClick(async()=>{if(o.length===0){new _n.Notice("Paste a secret before saving.");return}let d=await YI(this.app,this.command,e,o,ox(this.command,e),this.settings.options?.[e]);if(!d){new _n.Notice("SecretStorage is unavailable. Secret was not saved.");return}this.command.settings[e]=tx(d),o="",s&&(s.value=""),l(),this.onCommandChange?.(),new _n.Notice("Secret saved.")}),c.buttonEl.setAttribute("aria-label",`Save ${e}`)}),i.addButton(c=>{c.setIcon("trash-2").setTooltip("Clear secret").onClick(async()=>{let d=ox(this.command,e);if(d&&!await KI(this.app,d)){new _n.Notice("SecretStorage is unavailable. Secret was not cleared.");return}delete this.command.settings[e],o="",s&&(s.value=""),l(),this.onCommandChange?.(),new _n.Notice("Secret cleared.")}),c.buttonEl.setAttribute("aria-label",`Clear ${e}`)}),i}addTextArea(e,n,i){return new _n.Setting(this.contentEl).setName(e).addTextArea(o=>{o.setValue(n).onChange(s=>{this.command.settings[e]=s,this.onCommandChange?.()}).setPlaceholder(i??""),o.inputEl.addClass("qa-user-script-argument-textarea")})}addToggle(e,n){return new _n.Setting(this.contentEl).setName(e).addToggle(i=>i.setValue(n).onChange(o=>{this.command.settings[e]=o,this.onCommandChange?.()}))}addDropdown(e,n,i){return new _n.Setting(this.contentEl).setName(e).addDropdown(o=>{n.forEach(s=>{o.addOption(s,s)}),o.setValue(i),o.onChange(s=>{this.command.settings[e]=s,this.onCommandChange?.()})})}addFormatInput(e,n,i){let o=new _n.Setting(this.contentEl).setName(e),s=O8(n),a=new _n.TextAreaComponent(this.contentEl);new ln(this.app,a.inputEl,Wr()),zh(a.inputEl,{passThroughUntilUsed:!0}),a.inputEl.addClass("qa-user-script-format-textarea"),a.inputEl.setAttribute("aria-label",e);let l=tB(this.contentEl,{app:this.app,plugin:Wr(),value:s});return this.previewHandles.push(l),a.setValue(s).onChange(c=>{this.command.settings[e]=c,l.setValue(c),this.onCommandChange?.()}).setPlaceholder(i??""),o}destroyPreviews(){for(let e of this.previewHandles)e.destroy();this.previewHandles=[]}onClose(){this.destroyPreviews(),super.onClose()}async migrateSecretSettings(){await ix(this.app,this.command,this.settings)&&(this.onCommandChange?.(),this.display())}};ye();au();var X8=F('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function ZI(r,t){ie(t,!0);var e=X8(),n=R(e),i=re(n,!0),o=E(n,2),s=R(o);{let c=k(()=>`Configure ${t.command.name}`);Et(s,{iconId:"settings",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onConfigureAssistant(t.command)})}var a=E(s,2);{let c=k(()=>`Delete ${t.command.name}`);Et(a,{iconId:"trash-2",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onDeleteCommand(t.command.id)})}var l=E(a,2);{let c=k(()=>`Reorder ${t.command.name}`);Hr(l,{get label(){return f(c)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.startDrag},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(o),$(e),Q(()=>ee(i,t.command.name)),A(r,e),oe()}var oi=require("obsidian");var J8="QuickAdd sends the system prompt to the model as written - format syntax like {{DATE}} is not resolved here. Only the prompt template is formatted.",Z8=0;function fx(r,t,e){let n=r.createDiv({text:J8,cls:"qa-literal-format-note"}),i=`qa-literal-format-note-${++Z8}`;n.id=i;let o=s=>{let a=s.includes("{{");n.classList.toggle("qa-literal-format-note--shown",a),a?t.setAttribute("aria-describedby",i):t.removeAttribute("aria-describedby")};return o(e),o}bi();je();Gs();Gv();var bU=require("obsidian");Vm();var m7=[{key:"temperature",name:"Temperature",desc:"Sampling temperature (0-1, the range every provider accepts). Higher values like 0.8 make the output more random; lower values like 0.2 make it more focused and deterministic.",min:0,max:1,step:.1,fallback:1},{key:"top_p",name:"Top P",desc:"Nucleus sampling - an alternative to temperature. The model considers only the tokens comprising the top P probability mass, so 0.1 means the top 10%.",min:0,max:1,step:.1,fallback:1},{key:"frequency_penalty",name:"Frequency penalty",desc:"Positive values penalize tokens by how often they already appear, reducing verbatim repetition; negative values encourage it. Only sent to providers that support it.",min:-2,max:2,step:.1,fallback:0},{key:"presence_penalty",name:"Presence penalty",desc:"Positive values penalize tokens that have appeared at all, encouraging new topics; negative values do the opposite. Only sent to providers that support it.",min:-2,max:2,step:.1,fallback:0}];function wU(r,t,e,n){let i=lu(e,{silent:!0})?.model;i?.supportsTemperature===!1&&r.createDiv({text:`${i.name} uses fixed sampling, so these settings are not sent to it.`,cls:"setting-item-description"});for(let o of m7){let s=typeof t[o.key]=="number";new bU.Setting(r).setName(o.name).setDesc(s?o.desc:`${o.desc} Currently using the provider's default.`).addSlider(a=>{a.setLimits(o.min,o.max,o.step),a.setValue(t[o.key]??o.fallback),a.onChange(l=>{t[o.key]=l})}).addExtraButton(a=>{a.setIcon("rotate-ccw"),a.setTooltip("Reset to provider default"),a.setDisabled(!s),a.onClick(()=>{delete t[o.key],n()})})}}Vm();gi();je();var Bm="Ask me",Vx="__qa-missing-model__";function Bx(r,t,e){let n=U.getState().ai.providers,i=r.selectEl;t={model:t.model,modelRef:Nl(t.model,t.modelRef)},r.addOption(Bm,Bm);let o=new Map,s=0;for(let l of n){if(l.models.length===0)continue;let c=i.createEl("optgroup");c.label=l.name;for(let d of lp(l.models)){let u=`${l.id??l.name}/${d.name}:${s++}`;o.set(u,{providerId:l.id,modelName:d.name}),c.createEl("option",{value:u,text:d.deprecated?`${d.name} (retired)`:d.name})}}let a=f7(t,o);if(a)r.setValue(a);else{let l=t.modelRef?`${t.modelRef.providerId}/${t.modelRef.name}`:t.model;r.addOption(Vx,`(missing) ${l}`);let c=Array.from(i.options).find(d=>d.value===Vx);c&&(c.disabled=!0),r.setValue(Vx)}r.onChange(l=>{if(l===Vx)return;if(l===Bm){e({model:Bm,modelRef:void 0});return}let c=o.get(l);c&&e({model:c.modelName,modelRef:c.providerId?{providerId:c.providerId,name:c.modelName}:void 0})})}function f7(r,t){if(!r.model||r.model===Bm)return Bm;let e=r.modelRef?void 0:lu(r.model,{silent:!0}),n=r.modelRef??(e&&{providerId:e.provider.id,name:e.model.name});if(n){for(let[i,o]of t)if(o.providerId===n.providerId&&o.modelName===n.name)return i}}gi();var Ux=class extends oi.Modal{constructor(e,n){super(e);this.isResolved=!1;this.showAdvancedSettings=!1;this.settings=n,this.originalSettings=this.cloneSettings(n),this.waitForClose=new Promise((i,o)=>{this.rejectPromise=o,this.resolvePromise=i}),this.open(),this.display()}get systemPromptTokenLength(){return Ti(this.settings.systemPrompt)}resolve(e){this.isResolved||(this.isResolved=!0,this.resolvePromise(e))}cloneSettings(e){return{...e,promptTemplate:{...e.promptTemplate},modelParameters:{...e.modelParameters}}}restoreOriginal(){let e=this.cloneSettings(this.originalSettings);Object.assign(this.settings,e),this.settings.promptTemplate=e.promptTemplate,this.settings.modelParameters=e.modelParameters}display(){let e=this.contentEl.createEl("h2");e.addClass("qa-clickable-modal-title"),e.createEl("button",{cls:"qa-rename-title-button",text:`${this.settings.name} settings`,attr:{type:"button","aria-label":`Rename ${this.settings.name}`}}).addEventListener("click",()=>{(async()=>{try{let i=await ir.Prompt(this.app,"New name",this.settings.name,this.settings.name);i&&i!==this.settings.name&&(this.settings.name=i,this.reload())}catch{}})()}),this.addPromptTemplateSetting(this.contentEl),this.addModelSetting(this.contentEl),this.addOutputVariableNameSetting(this.contentEl),this.addShowAdvancedSettingsToggle(this.contentEl),this.showAdvancedSettings&&(this.settings.modelParameters||(this.settings.modelParameters={}),wU(this.contentEl,this.settings.modelParameters,Nl(this.settings.model,this.settings.modelRef)??this.settings.model,()=>this.reload())),this.addSystemPromptSetting(this.contentEl),this.addButtonBar(this.contentEl)}addButtonBar(e){let n=e.createDiv({cls:"qa-command-button-row"});new oi.ButtonComponent(n).setButtonText("Cancel").onClick(()=>{this.restoreOriginal(),this.resolve(null),this.close()}),new oi.ButtonComponent(n).setButtonText("Save").setCta().onClick(()=>{this.resolve(this.settings),this.close()})}reload(){this.contentEl.empty(),this.display()}addPromptTemplateSetting(e){let n=U.getState().ai.promptTemplatesFolderPath,i=ts(this.app,n).map(o=>o.name);new oi.Setting(e).setName("Prompt template").setDesc("Enabling this will have the assistant use the prompt template you specify. If disable, the assistant will ask you for a prompt template to use.").addToggle(o=>{o.setValue(this.settings.promptTemplate.enable),o.onChange(s=>{this.settings.promptTemplate.enable=s})}).addText(o=>{o.setValue(this.settings.promptTemplate.name).onChange(s=>{this.settings.promptTemplate.name=s}),new vi(this.app,o.inputEl,i)})}addModelSetting(e){new oi.Setting(e).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(n=>{Bx(n,this.settings,i=>{this.settings.model=i.model,this.settings.modelRef=i.modelRef,this.reload()})})}addOutputVariableNameSetting(e){new oi.Setting(e).setName("Output variable name").setDesc("The name of the variable used to store the AI Assistant output, i.e. {{value:output}}.").addText(n=>{n.setValue(this.settings.outputVariableName).onChange(i=>{this.settings.outputVariableName=i})})}addSystemPromptSetting(e){new oi.Setting(e).setName("System prompt").setDesc("The system prompt for the AI Assistant");let n=this.contentEl.createDiv(),i=n.createSpan({cls:"qa-ai-token-count"}),o=n.createDiv({text:"Estimated locally. Providers enforce exact context limits.",cls:"qa-ai-token-note"});n.appendChild(i),n.appendChild(o);let s=new oi.TextAreaComponent(e);s.inputEl.addClass("qa-ai-prompt-textarea"),s.inputEl.setAttribute("aria-label","System prompt");let a=fx(e,s.inputEl,this.settings.systemPrompt??""),l=(0,oi.debounce)(()=>{i.innerText=`Estimated tokens: ${this.systemPromptTokenLength}`},50);s.setValue(this.settings.systemPrompt).onChange(c=>{this.settings.systemPrompt=c,a(c),l()}),l()}addShowAdvancedSettingsToggle(e){new oi.Setting(e).setName("Show advanced settings").setDesc("Sampling settings such as temperature and top p. Untouched settings use the provider's defaults.").addToggle(n=>{n.setValue(this.showAdvancedSettings),n.onChange(i=>{this.showAdvancedSettings=i,this.reload()})})}onClose(){this.isResolved||(this.restoreOriginal(),this.resolve(null)),super.onClose()}};var h7=F('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function PP(r,t){ie(t,!0);var e=h7(),n=R(e),i=re(n,!0),o=E(n,2),s=R(o);{let c=k(()=>`Configure ${t.command.name}`);Et(s,{iconId:"settings",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onConfigureOpenFile(t.command)})}var a=E(s,2);{let c=k(()=>`Delete ${t.command.name}`);Et(a,{iconId:"trash-2",get label(){return f(c)},extraClass:"clickable",onclick:()=>t.onDeleteCommand(t.command.id)})}var l=E(a,2);{let c=k(()=>`Reorder ${t.command.name}`);Hr(l,{get label(){return f(c)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.startDrag},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(o),$(e),Q(()=>ee(i,t.command.name)),A(r,e),oe()}var js=require("obsidian");qx();er();var zx=class extends js.Modal{constructor(e,n){super(e);this.isResolved=!1;this.originalCommand=n,this.command={...n,type:"OpenFile"},this.command.focus=this.command.focus??!0,this.command.location=this.command.location??this.deriveLocation(),this.syncLegacyFlagsFromLocation(this.command.location),this.waitForClose=new Promise(i=>{this.resolvePromise=i}),this.display(),this.open()}onClose(){super.onClose(),this.isResolved||(this.resolvePromise(null),this.isResolved=!0)}resolveWithGuard(e){this.isResolved||(this.resolvePromise(e),this.isResolved=!0)}display(){this.containerEl.addClass("quickAddModal","openFileCommandSettingsModal"),this.contentEl.empty();let e=this.contentEl.createEl("h2");e.textContent="Open file command settings",e.addClass("qa-modal-title"),this.addFilePathSetting(),this.addOpenLocationSetting(),this.addFocusSetting(),this.addButtonBar()}addFilePathSetting(){new js.Setting(this.contentEl).setName("File path").setDesc("Path to the file. Supports formatting like {{DATE}}, {{VALUE}}, etc.").addText(e=>e.setPlaceholder("{{DATE}}todo.md").setValue(this.command.filePath).onChange(n=>{this.command.filePath=n,this.command.name=`Open file: ${n}`}))}addOpenLocationSetting(){let e=[{value:"reuse",label:"Reuse active tab"},{value:"tab",label:"New tab"},{value:"split",label:"Split"},{value:"window",label:"New window"},{value:"left-sidebar",label:"Left sidebar"},{value:"right-sidebar",label:"Right sidebar"}];new js.Setting(this.contentEl).setName("Where to open").setDesc("Choose tab, split, window, or sidebar").addDropdown(n=>{for(let{value:i,label:o}of e)n.addOption(i,o);n.setValue(this.deriveLocation()).onChange(i=>{this.command.location=i,this.syncLegacyFlagsFromLocation(i),this.reload()})}),this.deriveLocation()==="split"&&this.addDirectionSetting()}syncLegacyFlagsFromLocation(e){switch(e){case"split":this.command.openInNewTab=!0,this.command.direction||(this.command.direction="vertical");break;case"tab":case"reuse":this.command.openInNewTab=!1,this.command.direction=void 0;break;default:this.command.openInNewTab=!0,this.command.direction=void 0;break}}addDirectionSetting(){new js.Setting(this.contentEl).setName("Split direction").setDesc("How to arrange the new pane relative to the current one").addDropdown(e=>{e.addOption("vertical","Split right").addOption("horizontal","Split down").setValue(this.command.direction??"vertical").onChange(n=>{this.command.direction=n})})}addFocusSetting(){new js.Setting(this.contentEl).setName("Focus opened file").setDesc("Bring the opened file to the foreground").addToggle(e=>e.setValue(this.command.focus??!0).onChange(n=>{this.command.focus=n}))}deriveLocation(){return this.command.location?this.command.location:this.command.openInNewTab?"split":"reuse"}addButtonBar(){let e=this.contentEl.createDiv({cls:"qa-command-button-row qa-command-button-row-compact"});new js.ButtonComponent(e).setButtonText("Cancel").onClick(()=>{this.resolveWithGuard(null),this.close()}),new js.ButtonComponent(e).setButtonText("Save").setCta().onClick(()=>{this.resolveWithGuard(this.command),this.close()})}reload(){this.display()}};Xl();Gr();var g7=F('<li class="quickAddCommandListItem conditionalCommand svelte-3d0n7s"><div class="quickAddCommandLabel"><div class="conditionalSummary svelte-3d0n7s"> </div> <div class="conditionalBranches svelte-3d0n7s"><span> </span> <span> </span></div></div> <div class="quickAddCommandControls"><!> <!> <!> <!> <!></div></li>'),v7={hash:"svelte-3d0n7s",code:".conditionalCommand.svelte-3d0n7s {flex-wrap:wrap;}.conditionalSummary.svelte-3d0n7s {font-weight:600;margin-bottom:4px;}.conditionalBranches.svelte-3d0n7s {display:flex;gap:12px;font-size:0.9em;opacity:0.8;}"};function $P(r,t){ie(t,!0),Ae(r,v7);let e=k(()=>Ql(t.command.condition)),n=k(()=>Mt(t.command.thenCommands).length),i=k(()=>Mt(t.command.elseCommands).length);var o=g7(),s=R(o),a=R(s),l=re(a,!0),c=E(a,2),d=R(c),u=re(d),p=E(d,2),m=re(p);$(c),$(s);var h=E(s,2),g=R(h);{let w=k(()=>`Edit condition for ${f(e)}`);Et(g,{iconId:"settings",get label(){return f(w)},extraClass:"clickable",onclick:()=>t.onConfigureCondition(t.command)})}var v=E(g,2);{let w=k(()=>`Edit then branch for ${f(e)}`);Et(v,{iconId:"corner-down-right",get label(){return f(w)},extraClass:"clickable",onclick:()=>t.onEditThenBranch(t.command)})}var b=E(v,2);{let w=k(()=>`Edit else branch for ${f(e)}`);Et(b,{iconId:"corner-down-left",get label(){return f(w)},extraClass:"clickable",onclick:()=>t.onEditElseBranch(t.command)})}var y=E(b,2);{let w=k(()=>`Delete ${t.command.name}`);Et(y,{iconId:"trash-2",get label(){return f(w)},extraClass:"clickable",onclick:()=>t.onDeleteCommand(t.command.id)})}var C=E(y,2);{let w=k(()=>`Reorder ${t.command.name}`);Hr(C,{get label(){return f(w)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.startDrag},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(h),$(o),Q(()=>{ee(l,f(e)),ee(u,`Then: ${f(n)??""}`),ee(m,`Else: ${f(i)??""}`)}),A(r,o),oe()}var y7=F("<ol></ol>"),b7={hash:"svelte-15ra1ch",code:`.quickAddCommandList.svelte-15ra1ch {display:grid;grid-template-columns:auto;width:auto;border:0 solid black;overflow-y:auto;height:auto;margin-bottom:8px;padding:20px;}
|
||
|
||
/* A macro without steps shows no blank list area. The zone type is unique
|
||
to this list, so an empty list is never a drop target. */.quickAddCommandList.is-empty.svelte-15ra1ch {display:none;}`};function FP(r,t){let e=Ri();ie(t,!0),Ae(r,b7);let n=X(t,"commands",31,()=>Ze([])),i=k(()=>{let M=new Set;return Array.isArray(n())?n().filter(B=>{if(typeof B!="object"||B===null)return!1;let J=B.id;return typeof J!="string"||J===""||M.has(J)?!1:(M.add(J),!0)}):[]}),o=`command:${e}`,s=xU.Platform.isMobile,a=xm(),l=k(()=>!s&&!a.armed),c=pe(void 0),d=M=>M,u=M=>M,p=M=>M,m=M=>M,h=M=>M,g=M=>M;function v(){t.saveCommands(Wi(n()))}let b=null,y=pe(!1);function C(M){a.markStarted(),q(y,M.detail.info.trigger!==gr.DRAG_STOPPED),wm(M,Ec);let B=M.detail.items;b=ym(B,M.detail.info.id)??b,n(xi(B))}function w(M){let B=xi(M.detail.items),J=M.detail.info.id;b?.item.id===J&&!B.some(te=>te.id===J)&&(B=[...B],B.splice(Math.min(b.index,B.length),0,b.item)),b=null,q(y,!1),n(B),M.detail.info.source===fn.POINTER&&a.reset(),v()}let T=()=>{a.startDrag()};function P(M,B){let J=document.activeElement?.getAttribute("aria-label"),te=xi(f(i)),W=bm(te,M,B);if(!W)return;let Z=W.findIndex(ce=>ce.id===M),se=W[Z];n(W),v(),nu(`Moved ${Ec(se)} to position ${Z+1} of ${W.length}`),J&&Em(f(c),J)}function _(M){n(jV(f(i),{...M})),v()}async function I(M){await t.onConfigureCondition?.(M)&&_(M)}function D(M){t.onEditThenBranch?.(M,()=>_(M))}function N(M){t.onEditElseBranch?.(M,()=>_(M))}function K(M){let B=te=>{let W={...M,choice:te,name:te.name};_(W)},J=M.choice;J.type==="Template"?new Tm(t.app,J,t.plugin,B).open():J.type==="Capture"&&new sm(t.app,J,t.plugin,B).open()}async function ne(M){let B;try{B=await su(M,t.app)}catch(te){if(px(te))return;throw te}if(!B?.script){S.logWarning(`${M.name} could not be loaded.`);return}let J=B.settings??{};new cx(t.app,M,J,()=>v()).open()}async function H(M){await new Ux(t.app,M).waitForClose&&_(M)}async function O(M){let B=await new zx(t.app,M).waitForClose;B&&_(B)}var G=y7();let V;gt(G,21,()=>xi(f(i)),M=>M.id,(M,B)=>{var J=bt(),te=ae(J);{var W=he=>{{let Re=k(()=>d(f(B)));BI(he,{get command(){return f(Re)},get dragDisabled(){return f(l)},startDrag:T,get onDeleteCommand(){return t.deleteCommand},onUpdateCommand:_,onMoveUp:()=>P(f(B).id,-1),onMoveDown:()=>P(f(B).id,1)})}},Z=he=>{{let Re=k(()=>u(f(B)));UI(he,{get command(){return f(Re)},get dragDisabled(){return f(l)},startDrag:T,get onDeleteCommand(){return t.deleteCommand},onConfigureChoice:K,onMoveUp:()=>P(f(B).id,-1),onMoveDown:()=>P(f(B).id,1)})}},se=he=>{{let Re=k(()=>p(f(B)));qI(he,{get command(){return f(Re)},get dragDisabled(){return f(l)},startDrag:T,get onDeleteCommand(){return t.deleteCommand},onConfigureScript:ne,onMoveUp:()=>P(f(B).id,-1),onMoveDown:()=>P(f(B).id,1)})}},ce=he=>{{let Re=k(()=>m(f(B)));ZI(he,{get command(){return f(Re)},get dragDisabled(){return f(l)},startDrag:T,get onDeleteCommand(){return t.deleteCommand},onConfigureAssistant:H,onMoveUp:()=>P(f(B).id,-1),onMoveDown:()=>P(f(B).id,1)})}},$e=he=>{{let Re=k(()=>h(f(B)));PP(he,{get command(){return f(Re)},get dragDisabled(){return f(l)},startDrag:T,get onDeleteCommand(){return t.deleteCommand},onConfigureOpenFile:O,onMoveUp:()=>P(f(B).id,-1),onMoveDown:()=>P(f(B).id,1)})}},Xe=he=>{{let Re=k(()=>g(f(B)));$P(he,{get command(){return f(Re)},get dragDisabled(){return f(l)},startDrag:T,get onDeleteCommand(){return t.deleteCommand},onConfigureCondition:I,onEditThenBranch:D,onEditElseBranch:N,onMoveUp:()=>P(f(B).id,-1),onMoveDown:()=>P(f(B).id,1)})}},Ye=he=>{VI(he,{get command(){return f(B)},get dragDisabled(){return f(l)},startDrag:T,get onDeleteCommand(){return t.deleteCommand},onMoveUp:()=>P(f(B).id,-1),onMoveDown:()=>P(f(B).id,1)})};z(te,he=>{f(B).type==="Wait"?he(W):f(B).type==="NestedChoice"?he(Z,1):f(B).type==="UserScript"?he(se,2):f(B).type==="AIAssistant"?he(ce,3):f(B).type==="OpenFile"?he($e,4):f(B).type==="Conditional"?he(Xe,5):he(Ye,-1)})}A(M,J)}),$(G),xn(G,M=>q(c,M),()=>f(c)),Ft(G,(M,B)=>vm?.(M,B),()=>Cm({items:f(i),dragDisabled:f(l),type:o,resolveLabel:Ec})),Q(()=>V=Ge(G,1,"quickAddCommandList svelte-15ra1ch",null,V,{"is-empty":f(i).length===0&&!f(y)})),Kn("consider",G,C),Kn("finalize",G,w),A(r,G),oe()}Ki();MP();RP();OP();DP();LP();NP();VP();BP();UP();qP();var zP=new Map(Object.entries({Copy:Um,Cut:qm,Paste:zm,"Paste with format":Hm,"Select active line":Wm,"Select link on active line":Gm,"Move cursor to file start":jm,"Move cursor to file end":Ym,"Move cursor to line start":Km,"Move cursor to line end":Qm}));function TU(r){return Ze(r)}ll();er();Qo();var Yv=class extends hn{constructor(e,n){super(e,"Obsidian");this.generateId=()=>this.id=Vt();this.commandId=n}};ll();er();var Hx=class extends hn{constructor(t,e){super(t,"Choice"),this.choiceId=e}};ll();er();var Wx=class extends hn{constructor(t){super("Wait","Wait"),this.time=t}};er();ll();var Gx=class extends hn{constructor(t){super(t.name,"NestedChoice"),this.choice=t}};Qo();var Ys=class{constructor(t,e){this.id=Vt(),this.name=t,this.type=e,this.command=!1,this.onePageInput=void 0}};Le();function jx(r){if(!r||typeof r!="object"||!("property"in r)||!r.property||typeof r.property!="object"||!("kind"in r.property)||!("action"in r)||r.action!=="set"&&r.action!=="addToList"||!("createIfMissing"in r)||typeof r.createIfMissing!="boolean")throw new Error("Invalid property capture settings. Choose a property and action in the Capture settings.");let t=r.property;if(t.kind==="prompt")return{property:{kind:"prompt"},action:r.action,createIfMissing:r.createIfMissing};if(t.kind==="named"&&"format"in t&&typeof t.format=="string")return{property:{kind:"named",format:t.format},action:r.action,createIfMissing:r.createIfMissing};throw new Error("Invalid property capture selector.")}var Sc=class extends Ys{constructor(t){super(t,"Capture"),this.appendLink=!1,this.copyLinkToClipboard=!1,this.captureTo="",this.captureToActiveFile=!1,this.captureToCanvasNodeId="",this.activeFileWritePosition="cursor",this.createFileIfItDoesntExist={enabled:!1,createWithTemplate:!1,template:""},this.format={enabled:!1,format:""},this.insertAfter={enabled:!1,after:"",insertAtEnd:!0,considerSubsections:!1,createIfNotFound:!0,createIfNotFoundLocation:"top",inline:!1,replaceExisting:!1,blankLineAfterMatchMode:"auto",promptHeading:!1},this.insertBefore={enabled:!1,before:"",createIfNotFound:!1,createIfNotFoundLocation:"top"},this.newLineCapture={enabled:!1,direction:"below"},this.prepend=!1,this.task=!1,this.openFile=!1,this.fileOpening=rn(),this.templater={afterCapture:"none"}}static Load(t){let e=t;return e.propertyCapture!==void 0&&(e.propertyCapture=jx(e.propertyCapture)),e.activeFileWritePosition!=="cursor"&&e.activeFileWritePosition!=="top"&&e.activeFileWritePosition!=="bottom"&&(e.activeFileWritePosition="cursor"),typeof e.captureToCanvasNodeId!="string"&&(e.captureToCanvasNodeId=""),e.insertBefore||(e.insertBefore={enabled:!1,before:"",createIfNotFound:!1,createIfNotFoundLocation:"top"}),e.captureToActiveFile&&e.prepend&&!e.insertAfter?.enabled&&!e.insertBefore.enabled&&!e.newLineCapture?.enabled&&(e.activeFileWritePosition!=="top"&&(e.activeFileWritePosition="bottom"),e.prepend=!1),e.templater||(e.templater={afterCapture:"none"}),e.templater.afterCapture!=="wholeFile"&&(e.templater.afterCapture="none"),e.insertAfter&&!e.insertAfter.blankLineAfterMatchMode&&(e.insertAfter.blankLineAfterMatchMode="auto"),e.insertAfter&&e.insertAfter.inline===void 0&&(e.insertAfter.inline=!1),e.insertAfter&&e.insertAfter.replaceExisting===void 0&&(e.insertAfter.replaceExisting=!1),e.insertAfter&&e.insertAfter.promptHeading===void 0&&(e.insertAfter.promptHeading=!1),e.insertAfter?.createIfNotFoundLocation===Yo&&(e.insertAfter.createIfNotFound&&!e.insertAfter.orderBy&&(e.insertAfter.orderBy={by:"insertion",direction:"desc",unparseable:"bottom"}),e.insertAfter.inline=!1),e}};var Ks=class extends Ys{constructor(t){super(t,"Template"),this.templatePath="",this.fileNameFormat={enabled:!1,format:""},this.discoverExistingNotesBeforeCreate=!1,this.folder={enabled:!1,folders:[],chooseWhenCreatingNote:!1,createInSameFolderAsActiveFile:!1,chooseFromSubfolders:!1},this.appendLink=!1,this.copyLinkToClipboard=!1,this.openFile=!1,this.fileOpening=rn(),this.fileExistsBehavior={kind:"prompt"}}static Load(t){return t}};var _U=require("obsidian");Le();_m();function Yx(r){let t=[];for(let e of r.vault.getFiles())Fh.test(e.path)?t.push({file:e,isMarkdown:!1}):xt.test(e.path)&&w7(r,e)&&t.push({file:e,isMarkdown:!0});return t}function w7(r,t){return r.metadataCache.getFileCache(t)?.sections?.some(n=>n.type==="code")??!1}function kU(r,t,e){let n=t.find(s=>s.file.path===e);if(n)return n;let i=t.find(s=>!s.isMarkdown&&s.file.basename===e);if(i)return i;let o=r.vault.getAbstractFileByPath(e);if(o instanceof _U.TFile){if(Fh.test(o.path))return{file:o,isMarkdown:!1};if(xt.test(o.path))return{file:o,isMarkdown:!0}}return null}async function Kv(r,t){let e=await r.vault.read(t),{code:n,error:i}=Ws(e);return n!==null&&n.length>0?null:i??"No ```js code block found in the note."}function HP(r){let t=new Set(r.map(({file:n})=>n.path)),e=new Map;for(let{file:n,isMarkdown:i}of r)i||e.set(n.basename,(e.get(n.basename)??0)+1);return r.map(({file:n,isMarkdown:i})=>i||e.get(n.basename)>1||t.has(n.basename)?n.path:n.basename)}ll();er();var Qv=class extends hn{constructor(t,e){super(t,"UserScript"),this.path=e,this.settings={}}};tl();var SU=require("obsidian");function Kx(r){let e=new SU.Notice("",1e4).messageEl;e.replaceChildren(),e.createDiv({text:"No scripts found",cls:"quickadd-notice-title"});let n=e.createDiv();n.createDiv({text:"QuickAdd cannot find any .js files or notes with a ```js code block in your vault."}),n.createEl("br"),n.createDiv({text:"Please make sure your scripts are:"}),n.createDiv({text:`\u2713 In your vault (not in ${r.vault.configDir} folder)`}),n.createDiv({text:"\u2713 Not in hidden folders (starting with a dot)"}),n.createDiv({text:"\u2713 A .js file, or a note containing a ```js code block"}),n.createEl("br"),iC(n,is.userScripts,"View documentation")}cl();var Xv=require("obsidian");Ln();an();function Jm(r,t,e,n){let i=t.lastIndexOf("/"),o=i>=0?t.slice(0,i):"",s=aw(i>=0?t.slice(i+1):t),a=e?.vault.getAbstractFileByPath(t),l=e&&a instanceof Xv.TFile?Ds([a],h=>e.metadataCache.getFileCache(h))[0]:null,c=l?.primary??s,d=l?.secondary??o;r.addClass("mod-complex");let u=r.createDiv({cls:"suggestion-content"}),p=u.createDiv({cls:"suggestion-title"});if(n?(0,Xv.renderMatches)(p,c,n.matches):p.setText(c),!d)return;let m=u.createDiv({cls:"suggestion-note"});n&&d===t?(0,Xv.renderMatches)(m,d,n.matches,-n.pathOffset):m.setText(d)}Ln();ye();nt();ll();er();je();gi();var Qx=class extends hn{constructor(){super("AI Assistant","AIAssistant");let t=U.getState().ai;this.model=t.defaultModel;let e=Nl(t.defaultModel,t.defaultModelRef);this.modelRef=e?{...e}:void 0,this.systemPrompt=t.defaultSystemPrompt,this.outputVariableName="output",this.promptTemplate={enable:!1,name:""},this.modelParameters={}}};je();er();Qo();qx();var Xx=class{constructor(t="{{DATE}}.md",e=!1,n,i,o=!0){this.filePath=t;this.type="OpenFile";this.id=Vt();this.openInNewTab=e,this.direction=n,this.location=i,this.focus=o,this.name=`Open file: ${this.filePath}`,this.applyLegacyFromLocation()}applyLegacyFromLocation(){if(this.location)switch(this.location){case"split":this.openInNewTab=!0,this.direction||(this.direction="vertical");break;case"tab":case"reuse":this.openInNewTab=!1,this.direction=void 0;break;default:this.openInNewTab=!0,this.direction=void 0;break}}};au();ll();er();function C7(){return{mode:"variable",variableName:"",operator:"isTruthy",valueType:"string"}}function x7(r){return r.mode==="variable"?{...r}:{...r}}var Jx=class extends hn{constructor(t){super(t?.name??"If condition","Conditional"),this.condition=t?.condition?x7(t.condition):C7(),this.thenCommands=t?.thenCommands?[...t.thenCommands]:[],this.elseCommands=t?.elseCommands?[...t.elseCommands]:[]}};nl();Gr();var E7=F(`<div class="qaDataUnreadable svelte-sorpfp"><div class="qaDataUnreadableHead svelte-sorpfp"><!> <span class="qaDataUnreadableTitle svelte-sorpfp"> </span></div> <p class="qaDataUnreadableBody svelte-sorpfp">The saved value isn't in a shape QuickAdd understands, so it can't be shown
|
||
or edited here. Nothing has been changed or deleted, and QuickAdd will not
|
||
overwrite it.</p> <p class="qaDataUnreadableBody svelte-sorpfp">It's stored in <code>.obsidian/plugins/quickadd/data.json</code> inside this
|
||
vault. Make a copy of that file before editing it.</p></div>`),T7={hash:"svelte-sorpfp",code:".qaDataUnreadable.svelte-sorpfp {border:1px solid var(--background-modifier-border);border-radius:var(--radius-m);padding:12px 14px;margin:4px 0 8px;background:var(--background-secondary);}.qaDataUnreadableHead.svelte-sorpfp {display:flex;align-items:center;gap:8px;color:var(--text-warning, var(--text-normal));}.qaDataUnreadableTitle.svelte-sorpfp {font-weight:var(--font-semibold);color:var(--text-normal);}.qaDataUnreadableBody.svelte-sorpfp {margin:8px 0 0;color:var(--text-muted);font-size:var(--font-ui-small, 13px);max-width:68ch;}"};function GP(r,t){Ae(r,T7);var e=E7(),n=R(e),i=R(n);Qe(i,{iconId:"alert-triangle",size:16});var o=E(i,2),s=re(o);$(n),Xt(4),$(e),Q(()=>ee(s,`QuickAdd couldn't read ${t.what??""}`)),A(r,e)}var Zm=class{constructor(t){this.obsidianCommands=[];this.scriptCandidates=[];this.commandListHandle=null;this.commandListProps=null;this.containerEl=null;this.unreadableCardHandle=null;this.app=t.app,this.plugin=t.plugin,this.unreadable=Wt(t.commands),this.commandsRef=HI(t.commands).commands,this.choices=t.choices,this.onCommandsChange=t.onCommandsChange,this.conditionalHandlers=t.conditionalHandlers,this.loadObsidianCommands(),this.loadScriptCandidates()}render(t){return this.destroy(),this.containerEl=t,t.empty(),t.addClass("quickAddCommandEditor"),this.unreadable?(this.renderUnreadableCard(t),!1):this.renderCommandList(t)?(this.renderCommandBar(t),this.renderAddObsidianCommandSetting(t),this.renderAddEditorCommandSetting(t),this.renderAddUserScriptSetting(t),this.renderAddChoiceSetting(t),!0):!1}renderUnreadableCard(t){let e=t.createDiv("commandList");this.unreadableCardHandle=wi(e,GP,{what:"this macro's commands"},{what:"this macro's commands"})}destroy(){this.commandListHandle?.destroy(),this.commandListHandle=null,this.commandListProps=null,this.unreadableCardHandle?.destroy(),this.unreadableCardHandle=null}loadObsidianCommands(){Object.keys(this.app.commands.commands).forEach(t=>{let e=this.app.commands.commands[t];this.obsidianCommands.push(new Yv(e.name,e.id))})}loadScriptCandidates(){this.scriptCandidates=Yx(this.app)}renderCommandList(t){let e=t.createDiv("commandList");return this.commandListProps=TU({app:this.app,plugin:this.plugin,commands:this.commandsRef,deleteCommand:async n=>{let i=this.commandsRef.find(a=>a.id===n);if(!i)throw S.logError("command not found"),new Error("command not found");if(!await Ei(this.app,{title:`Delete '${i.name}'?`,message:"The command will be removed from this macro.",action:"Delete"}))return;if(!await sx(this.app,i)){new _i.Notice("Could not clear user script secrets. Command was not deleted.");return}this.commandsRef=this.commandsRef.filter(a=>a.id!==n),this.emitCommandsChanged()},saveCommands:n=>{this.commandsRef=n,this.onCommandsChange?.(n)},onConfigureCondition:this.conditionalHandlers?.configureCondition,onEditThenBranch:this.conditionalHandlers?.editThenBranch,onEditElseBranch:this.conditionalHandlers?.editElseBranch}),this.commandListHandle=wi(e,FP,this.commandListProps,{what:"this macro's commands"}),this.commandListHandle.ok}renderCommandBar(t){let e=t.createDiv("quickCommandContainer");this.addChoiceButton(e,"Capture",Sc),this.addChoiceButton(e,"Template",Ks),this.addCommandButton(e,"file-search","Add open file command",()=>new Xx),this.addCommandButton(e,"clock","Add wait command",()=>new Wx(100)),this.addCommandButton(e,"git-branch","Add conditional command",()=>new Jx),U.getState().disableOnlineFeatures||this.addCommandButton(e,"bot","Add AI Assistant command",()=>new Qx)}renderAddObsidianCommandSetting(t){let e,n=()=>{let i=e.getValue();if(!i.trim())return;let o=this.obsidianCommands.find(a=>a.name===i);if(!o){S.logError(`Could not find Obsidian command with name "${i}"`);return}let s=new Yv(o.name,o.commandId);s.generateId(),this.addCommand(s),e.setValue("")};new _i.Setting(t).setName("Obsidian command").setDesc("Add an Obsidian command").addText(i=>{e=this.configureSuggestedInput(i,"Obsidian command",this.obsidianCommands.map(o=>o.name),n)}).addButton(i=>i.setCta().setButtonText("Add").onClick(n))}renderAddEditorCommandSetting(t){let e,n=()=>{if(!e.getValue())return;let i=zP.get(e.getValue());if(!i)throw S.logError("invalid editor command type"),new Error("invalid editor command type");this.addCommand(new i),e.setValue("")};new _i.Setting(t).setName("Editor commands").setDesc("Add editor command").addDropdown(i=>{e=i,i.selectEl.addClass("qa-command-sequence-input"),i.addOption("","Select command");for(let o of zP.keys())i.addOption(o,o)}).addButton(i=>i.setCta().setButtonText("Add").onClick(n))}renderAddUserScriptSetting(t){let e,n=null,i=async()=>{this.loadScriptCandidates();let o=e.getValue().trim();if(!o)return;let s=Fm(o).basename??o,a=kU(this.app,this.scriptCandidates,s);if(!a){new _i.Notice(`QuickAdd: No script or js-block note named "${o}" found.`);return}if(a.isMarkdown){let l=await Kv(this.app,a.file);if(l){new _i.Notice(`QuickAdd: "${a.file.path}" \u2014 ${l}`);return}}this.addCommand(new Qv(o,a.file.path)),e.setValue(""),n&&n.buttonEl.addClass("qa-hidden")};new _i.Setting(t).setName("User scripts").setDesc("Add a .js file or a note with a ```js code block - type the name or click Browse").addText(o=>{e=this.configureSuggestedInput(o,"Start typing script name...",HP(this.scriptCandidates),i)}).addButton(o=>o.setButtonText("Browse").setTooltip("Browse and select a script (.js file or note)").onClick($s("Couldn't add that script",async()=>{let s=await this.showScriptPicker();s&&this.addCommand(s)}))).addButton(o=>{n=o,o.setButtonText("Add").setCta().onClick(()=>{i()}),o.buttonEl.addClass("qa-hidden")}),e.onChange(o=>{n&&n.buttonEl.toggleClass("qa-hidden",o.trim().length===0)})}renderAddChoiceSetting(t){let e,n=()=>{let i=e.getValue();if(!i.trim())return;let o=this.choices.find(s=>s.name===i);if(!o){new _i.Notice(`QuickAdd: No choice named "${i}".`);return}this.addCommand(new Hx(o.name,o.id)),e.setValue("")};new _i.Setting(t).setName("Choices").setDesc("Add existing choice").addText(i=>{e=this.configureSuggestedInput(i,"Choice",this.choices.map(o=>o.name),n)}).addButton(i=>i.setCta().setButtonText("Add").onClick(n))}configureSuggestedInput(t,e,n,i){return t.inputEl.addClass("qa-command-sequence-input"),t.setPlaceholder(e),new vi(this.app,t.inputEl,n),t.inputEl.addEventListener("keypress",o=>{o.key==="Enter"&&i()}),t}addChoiceButton(t,e,n){new _i.ButtonComponent(t).setButtonText(e).setTooltip(`Add ${e} choice`).onClick(()=>{let o=new n(`Untitled ${e} Choice`);this.addCommand(new Gx(o))})}addCommandButton(t,e,n,i){new _i.ButtonComponent(t).setIcon(e).setTooltip(n).onClick(()=>this.addCommand(i()))}async showScriptPicker(){if(this.loadScriptCandidates(),this.scriptCandidates.length===0)return Kx(this.app),null;let t=this.scriptCandidates.map(a=>a.file.path),e=HP(this.scriptCandidates),n=Ds(this.scriptCandidates.map(a=>a.file),a=>this.app.metadataCache.getFileCache(a)),i=await vr.Suggest(this.app,e,t,{placeholder:"Select a script (.js file or note with a ```js block)",renderItem:(a,l,c)=>Jm(l,a,this.app,{matches:c,pathOffset:n[t.indexOf(a)].primary.length+1}),searchItems:t.map((a,l)=>`${n[l].primary} ${a}`),allowCustomValue:!1}),o=t.indexOf(i);if(o===-1)return null;let s=this.scriptCandidates[o];if(s.isMarkdown){let a=await Kv(this.app,s.file);if(a)return new _i.Notice(`QuickAdd: "${s.file.path}" \u2014 ${a}`),null}return new Qv(e[o],s.file.path)}addCommand(t){this.commandsRef=[...this.commandsRef,t],this.emitCommandsChanged()}emitCommandsChanged(){this.commandListProps&&(this.commandListProps.commands=[...this.commandsRef]),this.onCommandsChange?.(this.commandsRef)}};var gn=require("obsidian");Xl();cl();nt();function IU(r){return r.mode==="variable"?{...r}:{...r}}function _7(){return{mode:"variable",variableName:"",operator:"isTruthy",valueType:"boolean"}}function k7(){return{mode:"script",scriptPath:""}}var Zx=class extends gn.Modal{constructor(e,n){super(e);this.isResolved=!1;this.scriptCandidates=[];this.originalCommand=n,this.workingCommand={...n,condition:IU(n.condition)},this.waitForClose=new Promise(i=>{this.resolvePromise=i}),this.loadScriptCandidates(),this.display(),this.open()}onClose(){super.onClose(),this.isResolved||this.resolve(null)}resolve(e){this.isResolved||(this.isResolved=!0,this.resolvePromise(e))}loadScriptCandidates(){this.scriptCandidates=Yx(this.app)}reload(){this.display()}display(){this.containerEl.addClass("quickAddModal","conditionalSettingsModal"),this.contentEl.empty(),this.contentEl.createEl("h2",{text:"Configure conditional command"}).addClass("qa-modal-title"),this.renderModeSelector(),this.workingCommand.condition.mode==="variable"?this.renderVariableConfiguration(this.workingCommand.condition):this.renderScriptConfiguration(this.workingCommand.condition),this.renderButtonBar()}renderModeSelector(){new gn.Setting(this.contentEl).setName("Condition type").setDesc("Choose how this condition should be evaluated.").addDropdown(e=>{e.addOption("variable","Macro variable").addOption("script","Run script").setValue(this.workingCommand.condition.mode).onChange(n=>{n!==this.workingCommand.condition.mode&&(this.workingCommand.condition=n==="variable"?_7():k7(),this.reload())})})}renderVariableConfiguration(e){this.renderVariableNameSetting(e),this.renderOperatorSetting(e),this.renderValueTypeSetting(e),Kl(e.operator)&&this.renderExpectedValueSetting(e)}renderVariableNameSetting(e){new gn.Setting(this.contentEl).setName("Variable name").setDesc("Name of the macro variable to inspect (without the $ prefix).").addText(n=>n.setPlaceholder("e.g. projectStatus").setValue(e.variableName).onChange(i=>{e.variableName=i.trim()}))}renderOperatorSetting(e){let n=[{value:"equals",label:"Equals"},{value:"notEquals",label:"Does not equal"},{value:"lessThan",label:"Less than"},{value:"lessThanOrEqual",label:"Less than or equal"},{value:"greaterThan",label:"Greater than"},{value:"greaterThanOrEqual",label:"Greater than or equal"},{value:"contains",label:"Contains"},{value:"notContains",label:"Does not contain"},{value:"isTruthy",label:"Is truthy"},{value:"isFalsy",label:"Is falsy"}];new gn.Setting(this.contentEl).setName("Operator").setDesc("How to compare the variable value.").addDropdown(i=>{i.addOptions(n.reduce((o,s)=>(o[s.value]=s.label,o),{})),i.setValue(e.operator),i.onChange(o=>{e.operator=o,e.valueType=M0(e.operator),Kl(e.operator)||delete e.expectedValue,this.reload()})})}renderValueTypeSetting(e){new gn.Setting(this.contentEl).setName("Value type").setDesc("How to interpret the comparison value.").addDropdown(n=>{n.addOption("string","Text").addOption("number","Number").addOption("boolean","Boolean").setValue(e.valueType).onChange(i=>{e.valueType=i,this.reload()})})}renderExpectedValueSetting(e){if(e.valueType==="boolean"){new gn.Setting(this.contentEl).setName("Expected value").setDesc("Choose true or false.").addDropdown(n=>{n.addOption("true","True").addOption("false","False").setValue(e.expectedValue??"true").onChange(i=>{e.expectedValue=i})});return}new gn.Setting(this.contentEl).setName("Expected value").setDesc("Value to compare against.").addText(n=>{n.setPlaceholder("Enter comparison value").setValue(e.expectedValue??"").onChange(i=>{e.expectedValue=i})})}renderScriptConfiguration(e){this.renderScriptPathSetting(e),this.renderScriptExportSetting(e)}renderScriptPathSetting(e){let n;new gn.Setting(this.contentEl).setName("Script path").setDesc("Vault-relative path to a .js file or a note with a ```js code block.").addText(i=>{n=i,i.setPlaceholder("scripts/myCheck.js or Notes/myCheck.md").setValue(e.scriptPath).onChange(o=>{e.scriptPath=o.trim()})}).addButton(i=>i.setButtonText("Browse").setTooltip("Select a script (.js file or note)").onClick($s("Couldn't select that script",async()=>{if(this.loadScriptCandidates(),this.scriptCandidates.length===0){Kx(this.app);return}let o=this.scriptCandidates.map(l=>l.file.path),s=await vr.Suggest(this.app,o,o,{placeholder:"Select a script (.js file or note with a ```js block)",emptyStateText:"No scripts found in your vault"});if(!s)return;let a=this.scriptCandidates.find(l=>l.file.path===s);if(a?.isMarkdown){let l=await Kv(this.app,a.file);if(l){new gn.Notice(`QuickAdd: "${a.file.path}" \u2014 ${l}`);return}}e.scriptPath=s,n.setValue(s)})))}renderScriptExportSetting(e){new gn.Setting(this.contentEl).setName("Export name").setDesc("Optional export or member to call (use :: to access nested members).").addText(n=>n.setPlaceholder("default").setValue(e.exportName??"").onChange(i=>{e.exportName=i.trim()||void 0}))}renderButtonBar(){let e=this.contentEl.createDiv({cls:"qa-command-button-row"});new gn.ButtonComponent(e).setButtonText("Cancel").onClick(()=>{this.resolve(null),this.close()}),new gn.ButtonComponent(e).setCta().setButtonText("Save").onClick(()=>{this.validateCondition()&&(this.applyChanges(),this.resolve(this.originalCommand),this.close())})}validateCondition(){let e=this.workingCommand.condition;return e.mode==="variable"?e.variableName.trim()?!0:(new gn.Notice("QuickAdd: Enter a variable name before saving."),!1):e.scriptPath.trim()?!0:(new gn.Notice("QuickAdd: Enter a script path before saving."),!1)}applyChanges(){this.originalCommand.condition=IU(this.workingCommand.condition);let e=Ql(this.originalCommand.condition);this.originalCommand.name=`If ${e}`}};var PU=require("obsidian");tn();Gr();var eE=class extends Ao{constructor(e){super(e.app,e.title,e.onSave);this.commandEditor=null;this.edited=!1;this.plugin=e.plugin,this.choices=e.choices,this.conditionalHandlers=e.conditionalHandlers,this.workingCommands=ke(e.commands),this.containerEl.addClass("conditionalBranchPage")}render(e){this.commandEditor=new Zm({app:this.app,plugin:this.plugin,commands:this.workingCommands,choices:this.choices,onCommandsChange:i=>{this.workingCommands=i,this.edited=!0},conditionalHandlers:this.conditionalHandlers});let n=new PU.SettingGroup(e).setHeading("Commands").listEl;this.commandEditor.render(n.createDiv("branchCommandEditor"))}result(){return this.edited?Mt(this.workingCommands):null}destroy(){this.commandEditor?.destroy(),this.commandEditor=null}};Xl();var tE=require("obsidian");lt();Ko();function S7(r){let t=r.trim();return t||void 0}function A7(r){return(typeof r.icon=="string"?r.icon.trim():"")||fp(r.type)}function rE(r,t,e,n){let i=fp(e.type),o=new tE.Setting(t).setName("Icon").setDesc(`Lucide/Obsidian icon id. Leave empty to use ${i}.`);o.settingEl.addClass("qa-choice-icon-setting");let s=At(t,"span");s.classList.add("qa-choice-icon-setting-preview"),s.setAttribute("aria-hidden","true"),o.controlEl.appendChild(s);function a(){s.replaceChildren(),(0,tE.setIcon)(s,A7(e))}o.addText(l=>{l.setPlaceholder(i),l.setValue(typeof e.icon=="string"?e.icon:""),l.inputEl.addClass("qa-choice-icon-input"),l.inputEl.setAttribute("aria-label","Choice icon"),new vi(r,l.inputEl,TC,50),l.onChange(c=>{let d=S7(c);e.icon=d,n(d),a()})}),a()}lt();Gr();Qo();Xp();uc();function I7(r){let t=[],e=n=>{n.forEach(i=>{Ee(i)&&(i.type==="Multi"?e(Ne(i)):t.push(i))})};return e(mr(r)),t}var nE=class extends Ao{constructor(e,n,i,o,s){super(e,i.name,s);this.choices=[];this.commandEditor=null;this.pickDaySetting=null;this.choice=i,this.macro=i.macro,this.openedName=i.name,this.choices=I7(o).filter(a=>a.id!==i.id),this.plugin=n,this.containerEl.addClass("macroBuilder")}result(){let e=im(this.choice.name,this.openedName);return this.choice.name=e,rl(this.macro)&&(this.macro.name=e),this.choice}destroy(){this.commandEditor?.destroy(),this.commandEditor=null}render(e){this.addNameSetting(e,this.choice.name,this.openedName,i=>{this.choice.name=i,rl(this.macro)&&(this.macro.name=i),this.pickDaySetting?.setName(Zp(i.trim()||this.openedName))}),this.addCommandEditor(this.addGroup(e,"Commands"));let n=this.addGroup(e,"Behavior");this.addOnePageInputSetting(n),this.addDateOriginSetting(n),this.addRunOnStartupSetting(n),this.addCommandPaletteSettings(n),this.addIconSetting(n)}addGroup(e,n){return new us.SettingGroup(e).setHeading(n).listEl}addOnePageInputSetting(e){new us.Setting(e).setName("One-page input override").addDropdown(n=>{n.addOption("","Follow global setting").addOption("always","Always").addOption("never","Never").setValue(this.choice.onePageInput??"").onChange(i=>{this.choice.onePageInput=i==="always"||i==="never"?i:void 0})})}addDateOriginSetting(e){let n=this.choice.dateOrigin,i=Xa(n);if(new us.Setting(e).setName(oC).setDesc(sC).addDropdown(o=>{for(let s of uC)o.addOption(s.value,s.label);o.setValue(i),o.onChange(s=>{mC(s)&&(this.choice.dateOrigin=fC({preset:s,previous:this.choice.dateOrigin}),this.reload())})}),i==="ask"){let o=n?.kind==="ask"?n.defaultValue:void 0;new us.Setting(e).setName(aC).setDesc(lC).addDropdown(s=>{for(let a of hC(o))s.addOption(a.value,a.label);s.setValue(uv(o)),s.onChange(a=>{let l=gC(a,o);this.choice.dateOrigin=l?{kind:"ask",defaultValue:l}:{kind:"ask"}})})}if(i==="custom"&&n?.kind==="relative"&&new us.Setting(e).setName(cv).setDesc(cC).addText(o=>{o.setValue(String(n.offset)),o.setPlaceholder("-2"),o.onChange(s=>{let a=this.choice.dateOrigin;if(a?.kind!=="relative")return;let l=s.trim();/^[+-]?\d+$/.test(l)&&(this.choice.dateOrigin={...a,offset:Number(l)})})}).addDropdown(o=>{for(let s of av)o.addOption(s,s);o.setValue(n.unit),o.onChange(s=>{let a=this.choice.dateOrigin;a?.kind==="relative"&&lv(s)&&(this.choice.dateOrigin={...a,unit:s})})}),i==="variable"){let o=n?.kind==="variable"?n.name:"";new us.Setting(e).setName(dv).setDesc(dC).addText(s=>{s.setValue(o),s.setPlaceholder("day"),s.onChange(a=>{this.choice.dateOrigin={kind:"variable",name:a}})})}}addCommandPaletteSettings(e){new us.Setting(e).setName(mv).setDesc(vC).addToggle(n=>{n.setValue(this.choice.command).onChange(i=>{this.choice.command=i,this.reload()})}),this.pickDaySetting=null,this.choice.command&&fv(this.choice.dateOrigin)&&(this.pickDaySetting=new us.Setting(e).setName(Zp(this.choice.name)).setDesc(yC).addToggle(n=>{n.setValue(this.choice.pickDayCommand??!1).onChange(i=>{this.choice.pickDayCommand=i})}))}addRunOnStartupSetting(e){new us.Setting(e).setName("Run on startup").setDesc("Execute this macro when Obsidian starts").addToggle(n=>n.setValue(this.choice.runOnStartup).onChange(i=>{this.choice.runOnStartup=i}))}addIconSetting(e){rE(this.app,e,this.choice,n=>{this.choice.icon=n})}reload(){this.destroy(),this.containerEl.empty(),this.render(this.containerEl)}macroCommandsValue(){return ur(this.macro)}setMacroCommands(e){if(!rl(this.macro)){this.macro={id:Vt(),name:this.choice.name,commands:e},this.choice.macro=this.macro;return}this.macro.commands=e}addCommandEditor(e){let n=e.createDiv("macroBuilder__editor");this.commandEditor=new Zm({app:this.app,plugin:this.plugin,commands:this.macroCommandsValue(),choices:this.choices,onCommandsChange:i=>{this.setMacroCommands(i)},conditionalHandlers:this.buildConditionalHandlers()}),this.commandEditor.render(n)}buildConditionalHandlers(){return{configureCondition:e=>this.configureConditionalCondition(e),editThenBranch:(e,n)=>this.openBranchPage(e,"then",n),editElseBranch:(e,n)=>this.openBranchPage(e,"else",n)}}async configureConditionalCondition(e){return await new Zx(this.app,e).waitForClose!==null}openBranchPage(e,n,i){new eE({app:this.app,plugin:this.plugin,choices:this.choices,title:`${n==="then"?"Then":"Else"}: ${Ql(e.condition)}`,commands:n==="then"?e.thenCommands:e.elseCommands,conditionalHandlers:this.buildConditionalHandlers(),onSave:o=>{o&&(n==="then"?e.thenCommands=o:e.elseCommands=o,i())}}).open()}};var iE=class extends Ao{constructor(e,n,i){super(e,n.name,i);this.choice=n;this.name=n.name,this.placeholder=n.placeholder??"",this.icon=typeof n.icon=="string"?n.icon:void 0,this.containerEl.addClass("qaMultiChoiceBuilder")}render(e){let n=o=>{},i=this.addNameSetting(e,this.name,this.choice.name,o=>{this.name=o,n(o.trim()||this.choice.name)});i.addSetting(o=>{o.setName("Placeholder").setDesc("Shown in the choice picker search box when this folder opens. Leave blank to use the folder name.").addText(s=>{n=a=>{s.setPlaceholder(a)},s.setPlaceholder(this.name),s.setValue(this.placeholder).onChange(a=>{this.placeholder=a})})}),rE(this.app,i.listEl,{type:this.choice.type,icon:this.icon},o=>{this.icon=o})}result(){let e=this.placeholder.trim();return{...this.choice,name:im(this.name,this.choice.name),placeholder:e||void 0,icon:this.icon}}};je();Qo();var oE=class{constructor(t){this.name=t,this.id=Vt(),this.commands=[]}};var ef=class extends Ys{constructor(e){super(e,"Macro");this.runOnStartup=!1;this.macro=new oE(e)}};var tf=class extends Ys{constructor(e){super(e,"Multi");this.choices=[];this.collapsed=!1}addChoice(e){return this.choices.push(e),this}addChoices(e){return this.choices.push(...e),this}};Gr();lt();function cu(r){return r==="Multi"?"folder":"choice"}function $U(r){return r==="Multi"?"Folder":"Choice"}tn();function jP(r,t){let e=ke(r);for(let n of t)delete e[n];return e}tn();nl();ye();Yi();var P7={Template:Ks,Capture:Sc,Macro:ef,Multi:tf};function KP(r,t){let e=P7[r];if(!e)throw new Error(`Unknown choice type: ${r}`);return new e(t)}function MU(r,t){let e=KP(r.type,`${r.name} (copy)`);if(r.type==="Multi"){let n=e,i=r;return Object.assign(n,jP(i,["id","name","choices"])),$a(i)?n.choices=Ne(i).filter(Ee).map(o=>MU(o,t)):n.choices=i.choices,n}return Object.assign(e,jP(r,["id","name"])),r.type==="Macro"&&(e.macro=ke(r.macro),aB(e.macro),ax(e,t)),e}async function RU(r,t){let e=await $7(t,r);return MU(r,{secretOptionNamesByPath:e,stripUnknownStringSettings:!0})}function OU(r){return r!==null&&typeof r=="object"}function YP(r,t){if(OU(r)){if(r.type==="UserScript"&&typeof r.path=="string"&&t.add(r.path),Array.isArray(r.thenCommands))for(let e of r.thenCommands)YP(e,t);if(Array.isArray(r.elseCommands))for(let e of r.elseCommands)YP(e,t);QP(r.choice,t)}}function QP(r,t){if(OU(r)){if(r.type==="Macro"){let e=ur(r.macro);if(Array.isArray(e))for(let n of e)YP(n,t)}if(r.type==="Multi"&&Array.isArray(r.choices))for(let e of r.choices)QP(e,t)}}async function $7(r,t){let e=new Set;QP(t,e);let n=new Map;for(let i of e)try{if(Ut(i)||!await r.vault.adapter.exists(i))continue;let s=Dv(await r.vault.adapter.read(i),i);n.set(i,s.foundSecretOptions&&s.names.size===0?null:s.names)}catch(o){S.logWarning(`QuickAdd could not inspect user-script settings '${i}' while duplicating choice: ${o?.message??o}`)}return n}function F7(r,t,e,n){switch(r.type){case"Template":return new Tm(t,r,e,n);case"Capture":return new sm(t,r,e,n);case"Macro":return new nE(t,e,r,U.getState().choices,n);case"Multi":return new iE(t,r,n);default:throw new Error("Invalid choice type")}}async function DU(r,t){let e=r.type==="Multi",n=r.type==="Macro",i=l=>{if(vo(l))return"QuickAdd couldn't read this folder's contents. Deleting it also deletes whatever is still stored under it in data.json.";let c=Zt(Ne(l));if(c.length===0)return"";let d=c.filter(m=>m.type==="Multi").length,u=c.length-d,p=[];return u>0&&p.push(`${u} ${u===1?"choice":"choices"}`),d>0&&p.push(`${d} ${d===1?"folder":"folders"}`),`Deleting this folder will also delete everything inside it: ${p.join(" and ")}.`},o=l=>Wt(ur(l.macro))?"QuickAdd couldn't read this macro's commands. Deleting it also deletes whatever is still stored under it in data.json.":"Deleting this choice will also delete its macro commands.",s=[`Are you sure you want to delete '${r.name}'?`,e?i(r):"",n?o(r):""].filter(Boolean).join(" ");return await Ei(t,{title:`Delete ${cu(r.type)}`,message:s,action:"Delete"})?(n||e)&&!await sx(t,{type:"NestedChoice",choice:r})?(new FU.Notice(`Could not clear user script secrets. The ${cu(r.type)} was not deleted.`),!1):!0:!1}function LU(r,t,e,n){let i=F7(r,t,e,s=>{let a=Wi(s);n(a,o),o=a}),o=Wi(r);return i.open()}function NU(r){return{...r,command:!r.command}}var sE=class{constructor(t){this.plugin=t}enableCommand(t){this.plugin.addCommandForChoice(t)}disableCommand(t,e){e?this.plugin.removeCommandForChoice(t,e):this.plugin.removeCommandForChoice(t)}updateCommand(t,e){this.plugin.removeCommandForChoice(t),this.plugin.addCommandForChoice(e)}};function VU(r,t,e){if(!t||!e)return r;let n=du(r,t),i=du(r,e);if(!n||!i||i.type!=="Multi"||n.type==="Multi"&&(n.id===i.id||M7(n).has(i.id)))return r;let{updated:o,removed:s}=Jv(r,t);return s?XP(o,e,s)??r:r}function BU(r,t){if(!t||r.some(i=>Ee(i)&&i.id===t))return r;let{updated:e,removed:n}=Jv(r,t);return n?[...e,n]:r}function du(r,t){for(let e of r){if(!Ee(e))continue;if(e.id===t)return e;let n=du(Ne(e),t);if(n)return n}}function M7(r){let t=new Set,e=n=>{Ee(n)&&(t.add(n.id),Ne(n).forEach(e))};return Ne(r).forEach(e),t}function Jv(r,t){let e;return{updated:r.map(i=>{if(!Ee(i))return i;if(i.id===t){e=i;return}if(!$a(i))return i;let o=Jv(Ne(i),t);return o.removed&&(e=o.removed),o.removed?{...i,choices:o.updated}:i}).filter(Boolean),removed:e}}function XP(r,t,e){let n=!1,i=r.map(o=>{if(!Ee(o))return o;if(o.id===t&&o.type==="Multi"){if(vo(o))return o;n=!0;let a=o;return{...a,choices:[...Ne(a),e]}}if(!$a(o))return o;let s=XP(Ne(o),t,e);return s?(n=!0,{...o,choices:s}):o});return n?i:void 0}function JP(r,t,e){let n=r.findIndex(s=>Ee(s)&&s.id===t);if(n!==-1){let s=[...r];return s.splice(n+1,0,e),s}let i=!1,o=r.map(s=>{if(!Ee(s)||!$a(s))return s;let a=JP(Ne(s),t,e);return a?(i=!0,{...s,choices:a}):s});return i?o:void 0}function UU(r,t,e){if(!e)return[...r,t];let n=XP(r,e,t)??[...r,t];return R7(n,e)}function ZP(r,t,e){return r.map(n=>{if(!Ee(n)||n.type!=="Multi")return n;let i=n;return i.id===t?e(i):$a(i)?{...i,choices:ZP(Ne(i),t,e)}:n})}function e$(r,t,e){return ZP(r,t,n=>({...n,collapsed:e}))}function R7(r,t){return e$(r,t,!1)}function qU(r,t,e){return ZP(r,t,n=>({...n,choices:e}))}var lE=require("obsidian");lt();var zU=[{type:"Template",label:"Template",description:"Create a note from a template file.",iconId:"file-text"},{type:"Capture",label:"Capture",description:"Add text to a note \u2014 append, prepend, or insert.",iconId:"pencil"},{type:"Macro",label:"Macro",description:"Run a sequence of commands and scripts.",iconId:"terminal"}];function aE(r){switch(r){case"Template":return"New template";case"Capture":return"New capture";case"Macro":return"New macro";case"Multi":return"New folder"}}function HU(r,t){let e=aE(r),n=new Set(Zt(t).map(o=>o.name));if(!n.has(e))return e;let i=2;for(;n.has(`${e} ${i}`);)i++;return`${e} ${i}`}var O7=F('<div><button type="button" class="qaNewFolderBtn svelte-jvakpr"><!> <span> </span></button> <button type="button" aria-haspopup="menu"><!> <span> </span> <!></button></div>'),D7={hash:"svelte-jvakpr",code:`.qaAddChoiceControls.svelte-jvakpr {display:flex;flex-direction:row;align-items:center;gap:0.5rem;}.qaAddChoiceControls.svelte-jvakpr button:where(.svelte-jvakpr) {display:inline-flex;align-items:center;gap:0.35em;}
|
||
|
||
/* The chevron sits tighter to the label than the leading plus. */.qaNewChoiceBtn.svelte-jvakpr svg:last-child {margin-left:-0.1em;opacity:0.85;}
|
||
|
||
/* Per-folder ("compact") controls render as quiet, clickable text links \u2014 not
|
||
filled buttons \u2014 so they read as "add inside this folder" affordances and
|
||
don't compete with the global primary CTA, especially when repeated across
|
||
nested folders. */.qaAddChoiceControls.compact.svelte-jvakpr {gap:1rem;}.qaAddChoiceControls.compact.svelte-jvakpr button:where(.svelte-jvakpr) {font-size:var(--font-ui-smaller);padding:2px 0;gap:0.25em;background:transparent;border:none;box-shadow:none;color:var(--text-muted);}.qaAddChoiceControls.compact.svelte-jvakpr button:where(.svelte-jvakpr):hover {color:var(--text-accent);text-decoration:underline;}
|
||
|
||
/* Mobile/touch: stretch so the two buttons fill the bar width instead of
|
||
cramming to the right. Driven by \`fill\` (Platform.isMobile from the bottom
|
||
bar) because viewport media queries don't fire under desktop mobile-emulation. */.qaAddChoiceControls.fill.svelte-jvakpr {flex:1;}.qaAddChoiceControls.fill.svelte-jvakpr button:where(.svelte-jvakpr) {flex:1;justify-content:center;}
|
||
|
||
/* Narrow desktop windows stack the non-compact controls. Filled controls (the
|
||
mobile bottom bar) are excluded so this can't override \`.fill\`'s side-by-side
|
||
50/50 layout on a phone-width viewport (Platform.isMobile + width <= 800px). */
|
||
@media (max-width: 800px) {.qaAddChoiceControls.svelte-jvakpr:not(.compact):not(.fill) {flex-direction:column;align-items:stretch;}
|
||
}`};function rf(r,t){ie(t,!0),Ae(r,D7);let e=X(t,"targetFolderId",3,void 0),n=X(t,"targetFolderName",3,void 0),i=X(t,"compact",3,!1),o=X(t,"fill",3,!1),s=pe(!1);function a(N){let K=new lE.Menu;for(let H of zU)K.addItem(O=>O.setTitle(lE.Platform.isPhone?H.label:`${H.label} \u2014 ${H.description}`).setIcon(H.iconId).onClick(G=>{let V=G.altKey===!0;t.onAddChoice(aE(H.type),H.type,e(),V)}));q(s,!0),K.onHide(()=>{q(s,!1)});let ne=N.target?.closest("button");if(ne){let H=ne.getBoundingClientRect();K.showAtPosition({x:H.left,y:H.bottom+4,width:H.width,overlap:!0,left:!i()})}else K.showAtMouseEvent(N)}function l(){t.onAddChoice(aE("Multi"),"Multi",e(),!0)}let c=k(()=>i()?"Add choice":"New choice"),d=k(()=>i()?"Add folder":"New folder"),u=k(()=>n()?`Add choice to ${n()}`:f(c)),p=k(()=>n()?`Add folder to ${n()}`:f(d));var m=O7();let h;var g=R(m),v=R(g);Qe(v,{iconId:"folder-plus",size:14});var b=E(v,2),y=re(b,!0);$(g);var C=E(g,2);let w;var T=R(C);Qe(T,{iconId:"plus",size:14});var P=E(T,2),_=re(P,!0),I=E(P,2);{var D=N=>{Qe(N,{iconId:"chevron-down",size:12})};z(I,N=>{i()||N(D)})}$(C),$(m),Q(()=>{h=Ge(m,1,"qaAddChoiceControls svelte-jvakpr",null,h,{compact:i(),fill:o()&&!i()}),le(g,"aria-label",f(p)),le(g,"title",i()?f(p):void 0),ee(y,f(d)),w=Ge(C,1,"qaNewChoiceBtn svelte-jvakpr",null,w,{"mod-cta":!i()}),le(C,"aria-expanded",f(s)),le(C,"aria-label",f(u)),le(C,"title",i()?f(u):void 0),ee(_,f(c))}),ge("click",g,l),ge("click",C,a),A(r,m),oe()}He(["click"]);var L7=F('<div class="rightButtonsContainer svelte-1tlf1y8"><!> <!> <!> <!> <!> <!></div>'),N7={hash:"svelte-1tlf1y8",code:`.rightButtonsContainer.svelte-1tlf1y8 {display:flex;align-items:center;
|
||
/* Icons carry their own 3px padding inside the choice rows (24px hit
|
||
boxes), so a tight gap keeps the cluster compact without touching. */gap:2px;flex:0 0 auto;}`};function Zv(r,t){ie(t,!0),Ae(r,N7);let e=X(t,"showConfigureButton",3,!0),n=X(t,"showDuplicateButton",3,!0),i=X(t,"commandEnabled",3,!1),o=X(t,"choiceName",3,"");var s=L7(),a=R(s);{var l=v=>{{let b=k(()=>`Configure${o()?" "+o():""}`);Et(v,{iconId:"settings",get label(){return f(b)},extraClass:"qa-row-secondary-action",get onclick(){return t.onConfigureChoice}})}};z(a,v=>{e()&&v(l)})}var c=E(a,2);{var d=v=>{{let b=k(()=>`Duplicate${o()?" "+o():""}`);Et(v,{iconId:"copy",get label(){return f(b)},extraClass:"qa-row-secondary-action",get onclick(){return t.onDuplicateChoice}})}};z(c,v=>{n()&&v(d)})}var u=E(c,2);{let v=k(()=>`Delete${o()?" "+o():""}`);Et(u,{iconId:"trash-2",get label(){return f(v)},extraClass:"qa-row-secondary-action",get onclick(){return t.onDeleteChoice}})}var p=E(u,2);{var m=v=>{{let b=k(()=>`More options${o()?" for "+o():""}`);Et(v,{iconId:"more-vertical",ariaHasPopup:"menu",get label(){return f(b)},onclick:y=>t.onOpenMenu?.(y.currentTarget)})}};z(p,v=>{t.onOpenMenu&&v(m)})}var h=E(p,2);{let v=k(()=>`Command palette${o()?": "+o():""}`);Et(h,{iconId:"zap",get ariaPressed(){return i()},get label(){return f(v)},extraClass:"qa-row-secondary-action",get onclick(){return t.onToggleCommand}})}var g=E(h,2);{let v=k(()=>`Reorder${o()?" "+o():""}`);Hr(g,{get label(){return f(v)},get dragDisabled(){return t.dragDisabled},get onDragStart(){return t.onDragHandleDown},get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown}})}$(s),A(r,s),oe()}var pE=require("obsidian");var WU=require("obsidian");lt();var t$="quickadd:move-to-root";function V7(r,t){let e=mr(t);if(e.some(i=>Ee(i)&&i.id===r.id))return!1;let n=i=>{for(let o of i){if(!Ee(o))continue;let s=Ne(o);if(s.some(a=>a?.id===r.id)||n(s))return!0}return!1};return n(e)}function B7(r,t){let e=[],n=Array.isArray(t)?t:[],i=(o,s=[])=>{for(let a of o){if(!Ee(a))continue;let l=a.name??"";if(a.type==="Multi"){let c=[...s,l];U7(r,a)||e.push({id:a.id,path:c.join(" / ")}),i(Ne(a),[...s,l])}}};return i(n,[]),e}function U7(r,t){if(t.type!=="Multi"||r.id===t.id||vo(t))return!0;if(r.type==="Multi"){let e=new Set,n=i=>{Ee(i)&&(e.add(i.id),Ne(i).forEach(n))};if(Ne(r).forEach(n),e.has(t.id))return!0}return!1}function nf(r,t){return{onRename:()=>t.onRenameChoice(r),onToggle:()=>t.onToggleCommand(r),onConfigure:()=>t.onConfigureChoice(r),onDuplicate:()=>t.onDuplicateChoice(r),onDelete:()=>t.onDeleteChoice(r),onMove:e=>t.onMoveChoice(r,e)}}function GU(r,t,e,n){let i=new WU.Menu;i.addItem(s=>s.setTitle(t.command?"Disable in command palette":"Enable in command palette").setIcon("zap").onClick(n.onToggle)).addItem(s=>s.setTitle("Rename").setIcon("pencil").onClick(n.onRename)).addItem(s=>s.setTitle("Configure").setIcon("settings").onClick(n.onConfigure)).addItem(s=>s.setTitle("Duplicate").setIcon("copy").onClick(n.onDuplicate)).addItem(s=>s.setTitle("Delete").setIcon("trash-2").onClick(n.onDelete)).addSeparator(),V7(t,e)&&i.addItem(s=>s.setTitle("Move to: (root)").setIcon("folder-up").onClick(()=>n.onMove(t$)));let o=B7(t,e);return o.length===0?i.addItem(s=>s.setTitle("Move to: (no folders)").setDisabled(!0).setIcon("folder")):o.forEach(s=>i.addItem(a=>a.setTitle(`Move to: ${s.path}`).setIcon("folder-open").onClick(()=>n.onMove(s.id)))),i}function cE(r,t,e,n,i){t.preventDefault(),GU(r,e,n,i).showAtMouseEvent(t)}function dE(r,t,e,n,i){let o=t.getBoundingClientRect();GU(r,e,n,i).showAtPosition({x:o.left,y:o.bottom})}var jU=require("obsidian");function uE(r,t,e,n){t.replaceChildren(),jU.MarkdownRenderer.render(n,r,t,"/",e)}lt();var q7=F('<div class="choiceListItem"><span class="qaChoiceRowIcon" aria-hidden="true"><!></span> <span class="choiceListItemName"></span> <!></div>'),z7={hash:"svelte-1xw9zlu",code:""};function r$(r,t){ie(t,!0),Ae(r,z7);let e=!0,n=pe(void 0),i=new pE.Component;Dt(()=>{f(n)&&uE(t.choice.name,f(n),i,t.app)}),Dt(()=>()=>i.unload());function o(p){cE(t.app,p,t.choice,t.roots,nf(t.choice,t.actions))}function s(p){dE(t.app,p,t.choice,t.roots,nf(t.choice,t.actions))}var a=q7(),l=R(a),c=R(l);{let p=k(()=>Sd(t.choice));Qe(c,{get iconId(){return f(p)},size:15})}$(l);var d=E(l,2);xn(d,p=>q(n,p),()=>f(n));var u=E(d,2);Zv(u,{get onDragHandleDown(){return t.startDrag},onDeleteChoice:()=>t.actions.onDeleteChoice(t.choice),onConfigureChoice:()=>t.actions.onConfigureChoice(t.choice),onToggleCommand:()=>t.actions.onToggleCommand(t.choice),onDuplicateChoice:()=>t.actions.onDuplicateChoice(t.choice),onOpenMenu:s,get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown},get choiceName(){return t.choice.name},get commandEnabled(){return t.choice.command},showConfigureButton:e,get dragDisabled(){return t.dragDisabled},showDuplicateButton:!0}),$(a),Q(()=>le(a,"data-choice-id",t.choice.id)),ge("contextmenu",a,o),ge("dblclick",a,p=>{pE.Platform.isMobile||p.target.closest("button, a")||t.actions.onConfigureChoice(t.choice)}),A(r,a),oe()}He(["contextmenu","dblclick"]);var mE=require("obsidian");lt();var H7=F('<span class="qaFolderCount svelte-gckzoy" aria-hidden="true"> </span>'),W7=F(`<p class="qaUnreadableFolder svelte-gckzoy">QuickAdd couldn't read this folder's contents. They're still
|
||
in <code class="svelte-gckzoy">data.json</code>.</p>`),G7=F('<div class="nestedAddRow svelte-gckzoy"><!></div>'),j7=F("<!> <!>",1),Y7=F('<div class="nestedChoiceList svelte-gckzoy"><!></div>'),K7=F('<div><div class="multiChoiceListItem"><button type="button" class="multiChoiceListItemName svelte-gckzoy"><span aria-hidden="true"><!></span> <span class="choiceListItemName"></span> <!></button> <!></div> <!></div>'),Q7={hash:"svelte-gckzoy",code:`
|
||
/* Row surface (min-height, padding, radius, hover, rhythm) is shared with
|
||
leaf rows and lives in styles.css \u2014 see "Choice list rows". Only the
|
||
folder-specific pieces stay here. */
|
||
|
||
/* Base icon = chevron-down (expanded); collapsed rotates to point RIGHT,
|
||
matching Obsidian's own collapse grammar (file explorer, outline). */.multiChoiceCollapseIcon.svelte-gckzoy {transition:transform 150ms ease;}.multiChoiceCollapseIcon.is-collapsed.svelte-gckzoy {transform:rotate(-90deg);}
|
||
|
||
@media (prefers-reduced-motion: reduce) {.multiChoiceCollapseIcon.svelte-gckzoy {transition:none;}
|
||
}
|
||
|
||
/* Full-width collapse toggle: reset native <button> chrome while keeping
|
||
native keyboard activation + aria-expanded. It hosts the shared icon
|
||
column (the chevron), so the folder NAME lands on the exact leaf-name x
|
||
for free \u2014 same 8px column gap as the leaf rows. */.multiChoiceListItemName.svelte-gckzoy {flex:1 1 auto;min-width:0;align-self:stretch;display:flex;align-items:center;
|
||
/* Obsidian's base button centers flex content; the name must not rely
|
||
on a growing child to stay left (it stopped growing for the count). */justify-content:flex-start;gap:8px;background:transparent;border:none;box-shadow:none;padding:0;
|
||
/* Obsidian's base button rule sets height: var(--input-height) (30px),
|
||
which would make folder rows 4px taller than leaf rows \u2014 the exact
|
||
rhythm break this redesign removes. */height:auto;min-height:0;font:inherit;color:inherit;text-align:left;cursor:pointer;
|
||
/* Suppress double-tap-zoom + its click delay on touch \u2014 proper touch hygiene
|
||
for a tap target, and reduces the ghost-click the dedupe above also guards. */touch-action:manipulation;}
|
||
|
||
/* The count reads as part of the label ("Misc \xB7 12"), so the name must not
|
||
grow \u2014 it keeps its ellipsis via flex-shrink + the shared min-width: 0. */.multiChoiceListItemName.svelte-gckzoy .choiceListItemName {flex:0 1 auto;}
|
||
|
||
/* Same slot, weight and colour as the empty-folder hint in ChoiceList, so a
|
||
folder we cannot read reads as a variation of "empty" rather than an alarm. */.qaUnreadableFolder.svelte-gckzoy {margin:0;padding:6px 8px 8px;color:var(--text-faint);font-size:var(--font-ui-smaller, 12px);line-height:1.4;}.qaUnreadableFolder.svelte-gckzoy code:where(.svelte-gckzoy) {font-size:inherit;}.qaFolderCount.svelte-gckzoy {flex:0 0 auto;color:var(--text-faint);font-size:var(--font-ui-smaller, 12px);font-variant-numeric:tabular-nums;line-height:1;}.multiChoiceListItemName.svelte-gckzoy:focus-visible {outline:2px solid var(--interactive-accent);outline-offset:1px;border-radius:var(--radius-s, 4px);}
|
||
|
||
/* Just the indent \u2014 the drop-into-folder ring is drawn on the ACTUAL dndzone
|
||
(.choiceList, in ChoiceList.svelte) so the highlighted area equals the
|
||
droppable area (WYSIWYG); it is NOT drawn on this wrapper, which extends past
|
||
the zone to the add-row/hint. The ::before is an indent GUIDE under the
|
||
parent's icon column (x = row padding 8px + half the 18px column, minus
|
||
half the line), clarifying what belongs to the open folder. */.nestedChoiceList.svelte-gckzoy {position:relative;padding-left:26px;}.nestedChoiceList.svelte-gckzoy::before {content:"";position:absolute;left:16px;top:3px;bottom:3px;width:1px;background:var(--background-modifier-border);pointer-events:none;}
|
||
|
||
/* The per-folder add-row reads as a ghost row of the folder: aligned to the
|
||
child rows' padding, one tight step (4px) below the last child. */.nestedAddRow.svelte-gckzoy {margin:2px 0 4px 0;padding:0 8px;}`};function n$(r,t){ie(t,!0),Ae(r,Q7);let e=X(t,"choice",7),n=X(t,"forceDragDisabled",3,!1),i=k(()=>Ne(e())),o=k(()=>vo(e())),s=!0,a=pe(void 0),l=new mE.Component;Dt(()=>{f(a)&&uE(e().name,f(a),l,t.app)}),Dt(()=>()=>l.unload());function c(D){cE(t.app,D,e(),t.roots,nf(e(),t.actions))}function d(D){dE(t.app,D,e(),t.roots,nf(e(),t.actions))}let u={...pt(()=>t.actions),onReorderChoices:D=>{e().choices=D,t.actions.onCommitFolder(e().id,D)}};function p(){n()||t.actions.onToggleCollapsed(e())}var m=K7(),h=R(m),g=R(h),v=R(g);let b;var y=R(v);Qe(y,{iconId:"chevron-down",size:16}),$(v);var C=E(v,2);xn(C,D=>q(a,D),()=>f(a));var w=E(C,2);{var T=D=>{var N=H7(),K=re(N,!0);Q(()=>ee(K,f(i).length)),A(D,N)};z(w,D=>{e().collapsed&&f(i).length>0&&D(T)})}$(g),Ft(g,D=>jC?.(D));var P=E(g,2);Zv(P,{get onDragHandleDown(){return t.startDrag},onDeleteChoice:()=>t.actions.onDeleteChoice(e()),onConfigureChoice:()=>t.actions.onConfigureChoice(e()),onToggleCommand:()=>t.actions.onToggleCommand(e()),onDuplicateChoice:()=>t.actions.onDuplicateChoice(e()),onOpenMenu:d,get onMoveUp(){return t.onMoveUp},get onMoveDown(){return t.onMoveDown},showConfigureButton:s,get dragDisabled(){return t.dragDisabled},get choiceName(){return e().name},get commandEnabled(){return e().command},showDuplicateButton:!0}),$(h);var _=E(h,2);{var I=D=>{var N=bt(),K=ae(N);{var ne=H=>{var O=Y7(),G=R(O);{var V=B=>{var J=W7();A(B,J)},M=B=>{var J=j7(),te=ae(J);{let se=k(()=>f(i).length===0),ce=k(()=>t.rootReorder??t.actions.onReorderChoices);of(te,{get app(){return t.app},get roots(){return t.roots},get choices(){return f(i)},nested:!0,get isEmptyFolder(){return f(se)},get forceDragDisabled(){return n()},get rootReorder(){return f(ce)},get actions(){return u}})}var W=E(te,2);{var Z=se=>{var ce=G7(),$e=R(ce);rf($e,{compact:!0,get targetFolderId(){return e().id},get targetFolderName(){return e().name},get onAddChoice(){return t.actions.onAddChoice}}),$(ce),A(se,ce)};z(W,se=>{n()||se(Z)})}A(B,J)};z(G,B=>{f(o)?B(V):B(M,-1)})}$(O),A(H,O)};z(K,H=>{e().collapsed||H(ne)})}A(D,N)};z(_,D=>{(!t.collapseId||t.collapseId&&e().id!==t.collapseId)&&D(I)})}$(m),Q(()=>{le(h,"data-choice-id",e().id),le(g,"aria-expanded",!e().collapsed),le(g,"aria-label",`Toggle ${e().name}`),b=Ge(v,1,"qaChoiceRowIcon multiChoiceCollapseIcon svelte-gckzoy",null,b,{"is-collapsed":e().collapsed})}),ge("contextmenu",h,c),ge("click",h,D=>{mE.Platform.isMobile||D.target.closest("button, a")||p()}),ge("click",g,p),A(r,m),oe()}He(["contextmenu","click"]);var YU=require("obsidian");lt();var X7=F("<div><!></div>"),J7=F("<div></div>"),Z7={hash:"svelte-10tg5sy",code:`.choiceList.svelte-10tg5sy {width:auto;}
|
||
|
||
/* Root (non-nested) empty list keeps a little bottom breathing room. The only way to
|
||
render it empty is a zero-match filter \u2014 a truly empty tree shows the hero state. */.choiceList.qa-empty.svelte-10tg5sy:not(.qa-nested) {padding-bottom:0.5rem;}.choiceList.qa-nested.svelte-10tg5sy {
|
||
/* Own the 2px name->first-row gap so the empty drop band sits the same distance
|
||
below the folder name as a populated folder's first row (collapses with the
|
||
row's own margin-top, so populated folders look identical). */margin-top:2px;position:relative; /* anchor the ring (::before) */border-radius:var(--radius-m);transition:background-color 120ms ease;}
|
||
|
||
/* The drop ring is drawn a few px OUTSIDE the content as an absolutely-positioned
|
||
::before (adds no layout) \u2014 "synthetically" bigger than the rows so it doesn't
|
||
clamp straight against the choice names. The right edge stays at the content edge:
|
||
the settings pane is overflow-x:hidden, so extending the ring right would clip it. */.choiceList.qa-nested.svelte-10tg5sy::before {content:"";position:absolute;inset:-4px 0 -4px -6px;border-radius:var(--radius-m);border:2px dashed transparent;pointer-events:none;transition:border-color 120ms ease;}.choiceList.qa-nested.svelte-10tg5sy.qa-folder-droptarget {background-color:var(--background-modifier-hover);}.choiceList.qa-nested.svelte-10tg5sy.qa-folder-droptarget::before {border-color:var(--interactive-accent);}
|
||
|
||
/* Empty folder: a GENEROUS, STABLE drop target. The band is sized by the folder's
|
||
PERSISTED emptiness (qa-folder-empty), NOT the live \`choices\` length \u2014 so when a
|
||
dragged item is previewed into the zone (filling \`choices\`, toggling qa-empty off)
|
||
the band keeps its height instead of collapsing/expanding under the cursor (the
|
||
"jumps all over the place"). Only persisted-empty folders get it, so populated
|
||
folders never heave at drag start. */.choiceList.qa-nested.qa-folder-empty.svelte-10tg5sy {min-height:3rem;display:flex;align-items:center;}
|
||
|
||
/* Hint shows only when the folder is persisted-empty AND nothing is previewed in it
|
||
(qa-empty = live \`choices\` empty), so it cleanly swaps out for the previewed row
|
||
without changing the band's size. */.choiceList.qa-nested.qa-folder-empty.qa-empty.svelte-10tg5sy::after {content:"Empty \u2014 add a choice or drag one here.";color:var(--text-faint);font-size:var(--font-ui-smaller, 12px);line-height:1.3;padding-left:8px; /* align with the child rows' own left padding */pointer-events:none;user-select:none;}
|
||
|
||
@media (prefers-reduced-motion: reduce) {.choiceList.qa-nested.svelte-10tg5sy,
|
||
.choiceList.qa-nested.svelte-10tg5sy::before {transition:none;}
|
||
}`};function of(r,t){ie(t,!0),Ae(r,Z7);let e=X(t,"choices",31,()=>Ze([])),n=X(t,"forceDragDisabled",3,!1),i=X(t,"isEmptyFolder",3,!1),o=X(t,"nested",3,!1),s=k(()=>{let w=new Set;return mr(e()).filter(T=>{if(!Ee(T))return!1;let P=T.id;return typeof P!="string"||P===""||w.has(P)?!1:(w.add(P),!0)})}),a=k(()=>t.rootReorder??t.actions.onReorderChoices),l=YU.Platform.isMobile,c=pe(""),d=xm(),u=k(()=>n()||!l&&!d.armed),p=pe(void 0),m=null;function h(w){if(n())return;d.markStarted(),wm(w);let T=w.detail.items;m=ym(T,w.detail.info.id)??m,q(c,w.detail.info.id,!0),e(xi(T))}function g(w){if(n())return;q(c,"");let T=xi(w.detail.items),P=w.detail.info.id;w.detail.info.trigger===gr.DROPPED_INTO_ANOTHER?T=T.filter(_=>_.id!==P):m?.item.id===P&&!T.some(_=>_.id===P)&&(T=[...T],T.splice(Math.min(m.index,T.length),0,m.item)),m=null,e(T),d.reset(),t.actions.onReorderChoices(e())}let v=()=>{n()||d.startDrag()};function b(w,T){if(n())return;let P=document.activeElement?.getAttribute("aria-label"),_=xi(f(s)),I=bm(_,w.id,T);if(!I)return;let D=I.findIndex(N=>N.id===w.id);e(I),t.actions.onReorderChoices(e()),nu(`Moved ${w.name} to position ${D+1} of ${I.length}`),P&&Em(f(p),P)}var y=J7();let C;gt(y,21,()=>xi(f(s)),w=>w.id,(w,T)=>{var P=X7(),_=R(P);{var I=N=>{{let K=k(()=>t.roots??e()),ne=k(()=>n()?void 0:()=>b(f(T),-1)),H=k(()=>n()?void 0:()=>b(f(T),1));r$(N,{get app(){return t.app},get roots(){return f(K)},get dragDisabled(){return f(u)},startDrag:v,get actions(){return t.actions},get choice(){return f(T)},get onMoveUp(){return f(ne)},get onMoveDown(){return f(H)}})}},D=N=>{{let K=k(()=>t.roots??e()),ne=k(()=>n()?void 0:()=>b(f(T),-1)),H=k(()=>n()?void 0:()=>b(f(T),1));n$(N,{get app(){return t.app},get roots(){return f(K)},get dragDisabled(){return f(u)},startDrag:v,get actions(){return t.actions},get collapseId(){return f(c)},get forceDragDisabled(){return n()},get rootReorder(){return f(a)},get choice(){return f(T)},get onMoveUp(){return f(ne)},get onMoveDown(){return f(H)}})}};z(_,N=>{f(T).type!=="Multi"?N(I):N(D,-1)})}$(P),A(w,P)}),$(y),xn(y,w=>q(p,w),()=>f(p)),Ft(y,(w,T)=>vm?.(w,T),()=>Cm({items:f(s),dragDisabled:f(u),dropTargetClasses:o()?["qa-folder-droptarget"]:[]})),Q(()=>C=Ge(y,1,"choiceList svelte-10tg5sy",null,C,{"qa-nested":o(),"qa-folder-empty":i(),"qa-empty":f(s).length===0})),Kn("consider",y,h),Kn("finalize",y,g),A(r,y),oe()}var eJ=F('<pre class="qaChoicesUnavailableDetail svelte-1t3kvu9"> </pre>'),tJ=F(`<div class="qaChoicesUnavailable svelte-1t3kvu9"><div class="qaChoicesUnavailableHead svelte-1t3kvu9"><!> <span class="qaChoicesUnavailableTitle svelte-1t3kvu9"> </span></div> <p class="qaChoicesUnavailableBody svelte-1t3kvu9">Something in this vault's QuickAdd settings could not be read. Your choices
|
||
have not been changed or deleted, and QuickAdd will not overwrite them.</p> <p class="qaChoicesUnavailableBody svelte-1t3kvu9">They are stored in <code>.obsidian/plugins/quickadd/data.json</code> inside this vault. Make a
|
||
copy of that file before editing it.</p> <!></div>`),rJ={hash:"svelte-1t3kvu9",code:".qaChoicesUnavailable.svelte-1t3kvu9 {border:1px solid var(--background-modifier-border);border-radius:var(--radius-m);padding:12px 14px;margin:4px 0 8px;background:var(--background-secondary);}.qaChoicesUnavailableHead.svelte-1t3kvu9 {display:flex;align-items:center;gap:8px;color:var(--text-warning, var(--text-normal));}.qaChoicesUnavailableTitle.svelte-1t3kvu9 {font-weight:var(--font-semibold);color:var(--text-normal);}.qaChoicesUnavailableBody.svelte-1t3kvu9 {margin:8px 0 0;color:var(--text-muted);font-size:var(--font-ui-small, 13px);max-width:68ch;}.qaChoicesUnavailableDetail.svelte-1t3kvu9 {margin:10px 0 0;padding:8px 10px;border-radius:var(--radius-s);background:var(--background-primary);color:var(--text-faint);font-size:var(--font-ui-smaller, 12px);white-space:pre-wrap;word-break:break-word;user-select:text;}"};function sf(r,t){Ae(r,rJ);let e=X(t,"what",3,"your choices"),n=X(t,"detail",3,"");var i=tJ(),o=R(i),s=R(o);Qe(s,{iconId:"alert-triangle",size:16});var a=E(s,2),l=re(a);$(o);var c=E(o,6);{var d=u=>{var p=eJ(),m=re(p,!0);Q(()=>ee(m,n())),A(u,p)};z(c,u=>{n()&&u(d)})}$(i),Q(()=>ee(l,`QuickAdd couldn't display ${e()??""}`)),A(r,i)}var fE=require("obsidian");ye();nt();Gs();ye();nt();function nJ(r){return`${$U(r)} name`}async function KU(r,t,e){try{let i=(await ir.Prompt(r,nJ(e),void 0,t)).trim();return!i||i===t?null:i}catch(n){return Be(n)||S.logError(Ia(n,"Could not rename")),null}}var JU=require("obsidian");lt();ye();lt();var i$=new WeakMap;function QU(r){let t=i$.get(r);if(t)return t;let e=o0(r);return i$.set(r,e),e}function XU(r){return i$.has(r)}function o$(r,t){if(!Array.isArray(r))return r;let e=XU(r),{choices:n,repaired:i}=QU(r);if(e)return n;for(let{choice:o}of i)if(o.command)try{t.enableCommand(o)}catch(s){S.logError(`Could not register a command for the repaired choice "${o.name}": ${s instanceof Error?s.message:String(s)}`)}return n}function ZU(r,t){let e=t.trim();if(!e)return r;let n=(0,JU.prepareFuzzySearch)(e),i=e.toLowerCase(),o=(s,a=!1)=>{if(!Ee(s))return null;let l=typeof s.name=="string"?s.name:"";if(s.type!=="Multi")return a||n(l)?s:null;let c=a||l.toLowerCase().includes(i),d=p=>Ne(s).map(m=>o(m,p)).filter(m=>m!==null),u=d(a);return c&&u.length===0&&(u=d(!0)),c||u.length>0?{...s,collapsed:!1,choices:u}:null};return r.map(s=>o(s)).filter(s=>s!==null)}function s$(r){return Ee(r)?r.command?!0:Ne(r).some(s$):!1}function ey(r,t){if(!Ee(r))return r;if(r.id===t.id)return{...r,...t};if($a(r)){let e=Ne(r).map(i=>ey(i,t));return{...r,choices:e}}return r}tn();function _r(r,t){if(Object.is(r,t))return!0;if(r===null||t===null)return r===t;if(typeof r!=typeof t)return!1;if(Array.isArray(r)||Array.isArray(t))return!Array.isArray(r)||!Array.isArray(t)||r.length!==t.length?!1:r.every((e,n)=>_r(e,t[n]));if(typeof r=="object"&&typeof t=="object"){let e=r,n=t,i=Object.keys(e),o=Object.keys(n);return i.length!==o.length?!1:i.every(s=>Object.prototype.hasOwnProperty.call(n,s)&&_r(e[s],n[s]))}return!1}function dl(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)&&Object.getPrototypeOf(r)===Object.prototype}function iJ(r){return dl(r)&&typeof r.name=="string"&&Array.isArray(r.models)}function oJ(r){return dl(r)&&typeof r.name=="string"&&typeof r.maxTokens=="number"&&!Array.isArray(r.models)}function sJ(r){if(typeof r.id=="string"&&r.id.trim().length>0)return`id:${r.id.trim().toLowerCase()}`;let t=String(r.name??"").trim().toLowerCase(),e=String(r.endpoint??"").trim().toLowerCase().replace(/\/+$/,"");return`name:${t}\0${e}`}function aJ(r){return dl(r)&&typeof r.id=="string"&&r.id.trim().length>0}function lJ(r){return`id:${String(r.id).trim()}`}function cJ(r){return String(r.name??"").trim().toLowerCase()}function eq(r,t){let e=new Map;for(let n of r){if(!dl(n))continue;let i=t(n);!i||i==="id:"||i==="name:\0"||e.has(i)||e.set(i,n)}return e}function dJ(r,t,e,n,i){let o=eq(r??[],n),s=eq(e,n),a=[],l=new Set;for(let c of t){if(!dl(c)){a.push(ke(c));continue}let d=n(c);if(l.has(d))continue;l.add(d);let u=o.get(d),p=s.get(d);if(!s.has(d)){(!o.has(d)||!_r(c,u))&&a.push(ke(c));continue}a.push(ul(u,c,p,i))}for(let c of e){if(!dl(c))continue;let d=n(c);l.has(d)||(l.add(d),o.has(d)||a.push(ke(c)))}return a}function ul(r,t,e,n=[]){if(_r(t,e))return ke(t);if(_r(t,r))return ke(e);if(_r(e,r))return ke(t);if(dl(r)&&dl(t)&&dl(e)){let a=new Set([...Object.keys(r),...Object.keys(t),...Object.keys(e)]),l={};for(let c of a)l[c]=ul(r[c],t[c],e[c],[...n,c]);return l}let i=Array.isArray(r)?r:void 0,o=Array.isArray(t)?t:void 0,s=Array.isArray(e)?e:void 0;if(o&&s){let a=n[n.length-1],l=[...o,...s,...i??[]],c=a==="providers"&&l.every(iJ)?sJ:a==="models"&&l.every(oJ)?cJ:a==="choices"&&l.every(aJ)?lJ:void 0;if(c)return dJ(i,o,s,c,n)}return ke(t)}function uJ(r,t){return!_r(r,t)}function pJ(r,t,e){return r==null||e==null?{toWrite:t,didMerge:!1}:uJ(r,e)?{toWrite:ul(r,t,e),didMerge:!0}:{toWrite:t,didMerge:!1}}function tq(r){let t=r.local,{toWrite:e,didMerge:n}=pJ(r.base,t,r.disk);_r(r.currentStore,t)||(e=ul(t,r.currentStore,e),t=r.currentStore,n=!0);let i=n&&_r(r.currentStore,t)&&!_r(e,r.currentStore);return{toWrite:e,didMerge:n,local:t,shouldReplaceStore:i}}function rq(r,t,e){return!_r(r,t)&&_r(t,e)}je();function nq(r){function t(){r.saveChoices(Wi(r.choices))}async function e(v,b,y,C=!1){let w=HU(b,r.choices),T=KP(b,w);if(r.choices=UU(r.choices,T,y),!y&&r.filterQuery.trim().length>0&&(r.filterQuery=""),t(),b==="Multi")await l(T);else if(!C)try{if(s(T))return}catch(P){S.logError(`Failed to configure the new choice: ${P instanceof Error?P.message:String(P)}`),t()}await n(T.id)}async function n(v){await Cs();try{document.querySelector(`[data-choice-id="${v}"]`)?.scrollIntoView({block:"nearest"})}catch{}}function i(v){return du(r.choices,v.id)??v}async function o(v){let b=i(v);await DU(b,r.app)&&(r.choices=Jv(r.choices,v.id).updated,r.commandRegistry.disableCommand(b,{recursive:!0}),t())}function s(v){let b=!1;return LU(i(v),r.app,r.plugin,(y,C)=>$s(`Couldn't save the ${cu(C.type)} \u201C${C.name}\u201D`,()=>{a(C,y)||b||(b=!0,new fE.Notice(`QuickAdd: \u201C${C.name}\u201D was deleted elsewhere, so your changes to it were not saved.`))})())}function a(v,b){let y=U.getState().choices,C=du(y,v.id);if(!C)return!1;let w=ul(v,b,Wi(C));return r.saveChoices(Wi(y.map(T=>ey(T,w)))),r.commandRegistry.updateCommand(C,w),!0}async function l(v){if(!v)return;let b=await KU(r.app,v.name,v.type);if(!b)return;let y=du(r.choices,v.id);if(!y){new fE.Notice(`QuickAdd: \u201C${v.name}\u201D was deleted elsewhere, so it was not renamed.`);return}let C={...y,name:b};r.choices=r.choices.map(w=>ey(w,C)),r.commandRegistry.updateCommand(y,C),t()}function c(v){let b=NU(i(v));r.choices=r.choices.map(y=>ey(y,b)),b.command?r.commandRegistry.enableCommand(b):r.commandRegistry.disableCommand(b),t()}async function d(v){let b=await RU(i(v),r.app);r.choices=JP(r.choices,v.id,b)??[...r.choices,b],s$(b)&&r.commandRegistry.enableCommand(b),t(),new fE.Notice(`Duplicated "${v.name}".`),await n(b.id)}function u(v,b){r.choices=b===t$?BU(r.choices,v.id):VU(r.choices,v.id,b),t()}function p(v){r.choices=v,t()}function m(v,b){r.choices=qU(r.choices,v,b),t()}function h(v){r.choices=e$(r.choices,v.id,!v.collapsed),t()}function g(v,b){return(y,...C)=>{let w=cu(y?.type),T=y?.name?`the ${w} \u201C${y.name}\u201D`:`that ${w}`;$s(`Couldn't ${v} ${T}`,b)(y,...C)}}return{onDeleteChoice:g("delete",o),onConfigureChoice:g("open the settings for",s),onToggleCommand:g("update the command palette entry for",c),onDuplicateChoice:g("duplicate",d),onRenameChoice:g("rename",l),onMoveChoice:g("move",u),onToggleCollapsed:g("open or close",h),onReorderChoices:$s("Couldn't save the new order",p),onCommitFolder:$s("Couldn't save that folder's contents",m),onAddChoice:(v,b,y,C)=>$s(`Couldn't add that ${cu(b)}`,e)(v,b,y,C)}}var mJ=F('<button type="button" class="qaAIAssistantBtn qaAIAssistantEmptyBtn clickable-icon svelte-i6fsu8" aria-label="Configure AI Assistant"><!> <span>Configure AI Assistant</span></button>'),fJ=F(`<div class="choiceEmptyState svelte-i6fsu8"><!> <div class="choiceEmptyTitle svelte-i6fsu8">No choices yet</div> <p class="choiceEmptyBody svelte-i6fsu8">A choice is an action QuickAdd can run: create a note, capture
|
||
text, or run a macro. Group them with folders. <a class="quickadd-docs-link" target="_blank" rel="noopener noreferrer">Learn more</a></p> <div class="choiceEmptyActions svelte-i6fsu8"><!></div> <!></div>`),hJ=F('<button class="search-input-clear-button qaFilterClearButton svelte-i6fsu8" aria-label="Clear filter"></button>'),gJ=F('<div class="choiceFilterEmpty svelte-i6fsu8">No choices match your filter.</div>'),vJ=F('<button type="button" class="qaAIAssistantBtn clickable-icon svelte-i6fsu8" aria-label="Configure AI Assistant" title="Configure AI Assistant"><!></button>'),yJ=F('<div class="choiceFilterBar svelte-i6fsu8"><div class="search-input-container choiceFilterInput svelte-i6fsu8"><input type="search" placeholder="Filter choices..." autocapitalize="off" autocorrect="off" enterkeyhint="search"/> <!></div></div> <!> <div class="choiceViewBottomBar svelte-i6fsu8"><!> <!></div>',1),bJ=F("<div><!></div>"),wJ={hash:"svelte-i6fsu8",code:`.qaAIAssistantEmptyBtn.svelte-i6fsu8 {display:inline-flex;align-items:center;gap:0.375rem;margin-top:0.75rem;width:auto;color:var(--text-muted);font-size:var(--font-ui-small);}.choiceViewBottomBar.svelte-i6fsu8 {display:flex;flex-direction:row;align-items:center;justify-content:flex-end; /* pack right; "New choice" (primary) is the terminal action */flex-wrap:wrap;gap:0.5rem;margin-top:0.75rem;}
|
||
|
||
/* AI Assistant as a quiet icon button (matches the per-row action icons),
|
||
leading the right cluster so the bar's width barely changes when AI/online
|
||
features toggle. */.qaAIAssistantBtn.svelte-i6fsu8 {flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;color:var(--text-muted);}.qaAIAssistantBtn.svelte-i6fsu8:hover {color:var(--text-normal);}.choiceEmptyState.svelte-i6fsu8 {display:flex;flex-direction:column;align-items:center;text-align:center;gap:0.5rem;padding:2.5rem 1rem;color:var(--text-muted);}.choiceEmptyTitle.svelte-i6fsu8 {font-weight:var(--font-semibold);color:var(--text-normal);}.choiceEmptyBody.svelte-i6fsu8 {margin:0;max-width:42ch;}.choiceEmptyActions.svelte-i6fsu8 {margin-top:0.5rem;}.choiceFilterBar.svelte-i6fsu8 {margin-bottom:8px;}
|
||
|
||
/* The native container is inline-block by default in some contexts; span
|
||
the full row so the filter aligns with the list edges. */.choiceFilterInput.svelte-i6fsu8 {width:100%;}
|
||
|
||
/* Obsidian styles .search-input-clear-button (position, the \xD7 glyph, hover)
|
||
\u2014 we only reset the <button> chrome so that styling shows through. A real
|
||
<button> (Obsidian uses a div) keeps it keyboard-operable. */.qaFilterClearButton.svelte-i6fsu8 {background:transparent;border:none;box-shadow:none;padding:0;margin:0;cursor:var(--cursor, pointer);}.choiceFilterEmpty.svelte-i6fsu8 {color:var(--text-faint);font-size:var(--font-ui-small, 13px);padding:12px 8px 16px;}`};function a$(r,t){ie(t,!0),Ae(r,wJ);let e=X(t,"choices",31,()=>Ze([])),n=pe(""),i=k(()=>!Array.isArray(e())),o=k(()=>`The "choices" value in data.json is ${e()===null?"null":`of type "${typeof e()}"`}, but QuickAdd expects a list.`),s=iq.Platform.isMobile,a=pe(Ze(U.getState().disableOnlineFeatures)),l=new sE(pt(()=>t.plugin));e(o$(e(),l)),Dt(()=>{let h=U.subscribe(g=>{e(o$(g.choices,l)),q(a,g.disableOnlineFeatures,!0)});return()=>h()});let c=nq({get app(){return t.app},get plugin(){return t.plugin},get choices(){return e()},set choices(h){e(h)},get filterQuery(){return f(n)},set filterQuery(h){q(n,h,!0)},commandRegistry:l,saveChoices:h=>t.saveChoices(h)});var d=bJ(),u=R(d);{var p=h=>{sf(h,{get detail(){return f(o)}})},m=h=>{var g=bt(),v=ae(g);wh(v,{onerror:y=>S.logError(`QuickAdd could not render the choice list: ${y instanceof Error?y.message:String(y)}`),failed:(y,C=$t)=>{{let w=k(()=>C()instanceof Error?C().message:String(C()));sf(y,{get detail(){return f(w)}})}}},y=>{var C=bt(),w=ae(C);{var T=I=>{var D=fJ(),N=R(D);Qe(N,{iconId:"folder-plus",size:28});var K=E(N,4),ne=E(R(K));$(K);var H=E(K,2),O=R(H);rf(O,{get onAddChoice(){return c.onAddChoice}}),$(H);var G=E(H,2);{var V=M=>{var B=mJ(),J=R(B);Qe(J,{iconId:"sparkles",size:16}),Xt(2),$(B),ge("click",B,function(...te){t.openAISettings?.apply(this,te)}),A(M,B)};z(G,M=>{f(a)||M(V)})}$(D),Q(()=>le(ne,"href",is.gettingStarted)),A(I,D)},P=k(()=>e().length===0&&f(n).trim().length===0),_=I=>{var D=yJ(),N=ae(D),K=R(N),ne=R(K);Ct(ne),le(ne,"spellcheck",!1);var H=E(ne,2);{var O=se=>{var ce=hJ();ge("click",ce,()=>q(n,"")),A(se,ce)};z(H,se=>{f(n)&&se(O)})}$(K),$(N);var G=E(N,2);{var V=se=>{of(se,{get app(){return t.app},get roots(){return e()},get actions(){return c},get choices(){return e()},set choices(ce){e(ce)}})},M=k(()=>f(n).trim().length===0),B=se=>{let ce=k(()=>ZU(e(),f(n)));var $e=bt(),Xe=ae($e);{var Ye=Re=>{var Je=gJ();A(Re,Je)},he=Re=>{of(Re,{get app(){return t.app},get roots(){return e()},get choices(){return f(ce)},forceDragDisabled:!0,get actions(){return c}})};z(Xe,Re=>{f(ce).length===0?Re(Ye):Re(he,-1)})}A(se,$e)};z(G,se=>{f(M)?se(V):se(B,-1)})}var J=E(G,2),te=R(J);{var W=se=>{var ce=vJ(),$e=R(ce);Qe($e,{iconId:"sparkles",size:16}),$(ce),ge("click",ce,function(...Xe){t.openAISettings?.apply(this,Xe)}),A(se,ce)};z(te,se=>{f(a)||se(W)})}var Z=E(te,2);rf(Z,{get onAddChoice(){return c.onAddChoice},get fill(){return s}}),$(J),ge("keydown",ne,se=>{se.key==="Escape"&&f(n)&&(q(n,""),se.stopPropagation())}),Zn(ne,()=>f(n),se=>q(n,se)),A(I,D)};z(w,I=>{f(P)?I(T):I(_,-1)})}A(y,C)}),A(h,g)};z(u,h=>{f(i)?h(p):h(m,-1)})}$(d),A(r,d),oe()}He(["click","keydown"]);Qi();je();Hh();var CJ=F('<div class="qa-gv__empty svelte-it20w4">No global variables yet.</div>'),xJ=F('<div class="qa-gv__row qa-gv__row--head svelte-it20w4"><div class="qa-gv__cell qa-gv__name">Name</div> <div class="qa-gv__cell qa-gv__value">Value</div> <div class="qa-gv__cell qa-gv__ops svelte-it20w4">Actions</div></div>'),EJ=F('<div class="qa-gv__row svelte-it20w4"><div class="qa-gv__cell qa-gv__name svelte-it20w4"><input type="text" placeholder="Name" class="svelte-it20w4"/></div> <div class="qa-gv__cell qa-gv__value svelte-it20w4"><textarea rows="2" placeholder="Snippet value (supports QuickAdd tokens)" class="svelte-it20w4"></textarea></div> <div class="qa-gv__cell qa-gv__ops svelte-it20w4"><button class="qa-gv__btn danger svelte-it20w4" title="Delete">Delete</button></div></div>'),TJ=F('<div class="qa-gv svelte-it20w4"><div class="qa-gv__desc svelte-it20w4">Define reusable snippets referenced as <code>{{GLOBAL_VAR:<name>}}</code>. Snippets support other QuickAdd tokens and expand before VALUE/VDATE/etc.</div> <div class="qa-gv__table svelte-it20w4"><!> <!></div> <div class="qa-gv__actions svelte-it20w4"><button class="mod-cta">Add variable</button></div></div>'),_J={hash:"svelte-it20w4",code:`.qa-gv.svelte-it20w4 {display:flex;flex-direction:column;gap:8px;}
|
||
/* Keeps "Add variable" right-aligned now that it is the row's only child. */.qa-gv__actions.svelte-it20w4 {display:flex;justify-content:flex-end;}.qa-gv__desc.svelte-it20w4 {color:var(--text-muted);font-size:12px;}.qa-gv__empty.svelte-it20w4 {color:var(--text-muted);font-size:var(--font-ui-smaller);padding:6px 0;}.qa-gv__table.svelte-it20w4 {display:grid;gap:8px;}.qa-gv__row.svelte-it20w4 {display:grid;grid-template-columns:180px 1fr 140px;gap:8px;align-items:start;}.qa-gv__row--head.svelte-it20w4 {font-weight:600;color:var(--text-muted);}.qa-gv__cell.svelte-it20w4 input[type="text"]:where(.svelte-it20w4) {width:100%;}.qa-gv__cell.svelte-it20w4 textarea:where(.svelte-it20w4) {width:100%;resize:vertical;}.qa-gv__ops.svelte-it20w4 {display:flex;gap:6px;align-items:center;}.qa-gv__btn.svelte-it20w4 {padding:4px 8px;}.qa-gv__btn.danger.svelte-it20w4 {color:var(--text-error);}
|
||
@media (max-width: 900px) {.qa-gv__row.svelte-it20w4 {grid-template-columns:1fr;}.qa-gv__row--head.svelte-it20w4 {display:none;}
|
||
}`};function l$(r,t){ie(t,!0),Ae(r,_J);let e=pe(Ze([]));function n(w,T){if(!T.has(w))return w;let P=1;for(;T.has(`${w}${P}`);)P++;return`${w}${P}`}function i(){let T=U.getState().globalVariables||{};q(e,Object.keys(T).map(P=>({name:P,value:T[P]??""})),!0)}let o=!1;function s(){let w=f(e).map(I=>I.name.trim()),T=w.some(I=>!I),P=new Set(w).size!==w.length;if(T||P)return;let _={};for(let I of f(e))_[I.name.trim()]=I.value??"";o=!0;try{U.setState({globalVariables:_})}finally{o=!1}}function a(){let w=new Set(f(e).map(P=>P.name)),T=n("NewVar",w);q(e,[...f(e),{name:T,value:""}],!0),s()}function l(w){q(e,f(e).filter((T,P)=>P!==w),!0),s()}function c(w){return new ln(t.app,w,t.plugin),{destroy(){}}}let d;function u(w){d!==void 0&&window.clearTimeout(d),d=window.setTimeout(()=>{d=void 0,s()},200)}Dt(()=>{let w=U.subscribe(()=>{o||i()});return i(),()=>{d!==void 0&&(window.clearTimeout(d),s()),w()}});var p=TJ(),m=E(R(p),2),h=R(m);{var g=w=>{var T=CJ();A(w,T)},v=w=>{var T=xJ();A(w,T)};z(h,w=>{f(e).length===0?w(g):w(v,-1)})}var b=E(h,2);gt(b,17,()=>f(e),yd,(w,T,P)=>{var _=EJ(),I=R(_),D=R(I);Ct(D),Ft(D,O=>c?.(O)),Cr(()=>Zn(D,()=>f(T).name,O=>f(T).name=O)),$(I);var N=E(I,2),K=R(N);rd(K),Ft(K,O=>c?.(O)),Ft(K,O=>pw?.(O)),Cr(()=>Zn(K,()=>f(T).value,O=>f(T).value=O)),$(N);var ne=E(N,2),H=re(ne);$(_),ge("input",D,()=>{u(f(T))}),ge("input",K,()=>u(f(T))),ge("click",H,()=>l(f(e).indexOf(f(T)))),A(w,_)}),$(m);var y=E(m,2),C=re(y);$(p),ge("click",C,a),A(r,p),oe()}He(["input","click"]);je();bi();Jt();var kq=require("obsidian");ml();lt();Gr();Jt();Ac();er();var AJ=new Set;function c$(r,t,e){return r?t.has(r.id)?e.has(r.id):!0:!1}function IJ(r,t,e,n){switch(r.type){case"Choice":{let i=r;if(!e.has(i.choiceId))return!0;let o=t.get(i.choiceId);return o&&c$(o.choice,t,e)&&n(o.choice),!0}case"NestedChoice":{let i=r;return i.choice&&c$(i.choice,t,e)&&n(i.choice),!0}default:return!1}}function PJ(r){let t=new Map,e=(n,i,o)=>{for(let s of n){if(!Ee(s))continue;let a=[...o,s.name];t.set(s.id,{choice:s,parentId:i,path:a}),uu(s)&&Array.isArray(s.choices)&&e(s.choices,s.id,a)}};return e(mr(r),null,[]),t}function aq(r){let t=new Set;for(let e of Ne(r))Ee(e)&&t.add(e.id);return Xi(r)&&d$(r.macro?.commands,t),t}function d$(r,t){for(let e of Mt(r))if(Tr(e))switch(e.type){case"Choice":{let n=e;n.choiceId&&t.add(n.choiceId);break}case"Conditional":{let n=e;d$(n.thenCommands,t),d$(n.elseCommands,t);break}case"NestedChoice":{let i=e.choice;if(!i)break;let o=aq(i);for(let s of o)t.add(s);break}default:break}}function gE(r,t,e){let n=PJ(r),i=new Set,o=new Set,s=e?.excludedChoiceIds??AJ,a=t.filter(c=>!s.has(c)),l=[];for(;a.length>0;){let c=a.shift();if(i.has(c))continue;if(s.has(c)){i.add(c);continue}let d=n.get(c);if(!d){o.add(c);continue}i.add(c),l.push(c);let u=aq(d.choice);for(let p of u){if(!n.has(p)){o.add(p);continue}s.has(p)||a.push(p)}}return{catalog:n,choiceIds:l,missingChoiceIds:Array.from(o)}}function lq(r,t,e,n){let i=new Set(t),o=new Set,s=l=>{!l||!c$(l,r,i)||o.has(l.id)||(o.add(l.id),e(l),uu(l)&&Array.isArray(l.choices)&&l.choices.forEach(s),Xi(l)&&a(l.macro?.commands))},a=l=>{for(let c of Mt(l))if(Tr(c)&&!IJ(c,r,i,s)&&(n(c),c.type==="Conditional")){let d=c;a(d.thenCommands),a(d.elseCommands)}};for(let l of t){let c=r.get(l);c&&s(c.choice)}}function vE(r,t){let e=new Set,n=new Set;return lq(r,t,()=>{},i=>{if(i.type==="UserScript"){let o=i;o.path&&e.add(o.path)}else if(i.type==="Conditional"){let{condition:o}=i;o.mode==="script"&&o.scriptPath&&n.add(o.scriptPath)}}),{userScriptPaths:e,conditionalScriptPaths:n}}function yE(r,t){let e=new Set,n=new Set,i=new Set;return lq(r,t,o=>{if(qn(o)&&o.templatePath&&e.add(En(o.templatePath)),pl(o)){let s=o.createFileIfItDoesntExist;s?.enabled&&s.createWithTemplate&&s.template&&n.add(En(s.template));for(let a of u$(o))i.add(a)}},()=>{}),{templatePaths:e,captureTemplatePaths:n,includePaths:i}}function u$(r){let t=r.format;return!t?.enabled||typeof t.format!="string"?new Set:Xs(t.format)}function cq(r,t){let e=t.trim().toLowerCase();return e?r.filter(n=>`${n.path.join(" ")} ${n.choice.type}`.toLowerCase().includes(e)):r}function dq(r,t){let e=[];for(let n of r)t.has(n.id)&&(!n.parentId||!t.has(n.parentId))&&e.push(n.id);return e}function uq(r,t,e){if(t.length===0)return{rootCount:0,totalChoices:0,dependencyCount:0,missingChoiceIds:[],userScripts:0,conditionalScripts:0,templateFiles:0,captureTemplates:0};let n=gE(r,t,{excludedChoiceIds:e}),i=vE(n.catalog,n.choiceIds),o=yE(n.catalog,n.choiceIds);return{rootCount:t.length,totalChoices:n.choiceIds.length,dependencyCount:Math.max(n.choiceIds.length-t.length,0),missingChoiceIds:n.missingChoiceIds,userScripts:i.userScriptPaths.size,conditionalScripts:i.conditionalScriptPaths.size,templateFiles:o.templatePaths.size,captureTemplates:o.captureTemplatePaths.size}}var ps=require("obsidian");lt();var pq=typeof TextEncoder<"u"?new TextEncoder:void 0,mq=typeof TextDecoder<"u"?new TextDecoder:void 0;function fq(r){return typeof window>"u"?!1:typeof window[r]=="function"}function hq(){if(!(typeof Buffer>"u"))return Buffer}function gq(r){if(pq&&fq("btoa")){let e=pq.encode(r),n="";for(let i=0;i<e.length;i++)n+=String.fromCharCode(e[i]);return window.btoa(n)}let t=hq();if(t)return t.from(r,"utf8").toString("base64");throw new Error("Base64 encoding is not supported in this environment.")}function Js(r){if(mq&&fq("atob")){let e=window.atob(r),n=Uint8Array.from(e,i=>i.charCodeAt(0));return mq.decode(n)}let t=hq();if(t)return t.from(r,"base64").toString("utf8");throw new Error("Base64 decoding is not supported in this environment.")}nl();ye();function bE(r,t){let e=new Map;for(let n of r)if(n.kind==="user-script")try{let i=Dv(Js(n.content),n.originalPath);e.set(n.originalPath,i.foundSecretOptions&&i.names.size===0?null:i.names)}catch(i){S.logWarning(`QuickAdd ${t} could not inspect user-script settings '${n.originalPath}': ${i?.message??i}`)}return e}var wq=require("obsidian");tl();ye();function wE(r){return!!r&&typeof r=="object"}function vq(r){return Array.isArray(r)&&r.every(t=>typeof t=="string")}function $J(r){return wE(r)?typeof r.id=="string"&&typeof r.name=="string"&&typeof r.type=="string":!1}function FJ(r){return wE(r)?$J(r.choice)&&vq(r.pathHint)&&(r.parentChoiceId===null||typeof r.parentChoiceId=="string"):!1}function MJ(r){if(!wE(r))return!1;let{kind:t,originalPath:e,contentEncoding:n,content:i}=r;return(t==="user-script"||t==="conditional-script"||t==="template"||t==="capture-template")&&typeof e=="string"&&n==="base64"&&typeof i=="string"}function yq(r){if(!wE(r))return!1;let{schemaVersion:t,quickAddVersion:e,createdAt:n,rootChoiceIds:i,choices:o,assets:s}=r;return typeof t=="number"&&Number.isInteger(t)&&t>=1&&typeof e=="string"&&typeof n=="string"&&vq(i)&&Array.isArray(o)&&o.every(FJ)&&Array.isArray(s)&&s.every(MJ)}lt();tn();async function CE(r,t){let e=t.lastIndexOf("/");if(e<0)return;let n=t.slice(0,e);if(!n)return;let i=n.split("/").filter(Boolean),o="";for(let s of i)o=o?`${o}/${s}`:s,await r.vault.adapter.exists(o)||await r.vault.createFolder(o)}Jt();Ac();Yi();nl();function Cq(){return`QuickAdd Packages/quickadd-package-${new Date().toISOString().replace(/[:.]/g,"-")}.quickadd.json`}async function xq(r,t){let{choices:e,rootChoiceIds:n,quickAddVersion:i}=t,o=new Set(t.excludedChoiceIds??[]),s=t.createdAt??new Date().toISOString(),a=gE(e,n,{excludedChoiceIds:o}),l=new Set(a.choiceIds),c=vE(a.catalog,a.choiceIds),d=yE(a.catalog,a.choiceIds),u=RJ(c,d),p=await Eq(r,u);await DJ(r,p);let m=bE(p.encodedAssets,"export"),h=a.choiceIds.map(b=>{let y=a.catalog.get(b);if(!y)throw new Error(`Choice '${b}' missing from catalog.`);let C=ke(y.choice);return Tq(C,l),ax(C,{secretOptionNamesByPath:m,stripUnknownStringSettings:!0}),{choice:C,pathHint:[...y.path],parentChoiceId:y.parentId}}),g=n.filter(b=>l.has(b));return{pkg:{schemaVersion:1,quickAddVersion:i,createdAt:s,rootChoiceIds:[...g],choices:h,assets:p.encodedAssets},missingChoiceIds:a.missingChoiceIds,missingAssets:p.missingAssets}}function RJ(r,t){let e=new Map;for(let n of r.userScriptPaths)n&&e.set(n,"user-script");for(let n of r.conditionalScriptPaths)n&&e.set(n,"conditional-script");for(let n of t.templatePaths)n&&(e.has(n)||e.set(n,"template"));for(let n of t.captureTemplatePaths)n&&(e.has(n)||e.set(n,"capture-template"));for(let n of t.includePaths)n&&(e.has(n)||e.set(n,"template"));return Array.from(e.entries()).map(([n,i])=>({path:n,kind:i}))}var OJ=10;async function DJ(r,t){let e=new Set(t.encodedAssets.map(i=>i.originalPath));for(let i of t.missingAssets)e.add(i.path);let n=t.encodedAssets.filter(bq);for(let i=0;i<OJ&&n.length>0;i++){let o=[];for(let a of n)for(let l of Xs(Js(a.content)))e.has(l)||(e.add(l),o.push({path:l,kind:"template"}));if(o.length===0)break;let s=await Eq(r,o);t.encodedAssets.push(...s.encodedAssets),t.missingAssets.push(...s.missingAssets),n=s.encodedAssets.filter(bq)}}function bq(r){return(r.kind==="template"||r.kind==="capture-template")&&Ps(r.originalPath)}async function Eq(r,t){let e=[],n=[];for(let{path:i,kind:o}of t){if(Ut(i)){n.push({path:i,kind:o}),S.logWarning(`QuickAdd export skipped ${o} outside the vault: ${i}`);continue}try{if(!await r.vault.adapter.exists(i)){n.push({path:i,kind:o}),S.logWarning(`QuickAdd export skipped missing ${o}: ${i}`);continue}let a=await r.vault.adapter.read(i);e.push({kind:o,originalPath:i,contentEncoding:"base64",content:gq(a)})}catch(s){n.push({path:i,kind:o}),S.logWarning(`QuickAdd export failed to read ${o} '${i}': ${s?.message??s}`)}}return{encodedAssets:e,missingAssets:n}}function Tq(r,t){if(r.type!=="Multi")return;let e=r;if(!Array.isArray(e.choices)||e.choices.length===0){e.choices=[];return}e.choices=e.choices.filter(n=>Ee(n)&&t.has(n.id)).map(n=>(Tq(n,t),n))}async function LJ(r,t){return Ei(r,{title:"Overwrite existing file?",message:`A file already exists at '${t}'. Saving the package will overwrite it.`,action:"Overwrite"})}async function _q(r,t,e,n={}){let i=(0,wq.normalizePath)(e.trim());if(!i)throw new Error("Output path cannot be empty.");let o=await r.vault.adapter.exists(i);if(o&&!await(n.confirmOverwrite??(c=>LJ(r,c)))(i))throw new Error(`Save cancelled: '${i}' already exists.`);await CE(r,i);let s=JSON.stringify(t,null,2);return await r.vault.adapter.write(i,s),{overwritten:o}}var NJ=F('<div class="setting-item mod-empty-state"><div class="setting-item-info"><div class="setting-item-name">No choices match the current filter.</div></div></div>'),VJ=F('<span class="qa-export-choice-path svelte-1way66v"> </span>'),BJ=F('<label class="qa-export-choice svelte-1way66v"><input type="checkbox" class="svelte-1way66v"/> <span class="qa-export-choice-name svelte-1way66v"> </span> <!> <span class="flair qa-export-choice-type svelte-1way66v"> </span></label>'),UJ=F('<div class="setting-item"><div class="setting-item-info"><div class="setting-item-name"> </div></div> <div class="setting-item-control"><span class="setting-item-value qa-export-count svelte-1way66v"> </span></div></div>'),qJ=F('<section class="callout qa-export-callout svelte-1way66v" data-callout="warning"><div class="callout-title"><div class="callout-icon"><!></div> <div class="callout-title-inner">Missing dependencies detected</div></div> <div class="callout-content svelte-1way66v"><p class="svelte-1way66v"> </p></div></section>'),zJ=F('<p class="svelte-1way66v"> </p>'),HJ=F('<li><code class="svelte-1way66v"> </code> <span class="qa-export-asset-kind svelte-1way66v"> </span></li>'),WJ=F('<p class="svelte-1way66v">Missing assets:</p> <ul class="svelte-1way66v"></ul>',1),GJ=F('<section class="callout qa-export-callout svelte-1way66v" data-callout="warning"><div class="callout-title"><div class="callout-icon"><!></div> <div class="callout-title-inner">Warnings</div></div> <div class="callout-content svelte-1way66v"><!> <!></div></section>'),jJ=F('<div class="qa-package-dialog"><div class="qa-package-body"><section class="qa-export-select svelte-1way66v"><div class="qa-export-controls svelte-1way66v"><div class="search-input-container svelte-1way66v"><label class="qa-visually-hidden" for="qa-export-filter">Filter choices</label> <input id="qa-export-filter" type="search" enterkeyhint="search" placeholder="Filter choices..." autocapitalize="off" autocorrect="off"/></div> <button type="button">Select visible</button> <button type="button">Clear selection</button></div> <div class="setting-group"><div class="setting-items qa-export-list svelte-1way66v"><!></div></div></section> <section class="setting-group mod-list"><div class="setting-item setting-item-heading"><div class="setting-item-name">Package summary</div></div> <div class="setting-items"></div></section> <!> <!> <section class="setting-group qa-export-save-group svelte-1way66v"><div class="setting-items"><div class="setting-item qa-export-save svelte-1way66v"><div class="setting-item-info svelte-1way66v"><label class="setting-item-name" for="qa-export-path">Save to file</label></div> <div class="setting-item-control svelte-1way66v"><input id="qa-export-path" type="text" placeholder="QuickAdd Packages/quickadd-package-YYYY-MM-DD.quickadd.json" class="svelte-1way66v"/> <button type="button"><!></button></div></div></div></section></div> <div class="modal-button-container"><button type="button">Cancel</button> <button type="button"><!></button></div></div>'),YJ={hash:"svelte-1way66v",code:`.qa-export-select.svelte-1way66v {display:flex;flex-direction:column;gap:var(--size-4-3);}.qa-export-controls.svelte-1way66v {display:flex;flex-wrap:wrap;align-items:center;gap:var(--size-4-2);}.qa-export-controls.svelte-1way66v .search-input-container:where(.svelte-1way66v) {flex:1 1 12rem;}.qa-export-list.svelte-1way66v {max-height:260px;overflow-y:auto;padding:var(--size-4-1);}
|
||
|
||
/* List padding + row padding lands on the 16px inset of the mod-list rows
|
||
below, so every row in the modal starts on the same edge. */.qa-export-choice.svelte-1way66v {display:flex;align-items:center;gap:var(--size-4-2);padding:var(--size-4-1) var(--size-4-3);padding-inline-start:calc(
|
||
var(--size-4-3) + var(--qa-export-depth, 0) * var(--size-4-4)
|
||
);font-size:var(--font-ui-small);border-radius:var(--radius-s);cursor:var(--cursor);}.qa-export-choice.svelte-1way66v:hover {background-color:var(--background-modifier-hover);}.qa-export-choice.svelte-1way66v input:where(.svelte-1way66v) {flex-shrink:0;margin:0;}.qa-export-choice-name.svelte-1way66v {min-width:0;overflow-wrap:anywhere;}.qa-export-choice-path.svelte-1way66v {min-width:0;color:var(--text-muted);font-size:var(--font-ui-smaller);overflow-wrap:anywhere;}.qa-export-choice-type.svelte-1way66v {margin-inline-start:auto;}.qa-export-count.svelte-1way66v {color:var(--text-normal);font-variant-numeric:tabular-nums;}.qa-export-callout.svelte-1way66v {margin:0;}.qa-export-callout.svelte-1way66v .callout-content:where(.svelte-1way66v) {font-size:var(--font-ui-small);}.qa-export-callout.svelte-1way66v p:where(.svelte-1way66v) {margin:var(--size-4-2) 0 0;}.qa-export-callout.svelte-1way66v ul:where(.svelte-1way66v) {margin:var(--size-4-1) 0 0;padding-inline-start:var(--size-4-5);}.qa-export-callout.svelte-1way66v code:where(.svelte-1way66v) {font-family:var(--font-monospace);font-size:var(--code-size);background-color:var(--code-background);border-radius:var(--code-radius);padding:0.1em 0.25em;overflow-wrap:anywhere;}.qa-export-asset-kind.svelte-1way66v {margin-inline-start:var(--size-4-1);color:var(--text-muted);font-size:var(--font-ui-smaller);}
|
||
|
||
/* Same inset as the mod-list summary rows above. Not mod-list itself:
|
||
Obsidian keeps mod-list rows horizontal on phones, where this row needs
|
||
to stack. */.qa-export-save-group.svelte-1way66v {--setting-items-padding-x: var(--size-4-4);--setting-items-padding-y: var(--size-4-3);}
|
||
|
||
/* The path is the point of this row: let the input take the width the
|
||
short name leaves over. */.qa-export-save.svelte-1way66v {align-items:center;}
|
||
|
||
/* Phones stack the row and make controls full width; wrap so the path
|
||
and Save each get a full line. */.is-phone .qa-export-save.svelte-1way66v .setting-item-control:where(.svelte-1way66v) {flex-wrap:wrap;}.qa-export-save.svelte-1way66v .setting-item-info:where(.svelte-1way66v) {flex:0 0 auto;}.qa-export-save.svelte-1way66v input:where(.svelte-1way66v) {flex:1 1 auto;min-width:0;}`};function p$(r,t){ie(t,!0),Ae(r,YJ);let e={"user-script":"User script","conditional-script":"Conditional script",template:"Template file","capture-template":"Capture template"},n=pe(""),i=pe(Ze(new Set)),o=pe(Ze(new Set)),s=pe(Ze(Cq())),a=pe(null),l=pe(null),c=k(()=>Ad(t.allChoices)),d=k(()=>cq(f(c),f(n))),u=k(()=>dq(f(c),f(i))),p=k(()=>uq(t.allChoices,f(u),f(o))),m=k(()=>new Map(f(c).map(me=>[me.id,me.path.join(" / ")])));function h(me){let Fe=[];for(let ut of Ne(me))Ee(ut)&&Fe.push(ut.id,...h(ut));return Fe}function g(me,Fe){let ut=[me.id,...h(me)],Yt=new Set(f(i)),Kt=new Set(f(o));for(let qt of ut)Fe?(Yt.add(qt),Kt.delete(qt)):(Yt.delete(qt),Kt.add(qt));q(i,Yt,!0),(!Fe||f(o).size>0)&&q(o,Kt,!0)}function v(me){let Fe=f(c).find(Yt=>Yt.id===me);if(!Fe)return;let ut=f(i).has(me);g(Fe.choice,!ut),q(a,null)}function b(){for(let me of f(d))g(me.choice,!0);q(a,null)}function y(){q(i,new Set,!0),q(o,new Set,!0),q(a,null)}function C(me){let{missingChoiceIds:Fe,missingAssets:ut}=me;return Fe.length===0&&ut.length===0?null:{missingChoices:Fe,missingAssets:ut}}async function w(){if(f(u).length===0)return new ps.Notice("Select at least one choice to export."),null;try{let me=await xq(t.app,{choices:t.allChoices,rootChoiceIds:f(u),excludedChoiceIds:Array.from(f(o)),quickAddVersion:t.plugin.manifest.version});return q(a,C(me),!0),me}catch(me){return console.error(me),q(a,null),new ps.Notice(`Export failed: ${me?.message??String(me)}`),null}}async function T(){if(!f(l)){q(l,"copy");try{let me=await w();if(!me)return;let Fe=JSON.stringify(me.pkg,null,2);await navigator.clipboard.writeText(Fe),new ps.Notice(`Copied package (${me.pkg.choices.length} choice${me.pkg.choices.length===1?"":"s"}) to clipboard.`),f(a)?new ps.Notice("Package copied with warnings. Review details below."):t.close()}catch(me){console.error(me),new ps.Notice(`Copy failed: ${me?.message??String(me)}`)}finally{q(l,null)}}}async function P(){if(f(l))return;let me=f(s).trim();if(!me){new ps.Notice("Enter a file path before saving.");return}q(l,"save");try{let Fe=await w();if(!Fe)return;let{overwritten:ut}=await _q(t.app,Fe.pkg,me),Yt=Fe.pkg.choices.length,Kt=`${Yt} choice${Yt===1?"":"s"}`;new ps.Notice(ut?`Overwrote package (${Kt}) at '${me}'.`:`Saved package (${Kt}) to '${me}'.`),f(a)?new ps.Notice("Package saved with warnings. Review details below."):t.close()}catch(Fe){let ut=Fe?.message??String(Fe);if(ut.startsWith("Save cancelled:")){new ps.Notice("Save cancelled.");return}console.error(Fe),new ps.Notice(`Save failed: ${ut}`)}finally{q(l,null)}}var _=jJ(),I=R(_),D=R(I),N=R(D),K=R(N),ne=E(R(K),2);Ct(ne),le(ne,"spellcheck",!1),$(K);var H=E(K,2),O=E(H,2);$(N);var G=E(N,2),V=R(G),M=R(V);{var B=me=>{var Fe=NJ();A(me,Fe)},J=me=>{var Fe=bt(),ut=ae(Fe);gt(ut,17,()=>f(d),Yt=>Yt.id,(Yt,Kt)=>{var qt=BJ(),Qt=R(qt);Ct(Qt);var Se=E(Qt,2),st=re(Se,!0),yr=E(Se,2);{var zt=In=>{var ua=VJ(),Y=re(ua,!0);Q(ue=>ee(Y,ue),[()=>f(Kt).path.slice(0,-1).join(" \u203A ")]),A(In,ua)};z(yr,In=>{f(Kt).path.length>1&&In(zt)})}var Do=E(yr,2),Tl=re(Do,!0);$(qt),Q((In,ua)=>{sp(qt,`--qa-export-depth: ${f(Kt).depth}`),bd(Qt,In),ee(st,ua),ee(Tl,f(Kt).choice.type)},[()=>f(i).has(f(Kt).id),()=>f(Kt).path.at(-1)]),ge("change",Qt,()=>v(f(Kt).id)),A(Yt,qt)}),A(me,Fe)};z(M,me=>{f(d).length===0?me(B):me(J,-1)})}$(V),$(G),$(D);var te=E(D,2),W=E(R(te),2);gt(W,21,()=>[["Selected choices",f(p).rootCount],["Total packaged",f(p).totalChoices],["Auto-included",f(p).dependencyCount],["Scripts embedded",f(p).userScripts+f(p).conditionalScripts],["Templates embedded",f(p).templateFiles+f(p).captureTemplates]],([me,Fe])=>me,(me,Fe)=>{var ut=k(()=>vk(f(Fe),2));let Yt=()=>f(ut)[0],Kt=()=>f(ut)[1];var qt=UJ(),Qt=R(qt),Se=R(Qt),st=re(Se,!0);$(Qt);var yr=E(Qt,2),zt=R(yr),Do=re(zt,!0);$(yr),$(qt),Q(()=>{ee(st,Yt()),ee(Do,Kt())}),A(me,qt)}),$(W),$(te);var Z=E(te,2);{var se=me=>{var Fe=qJ(),ut=R(Fe),Yt=R(ut),Kt=R(Yt);Qe(Kt,{iconId:"alert-triangle"}),$(Yt),Xt(2),$(ut);var qt=E(ut,2),Qt=R(qt),Se=re(Qt);$(qt),$(Fe),Q(st=>ee(Se,`The following choice IDs were referenced but not found:
|
||
${st??""}`),[()=>f(p).missingChoiceIds.join(", ")]),A(me,Fe)};z(Z,me=>{f(p).missingChoiceIds.length>0&&me(se)})}var ce=E(Z,2);{var $e=me=>{var Fe=GJ(),ut=R(Fe),Yt=R(ut),Kt=R(Yt);Qe(Kt,{iconId:"alert-triangle"}),$(Yt),Xt(2),$(ut);var qt=E(ut,2),Qt=R(qt);{var Se=zt=>{var Do=zJ(),Tl=re(Do);Q(In=>ee(Tl,`Missing choices:
|
||
${In??""}`),[()=>f(a).missingChoices.map(In=>f(m).get(In)??In).join(", ")]),A(zt,Do)};z(Qt,zt=>{f(a).missingChoices.length>0&&zt(Se)})}var st=E(Qt,2);{var yr=zt=>{var Do=WJ(),Tl=E(ae(Do),2);gt(Tl,21,()=>f(a).missingAssets,In=>In.path,(In,ua)=>{var Y=HJ(),ue=R(Y),Pt=re(ue,!0),br=E(ue,2),Lo=re(br,!0);$(Y),Q(()=>{ee(Pt,f(ua).path),ee(Lo,e[f(ua).kind])}),A(In,Y)}),$(Tl),A(zt,Do)};z(st,zt=>{f(a).missingAssets.length>0&&zt(yr)})}$(qt),$(Fe),A(me,Fe)};z(ce,me=>{f(a)&&me($e)})}var Xe=E(ce,2),Ye=R(Xe),he=R(Ye),Re=E(R(he),2),Je=R(Re);Ct(Je);var ve=E(Je,2),Ve=R(ve);{var Ie=me=>{var Fe=xs("Saving\u2026");A(me,Fe)},ze=me=>{var Fe=xs("Save");A(me,Fe)};z(Ve,me=>{f(l)==="save"?me(Ie):me(ze,-1)})}$(ve),$(Re),$(he),$(Ye),$(Xe),$(I);var ct=E(I,2),Ke=R(ct),ot=E(Ke,2),or=R(ot);{var Ir=me=>{var Fe=xs("Copying\u2026");A(me,Fe)},Hn=me=>{var Fe=xs("Copy JSON");A(me,Fe)};z(or,me=>{f(l)==="copy"?me(Ir):me(Hn,-1)})}$(ot),$(ct),$(_),Q(()=>{ve.disabled=f(l)!==null,Ke.disabled=f(l)!==null,ot.disabled=f(l)!==null}),Zn(ne,()=>f(n),me=>q(n,me)),ge("click",H,b),ge("click",O,y),Zn(Je,()=>f(s),me=>q(s,me)),ge("click",ve,P),ge("click",Ke,function(...me){t.close?.apply(this,me)}),ge("click",ot,T),A(r,_),oe()}He(["click","change"]);var EE=class extends kq.Modal{constructor(e,n,i){super(e);this.plugin=n;this.choices=i;this.handle=null}onOpen(){this.modalEl.addClass("quickAddModal","qa-package-modal","packageExportModal"),this.setTitle("Export QuickAdd package"),this.handle=wi(this.contentEl,p$,{app:this.app,plugin:this.plugin,allChoices:this.choices,close:()=>this.close()},{what:"the package exporter"})}onClose(){this.handle?.destroy(),this.handle=null}};var tz=require("obsidian");var ay=require("obsidian");je();var O$=require("obsidian");Dr();Qo();er();ml();er();lt();Gr();function _E(r,t,e){if(!(!r||typeof r!="object")){if(Array.isArray(r)){t.onUnreadable?.();return}if(!e.has(r)){if(e.add(r),t.onChoice?.(r),uu(r))if(Array.isArray(r.choices))for(let n of r.choices)_E(n,t,e);else Wt(r.choices)&&t.onUnreadable?.();Xi(r)&&TE(ur(r.macro),t,e)}}}function TE(r,t,e){if(!Array.isArray(r)){Wt(r)&&t.onUnreadable?.();return}for(let n of r){if(!n||typeof n!="object")continue;if(Array.isArray(n)){t.onUnreadable?.();continue}t.onCommand?.(n);let i=n;(n.type==="Conditional"||Array.isArray(i.thenCommands)||Array.isArray(i.elseCommands))&&(TE(i.thenCommands,t,e),TE(i.elseCommands,t,e));let s=n,a=n.type==="NestedChoice"||s.choice&&typeof s.choice=="object"?s.choice:void 0;a&&_E(a,t,e)}}function m$(r,t){let e=new Set;if(Array.isArray(r.choices))for(let i of r.choices)_E(i,t,e);else t.onUnreadable?.();let n=r.macros;if(Array.isArray(n))for(let i of n)TE(ur(i),t,e);else Wt(n)&&t.onUnreadable?.()}function af(r){let t=!1;return m$(r,{onUnreadable:()=>{t=!0}}),t}function Sq(r,t){_E(r,{onChoice:t},new Set)}function lf(r,t){f$(r.settings,t)}function f$(r,t){m$(r,{onChoice:t})}function kE(r,t){m$(r,{onCommand:t})}function KJ(r){return r.type==="AIAssistant"}function SE(r,t,e){let n=0;return kE({choices:r},i=>{if(!KJ(i)||i.modelRef&&i.modelRef.name===i.model&&t.find(l=>l.id===i.modelRef?.providerId)?.models.some(l=>l.name===i.model)||!i.model||i.model==="Ask me")return;let o=t.find(a=>a.models.some(l=>l.name===i.model));if(!o?.id)return;let s={providerId:o.id,name:i.model};i.modelRef=s,n++,e?.(i,s)}),n}ye();Le();lt();tn();_m();Jt();Ac();Yi();g$();Qo();Dr();Jt();Za();function AE(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="Template"}function XJ(r){return r.fileExistsBehavior?r.fileExistsBehavior:r.setFileExistsBehavior?{kind:"apply",mode:cV(r.fileExistsMode)??"increment"}:r.incrementFileName?{kind:"apply",mode:"increment"}:{kind:"prompt"}}function IE(r){r.fileExistsBehavior=XJ(r),delete r.incrementFileName,delete r.setFileExistsBehavior,delete r.fileExistsMode}function df(r){if(r==null)return null;if(typeof r=="boolean")return{enabled:r};if(typeof r!="object")return null;let t=r;return{enabled:typeof t.enabled=="boolean"?t.enabled:void 0,direction:t.direction==="horizontal"||t.direction==="vertical"?t.direction:void 0,focus:typeof t.focus=="boolean"?t.focus:void 0}}function uf(r,t){let e=r.direction==="horizontal"?"horizontal":"vertical",n=typeof t=="string"&&t!=="default"?t:"default";return rn({location:r.enabled?"split":"tab",direction:e,focus:r.focus??!0,mode:n})}er();lt();Gr();Ac();nl();function v$(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Pq(r){if(AE(r)&&IE(r),r.type==="Capture"||r.type==="Template"){let i=r,o=df(i.openFileInNewTab);!i.fileOpening&&o&&(i.fileOpening=uf(o,i.openFileInMode))}let t=r.insertAfter;r.type==="Capture"&&v$(t)&&(t.insertAtEnd??(t.insertAtEnd=!1),t.createIfNotFound??(t.createIfNotFound=!1));let e=r.type==="Capture"?new Sc(r.name):r.type==="Template"?new Ks(r.name):void 0;if(!e)return;let n=r;for(let[i,o]of Object.entries(e)){if(o===void 0)continue;let s=n[i];s===void 0?n[i]=o:v$(s)&&v$(o)&&(n[i]={...o,...s})}uw(r)}function $E(r,t,e,n){Pq(r);let i=r.id,o=t.get(i)??i;r.id=o;let s=o!==i;if(r.type==="Macro"){let a=r;s&&rl(a.macro)&&(a.macro.id=Vt()),y$(ur(a.macro),t,e,s,n)}if(r.type==="Multi"){let a=r;Array.isArray(a.choices)&&(a.choices=a.choices.filter(l=>Ee(l)&&e.has(l.id)).map(l=>$E(l,t,e,n)))}return r}function y$(r,t,e,n,i){for(let o of Mt(r))if(Tr(o))switch(gB(o,i),n&&(o.id=Vt()),o.type){case"Choice":{let s=o,a=t.get(s.choiceId);a&&(s.choiceId=a);break}case"Conditional":{let s=o;y$(s.thenCommands,t,e,n,i),y$(s.elseCommands,t,e,n,i);break}case"NestedChoice":{let s=o;s.choice&&e.has(s.choice.id)?s.choice=$E(s.choice,t,e,i):Ee(s.choice)&&Sq(s.choice,Pq);break}default:break}}function FE(r,t){for(let e of r){if(!Ee(e))continue;if(e.id===t)return e;let n=FE(Ne(e),t);if(n)return n}}function $q(r,t,e){let n=FE(r,t);return n!==void 0&&Ne(n).some(i=>Ee(i)&&i.id===e)}function PE(r,t,e){if(!Array.isArray(t.choices)||r&&!Array.isArray(r.choices))return;let n=new Map;for(let o of t.choices)Ee(o)&&n.set(o.id,o);let i=[];for(let o of r?.choices??[]){let s=Ee(o)?n.get(o.id):void 0;if(!s){i.push(o);continue}o.type==="Multi"&&s.type==="Multi"&&PE(o,s,e),i.push(s),n.delete(s.id)}for(let o of n.values()){let s=e.get(o.id);o.type==="Multi"&&PE(s?.type==="Multi"?s:void 0,o,e),i.push(o)}t.choices=i}function w$(r,t){for(let e=0;e<r.length;e++){let n=r[e];if(Ee(n)){if(n.id===t.id)return r.splice(e,1,t),!0;if(w$(Ne(n),t))return!0}}return!1}function C$(r,t){for(let e=0;e<r.length;e++){let n=r[e];if(!Ee(n))continue;if(n.id===t)return r.splice(e,1),n;let i=C$(Ne(n),t);if(i)return i}}function x$(r,t,e){for(let n of r)if(Ee(n)){if(n.id===t&&n.type==="Multi")return E$(n,e);if(x$(Ne(n),t,e))return!0}return!1}function E$(r,t){if(!Array.isArray(r.choices)){if(vo(r))return!1;r.choices=[]}let e=r.choices.findIndex(n=>Ee(n)&&n.id===t.id);return e!==-1?r.choices.splice(e,1,t):r.choices.push(t),!0}function Fq(r,t){if(t.length===0)return null;let e=r,n=null;for(let i of t){let o=e.find(s=>Ee(s)&&s.type==="Multi"&&s.name===i);if(!o)return null;n=o,e=Ne(o)}return n}function ME(r,t){switch(r.type){case"Macro":{b$(ur(r.macro),t);break}case"Template":{let e=r,n=t.get(En(e.templatePath))??t.get(e.templatePath);n&&(e.templatePath=n);break}case"Capture":{let e=r,n=e.createFileIfItDoesntExist?.template;if(n){let o=t.get(En(n))??t.get(n);o&&(e.createFileIfItDoesntExist={...e.createFileIfItDoesntExist,template:o})}let i=e.format;if(i&&typeof i.format=="string"){let o=hE(i.format,t);o!==i.format&&(e.format={...i,format:o})}break}case"Multi":{r.choices?.forEach(n=>ME(n,t));break}default:break}}function Iq(r,t){let e=go(r),n=t.get(r)??t.get(e)??e;return n===r?void 0:n}function b$(r,t){for(let e of Mt(r))if(Tr(e))switch(e.type){case"UserScript":{let n=e,i=Iq(n.path,t);i&&(n.name===n.path?n.name=i:n.name.startsWith(`${n.path}::`)&&(n.name=i+n.name.slice(n.path.length)),n.path=i);break}case"Conditional":{let n=e;if(n.condition.mode==="script"&&n.condition.scriptPath){let i=Iq(n.condition.scriptPath,t);i&&(n.condition={...n.condition,scriptPath:i})}b$(n.thenCommands,t),b$(n.elseCommands,t);break}case"NestedChoice":{let n=e;n.choice&&ME(n.choice,t);break}default:break}}var T$={"user-script":{severity:"critical",label:"SCRIPT",description:"Runs custom JavaScript with full access to your vault and the network."},"conditional-script":{severity:"critical",label:"CONDITIONAL",description:"Runs custom JavaScript to decide which branch executes."},"bundled-script":{severity:"critical",label:"SCRIPT FILE",description:"Bundles a file that will be written to your vault and can be run as code."},"run-on-startup":{severity:"critical",label:"STARTUP",description:"Runs automatically every time Obsidian starts."},"mislabeled-executable":{severity:"critical",label:"EXECUTABLE",description:"A bundled file is run as code even though it is labeled a template."},"registers-command":{severity:"warning",label:"COMMAND",description:"Adds a command to the command palette."},"obsidian-command":{severity:"warning",label:"OBSIDIAN",description:"Triggers another Obsidian command."},ai:{severity:"warning",label:"AI",description:"Sends note content to your AI provider over the network."},"ai-tools":{severity:"critical",label:"AI TOOLS",description:"Lets an AI model read and write your vault: the script gives the model tools (functions) it calls with model-chosen arguments."},"capture-writes":{severity:"warning",label:"WRITES",description:"Writes captured text into your notes."},"template-write":{severity:"warning",label:"TEMPLATE",description:"Creates notes from a bundled template."},"overwrites-existing-choice":{severity:"warning",label:"OVERWRITES",description:"Replaces a choice that already exists in your vault."},"overwrites-existing-file":{severity:"warning",label:"OVERWRITES",description:"Overwrites a file that already exists in your vault."},"missing-reference":{severity:"warning",label:"MISSING",description:"References a file that is not bundled in this package."},"unknown-command":{severity:"warning",label:"UNKNOWN",description:"An unrecognised command type. Review it manually."},"editor-command":{severity:"info",label:"EDITOR",description:"Runs a built-in editor command."},"open-file":{severity:"info",label:"OPEN FILE",description:"Opens a file in your vault."}};function pf(r){return T$[r].severity}function _$(r){return T$[r].label}function k$(r){return T$[r].description}Le();Oa();lt();_m();Dr();Yi();Jt();Ac();Oa();Dr();Jt();ml();er();lt();Gr();var JJ=new Set(Object.values(jt));function ki(r){return r.filter(t=>!!t).join(" \u203A ")}function A$(r,t){return r.split("::")[0].trim()===t}function Mq(r,t,e){return A$(t,e)?ki(r):`${ki(r)} (${e})`}function ZJ(r){let t=r.name?.trim();return t&&t.length>0?t:String(r.type)}function eZ(r){if(r.mode==="script")return`script: ${r.scriptPath}${r.exportName?` (${r.exportName})`:""}`;let t=r.expectedValue!==void 0?` ${r.expectedValue}`:"";return`${r.variableName} ${r.operator}${t}`}function tZ(r){if(qn(r)){let t=Array.isArray(r.folder?.folders)?r.folder.folders:[];return[["file name format",r.fileNameFormat?.format],...t.map(e=>["folder",e])]}if(pl(r)){let t=r.propertyCapture?.property;return[["capture to",r.captureTo],["capture format",r.format?.format],["insert after",r.insertAfter?.after],["insert before",r.insertBefore?.before],["property name",t?.kind==="named"?t.format:void 0]]}return[]}function Rq(r){return typeof r=="string"&&$w(r).length>0}function Oq(r,t,e,n=!0){r.inlineScripts.push({setting:ki(t.slice(1)),text:e}),n&&(r.flags.add("user-script"),r.rows.push({flag:"user-script",severity:"critical",title:"Runs custom JavaScript written into a choice setting",detail:ki(t)}))}function rZ(r){let t=r.fileExistsBehavior;return!t||t.kind!=="apply"?!1:t.mode==="overwrite"||t.mode==="appendTop"||t.mode==="appendBottom"}function I$(r){let t=[],e=new Set(r.choices.map(n=>n.choice.id));for(let n of r.choices){let i=n.choice,o=ki(n.pathHint.slice(0,-1))||"Root",s={choiceId:i.id,name:i.name,type:i.type,location:o,registersCommand:!1,flags:new Set,commands:[],usages:[],rows:[],inlineScripts:[]};P$(i,s,[i.name],e,0),t.push(s)}return{choiceWalks:t}}function P$(r,t,e,n,i){if(r.command&&(t.registersCommand=!0,t.flags.add("registers-command")),Xi(r)&&(r.runOnStartup&&(t.flags.add("run-on-startup"),t.rows.push({flag:"run-on-startup",severity:"critical",title:"Runs automatically every time Obsidian starts",detail:ki(e)})),S$(ur(r.macro),t,e,n,i)),qn(r)&&(r.templatePath&&t.usages.push({choiceId:t.choiceId,path:En(r.templatePath),asScript:!1,impliedKind:"template",breadcrumb:ki([...e,"template"])}),rZ(r)&&t.flags.add("template-write")),pl(r)){t.flags.add("capture-writes");let s=r.createFileIfItDoesntExist;s?.enabled&&s.createWithTemplate&&s.template&&t.usages.push({choiceId:t.choiceId,path:En(s.template),asScript:!1,impliedKind:"capture-template",breadcrumb:ki([...e,"new-file template"])});for(let a of u$(r))t.usages.push({choiceId:t.choiceId,path:a,asScript:!1,impliedKind:"template",breadcrumb:ki([...e,"{{TEMPLATE}} include"])})}let o=new Set;for(let[s,a]of tZ(r))Rq(a)&&(Oq(t,[...e,s],a,!o.has(s)),o.add(s));if(uu(r)&&Array.isArray(r.choices))for(let s of r.choices)Ee(s)&&(n.has(s.id)||P$(s,t,[...e,s.name],n,i))}function S$(r,t,e,n,i){for(let o of Mt(r)){if(!Tr(o))continue;let s=ZJ(o),a=[...e,s],l={name:s,type:o.type,depth:i};switch(t.commands.push(l),o.type){case"UserScript":{let c=o;t.flags.add("user-script"),Object.assign(l,{flag:"user-script",scriptPath:c.path}),c.path&&(t.usages.push({choiceId:t.choiceId,path:go(c.path),asScript:!0,impliedKind:"user-script",breadcrumb:ki(a)}),t.rows.push({flag:"user-script",severity:"critical",title:"Runs custom JavaScript with full access to your vault and the network",detail:Mq(a,s,c.path),scriptPath:c.path}));break}case"Conditional":{let c=o,d=c.condition,u=d?eZ(d):void 0,p=d?.mode==="script"&&!!d.scriptPath;if(Object.assign(l,{flag:p?"conditional-script":void 0,scriptPath:p?d.scriptPath:void 0,summary:u}),p){let m=d.scriptPath;t.flags.add("conditional-script"),t.usages.push({choiceId:t.choiceId,path:go(m),asScript:!0,impliedKind:"conditional-script",breadcrumb:ki(a)}),t.rows.push({flag:"conditional-script",severity:"critical",title:"Runs custom JavaScript chosen by a condition",detail:Mq(a,s,m),scriptPath:m})}S$(c.thenCommands??[],t,[...a,"then"],n,i+1),S$(c.elseCommands??[],t,[...a,"else"],n,i+1);break}case"NestedChoice":{let c=o;c.choice&&P$(c.choice,t,[...a,c.choice.name],n,i+1);break}case"Obsidian":{let c=o;t.flags.add("obsidian-command"),t.rows.push({flag:"obsidian-command",severity:"warning",title:"Triggers another Obsidian command",detail:`${ki(a)}${c.commandId?` (${c.commandId})`:""}`});break}case"AIAssistant":{t.flags.add("ai"),t.rows.push({flag:"ai",severity:"warning",title:"Sends note content to your AI provider over the network",detail:ki(a)});break}case"EditorCommand":{t.flags.add("editor-command");break}case"OpenFile":{t.flags.add("open-file");let c=o.filePath;Rq(c)&&(l.flag="user-script",Oq(t,[...a,"file path"],c));break}case"Choice":case"Wait":break;default:{l.type=String(o.type),JJ.has(String(o.type))||(t.flags.add("unknown-command"),l.flag="unknown-command",t.rows.push({flag:"unknown-command",severity:"warning",title:"Unknown capability. Review it manually.",detail:`${ki(a)} (${String(o.type)})`}));break}}}}function nZ(r){return r==="user-script"||r==="conditional-script"}var iZ=/\.[cm]?js$/i;function oZ(r,t){let e;try{e=Js(t)}catch{return null}if(iZ.test(r))return e;if(!Ps(r))return null;let n=[];if(xt.test(r)){let{code:i}=Ws(e);i&&n.push(i)}for(let i of $w(e))n.push(i);return n.length>0?n.join(`
|
||
`):null}var sZ=/\bai\s*\.\s*(?:tools|agent|tool)\b|\btools\s*\.\s*(?:vault|workspace|system)\s*\(/;function aZ(r){return sZ.test(r)}var RE={critical:0,warning:1,info:2};function Lq(r){return Array.from(Bq(r,I$(r).choiceWalks).keys())}var lZ=10;function Nq(r){return cr(r.originalPath)}function $$(r){let t=Nq(r),e=go(r.originalPath);return e===t?[t]:[t,e]}function Vq(r){return r.assets.filter(t=>kx(t.originalPath))}function Bq(r,t){let e=new Map,n=a=>{if(!a.path)return;let l=e.get(a.path)??[];l.push(a),e.set(a.path,l)};for(let a of t)for(let l of a.usages)n(l);let i=new Map(Vq(r).flatMap(a=>$$(a).map(l=>[l,a]))),o=new Set,s=Array.from(e.keys());for(let a=0;a<lZ&&s.length>0;a++){let l=[];for(let c of s){if(o.has(c))continue;let d=i.get(c);if(!d||!Ps(c))continue;let u=(e.get(c)??[]).filter(g=>!g.asScript);if(u.length===0)continue;o.add(c);let p;try{p=Js(d.content)}catch{continue}let m=Xs(p);if(m.size===0)continue;let h=new Map;for(let g of u)h.has(g.choiceId)||h.set(g.choiceId,g);for(let g of m){for(let v of h.values())n({choiceId:v.choiceId,path:g,asScript:!1,impliedKind:"template",breadcrumb:`${v.breadcrumb} \u203A {{TEMPLATE}} include`});o.has(g)||l.push(g)}}s=l}return e}function cZ(r){let t=r.length;if(t===0)return 0;let e=0;return r.endsWith("==")?e=2:r.endsWith("=")&&(e=1),Math.max(0,Math.floor(t*3/4)-e)}function dZ(r,t){return RE[pf(r)]-RE[pf(t)]}function Uq(r,t,e){let{choiceWalks:n}=I$(t),i=new Set(Zt(r).map(_=>_.id)),o=Bq(t,n),s=new Set;for(let[_,I]of o)I.some(D=>D.asScript)&&s.add(_);let a=new Set(Vq(t).flatMap($$)),l=new Map(t.assets.map(_=>[_.originalPath,oZ(Nq(_),_.content)])),c=t.assets.map(_=>{let I=$$(_),D=a.has(I[0]),N=D?I.flatMap(H=>o.get(H)??[]):[],K=I.some(H=>s.has(H)),ne=K||l.get(_.originalPath)!=null;return{originalPath:_.originalPath,kind:_.kind,bundled:!0,executable:K,requiresReview:ne,exists:D&&(I.some(H=>e.has(H))||e.has(_.originalPath)),sizeBytes:cZ(_.content),orphan:N.length===0,referencedBy:N}}),d=n.map(_=>{let I=i.has(_.choiceId),D=Array.from(_.flags);return I&&D.push("overwrites-existing-choice"),D.sort(dZ),{choiceId:_.choiceId,name:_.name,type:_.type,location:_.location,exists:I,registersCommand:_.registersCommand,flags:D,commands:_.commands,inlineScripts:_.inlineScripts}}),u=[];for(let[_,I]of o){if(a.has(_)||e.has(_))continue;let D=I.some(N=>N.asScript);u.push({path:_,asScript:D,breadcrumb:I[0]?.breadcrumb??_})}let p=c.filter(_=>_.orphan).map(_=>_.originalPath),m=[];for(let _ of n)for(let I of _.rows)m.push(I);for(let _ of c)_.executable&&(nZ(_.kind)||m.push({flag:"mislabeled-executable",severity:"critical",title:"Runs a file as code even though it is labeled a template",detail:_.originalPath,scriptPath:_.originalPath}));for(let _ of c)_.requiresReview&&(_.executable||m.push({flag:"bundled-script",severity:"critical",title:"Bundles a file that will be written to your vault and can be run as code",detail:_.originalPath,scriptPath:_.originalPath}));for(let _ of c){let I=l.get(_.originalPath);!I||!aZ(I)||m.push({flag:"ai-tools",severity:"critical",title:"Lets an AI model read and write your vault",detail:_.originalPath,scriptPath:_.originalPath})}let h=d.filter(_=>_.registersCommand).length;h>0&&m.push({flag:"registers-command",severity:"warning",title:"Adds commands to the command palette",detail:`${h} choice${h===1?"":"s"}`});let g=d.filter(_=>_.exists).length;g>0&&m.push({flag:"overwrites-existing-choice",severity:"warning",title:"Replaces choices that already exist in your vault",detail:`${g} choice${g===1?"":"s"}`});let v=c.filter(_=>_.exists).length;if(v>0&&m.push({flag:"overwrites-existing-file",severity:"warning",title:"Overwrites existing files in your vault",detail:`${v} file${v===1?"":"s"}`}),u.length>0){let _=u.filter(I=>I.asScript).length;m.push({flag:"missing-reference",severity:_>0?"critical":"warning",title:_>0?"References scripts that are not bundled, so they run from whatever exists at those paths after import":"References files that are not bundled and not in your vault",detail:`${u.length} reference${u.length===1?"":"s"}`})}m.sort((_,I)=>RE[_.severity]-RE[I.severity]);let b=c.filter(_=>_.requiresReview).map(_=>_.originalPath),y=s.size,C=n.some(_=>_.flags.has("run-on-startup")),w=m.filter(_=>_.severity==="critical").length,T=m.filter(_=>_.severity==="warning").length,P={hasCritical:w>0,hasWarning:T>0,criticalCount:w,warningCount:T,runsOnStartup:C,scriptCount:y,registersCommandCount:h,overwritesChoices:g,overwritesFiles:v,missingCount:u.length};return{quickAddVersion:t.quickAddVersion,createdAt:t.createdAt,choiceCount:t.choices.length,fileCount:t.assets.length,choices:d,files:c,capabilityRows:m,missingReferences:u,orphanAssets:p,criticalScriptPaths:b,summary:P}}var Dq=1e5;function uZ(r){return typeof TextEncoder<"u"?new TextEncoder().encode(r).length:r.length}function pZ(r){if(r.length<1e3)return!1;let t=0,e=1,n=0;for(let o=0;o<r.length;o++)r[o]===`
|
||
`?(n>t&&(t=n),n=0,e++):n++;n>t&&(t=n);let i=r.length/e;return t>1e3||i>250}function F$(r){let t=r.length>Dq,e=t?r.slice(0,Dq):r;return{found:!0,text:e,truncated:t,sizeBytes:uZ(r),looksMinified:pZ(e)}}function OE(r,t){let e=r.assets.find(n=>n.originalPath===t);if(!e)return{found:!1,text:"",truncated:!1,sizeBytes:0,looksMinified:!1,error:"File is not bundled in this package."};try{return F$(Js(e.content))}catch(n){return{found:!0,text:"",truncated:!1,sizeBytes:0,looksMinified:!1,error:n instanceof Error?n.message:String(n)}}}function DE(r){return r.summary.hasCritical}function qq(r,t,e){let n=r.criticalScriptPaths.filter(o=>!t.has(o)).length,i=r.choices.filter(o=>o.inlineScripts.length>0&&!e.has(o.choiceId)).length;return n+i}Gr();Dr();er();lt();function ry(r){let t;try{t=JSON.parse(r)}catch(o){throw new Error(`Package content is not valid JSON: ${o?.message??o}`)}if(!yq(t))throw new Error("Content is not a valid QuickAdd package.");if(t.schemaVersion>1)throw new Error(`Package schema version ${t.schemaVersion} is newer than this plugin supports (${1}).`);let e=mZ(t.assets);if(e!==null)throw new Error(`Package contains duplicate asset path "${e}". Each asset must have a unique path.`);let n=fZ(t.choices);if(n!==null)throw new Error(`Package contains conflicting definitions for choice "${n}". Each choice id must describe the same choice everywhere it appears.`);let i=hZ(t.choices);if(i!==null)throw new Error(`Package choice "${i}" names a parent that does not list it as a child. Each parented choice must appear inside its parent.`);return t}function mZ(r){let t=new Set;for(let e of r){let n=cr(e.originalPath??"");if(t.has(n))return e.originalPath;t.add(n)}return null}function fZ(r){let t=new Map,e=null,n=i=>{if(e!==null||!i||typeof i!="object")return;let o=i.id;if(typeof o=="string"){let s=R$(i),a=t.get(o);if(a===void 0)t.set(o,s);else if(a!==s){e=o;return}}if(i.type==="Multi"){let s=i;if(Array.isArray(s.choices))for(let a of s.choices)n(a)}i.type==="Macro"&&M$(Mt(ur(i.macro)),n)};for(let i of r){if(e!==null)break;n(i?.choice)}return e}function M$(r,t){if(Array.isArray(r)){for(let e of r)if(e){if(e.type==="NestedChoice")t(e.choice);else if(e.type==="Conditional"){let n=e;M$(n.thenCommands,t),M$(n.elseCommands,t)}}}}function R$(r){if(r===null||typeof r!="object"){let n=JSON.stringify(r);return n===void 0?"\0undefined":n}if(Array.isArray(r))return`[${r.map(R$).join(",")}]`;let t=r;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${R$(t[n])}`).join(",")}}`}function hZ(r){let t=new Map(r.map(e=>[e.choice.id,e]));for(let e of r){let n=e.parentChoiceId;if(n===null)continue;let i=t.get(n);if(!i)continue;let o=i.choice;if(!Ne(o).some(a=>a?.id===e.choice.id))return e.choice.id}return null}async function LE(r,t){if(Ut(t))throw new Error(`Refusing to read a package outside the vault: "${t}".`);let e=(0,O$.normalizePath)(t.trim());if(!e)throw new Error("Package path cannot be empty.");if(!await r.vault.adapter.exists(e))throw new Error(`Package file not found: ${e}`);let i=await r.vault.adapter.read(e);return{pkg:ry(i),path:e}}async function NE(r,t,e){let n=new Map(Zt(t).map(s=>[s.id,s])),i=e.choices.map(s=>({choiceId:s.choice.id,name:s.choice.name,parentChoiceId:s.parentChoiceId,pathHint:s.pathHint??[],exists:n.has(s.choice.id)})),o=[];for(let s of e.assets){let a=Ut(s.originalPath)?!1:await r.vault.adapter.exists(s.originalPath);o.push({originalPath:s.originalPath,exists:a,kind:s.kind})}return{choiceConflicts:i,assetConflicts:o}}async function mf(r,t,e){let n=new Set([...e.assets.flatMap(a=>kx(a.originalPath)?[a.originalPath,cr(a.originalPath)]:[]),...Lq(e)]),i=new Set;await Promise.all(Array.from(n,async a=>{a&&(Ut(a)||await zq(r,a)&&i.add(a))}));let o=Uq(t,e,i),{summary:s}=o;return S.logMessage(`QuickAdd import preview: choices=${o.choiceCount} files=${o.fileCount} scripts=${s.scriptCount} runOnStartup=${s.runsOnStartup} registersCommands=${s.registersCommandCount} overwritesChoices=${s.overwritesChoices} overwritesFiles=${s.overwritesFiles} missing=${s.missingCount} critical=${s.criticalCount} warning=${s.warningCount}`),o}function gZ(r){let e=(r??"").trim();if(!e)throw new Error("Package asset has an empty destination path.");let n=e.replace(/\\/g,"/");if(n.startsWith("/")||/^[a-zA-Z]:/.test(n))throw new Error(`Refusing to import asset to an absolute path outside the vault: "${n}".`);let i=(0,O$.normalizePath)(e);if(!i||i.trim()==="")throw new Error("Package asset has an empty destination path.");let o=i.split("/").filter(a=>a.length>0);if(o.some(a=>a===".."))throw new Error(`Refusing to import asset with a path-traversal segment ("..") in: "${i}".`);if(o.find(a=>a.startsWith(".")&&!a.startsWith("..%")))throw new Error(`Refusing to import asset into a config directory: "${i}".`);return i}async function VE(r){let{app:t,existingChoices:e,pkg:n}=r,i=new Map(r.choiceDecisions.map(O=>[O.choiceId,O.mode])),o=new Map(r.assetDecisions.map(O=>[O.originalPath,O])),s=new Map(n.choices.map(O=>[O.choice.id,O])),a=bE(n.assets,"import"),l=new Set(n.choices.filter(O=>i.get(O.choice.id)!=="skip").map(O=>O.choice.id)),c=new Map,d=new Set,u=new Map,p=O=>{if(!l.has(O))return!1;let G=c.get(O);if(G!==void 0)return G;if(d.has(O))return c.set(O,!1),!1;d.add(O);try{let V=s.get(O)?.parentChoiceId,M=i.get(O)==="duplicate"||!!(V&&(i.get(V)==="duplicate"||l.has(V)&&p(V)));return c.set(O,M),M}finally{d.delete(O)}};for(let O of n.choices){if(!l.has(O.choice.id))continue;let V=p(O.choice.id)?Vt():O.choice.id;u.set(O.choice.id,V)}let m=new Set(Zt(e).map(O=>O.id)),h=n.choices.filter(O=>l.has(O.choice.id)&&(i.get(O.choice.id)??"import")==="import"&&u.get(O.choice.id)===O.choice.id&&m.has(O.choice.id));if(h.length>0){let O=h.map(G=>`"${G.choice.name}"`).join(", ");throw new Error(`Already in this vault: ${O}. Import only adds new choices, so choose overwrite, duplicate or skip for ${h.length===1?"it":"them"}.`)}let g=ke(e),v=[],b=[],y=[],C=new Map;for(let O of n.choices){if(!l.has(O.choice.id)){y.push(O.choice.id);continue}let G=ke(O.choice),V=$E(G,u,l,{secretOptionNamesByPath:a,stripUnknownStringSettings:!0});C.set(O.choice.id,V)}let w=n.assets.map(O=>{let V=o.get(O.originalPath)?.destinationPath?.trim(),M=gZ(V||O.originalPath);return{asset:O,destinationPath:M}}),T=new Map;for(let{asset:O,destinationPath:G}of w)T.set(O.originalPath,G),T.set(cr(O.originalPath),G);for(let O of C.values())ME(O,T);r.aiProviders?.length&&SE(Array.from(C.values()),r.aiProviders);let P=new Set,_=[],I=new Map;for(let O of n.choices){let G=O.choice.id,V=O.parentChoiceId;if(!l.has(G)||!V||!l.has(V))continue;let M=u.get(G)??G,B=u.get(V)??V;if($q(g,B,M))continue;let J=C$(g,M);J?.type==="Multi"&&I.set(M,J)}for(let O of n.choices){let G=O.choice.id;if(!l.has(G)||P.has(G))continue;let V=C.get(G);if(!V)continue;let M=V.id,B=i.get(G)??"import",J=O.parentChoiceId;if(J&&l.has(J)?C.get(J):null){P.add(G),_.push({finalId:M});continue}if(V.type==="Multi"){let Z=FE(g,M);PE(Z?.type==="Multi"?Z:void 0,V,I)}if((B==="overwrite"||B==="import")&&w$(g,V)){b.push(M),P.add(G);continue}if(J){let Z=u.get(J)??J;if(x$(g,Z,V)){v.push(M),P.add(G);continue}let ce=Fq(g,O.pathHint.slice(0,-1));if(ce&&E$(ce,V)){v.push(M),P.add(G);continue}S.logWarning(`QuickAdd import: could not locate parent for '${O.choice.name}'. Adding to root.`)}let W=g.findIndex(Z=>Ee(Z)&&Z.id===M);W!==-1?(g.splice(W,1,V),b.push(M)):(g.push(V),v.push(M)),P.add(G)}for(let{finalId:O}of _)m.has(O)?b.push(O):v.push(O);let D=[],N=[],K=await yZ(t),ne=new Map;for(let{asset:O,destinationPath:G}of w){if(o.get(O.originalPath)?.mode==="skip")continue;let V=K?G.toLowerCase():G,M=ne.get(V);if(M)throw new Error(`Refusing to import: assets "${M.originalPath}" and "${O.originalPath}" resolve to the same destination ("${G}"). Rename one so each imported file is unique.`);ne.set(V,{originalPath:O.originalPath,destinationPath:G})}for(let{destinationPath:O}of w)await cf(t,O);let H=[];for(let{asset:O,destinationPath:G}of w){let V=o.get(O.originalPath),M=await zq(t,G);if((V?.mode??(M?"overwrite":"write"))==="skip"){N.push(G);continue}if(M&&(await t.vault.adapter.stat(G))?.type==="folder")throw new Error(`Refusing to import: "${G}" is a folder. Choose a file path for "${O.originalPath}".`);H.push({asset:O,destinationPath:G})}for(let{asset:O,destinationPath:G}of H){await CE(t,G);let V=vZ(O,G,T);await t.vault.adapter.write(G,V),D.push(G)}return{updatedChoices:g,addedChoiceIds:v,overwrittenChoiceIds:b,skippedChoiceIds:y,writtenAssets:D,skippedAssets:N}}function vZ(r,t,e){let n=Js(r.content);return!(r.kind==="template"||r.kind==="capture-template")||!Ps(t)||xt.test(t)&&Ws(n).code?n:hE(n,e)}async function zq(r,t){try{return await r.vault.adapter.exists(t)}catch{return!1}}async function yZ(r){let t=r.vault.configDir;if(!t)return!1;let e=t===t.toLowerCase()?t.toUpperCase():t.toLowerCase();if(e===t)return!1;try{return await r.vault.adapter.exists(e)}catch{return!1}}var BE=require("obsidian");function ny(r,t){return t&&(0,BE.setTooltip)(r,t),{update(e){(0,BE.setTooltip)(r,e??"")},destroy(){(0,BE.setTooltip)(r,"")}}}var bZ=F("<span> </span>"),wZ={hash:"svelte-vwgq2t",code:".qa-capability-flair.svelte-vwgq2t {margin-inline-start:0;cursor:help;}"};function iy(r,t){ie(t,!0),Ae(r,wZ);let e=k(()=>pf(t.flag)),n=k(()=>_$(t.flag)),i=k(()=>k$(t.flag));var o=bZ();let s;var a=re(o,!0);Ft(o,(l,c)=>ny?.(l,c),()=>f(i)),Q(()=>{s=Ge(o,1,"flair qa-capability-flair svelte-vwgq2t",null,s,{"qa-flair-critical":f(e)==="critical","qa-flair-warning":f(e)==="warning"}),ee(a,f(n))}),A(r,o),oe()}var CZ=F('<span class="qa-import-banner-detail svelte-1l3m8bg"> </span>'),xZ=F('<li class="svelte-1l3m8bg"><!> <span class="qa-import-banner-title svelte-1l3m8bg"> </span> <!></li>'),EZ=F(`<p class="qa-import-banner-note svelte-1l3m8bg">Importing doesn't run startup macros. They first run the next time
|
||
Obsidian starts or you reload QuickAdd.</p>`),TZ=F('<section class="callout qa-import-banner svelte-1l3m8bg" aria-labelledby="qa-import-banner-title"><div class="callout-title"><div class="callout-icon"><!></div> <div class="callout-title-inner" id="qa-import-banner-title">What this package can do</div></div> <div class="callout-content svelte-1l3m8bg"><ul class="qa-import-banner-rows svelte-1l3m8bg"></ul> <!></div></section>'),_Z={hash:"svelte-1l3m8bg",code:`.qa-import-banner.svelte-1l3m8bg {margin:0;}
|
||
|
||
/* Setting-row text size, so the callout sits level with the cards. */.qa-import-banner.svelte-1l3m8bg .callout-content:where(.svelte-1l3m8bg) {padding-top:var(--size-4-2);font-size:var(--font-ui-small);}.qa-import-banner-rows.svelte-1l3m8bg {list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:var(--size-4-2);}
|
||
|
||
/* The flair is an inline lead-in to the sentence, so long titles wrap
|
||
full-width under it instead of leaving a dead column beside it. */.qa-import-banner-rows.svelte-1l3m8bg li:where(.svelte-1l3m8bg) {line-height:var(--line-height-tight);}.qa-import-banner-title.svelte-1l3m8bg {margin-inline-start:var(--size-4-1);}.qa-import-banner-detail.svelte-1l3m8bg {display:block;margin-top:var(--size-2-1);font-size:var(--font-ui-smaller);color:var(--text-muted);overflow-wrap:anywhere;}.qa-import-banner-note.svelte-1l3m8bg {margin:var(--size-4-3) 0 0;font-size:var(--font-ui-smaller);color:var(--text-muted);}`};function D$(r,t){ie(t,!0),Ae(r,_Z);let e=k(()=>t.preview.summary.hasCritical);var n=TZ(),i=R(n),o=R(i),s=R(o);{let u=k(()=>f(e)?"zap":"alert-triangle");Qe(s,{get iconId(){return f(u)}})}$(o),Xt(2),$(i);var a=E(i,2),l=R(a);gt(l,21,()=>t.preview.capabilityRows,u=>u.flag+u.detail,(u,p)=>{var m=xZ(),h=R(m);iy(h,{get flag(){return f(p).flag}});var g=E(h,2),v=re(g,!0),b=E(g,2);{var y=C=>{var w=CZ(),T=re(w,!0);Q(()=>ee(T,f(p).detail)),A(C,w)};z(b,C=>{f(p).detail&&C(y)})}$(m),Q(()=>ee(v,f(p).title)),A(u,m)}),$(l);var c=E(l,2);{var d=u=>{var p=EZ();A(u,p)};z(c,u=>{t.preview.summary.runsOnStartup&&u(d)})}$(a),$(n),Q(()=>le(n,"data-callout",f(e)?"danger":"warning")),A(r,n),oe()}var kZ=F('<p class="qa-code-preview-note mod-error svelte-azzakv"> </p>'),SZ=F(`<p class="qa-code-preview-note mod-warning svelte-azzakv">Minified: cannot be visually reviewed. Import only if you trust
|
||
the source.</p>`),AZ=F('<p class="qa-code-preview-note mod-warning svelte-azzakv"> </p>'),IZ=F('<!> <span class="qa-visually-hidden"> </span> <pre tabindex="0" role="region"> </pre> <!>',1),PZ=F('<div class="qa-code-preview svelte-azzakv"><!></div>'),$Z={hash:"svelte-azzakv",code:`.qa-code-preview.svelte-azzakv {display:flex;flex-direction:column;gap:var(--size-4-2);}.qa-code-preview-note.svelte-azzakv {margin:0;font-size:var(--font-ui-smaller);}.qa-code-preview-note.mod-error.svelte-azzakv {color:var(--text-error);}
|
||
|
||
/* Obsidian's code-block look. The card already uses --code-background, so
|
||
the block sits on the modal background instead to stay distinct. */.qa-code-preview-code.svelte-azzakv {margin:0;max-height:240px;overflow:auto;padding:var(--size-4-3) var(--size-4-4);border-radius:var(--code-radius);background-color:var(--background-primary);color:var(--code-normal);font-family:var(--font-monospace);font-size:var(--code-size);line-height:var(--line-height-normal);white-space:pre;tab-size:4;user-select:text;}.qa-code-preview-code.mod-wrap.svelte-azzakv {white-space:pre-wrap;overflow-wrap:anywhere;}.qa-code-preview-code.svelte-azzakv:focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:-2px;}`};function oy(r,t){let e=Ri();ie(t,!0),Ae(r,$Z);let n=X(t,"wrap",3,!1),i=`${e}-label`;var o=PZ(),s=R(o);{var a=c=>{var d=kZ(),u=re(d);Q(()=>ee(u,`Preview unavailable: ${t.content.error??""}`)),A(c,d)},l=c=>{var d=IZ(),u=ae(d);{var p=w=>{var T=SZ();A(w,T)};z(u,w=>{t.content.looksMinified&&w(p)})}var m=E(u,2),h=re(m,!0),g=E(m,2);let v;var b=re(g,!0),y=E(g,2);{var C=w=>{var T=AZ(),P=re(T);Q(()=>ee(P,`Preview truncated. The full ${t.executable?"script will run":"file will be imported"}.`)),A(w,T)};z(y,w=>{t.content.truncated&&w(C)})}Q(()=>{le(m,"id",i),ee(h,t.label),v=Ge(g,1,"qa-code-preview-code svelte-azzakv",null,v,{"mod-wrap":n()}),le(g,"aria-labelledby",i),ee(b,t.content.text)}),A(c,d)};z(s,c=>{t.content.error?c(a):c(l,-1)})}$(o),A(r,o),oe()}var FZ=F('<span class="flair qa-import-file-flair qa-flair-critical svelte-4j5ctu">Executable</span>'),MZ=F('<span class="flair qa-import-file-flair svelte-4j5ctu">Unused</span>'),RZ=F('<span class="qa-import-reviewed"><!> Reviewed</span>'),OZ=F('<span class="qa-import-file-folder svelte-4j5ctu">The destination is a folder. Add a file name.</span>'),DZ=F("<span> </span>"),LZ=F(`<div class="setting-item-description mod-warning" role="note">Won't be written. Any choice that uses this script will run
|
||
whatever file already exists at this path after import, not the
|
||
contents you reviewed.</div>`),NZ=F("<option>Overwrite</option>"),VZ=F('<div class="qa-import-file-preview svelte-4j5ctu"><!></div>'),BZ=F('<div class="setting-items qa-import-file"><div class="setting-item qa-import-file-main svelte-4j5ctu"><div class="setting-item-info"><div class="setting-item-name qa-import-file-name svelte-4j5ctu"><span class="qa-import-file-icon svelte-4j5ctu"><!></span> <span class="qa-import-file-label svelte-4j5ctu"> </span> <!> <!> <!></div> <div class="setting-item-description"><!> </div> <!> <button type="button" class="qa-link-button qa-import-file-toggle svelte-4j5ctu"><span><!></span> <span> </span></button></div> <div class="setting-item-control"><label class="qa-visually-hidden"> </label> <select class="dropdown"><option>Write</option><!><option>Skip</option></select></div> <div><div class="qa-import-file-preview-inner svelte-4j5ctu"><!></div></div></div> <div class="setting-item qa-import-file-destination svelte-4j5ctu"><div class="setting-item-info svelte-4j5ctu"><label class="setting-item-name">Destination <span class="qa-visually-hidden"> </span></label></div> <div class="setting-item-control"><input type="text" placeholder="vault/path/to/file" class="svelte-4j5ctu"/></div></div></div>'),UZ={hash:"svelte-4j5ctu",code:`.qa-import-file-name.svelte-4j5ctu {display:flex;flex-wrap:wrap;align-items:center;gap:var(--size-4-1) var(--size-4-2);}.qa-import-file-icon.svelte-4j5ctu {display:inline-flex;color:var(--text-muted);--icon-size: var(--icon-s);}.qa-import-file-label.svelte-4j5ctu {min-width:0;overflow-wrap:anywhere;}.qa-import-file-flair.svelte-4j5ctu {margin-inline-start:0;cursor:help;}.qa-import-file-folder.svelte-4j5ctu {color:var(--text-error);}
|
||
|
||
/* The path is the point of this row: let the input take the width the
|
||
short "Destination" name leaves over. */.qa-import-file-destination.svelte-4j5ctu {align-items:center;}.qa-import-file-destination.svelte-4j5ctu .setting-item-info:where(.svelte-4j5ctu) {flex:0 0 auto;}.qa-import-file-destination.svelte-4j5ctu input:where(.svelte-4j5ctu) {flex:1 1 auto;min-width:0;}.qa-import-file-destination.svelte-4j5ctu input:where(.svelte-4j5ctu):disabled {opacity:0.5;cursor:not-allowed;}
|
||
|
||
/* The preview opens under the row at full width. No row gap, so the
|
||
collapsed preview adds no space; the preview pads itself instead. */.qa-import-file-main.svelte-4j5ctu {flex-wrap:wrap;row-gap:0;}.qa-import-file-toggle.svelte-4j5ctu {margin-top:var(--size-4-1);font-size:var(--font-ui-smaller);}.qa-import-file-preview-wrap.svelte-4j5ctu {flex-basis:100%;min-width:0;}
|
||
|
||
/* Pulls the glyph's built-in side bearing back to the text edge. */.qa-import-file-chevron.svelte-4j5ctu {display:inline-flex;margin-inline-start:-3px;transition:transform 150ms ease;}.qa-import-file-chevron.open.svelte-4j5ctu {transform:rotate(90deg);}.qa-import-file-preview-wrap.svelte-4j5ctu {display:grid;grid-template-rows:0fr;transition:grid-template-rows 200ms ease;}.qa-import-file-preview-wrap.open.svelte-4j5ctu {grid-template-rows:1fr;}.qa-import-file-preview-inner.svelte-4j5ctu {overflow:hidden;min-height:0;}.qa-import-file-preview.svelte-4j5ctu {padding-top:var(--size-4-3);}
|
||
|
||
@media (prefers-reduced-motion: reduce) {.qa-import-file-chevron.svelte-4j5ctu,
|
||
.qa-import-file-preview-wrap.svelte-4j5ctu {transition:none;}
|
||
}`};function L$(r,t){let e=Ri();ie(t,!0),Ae(r,UZ);let n=X(t,"destinationIsFolder",3,!1),i=X(t,"reviewed",3,!1),o=pe(!1),s=k(()=>f(o)?OE(t.pkg,t.file.originalPath):null),a=`${e}-preview`,l=`${e}-destination`,c=`${e}-action`,d=`${e}-folder`,u=k(()=>t.file.originalPath.split("/").pop()??t.file.originalPath);function p(Se){return Se<1024?`${Se} B`:Se<1024*1024?`${(Se/1024).toFixed(1)} KB`:`${(Se/(1024*1024)).toFixed(1)} MB`}function m(){q(o,!f(o)),f(o)&&t.file.requiresReview&&t.onReviewed(t.file.originalPath)}function h(Se){t.onPathInput(Se.currentTarget.value)}function g(Se){t.onModeChange(Se.currentTarget.value)}var v=BZ(),b=R(v),y=R(b),C=R(y),w=R(C),T=R(w);{let Se=k(()=>t.destinationExists?"file-warning":"file-plus");Qe(T,{get iconId(){return f(Se)}})}$(w);var P=E(w,2),_=re(P,!0),I=E(P,2);{var D=Se=>{var st=FZ();Ft(st,(yr,zt)=>ny?.(yr,zt),()=>"Runs as code when its choice runs. It can read, change, or delete files in your vault and access the network."),A(Se,st)};z(I,Se=>{t.file.executable&&Se(D)})}var N=E(I,2);{var K=Se=>{var st=MZ();Ft(st,(yr,zt)=>ny?.(yr,zt),()=>"Bundled in this package but not referenced by any choice."),A(Se,st)};z(N,Se=>{t.file.orphan&&Se(K)})}var ne=E(N,2);{var H=Se=>{var st=RZ(),yr=R(st);Qe(yr,{iconId:"check",size:14}),Xt(),$(st),A(Se,st)};z(ne,Se=>{i()&&t.mode!=="skip"&&t.file.requiresReview&&Se(H)})}$(C);var O=E(C,2),G=R(O);{var V=Se=>{var st=OZ();Q(()=>le(st,"id",d)),A(Se,st)},M=Se=>{var st=DZ();let yr;var zt=re(st,!0);Q(()=>{yr=Ge(st,1,"",null,yr,{"mod-warning":t.destinationExists}),ee(zt,t.destinationExists?"Will overwrite":"New file")}),A(Se,st)};z(G,Se=>{n()?Se(V):Se(M,-1)})}var B=E(G);$(O);var J=E(O,2);{var te=Se=>{var st=LZ();A(Se,st)};z(J,Se=>{t.file.requiresReview&&t.mode==="skip"&&Se(te)})}var W=E(J,2),Z=R(W);let se;var ce=R(Z);Qe(ce,{iconId:"chevron-right",size:14}),$(Z);var $e=E(Z,2),Xe=re($e,!0);$(W),$(y);var Ye=E(y,2),he=R(Ye),Re=re(he),Je=E(he,2),ve=R(Je);ve.value=ve.__value="write";var Ve=E(ve);{var Ie=Se=>{var st=NZ();st.value=st.__value="overwrite",A(Se,st)};z(Ve,Se=>{t.destinationExists&&Se(Ie)})}var ze=E(Ve);ze.value=ze.__value="skip",$(Je);var ct;Ll(Je),$(Ye);var Ke=E(Ye,2);let ot;var or=R(Ke),Ir=R(or);{var Hn=Se=>{var st=VZ(),yr=R(st);{let zt=k(()=>`Contents of ${t.file.originalPath}`);oy(yr,{get content(){return f(s)},get label(){return f(zt)},get executable(){return t.file.executable}})}$(st),A(Se,st)};z(Ir,Se=>{f(s)&&Se(Hn)})}$(or),$(Ke),$(b);var me=E(b,2),Fe=R(me),ut=R(Fe),Yt=E(R(ut)),Kt=re(Yt);$(ut),$(Fe);var qt=E(Fe,2),Qt=R(qt);Ct(Qt),$(qt),$(me),$(v),Q(Se=>{ee(_,f(u)),ee(B,` \xB7 ${Se??""}`),le(W,"aria-expanded",f(o)),le(W,"aria-controls",a),se=Ge(Z,1,"qa-import-file-chevron svelte-4j5ctu",null,se,{open:f(o)}),ee(Xe,f(o)?"Hide contents":"View contents"),le(he,"for",c),ee(Re,`Action for ${t.file.originalPath??""}`),le(Je,"id",c),ct!==(ct=t.mode)&&(Je.value=(Je.__value=ct)??"",Dl(Je,ct)),ot=Ge(Ke,1,"qa-import-file-preview-wrap svelte-4j5ctu",null,ot,{open:f(o)}),le(Ke,"id",a),le(ut,"for",l),ee(Kt,`for ${t.file.originalPath??""}`),le(Qt,"id",l),Jn(Qt,t.destinationPath),le(Qt,"aria-invalid",n()),le(Qt,"aria-describedby",n()?d:void 0),Qt.disabled=t.mode==="skip"},[()=>p(t.file.sizeBytes)]),ge("click",W,m),ge("change",Je,g),ge("input",Qt,h),A(r,v),oe()}He(["click","change","input"]);var qZ=F('<section class="qa-import-ack"><label><input id="qa-import-ack-checkbox" type="checkbox" class="svelte-w06gp4"/> <span> </span></label></section>'),zZ={hash:"svelte-w06gp4",code:".qa-import-ack-label.svelte-w06gp4 {display:flex;align-items:flex-start;gap:var(--size-4-2);font-size:var(--font-ui-small);line-height:var(--line-height-tight);cursor:var(--cursor);}.qa-import-ack-label.is-disabled.svelte-w06gp4 {cursor:not-allowed;color:var(--text-muted);}.qa-import-ack-label.svelte-w06gp4 input:where(.svelte-w06gp4) {flex-shrink:0;margin:0;}"};function N$(r,t){ie(t,!0),Ae(r,zZ);let e=X(t,"acknowledged",15,!1),n=k(()=>(t.preview?.criticalScriptPaths.length??0)+(t.preview?.choices.filter(p=>p.inlineScripts.length>0).length??0)),i=k(()=>t.preview?.missingReferences.some(p=>p.asScript)??!1),o=k(()=>f(n)>0?f(i)?"I have reviewed each script shown above and trust the source, including scripts that are not included and cannot be shown.":"I have reviewed each script above and trust the source.":f(i)?"This package runs scripts that are not included and cannot be reviewed. I trust the source.":"I understand this package can run code, and I trust the source.");var s=qZ(),a=R(s);let l;var c=R(a);Ct(c);var d=E(c,2),u=re(d,!0);$(a),$(s),Q(()=>{l=Ge(a,1,"qa-import-ack-label svelte-w06gp4",null,l,{"is-disabled":!t.fullyReviewed}),bd(c,e()),c.disabled=!t.fullyReviewed,le(c,"aria-describedby",t.reasonId),ee(u,f(o))}),ge("change",c,p=>e(p.currentTarget.checked)),A(r,s),oe()}He(["change"]);var pu=require("obsidian");Jt();Yi();function qE(r,t){return r==="skip"?r:t&&r==="write"?"overwrite":!t&&r==="overwrite"?"write":r}function sy(r,t){return!t&&r==="overwrite"?"import":r}function zE(r,t){let[e]=ti(t),n=r.kind==="template"||r.kind==="capture-template";if(e&&n){let i=r.originalPath.split("/").pop()??r.originalPath;return`${e}/${i}`}return r.originalPath}function Hq(r,t,e){let n=t(r),i=r.exists||e(n);return{mode:i?"overwrite":"write",destinationPath:n,destinationExists:i}}function Wq(r,t){let e=t(r);return{mode:e?"overwrite":"write",destinationPath:r,destinationExists:e}}function Gq(r,t,e){let n=new Map;for(let i of r)n.set(i.originalPath,Hq(i,t,e));return n}function jq(r,t,e,n){return r.get(t.originalPath)??Hq(t,e,n)}function Yq(r){let t=new Map;for(let e of r)t.set(e.choiceId,e.exists?"overwrite":"import");return t}function Kq(r,t,e){let n=new Map(r);return n.set(t,e),n}function Qq(r,t,e,n){let i=r.get(t)??Wq(t,n),o=new Map(r);return o.set(t,{...i,mode:e}),o}function Xq(r,t,e,n){let i=r.get(t)??Wq(t,n),o=e.trim(),s=o||t,a=o||e,l=n(s),c=new Map(r);return c.set(t,{...i,mode:qE(i.mode,l),destinationPath:a,destinationExists:l}),{decisions:c,effectivePath:s}}function Jq(r,t,e){let n=r.get(t);if(!n||n.destinationExists===e)return r;let i=new Map(r);return i.set(t,{...n,destinationExists:e,mode:qE(n.mode,e)}),i}function Zq(r,t){return r.map(e=>({choiceId:e.choiceId,mode:sy(t.get(e.choiceId)??"import",e.exists)}))}function ez(r,t,e){return r.map(n=>{let i=t.get(n.originalPath),o=i?.destinationPath?.trim()||n.originalPath,s=i?.destinationExists??(n.exists||e(o)),a=i?.mode??(s?"overwrite":"write");return{originalPath:n.originalPath,destinationPath:o,mode:a}})}var UE=class{constructor(t){this.app=t;this.tokens=new Map}indexed(t){let e=t.trim();return!e||Ut(e)?null:this.app.vault.getAbstractFileByPath((0,pu.normalizePath)(e))}optimistic(t){return this.indexed(t)instanceof pu.TFile}isFolder(t){return this.indexed(t)instanceof pu.TFolder}async resolve(t){let e=t.trim();if(!e||Ut(e))return!1;try{return(await this.app.vault.adapter.stat((0,pu.normalizePath)(e)))?.type==="file"}catch{return!1}}schedule(t,e,n){let i=(this.tokens.get(t)??0)+1;this.tokens.set(t,i),this.resolve(e).then(o=>{this.tokens.get(t)===i&&n(o)})}};var HZ=F('<span class="qa-macro-command-type svelte-131fx5e"> </span>'),WZ=F('<code class="svelte-131fx5e"> </code>'),GZ=F('<span class="qa-macro-command-summary svelte-131fx5e"> </span>'),jZ=F('<li class="svelte-131fx5e"><span class="qa-macro-command-name"> </span> <!> <!></li>'),YZ=F('<ul class="qa-macro-commands svelte-131fx5e"></ul>'),KZ={hash:"svelte-131fx5e",code:`
|
||
/* Obsidian's outline/file-tree indentation guide on the left. */.qa-macro-commands.svelte-131fx5e {list-style:none;margin:0;padding:0 0 0 var(--size-4-3);border-inline-start:var(--nav-indentation-guide-width, 1px) solid
|
||
var(--nav-indentation-guide-color, var(--background-modifier-border));display:flex;flex-direction:column;gap:var(--size-4-1);}.qa-macro-commands.svelte-131fx5e li:where(.svelte-131fx5e) {display:flex;flex-wrap:wrap;align-items:center;gap:var(--size-4-1) var(--size-4-2);padding-inline-start:calc(var(--qa-macro-depth, 0) * var(--size-4-4));font-size:var(--font-ui-smaller);line-height:var(--line-height-tight);}.qa-macro-command-type.svelte-131fx5e,
|
||
.qa-macro-command-summary.svelte-131fx5e {color:var(--text-muted);}.qa-macro-commands.svelte-131fx5e code:where(.svelte-131fx5e) {font-family:var(--font-monospace);font-size:var(--code-size);color:var(--text-muted);overflow-wrap:anywhere;}`};function V$(r,t){ie(t,!0),Ae(r,KZ);let e={UserScript:"User script",Conditional:"Conditional",NestedChoice:"Nested choice",Obsidian:"Obsidian command",Choice:"Choice",Wait:"Wait",EditorCommand:"Editor command",AIAssistant:"AI assistant",OpenFile:"Open file"};function n(o){return e[o]??o}var i=YZ();gt(i,21,()=>t.commands,yd,(o,s)=>{var a=jZ(),l=R(a),c=re(l,!0),d=E(l,2);{var u=v=>{iy(v,{get flag(){return f(s).flag}})},p=v=>{var b=HZ(),y=re(b,!0);Q(C=>ee(y,C),[()=>n(f(s).type)]),A(v,b)};z(d,v=>{f(s).flag?v(u):v(p,-1)})}var m=E(d,2);{var h=v=>{var b=bt(),y=ae(b);{var C=T=>{var P=WZ(),_=re(P,!0);Q(()=>ee(_,f(s).scriptPath)),A(T,P)},w=k(()=>!A$(f(s).name,f(s).scriptPath));z(y,T=>{f(w)&&T(C)})}A(v,b)},g=v=>{var b=GZ(),y=re(b,!0);Q(()=>ee(y,f(s).summary)),A(v,b)};z(m,v=>{f(s).scriptPath?v(h):f(s).summary&&v(g,1)})}$(a),Q(()=>{sp(a,`--qa-macro-depth: ${f(s).depth}`),ee(c,f(s).name)}),A(o,a)}),$(i),A(r,i),oe()}var QZ=F('<div class="setting-item mod-empty-state svelte-1vg70zw"><div class="setting-item-info"><div class="setting-item-name svelte-1vg70zw">No choices found in this package.</div></div></div>'),XZ=F('<span class="qa-import-reviewed"><!> Reviewed</span>'),JZ=F('<div class="setting-item-description"> </div>'),ZZ=F('<button type="button" class="qa-link-button svelte-1vg70zw"><span><!></span> <span> </span></button>'),eee=F('<div><button type="button" class="qa-link-button svelte-1vg70zw"><span><!></span> <span> </span></button></div>'),tee=F("<option>Overwrite</option>"),ree=F("<option>Import</option>"),nee=F('<div class="qa-import-choice-macro svelte-1vg70zw"><!></div>'),iee=F('<div class="qa-import-choice-code-setting svelte-1vg70zw"> </div> <!>',1),oee=F('<div class="qa-import-choice-code svelte-1vg70zw"></div>'),see=F('<div class="setting-item svelte-1vg70zw"><div class="setting-item-info"><div class="setting-item-name qa-import-choice-name svelte-1vg70zw"><span> </span> <!></div> <!> <!> <!></div> <div class="setting-item-control"><label class="qa-visually-hidden"> </label> <select class="dropdown"><!><option>Duplicate</option><option>Skip</option></select></div> <!> <!></div>'),aee=F('<section class="setting-group qa-import-choices svelte-1vg70zw"><div class="setting-item setting-item-heading svelte-1vg70zw"><div class="setting-item-name svelte-1vg70zw">Choices</div></div> <div class="setting-items"><!> <!></div></section>'),lee={hash:"svelte-1vg70zw",code:`.qa-import-choices.svelte-1vg70zw .setting-item:where(.svelte-1vg70zw) {flex-wrap:wrap;}.qa-import-choices.svelte-1vg70zw .setting-item-name:where(.svelte-1vg70zw) {overflow-wrap:anywhere;}.qa-import-choice-name.svelte-1vg70zw {display:flex;flex-wrap:wrap;align-items:center;gap:var(--size-4-1) var(--size-4-2);}.qa-import-choices.svelte-1vg70zw .qa-link-button:where(.svelte-1vg70zw) {margin-top:var(--size-4-1);font-size:var(--font-ui-smaller);}
|
||
|
||
/* Pulls the glyph's built-in side bearing back to the text edge. */.qa-import-choice-chevron.svelte-1vg70zw {display:inline-flex;margin-inline-start:-3px;transition:transform 150ms ease;}.qa-import-choice-chevron.open.svelte-1vg70zw {transform:rotate(90deg);}.qa-import-choice-macro.svelte-1vg70zw {flex-basis:100%;min-width:0;}
|
||
|
||
/* Opens under the row at full width, like a file's contents. */.qa-import-choice-code.svelte-1vg70zw {flex-basis:100%;min-width:0;display:flex;flex-direction:column;gap:var(--size-4-2);}.qa-import-choice-code-setting.svelte-1vg70zw {font-size:var(--font-ui-smaller);color:var(--text-muted);}
|
||
@media (prefers-reduced-motion: reduce) {.qa-import-choice-chevron.svelte-1vg70zw {transition:none;}
|
||
}`};function B$(r,t){let e=Ri();ie(t,!0),Ae(r,lee);function n(c){let d=(c.pathHint??[]).slice(0,-1),u=[];return d.length>0&&u.push(`In ${d.join(" \u203A ")}`),c.exists&&u.push("Already in vault"),u.join(" \xB7 ")}var i=aee(),o=E(R(i),2),s=R(o);{var a=c=>{var d=QZ();A(c,d)};z(s,c=>{t.conflicts.length===0&&c(a)})}var l=E(s,2);gt(l,19,()=>t.conflicts,c=>c.choiceId,(c,d,u)=>{let p=k(()=>sy(t.choiceDecisions.get(f(d).choiceId)??"import",f(d).exists)),m=k(()=>t.previewChoiceById.get(f(d).choiceId)),h=k(()=>(f(m)?.commands?.length??0)>0),g=k(()=>f(h)&&t.expandedMacros.has(f(d).choiceId)),v=k(()=>f(m)?.inlineScripts??[]),b=k(()=>f(v).length>0&&t.expandedCode.has(f(d).choiceId)),y=k(()=>n(f(d)));var C=see(),w=R(C),T=R(w),P=R(T),_=re(P,!0),I=E(P,2);{var D=ve=>{var Ve=XZ(),Ie=R(Ve);Qe(Ie,{iconId:"check",size:14}),Xt(),$(Ve),A(ve,Ve)},N=k(()=>t.reviewedChoiceIds.has(f(d).choiceId)&&f(p)!=="skip");z(I,ve=>{f(N)&&ve(D)})}$(T);var K=E(T,2);{var ne=ve=>{var Ve=JZ(),Ie=re(Ve,!0);Q(()=>ee(Ie,f(y))),A(ve,Ve)};z(K,ve=>{f(y)&&ve(ne)})}var H=E(K,2);{var O=ve=>{var Ve=ZZ(),Ie=R(Ve);let ze;var ct=R(Ie);Qe(ct,{iconId:"chevron-right",size:14}),$(Ie);var Ke=E(Ie,2),ot=re(Ke,!0);$(Ve),Q(()=>{le(Ve,"aria-expanded",f(g)),ze=Ge(Ie,1,"qa-import-choice-chevron svelte-1vg70zw",null,ze,{open:f(g)}),ee(ot,f(g)?"Hide macro":"Show macro")}),ge("click",Ve,()=>t.toggleMacro(f(d).choiceId)),A(ve,Ve)};z(H,ve=>{f(h)&&ve(O)})}var G=E(H,2);{var V=ve=>{var Ve=eee(),Ie=R(Ve),ze=R(Ie);let ct;var Ke=R(ze);Qe(Ke,{iconId:"chevron-right",size:14}),$(ze);var ot=E(ze,2),or=re(ot,!0);$(Ie),$(Ve),Q(()=>{le(Ie,"aria-expanded",f(b)),ct=Ge(ze,1,"qa-import-choice-chevron svelte-1vg70zw",null,ct,{open:f(b)}),ee(or,f(b)?"Hide code":"View code")}),ge("click",Ie,()=>t.toggleCode(f(d).choiceId)),A(ve,Ve)};z(G,ve=>{f(v).length>0&&ve(V)})}$(w);var M=E(w,2),B=R(M),J=re(B),te=E(B,2),W=R(te);{var Z=ve=>{var Ve=tee();Ve.value=Ve.__value="overwrite",A(ve,Ve)},se=ve=>{var Ve=ree();Ve.value=Ve.__value="import",A(ve,Ve)};z(W,ve=>{f(d).exists?ve(Z):ve(se,-1)})}var ce=E(W);ce.value=ce.__value="duplicate";var $e=E(ce);$e.value=$e.__value="skip",$(te);var Xe;Ll(te),$(M);var Ye=E(M,2);{var he=ve=>{var Ve=nee(),Ie=R(Ve);{let ze=k(()=>f(m)?.commands??[]);V$(Ie,{get commands(){return f(ze)}})}$(Ve),A(ve,Ve)};z(Ye,ve=>{f(g)&&ve(he)})}var Re=E(Ye,2);{var Je=ve=>{var Ve=oee();gt(Ve,21,()=>f(v),yd,(Ie,ze)=>{var ct=iee(),Ke=ae(ct),ot=re(Ke,!0),or=E(Ke,2);{let Ir=k(()=>F$(f(ze).text)),Hn=k(()=>`${f(d).name} \u203A ${f(ze).setting}`);oy(or,{get content(){return f(Ir)},get label(){return f(Hn)},executable:!0,wrap:!0})}Q(()=>ee(ot,f(ze).setting)),A(Ie,ct)}),$(Ve),A(ve,Ve)};z(Re,ve=>{f(b)&&ve(Je)})}$(C),Q(()=>{ee(_,f(d).name),le(B,"for",`${e}-action-${f(u)}`),ee(J,`Action for ${f(d).name??""}`),le(te,"id",`${e}-action-${f(u)}`),Xe!==(Xe=f(p))&&(te.value=(te.__value=Xe)??"",Dl(te,Xe))}),ge("change",te,ve=>t.onChoiceModeChange(f(d).choiceId,ve)),A(c,C)}),$(o),$(i),A(r,i),oe()}He(["click","change"]);var cee=F('<li class="svelte-88pyz9"><code class="svelte-88pyz9"> </code> <span class="qa-package-callout-loc svelte-88pyz9"> </span></li>'),dee=F('<section class="callout qa-package-callout svelte-88pyz9"><div class="callout-title"><div class="callout-icon"><!></div> <div class="callout-title-inner">Missing files</div></div> <div class="callout-content svelte-88pyz9"><ul class="svelte-88pyz9"></ul></div></section>'),uee=F('<li class="svelte-88pyz9"><code class="svelte-88pyz9"> </code>: bundled but not used by any choice</li>'),pee=F('<section class="callout qa-package-callout svelte-88pyz9" data-callout="info"><div class="callout-title"><div class="callout-icon"><!></div> <div class="callout-title-inner">Unreferenced files</div></div> <div class="callout-content svelte-88pyz9"><ul class="svelte-88pyz9"></ul></div></section>'),mee=F("<!> <!>",1),fee={hash:"svelte-88pyz9",code:`.qa-package-callout.svelte-88pyz9 {margin:0;}.qa-package-callout.svelte-88pyz9 .callout-content:where(.svelte-88pyz9) {font-size:var(--font-ui-small);}.qa-package-callout.svelte-88pyz9 ul:where(.svelte-88pyz9) {margin:var(--size-4-2) 0 0;padding-inline-start:var(--size-4-5);display:flex;flex-direction:column;gap:var(--size-4-1);}.qa-package-callout.svelte-88pyz9 li:where(.svelte-88pyz9) {overflow-wrap:anywhere;line-height:var(--line-height-tight);}
|
||
|
||
/* Obsidian's inline-code look, which is otherwise scoped to rendered notes. */.qa-package-callout.svelte-88pyz9 code:where(.svelte-88pyz9) {font-family:var(--font-monospace);font-size:var(--code-size);background-color:var(--code-background);border-radius:var(--code-radius);padding:0.1em 0.25em;}.qa-package-callout-loc.svelte-88pyz9 {display:block;color:var(--text-muted);font-size:var(--font-ui-smaller);}`};function U$(r,t){ie(t,!0),Ae(r,fee);let e=k(()=>t.preview?.missingReferences.some(l=>l.asScript)??!1);var n=mee(),i=ae(n);{var o=l=>{var c=dee(),d=R(c),u=R(d),p=R(u);{let g=k(()=>f(e)?"zap":"alert-triangle");Qe(p,{get iconId(){return f(g)}})}$(u),Xt(2),$(d);var m=E(d,2),h=R(m);gt(h,21,()=>t.preview.missingReferences,g=>g.path,(g,v)=>{var b=cee(),y=R(b),C=re(y,!0),w=E(y),T=E(w),P=re(T,!0);$(b),Q(()=>{ee(C,f(v).path),ee(w,`:
|
||
${f(v).asScript?"not bundled, so it runs from whatever file exists at that path after import":"not bundled and not in your vault"} `),ee(P,f(v).breadcrumb)}),A(g,b)}),$(h),$(m),$(c),Q(()=>le(c,"data-callout",f(e)?"danger":"warning")),A(l,c)};z(i,l=>{t.preview&&t.preview.missingReferences.length>0&&l(o)})}var s=E(i,2);{var a=l=>{var c=pee(),d=R(c),u=R(d),p=R(u);Qe(p,{iconId:"info"}),$(u),Xt(2),$(d);var m=E(d,2),h=R(m);gt(h,20,()=>t.preview.orphanAssets,g=>g,(g,v)=>{var b=uee(),y=R(b),C=re(y,!0);Xt(),$(b),Q(()=>ee(C,v)),A(g,b)}),$(h),$(m),$(c),A(l,c)};z(s,l=>{t.preview&&t.preview.orphanAssets.length>0&&l(a)})}A(r,n),oe()}var hee=F('<p class="qa-import-status mod-error svelte-dvnvtv"> </p>'),gee=F('<p class="qa-import-status svelte-dvnvtv">Analyzing package\u2026</p>'),vee=F('<p class="qa-import-status svelte-dvnvtv"> </p>'),yee=F('<div class="setting-items"><div class="setting-item mod-empty-state"><div class="setting-item-info"><div class="setting-item-name">No files bundled with this package.</div></div></div></div>'),bee=F("<h4> </h4> <!>",1),wee=F('<section class="callout qa-import-summary svelte-dvnvtv" data-callout="success" role="status"><div class="callout-title"><div class="callout-icon"><!></div> <div class="callout-title-inner"> </div></div></section>'),Cee=F('<!> <!> <section class="setting-group qa-import-files svelte-dvnvtv"><div class="setting-item setting-item-heading svelte-dvnvtv"><div class="setting-item-name">Files</div></div> <!></section> <!> <!>',1),xee=F('<p id="qa-import-reason" class="qa-import-reason svelte-dvnvtv"> </p>'),Eee=F('<button type="button">Cancel</button>'),Tee=F('<div class="qa-package-dialog"><div class="qa-package-body"><section class="qa-import-paste svelte-dvnvtv"><label class="qa-visually-hidden" for="qa-import-json">Package JSON</label> <textarea id="qa-import-json" placeholder="Paste the contents of a .quickadd.json package here" rows="8" class="svelte-dvnvtv"></textarea> <!></section> <!> <!></div> <div class="modal-button-container"><!> <!> <button type="button" class="mod-cta"><!></button></div></div>'),_ee={hash:"svelte-dvnvtv",code:`.qa-import-paste.svelte-dvnvtv {display:flex;flex-direction:column;gap:var(--size-4-2);}.qa-import-paste.svelte-dvnvtv textarea:where(.svelte-dvnvtv) {width:100%;font-family:var(--font-monospace);font-size:var(--font-ui-small);resize:vertical;}.qa-import-status.svelte-dvnvtv {margin:0;font-size:var(--font-ui-smaller);color:var(--text-muted);overflow-wrap:anywhere;}.qa-import-status.mod-error.svelte-dvnvtv {color:var(--text-error);}.qa-import-files.svelte-dvnvtv {display:flex;flex-direction:column;gap:var(--size-4-3);}.qa-import-files.svelte-dvnvtv .setting-item-heading:where(.svelte-dvnvtv) {margin-bottom:var(--size-4-1);}
|
||
|
||
/* Small muted group label, like Obsidian's settings sidebar sections. */.qa-import-files-group.svelte-dvnvtv {margin:var(--size-4-2) 0 0;padding:0 var(--size-4-4);font-size:var(--font-ui-smaller);font-weight:var(--font-semibold);color:var(--text-muted);}.qa-import-files-group.svelte-dvnvtv:first-of-type {margin-top:0;}.qa-import-files-group.mod-warning.svelte-dvnvtv {color:var(--text-warning);}.qa-import-summary.svelte-dvnvtv {margin:0;}
|
||
|
||
/* Left of the buttons; the text wraps before they do. */.qa-import-reason.svelte-dvnvtv {flex:1 1 0;align-self:center;margin:0;font-size:var(--font-ui-smaller);color:var(--text-muted);}
|
||
|
||
/* The phone footer stacks its buttons bottom-up; put the reason on top. */.is-phone .qa-import-reason.svelte-dvnvtv {flex:none;order:1;text-align:center;}`};function q$(r,t){ie(t,!0),Ae(r,_ee);let e;function n(){return e??(e=new UE(t.app))}let i=pe(null),o=pe(null),s=pe(null),a=pe(!1),l=pe(Ze(new Set)),c=pe(Ze(new Set)),d=pe(Ze(new Set)),u=pe(Ze(new Set)),p=pe(null),m=pe(!1),h=pe(null),g=pe(Ze(new Map)),v=pe(Ze(new Map)),b=pe(Ze(new Set)),y=pe(""),C=pe(!1),w=pe(0),T=pe(!1),P=pe(null),_=k(()=>f(s)?DE(f(s)):!1),I=k(()=>f(s)?qq(f(s),f(l),f(c)):0),D=k(()=>f(I)===0),N=k(()=>new Map((f(s)?.choices??[]).map(Y=>[Y.choiceId,Y]))),K=k(()=>new Map((f(s)?.files??[]).map(Y=>[Y.originalPath,Y]))),ne=k(()=>!!(f(s)&&(f(s).summary.hasCritical||f(s).summary.hasWarning))),H=k(()=>{let Y=f(h);if(!Y)return"";let ue=[];Y.added&&ue.push(`${Y.added} choice${Y.added===1?"":"s"} added`),Y.overwritten&&ue.push(`${Y.overwritten} overwritten`),Y.assetsWritten&&ue.push(`${Y.assetsWritten} file${Y.assetsWritten===1?"":"s"} written`);let Pt=Y.skipped+Y.assetsSkipped;return Pt&&ue.push(`${Pt} skipped`),ue.length?`Imported: ${ue.join(", ")}.`:"Nothing was imported."});function O(Y){if(f(l).has(Y))return;let ue=new Set(f(l));ue.add(Y),q(l,ue,!0)}function G(Y){let ue=new Set(f(d));ue.has(Y)?ue.delete(Y):ue.add(Y),q(d,ue,!0)}function V(Y){let ue=new Set(f(u));ue.has(Y)?ue.delete(Y):ue.add(Y),q(u,ue,!0),ue.has(Y)&&!f(c).has(Y)&&q(c,new Set(f(c)).add(Y),!0)}let M=Y=>n().optimistic(Y),B=k(()=>(f(o)?.assetConflicts??[]).map(Y=>{let ue=jq(f(v),Y,se,M);return{conflict:Y,state:ue,destinationIsFolder:ue.mode!=="skip"&&n().isFolder(ue.destinationPath),file:f(K).get(Y.originalPath)}})),J=k(()=>f(B).filter(Y=>!f(b).has(Y.conflict.originalPath))),te=k(()=>f(B).filter(Y=>f(b).has(Y.conflict.originalPath))),W=k(()=>!!(f(i)&&f(o))&&!f(C)&&!f(B).some(Y=>Y.destinationIsFolder)&&(!f(_)||f(a)&&f(D))),Z=k(()=>!f(i)||!f(o)||f(C)||f(T)?"":f(_)&&!f(D)?`View ${f(I)} script${f(I)===1?"":"s"} above to import.`:f(_)&&!f(a)?"Confirm the acknowledgement above to import.":f(B).some(Y=>Y.destinationIsFolder)?"A destination above is a folder. Add a file name to import.":"");function se(Y){return zE(Y,U.getState().templateFolderPaths)}function ce(Y,ue,Pt=!1){n().schedule(Y,ue,br=>{if(q(v,Jq(f(v),Y,br),!0),Pt&&br!==f(b).has(Y)){let Lo=new Set(f(b));br?Lo.add(Y):Lo.delete(Y),q(b,Lo,!0)}})}function $e(){if(!f(o)){q(g,new Map,!0),q(v,new Map,!0),q(b,new Set,!0);return}q(g,Yq(f(o).choiceConflicts),!0),q(v,Gq(f(o).assetConflicts,se,M),!0),q(b,new Set(f(o).assetConflicts.filter(Y=>f(v).get(Y.originalPath)?.destinationExists).map(Y=>Y.originalPath)),!0);for(let Y of f(o).assetConflicts){let ue=f(v).get(Y.originalPath);ue&&ce(Y.originalPath,ue.destinationPath,!0)}}function Xe(Y,ue){q(g,Kq(f(g),Y,ue),!0)}function Ye(Y,ue){q(v,Qq(f(v),Y,ue,M),!0)}function he(Y,ue){let{decisions:Pt,effectivePath:br}=Xq(f(v),Y.originalPath,ue,M);q(v,Pt,!0),ce(Y.originalPath,br)}function Re(Y,ue){let br=ue.currentTarget.value;Xe(Y,br)}function Je(){q(s,null),q(a,!1),q(l,new Set,!0),q(c,new Set,!0),q(d,new Set,!0),q(u,new Set,!0)}async function ve(Y){let ue=Y.trim(),Pt=Nk(w);if(q(h,null),q(T,!1),!ue){q(i,null),q(o,null),q(g,new Map,!0),q(v,new Map,!0),Je(),q(p,null);return}q(C,!0);try{let br=ry(ue),Lo=U.getState().choices,jf=await NE(t.app,Lo,br),sk=await mf(t.app,Lo,br);if(Pt!==f(w))return;q(i,{pkg:br,path:"[pasted]"},!0),q(o,jf,!0),Je(),q(s,sk,!0),q(p,null),$e()}catch(br){if(Pt!==f(w))return;q(p,br?.message??String(br),!0),q(i,null),q(o,null),q(g,new Map,!0),q(v,new Map,!0),Je()}finally{Pt===f(w)&&q(C,!1)}}function Ve(Y){let ue=Y.currentTarget.value;q(y,ue,!0),ve(ue)}async function Ie(){if(f(T)){new ay.Notice("This package has already been imported.");return}if(!f(i)||!f(o)){new ay.Notice("Load a package before importing.");return}q(m,!0),q(h,null);try{let Y=U.getState().choices,ue=await VE({app:t.app,existingChoices:Y,aiProviders:U.getState().ai.providers,pkg:f(i).pkg,choiceDecisions:Zq(f(o).choiceConflicts,f(g)),assetDecisions:ez(f(o).assetConflicts,f(v),M)});U.setState(Pt=>({...Pt,choices:ue.updatedChoices})),t.onImported?.(ue,Y),q(h,{added:ue.addedChoiceIds.length,overwritten:ue.overwrittenChoiceIds.length,skipped:ue.skippedChoiceIds.length,assetsWritten:ue.writtenAssets.length,assetsSkipped:ue.skippedAssets.length},!0),q(T,!0),new ay.Notice(`Imported ${ue.addedChoiceIds.length+ue.overwrittenChoiceIds.length} choice${ue.addedChoiceIds.length+ue.overwrittenChoiceIds.length===1?"":"s"} successfully.`)}catch(Y){console.error(Y),new ay.Notice(`Import failed: ${Y?.message??Y}`)}finally{q(m,!1)}f(T)&&(await Cs(),f(P)?.scrollIntoView({block:"nearest"}))}var ze=Tee(),ct=R(ze),Ke=R(ct),ot=E(R(Ke),2);rd(ot);var or=E(ot,2);{var Ir=Y=>{var ue=hee(),Pt=re(ue,!0);Q(()=>ee(Pt,f(p))),A(Y,ue)},Hn=Y=>{var ue=gee();A(Y,ue)},me=Y=>{var ue=vee(),Pt=re(ue);Q(br=>ee(Pt,`Version ${f(i).pkg.quickAddVersion??""} \xB7 Created ${br??""} \xB7 ${f(o).choiceConflicts.length??""} choice${f(o).choiceConflicts.length===1?"":"s"} \xB7 ${f(i).pkg.assets.length??""} file${f(i).pkg.assets.length===1?"":"s"}`),[()=>new Date(f(i).pkg.createdAt).toLocaleDateString()]),A(Y,ue)};z(or,Y=>{f(p)?Y(Ir):f(C)?Y(Hn,1):f(i)&&f(o)&&Y(me,2)})}$(Ke);var Fe=E(Ke,2);{var ut=Y=>{var ue=Cee(),Pt=ae(ue);{var br=ci=>{D$(ci,{get preview(){return f(s)}})};z(Pt,ci=>{f(ne)&&f(s)&&ci(br)})}var Lo=E(Pt,2);B$(Lo,{get conflicts(){return f(o).choiceConflicts},get choiceDecisions(){return f(g)},get previewChoiceById(){return f(N)},get expandedMacros(){return f(d)},toggleMacro:G,get expandedCode(){return f(u)},get reviewedChoiceIds(){return f(c)},toggleCode:V,onChoiceModeChange:Re});var jf=E(Lo,2),sk=E(R(jf),2);{var jj=ci=>{var pa=yee();A(ci,pa)},Yj=ci=>{var pa=bt(),ab=ae(pa);gt(ab,17,()=>[{label:"Added",rows:f(J),overwrite:!1},{label:"Will overwrite",rows:f(te),overwrite:!0}],jc=>jc.label,(jc,Yc)=>{var lb=bt(),ak=ae(lb);{var lk=ck=>{var fR=bee(),dk=ae(fR);let hR;var Xj=re(dk),Jj=E(dk,2);gt(Jj,17,()=>f(Yc).rows,uk=>uk.conflict.originalPath,(uk,ma)=>{var gR=bt(),Zj=ae(gR);{var eY=pk=>{{let tY=k(()=>f(l).has(f(ma).file.originalPath));L$(pk,{get file(){return f(ma).file},get pkg(){return f(i).pkg},get mode(){return f(ma).state.mode},get destinationPath(){return f(ma).state.destinationPath},get destinationExists(){return f(ma).state.destinationExists},get destinationIsFolder(){return f(ma).destinationIsFolder},onPathInput:mk=>he(f(ma).conflict,mk),onModeChange:mk=>Ye(f(ma).conflict.originalPath,mk),get reviewed(){return f(tY)},onReviewed:O})}};z(Zj,pk=>{f(ma).file&&pk(eY)})}A(uk,gR)}),Q(()=>{hR=Ge(dk,1,"qa-import-files-group svelte-dvnvtv",null,hR,{"mod-warning":f(Yc).overwrite}),ee(Xj,`${f(Yc).label??""} (${f(Yc).rows.length??""})`)}),A(ck,fR)};z(ak,ck=>{f(Yc).rows.length>0&&ck(lk)})}A(jc,lb)}),A(ci,pa)};z(sk,ci=>{f(B).length===0?ci(jj):ci(Yj,-1)})}$(jf);var mR=E(jf,2);U$(mR,{get preview(){return f(s)}});var Kj=E(mR,2);{var Qj=ci=>{var pa=wee(),ab=R(pa),jc=R(ab),Yc=R(jc);Qe(Yc,{iconId:"check"}),$(jc);var lb=E(jc,2),ak=re(lb,!0);$(ab),$(pa),xn(pa,lk=>q(P,lk),()=>f(P)),Q(()=>ee(ak,f(H))),A(ci,pa)};z(Kj,ci=>{f(h)&&ci(Qj)})}A(Y,ue)};z(Fe,Y=>{f(i)&&f(o)&&Y(ut)})}var Yt=E(Fe,2);{var Kt=Y=>{{let ue=k(()=>f(Z)?"qa-import-reason":void 0);N$(Y,{get preview(){return f(s)},get fullyReviewed(){return f(D)},get reasonId(){return f(ue)},get acknowledged(){return f(a)},set acknowledged(Pt){q(a,Pt,!0)}})}};z(Yt,Y=>{f(i)&&f(_)&&!f(T)&&Y(Kt)})}$(ct);var qt=E(ct,2),Qt=R(qt);{var Se=Y=>{var ue=xee(),Pt=re(ue,!0);Q(()=>ee(Pt,f(Z))),A(Y,ue)};z(Qt,Y=>{f(Z)&&Y(Se)})}var st=E(Qt,2);{var yr=Y=>{var ue=Eee();Q(()=>ue.disabled=f(m)),ge("click",ue,function(...Pt){t.close?.apply(this,Pt)}),A(Y,ue)};z(st,Y=>{f(T)||Y(yr)})}var zt=E(st,2),Do=R(zt);{var Tl=Y=>{var ue=xs("Importing\u2026");A(Y,ue)},In=Y=>{var ue=xs("Close");A(Y,ue)},ua=Y=>{var ue=xs("Import package");A(Y,ue)};z(Do,Y=>{f(m)?Y(Tl):f(T)?Y(In,1):Y(ua,-1)})}$(zt),$(qt),$(ze),Q(()=>{zt.disabled=f(m)||!f(T)&&!f(W),le(zt,"aria-describedby",f(Z)?"qa-import-reason":void 0)}),ge("input",ot,Ve),Zn(ot,()=>f(y),Y=>q(y,Y)),ge("click",zt,function(...Y){(f(T)?t.close:Ie)?.apply(this,Y)}),A(r,ze),oe()}He(["input","click"]);var HE=class extends tz.Modal{constructor(e,n={}){super(e);this.options=n;this.handle=null}onOpen(){this.modalEl.addClass("quickAddModal","qa-package-modal","packageImportModal"),this.setTitle("Import QuickAdd package"),this.handle=wi(this.contentEl,q$,{app:this.app,close:()=>this.close(),onImported:this.options.onImported},{what:"the package importer"})}onClose(){this.handle?.destroy(),this.handle=null}};lt();function WE(r,t,e){let n=new Map(Zt(t).map(c=>[c.id,c])),i=Ad(e.updatedChoices),o=new Map(i.map(c=>[c.id,c.choice])),s=new Map(i.map(c=>[c.id,c.parentId])),a=new Set([...e.overwrittenChoiceIds,...e.addedChoiceIds]),l=c=>{for(let d=s.get(c);d;d=s.get(d))if(a.has(d))return!0;return!1};for(let c of e.overwrittenChoiceIds){let d=n.get(c);d&&r.removeCommandForChoice(d,{recursive:!0})}for(let c of a){if(l(c))continue;let d=o.get(c);d&&r.addCommandForChoice(d)}}Dm();wd();Ko();function z$(r,t,e,n){let i=At(r,"div"),o=At(r,"strong");return o.textContent=t,i.appendChild(o),i.appendChild(_d(r,` ${e}`)),n?.className&&i.classList.add(n.className),i.classList.add("qa-dev-info-row"),r.appendChild(i),i}function rz(r,t){if(t.branch!==null&&z$(r,"Branch:",t.branch),t.commit!==null&&z$(r,"Commit:",t.commit),t.dirty!==null){let e=t.dirty?"Yes (uncommitted changes)":"No",n=t.dirty?"qa-dev-dirty-status":"qa-dev-clean-status";z$(r,"Uncommitted changes:",e,{className:n})}}var GE="Bundle or import QuickAdd automations as reusable packages.";function nz(r,t,e,n){let i=[{type:"group",heading:"Choices & packages",extraButtons:[o=>o.setIcon("help-circle").setTooltip("QuickAdd documentation").onClick(()=>F1(is.gettingStarted,o.extraSettingsEl))],items:[{name:"Choices",render:r.choices},{name:"Packages",desc:GE,render:r.packages}]},{type:"group",heading:"Input",items:[{name:"Use multi-line input prompt",desc:"Use multi-line input prompt instead of single-line input prompt. Submit multi-line prompts with Ctrl/Cmd+Enter; Enter inserts a newline.",control:{type:"toggle",key:"inputPrompt"}},{name:"One-page input for choices",desc:H$("Collect a choice's inputs in one form before it runs, instead of one prompt at a time. Works with Template and Capture choices, and with Macros whose scripts declare inputs. Template and Capture choices can override this individually. ",is.onePageInputs,"Learn more about one-page inputs"),control:{type:"toggle",key:"onePageInputEnabled"}}]},...n?[n]:[],{type:"group",heading:"Notifications",items:[{name:"Announce updates",desc:"Display release notes when a new version is installed. This includes new features, demo videos, and bug fixes.",control:{type:"dropdown",key:"announceUpdates",defaultValue:"major",options:{all:"Every release",major:"Feature releases",none:"Never"}}},{name:"Show capture notifications",desc:"Display a notification when content is captured successfully to confirm the operation completed.",control:{type:"toggle",key:"showCaptureNotification"}}]},{type:"group",heading:"AI & online",items:[{name:"Disable AI & online features",desc:"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.",control:{type:"toggle",key:"disableOnlineFeatures"}},...e?[e]:[]]},{type:"group",heading:"Appearance",items:[{name:"Show icon in sidebar",desc:"Add QuickAdd icon to the sidebar ribbon. Requires a reload.",control:{type:"toggle",key:"enableRibbonIcon"}}]},{type:"group",items:[kee(r)]}];return t&&i.push({type:"group",heading:"Developer",items:[{name:"Development information",desc:"Git information for developers.",render:r.developmentInfo}]}),i}function kee(r){return{type:"page",name:"Advanced",items:[{type:"group",heading:"Choice picker",items:[{name:"\u201CNew note from template\u201D in the launcher",desc:"Add a row to Run QuickAdd that lists templates from your configured template folder, so you can create a note from a template without a dedicated Template choice. Only appears when a template folder is configured; the command palette entry works regardless.",control:{type:"dropdown",key:"templateFolderLauncherRow",defaultValue:"bottom",options:{bottom:"Bottom",top:"Top",off:"Hidden"}}},{name:"Search nested choices",desc:"When searching in the choice picker, also match choices nested inside folders and show their path. Note that nested matches can outrank same-level ones. Disable to search only the open level.",control:{type:"toggle",key:"searchNestedChoices"}}]},{type:"group",heading:"Input",items:[{name:"Use editor selection as default Capture value",desc:"When enabled, Capture uses the current editor selection as {{VALUE}} and may skip the prompt. When disabled, Capture always prompts for {{VALUE}}.",control:{type:"toggle",key:"useSelectionAsCaptureValue"}},{name:"Name pasted images after the note title",desc:"When on, clipboard images saved by QuickAdd (pasting into a prompt, or {{CLIPBOARD}} with an image and no text) are named after the destination note. When the destination is not yet known, QuickAdd keeps the timestamp name. Duplicate names are handled by Obsidian's attachment folder setting.",control:{type:"toggle",key:"namePastedImagesAfterNoteTitle"}},{name:"Persist input prompt drafts",desc:"Keep drafts when closing input prompts so they can be restored on reopen. Drafts are stored only for this session.",control:{type:"toggle",key:"persistInputPromptDrafts"}},{name:"Date aliases",desc:"Shortcodes for natural language date parsing. One per line: alias = phrase. Example: tm = tomorrow.",render:r.dateAliases}]},{type:"group",heading:"Notifications",items:[{name:"Show input cancellation notifications",desc:"Display a notification when an input prompt is cancelled without submitting. Disable this to avoid extra notices when dismissing prompts.",control:{type:"toggle",key:"showInputCancellationNotification"}}]},{type:"group",heading:"Properties",items:[{name:"Convert string front matter variables to typed properties (Beta)",desc:'List/object values from scripts are always written as proper Obsidian properties (a list becomes a List). This toggle additionally converts string values into typed properties: a comma or bullet-list string becomes a List, "42" becomes a Number, "true" becomes a Checkbox, etc. Disabled by default; the string conversion is a beta heuristic that may have edge cases.',control:{type:"toggle",key:"enableTemplatePropertyTypes"}}]},{type:"group",heading:"Global variables",items:[{name:"Global variables",render:r.globalVariables}]},{type:"group",heading:"Obsidian URI",items:[{name:"Allow URI x-callback-url",desc:"When on, an obsidian://quickadd URI may open a callback URL (x-success / x-error / x-cancel) after a Template or Capture choice finishes \u2014 sending the outcome and the affected note's vault path and URL to that callback. While on, a URI that carries x-* callback params is restricted to Template and Capture choices (other choice types are warned and skipped). Off by default because the callback URL is set by whoever creates the obsidian:// link. Only shortcuts: and obsidian: callback URLs are permitted.",control:{type:"toggle",key:"enableUriCallbacks"}}]}]}}function H$(r,t,e="Learn more"){let n=createFragment();return n.append(document.createTextNode(r)),iC(n,t,e),n}lt();gi();je();tl();var jE=require("obsidian");function iz(r,t,e){return W$(new jE.Setting(r),t,e)}function W$(r,t,e){return r.setName("API key").setDesc(e.hasLegacyKey?"A legacy API key is stored in plain text. Link a keychain secret to replace it.":"Link a secret from Settings \u2192 Keychain.").addComponent(n=>new jE.SecretComponent(t,n).setValue(e.value).onChange(e.onChange))}var Ji=require("obsidian");gi();ye();je();var fz=require("obsidian");gi();var oz=require("obsidian");je();var YE=null,See=1440*60*1e3,G$=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function Aee(r){if(!G$(r))return null;let t=Object.entries(r).filter(([,e])=>G$(e)&&G$(e.models));return t.length>0?Object.fromEntries(t):null}async function j$(){if(YE&&Date.now()-YE.fetchedAt<See)return YE.data;if(U.getState().disableOnlineFeatures)throw new Error("Fetching models directory is disabled: Online features are turned off.");let r=await(0,oz.requestUrl)({url:"https://models.dev/api.json",method:"GET"}),t=Aee(r.json);if(!t)throw new Error("models.dev returned an unexpected response.");return YE={data:t,fetchedAt:Date.now()},t}function Iee(r){for(let t of[r,`https://${r}`])try{let e=new URL(t).hostname.toLowerCase();if(e)return e}catch{}return""}function ly(r){let t=r.toLowerCase(),e=Iee(r),n=i=>e===i||e.endsWith(`.${i}`);return n("openai.com")?"openai":n("openrouter.ai")?"openrouter":n("generativelanguage.googleapis.com")?"google":t.includes("anthropic")?"anthropic":n("groq.com")?"groq":n("together.ai")||n("together.xyz")?"togetherai":t.includes("huggingface")?"huggingface":t.includes("github")&&t.includes("models")?"github-models":t.includes("bedrock")||t.includes("aws")?"amazon-bedrock":t.includes("modelscope")?"modelscope":t.includes("dashscope")?"alibaba":n("fireworks.ai")?"fireworks-ai":t.includes("vercel")?"vercel":n("inference.net")?"inference":n("z.ai")||t.includes("zhipu")?"zhipuai":n("deepseek.com")?"deepseek":n("mistral.ai")?"mistral":t.includes("cerebras")?"cerebras":n("venice.ai")?"venice":n("upstage.ai")?"upstage":n("llama.com")?"llama":t.includes("morphllm")?"morph":n("inceptionlabs.ai")?"inception":t.includes("deepinfra")?"deepinfra":n("opencode.ai")?"opencode":n("inference.wandb.ai")?"wandb":n("githubcopilot.com")?"github-copilot":null}var Y$=/(whisper|-tts|tts-|embed|dall-e|image|moderation|transcribe|realtime|rerank)/i;function Pee(r){let t=r.modalities?.output;if(Array.isArray(t)&&!t.includes("text"))return!1;let e=r.limit??{};if(typeof e.context=="number"&&e.context<=0||typeof e.output=="number"&&e.output<=1)return!1;let n=(r.family??"").toLowerCase(),i=r.id.toLowerCase();return!(n.includes("embedding")||i.includes("embedding")||Y$.test(i))}function sz(r){return r.filter(Pee).map(t=>{let e={name:t.id,maxTokens:Math.max(1,Math.floor(t.limit?.context??128e3))};return typeof t.limit?.output=="number"&&t.limit.output>0&&(e.maxOutputTokens=Math.floor(t.limit.output)),typeof t.temperature=="boolean"&&(e.supportsTemperature=t.temperature),Object.assign(e,az(t)),e})}function az(r){let t={};return r.status==="deprecated"&&(t.deprecated=!0),typeof r.release_date=="string"&&r.release_date&&(t.releaseDate=r.release_date),t}var $ee=/^(.+)-(?:\d{4}-\d{2}-\d{2}|\d{8})$/;function lz(r){let t=new Set(r.map(e=>e.name));return r.filter(e=>{let n=$ee.exec(e.name)?.[1];return!n||!t.has(n)})}async function cz(r,t){let e=ly(r);if(!e)return t;let n;try{n=await j$()}catch{return t}let i=n[e]?.models;return i?t.map(o=>{let s=i[o.name];if(!s)return o;let a={...o};return typeof s.limit?.context=="number"&&s.limit.context>0&&(a.maxTokens=Math.floor(s.limit.context)),a.maxOutputTokens===void 0&&typeof s.limit?.output=="number"&&s.limit.output>0&&(a.maxOutputTokens=Math.floor(s.limit.output)),a.supportsTemperature===void 0&&typeof s.temperature=="boolean"&&(a.supportsTemperature=s.temperature),Object.assign(a,az(s)),a}):t}function K$(r,t){let e=new Map(t.map(s=>[s.name,s])),n=r.map(s=>{let a=e.get(s.name);if(!a)return s;let l={...s,maxTokens:a.maxTokens,maxOutputTokens:a.maxOutputTokens??s.maxOutputTokens,supportsTemperature:a.supportsTemperature??s.supportsTemperature},c=a.releaseDate??s.releaseDate;c!==void 0&&(l.releaseDate=c);let d=a.deprecated??s.deprecated;return d!==void 0&&(l.deprecated=d),l}),i=new Set(r.map(s=>s.name)),o=t.filter(s=>!i.has(s.name));return n.concat(o)}function KE(r,t){let e=new Set(r.map(n=>n.name));return K$(r,t.filter(n=>e.has(n.name)||!n.deprecated))}ff();je();var JE=128e3;async function hf(r,t){return lz(await Nee(r,t))}async function Nee(r,t){let e=r.modelSource??"providerApi";if(e==="modelsDev")return pz(r);if(e==="providerApi")return mz(r,t);try{return await mz(r,t)}catch(n){if(!ly(r.endpoint))throw n;return pz(r,n)}}async function pz(r,t){try{let e=await j$(),n=ly(r.endpoint);if(!n||!(n in e))throw new Error(`models.dev does not list a provider that matches ${r.endpoint}.`);let i=Object.values(e[n].models);return sz(i)}catch(e){throw t?new Error(`Provider API failed (${t.message}). Fallback to models.dev also failed: ${e.message}`):e}}async function mz(r,t){let{disableOnlineFeatures:e}=U.getState();if(e)throw new Error("Online features are disabled \u2014 enable them to browse provider models.");if(!r.endpoint)throw new Error("Provider is missing an endpoint URL.");let n=t??r.apiKey??"",i=Sh(r),o=i==="anthropic"?await Uee(r,n):i==="gemini"?await qee(r,n):await Bee(r,n);if(!o.length)throw new Error("The provider's models endpoint did not include any usable models.");let s=await cz(r.endpoint,o);return Vee(r.endpoint,s)}function Vee(r,t){let e=ly(r);if(e!=="openai"&&e!=="google"&&e!=="anthropic")return t;let n=new Map(Ah[e].map(i=>[i.name,i]));return t.map(i=>{let o=n.get(i.name);return o?{...i,maxTokens:i.maxTokens===JE?o.maxTokens:i.maxTokens,maxOutputTokens:i.maxOutputTokens??o.maxOutputTokens,supportsTemperature:i.supportsTemperature??o.supportsTemperature}:i})}async function X$(r,t,e){try{let n=await(0,fz.requestUrl)({url:t,headers:e,throw:!1});if(n.status>=400)throw XE(r.name,n);return await n.json}catch(n){throw new Error(`Provider rejected the models request: ${n.message}`)}}async function Bee(r,t){let e=r.endpoint.replace(/\/+$/,""),n=e.endsWith("/v1")?`${e}/models`:`${e}/v1/models`,i={};t&&(i.Authorization=`Bearer ${t}`);let o=await X$(r,n,i),s=zee(o),a=[];for(let l of s){let c=Hee(l);c&&!Y$.test(c.name)&&a.push(c)}return a}async function Uee(r,t){let e=r.endpoint.replace(/\/+$/,""),n={"anthropic-version":"2023-06-01"};t&&(n["x-api-key"]=t);let i=[],o=null;for(let s=0;s<10;s++){let a=`${e}/v1/models?limit=1000`+(o?`&after_id=${encodeURIComponent(o)}`:""),l=await X$(r,a,n);for(let c of l.data??[])c.id&&i.push({name:c.id,maxTokens:JE});if(!l.has_more||!l.last_id)break;o=l.last_id}return i}async function qee(r,t){let e=r.endpoint.replace(/\/+$/,""),n={};t&&(n["x-goog-api-key"]=t);let i=[],o=null;for(let s=0;s<10;s++){let a=`${e}/v1beta/models?pageSize=1000`+(o?`&pageToken=${encodeURIComponent(o)}`:""),l=await X$(r,a,n);for(let c of l.models??[]){if(!c.name)continue;let d=c.supportedGenerationMethods;if(Array.isArray(d)&&!d.includes("generateContent"))continue;let u={name:c.name.replace(/^models\//,""),maxTokens:typeof c.inputTokenLimit=="number"&&c.inputTokenLimit>0?c.inputTokenLimit:JE};typeof c.outputTokenLimit=="number"&&c.outputTokenLimit>0&&(u.maxOutputTokens=c.outputTokenLimit),i.push(u)}if(!l.nextPageToken)break;o=l.nextPageToken}return i}function zee(r){if(Array.isArray(r))return r;if(r&&typeof r=="object"&&Array.isArray(r.data))return r.data;throw new Error("The provider's models response was not a list.")}function Hee(r){let t=r.id??r.name;return t?{name:t,maxTokens:Wee(r)}:null}function Wee(r){let t=[r.context_length,r.contextLength,r.context_tokens,r.max_context_tokens,r.max_context_length,r.max_input_tokens,r.max_tokens,r.limit?.context];for(let e of t){let n=Gee(e);if(n&&n>0)return Math.floor(n)}return JE}function Gee(r){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"){let t=Number(r);if(Number.isFinite(t))return t}return null}Ic();var Qee=1440*60*1e3;function Z$(r,t){let e=new Map(r.map(o=>[o.name,JSON.stringify(o)])),n=0,i=0;for(let o of t){let s=e.get(o.name);s===void 0?n+=1:s!==JSON.stringify(o)&&(i+=1)}return{added:n,updated:i}}async function ZE(r,t){let e;try{let i=await Po(r,t);e=await hf(t,i)}catch(i){throw t.lastModelSync={at:Date.now(),error:vz(i)},i}let n=t.models;return t.models=KE(t.models,e),t.lastModelSync={at:Date.now()},{...Z$(n,t.models),discovered:e}}async function eF(r,t){let e=U.getState().ai.providers.find(a=>a.id===t);if(!e)return null;let n={...e,models:e.models.map(a=>({...a}))},i,o;try{({discovered:i}=await ZE(r,n))}catch(a){o={error:a}}let s=!1;if(U.setState(a=>({ai:{...a.ai,providers:a.ai.providers.map(l=>l.id!==t?l:(s=!0,{...l,models:i?KE(l.models,i):l.models,lastModelSync:n.lastModelSync}))}})),o)throw o.error;return s?i??[]:null}function vz(r){let t=r?.message;if(typeof t=="string"&&t.length>0)return t;let e=String(r);return e.length>0?e:"Unknown error"}function J$(r){return r.id?`id:${r.id}`:`ne:${(r.name??"").trim().toLowerCase()}\0${(r.endpoint??"").trim().toLowerCase().replace(/\/+$/,"")}`}async function yz(r,t={}){let e=U.getState();if(e.disableOnlineFeatures)return[];let n=e.ai.providers.filter(l=>l.autoSyncModels);if(n.length===0)return[];let i=e.ai.lastModelAutoSyncAt??0;if(!t.ignoreThrottle&&Date.now()-i<Qee)return[];let o=[],s=new Map;for(let l of n){let c={...l,models:l.models.map(d=>({...d}))};try{let{added:d,updated:u}=await ZE(r,c);o.push({provider:c.name,added:d,updated:u}),s.set(J$(c),c)}catch(d){o.push({provider:c.name,added:0,updated:0,error:vz(d)}),s.set(J$(c),c)}}let a=o.some(l=>!l.error);U.setState(l=>({...l,ai:{...l.ai,providers:l.ai.providers.map(c=>{let d=s.get(J$(c));return d?{...c,models:d.lastModelSync?.error?c.models:KE(c.models,d.models),lastModelSync:d.lastModelSync}:c}),lastModelAutoSyncAt:a?Date.now():l.ai.lastModelAutoSyncAt}}));for(let l of o)l.error?S.logMessage(`[Model auto-sync] ${l.provider}: failed (${l.error})`):(l.added>0||l.updated>0)&&S.logMessage(`[Model auto-sync] ${l.provider}: ${l.added} new model(s), ${l.updated} updated.`);return o}var bz=[{id:"openai",name:"OpenAI",endpoint:"https://api.openai.com/v1",doc:"https://platform.openai.com/docs/models",kind:"openai",modelSource:"modelsDev",seedKey:"openai"},{id:"gemini",name:"Gemini",endpoint:"https://generativelanguage.googleapis.com",doc:"https://ai.google.dev/gemini-api/docs",kind:"gemini",modelSource:"auto",seedKey:"google"},{id:"anthropic",name:"Anthropic",endpoint:"https://api.anthropic.com",doc:"https://docs.anthropic.com/",kind:"anthropic",modelSource:"auto",seedKey:"anthropic"},{id:"groq",name:"Groq",endpoint:"https://api.groq.com/openai/v1",doc:"https://console.groq.com/docs/models",kind:"openai",modelSource:"auto"},{id:"togetherai",name:"TogetherAI",endpoint:"https://api.together.xyz/v1",doc:"https://docs.together.ai/docs/serverless-models",kind:"openai",modelSource:"auto"},{id:"openrouter",name:"OpenRouter",endpoint:"https://openrouter.ai/api/v1",doc:"https://openrouter.ai/models",kind:"openai",modelSource:"auto"},{id:"hugging-face",name:"Hugging Face",endpoint:"https://router.huggingface.co/v1",doc:"https://huggingface.co/docs/inference-providers",kind:"openai",modelSource:"auto"},{id:"mistral",name:"Mistral",endpoint:"https://api.mistral.ai/v1",doc:"https://docs.mistral.ai/getting-started/models/",kind:"openai",modelSource:"auto"},{id:"deepseek",name:"DeepSeek",endpoint:"https://api.deepseek.com",doc:"https://platform.deepseek.com/api-docs/",kind:"openai",modelSource:"auto"}];var eT=class extends Ji.Modal{constructor(t,e){super(t),this.providers=e,this.waitForClose=new Promise((n,i)=>{this.resolvePromise=n,this.rejectPromise=i}),this.open(),this.display()}addHeader(t){t.createEl("h2",{text:"Add a provider",cls:"qa-modal-title"})}display(){this.contentEl.empty(),this.modalEl.addClass("qa-ai-wide-modal"),this.contentEl.addClass("qa-ai-scroll-content"),this.addHeader(this.contentEl);let t=this.contentEl.createDiv({cls:"qa-provider-grid"});for(let e of bz){let n=t.createDiv({cls:"qa-provider-card"});if(n.createDiv({text:e.name,cls:"qa-provider-card-title"}),n.createDiv({text:e.endpoint,cls:"qa-provider-card-endpoint"}),e.doc){let s=n.createEl("a",{text:"Docs",href:e.doc});s.target="_blank",s.rel="noopener noreferrer"}let i="",o=iz(n,this.app,{value:i,onChange:s=>{i=s}});o.settingEl.addClass("qa-provider-api-setting"),o.addButton(s=>{s.setButtonText("Connect").setCta().onClick(async()=>{try{let a=i.trim();try{new URL(e.endpoint)}catch{new Ji.Notice(`Invalid endpoint URL for ${e.name}.`);return}let l=e.endpoint.toLowerCase();if(["openai.com","generativelanguage.googleapis.com","anthropic","api.groq.com","together.xyz","openrouter.ai","router.huggingface.co","api.mistral.ai","api.deepseek.com"].some(h=>l.includes(h))&&!a){new Ji.Notice(`${e.name} requires an API key.`);return}let d=h=>h.trim().toLowerCase(),u=h=>h.trim().toLowerCase().replace(/\/+$/,"");if(this.providers.some(h=>d(h.name)===d(e.name)&&u(h.endpoint)===u(e.endpoint))){new Ji.Notice(`${e.name} is already configured.`);return}let m={name:e.name,endpoint:e.endpoint,id:Qb(e.id,this.providers),kind:e.kind,apiKey:"",apiKeyRef:a,models:[],modelSource:e.modelSource??"auto",autoSyncModels:!0};s.setButtonText("Connecting..."),s.setDisabled(!0),await this.importInitialModels(m,e),this.providers.push(m),this.close()}catch(a){s.setButtonText("Connect"),s.setDisabled(!1),new Ji.Notice(`Failed to add provider: ${a.message??a}`)}})})}new Ji.Setting(this.contentEl).setName("Custom provider").setDesc("Create any custom endpoint (OpenAI-compatible or otherwise)").addButton(e=>{e.setButtonText("Add custom...").onClick(()=>{let n={id:Qb("custom",this.providers),name:"Custom",endpoint:"",apiKey:"",apiKeyRef:"",models:[],modelSource:"providerApi"};this.providers.push(n),new Ji.Notice("Custom provider added. Open it in the list to configure it."),this.close()})})}async importInitialModels(t,e){try{await ZE(this.app,t),new Ji.Notice(`${e.name} connected with ${t.models.length} models.`)}catch(n){let i=n.message??String(n);e.seedKey?(t.models=Jb(e.seedKey),new Ji.Notice(`${e.name} added with its built-in model list. Live model loading failed: ${i}`)):new Ji.Notice(`${e.name} added, but loading models failed: ${i} Use "Sync now" in the provider's settings to retry.`)}}onClose(){this.resolvePromise(this.providers??null),super.onClose()}};var vn=require("obsidian");gi();Ic();async function tT(r,t){let e="";try{return e=await Po(r,t),{ok:!0,modelCount:(await hf({...t,modelSource:"providerApi"},e)).length,apiKeyLinked:!!e}}catch(n){return{ok:!1,error:n?.message||String(n)||"Unknown error",apiKeyLinked:!!e}}}function wz(r){return r.ok?`\u2713 Connected. The provider lists ${`${r.modelCount} model${r.modelCount===1?"":"s"}`}.`:`\u2717 ${r.error}${r.apiKeyLinked?"":" (No API key is linked.)"}`}je();Gs();tl();var Zs=require("obsidian");Ic();var rT=class extends Zs.Modal{constructor(e,n){super(e);this.allModels=[];this.filtered=[];this.selectedIds=new Set;this.mode="add";this.resolved=!1;this.loadError=null;this.provider=n,this.waitForClose=new Promise((i,o)=>{this.resolvePromise=i,this.rejectPromise=o}),this.open(),this.loadData().then(()=>this.display())}async loadData(){try{let e=await Po(this.app,this.provider);this.allModels=await hf(this.provider,e),this.filtered=this.allModels.slice(),this.loadError=null}catch(e){this.loadError=`${e.message??e}`,new Zs.Notice(`Failed to load model directory: ${this.loadError}`)}}display(){this.contentEl.empty(),this.modalEl.addClass("qa-ai-wide-modal"),this.contentEl.addClass("qa-ai-scroll-content"),this.contentEl.createEl("h2",{text:`Browse models for ${this.provider.name}`,cls:"qa-modal-title"}),new Zs.Setting(this.contentEl).setName("Search").addText(e=>{e.setPlaceholder("Filter by name").onChange(n=>{let i=n.trim().toLowerCase();this.filtered=this.allModels.filter(o=>o.name.toLowerCase().includes(i)),this.renderList()})}).addExtraButton(e=>{e.setIcon("check"),e.setTooltip("Select all"),e.onClick(()=>{this.filtered.forEach(n=>this.selectedIds.add(n.name)),this.renderList()})}).addExtraButton(e=>{e.setIcon("x"),e.setTooltip("Clear selection"),e.onClick(()=>{this.selectedIds.clear(),this.renderList()})}),new Zs.Setting(this.contentEl).setName("Import mode").setDesc("Add will append new models. Replace will overwrite existing models with the selected list.").addDropdown(e=>{e.addOption("add","Add only"),e.addOption("replace","Replace existing"),e.setValue(this.mode),e.onChange(n=>this.mode=n)}).addButton(e=>{e.setButtonText("Import selected").setCta().onClick(()=>this.importSelected())}),this.contentEl.createDiv({cls:"qa-model-directory"}),this.renderList()}renderList(){let e=this.contentEl.querySelector(".qa-model-directory");if(e){if(e.empty(),this.filtered.length===0){let n=this.loadError?`Couldn't load models: ${this.loadError}. Check the API key and endpoint.`:this.allModels.length===0?"No models available for this provider.":"No models match your filter.";e.createDiv({text:n,cls:"qa-model-directory-empty"});return}for(let n of this.filtered){let i=e.createEl("label",{cls:"qa-model-row"}),o=i.createEl("input",{type:"checkbox"});o.checked=this.selectedIds.has(n.name),o.onchange=()=>{o.checked?this.selectedIds.add(n.name):this.selectedIds.delete(n.name)},i.createDiv({text:n.name,cls:"qa-model-row-title"}),i.createDiv({text:`${n.maxTokens.toLocaleString()} tokens max`,cls:"qa-model-row-meta"})}}}importSelected(){if(this.selectedIds.size===0){new Zs.Notice("Select at least one model.");return}try{let n=this.allModels.filter(i=>this.selectedIds.has(i.name)).map(i=>({...i}));if(!n.length){new Zs.Notice("No models selected to import.");return}this.resolved=!0,this.resolvePromise({imported:n,mode:this.mode}),this.close()}catch(e){new Zs.Notice(`Import failed: ${e.message??e}`)}}onClose(){this.resolved||this.resolvePromise(null),super.onClose()}};je();function $o(r=U.getState()){let t=r.ai?.providers;return Array.isArray(t)?t:[]}function tF(r){U.setState(t=>({ai:{...t.ai,...r}}))}function Cz(r){return $o().find(t=>t.id===r)}function xz(r,t){U.setState(e=>({ai:{...e.ai,providers:e.ai.providers.map(n=>n.id===r?t(n):n)}}))}function nT(r){U.setState(t=>({ai:{...t.ai,providers:t.ai.providers.filter(e=>e.id!==r)}}))}function Ez(r){let t={...r};return delete t.lastModelSync,t}function Tz(r){let t=r.map(i=>i.name.trim()||"Untitled provider"),e=new Map;for(let i of t)e.set(i,(e.get(i)??0)+1);let n=new Set;return t.map((i,o)=>{let s=(e.get(i)??0)>1&&r[o].id?`${i} (${r[o].id})`:i;for(let a=2;n.has(s);a++)s=`${i} (${a})`;return n.add(s),s})}function dy(r){return`${r} model${r===1?"":"s"}`}function Xee(r,t){let e=Math.floor(Math.max(0,t-r)/6e4);if(e<1)return"just now";if(e<60)return`${e} minute${e===1?"":"s"} ago`;let n=Math.floor(e/60);if(n<24)return`${n} hour${n===1?"":"s"} ago`;let i=Math.floor(n/24);return`${i} day${i===1?"":"s"} ago`}function _z(r,t){let e=r.lastModelSync;if(!e)return"Not synced yet.";let n=Xee(e.at,t);return e.error?`Last sync failed ${n}: ${e.error}`:`Last synced ${n} \xB7 ${dy(r.models.length)}.`}function kz(r){switch(r.modelSource??"providerApi"){case"modelsDev":return"the models.dev directory";case"auto":return"the provider's models endpoint (falls back to models.dev)";default:return"the provider's models endpoint"}}function iT(r,t,e){r.setText(t),r.classList.toggle("mod-success",e==="success"),r.classList.toggle("mod-error",e==="error")}function Jee(r){let t=[`Context: ${r.maxTokens.toLocaleString()} tokens`];return r.maxOutputTokens&&t.push(`Output: ${r.maxOutputTokens.toLocaleString()} tokens`),r.supportsTemperature===!1&&t.push("Fixed sampling (no temperature)"),r.releaseDate&&t.push(`Released ${r.releaseDate}`),t.join(" \xB7 ")}var oT=class extends vn.SettingPage{constructor(e,n){super();this.app=e;this.providerId=n;this.unsubscribe=null;this.modelFilter="";this.modelListEl=null;this.syncStatusEl=null;this.connectionResultEl=null}get provider(){return Cz(this.providerId)}display(){this.teardown(),this.containerEl.empty();let e=this.provider;if(!e){this.containerEl.createDiv({cls:"setting-item-description",text:"This provider no longer exists."});return}this.renderConnectionGroup(e),this.renderModelSyncGroup(e),this.renderModelsGroup(),this.renderDeleteGroup();let n=e;this.unsubscribe=U.subscribe(()=>{let i=this.provider;if(!i||i===n)return;let o=n;n=i,i.models!==o.models&&this.renderModelList(),(i.lastModelSync!==o.lastModelSync||i.models.length!==o.models.length)&&this.renderSyncStatus()}),this.syncOnOpen(e)}hide(){this.teardown(),super.hide()}teardown(){this.unsubscribe?.(),this.unsubscribe=null,this.modelListEl=null,this.syncStatusEl=null,this.connectionResultEl=null}async syncOnOpen(e){if(e.autoSyncModels&&!U.getState().disableOnlineFeatures)try{await eF(this.app,this.providerId)}catch{}}edit(e){xz(this.providerId,e)}editConnection(e){this.edit(n=>Ez(e(n))),this.connectionResultEl&&iT(this.connectionResultEl,"")}close(){let e=this.app.setting;typeof e?.closePage=="function"?e.closePage():this.display()}renderConnectionGroup(e){let n=new vn.SettingGroup(this.containerEl);n.addSetting(i=>{i.setName("Name").setDesc(e.id?`ID: ${e.id}. Scripts can address this provider's models as "${e.id}/model-name".`:"The display name of the provider.").addText(o=>{o.setValue(e.name).onChange(s=>{this.edit(a=>({...a,name:s})),_C(this.app,this,s.trim()||"Untitled provider")})})}),n.addSetting(i=>{i.setName("Endpoint").setDesc("The base URL of the provider's API.").addText(o=>{o.setPlaceholder("https://api.example.com/v1"),o.setValue(e.endpoint).onChange(s=>{this.editConnection(a=>({...a,endpoint:s}))})})}),n.addSetting(i=>{i.setName("Provider type").setDesc("The request format this provider expects. Auto-detect recognizes the official Anthropic and Gemini endpoints and treats everything else as OpenAI-compatible; pick a type explicitly for a proxy or custom endpoint.").addDropdown(o=>{o.addOption("","Auto-detect"),o.addOption("openai","OpenAI-compatible"),o.addOption("anthropic","Anthropic"),o.addOption("gemini","Gemini"),o.setValue(e.kind??""),o.onChange(s=>{this.editConnection(a=>({...a,kind:s||void 0}))})})}),n.addSetting(i=>{W$(i,this.app,{value:e.apiKeyRef??"",hasLegacyKey:!!e.apiKey&&!e.apiKeyRef,onChange:o=>{this.editConnection(s=>({...s,apiKeyRef:o,apiKey:""}))}})}),n.addSetting(i=>{i.setName("Connection").setDesc("Check that QuickAdd can reach this provider's models endpoint with the linked key.");let o=i.descEl.createDiv({cls:"qa-ai-status-line"});this.connectionResultEl=o,i.addButton(s=>{s.setButtonText("Test connection").onClick(async()=>{let a=this.provider;if(a){s.setDisabled(!0),iT(o,"Testing\u2026");try{let l=await tT(this.app,a);iT(o,wz(l),l.ok?"success":"error")}finally{s.setDisabled(!1)}}})})})}renderModelSyncGroup(e){let n=kz(e),i=new vn.SettingGroup(this.containerEl).setHeading("Model sync");i.addSetting(o=>{o.setName("Model source").setDesc("Where QuickAdd looks when browsing or syncing models for this provider.").addDropdown(s=>{s.addOption("providerApi","Provider models endpoint (requires API key)"),s.addOption("modelsDev","models.dev directory"),s.addOption("auto","Automatic (try provider, fall back to models.dev)"),s.setValue(e.modelSource??"providerApi"),s.onChange(a=>{this.editConnection(l=>({...l,modelSource:a})),this.display()})})}),i.addSetting(o=>{o.setName("Auto-sync models").setDesc(`Import new models and refreshed context limits from ${n} once a day and when this page opens.`),this.syncStatusEl=o.descEl.createDiv({cls:"qa-ai-status-line"}),this.renderSyncStatus(),o.addToggle(s=>{s.setValue(!!e.autoSyncModels).onChange(a=>{this.edit(l=>({...l,autoSyncModels:a}))})}).addButton(s=>{s.setButtonText("Sync now").onClick(()=>this.syncNow(s))})}),i.addSetting(o=>{o.setName("Browse models").setDesc(`Pick models to import from ${n}.`).addButton(s=>{s.setButtonText("Browse\u2026").onClick(()=>this.browseModels())})})}async syncNow(e){let n=this.provider;if(!n)return;let i=kz(n),o=n.models.map(s=>({...s}));e.setDisabled(!0);try{let s=await eF(this.app,this.providerId),a=this.provider;if(!s||!a)return;let l=new Set(s.map(d=>d.name)),c=Z$(o,a.models.filter(d=>l.has(d.name)));new vn.Notice(c.added>0||c.updated>0?`Synced from ${i}: ${c.added} new, ${c.updated} updated.`:`Synced from ${i}: already up to date.`)}catch(s){new vn.Notice(`Sync failed: ${s.message??String(s)}`)}finally{e.setDisabled(!1)}}async browseModels(){let e=this.provider;if(!e)return;let n=await new rT(this.app,e).waitForClose;if(!n)return;let{imported:i,mode:o}=n;this.edit(s=>({...s,models:o==="replace"?i:K$(s.models,i)})),new vn.Notice(`Imported ${dy(i.length)}${o==="replace"?" (replaced the list)":""}.`)}renderModelsGroup(){let e=new vn.SettingGroup(this.containerEl).setHeading("Models").addClass("mod-list","qa-ai-models-group");e.addSearch(n=>{n.setPlaceholder("Filter models").setValue(this.modelFilter).onChange(i=>{this.modelFilter=i,this.renderModelList()})}),e.addExtraButton(n=>{n.setIcon("plus").setTooltip("Add model").onClick(()=>{this.addModel()})}),this.modelListEl=e.listEl,this.renderModelList()}renderModelList(){let e=this.modelListEl,n=this.provider;if(!e||!n)return;e.empty();let i=n.models.filter(a=>a.deprecated);if(i.length>0){let a=new Set(i.map(c=>c.name));new vn.Setting(e).setName(`${dy(i.length)} retired by the provider`).setDesc("Requests to them may fail. Commands that use them need another model.").addButton(c=>{c.setButtonText("Remove retired").onClick(async()=>{await Ei(this.app,{title:`Remove ${dy(a.size)} retired by the provider from ${n.name}?`,action:"Remove"})&&this.edit(u=>({...u,models:u.models.filter(p=>!a.has(p.name))}))})}).settingEl.addClass("qa-ai-retired-notice")}let o=this.modelFilter.trim().toLowerCase(),s=lp(n.models).filter(a=>!o||a.name.toLowerCase().includes(o));if(s.length===0){new vn.Setting(e).setName(o?`No models match "${this.modelFilter.trim()}".`:"No models yet. Sync, browse, or add one.").settingEl.addClass("mod-empty-state");return}for(let a of s){let l=new vn.Setting(e).setName(a.name).setDesc(Jee(a));a.deprecated&&l.nameEl.createSpan({cls:"qa-ai-model-badge",text:"Retired"}),l.addExtraButton(c=>{c.setIcon("trash-2").setTooltip("Delete model").onClick(()=>{this.deleteModel(a.name)})})}}async deleteModel(e){await Ei(this.app,{title:`Delete ${e}?`,action:"Delete"})&&this.edit(i=>({...i,models:i.models.filter(o=>o.name!==e)}))}async addModel(){let e,n;try{e=await ir.Prompt(this.app,"Model name"),n=await ir.Prompt(this.app,"Context window (tokens)")}catch{return}let i=e.trim();if(!i){new vn.Notice("Model name cannot be empty.");return}let o=n.trim();if(!/^[1-9]\d*$/.test(o)||!Number.isSafeInteger(Number(o))){new vn.Notice("The context window must be a positive whole number.");return}if(this.provider?.models.some(s=>s.name===i)){new vn.Notice(`${i} is already in the list.`);return}this.edit(s=>({...s,models:[...s.models,{name:i,maxTokens:Number(o)}]}))}renderSyncStatus(){let e=this.provider;!this.syncStatusEl||!e||iT(this.syncStatusEl,_z(e,Date.now()),e.lastModelSync?.error?"error":void 0)}renderDeleteGroup(){new vn.SettingGroup(this.containerEl).addSetting(e=>{e.setName("Delete provider").setDesc("Commands that use its models will need another model.").addButton(n=>{n.setButtonText("Delete").setDestructive().setCta().onClick(async()=>{let i=this.provider;!i||!await Ei(this.app,{title:`Delete ${i.name.trim()||"this provider"}?`,message:"Commands that use its models will need another model.",action:"Delete"})||(nT(this.providerId),this.close())})})})}};var sT="AI Assistant";function Zee(r){return r===0?"No providers":`${r} provider${r===1?"":"s"}`}function Sz(r){return $o().find(e=>e.id===r)?.models.filter(e=>e.deprecated).length??0}function Az(r){return JSON.stringify(r.map(t=>[t.id,t.name,t.endpoint]))}function Iz(r){return{type:"page",name:sT,desc:"Providers, models, and defaults for AI commands.",displayValue:()=>Zee($o().length),visible:()=>!U.getState().disableOnlineFeatures,items:[ete(r),nte()]}}function ete(r){let t=$o(),e=Tz(t);return{type:"list",heading:"Providers",emptyState:"No providers yet. Add one to use AI commands.",addItem:{name:"Add provider",action:()=>{tte(r)}},onDelete:n=>{rte(r,t[n])},items:t.map((n,i)=>({type:"page",name:e[i],desc:n.endpoint,displayValue:()=>{let o=Sz(n.id);return o?`${o} retired`:""},status:()=>Sz(n.id)?"warning":null,page:()=>new oT(r,n.id??"")}))}}async function tte(r){let t=[...$o()],e=t.length;await new eT(r,t).waitForClose;let n=t.slice(e);n.length!==0&&U.setState(i=>({ai:{...i.ai,providers:[...$o(i),...n]}}))}async function rte(r,t){if(!t?.id)return;await Ei(r,{title:`Delete ${t.name.trim()||"this provider"}?`,message:"Commands that use its models will need another model.",action:"Delete"})&&nT(t.id)}function nte(){return{type:"group",heading:"Defaults",items:[{name:"Default model",desc:"The model new AI commands start with. \u201CAsk me\u201D prompts you to choose a model each run.",aliases:["AI provider","provider","API key","LLM"],render:r=>ite(r)},{name:"Prompt template folder",desc:"The folder QuickAdd reads prompt templates from.",control:{type:"folder",key:"ai.promptTemplatesFolderPath",placeholder:"prompts/"}},{name:"Show assistant",desc:"Show progress notices while the AI Assistant works.",control:{type:"toggle",key:"ai.showAssistant"}},{name:"Confirm AI tool calls",desc:"When an AI agent runs script-defined or built-in tools, ask before executing. A tool that requires approval is always confirmed.",control:{type:"dropdown",key:"ai.confirmToolCalls",defaultValue:"destructive",options:{destructive:"Destructive tools only (recommended)",always:"Always confirm every tool",never:"Never (use each tool's own setting)"}}},{name:"Default system prompt",desc:"The system prompt new AI commands start with.",render:r=>ote(r)}]}}function ite(r){let t=()=>{};return r.addDropdown(e=>{let n=()=>{let o=U.getState().ai;e.selectEl.empty(),Bx(e,{model:o.defaultModel,modelRef:o.defaultModelRef},s=>tF({defaultModel:s.model,defaultModelRef:s.modelRef}))};n();let i=$o();t=U.subscribe(o=>{let s=$o(o);s!==i&&(i=s,n())})}),()=>t()}function ote(r){r.settingEl.addClass("qa-ai-system-prompt-setting");let t=U.getState().ai.defaultSystemPrompt??"";r.addTextArea(e=>{e.inputEl.addClass("qa-ai-system-prompt-input"),e.inputEl.setAttribute("aria-label","Default system prompt");let n=fx(r.controlEl,e.inputEl,t);e.setValue(t).onChange(i=>{tF({defaultSystemPrompt:i}),n(i)})})}nt();var aT="ai.",cT=class extends uy.PluginSettingTab{constructor(e,n){super(e,n);this.choiceView=null;this.globalVariablesViewHandle=null;this.packagesUnsubscribe=null;this.plugin=n,this.icon="zap";let i=$o().map(a=>({...a}));Xb(i)&&U.setState(a=>({ai:{...a.ai,providers:i}}));let o=a=>JSON.stringify([Az($o(a)),ti(a.templateFolderPaths)]),s=o(U.getState());n.register(U.subscribe(a=>{let l=o(a);l!==s&&(s=l,this.update())}))}openAIAssistantPageFromCommand(){if(U.getState().disableOnlineFeatures){new uy.Notice("QuickAdd: Turn off \u201CDisable AI & online features\u201D in QuickAdd settings to use the AI Assistant.");return}mc(this.app,this.plugin.manifest.id)&&this.openAIAssistantPage()}openAIAssistantPage(){K1(this.app,this,[sT])||new uy.Notice(`QuickAdd: Open the ${sT} page under "AI & online" below.`)}getControlValue(e){let n=U.getState();if(e.startsWith(aT)){let i=e.slice(aT.length);return n.ai[i]}return e==="inputPrompt"?n.inputPrompt==="multi-line":n[e]}setControlValue(e,n){if(e.startsWith(aT)){let i=e.slice(aT.length);U.setState(o=>({ai:{...o.ai,[i]:n}}));return}if(e==="inputPrompt"){U.setState({inputPrompt:n?"multi-line":"single-line"});return}if(e==="persistInputPromptDrafts"){let i=!!n;U.setState({persistInputPromptDrafts:i}),i||Bn.getInstance().clearAll();return}U.setState({[e]:n})}getSettingDefinitions(){return nz({choices:e=>this.renderChoicesView(e),packages:e=>this.renderPackages(e),dateAliases:e=>this.renderDateAliases(e),globalVariables:e=>this.renderGlobalVariablesView(e),developmentInfo:e=>this.renderDevInfo(e)},!1,Iz(this.app),this.templateFoldersList())}templateFoldersList(){let e=lT(),n={name:"Add folder",action:()=>{this.addTemplateFolder()}},i=["Template folders"];return e.length===0?{type:"group",heading:"Template folders",items:[{...n,desc:"No folders yet. QuickAdd suggests templates from the whole vault.",aliases:i}]}:{type:"list",heading:"Template folders",addItem:n,onDelete:o=>{U.setState({templateFolderPaths:lT().filter(s=>s!==e[o])})},items:e.map(o=>({name:o,aliases:i}))}}async addTemplateFolder(){let e=new Set(lT()),n=Ja(za(this.app)).filter(s=>s!=="/"&&!e.has(s)),i;try{i=await It.Suggest(this.app,n,n,"Choose a template folder")}catch(s){if(Be(s))return;throw s}let o=lT();o.includes(i)||U.setState({templateFolderPaths:[...o,i]})}hide(){super.hide(),this.destroySettingViews()}destroySettingViews(){this.choiceView?.handle.destroy(),this.choiceView=null,this.globalVariablesViewHandle?.destroy(),this.globalVariablesViewHandle=null,this.packagesUnsubscribe?.(),this.packagesUnsubscribe=null}prepareFullWidthSetting(e){e.infoEl.remove(),e.settingEl.addClass("qa-setting-full-width"),e.controlEl.addClass("qa-setting-full-width-control")}mountView(e,n){this.prepareFullWidthSetting(e),this.globalVariablesViewHandle?.destroy();let i=n(e.controlEl);return this.globalVariablesViewHandle=i,()=>{i.destroy(),this.globalVariablesViewHandle===i&&(this.globalVariablesViewHandle=null)}}renderChoicesView(e){if(this.prepareFullWidthSetting(e),!this.choiceView){let i=createDiv(),o=this.mountChoiceView(i);if(!o.ok)return e.controlEl.appendChild(i),()=>o.destroy();this.choiceView={el:i,handle:o}}let{el:n}=this.choiceView;return e.controlEl.appendChild(n),()=>n.remove()}mountChoiceView(e){return wi(e,a$,{app:this.app,plugin:this.plugin,choices:U.getState().choices,saveChoices:n=>{U.setState({choices:n})},openAISettings:()=>this.openAIAssistantPage()},{what:"your choices",fallbackComponent:sf})}renderGlobalVariablesView(e){return this.mountView(e,n=>wi(n,l$,{app:this.app,plugin:this.plugin},{what:"your global variables"}))}packagesDesc(e){return H$(e?`${GE} Export becomes available once you have a choice. `:`${GE} `,is.packages,"Learn more about packages")}renderPackages(e){let n;e.addButton(a=>{n=a,a.setButtonText("Export package\u2026").onClick(()=>{let l=mr(U.getState().choices);new EE(this.app,this.plugin,l).open()})}),e.addButton(a=>a.setButtonText("Import package\u2026").onClick(()=>{new HE(this.app,{onImported:(l,c)=>WE(this.plugin,c,l)}).open()}));let i=a=>{e.setDesc(this.packagesDesc(a)),n&&(n.setDisabled(a),a?n.setTooltip("Nothing to export yet"):n.buttonEl.removeAttribute("aria-label"))},o=mr(U.getState().choices).length===0;i(o),this.packagesUnsubscribe?.();let s=U.subscribe(a=>{let l=mr(a.choices).length===0;l!==o&&(o=l,i(l))});return this.packagesUnsubscribe=s,()=>{s(),this.packagesUnsubscribe===s&&(this.packagesUnsubscribe=null)}}renderDateAliases(e){e.settingEl.addClass("qa-date-alias-setting"),e.controlEl.addClass("qa-date-alias-control");let n=null;e.addTextArea(i=>{n=i,i.setPlaceholder(`t = today
|
||
tm = tomorrow
|
||
yd = yesterday`).setValue(yS(U.getState().dateAliases)).onChange(o=>{U.setState({dateAliases:pD(o)})}),i.inputEl.addClass("qa-date-alias-input")}),e.addButton(i=>{i.setButtonText("Reset to defaults").onClick(()=>{U.setState({dateAliases:cp}),n?.setValue(yS(cp))}),i.buttonEl.addClass("qa-date-alias-reset")})}renderDevInfo(e){let n=e.settingEl.createDiv();n.addClass("qa-dev-info"),rz(n,{branch:null,commit:null,dirty:null})}};function lT(){return ti(U.getState().templateFolderPaths)}bS();ye();sw();nt();var py=class extends Dp{constructor(){super(...arguments);this.ErrorLog=[]}logError(e,n,i){let o=this.getQuickAddError(e,"ERROR",n,i);this.addMessageToErrorLog(o);let s=i||new Error(e);console.error(this.formatOutputString(o),s)}logWarning(e,n,i){let o=this.getQuickAddError(e,"WARNING",n,i);this.addMessageToErrorLog(o);let s=i||new Error(e);console.warn(this.formatOutputString(o),s)}logMessage(e,n,i){let o=this.getQuickAddError(e,"LOG",n,i);this.addMessageToErrorLog(o)}addMessageToErrorLog(e){this.ErrorLog.push(e),this.ErrorLog.length>OS&&(this.ErrorLog=this.ErrorLog.slice(-OS))}clearErrorLog(){this.ErrorLog=[]}};var rF=require("obsidian");sw();var dT=class extends Dp{constructor(e){super();this.plugin=e}logError(e,n,i){let o=this.getQuickAddError(e,"ERROR",n,i);new rF.Notice(this.formatOutputString(o),15e3)}logWarning(e,n,i){let o=this.getQuickAddError(e,"WARNING",n,i);new rF.Notice(this.formatOutputString(o))}logMessage(e,n,i){}};ye();nt();nt();var Pz=1e4,$z=50,ste=/plugin:([^\s:)]+)/;function ate(r){let t=r.stack??"",e=`${r.name}: ${r.message}`;return(t.startsWith(e)?t.slice(e.length):t).split(`
|
||
`)}function lte(r){for(let t of ate(r)){let e=ste.exec(t);if(e)return{pluginId:e[1],frame:t.trim()}}return null}function cte(r,t){return`${r.name}@${t}`}function Fz(r,t=Date.now){let e=r.manifest.id,n=new Map;r.registerDomEvent(window,"unhandledrejection",i=>{let o=i.reason,s=o instanceof Error?lte(o):null;if(s?.pluginId!==e)return;if(Be(o)){i.preventDefault();return}let a=o,l=cte(a,s.frame),c=t(),d=n.get(l);if(n.set(l,c),!(d!==void 0&&c-d<Pz)){if(n.size>=$z){for(let[u,p]of n)c-p>=Pz&&n.delete(u);if(n.size>=$z){let u=n.keys().next();!u.done&&u.value!==l&&n.delete(u.value)}}Me(a,"A QuickAdd action failed")&&i.preventDefault()}})}Sy();lt();nt();var M_=class{constructor(t,e,n,i){this.app=t;this.plugin=e;this.choices=n;this.choiceExecutor=i}async run(){let t=Zt(this.choices).filter(e=>e.type==="Macro"&&e.runOnStartup);for(let e of t)try{await new ta(this.app,this.plugin,e,this.choiceExecutor,new Map).run()}catch(n){Me(n,`Startup macro '${e.name}' failed`)}}};var PG=require("obsidian");MT();vl();ye();Ua();Nc();$_();qd();Ay();function R_(r,t){return!t.enabled||t.destination.type!=="specifiedFile"||bg(r,t.destination)?null:`Append link target file not found or is not a Markdown file: ${t.destination.path}`}async function O_(r,t,e,n,i){if(!e.enabled)return;let o=kr(r,n),s=PT(n),a=!s||n.focusedProperty?.file.path===o?.path?n.focusedProperty:null;e.destination?.type==="specifiedFile"?await hL(r,t,e,i):a&&!Ba(e.placement)?await U2(r,a,t):await j2(r,t,o,e,i,s)}async function D_(r){try{await gL(r)}catch(t){S.logWarning(`Could not copy link to clipboard for '${r.path}': ${t instanceof Error?t.message:String(t)}`)}}async function Bf({app:r,file:t,opening:e,originLeaf:n,forceFocus:i}){let o=rn(e),s=i??o.focus??!0;return tG(r,t,s)||await P_(r,t,{...o,...i===void 0?{}:{focus:i},originLeaf:n}),s}var qf=require("obsidian");Nd();Le();YT();Qi();ye();Za();var N_=require("obsidian");rr();Za();$f();var L_=class extends N_.FuzzySuggestModal{constructor(e,n,i){super(e);this.settled=!1;this.modalEl.addClass("qa-suggester"),this.rows=i.map(o=>({kind:"candidate",candidate:o})),this.action=fc(n.existingNoteAction),this.promise=new Promise((o,s)=>{this.resolvePromise=o,this.rejectPromise=s}).then(o=>o.kind==="candidate"?zy(o.candidate.item):oa(o.title)),this.setPlaceholder(`Search notes or create ${n.name}`),this.open()}getItems(){return this.rows}getItemText(e){return e.kind==="candidate"?e.candidate.display:e.title}getSuggestions(e){let n=e.trim(),i=to(n),o=a=>a.kind==="candidate"&&a.candidate.exactKeys.includes(i),s=super.getSuggestions(n).sort((a,l)=>Number(o(l.item))-Number(o(a.item)));return n&&!this.rows.some(o)&&s.unshift({item:{kind:"create",title:n},match:{score:Number.NEGATIVE_INFINITY,matches:[]}}),s}renderSuggestion({item:e},n){if(e.kind==="candidate"&&e.candidate.renderPath){let o=e.candidate;Jm(n,e.candidate.renderPath),this.action!=="Open"&&n.querySelector(".suggestion-title")?.prepend(`${this.action}: `),o.renderAlias&&n.querySelector(".suggestion-content")?.createDiv({cls:"suggestion-note",text:`Alias: ${o.renderAlias}`});return}n.addClass("mod-complex");let i=n.createDiv({cls:"suggestion-content"});i.createDiv({cls:"suggestion-title",text:e.kind==="create"?`Create new note: ${e.title}`:e.candidate.unresolvedTitle??e.candidate.title}),e.kind==="create"?(0,N_.setIcon)(n.createDiv({cls:"suggestion-aux"}).createSpan({cls:"suggestion-flair"}),"file-plus"):i.createDiv({cls:"suggestion-note",text:"Unresolved link"})}selectSuggestion(e,n){this.settled=!0,super.selectSuggestion(e,n)}onChooseItem(e){this.settled=!0,this.resolvePromise(e)}onClose(){super.onClose(),this.settled||this.rejectPromise(on())}};_u();ku();Sn();nt();rr();Za();$f();async function mG(r,t,e){let{candidates:n}=n_(r,t),i=`Search notes or create ${t.name}`,o=fc(t.existingNoteAction);try{let s=await Zi(e,{remote:async a=>{let l=await eo(a,{items:n.map(c=>({value:zy(c.item),title:c.renderPath&&o!=="Open"?`${o}: ${c.title}`:c.title})),placeholder:i,allowCustomInput:!0,what:"the note-discovery picker"});return typeof l=="string"?oa(l):l},headless:()=>{throw new de(`'${t.name}' needs to ask which note to open or create, but this run is non-interactive. Pass the note name (e.g. value-value=<name>), or re-run with the ui flag.`)},app:()=>new L_(r,t,n).promise});return Hy(r,s)}catch(s){throw Be(s)?new et("Input cancelled by user"):s}}$f();ou();Rf();_u();ku();Ua();bi();Uc();Nc();vl();nt();var Uf=class{constructor(t){this.executor=t;this.closed=!1}success(t,e){this.closed=!0,this.executor.recordExecutionResult?.({status:"success",file:t,effect:e})}failure(t){this.closed||this.executor.recordExecutionResult?.({status:"error",reason:t})}};function V_(r){return r instanceof Error?r.message||fG:String(r)||fG}var fG="Choice execution failed.";es();Dm();zT();jT();ri();Sn();ky();Dr();function B_(r,t){if(r.content!==t.before)return null;let e=[...t.edits].sort((s,a)=>s.from-a.from),n="",i=0;for(let s of e){if(s.from<i||s.to<s.from||s.to>t.before.length)return null;n+=t.before.slice(i,s.from)+s.text,i=s.to}if(n+=t.before.slice(i),n!==t.after)return null;let o=[];for(let s of r.offsets){let a=0;for(let l of e){let c=l.from!==l.to;if(c&&l.from<=s&&s<l.to)return null;(l.to<s||c&&l.to===s)&&(a+=l.text.length-(l.to-l.from))}o.push(s+a)}return{offsets:o,content:n}}Jt();var U_=class extends qc{constructor(e,n,i,o,s=null,a=[i]){super(e,n,o);this.originLeaf=s;this.chain=a;this.choiceExecutor=o,this.outcome=new Uf(o),this.choice=i,this.formatter.setPromptRunContext({draftScopeId:i.id,choiceName:i.name}),this.formatter.choiceChain=a}async run(){this.cursorPlacement=null;let e=null,n=null,i=null;try{Vr(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 o=Zo(this.choice.appendLink);this.setLinkToCurrentFileBehavior(o.enabled&&!o.requireActiveFile?"optional":"required");let s=this.choice.fileNameFormat.enabled?this.choice.fileNameFormat.format:xr;if(xc(this.choice,s,this.choiceExecutor.variables.get("value"))){let h=eW(this.choiceExecutor,this.choice.id),g=h?Hy(this.app,h):await mG(this.app,this.choice,this.choiceExecutor);if(g.kind==="existing"){let v=AC(this.choice.existingNoteAction);if(v==="open"){await this.openDiscoveredExistingNote(g.file),this.outcome.success(g.file,"unchanged");return}i={file:g.file,mode:v},e=this.setTemporaryValueVariable(g.file.basename)}else e=this.setTemporaryValueVariable(g.title),n=g.vaultRelativePath??null;await this.choiceExecutor.resolveDateOrigin?.(this.choice)}if(!this.validateAppendLinkDestination(o))return;let a=await this.resolveTemplateSourcePath(this.choice.templatePath);if(i&&nn(this.app,a)?.path===i.file.path)throw new de("Cannot apply a template to its own template source.");let l=i?.file.path??await this.resolveNewNotePath({templatePath:a,format:s,discoveryVaultRelativePath:n}),c,d=!1,u=!1,p="created";if(i){if(!Hc(a))throw new de("Only Markdown templates can be applied to a selected note.");if(c=await this.applyExistingFileUpdate(i.mode,i.file,a,o),!c){this.failRun(this.lastTemplateFileFailure??`Could not apply template to '${l}'.`,"none");return}p="changed"}else if(await this.app.vault.adapter.exists(l)){let h=await this.getSelectedFileExistsMode(),g=am(h);p=g.resolutionKind==="reuseExisting"?"unchanged":g.resolutionKind==="createNew"?"created":"changed";let v=g.requiresExistingFile?this.findExistingFile(l):null;if(g.requiresExistingFile&&(!(v instanceof qf.TFile)||v.extension!=="md"&&v.extension!=="canvas"&&v.extension!=="base")){this.failRun(`'${l}' already exists but could not be resolved as a markdown, canvas, or base file.`);return}if({createdFile:c,shouldAutoOpen:d}=await this.applyFileExistsMode(h,l,v,a,o),!c){this.lastTemplateFileFailure?this.failRun(this.lastTemplateFileFailure,"none"):this.failRun(`Could not resolve file exists behavior for '${l}'.`,"warning");return}}else{if(c=await this.createFileWithTemplate(l,a),!c){this.failRun(this.lastTemplateFileFailure??`Could not create file '${l}'.`,"none");return}u=!0}this.outcome.success(c,p);let m=this.cursorPlacement;if(o.enabled&&c)try{await O_(this.app,c,o,this.choiceExecutor,this.cursorPlacement?h=>{this.cursorPlacement&&h.filePath===c?.path&&(this.cursorPlacement=B_(this.cursorPlacement,h))}:void 0)}catch(h){if(h instanceof at)throw h;S.logWarning(`Created '${c.basename}' but could not insert the link: ${h instanceof Error?h.message:String(h)}`)}this.choice.copyLinkToClipboard&&c&&await D_(c),(this.choice.openFile||d)&&c?(await Bf({app:this.app,file:c,opening:this.choice.fileOpening,originLeaf:this.originLeaf}),!this.templaterCursorHandled&&!await Tu(this.app,c)&&this.placeCursor(c,m)):this.cursorPlacement&&ai(this.app,c)?!this.templaterCursorHandled&&!await Tu(this.app,c)&&this.placeCursor(c,m):u&&!o.enabled&&!this.choice.copyLinkToClipboard&&new qf.Notice(`Created '${c.basename}'.`)}catch(o){if(Dc(o,{logPrefix:"Template execution aborted",noticePrefix:"Template execution aborted",defaultReason:"Template execution aborted"})){this.choiceExecutor.signalAbort?.(o);return}Bn.getInstance().markExecutionScopeFailed(),this.outcome.failure(V_(o)),Me(o,`Error running template choice "${this.choice.name}"`)}finally{e?.()}}failRun(e,n="error"){Bn.getInstance().markExecutionScopeFailed(),n==="warning"?S.logWarning(e):n==="error"&&S.logError(e),this.outcome.failure(e)}async resolveNewNotePath({templatePath:e,format:n,discoveryVaultRelativePath:i}){let o="";if(i)o=ei(i);else if(this.choice.folder.enabled)o=await this.getFolderPath();else{let u=this.app.fileManager.getNewFileParent(kr(this.app,this.choiceExecutor)?.path??"");o=u===this.app.vault.getRoot()?"":u.path}this.formatter.setTargetFolderPath(o),this.choice.folder.enabled&&this.formatter.setPromptRunContext({destination:o,destinationKind:"folder"});let s=i||await this.formatter.formatFileName(n,"noteTitle"),a=Br(s,"File name"),{fileName:l,strippedPrefix:c}=i?{fileName:a,strippedPrefix:!1}:this.stripDuplicateFolderPrefix(a,o),d=this.shouldTreatFormattedNameAsVaultRelativePath(a,c,this.choice.folder.enabled);return this.normalizeTemplateFilePath(i||d?"":o,l,e)}setTemporaryValueVariable(e){let n=this.choiceExecutor.variables,i=n.has("value"),o=n.get("value");return n.set("value",e),()=>{if(i){n.set("value",o);return}n.delete("value")}}validateAppendLinkDestination(e){let n=R_(this.app,e);return n?(this.failRun(n),!1):!0}async getSelectedFileExistsMode(){var i;if((i=this.choice).fileExistsBehavior??(i.fileExistsBehavior={kind:"prompt"}),this.choice.fileExistsBehavior.kind==="apply")return this.choice.fileExistsBehavior.mode;let e=sV(),n="If the target file already exists";return await Zi(this.choiceExecutor,{remote:o=>eo(o,{items:e.map(s=>({value:s.id,title:s.label})),placeholder:n,what:'the "file already exists" chooser'}),headless:()=>{throw new de(`'${this.choice.name}' needs to ask what to do because a note with that name already exists, but this run is non-interactive. Set the choice's "If the file already exists" behaviour to a specific action (e.g. Increment, Overwrite), or re-run with the ui flag.`)},app:()=>It.Suggest(this.app,e.map(o=>o.label),e.map(o=>o.id),n)})}async applyFileExistsMode(e,n,i,o,s){let a=am(e);switch(a.resolutionKind){case"modifyExisting":return{createdFile:await this.applyExistingFileUpdate(a.id,i,o,s),shouldAutoOpen:!1};case"createNew":{let l=await dV(n,a.id,async d=>await this.app.vault.adapter.exists(d)),c=await this.createFileWithTemplate(l,o);return c&&l!==n&&!this.choice.openFile&&new qf.Notice(`Created '${c.basename}'.`),{createdFile:c,shouldAutoOpen:!1}}case"reuseExisting":return S.logMessage(`Opening existing file: ${i.path}`),{createdFile:i,shouldAutoOpen:!0}}}async openDiscoveredExistingNote(e){await Bf({app:this.app,file:e,opening:this.choice.fileOpening,originLeaf:this.originLeaf,forceFocus:!0})}async applyExistingFileUpdate(e,n,i,o){return e==="overwrite"?this.overwriteFileWithTemplate(n,i):this.appendToExistingFileWithTemplate(n,i,e==="appendTop"?"top":"bottom",o)}async appendToExistingFileWithTemplate(e,n,i,o){if(e.extension==="canvas"||e.extension==="base")return this.lastTemplateFileFailure=`Cannot append to '${e.path}': appending a template to a ${e.extension} file would corrupt it. Use the "Overwrite" file-exists option instead.`,Bn.getInstance().markExecutionScopeFailed(),S.logError(this.lastTemplateFileFailure),null;if(e.extension!=="md")return await this.appendToFileWithTemplate(e,n,i);let s=new kf(this.app,this.plugin,e,n,i,this.choiceExecutor,n);s.setPromptRunContext({draftScopeId:this.choice.id,choiceName:this.choice.name,destination:e.path,destinationKind:"file"}),s.choiceChain=this.chain,s.setLinkToCurrentFileBehavior(o.enabled&&!o.requireActiveFile?"optional":"required");let a=await this.withAnonymousValueForInsertEngine(()=>s.apply());return this.cursorPlacement=s.getCursorPlacement(),a}async withAnonymousValueForInsertEngine(e){let n=this.formatter.getAnonymousValue(),i=this.choiceExecutor.variables;if(!(n!==void 0&&!i.has("value")))return await e();let s=this.setTemporaryValueVariable(n);try{return await e()}finally{s()}}findExistingFile(e){let n=this.app.vault.getAbstractFileByPath(e);if(n instanceof qf.TFile)return n;if(n)return null;let i=e.toLowerCase(),o=this.app.vault.getFiles().filter(s=>s.path.toLowerCase()===i);if(o.length===1)return o[0];if(o.length>1){let s=o.map(a=>a.path).join(", ");S.logError(`Multiple files match '${e}' when ignoring case: ${s}`)}return null}async formatFolderPaths(e){let n=[];for(let i of e)n.push(await this.formatter.formatFolderPath(i));return n}async getFolderPath(){let e=this.choice.folder,n=e?.chooseWhenCreatingNote?[]:(await this.formatFolderPaths([...e.folders])).map(l=>this.canonicalFolderPath(l)),i=this.getCurrentFolderSuggestion(),o=i?[i]:[],s=n,a=n;if(e?.chooseWhenCreatingNote)s=Ja(za(this.app)),a=void 0;else if(e?.createInSameFolderAsActiveFile){let l=kr(this.app,this.choiceExecutor);if(!l||!l.parent)return S.logWarning("No active file or active file has no parent. Cannot create file in same folder as active file. Creating in root folder."),"";s=[l.parent.path],a=void 0}else e?.chooseFromSubfolders&&(s=L1(Ja(za(this.app)),n));return this.getOrCreateFolder(s,{allowCreate:!0,allowedRoots:a,topItems:o,executor:this.choiceExecutor})}getCurrentFolderSuggestion(){let e=kr(this.app,this.choiceExecutor),n=e?.parent;return!e||!n?null:{path:n.path??"",label:"<current folder>"}}};Ma();vf();Nc();qd();var aa=require("obsidian");sl();cl();Nd();Ns();Le();x_();Ma();Pp();Lc();x_();bu();$M();__();function hG({capture:r,targetString:t,fileContent:e,insertAfter:n,task:i}){let o=r.content,s=n?.orderBy??{by:"insertion",direction:"desc",unparseable:"bottom"},a=t.split(/\r?\n/,1)[0],l=si([a])[0]?.level??0,c=Fa(r,`${t}
|
||
`),d=()=>{let w=wu(e,c.content,{separateBlockquotes:!0});return Wl(c,w.content,w.insertedStartOffset===null||c.cursor.kind==="none"?null:w.insertedStartOffset+c.cursor.value)};if(l===0)return d();let u=Zl(e),p=u.map(w=>w.replace(/\r$/,"")),m=OM(e),h=Xy(p),g=a.replace(/\r$/,"").trimEnd(),v=h.findIndex((w,T)=>T>=m&&w.trimEnd()===g);if(v!==-1){let w=n?.insertAtEnd?Jy(h,xl(h,v,E_(!!n?.considerSubsections,h,v))??h.length-1,e,o):T_(h,v,e,n?.blankLineAfterMatchMode??"auto"),T=Df(o,e,w,i,r.cursor.kind==="offset"?r.cursor.value:void 0);return Wl(r,T.content,T.insertedEndOffset)}let b=typeof window<"u"?window.moment:void 0,y=vW(p,a,l,s,b,m);if(y.mode==="bodyStart")return d();let C=_W(u,y,c.content,e,c.cursor.kind==="offset"&&c.cursor.source==="marker"?c.cursor.value:void 0);return Wl(c,C.content,C.insertedEndOffset)}sl();Nc();vl();Pp();Le();Uc();Sn();Ma();Su();vf();__();Lc();Dr();Px();var bie=/^[ \t\r\n\f\v]*$/;function wie(r){return bie.test(r)}var q_=class extends Ai{constructor(){super(...arguments);this.file=null;this.fileContent="";this.sourcePath=null;this.useSelectionAsCaptureValue=!0;this.clipboardImageFallbackEnabled=!1;this.createdClipboardAttachmentPaths=[];this.templaterProcessed=!1;this.insertAfterTargetOverride=null;this.lastResolvedInsertAfterHeading=null;this.linebreaksProcessed=!1;this.splitValueLines=!1}setDestinationFile(e){this.file=e,this.sourcePath=e.path,this.clipboardAttachmentLink=void 0,this.setTargetFolderPath(ei(e.path)),this.setPromptRunContext({destination:e.path,destinationKind:"file"})}setDestinationSourcePath(e){this.sourcePath=e,this.file=null,this.clipboardAttachmentLink=void 0,this.setTargetFolderPath(ei(e)),this.setPromptRunContext({destination:e,destinationKind:"file"})}setUseSelectionAsCaptureValue(e){this.useSelectionAsCaptureValue=e}setInsertAfterTargetOverride(e){this.insertAfterTargetOverride=e}getResolvedInsertAfterHeading(){return this.lastResolvedInsertAfterHeading}consumeCreatedClipboardAttachmentPaths(){let e=this.createdClipboardAttachmentPaths;return this.createdClipboardAttachmentPaths=[],e}shouldUseSelectionForValue(){return this.useSelectionAsCaptureValue}async getSelectedTextForValue(){let e=await this.getSelectedText();return e.trim().length>0?e:""}getLinkSourcePath(){return this.sourcePath??this.file?.path??null}async getClipboardContent(){let e=await super.getClipboardContent();return e.length>0||!this.clipboardImageFallbackEnabled?e:this.clipboardAttachmentLink!==void 0?this.clipboardAttachmentLink??"":(this.clipboardAttachmentLink=await this.saveClipboardImageAsAttachment(),this.clipboardAttachmentLink??"")}async withClipboardImageFallback(e){let n=this.clipboardImageFallbackEnabled;this.clipboardImageFallbackEnabled=!0;try{return await e()}finally{this.clipboardImageFallbackEnabled=n}}async saveClipboardImageAsAttachment(){let e=navigator.clipboard;if(typeof e?.read!="function")return null;let n,i;try{if(n=await this.getFirstClipboardImageItem(e),!n)return null;i=await(await n.clipboardItem.getType(n.mimeType)).arrayBuffer()}catch{return null}let o=this.getLinkSourcePath()??"",s=await Ax(this.app,i,n.mimeType,o);return this.createdClipboardAttachmentPaths.push(s.path),Ix(this.app,s,o)}async getFirstClipboardImageItem(e){let n=await e.read();for(let i of n){let o=i.types.find(s=>il[s]!==void 0);if(o)return{clipboardItem:i,mimeType:o}}return null}getCurrentFileLink(){let e=kr(this.app,this.choiceExecutor);if(!e)return null;let n=this.sourcePath??this.file?.path??"";return this.app.fileManager.generateMarkdownLink(e,n)}async formatContentWithFile(e,n,i,o){return this.captureIntoFile(e,n,i,o,!0)}async insertFormattedContent(e,n,i,o){return this.captureIntoFile(e,n,i,o,!1)}async captureIntoFile(e,n,i,o,s){if(this.choice=n,this.file=o,this.fileContent=i,!n||!o||i===null){let l=An(e);return{content:l,captureContent:l,cursor:{kind:"none"}}}this.setTargetFolderPath(ei(o.path));let a=n.insertAfter.enabled||!!n.insertBefore?.enabled||n.prepend||!n.captureToActiveFile||n.activeFileWritePosition==="top"||n.activeFileWritePosition==="bottom";return await this.formatCapture(e,a,s)}async formatContent(e,n){return this.choice=n,n?await this.formatFileContent(e):e}async formatFileContent(e,n=!0){return(await this.formatCapture(e,n)).content}async formatCapture(e,n,i=!0){let o=i?await this.withValueLines(!!this.choice?.eachLine,()=>this.withClipboardImageFallback(async()=>this.withPromptScope("captureText",e,async()=>this.withUserTextProtected(async()=>super.formatFileContent(await this.expandTemplateLinebreaksOnce(e)))))):e;if(n&&this.file&&!this.templaterProcessed){let l=await Bc(this.app,o,this.file);l&&(o=l),this.templaterProcessed=!0}let s=bT(gp(o));return{...s.cursor.kind==="none"?{content:this.fileContent,cursor:s.cursor}:await this.insertCapture(s),captureContent:s.content,markerOnly:s.cursor.kind==="none"&&/{{CURSOR}}/i.test(o)}}async insertCapture(e){return this.choice.prepend||this.choice.captureToActiveFile&&this.choice.activeFileWritePosition==="bottom"?Fa(e,this.withLastLineEnded()):this.choice.insertAfter.enabled?this.insertAfterHandler(e):this.choice.insertBefore?.enabled?this.insertBeforeHandler(e):this.insertAtNoteBodyStartTracking(e)}withLastLineEnded(){let e=this.fileContent;return e.length>0&&!e.endsWith(`
|
||
`)?`${e}
|
||
`:e}async formatContentOnly(e,n={}){let i=await this.withValueLines(n.eachLine??!1,()=>this.withClipboardImageFallback(async()=>this.withPromptScope("captureText",e,async()=>this.withUserTextProtected(async()=>super.formatFileContent(await this.expandTemplateLinebreaksOnce(e))))));return wie(i)?this.fileContent:i}async withValueLines(e,n){this.splitValueLines=e,this.defaultValueInputType=e?"multiline":void 0;try{return await n()}finally{this.splitValueLines=!1,this.defaultValueInputType=void 0}}async format(e){if(!this.splitValueLines)return super.format(e);this.splitValueLines=!1;let n=await this.expandCodeAndIncludes(e);if(!fo.test(n))return this.formatScalarTokens(n);let i=await this.resolveValue(n),o=i.split(/\r\n|\r|\n/).map(d=>d.trim()).filter(Boolean);if(o.length===0){let d=this.valuePromptContext;if(!d?.defaultValue||d.optional)return"";o.push("")}let s=await this.replaceMathValueInString(n),a=this.hasConcreteVariable("value"),l=this.variables.get("value"),c=[];try{for(let d of o)this.value=d,a&&this.variables.set("value",d),c.push(await this.formatScalarTokens(s))}finally{this.value=i,a&&this.variables.set("value",l)}return c.map((d,u)=>u<c.length-1&&!d.endsWith(`
|
||
`)?`${d}
|
||
`:d).join("")}async expandTemplateLinebreaksOnce(e){return this.linebreaksProcessed?e:(this.linebreaksProcessed=!0,this.expandFormatTemplateEscapes(e))}async expandFormatTemplateEscapes(e){let n=await this.replaceGlobalVarInString(e);return this.expandLinebreakEscapesOutsideTokens(n)}async insertAfterHandler(e){let n=e.content,i=this.insertAfterTargetOverride;if(this.choice.insertAfter?.inline&&i===null){let m=await this.formatLocationString(await this.expandFormatTemplateEscapes(this.choice.insertAfter.after));return await this.insertAfterInlineHandler(e,m)}let o=i??await this.formatLocationString(await this.expandFormatTemplateEscapes(this.choice.insertAfter.after));if(i===null){let m=o.split(`
|
||
`,1)[0];this.lastResolvedInsertAfterHeading=/^#+\s+\S/.test(m)?m.trim():null}let s=FM(o);if(MM(s))throw new de("Insert-after target is empty after formatting.");let a=Zl(this.fileContent),l=i!==null&&CW(i)?xW(a):this.isOrderedCreate()?EW(a,this.fileContent):a,{start:c,end:d}=RM(l,s);if(c===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInsertAfterIfNotFound(e,o);throw new de(`Insert-after target not found: '${o}'.`)}let p;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let m=xl(a,c,this.considerSubsectionsForAnchor(a,c)),h=Math.max(m??a.length-1,d);p=Jy(a,h,this.fileContent,n)}else{let m=this.choice.insertAfter?.blankLineAfterMatchMode??"auto";p=T_(a,d,this.fileContent,m)}return this.insertTextAfterPositionInBody(e,this.fileContent,p)}async insertBeforeHandler(e){let n=this.choice.insertBefore;if(!n)throw new de("Insert-before settings are missing.");let i=await this.formatLocationString(await this.expandFormatTemplateEscapes(n.before)),o=FM(i);if(MM(o))throw new de("Insert-before target is empty after formatting.");let s=Zl(this.fileContent),{start:a}=RM(s,o);if(a===-1){if(n.createIfNotFound)return await this.createInsertBeforeIfNotFound(e,i);throw new de(`Insert-before target not found: '${i}'.`)}return this.insertTextBeforePositionInBody(e,this.fileContent,a)}async insertAfterInlineHandler(e,n){if(bW(n))throw new de("Inline insert-after target must be a single line \u2014 remove the line break (\\n) or turn off inline insertion.");let i=this.fileContent.indexOf(n);if(i===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInlineInsertAfterIfNotFound(e,n);throw new de(`Inline insert-after target not found: '${n}'.`)}let o=i+n.length,s=this.choice.insertAfter?.replaceExisting?wW(this.fileContent,o):o;return Fa(e,this.fileContent.slice(0,o),this.fileContent.slice(s))}async createInsertAfterIfNotFound(e,n){let i=this.choice.insertAfter;if(i?.createIfNotFoundLocation===Yo)return this.createInsertAfterOrdered(e,n);let o=Fa(e,`${n}
|
||
`);return this.createMissingTarget({payload:o,location:i?.createIfNotFoundLocation,rawTarget:i.after,insertAtCursor:s=>{let a=s;if(i?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let l=Zl(this.fileContent),c=xl(l,s,this.considerSubsectionsForAnchor(l,s));a=Jy(l,c??l.length-1,this.fileContent,o.content)}return this.insertTextAfterPositionInBody(o,this.fileContent,a)}})}isOrderedCreate(){return!!this.choice.insertAfter?.createIfNotFound&&this.choice.insertAfter?.createIfNotFoundLocation===Yo}considerSubsectionsForAnchor(e,n){return E_(!!this.choice.insertAfter?.considerSubsections,e,n)}createInsertAfterOrdered(e,n){return hG({capture:e,targetString:n,fileContent:this.fileContent,insertAfter:this.choice.insertAfter,task:!!this.choice.task})}async createInsertBeforeIfNotFound(e,n){let i=this.choice.insertBefore;if(!i)throw new de("Insert-before settings are missing.");let o=Fa(e,"",`${e.content.endsWith(`
|
||
`)||e.content.length===0?"":`
|
||
`}${n}`);return this.createMissingTarget({payload:o,location:i.createIfNotFoundLocation,rawTarget:i.before,insertAtCursor:s=>this.insertTextBeforePositionInBody(o,this.fileContent,s)})}async createInlineInsertAfterIfNotFound(e,n){let i=Fa(e,n);return this.createMissingTarget({payload:i,location:this.choice.insertAfter?.createIfNotFoundLocation,rawTarget:this.choice.insertAfter.after,insertAtCursor:o=>this.insertTextAfterPositionInBody(i,this.fileContent,o)})}createMissingTarget({payload:e,location:n,rawTarget:i,insertAtCursor:o}){switch(n){case Vi:return this.insertAtNoteBodyStartTracking(e,!0);case xd:{let s=this.withLastLineEnded();return Fa(e,s+UF(s,e.content))}case Ed:{let s=this.file?ai(this.app,this.file):Un(this.app);if(!s)throw new de(`Unable to insert line '${i}' at cursor position: ${this.file?`'${this.file.path}' isn't open in the active editor`:"no active markdown editor"}.`);try{return o(s.editor.getCursor().line)}catch{throw new de(`Unable to insert line '${i}' at cursor position.`)}}default:throw new de(`Unknown createIfNotFoundLocation: ${n}`)}}insertAtNoteBodyStartTracking(e,n=!1){let i=wu(this.fileContent,e.content,{separateBlockquotes:n});return Wl(e,i.content,i.insertedStartOffset===null||e.cursor.kind==="none"?null:i.insertedStartOffset+e.cursor.value)}insertTextAfterPositionInBody(e,n,i){let o=Df(e.content,n,i,!!this.choice.task,e.cursor.kind==="offset"?e.cursor.value:void 0);return Wl(e,o.content,o.insertedEndOffset)}insertTextBeforePositionInBody(e,n,i){let o=TW(e.content,n,i,e.cursor.kind==="offset"?e.cursor.value:void 0);return Wl(e,o.content,o.insertedEndOffset)}};bu();Pp();ye();kA();bp();jh();Cp();bM();sM();Ua();Uc();nt();_u();ku();Dm();Dr();var yG=require("obsidian");UM();Le();bi();cl();Nd();EM();es();Yi();Dr();_u();ku();Sn();gM();Ln();vM();var gG=require("obsidian");Le();Sn();xC();CC();es();function vG(r,t){let e=r.trim().replace(/^\/+/,"");if(e==="")return{kind:"vault"};let n=tm(e);if(n){if(!n.field)throw new de("Property capture target needs a field name, e.g. property:type=draft");return{kind:"property",field:n.field,value:n.value,filter:n.filter}}let i=em(e);if(i){if(i.multiSelect)throw new de("Capture target filters select one destination file. Use {{FILE:...|multi}} in the capture format for multi-value metadata.");return{kind:"filter",filter:i.filter}}let o=Br(e,"Capture target file path");if(Rn.test(o))throw new de(`Capture to '.base' files is not supported (${o}). Use a Template choice instead.`);let s=o.endsWith("/"),a=o.replace(/\/+$/,"");if(s)return{kind:"folder",folder:a};if(xt.test(o)||lr.test(o))return{kind:"file",path:o};let l=t.normalizeMarkdownFilePath("",a),d=t.getAbstractFileByPath(l)instanceof gG.TFile;return t.isFolder(a)&&!d?{kind:"folder",folder:a}:{kind:"file",path:o}}vl();var z_=class extends Vf{async getFormattedPathToCaptureTo(t){if(t){let s=kr(this.app,this.choiceExecutor);return Vr(s,"Cannot capture to active file - no active file."),s.path}let e=this.getPreselectedCaptureTargetPath();if(e!==void 0){let s=p_({isFolder:a=>Eg(this.app,a),markdownFileExists:a=>this.app.vault.getAbstractFileByPath(u_(a))instanceof yG.TFile},this.choice.captureTo??"",!1);if(s){let a=this.confinePreselectedToScope(s,e);if(a!==null)return this.normalizeCaptureFilePath(a)}}let n=this.choice.captureTo,i=await this.formatter.formatFileName(n,"captureTarget");if(i===this.formatter.periodicNoteTarget?.path)return this.normalizeCaptureFilePath(`${i}.md`);let o=this.resolveCaptureTarget(i);switch(o.kind){case"vault":return this.selectFileInFolder("",!0);case"filter":return this.selectFileWithFilter(o.filter);case"property":return this.selectFileWithProperty(o.field,o.value,o.filter);case"folder":return this.selectFileInFolder(o.folder,!1);case"file":return this.normalizeCaptureFilePath(o.path)}}getPreselectedCaptureTargetPath(){return BH(this.choiceExecutor?.variables,this.choice.id)}confinePreselectedToScope(t,e){let n=this.stripLeadingSlash(e);if(t.kind==="folder")return t.folderPathSlash&&!n.startsWith(t.folderPathSlash)?`${t.folderPathSlash}${n}`:n;if(this.resolveScopeFiles(t).some(a=>a.path===n))return n;if(!(this.choice.createFileIfItDoesntExist?.enabled??!1))return null;let s=new Set(this.app.vault.getMarkdownFiles().map(a=>a.basename.toLowerCase()));return this.captureTargetAlreadyExists(n,s)?null:n}resolveScopeFiles(t){return c_(this.app,t)}resolveCaptureTarget(t){return vG(t,{getAbstractFileByPath:e=>this.app.vault.getAbstractFileByPath(e),isFolder:e=>Eg(this.app,e),normalizeMarkdownFilePath:(e,n)=>this.normalizeMarkdownFilePath(e,n)})}captureTargetExists(t,e){let n=e.startsWith(t)?e:`${t}${e}`,i;try{i=Br(n,"Capture target file path")}catch{return!1}let o=[i];return/\.(md|canvas)$/i.test(i)||o.push(`${i}.md`,`${i}.canvas`),o.some(s=>!!this.app.vault.getAbstractFileByPath(s))}async selectFileInFolder(t,e){let n=t.endsWith("/")||e?t:`${t}/`,i=ts(this.app,n),o=this.choice.createFileIfItDoesntExist?.enabled??!1;Vr(o||i.length>0,`Folder ${n} is empty.`);let s=await this.chooseCaptureTarget(i,{allowCreate:o,nameIsTaken:l=>this.captureTargetExists(n,l)}),a=s.startsWith(`${n}`)?s:`${n}${s}`;return await this.formatFilePath(a)}async selectFileWithFilter(t){let e=Yw(this.app,t);return this.selectFileFromSet(e,"No files matched the capture target filters.")}async selectFileWithProperty(t,e,n){let i=Kw(this.app,t,e,n),o=e!==void 0?`${t}=${e}`:t;return this.selectFileFromSet(i,`No notes with property ${o}.`)}captureTargetAlreadyExists(t,e){let n=t.trim();if(!n)return!1;let i;try{i=Br(n,"Capture target file path")}catch{return!1}let o=i.replace(/\.(md|canvas)$/i,"");if([i,`${o}.md`,`${o}.canvas`].some(l=>!!this.app.vault.getAbstractFileByPath(l)))return!0;let a=o.slice(o.lastIndexOf("/")+1);return e.has(a.toLowerCase())}async selectFileFromSet(t,e){let n=this.choice.createFileIfItDoesntExist?.enabled??!1;Vr(n||t.length>0,e);let i=new Set(this.app.vault.getMarkdownFiles().map(s=>s.basename.toLowerCase())),o=await this.chooseCaptureTarget(t,{allowCreate:n,nameIsTaken:s=>this.captureTargetAlreadyExists(s,i),restrictToScope:!0});return await this.formatFilePath(o)}async chooseCaptureTarget(t,e){let{paths:n,labels:i,aliases:o,search:s}=d_(this.app,t),a=new Set(i.map(m=>m.toLowerCase())),l=new Set(o.flat().map(m=>m.toLowerCase())),c=new Map(n.map((m,h)=>[m,s[h].length-m.length])),d=m=>a.has(m.toLowerCase())||e.nameIsTaken(m),u=e.allowCreate?"Choose a note or type to create one":void 0,p=String(await Zi(this.choiceExecutor,{remote:async m=>{let h=await eo(m,{items:n.map((v,b)=>({value:v,title:i[b]??v})),placeholder:u,allowCustomInput:e.allowCreate,what:"the capture-target picker"}),g=n.includes(h)?void 0:Dd(n,o,h);if(g!==void 0)return g;if(e.restrictToScope&&!n.includes(h)&&d(h))throw new Error(`"${h}" already exists but is not one of the notes this capture targets. Pick one of the offered notes, or type a name that does not exist yet.`);return h},headless:()=>{throw this.assertInteractiveCaptureTarget(),new Error("unreachable")},app:()=>vr.Suggest(this.app,i,n,{placeholder:u,emptyStateText:e.allowCreate?"Type a note name to create it":void 0,renderItem:(m,h,g)=>Jm(h,m,this.app,{matches:g,pathOffset:c.get(m)??0}),searchItems:s,aliases:o,allowCustomValue:e.allowCreate,customValueLabel:m=>`Create new note: ${m}`,valueExists:m=>l.has(m.toLowerCase())||d(m)})}));return Vr(!!p&&p.length>0,"No file selected for capture."),p}async formatFilePath(t){let e=await this.formatter.formatFileName(t,"captureTarget");return this.normalizeCaptureFilePath(e)}normalizeCaptureFilePath(t){let e=Br(this.stripLeadingSlash(t),"Capture target file path");if(Rn.test(e))throw new de(`Capture to '.base' files is not supported (${e}). Use a Template choice instead.`);let n=this.normalizeCaptureFilePathExtension(e);if(!Is(n).trim())throw new de(`Capture target file name is empty after formatting ('${n}'). Make sure the tokens in 'Capture to' produce a value.`);if(Ut(n))throw new de(`Refusing to capture to a file outside the vault: "${n}".`);return n}normalizeCaptureFilePathExtension(t){for(let e of[xt,lr]){let n=t.match(e)?.[0];if(n)return`${Br(t.replace(e,""),"Capture target file path")}${n}`}return this.normalizeMarkdownFilePath("",t)}assertInteractiveCaptureTarget(){if(this.choiceExecutor.interactive===!1)throw new de(`'${this.choice.name}' needs to ask which note to capture into, but this run is non-interactive. Point "Capture to" at a specific file, or re-run with the ui flag.`)}};UT();Sn();qT();iM();vl();var bG=require("obsidian");Le();Sn();function zM(r){return r?.type==="text"?"text":r?.type==="file"||r?.file?"file":typeof r?.text=="string"?"text":"unsupported"}function Cie(r,t){let e=t.id;if(!e)return null;let n=r.getData?.();return n?.nodes?.length?n.nodes.find(i=>i.id===e)??null:null}function wG(r,t){if(r==="text"){if(t==="currentLine")return"Canvas capture does not support 'At cursor' for text cards. Use top, bottom, insert-after, or insert-before placement.";if(t==="newLineAbove"||t==="newLineBelow")return"Canvas capture does not support 'New line above/below cursor' for text cards. Use top, bottom, insert-after, or insert-before placement."}return r==="file"&&(t==="currentLine"||t==="newLineAbove"||t==="newLineBelow")?"Canvas file cards do not support cursor-based capture modes. Use top, bottom, insert-after, or insert-before modes.":null}function xie(r){let t=r.file;return t?typeof t=="string"?t:typeof t=="object"&&"path"in t&&typeof t.path=="string"?t.path:null:null}function HM(r){return!!r&&"path"in r&&"extension"in r}function Eie(r){let t=r.workspace.getActiveViewOfType(bG.View)??r.workspace.getMostRecentLeaf?.()?.view;return!t||t.getViewType?.()!=="canvas"?null:t}function Tie(r,t){let e=t.file??r.workspace.getActiveFile?.();if(!e)throw new de("Cannot capture to Canvas because no active Canvas file is available.");return e}function _ie(r){let t=r.selection?Array.from(r.selection):[];if(t.length!==1)throw new de("Canvas capture requires exactly one selected node.");return t[0]}function CG(r){let t=xie(r);if(!t)throw new de("Selected Canvas file card does not have a valid linked file path.");if(!xt.test(t))throw new de("Canvas file card targets markdown files only in this version.");return t}function kie(r,t){let e=CG(t),n=r.vault.getAbstractFileByPath(e);if(!HM(n))throw new de(`Selected Canvas file card target not found: ${e}`);return n}function Sie(r,t){let e=CG(t),n=r.vault.getAbstractFileByPath(e);if(!n)return{targetPath:e};if(!HM(n))throw new de(`Selected Canvas file card target not found: ${e}`);return{targetPath:e,targetFile:n}}function Aie(r,t){let e;try{e=JSON.parse(r)}catch{throw new de(`Canvas file is not valid JSON: ${t}`)}if(!e||typeof e!="object")throw new de(`Canvas file has invalid structure: ${t}`);if(!Array.isArray(e.nodes))throw new de(`Canvas file has no nodes array: ${t}`);return e}function xG(r,t,e){let n=r,i=Eie(n);if(!i)return null;let o=i.canvas;if(!o)throw new de("Canvas capture is unavailable in this Obsidian version.");let s=Tie(n,i);if(e&&s.path!==e.path)return null;let a=_ie(o),l=Cie(o,a),c=zM(a);if(c==="unsupported"&&l&&(c=zM(l)),c==="unsupported")throw new de("Canvas capture currently supports only text and file cards.");let d=wG(c,t);if(d)throw new de(d);if(c==="text")return{kind:"text",source:"active",canvas:o,canvasFile:s,node:a,nodeData:l};let u=a.file||!l?.file?a:{...a,file:l.file};return{kind:"file",source:"active",canvasFile:s,node:u,targetFile:kie(n,u)}}async function EG(r,t,e,n){let i=e.trim();if(!i)throw new de("Canvas node id is required for Canvas node capture.");let o=r.vault.getAbstractFileByPath(t);if(!HM(o))throw new de(`Canvas target not found: ${t}`);if(!lr.test(o.path))throw new de("Canvas node capture requires the target path to be a .canvas file.");let s=await r.vault.read(o),a=Aie(s,o.path),l=a.nodes.findIndex(g=>g.id===i);if(l===-1)throw new de(`Canvas node id '${i}' was not found in ${o.path}.`);let c=a.nodes[l],d=zM(c);if(d==="unsupported")throw new de("Canvas capture currently supports only text and file cards.");let u=wG(d,n);if(u)throw new de(u);if(d==="text")return{kind:"text",source:"configured",canvasFile:o,rawCanvas:s,canvasData:a,nodeData:c,nodeIndex:l};let p=r,{targetPath:m,targetFile:h}=Sie(p,c);return{kind:"file",source:"configured",canvasFile:o,nodeData:c,targetPath:m,targetFile:h}}function TG(r){return r.source==="active"?typeof r.node.text=="string"?r.node.text:typeof r.nodeData?.text=="string"?r.nodeData.text:"":typeof r.nodeData.text=="string"?r.nodeData.text:""}async function _G(r,t,e){if(t.source==="active"){typeof t.node.setText=="function"?t.node.setText(e):t.node.text=e,t.canvas.requestSave?.();return}if(await r.vault.read(t.canvasFile)!==t.rawCanvas)throw new de("Canvas target changed while capture was running. Re-run capture to avoid overwriting newer Canvas edits.");t.nodeData.text=e,t.canvasData.nodes[t.nodeIndex]=t.nodeData,await r.vault.modify(t.canvasFile,JSON.stringify(t.canvasData,null," "))}ky();_A();var zf=4e3,Iie=/^[ \t\r\n\f\v]*$/;function kG(r){return Iie.test(r)}var Pie=/\{\{(?:VALUE|FILE|FIELD):[^}]*\|\s*multi\s*(?=[:}|]|$)[^}]*\}\}/gi,$ie=/\|\s*format\s*:\s*(?:inline|spaced|yaml|markdown)\s*(?=\||}})/i;function Fie(r){return Array.from(r.matchAll(Pie)).some(t=>!$ie.test(t[0]))}var H_=class extends z_{constructor(e,n,i,o,s=null,a=[i]){super(e);this.choiceExecutor=o;this.originLeaf=s;this.chain=a;this.capturePropertyVars=new Map;this.suppressFrontmatterCollection=!1;this.resolvedInsertAfterHeading=null;this.choice=i,this.plugin=n,this.outcome=new Uf(o),this.formatter=new q_(e,n,o),this.formatter.choiceChain=a,this.formatter.setPromptRunContext({draftScopeId:i.id,choiceName:i.name})}captureResolvedOrderedHeading(){if(this.choice.insertAfter?.enabled&&this.choice.insertAfter.createIfNotFoundLocation===Yo){let e=this.formatter.getResolvedInsertAfterHeading();e&&(this.resolvedInsertAfterHeading=e)}}showSuccessNotice(e,{wasNewFile:n,action:i}){let o=`'${e.basename}'`;if(n){new aa.Notice(`Created and captured to ${o}`,zf);return}let s=this.choice.prepend||this.choice.captureToActiveFile&&this.choice.activeFileWritePosition==="bottom",a="";switch(i){case"currentLine":a=`Captured to current line in ${o}`;break;case"newLineAbove":a=`Captured on a new line above cursor in ${o}`;break;case"newLineBelow":a=`Captured on a new line below cursor in ${o}`;break;case"activeFileTop":a=`Captured to top of ${o}`;break;case"prepend":case"append":a=s?`Captured to bottom of ${o}`:`Captured to top of ${o}`;break;case"insertAfter":{let l=this.resolvedInsertAfterHeading??this.choice.insertAfter.after;a=l?`Captured to ${o} under '${l}'`:`Captured to ${o}`;break}case"insertBefore":{let l=this.choice.insertBefore?.before;a=l?`Captured to ${o} before '${l}'`:`Captured to ${o}`;break}default:a=`Captured to ${o}`;break}new aa.Notice(a,zf)}showNothingToCaptureNotice(e,{wasNewFile:n}){let i=`'${e.basename}'`;new aa.Notice(n?`Created ${i} \u2014 nothing to capture (no content)`:`Nothing to capture \u2014 ${i} unchanged`,zf)}hasActiveMarkdownCaptureContext(){return!!kr(this.app,this.choiceExecutor)&&!!Un(this.app)}namedNoteHasNoEditor(){return PT(this.choiceExecutor)&&kr(this.app,this.choiceExecutor)?.extension==="md"&&!DF(this.app,this.choiceExecutor)}shouldSkipRequiredCanvasLinkInsertion(e,n){return n&&e.destination?.type!=="specifiedFile"&&e.requireActiveFile&&!this.hasActiveMarkdownCaptureContext()}async insertCaptureLink(e,n,{isCanvasTriggered:i,onEditorTextMutation:o}){if(n.enabled){if(n.destination?.type!=="specifiedFile"&&!Ba(n.placement)&&this.shouldSkipRequiredCanvasLinkInsertion(n,i)){this.plugin.settings.showCaptureNotification&&new aa.Notice("Canvas capture skipped link insertion because no Markdown editor is focused.",zf);return}await O_(this.app,e,n,this.choiceExecutor,o)}}async copyCapturedFileLinkToClipboard(e){this.choice.copyLinkToClipboard&&await D_(e)}validateAppendLinkDestination(e){let n=R_(this.app,e);return n?(this.failRun(n),!1):!0}configureFormatter(e){this.formatter.setLinkToCurrentFileBehavior(e.enabled&&!e.requireActiveFile?"optional":"required");let n=this.choice.useSelectionAsCaptureValue,i=this.plugin.settings.useSelectionAsCaptureValue??!0,o=typeof n=="boolean"?n:i;this.formatter.setUseSelectionAsCaptureValue(o)}async resolveWriteTarget(e,n){let i=kr(this.app,this.choiceExecutor),o=this.choice.captureToActiveFile&&i?.extension==="canvas"?i:null,s=o?xG(this.app,e,o):await this.resolveConfiguredCanvasTarget(e);if(o&&!s)throw new de(`Cannot capture to Canvas '${o.path}' - it is not the active view. Open it and select one card.`);if(s?.kind==="text"){if(n)throw new de("Property capture requires a Markdown note. Canvas text cards do not have note properties.");return{kind:"canvasText",canvas:s}}if(!n&&s?.kind==="file"&&this.createsMissingLineTargetAtCursor(e))throw new de("Canvas file cards do not support creating missing line targets at cursor. Use top or bottom.");let a=s?.kind==="file"?s.source==="configured"?s.targetFile?.path??s.targetPath:s.targetFile.path:await this.getFormattedPathToCaptureTo(this.choice.captureToActiveFile);if(!s&&!this.choice.captureToActiveFile&&lr.test(a))throw new de("Capture to a .canvas file requires a target canvas node id.");return{kind:"note",filePath:a,isCanvasTriggered:!!s}}createsMissingLineTargetAtCursor(e){let n=e==="insertAfter"?this.choice.insertAfter:e==="insertBefore"?this.choice.insertBefore:void 0;return!!n?.createIfNotFound&&n.createIfNotFoundLocation==="cursor"}async prepareNoteWrite(e,n){this.isInsertAfterHeadingMode()&&!lr.test(e)&&await this.maybeResolveInsertAfterHeading(await this.readNoteBodyForHeadingPicker(e,n));let i=!n&&!!this.choice?.createFileIfItDoesntExist?.enabled&&!this.choice?.createFileIfItDoesntExist?.createWithTemplate&&!this.periodicNoteFor(e)?.settings.template;if(this.suppressFrontmatterCollection=!i,this.suppressFrontmatterCollection&&Fie(this.choice?.format?.format??"")&&S.logWarning("QuickAdd: {{VALUE:\u2026|multi}}, {{FILE:\u2026|multi}} and {{FIELD:\u2026|multi}} in this capture write comma-separated strings by default. Add |format:yaml, |format:markdown, |format:inline or |format:spaced to choose the output explicitly."),!n&&!this.choice?.createFileIfItDoesntExist?.enabled)throw new de(`Target file missing: ${e}. Enable "Create file if it doesn't exist" or choose an existing file.`)}async run(){let e=!1;try{this.capturePropertyVars.clear();let n=Zo(this.choice.appendLink);if(this.configureFormatter(n),!this.validateAppendLinkDestination(n))return;let i=this.choice.propertyCapture===void 0?void 0:jx(this.choice.propertyCapture);!i&&bv(oI(this.choice))&&this.namedNoteHasNoEditor()&&(this.choice=W1(this.choice));let o=i?"append":oI(this.choice),s=await this.resolveWriteTarget(o,!!i);if(s.kind==="canvasText"){await this.handleCanvasTextCapture(s.canvas,o,n,()=>{e=!0});return}let{filePath:a,isCanvasTriggered:l}=s,c=this.getCaptureContent(),d=await this.fileExists(a);if(!d&&this.choice?.createFileIfItDoesntExist?.enabled&&Oy(a),i){await this.captureToProperty({filePath:a,fileAlreadyExists:d,config:i,linkOptions:n,isCanvasTriggered:l,onCommit:()=>{e=!0}});return}await this.prepareNoteWrite(a,d);let u=d?await this.onFileExists(a,c,bv(o)):await this.onCreateFileIfItDoesntExist(a,c,n);if(u===null){this.plugin.settings.showCaptureNotification&&new aa.Notice("Nothing to capture (no content)",zf),this.outcome.success(void 0,"unchanged");return}if(u.markerOnly){e=!d,this.plugin.settings.showCaptureNotification&&this.showNothingToCaptureNotice(u.file,{wasNewFile:!d}),this.outcome.success(u.file,d?"unchanged":"created");return}this.captureResolvedOrderedHeading();let p=await this.commitCapture(u,{action:o,fileAlreadyExists:d,onCommit:()=>{e=!0}});if(!p)return;await this.finishCapture(u.file,{...p,action:o,wasNewFile:!d,linkOptions:n,isCanvasTriggered:l})}catch(n){if(e||await this.cleanupCreatedClipboardAttachments(),Dc(n,{logPrefix:"Capture execution aborted",noticePrefix:"Capture execution aborted",defaultReason:"Capture aborted"})){this.choiceExecutor.signalAbort?.(n);return}Bn.getInstance().markExecutionScopeFailed(),this.outcome.failure(V_(n)),Me(n,`Error running capture choice "${this.choice.name}"`)}finally{e&&this.formatter.consumeCreatedClipboardAttachmentPaths()}}async finishCapture(e,n){let{captureIsNoOp:i,marked:o,action:s,wasNewFile:a,linkOptions:l,isCanvasTriggered:c}=n,d=n.cursor;this.outcome.success(e,n.effect),this.plugin.settings.showCaptureNotification&&(i?this.showNothingToCaptureNotice(e,{wasNewFile:a}):this.showSuccessNotice(e,{wasNewFile:a,action:s})),await this.copyCapturedFileLinkToClipboard(e),d&&l.enabled&&(l.destination.type==="specifiedFile"?bg(this.app,l.destination):Ba(l.placement)?kr(this.app,this.choiceExecutor):this.choiceExecutor.focusedProperty?.file)?.path===e.path&&(d=null),await this.insertCaptureLink(e,l,{isCanvasTriggered:c,onEditorTextMutation:o&&d&&!Ba(l.placement)?m=>{o&&d&&m.filePath===e.path&&(d=B_(d,m))}:void 0});let u=rn(this.choice.fileOpening).focus??!0;this.choice.openFile&&(u=await Bf({app:this.app,file:e,opening:this.choice.fileOpening,originLeaf:this.originLeaf}));let p=Un(this.app)?.file?.path===e.path;(this.choice.openFile||o&&p)&&!await Tu(this.app,e)&&d&&(u||o&&p)&&(d.offsets.length===1?Y2(this.app,e,d.offsets[0],d.content):Iy(this.app,e,d.offsets,d.content))}async commitCapture(e,n){let{file:i,captureContent:o,newFileContent:s,priorContent:a,cursor:l}=e,c=kG(o),{action:d}=n;if(bv(d)){let y=c?o:await Bc(this.app,o,i),C=bT(gp(y));if(C.cursor.kind==="none"&&/{{CURSOR}}/i.test(y))return this.plugin.settings.showCaptureNotification&&this.showNothingToCaptureNotice(i,{wasNewFile:!n.fileAlreadyExists}),this.outcome.success(i,"unchanged"),null;c=kG(C.content);let w=C.cursor.kind==="offset"&&C.cursor.source==="marker",T=null;return!c&&!(w?(T=q2(C,this.app,i,d))!==null:(d==="currentLine"?z2:d==="newLineAbove"?W2:G2)(C.content,this.app,i))?(await this.cleanupCreatedClipboardAttachments(),this.failRun(`Capture "${this.choice.name}": no active Markdown editor to insert into.`),null):(n.onCommit(),{effect:c?"unchanged":"changed",captureIsNoOp:c,cursor:T,marked:w})}let{content:u,merged:p}=await mL(this.app,i,a,s);n.onCommit();let m=this.choice.templater?.afterCapture==="wholeFile";m&&(WT(`templater-whole-file:${this.choice.id}`,`'${this.choice.name}' uses "Run Templater on entire destination file after capture", which is deprecated and will be removed in a future release. QuickAdd already runs Templater in what it captures. Turn the option off in the Capture's settings.`),await Eu(this.app,i));let h=await this.applyCapturePropertyVars(i),g=(m||h)&&await this.app.vault.read(i)!==u,v=n.fileAlreadyExists?s!==a||g?"changed":"unchanged":"created",b=!p&&!g&&l.kind==="offset"?{offsets:[l.value],content:s}:null;return{effect:v,captureIsNoOp:c,cursor:b,marked:l.kind==="offset"&&l.source==="marker"}}async captureToProperty(e){let{filePath:n,fileAlreadyExists:i,config:o,linkOptions:s}=e;if(!xt.test(n))throw new de("Property capture requires a Markdown note.");if(!i&&!this.choice.createFileIfItDoesntExist.enabled)throw new de(`Target file missing: ${n}. Enable "Create file if it doesn't exist" or choose an existing file.`);let a=i?this.getFileByPath(n):void 0;this.formatter.setTitle(Is(n)),this.formatter.setTargetFolderPath(ei(n)),this.formatter.setDestinationSourcePath(n),a&&this.formatter.setDestinationFile(a),this.formatter.setPromptRunContext({draftScopeId:this.choice.id,choiceName:this.choice.name,destination:n,destinationKind:"file"});let l=!a&&this.choice.createFileIfItDoesntExist.createWithTemplate,c=a?await Bd(this.app,a):l?"":await this.periodicNoteContent(n)??"",d=new Map;if(l){let y=new _f(this.app,this.plugin,this.choice.createFileIfItDoesntExist.template,this.choiceExecutor);y.setDestinationPath(n),y.setPromptRunContext({draftScopeId:`${this.choice.id}#${this.choice.createFileIfItDoesntExist.template}`,choiceName:this.choice.name,destination:n,destinationKind:"file"}),y.choiceChain=this.chain,s.enabled&&!s.requireActiveFile&&y.setLinkToCurrentFileBehavior("optional"),c=await y.run(),d=y.getAndClearTemplatePropertyVars()}let u=BL(c);for(let[y,C]of d)Ry(u,y.split(Ui.PATH_SEPARATOR),wp(C));let p=wg(u,AL(o.property.kind==="named"?await this.formatter.formatPropertyName(o.property.format):await this.promptForCaptureProperty(u,o.createIfMissing))),m=Rs(this.app,p,{registeredOnly:!0}),h=Object.prototype.hasOwnProperty.call(u,p)?u[p]:void 0,g=m??(typeof h=="number"?"number":typeof h=="boolean"?"checkbox":null),v=this.choice.format.enabled?this.choice.format.format:xr,b=FL(this.choiceExecutor.variables);try{RL(this.choiceExecutor.variables,p,h),this.formatter.consumePropertyTokenExpanded();let y=await this.formatter.formatPropertyValue(m_(v,g),{listItems:NL({key:p,action:o.action,registeredType:m,existing:h})}),C=IL(v)||this.formatter.consumePropertyTokenExpanded(),w=I=>VL({frontmatter:I,key:p,value:y,config:o,registeredType:Rs(this.app,p,{registeredOnly:!0}),compose:C}),T=w(u);if(o.action==="addToList"&&DL(y)){this.outcome.success(a,"unchanged");return}let P="";if(a)P=await Bd(this.app,a),await this.app.fileManager.processFrontMatter(a,I=>{I[wg(I,p)]=w(I)});else{u[p]=T;let I=()=>this.createFileWithInput(n,UL(c,u),{suppressTemplaterOnCreate:l});a=l?await I():await XF(this.app,n,I)}e.onCommit(),!i&&(l||Fy(this.app))&&(l&&await Eu(this.app,a),await this.app.fileManager.processFrontMatter(a,I=>{I[wg(I,p)]=w(I)}));let _=await this.app.vault.read(a);this.outcome.success(a,i?_===P?"unchanged":"changed":"created"),this.plugin.settings.showCaptureNotification&&new aa.Notice(`Captured to '${p}' in '${a.basename}'`,zf),await this.copyCapturedFileLinkToClipboard(a),await this.insertCaptureLink(a,s,{isCanvasTriggered:e.isCanvasTriggered}),this.choice.openFile&&await Bf({app:this.app,file:a,opening:this.choice.fileOpening,originLeaf:this.originLeaf})}finally{ML(this.choiceExecutor.variables,b)}}async promptForCaptureProperty(e,n){let i=Object.keys(e).filter(o=>o!=="__proto__").sort((o,s)=>o.localeCompare(s));if(!n&&i.length===0)throw new de("The capture target has no properties. Enable 'Create property if missing' to add one.");return await Zi(this.choiceExecutor,{remote:o=>eo(o,{items:i.map(s=>({value:s,title:s})),placeholder:"Property",allowCustomInput:n,what:"the property picker"}),headless:async()=>{throw new de("Property capture needs a property selection. Configure a named property or run with the ui flag.")},app:()=>vr.Suggest(this.app,i,i,{placeholder:"Property",allowCustomValue:n,customValueLabel:o=>`Create property: ${o}`,valueExists:o=>i.some(s=>s.trim().toLowerCase()===o.trim().toLowerCase())})})}failRun(e){Bn.getInstance().markExecutionScopeFailed(),S.logError(e),this.outcome.failure(e)}async cleanupCreatedClipboardAttachments(){let e=this.formatter.consumeCreatedClipboardAttachmentPaths();for(let n of e)try{let i=this.app.vault.getAbstractFileByPath(n);i instanceof aa.TFile&&await this.app.fileManager.trashFile(i)}catch(i){S.logWarning(`QuickAdd: failed to clean up clipboard attachment '${n}': ${String(i)}`)}}async handleCanvasTextCapture(e,n,i,o){if(bv(n))throw new de("Canvas text cards support top, bottom, insert-after, and insert-before positions only.");if(this.createsMissingLineTargetAtCursor(n))throw new de("Canvas text cards do not support creating missing line targets at cursor. Use top or bottom.");let s=e.canvasFile;this.formatter.setTitle(Is(s.basename)),this.formatter.setDestinationFile(s);let a=this.getCaptureContent(),l=TG(e);this.isInsertAfterHeadingMode()&&await this.maybeResolveInsertAfterHeading(l);let{content:c,markerOnly:d}=await this.formatter.formatContentWithFile(a,this.choice,l,s);if(d){this.plugin.settings.showCaptureNotification&&this.showNothingToCaptureNotice(s,{wasNewFile:!1}),this.outcome.success(s,"unchanged");return}this.captureResolvedOrderedHeading();let u=c===l;u||await _G(this.app,e,c),o(),await this.finishCapture(s,{effect:u?"unchanged":"changed",captureIsNoOp:u,cursor:null,marked:!1,action:n,wasNewFile:!1,linkOptions:i,isCanvasTriggered:!0})}async resolveConfiguredCanvasTarget(e){if(this.choice.captureToActiveFile)return null;let n=this.choice.captureTo?.trim()??"",i=this.choice.captureToCanvasNodeId?.trim()??"";if(!n||!i)return null;let o=await this.formatFilePath(n);return lr.test(o)?await EG(this.app,o,i,e):null}async maybeResolveInsertAfterHeading(e){let n=this.choice.insertAfter;if(!n?.enabled||!n.promptHeading)return;let i=!!n.createIfNotFound,o=Zl(e),s=si(o).filter(m=>o[m.line].trim()!==m.heading),a=s.map(m=>o[m.line].trimStart().replace(/\r$/,"")),l=s.map(m=>`${" ".repeat(Math.max(0,m.level-1))}${m.heading}`),c=s.map(m=>m.heading),d="Choose a heading to insert under",u=String(await Zi(this.choiceExecutor,{remote:m=>eo(m,{items:a.map((h,g)=>({value:h,title:l[g]??h})),placeholder:d,allowCustomInput:i,what:"the heading picker"}),headless:()=>{throw new de(`'${this.choice.name}' needs to ask which heading to capture under, but this run is non-interactive. Turn off "Choose heading when capturing" and set a fixed heading, or re-run with the ui flag.`)},app:()=>vr.Suggest(this.app,l,a,{allowCustomValue:i,placeholder:d,emptyStateText:i?"No headings found \u2014 type a heading to create":"No headings found in the target note",customValueLabel:m=>`Insert after new line: ${m}`})}));Vr(!!u&&u.length>0,"No heading selected for capture."),this.formatter.setInsertAfterTargetOverride(u);let p=a.indexOf(u);this.resolvedInsertAfterHeading=p>=0?c[p]:u}isInsertAfterHeadingMode(){return!!this.choice.insertAfter?.enabled&&!!this.choice.insertAfter.promptHeading}async readNoteBodyForHeadingPicker(e,n){if(!n)return"";let i=this.app.vault.getAbstractFileByPath(e);return i instanceof aa.TFile?await Bd(this.app,i):""}getCaptureContent(){let e;return this.choice.format.enabled?e=this.choice.format.format:e=xr,this.choice.task&&(e=`- [ ] ${e}
|
||
`),e}async onFileExists(e,n,i=!1){let o=this.getFileByPath(e);if(!o)throw new Error("File not found");this.formatter.setTitle(o.basename),this.formatter.setDestinationFile(o);let s=await this.collectIfFrontmatter(()=>this.formatter.formatContentOnly(n,{eachLine:this.choice.eachLine}));this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let a=await Bd(this.app,o);if(/{{CURSOR}}/i.test(s)&&gp(s).cursor.kind==="none")return{file:o,newFileContent:a,captureContent:"",priorContent:a,cursor:{kind:"none"},markerOnly:!0};if(i)return{file:o,newFileContent:a,captureContent:s,priorContent:a,cursor:{kind:"none"}};let l=await this.collectIfFrontmatter(()=>this.formatter.insertFormattedContent(s,this.choice,a,o));return this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars()),l.markerOnly?{file:o,newFileContent:a,captureContent:l.captureContent,priorContent:a,cursor:l.cursor,markerOnly:!0}:{file:o,newFileContent:l.content,captureContent:l.captureContent,priorContent:a,cursor:l.cursor}}periodicNoteFor(e){if(this.choice.captureToActiveFile||this.choice.createFileIfItDoesntExist.createWithTemplate)return null;let n=this.formatter.periodicNoteTarget;return!n||`${n.path}.md`!==e?null:{period:n.period,settings:Hw(this.app,n.period)}}async periodicNoteContent(e){let n=this.periodicNoteFor(e);if(!n)return null;let i=await EL(this.app,n.settings,n.period);if(i===null)return null;let o=this.choiceExecutor.clocks;return TL(i,n.settings,n.period,window.moment(o?.date??o?.now),window.moment(o?.now))}async onCreateFileIfItDoesntExist(e,n,i){Oy(e);let o=Is(e);this.formatter.setTitle(o),this.formatter.setDestinationSourcePath(e);let s=await this.collectIfFrontmatter(()=>this.formatter.formatContentOnly(n,{eachLine:this.choice.eachLine}));if(this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars()),/{{CURSOR}}/i.test(s)&&gp(s).cursor.kind==="none")return null;let a="";if(!this.choice.createFileIfItDoesntExist.createWithTemplate)a=await this.periodicNoteContent(e)??"";else{let m=new _f(this.app,this.plugin,this.choice.createFileIfItDoesntExist.template,this.choiceExecutor);i?.enabled&&!i.requireActiveFile&&m.setLinkToCurrentFileBehavior("optional"),m.setTargetFolderPath(ei(e)),m.setPromptRunContext({draftScopeId:`${this.choice.id}#${this.choice.createFileIfItDoesntExist.template}`,choiceName:this.choice.name,destination:e,destinationKind:"file"}),m.choiceChain=this.chain,m.setKeepUserTextProtected(!0),a=await m.run();let h=m.getAndClearTemplatePropertyVars();S.logMessage(`CaptureChoiceEngine: Collected ${h.size} template property variables`),h.size>0&&S.logMessage(`Variables: ${Array.from(h.keys()).join(", ")}`),this.templatePropertyVars=h}let l=this.choice.createFileIfItDoesntExist.createWithTemplate,c=()=>this.createFileWithInput(e,a,{suppressTemplaterOnCreate:l}),d=l?await c():await XF(this.app,e,c);try{this.choice.createFileIfItDoesntExist.createWithTemplate&&this.templatePropertyVars&&Ef(d,this.templatePropertyVars)&&await Tf(this.app,d,this.templatePropertyVars),l&&a&&await Eu(this.app,d)}finally{a&&await this.restoreUserTextInNote(d)}let u=await this.app.vault.read(d),p=await this.collectIfFrontmatter(()=>this.formatter.insertFormattedContent(s,this.choice,u,d));return this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars()),{file:d,newFileContent:p.content,captureContent:p.captureContent,priorContent:u,cursor:p.cursor,markerOnly:p.markerOnly}}async restoreUserTextInNote(e){let n=await this.app.vault.read(e);An(n)!==n&&await To(this.app,e,An)}collectIfFrontmatter(e){return this.suppressFrontmatterCollection?e():this.formatter.withTemplatePropertyCollection(e)}mergeCapturePropertyVars(e){if(!(!e||e.size===0)){for(let[n,i]of e)this.capturePropertyVars.set(n,i);S.logMessage(`CaptureChoiceEngine: Accumulated ${this.capturePropertyVars.size} structured capture variables`)}}async applyCapturePropertyVars(e){return this.capturePropertyVars.size===0?!1:Ef(e,this.capturePropertyVars)?(S.logMessage(`CaptureChoiceEngine: Post-processing front matter with ${this.capturePropertyVars.size} capture variables`),await Tf(this.app,e,this.capturePropertyVars),this.capturePropertyVars.clear(),!0):(this.capturePropertyVars.clear(),!1)}};Sy();var ro=require("obsidian");an();nt();rr();je();lt();Ay();var WM=require("obsidian");Le();Qi();Jt();nt();function SG(r){let t=r.split("/").pop()??r,e=t.lastIndexOf(".");return e>0?t.slice(0,e):t}function GM(r){let t=new Ks(SG(r));return t.id=`folder-template:${r}`,t.templatePath=r,t.openFile=!0,t.fileNameFormat={enabled:!0,format:xr},t.discoverExistingNotesBeforeCreate=!0,t}function jM(r){return ti(r.settings.templateFolderPaths).length>0}function Mie(r,t){let e=r.lastIndexOf("/"),n=e===-1?"":r.slice(0,e),i=t.createDiv({cls:"suggestion-content"});i.createDiv({cls:"suggestion-title",text:SG(r)}),n&&(t.classList.add("mod-complex"),i.createDiv({cls:"suggestion-note",text:n}))}async function Rie(r,t){let n=[...t].sort((i,o)=>i.path.localeCompare(o.path)).map(i=>i.path);try{return await It.Suggest(r,n,n,"New note from template",(i,o)=>Mie(i,o))}catch(i){if(Be(i))return null;throw i}}async function W_(r,t,e){try{let n=e.templatePath?.trim()||void 0;if(!n){if(!jM(t)){new WM.Notice("QuickAdd: Set a template folder in Settings \u2192 QuickAdd \u2192 Template folders to use \u201CNew note from template\u201D.",8e3),mc(r,t.manifest.id,{notice:!1});return}let i=t.getTemplateFiles();if(i.length===0){new WM.Notice("QuickAdd: No template files found in your configured template folder(s).");return}let o=await Rie(r,i);if(!o)return;n=o}await e.choiceExecutor.execute(GM(n))}catch(n){if(Be(n))return;Me(n,"Error running template from folder")}}lt();Ko();var Oie="\u2190 Back",Die="Select a choice";function tb(r){return vo(r)?`QuickAdd couldn't read the contents of "${r.name}". They're still in data.json.`:`Folder "${r.name}" is empty.`}var Lie="Empty",Nie="Unreadable";function Vie(r){return YM(r)?vo(r)?Nie:Lie:""}var eb="quickadd:run-template-from-folder",Bie="New note from template\u2026",Hf="quickadd:back";function YM(r){return r.type==="Multi"&&r.id!==Hf&&Ne(r).length===0}var Uie=.5;function qie(r){return r.replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g,"$2").replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/(\*\*|__)(.+?)\1/g,"$2").replace(/\*(.+?)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/~~(.+?)~~/g,"$1")}function KM(r){return(r.settings.templateFolderLauncherRow??"bottom")!=="off"&&jM(r)}function zie(){return{id:eb,name:Bie,type:"Template",command:!1}}var Ru=class r extends ro.FuzzySuggestModal{constructor(e,n,i){super(e.app);this.plugin=e;this.choices=n;this.focusedProperty=null;this.triggerContext=null;this.placeholderStack=[];this.selectionDispatched=!1;this.breadcrumbById=new Map;this.markdownComponent=new ro.Component;this.warnRenderFailure=pp("Could not render a choice name as Markdown; showing it as plain text");if(this.modalEl.addClass("qa-choice-suggester"),this.choiceExecutor=i?.choiceExecutor??new Ar(this.app,this.plugin),this.focusedProperty=i&&"focusedProperty"in i?i.focusedProperty??null:OT(this.app),this.triggerContext=i&&"triggerContext"in i?i.triggerContext??null:{activeFile:this.app.workspace.getActiveFile()},this.placeholderStack=i?.placeholderStack??[],this.completion=i?.completion,this.ancestry=i?.ancestry,this.currentPlaceholder=i?.placeholder?.trim()||Die,this.setPlaceholder(this.currentPlaceholder),this.markdownComponent.load(),i?.includeTemplateFolderRow){let o=this.plugin.settings.templateFolderLauncherRow??"bottom";if(KM(this.plugin)){let s=zie();this.choices=o==="top"?[s,...this.choices]:[...this.choices,s]}}}static Open(e,n,i){new r(e,n,i).open()}onClose(){super.onClose(),this.markdownComponent.unload(),this.completion&&!this.selectionDispatched&&this.completion(on())}getSuggestions(e){let n=e.trim();if(!n||!U.getState().searchNestedChoices)return super.getSuggestions(n);let i=(0,ro.prepareFuzzySearch)(n),o=[];for(let s of this.getNestedSearchCandidates()){let a=i(s.text);a&&(s.nameOffset>0&&a.matches.length>0&&a.matches.every(([,l])=>l<=s.nameOffset)&&(a.score-=Uie),o.push({item:s.choice,match:a}))}return o.sort((s,a)=>a.match.score-s.match.score),o}getNestedSearchCandidates(){if(!this.nestedSearchCandidates){let e=this.choices.filter(n=>n.id!==Hf&&n.id!==eb);this.nestedSearchCandidates=Ad(e).map(({choice:n,path:i})=>{let o=i.slice(0,-1);o.length>0&&this.breadcrumbById.set(n.id,o.map(qie).join(" / "));let s=i.join(" / ");return{choice:n,text:s,nameOffset:s.length-n.name.length}})}return this.nestedSearchCandidates}selectSuggestion(e,n){if(YM(e.item)){if("repeat"in n&&n.repeat)return;new ro.Notice(tb(e.item)),this.inputEl.focus();return}this.selectionDispatched=!0,super.selectSuggestion(e,n)}renderSuggestion(e,n){n.empty(),n.classList.remove("mod-complex");let i=this.breadcrumbById.get(e.item.id),o=n.createDiv({cls:"quickadd-choice-suggestion-content"});this.renderChoiceIcon(e.item,o);let s;if(i){n.classList.add("mod-complex");let c=o.createDiv({cls:"suggestion-content quickadd-choice-suggestion-text"});s=c.createDiv({cls:"suggestion-title"}),c.createDiv({cls:"suggestion-note",text:i})}else s=o.createDiv({cls:"quickadd-choice-suggestion-title quickadd-choice-suggestion-text"});ro.MarkdownRenderer.render(this.app,e.item.name,s,"",this.markdownComponent).catch(c=>{s.textContent=e.item.name,this.warnRenderFailure(c)}),n.classList.add("quickadd-choice-suggestion"),e.item.id===Hf&&n.classList.add("quickadd-choice-suggestion-back"),e.item.id===eb&&n.classList.add("quickadd-choice-suggestion-run-template");let a=Vie(e.item),l=a!=="";if(n.classList.toggle("quickadd-choice-suggestion-empty",l),l){n.setAttribute("aria-disabled","true");let c=At(o,"span");c.classList.add("quickadd-choice-suggestion-empty-flair"),c.textContent=a,o.appendChild(c)}else n.removeAttribute("aria-disabled")}renderChoiceIcon(e,n){let i=this.getChoiceSuggestionIcon(e);if(!i)return;let o=At(n,"span");o.classList.add("quickadd-choice-icon"),o.setAttribute("aria-hidden","true"),n.appendChild(o),(0,ro.setIcon)(o,i)}getChoiceSuggestionIcon(e){if(e.id!==Hf)return e.id===eb?"file-plus":Sd(e)}getItemText(e){return e.name}getItems(){return this.choices}settleCompletion(e,n){e.then(()=>this.completion?.(),i=>{let o=typeof i=="string"&&Be(i)?on():Ia(i);kd(o,n),this.completion?.(o)})}onChooseItem(e,n){if(e.id===eb){this.settleCompletion(W_(this.app,this.plugin,{choiceExecutor:this.choiceExecutor}),"Could not run a template from that folder");return}if(e.type==="Multi")this.onChooseMultiType(e);else{"shiftKey"in n&&n.shiftKey&&(this.choiceExecutor.pickDate=!0);let i=this.choiceExecutor.executeWithFocusedProperty?this.choiceExecutor.executeWithFocusedProperty(e,this.focusedProperty,this.triggerContext,this.ancestry):this.choiceExecutor.execute(e,this.ancestry);this.settleCompletion(i,`Could not run "${e.name}"`)}}onChooseMultiType(e){let n=e.id===Hf;if(!n&&YM(e)){new ro.Notice(tb(e)),this.completion?.();return}let i=[...Ne(e)];if(!n){let a=new tf(Oie).addChoices(this.choices);a.id=Hf,i.push(a)}let o=n?this.placeholderStack[this.placeholderStack.length-1]:e.placeholder?.trim()||e.name,s=n?this.placeholderStack.slice(0,-1):[...this.placeholderStack,this.currentPlaceholder];r.Open(this.plugin,i,{choiceExecutor:this.choiceExecutor,focusedProperty:this.focusedProperty,triggerContext:this.triggerContext,placeholder:o,placeholderStack:s,completion:this.completion,ancestry:this.ancestry})}};je();ri();ye();SM();Ln();YS();jy();Le();Xp();uc();If();kM();Rf();function Hie(r,t,e){let n=t.pickDate?Jp(Qa(r.dateOrigin)):Qa(r.dateOrigin),i=KT({setting:n,clocks:t.clocks,variables:new Map([...t.variables,...Object.entries(e)]),reservedSeed:n?.kind==="ask"?e[Sa]:void 0});return i.status!=="set"?t.clocks:{now:t.clocks?.now??new Date,date:i.date}}function AG(r,t){let e=r.trim();if(!e)return[];let n=Array.from(t.keys()).sort((s,a)=>a.length-s.length),i=[],o=e;for(;o.length>0;){let s=n.find(a=>o===a||o.startsWith(`${a}, `));if(!s)break;i.push(s),o=o===s?"":o.slice(s.length+2)}if(o.length>0)for(let s of o.split(",")){let a=s.trim();a&&i.push(a)}return i}function Wie(r,t,e){let n=r.filter(o=>e||t.includes(o)),i=new Set(n);return[...t.filter(o=>i.has(o)),...n.filter((o,s)=>!t.includes(o)&&n.indexOf(o)===s)]}async function IG(r,t,e,n){try{if(ZH(e,n.id))return!1;let i=e.promptProvider?null:await nW(r,t,e,n),o=i?.requirements??await sa(r,t,e,n,{seedCaptureSelectionAsValue:!0,preloadedUserScripts:e.preloadedUserScripts});if(o.length===0)return!1;let s=wl(o,e.variables);if(s.length===0)return!1;let a=s.filter(g=>!g.runtimeOnly||i?.config.fieldUsages.has(g.id));if(a.length===0)return!1;let l=async g=>{try{let v=new Qp(r,t);v.setRunClocks(Hie(n,e,g));let b=[];if(n.type==="Template"){let y=n;if(y.fileNameFormat?.enabled){v.setTargetFolderPath(YC(y.folder)??"Folder/Name");for(let[C,w]of Object.entries(g))v.variables.set(C,w);b.push({label:"File name",text:await v.format(y.fileNameFormat.format),diagnostics:v.diagnostics.list()})}}return b}catch{return[]}},c=e.promptProvider,d=null,u;c?u=await c.requestInputs(a):(d=new Of(r,a,e.variables,l,i?.config),u=await d.waitForClose);let p=new Map,m=new Map;for(let g of d?.activeRequirements??a){if(g.id.startsWith(mg)){let v=g.options??[],b=g.displayOptions??v;p.set(g.id,{options:v,displayToValue:new Map(v.map((y,C)=>[(b[C]??y).trim(),y])),allowCustom:g.suggesterConfig?.allowCustomInput??!1,multiSelect:g.suggesterConfig?.multiSelect??!1})}if(g.suggesterConfig?.multiSelect&&!g.id.startsWith(mg)){let v=g.options??[],b=g.displayOptions??v,y=new Map;v.forEach((C,w)=>{y.set((b[w]??C).trim(),C)}),m.set(g.id,{emit:g.multiEmit??"text",allowCustom:g.suggesterConfig.allowCustomInput??!1,displayToValue:y})}}let h=i?new Map:e.variables;return Object.entries(u).forEach(([g,v])=>{let b=p.get(g);if(b!==void 0){let w=d?.fileSelections.get(g)??(Array.isArray(v)?v.map(String):void 0)??(b.multiSelect?AG(String(v),b.displayToValue).map(_=>b.displayToValue.get(_)??_):[String(v)]),P=Wie(w,b.options,b.allowCustom).map(_=>J0(_,b.options));h.set(g,b.multiSelect?P:P[0]??"");return}let y=m.get(g);if(y!==void 0){let w=(d?.multiSelections.get(g)??AG(String(v),y.displayToValue)).filter(T=>y.allowCustom||y.displayToValue.has(T)).map(T=>y.displayToValue.get(T)??T);h.set(g,y.emit==="linklist"?w.map(Tw):w);return}h.set(g,v)}),i&&d&&iW(e,i,h,d.discoverySelections),!0}catch(i){if(i instanceof at)throw i;return e.promptProvider||S.logWarning(`One-page input failed for choice "${n.name}"; falling back to step-by-step prompts: ${i instanceof Error?i.message:String(i)}`),!1}}ri();Sn();rr();nt();$_();Dm();Ay();Xp();uc();lt();Le();ET();If();ye();Rf();ml();ou();var Ar=class{constructor(t,e){this.app=t;this.plugin=e;this.variables=new Map;this.preparedInputs=KH();this.interactive=!0;this.preloadedUserScripts=new Map;this.focusedProperty=null;this.triggerContext=null;this.pickDate=!1;this.pendingAbort=null;this.pendingResult=null;this.executionDepth=0;this.dispatchAncestry=A2()}signalAbort(t){this.pendingAbort=t}consumeAbortSignal(){let t=this.pendingAbort;return this.pendingAbort=null,t??null}recordExecutionResult(t){this.pendingResult=t}setCurrentFile(t){this.triggerContext={activeFile:t,named:!0},this.triggerContextOverride=this.triggerContext}beginExecutionContext(){this.executionDepth===0&&(this.focusedProperty=this.focusedPropertyOverride!==void 0?this.focusedPropertyOverride:OT(this.app),this.triggerContext=this.triggerContextOverride!==void 0?this.triggerContextOverride:{activeFile:this.app.workspace.getActiveFile()},this.clocks={now:this.clocks?.now??new Date,date:this.clocks?.date}),this.executionDepth++}endExecutionContext(){this.executionDepth=Math.max(0,this.executionDepth-1),this.executionDepth===0&&(this.focusedProperty=null,this.triggerContext=null,this.clocks=void 0,this.pickDate=!1,this.preloadedUserScripts.clear(),tW(this))}async execute(t,e=this.dispatchAncestry){let n=_y(t,e);this.pendingAbort=null;let i=this.pendingResult;this.beginExecutionContext();let o=I_(this.app),s=Bn.getInstance(),a=s.beginExecutionScope();try{await this.runOnePagePreflightIfEnabled(t),await Yy(this,t.id,async()=>{switch(await this.applyDateOrigin(t),t.type){case"Template":{let l=t;await this.onChooseTemplateType(l,o,n);break}case"Capture":{let l=t;await this.onChooseCaptureType(l,o,n);break}case"Macro":{let l=t;await this.onChooseMacroType(l,o,n);break}case"Multi":{let l=t;await this.onChooseMultiType(l,n);break}default:break}if(this.pendingAbort){s.rollbackExecutionScope(a);return}s.commitExecutionScope(a)})}catch(l){throw s.rollbackExecutionScope(a),l}finally{this.pendingResult=i,this.endExecutionContext()}}async executeWithFocusedProperty(t,e,n,i){let o=this.focusedPropertyOverride,s=this.triggerContextOverride;this.focusedPropertyOverride=e,this.triggerContextOverride=n;try{await this.execute(t,i)}finally{this.focusedPropertyOverride=o,this.triggerContextOverride=s}}async executeWithOutcome(t){let e=_y(t,this.dispatchAncestry);this.pendingAbort=null,this.pendingResult=null,this.beginExecutionContext();let n=I_(this.app),i=Bn.getInstance(),o=i.beginExecutionScope();try{return await this.runOnePagePreflightIfEnabled(t),await Yy(this,t.id,async()=>{if(await this.applyDateOrigin(t),t.type==="Template"?await this.onChooseTemplateType(t,n,e):await this.onChooseCaptureType(t,n,e),this.pendingAbort){i.rollbackExecutionScope(o);let a=this.consumeAbortSignal(),l=a instanceof et;return{status:"cancelled",cancelKind:l?"user":"aborted",reason:l?void 0:a?.message}}i.commitExecutionScope(o);let s=this.pendingResult;return this.pendingResult=null,s??{status:"error"}})}catch(s){return i.rollbackExecutionScope(o),s instanceof et?{status:"cancelled",cancelKind:"user"}:s instanceof at?{status:"cancelled",cancelKind:"aborted",reason:s.message}:(Me(s,"Error executing choice from URI"),{status:"error",reason:s instanceof Error?s.message:String(s)})}finally{this.endExecutionContext()}}async applyDateOrigin(t){qn(t)&&xc(t,t.fileNameFormat.enabled?t.fileNameFormat.format:xr,this.variables.get("value"))||await this.resolveDateOrigin(t)}async resolveDateOrigin(t){let e=this.pickDate?Jp(Qa(t.dateOrigin)):Qa(t.dateOrigin),n=e?.kind==="ask"?this.variables.get(Sa):void 0,i=KT({setting:e,clocks:this.clocks,variables:this.variables,reservedSeed:n});if(i.status==="inherit")return;if(i.status==="error")throw S.logError(i.message),new de(i.message);if(i.status==="set"){this.clocks={now:this.clocks?.now??new Date,date:i.date};return}if(this.interactive===!1&&!this.promptProvider)throw new de(`"${t.name}" needs a date. Re-run with date= or the ui flag.`);let o=`Date for ${t.name}`;try{let s=this.promptProvider?await this.promptProvider.datePrompt(o,{defaultValue:i.defaultValue,dateFormat:"YYYY-MM-DD"}):await fl.Prompt(this.app,o,void 0,i.defaultValue,"YYYY-MM-DD"),a=Ny(s);if(!a)throw new de("Could not parse the date origin.");this.clocks={now:this.clocks?.now??new Date,date:a}}catch(s){throw Be(s)?new et("Date origin cancelled by user"):s}}async prepareMacroInputs(t,e){if(e.length===0)return;let n={...t,macro:{...t.macro,commands:e}};await this.runOnePagePreflightIfEnabled(n)}async runOnePagePreflightIfEnabled(t){let e=U.getState().onePageInputEnabled,n=t.onePageInput??this.macroOnePageInput,i=this.promptProvider!=null;if((n==="always"||n!=="never"&&(e||i))&&(t.type==="Template"||t.type==="Capture"||t.type==="Macro"))try{await IG(this.app,this.plugin,this,t)}catch(s){throw Be(s)?new et("One-page input cancelled by user"):s}}async onChooseTemplateType(t,e,n){await new U_(this.app,this.plugin,t,this,e,n).run()}async onChooseCaptureType(t,e,n){await new H_(this.app,this.plugin,t,this,e,n).run()}async onChooseMacroType(t,e,n){let i=new ta(this.app,this.plugin,t,this,this.variables,this.preloadedUserScripts,void 0,e,n),o=this.macroOnePageInput;this.macroOnePageInput=t.onePageInput??o;try{await i.run()}finally{this.macroOnePageInput=o}Object.entries(i.params.variables).forEach(([s,a])=>{this.variables.set(s,a)})}async onChooseMultiType(t,e){let n=Ne(t);if(this.promptProvider||this.interactive===!1){let i=this.promptProvider?"Run one of its choices directly.":"Run one of its choices directly, or re-run with the ui flag.";this.signalAbort(new de(n.length===0?tb(t):`"${t.name}" is a folder of choices, and picking from it needs someone at the window. ${i}`));return}if(n.length===0){new PG.Notice(tb(t));return}await new Promise((i,o)=>{Ru.Open(this.plugin,n,{choiceExecutor:this,focusedProperty:this.focusedProperty,triggerContext:this.triggerContext,placeholder:t.placeholder?.trim()||t.name,ancestry:e,completion:s=>s===void 0?i():o(s)})})}};Jt();var $G=require("obsidian");var Gie="QuickAdd: No choices yet. Create your first one in Settings \u2192 QuickAdd.";function G_(r){let t=Array.isArray(r.settings.choices)?r.settings.choices:[];if(!(t.length>0||KM(r))){new $G.Notice(Gie,8e3),mc(r.app,r.manifest.id,{notice:!1});return}Ru.Open(r,t,{includeTemplateFolderRow:!0})}BM();ye();ye();Jt();var FG={description:"Use QuickAdd template folder instead of Obsidian templates plugin folder / Templater templates folder.",migrate:async r=>{try{let t=r.app.plugins.plugins.templater,e=r.app.internalPlugins.plugins.templates;if(!t&&!e){S.logMessage("No template plugin found. Skipping migration.");return}let n=[];if(e){let s=e.instance.options;s.folder&&(n.push(s.folder),S.logMessage("Migrated template folder path to Obsidian Templates' setting."))}if(t){let s=t.settings;s.template_folder&&(n.push(s.template_folder),S.logMessage("Migrated template folder path to Templaters setting."))}let i=ti(r.settings.templateFolderPaths),o=ti([...i,...n]);o.length>0&&(r.settings.templateFolderPaths=o)}catch(t){throw S.logError("Failed to migrate template folder path."),t}}};tn();function j_(r){return r===null||typeof r!="object"||!("type"in r)||!("choices"in r)?!1:r.type==="Multi"&&Array.isArray(r.choices)}function Y_(r){return r===null||typeof r!="object"||!("choice"in r)?!1:r.choice!==void 0}lt();Gr();function MG(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="Template"&&"incrementFileName"in r}function RG(r){for(let t of r)j_(t)&&(t.choices=RG(t.choices)),MG(t)&&(t.setFileExistsBehavior=!0,t.fileExistsMode="Increment the file name",delete t.incrementFileName);return r}function jie(r){for(let t of r)for(let e of Mt(ur(t)))Y_(e)&&MG(e.choice)&&(e.choice.setFileExistsBehavior=!0,e.choice.fileExistsMode="Increment the file name",delete e.choice.incrementFileName);return r}var Yie={description:"'Increment file name' setting moved to 'Set default behavior if file already exists' setting",migrate:async r=>{let t=r.settings,e=!mp(r.settings.choices)&&!Wt(t.macros);if(Array.isArray(r.settings.choices)){let o=ke(r.settings.choices);r.settings.choices=ke(RG(o))}let n=ke(km(t.macros)),i=jie(n);if(Array.isArray(t.macros)&&(t.macros=i),!e)return{complete:!1}}},OG=Yie;tn();var Kie={description:"Re-run template file collision normalization for users with older migration state",migrate:async r=>{let t=r.settings,e=!af(t);if(Array.isArray(r.settings.choices)&&(r.settings.choices=ke(r.settings.choices)),Array.isArray(t.macros)&&(t.macros=ke(t.macros)),lf(r,n=>{AE(n)&&IE(n)}),!e)return{complete:!1}}},K_=Kie;var Qie={description:"Repair template file collision settings that may have been left in legacy format",migrate:K_.migrate},DG=Qie;lt();function QM(r){return Ee(r)&&r.type==="Capture"}tn();lt();Gr();function LG(r){for(let t of r)j_(t)&&(t.choices=LG(t.choices)),QM(t)&&t.insertAfter?.enabled&&t.prepend&&(t.prepend=!1);return r}function Xie(r){for(let t of r)for(let e of Mt(ur(t)))Y_(e)&&QM(e.choice)&&e.choice.insertAfter?.enabled&&e.choice.prepend&&(e.choice.prepend=!1);return r}var Jie={description:"Mutual exclusion of insertAfter and writeToBottomOfFile settings. If insertAfter is enabled, writeToBottomOfFile is disabled. To support changes in settings UI.",migrate:async r=>{let t=r.settings,e=!mp(r.settings.choices)&&!Wt(t.macros);if(Array.isArray(r.settings.choices)){let o=ke(r.settings.choices);r.settings.choices=LG(o)}let n=ke(km(t.macros)),i=Xie(n);if(Array.isArray(t.macros)&&(t.macros=i),!e)return{complete:!1}}},NG=Jie;je();var Zie={description:"Set version to the current plugin version.",migrate:async r=>{U.setState({version:r.manifest.version})}},VG=Zie;gi();je();tn();var eoe={description:"Add default AI providers to the settings.",migrate:async r=>{let t=U.getState().ai,e=ke(Zb);if("OpenAIApiKey"in t&&typeof t.OpenAIApiKey=="string"){let n=e.find(i=>i.name==="OpenAI");n&&(n.apiKey=t.OpenAIApiKey)}"OpenAIApiKey"in t&&delete t.OpenAIApiKey,U.setState({ai:{...U.getState().ai,providers:e}})}},BG=eoe;ye();lt();Gr();var toe={description:"Remove macro indirection - embed macros directly in macro choices",migrate:async r=>{let t=r.settings;if(mp(t.choices))return S.logMessage("QuickAdd could not read part of the choice list, so legacy macros were left in place to be migrated later."),{complete:!1};if(!Array.isArray(t.choices))return S.logMessage("QuickAdd could not read the choice list, so legacy macros were left in place to be migrated later."),{complete:!1};if(Wt(t.macros))return S.logMessage("QuickAdd could not read the legacy macro list, so it was left in place to be migrated later."),{complete:!1};let e=km(t.macros),n=new Map,i=Zt(t.choices);for(let o of i)if(o.type==="Macro"){let s=o;if(s.macroId){let a=s.macroId;n.has(a)||n.set(a,[]),n.get(a).push(s)}}for(let o of e){if(!o||typeof o!="object"||typeof o.id!="string"||o.id==="")continue;let s=n.get(o.id)??i.filter(a=>a.type==="Macro"&&a.macro?.id===o.id);if(s.length===0){let a=new ef(o.name);a.macro={id:o.id,name:o.name,commands:o.commands||[]},a.runOnStartup=o.runOnStartup||!1,t.choices.push(a)}else for(let a of s)a.macro={id:o.id,name:o.name,commands:o.commands||[]},a.runOnStartup??(a.runOnStartup=o.runOnStartup??!1),delete a.macroId}for(let o of i)if(o.type==="Macro"){let s=o;s.macroId&&(S.logMessage(`Removing orphaned macroId reference: ${s.macroId}`),delete s.macroId)}"macros"in t&&delete t.macros}},UG=toe;ye();var roe={description:"Migrate legacy openFileInNewTab settings to new fileOpening format",migrate:async r=>{S.logMessage("Starting migration of file opening settings...");let t=af(r.settings),e=0;if(lf(r,i=>{if(i.type!=="Template"&&i.type!=="Capture")return;let o=i,s=o.openFileInNewTab,a=o.openFileInMode,l=df(s);!o.fileOpening&&l&&(o.fileOpening=uf(l,a),e++,S.logMessage(`Migrated file opening settings for choice: ${i.name}`))}),S.logMessage(`Migration complete. Migrated ${e} choices.`),t)return{complete:!1}}},qG=roe;ye();var noe={description:"Backfill missing file opening defaults for older choices",migrate:async r=>{S.logMessage("Starting file opening defaults backfill...");let t=af(r.settings),e=0;if(lf(r,i=>{if(i.type!=="Template"&&i.type!=="Capture")return;let o=i,s=typeof o.fileOpening=="object"&&o.fileOpening!==null?o.fileOpening:void 0,a=o,l=a.openFileInNewTab,c=a.openFileInMode,d=df(l);(!s||s.location==null||s.direction==null||s.mode==null||s.focus==null)&&(!s&&d?o.fileOpening=uf(d,c):o.fileOpening=rn(s),e++)}),S.logMessage(`File opening defaults backfill complete. Updated ${e} choice(s).`),t)return{complete:!1}}},zG=noe;je();tn();var ioe={description:"Ensure every AI provider has a discovery mode so browsing works without models.dev",migrate:async r=>{let e=U.getState().ai.providers??[],n=!1;for(let i of e)i.modelSource||(i.modelSource="auto",n=!0);n&&U.setState(i=>({...i,ai:{...i.ai,providers:ke(e)}}))}},HG=ioe;tn();ye();je();tn();Ic();var ooe={description:"Move AI provider API keys into Obsidian SecretStorage",migrate:async r=>{let t=U.getState().ai.providers??[],e=()=>t.some(o=>(o.apiKey?.trim()??"")!==""),n=r.app?.secretStorage;if(!n?.getSecret||!n?.setSecret)return e()?(S.logWarning("SecretStorage unavailable; deferring AI provider API key migration until it is available."),{complete:!1}):void 0;let i=!1;for(let o of t){let s=o.apiKey?.trim(),a=o.apiKeyRef?.trim();if(a){try{let l=await Promise.resolve(n.getSecret(a));!l&&s?(await Promise.resolve(n.setSecret(a,s)),o.apiKey="",i=!0):l&&s&&(o.apiKey="",i=!0)}catch(l){S.logWarning(`Failed to migrate secret for ${o.name}: ${l.message??l}`)}continue}if(s)try{let l=await gz(r.app,o,s);l&&(o.apiKeyRef=l,o.apiKey="",i=!0)}catch(l){S.logWarning(`Failed to store API key for ${o.name}: ${l.message??l}`)}}if(i&&U.setState(o=>({...o,ai:{...o.ai,providers:ke(t)}})),e())return{complete:!1}}},WG=ooe;Jt();var GG={description:"Move the single template folder path into the multi-folder list.",migrate:async r=>{let t=r.settings,e=ti(t.templateFolderPaths);e.length>0?t.templateFolderPaths=e:t.templateFolderPaths=ti([t.templateFolderPath]),delete t.templateFolderPath}};gi();er();je();tn();ye();function soe(r){for(let t of[r,`https://${r}`])try{let e=new URL(t).hostname.toLowerCase();if(e)return e}catch{}return""}function aoe(r){let t=soe(r.endpoint??"");return t==="api.openai.com"?"openai":t==="generativelanguage.googleapis.com"?"google":t==="api.anthropic.com"?"anthropic":null}function loe(r,t,e){let n=new Set(t==="anthropic"?[]:dD[t]);r.models=r.models.filter(o=>!n.has(o.name));let i=new Map(r.models.map(o=>[o.name,o]));for(let o of Ah[t]){let s=i.get(o.name);s?(s.maxTokens=o.maxTokens,s.maxOutputTokens=o.maxOutputTokens,s.supportsTemperature=o.supportsTemperature):e.has(o.name)||r.models.push({...o})}}var coe={temperature:1,top_p:1,frequency_penalty:0,presence_penalty:0};function doe(r){return r.type==="AIAssistant"}var uoe={description:"Refresh built-in AI provider model lists: drop retired models, add the current generation, and turn on auto-sync.",migrate:async r=>{let t=U.getState(),e=ke(t.ai.providers??[]),n=ke(t.choices??[]),i=new Set;for(let l of e){let c=aoe(l);if(!c)continue;let d=new Set(e.filter(m=>m!==l).flatMap(m=>m.models.map(h=>h.name))),u=l.models.map(m=>m.name);loe(l,c,d);let p=new Set(l.models.map(m=>m.name));for(let m of u)p.has(m)||i.add(m);l.autoSyncModels=!0,c==="openai"&&(l.modelSource="modelsDev")}let o=new Set(e.flatMap(l=>l.models.map(c=>c.name))),s=new Set([...i].filter(l=>!o.has(l)));kE({choices:n},l=>{if(!doe(l))return;l.model&&s.has(l.model)&&(S.logMessage(`AI command "${l.name}" used ${l.model}, which its provider has retired. It now asks for a model when it runs.`),l.model="Ask me");let c=l.modelParameters;if(c&&typeof c=="object")for(let[d,u]of Object.entries(coe))c[d]===u&&delete c[d]});let a=s.has(t.ai.defaultModel)?"Ask me":t.ai.defaultModel;U.setState({choices:n,ai:{...U.getState().ai,defaultModel:a,providers:e}})}},jG=uoe;gi();je();tn();ye();function poe(r,t){return r.find(e=>e.models.some(n=>n.name===t))}var moe={description:"Pin AI commands' models to the provider they currently resolve to, and give every provider a stable id.",migrate:async r=>{let t=U.getState(),e=ke(t.ai.providers??[]),n=ke(t.choices??[]);Xb(e),SE(n,e,(s,a)=>{S.logMessage(`Pinned AI command "${s.name}"'s model to ${a.providerId}/${a.name}.`)});let i,o=t.ai.defaultModel;if(t.ai.defaultModelRef&&t.ai.defaultModelRef.name===o)i=t.ai.defaultModelRef;else if(o&&o!=="Ask me"){let s=poe(e,o);s?.id&&(i={providerId:s.id,name:o},S.logMessage(`Pinned the default model to ${s.id}/${o}.`))}U.setState({choices:n,ai:{...U.getState().ai,providers:e,...i?{defaultModelRef:i}:{}}})}},YG=moe;je();var XM={useQuickAddTemplateFolder:FG,incrementFileNameSettingMoveToDefaultBehavior:OG,consolidateFileExistsBehavior:K_,repairTemplateFileExistsBehavior:DG,mutualExclusionInsertAfterAndWriteToBottomOfFile:NG,setVersionAfterUpdateModalRelease:VG,addDefaultAIProviders:BG,removeMacroIndirection:UG,migrateFileOpeningSettings:qG,backfillFileOpeningDefaults:zG,setProviderModelDiscoveryMode:HG,migrateProviderApiKeysToSecretStorage:WG,migrateToMultipleTemplateFolders:GG,refreshStaleDefaultModelSeeds:jG,pinAiModelRefs:YG};async function foe(r){let t=Object.keys(XM).filter(e=>!r.settings.migrations[e]);if(t.length===0){S.logMessage("No migrations to run.");return}U.replaceState(ke(r.settings));for(let e of t){S.logMessage(`Running migration ${e}: ${XM[e].description}`);let n=ke(r.settings),i=U.getState();try{let o=await XM[e].migrate(r);U.getState()!==i&&(r.settings=ke(U.getState()));let s=o?.complete===!1;s||(r.settings.migrations[e]=!0),U.replaceState(ke(r.settings)),S.logMessage(s?`Migration ${e} incomplete; will retry on a later launch.`:`Migration ${e} successful.`)}catch(o){S.logError(`Migration '${e}' was unsuccessful. Please create an issue with the following error message:
|
||
|
||
${o}
|
||
|
||
QuickAdd will now revert to backup.`),r.settings=n,U.replaceState(ke(r.settings))}}r.saveSettings()}var KG=foe;je();var la=require("obsidian");ye();function Wf(r){if(!r||typeof r!="string")return null;let t=r.split("-")[0]?.split("+")[0]?.trim();if(!t)return null;let e=t.split(".");if(e.length!==3)return null;let n=Number.parseInt(e[0]??"",10),i=Number.parseInt(e[1]??"",10),o=Number.parseInt(e[2]??"",10);return Number.isNaN(n)||Number.isNaN(i)||Number.isNaN(o)||n<0||i<0||o<0?null:{major:n,minor:i,patch:o}}function QG(r,t){return r.major-t.major||r.minor-t.minor||r.patch-t.patch}async function hoe(r,t,e){let n=await(0,la.requestUrl)({url:`https://api.github.com/repos/${r}/${t}/releases?per_page=100`,throw:!1}),i=n.json;if(n.status>=400||!Array.isArray(i)){let s=typeof i=="object"&&i!==null&&"message"in i&&typeof i.message=="string"?i.message:"Unknown error";throw new Error(`Failed to fetch releases: ${s}`)}let o=Wf(e);if(!o)throw new Error(`Invalid version ${e}`);return i.filter(s=>{if(s.draft||s.prerelease)return!1;let a=Wf(s.tag_name);return a!==null&&QG(a,o)>0})}var JM=/^https:\/\/github\.com\/user-attachments\/assets\/[A-Za-z0-9-]+$/,XG=/^\[!\[[^\]]*\]\(([^)\s"]+)\)\]\((https:\/\/github\.com\/user-attachments\/assets\/[A-Za-z0-9-]+)\)$/,goe=/^<!--\s*poster:\s*(https:\/\/[^\s"'>]+)\s*-->$/;function voe(r,t){let e=t?` poster="${t}"`:"";return`<video controls preload="metadata" playsinline style="width: 100%; border-radius: 8px;" src="${r}"${e}></video>`}function yoe(r){let t=r.split(`
|
||
`),e=new Set;for(let s of t){let a=s.trim();JM.test(a)&&e.add(a)}let n=new Map;for(let s of t){let a=s.trim().match(XG);a&&e.has(a[2])&&n.set(a[2],a[1])}let i=new Set;for(let s=0;s<t.length;s++)if(JM.test(t[s].trim()))for(let a of[1,-1]){let l=s+a;for(;l>=0&&l<t.length&&t[l].trim()==="";)l+=a;let c=l>=0&&l<t.length?t[l].trim().match(goe):null;if(c){n.set(t[s].trim(),c[1]),i.add(l);break}}let o=[];for(let s=0;s<t.length;s++){let a=t[s],l=a.trim();if(i.has(s))continue;let c=l.match(XG);if(!(c&&e.has(c[2]))){if(JM.test(l)){o.push(voe(l,n.get(l)));continue}o.push(a)}}return o.join(`
|
||
`)}var Q_=class extends la.Modal{constructor(e,n){super(e);this.markdownComponent=new la.Component;this.isClosed=!1;this.previousVersion=n,this.releaseNotesPromise=hoe("chhoumann","quickadd",n),this.releaseNotesPromise.then(i=>{if(!this.isClosed){if(this.releases=i,this.releases.length===0){this.close();return}this.display()}}).catch(i=>{S.logError(`Failed to fetch release notes: ${i}`),this.isClosed||this.close()})}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h1",{text:"Fetching release notes..."}),this.addCloseFooter()}addCloseFooter(){let e=this.contentEl.createDiv("quickadd-update-modal-footer");new la.ButtonComponent(e).setButtonText("Done").setCta().onClick(()=>this.close())}onClose(){let{contentEl:e}=this;this.isClosed=!0,this.markdownComponent.unload(),e.empty()}display(){let{contentEl:e}=this;e.empty(),e.classList.add("quickadd-update-modal-container");let n=`## New in QuickAdd v${this.releases[0].tag_name}
|
||
`,i="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.",o='<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>',s=e.createDiv("quickadd-update-modal markdown-rendered"),a=this.releases.map(u=>yoe(u.body??"")).join(`
|
||
---
|
||
`),l=`And now, here is everything new in QuickAdd since your last update (v${this.previousVersion}):`,d=`${n}
|
||
${i}
|
||
${o}
|
||
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.
|
||
|
||
${l}
|
||
|
||
---
|
||
|
||
${a}`;this.markdownComponent.load(),la.MarkdownRenderer.render(this.app,d,s,this.app.vault.getRoot().path,this.markdownComponent),this.addCloseFooter()}};TT();tn();function ZM(r){if(r===!0||r==="true")return!0;if(r===!1||r==="false")return!1}function JG(r,t){if(t.cancelled!==void 0&&typeof t.cancelled!="boolean")return`The "cancelled" flag must be the literal true (or omitted). A cancel that is not recognised would otherwise be answered on the user's behalf.`;if(t.cancelled===!0)return null;if(r==="confirm"){let e=t.value;if(ZM(e)===void 0)return`A confirm prompt needs a boolean reply, or {"cancelled": true} if the user dismissed it. Got ${eR(e)}.`}return null}function eR(r){return r===void 0?"no value":r===null?"null":typeof r=="string"?JSON.stringify(r.slice(0,40)):typeof r=="number"||typeof r=="boolean"?String(r):Array.isArray(r)?"an array":typeof r}rr();Sn();var boe=25e3,woe=6e4,Coe=3e4,xoe=75e3,Eoe=3e3,Toe=32;function _oe(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r.charCodeAt(n)^t.charCodeAt(n);return e===0}function koe(r){if(r.origin||r.referer)return!1;let t=(r.host??"").split(":")[0];return t==="127.0.0.1"||t==="localhost"}function Soe(r){try{let t=window.require;return t?t(r):null}catch{return null}}function X_(){let r=window.crypto;if(r?.randomUUID)return r.randomUUID();if(r?.getRandomValues){let t=r.getRandomValues(new Uint8Array(16));return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}throw new Error("Interactive prompts require a secure random source (crypto), which is unavailable here.")}var J_="No pending prompt for that requestId",tR="The interactive client disconnected, so the run was ended.",rR=class{constructor(){this.server=null;this.port=0;this.sessions=new Map;this.startPromise=null;this.generation=0}async ensureStarted(){if(this.server)return this.port;if(this.startPromise)return this.startPromise;let t=Soe("http");if(!t)throw new Error("Interactive prompts require desktop Obsidian (Node http is unavailable).");let e=this.generation;return this.startPromise=new Promise((n,i)=>{let o=t.createServer((s,a)=>{this.handle(s,a)});o.on("error",s=>{this.generation===e&&(this.startPromise=null),i(s)}),o.listen(0,"127.0.0.1",()=>{if(this.generation!==e){o.close(),i(new Error("Interactive server stopped during startup."));return}let s=o.address();this.port=typeof s=="object"&&s?s.port:0,this.server=o,n(this.port)})}),this.startPromise}createSession(){if(this.sessions.size>=Toe)throw new Error("Too many active interactive sessions.");let t=X_(),e=X_()+X_(),n={id:t,token:e,queue:[],waiter:null,waiterTimer:null,pending:new Map,finished:!1,aborted:!1,cleanupTimer:null,attached:!1,attachTimer:null,pollWatchdog:null,disconnectGrace:null};return n.attachTimer=window.setTimeout(()=>{!n.attached&&!n.finished&&this.finish(n.id,{kind:"error",error:"No client attached to the interactive session."})},Coe),this.sessions.set(t,n),{id:t,token:e}}emitPrompt(t,e){let n=this.sessions.get(t);if(!n)return Promise.reject(new Error("Unknown session"));if(n.finished)return Promise.reject(new de(tR));if(n.aborted)return Promise.reject(new et(ql));let i=X_();return new Promise((o,s)=>{n.pending.set(i,{resolve:o,reject:s,promptType:e.type}),this.push(n,{kind:"prompt",requestId:i,prompt:e})})}finish(t,e){let n=this.sessions.get(t);if(!(!n||n.finished)){n.finished=!0,n.attachTimer&&(window.clearTimeout(n.attachTimer),n.attachTimer=null),n.pollWatchdog&&(window.clearTimeout(n.pollWatchdog),n.pollWatchdog=null),n.disconnectGrace&&(window.clearTimeout(n.disconnectGrace),n.disconnectGrace=null);for(let[,i]of n.pending)i.reject(new de(tR));n.pending.clear(),this.push(n,e),n.cleanupTimer=window.setTimeout(()=>this.destroySession(n),woe)}}abortSession(t){let e=this.sessions.get(t);if(!e||e.finished)return null;e.aborted=!0;let n=[...e.pending.values()];e.pending.clear();for(let i of n)i.reject(new et(ql));return e.queue=e.queue.filter(i=>i.kind!=="prompt"),n.length}stop(){this.generation++;for(let t of this.sessions.values()){this.clearSessionTimers(t);for(let[,e]of t.pending)e.reject(new de("QuickAdd was unloaded during an interactive run."));if(t.waiter){let e=t.waiter;t.waiter=null,e({kind:"error",error:"QuickAdd unloaded"})}}this.sessions.clear(),this.server?.close(),this.server=null,this.port=0,this.startPromise=null}push(t,e){if(t.waiter){let n=t.waiter;t.waiter=null,t.waiterTimer&&(window.clearTimeout(t.waiterTimer),t.waiterTimer=null),n(e)}else t.queue.push(e)}clearSessionTimers(t){for(let e of[t.waiterTimer,t.cleanupTimer,t.attachTimer,t.pollWatchdog,t.disconnectGrace])e&&window.clearTimeout(e)}destroySession(t){this.clearSessionTimers(t);for(let[,e]of t.pending)e.reject(new de(tR));t.pending.clear(),this.sessions.delete(t.id),this.sessions.size===0&&(this.server?.close(),this.server=null,this.port=0,this.startPromise=null)}authed(t,e){return!!t&&!!e&&_oe(t.token,e)}originAllowed(t){return koe({origin:t.headers.origin,referer:t.headers.referer,host:t.headers.host})}submitReply(t,e,n,i=!1){let o=this.sessions.get(t);if(!o)return!1;let s=o.pending.get(e);return s?(o.pending.delete(e),i===!0?s.promptType==="info"?s.resolve(n):s.reject(new et(ql)):s.resolve(n),!0):!1}pendingPromptType(t,e){return t.pending.get(e)?.promptType}send(t,e,n){let i=JSON.stringify(n);t.writeHead(e,{"content-type":"application/json","cache-control":"no-store"}),t.end(i)}async drainBody(t){let e=0;for await(let n of t)if(e+=n.length,e>1e6)throw new Error("Request body too large")}async readBody(t){let e=[],n=0;for await(let i of t){if(n+=i.length,n>1e6)throw new Error("Request body too large");e.push(i)}return e.length===0?{}:JSON.parse(Buffer.concat(e).toString("utf8"))}async handle(t,e){try{if(!this.originAllowed(t)){this.send(e,403,{ok:!1,error:"Forbidden"});return}let n=new URL(t.url??"/","http://127.0.0.1"),i=n.searchParams.get("session"),o=n.searchParams.get("token"),s=i?this.sessions.get(i):void 0;if(!this.authed(s,o)){this.send(e,404,{ok:!1,error:"Unknown session or token"});return}if(t.method==="GET"&&n.pathname==="/poll"){this.handlePoll(s,e);return}if(t.method==="POST"&&n.pathname==="/abort"){await this.drainBody(t);let a=this.abortSession(s.id);if(a===null){this.send(e,409,{ok:!1,error:"The interactive session has already ended"});return}this.send(e,200,{ok:!0,interrupted:a});return}if(t.method==="POST"&&n.pathname==="/reply"){let a=await this.readBody(t),l=this.submitWireReply(s.id,a);l.ok?this.send(e,200,{ok:!0}):this.send(e,l.status,{ok:!1,error:l.error});return}this.send(e,404,{ok:!1,error:"Not found"})}catch(n){this.send(e,400,{ok:!1,error:n instanceof Error?n.message:String(n)})}}handlePoll(t,e){t.attached||(t.attached=!0,t.attachTimer&&(window.clearTimeout(t.attachTimer),t.attachTimer=null)),t.pollWatchdog&&window.clearTimeout(t.pollWatchdog),t.pollWatchdog=window.setTimeout(()=>this.finishDisconnected(t),xoe),t.disconnectGrace&&(window.clearTimeout(t.disconnectGrace),t.disconnectGrace=null);let n=t.queue.shift();if(n){this.send(e,200,n);return}if(t.waiter){this.send(e,200,{kind:"idle"});return}let i=o=>this.send(e,200,o);t.waiter=i,t.waiterTimer=window.setTimeout(()=>{t.waiter===i&&(t.waiter=null,t.waiterTimer=null,this.send(e,200,{kind:"idle"}))},boe),e.on("close",()=>{t.waiter===i&&(t.waiterTimer&&window.clearTimeout(t.waiterTimer),t.waiter=null,t.waiterTimer=null,t.disconnectGrace&&window.clearTimeout(t.disconnectGrace),t.disconnectGrace=window.setTimeout(()=>this.finishDisconnected(t),Eoe))})}finishDisconnected(t){this.finish(t.id,{kind:"error",error:"Interactive client disconnected."})}submitWireReply(t,e){let n=this.sessions.get(t);if(!n)return{ok:!1,status:409,error:J_};if(!e.requestId)return{ok:!1,status:409,error:J_};let i=this.pendingPromptType(n,e.requestId);if(!i)return{ok:!1,status:409,error:J_};let o=JG(i,e);return o?{ok:!1,status:400,error:o}:this.submitReply(n.id,e.requestId,e.value,e.cancelled)?{ok:!0}:{ok:!1,status:409,error:J_}}},El=new rR;lt();ye();lt();jy();Dr();Le();sA();Ua();Jt();Ac();function Aoe(r,t){return r.type==="Capture"?ZG(Foe(r,t)):r.type==="Template"?ZG(Moe(r,t)):"none"}async function Z_(r,t){let e=r.app.vault;return Aoe(t,{templates:await Poe(r.app,Ioe(t)),newNotesInCurrentFolder:e.getConfig?.("newFileLocation")==="current"})}function Ioe(r){let t=r.type==="Capture"?r.createFileIfItDoesntExist:void 0;return[...r.type==="Template"?[[r.templatePath??"","content"]]:t?.enabled&&t.createWithTemplate?[[t.template,"content"]]:[],...nR(r).flatMap(([n,i])=>ej(n,i))]}function ej(r,t){return[...Xs(r)].map(e=>[e,t])}async function Poe(r,t){let e=[...t],n=new Set,i=[];for(let o=e.shift();o!==void 0;o=e.shift()){let[s,a]=o,l=nn(r,s);if(!l||n.has(`${a}:${l.path}`))continue;n.add(`${a}:${l.path}`);let c=await r.vault.cachedRead(l);i.push([c,a]),e.push(...ej(c,a))}return i}function nR(r){if(r.type==="Capture"){let t=r,e=t.propertyCapture?.property;return[[$oe(t),"content"],[t.captureToActiveFile?"":t.captureTo??"","path"],[t.insertAfter?.enabled&&!t.insertAfter.promptHeading?t.insertAfter.after:"","line"],[t.insertBefore?.enabled?t.insertBefore.before:"","line"],[e?.kind==="named"?e.format:"","property"]]}if(r.type==="Template"){let t=r,e=tj(t);return[[t.fileNameFormat?.enabled?t.fileNameFormat.format:"{{VALUE}}","path"],[iu(e)==="specified"?(e.folders??[]).join(`
|
||
`):"","path"]]}return[]}function $oe(r){return r.format?.enabled?r.format.format:"{{VALUE}}"}function tj(r){return r.folder??{enabled:!1,folders:[]}}function Foe(r,{templates:t}){let e=Zo(r.appendLink),n=[...nR(r),...t];return[r.captureToActiveFile?"required":"none",rj(e),...n.map(([i,o])=>nj(i,o,e)),...n.map(([i])=>ij(i)),...n.map(([i])=>oj(i))]}function Moe(r,{templates:t,newNotesInCurrentFolder:e}){let n=Zo(r.appendLink),i=iu(tj(r)),o=[...nR(r),...t];return[i==="active-file"||i==="obsidian-default"&&e?"required":"none",rj(n),...o.map(([s,a])=>nj(s,a,n)),...o.map(([s])=>ij(s)),...o.map(([s])=>oj(s))]}function rj(r){return!r.enabled||r.destination.type!=="activeFile"?"none":r.requireActiveFile?"required":"optional"}var Roe=new RegExp(H0.source,"gi");function nj(r,t,e){let n=t==="line"?r.replace(Roe,""):r;return z0.test(n)?t==="content"&&e.enabled&&!e.requireActiveFile?"optional":"required":"none"}var Ooe=/{{FIELD:[^}]*\|\s*default-from\s*:\s*active\s*(?:\||}})/i;function ij(r){return Ooe.test(r)?"optional":"none"}function oj(r){return Oh.test(r)?"optional":"none"}function ZG(r){return r.includes("required")?"required":r.includes("optional")?"optional":"none"}var iR={choice:{value:"<name>",description:"Choice name"},id:{value:"<id>",description:"Choice id"}},oR={value:"<json>",description:"Variables object as JSON"},sj={description:"Allow interactive prompts"},aj={value:"<when>",description:"Day for {{DATE}} (YYYY-MM-DD, last week, last friday, ask, @date:ISO)"},ek={value:"<vault-path|none>",description:"Current note for the run: a vault path, or none (default: the active tab)"},tk={...iR,vars:oR,ui:sj,verify:{description:"Report the verified outcome for Template/Capture choices (file path and effect on success, honest failure when the engine swallows an error)"},date:aj,current:ek},lj={type:{value:"<Template|Capture|Macro|Multi>",description:"Filter by choice type"},commands:{description:"Only include command-enabled choices"}},cj={kind:{value:"<links|tags>",description:"Which suggestions to list"},source:{value:"<vault-path>",description:"Note the link will be inserted in (link text follows the vault's link format from there)"}},sR={path:{value:"<vault-path>",description:"Path to a template file in the vault"},vars:oR,ui:sj,date:aj,current:ek},aR={...iR,vars:oR,fields:{description:"Include full field metadata (options, defaults, widget config)"},current:ek},lR={...iR,vars:{value:"<json>",description:"Variables object as JSON (pre-seeded inputs)"},current:ek},dj={path:{value:"<vault-path>",description:"Path to a .quickadd.json package file in the vault"},decode:{description:"Inline decoded contents for each bundled file"}},uj=new Set(Object.keys(tk)),cR=new Set(Object.keys(sR)),pj=new Set(Object.keys(aR)),mj=new Set(Object.keys(lR));function ca(r){if(r===void 0)return!1;let t=r.toLowerCase();return t==="true"||t==="1"||t==="yes"||t==="on"}function Doe(r){let t;try{t=JSON.parse(r)}catch(e){throw new Error(`Invalid vars JSON: ${e instanceof Error?e.message:String(e)}`)}if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid vars JSON: expected an object");return t}function Gf(r,t){let e={};typeof r.vars=="string"&&Object.assign(e,Doe(r.vars));for(let[n,i]of Object.entries(r)){if(n.startsWith("value-")){let o=n.slice(6);o&&(e[o]=i);continue}t.has(n)||(e[n]=i)}return e}function rb(r,t){if(typeof t.current!="string")return;let e=t.current.trim();if(e==="none")return null;let n=cr(e),i=r.vault.getFileByPath(n)??r.vault.getFileByPath(`${n}.md`);if(!i)throw new Error(`No note at '${e}'.`);return i}function nb(r,t){if(typeof t.id=="string"&&t.id.trim().length>0)return r.getChoiceById(t.id);if(typeof t.choice=="string"&&t.choice.trim().length>0)return r.getChoiceByName(t.choice);throw new Error("Missing choice selector. Provide either choice=<name> or id=<id>")}function ib(r){return{id:r.id,label:r.label,type:r.type,source:r.source??"collected",placeholder:r.placeholder,defaultValue:r.defaultValue,description:r.description,optionCount:r.options?.length??0}}function fj(r){return{...ib(r),options:r.options,displayOptions:r.displayOptions,dateFormat:r.dateFormat,withTime:r.withTime,optional:r.optional,runtimeOnly:r.runtimeOnly,multiEmit:r.multiEmit,filters:r.filters,numericConfig:r.numericConfig,sliderConfig:r.sliderConfig,suggesterConfig:r.suggesterConfig}}function ob(r,t){for(let[e,n]of Object.entries(t))r.variables.set(e,n)}async function Ou(r,t){return{id:t.id,name:t.name,type:t.type,currentNote:await Z_(r,t)}}var Loe=new Set(["template","capture","macro","multi"]);function Noe(r){if(r.type==="Capture"){let t=r,e=EC(t),n={target:t.captureToActiveFile?"<active file>":t.captureTo,position:e==="activeTop"?"top":e==="top"&&t.captureToActiveFile?"cursor":e};if(e==="after"&&(n.line=t.insertAfter.promptHeading?"<ask>":t.insertAfter.after),e==="before"&&(n.line=t.insertBefore?.before??""),t.propertyCapture){let o=t.propertyCapture.property;n.property=o.kind==="named"?o.format:"<ask>"}n.format=t.format?.enabled?t.format.format:"{{VALUE}}",t.propertyCapture||(t.task&&(n.task=!0),t.eachLine&&(n.eachLine=!0));let i=t.createFileIfItDoesntExist;return i?.enabled&&i.createWithTemplate&&i.template&&(n.createWithTemplate=i.template),n}if(r.type==="Template"){let t=r,e=t.folder??{enabled:!1,folders:[]},n=iu(e);return{template:t.templatePath,folder:n==="obsidian-default"?"<default>":n==="active-file"?"<active file's folder>":n==="specified"&&e.folders?.length===1&&!e.chooseFromSubfolders?e.folders[0]:"<ask>",fileName:t.fileNameFormat?.enabled?t.fileNameFormat.format:"{{VALUE}}"}}}async function hj(r,t,e=[]){let n=[];for(let i of mr(t)){if(!Ee(i))continue;let o=[...e,i.name],s=o.join(" / "),a=i.type==="Multi";n.push({id:i.id,name:i.name,type:i.type,command:i.command,path:s,runnable:!a,currentNote:await Z_(r,i),writes:Noe(i)}),a&&n.push(...await hj(r,Ne(i),o))}return n}async function gj(r,t){let e=typeof t.type=="string"?t.type.trim():"",n=e.toLowerCase();if(n&&!Loe.has(n))return{ok:!1,error:`Invalid type filter '${e}'.`};let i=(await hj(r,r.settings.choices)).filter(o=>(!n||o.type.toLowerCase()===n)&&(!ca(t.commands)||o.command));return{ok:!0,count:i.length,choices:i}}async function vj(r,t){let e=nb(r,t);if(e.type==="Multi")return{ok:!1,error:"Multi choices are interactive and cannot be checked via CLI.",choice:await Ou(r,e)};let n=Gf(t,pj),i=new Ar(r.app,r),o=rb(r.app,t);o!==void 0&&i.setCurrentFile(o),ob(i,n);let s=await sa(r.app,r,i,e),a=wl(s,i.variables),l=ca(t.fields)?fj:ib;return{ok:a.length===0,choice:await Ou(r,e),requiredInputCount:s.length,missingInputCount:a.length,missing:a.map(l),missingFlags:a.map(c=>`value-${c.id}=<value>`),...e.type==="Macro"?{deferred:YH(r,e,i.variables.get("value"))}:{}}}async function yj(r,t){let e=typeof t.path=="string"?t.path.trim():"";if(!e)return{ok:!1,error:"Missing package path. Provide path=<vault-path>."};let{pkg:n}=await LE(r.app,e),i=await mf(r.app,r.settings.choices,n),o={ok:!0,preview:i};return ca(t.decode)&&(o.contents=i.files.map(s=>({path:s.originalPath,...OE(n,s.originalPath)}))),o}function bj(r){let t=r.metadataCache;return{linkCandidates:e=>t.getLinkSuggestions?.().flatMap(({file:n,alias:i})=>n?[{path:n.path,mtime:n.stat.mtime,linktext:t.fileToLinktext(n,e),alias:i,excluded:t.isUserIgnored(n.path)}]:[])??null,tagCounts:()=>t.getTags()}}function wj(r,t){if(t.kind==="links"){let e=typeof t.source=="string"?t.source:"",n=r.linkCandidates(e);return n?{ok:!0,kind:"links",items:[...n].sort((o,s)=>Number(o.excluded)-Number(s.excluded)||s.mtime-o.mtime).map(({path:o,linktext:s,alias:a})=>a===void 0?{text:s,path:o}:{text:`${s}|${a}`,path:o,alias:a})}:{ok:!1,error:"This Obsidian version has no link suggestions API; update Obsidian."}}return t.kind==="tags"?{ok:!0,kind:"tags",items:Object.entries(r.tagCounts()).map(([n,i])=>({tag:n.replace(/^#/,""),count:i})).sort((n,i)=>i.count-n.count||n.tag.localeCompare(i.tag))}:{ok:!1,error:"kind must be links or tags"}}Le();vu();var sb="\0qa-idx:";function Cj(r,t){let e=String(r);if(e.startsWith(sb)){let n=Number(e.slice(sb.length));if(Number.isInteger(n)&&n>=0&&n<t.length)return t[n]}return e}var rk=class{constructor(t,e=El){this.sessionId=t;this.server=e}async suggester(t,e,n,i=!1){let o=typeof t=="function"?e.map((l,c,d)=>String(t(l,c,d))):t.map(l=>String(l)),s=e.map((l,c)=>({title:o[c]??String(l),value:`${sb}${c}`})),a=await this.server.emitPrompt(this.sessionId,{type:"suggester",placeholder:n,allowCustomInput:i,items:s});return a==null?"":Cj(a,e)}async suggesterMulti(t,e,n){let i=e.map((a,l)=>({title:t[l]??String(a),value:`${sb}${l}`})),o=[];for(let a of n?.preselected??[]){let l=e.indexOf(a);if(l>=0)o.push(`${sb}${l}`);else{let c=String(a);i.push({title:c,value:c}),o.push(c)}}let s=await this.server.emitPrompt(this.sessionId,{type:"multiselect",placeholder:n?.placeholder,allowCustomInput:n?.allowCustomInput??!1,items:i,preselected:o});return Array.isArray(s)?s.map(a=>Cj(a,e)):[]}async inputPrompt(t,e,n){return this.textPrompt(t,e,n,!1)}async wideInputPrompt(t,e,n){return this.textPrompt(t,e,n,!0)}async textPrompt(t,e,n,i){let o=await this.server.emitPrompt(this.sessionId,{type:"input",header:t,placeholder:e,defaultValue:n,multiline:i});return o==null?"":String(o)}async datePrompt(t,e){let n=await this.server.emitPrompt(this.sessionId,{type:"date",header:t,placeholder:e?.placeholder,defaultValue:e?.defaultValue,dateFormat:e?.dateFormat,withTime:e?.withTime}),i=String(n??"");if(!i)return"";let o=i.startsWith("@date:")?i.slice(6):i,s=e?.dateFormat;return(s?Mo(o,s):null)??o}async yesNoPrompt(t,e){let n=await this.server.emitPrompt(this.sessionId,{type:"confirm",header:t,text:e}),i=ZM(n);if(i!==void 0)return i;throw new Error(`A confirm prompt needs a boolean reply, or {"cancelled": true} if the user dismissed it. Got ${eR(n)}.`)}async checkboxPrompt(t,e,n){let i=new Set(e??[]),o=await this.server.emitPrompt(this.sessionId,{type:"checkbox",header:n,items:t.map(s=>({title:String(s),value:String(s),checked:i.has(s)}))});return Array.isArray(o)?o.map(s=>String(s)):[]}async infoDialog(t,e){await this.server.emitPrompt(this.sessionId,{type:"info",header:t,text:Array.isArray(e)?e:[e]})}async requestInputs(t){let e=t.map(s=>({id:s.id,label:s.label??s.id,type:s.type==="file-picker"?"suggester":s.type,placeholder:s.placeholder,defaultValue:s.defaultValue,description:s.description,options:s.options,displayOptions:s.displayOptions,dateFormat:s.dateFormat,optional:s.optional,numericConfig:s.numericConfig,suggesterConfig:s.suggesterConfig?{allowCustomInput:s.suggesterConfig.allowCustomInput,multiSelect:s.suggesterConfig.multiSelect}:void 0,picker:s.type==="file-picker"?"file":void 0})),n=await this.server.emitPrompt(this.sessionId,{type:"form",fields:e});if(!n||typeof n!="object")return{};let i=new Set(t.filter(s=>s.type==="date").map(s=>s.id)),o={};for(let[s,a]of Object.entries(n)){if(Array.isArray(a)){o[s]=a.map(c=>String(c));continue}let l=a==null?"":String(a);l&&i.has(s)&&!l.startsWith("@date:")&&(l=`@date:${l}`),o[s]=l}return o}};jy();Jt();If();ri();async function dR(r,t,e){if(e&&(t.type==="Template"||t.type==="Capture")&&typeof r.executeWithOutcome=="function"){let i=await r.executeWithOutcome(t);switch(i.status){case"success":return{ok:!0,verified:!0,effect:i.effect,file:i.file?.path};case"cancelled":return{ok:!1,aborted:!0,error:i.reason||(i.cancelKind==="user"?"Execution cancelled by user":"Execution aborted")};case"error":return{ok:!1,error:i.reason||"Choice execution failed; no file was created."}}}let n;try{await r.execute(t),n=r.consumeAbortSignal?.()}catch(i){if(!(i instanceof at))throw i;n=i}return n?{ok:!1,aborted:!0,error:n.message||"Choice execution aborted"}:{ok:!0,verified:!1,effect:"unknown"}}async function xj(r,t,e,n,i){let o=Date.now(),s=await Ou(r,e);if(e.type==="Multi")return{ok:!1,error:"Multi choices are interactive and cannot be run via CLI.",choice:s};let a=new Ar(r.app,r),l=rb(r.app,t);if(l!==void 0&&a.setCurrentFile(l),ob(a,Gf(t,n)),!Af(a,t.date))return{ok:!1,error:`Could not parse date origin '${t.date}'.`,choice:s};if(a.interactive=ca(t.ui),!a.interactive){let d=await sa(r.app,r,a,e,{preloadedUserScripts:a.preloadedUserScripts}),u=wl(d,a.variables);if(u.length)return{ok:!1,error:"Missing required inputs for non-interactive CLI run.",choice:s,missing:u.map(ib),missingFlags:u.map(({id:p})=>p===Sa?"date=<when>":`value-${p}=<value>`)}}return{...await dR(a,e,i),choice:s,durationMs:Date.now()-o}}function uR(r,t){return xj(r,t,nb(r,t),uj,ca(t.verify))}async function Ej(r,t){let e=typeof t.path=="string"?t.path.trim():"";if(!e)return{ok:!1,error:"Missing template path. Provide path=<vault-path>."};let n=nn(r.app,e);if(!n)return{ok:!1,error:`No template file found at '${e}'.`};let i=GM(n.path);if(!ca(t.ui)){let{value:o}=Gf(t,cR);if(o==null||String(o).trim().length===0)return{ok:!1,error:"Missing required inputs for non-interactive CLI run.",choice:await Ou(r,i),missing:[{id:"value",label:"New note name",type:"text",source:"collected",optionCount:0}],missingFlags:["value-value=<value>"]}}return xj(r,t,i,cR,!0)}async function Tj(r,t){let e=nb(r,t),n=await Ou(r,e);if(e.type==="Multi")return{ok:!1,error:"Multi choices cannot be run interactively via CLI.",choice:n};let i=rb(r.app,t),o=await El.ensureStarted(),{id:s,token:a}=El.createSession(),l=new Ar(r.app,r);return i!==void 0&&l.setCurrentFile(i),ob(l,Gf(t,mj)),l.interactive=!0,l.promptProvider=new rk(s),dR(l,e,!0).then(c=>El.finish(s,c.ok?{kind:"done",result:{...c,choice:n}}:{kind:"error",error:c.error})).catch(c=>El.finish(s,{kind:"error",error:c instanceof Error?c.message:String(c)})),{ok:!0,choice:n,host:"127.0.0.1",port:o,sessionId:s,token:a,capabilities:["abort","outcome-effect"]}}je();var _j="quickadd:ai-test-connection",kj={provider:{value:"<id|name>",description:"AI provider id (e.g. openai) or name"}};async function Sj(r,t){let e=String(t.provider??"").trim(),n=U.getState().ai.providers;if(!e)return{ok:!1,error:"Pass provider=<id|name>.",providers:n.map(a=>a.id??a.name)};let i=e.toLowerCase(),o=n.find(a=>a.id===e)??n.find(a=>a.name.trim().toLowerCase()===i);if(!o)return{ok:!1,error:`No AI provider matches "${e}".`,providers:n.map(a=>a.id??a.name)};let s=await tT(r.app,o);return{provider:o.id??o.name,...s}}Px();var nk="quickadd:save-clipboard-image",Aj={sourcePath:{value:"<vault-path>",description:"Note path the image will live in (capture destination). Empty keeps a vault-root attachment."},nameAfterNoteTitle:{value:"<true|false>",description:"Override the Name pasted images after the note title setting for this save"}},Voe=Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="),r=>r.charCodeAt(0));function Boe(r){if(r===void 0||r==="")return;let t=r.toLowerCase();if(t==="true"||t==="1"||t==="yes"||t==="on")return!0;if(t==="false"||t==="0"||t==="no"||t==="off")return!1;throw new Error(`Invalid nameAfterNoteTitle: ${r}. Use true or false.`)}async function Ij(r,t){try{let e=typeof t.sourcePath=="string"?t.sourcePath:"",n=Boe(typeof t.nameAfterNoteTitle=="string"?t.nameAfterNoteTitle:void 0),i=await Ax(r.app,Voe.buffer,"image/png",e,n===void 0?void 0:{nameAfterNoteTitle:n});return JSON.stringify({ok:!0,command:nk,path:i.path,name:i.name,sourcePath:e||"",nameAfterNoteTitle:n??r.settings.namePastedImagesAfterNoteTitle})}catch(e){return JSON.stringify({ok:!1,command:nk,error:e instanceof Error?e.message:String(e)})}}je();lt();Yi();var Fj="quickadd:package-import",Mj={path:{value:"<vault-path>",description:"Path to a .quickadd.json package file in the vault"},acknowledge:{description:"Required when the package runs code: confirms you reviewed its scripts (see quickadd:package-preview)"},choices:{value:"import|overwrite|duplicate|skip",description:"Mode for every choice (default: overwrite when the id already exists, otherwise import). import refuses a package with a choice already in the vault"},files:{value:"write|overwrite|skip",description:"Mode for every bundled file (default: overwrite when the destination exists, otherwise write)"}},Uoe=new Set(["import","overwrite","duplicate","skip"]),qoe=new Set(["write","overwrite","skip"]);function Pj(r,t,e){let n=typeof r=="string"?r.trim().toLowerCase():"";if(n){if(!t.has(n))throw new Error(`Invalid ${e}=${r}. Use one of: ${Array.from(t).join(", ")}.`);return n}}function zoe(r,t){let e=new Map(r.map(i=>[i.originalPath,zE(i,t)])),n=new Map;for(let i of e.values()){let o=i.toLowerCase();n.set(o,(n.get(o)??0)+1)}for(let[i,o]of e)(n.get(o.toLowerCase())??0)>1&&e.set(i,i);return e}var $j=Promise.resolve();function Rj(r,t){let e=$j.then(()=>Hoe(r,t));return $j=e.catch(()=>{}),e}async function Hoe(r,t){let e=typeof t.path=="string"?t.path.trim():"";if(!e)return{ok:!1,error:"Missing package path. Provide path=<vault-path>."};let n=Pj(t.choices,Uoe,"choices"),i=Pj(t.files,qoe,"files"),{app:o}=r,{pkg:s}=await LE(o,e),a=U.getState().choices,l=await NE(o,a,s),c=await mf(o,a,s);if(DE(c)&&!ca(t.acknowledge))return{ok:!1,error:"This package can run code. Review it with quickadd:package-preview, then pass acknowledge=true to import.",criticalScriptPaths:c.criticalScriptPaths,capabilities:c.capabilityRows.filter(v=>v.severity==="critical").map(v=>({flag:v.flag,title:v.title,detail:v.detail}))};let d=l.choiceConflicts.map(v=>({choiceId:v.choiceId,mode:sy(n??(v.exists?"overwrite":"import"),v.exists)})),u=zoe(l.assetConflicts,U.getState().templateFolderPaths),p=[];for(let v of l.assetConflicts){let b=u.get(v.originalPath)??v.originalPath,y=b===v.originalPath?v.exists:!Ut(b)&&await o.vault.adapter.exists(b);p.push({originalPath:v.originalPath,destinationPath:b,mode:qE(i??(y?"overwrite":"write"),y)})}let m=await VE({app:o,existingChoices:a,aiProviders:U.getState().ai.providers,pkg:s,choiceDecisions:d,assetDecisions:p});U.setState(v=>({...v,choices:m.updatedChoices})),WE(r,a,m),await r.saveSettings();let h=new Map(Zt(m.updatedChoices).map(v=>[v.id,v])),g=[...m.addedChoiceIds,...m.overwrittenChoiceIds].map(v=>h.get(v)).filter(v=>!!v).map(v=>({id:v.id,name:v.name,type:v.type}));return{ok:!0,added:m.addedChoiceIds,overwritten:m.overwrittenChoiceIds,skipped:m.skippedChoiceIds,writtenAssets:m.writtenAssets,skippedAssets:m.skippedAssets,choices:g}}var ms={runDefault:"quickadd",run:"quickadd:run",runTemplate:"quickadd:run-template",list:"quickadd:list",check:"quickadd:check",suggest:"quickadd:suggest",preview:"quickadd:package-preview",packageImport:Fj,interactive:"quickadd:interactive",saveClipboardImage:nk,aiTestConnection:_j};function Oj(r){let t=r;if(typeof t.registerCliHandler!="function")return S.logMessage("Skipping QuickAdd CLI handler registration: registerCliHandler is unavailable."),!1;let e=(n,i,o,s)=>t.registerCliHandler.call(t,n,i,o,async a=>{try{return JSON.stringify({command:n,...await s(a)})}catch(l){return JSON.stringify({ok:!1,command:n,error:l instanceof Error?l.message:String(l)})}});return e(ms.runDefault,"Run a QuickAdd choice (ok:true reports the choice ran without aborting; check verified to know QuickAdd confirmed the run, and effect to know whether the vault changed: created/changed/unchanged/unknown)",tk,n=>uR(r,n)),e(ms.run,"Run a QuickAdd choice (ok:true reports the choice ran without aborting; check verified to know QuickAdd confirmed the run, and effect to know whether the vault changed: created/changed/unchanged/unknown)",tk,n=>uR(r,n)),e(ms.runTemplate,"Create a new note from a template file (no Template choice required)",sR,n=>Ej(r,n)),e(ms.list,"List QuickAdd choices",lj,n=>gj(r,n)),e(ms.check,"Check missing inputs for a QuickAdd choice",aR,n=>vj(r,n)),e(ms.suggest,"List Obsidian's own [[ link or # tag suggestions for completion in another app",cj,n=>wj(bj(r.app),n)),e(ms.preview,"Preview a QuickAdd package before importing (files + capabilities)",dj,n=>yj(r,n)),e(ms.packageImport,"Import a QuickAdd package with the modal's default decisions (pass acknowledge=true after reviewing a package that runs code)",Mj,n=>Rj(r,n)),e(ms.interactive,"Run a choice interactively: forwards its runtime prompts to the caller over a local server (returns host/port/sessionId/token to attach)",lR,n=>Tj(r,n)),e(ms.aiTestConnection,"Check an AI provider's models endpoint with its linked API key (reports the model count or the provider's error; never the key)",kj,n=>Sj(r,n)),t.registerCliHandler.call(t,ms.saveClipboardImage,"Save a 1x1 PNG as a vault attachment using QuickAdd clipboard-image naming",Aj,n=>Ij(r,n)),S.logMessage("Registered QuickAdd CLI handlers."),!0}var da={run:"Run",runTemplateFromFolder:"New note from template",applyTemplate:"Apply template to active note",reloadDev:"Reload (dev)",openSettings:"Open settings",openAISettings:"Open AI Assistant settings",resumePrompt:"Return to prompt"};Ox();Rx();ss();ye();nt();AM();If();var Woe=new Set(["shortcuts:","obsidian:"]);function ik(r){return typeof r=="string"&&r.length>0?r:void 0}function Dj(r){let t=ik(r["x-success"]),e=ik(r["x-error"]),n=ik(r["x-cancel"]);if(t||e||n)return{success:t,error:e,cancel:n,any:!0};let i=ik(r["x-callback-url"]);return i?{success:i,cancel:i,any:!0}:{any:!1}}function Lj(r){return[r.success,r.error,r.cancel].filter(t=>typeof t=="string"&&t.length>0)}function pR(r){try{let t=new URL(r).protocol.toLowerCase();return Woe.has(t)}catch{return!1}}function Nj(r,t){let e=new URL(r);for(let[n,i]of Object.entries(t))e.searchParams.set(n,i);return e.toString()}function Vj(r,t){return"obsidian://open?vault="+encodeURIComponent(r)+"&file="+encodeURIComponent(t)}function Bj(r,t,e){r.registerObsidianProtocolHandler("quickadd",async c=>{let d=c,u=r.settings.enableUriCallbacks?Dj(d):{any:!1};if(!u.any){await n(d);return}let p=Lj(u).filter(v=>!pR(v));if(p.length>0){S.logWarning(`QuickAdd URI: ignoring disallowed callback URL(s): ${p.join(", ")}`),u.error&&pR(u.error)&&l(u.error,{status:"error",errorCode:"bad-callback-url"});return}if(!d.choice){S.logWarning("URI was executed without a `choice` parameter."),s(u,"choice-not-found");return}let m=t(d.choice);if(!m){S.logWarning(`URI could not find any choice named '${d.choice}'`),s(u,"choice-not-found");return}if(e(d.choice),m.type!=="Template"&&m.type!=="Capture"){S.logWarning(`QuickAdd URI x-callback supports Template and Capture choices only ('${m.name}' is ${m.type}). A URI with x-* callback params cannot run a ${m.type} choice while "Enable URI callbacks" is on; remove the x-* params to run it on the legacy path.`),s(u,"unsupported-choice-type");return}let h=new Ar(r.app,r);if(!i(h,d)){S.logWarning(`QuickAdd URI: could not parse date origin '${d.date}'.`),s(u,"execution-failed");return}let g=await h.executeWithOutcome(m);switch(g.status){case"success":o(u,g.file,g.effect);break;case"cancelled":g.cancelKind==="user"?a(u):s(u,"execution-aborted");break;case"error":s(u,"execution-failed");break}});async function n(c){if(!c.choice){S.logWarning("URI was executed without a `choice` parameter.");return}let d=t(c.choice);if(!d){Me(new Error(`URI could not find any choice named '${c.choice}'`),"URI handler error");return}e(c.choice);let u=new Ar(r.app,r);if(!i(u,c)){Me(new Error(`Could not parse date origin '${c.date}'`),"URI handler error");return}try{await u.execute(d)}catch(p){kd(p,`Could not run "${d.name}"`)}}function i(c,d){return Object.entries(d).filter(([u])=>u.startsWith("value-")).forEach(([u,p])=>{let m=u.slice(6);m&&typeof p=="string"&&!b_(m)&&c.variables.set(m,p)}),!!Af(c,d.date)}function o(c,d,u){let p={status:"success",effect:u};d&&(p.path=d.path,p.url=Vj(r.app.vault.getName(),d.path)),c.success&&l(c.success,p)}function s(c,d){c.error&&l(c.error,{status:"error",errorCode:d})}function a(c){c.cancel&&l(c.cancel,{status:"cancel"})}function l(c,d){JD(()=>{window.open(Nj(c,d))},"QuickAdd URI: failed to open callback URL")}}var Uj=require("obsidian");YT();Ox();function qj(r){r.addCommand({id:"runQuickAdd",name:da.run,callback:()=>{G_(r)}}),r.addCommand({id:"resumePrompt",name:da.resumePrompt,checkCallback:t=>al.isPeeking()?(t||al.getActive()?.resume(),!0):!1}),r.addCommand({id:"runTemplateFromFolder",name:da.runTemplateFromFolder,callback:()=>{W_(r.app,r,{choiceExecutor:new Ar(r.app,r)})}}),r.addCommand({id:"applyTemplateToActiveFile",name:da.applyTemplate,checkCallback:t=>{let e=r.app.workspace.getActiveFile(),n=e?.extension==="md";if(t)return n;n&&Ly(r.app,r,{file:e,choiceExecutor:new Ar(r.app,r)})}}),r.registerEvent(r.app.workspace.on("file-menu",(t,e)=>{e instanceof Uj.TFile&&e.extension==="md"&&t.addItem(n=>n.setTitle(`QuickAdd: ${da.applyTemplate}`).setIcon("file-plus").onClick(()=>{Ly(r.app,r,{file:e,choiceExecutor:new Ar(r.app,r)})}))})),r.addCommand({id:"reloadQuickAdd",name:da.reloadDev,checkCallback:t=>{if(t)return r.settings.devMode;let e=r.manifest.id,n=r.app.plugins;n.disablePlugin(e).then(()=>n.enablePlugin(e))}})}function zj(r,t,e=5e3){let n=!1,i;r.register(()=>{n=!0,window.clearTimeout(i)}),r.app.workspace.onLayoutReady(()=>{n||(i=window.setTimeout(t,e))})}function Hj(r){let t=()=>{let e=activeDocument.activeElement;e?.instanceOf(HTMLElement)&&e.closest(".quickAddModal")&&e.scrollIntoView({block:"nearest"})};window.addEventListener("keyboardDidShow",t),r.register(()=>window.removeEventListener("keyboardDidShow",t))}function Wj(r,t){r.registerEvent(r.app.workspace.on("quit",n=>{kC(r.app);let i=t();i&&n.addPromise(i.catch(()=>{}))}));let e=()=>{Z1(r.app),t()};r.registerDomEvent(document,"visibilitychange",()=>{document.visibilityState==="hidden"&&e()}),r.registerDomEvent(window,"blur",e)}var Goe=1e3,ok=class extends Gj.Plugin{constructor(){super(...arguments);this.lastPersistedSettings=null;this.suppressSettingsSave=!1;this.persistChain=null;this.pendingSave=null;this.requestSave=Object.assign(()=>{this.pendingSave??(this.pendingSave=window.setTimeout(()=>this.requestSave.run(),Goe))},{run:()=>{this.pendingSave!==null&&(this.requestSave.cancel(),(async()=>await this.persistSettings())())},cancel:()=>{this.pendingSave!==null&&window.clearTimeout(this.pendingSave),this.pendingSave=null}})}get api(){return Nf.GetApi(this.app,this,new Ar(this.app,this))}ingestImagesIntoActivePrompt(e){return JB(e)}async onload(){S.logMessage("Loading QuickAdd"),eB(this),await this.loadSettings(),U.replaceState(this.settings),this.unsubscribeSettingsStore=U.subscribe(s=>{this.settings=s,this.suppressSettingsSave||this.requestSave()}),qj(this),Wj(this,()=>this.flushPendingSave());let e=hl.getInstance();e.startAutomaticCleanup(s=>this.registerInterval(s)),e.registerInvalidationListeners(this.app,s=>this.registerEvent(s)),this.addCommand({id:"openQuickAddSettings",name:da.openSettings,callback:()=>{mc(this.app,this.manifest.id)}}),Bj(this,s=>this.getChoice("name",s),s=>this.warnIfChoiceNameAmbiguous(s)),S.register(new py).register(new dT(this)),Fz(this),Hj(this),this.settings.enableRibbonIcon&&this.addRibbonIcon("file-plus","QuickAdd",()=>{G_(this)});let n=new cT(this.app,this);this.addSettingTab(n),this.addCommand({id:"openAIAssistantSettings",name:da.openAISettings,callback:()=>n.openAIAssistantPageFromCommand()}),this.addCommandsForChoices(this.settings.choices);try{await KG(this)}catch(s){Me(s,"QuickAdd could not run its settings migrations")}let i=()=>{try{Oj(this)}catch(s){Me(s,"QuickAdd could not register its CLI handlers")}};this.app.workspace.layoutReady?i():this.app.workspace.onLayoutReady(i);let o=async()=>{try{await new M_(this.app,this,this.settings.choices,new Ar(this.app,this)).run()}catch(s){Me(s,"QuickAdd could not run its startup macros")}};this.app.workspace.layoutReady?o():this.app.workspace.onLayoutReady(o),zj(this,()=>{yz(this.app)}),this.announceUpdate()}onunload(){S.logMessage("Unloading QuickAdd"),kC(this.app),this.flushPendingSave(),this.unsubscribeSettingsStore?.call(this),$h.loggers.forEach(n=>{n instanceof py&&n.clearErrorLog()}),hl.getInstance().destroy(),El.stop(),al.getActive()?.cancel()}normalizeLoadedSettings(e){let n=Object.assign({},tw,e??{});return typeof n.announceUpdates=="boolean"&&(n.announceUpdates=n.announceUpdates?"all":"none"),Array.isArray(n.choices)&&(n.choices=i0(n.choices)),f$(n,uw),n}async loadSettings(){let e=await this.loadData(),n=this.normalizeLoadedSettings(e);this.settings=n,this.lastPersistedSettings=ke(n)}flushPendingSave(){return this.requestSave.run(),this.persistChain}queuePersistRun(e){let n=(this.persistChain??Promise.resolve()).then(e,e).finally(()=>{this.persistChain===n&&(this.persistChain=null)});return this.persistChain=n,n}async saveSettings(){this.requestSave.cancel(),await this.persistSettings()}persistSettings(){let e=async()=>{let n=this.lastPersistedSettings,i=async()=>n?this.normalizeLoadedSettings(await this.loadData()):null,o=await i(),s=u=>{let p=ke(this.settings);return tq({base:n,disk:u,local:p,currentStore:this.settings})},a=u=>{u.shouldReplaceStore&&_r(this.settings,u.local)&&this.publishSettingsFromDisk(u.toWrite)},l=s(o);if(l.didMerge&&S.logMessage("[Settings] data.json changed on disk since the last QuickAdd write; merged in-memory changes with on-disk settings before saving."),a(l),n){let u=await i();u&&(!o||!_r(u,o))&&(S.logMessage("[Settings] data.json changed again before save; re-merging with the fresher on-disk snapshot."),o=u,l=s(o),a(l))}let c=ke(this.settings),d=l.toWrite;_r(c,l.local)||(d=ul(l.local,c,l.toWrite)),rq(d,this.settings,c)&&this.publishSettingsFromDisk(d),await this.saveData(d),this.lastPersistedSettings=ke(d)};return this.queuePersistRun(e)}async onExternalSettingsChange(){let e=async()=>{let n;try{n=await this.loadData()}catch(a){S.logWarning(`QuickAdd could not read its changed settings: ${String(a)}`);return}if(!n)return;let i=this.lastPersistedSettings,o=this.normalizeLoadedSettings(n);if(i&&_r(o,i))return;let s=i?ul(i,ke(this.settings),o):o;this.lastPersistedSettings=ke(o),_r(s,this.settings)||this.publishSettingsFromDisk(s),_r(s,o)?this.requestSave.cancel():this.requestSave(),S.logMessage("[Settings] Applied settings that changed outside this Obsidian instance.")};await this.queuePersistRun(e)}publishSettingsFromDisk(e){let n=this.settings.choices;this.suppressSettingsSave=!0;try{U.replaceState(e),this.settings=e}finally{this.suppressSettingsSave=!1}if(!_r(n,e.choices)){for(let i of mr(n))Ee(i)&&this.removeCommandForChoice(i,{recursive:!0});this.addCommandsForChoices(e.choices)}}addCommandsForChoices(e){for(let n of mr(e))if(Ee(n))try{this.addCommandForChoice(n)}catch(i){Me(i,"Could not add a command for a QuickAdd choice")}}addCommandForChoice(e){if(e.type==="Multi"&&this.addCommandsForChoices(Ne(e)),e.command){let n=e.id;this.addCommand({id:bC(n),name:e.name,icon:Sd(e),callback:()=>this.runRegisteredChoice(n,e.name)}),D1({origin:e.dateOrigin,enabled:e.pickDayCommand})&&this.addCommand({id:QA(n),name:XA(e.name),icon:Sd(e),callback:()=>this.runRegisteredChoice(n,e.name,!0)})}}async runRegisteredChoice(e,n,i=!1){let o;try{o=this.getChoiceById(e);let s=new Ar(this.app,this);s.pickDate=i,await s.execute(o)}catch(s){kd(s,`Could not run "${o?.name??n}"`)}}getChoiceById(e){let n=this.getChoice("id",e);if(!n)throw new Error(`Choice ${e} not found`);return n}getChoiceByName(e){let n=this.getChoice("name",e);if(!n)throw new Error(`Choice ${e} not found`);return n}getChoice(e,n,i=this.settings.choices){for(let o of mr(i))if(Ee(o)){if(o[e]===n)return o;if(o.type==="Multi"){let s=this.getChoice(e,n,Ne(o));if(s)return s}}return null}countChoicesByName(e,n=this.settings.choices){let i=0;for(let o of mr(n))Ee(o)&&(o.name===e&&i++,o.type==="Multi"&&(i+=this.countChoicesByName(e,Ne(o))));return i}warnIfChoiceNameAmbiguous(e){let n=this.countChoicesByName(e);n>1&&S.logWarning(`QuickAdd URI: ${n} choices are named '${e}'. Ran the first match \u2014 rename choices to keep names unique so URIs target the right one.`)}removeCommandForChoice(e,n){if(n?.recursive&&e.type==="Multi")for(let i of Ne(e))Ee(i)&&this.removeCommandForChoice(i,n);this.removeCommand(bC(e.id)),this.removeCommand(QA(e.id))}getTemplateFiles(){let e=ti(this.settings.templateFolderPaths);return this.app.vault.getFiles().filter(n=>Ps(n.path)).filter(n=>KD(n.path,e))}announceUpdate(){let e=(l,c)=>{let d=Wf(l),u=Wf(c);return!d||!u?!0:d.major!==u.major?d.major>u.major:d.minor>u.minor},n=this.manifest.version,i=this.settings.version;if(n===i)return;let o=this.settings.announceUpdates,s=!0;if((o==="none"||o==="major"&&!e(n,i))&&(s=!1),this.settings.version=n,this.saveSettings(),!s)return;new Q_(this.app,i).open()}};
|
||
|
||
/* nosourcemap */ |