Files
my-vault/.obsidian/plugins/quickadd/main.js
T
windyboy ee6e7518fa refactor(vault): Phase 4 — 06_Metadata slimming 42 → 8
Keep (8 files, all wired to .obsidian):
- Templates: Daily Note Template, Project Template, book-note, quick-note
- Reference: PARA_METHOD, GIT_WORKFLOW, TROUBLESHOOTING
- SECURITY_ROTATION_LOG_2026-02

Delete (27 files): upstream claudesidian remnants (CHANGELOG, CONTRIBUTING,
CLAUDE-BOOTSTRAP, etc.), 4 workflow docs, review reports, improvement plans,
Hermes templates, duplicate/unwired templates

Archive to 04_Archive/Metadata-Docs (8 files): review reports, plugin manuals,
DAILY_NOTE_GUIDE, Common Claude Code Prompts
2026-09-26 11:38:51 +08:00

423 lines
1.2 MiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var D4=Object.create;var zh=Object.defineProperty;var F4=Object.getOwnPropertyDescriptor;var P4=Object.getOwnPropertyNames;var M4=Object.getPrototypeOf,$4=Object.prototype.hasOwnProperty;var U$=r=>{throw TypeError(r)};var O4=(r,e,t)=>e in r?zh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var E=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var R4=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},fw=(r,e)=>{for(var t in e)zh(r,t,{get:e[t],enumerable:!0})},H$=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of P4(e))!$4.call(r,i)&&i!==t&&zh(r,i,{get:()=>e[i],enumerable:!(n=F4(e,i))||n.enumerable});return r};var z$=(r,e,t)=>(t=r!=null?D4(M4(r)):{},H$(e||!r||!r.__esModule?zh(t,"default",{value:r,enumerable:!0}):t,r)),N4=r=>H$(zh({},"__esModule",{value:!0}),r);var he=(r,e,t)=>O4(r,typeof e!="symbol"?e+"":e,t),m_=(r,e,t)=>e.has(r)||U$("Cannot "+t);var V=(r,e,t)=>(m_(r,e,"read from private field"),t?t.call(r):e.get(r)),rt=(r,e,t)=>e.has(r)?U$("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Ge=(r,e,t,n)=>(m_(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t),lt=(r,e,t)=>(m_(r,e,"access private method"),t);var $R,OR,RR=E(()=>{$R=r=>{let e,t=new Set,n=(c,u)=>{let d=typeof c=="function"?c(e):c;if(!Object.is(d,e)){let p=e;e=u??(typeof d!="object"||d===null)?d:Object.assign({},e,d),t.forEach(f=>f(e,p))}},i=()=>e,a={setState:n,getState:i,getInitialState:()=>l,subscribe:c=>(t.add(c),()=>t.delete(c))},l=e=r(n,i,a);return a},OR=(r=>r?$R(r):$R)});function Eg(r){if(r.kind)return r.kind;let e=(r.name??"").toLowerCase(),t=s8(r.endpoint),n=i=>t===i||t.endsWith(`.${i}`);return e==="anthropic"||n("api.anthropic.com")?"anthropic":e==="gemini"||n("generativelanguage.googleapis.com")?"gemini":"openai"}function s8(r){let e=(r??"").trim();if(!e)return"";for(let t of[e,`https://${e}`])try{return new URL(t).hostname.toLowerCase()}catch{}return""}function a8(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function nC(r,e){let t=a8(r),n=new Set(e.map(o=>o.id).filter(o=>!!o)),i=t;for(let o=2;n.has(i);o++)i=`${t}-${o}`;return i}function iC(r){let e=!1,t=new Set;for(let n of r){if(n.id&&!t.has(n.id)){t.add(n.id);continue}n.id=nC(n.id??n.name,r),t.add(n.id),e=!0}return e}function pc(r,e){return e&&e.name===r?e:void 0}function oC(r){return Tg[r].map(e=>({...e}))}var Tg,NR,l8,c8,sC,ro=E(()=>{Tg={openai:[{name:"gpt-5.5",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.4",maxTokens:105e4,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.4-mini",maxTokens:4e5,maxOutputTokens:128e3,supportsTemperature:!1},{name:"gpt-5.4-nano",maxTokens:4e5,maxOutputTokens:128e3,supportsTemperature:!1},{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.5-flash",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-pro-preview",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-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}]},NR={openai:["gpt-4-32k","gpt-4-1106-preview"],google:["gemini-1.5-pro","gemini-1.5-flash","gemini-1.5-flash-8b"]};l8={id:"openai",name:"OpenAI",endpoint:"https://api.openai.com/v1",kind:"openai",apiKey:"",models:oC("openai"),autoSyncModels:!0,modelSource:"modelsDev"},c8={id:"gemini",name:"Gemini",endpoint:"https://generativelanguage.googleapis.com",kind:"gemini",apiKey:"",models:oC("google"),autoSyncModels:!0,modelSource:"modelsDev"},sC=[l8,c8]});function LR(r,e){return Object.prototype.hasOwnProperty.call(r,e)?r[e]:void 0}function kg(r,e=Kp){let t=r.trim();if(!t)return r;let n=LR(e,t.toLowerCase());if(n)return n;let[i,...o]=t.split(/\s+/),s=LR(e,i.toLowerCase());return s?[s,...o].join(" "):r}function VR(r){let e={},t=r.split(/\r?\n/);for(let n of t){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(e,s,{value:a,enumerable:!0,writable:!0,configurable:!0})}return e}function bA(r){return Object.entries(r).filter(([e,t])=>e&&t).map(([e,t])=>`${e} = ${t}`).join(`
`)}function Sg(r){let e=Object.entries(r);if(e.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=e.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 aC(r){return Sg(r).map(([e,t])=>`${e}=${t}`).join(", ")}var Kp,td=E(()=>{Kp={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 lC,wA=E(()=>{ro();td();lC={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:Kp,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:sC,confirmToolCalls:"destructive"},migrations:{migrateToMacroIDFromEmbeddedMacro:!0,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 Ve(r){if(typeof structuredClone=="function")try{return structuredClone(r)}catch{}return fc(r,new Map)}function fc(r,e){if(r===null||typeof r!="object")return r;if(e.has(r))return e.get(r);if(r instanceof Date){let i=new Date(r.getTime());return e.set(r,i),i}if(Array.isArray(r)){let i=[];e.set(r,i);for(let o of r)i.push(fc(o,e));return i}if(r instanceof Map){let i=new Map;e.set(r,i);for(let[o,s]of r.entries())i.set(fc(o,e),fc(s,e));return i}if(r instanceof Set){let i=new Set;e.set(r,i);for(let o of r.values())i.add(fc(o,e));return i}if(r instanceof RegExp){let i=new RegExp(r.source,r.flags);return i.lastIndex=r.lastIndex,e.set(r,i),i}if(r instanceof ArrayBuffer){let i=r.slice(0);return e.set(r,i),i}if(ArrayBuffer.isView(r)){if(r instanceof DataView){let a=new DataView(fc(r.buffer,e),r.byteOffset,r.byteLength);return e.set(r,a),a}let i=r,o=fc(i.buffer,e),s=new i.constructor(o,i.byteOffset,i.length);return e.set(r,s),s}let t=Object.getPrototypeOf(r),n=Object.create(t);e.set(r,n);for(let[i,o]of Object.entries(r))Object.defineProperty(n,i,{value:fc(o,e),writable:!0,enumerable:!0,configurable:!0});return n}var Jr=E(()=>{});var X,dt=E(()=>{RR();wA();Jr();X=(()=>{let r=OR((i,o)=>({...Ve(lC)})),{getState:e,setState:t,subscribe:n}=r;return{getState:e,replaceState:i=>t(i,!0),setState:t,subscribe:n}})()});var rd,_g,I,Ie=E(()=>{rd=class rd{register(e){return rd.loggers.push(e),this}logError(e){let t=e instanceof Error?e.message:e,n=e instanceof Error?e.stack:void 0,i=e instanceof Error?e:void 0;rd.loggers.forEach(o=>o.logError(t,n,i))}logWarning(e){let t=e instanceof Error?e.message:e,n=e instanceof Error?e.stack:void 0,i=e instanceof Error?e:void 0;rd.loggers.forEach(o=>o.logWarning(t,n,i))}logMessage(e){let t=e instanceof Error?e.message:e,n=e instanceof Error?e.stack:void 0,i=e instanceof Error?e:void 0;rd.loggers.forEach(o=>o.logMessage(t,n,i))}};rd.loggers=[];_g=rd,I=new _g});var Or,BR,qR,no,nd,id,vs,UR,CA,HR,xA,el,od,Dke,sd,cC,uC,mc,EA,TA,Fke,Pke,Mke,Nt,cr,wn,kA,hc,Oo,dC,tl,pC,Ro,Ag,SA,_A,AA,zR,WR,jR,GR,YR,KR,QR,XR,ZR,JR,eN,IA,tN,rN,nN,iN,oN,sN,aN,lN,cN,uN,dN,pN,fN,mN,hN,fC,Ig,rl,gN,Xe=E(()=>{Or="{{value}}",BR="{{name}}",qR=new RegExp(/^-?[0-9]*$/),no="top",nd="bottom",id="cursor",vs="ordered",UR=new RegExp(/{{DATE(\+-?[0-9]+)?(?:\|((?:startof|endof):[a-z]+))?(?:\|case:([a-z-]+))?}}/i),CA=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),HR=new RegExp(/{{TIME(?:\|case:([a-z-]+))?}}/i),xA=new RegExp(/{{TIME:((?:\[[^\]\n\r]*\]|\[(?![^\]\n\r]*\])|[^}\n\r+|[]|\|(?!(?:case):[a-z-]+}}))*)(?:\|case:([a-z-]+))?}}/i),el=new RegExp(/{{(?:NAME|VALUE)(?!:)(?:\|[^\n\r}]*)?}}/i),od=new RegExp(/{{VALUE:([^\n\r}]*)}}/i),Dke=new RegExp(/{{FIELD:([^\n\r}]*)}}/i),sd="FIELD:",cC=new RegExp(/{{FIELD:([^\n\r}|{]*)(\|[^\n\r}{]*)?}}/i),uC=new RegExp(/{{FILE:([^\n\r{}]*)}}/i),mc=new RegExp(/{{VDATE:([^\n\r},|{]*)(?:,([^\n\r}|{]*))?(?:\|([^\n\r}{]*))?}}/i),EA=new RegExp(/{{LINKCURRENT}}/i),TA=new RegExp(/{{LINKSECTION}}/i),Fke=new RegExp(/{{FILENAMECURRENT}}/i),Pke=new RegExp(/{{FOLDERCURRENT(\|name)?}}/i),Mke=new RegExp(/{{FOLDER(\|name)?}}/i),Nt=new RegExp(/\.md$/i),cr=new RegExp(/\.canvas$/i),wn=new RegExp(/\.base$/i),kA=new RegExp(/\.js$/),hc=new RegExp(/{{MACRO:([^\n\r}]*)}}/i),Oo=new RegExp(/{{TEMPLATE:([^\n\r}]*\.(?:md|canvas|base))}}/i),dC=new RegExp(/{{GLOBAL_VAR:([^\n\r}]*)}}/i),tl=new RegExp(/`{3,}js quickadd([\s\S]*?)`{3,}/),pC=new RegExp(/{{MVALUE}}/i),Ro=new RegExp(/{{TITLE}}/i),Ag=new RegExp(/{{PROPERTY}}/i),SA=new RegExp(/{{SELECTED}}/i),_A=new RegExp(/{{CLIPBOARD}}/i),AA=new RegExp(/{{RANDOM:(\d+)}}/i),zR=new RegExp(/\[\[([^\]]*)$/),WR=new RegExp(/#([^ ]*)$/),jR=new RegExp(/{{[D]?[A]?[T]?[E]?[}]?[}]?$/i),GR=new RegExp(/{{[D]?[A]?[T]?[E]?[:]?$|{{DATE:[^\n\r}]*}}$/i),YR=new RegExp(/{{[N]?[A]?[M]?[E]?[}]?[}]?$/i),KR=new RegExp(/{{[V]?[A]?[L]?[U]?[E]?[}]?[}]?$/i),QR=new RegExp(/{{[V]?[A]?[L]?[U]?[E]?[:]?$|{{VALUE:[^\n\r}]*}}$/i),XR=new RegExp(/{{[V]?[D]?[A]?[T]?[E]?[:]?$|{{VDATE:[^\n\r}]*}}$/i),ZR=new RegExp(/{{[L]?[I]?[N]?[K]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),JR=new RegExp(/^\{\{(?:l(?:i(?:n(?:k(?:s(?:e(?:c(?:t(?:i(?:o(?:n(?:\}\}?)?)?)?)?)?)?)?)?)?)?)?)?$/i),eN=new RegExp(/{{[F]?[I]?[L]?[E]?[N]?[A]?[M]?[E]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),IA=new RegExp(/{{[F]?[O]?[L]?[D]?[E]?[R]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i),tN=new RegExp(/{{[F]?[O]?[L]?[D]?[E]?[R]?[}]?[}]?$/i),rN=new RegExp(/{{[F]?[I]?[L]?[E]?[:]?$/i),nN=new RegExp(/{{[F]?[I]?[E]?[L]?[D]?[:]?$/i),iN=new RegExp(/{{[T]?[E]?[M]?[P]?[L]?[A]?[T]?[E]?[:]?$|{{TEMPLATE:[^\n\r}]*[}]?[}]?$/i),oN=new RegExp(/{{[M]?[A]?[C]?[R]?[O]?[:]?$|{{MACRO:[^\n\r}]*}}$/i),sN=new RegExp(/{{[M]?[V]?[A]?[L]?[U]?[E]?[}]?[}]?/i),aN=new RegExp(/{{[T]?[I]?[T]?[L]?[E]?[}]?[}]?/i),lN=new RegExp(/{{[P]?[R]?[O]?[P]?[E]?[R]?[T]?[Y]?[}]?[}]?$/i),cN=/{{(?:C(?:U(?:R(?:S(?:O(?:R)?)?)?)?)?)?[}]?[}]?$/i,uN=new RegExp(/{{[S]?[E]?[L]?[E]?[C]?[T]?[E]?[D]?[}]?[}]?/i),dN=new RegExp(/{{[C]?[L]?[I]?[P]?[B]?[O]?[A]?[R]?[D]?[}]?[}]?$/i),pN=new RegExp(/{{[R]?[A]?[N]?[D]?[O]?[M]?[:]?$|{{RANDOM:[^\n\r}]*}}$/i),fN=new RegExp(/{{[G]?[L]?[O]?[B]?[A]?[L]?[_]?[V]?[A]?[R]?[:]?$|{{GLOBAL_VAR:[^\n\r}]*}}$/i),mN=new RegExp(/{{[T]?[I]?[M]?[E]?[}]?[}]?/i),hN=new RegExp(/{{[T]?[I]?[M]?[E]?[:]?$|{{TIME:[^\n\r}]*}}$/i),fC="__qa.",Ig=`${fC}captureTargetFilePath`,rl=`${fC}dateOrigin`,gN=new RegExp(/\[\[([^\]]*)\]\]/)});var mC=E(()=>{});var yt,Ni=E(()=>{yt=class extends Error{constructor(e){super(e||"Macro execution aborted"),this.name="MacroAbortError"}}});function Rr(){return new at(vc)}var at,vc,ur=E(()=>{Ni();at=class extends yt{},vc="Input cancelled by user"});function nl(r,e){if(r instanceof Error){if(!e)return r;let n=new Error(`${e}: ${r.message}`);return n.name=r.name,n.stack=r.stack,n}let t=e?`${e}: ${String(r)}`:String(r);return new Error(t)}function ot(r){return r instanceof at?!0:typeof r=="string"&&p8.has(r)}function xN(r){return typeof r=="object"&&r!==null||typeof r=="function"}function h8(r,e){let t=r;for(let n=0;n<m8&&xN(t);n++){let i=CN.get(t);if(i!==void 0&&e-i<f8)return!0;t=t.cause}return!1}function Ze(r,e,t="ERROR"){let n=Date.now();if(h8(r,n))return!1;xN(r)&&CN.set(r,n);let i=nl(r,e);switch(t){case"ERROR":I.logError(i);break;case"WARNING":I.logWarning(i);break;case"LOG":I.logMessage(i);break;default:I.logError(i)}return!0}function ad(r,e,t="ERROR"){return ot(r)?!1:Ze(r,e,t)}function EN(r,e,t="ERROR"){try{return r()}catch(n){Ze(n,e,t);return}}function ld(r,e){let t=n=>{ad(n,r)};return(...n)=>{try{let i=e(...n);typeof i?.then=="function"&&Promise.resolve(i).catch(t)}catch(i){t(i)}}}var PA,p8,CN,f8,m8,xt=E(()=>{Ie();mC();ur();PA=100;p8=new Set(["no input given.","No input given.","cancelled"]),CN=new WeakMap,f8=1e4,m8=8});function gC(r,e){try{let t=r.workspace.getActiveViewOfType(SN.MarkdownView);if(!t||t.file?.path!==e.path)return{cursor:null,value:null};let n=t.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 v8(r,e){return r!==null&&e!==null&&(r.line!==e.line||r.ch!==e.ch)}function TN(r){return typeof r!="string"?null:[...r.matchAll(g8)].length}function _N(r,e){let t=TN(r),n=TN(e);return t!==null&&n!==null&&t>n}function kN(r,e){return v8(r.cursor,e.cursor)||_N(r.value,e.value)}async function vC(r,e,t=500){try{let n=r.vault.adapter;if(!("stat"in n)||typeof n.stat!="function")return;let i=await n.stat(e.path);if(!i)return;let o=i.mtime,s=Date.now(),a=30;for(;Date.now()-s<t;){await Pg(a);let l=await n.stat(e.path);if(!l||l.mtime===o)return;o=l.mtime,a=Math.min(a*2,200)}}catch(n){I.logWarning(`waitForFileSettle: fallback due to adapter/stat failure \u2013 ${n.message}`)}}function yC(r){return r.plugins.plugins["templater-obsidian"]}function cd(r){let e=yC(r);return e||null}function Xp(r){let e=cd(r);if(!e)return!1;let t=e.settings?.trigger_on_file_creation;if(typeof t=="boolean")return t;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 Pg(r){return new Promise(e=>window.setTimeout(e,r))}async function bC(r,e,t={}){if(e.extension!=="md"||!Xp(r))return;let i=cd(r)?.templater?.files_with_pending_templates;if(!(i instanceof Set)){await AN(r,e,{timeoutMs:t.timeoutMs??5e3,gracePeriodMs:t.appearTimeoutMs??2500,quietPeriodMs:200});return}let{timeoutMs:o=5e3,appearTimeoutMs:s=2500}=t,a=Date.now();for(;Date.now()-a<s&&!i.has(e.path);)await Pg(50);for(;Date.now()-a<o&&i.has(e.path);)await Pg(50);await vC(r,e,800)}async function b8(r,e,t){if(!($A>0)&&t.size===0){if(Fg){await Fg;return}Fg=(async()=>{try{r.workspace.trigger("templater:all-templates-executed"),await e.templater?.functions_generator?.teardown?.()}catch(n){I.logWarning(`withTemplaterFileCreationSuppressed: teardown failed \u2013 ${n.message}`)}})();try{await Fg}finally{Fg=null}}}async function OA(r,e,t){let n=cd(r),i=n?.templater?.files_with_pending_templates;if(!n||!Xp(r)||!(i instanceof Set))return await t();$A++;let o=MA.get(e);o||(o={count:0,hadPathInitially:i.has(e)},MA.set(e,o),o.hadPathInitially||i.add(e)),o.count++;let s=!1;try{let a=await t();return s=!0,a}finally{o.count--,$A--,o.count<=0&&(MA.delete(e),o.hadPathInitially||(s&&await Pg(y8),i.delete(e),await b8(r,n,i)))}}async function AN(r,e,t={}){let{timeoutMs:n=2e3,quietPeriodMs:i=150,gracePeriodMs:o=800}=t;try{let s=r.vault.adapter;if(!("stat"in s)||typeof s.stat!="function")return;let a=await s.stat(e.path);if(!a)return;let l=a.mtime,c=Date.now(),u=!1,d=c,p=50;for(;Date.now()-d<n;){await Pg(p);let f=await s.stat(e.path);if(!f)return;let m=Date.now();if(f.mtime!==l){u=!0,l=f.mtime,c=m,p=50;continue}if(u){if(m-c>=i)return}else if(m-d>=o)return;p=Math.min(Math.floor(p*1.5),200)}}catch(s){I.logWarning(`waitForFileToStopChanging: fallback due to adapter/stat failure \u2013 ${s.message}`)}}async function w8(r,e){let t=hC.get(r)??Promise.resolve(),n,i=new Promise(s=>{n=()=>s()}),o=t.catch(()=>{}).then(()=>i);hC.set(r,o),o.finally(()=>{hC.get(r)===o&&hC.delete(r)}).catch(()=>{}),await t.catch(()=>{});try{return await e()}finally{n()}}async function yc(r,e,t={}){if(e.extension!=="md")return!1;let n=cd(r),i=n?.templater,o=i?.overwrite_file_commands;if(!n||!i||typeof o!="function")return!1;let{skipIfNoTags:s=!0,postWait:a=!0}=t;return await w8(e.path,async()=>{await vC(r,e);let l;try{l=await r.vault.read(e)}catch(d){return Ze(d,`overwriteTemplaterOnce: failed to read ${e.path} before render`),!1}if(s&&!l.includes("<%"))return!1;let c=null,u=r.workspace.on("templater:overwrite-file",d=>{d.file.path===e.path&&(c=d.content)});try{await o.call(i,e);let d=_N(c,gC(r,e).value);return a&&await vC(r,e,800),d}catch(d){try{await r.vault.modify(e,l)}catch(p){I.logWarning(`Failed to rollback ${e.path} after Templater error: ${p.message}`)}return Ze(d,`Templater failed on ${e.path}. Rolled back to pre-render state.`),!1}finally{r.workspace.offref(u)}})}async function il(r,e,t){if(t.extension!=="md")return e;let n=cd(r),i=n?.templater,o=i?.parse_template;if(!n||!i||typeof o!="function")return e;let s=i.create_running_config,a=typeof s=="function"?s.call(i,void 0,t,4):{target_file:t,run_mode:4,frontmatter:{}};return await o.call(i,a,e)}async function ol(r,e){if(e.extension!=="md"||r.workspace.getActiveFile()?.path!==e.path)return!1;let t=cd(r),n=!!t?.settings?.auto_jump_to_cursor,i=t?.editor_handler,o=i?.jump_to_next_cursor_location;if(!n)return!1;let s=gC(r,e);if(typeof o=="function")try{return await o.call(i,e,!0),kN(s,gC(r,e))}catch(a){I.logWarning(`jumpToNextTemplaterCursorIfPossible: API failed \u2013 ${a.message}`)}try{return!r.commands.executeCommandById?.("templater-obsidian:jump-to-next-cursor-location")?!1:kN(s,gC(r,e))}catch{}return!1}var SN,g8,MA,$A,Fg,y8,hC,IN=E(()=>{SN=require("obsidian");Ie();xt();g8=/<%\s*tp\.file\.cursor\((?:-?[0-9]+(?:\.[0-9]+)?)?\)\s*%>/g;MA=new Map,$A=0,Fg=null,y8=350;hC=new Map});function xn(r){let e=r.workspace.getActiveViewOfType(DN.MarkdownView);return e?.editor?e:null}function sl(r){return xn(r)?.editor.getSelection()??""}var DN,ys=E(()=>{DN=require("obsidian")});function Zp(r){return C8.has(r)}function al(r){return r==="inFrontmatter"}function wC(r){return x8.has(r)}function E8(r,e,t){return r==="embed"&&t.type==="activeFile"&&Zp(e)?"embed":"link"}function T8(r,e,t,n){return r==="selection"&&t.type==="activeFile"&&wC(e)&&n==="link"?"selection":"none"}function k8(r){return r?.type==="specifiedFile"?{type:"specifiedFile",path:typeof r.path=="string"?r.path.trim():""}:{type:"activeFile"}}function S8(r){return typeof r=="object"&&r!==null&&"enabled"in r&&"placement"in r}function bc(r){if(S8(r)){let e=r.placement??"replaceSelection",t=k8(r.destination),n=E8(r.linkType,e,t);return{enabled:r.enabled,placement:e,requireActiveFile:r.requireActiveFile??!0,linkType:n,displayText:T8(r.displayText,e,t,n),destination:t,frontmatterProperty:r.frontmatterProperty,frontmatterHandling:al(e)?r.frontmatterHandling??ud:r.frontmatterHandling}}return{enabled:r,placement:"replaceSelection",requireActiveFile:!!r,linkType:"link",displayText:"none",destination:{type:"activeFile"}}}var ud,C8,x8,wc=E(()=>{ud="alwaysAppend",C8=new Set(["replaceSelection","afterSelection","endOfLine","newLine"]);x8=new Set(["replaceSelection","afterSelection"])});function _8(r){return r.vault.getConfig?.("useMarkdownLinks")===!0}function A8(r,e){let t=e.replace(/\s+/g,n=>/[\r\n]/.test(n)?" ":n).trim();if(t){if(_8(r))return t.replace(/\\/g,"\\\\").replace(/\[/g,"\\[").replace(/\]/g,"\\]");if(!(t.includes("]]")||t.includes("[[")||t.endsWith("]")))return t}}function I8(r){return`[[${r.path.replace(/\.md$/i,"")}]]`}function CC(r,e,t={}){let n=t.sourcePath??"";if(t.linkType==="embed"&&(!t.placement||Zp(t.placement)))return`![[${r.metadataCache.fileToLinktext(e,n)}]]`;let o=t.alias===void 0?void 0:A8(r,t.alias);return o===void 0?r.fileManager.generateMarkdownLink(e,n):r.fileManager.generateMarkdownLink(e,n,void 0,o)}function RA(r){let e=r.trim().replace(/^\/+/,"");return e?/\.md$/i.test(e)?e:`${e}.md`:""}function $g(r,e){if(e.type!=="specifiedFile")return null;let t=RA(e.path);if(!t)return null;let n=r.vault.getAbstractFileByPath(t);return!(n instanceof Mg.TFile)||n.extension!=="md"?null:n}function D8(r,e){return r.length===0?e:r.endsWith(`
`)?`${r}${e}`:`${r}
${e}`}async function PN(r,e,t,n){let i=t.destination;if(i?.type!=="specifiedFile")return!1;let o=$g(r,i);if(!o)throw new Error(`Append link target file not found or is not a Markdown file: ${i.path}`);let s=CC(r,e,{sourcePath:o.path,linkType:"link"}),a;return await r.vault.process(o,l=>{let c=D8(l,s);return a={filePath:o.path,before:l,after:c,edits:[{from:l.length,to:l.length,text:c.slice(l.length)}]},c}),a&&n?.(a),!0}async function F8(r){let e=window.navigator?.clipboard;if(!e?.writeText)return I.logMessage("QuickAdd: Clipboard API is unavailable."),!1;try{return await e.writeText(r),!0}catch(t){return I.logMessage(`QuickAdd: Could not copy link to clipboard: ${t instanceof Error?t.message:String(t)}`),!1}}async function MN(r){let e=I8(r);return await F8(e)?(new Mg.Notice(`Copied link to '${r.basename}' to clipboard.`,FN),!0):(new Mg.Notice(`Created '${r.basename}', but QuickAdd could not copy its link to the clipboard.`,FN),!1)}var Mg,FN,Og=E(()=>{Mg=require("obsidian");Ie();wc();FN=4e3});function io(r){if(r.nodeType===Node.DOCUMENT_NODE)return r;let e=r.ownerDocument;if(!e)throw new Error("Unable to resolve owner document for DOM node.");return e}function Rg(r){let e=io(r).defaultView;if(!e)throw new Error("Unable to resolve owner window for DOM node.");return e}function er(r,e){return io(r).win.createEl(e)}function Ng(r,e){return io(r).createTextNode(e)}var bs=E(()=>{});function xC(r){for(let e of r.workspace.getLeavesOfType("markdown")){let t=e.view;if(!(!t.containerEl||!t.file||t.file.extension!=="md"))try{let n=io(t.containerEl).activeElement;if(!n||!t.containerEl.contains(n)||!n.closest(".metadata-property-value")||n.matches(P8))continue;let o=n.closest(".metadata-property")?.getAttribute("data-property-key");if(!o)continue;return{file:t.file,key:o}}catch{continue}}return null}function M8(r,e,t){let n=NN(r,e),i=r[n];if(Array.isArray(i)){i.push(t);return}if(i==null||i===""){r[n]=t;return}if(typeof i=="string"){r[n]=`${i} ${t}`;return}throw new Error(`Cannot append link to frontmatter property '${n}' because it contains a ${typeof i} value.`)}function RN(r,e,t,n=ud){let i=NN(r,e),o=r[i];if(Array.isArray(o)){o.push(t);return}if(o===null||o===""){r[i]=[t];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]=[t];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 '${$N[n]}'. Choose '${$N.alwaysAppend}' to convert it into a list and append.`);r[i]=[o,t]}function NN(r,e){if(e=e.trim(),!e)throw new Error("Cannot append link to an empty frontmatter property key.");let t=ON(e),n=Object.keys(r).filter(i=>ON(i)===t);if(n.length>1)throw new Error(`Cannot append link to frontmatter property '${e}' because the note has multiple properties that normalize to that key.`);return n[0]??e}function ON(r){return r.trim().toLowerCase()}async function LN(r,e,t){let n=r.fileManager.generateMarkdownLink(t,e.file.path);try{return await r.fileManager.processFrontMatter(e.file,i=>{M8(i,e.key,n)}),!0}catch(i){return I.logError(`QuickAdd: created the file but could not append the link to frontmatter property '${e.key}' in '${e.file.path}': ${i instanceof Error?i.message:String(i)}`),!1}}var $N,P8,Lg=E(()=>{Ie();wc();bs();$N={alwaysAppend:"Create or convert",createProperty:"Create if missing",error:"Require list"},P8=['input[type="number"]','input[type="date"]','input[type="datetime-local"]','input[type="time"]','input[type="month"]','input[type="checkbox"]'].join(", ")});function VN(r,e,t,n){let i=No(e,t);return i?NA(r,i.editor,n):null}function NA(r,e,t){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=d=>e.posToOffset(d),s=e.getCursor(),a;if(t==="currentLine")a=e.listSelections().map(({anchor:d,head:p})=>({from:o(d)<=o(p)?d:p,to:o(d)<=o(p)?p:d,text:n,cursor:i}));else if(t==="newLineAbove"||t==="newLineBelow"){let d=t==="newLineAbove";a=[{from:{line:s.line,ch:d?0:e.getLine(s.line).length},text:d?n+`
`:`
`+n,cursor:i+(d?0:1)}]}else return null;let l=[],c=[],u=0;a.sort((d,p)=>o(d.from)-o(p.from));for(let d of a)l.push(o(d.from)+u+d.cursor),c.push(o(d.from)+u+d.text.length-(t==="newLineAbove"?1:0)),u+=d.text.length-(o(d.to??d.from)-o(d.from));return e.transaction({changes:a.map(({from:d,to:p,text:f})=>({from:d,to:p,text:f}))}),e.setSelections(c.map(d=>({anchor:e.offsetToPos(d)}))),{offsets:l,content:e.getValue()}}function No(r,e){let t=xn(r);return t?.file?.path===e.path?t:null}function LA(r,e){try{let t=xn(e);return t?(t.editor.replaceSelection(r),!0):(I.logError(`unable to append '${r}' to current line.`),!1)}catch{return I.logError(`unable to append '${r}' to current line.`),!1}}function VA(r,e,t){try{let n=xn(t);if(!n)return I.logError(`unable to insert '${r}' on new line ${e}.`),!1;let i=n.editor,s=i.getCursor().line,a=r.split(`
`),l=a.length,c=a[l-1]?.length??0;if(e==="above")i.replaceRange(r+`
`,{line:s,ch:0}),i.setCursor({line:s+l-1,ch:c});else{let u=i.getLine(s);i.replaceRange(`
`+r,{line:s,ch:u.length}),i.setCursor({line:s+l,ch:c})}return!0}catch{return I.logError(`unable to insert '${r}' on new line ${e}.`),!1}}function BA(r,e){return VA(r,"above",e)}function qA(r,e){return VA(r,"below",e)}function $8(r,e,t,n,i){let o=c=>r.posToOffset(c),s=e.map(c=>{let[u,d]=o(c.anchor)<=o(c.head)?[c.anchor,c.head]:[c.head,c.anchor];return{from:u,to:d,text:n(r.getRange(u,d))}}).sort((c,u)=>o(c.from)-o(u.from)),a=s.map(({from:c,to:u,text:d})=>t==="replaceSelection"?{from:c,to:u,text:d}:{from:u,text:d}),l=[];if(t==="replaceSelection"){let c=0;for(let{from:u,to:d,text:p}of s)l.push(o(u)+c+p.length),c+=p.length-(o(d)-o(u))}i(a,()=>r.transaction({changes:a})),t==="replaceSelection"&&r.setSelections(l.map(c=>({anchor:r.offsetToPos(c)})))}async function BN(r,e,t="replaceSelection",n={}){let{requireActiveView:i=!0,frontmatterProperty:o,frontmatterHandling:s=ud,textForSelection:a,onEditorTextMutation:l}=n,c=r.workspace.getActiveViewOfType(EC.MarkdownView);if(!c){let g="Cannot append link because no active Markdown view is available.";if(i)throw new Error(g);I.logMessage(g);return}if(t==="inFrontmatter"){let g=c.file;if(!g)throw new Error("Cannot append link because the active Markdown view has no file.");await r.fileManager.processFrontMatter(g,v=>{RN(v,o??"",e,s)});return}let u=c.editor;if(!u){let g="Cannot append link because the active Markdown view has no editor.";if(i)throw new Error(g);I.logMessage(g);return}let d=(g,v)=>{if(!l){v();return}let y=u.getValue(),b=g.map(x=>({from:u.posToOffset(x.from),to:u.posToOffset(x.to??x.from),text:x.text}));v(),l({filePath:c.file?.path??null,before:y,after:u.getValue(),edits:b})},p=u.listSelections().map(g=>({anchor:{...g.anchor},head:{...g.head}}));if(a&&p.length>0&&(t==="replaceSelection"||t==="afterSelection")){$8(u,p,t,a,d);return}if(t==="replaceSelection"){let g=p.map(({anchor:v,head:y})=>({from:u.posToOffset(v)<=u.posToOffset(y)?v:y,to:u.posToOffset(v)<=u.posToOffset(y)?y:v,text:e}));d(g,()=>u.replaceSelection(e));return}let f=({line:g,ch:v})=>u.posToOffset({line:g,ch:v}),m=p.sort((g,v)=>f(v.head)-f(g.head));for(let g of m){let v=f(g.anchor)>f(g.head)?g.anchor:g.head;switch(t){case"afterSelection":{d([{from:v,text:e}],()=>u.replaceRange(e,v));break}case"endOfLine":case"newLine":{let y=u.getLine(v.line).length,b=t==="newLine"&&y>0?`
`:"",x={line:v.line,ch:y};d([{from:x,text:b+e}],()=>u.replaceRange(b+e,x));break}}}}async function TC(r,e,t,n){if(!t?.enabled)return!1;let i=bc(t),o=r.workspace.getActiveViewOfType(EC.MarkdownView),s=i.placement!=="inFrontmatter";if(!o||!o.file||s&&!o.editor){if(t.requireActiveFile)throw new Error("Cannot append link because no active Markdown view is available.");return!1}let a=o.file.path,l=CC(r,e,{sourcePath:a,linkType:i.linkType,placement:i.placement}),c=i.displayText==="selection"?u=>CC(r,e,{sourcePath:a,linkType:i.linkType,placement:i.placement,alias:u}):void 0;return await BN(r,l,i.placement,{requireActiveView:!1,frontmatterProperty:i.frontmatterProperty,frontmatterHandling:i.frontmatterHandling,textForSelection:c,onEditorTextMutation:n}),!0}function UA(r,e,t,n){return Vg(r,e,[t],n)}function Vg(r,e,t,n){try{if(e.extension!=="md"||!t.length||t.some(c=>!Number.isSafeInteger(c)||c<0||c>n.length))return!1;let i=r.workspace.getActiveViewOfType(EC.MarkdownView);if(!i||i.file?.path!==e.path||i.getMode()==="preview")return!1;let o=i.editor;if(!o)return!1;let s=o.getValue(),a=t;if(s!==n){if(s!==n.replace(/\r\n?/g,`
`))return!1;a=t.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 I.logMessage(`Unable to place cursor after capture in '${e.path}'.`),!1}}var EC,Bg=E(()=>{EC=require("obsidian");ys();Ie();wc();Og();Lg()});function kC(r){return Nt.test(r)||cr.test(r)||wn.test(r)}function Vn(r,e){let t=e.trim().replace(/^\/+/,"");if(!t)return null;let n=kC(t)?t:`${t}.md`,i=r.vault.getAbstractFileByPath(n);return i instanceof qN.TFile?i:null}function ri(r){if(!Array.isArray(r))return[];let e=new Set,t=[];for(let n of r){if(typeof n!="string")continue;let i=n.trim().replace(/^\/+/,"").replace(/\/+$/,"");!i||e.has(i)||(e.add(i),t.push(i))}return t}function HA(r,e){return e.length===0?!0:e.some(t=>r===t||r.startsWith(`${t}/`))}var qN,qg=E(()=>{qN=require("obsidian");Xe()});function HN(r){if(!r)return!1;let e=r,t=e.getViewState?.();return!!e.pinned||!!t?.pinned||!!t?.state?.pinned}function Ug(r){let e=r.workspace;return(e.rootSplit?e.getMostRecentLeaf?.(e.rootSplit):null)??e.getMostRecentLeaf?.()??null}function O8(r){let e=[];return r.workspace.iterateRootLeaves(t=>{e.includes(t)||e.push(t)}),e}function UN(r){return r.parent?.id??r.parent??null}function R8(r,e){let t=UN(e),n=r.filter(s=>s===e||HN(s)?!1:t===null||UN(s)!==t);if(n.length===0)return null;let i=r.indexOf(e);return(i===-1?r:[...r.slice(i+1),...r.slice(0,i)]).find(s=>n.includes(s))??n[0]}function N8(r){return r instanceof Jp.TFile?!0:typeof r=="object"&&r!==null&&"path"in r&&typeof r.path=="string"&&"extension"in r&&typeof r.extension=="string"}function L8(r,e,t,n){if(n&&(e==="tab"||e==="reuse")&&HN(n))return R8(O8(r),n)??r.workspace.getLeaf("tab");switch(e){case"reuse":return r.workspace.getLeaf(!1);case"tab":return r.workspace.getLeaf("tab");case"split":return r.workspace.getLeaf("split",t);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 Hg(r,e,t={}){let{location:n="tab",direction:i="vertical",mode:o,focus:s=!0,eState:a,originLeaf:l}=t,c=typeof e=="string"?r.vault.getAbstractFileByPath(e):e;if(!N8(c)){let f=typeof e=="string"?e:e.path;throw new Error(`File not found: ${f}`)}let u=l??Ug(r),d=s?null:r.workspace.activeLeaf,p=L8(r,n,i,u);if(!p)throw new Error("Could not obtain a workspace leaf.");if(d&&r.workspace.activeLeaf!==d&&r.workspace.setActiveLeaf(d,{focus:!1}),s?await p.openFile(c):await p.openFile(c,{active:!1}),o&&o!=="default"&&!(typeof o=="object"&&o.mode==="default")){let f=p.getViewState(),m={...f.state??{}};o==="preview"||typeof o=="object"&&o.mode==="preview"?(m.mode="preview",delete m.source):o==="source"?(m.mode="source",m.source=!0):o==="live"||o==="live-preview"?(m.mode="source",m.source=!1):typeof o=="object"&&o.mode==="source"&&(m.mode="source",m.source=o.source),await p.setViewState({...f,...!s&&{active:!1},state:{...m,...a}})}return s&&r.workspace.setActiveLeaf(p,{focus:!0}),p}function zA(r){return(0,Jp.normalizePath)(r).replace(/\/{2,}/g,"/").replace(/^\/+/,"")}function zN(r,e){return zA(r)===zA(e)}function WA(r,e,t=!0){let n;return r.workspace.iterateRootLeaves(i=>{if(n&&n===r.workspace.activeLeaf)return;let o=i.view;if(o instanceof Jp.FileView&&o.file&&(o.file===e||zN(e.path,o.file.path))){n=i;return}}),n!==void 0?(t&&r.workspace.setActiveLeaf(n,{focus:!0}),n):null}var Jp,WN=E(()=>{Jp=require("obsidian")});function ll(r){let e=0,t=0,n=!1,i=0,o=0,s=0;for(;e<=r.length;){let a=r.indexOf(`
`,e),l=a===-1?r.length:a,c=r.slice(e,l).replace(/\r$/,""),u=a===-1?r.length+1:a+1,d=V8.exec(c);if(n){if(d&&d[1].length>=i&&d[2].trim().length===0)return jN(r.slice(o,e),s)}else if(d){let p=d[2].trim().split(/\s+/)[0]?.toLowerCase();(p==="js"||p==="javascript")&&(n=!0,i=d[1].length,o=u,s=t+1)}if(e=u,t++,a===-1)break}return n?jN(r.slice(o),s):{code:null,error:B8}}function jN(r,e){return r.trim().length===0?{code:"",error:q8}:{code:`
`.repeat(e)+r}}var V8,B8,q8,zg=E(()=>{V8=/^ {0,3}(`{3,})(.*)$/,B8="No ```js (or ```javascript) code block found in the note.",q8="The ```js code block is empty."});function GN(r){return r instanceof SC}function H8(r){return r.charCodeAt(0)===65279?r.slice(1):r}function z8(r){return H8(r).trimStart().slice(0,U8).toLowerCase()}function W8(r){return/^<(?:!doctype\s+html|html\b|head\b|body\b|script\b|meta\b|title\b|div\b)/.test(z8(r))}function jA(r,e){let t=new SC(r);throw e.reportLoadErrors!==!1&&Ze(t),t}function j8(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 G8(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 Y8(r,e){let t=e?`the required module "${e}"`:"a required module";return`QuickAdd could not load ${r} because it could not find ${t}. Check that the required file or package exists, and that the capitalization in require(...) matches the file name exactly.`}function K8(r){return YN(r)?(r instanceof Error?r.message:String(r)).match(/Cannot find module ['"]([^'"]+)['"]/)?.[1]:void 0}function YN(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 Q8(r){return r!==null&&typeof r=="object"}function X8(r){return typeof r.entry=="function"?!0:Object.entries(r).some(([e,t])=>e!=="settings"&&e!=="quickadd"&&typeof t=="function")}function Z8(r){return typeof r=="function"?!0:Q8(r)?X8(r):!1}function dd(r){let e=r.split("::").map(t=>t.trim()).filter(Boolean);return{basename:e[0],memberAccess:e.slice(1)}}function AC(r){let e=r.path??r.id;if(e===void 0)return;let{memberAccess:t}=dd(r.name??"");return t&&t.length>0?`${e}::${t.join("::")}`:e}async function Lo(r,e,t={}){let n=e.vault.getAbstractFileByPath(r.path);if(!n){I.logError(`failed to load file ${r.path}.`);return}if(n instanceof _C.TFile){let i=m=>window.require&&window.require(m),o={},s={exports:o},a=await e.vault.read(n),l=a;if(Nt.test(n.path)){let{code:m,error:g}=ll(a);if(m===null||m.length===0){t.reportLoadErrors!==!1&&new _C.Notice(`QuickAdd: ${g} (${r.path})`);return}l=m}W8(l)&&jA(j8(r.path),t);try{new Function("require","module","exports",l)(i,s,o)}catch(m){throw YN(m)&&jA(Y8(r.path,K8(m)),t),m}let c=o.default||s.exports;if(!c)return;let u=c,d=!!o.default,{memberAccess:p}=dd(r.name),f=!!(p&&p.length>0);if(p&&p.length>0){let m;for(;m=p.shift();)u=u[m]}return d&&!f&&!Z8(u)&&jA(G8(r.path),t),u}}var _C,U8,SC,IC=E(()=>{_C=require("obsidian");Xe();Ie();zg();xt();U8=1024,SC=class extends Error{constructor(e){super(e),this.name="UserScriptLoadError"}}});function ef(r){if(r==null||typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")return"";let e=String(r).trim();return e.startsWith("#")?e.substring(1).trim():e}function Wg(r){return r==null?[]:(Array.isArray(r)?r:typeof r=="string"?r.split(/,|\s+/):[r]).map(ef).filter(Boolean)}var GA=E(()=>{});var xi,pd=E(()=>{GA();xi=class{static filterFiles(e,t,n){let i=this.applyInclusionFilters(e,t,n);return this.applyExclusionFilters(i,t,n)}static applyInclusionFilters(e,t,n){let i=e,o=this.getIncludeFolders(t);return o.length>0&&(i=i.filter(s=>o.some(a=>this.matchesFolder(s,a)))),t.tags&&t.tags.length>0&&(i=i.filter(s=>this.matchesTags(s,t.tags??[],n,"all"))),i}static applyExclusionFilters(e,t,n){return e.filter(i=>!(t.excludeFolders?.length&&t.excludeFolders.some(o=>this.matchesFolder(i,o)))&&!(t.excludeTags?.length&&this.matchesTags(i,t.excludeTags,n,"any"))&&!(t.excludeFiles?.length&&t.excludeFiles.some(o=>this.matchesFile(i,o))))}static getIncludeFolders(e){let t=e.folders?.length?e.folders:e.folder?[e.folder]:[];return[...new Set(t.map(n=>this.normalizePath(n)).filter(Boolean))]}static matchesFolder(e,t){let n=this.normalizePath(t),i=this.normalizePath(e.path);return i.startsWith(n+"/")||i.substring(0,i.lastIndexOf("/"))===n}static matchesTags(e,t,n,i){let o=n(e);if(!o)return!1;let s=this.getAllTags(o),a=t.map(ef).filter(Boolean),l=c=>s.some(u=>u===c||u.startsWith(c+"/"));return i==="all"?a.every(l):a.some(l)}static matchesFile(e,t){return e.name===t||e.path===t}static getAllTags(e){let t=[];return e.frontmatter?.tags&&t.push(...Wg(e.frontmatter.tags)),e.frontmatter?.tag&&t.push(...Wg(e.frontmatter.tag)),e.tags&&t.push(...e.tags.map(n=>ef(n.tag))),t.filter(Boolean)}static normalizePath(e){return e.replace(/^\/+|\/+$/g,"")}}});function Vo(r){return r.vault.getAllLoadedFiles().filter(e=>e instanceof YA.TFolder).map(e=>e.path)}function tf(r,e){let t=r.vault.getAbstractFileByPath(e);return!!t&&t instanceof YA.TFolder}function Bo(r,e){let t=e.replace(/\/+$/,"");if(t==="")return r.vault.getMarkdownFiles();let n=`${t}/`;return r.vault.getMarkdownFiles().filter(i=>i.path===t||i.path.startsWith(n))}function J8(r){return Object.entries(r.frontmatter??{}).filter(([e])=>["tag","tags"].includes(e.toLowerCase())).flatMap(([,e])=>Wg(e)).filter(Boolean)}function e5(r,e){let t=r.metadataCache.getFileCache(e);if(!t)return[];let n=[];return t.frontmatter&&n.push(...J8(t)),t.tags&&Array.isArray(t.tags)&&n.push(...t.tags.map(i=>ef(i.tag))),n}function KA(r,e){let t=e.replace(/^#/,"");return r.vault.getMarkdownFiles().filter(n=>e5(r,n).includes(t))}function jg(r,e){return xi.filterFiles(r.vault.getMarkdownFiles(),e,t=>r.metadataCache.getFileCache(t))}function t5(r,e){let t=e.trim().toLowerCase();return r==null?!1:Array.isArray(r)?r.some(n=>n!=null&&typeof n!="object"&&String(n).trim().toLowerCase()===t):typeof r=="object"?!1:String(r).trim().toLowerCase()===t}function Gg(r,e,t,n){let i=e.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(([u])=>u.toLowerCase()===i);return c?t===void 0?!0:t5(c[1],t):!1});return n&&(n.folder||n.tags?.length||n.excludeFolders?.length||n.excludeTags?.length||n.excludeFiles?.length)&&(o=xi.filterFiles(o,n,a=>r.metadataCache.getFileCache(a))),o}var YA,KN=E(()=>{YA=require("obsidian");pd();GA()});function QN(r,e){return r.commands.findCommand(e)}function DC(r,e){QN(r,e)&&(delete r.commands.commands[e],delete r.commands.editorCommands[e])}var XN=E(()=>{});function qo(r){return r.split("|")}function ZN(r){return r.startsWith("|")?r.slice(1):r}function Uo(r){let e=r.indexOf(":");if(e===-1)return null;let t=r.slice(0,e).trim().toLowerCase();if(!t)return null;let n=r.slice(e+1).trim();return{key:t,value:n}}function Cc(r){if(!r)return!0;let e=r.trim().toLowerCase();return!["false","no","0","off"].includes(e)}function ws(r,e){let t=!1;return{remaining:r.filter(i=>i.trim().toLowerCase()===e?(t=!0,!1):!0),found:t}}var xc=E(()=>{});function FC(r){let e=r.trim().toLowerCase(),t=r5[e];if(!t)throw new Error(`Unknown date unit "${r.trim()}". Valid units: ${n5}.`);return t}function JN(r){let e=Uo(r);return e?e.key==="startof"?{boundary:"start",unit:FC(e.value)}:e.key==="endof"?{boundary:"end",unit:FC(e.value)}:null:null}function rf(r,e){return e?e.boundary==="start"?r.startOf(e.unit):r.endOf(e.unit):r}var r5,n5,Yg=E(()=>{xc();r5={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"},n5="year, quarter, month, week, isoweek, day"});function i5(r){return r===void 0?window.moment():window.moment(r)}function o5(r){let e=i5(r?.now);return r?.origin?window.moment(r.origin).hour(e.hour()).minute(e.minute()).second(e.second()).millisecond(e.millisecond()):e}function aa(r){let e;return r?.offset!==null&&r?.offset!==void 0&&typeof r.offset=="number"&&(e=window.moment.duration(r.offset,"days")),rf(o5(r).add(e),r?.snap).format(r?.format??"YYYY-MM-DD")}var eL=E(()=>{Yg()});var ht=E(()=>{IN();Bg();qg();WN();IC();KN();XN();eL()});function cl(r){return/\{\{[^}]*\}\}/.test(r)}var Kg=E(()=>{});var Cr,en,Nr,Ir,PC,Ec,ul,fd,tL,MC,nf,rL,QA,$C,s5,a5,l5,c5,u5,d5,p5,f5,m5,nL,oo=E(()=>{Cr="top",en="bottom",Nr="right",Ir="left",PC="auto",Ec=[Cr,en,Nr,Ir],ul="start",fd="end",tL="clippingParents",MC="viewport",nf="popper",rL="reference",QA=Ec.reduce(function(r,e){return r.concat([e+"-"+ul,e+"-"+fd])},[]),$C=[].concat(Ec,[PC]).reduce(function(r,e){return r.concat([e,e+"-"+ul,e+"-"+fd])},[]),s5="beforeRead",a5="read",l5="afterRead",c5="beforeMain",u5="main",d5="afterMain",p5="beforeWrite",f5="write",m5="afterWrite",nL=[s5,a5,l5,c5,u5,d5,p5,f5,m5]});function En(r){return r?(r.nodeName||"").toLowerCase():null}var Tc=E(()=>{});function dr(r){if(r==null)return window;if(r.toString()!=="[object Window]"){var e=r.ownerDocument;return e&&e.defaultView||window}return r}var Cs=E(()=>{});function Ho(r){var e=dr(r).Element;return r instanceof e||r instanceof Element}function tn(r){var e=dr(r).HTMLElement;return r instanceof e||r instanceof HTMLElement}function of(r){if(typeof ShadowRoot>"u")return!1;var e=dr(r).ShadowRoot;return r instanceof e||r instanceof ShadowRoot}var so=E(()=>{Cs()});function h5(r){var e=r.state;Object.keys(e.elements).forEach(function(t){var n=e.styles[t]||{},i=e.attributes[t]||{},o=e.elements[t];!tn(o)||!En(o)||(Object.assign(o.style,n),Object.keys(i).forEach(function(s){var a=i[s];a===!1?o.removeAttribute(s):o.setAttribute(s,a===!0?"":a)}))})}function g5(r){var e=r.state,t={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,t.popper),e.styles=t,e.elements.arrow&&Object.assign(e.elements.arrow.style,t.arrow),function(){Object.keys(e.elements).forEach(function(n){var i=e.elements[n],o=e.attributes[n]||{},s=Object.keys(e.styles.hasOwnProperty(n)?e.styles[n]:t[n]),a=s.reduce(function(l,c){return l[c]="",l},{});!tn(i)||!En(i)||(Object.assign(i.style,a),Object.keys(o).forEach(function(l){i.removeAttribute(l)}))})}}var iL,oL=E(()=>{Tc();so();iL={name:"applyStyles",enabled:!0,phase:"write",fn:h5,effect:g5,requires:["computeStyles"]}});function Tn(r){return r.split("-")[0]}var kc=E(()=>{});var xs,md,dl,Sc=E(()=>{xs=Math.max,md=Math.min,dl=Math.round});function sf(){var r=navigator.userAgentData;return r!=null&&r.brands&&Array.isArray(r.brands)?r.brands.map(function(e){return e.brand+"/"+e.version}).join(" "):navigator.userAgent}var XA=E(()=>{});function Qg(){return!/^((?!chrome|android).)*safari/i.test(sf())}var ZA=E(()=>{XA()});function zo(r,e,t){e===void 0&&(e=!1),t===void 0&&(t=!1);var n=r.getBoundingClientRect(),i=1,o=1;e&&tn(r)&&(i=r.offsetWidth>0&&dl(n.width)/r.offsetWidth||1,o=r.offsetHeight>0&&dl(n.height)/r.offsetHeight||1);var s=Ho(r)?dr(r):window,a=s.visualViewport,l=!Qg()&&t,c=(n.left+(l&&a?a.offsetLeft:0))/i,u=(n.top+(l&&a?a.offsetTop:0))/o,d=n.width/i,p=n.height/o;return{width:d,height:p,top:u,right:c+d,bottom:u+p,left:c,x:c,y:u}}var af=E(()=>{so();Sc();Cs();ZA()});function hd(r){var e=zo(r),t=r.offsetWidth,n=r.offsetHeight;return Math.abs(e.width-t)<=1&&(t=e.width),Math.abs(e.height-n)<=1&&(n=e.height),{x:r.offsetLeft,y:r.offsetTop,width:t,height:n}}var OC=E(()=>{af()});function Xg(r,e){var t=e.getRootNode&&e.getRootNode();if(r.contains(e))return!0;if(t&&of(t)){var n=e;do{if(n&&r.isSameNode(n))return!0;n=n.parentNode||n.host}while(n)}return!1}var JA=E(()=>{so()});function Ei(r){return dr(r).getComputedStyle(r)}var lf=E(()=>{Cs()});function eI(r){return["table","td","th"].indexOf(En(r))>=0}var sL=E(()=>{Tc()});function Bn(r){return((Ho(r)?r.ownerDocument:r.document)||window.document).documentElement}var pl=E(()=>{so()});function fl(r){return En(r)==="html"?r:r.assignedSlot||r.parentNode||(of(r)?r.host:null)||Bn(r)}var Zg=E(()=>{Tc();pl();so()});function aL(r){return!tn(r)||Ei(r).position==="fixed"?null:r.offsetParent}function v5(r){var e=/firefox/i.test(sf()),t=/Trident/i.test(sf());if(t&&tn(r)){var n=Ei(r);if(n.position==="fixed")return null}var i=fl(r);for(of(i)&&(i=i.host);tn(i)&&["html","body"].indexOf(En(i))<0;){var o=Ei(i);if(o.transform!=="none"||o.perspective!=="none"||o.contain==="paint"||["transform","perspective"].indexOf(o.willChange)!==-1||e&&o.willChange==="filter"||e&&o.filter&&o.filter!=="none")return i;i=i.parentNode}return null}function Es(r){for(var e=dr(r),t=aL(r);t&&eI(t)&&Ei(t).position==="static";)t=aL(t);return t&&(En(t)==="html"||En(t)==="body"&&Ei(t).position==="static")?e:t||v5(r)||e}var cf=E(()=>{Cs();Tc();lf();so();sL();Zg();XA()});function gd(r){return["top","bottom"].indexOf(r)>=0?"x":"y"}var RC=E(()=>{});function vd(r,e,t){return xs(r,md(e,t))}function lL(r,e,t){var n=vd(r,e,t);return n>t?t:n}var tI=E(()=>{Sc()});function Jg(){return{top:0,right:0,bottom:0,left:0}}var rI=E(()=>{});function ev(r){return Object.assign({},Jg(),r)}var nI=E(()=>{rI()});function tv(r,e){return e.reduce(function(t,n){return t[n]=r,t},{})}var iI=E(()=>{});function b5(r){var e,t=r.state,n=r.name,i=r.options,o=t.elements.arrow,s=t.modifiersData.popperOffsets,a=Tn(t.placement),l=gd(a),c=[Ir,Nr].indexOf(a)>=0,u=c?"height":"width";if(!(!o||!s)){var d=y5(i.padding,t),p=hd(o),f=l==="y"?Cr:Ir,m=l==="y"?en:Nr,g=t.rects.reference[u]+t.rects.reference[l]-s[l]-t.rects.popper[u],v=s[l]-t.rects.reference[l],y=Es(o),b=y?l==="y"?y.clientHeight||0:y.clientWidth||0:0,x=g/2-v/2,w=d[f],T=b-p[u]-d[m],C=b/2-p[u]/2+x,S=vd(w,C,T),A=l;t.modifiersData[n]=(e={},e[A]=S,e.centerOffset=S-C,e)}}function w5(r){var e=r.state,t=r.options,n=t.element,i=n===void 0?"[data-popper-arrow]":n;i!=null&&(typeof i=="string"&&(i=e.elements.popper.querySelector(i),!i)||Xg(e.elements.popper,i)&&(e.elements.arrow=i))}var y5,cL,uL=E(()=>{kc();OC();JA();cf();RC();tI();nI();iI();oo();y5=function(e,t){return e=typeof e=="function"?e(Object.assign({},t.rects,{placement:t.placement})):e,ev(typeof e!="number"?e:tv(e,Ec))};cL={name:"arrow",enabled:!0,phase:"main",fn:b5,effect:w5,requires:["popperOffsets"],requiresIfExists:["preventOverflow"]}});function Wo(r){return r.split("-")[1]}var uf=E(()=>{});function x5(r,e){var t=r.x,n=r.y,i=e.devicePixelRatio||1;return{x:dl(t*i)/i||0,y:dl(n*i)/i||0}}function dL(r){var e,t=r.popper,n=r.popperRect,i=r.placement,o=r.variation,s=r.offsets,a=r.position,l=r.gpuAcceleration,c=r.adaptive,u=r.roundOffsets,d=r.isFixed,p=s.x,f=p===void 0?0:p,m=s.y,g=m===void 0?0:m,v=typeof u=="function"?u({x:f,y:g}):{x:f,y:g};f=v.x,g=v.y;var y=s.hasOwnProperty("x"),b=s.hasOwnProperty("y"),x=Ir,w=Cr,T=window;if(c){var C=Es(t),S="clientHeight",A="clientWidth";if(C===dr(t)&&(C=Bn(t),Ei(C).position!=="static"&&a==="absolute"&&(S="scrollHeight",A="scrollWidth")),C=C,i===Cr||(i===Ir||i===Nr)&&o===fd){w=en;var D=d&&C===T&&T.visualViewport?T.visualViewport.height:C[S];g-=D-n.height,g*=l?1:-1}if(i===Ir||(i===Cr||i===en)&&o===fd){x=Nr;var P=d&&C===T&&T.visualViewport?T.visualViewport.width:C[A];f-=P-n.width,f*=l?1:-1}}var U=Object.assign({position:a},c&&C5),K=u===!0?x5({x:f,y:g},dr(t)):{x:f,y:g};if(f=K.x,g=K.y,l){var W;return Object.assign({},U,(W={},W[w]=b?"0":"",W[x]=y?"0":"",W.transform=(T.devicePixelRatio||1)<=1?"translate("+f+"px, "+g+"px)":"translate3d("+f+"px, "+g+"px, 0)",W))}return Object.assign({},U,(e={},e[w]=b?g+"px":"",e[x]=y?f+"px":"",e.transform="",e))}function E5(r){var e=r.state,t=r.options,n=t.gpuAcceleration,i=n===void 0?!0:n,o=t.adaptive,s=o===void 0?!0:o,a=t.roundOffsets,l=a===void 0?!0:a,c={placement:Tn(e.placement),variation:Wo(e.placement),popper:e.elements.popper,popperRect:e.rects.popper,gpuAcceleration:i,isFixed:e.options.strategy==="fixed"};e.modifiersData.popperOffsets!=null&&(e.styles.popper=Object.assign({},e.styles.popper,dL(Object.assign({},c,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:s,roundOffsets:l})))),e.modifiersData.arrow!=null&&(e.styles.arrow=Object.assign({},e.styles.arrow,dL(Object.assign({},c,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})}var C5,pL,fL=E(()=>{oo();cf();Cs();pl();lf();kc();uf();Sc();C5={top:"auto",right:"auto",bottom:"auto",left:"auto"};pL={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:E5,data:{}}});function T5(r){var e=r.state,t=r.instance,n=r.options,i=n.scroll,o=i===void 0?!0:i,s=n.resize,a=s===void 0?!0:s,l=dr(e.elements.popper),c=[].concat(e.scrollParents.reference,e.scrollParents.popper);return o&&c.forEach(function(u){u.addEventListener("scroll",t.update,NC)}),a&&l.addEventListener("resize",t.update,NC),function(){o&&c.forEach(function(u){u.removeEventListener("scroll",t.update,NC)}),a&&l.removeEventListener("resize",t.update,NC)}}var NC,mL,hL=E(()=>{Cs();NC={passive:!0};mL={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:T5,data:{}}});function df(r){return r.replace(/left|right|bottom|top/g,function(e){return k5[e]})}var k5,gL=E(()=>{k5={left:"right",right:"left",bottom:"top",top:"bottom"}});function LC(r){return r.replace(/start|end/g,function(e){return S5[e]})}var S5,vL=E(()=>{S5={start:"end",end:"start"}});function yd(r){var e=dr(r),t=e.pageXOffset,n=e.pageYOffset;return{scrollLeft:t,scrollTop:n}}var VC=E(()=>{Cs()});function bd(r){return zo(Bn(r)).left+yd(r).scrollLeft}var BC=E(()=>{af();pl();VC()});function oI(r,e){var t=dr(r),n=Bn(r),i=t.visualViewport,o=n.clientWidth,s=n.clientHeight,a=0,l=0;if(i){o=i.width,s=i.height;var c=Qg();(c||!c&&e==="fixed")&&(a=i.offsetLeft,l=i.offsetTop)}return{width:o,height:s,x:a+bd(r),y:l}}var yL=E(()=>{Cs();pl();BC();ZA()});function sI(r){var e,t=Bn(r),n=yd(r),i=(e=r.ownerDocument)==null?void 0:e.body,o=xs(t.scrollWidth,t.clientWidth,i?i.scrollWidth:0,i?i.clientWidth:0),s=xs(t.scrollHeight,t.clientHeight,i?i.scrollHeight:0,i?i.clientHeight:0),a=-n.scrollLeft+bd(r),l=-n.scrollTop;return Ei(i||t).direction==="rtl"&&(a+=xs(t.clientWidth,i?i.clientWidth:0)-o),{width:o,height:s,x:a,y:l}}var bL=E(()=>{pl();lf();BC();VC();Sc()});function wd(r){var e=Ei(r),t=e.overflow,n=e.overflowX,i=e.overflowY;return/auto|scroll|overlay|hidden/.test(t+i+n)}var qC=E(()=>{lf()});function UC(r){return["html","body","#document"].indexOf(En(r))>=0?r.ownerDocument.body:tn(r)&&wd(r)?r:UC(fl(r))}var wL=E(()=>{Zg();qC();Tc();so()});function _c(r,e){var t;e===void 0&&(e=[]);var n=UC(r),i=n===((t=r.ownerDocument)==null?void 0:t.body),o=dr(n),s=i?[o].concat(o.visualViewport||[],wd(n)?n:[]):n,a=e.concat(s);return i?a:a.concat(_c(fl(s)))}var aI=E(()=>{wL();Zg();Cs();qC()});function pf(r){return Object.assign({},r,{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height})}var lI=E(()=>{});function _5(r,e){var t=zo(r,!1,e==="fixed");return t.top=t.top+r.clientTop,t.left=t.left+r.clientLeft,t.bottom=t.top+r.clientHeight,t.right=t.left+r.clientWidth,t.width=r.clientWidth,t.height=r.clientHeight,t.x=t.left,t.y=t.top,t}function CL(r,e,t){return e===MC?pf(oI(r,t)):Ho(e)?_5(e,t):pf(sI(Bn(r)))}function A5(r){var e=_c(fl(r)),t=["absolute","fixed"].indexOf(Ei(r).position)>=0,n=t&&tn(r)?Es(r):r;return Ho(n)?e.filter(function(i){return Ho(i)&&Xg(i,n)&&En(i)!=="body"}):[]}function cI(r,e,t,n){var i=e==="clippingParents"?A5(r):[].concat(e),o=[].concat(i,[t]),s=o[0],a=o.reduce(function(l,c){var u=CL(r,c,n);return l.top=xs(u.top,l.top),l.right=md(u.right,l.right),l.bottom=md(u.bottom,l.bottom),l.left=xs(u.left,l.left),l},CL(r,s,n));return a.width=a.right-a.left,a.height=a.bottom-a.top,a.x=a.left,a.y=a.top,a}var xL=E(()=>{oo();yL();bL();aI();cf();pl();lf();so();af();Zg();JA();Tc();lI();Sc()});function rv(r){var e=r.reference,t=r.element,n=r.placement,i=n?Tn(n):null,o=n?Wo(n):null,s=e.x+e.width/2-t.width/2,a=e.y+e.height/2-t.height/2,l;switch(i){case Cr:l={x:s,y:e.y-t.height};break;case en:l={x:s,y:e.y+e.height};break;case Nr:l={x:e.x+e.width,y:a};break;case Ir:l={x:e.x-t.width,y:a};break;default:l={x:e.x,y:e.y}}var c=i?gd(i):null;if(c!=null){var u=c==="y"?"height":"width";switch(o){case ul:l[c]=l[c]-(e[u]/2-t[u]/2);break;case fd:l[c]=l[c]+(e[u]/2-t[u]/2);break;default:}}return l}var uI=E(()=>{kc();uf();RC();oo()});function Ts(r,e){e===void 0&&(e={});var t=e,n=t.placement,i=n===void 0?r.placement:n,o=t.strategy,s=o===void 0?r.strategy:o,a=t.boundary,l=a===void 0?tL:a,c=t.rootBoundary,u=c===void 0?MC:c,d=t.elementContext,p=d===void 0?nf:d,f=t.altBoundary,m=f===void 0?!1:f,g=t.padding,v=g===void 0?0:g,y=ev(typeof v!="number"?v:tv(v,Ec)),b=p===nf?rL:nf,x=r.rects.popper,w=r.elements[m?b:p],T=cI(Ho(w)?w:w.contextElement||Bn(r.elements.popper),l,u,s),C=zo(r.elements.reference),S=rv({reference:C,element:x,strategy:"absolute",placement:i}),A=pf(Object.assign({},x,S)),D=p===nf?A:C,P={top:T.top-D.top+y.top,bottom:D.bottom-T.bottom+y.bottom,left:T.left-D.left+y.left,right:D.right-T.right+y.right},U=r.modifiersData.offset;if(p===nf&&U){var K=U[i];Object.keys(P).forEach(function(W){var ee=[Nr,en].indexOf(W)>=0?1:-1,me=[Cr,en].indexOf(W)>=0?"y":"x";P[W]+=K[me]*ee})}return P}var nv=E(()=>{xL();pl();af();uI();lI();oo();so();nI();iI()});function dI(r,e){e===void 0&&(e={});var t=e,n=t.placement,i=t.boundary,o=t.rootBoundary,s=t.padding,a=t.flipVariations,l=t.allowedAutoPlacements,c=l===void 0?$C:l,u=Wo(n),d=u?a?QA:QA.filter(function(m){return Wo(m)===u}):Ec,p=d.filter(function(m){return c.indexOf(m)>=0});p.length===0&&(p=d);var f=p.reduce(function(m,g){return m[g]=Ts(r,{placement:g,boundary:i,rootBoundary:o,padding:s})[Tn(g)],m},{});return Object.keys(f).sort(function(m,g){return f[m]-f[g]})}var EL=E(()=>{uf();oo();nv();kc()});function I5(r){if(Tn(r)===PC)return[];var e=df(r);return[LC(r),e,LC(e)]}function D5(r){var e=r.state,t=r.options,n=r.name;if(!e.modifiersData[n]._skip){for(var i=t.mainAxis,o=i===void 0?!0:i,s=t.altAxis,a=s===void 0?!0:s,l=t.fallbackPlacements,c=t.padding,u=t.boundary,d=t.rootBoundary,p=t.altBoundary,f=t.flipVariations,m=f===void 0?!0:f,g=t.allowedAutoPlacements,v=e.options.placement,y=Tn(v),b=y===v,x=l||(b||!m?[df(v)]:I5(v)),w=[v].concat(x).reduce(function(ue,be){return ue.concat(Tn(be)===PC?dI(e,{placement:be,boundary:u,rootBoundary:d,padding:c,flipVariations:m,allowedAutoPlacements:g}):be)},[]),T=e.rects.reference,C=e.rects.popper,S=new Map,A=!0,D=w[0],P=0;P<w.length;P++){var U=w[P],K=Tn(U),W=Wo(U)===ul,ee=[Cr,en].indexOf(K)>=0,me=ee?"width":"height",O=Ts(e,{placement:U,boundary:u,rootBoundary:d,altBoundary:p,padding:c}),H=ee?W?Nr:Ir:W?en:Cr;T[me]>C[me]&&(H=df(H));var ce=df(H),te=[];if(o&&te.push(O[K]<=0),a&&te.push(O[H]<=0,O[ce]<=0),te.every(function(ue){return ue})){D=U,A=!1;break}S.set(U,te)}if(A)for(var z=m?3:1,G=function(be){var Ke=w.find(function(Oe){var Ee=S.get(Oe);if(Ee)return Ee.slice(0,be).every(function(He){return He})});if(Ke)return D=Ke,"break"},ie=z;ie>0;ie--){var xe=G(ie);if(xe==="break")break}e.placement!==D&&(e.modifiersData[n]._skip=!0,e.placement=D,e.reset=!0)}}var TL,kL=E(()=>{gL();kc();vL();nv();EL();oo();uf();TL={name:"flip",enabled:!0,phase:"main",fn:D5,requiresIfExists:["offset"],data:{_skip:!1}}});function SL(r,e,t){return t===void 0&&(t={x:0,y:0}),{top:r.top-e.height-t.y,right:r.right-e.width+t.x,bottom:r.bottom-e.height+t.y,left:r.left-e.width-t.x}}function _L(r){return[Cr,Nr,en,Ir].some(function(e){return r[e]>=0})}function F5(r){var e=r.state,t=r.name,n=e.rects.reference,i=e.rects.popper,o=e.modifiersData.preventOverflow,s=Ts(e,{elementContext:"reference"}),a=Ts(e,{altBoundary:!0}),l=SL(s,n),c=SL(a,i,o),u=_L(l),d=_L(c);e.modifiersData[t]={referenceClippingOffsets:l,popperEscapeOffsets:c,isReferenceHidden:u,hasPopperEscaped:d},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":u,"data-popper-escaped":d})}var AL,IL=E(()=>{oo();nv();AL={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:F5}});function P5(r,e,t){var n=Tn(r),i=[Ir,Cr].indexOf(n)>=0?-1:1,o=typeof t=="function"?t(Object.assign({},e,{placement:r})):t,s=o[0],a=o[1];return s=s||0,a=(a||0)*i,[Ir,Nr].indexOf(n)>=0?{x:a,y:s}:{x:s,y:a}}function M5(r){var e=r.state,t=r.options,n=r.name,i=t.offset,o=i===void 0?[0,0]:i,s=$C.reduce(function(u,d){return u[d]=P5(d,e.rects,o),u},{}),a=s[e.placement],l=a.x,c=a.y;e.modifiersData.popperOffsets!=null&&(e.modifiersData.popperOffsets.x+=l,e.modifiersData.popperOffsets.y+=c),e.modifiersData[n]=s}var DL,FL=E(()=>{kc();oo();DL={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:M5}});function $5(r){var e=r.state,t=r.name;e.modifiersData[t]=rv({reference:e.rects.reference,element:e.rects.popper,strategy:"absolute",placement:e.placement})}var PL,ML=E(()=>{uI();PL={name:"popperOffsets",enabled:!0,phase:"read",fn:$5,data:{}}});function pI(r){return r==="x"?"y":"x"}var $L=E(()=>{});function O5(r){var e=r.state,t=r.options,n=r.name,i=t.mainAxis,o=i===void 0?!0:i,s=t.altAxis,a=s===void 0?!1:s,l=t.boundary,c=t.rootBoundary,u=t.altBoundary,d=t.padding,p=t.tether,f=p===void 0?!0:p,m=t.tetherOffset,g=m===void 0?0:m,v=Ts(e,{boundary:l,rootBoundary:c,padding:d,altBoundary:u}),y=Tn(e.placement),b=Wo(e.placement),x=!b,w=gd(y),T=pI(w),C=e.modifiersData.popperOffsets,S=e.rects.reference,A=e.rects.popper,D=typeof g=="function"?g(Object.assign({},e.rects,{placement:e.placement})):g,P=typeof D=="number"?{mainAxis:D,altAxis:D}:Object.assign({mainAxis:0,altAxis:0},D),U=e.modifiersData.offset?e.modifiersData.offset[e.placement]:null,K={x:0,y:0};if(C){if(o){var W,ee=w==="y"?Cr:Ir,me=w==="y"?en:Nr,O=w==="y"?"height":"width",H=C[w],ce=H+v[ee],te=H-v[me],z=f?-A[O]/2:0,G=b===ul?S[O]:A[O],ie=b===ul?-A[O]:-S[O],xe=e.elements.arrow,ue=f&&xe?hd(xe):{width:0,height:0},be=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:Jg(),Ke=be[ee],Oe=be[me],Ee=vd(0,S[O],ue[O]),He=x?S[O]/2-z-Ee-Ke-P.mainAxis:G-Ee-Ke-P.mainAxis,Le=x?-S[O]/2+z+Ee+Oe+P.mainAxis:ie+Ee+Oe+P.mainAxis,At=e.elements.arrow&&Es(e.elements.arrow),mr=At?w==="y"?At.clientTop||0:At.clientLeft||0:0,zr=(W=U?.[w])!=null?W:0,ge=H+He-zr-mr,ve=H+Le-zr,Fe=vd(f?md(ce,ge):ce,H,f?xs(te,ve):te);C[w]=Fe,K[w]=Fe-H}if(a){var Je,mt=w==="x"?Cr:Ir,Ft=w==="x"?en:Nr,Qe=C[T],zt=T==="y"?"height":"width",rr=Qe+v[mt],Qn=Qe-v[Ft],di=[Cr,Ir].indexOf(y)!==-1,Z=(Je=U?.[T])!=null?Je:0,De=di?rr:Qe-S[zt]-A[zt]-Z+P.altAxis,Pt=di?Qe+S[zt]+A[zt]-Z-P.altAxis:Qn,It=f&&di?lL(De,Qe,Pt):vd(f?De:rr,Qe,f?Pt:Qn);C[T]=It,K[T]=It-Qe}e.modifiersData[n]=K}}var OL,RL=E(()=>{oo();kc();RC();$L();tI();OC();cf();nv();uf();rI();Sc();OL={name:"preventOverflow",enabled:!0,phase:"main",fn:O5,requiresIfExists:["offset"]}});var fI=E(()=>{});function mI(r){return{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}}var NL=E(()=>{});function hI(r){return r===dr(r)||!tn(r)?yd(r):mI(r)}var LL=E(()=>{VC();Cs();so();NL()});function R5(r){var e=r.getBoundingClientRect(),t=dl(e.width)/r.offsetWidth||1,n=dl(e.height)/r.offsetHeight||1;return t!==1||n!==1}function gI(r,e,t){t===void 0&&(t=!1);var n=tn(e),i=tn(e)&&R5(e),o=Bn(e),s=zo(r,i,t),a={scrollLeft:0,scrollTop:0},l={x:0,y:0};return(n||!n&&!t)&&((En(e)!=="body"||wd(o))&&(a=hI(e)),tn(e)?(l=zo(e,!0),l.x+=e.clientLeft,l.y+=e.clientTop):o&&(l.x=bd(o))),{x:s.left+a.scrollLeft-l.x,y:s.top+a.scrollTop-l.y,width:s.width,height:s.height}}var VL=E(()=>{af();LL();Tc();so();BC();pl();qC();Sc()});function N5(r){var e=new Map,t=new Set,n=[];r.forEach(function(o){e.set(o.name,o)});function i(o){t.add(o.name);var s=[].concat(o.requires||[],o.requiresIfExists||[]);s.forEach(function(a){if(!t.has(a)){var l=e.get(a);l&&i(l)}}),n.push(o)}return r.forEach(function(o){t.has(o.name)||i(o)}),n}function vI(r){var e=N5(r);return nL.reduce(function(t,n){return t.concat(e.filter(function(i){return i.phase===n}))},[])}var BL=E(()=>{oo()});function yI(r){var e;return function(){return e||(e=new Promise(function(t){Promise.resolve().then(function(){e=void 0,t(r())})})),e}}var qL=E(()=>{});function bI(r){var e=r.reduce(function(t,n){var i=t[n.name];return t[n.name]=i?Object.assign({},i,n,{options:Object.assign({},i.options,n.options),data:Object.assign({},i.data,n.data)}):n,t},{});return Object.keys(e).map(function(t){return e[t]})}var UL=E(()=>{});function zL(){for(var r=arguments.length,e=new Array(r),t=0;t<r;t++)e[t]=arguments[t];return!e.some(function(n){return!(n&&typeof n.getBoundingClientRect=="function")})}function WL(r){r===void 0&&(r={});var e=r,t=e.defaultModifiers,n=t===void 0?[]:t,i=e.defaultOptions,o=i===void 0?HL:i;return function(a,l,c){c===void 0&&(c=o);var u={placement:"bottom",orderedModifiers:[],options:Object.assign({},HL,o),modifiersData:{},elements:{reference:a,popper:l},attributes:{},styles:{}},d=[],p=!1,f={state:u,setOptions:function(y){var b=typeof y=="function"?y(u.options):y;g(),u.options=Object.assign({},o,u.options,b),u.scrollParents={reference:Ho(a)?_c(a):a.contextElement?_c(a.contextElement):[],popper:_c(l)};var x=vI(bI([].concat(n,u.options.modifiers)));return u.orderedModifiers=x.filter(function(w){return w.enabled}),m(),f.update()},forceUpdate:function(){if(!p){var y=u.elements,b=y.reference,x=y.popper;if(zL(b,x)){u.rects={reference:gI(b,Es(x),u.options.strategy==="fixed"),popper:hd(x)},u.reset=!1,u.placement=u.options.placement,u.orderedModifiers.forEach(function(P){return u.modifiersData[P.name]=Object.assign({},P.data)});for(var w=0;w<u.orderedModifiers.length;w++){if(u.reset===!0){u.reset=!1,w=-1;continue}var T=u.orderedModifiers[w],C=T.fn,S=T.options,A=S===void 0?{}:S,D=T.name;typeof C=="function"&&(u=C({state:u,options:A,name:D,instance:f})||u)}}}},update:yI(function(){return new Promise(function(v){f.forceUpdate(),v(u)})}),destroy:function(){g(),p=!0}};if(!zL(a,l))return f;f.setOptions(c).then(function(v){!p&&c.onFirstUpdate&&c.onFirstUpdate(v)});function m(){u.orderedModifiers.forEach(function(v){var y=v.name,b=v.options,x=b===void 0?{}:b,w=v.effect;if(typeof w=="function"){var T=w({state:u,name:y,instance:f,options:x}),C=function(){};d.push(T||C)}})}function g(){d.forEach(function(v){return v()}),d=[]}return f}}var HL,jL=E(()=>{VL();OC();aI();cf();BL();qL();UL();so();HL={placement:"bottom",modifiers:[],strategy:"absolute"}});var L5,wI,GL=E(()=>{jL();hL();ML();fL();oL();FL();kL();RL();uL();IL();fI();L5=[mL,PL,pL,iL,DL,TL,OL,cL,AL],wI=WL({defaultModifiers:L5})});var YL=E(()=>{oo();fI();GL()});function KL(r,e){return V5.test(r[e])}function B5(r){if(!r.includes("![["))return r;let e="",t=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){e+=r.slice(t,n),n=i+2,t=n;continue}}n++}return e+r.slice(t)}function q5(r){if(!r.includes("[["))return r;let e="",t=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){e+=r.slice(t,n)+r.slice(n+2,i),n=i+2,t=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){e+=r.slice(t,n)+r.slice(i+1,o),n=o+2,t=n;continue}}}n++}return e+r.slice(t)}function U5(r){let e=0;if(r.charCodeAt(0)===35){for(;r.charCodeAt(e)===35;)e++;for(;e<r.length&&KL(r,e);)e++}let t=r.length;if(t>e&&r.charCodeAt(t-1)===35){for(;t>e&&r.charCodeAt(t-1)===35;)t--;for(;t>e&&KL(r,t-1);)t--}return r.slice(e,t)}function H5(r){if(!r.includes("[[")&&!r.includes("]]"))return r;let e="",t=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){e+=r.slice(t,n),n+=2,t=n;continue}n++}return e+r.slice(t)}function CI(r){return H5(U5(q5(B5(r)).replace(z5,""))).trim()}var V5,z5,QL=E(()=>{V5=/^\s$/;z5=/[*_`~]/g});function kn(r){return typeof r=="string"?r:r==null?"":String(r)}function XL(r,e){r.scope?.register(["Mod","Shift"],"Enter",()=>(e(),!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 t=r.modalEl;if(t&&typeof t.createDiv=="function"){let i=t.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(),e()})}}function ff(r){let e=!1;return t=>{e||(e=!0,I.logWarning(nl(t,r)))}}function Ac(r){return kn(r)}function tr(r){return r.normalize("NFC").toLowerCase()}function iv(r){return r.toLowerCase().endsWith(".md")?r.slice(0,-3):r}function HC(r,e,t,n,i={}){let o=r.value;r.value=o.slice(0,e)+n+o.slice(t),r.setSelectionRange(e+n.length,e+n.length);let s=new Event("input",{bubbles:!0});i.fromCompletion&&(s.fromCompletion=!0),r.dispatchEvent(s)}function ZL(r,e,t){if(r.replaceChildren(),!t){r.textContent=e;return}let n="",i=[],o=[],s=0;for(let d of e){let p=d.toLowerCase(),f=s,m=s+d.length;for(let g=0;g<p.length;g++)i.push(f),o.push(m);n+=p,s=m}let a="";for(let d of t)a+=d.toLowerCase();let l=0,c=0,u=n.indexOf(a,c);for(;u!==-1;){let d=Math.max(l,i[u]),p=o[u+a.length-1];if(p>d){d>l&&r.append(Ng(r,e.slice(l,d)));let f=er(r,"mark");f.className="qa-highlight",f.textContent=e.slice(d,p),r.append(f),l=p}c=u+a.length,u=n.indexOf(a,c)}l<e.length&&r.append(Ng(r,e.slice(l)))}function Cd(r,e=!1){let t=Object.assign(new Event("input",{bubbles:!0}),{fromCompletion:!0,...e?{keepOpen:!0}:{}});r.dispatchEvent(t)}var rn=E(()=>{Ie();bs();xt();QL()});var zC,W5,j5,xI,ov,xr,ks=E(()=>{YL();zC=require("obsidian");Ie();bs();rn();W5=(r,e)=>(r%e+e)%e,j5=0,xI=class{constructor(e,t,n,i,o){this.isOpen=!1;this.owner=e,this.containerEl=t,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)},t.addEventListener("click",this.clickListener),t.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});n.register([],"Enter",a=>{if(!a.isComposing&&this.isOpen)return this.useSelectedItem(a),!1})}findSuggestionItem(e){let t=this.containerEl.ownerDocument.defaultView;if(!t||!(e instanceof t.Element))return null;let n=e.closest(".suggestion-item");return n&&this.containerEl.contains(n)?n:null}onSuggestionClick(e,t){e.preventDefault();let n=this.suggestions.indexOf(t);this.setSelectedItem(n,!1),this.useSelectedItem(e)}onSuggestionMouseover(e,t){let n=this.suggestions.indexOf(t);this.setSelectedItem(n,!1)}setSuggestions(e){this.containerEl.replaceChildren();let t=[];if(e.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),t.push(o)}),this.values=e,this.suggestions=t,e.length===0){this.isOpen=!1,this.onActiveOptionChange(null);return}this.setSelectedItem(0,!1),this.isOpen=!0}useSelectedItem(e){let t=this.values[this.selectedItem];t&&this.owner.selectSuggestion(t,e)}setSelectedItem(e,t){if(!this.suggestions?.length)return;let n=W5(e,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,t&&o.scrollIntoView(!1)}close(){this.isOpen=!1,this.onActiveOptionChange(null)}getIsOpen(){return this.isOpen}},ov=new WeakMap,xr=class{constructor(e,t,n){this.popper=null;this.currentRequestId=0;this.isOpen=!1;this.destroyed=!1;this.currentQuery="";this.renderMatch=ZL;let i=this.constructor.name,o=ov.get(t);o||(o=new Map,ov.set(t,o));let s=o.get(i);s&&s.destroy(),ov.set(t,o),o.set(i,this),this.app=e,this.inputEl=t,this.scope=new zC.Scope(n),this.suggestEl=this.inputEl.ownerDocument.win.createDiv(),this.suggestEl.classList.add("suggestion-container");let a=this.suggestEl.createDiv({cls:"suggestion"});this.listboxId=`qa-suggest-listbox-${++j5}`,a.id=this.listboxId,a.setAttribute("role","listbox"),a.setAttribute("aria-label","Suggestions"),this.suggest=new xI(this,a,this.scope,this.listboxId,l=>this.setActiveDescendant(l)),this.scope.register([],"Escape",this.close.bind(this)),this.debouncedOnInputChanged=(0,zC.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.globalResizeListener=this.close.bind(this),this.globalBlurListener=this.close.bind(this)}onGlobalClick(e){if(!this.isOpen)return;let t=e.target;!this.suggestEl.contains(t)&&!this.inputEl.contains(t)&&this.close()}onGlobalWheel(e){if(!this.isOpen)return;let t=e.target;this.suggestEl.contains(t)||this.close()}async onInputChanged(e){if(this.destroyed||this.inputEl.closest("[hidden]"))return;let t=!!(e?.fromCompletion&&e.keepOpen);if(e?.fromCompletion&&!t)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){(t||this.isOpen)&&this.close();return}this.suggest.setSuggestions(o),(!t||!this.isOpen)&&this.open(this.app.dom.appContainerEl,this.inputEl)}catch(o){I.logError(o),t||this.close()}}open(e,t){if(this.destroyed||t.closest("[hidden]"))return;this.isOpen||this.app.keymap.pushScope(this.scope),this.isOpen=!0,this.inputEl.setAttribute("aria-expanded","true"),this.inputEl.setAttribute("aria-controls",this.listboxId);let n=io(t);if((io(e)===n?e:n.body).appendChild(this.suggestEl),this.popper){this.popper.update();return}this.popper=wI(t,this.suggestEl,{placement:"bottom-start",modifiers:[{name:"sameWidth",enabled:!0,fn:({state:l,instance:c})=>{let u=`${l.rects.reference.width}px`;l.styles.popper.width!==u&&(l.styles.popper.width=u,c.update())},phase:"beforeWrite",requires:["computeStyles"]},{name:"flip",enabled:!0},{name:"preventOverflow",enabled:!0},{name:"offset",enabled:!0,options:{offset:[0,4]}}]});let s=n,a=Rg(t);s.addEventListener("pointerdown",this.globalClickListener,!0),s.addEventListener("wheel",this.globalWheelListener,!0),a.addEventListener("resize",this.globalResizeListener),a.addEventListener("blur",this.globalBlurListener)}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.popper&&(this.popper.destroy(),this.popper=null),this.suggestEl.remove();let e=io(this.inputEl),t=Rg(this.inputEl);e.removeEventListener("pointerdown",this.globalClickListener,!0),e.removeEventListener("wheel",this.globalWheelListener,!0),t.removeEventListener("resize",this.globalResizeListener),t.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 e=this.constructor.name,t=ov.get(this.inputEl);t&&(t.delete(e),t.size===0&&ov.delete(this.inputEl))}setActiveDescendant(e){if(e){this.inputEl.setAttribute("aria-activedescendant",e);return}this.inputEl.removeAttribute("aria-activedescendant")}getCurrentQuery(){return this.currentQuery}}});function sr(r){return Array.isArray(r)||r==null?!1:typeof r=="object"?Object.keys(r).length>0:!!r}var sv=E(()=>{});function JL(r,e=0){return(qn[r[e+0]]+qn[r[e+1]]+qn[r[e+2]]+qn[r[e+3]]+"-"+qn[r[e+4]]+qn[r[e+5]]+"-"+qn[r[e+6]]+qn[r[e+7]]+"-"+qn[r[e+8]]+qn[r[e+9]]+"-"+qn[r[e+10]]+qn[r[e+11]]+qn[r[e+12]]+qn[r[e+13]]+qn[r[e+14]]+qn[r[e+15]]).toLowerCase()}var qn,e1=E(()=>{qn=[];for(let r=0;r<256;++r)qn.push((r+256).toString(16).slice(1))});function EI(){return crypto.getRandomValues(G5)}var G5,t1=E(()=>{G5=new Uint8Array(16)});function Y5(r,e,t){return!e&&!r&&crypto.randomUUID?crypto.randomUUID():K5(r,e,t)}function K5(r,e,t){r=r||{};let n=r.random??r.rng?.()??EI();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(t=t||0,t<0||t+16>e.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[t+i]=n[i];return e}return JL(n)}var Kt,r1=E(()=>{t1();e1();Kt=Y5});var Ss=E(()=>{r1()});function WC(r){return Ue(r)&&r.type==="Multi"}function Ue(r){return typeof r=="object"&&r!==null}function et(r){return WC(r)?Array.isArray(r.choices)?r.choices:[]:[]}function ml(r){return WC(r)&&Array.isArray(r.choices)}function mf(r){if(!Array.isArray(r))return!0;let e=t=>t.some(n=>{if(Array.isArray(n))return!0;if(!Ue(n)||n.type!=="Multi")return!1;let i=n.choices;return Array.isArray(i)?e(i):sr(i)});return e(r)}function Lr(r){return Array.isArray(r)?r:[]}function jo(r){return WC(r)?sr(r.choices):!1}function hf(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 xd(r){return(typeof r.icon=="string"?r.icon.trim():"")||hf(r.type)}function nn(r){let e=[],t=n=>{Ue(n)&&(e.push(n),et(n).forEach(t))};return Lr(r).forEach(t),e}function n1(r){let e=new Map,t=n=>{let i=[];for(let o of n){if(!Ue(o)){i.push(o);continue}let s=o,a=e.get(s.id);if(a){if(JSON.stringify(s)===JSON.stringify(a))continue;s={...s,id:Kt()}}e.set(s.id,s),WC(s)&&Array.isArray(s.choices)&&(s={...s,choices:t(s.choices)}),i.push(s)}return i};return t(r)}function i1(r){if(!Array.isArray(r))return{choices:[],changed:!1,repaired:[]};let e=new Set,t=[],n=o=>{let s=!1,a=[];for(let l of o){if(Array.isArray(l)){s=!0,a.push(...n(l));continue}if(!Ue(l)){s=!0;continue}let c=l;if(ml(c)){let p=c.choices,f=n(p);f!==p&&(c={...c,choices:f},s=!0)}let u=c.id;if(typeof u=="string"&&u!==""&&!e.has(u)){e.add(u),a.push(c);continue}let d={...c,id:Kt()};e.add(d.id),t.push({previousId:u,choice:d}),a.push(d),s=!0}return s?a:o},i=n(r);return{choices:i,changed:i!==r,repaired:t}}function av(r,e=[],t=0,n=null){let i=[];for(let o of Lr(r)){if(!Ue(o))continue;let s=[...e,o.name];i.push({choice:o,id:o.id,path:s,depth:t,parentId:n}),i.push(...av(et(o),s,t+1,o.id))}return i}var bt=E(()=>{sv();Ss();sv()});function Ic(r){return Array.isArray?Array.isArray(r):v1(r)==="[object Array]"}function pK(r){if(typeof r=="string")return r;if(typeof r=="bigint")return r.toString();let e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function kI(r){return r==null?"":pK(r)}function ni(r){return typeof r=="string"}function GC(r){return typeof r=="number"}function fK(r){return r===!0||r===!1||mK(r)&&v1(r)=="[object Boolean]"}function g1(r){return typeof r=="object"}function mK(r){return g1(r)&&r!==null}function ao(r){return r!=null}function jC(r){return!r.trim().length}function v1(r){return r==null?r===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(r)}function y1(r){let e=null,t=null,n=null,i=1,o=null;if(ni(r)||Ic(r))n=r,e=u1(r),t=YC(r);else{if(!c1.call(r,"name"))throw new Error(yK("name"));let s=r.name;if(n=s,c1.call(r,"weight")&&r.weight!==void 0&&(i=r.weight,i<=0))throw new Error(bK(YC(s)));e=u1(s),t=YC(s),o=r.getFn??null}return{path:e,id:t,weight:i,src:n,getFn:o}}function u1(r){return Ic(r)?r:r.split(".")}function YC(r){return Ic(r)?r.join("."):r}function xK(r,e){let t=[],n=!1,i=(o,s,a,l)=>{if(ao(o))if(!s[a])t.push(l!==void 0?{v:o,i:l}:o);else{let c=o[s[a]];if(!ao(c))return;if(a===s.length-1&&(ni(c)||GC(c)||fK(c)||typeof c=="bigint"))t.push(l!==void 0?{v:kI(c),i:l}:kI(c));else if(Ic(c)){n=!0;for(let u=0,d=c.length;u<d;u+=1)i(c[u],s,a+1,u)}else s.length&&i(c,s,a+1,l)}};return i(r,ni(e)?e.split("."):e,0),n?t:t[0]}function _K(r){return r>=9&&r<=13||r===32||r===160}function AK(r=1,e=3){let t=new Map,n=Math.pow(10,e);return{get(i){let o=0,s=!1;for(let l=0;l<i.length;l++)_K(i.charCodeAt(l))?s=!1:s||(o++,s=!0);if(o===0&&(o=1),t.has(o))return t.get(o);let a=Math.round(n/Math.pow(o,.5*r))/n;return t.set(o,a),a},clear(){t.clear()}}}function b1(r,e,{getFn:t=tt.getFn,fieldNormWeight:n=tt.fieldNormWeight}={}){let i=new MI({getFn:t,fieldNormWeight:n});return i.setKeys(r.map(y1)),i.setSources(e),i.create(),i}function IK(r,{getFn:e=tt.getFn,fieldNormWeight:t=tt.fieldNormWeight}={}){let{keys:n,records:i}=r,o=new MI({getFn:e,fieldNormWeight:t});return o.setKeys(n),o.setIndexRecords(i),o}function DK(r=[],e=tt.minMatchCharLength){let t=[],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>=e&&t.push([n,i]),n=-1)}return r[o-1]&&o-n>=e&&t.push([n,o-1]),t}function FK(r,e,t,{location:n=tt.location,distance:i=tt.distance,threshold:o=tt.threshold,findAllMatches:s=tt.findAllMatches,minMatchCharLength:a=tt.minMatchCharLength,includeMatches:l=tt.includeMatches,ignoreLocation:c=tt.ignoreLocation}={}){if(e.length>32)throw new Error(vK(32));let u=e.length,d=r.length,p=Math.max(0,Math.min(n,d)),f=o,m=p,g=(D,P)=>{let U=D/u;if(c)return U;let K=Math.abs(p-P);return i?U+K/i:K?1:U},v=a>1||l,y=v?Array(d):[],b;for(;(b=r.indexOf(e,m))>-1;){let D=g(0,b);if(f=Math.min(D,f),m=b+u,v){let P=0;for(;P<u;)y[b+P]=1,P+=1}}m=-1;let x=[],w=1,T=0,C=u+d,S=1<<u-1;for(let D=0;D<u;D+=1){let P=0,U=C;for(;P<U;)g(D,p+U)<=f?P=U:C=U,U=Math.floor((C-P)/2+P);C=U;let K=Math.max(1,p-U+1),W=s?d:Math.min(p+U,d)+u,ee=Array(W+2);ee[W+1]=(1<<D)-1;for(let me=W;me>=K;me-=1){let O=me-1,H=t[r[O]];if(ee[me]=(ee[me+1]<<1|1)&H,D&&(ee[me]|=(x[me+1]|x[me])<<1|1|x[me+1]),ee[me]&S&&(w=g(D,O),w<=f)){if(f=w,m=O,T=D,m<=p)break;K=Math.max(1,2*p-m)}}if(g(D+1,p)>f)break;x=ee}if(v&&m>=0){let D=Math.min(d-1,m+u-1+T);for(let P=m;P<=D;P+=1)t[r[P]]&&(y[P]=1)}let A={isMatch:m>=0,score:Math.max(.001,w)};if(v){let D=DK(y,a);D.length?l&&(A.indices=D):A.isMatch=!1}return A}function PK(r){let e={};for(let t=0,n=r.length;t<n;t+=1){let i=r.charAt(t);e[i]=(e[i]||0)|1<<n-t-1}return e}function $I(r){if(r.length<=1)return r;r.sort((t,n)=>t[0]-n[0]||t[1]-n[1]);let e=[r[0]];for(let t=1,n=r.length;t<n;t+=1){let i=e[e.length-1],o=r[t];o[0]<=i[1]+1?i[1]=Math.max(i[1],o[1]):e.push(o)}return e}function OK(r){return r.startsWith("inverse")}function LK(r){let e=[],t=r.length,n=0;for(;n<t;){for(;n<t&&r[n]===" ";)n++;if(n>=t)break;let i=n;for(;i<t&&r[i]!==" "&&r[i]!=='"';)i++;if(i<t&&r[i]==='"'){for(i++;i<t;){if(r[i]==='"'){let o=i+1;if(o>=t||r[o]===" "){i++;break}if(r[o]==="$"&&(o+1>=t||r[o+1]===" ")){i+=2;break}}i++}e.push(r.substring(n,i)),n=i}else{for(;i<t&&r[i]!==" ";)i++;e.push(r.substring(n,i)),n=i}}return e}function p1(r,e){let t=r.match(e);return t?t[1]:null}function VK(r,e={}){return r.replace(/\\\|/g,RK).split(NK).map(t=>{let n=LK(t.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<d1;){let u=_I[c],d=p1(a,u.multiRegex);d&&(i.push(u.create(d,e)),l=!0)}if(!l)for(c=-1;++c<d1;){let u=_I[c],d=p1(a,u.singleRegex);if(d){i.push(u.create(d,e));break}}}return i})}function RI(...r){AI.push(...r)}function KC(r,e){for(let t=0,n=AI.length;t<n;t+=1){let i=AI[t];if(i.condition(r,e))return new i(r,e)}return new OI(r,e)}function C1(r,e,{auto:t=!0}={}){let n=i=>{if(ni(i)){let l={keyId:null,pattern:i};return t&&(l.searcher=KC(i,e)),l}let o=Object.keys(i),s=qK(i);if(!s&&o.length>1&&!DI(i))return n(f1(i));if(UK(i)){let l=s?i[II.PATH]:o[0],c=s?i[II.PATTERN]:i[l];if(!ni(c))throw new Error(gK(l));let u={keyId:YC(l),pattern:c};return t&&(u.searcher=KC(c,e)),u}let a={children:[],operator:o[0]};return o.forEach(l=>{let c=i[l];Ic(c)&&c.forEach(u=>{a.children.push(n(u))})}),a};return DI(r)||(r=f1(r)),n(r)}function FI(r,{ignoreFieldNorm:e=tt.ignoreFieldNorm}){let t=1;return r.forEach(({key:n,norm:i,score:o})=>{let s=n?n.weight:null;t*=Math.pow(o===0&&s?Number.EPSILON:o,(s||1)*(e?1:i))}),t}function HK(r,{ignoreFieldNorm:e=tt.ignoreFieldNorm}){r.forEach(t=>{t.score=FI(t.matches,{ignoreFieldNorm:e})})}function WK(r){let e=[];return r.matches.forEach(t=>{if(!ao(t.indices)||!t.indices.length)return;let n={indices:t.indices,value:t.value};t.key&&(n.key=t.key.id),t.idx>-1&&(n.refIndex=t.idx),e.push(n)}),e}function jK(r,e,{includeMatches:t=tt.includeMatches,includeScore:n=tt.includeScore}={}){return r.map(i=>{let{idx:o}=i,s={item:e[o],refIndex:o};return t&&(s.matches=WK(i)),n&&(s.score=i.score),s})}function YK(r){m1.has(r)||(m1.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 KK(r){if(typeof r=="function"){let e=!1;return t=>{let n=r(t);if(!e&&(e=!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||YK(r),e=>e.match(r)||[]):e=>e.match(GK)||[]}function PI({isCaseSensitive:r=!1,ignoreDiacritics:e=!1,tokenize:t}={}){let n=KK(t);return{tokenize(i){return r||(i=i.toLowerCase()),e&&(i=lv(i)),n(i)}}}function TI(r,e,t,n){let i=n.tokenize(e);if(!i.length)return;r.fieldCount++,r.docFieldCount.set(t,(r.docFieldCount.get(t)||0)+1);let o=new Set(i),s=r.docTermFieldHits.get(t);s||(s=new Map,r.docTermFieldHits.set(t,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 x1(r,e,t,n){let{i,v:o,$:s}=e;if(o!==void 0){TI(r,o,i,n);return}if(s)for(let a=0;a<t;a++){let l=s[a];if(l)if(Array.isArray(l))for(let c of l)TI(r,c.v,i,n);else TI(r,l.v,i,n)}}function XK(r,e,t){let n={fieldCount:0,df:new Map,docFieldCount:new Map,docTermFieldHits:new Map};for(let i of r)x1(n,i,e,t);return n}function ZK(r,e,t,n){x1(r,e,t,n)}function JK(r,e){let t=r.docFieldCount.get(e);if(t===void 0)return;r.fieldCount-=t,r.docFieldCount.delete(e);let n=r.docTermFieldHits.get(e);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(e)}}function h1(r,e){if(e.length===0)return;let t=Array.from(new Set(e)).sort((a,l)=>a-l);for(let a of t)JK(r,a);let n=a=>{let l=0,c=t.length;for(;l<c;){let u=l+c>>>1;t[u]<a?l=u+1:c=u}return a-l},i=t[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 hK,SI,gK,vK,yK,bK,wK,c1,CK,EK,TK,kK,SK,tt,MI,w1,MK,lv,OI,$K,_I,d1,RK,NK,BK,AI,QC,II,DI,qK,UK,f1,zK,GK,m1,QK,Dc,Fc,XC=E(()=>{hK="Incorrect 'index' type",SI="Invalid doc index: must be a non-negative integer within the bounds of the docs array",gK=r=>`Invalid value for key ${r}`,vK=r=>`Pattern length exceeds max of ${r}.`,yK=r=>`Missing ${r} property in key`,bK=r=>`Property 'weight' in key '${r}' must be a positive integer`,wK="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.",c1=Object.prototype.hasOwnProperty,CK=class{constructor(r){this._keys=[],this._keyMap={};let e=0;r.forEach(t=>{let n=y1(t);this._keys.push(n),this._keyMap[n.id]=n,e+=n.weight}),this._keys.forEach(t=>{t.weight/=e})}get(r){return this._keyMap[r]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};EK={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},TK={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(r,e)=>r.score===e.score?r.idx<e.idx?-1:1:r.score<e.score?-1:1},kK={location:0,threshold:.6,distance:100},SK={useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:"any",getFn:xK,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1},tt=Object.freeze({...TK,...EK,...kK,...SK});MI=class{constructor({getFn:r=tt.getFn,fieldNormWeight:e=tt.fieldNormWeight}={}){this.norm=AK(e,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((e,t)=>{this._keysMap[e.id]=t})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;let r=this.docs.length;this.records=new Array(r);let e=0;if(ni(this.docs[0]))for(let t=0;t<r;t++){let n=this._createStringRecord(this.docs[t],t);n&&(this.records[e++]=n)}else for(let t=0;t<r;t++)this.records[e++]=this._createObjectRecord(this.docs[t],t);this.records.length=e,this.norm.clear()}add(r,e){if(!Number.isInteger(e)||e<0)throw new Error(SI);if(ni(r)){let n=this._createStringRecord(r,e);return n&&this.records.push(n),n}let t=this._createObjectRecord(r,e);return this.records.push(t),t}removeAt(r){if(!Number.isInteger(r)||r<0)throw new Error(SI);for(let e=0,t=this.records.length;e<t;e+=1)if(this.records[e].i===r){this.records.splice(e,1);break}for(let e=0,t=this.records.length;e<t;e+=1)this.records[e].i>r&&(this.records[e].i-=1)}removeAll(r){let e=new Set;for(let n of r)Number.isInteger(n)&&n>=0&&e.add(n);if(e.size===0)return;this.records=this.records.filter(n=>!e.has(n.i));let t=Array.from(e).sort((n,i)=>n-i);for(let n of this.records){let i=0,o=t.length;for(;i<o;){let s=i+o>>>1;t[s]<n.i?i=s+1:o=s}n.i-=i}}getValueForItemAtKeyId(r,e){return r[this._keysMap[e]]}size(){return this.records.length}_createStringRecord(r,e){return!ao(r)||jC(r)?null:{v:r,i:e,n:this.norm.get(r)}}_createObjectRecord(r,e){let t={i:e,$:{}};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(ao(s)){if(Ic(s)){let a=[];for(let l=0,c=s.length;l<c;l+=1){let u=s[l];if(ao(u)){if(ni(u)){if(!jC(u)){let d={v:u,i:l,n:this.norm.get(u)};a.push(d)}}else if(ao(u.v)){let d=ni(u.v)?u.v:kI(u.v);if(!jC(d)){let p={v:d,i:u.i,n:this.norm.get(d)};a.push(p)}}}}t.$[n]=a}else if(ni(s)&&!jC(s)){let a={v:s,n:this.norm.get(s)};t.$[n]=a}}}return t}toJSON(){return{keys:this.keys.map(({getFn:r,...e})=>e),records:this.records}}};w1={\u0142:"l",\u0141:"L",\u0111:"d",\u0110:"D",\u00F8:"o",\u00D8:"O",\u0127:"h",\u0126:"H",\u0167:"t",\u0166:"T",\u0131:"i",\u00DF:"ss"},MK=new RegExp("["+Object.keys(w1).join("")+"]","g"),lv=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(MK,e=>w1[e]):r=>r,OI=class{constructor(r,{location:e=tt.location,threshold:t=tt.threshold,distance:n=tt.distance,includeMatches:i=tt.includeMatches,findAllMatches:o=tt.findAllMatches,minMatchCharLength:s=tt.minMatchCharLength,isCaseSensitive:a=tt.isCaseSensitive,ignoreDiacritics:l=tt.ignoreDiacritics,ignoreLocation:c=tt.ignoreLocation}={}){if(this.options={location:e,threshold:t,distance:n,includeMatches:i,findAllMatches:o,minMatchCharLength:s,isCaseSensitive:a,ignoreDiacritics:l,ignoreLocation:c},r=a?r:r.toLowerCase(),r=l?lv(r):r,this.pattern=r,this.chunks=[],!this.pattern.length)return;let u=(p,f)=>{this.chunks.push({pattern:p,alphabet:PK(p),startIndex:f})},d=this.pattern.length;if(d>32){let p=0,f=d%32,m=d-f;for(;p<m;)u(this.pattern.substr(p,32),p),p+=32;if(f){let g=d-32;u(this.pattern.substr(g),g)}}else u(this.pattern,0)}searchIn(r){let{isCaseSensitive:e,ignoreDiacritics:t,includeMatches:n}=this.options;if(r=e?r:r.toLowerCase(),r=t?lv(r):r,this.pattern===r){if(r.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};let m={isMatch:!0,score:0};return n&&(m.indices=[[0,r.length-1]]),m}let{location:i,distance:o,threshold:s,findAllMatches:a,minMatchCharLength:l,ignoreLocation:c}=this.options,u=[],d=0,p=!1;this.chunks.forEach(({pattern:m,alphabet:g,startIndex:v})=>{let{isMatch:y,score:b,indices:x}=FK(r,m,g,{location:i+v,distance:o,threshold:s,findAllMatches:a,minMatchCharLength:l,includeMatches:n,ignoreLocation:c});y&&(p=!0),d+=b,y&&x&&u.push(...x)});let f={isMatch:p,score:p?d/this.chunks.length:1};return p&&n&&(f.indices=$I(u)),f}},$K=new Set(["fuzzy","include"]);_I=[{type:"exact",multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:r=>({type:"exact",search(e){let t=e===r;return{isMatch:t,score:t?0:1,indices:[0,r.length-1]}}})},{type:"include",multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:r=>({type:"include",search(e){let t=0,n,i=[],o=r.length;for(;(n=e.indexOf(r,t))>-1;)t=n+o,i.push([n,t-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(e){let t=e.startsWith(r);return{isMatch:t,score:t?0:1,indices:[0,r.length-1]}}})},{type:"inverse-prefix-exact",multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:r=>({type:"inverse-prefix-exact",search(e){let t=!e.startsWith(r);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}})},{type:"inverse-suffix-exact",multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:r=>({type:"inverse-suffix-exact",search(e){let t=!e.endsWith(r);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}})},{type:"suffix-exact",multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:r=>({type:"suffix-exact",search(e){let t=e.endsWith(r);return{isMatch:t,score:t?0:1,indices:[e.length-r.length,e.length-1]}}})},{type:"inverse-exact",multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:r=>({type:"inverse-exact",search(e){let t=e.indexOf(r)===-1;return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}})},{type:"fuzzy",multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(r,e={})=>{let t=new OI(r,{location:e.location??tt.location,threshold:e.threshold??tt.threshold,distance:e.distance??tt.distance,includeMatches:e.includeMatches??tt.includeMatches,findAllMatches:e.findAllMatches??tt.findAllMatches,minMatchCharLength:e.minMatchCharLength??tt.minMatchCharLength,isCaseSensitive:e.isCaseSensitive??tt.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics??tt.ignoreDiacritics,ignoreLocation:e.ignoreLocation??tt.ignoreLocation});return{type:"fuzzy",search(n){return t.searchIn(n)}}}}],d1=_I.length,RK="\0",NK="|";BK=class{constructor(r,{isCaseSensitive:e=tt.isCaseSensitive,ignoreDiacritics:t=tt.ignoreDiacritics,includeMatches:n=tt.includeMatches,minMatchCharLength:i=tt.minMatchCharLength,ignoreLocation:o=tt.ignoreLocation,findAllMatches:s=tt.findAllMatches,location:a=tt.location,threshold:l=tt.threshold,distance:c=tt.distance}={}){this.query=null,this.options={isCaseSensitive:e,ignoreDiacritics:t,includeMatches:n,minMatchCharLength:i,findAllMatches:s,ignoreLocation:o,location:a,threshold:l,distance:c},r=e?r:r.toLowerCase(),r=t?lv(r):r,this.pattern=r,this.query=VK(this.pattern,this.options)}static condition(r,e){return e.useExtendedSearch}searchIn(r){let e=this.query;if(!e)return{isMatch:!1,score:1};let{includeMatches:t,isCaseSensitive:n,ignoreDiacritics:i}=this.options;r=n?r:r.toLowerCase(),r=i?lv(r):r;let o=0,s=[],a=0,l=!1;for(let c=0,u=e.length;c<u;c+=1){let d=e[c];s.length=0,o=0,l=!1;for(let p=0,f=d.length;p<f;p+=1){let m=d[p],{isMatch:g,indices:v,score:y}=m.search(r);if(g)o+=1,a+=y,OK(m.type)&&(l=!0),t&&($K.has(m.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),t&&(p.indices=$I(s)),p}}return{isMatch:!1,score:1}}},AI=[];QC={AND:"$and",OR:"$or"},II={PATH:"$path",PATTERN:"$val"},DI=r=>!!(r[QC.AND]||r[QC.OR]),qK=r=>!!r[II.PATH],UK=r=>!Ic(r)&&g1(r)&&!DI(r),f1=r=>({[QC.AND]:Object.keys(r).map(e=>({[e]:r[e]}))});zK=class{constructor(r,e){this.limit=r,this.heap=[],this.comparator=e}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 e=this.heap;for(;r>0;){let t=r-1>>1;if(this.comparator(e[r],e[t])<=0)break;let n=e[r];e[r]=e[t],e[t]=n,r=t}}_sinkDown(r){let e=this.heap,t=e.length,n=r;do{r=n;let i=2*r+1,o=2*r+2;if(i<t&&this.comparator(e[i],e[n])>0&&(n=i),o<t&&this.comparator(e[o],e[n])>0&&(n=o),n!==r){let s=e[r];e[r]=e[n],e[n]=s}}while(n!==r)}};GK=/[\p{L}\p{M}\p{N}_]+/gu,m1=new WeakSet;QK=class{static condition(r,e){return e.useTokenSearch}constructor(r,e){this.options=e,this.analyzer=PI({isCaseSensitive:e.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics,tokenize:e.tokenize});let t=this.analyzer.tokenize(r),{df:n,fieldCount:i}=e._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(let o of t){this.termSearchers.push(new OI(o,{location:e.location,threshold:e.threshold,distance:e.distance,includeMatches:e.includeMatches,findAllMatches:e.findAllMatches,minMatchCharLength:e.minMatchCharLength,isCaseSensitive:e.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics,ignoreLocation:!0}));let s=n.get(o)||0,a=Math.log(1+(i-s+.5)/(s+.5));this.idfWeights.push(a)}this.combineAll=e.tokenMatch==="all",this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(r){if(!this.termSearchers.length)return{isMatch:!1,score:1};let e=[],t=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 u=this.termSearchers[c].searchIn(r),d=this.idfWeights[c];n+=d,u.isMatch&&(i++,t+=d*(1-u.score),u.indices&&e.push(...u.indices),this.combineAll&&(this.useMask?o|=1<<c:s.add(c)))}if(i===0)return{isMatch:!1,score:1};let a=n>0?1-t/n:0,l={isMatch:!0,score:Math.max(.001,a)};return this.options.includeMatches&&e.length&&(l.indices=$I(e)),this.combineAll&&(this.useMask?l.matchedMask=o:l.matchedTerms=s,l.termCount=this.numTerms),l}};Dc=class{constructor(r,e,t){this.options={...tt,...e},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new CK(this.options.keys),this._docs=r,this._myIndex=null,this._invertedIndex=null,this.setCollection(r,t),this._lastQuery=null,this._lastSearcher=null}_getSearcher(r){if(this._lastQuery===r)return this._lastSearcher;let e=KC(r,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=r,this._lastSearcher=e,e}setCollection(r,e){if(this._docs=r,e&&!(e instanceof MI))throw new Error(hK);if(this._myIndex=e||b1(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){let t=PI({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=XK(this._myIndex.records,this._myIndex.keys.length,t)}this._invalidateSearcherCache()}add(r){if(!ao(r))return;this._docs.push(r);let e=this._myIndex.add(r,this._docs.length-1);if(this._invertedIndex&&e){let t=PI({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});ZK(this._invertedIndex,e,this._myIndex.keys.length,t)}this._invalidateSearcherCache()}remove(r=()=>!1){let e=[],t=[];for(let n=0,i=this._docs.length;n<i;n+=1)r(this._docs[n],n)&&(e.push(this._docs[n]),t.push(n));if(t.length){this._invertedIndex&&h1(this._invertedIndex,t);let n=new Set(t);this._docs=this._docs.filter((i,o)=>!n.has(o)),this._myIndex.removeAll(t),this._invalidateSearcherCache()}return e}removeAt(r){if(!Number.isInteger(r)||r<0||r>=this._docs.length)throw new Error(SI);this._invertedIndex&&h1(this._invertedIndex,[r]);let e=this._docs.splice(r,1)[0];return this._myIndex.removeAt(r),this._invalidateSearcherCache(),e}_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,e){let{limit:t=-1}=e||{},{includeMatches:n,includeScore:i,shouldSort:o,sortFn:s,ignoreFieldNorm:a}=this.options;if(ni(r)&&!r.trim()){let p=this._docs.map((f,m)=>({item:f,refIndex:m}));return GC(t)&&t>-1&&(p=p.slice(0,t)),p}let l=o&&GC(t)&&t>0&&ni(r),c=s,u=(p,f)=>c(p,f)||p.idx-f.idx,d;if(l){let p=new zK(t,u);ni(this._docs[0])?this._searchStringList(r,{heap:p,ignoreFieldNorm:a}):this._searchObjectList(r,{heap:p,ignoreFieldNorm:a}),d=p.extractSorted()}else d=ni(r)?ni(this._docs[0])?this._searchStringList(r):this._searchObjectList(r):this._searchLogical(r),HK(d,{ignoreFieldNorm:a}),o&&d.sort(ni(r)?u:c),GC(t)&&t>-1&&(d=d.slice(0,t));return jK(d,this._docs,{includeMatches:n,includeScore:i})}_searchStringList(r,{heap:e,ignoreFieldNorm:t}={}){let n=this._getSearcher(r),i=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:o}=this._myIndex,s=e?null:[];return o.forEach(({v:a,i:l,n:c})=>{if(!ao(a))return;let u=n.searchIn(a);if(u.isMatch){let d={score:u.score,value:a,norm:c,indices:u.indices};i&&(d.matchedMask=u.matchedMask,d.matchedTerms=u.matchedTerms,d.termCount=u.termCount);let p=[d];if(!i||this._coversAllTokens(p)){let f={item:a,idx:l,matches:p};e?(f.score=FI(f.matches,{ignoreFieldNorm:t}),e.insert(f)):s.push(f)}}}),s}_searchLogical(r){let e=C1(r,this.options),t=this._normalizedKeys(),n=(a,l,c)=>{if(!("children"in a)){let{keyId:f,searcher:m}=a,g;return f===null?(g=[],t.forEach((v,y)=>{g.push(...this._findMatches({key:v,value:l[y],searcher:m}))})):g=this._findMatches({key:this._keyStore.get(f),value:this._myIndex.getValueForItemAtKeyId(l,f),searcher:m}),g&&g.length?[{idx:c,item:l,matches:g}]:[]}let{children:u,operator:d}=a,p=[];for(let f=0,m=u.length;f<m;f+=1){let g=u[f],v=n(g,l,c);if(v.length)p.push(...v);else if(d===QC.AND)return[]}return p},i=this._myIndex.records,o=new Map,s=[];return i.forEach(({$:a,i:l})=>{if(ao(a)){let c=n(e,a,l);c.length&&(o.has(l)||(o.set(l,{idx:l,item:a,matches:[]}),s.push(o.get(l))),c.forEach(({matches:u})=>{o.get(l).matches.push(...u)}))}}),s}_searchObjectList(r,{heap:e,ignoreFieldNorm:t}={}){let n=this._getSearcher(r),i=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:o}=this._myIndex,s=this._normalizedKeys(),a=e?null:[];return o.forEach(({$:l,i:c})=>{if(!ao(l))return;let u=[],d=!1,p=!1;if(s.forEach((f,m)=>{let g=this._findMatches({key:f,value:l[m],searcher:n});g.length?(u.push(...g),g[0].hasInverse&&(p=!0)):d=!0}),!(p&&d)&&u.length&&(!i||this._coversAllTokens(u))){let f={idx:c,item:l,matches:u};e?(f.score=FI(f.matches,{ignoreFieldNorm:t}),e.insert(f)):a.push(f)}}),a}_findMatches({key:r,value:e,searcher:t}){if(!ao(e))return[];let n=[];if(Ic(e))e.forEach(({v:i,i:o,n:s})=>{if(!ao(i))return;let a=t.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}=e,s=t.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 e=r.length?r[0].termCount:void 0;if(e===void 0)return!0;if(e<=31){let n=0;for(let i=0;i<r.length;i++)n|=r[i].matchedMask||0;return n===2**e-1}let t=new Set;for(let n=0;n<r.length;n++){let i=r[n].matchedTerms;if(i)for(let o of i)t.add(o)}return t.size===e}};Dc.version="7.5.0";Dc.createIndex=b1;Dc.parseIndex=IK;Dc.config=tt;Dc.match=function(r,e,t){if(t&&t.useTokenSearch)throw new Error(wK);return KC(r,{...tt,...t}).searchIn(e)};Dc.parseQuery=C1;RI(BK);RI(QK);Dc.use=function(...r){r.forEach(e=>RI(e))};Fc=Dc});function eQ(r){if(!r)return[];let e=[];for(let[t,n]of Object.entries(r)){let i=t.toLowerCase();if(i!=="alias"&&i!=="aliases")continue;let o=typeof n=="string"?n.split(","):n;Array.isArray(o)&&e.push(...o.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean))}return e}function E1(r,e,t){let n=r.metadataCache.getFileCache(e),i=n?.frontmatter,o=eQ(i),s=o.map(u=>tr(u)),a=(n?.headings??[]).map(u=>CI(u.heading)),l=[];if(n?.blocks)for(let u of Object.values(n.blocks))u.id&&l.push(u.id);let c=n?.tags?.map(u=>u.tag)??[];if(i?.tags){let u=Array.isArray(i.tags)?i.tags:[i.tags];c.push(...u.filter(d=>typeof d=="string"))}return{path:e.path,pathNormalized:tr(e.path),basename:e.basename,basenameNormalized:tr(e.basename),aliases:o,aliasesNormalized:s,headings:a,blockIds:l,tags:c,modified:e.stat.mtime,openedAt:t,folder:e.parent?.path??""}}var T1=E(()=>{rn()});function k1(r,e,t,n,i,o,s){let a=n;if(t.currentFolder&&r.folder===t.currentFolder&&(a+=i.boosts.sameFolder),r.openedAt&&(Date.now()-r.openedAt)/864e5<i.thresholds.recencyDays&&(a+=i.boosts.recency),t.currentFile&&o){let f=r.tags.filter(m=>o.tags.includes(m));f.length>0&&(a+=i.boosts.tagOverlap*Math.min(f.length,Math.abs(i.boosts.tagOverlapMax/i.boosts.tagOverlap)))}let l=tr(e),c=s==="alias"&&r.aliases.length>0?r.aliasesNormalized.findIndex(f=>f.includes(l)):-1,u=c>=0?r.aliases[c].length:r.basename.length;if(s==="alias"){let f=Math.max(0,(u-i.penalties.titleLengthThreshold)*i.penalties.aliasLengthMultiplier),m=Math.min(i.penalties.aliasMaxPenalty,i.penalties.aliasMinPenalty+f);a+=m}u>i.penalties.titleLengthThreshold&&(a+=(u-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 ZC,NI=E(()=>{rn();ZC={base:{basenameExact:-1e3,aliasExact:-900,basenamePrefix:-500,aliasPrefix:-500,substringBasename:-300,fuzzyMatch:0,unresolvedLink:1e3},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 cv,LI,tQ,rQ,nQ,gf,VI=E(()=>{cv=require("obsidian");XC();T1();NI();NI();rn();LI=class{constructor(e=100){this.cache=new Map;this.maxSize=e}peek(e){return this.cache.get(e)}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;this.cache.delete(n)}this.cache.set(e,t)}clear(){this.cache.clear()}},tQ=20,rQ=100,nQ=/\w/,gf=class r{constructor(e,t){this.fileMap=new Map;this.recentFiles=new LI;this.unresolvedLinks=new Set;this.unresolvedLinksDirty=!0;this.isIndexing=!1;this.indexPromise=null;this.reindexTimeout=null;this.fuseUpdateTimeout=null;this.pendingFuseUpdates=new Map;this.reindexBuffer=null;this.effectiveWeights=ZC;this.app=e,this.plugin=t;let n={keys:[{name:"basenameNormalized",weight:.8},{name:"aliasesNormalized",weight:.6},{name:"pathNormalized",weight:.2}],ignoreLocation:!0,findAllMatches:!0,shouldSort:!1,includeMatches:!0};this.fuseStrict=new Fc([],{...n,threshold:.2}),this.fuseRelaxed=new Fc([],{...n,threshold:.4}),this.setupEventListeners(),this.effectiveWeights=ZC}static getInstance(e,t){return r.instance||(r.instance=new r(e,t)),r.instance}static getInstanceIfExists(){return r.instance??void 0}getLastOpenedAt(e){return this.recentFiles.peek(e)}setupEventListeners(){this.plugin.registerEvent(this.app.workspace.on("file-open",e=>{if(e){this.recentFiles.set(e.path,Date.now());let t=this.fileMap.get(e.path);t&&(t.openedAt=Date.now())}})),this.plugin.registerEvent(this.app.metadataCache.on("changed",e=>{e instanceof cv.TFile&&e.extension==="md"&&this.updateFile(e)})),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",e=>{e instanceof cv.TFile&&e.extension==="md"&&this.addFile(e)})),this.plugin.registerEvent(this.app.vault.on("delete",e=>{e instanceof cv.TFile&&this.removeFile(e)})),this.plugin.registerEvent(this.app.vault.on("rename",(e,t)=>{e instanceof cv.TFile&&e.extension==="md"&&(this.removeFileByPath(t),this.addFile(e))}))}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 e=new Map;this.reindexBuffer=e;try{let t=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 u=this.createIndexedFile(c);n.set(c.path,u)}await new Promise(c=>window.setTimeout(c,0))}})(t),this.fileMap=n;for(let[o,s]of e)s.op==="remove"?this.fileMap.delete(o):s.file&&this.fileMap.set(o,this.createIndexedFile(s.file));this.updateFuseIndex(),this.updateUnresolvedLinks()}catch(t){try{this.updateFuseIndex()}catch{}throw t}finally{this.reindexBuffer=null}}createIndexedFile(e){return E1(this.app,e,this.recentFiles.peek(e.path))}addFile(e){this.upsertFile(e,"add")}updateFile(e){this.upsertFile(e,"update"),this.unresolvedLinksDirty=!0}upsertFile(e,t){this.fileMap.set(e.path,this.createIndexedFile(e)),this.scheduleFuseUpdate(e.path,t),this.reindexBuffer?.set(e.path,{op:"upsert",file:e})}removeFile(e){this.removeFileByPath(e.path)}removeFileByPath(e){this.fileMap.delete(e),this.scheduleFuseUpdate(e,"remove"),this.reindexBuffer?.set(e,{op:"remove"})}updateFuseIndex(){let e=Array.from(this.fileMap.values());this.fuseStrict.setCollection(e),this.fuseRelaxed.setCollection(e)}scheduleFuseUpdate(e,t){if(this.isIndexing)return;let n=this.pendingFuseUpdates.get(e);if(n==="add"&&t==="remove"){this.pendingFuseUpdates.delete(e);return}this.pendingFuseUpdates.set(e,n==="remove"&&t==="add"?"update":t),this.fuseUpdateTimeout!==null&&window.clearTimeout(this.fuseUpdateTimeout),this.fuseUpdateTimeout=window.setTimeout(()=>{this.processPendingFuseUpdates()},rQ)}processPendingFuseUpdates(){if(this.pendingFuseUpdates.size!==0){if(this.isIndexing){this.pendingFuseUpdates.clear();return}if(this.pendingFuseUpdates.size>tQ){this.updateFuseIndex(),this.pendingFuseUpdates.clear();return}for(let[e,t]of this.pendingFuseUpdates)for(let n of[this.fuseStrict,this.fuseRelaxed]){n.remove(o=>o.path===e);let i=t!=="remove"&&this.fileMap.get(e);i&&n.add(i)}this.pendingFuseUpdates.clear()}}updateUnresolvedLinks(){let e=this.app.metadataCache.unresolvedLinks;this.unresolvedLinks.clear();for(let t in e)for(let n in e[t])this.unresolvedLinks.add(n);this.unresolvedLinksDirty=!1}search(e,t={},n=50){if(this.unresolvedLinksDirty&&this.updateUnresolvedLinks(),e.includes("#"))return this.searchWithHeadings(e,t,n);let i=tr(e),o=this.matchFiles(e,t,n);if(e.length>=2){let s=0,a=e.length<3?10:20;for(let l of this.unresolvedLinks){if(s>=a)break;tr(l).includes(i)&&(o.push({file:{path:l,pathNormalized:tr(l),basename:l,basenameNormalized:tr(l),aliases:[],aliasesNormalized:[],headings:[],blockIds:[],tags:[],modified:0,folder:""},score:this.effectiveWeights.base.unresolvedLink,matchType:"unresolved",displayText:l}),s++)}}return o.sort((s,a)=>s.score-a.score).slice(0,n)}calculateScore(e,t,n,i,o){return k1(e,t,n,i,this.effectiveWeights,n.currentFile?this.fileMap.get(n.currentFile.path):void 0,o)}searchWithHeadings(e,t,n){let[i,o]=e.split("#"),s=tr(o??""),a=[];if(i===""){let l=0,c=200,u=Array.from(this.fileMap.values());for(let d of u){if(l>=c)break;for(let p of d.headings){if(l>=c)break;tr(p).includes(s)&&(a.push({file:d,score:this.calculateScore(d,e,t,.1),matchType:"heading",displayText:`${d.basename}#${p}`}),l++)}}}else{let l=this.searchFiles(i,t,n);if(l.length===0)return[];for(let c of l)for(let u of c.file.headings)tr(u).includes(s)&&a.push({file:c.file,score:c.score+.05,matchType:"heading",displayText:`${c.file.basename}#${u}`})}return a.sort((l,c)=>l.score-c.score).slice(0,n)}searchFiles(e,t,n){return this.matchFiles(e,t,n,{...this.effectiveWeights.base,basenameExact:-1e3,basenamePrefix:-500,aliasPrefix:-500,substringBasename:-300}).sort((i,o)=>i.score-o.score).slice(0,n)}matchFiles(e,t,n,i=this.effectiveWeights.base){let o=[],s=tr(e),a=new Set,l=Array.from(this.fileMap.values()),c=(d,p,f,m)=>{a.has(d.path)||(o.push({file:d,score:this.calculateScore(d,e,t,p,f),matchType:f,displayText:m}),a.add(d.path))};for(let d of l)d.basenameNormalized===s&&c(d,i.basenameExact,"exact",d.basename);for(let d of l){let p=d.aliasesNormalized.indexOf(s);p!==-1&&c(d,i.aliasExact,"alias",d.aliases[p])}for(let d of l)d.basenameNormalized.startsWith(s)&&c(d,i.basenamePrefix,"fuzzy",d.basename);for(let d of l){let p=d.aliasesNormalized.findIndex(f=>f.startsWith(s));p!==-1&&c(d,i.aliasPrefix,"alias",d.aliases[p])}for(let d of l){let p=d.basenameNormalized.indexOf(s);p>0&&!nQ.test(d.basenameNormalized[p-1])&&c(d,i.substringBasename,"fuzzy",d.basename)}let u=this.fuseStrict.search(s,{limit:n*2});u.length<this.effectiveWeights.thresholds.fuzzyRelaxCount&&(u=this.fuseRelaxed.search(s,{limit:n*2}));for(let d of u){if(!d||!d.item||!d.item.path||a.has(d.item.path))continue;let p=(d.matches??[]).find(v=>v.key==="aliasesNormalized"),f=!!p,m=f?"alias":"fuzzy",g=d.item.basename;if(f){let v=typeof p?.value=="string"?p.value:void 0,y=v?d.item.aliasesNormalized.findIndex(b=>b===v):d.item.aliasesNormalized.findIndex(b=>b.includes(s));y>=0&&(g=d.item.aliases[y])}c(d.item,(d.score??.5)+i.fuzzyMatch,m,g)}return o}getFile(e){return this.fileMap.get(e)}getHeadings(e){return e.headings}getBlockIds(e){return e.blockIds}getIndexedFileCount(){return this.fileMap.size}}});function S1(r){BI=r}function on(){if(!BI)throw new Error("QuickAdd plugin instance accessed before it was initialised.");return BI}var BI,_s=E(()=>{});function iQ(r,e){let t=er(r,"span");switch(t.classList.add("qa-suggestion-pill"),e){case"alias":return t.classList.add("qa-alias-pill"),t.textContent="alias",t;case"heading":return t.classList.add("qa-heading-pill"),t.textContent="H",t;case"block":return t.classList.add("qa-block-pill"),t.textContent="^",t;case"unresolved":return t.classList.add("qa-unresolved-pill"),t.textContent="unresolved",t;default:return null}}var JC,vf,qI=E(()=>{ks();JC=require("obsidian");Xe();VI();rn();_s();bs();vf=class extends xr{constructor(t,n,i){super(t,n);this.app=t;this.inputEl=n;this.lastInput="";this.sourcePathOverride=i?.sourcePath,this.fileIndex=gf.getInstance(t,on()),this.fileIndex.ensureIndexed()}normalizeFolderPath(t){return!t||t==="/"?"":t.replace(/\/+$/,"")}getSourcePath(){return this.sourcePathOverride??this.app.workspace.getActiveFile()?.path??""}getSourceFolder(){let t=this.getSourcePath();if(!t)return"";let n=this.app.fileManager.getNewFileParent(t);return this.normalizeFolderPath(n?.path)}resolveRelative(t,n){let i=this.normalizeFolderPath(t),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(t){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=t.slice(0,n),o=zR.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(),u=this.app.workspace.getActiveFile(),d={currentFile:this.sourcePathOverride?void 0:u??void 0,currentFolder:c};return this.fileIndex.search(s,d,50)}getHeadingSuggestions(t){let[n,i]=t.split("#"),o=n.trim()==="",s=tr(i??""),a=[];if(o){let c=this.app.workspace.getActiveFile();if(c){let u=this.fileIndex.getFile(c.path);u&&(a=[u])}}else a=this.fileIndex.search(n,{},1).map(c=>c.file);if(a.length===0)return[];let l=[];for(let c of a){let d=this.fileIndex.getHeadings(c).filter(p=>i===""||tr(p).includes(s)).slice(0,20);for(let p of d)l.push({file:c,score:0,matchType:"heading",displayText:o?`#${p}`:`${c.basename}#${p}`})}return l}getBlockSuggestions(t){let[n,i]=t.split("#^"),o=tr(i??""),s=this.fileIndex.search(n,{},1);if(s.length===0)return[];let a=s[0].file;return this.fileIndex.getBlockIds(a).filter(c=>i===""||tr(c).includes(o)).slice(0,20).map(c=>({file:a,score:0,matchType:"block",displayText:`${a.basename}#^${c}`}))}getRelativePathSuggestions(t){let n=this.getSourceFolder(),{folder:i,query:o}=this.resolveRelative(n,t);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(t){let n=this.app.vault.getFiles(),i=["png","jpg","jpeg","gif","svg","pdf","mp4","webm","mov","canvas"],o=tr(t);return n.filter(a=>i.includes(a.extension.toLowerCase())&&(t===""||tr(a.basename).includes(o))).slice(0,20).map(a=>({file:{path:a.path,pathNormalized:tr(a.path),basename:a.basename,basenameNormalized:tr(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(t,n){let{file:i,matchType:o,displayText:s}=t;n.classList.add("qaFileSuggestionItem"),n.classList.add(`qa-suggest-${o}`);let a=s,l="",c=!1,u="";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("#"),y=this.lastInput.includes("#")?this.lastInput.split("#")[1]:"",b=tr(y??"");y&&tr(v).includes(b)?(a=v,c=!0,u=y):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 d=er(n,"div");d.className="qa-suggestion-content";let p=er(n,"span");p.className="suggestion-main-text",c?this.renderMatch(p,a,u):p.textContent=a,d.appendChild(p);let f=iQ(n,o);f&&d.appendChild(f);let m=er(n,"span");m.className="suggestion-sub-text",m.textContent=l,n.replaceChildren(d,m),this.addHoverTooltip(n,i)}open(t,n){if(super.open(t,n),!this.scrollListener){let i=io(this.inputEl),o=()=>this.hideTooltip();i.addEventListener("scroll",o,{passive:!0}),this.scrollListener=o,this.scrollListenerDocument=i}}hideTooltip(){let t=io(this.inputEl);this.tooltipTimeout!==void 0&&(window.clearTimeout(this.tooltipTimeout),this.tooltipTimeout=void 0),t.querySelector(".qa-file-tooltip")?.remove()}addHoverTooltip(t,n){let i=io(t);t.addEventListener("mouseenter",()=>{this.hideTooltip(),this.tooltipTimeout=window.setTimeout(()=>{let o=this.createTooltip(n);o&&(i.body.appendChild(o),this.positionTooltip(o,t))},200)}),t.addEventListener("mouseleave",()=>this.hideTooltip()),t.addEventListener("blur",()=>this.hideTooltip())}createTooltip(t){let n=this.app.vault.getAbstractFileByPath(t.path);if(!n||!(n instanceof JC.TFile))return null;let i=this.inputEl,o=er(i,"div");o.className="qa-file-tooltip";let s=er(i,"div");s.className="qa-tooltip-header",s.textContent=n.basename;let a=er(i,"div");a.className="qa-tooltip-content";let l=er(i,"div");l.textContent=`Path: ${n.path}`;let c=er(i,"div");return c.textContent=`Modified: ${new Date(n.stat.mtime).toLocaleDateString()}`,a.append(l,c),o.append(s,a),o}positionTooltip(t,n){let i=n.getBoundingClientRect();t.style.left=`${i.right+10}px`,t.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(t){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)==="![["||t.matchType==="unresolved"||t.matchType==="heading"||t.matchType==="block"?void 0:this.app.vault.getAbstractFileByPath(t.file.path);c instanceof JC.TFile?s=this.makeLinkObsidianMethod(c,o,n,i,t.matchType==="alias"?t.displayText:void 0):s=this.makeLinkManually(o,t.matchType==="unresolved"?t.displayText.replace(/.md$/,""):t.displayText,n,i),this.inputEl.trigger("input"),this.close(),this.inputEl.setSelectionRange(s,s)}makeLinkObsidianMethod(t,n,i,o,s){let a=this.app.vault.getAbstractFileByPath(t.path);if(!(a instanceof JC.TFile))return this.makeLinkManually(n,t.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(t,n,i,o){return this.inputEl.value=this.getNewInputValueForFileName(t,n,i,o),i-o+n.length+2}getNewInputValueForFileLink(t,n,i,o){return`${t.slice(0,i-o-2)}${n}${t.slice(i)}`}getNewInputValueForFileName(t,n,i,o){return`${t.slice(0,i-o)}${n}]]${t.slice(i)}`}}});var _1,ex,A1=E(()=>{XC();_1={threshold:.4,includeScore:!0,keys:[""]},ex=class r{constructor(e,t){this.sortedTags=[];this.fuse=new Fc([],_1);this.app=e,this.refresh(),t.registerEvent(this.app.metadataCache.on("resolved",()=>this.refresh()))}static getInstance(e,t){return r.instance||(r.instance=new r(e,t)),r.instance}refresh(){let e=this.app.metadataCache.getTags(),t=Object.keys(e);this.sortedTags=t.sort((n,i)=>n.length!==i.length?n.length-i.length:n.localeCompare(i)),this.fuse=new Fc(this.sortedTags,_1)}getSortedTags(){return this.sortedTags}search(e){return this.fuse.search(e)}}});function oQ(r,e){let t=r.slice(0,e),n=t.lastIndexOf("[[");return n===-1?!1:t.lastIndexOf("]]")<n}var yf,UI=E(()=>{Xe();ks();rn();_s();A1();yf=class extends xr{constructor(t,n,i){super(t,n);this.app=t;this.inputEl=n;this.lastInput="";this.lastInputStart=0;this.lastInputLength=0;this.tagIndex=ex.getInstance(t,on()),i?.refreshIndex!==!1&&this.tagIndex.refresh()}getSuggestions(t){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=t.slice(0,n),o=WR.exec(i);if(!o)return[];if(o.index===void 0)return[];if(oQ(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(f=>f.replace(/^#/,"").toLowerCase().startsWith(l)).slice(0,5),u=this.tagIndex.search(s).filter(f=>f.score!==void 0&&f.score<.8).map(f=>f.item).slice(0,10),d=new Set(c),p=[...c];for(let f of u)!d.has(f)&&p.length<15&&(p.push(f),d.add(f));return p}renderSuggestion(t,n){this.renderMatch(n,t,this.lastInput)}selectSuggestion(t){let n=this.inputEl;if(n.selectionStart===null)return;let i=this.lastInputStart,o=i+this.lastInputLength,s=t.startsWith("#")?t:`#${t}`;HC(n,i,o,s,{fromCompletion:!0}),this.close()}}});var ii,bf=E(()=>{ii=class r{constructor(){this.drafts=new Map;this.pendingSubmittedDraftKeys=new Set;this.executionScopeDepth=0;this.executionScopeFailed=!1;this.MAX_ENTRIES=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}makeKey(e){return JSON.stringify({v:1,kind:e.kind,header:e.header,placeholder:e.placeholder??"",linkSourcePath:e.linkSourcePath??"",scopeId:e.scopeId??""})}get(e){let t=this.drafts.get(e);if(t)return t.timestamp=Date.now(),t.value}set(e,t){this.drafts.size>=this.MAX_ENTRIES&&!this.drafts.has(e)&&this.evictOldest(1),this.drafts.set(e,{value:t,timestamp:Date.now()})}handleSubmittedDraft(e,t){if(!this.hasActiveExecutionScope()){this.clear(e);return}this.set(e,t),this.pendingSubmittedDraftKeys.add(e)}beginExecutionScope(){this.executionScopeDepth+=1}commitExecutionScope(){if(this.hasActiveExecutionScope()&&(this.executionScopeDepth-=1,!(this.executionScopeDepth>0))){if(!this.executionScopeFailed)for(let e of this.pendingSubmittedDraftKeys)this.clear(e);this.resetExecutionScope()}}rollbackExecutionScope(){this.hasActiveExecutionScope()&&(this.executionScopeFailed=!0,this.executionScopeDepth-=1,this.executionScopeDepth===0&&this.resetExecutionScope())}markExecutionScopeFailed(){this.hasActiveExecutionScope()&&(this.executionScopeFailed=!0)}hasActiveExecutionScope(){return this.executionScopeDepth>0}clear(e){this.drafts.delete(e),this.pendingSubmittedDraftKeys.delete(e)}clearAll(){this.drafts.clear(),this.resetExecutionScope()}evictOldest(e){let t=Array.from(this.drafts.entries()).sort(([,n],[,i])=>n.timestamp-i.timestamp).slice(0,e);for(let[n]of t)this.drafts.delete(n),this.pendingSubmittedDraftKeys.delete(n)}resetExecutionScope(){this.pendingSubmittedDraftKeys.clear(),this.executionScopeDepth=0,this.executionScopeFailed=!1}}});var tx,I1=E(()=>{dt();bf();tx=class{constructor(e,t){this.store=ii.getInstance();this.initialValue="";this.didChange=!1;this.draftKey=this.store.makeKey(e),this.shouldPersist=t??(()=>X.getState().persistInputPromptDrafts)}hydrate(e){return this.initialValue=e,this.shouldPersist()?this.store.get(this.draftKey)??e:e}markChanged(){this.didChange=!0}persist(e,t){if(this.shouldPersist()){if(t){this.store.handleSubmittedDraft(this.draftKey,e);return}if(!(!this.didChange||e===this.initialValue)){if(!e.trim()){this.store.clear(this.draftKey);return}this.store.set(this.draftKey,e)}}}}});function D1(r,e){if(r.focus(),e?.cursorAtEnd){let t=r.value.length;r.setSelectionRange(t,t);return}r.select()}var F1=E(()=>{});function P1(r,e,t){let n=e?.trim();if(!n)return;let i=r.createDiv({text:n,cls:"qa-prompt-context"});return i.setAttr("title",t?.trim()||n),i}var M1=E(()=>{});var wf,uv,dv=E(()=>{Ie();wf=r=>{I.logWarning(r)},uv=()=>{}});function sQ(r,e){let t=Math.min(r.length,e.length),n=0;for(;n<t&&r[n]===e[n];)n++;return n}function $1(r,e,t){if(r===e)return 0;if(Math.abs(r.length-e.length)>t||r.length>64||e.length>64)return t+1;let n=[],i=Array.from({length:e.length+1},(s,a)=>a),o=[];for(let s=1;s<=r.length;s++){o=new Array(e.length+1),o[0]=s;let a=o[0];for(let l=1;l<=e.length;l++){let c=r[s-1]===e[l-1]?0:1,u=Math.min(i[l]+1,o[l-1]+1,i[l-1]+c);s>1&&l>1&&r[s-1]===e[l-2]&&r[s-2]===e[l-1]&&(u=Math.min(u,n[l-2]+1)),o[l]=u,u<a&&(a=u)}if(a>t)return t+1;n=i,i=o}return i[e.length]}function O1(r,e,t=3){let n=r.trim().toLowerCase();if(!n)return[];let i=e.map((a,l)=>({candidate:a,index:l})).filter(a=>a.candidate!==n),o=i.map(a=>({...a,distance:$1(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,t).map(a=>a.candidate);if(n.length>=2){let a=i.map(l=>({...l,shared:sQ(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,t).map(l=>l.candidate)}return i.map(a=>({...a,distance:$1(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,t).map(a=>a.candidate)}var R1=E(()=>{});function pv(r){let t=/^(\s*---\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)\s*(?:\r?\n|$))/.exec(r);return t?[0,t[0].length]:null}function fv(r,e,t,n){let[i,o]=n??[Number.NaN,Number.NaN];if(!(n!==null&&e>=i&&e<o))return{isInYaml:!1,isQuoted:!1,lineStart:0,lineEnd:0,baseIndent:"",isKeyValuePosition:!1,isListItemPosition:!1};let a=r.lastIndexOf(`
`,e-1)+1,l=r.indexOf(`
`,Math.max(e,t)),c=l===-1?r.length:l,u=r.slice(a,e),d=r.slice(t,c),p=(u.match(/^\s*/)||[""])[0],f=r[e-1]==='"'&&r[t]==='"'||r[e-1]==="'"&&r[t]==="'",m=u.replace(/["']$/,""),v=d.replace(/^["']/,"").replace(/\s+#.*$/,"").trim().length===0,y=/:\s*$/.test(m)&&v,b=/^\s*-\s*$/.test(m)&&v;return{isInYaml:!0,isQuoted:f,lineStart:a,lineEnd:c,baseIndent:p,isKeyValuePosition:y,isListItemPosition:b}}var HI=E(()=>{});function N1(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(aQ,e=>`\\x${e.charCodeAt(0).toString(16).padStart(2,"0")}`)}function mv(r){return`"${N1(r)}"`}function zI(r,e,t){let n=fv(r,e,t,pv(r));return!n.isInYaml||!n.isQuoted?!1:n.isKeyValuePosition||n.isListItemPosition}function Ed(r,e,t,n){return zI(r,e,t)?r[e-1]==='"'?N1(n):n.replace(/'/g,"''"):n}function WI(r,e,t){let n=fv(r,e,t,pv(r));return!n.isInYaml||n.isQuoted?!1:n.isKeyValuePosition||n.isListItemPosition}var aQ,rx=E(()=>{HI();aQ=new RegExp("[\0-\x7F]","g")});function nx(r,e,t){let n=r.trim().toLowerCase();if(lQ.has(n))return n;t?.(`QuickAdd: Unsupported multi-select format "${r}" in "${e}". Supported formats: auto, inline, spaced, yaml, markdown.`)}function cQ(r,e){let t=r.lastIndexOf(`
`,e-1)+1;return r.slice(t,e).match(/^\s*/)?.[0]??""}function uQ(r){return`- ${r.replace(/\r\n?|\n/g,`
`)}`}function L1(r){let{input:e,matchStart:t,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(mv).join(", ")}]`;case"markdown":{if(o.length===0)return"";let s=cQ(e,t);return o.map(uQ).join(`
${s}`)}default:return i}}var lQ,ix=E(()=>{rx();lQ=new Set(["auto","inline","spaced","yaml","markdown"])});function sx(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function pQ(r){let e=r.map(t=>`"${t}"`);return e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function V1(r,e){let t=sx(r,32),n=`{{FIELD:${sx(e,48)}}}`,i=dQ.get(r);if(i)return`Unknown FIELD filter "${t}" - ${i}. Ignored in ${n}.`;let o=O1(r,ox);return o.length>0?`Unknown FIELD filter "${t}" - did you mean ${pQ(o)}? Ignored in ${n}.`:`Unknown FIELD filter "${t}" in ${n} was ignored. Supported filters: ${ox.join(", ")}.`}function fQ(r,e){let t=sx(r,32);return`FIELD filter "${t}" needs a value - write "${t}:value". Ignored in {{FIELD:${sx(e,48)}}}.`}function mQ(r,e,t){(t.warn??wf)(V1(r,e))}var ox,dQ,oi,hl=E(()=>{dv();xc();R1();ix();ox=["folder","tag","inline","inline-code-blocks","exclude-folder","exclude-tag","exclude-file","default","default-from","default-empty","default-always","case-sensitive","multi","format"],dQ=new Map([["case-insensitive",'matching is already case-insensitive; use "case-sensitive:true" to match exactly']]);oi=class{static parse(e,t){let n=qo(e).map(c=>c.trim()),i=n[0],o={},s=!1,a="auto",l=!1;for(let c=1;c<n.length;c++){let u=n[c];if(u.toLowerCase()==="multi"){s=!0;continue}let d=Uo(u);if(!d){let m=u.toLowerCase();t?.warnUnknown&&m&&(t.warn??wf)(ox.includes(m)?fQ(m,e):V1(m,e));continue}let p=d.key,f=d.value;if(!ox.includes(p)){t?.warnUnknown&&mQ(p,e,t);continue}switch(p){case"multi":s=Cc(f);break;case"format":l=!0,a=nx(f,`{{FIELD:${e}}}`,t?.warn)??"auto";break;case"folder":o.folders??(o.folders=[]),o.folders.push(f),o.folder||(o.folder=f);break;case"tag":{o.tags??(o.tags=[]);let m=f.startsWith("#")?f.substring(1):f;o.tags.push(m);break}case"inline":o.inline=f.toLowerCase()==="true";break;case"inline-code-blocks":o.inlineCodeBlocks??(o.inlineCodeBlocks=[]),o.inlineCodeBlocks.push(...f.split(",").map(m=>m.trim().toLowerCase()).filter(m=>m.length>0));break;case"default":o.defaultValue=f;break;case"default-from":o.defaultFrom=f.toLowerCase();break;case"default-empty":o.defaultEmpty=f.toLowerCase()==="true";break;case"default-always":o.defaultAlways=f.toLowerCase()==="true";break;case"case-sensitive":o.caseSensitive=f.toLowerCase()==="true";break;case"exclude-folder":o.excludeFolders??(o.excludeFolders=[]),o.excludeFolders.push(f);break;case"exclude-tag":{o.excludeTags??(o.excludeTags=[]);let m=f.startsWith("#")?f.substring(1):f;o.excludeTags.push(m);break}case"exclude-file":o.excludeFiles??(o.excludeFiles=[]),o.excludeFiles.push(f);break}}return!s&&l&&(t?.warn?.(`QuickAdd: |format: needs |multi in "{{FIELD:${e}}}"; ignoring.`),a="auto"),{fieldName:i,filters:o,...s?{multiSelect:s}:{},...a!=="auto"?{multiFormat:a}:{}}}}});function jI(r){return r.replace(/^\/+|\/+$/g,"")}function hv(r,e=t=>t){return JSON.stringify([...r].map(e).sort())}function B1(r,e){let t=[`folder=${jI(r)}`];return e.folders?.length&&t.push(`folders=${hv(e.folders,jI)}`),e.tags?.length&&t.push(`tags=${hv(e.tags)}`),e.excludeFolders?.length&&t.push(`xfolder=${hv(e.excludeFolders,jI)}`),e.excludeTags?.length&&t.push(`xtag=${hv(e.excludeTags)}`),e.excludeFiles?.length&&t.push(`xfile=${hv(e.excludeFiles)}`),t.join("|")}function gQ(r){let{folderPath:e,mode:t,label:n,optional:i,allowCustomInput:o,multiSelect:s,filter:a}=r,l=[B1(e,a),`mode=${t}`];return n&&l.push(`label=${n}`),i&&l.push("optional"),o&&l.push("custom"),s&&l.push("multi"),l.join("|")}function ax(r,e){if(!r)return null;let t=qo(r),n=(t.shift()??"").trim();if(!n)return null;let i=t,o=ws(i,"optional");i=o.remaining;let s=o.found,a=ws(i,"custom");i=a.remaining;let l=a.found,c=ws(i,"multi");i=c.remaining;let u=c.found,d="name",p=[];for(let w of i){let T=w.trim().toLowerCase();if(hQ.has(T)){d=T;continue}p.push(w)}let f,m;for(let w of p){let T=Uo(w);T&&(T.key==="label"&&T.value?f=T.value:T.key==="name"&&T.value&&(m=T.value))}let g=oi.parse(r,{warn:e?.warn}),v=u||(g.multiSelect??!1),y=g.multiFormat??"auto",b={folder:n,tags:g.filters.tags,excludeFolders:g.filters.excludeFolders,excludeTags:g.filters.excludeTags,excludeFiles:g.filters.excludeFiles},x=m?`${gv}name=${m}|${B1(n,b)}${v?"|multi":""}`:`${gv}${gQ({folderPath:n,mode:d,label:f,optional:s,allowCustomInput:l,multiSelect:v,filter:b})}`;return{raw:r,folderPath:n,mode:d,label:f,aliasName:m,optional:s,allowCustomInput:l,filter:b,multiSelect:v,multiFormat:y,variableKey:x}}function q1(r,e){if(!r)return r;for(let t of e)if(r===t)return r;return`${As}${r}`}function Td(r){return typeof r!="string"||r===""?{kind:"empty"}:r.startsWith(As)?{kind:"custom",text:r.slice(As.length)}:r.startsWith(Pc)?{kind:"file",path:r.slice(Pc.length)}:{kind:"raw",value:r}}function Mc(r){return(r.split("/").pop()??r).replace(/\.(md|canvas|base)$/i,"")}function U1(r){return typeof r=="string"&&r.trim().length>0?r.trim():void 0}function vQ(r){if(!r)return;let e=Object.entries(r).find(([t])=>t.toLowerCase()==="title");return e?U1(e[1]):void 0}function yQ(r){let e=r?.headings?.find(t=>t.level===1);return U1(e?.heading)}function bQ(r){let e=r.parent?.path;return e&&e!=="/"?e:r.path.includes("/")?r.path.slice(0,r.path.lastIndexOf("/")):"vault root"}function wQ(r){return r.basename?r.basename:Mc(r.path)}function GI(r,e){let t=r.map(i=>{let o=e?.(i)??null,s=wQ(i),a=vQ(o?.frontmatter)??yQ(o)??s,l=a===s?s:`${a} (${s})`;return{file:i,primary:a,label:l}}),n=new Map;for(let{label:i}of t)n.set(i,(n.get(i)??0)+1);return t.map(({file:i,primary:o,label:s})=>{let a=(n.get(s)??0)<=1?s:`${s} - ${bQ(i)}`;return{primary:o,secondary:i.path,label:a}})}function $c(r,e){return GI(r,e).map(t=>t.label)}var gv,Pc,As,hQ,lo=E(()=>{hl();xc();gv="FILE:",Pc="@file:",As="@filecustom:",hQ=new Set(["name","link","path"])});function kd(r){return CQ.has(r.toUpperCase())}function YI(r){if(r.length===0||r==="."||r===".."||r.startsWith(".")||vv.test(r)||yv.test(r)||bv.test(r))return!1;let e=r.split(".")[0]??"";return e.length===0||!kd(e)}var vv,yv,bv,CQ,wv=E(()=>{vv=new RegExp("[\0-]","u"),yv=/[\\/:*?"<>|]/u,bv=/[. ]$/u,CQ=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 xQ(r){return(r??"").trim().replace(/\\/g,"/")}function EQ(r){return r.startsWith("/")||/^[a-zA-Z]:/.test(r)}function TQ(r){return r.split("/").some(e=>/^\.\.[. ]*$/u.test(e))}function Dr(r){let e=xQ(r);return e?EQ(e)||TQ(e):!1}var la=E(()=>{});function vl(r){return Object.hasOwn(gl,r)}function H1(r){let e=r.toLowerCase();return e==="jpeg"||Object.values(gl).includes(e)}function kQ(r){let e=t=>String(t).padStart(2,"0");return`${r.getFullYear()}-${e(r.getMonth()+1)}-${e(r.getDate())} ${e(r.getHours())}.${e(r.getMinutes())}.${e(r.getSeconds())}`}function _Q(r){return r.replace(SQ,"").replace(/\s+/g," ").replace(/[. ]+$/g,"").trim()}function lx(r){if(r.nameAfterNoteTitle){let e=_Q(Mc(r.sourcePath));if(e.length>0&&YI(e))return`${e}.${r.extension}`}return`Clipboard image ${kQ(r.now)}.${r.extension}`}function z1(r,e){if(!vl(r))throw new Error(`Unsupported clipboard image type: ${r}`);return lx({extension:gl[r],sourcePath:"",now:e,nameAfterNoteTitle:!1})}function W1(r){let e=r.split(/[\\/]/u).at(-1)??"",t=e.lastIndexOf("."),n=t>=0?e.slice(0,t):e;return YI(n)?n:null}async function KI(r,e,t,n,i){if(!vl(t))throw new Error(`Unsupported image type: ${t}`);let o=await r.fileManager.getAvailablePathForAttachment(i,n||void 0);if(Dr(o))throw new Error(`Refusing to save image outside the vault: '${o}'`);return r.vault.createBinary(o,e)}async function cx(r,e,t,n,i){if(!vl(t))throw new Error(`Unsupported clipboard image type: ${t}`);let o=i?.nameAfterNoteTitle??X.getState().namePastedImagesAfterNoteTitle;return KI(r,e,t,n,lx({extension:gl[t],sourcePath:n,now:i?.now??new Date,nameAfterNoteTitle:o}))}function ux(r,e,t){let n=r.fileManager.generateMarkdownLink(e,t);return n.startsWith("!")?n:`!${n}`}var gl,SQ,dx=E(()=>{dt();lo();wv();la();gl=Object.assign(Object.create(null),{"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg"});SQ=/[/\\:*?"<>|#^[\]]/g});function AQ(){let r=px.filter(t=>t.inputEl.isConnected);return r.find(t=>document.activeElement!==null&&t.inputEl.contains(document.activeElement))??r.at(-1)??null}function mx(r,e,t={}){let n=t.sourcePath??"",i=null,o=!1,s=!1,a=()=>{s=!0},l=()=>{s=!1},c=(y,b,x,w)=>{switch(x.kind){case"stand-down":return;case"take":if(b.preventDefault(),i){new Cv.Notice(y==="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=m(x.images,w).then(()=>{}).finally(()=>{i=null});return;default:return fx(x)}},u=y=>{let b=y.clipboardData;if(!b||s)return;let x=new Date;c("paste",y,j1("paste",b,r),x)},d=y=>{if(s)return;let b=y.dataTransfer;!b||!Y1(b)||(y.preventDefault(),b.dropEffect="copy",e.classList.add("qa-image-drop-target"))},p=()=>{e.classList.remove("qa-image-drop-target")},f=y=>{if(p(),s)return;let b=y.dataTransfer;if(!b||!Y1(b))return;let x=new Date;c("drop",y,j1("drop",b,r),x)};async function m(y,b){let x=e.readOnly;e.readOnly=!0,e.setAttribute("aria-busy","true"),e.classList.add("qa-image-paste-busy");let w=[];try{for(let C of y){let S;switch(C.origin){case"vault":S=C.file;break;case"bytes":{let A=await C.file.arrayBuffer(),D=PQ(C,b,n);S=await MQ(()=>KI(r,A,C.mimeType,n,D));break}default:return fx(C)}w.push(ux(r,S,n))}}catch(C){I.logError(`Failed to save image: ${C instanceof Error?C.message:String(C)}`),new Cv.Notice("QuickAdd: failed to save image.")}finally{e.readOnly=x,e.removeAttribute("aria-busy"),e.classList.remove("qa-image-paste-busy")}if(w.length===0||o)return"";let T=w.join(e.tagName==="TEXTAREA"?`
`:" ");try{return $Q(e,T),T}catch(C){return I.logError(`Failed to insert image link: ${C instanceof Error?C.message:String(C)}`),new Cv.Notice("QuickAdd: saved the image but could not insert its link."),""}}async function g(y){let b=new Date,x=FQ(y);if(x.length===0)return I.logMessage("QuickAdd: image ingest skipped (no-images)."),"";if(i)return new Cv.Notice("QuickAdd: an image is still being saved \u2014 drop again in a moment."),I.logMessage("QuickAdd: image ingest skipped (busy)."),"";let w="";return i=(async()=>{w=await m(x,b)})().finally(()=>{i=null}),await i,w.length>0&&I.logMessage(`QuickAdd: ingested ${x.length} image(s) into the active prompt.`),w}e.addEventListener("paste",u),e.addEventListener("dragenter",d),e.addEventListener("dragover",d),e.addEventListener("dragleave",p),e.addEventListener("drop",f),e.addEventListener("compositionstart",a),e.addEventListener("compositionend",l);let v={isBusy:()=>i!==null,whenIdle:()=>i??Promise.resolve(),ingestFiles:g,detach:()=>{o=!0,p(),e.removeEventListener("paste",u),e.removeEventListener("dragenter",d),e.removeEventListener("dragover",d),e.removeEventListener("dragleave",p),e.removeEventListener("drop",f),e.removeEventListener("compositionstart",a),e.removeEventListener("compositionend",l);let y=px.findIndex(b=>b.handle===v);y>=0&&px.splice(y,1)}};return px.push({handle:v,inputEl:e}),v}async function Q1(r){let e=AQ();if(!e)return I.logMessage("QuickAdd: image ingest skipped (no-active-prompt)."),{ok:!1,reason:"no-active-prompt"};if(e.handle.isBusy())return I.logMessage("QuickAdd: image ingest skipped (busy)."),{ok:!1,reason:"busy"};let t=await e.handle.ingestFiles(r);return t.length===0?{ok:!1,reason:"no-images"}:{ok:!0,inserted:t}}function j1(r,e,t){switch(r){case"paste":{if(e.getData("text/plain").length>0)return{kind:"stand-down"};let n=G1(e).map(i=>({origin:"bytes",...i,naming:{kind:"paste-name"}}));return n.length>0?{kind:"take",images:n}:{kind:"stand-down"}}case"drop":{let n=IQ(e,t);if(n.length>0)return{kind:"take",images:n};let i=G1(e).map(o=>({origin:"bytes",...o,naming:X1(o)}));return i.length>0?{kind:"take",images:i}:{kind:"stand-down"}}default:return fx(r)}}function IQ(r,e){let t=[];for(let n of r.getData("text/plain").split(/\r?\n/u)){let i=n.trim();if(i.length===0||i.toLowerCase().startsWith("file://")||Dr(i))continue;let o=e.vault.getAbstractFileByPath(i);DQ(o)&&t.push({origin:"vault",file:o})}return t}function DQ(r){return r!==null&&"extension"in r&&typeof r.extension=="string"&&H1(r.extension)}function G1(r){let e=[],t=0;for(let o of Array.from(r.items??[])){if(o.kind!=="file"||(t++,!vl(o.type)))continue;let s=o.getAsFile();s&&e.push({file:s,mimeType:o.type})}if(t>0&&e.length===t)return e;if(e.length===0){let o=[];for(let s of Array.from(r.files??[]))vl(s.type)&&o.push({file:s,mimeType:s.type});return o}let n=[...e],i=new Set(e.map(({file:o,mimeType:s})=>`${o.name}\0${o.size}\0${s}\0${o.lastModified}`));for(let o of Array.from(r.files??[])){if(!vl(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 FQ(r){return r.flatMap(e=>{if(!vl(e.type))return[];let t={file:e,mimeType:e.type};return[{origin:"bytes",...t,naming:X1(t)}]})}function X1(r){let e=W1(r.file.name);return e===null?{kind:"clipboard-stamp"}:{kind:"original-stem",stem:e}}function PQ(r,e,t){switch(r.naming.kind){case"clipboard-stamp":return z1(r.mimeType,e);case"paste-name":return lx({extension:gl[r.mimeType],sourcePath:t,now:e,nameAfterNoteTitle:X.getState().namePastedImagesAfterNoteTitle});case"original-stem":return`${r.naming.stem}.${gl[r.mimeType]}`;default:return fx(r.naming)}}function Y1(r){return Array.from(r.types??[]).some(e=>e==="Files"||vl(e))}function fx(r){throw new Error(`Unexpected image intake value: ${String(r)}`)}function MQ(r){let e=K1.then(r,r);return K1=e.catch(()=>{}),e}function $Q(r,e){r.focus();let t=!1;try{t=r.ownerDocument.execCommand("insertText",!1,e)}catch{t=!1}if(t)return;let n=r.selectionStart??r.value.length,i=r.selectionEnd??n;r.setRangeText(e,n,i,"end"),r.dispatchEvent(new Event("input",{bubbles:!0}))}var Cv,px,K1,hx=E(()=>{Cv=require("obsidian");Ie();dx();dt();la();px=[];K1=Promise.resolve()});function Z1(r,e){return!r.isComposing&&r.key.toLowerCase()===e.toLowerCase()&&r.shiftKey&&(r.ctrlKey||r.metaKey)}function J1(r){return Z1(r,"Enter")}function t2(r){return Z1(r,xv)}function r2(r){return r?`Look at the note without losing this draft. ${e2}`:"Look at the note without losing this draft."}function n2(){return`${e2} returns to the prompt`}var xv,e2,Ev=E(()=>{xv="E",e2="Ctrl/Cmd+Shift+E"});function i2(r,e,t,n){let i=Math.max(0,Math.min(e,r.length)),o=Math.max(i,Math.min(t,r.length));return{text:r.slice(0,i)+n+r.slice(o),cursor:i+n.length}}function o2(r,e=42){let t=r.slice(0,e*4),n=t.replace(/\s+/g," ").trim();return n.length<=e?t.length<r.length?`${n}\u2026`:n:`${n.slice(0,Math.max(0,e-1))}\u2026`}var QI=E(()=>{});function ZI(r){XI.add(r)}function JI(r){XI.delete(r)}function s2(){return XI.size>0}var XI,eD=E(()=>{XI=new Set});function OQ(r,e){let t=new Set([e]);return r.workspace.iterateAllLeaves?.(i=>{let o=i.view?.containerEl?.ownerDocument;o&&t.add(o)}),[...t]}var Hn,Is,yl,gx=E(()=>{Hn=require("obsidian");ys();bs();Ev();QI();eD();Is=class Is{constructor(e,t){this.app=e;this.handle=t;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 Is.active!==null}static getActive(){return Is.active}static activate(e,t){let n=Is.active;if(n){let o=n.handle.title;n.cancel(),new Hn.Notice(`QuickAdd: cancelled the peeked prompt "${o}".`)}let i=new Is(e,t);return Is.active=i,i.mount(),i}static discard(){Is.active?.destroy()}discard(){this.destroy()}resume(){if(!this.canReturnNow())return;let e=this.handle;this.destroy(),e.resume()}cancel(){let e=this.handle;this.destroy(),e.cancel()}insertSelectionAndResume(){if(!this.canReturnNow())return;let e=sl(this.app);if(!e){this.resume();return}let t=this.handle;this.destroy(),t.insertSelectionAndResume(e)}canReturnNow(){return s2()?(new Hn.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=Hn.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,Hn.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 Hn.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 Hn.ButtonComponent(l).setButtonText("Return").setTooltip("Go back to the prompt without inserting").onClick(()=>this.resume());let c=new Hn.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 u=er(c.buttonEl,"span");u.className="qa-peek-chip-cancel-icon",u.setAttribute("aria-hidden","true"),(0,Hn.setIcon)(u,"x"),c.buttonEl.replaceChildren(u)}else c.setButtonText("Cancel");Hn.Platform.isMobile||i.createEl("p",{cls:"qa-peek-chip-keys",text:n2()}),this.chipEl=i,this.refreshInsertButton(),this.listenForSelection(),this.listenForChipEscape(),this.pushReturnShortcut()}listenForSelection(){let e=(0,Hn.debounce)(()=>this.refreshInsertButton(),100,!0);this.selectionListener=e,this.selectionDocuments=OQ(this.app,this.chipEl?.ownerDocument??document);for(let t of this.selectionDocuments)t.addEventListener("selectionchange",e)}refreshInsertButton(){let e=this.insertButton;if(!e)return;let t=sl(this.app),n=t.length>0,i=n&&!this.compactChrome?o2(t):"";n===this.hasSelection&&i===this.selectionPreview||(this.hasSelection=n,this.selectionPreview=i,e.setDisabled(!n),e.buttonEl.classList.toggle("qa-peek-insert-ready",n),this.compactChrome||e.setButtonText(n?`Insert \u201C${i}\u201D`:"Insert selection"))}listenForChipEscape(){let e=this.chipEl;e&&(this.chipKeyListener=t=>{if(t.isComposing||t.key!=="Escape")return;let n=t.target;!(n instanceof Node)||!e.contains(n)||(t.preventDefault(),this.resume())},e.addEventListener("keydown",this.chipKeyListener))}pushReturnShortcut(){this.returnScope=new Hn.Scope(this.app.scope),this.returnScope.register(["Mod","Shift"],xv,()=>(this.resume(),!1)),this.app.keymap.pushScope(this.returnScope)}destroy(){if(Is.active===this&&(Is.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 e of this.selectionDocuments)e.removeEventListener("selectionchange",this.selectionListener);this.selectionListener.cancel?.(),this.selectionListener=null}this.selectionDocuments=[],this.chipEl?.remove(),this.chipEl=null,this.insertButton=null}};Is.active=null;yl=Is});function RQ(r){xn(r)?.editor?.focus?.()}var a2,Cf,tD=E(()=>{ys();gx();QI();eD();a2="qa-prompt-peek-hidden",Cf=class{constructor(e){this.host=e;this.peeking=!1;this.session=null}peek(){if(this.peeking)return;let e=this.host.getField();e&&this.host.setValue(e.value),this.host.persistDraft(),this.peeking=!0,this.hideModal(),this.session=yl.activate(this.host.app,{title:this.host.title,resume:()=>this.resume(),cancel:()=>this.cancel(),insertSelectionAndResume:t=>this.insertSelectionAndResume(t)})}onHostOpened(){ZI(this.host)}onHostClosed(){JI(this.host),this.peeking&&(this.peeking=!1,this.session?.discard(),this.session=null)}hideModal(){JI(this.host),this.host.containerEl.addClass(a2),this.host.app.keymap.popScope(this.host.scope),RQ(this.host.app)}showModal(){this.host.app.keymap.pushScope(this.host.scope),this.host.containerEl.removeClass(a2),ZI(this.host),this.host.getField()?.focus()}resume(){this.peeking&&(this.peeking=!1,this.session=null,this.showModal())}insertSelectionAndResume(e){if(!this.peeking)return;let t=this.host.getField();if(t){let n=t.selectionStart??t.value.length,i=t.selectionEnd??n,o=i2(t.value,n,i,e);t.value=o.text,t.setSelectionRange(o.cursor,o.cursor),this.host.setValue(o.text)}else this.host.setValue(this.host.getValue()+e);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 l2(r){return Tv.Platform.isPhone||(r?.innerWidth??Number.POSITIVE_INFINITY)<=540}function vx(r){let e=l2(r.ownerDocument.defaultView);return r.classList.toggle("qa-prompt-compact",e),e}function yx(r){let e=l2(r.buttonEl.ownerDocument.defaultView);r.setButtonText(e?LQ:NQ),r.setTooltip(r2(!Tv.Platform.isMobile)),r.buttonEl.setAttribute("aria-label","Peek at the note. Your draft stays."),r.buttonEl.classList.add("qa-peek-button");let t=er(r.buttonEl,"span");return t.className="qa-peek-button-icon",t.setAttribute("aria-hidden","true"),(0,Tv.setIcon)(t,"eye"),r.buttonEl.prepend(t),r}var Tv,NQ,LQ,rD=E(()=>{Tv=require("obsidian");bs();Ev();NQ="Peek at note",LQ="Peek"});var bx,xf,nD=E(()=>{bx=require("obsidian");qI();UI();I1();F1();M1();hx();ur();tD();Ev();rD();xf=class extends bx.Modal{constructor(t,n,i,o,s,a,l){super(t);this.header=n;this.linkSourcePath=s;this.options=l;this.didSubmit=!1;this.didClose=!1;this.submitClickCallback=t=>this.submit();this.cancelClickCallback=t=>this.cancel();this.skipClickCallback=t=>this.skip();this.submitEnterCallback=t=>{if(this.supportsPeek()&&t2(t)){t.preventDefault(),this.peek.peek();return}if(this.isOptionalPrompt&&J1(t)){t.preventDefault(),this.skip();return}this.shouldSubmit(t)&&(t.preventDefault(),this.submit())};this.placeholder=i??"",this.description=a?.trim()||void 0,this.draftHandler=new tx({kind:this.getPromptKind(),header:this.header,placeholder:this.placeholder,linkSourcePath:this.linkSourcePath,scopeId:l?.draftScopeId}),this.input=this.draftHandler.hydrate(o??""),this.waitForClose=new Promise((c,u)=>{this.resolvePromise=c,this.rejectPromise=u}),this.peek=new Cf({app:t,title:this.header,containerEl:this.containerEl,scope:this.scope,getField:()=>this.inputComponent?.inputEl,getValue:()=>this.input,setValue:c=>{this.input=c},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"),vx(this.containerEl),this.contentEl.empty(),this.titleEl.textContent=this.header,P1(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 t=this.contentEl.createDiv();this.inputComponent=this.createInputField(t,this.placeholder,this.input),this.createButtonBar(t)}get isOptionalPrompt(){return this.options?.optional===!0}supportsPeek(){return this.options?.allowPeek===!0}configureInput(t,n,i){return t.setPlaceholder(n??"").setValue(i??"").onChange(o=>this.onInputChanged(o)),t.inputEl.addEventListener("keydown",this.submitEnterCallback),this.options?.imagePaste&&(this.imagePasteHandle=mx(this.app,t.inputEl,this.options.imagePaste)),t}disposeInput(){}createButton(t,n,i){let o=new bx.ButtonComponent(t);return o.setButtonText(n).onClick(i),o}createButtonBar(t){let n=t.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"});yx(this.createButton(o,"Peek at note",()=>this.peek.peek()))}}transformInputOnSubmit(t){return t}submit(){if(this.didSubmit||this.didClose)return;if(this.imagePasteHandle?.isBusy()){this.imagePasteHandle.whenIdle().then(()=>this.submit());return}let t=this.inputComponent?.inputEl?.value??this.input;this.input=this.transformInputOnSubmit(t),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(Rr())}onInputChanged(t){this.draftHandler.markChanged(),this.input=t}syncInputFromEl(){this.inputComponent?.inputEl&&(this.input=this.inputComponent.inputEl.value)}persistDraft(){this.draftHandler.persist(this.input,this.didSubmit)}attachSuggesters(){this.fileSuggester=new vf(this.app,this.inputComponent.inputEl,{sourcePath:this.linkSourcePath}),this.tagSuggester=new yf(this.app,this.inputComponent.inputEl)}removeInputListener(){this.inputComponent.inputEl.removeEventListener("keydown",this.submitEnterCallback),this.disposeInput(),this.imagePasteHandle?.detach()}onOpen(){super.onOpen(),this.peek.onHostOpened(),D1(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 c2,ar,Ds=E(()=>{c2=require("obsidian");nD();ar=class r extends xf{static Prompt(e,t,n,i,o,s){return new r(e,t,n,i,void 0,o,s).waitForClose}static PromptWithContext(e,t,n,i,o,s,a){return new r(e,t,n,i,o,s,a).waitForClose}getPromptKind(){return"single"}createInputField(e,t,n){let i=new c2.TextComponent(e);return i.inputEl.setCssStyles({width:"100%"}),this.configureInput(i,t,n)}shouldSubmit(e){return!e.isComposing&&e.key==="Enter"}}});function zn(r){return r.replace(/\{\{CURSOR\}\}/gi,"")}function Tf(r){let e=/\{\{CURSOR\}\}/i.exec(r);return r=zn(r),{content:r,cursor:/^[ \t\r\n\f\v]*$/.test(r)?{kind:"none"}:{kind:"offset",value:e?.index??r.length,source:e?"marker":"defaultEnd"}}}function bl(r,e,t=""){return{content:e+r.content+t,cursor:r.cursor.kind==="none"?r.cursor:{...r.cursor,value:e.length+r.cursor.value}}}function Oc(r,e,t){return{content:e,cursor:r.cursor.kind==="none"||t===null?{kind:"none"}:{...r.cursor,value:t}}}var wl=E(()=>{});function ZQ(r){return KQ.test(r.trim())}function JQ(r){let e=r.replace(QQ,"");return e===r?!1:!XQ.test(e)}function Cx(r,e){return GQ.has(r)?JQ(e):ZQ(e)}function xx(r){return r==="noteTitle"||r==="captureTarget"||r==="propertyName"||r==="propertyValue"||r==="folder"||r==="templatePath"||r==="lineTarget"||r==="filePath"}function Ex(r){return r!=="templatePath"&&r!=="generic"}function Tx(r,e){if(r==="generic")return{};let t=YQ[r];return e?{title:t.ask,placeholder:t.hint}:{placeholder:t.partOf}}function eX(r,e=44){if(r.length<=e)return r;let t=r.split("/");if(t.length===1)return r;let n=t[t.length-1];if(t.length===2){let s=`${d2}/${n}`;return s.length<r.length?s:r}let o=`${t[0]}/${d2}/${n}`;return o.length<r.length?o:r}function kf(r,e,t){if(!r)return;let n=[],i=r.choiceName?.trim();i&&i!==e?.trim()&&n.push(i);let o=t?.showDestination===!1?void 0:r.destination?.trim();if(o){let s=t?.elide===!1?o:eX(o);n.push(`\u2192 ${r.destinationKind==="folder"?`${s}/`:s}`)}return n.length?n.join(" "):void 0}var GQ,YQ,KQ,QQ,XQ,d2,Sf=E(()=>{Xe();GQ=new Set(["captureText"]),YQ={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"}},KQ=new RegExp(`^(?:${el.source})$`,"i"),QQ=new RegExp(el.source,"gi"),XQ=/\{\{[^}\n\r]*\}\}/;d2="\u2026"});function ca(r,e,t={}){if(!r||!e)return null;let n=r,i=n.metadataTypeManager??n.metadataCache?.app?.metadataTypeManager;if(!i||typeof i.getTypeInfo!="function")return null;if(t.registeredOnly){let a=i.getAllProperties?.();if(!a||typeof a!="object"||!Object.keys(a).some(l=>l.toLowerCase()===e.toLowerCase()))return null}let o=i.getTypeInfo(e),s=o?.expected?.type??o?.inferred?.type;return typeof s=="string"?s:null}function nX(r){return r!==null&&tX.has(r.toLowerCase())}function p2(r,e){return rX.has(e.toLowerCase())||nX(ca(r,e))}var tX,rX,_f=E(()=>{tX=new Set(["aliases","list","multitext","tags"]),rX=new Set(["aliases","cssclasses","tags"])});function iX(r,e=","){let t=[],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 u=a-1;u>=0&&r[u]==="\\";u--)c++;c%2===0&&(o=null)}continue}if(l==='"'){o=l,n+=l;continue}if(l in f2){i.push(f2[l]),n+=l;continue}if(i.length>0){let c=i[i.length-1];l===c&&i.pop(),n+=l;continue}if(l===e){let c=n.trim();c.length>0&&t.push(c),n="";continue}n+=l}let s=n.trim();return s.length>0&&t.push(s),t}function oX(r){return r.includes(`
`)?r.replace(/\r?\n/g,`
`):r.includes("\\n")?r.replace(/\\n/g,`
`):r}function sX(r){if(!r)return!1;let e=r.toLowerCase();return e==="list"||e==="tags"||e==="multitext"}function m2(r,e){let t=r.trim();if(!t)return;let n=oX(t),i=e?.propertyType??ca(e?.app,e?.propertyKey),o=sX(i),a=o||i===null,c=n.split(/\n/).map(u=>u.trim()).filter(u=>u.length>0);if(a&&c.length>0&&c.every(u=>/^-\s+/.test(u)))return c.map(u=>u.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 u=iX(n);if(u.length>1)return u}}var f2,h2=E(()=>{_f();f2={"[":"]","(":")","{":"}","<":">"}});function Af(r){if(typeof r=="string"&&r.startsWith("@date:")){let e=r.substring(6),t=new Date(e);if(!Number.isNaN(t.getTime()))return t}return r}function iD(r){return typeof r!="string"&&(Array.isArray(r)||typeof r=="object"&&r!==null||typeof r=="number"||typeof r=="boolean"||r===null)}function g2(r){return Array.isArray(r)||typeof r=="object"&&r!==null}function v2(r){if(iD(r))return Array.isArray(r)?"[]":r===null?"null":typeof r=="object"?"{}":String(r)}var If=E(()=>{});var y2,co,Sv=E(()=>{HI();h2();If();_f();y2="\0",co=class{constructor(e){this.app=e;this.map=new Map;this.propertyTypeCache=new Map}maybeCollect(e){let{input:t,matchStart:n,matchEnd:i,rawValue:o,fallbackKey:s,collectionActive:a,heuristicEnabled:l}=e;if(!a)return;let c=pv(t),u=fv(t,n,i,c);if(!u.isInYaml)return;let d=t.slice(u.lineStart,u.lineEnd),p=d.trim(),f=d.match(/^\s*([^:]+):/),m=f?f[1].trim():s,g=/^-\s*['"]?\{\{(?:VALUE|FIELD|FILE):[^}]+\}\}['"]?\s*$/i,v=null;if(u.isKeyValuePosition?v=[m]:g.test(p)&&(v=this.findListParentPath(t,u.lineStart,u.baseIndent??"")),!v||v.length===0)return;let y=v[v.length-1],b=o;if(l&&typeof o=="string"){let w=m2(o,this.buildParseOptions(y));w!==void 0&&(b=w)}if(!iD(b)||Array.isArray(b)&&b.length===0||!l&&!g2(b))return;let x=v.join(y2);return this.map.set(x,b),b}drain(){let e=new Map(this.map);return this.map.clear(),e}merge(e){for(let[t,n]of e)this.map.set(t,n)}buildParseOptions(e){return{propertyKey:e,propertyType:this.resolvePropertyType(e),app:this.app}}findListParentPath(e,t,n){let i=t-1,o=[],s=n.length;for(;i>=0;){let a=e.lastIndexOf(`
`,i),l=a===-1?0:a+1,c=e.slice(l,i+1),u=c.trim();if(u.length===0){i=l-2;continue}if(u==="---"||u==="...")break;if(u.startsWith("-")){i=l-2;continue}let d=c.match(/^(\s*)([^:\n]+):/);if(d){let f=(d[1]??"").length;if(f<s&&(o.unshift(d[2].trim()),s=f,s===0))break}i=l-2}return o.length>0?o:null}resolvePropertyType(e){if(!this.app)return null;if(this.propertyTypeCache.has(e))return this.propertyTypeCache.get(e)??null;let t=ca(this.app,e);return this.propertyTypeCache.set(e,t),t}};co.PATH_SEPARATOR=y2});function b2(r){if(!r)return null;let e=r.trim().toLowerCase();switch(e){case"kebab":case"snake":case"camel":case"pascal":case"title":case"lower":case"upper":case"slug":return e;default:return null}}function _x(r){return b2(r)!==null}function oD(r){if(!r)return r;let e=r.toLowerCase();return e.slice(0,1).toUpperCase()+e.slice(1)}function sD(r){return/\p{L}/u.test(r)?/\p{Lu}/u.test(r)&&!/\p{Ll}/u.test(r):!1}function kx(r){return/\p{Lu}/u.test(r)&&/\p{Ll}/u.test(r)}function aX(r){return/^\p{Ll}/u.test(r)&&kx(r)}function lX(r){if(!r)return[];{let t=r.match(/^([\p{Ll}][\p{Lu}]{2,})([\p{N}]+)?$/u);if(t){let n=[t[1]];return t[2]&&n.push(t[2]),n}}if(/^[\p{Ll}][\p{Lu}][\p{Ll}]+(?:[\p{Lu}][\p{Ll}]+)*$/u.test(r))return[r];let e=r;return e=e.replace(/([\p{Lu}])([\p{Lu}][\p{Ll}])/gu,"$1 $2"),e=e.replace(/([\p{Ll}\p{N}])([\p{Lu}])/gu,"$1 $2"),e=e.replace(/([\p{L}])([\p{N}])/gu,"$1 $2"),e=e.replace(/([\p{N}])([\p{L}])/gu,"$1 $2"),e.trim().split(/\s+/u).map(t=>t.trim()).filter(Boolean)}function cX(r){return r.split(/[^\p{L}\p{N}\p{M}]+/gu).filter(Boolean).flatMap(lX).filter(Boolean)}function _v(r,e){let t=b2(e);if(!t)return r;if(t==="lower")return r.toLowerCase();if(t==="upper")return r.toUpperCase();let n=cX(r);if(n.length===0)return"";switch(t){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?aX(i)?i:i.toLowerCase():"",a=o.map(l=>sD(l)||kx(l)?l:oD(l));return[s,...a].join("")}case"pascal":return n.map(i=>sD(i)||kx(i)?i:oD(i)).join("");case"title":return n.map(i=>sD(i)||kx(i)?i:oD(i)).join(" ");case"slug":{let i=n.map(o=>o.toLowerCase()).join("-");return kd(i)?`${i}-`:i}default:return r}}var Sx,Ax=E(()=>{wv();Sx=["kebab","snake","camel","pascal","title","lower","upper","slug"]});function Ix(r){let e=r.trim();return e&&(/^\[\[.*\]\]$/.test(e)?e:`[[${e}]]`)}var aD=E(()=>{});function lD(r){let{remaining:e,found:t}=ws(r,"optional"),{remaining:n,found:i}=ws(e,"trim");return{remaining:n,optional:t,trim:i}}function cD(r,e,t,n,i){let o=r.map(d=>{let p=d.trim();return{raw:p,option:Uo(p)}}),s=t?dX:w2,a=o.some(({option:d})=>d?.key==="type"&&["number","slider"].includes(d.value.toLowerCase())),l=d=>s.has(d)||a&&uX.has(d);if(!o.some(({raw:d,option:p})=>p&&l(p.key)||e&&["custom","multi"].includes(d.toLowerCase())))return{defaultValue:r.join("|").trim(),allowCustomInput:!1,usesOptions:!1};let u={defaultValue:"",allowCustomInput:!1,usesOptions:!0,multiSelect:!1};for(let{raw:d,option:p}of o){if(e&&d.toLowerCase()==="custom"){u.allowCustomInput=!0;continue}if(e&&d.toLowerCase()==="multi"){u.multiSelect=!0;continue}if(!p||!l(p.key))continue;let{key:f,value:m}=p;switch(f){case"label":m&&(u.label=m);break;case"case":m&&(u.caseStyle=m);break;case"default":u.defaultValue=m;break;case"custom":u.allowCustomInput=Cc(m);break;case"type":m&&(u.inputTypeOverride=m);break;case"min":u.minRaw=m;break;case"max":u.maxRaw=m;break;case"step":u.stepRaw=m;break;case"text":u.displayValuesRaw=m;break;case"optional":u.optionalExplicit=Cc(m);break;case"trim":u.trimExplicit=Cc(m);break;case"multi":u.multiSelect=!0,u.multiEmit=m.trim().toLowerCase()==="linklist"?"linklist":"text";break;case"format":u.multiFormat=nx(m,n,i);break;case"name":m?u.name=m:i(`QuickAdd: empty |name: ignored in "${n}"; provide a variable name, e.g. {{VALUE:a,b|name:category}}.`);break;default:break}}return u}var uX,w2,dX,C2=E(()=>{xc();ix();uX=new Set(["min","max","step"]),w2=new Set(["label","default","custom","type","case","text","optional","trim","multi","format"]),dX=new Set([...w2,"name"])});function Df(r){if(r===void 0)return;let e=r.trim();if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function pX(r){return r.minRaw!==void 0||r.maxRaw!==void 0||r.stepRaw!==void 0}function x2(r,e,t){let n=Df(r.minRaw),i=Df(r.maxRaw),o=Df(r.stepRaw),s={};for(let[a,l,c]of[["min",r.minRaw,n],["max",r.maxRaw,i]])l!==void 0&&(c===void 0?t(`QuickAdd: Ignoring invalid ${a} in VALUE token "${e}".`):s[a]=c);return s.min!==void 0&&s.max!==void 0&&s.max<s.min&&(t(`QuickAdd: Ignoring invalid numeric range in VALUE token "${e}"; max must be greater than or equal to min.`),delete s.min,delete s.max),r.stepRaw!==void 0&&(o===void 0||o<=0?t(`QuickAdd: Ignoring invalid step in VALUE token "${e}"; step must be greater than 0.`):s.step=o),Object.keys(s).length>0?s:void 0}function uD(r,e,t,n){if(t!=="number"&&t!=="slider")return pX(r)&&n(`QuickAdd: Ignoring numeric range options in "${e}" because type is not number or slider.`),{inputTypeOverride:t};if(t!=="slider"){let c=x2(r,e,n);return{inputTypeOverride:t,numericConfig:c}}let i=Df(r.minRaw),o=Df(r.maxRaw),s=r.stepRaw===void 0?1:Df(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 "${e}" (${a}); falling back to type:number.`),{inputTypeOverride:"number",numericConfig:x2(r,e,uv)};let l={min:i,max:o,step:s};return{inputTypeOverride:t,numericConfig:l,sliderConfig:l}}function E2(r){let e=String(r),t=/e-(\d+)$/i.exec(e);if(t)return Number(t[1]);let n=e.indexOf(".");return n===-1?0:e.length-n-1}function fX(r,e){return String(Number(r.toFixed(e)))}function Go(r,e){let t=r?.trim()??"";if(!t)return"";let n=Number(t);if(!Number.isFinite(n))return"";let i=e?.min,o=e?.max,s=n;if(i!==void 0&&(s=Math.max(i,s)),o!==void 0&&(s=Math.min(o,s)),e?.step!==void 0&&e.step>0){let a=i??0,l=Math.round((s-a)/e.step);s=a+l*e.step,i!==void 0&&(s=Math.max(i,s)),o!==void 0&&(s=Math.min(o,s));let c=Math.max(E2(a),E2(e.step));return fX(s,c)}return String(s)}function Ff(r,e){return Go(r,e)||String(e.min)}var dD=E(()=>{dv()});function Dx(r){return r!==void 0&&mX.has(r)}function _d(r){let e=[],t="",n=!1;for(let i=0;i<r.length;i++){let o=r[i];if(n){if(Dx(o)){if(Dx(r[i+1])){t+='"',i++;continue}let s=i+1;for(;s<r.length&&hX.test(r[s]);)s++;if(s>=r.length||r[s]===","){n=!1,i=s-1;continue}return r.split(",")}t+=o;continue}if(o===","){e.push(t),t="";continue}if(Dx(o)&&t.trim()===""){n=!0,t="";continue}t+=o}return n?r.split(","):(e.push(t),e)}function Av(r){let e=r.trim();if(!Dx(e[0]))return r;let t=_d(e);return t.length===1&&t[0]!==e?t[0].trim():r}var mX,hX,pD=E(()=>{mX=new Set(['"',"\u201C","\u201D"]);hX=/[^\S\r\n]/});function yX(r,e,t){return t&&e?`${r}${fD}${e}`:r}function Iv(r){let e=r.indexOf(fD);return e===-1?r:r.slice(0,e)}function bX(r,e){let t=e.toLowerCase(),n=null;for(let i of r.keys())if(i.toLowerCase()===t&&r.get(i)!==void 0){if(n)return null;n=i}return n}function Rc(r,e){if(!e)return null;let t=[e],n=Iv(e);n!==e&&t.push(n);for(let i of t){if(r.has(i)&&r.get(i)!==void 0)return i;let o=bX(r,i);if(o)return o}return null}function T2(r,e,t){if(r&&!_x(r)){t(`QuickAdd: Unsupported |case style "${r}" in token "${e}". Supported styles: ${Sx.join(", ")}.`);return}return r}function k2(r,{tokenDisplay:e,hasOptions:t,allowCustomInput:n},i){if(!r)return;let o=r.trim().toLowerCase(),s=o==="boolean"?"checkbox":o;if(!gX.has(s)){i(`QuickAdd: Unsupported VALUE type "${r}" in token "${e}". Supported types: multiline, number, slider, checkbox, text.`);return}if(t||n){i(`QuickAdd: Ignoring type:${s} for option-list VALUE token "${e}".`);return}return s}function Ad(r,e){if(!r)return null;let t=e?.warn??wf,n=qo(r),i=(n.shift()??"").trim();if(!i)return null;let o=_d(i).map(P=>P.trim()).filter(Boolean),s=o.length>1,{remaining:a,optional:l,trim:c}=lD(n),u=`{{VALUE:${r}}}`,d=cD(a,s,!0,u,t),{label:p,caseStyle:f,defaultValue:m,allowCustomInput:g}=d,v=d.multiSelect??!1,y=d.multiEmit??"text",b=d.multiFormat??"auto",x=d.optionalExplicit??l,w=d.trimExplicit??c;if(!d.usesOptions){let P=m;g=s&&P.toLowerCase()==="custom",m=g?"":P}s&&m&&(m=Av(m));let T=k2(d.inputTypeOverride,{tokenDisplay:u,hasOptions:s,allowCustomInput:g},t),C=uD(d,u,T,t),S;if(d.displayValuesRaw!==void 0){if(!s)throw new Error(`QuickAdd: VALUE option "text" is only supported for option-list tokens in "${u}".`);if(S=_d(d.displayValuesRaw).map(P=>P.trim()).filter(Boolean),S.length!==o.length)throw new Error(`QuickAdd: VALUE token "${u}" 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(S).size!==S.length)throw new Error(`QuickAdd: VALUE token "${u}" has duplicate text entries. Text entries must be unique.`)}let A=d.name?.trim()||void 0;A&&A.includes(fD)&&(t(`QuickAdd: |name in "${u}" contains a reserved control character and was ignored.`),A=void 0),A&&vX.has(A.toLowerCase())&&(t(`QuickAdd: |name:${A} is reserved and was ignored in "${u}". Choose a different name.`),A=void 0),A&&!s&&t(`QuickAdd: |name on a single value in "${u}" is redundant \u2014 use {{VALUE:${A}}} directly.`),f=T2(f,u,t),v&&!s&&(t(`QuickAdd: |multi needs an option list (2+ comma-separated values) in "${u}"; ignoring.`),v=!1),v&&f&&(t(`QuickAdd: |case is ignored with |multi in "${u}" \u2014 a list is not case-transformed.`),f=void 0),!v&&d.multiFormat!==void 0&&(t(`QuickAdd: |format: needs |multi in "${u}"; ignoring.`),b="auto"),!s&&!d.usesOptions&&a.some(P=>P.trim().toLowerCase()==="custom")&&(t(`QuickAdd: |custom needs an option list (2+ comma-separated values) in "${u}"; ignoring.`),m.toLowerCase()==="custom"&&(m=""));let D=A||yX(i,p,s);return{raw:r,variableName:i,aliasName:A,variableKey:D,label:p,caseStyle:f,defaultValue:m,allowCustomInput:g,suggestedValues:o,displayValues:S,hasOptions:s,inputTypeOverride:C.inputTypeOverride,numericConfig:C.numericConfig,sliderConfig:C.sliderConfig,optional:x,trim:w,multiSelect:v,multiEmit:y,multiFormat:b}}function Dv(r,e){let t=e?.warn??wf,n=ZN(r),i=qo(n).map(g=>g.trim()).filter(Boolean),{remaining:o,optional:s,trim:a}=lD(i);if(o.length===0)return{defaultValue:"",optional:s,trim:a};let l=`{{VALUE${r}}}`,c=cD(o,!1,!1,l,t);if(c.displayValuesRaw!==void 0)throw new Error(`QuickAdd: VALUE option "text" is only supported for option-list tokens in "${l}".`);let{label:u,caseStyle:d,defaultValue:p}=c;c.usesOptions||(p=p.trim()),d=T2(d,l,t);let f=k2(c.inputTypeOverride,{tokenDisplay:l,hasOptions:!1,allowCustomInput:c.allowCustomInput},t),m=uD(c,l,f,t);return{label:u,caseStyle:d,defaultValue:p,inputTypeOverride:m.inputTypeOverride,numericConfig:m.numericConfig,sliderConfig:m.sliderConfig,optional:c.optionalExplicit??s,trim:c.trimExplicit??a}}var fD,gX,vX,uo=E(()=>{C2();dD();pD();dD();pD();xc();Ax();dv();fD="",gX=new Set(["multiline","number","slider","checkbox","text"]),vX=new Set(["value","title"])});function ua(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 Nc(r){return wX.includes(r)}function A2(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 I2(r){if(!Nc(r.operator)||r.expectedValue===void 0||r.expectedValue===null)return;let e=r.expectedValue.trim();switch(r.valueType){case"number":{let t=Number(e);return Number.isNaN(t)?NaN:t}case"boolean":{let t=e.toLowerCase();return S2.has(t)?!0:_2.has(t)?!1:!!e}default:return e}}function mD(r,e){switch(e){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 t=r.trim().toLowerCase();if(S2.has(t))return!0;if(_2.has(t))return!1}return!!r;default:return r==null?"":ua(r)}}function CX(r){if(!Nc(r.operator))return"";let e=r.expectedValue??"";return e.length===0?"(empty)":r.valueType==="string"?`"${e}"`:e}function xX(r){let e=r.variableName?`$${r.variableName}`:"(missing variable)",t=TX(r.operator),n=Nc(r.operator)?` ${CX(r)}`:"";return`${e} ${t}${n}`.trim()}function EX(r){let e=r.exportName?`::${r.exportName}`:"";return`script ${r.scriptPath}${e}`}function Pf(r){return r.mode==="variable"?xX(r):EX(r)}function TX(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 wX,S2,_2,Id=E(()=>{wX=["equals","notEquals","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","contains","notContains"],S2=new Set(["true","1","yes","on"]),_2=new Set(["false","0","no","off"])});var kX,Fx,hD=E(()=>{Xe();Sf();Ie();Sv();Ax();If();rx();ix();aD();uo();dv();Id();kX=new Set(["number","slider","checkbox"]),Fx=class{constructor(e){this.app=e;this.variables=new Map;this.promptScope="generic";this.promptScopeSoleValue=!1;this.templatePropertyCollectionDepth=0;this.namedSuggesterOptionSigs=new Map;this.namedSuggesterConflictsWarned=new Set;this.warnSink=e=>this.warn(e);this.propertyCollector=new co(e)}async preserveSingleTokenValue(e,t){let n=this.singleTokenValue,i=/^(?:\{\{(?:VALUE|NAME)(?::[^{}]+|\|[^{}]+)?\}\}|\{\{(?:FIELD|FILE):[^{}]+\}\}|\{\{PROPERTY\}\}|`{3,}js quickadd[\s\S]*`{3,})$/i.test(e)?{input:e}:void 0;this.singleTokenValue=i;try{let o=await t();return i?.result&&typeof i.result.value!="string"?i.result.value:o}finally{this.singleTokenValue=n}}retainSingleTokenValue(e,t,n,i){this.singleTokenValue?.input===e&&t===0&&n===e.length&&(this.singleTokenValue.result={value:i})}propertyTokenValue(e,t){if(t==="text")return ua(e);if(t==="checkbox"){if(typeof e=="boolean")return e;if(e==="true")return!0;if(e==="false")return!1;throw new Error("A checkbox property value must be true or false.")}if(t==="number"||t==="slider"){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e!="string"||!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e.trim())||!Number.isFinite(Number(e)))throw new Error("A number property value must be a finite number.");return Number(e)}return e}warn(e){I.logWarning(e)}reportProblem(e){I.logError(e)}setPromptRunContext(e){this.promptRunContext={...this.promptRunContext,...e}}getPromptRunContext(){return this.promptRunContext}async withPromptScope(e,t,n){let i=this.promptScope,o=this.promptScopeSoleValue;this.promptScope=e,this.promptScopeSoleValue=Cx(e,t);try{return await n()}finally{this.promptScope=i,this.promptScopeSoleValue=o}}hasConcreteVariable(e){return this.variables.has(e)?this.variables.get(e)!==void 0:!1}setTitle(e){this.hasConcreteVariable("title")||this.variables.set("title",e)}getAnonymousValue(){return this.value}replacer(e,t,n){return e.replace(t,function(){return n})}applyCaseOption(e,t,n){return t?_x(t)?_v(e,t):(this.warn(`QuickAdd: Unsupported |case style "${t}" in token "${n}". Supported styles: ${Sx.join(", ")}.`),e):e}async replaceValueInString(e){let t=e;if(!el.test(t))return t;if(this.valuePromptContext=this.getValuePromptContext(t),this.hasConcreteVariable("value")){let i=this.variables.get("value");this.value=ua(i)}this.value===void 0&&(this.value=await this.promptForValue());let n=new RegExp(el.source,"gi");return t=t.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),Ed(a,s,s+o.length,this.value);let u=l.slice(c),d=Dv(u,{warn:this.warnSink}),p=this.value===""&&d.defaultValue&&!d.optional?d.defaultValue:this.value,f=this.applyValueTextOptions(p,d);if(this.singleTokenValue){let m=this.value===""&&d.defaultValue&&!d.optional?d.defaultValue:this.hasConcreteVariable("value")?this.variables.get("value"):this.value;this.retainSingleTokenValue(a,s,s+o.length,this.propertyTokenValue(this.applyValueTokenOptions(m,d),d.inputTypeOverride))}return d.inputTypeOverride==="text"&&f!==""&&WI(a,s,s+o.length)?mv(f):Ed(a,s,s+o.length,f)}),t}applyValueTextOptions(e,t){let n=String(e??""),i=t.trim?n.trim():n;return _v(i,t.caseStyle)}applyValueTokenOptions(e,t){return Array.isArray(e)?t.trim?e.map(n=>typeof n=="string"?n.trim():n):e:typeof e=="string"?this.applyValueTextOptions(e,t):e}getValuePromptContext(e){let t=new RegExp(el.source,"gi"),n,i;for(;(n=t.exec(e))!==null;){let s=n[0].slice(2,-2),a=s.indexOf("|");if(a===-1)continue;let l=s.slice(a),c=Dv(l,{warn:uv});i||(i={}),!i.description&&c.label&&(i.description=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(e){this.propertyCollector.merge(e)}renderCollectedOrArrayValue(e){if((!e.multiFormat||e.multiFormat==="auto")&&this.retainSingleTokenValue(e.input,e.matchStart,e.matchEnd,e.rawValue),Array.isArray(e.rawValue)&&e.multiFormat){let i=L1({input:e.input,matchStart:e.matchStart,values:e.rawValue,format:e.multiFormat});if(i!==void 0)return i}let t=this.propertyCollector.maybeCollect({...e,collectionActive:this.templatePropertyCollectionDepth>0}),n=v2(t);if(n!==void 0)return n;if(Array.isArray(e.rawValue))return Ed(e.input,e.matchStart,e.matchEnd,e.rawValue.join(","))}async withTemplatePropertyCollection(e){this.templatePropertyCollectionDepth+=1;try{return await e()}finally{this.templatePropertyCollectionDepth-=1}}warnOnNamedOptionConflict(e){if(!e.aliasName||!e.hasOptions)return;let t=e.variableKey.toLowerCase(),n=JSON.stringify([e.suggestedValues,e.allowCustomInput,e.displayValues??null,e.multiSelect,e.multiEmit]),i=this.namedSuggesterOptionSigs.get(t);if(i===void 0){this.namedSuggesterOptionSigs.set(t,n);return}i!==n&&!this.namedSuggesterConflictsWarned.has(t)&&(this.namedSuggesterConflictsWarned.add(t),this.warn(`QuickAdd: named value "${e.variableKey}" is defined with different option lists; the first definition's value is reused.`))}async ensureValueVariableResolved(e){let{variableName:t,variableKey:n,label:i,defaultValue:o,allowCustomInput:s,suggestedValues:a,displayValues:l,hasOptions:c}=e;this.warnOnNamedOptionConflict(e);let u=Rc(this.variables,n);if(u)return u;let d=!c&&i?i:void 0,p=c&&i?i:void 0;if(c&&e.multiSelect){let m=await this.suggestForValueMulti(a,s,{placeholder:p,variableKey:n,displayValues:l,optional:e.optional});return this.variables.set(n,e.multiEmit==="linklist"?m.map(Ix):m),n}let f="";return c?f=await this.suggestForValue(a,s,{placeholder:p,variableKey:n,displayValues:l,optional:e.optional}):f=await this.promptForVariable(t,{defaultValue:o,description:d,inputTypeOverride:e.inputTypeOverride,numericConfig:e.numericConfig,sliderConfig:e.sliderConfig,variableKey:n,optional:e.optional}),!f&&o&&!e.optional&&(f=o),this.variables.set(n,f),n}async resolveNamedSuggesterDefinitions(e){if(!/\|\s*name\s*:/i.test(e))return;let t=new RegExp(od.source,"gi"),n=[],i;for(;(i=t.exec(e))!==null;){if(!i[1])continue;let a;try{a=Ad(i[1],{warn:uv})}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(e){let t=e;await this.resolveNamedSuggesterDefinitions(t);let n=new RegExp(od.source,"gi"),i=this.isTemplatePropertyTypesEnabled(),o;for(;(o=n.exec(t))!==null;){if(!o[1])throw new Error(`Unable to parse variable. Invalid syntax in: "${t.substring(Math.max(0,o.index-10),Math.min(t.length,o.index+30))}..."`);let s=Ad(o[1],{warn:this.warnSink});if(!s)throw new Error(`Unable to parse variable. Invalid syntax in: "${t.substring(Math.max(0,o.index-10),Math.min(t.length,o.index+30))}..."`);let{variableName:a}=s,l=await this.ensureValueVariableResolved(s),c=this.variables.get(l),u=this.applyValueTokenOptions(c,s);this.singleTokenValue&&(!s.multiFormat||s.multiFormat==="auto")&&this.retainSingleTokenValue(t,o.index,o.index+o[0].length,this.propertyTokenValue(u,s.inputTypeOverride));let d=this.renderCollectedOrArrayValue({input:t,matchStart:o.index,matchEnd:o.index+o[0].length,rawValue:this.singleTokenValue?.result?this.singleTokenValue.result.value:u,fallbackKey:a,heuristicEnabled:i&&this.templatePropertyCollectionDepth>0&&s.inputTypeOverride!=="text",multiFormat:s.multiFormat}),p,f=!1;if(d!==void 0)p=d;else{let v=String(this.applyValueTextOptions(this.getVariableValue(l),s)??"");s.inputTypeOverride==="text"&&v!==""&&WI(t,o.index,o.index+o[0].length)?p=mv(v):kX.has(s.inputTypeOverride??"")&&zI(t,o.index,o.index+o[0].length)?(f=!0,p=v):p=Ed(t,o.index,o.index+o[0].length,v)}let m=f?o.index-1:o.index,g=o.index+o[0].length+(f?1:0);t=t.slice(0,m)+p+t.slice(g),n.lastIndex=m+p.length}return t}suggestForValueMulti(e,t,n){return[]}}});function Fv(r){if(!r)return{optional:!1,withTime:!1};let{remaining:e,found:t}=ws(qo(r),"optional"),{remaining:n,found:i}=ws(e,"time"),{remaining:o,found:s}=ws(n,"datetime"),a,l=!1,c,u,d=[];for(let f of o){let m=Uo(f.trim());if(m?.key==="optional"){a=Cc(m.value);continue}if(m?.key==="type"){m.value.trim().toLowerCase()==="datetime"&&(l=!0);continue}if(m?.key==="startof"||m?.key==="endof"){c||(c={boundary:m.key==="startof"?"start":"end",unit:FC(m.value)});continue}if(m?.key==="case"){u=m.value.trim()||void 0;continue}d.push(f)}return{defaultValue:d.join("|").trim()||void 0,optional:a??t,withTime:i||s||l,snap:c,...u?{caseStyle:u}:{}}}function Px(r){try{return{options:Fv(r)}}catch(e){return{options:{optional:!1,withTime:!1},error:e instanceof Error?e.message:String(e)}}}var Pv=E(()=>{xc();Yg()});function D2(r,e,t){return r.replace(e,()=>t)}function Mf(r){return r?"YYYY-MM-DD HH:mm":"YYYY-MM-DD"}function $f(r,e,t,n){if(r===void 0)return null;let i=r,o;if(typeof i=="string"&&i&&!i.startsWith("@date:")){if(n){let s=X.getState().dateAliases,a=n.parseDate(kg(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:rf(a,t).format(e),...o!==void 0?{normalized:o}:{}}}return{text:"",...o!==void 0?{normalized:o}:{}}}return typeof i=="string"&&i?{text:i}:i!=null?{text:ua(i)}:{text:""}}function F2(r,e){let t=r;for(let n of[UR,CA]){let i=n===CA;for(;n.test(t);){let o=n.exec(t);if(i&&!o)throw M2("date",t,n);let s=o?.[i?2:1]?.replace("+","").trim(),a=s&&qR.test(s)?parseInt(s):void 0,l=o?.[i?3:2],c=e.clocks(),u=aa({...i?{format:o?.[1]}:{},offset:a,snap:l?JN(l)??void 0:void 0,origin:c?.date,now:c?.now});t=D2(t,n,e.applyCase(u,o?.[i?4:3],o?.[0]??"{{DATE}}"))}}return t}function P2(r,e){let t=r;for(let n of[HR,xA]){let i=n===xA;for(;n.test(t);){let o=n.exec(t);if(!o)throw M2("time",t,n);let s=aa({format:i?o[1]:"HH:mm",now:e.clocks()?.now});t=D2(t,n,e.applyCase(s,o[i?2:1],o[0]))}}return t}function M2(r,e,t){let n=e.search(t);return new Error(`Unable to parse ${r} format. Invalid syntax in: "${e.substring(Math.max(0,n-10),Math.min(e.length,n+30))}..."`)}async function $2(r,e){let t=new RegExp(mc.source,"gi"),n="",i=0,o;for(;(o=t.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:u,caseStyle:d}=Fv(o[3]),p=o[2]?.trim()||Mf(c);if(e.variables.get(s)===void 0){let g=await e.prompt(s,{type:"VDATE",dateFormat:p,defaultValue:a,optional:l,withTime:c});if(l&&!g?.trim())e.variables.set(s,"");else if(g?.startsWith("@date:"))e.variables.set(s,g);else{if(!e.dateParser)throw new Error("Date parser is not available");let v=X.getState().dateAliases,y=kg(g,v),b=e.dateParser.parseDate(y);if(b)e.variables.set(s,`@date:${b.moment.toISOString()}`);else throw new Error(`unable to parse date variable ${g}${l?"":". Tip: add |optional inside the {{VDATE}} token to allow leaving this date empty"}`)}}let m=$f(e.variables.get(s),p,u,e.dateParser);m?.normalized!==void 0&&e.variables.set(s,m.normalized),n+=e.applyCase(m?.text??"",d,o[0])}return n+r.slice(i)}var gD=E(()=>{Xe();ht();dt();td();Yg();Pv();Id()});function Dd(r){let e=[],t=r.length,n=0;for(;n<t;){let i=r.indexOf("`",n);if(i===-1)break;let o=i;for(;o<t&&r[o]==="`";)o++;if(o-i<3||!r.startsWith(vD,o)){n=o;continue}let s=o+vD.length,a=-1;for(;s<t;){let l=r.indexOf("`",s);if(l===-1)break;let c=l;for(;c<t&&r[c]==="`";)c++;if(c-l>=3){a=c;break}s=c}if(a===-1)break;e.push({start:i,end:a}),n=a}return e}function yD(r){let e=Dd(r),t=r.length,n=e.length>0?e[e.length-1].end:0;for(;n<t;){let i=r.indexOf("`",n);if(i===-1)return!1;let o=i;for(;o<t&&r[o]==="`";)o++;if(o-i>=3&&r.startsWith(vD,o))return!0;n=o}return!1}var vD,bD=E(()=>{vD="js quickadd"});function O2(r,e,t,n){let i=new Map,o=new Set,s={LINKCURRENT:e.links,LINKSECTION:e.links,FILENAMECURRENT:e.fileName,FOLDER:e.folder,FOLDERCURRENT:e.activeFolder,TITLE:e.title},a=r.replace(/{{(?:(LINKCURRENT|LINKSECTION|FILENAMECURRENT|TITLE)|(FOLDERCURRENT|FOLDER)(\|name)?)}}/gi,(c,u,d,p)=>{let f=(u??d??"").toUpperCase();if(!(f in t))return c;let m=f;if(!s[m])return c;i.has(m)||i.set(m,t[m]());let g=i.get(m)??null;return(m==="FOLDERCURRENT"?g===null:(m==="LINKCURRENT"||m==="LINKSECTION"||m==="FILENAMECURRENT")&&!g)&&o.add(m),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")&&e.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);I.logMessage("Skipping current-file token replacement because no active file is available.")}return a}var R2=E(()=>{Ie()});function L2(r,e,t){return Array.isArray(r)?r.map(n=>N2(n,e,t)):N2(r,e,t)}function N2(r,e,t){if(e==="link")return t(r);let n=Td(r);switch(n.kind){case"empty":return"";case"file":return e==="path"?n.path:Mc(n.path);case"custom":case"raw":return n.kind==="custom"?n.text:n.value}}var V2=E(()=>{lo()});function B2(r){if(!r)return null;let e=r.indexOf("|");if(e===-1){let o=r.trim();return o?{macroName:o}:null}let t=r.slice(0,e).trim();if(!t)return null;let n=r.slice(e+1).trim();if(!n)return{macroName:t};if(!n.toLowerCase().startsWith("label:"))return null;let i=n.slice(6).trim();return{macroName:t,label:i||void 0}}var q2=E(()=>{});function H2(r){let e=r.trim();if(!e||/[\r\n\0]/.test(e)||e==="__proto__")throw new Error("Property name must be nonempty and contain no line breaks or unsafe keys.");return e}function z2(r){return Ag.test(r)}function W2(r){if(r==null)return"";if(Array.isArray(r)){if(!r.every(e=>typeof e=="string"))throw new Error("{{PROPERTY}} only expands lists of text.");if(r.some(e=>/[\r\n]/.test(e)))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 G2(r){return j2.map(e=>({key:e,present:r.has(e),value:r.get(e)}))}function Y2(r,e){for(let t of e)t.present?r.set(t.key,t.value):r.delete(t.key)}function K2(r,e,t){for(let i of j2)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;t!=null&&(n=SX(t,e)),r.set("propertyKey",e),r.set("propertyValue",n),r.set("list",Array.isArray(n)?[...n]:[])}function SX(r,e){if(typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r))return r;if(Array.isArray(r)&&r.every(t=>typeof t=="string"))return[...r];throw new Error(`Property '${e}' supports text, finite numbers, checkboxes, and lists of text only.`)}function Mv(r,e){if(Object.prototype.hasOwnProperty.call(r,e))return e;let t=Object.keys(r).filter(n=>n.trim().toLowerCase()===e.trim().toLowerCase());if(t.length>1)throw new Error(`Property '${e}' matches multiple properties in the target note.`);return t[0]??e}function Q2(r){return r.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!=="")}function X2(r){return typeof r=="string"?Q2(r).length===0:Array.isArray(r)&&r.length===0}function U2(r,e){if(typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r))return r;if(Array.isArray(r)&&r.every(t=>typeof t=="string"))return[...r];throw new Error(`Property '${e}' supports text, finite numbers, checkboxes, and lists of text only.`)}function _X(r,e){if(r===null&&["tags","aliases","cssclasses"].includes(e.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 '${e}' has unsupported type '${r}'.`)}}function Mx(r){return Array.isArray(r)?"list":typeof r=="boolean"?"checkbox":typeof r=="number"?"number":"text"}function AX(r,e,t){let n=Mx(r);if(e==="date"||e==="datetime"){if(typeof r=="string"&&(r===""||(e==="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===e)return;throw new Error(`Property '${t}' requires ${e}; the capture is ${n}. Use a matching typed VALUE token or value.`)}function Z2(r){let{frontmatter:e,config:t}=r,n=Mv(e,r.key),i=Object.prototype.hasOwnProperty.call(e,n);if(!i&&!t.createIfMissing)throw new Error(`Property '${n}' is missing. Enable 'Create property if missing' to add it.`);let o=i?e[n]:void 0,s=U2(r.value,n),a=o==null?null:U2(o,n),l=_X(r.registeredType,n)??(a===null?null:Mx(a)),c=typeof s=="string"?Q2(s):null;if(t.action==="addToList"){if(a!==null&&!Array.isArray(a))throw new Error(`Property '${n}' is ${Mx(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 d=c??s;if(!Array.isArray(d))throw new Error(`Property '${n}' requires text or a list of text to add.`);return d.length===0?a??[]:r.compose?[...new Set(d)]:[...new Set([...a??[],...d])]}if(l==="list"&&a!==null&&!Array.isArray(a))throw new Error(`Property '${n}' contains ${Mx(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 u=l==="list"?c??s:s;return l!==null&&AX(u,l,n),Array.isArray(u)?[...new Set(u)]:u}function J2(r){let e=(0,Fd.getFrontMatterInfo)(r);if(!e.exists||!e.frontmatter.trim())return{};let t=(0,Fd.parseYaml)(e.frontmatter);if(t===null)return{};if(!t||typeof t!="object"||Array.isArray(t))throw new Error("The capture target's frontmatter must be a property mapping.");return Object.fromEntries(Object.entries(t))}function eV(r,e){let t=(0,Fd.getFrontMatterInfo)(r),n=t.exists?r.slice(t.contentStart):r;return`---
${(0,Fd.stringifyYaml)(e)}---
${n}`}var Fd,j2,wD=E(()=>{Fd=require("obsidian");Xe();j2=["propertyKey","propertyValue","list"]});var tV,$x,Lc,Pd=E(()=>{hD();gD();gD();bD();R2();tV=require("obsidian");Xe();lo();V2();Ie();rx();hl();q2();wD();hD();bD();$x=10,Lc=class extends Fx{constructor(){super(...arguments);this.linkToCurrentFileBehavior="required";this.targetFolderPath=null;this.propertyTokenExpanded=!1}runClocks(){return this.clocks}setTemplateInclusionState(t){this.templateInclusion=t}replaceDateInString(t){return F2(t,{clocks:()=>this.runClocks(),applyCase:(n,i,o)=>this.applyCaseOption(n,i,o)})}replaceTimeInString(t){return P2(t,{clocks:()=>this.runClocks(),applyCase:(n,i,o)=>this.applyCaseOption(n,i,o)})}async replaceSelectedInString(t){if(!SA.test(t))return t;let n=await this.getSelectedText(),i=new RegExp(SA.source,"gi");return t.replace(i,()=>n)}async replaceClipboardInString(t){if(!_A.test(t))return t;let n=await this.getClipboardContent(),i=new RegExp(_A.source,"gi");return t.replace(i,()=>n)}async replaceLinkToCurrentFileInString(t){if(!EA.test(t))return t;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.");I.logMessage("Skipping {{LINKCURRENT}} replacement because no active file is available.")}let i=new RegExp(EA.source,"gi");return t.replace(i,()=>n??"")}replaceLinkToCurrentSectionInString(t){if(!TA.test(t))return t;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.");I.logMessage("Skipping {{LINKSECTION}} replacement because no active file is available.")}let i=new RegExp(TA.source,"gi");return t.replace(i,()=>n??"")}replaceCurrentFileLinksInString(t){return this.replaceCurrentFileTokensInString(t,{links:!0})}replaceCurrentFileTokensInString(t,n){return O2(t,n,{LINKCURRENT:()=>this.getCurrentFileLink(),LINKSECTION:()=>this.getCurrentFileLinkToSection(),FILENAMECURRENT:()=>this.getCurrentFileName(),FOLDER:()=>this.targetFolderPath??"",FOLDERCURRENT:()=>this.getCurrentFolderPath(),TITLE:()=>this.getVariableValue("title")},this.linkToCurrentFileBehavior)}async replaceCurrentFileNameInString(t){return this.replaceCurrentFileTokensInString(t,{fileName:!0})}setLinkToCurrentFileBehavior(t){this.linkToCurrentFileBehavior=t}setTargetFolderPath(t){if(t==null){this.targetFolderPath=null;return}let n=t.trim();this.targetFolderPath=n==="/"?"":n.replace(/^\/+/,"").replace(/\/+$/,"")}replaceTargetFolderInString(t){return this.replaceCurrentFileTokensInString(t,{folder:!0})}getCurrentFileLinkToSection(){return null}getCurrentFolderPath(){return null}async replaceFieldVarInString(t){let n=new RegExp(cC.source,"gi"),i="",o=0,s;for(;(s=n.exec(t))!==null;){i+=t.slice(o,s.index);let a=s[1]+(s[2]||"");if(a){let l=this.getFieldVariableKey(a),c=oi.parse(a,{warnUnknown:!0,warn:this.warnSink});this.hasConcreteVariable(l)||this.variables.set(l,await this.suggestForField(a,c));let u=this.hasConcreteVariable(l)?this.variables.get(l):this.getVariableValue(l);(!c.multiFormat||c.multiFormat==="auto")&&this.retainSingleTokenValue(t,s.index,s.index+s[0].length,u);let d;Array.isArray(u)?d=this.renderCollectedOrArrayValue({input:t,matchStart:s.index,matchEnd:s.index+s[0].length,rawValue:u,fallbackKey:c.fieldName,heuristicEnabled:!1,multiFormat:c.multiFormat??"auto"})??u.join(","):d=Ed(t,s.index,s.index+s[0].length,String(u??"")),i+=d}else i+=s[0];o=n.lastIndex}return i+t.slice(o)}getFieldVariableKey(t){return`${sd}${t}`}async replaceFileInString(t){let n=new RegExp(uC.source,"gi"),i="",o=0,s;for(;(s=n.exec(t))!==null;){i+=t.slice(o,s.index);let a=ax(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=L2(this.variables.get(l),a.mode,u=>this.getFileLinkForStoredValue(u));if(Array.isArray(c)){let u=this.renderCollectedOrArrayValue({input:t,matchStart:s.index,matchEnd:s.index+s[0].length,rawValue:c,fallbackKey:a.aliasName??a.folderPath,heuristicEnabled:!1,multiFormat:a.multiFormat});i+=u??c.join(",")}else i+=c;o=n.lastIndex}return i+t.slice(o)}getFileLinkForStoredValue(t){let n=Td(t);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 tV.TFile?this.app?.fileManager.generateMarkdownLink(o,this.getLinkSourcePath()??"")??`[[${Mc(i)}]]`:`[[${Mc(i)}]]`}getLinkSourcePath(){return null}async replaceMathValueInString(t){let n=new RegExp(pC.source,"gi"),i=this.variables.get("mvalue"),o=typeof i=="string"&&i.trim()?i:null,s="",a=0,l;for(;(l=n.exec(t))!==null;)s+=t.slice(a,l.index),s+=o??await this.promptForMathValue(),a=l.index+l[0].length;return s+=t.slice(a),s}async replaceMacrosInString(t){let n=t;for(;hc.test(n);){let i=hc.exec(n);if(!i)continue;if(!i[1]){n=this.replacer(n,hc,"");continue}let o=B2(i[1]);if(!o){n=this.replacer(n,hc,"");continue}let{macroName:s,label:a}=o,l=await this.getMacroValue(s,a?{label:a}:void 0);n=this.replacer(n,hc,l?l.toString():"")}return n}async replaceDateVariableInString(t){return $2(t,{variables:this.variables,dateParser:this.dateParser,prompt:(n,i)=>this.promptForVariable(n,i),applyCase:(n,i,o)=>this.applyCaseOption(n,i,o)})}async replaceTemplateInString(t){let n=t;for(;Oo.test(n);){let i=Oo.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,Oo,a);continue}if(this.templateInclusion.depth>=$x){let a=`[QuickAdd: max template inclusion depth (${$x}) exceeded at "${o}"]`;this.reportProblem(a),n=this.replacer(n,Oo,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,Oo,s)}return n}replaceLinebreakInString(t){let n="";for(let i=0;i<t.length;i++){let o=t[i],s=t[i+1];o=="\\"?s=="n"?(n+=`
`,i++):s=="\\"?(n+="\\",i++):n+="\\":n+=o}return n}expandLinebreakEscapesOutsideTokens(t){let n=Dd(t),i="",o=0,s=0;for(;o<t.length;){for(;s<n.length&&n[s].end<=o;)s++;let a=n[s];if(a&&a.start===o){i+=t.slice(a.start,a.end),o=a.end;continue}if(t[o]==="{"&&t[o+1]==="{"){let u=t.indexOf("}}",o+2),d=!1;if(u!==-1){let p=u+2;for(let f=s;f<n.length;f++){let m=n[f];if(m.start>=p)break;if(p<m.end&&p>m.start){d=!0;break}}}if(u!==-1&&!d){i+=t.slice(o,u+2),o=u+2;continue}}let l=t[o],c=t[o+1];l==="\\"?c==="n"?(i+=`
`,o+=2):c==="\\"?(i+="\\",o+=2):(i+="\\",o+=1):(i+=l,o+=1)}return i}replaceRandomInString(t){let n=t;for(;AA.test(n);){let i=AA.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(t){return this.replaceCurrentFileTokensInString(t,{title:!0})}consumePropertyTokenExpanded(){let t=this.propertyTokenExpanded;return this.propertyTokenExpanded=!1,t}replacePropertyInString(t){if(!Ag.test(t))return t;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(t.trim())&&t.trim()===t&&this.retainSingleTokenValue(t,0,t.length,n===void 0?"":n);let i=W2(n);return t.replace(new RegExp(Ag.source,"gi"),()=>i)}}});function nV(r){return r<=31||r===127||r===8232||r===8233}function PX(r){let e="",t=0;for(;t<r.length;){let n=t;for(;n<r.length&&r.charCodeAt(n)===32;)n++;if(n<r.length&&nV(r.charCodeAt(n))){for(;n<r.length&&nV(r.charCodeAt(n));)n++;for(;n<r.length&&r.charCodeAt(n)===32;)n++;e+=" ",t=n;continue}e+=r.slice(t,Math.min(n+1,r.length)),t=n+1}return e}function iV(r,e){let t=r.length;for(;t>0&&e.includes(r[t-1]);)t--;return r.slice(0,t)}function Md(r){return MX.filter(e=>r.includes(e))}function sV(r){return`A file or folder name cannot contain ${cV(r)}, so this choice would fail at run time. ${lV}`}function aV(r,e){return`Cannot create "${e}": a file or folder name cannot contain ${cV(r)}. ${lV}`}function cV(r){return r.map(e=>`"${e}"`).join(", ")}function Wn(r,e="File path"){let{path:t,problems:n}=dV(r,e);if(n.length>0)throw new Error(n[0]);return t}function uV(r,e="File path"){return dV(r,e)}function dV(r,e){let t=[],n=r.replace(/\\/g,"/").split("/");return{path:n.map((o,s)=>o.length===0&&s!==0&&s!==n.length-1?(t.push(`${e} contains an empty path segment after formatting.`),o):$X(o,e,t)).join("/"),problems:t}}function $X(r,e,t){if(r.length===0)return r;let n=DX.test(r),i=FX.test(r),o=PX(r);n&&(o=o.replace(/^ /u,"")),i&&(o=o.replace(/ $/u,""));let s=iV(o," ");return s==="."||s===".."?(t.push(`${e} cannot contain "." or ".." path segments.`),s):(o=iV(o,". "),o||t.push(`${e} contains an empty path segment after formatting.`),o)}var oV,DX,FX,MX,lV,da=E(()=>{oV="\0-\x7F\u2028\u2029",DX=new RegExp(`^ *[${oV}]`,"u"),FX=new RegExp(`[${oV}] *$`,"u");MX=[":"];lV="Check your own text and tokens like {{TIME}}, which is HH:mm."});function Bc(r,e){let t=r,n=new RegExp(dC.source,"gi"),i=0;for(;n.test(t)&&!(++i>5);)t=t.replace(n,(o,s)=>{let a=String(s??"").trim();if(!a)return o;let l=e?.[a];return typeof l=="string"?l:""});return t}var $v=E(()=>{Xe()});var gt,Qt,po,Cl=E(()=>{(function(r){r[r.AM=0]="AM",r[r.PM=1]="PM"})(gt||(gt={}));(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"})(Qt||(Qt={}));(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"})(po||(po={}))});function Fs(r,e){r.assign("day",e.getDate()),r.assign("month",e.getMonth()+1),r.assign("year",e.getFullYear())}function Bx(r,e){r.assign("hour",e.getHours()),r.assign("minute",e.getMinutes()),r.assign("second",e.getSeconds()),r.assign("millisecond",e.getMilliseconds()),r.assign("meridiem",e.getHours()<12?gt.AM:gt.PM)}function xl(r,e){r.imply("day",e.getDate()),r.imply("month",e.getMonth()+1),r.imply("year",e.getFullYear())}function Ov(r,e){r.imply("hour",e.getHours()),r.imply("minute",e.getMinutes()),r.imply("second",e.getSeconds()),r.imply("millisecond",e.getMilliseconds()),r.imply("meridiem",e.getHours()<12?gt.AM:gt.PM)}var $d=E(()=>{Cl()});function qc(r,e,t,n,i=0){let o=0,s=0;for(;s<n;)o++,new Date(r,e-1,o).getDay()===t&&s++;return new Date(r,e-1,o,i)}function hV(r,e,t,n=0){let i=t===0?7:t,o=new Date(r,e-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,e-1,o.getDate(),n)}function qx(r,e,t={}){if(r==null)return null;if(typeof r=="number")return r;let n=t[r]??VX[r];return n==null?null:typeof n=="number"?n:e==null?null:e>n.dstStart(e.getFullYear())&&!(e>n.dstEnd(e.getFullYear()))?n.timezoneOffsetDuringDst:n.timezoneOffsetNonDst}var VX,CD=E(()=>{Cl();VX={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=>hV(r,po.MARCH,Qt.SUNDAY,2),dstEnd:r=>hV(r,po.OCTOBER,Qt.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-300,timezoneOffsetNonDst:-360,dstStart:r=>qc(r,po.MARCH,Qt.SUNDAY,2,2),dstEnd:r=>qc(r,po.NOVEMBER,Qt.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=>qc(r,po.MARCH,Qt.SUNDAY,2,2),dstEnd:r=>qc(r,po.NOVEMBER,Qt.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=>qc(r,po.MARCH,Qt.SUNDAY,2,2),dstEnd:r=>qc(r,po.NOVEMBER,Qt.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=>qc(r,po.MARCH,Qt.SUNDAY,2,2),dstEnd:r=>qc(r,po.NOVEMBER,Qt.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 _n(r,e){let t=new Date(r);if(e.y&&(e.year=e.y,delete e.y),e.mo&&(e.month=e.mo,delete e.mo),e.M&&(e.month=e.M,delete e.M),e.w&&(e.week=e.w,delete e.w),e.d&&(e.day=e.d,delete e.d),e.h&&(e.hour=e.h,delete e.h),e.m&&(e.minute=e.m,delete e.m),e.s&&(e.second=e.s,delete e.s),e.ms&&(e.millisecond=e.ms,delete e.ms),"year"in e){let n=Math.floor(e.year);t.setFullYear(t.getFullYear()+n);let i=e.year-n;i>0&&(e.month=e?.month??0,e.month+=i*12)}if("quarter"in e){let n=Math.floor(e.quarter);t.setMonth(t.getMonth()+n*3)}if("month"in e){let n=Math.floor(e.month);t.setMonth(t.getMonth()+n);let i=e.month-n;i>0&&(e.week=e?.week??0,e.week+=i*4)}if("week"in e){let n=Math.floor(e.week);t.setDate(t.getDate()+n*7);let i=e.week-n;i>0&&(e.day=e?.day??0,e.day+=Math.round(i*7))}if("day"in e){let n=Math.floor(e.day);t.setDate(t.getDate()+n);let i=e.day-n;i>0&&(e.hour=e?.hour??0,e.hour+=Math.round(i*24))}if("hour"in e){let n=Math.floor(e.hour);t.setHours(t.getHours()+n);let i=e.hour-n;i>0&&(e.minute=e?.minute??0,e.minute+=Math.round(i*60))}if("minute"in e){let n=Math.floor(e.minute);t.setMinutes(t.getMinutes()+n);let i=e.minute-n;i>0&&(e.second=e?.second??0,e.second+=Math.round(i*60))}if("second"in e){let n=Math.floor(e.second);t.setSeconds(t.getSeconds()+n);let i=e.second-n;i>0&&(e.millisecond=e?.millisecond??0,e.millisecond+=Math.round(i*1e3))}if("millisecond"in e){let n=Math.floor(e.millisecond);t.setMilliseconds(t.getMilliseconds()+n)}return t}function Uc(r){let e={};for(let t in r)e[t]=-r[t];return e}var gV,El=E(()=>{gV={day:0,second:0,millisecond:0}});var Hc,Tt,Tl,Ps=E(()=>{$d();CD();El();Hc=class r{constructor(e,t){he(this,"instant");he(this,"timezoneOffset");this.instant=e??new Date,this.timezoneOffset=t??null}static fromDate(e){return new r(e)}static fromInput(e,t){if(e instanceof Date)return r.fromDate(e);let n=e?.instant??new Date,i=qx(e?.timezone,n,t);return new r(n,i)}getDateWithAdjustedTimezone(){let e=new Date(this.instant);return this.timezoneOffset!==null&&e.setMinutes(e.getMinutes()-this.getSystemTimezoneAdjustmentMinute(this.instant)),e}getSystemTimezoneAdjustmentMinute(e,t){e||(e=new Date);let n=-e.getTimezoneOffset(),i=t??this.timezoneOffset??n;return n-i}getTimezoneOffset(){return this.timezoneOffset??-this.instant.getTimezoneOffset()}},Tt=class r{constructor(e,t){he(this,"knownValues");he(this,"impliedValues");he(this,"reference");he(this,"_tags",new Set);if(this.reference=e,this.knownValues={},this.impliedValues={},t)for(let i in t)this.knownValues[i]=t[i];let n=e.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(e,t=gV){let n=_n(e.getDateWithAdjustedTimezone(),t),i=new r(e);return i.addTag("result/relativeDate"),"hour"in t||"minute"in t||"second"in t||"millisecond"in t?(i.addTag("result/relativeDateAndTime"),Bx(i,n),Fs(i,n),i.assign("timezoneOffset",e.getTimezoneOffset())):(Ov(i,n),i.imply("timezoneOffset",e.getTimezoneOffset()),"day"in t?(i.assign("day",n.getDate()),i.assign("month",n.getMonth()+1),i.assign("year",n.getFullYear()),i.assign("weekday",n.getDay())):"week"in t?(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 t?(i.assign("month",n.getMonth()+1),i.assign("year",n.getFullYear())):(i.imply("month",n.getMonth()+1),"year"in t?i.assign("year",n.getFullYear()):i.imply("year",n.getFullYear())))),i}get(e){return e in this.knownValues?this.knownValues[e]:e in this.impliedValues?this.impliedValues[e]:null}isCertain(e){return e in this.knownValues}getCertainComponents(){return Object.keys(this.knownValues)}imply(e,t){return e in this.knownValues?this:(this.impliedValues[e]=t,this)}assign(e,t){return this.knownValues[e]=t,delete this.impliedValues[e],this}addDurationAsImplied(e){let t=this.dateWithoutTimezoneAdjustment(),n=_n(t,e);return("day"in e||"week"in e||"month"in e||"year"in e)&&(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 e||"minute"in e||"hour"in e)&&(this.delete(["second","minute","hour"]),this.imply("second",n.getSeconds()),this.imply("minute",n.getMinutes()),this.imply("hour",n.getHours())),this}delete(e){typeof e=="string"&&(e=[e]);for(let t of e)delete this.knownValues[t],delete this.impliedValues[t]}clone(){let e=new r(this.reference);e.knownValues={},e.impliedValues={};for(let t in this.knownValues)e.knownValues[t]=this.knownValues[t];for(let t in this.impliedValues)e.impliedValues[t]=this.impliedValues[t];return e}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 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")),!(e.getUTCFullYear()!==this.get("year")||e.getUTCMonth()!==this.get("month")-1||e.getUTCDate()!==this.get("day")||this.get("hour")!=null&&e.getUTCHours()!=this.get("hour")||this.get("minute")!=null&&e.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 e=this.get("timezoneOffset")??this.reference.timezoneOffset;if(e==null)return this.dateWithoutTimezoneAdjustment();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")),new Date(t.getTime()-e*6e4)}addTag(e){return this._tags.add(e),this}addTags(e){for(let t of e)this._tags.add(t);return this}tags(){return new Set(this._tags)}dateWithoutTimezoneAdjustment(){let e=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 e.setFullYear(this.get("year")),e}},Tl=class r{constructor(e,t,n,i,o){he(this,"refDate");he(this,"index");he(this,"text");he(this,"reference");he(this,"start");he(this,"end");this.reference=e,this.refDate=e.instant,this.index=t,this.text=n,this.start=i||new Tt(e),this.end=o}clone(){let e=new r(this.reference,this.index,this.text);return e.start=this.start?this.start.clone():null,e.end=this.end?this.end.clone():null,e}date(){return this.start.date()}addTag(e){return this.start.addTag(e),this.end&&this.end.addTag(e),this}addTags(e){return this.start.addTags(e),this.end&&this.end.addTags(e),this}tags(){let e=new Set(this.start.tags());if(this.end)for(let t of this.end.tags())e.add(t);return e}toString(){let e=Array.from(this.tags()).sort();return`[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(e)} ...}]`}}});function xD(r,e,t="\\s{0,5},?\\s{0,5}"){let n=e.replace(/\((?!\?)/g,"(?:");return`${r}${n}(?:${t}${n}){0,10}`}function BX(r){let e;return r instanceof Array?e=[...r]:r instanceof Map?e=Array.from(r.keys()):e=Object.keys(r),e}function an(r){return`(?:${BX(r).sort((t,n)=>n.length-t.length).join("|").replace(/\./g,"\\.")})`}var kl=E(()=>{});function Ux(r){return r<100&&(r>50?r=r+1900:r=r+2e3),r}function zc(r,e,t){let n=new Date(r);n.setMonth(t-1),n.setDate(e);let i=_n(n,{year:1}),o=_n(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 Vf=E(()=>{El()});function qX(r){let e=r.toLowerCase();return ED[e]!==void 0?ED[e]:e==="a"||e==="an"||e=="the"?1:e.match(/few/)?3:e.match(/half/)?.5:e.match(/couple/)?2:e.match(/several/)?7:parseFloat(e)}function qf(r){let e=r.toLowerCase();return TD[e]!==void 0?TD[e]:(e=e.replace(/(?:st|nd|rd|th)$/i,""),parseInt(e))}function fa(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 e=parseInt(r);return Ux(e)}function Yo(r){let e={},t=r,n=vV.exec(t);for(;n;)HX(e,n),t=t.substring(n[0].length).trim(),n=vV.exec(t);return Object.keys(e).length==0?null:e}function HX(r,e){if(e[0].match(/^[a-zA-Z]+$/))return;let t=qX(e[1]),n=Rv[e[2].toLowerCase()];r[n]=t}var Hx,kD,ki,ED,TD,yV,Rv,bV,Bf,Wc,wV,vV,UX,CV,Sl,jc,Fr=E(()=>{kl();Vf();Hx={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},kD={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},ki={...kD,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},ED={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},TD={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},yV={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"},Rv={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",...yV},bV=`(?:${an(ED)}|[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)?)`;Bf=`(?:${an(TD)}|[0-9]{1,2}(?:st|nd|rd|th)?)`;Wc="(?:[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)))";wV=`(${bV})\\s{0,3}(${an(Rv)})`,vV=new RegExp(wV,"i"),UX=`(${bV})\\s{0,3}(${an(yV)})`,CV="\\s{0,5},?(?:\\s*and)?\\s{0,5}",Sl=xD("(?:(?:about|around)\\s{0,3})?",wV,CV),jc=xD("(?:(?:about|around)\\s{0,3})?",UX,CV)});var Dt,ai=E(()=>{Dt=class{constructor(){he(this,"cachedInnerPattern",null);he(this,"cachedPattern",null)}innerPatternHasChange(e,t){return this.innerPattern(e)!==t}patternLeftBoundary(){return"(\\W|^)"}pattern(e){return this.cachedInnerPattern&&!this.innerPatternHasChange(e,this.cachedInnerPattern)?this.cachedPattern:(this.cachedInnerPattern=this.innerPattern(e),this.cachedPattern=new RegExp(`${this.patternLeftBoundary()}${this.cachedInnerPattern.source}`,this.cachedInnerPattern.flags),this.cachedPattern)}extract(e,t){let n=t[1]??"";t.index=t.index+n.length,t[0]=t[0].substring(n.length);for(let i=2;i<t.length;i++)t[i-1]=t[i];return this.innerExtract(e,t)}}});var zX,WX,jX,Nv,xV=E(()=>{Fr();Ps();ai();zX=new RegExp(`(?:(?:within|in|for)\\s*)?(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${Sl})(?=\\W|$)`,"i"),WX=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${Sl})(?=\\W|$)`,"i"),jX=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${jc})(?=\\W|$)`,"i"),Nv=class extends Dt{constructor(t){super();he(this,"strictMode");this.strictMode=t}innerPattern(t){return this.strictMode?jX:t.option.forwardDate?zX:WX}innerExtract(t,n){if(n[0].match(/^for\s*the\s*\w+/))return null;let i=Yo(n[1]);return i?Tt.createRelativeFromReference(t.reference,i):null}}});var GX,EV,TV,YX,kV,Lv,SV=E(()=>{Vf();Fr();Fr();Fr();kl();ai();GX=new RegExp(`(?:on\\s{0,3})?(${Bf})(?:\\s{0,3}(?:to|\\-|\\\u2013|until|through|till)\\s{0,3}(${Bf}))?(?:-|/|\\s{0,3}(?:of)?\\s{0,3})(${an(ki)})(?:(?:-|/|,?\\s{0,3})(${Wc}(?!\\w)))?(?=\\W|$)`,"i"),EV=1,TV=2,YX=3,kV=4,Lv=class extends Dt{innerPattern(){return GX}innerExtract(e,t){let n=e.createParsingResult(t.index,t[0]),i=ki[t[YX].toLowerCase()],o=qf(t[EV]);if(o>31)return t.index=t.index+t[EV].length,null;if(n.start.assign("month",i),n.start.assign("day",o),t[kV]){let s=fa(t[kV]);n.start.assign("year",s)}else{let s=zc(e.refDate,o,i);n.start.imply("year",s)}if(t[TV]){let s=qf(t[TV]);n.end=n.start.clone(),n.end.assign("day",s)}return n}}});var KX,QX,_V,SD,_D,Vv,AV=E(()=>{Vf();Fr();Fr();Fr();kl();ai();KX=new RegExp(`(${an(ki)})(?:-|/|\\s*,?\\s*)(${Bf})(?!\\s*(?:am|pm))\\s*(?:(?:to|\\-)\\s*(${Bf})\\s*)?(?:(?:-|/|\\s*,\\s*|\\s+)(${Wc}))?(?=\\W|$)(?!\\:\\d)`,"i"),QX=1,_V=2,SD=3,_D=4,Vv=class extends Dt{constructor(t){super();he(this,"shouldSkipYearLikeDate");this.shouldSkipYearLikeDate=t}innerPattern(){return KX}innerExtract(t,n){let i=ki[n[QX].toLowerCase()],o=qf(n[_V]);if(o>31||this.shouldSkipYearLikeDate&&!n[SD]&&!n[_D]&&n[_V].match(/^\d{2}$/))return null;let s=t.createParsingComponents({day:o,month:i}).addTag("parser/ENMonthNameMiddleEndianParser");if(n[_D]){let c=fa(n[_D]);s.assign("year",c)}else{let c=zc(t.refDate,o,i);s.imply("year",c)}if(!n[SD])return s;let a=qf(n[SD]),l=t.createParsingResult(n.index,n[0]);return l.start=s,l.end=s.clone(),l.end.assign("day",a),l}}});var XX,ZX,JX,IV,Bv,DV=E(()=>{Fr();Vf();kl();Fr();ai();XX=new RegExp(`((?:in)\\s*)?(${an(ki)})\\s*(?:(?:,|-|of)?\\s*(${Wc})?)?(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`,"i"),ZX=1,JX=2,IV=3,Bv=class extends Dt{innerPattern(){return XX}innerExtract(e,t){let n=t[JX].toLowerCase();if(t[0].length<=3&&!kD[n])return null;let i=e.createParsingResult(t.index+(t[ZX]||"").length,t.index+t[0].length);i.start.imply("day",1),i.start.addTag("parser/ENMonthNameParser");let o=ki[n];if(i.start.assign("month",o),t[IV]){let s=fa(t[IV]);i.start.assign("year",s)}else{let s=zc(e.refDate,1,o);i.start.imply("year",s)}return i}}});var e7,t7,r7,FV,n7,qv,PV=E(()=>{Fr();kl();ai();e7=new RegExp(`([0-9]{4})[-\\.\\/\\s](?:(${an(ki)})|([0-9]{1,2}))[-\\.\\/\\s]([0-9]{1,2})(?=\\W|$)`,"i"),t7=1,r7=2,FV=3,n7=4,qv=class extends Dt{constructor(t){super();he(this,"strictMonthDateOrder");this.strictMonthDateOrder=t}innerPattern(){return e7}innerExtract(t,n){let i=parseInt(n[t7]),o=parseInt(n[n7]),s=n[FV]?parseInt(n[FV]):ki[n[r7].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 i7,o7,s7,a7,Uv,MV=E(()=>{Fr();kl();Fr();ai();i7="(?:[1-9][0-9]{0,3}\\s{0,2}(?:BE|AD|BC|BCE|CE)|[1-9][0-9]{3})",o7=new RegExp(`(${i7})(?:\\s*[-.\\/,]?\\s*|\\s+of\\s+)(${an(ki)})(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`,"i"),s7=1,a7=2,Uv=class extends Dt{innerPattern(){return o7}innerExtract(e,t){let n=fa(t[s7]),i=t[a7].toLowerCase(),o=ki[i],s=e.createParsingResult(t.index,t[0]);return s.start.imply("day",1),s.start.assign("month",o),s.start.assign("year",n),s.start.addTag("parser/ENYearMonthNameParser"),s}}});var l7,c7,u7,Hv,$V=E(()=>{ai();l7=new RegExp("([0-9]|0[1-9]|1[012])/([0-9]{4})","i"),c7=1,u7=2,Hv=class extends Dt{innerPattern(){return l7}innerExtract(e,t){let n=parseInt(t[u7]),i=parseInt(t[c7]);return e.createParsingComponents().imply("day",1).assign("month",i).assign("year",n)}}});function d7(r,e,t,n){return new RegExp(`${r}${e}(\\d{1,4})(?:(?:\\.|:|\uFF1A)(\\d{1,2})(?:(?::|\uFF1A)(\\d{2})(?:\\.(\\d{1,6}))?)?)?(?:\\s*(a\\.m\\.|p\\.m\\.|am?|pm?))?${t}`,n)}function p7(r,e){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?))?${e}`,"i")}var AD,Od,zx,Wx,Uf,jx,OV=E(()=>{Cl();AD=2,Od=3,zx=4,Wx=5,Uf=6,jx=class{constructor(e=!1){he(this,"strictMode");he(this,"cachedPrimaryPrefix",null);he(this,"cachedPrimarySuffix",null);he(this,"cachedPrimaryTimePattern",null);he(this,"cachedFollowingPhase",null);he(this,"cachedFollowingSuffix",null);he(this,"cachedFollowingTimePatten",null);this.strictMode=e}patternFlags(){return"i"}primaryPatternLeftBoundary(){return"(^|\\s|T|\\b)"}primarySuffix(){return"(?!/)(?=\\W|$)"}followingSuffix(){return"(?!/)(?=\\W|$)"}pattern(e){return this.getPrimaryTimePatternThroughCache()}extract(e,t){let n=this.extractPrimaryTimeComponents(e,t);if(!n)return t[0].match(/^\d{4}/)?(t.index+=4,null):(t.index+=t[0].length,null);let i=t.index+t[1].length,o=t[0].substring(t[1].length),s=e.createParsingResult(i,o,n);t.index+=t[0].length;let a=e.text.substring(t.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(e,c,s),s.end&&(s.text+=c[0]),this.checkAndReturnWithFollowingPattern(s))}extractPrimaryTimeComponents(e,t,n=!1){let i=e.createParsingComponents(),o=0,s=null,a=parseInt(t[AD]);if(a>100){if(t[AD].length==4&&t[Od]==null&&!t[Uf]||this.strictMode||t[Od]!=null)return null;o=a%100,a=Math.floor(a/100)}if(a>24)return null;if(t[Od]!=null){if(t[Od].length==1&&!t[Uf])return null;o=parseInt(t[Od])}if(o>=60)return null;if(a>12&&(s=gt.PM),t[Uf]!=null){if(a>12)return null;let l=t[Uf][0].toLowerCase();l=="a"&&(s=gt.AM,a==12&&(a=0)),l=="p"&&(s=gt.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",gt.AM):i.imply("meridiem",gt.PM),t[Wx]!=null){let l=parseInt(t[Wx].substring(0,3));if(l>=1e3)return null;i.assign("millisecond",l)}if(t[zx]!=null){let l=parseInt(t[zx]);if(l>=60)return null;i.assign("second",l)}return i}extractFollowingTimeComponents(e,t,n){let i=e.createParsingComponents();if(t[Wx]!=null){let l=parseInt(t[Wx].substring(0,3));if(l>=1e3)return null;i.assign("millisecond",l)}if(t[zx]!=null){let l=parseInt(t[zx]);if(l>=60)return null;i.assign("second",l)}let o=parseInt(t[AD]),s=0,a=-1;if(t[Od]!=null?s=parseInt(t[Od]):o>100&&(s=o%100,o=Math.floor(o/100)),s>=60||o>24)return null;if(o>=12&&(a=gt.PM),t[Uf]!=null){if(o>12)return null;let l=t[Uf][0].toLowerCase();l=="a"&&(a=gt.AM,o==12&&(o=0,i.isCertain("day")||i.imply("day",i.get("day")+1))),l=="p"&&(a=gt.PM,o!=12&&(o+=12)),n.start.isCertain("meridiem")||(a==gt.AM?(n.start.imply("meridiem",gt.AM),n.start.get("hour")==12&&n.start.assign("hour",0)):(n.start.imply("meridiem",gt.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",gt.AM):o<=12&&(i.assign("hour",o+12),i.assign("meridiem",gt.PM)):o>12?i.imply("meridiem",gt.PM):o<=12&&i.imply("meridiem",gt.AM),i.date().getTime()<n.start.date().getTime()&&i.imply("day",i.get("day")+1),i}checkAndReturnWithoutFollowingPattern(e){if(e.text.match(/^\d$/)||e.text.match(/^\d\d\d+$/)||e.text.match(/\d[apAP]$/))return null;let t=e.text.match(/[^\d:.](\d[\d.]+)$/);if(t){let n=t[1];if(this.strictMode||n.includes(".")&&!n.match(/\d(\.\d{2})+$/)||parseInt(n)>24)return null}return e}checkAndReturnWithFollowingPattern(e){if(e.text.match(/^\d+-\d+$/))return null;let t=e.text.match(/[^\d:.](\d[\d.]+)\s*-\s*(\d[\d.]+)$/);if(t){if(this.strictMode)return null;let n=t[1],i=t[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 e}getPrimaryTimePatternThroughCache(){let e=this.primaryPrefix(),t=this.primarySuffix();return this.cachedPrimaryPrefix===e&&this.cachedPrimarySuffix===t?this.cachedPrimaryTimePattern:(this.cachedPrimaryTimePattern=d7(this.primaryPatternLeftBoundary(),e,t,this.patternFlags()),this.cachedPrimaryPrefix=e,this.cachedPrimarySuffix=t,this.cachedPrimaryTimePattern)}getFollowingTimePatternThroughCache(){let e=this.followingPhase(),t=this.followingSuffix();return this.cachedFollowingPhase===e&&this.cachedFollowingSuffix===t?this.cachedFollowingTimePatten:(this.cachedFollowingTimePatten=p7(e,t),this.cachedFollowingPhase=e,this.cachedFollowingSuffix=t,this.cachedFollowingTimePatten)}}});var zv,RV=E(()=>{Cl();OV();zv=class extends jx{constructor(e){super(e)}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(e,t){let n=super.extractPrimaryTimeComponents(e,t);if(!n)return n;if(t[0].endsWith("night")){let i=n.get("hour");i>=6&&i<12?(n.assign("hour",n.get("hour")+12),n.assign("meridiem",gt.PM)):i<6&&n.assign("meridiem",gt.AM)}if(t[0].endsWith("afternoon")){n.assign("meridiem",gt.PM);let i=n.get("hour");i>=0&&i<=6&&n.assign("hour",n.get("hour")+12)}return t[0].endsWith("morning")&&(n.assign("meridiem",gt.AM),n.get("hour")<12&&n.assign("hour",n.get("hour"))),n.addTag("parser/ENTimeExpressionParser")}extractFollowingTimeComponents(e,t,n){let i=super.extractFollowingTimeComponents(e,t,n);return i&&i.addTag("parser/ENTimeExpressionParser"),i}}});var f7,m7,Wv,NV=E(()=>{Fr();Ps();ai();El();f7=new RegExp(`(${Sl})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),m7=new RegExp(`(${jc})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),Wv=class extends Dt{constructor(t){super();he(this,"strictMode");this.strictMode=t}innerPattern(){return this.strictMode?m7:f7}innerExtract(t,n){let i=Yo(n[1]);return i?Tt.createRelativeFromReference(t.reference,Uc(i)):null}}});var h7,g7,v7,jv,LV=E(()=>{Fr();Ps();ai();h7=new RegExp(`(${Sl})\\s{0,5}(?:later|after|from now|henceforth|forward|out)(?=(?:\\W|$))`,"i"),g7=new RegExp(`(${jc})\\s{0,5}(later|after|from now)(?=\\W|$)`,"i"),v7=1,jv=class extends Dt{constructor(t){super();he(this,"strictMode");this.strictMode=t}innerPattern(){return this.strictMode?g7:h7}innerExtract(t,n){let i=Yo(n[v7]);return i?Tt.createRelativeFromReference(t.reference,i):null}}});var Hf,Ko,Gc=E(()=>{Hf=class{refine(e,t){return t.filter(n=>this.isValid(e,n))}},Ko=class{refine(e,t){if(t.length<2)return t;let n=[],i=t[0],o=null;for(let s=1;s<t.length;s++){o=t[s];let a=e.text.substring(i.index+i.text.length,o.index);if(!this.shouldMergeResults(a,i,o,e))n.push(i),i=o;else{let l=i,c=o,u=this.mergeResults(a,l,c,e);e.debug(()=>{console.log(`${this.constructor.name} merged ${l} and ${c} into ${u}`)}),i=u}}return i!=null&&n.push(i),n}}});var Gv,VV=E(()=>{Gc();El();Gv=class extends Ko{shouldMergeResults(e,t,n){return!t.end&&!n.end&&e.match(this.patternBetween())!=null}mergeResults(e,t,n){if(!t.start.isOnlyWeekdayComponent()&&!n.start.isOnlyWeekdayComponent()&&(n.start.getCertainComponents().forEach(o=>{t.start.isCertain(o)||t.start.imply(o,n.start.get(o))}),t.start.getCertainComponents().forEach(o=>{n.start.isCertain(o)||n.start.imply(o,t.start.get(o))})),t.start.date()>n.start.date()){let o=t.start.date(),s=n.start.date();n.start.isOnlyWeekdayComponent()&&_n(s,{day:7})>o?(s=_n(s,{day:7}),n.start.imply("day",s.getDate()),n.start.imply("month",s.getMonth()+1),n.start.imply("year",s.getFullYear())):t.start.isOnlyWeekdayComponent()&&_n(o,{day:-7})<s?(o=_n(o,{day:-7}),t.start.imply("day",o.getDate()),t.start.imply("month",o.getMonth()+1),t.start.imply("year",o.getFullYear())):n.start.isDateWithUnknownYear()&&_n(s,{year:1})>o?(s=_n(s,{year:1}),n.start.imply("year",s.getFullYear())):t.start.isDateWithUnknownYear()&&_n(o,{year:-1})<s?(o=_n(o,{year:-1}),t.start.imply("year",o.getFullYear())):[n,t]=[t,n]}let i=t.clone();return i.start=t.start,i.end=n.start,i.index=Math.min(t.index,n.index),t.index<n.index?i.text=t.text+e+n.text:i.text=n.text+e+t.text,i}}});var Yv,BV=E(()=>{VV();Yv=class extends Gv{patternBetween(){return/^\s*(to|-|–|until|through|till)\s*$/i}}});function ID(r,e){let t=r.clone(),n=r.start,i=e.start;if(t.start=qV(n,i),r.end!=null||e.end!=null){let o=r.end==null?r.start:r.end,s=e.end==null?e.start:e.end,a=qV(o,s);if(r.end==null&&a.date().getTime()<t.start.date().getTime()){let l=new Date(a.date().getTime());l.setDate(l.getDate()+1),a.isCertain("day")?Fs(a,l):xl(a,l)}t.end=a}return t}function qV(r,e){let t=r.clone();e.isCertain("hour")?(t.assign("hour",e.get("hour")),t.assign("minute",e.get("minute")),e.isCertain("second")?(t.assign("second",e.get("second")),e.isCertain("millisecond")?t.assign("millisecond",e.get("millisecond")):t.imply("millisecond",e.get("millisecond"))):(t.imply("second",e.get("second")),t.imply("millisecond",e.get("millisecond")))):(t.imply("hour",e.get("hour")),t.imply("minute",e.get("minute")),t.imply("second",e.get("second")),t.imply("millisecond",e.get("millisecond"))),e.isCertain("timezoneOffset")&&t.assign("timezoneOffset",e.get("timezoneOffset"));let n=r.get("meridiem")!=null&&(r.isCertain("meridiem")||Array.from(r.tags()).some(i=>i.startsWith("casualReference/")));return e.isCertain("meridiem")?t.assign("meridiem",e.get("meridiem")):e.get("meridiem")!=null&&!n&&t.imply("meridiem",e.get("meridiem")),t.get("meridiem")==gt.PM&&t.get("hour")<12&&(e.isCertain("hour")?t.assign("hour",t.get("hour")+12):t.imply("hour",t.get("hour")+12)),t.addTags(r.tags()),t.addTags(e.tags()),t}var UV=E(()=>{Cl();$d()});var Kv,HV=E(()=>{Gc();UV();Kv=class extends Ko{shouldMergeResults(e,t,n){return(t.start.isOnlyDate()&&n.start.isOnlyTime()||n.start.isOnlyDate()&&t.start.isOnlyTime())&&e.match(this.patternBetween())!=null}mergeResults(e,t,n){let i=t.start.isOnlyDate()?ID(t,n):ID(n,t);return i.index=t.index,i.text=t.text+e+n.text,i}}});var zf,zV=E(()=>{HV();zf=class extends Kv{patternBetween(){return new RegExp("^\\s*(T|at|after|before|on|of|,|-|\\.|\u2219|:)?\\s*$")}}});var y7,Qv,WV=E(()=>{CD();y7=new RegExp("^\\s*,?\\s*\\(?([A-Z]{2,4})\\)?(?=\\W|$)","i"),Qv=class{constructor(e){he(this,"timezoneOverrides");this.timezoneOverrides=e}refine(e,t){let n=e.option.timezones??{};return t.forEach(i=>{let o=e.text.substring(i.index+i.text.length),s=y7.exec(o);if(!s)return;let a=s[1].toUpperCase(),l=i.start.date()??i.refDate??new Date,c={...this.timezoneOverrides,...n},u=qx(a,l,c);if(u==null)return;e.debug(()=>{console.log(`Extracting timezone: '${a}' into: ${u} for: ${i.start}`)});let d=i.start.get("timezoneOffset");d!==null&&u!=d&&(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",u),i.end!=null&&!i.end.isCertain("timezoneOffset")&&i.end.assign("timezoneOffset",u))}),t}}});var b7,w7,C7,x7,Xv,jV=E(()=>{b7=new RegExp("^\\s*(?:\\(?(?:GMT|UTC)\\s?)?([+-])(\\d{1,2})(?::?(\\d{2}))?\\)?","i"),w7=1,C7=2,x7=3,Xv=class{refine(e,t){return t.forEach(function(n){if(n.start.isCertain("timezoneOffset"))return;let i=e.text.substring(n.index+n.text.length),o=b7.exec(i);if(!o)return;e.debug(()=>{console.log(`Extracting timezone: '${o[0]}' into : ${n}`)});let s=parseInt(o[C7]),a=parseInt(o[x7]||"0"),l=s*60+a;l>840||(o[w7]==="-"&&(l=-l),n.end!=null&&n.end.assign("timezoneOffset",l),n.start.assign("timezoneOffset",l),n.text+=o[0])}),t}}});var Yc,DD=E(()=>{Yc=class{refine(e,t){if(t.length<2)return t;let n=[],i=t[0];for(let o=1;o<t.length;o++){let s=t[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),e.debug(()=>{console.log(`${this.constructor.name} remove ${l} by ${a}`)}),i=a}return i!=null&&n.push(i),n}}});function GV(r,e,t){let n=r.getDateWithAdjustedTimezone(),i=E7(n,e,t),o=new Tt(r);return o=o.addDurationAsImplied({day:i}),o.assign("weekday",e),o}function E7(r,e,t){let n=r.getDay();switch(t){case"this":return Rd(r,e);case"last":return YV(r,e);case"next":return n==Qt.SUNDAY?e==Qt.SUNDAY?7:e:n==Qt.SATURDAY?e==Qt.SATURDAY?7:e==Qt.SUNDAY?8:1+e:e<n&&e!=Qt.SUNDAY?Rd(r,e):Rd(r,e)+7}return T7(r,e)}function T7(r,e){let t=YV(r,e),n=Rd(r,e);return n<-t?n:t}function Rd(r,e){let t=r.getDay(),n=e-t;return n<0&&(n+=7),n}function YV(r,e){let t=r.getDay(),n=e-t;return n>=0&&(n-=7),n}var FD=E(()=>{Cl();Ps()});var Zv,KV=E(()=>{$d();$d();El();FD();Zv=class{refine(e,t){return e.option.forwardDate&&t.forEach(n=>{let i=e.reference.getDateWithAdjustedTimezone();if(n.start.isOnlyTime()&&e.reference.instant>n.start.date()){let o=e.reference.getDateWithAdjustedTimezone(),s=new Date(o);s.setDate(s.getDate()+1),xl(n.start,s),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} time from the ref date (${o}) to the following day (${s})`)}),n.end&&n.end.isOnlyTime()&&(xl(n.end,s),n.start.date()>n.end.date()&&(s.setDate(s.getDate()+1),xl(n.end,s)))}if(n.start.isOnlyWeekdayComponent()&&i>n.start.date()){let o=Rd(i,n.start.get("weekday"))||7,s=_n(i,{day:o});if(xl(n.start,s),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} weekday (${n.start})`)}),n.end&&n.start.date()>n.end.date()){let a=Rd(i,n.start.get("weekday"))||7,l=_n(i,{day:a});xl(n.end,l),e.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),e.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),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${n} month (${n.start})`)}))}),t}}});var Jv,QV=E(()=>{Gc();Jv=class extends Hf{constructor(t){super();he(this,"strictMode");this.strictMode=t}isValid(t,n){return n.text.replace(" ","").match(/^\d*(\.\d*)?$/)?(t.debug(()=>{console.log(`Removing unlikely result '${n.text}'`)}),!1):n.start.isValidDate()?n.end&&!n.end.isValidDate()?(t.debug(()=>{console.log(`Removing invalid result: ${n} (${n.end})`)}),!1):this.strictMode?this.isStrictModeValid(t,n):!0:(t.debug(()=>{console.log(`Removing invalid result: ${n} (${n.start})`)}),!1)}isStrictModeValid(t,n){return n.start.isOnlyWeekdayComponent()?(t.debug(()=>{console.log(`(Strict) Removing weekday only component: ${n} (${n.end})`)}),!1):!0}}});var k7,S7,_7,A7,XV,I7,ZV,JV,D7,eB,tB,ey,rB=E(()=>{ai();k7=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"),S7=1,_7=2,A7=3,XV=4,I7=5,ZV=6,JV=7,D7=8,eB=9,tB=10,ey=class extends Dt{innerPattern(){return k7}innerExtract(e,t){let n=e.createParsingComponents({year:parseInt(t[S7]),month:parseInt(t[_7]),day:parseInt(t[A7])});if(t[XV]!=null&&(n.assign("hour",parseInt(t[XV])),n.assign("minute",parseInt(t[I7])),t[ZV]!=null&&n.assign("second",parseInt(t[ZV])),t[JV]!=null&&n.assign("millisecond",parseInt(t[JV])),t[D7]!=null)){let i=0;if(t[eB]){let o=parseInt(t[eB]),s=0;t[tB]!=null&&(s=parseInt(t[tB])),i=o*60,i<0?i-=s:i+=s}n.assign("timezoneOffset",i)}return n.addTag("parser/ISOFormatParser")}}});var ty,nB=E(()=>{Gc();ty=class extends Ko{mergeResults(e,t,n){let i=n.clone();return i.index=t.index,i.text=t.text+e+i.text,i.start.assign("weekday",t.start.get("weekday")),i.end&&i.end.assign("weekday",t.start.get("weekday")),i}shouldMergeResults(e,t,n){return t.start.isOnlyWeekdayComponent()&&!t.start.isCertain("hour")&&n.start.isCertain("day")&&e.match(/^,?\s*$/)!=null}}});function iB(r,e=!1){return r.parsers.unshift(new ey),r.refiners.unshift(new ty),r.refiners.unshift(new Xv),r.refiners.unshift(new Yc),r.refiners.push(new Qv),r.refiners.push(new Yc),r.refiners.push(new Zv),r.refiners.push(new Jv(e)),r}var oB=E(()=>{WV();jV();DD();KV();QV();rB();nB()});function sB(r){let e=r.getDateWithAdjustedTimezone(),t=new Tt(r,{});return Fs(t,e),Bx(t,e),t.assign("timezoneOffset",r.getTimezoneOffset()),t.addTag("casualReference/now"),t}function aB(r){let e=r.getDateWithAdjustedTimezone(),t=new Tt(r,{});return Fs(t,e),Ov(t,e),t.delete("meridiem"),t.addTag("casualReference/today"),t}function lB(r){return F7(r,1).addTag("casualReference/yesterday")}function cB(r){return Gx(r,1).addTag("casualReference/tomorrow")}function F7(r,e){return Gx(r,-e)}function Gx(r,e){let t=r.getDateWithAdjustedTimezone(),n=new Tt(r,{}),i=new Date(t.getTime());return i.setDate(i.getDate()+e),Fs(n,i),Ov(n,i),n.delete("meridiem"),n}function uB(r,e=22){let t=r.getDateWithAdjustedTimezone(),n=new Tt(r,{});return Fs(n,t),n.imply("hour",e),n.imply("meridiem",gt.PM),n.addTag("casualReference/tonight"),n}function dB(r,e=20){let t=new Tt(r,{});return t.imply("meridiem",gt.PM),t.imply("hour",e),t.addTag("casualReference/evening"),t}function pB(r){let e=new Tt(r,{});return r.getDateWithAdjustedTimezone().getHours()>2&&e.addDurationAsImplied({day:1}),e.assign("hour",0),e.imply("minute",0),e.imply("second",0),e.imply("millisecond",0),e.addTag("casualReference/midnight"),e}function fB(r,e=6){let t=new Tt(r,{});return t.imply("meridiem",gt.AM),t.imply("hour",e),t.imply("minute",0),t.imply("second",0),t.imply("millisecond",0),t.addTag("casualReference/morning"),t}function mB(r,e=15){let t=new Tt(r,{});return t.imply("meridiem",gt.PM),t.imply("hour",e),t.imply("minute",0),t.imply("second",0),t.imply("millisecond",0),t.addTag("casualReference/afternoon"),t}function hB(r){let e=new Tt(r,{});return e.imply("meridiem",gt.AM),e.assign("hour",12),e.imply("minute",0),e.imply("second",0),e.imply("millisecond",0),e.addTag("casualReference/noon"),e}var PD=E(()=>{Ps();$d();Cl()});var P7,ry,vB=E(()=>{ai();$d();PD();P7=/(now|today|tonight|tomorrow|overmorrow|tmr|tmrw|yesterday|last\s*night)(?=\W|$)/i,ry=class extends Dt{innerPattern(e){return P7}innerExtract(e,t){let n=e.refDate,i=t[0].toLowerCase(),o=e.createParsingComponents();switch(i){case"now":o=sB(e.reference);break;case"today":o=aB(e.reference);break;case"yesterday":o=lB(e.reference);break;case"tomorrow":case"tmr":case"tmrw":o=cB(e.reference);break;case"tonight":o=uB(e.reference);break;case"overmorrow":o=Gx(e.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}Fs(o,n),o.imply("hour",0)}break}return o.addTag("parser/ENCasualDateParser"),o}}});var M7,ny,yB=E(()=>{ai();PD();M7=/(?:this)?\s{0,3}(morning|afternoon|evening|night|midnight|midday|noon)(?=\W|$)/i,ny=class extends Dt{innerPattern(){return M7}innerExtract(e,t){let n=null;switch(t[1].toLowerCase()){case"afternoon":n=mB(e.reference);break;case"evening":case"night":n=dB(e.reference);break;case"midnight":n=pB(e.reference);break;case"morning":n=fB(e.reference);break;case"noon":case"midday":n=hB(e.reference);break}return n&&n.addTag("parser/ENCasualTimeParser"),n}}});var $7,O7,R7,N7,iy,bB=E(()=>{Fr();kl();ai();FD();Cl();$7=new RegExp(`(?:(?:\\,|\\(|\\\uFF08)\\s*)?(?:on\\s*?)?(?:(this|last|past|next)\\s*)?(${an(Hx)}|weekend|weekday)(?:\\s*(?:\\,|\\)|\\\uFF09))?(?:\\s*(?:of\\s*)?(this|last|past|next)\\s*week)?(?=\\W|$)`,"i"),O7=1,R7=2,N7=3,iy=class extends Dt{innerPattern(){return $7}innerExtract(e,t){let n=t[O7],i=t[N7],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=t[R7].toLowerCase(),l;if(Hx[a]!==void 0)l=Hx[a];else if(a=="weekend")l=s=="last"?Qt.SUNDAY:Qt.SATURDAY;else if(a=="weekday"){let c=e.reference.getDateWithAdjustedTimezone().getDay();c==Qt.SUNDAY||c==Qt.SATURDAY?l=s=="last"?Qt.FRIDAY:Qt.MONDAY:(l=c-1,l=s=="last"?l-1:l+1,l=l%5+1)}else return null;return GV(e.reference,l,s)}}});var L7,V7,B7,oy,wB=E(()=>{Fr();Ps();ai();kl();L7=new RegExp(`(this|last|past|next|after\\s*this)\\s*(${an(Rv)})(?=\\s*)(?=\\W|$)`,"i"),V7=1,B7=2,oy=class extends Dt{innerPattern(){return L7}innerExtract(e,t){let n=t[V7].toLowerCase(),i=t[B7].toLowerCase(),o=Rv[i];if(n=="next"||n.startsWith("after")){let l={};return l[o]=1,Tt.createRelativeFromReference(e.reference,l)}if(n=="last"||n=="past"){let l={};return l[o]=-1,Tt.createRelativeFromReference(e.reference,l)}let s=e.createParsingComponents(),a=new Date(e.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 q7,U7,H7,CB,xB,MD,sy,EB=E(()=>{Vf();q7=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"),U7=1,H7=5,CB=2,xB=3,MD=4,sy=class{constructor(e){he(this,"groupNumberMonth");he(this,"groupNumberDay");this.groupNumberMonth=e?xB:CB,this.groupNumberDay=e?CB:xB}pattern(){return q7}extract(e,t){let n=t.index+t[U7].length,i=t.index+t[0].length-t[H7].length;if(n>0&&e.text.substring(0,n).match("\\d/?$")||i<e.text.length&&e.text.substring(i).match("^/?\\d"))return;let o=e.text.substring(n,i);if(o.match(/^\d\.\d$/)||o.match(/^\d\.\d{1,2}\.\d{1,2}\s*$/)||!t[MD]&&o.indexOf("/")<0)return;let s=e.createParsingResult(n,o),a=parseInt(t[this.groupNumberMonth]),l=parseInt(t[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),t[MD]){let c=parseInt(t[MD]),u=Ux(c);s.start.assign("year",u)}else{let c=zc(e.refDate,l,a);s.start.imply("year",c)}return s.addTag("parser/SlashDateFormatParser")}}});var z7,W7,ay,TB=E(()=>{Fr();Ps();ai();El();z7=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${Sl})(?=\\W|$)`,"i"),W7=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${jc})(?=\\W|$)`,"i"),ay=class extends Dt{constructor(t=!0){super();he(this,"allowAbbreviations");this.allowAbbreviations=t}innerPattern(){return this.allowAbbreviations?z7:W7}innerExtract(t,n){let i=n[1].toLowerCase(),o=Yo(n[2]);if(!o)return null;switch(i){case"last":case"past":case"-":o=Uc(o);break}return Tt.createRelativeFromReference(t.reference,o)}}});function j7(r){return r.text.match(/^[+-]/i)!=null}function kB(r){return r.text.match(/^-/i)!=null}var ly,SB=E(()=>{Gc();Ps();Fr();El();ly=class extends Ko{shouldMergeResults(e,t,n){return e.match(/^\s*$/i)?j7(n)||kB(n):!1}mergeResults(e,t,n,i){let o=Yo(n.text);kB(n)&&(o=Uc(o));let s=Tt.createRelativeFromReference(Hc.fromDate(t.start.date()),o);return new Tl(t.reference,t.index,`${t.text}${e}${n.text}`,s)}}});function _B(r){return r.text.match(/\s+(before|from)$/i)!=null}function G7(r){return r.text.match(/\s+(after|since)$/i)!=null}var cy,AB=E(()=>{Gc();Ps();Fr();El();cy=class extends Ko{patternBetween(){return/^\s*$/i}shouldMergeResults(e,t,n){return!e.match(this.patternBetween())||!_B(t)&&!G7(t)?!1:!!n.start.get("day")&&!!n.start.get("month")&&!!n.start.get("year")}mergeResults(e,t,n){let i=Yo(t.text);_B(t)&&(i=Uc(i));let o=Tt.createRelativeFromReference(Hc.fromDate(n.start.date()),i);return new Tl(n.reference,t.index,`${t.text}${e}${n.text}`,o)}}});var Y7,K7,uy,IB=E(()=>{Fr();Y7=new RegExp(`^\\s*(${Wc})`,"i"),K7=1,uy=class{refine(e,t){return t.forEach(function(n){if(!n.start.isDateWithUnknownYear())return;let i=e.text.substring(n.index+n.text.length),o=Y7.exec(i);if(!o||o[0].trim().length<=3)return;e.debug(()=>{console.log(`Extracting year: '${o[0]}' into : ${n}`)});let s=fa(o[K7]);n.end!=null&&n.end.assign("year",s),n.start.assign("year",s),n.text+=o[0]}),t}}});var dy,DB=E(()=>{Gc();dy=class extends Hf{constructor(){super()}isValid(e,t){let n=t.text.trim();return n===e.text.trim()?!0:n.toLowerCase()==="may"&&!e.text.substring(0,t.index).trim().match(/\b(in)$/i)?(e.debug(()=>{console.log(`Removing unlikely result: ${t}`)}),!1):n.toLowerCase().endsWith("the second")?(e.text.substring(t.index+t.text.length).trim().length>0&&e.debug(()=>{console.log(`Removing unlikely result: ${t}`)}),!1):!0}}});var Nd,$D=E(()=>{xV();SV();AV();DV();PV();MV();$V();RV();NV();LV();BV();zV();oB();vB();yB();bB();wB();EB();TB();SB();AB();DD();IB();DB();Nd=class{createCasualConfiguration(e=!1){let t=this.createConfiguration(!1,e);return t.parsers.push(new ry),t.parsers.push(new ny),t.parsers.push(new Bv),t.parsers.push(new oy),t.parsers.push(new ay),t.refiners.push(new dy),t}createConfiguration(e=!0,t=!1){let n=iB({parsers:[new sy(t),new Nv(e),new Lv,new Vv(t),new iy,new Hv,new zv(e),new Wv(e),new jv(e),new Uv],refiners:[new zf]},e);return n.parsers.unshift(new qv(e)),n.refiners.unshift(new cy),n.refiners.unshift(new ly),n.refiners.unshift(new Yc),n.refiners.push(new zf),n.refiners.push(new uy),n.refiners.push(new Yv),n}}});var Wf,OD,FB=E(()=>{Ps();$D();Wf=class r{constructor(e){he(this,"parsers");he(this,"refiners");he(this,"defaultConfig",new Nd);e=e||this.defaultConfig.createCasualConfiguration(),this.parsers=[...e.parsers],this.refiners=[...e.refiners]}clone(){return new r({parsers:[...this.parsers],refiners:[...this.refiners]})}parseDate(e,t,n){let i=this.parse(e,t,n);return i.length>0?i[0].start.date():null}parse(e,t,n){let i=new OD(e,t,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(e,t){let n=[],i=t.pattern(e),o=e.text,s=e.text,a=i.exec(s);for(;a;){let l=a.index+o.length-s.length;a.index=l;let c=t.extract(e,a);if(!c){s=o.substring(a.index+1),a=i.exec(s);continue}let u=null;c instanceof Tl?u=c:c instanceof Tt?(u=e.createParsingResult(a.index,a[0]),u.start=c):u=e.createParsingResult(a.index,a[0],c);let d=u.index,p=u.text;e.debug(()=>console.log(`${t.constructor.name} extracted (at index=${d}) '${p}'`)),n.push(u),s=o.substring(d+p.length),a=i.exec(s)}return n}},OD=class{constructor(e,t,n){he(this,"text");he(this,"option");he(this,"reference");he(this,"refDate");this.text=e,this.option=n??{},this.reference=Hc.fromInput(t,this.option.timezones),this.refDate=this.reference.instant}createParsingComponents(e){return e instanceof Tt?e:new Tt(this.reference,e)}createParsingResult(e,t,n,i){let o=typeof t=="string"?t:this.text.substring(e,t),s=n?this.createParsingComponents(n):null,a=i?this.createParsingComponents(i):null;return new Tl(this.reference,e,o,s,a)}debug(e){this.option.debug&&(this.option.debug instanceof Function?this.option.debug(e):this.option.debug.debug(e))}}});var RD,PB,Q7,BNe,MB=E(()=>{FB();$D();RD=new Nd,PB=new Wf(RD.createCasualConfiguration(!1)),Q7=new Wf(RD.createConfiguration(!0,!1)),BNe=new Wf(RD.createCasualConfiguration(!0))});function $B(r,e,t){return Z7.parseDate(r,e,t)}var Z7,OB=E(()=>{MB();Z7=PB});function r9(r){return!e9.test(r)}var e9,t9,ND,Qo,Ld=E(()=>{OB();e9=/\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,t9=/\bprevious\b/gi;ND=class{getParsedDate(e,t=new Date){let n=e.replace(t9,"last");return $B(n,t,{forwardDate:r9(n)})}parseDate(e){if(!e||!e.trim())return null;try{let t=this.getParsedDate(e);return t?window.moment?{moment:window.moment(t)}:(console.warn("Moment.js is not available"),null):null}catch(t){return console.warn("Failed to parse date:",e,t),null}}},Qo=new ND});function yy(r){return typeof r=="string"&&vy.includes(r)}function _l(r){if(!r||typeof r!="object")return;let e=r;switch(e.kind){case"now":return{kind:"now"};case"ask":{let t=typeof e.defaultValue=="string"?e.defaultValue.trim():"";return t?{kind:"ask",defaultValue:t}:{kind:"ask"}}case"relative":return typeof e.offset!="number"||!Number.isInteger(e.offset)||!yy(e.unit)?void 0:{kind:"relative",offset:e.offset,unit:e.unit};case"variable":return typeof e.name!="string"||!e.name.trim()?void 0:{kind:"variable",name:e.name.trim()};default:return}}var vy,Kf=E(()=>{vy=["days","weeks","months","years"]});function iE(r){return f9.has(r)}function Al(r){if(!r||r.kind==="now")return"today";if(r.kind==="ask")return"ask";if(r.kind==="variable")return"variable";for(let e of VD)if(r.offset===e.offset&&r.unit===e.unit)return e.id;return"custom"}function oE(r){let{preset:e,previous:t}=r;if(e!=="today"){if(e==="ask")return t?.kind==="ask"?t:VB(Al(t));if(e==="variable")return t?.kind==="variable"?t:{kind:"variable",name:""};if(e==="custom")return t?.kind==="relative"&&Al(t)==="custom"?t:{kind:"relative",offset:-2,unit:"days"};for(let n of VD)if(n.id===e)return{kind:"relative",offset:n.offset,unit:n.unit}}}function VB(r){for(let e of nE)if(e.id===r&&e.defaultValue)return{kind:"ask",defaultValue:e.defaultValue};return{kind:"ask"}}function Cy(r){let e=(r??"").trim().toLowerCase();for(let t of nE)if(t.aliases.some(n=>n===e))return t.id;return"kept"}function sE(r){let e=nE.map(t=>({value:t.id,label:t.label}));if(Cy(r)==="kept"){let t=r?.trim();t&&e.push({value:"kept",label:t})}return e}function aE(r,e){if(r==="kept"){let t=e?.trim();return t||void 0}for(let t of nE)if(t.id===r)return t.defaultValue}function BB(r){return typeof r=="string"&&r.trim().toLowerCase()==="ask"}function Qf(r){return r?.kind==="ask"?r:VB(Al(r))}var p9,Qx,Xx,Zx,Jx,by,eE,wy,tE,VD,rE,nE,f9,Kc=E(()=>{p9=["today","ask","yesterday","last-week","next-week","last-month","custom","variable"],Qx="Which day",Xx="The day {{DATE}} writes. The clock stays now. Hold Shift in the QuickAdd menu to pick a different day.",Zx="Picker starts on",Jx="The date the picker suggests first. You can still pick a different day.",by="How far from today",eE="How many days, weeks, months, or years from today. Negative is the past.",wy="Variable name",tE="A VDATE or script value that already has the day.",VD=[{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"}],rE=[{value:"today",label:"Today"},{value:"ask",label:"Ask each time"},...VD.map(r=>({value:r.id,label:r.label})),{value:"custom",label:"Custom\u2026"},{value:"variable",label:"A variable\u2026"}],nE=[{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"]}],f9=new Set(p9)});function I9(r,e){let t=[r,...e??[]].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);return t.length>0?t:void 0}function HB(r){let e=oi.parse(`__capture_scope|${r}`);return{filter:e.filters,multiSelect:e.multiSelect??!1}}function D9(r){return!!(r.folder||r.folders?.length||r.tags?.length||r.excludeFolders?.length||r.excludeTags?.length||r.excludeFiles?.length)}function Xf(r){let e=r.trim();if(!e)return null;if(e.startsWith("#")){let o=qo(e),s=(o.shift()??"").replace(/^#/,"").replace(/\.md$/i,"").trim();if(!s)return null;let a=o.length>0?HB(o.join("|")):{filter:{},multiSelect:!1};return{filter:{...a.filter,tags:I9(s,a.filter.tags)},multiSelect:a.multiSelect}}let t=qo(e)[0]??"",n=Uo(t);if(!n||!A9.has(n.key))return null;let i=HB(e);return D9(i.filter)?i:null}var A9,pE=E(()=>{hl();xc();A9=new Set(["folder","tag","exclude-folder","exclude-tag","exclude-file"])});function Zf(r){let e=r.trim();if(!zB.test(e))return null;let t=e.replace(zB,""),{fieldName:n,filters:i}=oi.parse(t),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 zB,fE=E(()=>{hl();zB=/^property:/i});function rq(r){let e=vE.find(t=>t.id===(r===void 0?"open":r));if(!e)throw new Error(`Unknown existing-note action: ${String(r)}`);return e}function yE(r){return rq(r).id}function Zc(r){return rq(r).verb}function tm(r){let e=J9.get(r);if(!e)throw new Error(`Unknown file exists mode: ${r}`);return e}function nq(r){return ZD.filter(e=>e.category===r)}function iq(r){return tm(r).category}function oq(){return[...ZD]}function sq(r){return r.kind==="prompt"?"prompt":iq(r.mode)}function aq(r,e){return r==="prompt"?{kind:"prompt"}:e?.kind==="apply"&&iq(e.mode)===r?e:{kind:"apply",mode:eZ[r]}}function lq(r){return typeof r!="string"||!Object.prototype.hasOwnProperty.call(eq,r)?null:eq[r]??null}async function cq(r,e,t){return await tZ[e](r,t)}async function rZ(r,e){let t=r;for(;await e(t);){let{basename:n,extension:i}=uq(t),o=n.match(/^(.*?)(\d+)$/);t=`${o?`${o[1]}${String(BigInt(o[2])+1n).padStart(o[2].length,"0")}`:`${n}1`}${i}`}return t}async function nZ(r,e){let t=r;for(;await e(t);){let{basename:n,extension:i}=uq(t),o=n.match(/^(.*) \((\d+)\)$/);t=`${o?`${o[1]} (${String(BigInt(o[2])+1n)})`:`${n} (1)`}${i}`}return t}function uq(r){return cr.test(r)?{basename:r.replace(cr,""),extension:".canvas"}:wn.test(r)?{basename:r.replace(wn,""),extension:".base"}:{basename:r.replace(Nt,""),extension:".md"}}var tq,ZD,vE,J9,eZ,eq,tZ,Dl=E(()=>{Xe();tq=[{id:"prompt",label:"Ask every time"},{id:"update",label:"Update existing file"},{id:"create",label:"Create another file"},{id:"keep",label:"Keep existing file"}],ZD=[{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"}],vE=[{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"}];J9=new Map(ZD.map(r=>[r.id,r])),eZ={update:"appendBottom",create:"duplicateSuffix",keep:"doNothing"},eq={"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"},tZ={increment:rZ,duplicateSuffix:nZ}});function yF(r,e){if(!r.fileNameFormat?.enabled)return!0;let t=e.trim().toLowerCase();return t===Or.toLowerCase()||t===BR.toLowerCase()}function bF(r,e){return r.discoverExistingNotesBeforeCreate===!0&&yF(r,e)}function nu(r,e,t){return!(!bF(r,e)||t!=null)}var zd=E(()=>{Xe()});function Zq(r){let e=t=>{t.preventDefault(),t.stopPropagation()};r.addEventListener("pointerdown",e),r.addEventListener("mousedown",e)}function MJ(r){r.forEach(e=>{e.addEventListener("keydown",t=>{if(t.key==="ArrowRight"||t.key==="ArrowLeft"){let i=(r.indexOf(e)+(t.key==="ArrowRight"?1:-1)+r.length)%r.length;r[i].focus(),t.preventDefault()}})})}var qy,Si,Wd=E(()=>{qy=require("obsidian"),Si=class r extends qy.Modal{constructor(t,n,i){super(t);this.header=n;this.text=i;this.input=null;this.waitForClose=new Promise(o=>{this.resolvePromise=o}),this.open(),this.display()}static Ask(t,n,i){return new r(t,n,i).waitForClose}static async Prompt(t,n,i){return await r.Ask(t,n,i)===!0}display(){this.containerEl.addClass("quickAddModal","qaYesNoPrompt"),this.contentEl.empty(),this.titleEl.textContent=this.header,this.contentEl.createEl("p",{text:this.text});let t=this.contentEl.createDiv({cls:"yesNoPromptButtonContainer"}),n=new qy.ButtonComponent(t).setButtonText("No").onClick(()=>this.submit(!1));Zq(n.buttonEl);let i=new qy.ButtonComponent(t).setButtonText("Yes").onClick(()=>this.submit(!0)).setDestructive();Zq(i.buttonEl),i.buttonEl.focus(),MJ([n.buttonEl,i.buttonEl])}submit(t){this.input=t,this.close()}onClose(){super.onClose(),this.resolvePromise(this.input)}}});var fr,vr=E(()=>{fr=(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))(fr||{})});function Os(r,e){let t=e;for(;t<r.length;){let n=r[t],i=r[t+1];if(/\s/.test(n)){t+=1;continue}if(n==="/"&&i==="/"){let o=r.indexOf(`
`,t+2);t=o===-1?r.length:o+1;continue}if(n==="/"&&i==="*"){let o=r.indexOf("*/",t+2);t=o===-1?r.length:o+2;continue}return t}return t}function Uy(r,e){let t=r[e];if(t!=='"'&&t!=="'"&&t!=="`")return null;let n="";for(let i=e+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===t)return{value:n,end:i+1};n+=o}return null}function tU(r,e){let t=/^[A-Za-z_$][\w$]*/.exec(r.slice(e));return t?{value:t[0],end:e+t[0].length}:null}function NE(r,e,t,n){let i=0;for(let o=e;o<r.length;o++){let s=r[o],a=r[o+1];if(s==='"'||s==="'"||s==="`"){let l=Uy(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===t){i+=1;continue}if(s===n&&(i-=1,i===0))return o}return-1}function rU(r){let e=new Map,t=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(["'`])/g,n;for(;(n=t.exec(r))!==null;){let i=Uy(r,t.lastIndex-1);i&&(e.set(n[1],i.value),t.lastIndex=i.end)}return e}function BJ(r){let e=[],t=rU(r),n=0;for(;n<r.length;){n=Os(r,n);let i=r[n];if(i==='"'||i==="'"||i==="`"){let a=Uy(r,n);n=a?a.end:n+1;continue}let o=kF(r,n,t);if(!o){n+=1;continue}if(n=Os(r,o.end),r[n]!==":"){n=o.end;continue}if(n=Os(r,n+1),o.name!=="options"||r[n]!=="{")continue;let s=NE(r,n,"{","}");if(s===-1)break;e.push({start:n+1,end:s}),n=s+1}return e}function kF(r,e,t){if(r[e]==='"'||r[e]==="'"||r[e]==="`"){let i=Uy(r,e);return i?{name:i.value,end:i.end}:null}if(r[e]==="["){let i=Os(r,e+1),o=tU(r,i),s=NE(r,e,"[","]");if(s===-1)return null;let a=o?Os(r,o.end):i;return{name:o&&a===s?t.get(o.value)??null:null,end:s+1}}let n=tU(r,e);return n?{name:n.value,end:n.end}:null}function qJ(r){let e=new Map,t=0;for(;t<r.length;){if(t=Os(r,t),r[t]===","){t+=1;continue}if(t>=r.length)break;let n=kF(r,t,new Map);if(!n?.name){t+=1;continue}if(t=Os(r,n.end),r[t]!==":"){t+=1;continue}if(t=Os(r,t+1),r[t]==='"'||r[t]==="'"||r[t]==="`"){let o=Uy(r,t);if(!o)break;e.set(n.name,o.value),t=o.end;continue}if(r.slice(t,t+4)==="true"){e.set(n.name,!0),t+=4;continue}if(r.slice(t,t+5)==="false"){e.set(n.name,!1),t+=5;continue}let i=r[t];if(i==="{"||i==="["){let o=NE(r,t,i,i==="{"?"}":"]");if(o===-1)break;t=o+1;continue}for(;t<r.length&&r[t]!==",";)t+=1}return e}function UJ(r){let e=qJ(r),t=e.get("type"),n=e.get("secret");return t==="secret"||(t==="text"||t==="input")&&n===!0}function Hy(r,e){let t=e&&VJ.test(e)?ll(r).code??"":r,n=new Set,i=!1,o=rU(t);for(let{start:s,end:a}of BJ(t)){let l=s;for(;l<a;){if(l=Os(t,l),t[l]===","){l+=1;continue}if(l>=a)break;let c=kF(t,l,o);if(!c){l+=1;continue}if(l=Os(t,c.end),t[l]!==":"){l+=1;continue}if(l=Os(t,l+1),t[l]!=="{"){l+=1;continue}let u=NE(t,l,"{","}");if(u===-1||u>a)break;let d=t.slice(l+1,u);UJ(d)&&(i=!0,c.name&&n.add(c.name)),l=u+1}}return{names:n,foundSecretOptions:i}}var VJ,nU=E(()=>{zg();VJ=/\.md$/i});function qr(r){return typeof r=="object"&&r!==null}function iu(r){return qr(r)&&!Array.isArray(r)}function HJ(r){return iu(r)?!1:Array.isArray(r)?r.length>0:sr(r)}function Er(r){return iu(r)?r.commands:HJ(r)?r:void 0}function Ht(r){return Array.isArray(r)?r:[]}function bm(r){return Array.isArray(r)?r:[]}function zy(r){return Array.isArray(r)}function SF(r){let e=Ht(r),t=new Set,n=!1,i=[];for(let o of e){if(Array.isArray(o)){let l=SF(o);for(let c of l.commands){let u=c.id;if(typeof u=="string"&&u!==""&&!t.has(u)){t.add(u),i.push(c);continue}let d={...c,id:Kt()};t.add(d.id),i.push(d)}n=!0;continue}if(!qr(o)){n=!0;continue}let s=o.id;if(typeof s=="string"&&s!==""&&!t.has(s)){t.add(s),i.push(o);continue}let a={...o,id:Kt()};t.add(a.id),i.push(a),n=!0}return n?{commands:i,changed:n}:{commands:e,changed:!1}}function iU(r){oU(r,new Set)}function oU(r,e){qr(r)&&(e.has(r)||(e.add(r),iu(r)&&(r.id=Kt()),LE(Er(r),e)))}function LE(r,e){if(zy(r))for(let t of r){if(Array.isArray(t)){LE(t,e);continue}if(!qr(t)||e.has(t))continue;e.add(t),t.id=Kt();let n=t;LE(n.thenCommands,e),LE(n.elseCommands,e),sU(n.choice,e)}}function sU(r,e){if(!qr(r)||e.has(r))return;e.add(r);let t=r;if(t.id=Kt(),t.type==="Macro"&&oU(t.macro,e),t.type==="Multi"&&Array.isArray(t.choices))for(let n of t.choices)sU(n,e)}var un=E(()=>{sv();Ss();sv()});function Cm(r){return r!==null&&typeof r=="object"}function HE(r){return r?.secretStorage}function BE(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"setting"}function WJ(r){let e=5381;for(let t=0;t<r.length;t+=1)e=e*33^r.charCodeAt(t);return(e>>>0).toString(36).slice(0,zJ)}function lU(r,e){return r.length<=e?r:r.slice(0,e).replace(/-+$/g,"")||"setting"}function uU(r,e){let t=e?.id;return typeof t=="string"&&t.trim().length>0?t:r}function _F(r,e,t){let i=(t?[VE,r,e,t]:[VE,r,e]).join("-");if(i.length<=aU)return i;let o=WJ([r,e,t].filter(Boolean).join(":")),s=t?4:3,a=aU-VE.length-o.length-(t?.length??0)-s,l=Math.max(8,Math.floor(a*.6)),c=Math.max(8,a-l);return[VE,lU(r,l),lU(e,c),...t?[t]:[],o].join("-")}function AF(r){return r?.message??String(r)}function xm(r){return Cm(r)?r.type==="secret"||(r.type==="text"||r.type==="input")&&r.secret===!0:!1}function wm(r){return Cm(r)&&r[cU]===!0&&typeof r.secretRef=="string"&&r.secretRef.trim().length>0}function qE(r){return{[cU]:!0,secretRef:r}}function jJ(r,e,t){let n=r.id?.trim()||r.path||r.name||"script";return _F(BE(n),BE(uU(e,t)))}function GJ(r){let e=r?.options;return e?Object.entries(e).filter(([,t])=>xm(t)).map(([t])=>t):[]}function YJ(r){let e=r?.options;return e?Object.entries(e).filter(([,t])=>xm(t)):[]}function KJ(r){return typeof r.id=="string"&&r.id.trim().length>0}async function IF(r,e){let t=HE(r);if(!t?.getSecret)return null;try{return await Promise.resolve(t.getSecret(e))}catch(n){return I.logWarning(`Failed to read user script SecretStorage entry "${e}": ${AF(n)}`),null}}async function QJ(r,e,t){let n=HE(r);if(!n?.setSecret)return!1;try{return await Promise.resolve(n.setSecret(e,t)),!0}catch(i){return I.logWarning(`Failed to write user script SecretStorage entry "${e}": ${AF(i)}`),!1}}async function XJ(r,e,t,n,i){let o=e.id?.trim()||e.path||e.name||"script",s=BE(o),a=BE(uU(t,i)),l=_F(s,a),c=1;for(;;){let u=await IF(r,l);if(!u||u===n)return l;c+=1,l=_F(s,a,String(c))}}async function DF(r,e,t,n,i,o){if(n.length===0)return null;let s=i?.trim()||await XJ(r,e,t,n,o);return await QJ(r,s,n)?s:null}async function FF(r,e){let t=e?.trim();if(!t)return!0;let n=HE(r);if(!n)return!0;let i=n.deleteSecret??n.removeSecret??n.delete;try{if(i)return await Promise.resolve(i.call(n,t)),!0;if(n.setSecret)return await Promise.resolve(n.setSecret(t,"")),!0}catch(o){I.logWarning(`Failed to clear user script SecretStorage entry "${t}": ${AF(o)}`)}return!1}async function dU(r,e,t){let n=e.settings??{},i={...n},o=new Set(GJ(t));for(let[s,a]of Object.entries(n)){if(wm(a)){let l=await IF(r,a.secretRef);if(l){i[s]=l;continue}throw new Error(`Secret setting "${s}" for user script "${e.name}" is unavailable. Re-enter it on this device.`)}o.has(s)&&(i[s]=typeof a=="string"?a:"")}return i}async function zE(r,e,t){let n=YJ(t);if(n.length===0)return!1;let i=HE(r);if(!i?.getSecret||!i?.setSecret)return n.some(([a])=>{let l=e.settings?.[a];return typeof l=="string"&&l.length>0})&&I.logWarning(`SecretStorage unavailable; leaving plaintext user script secret settings for "${e.name}" unchanged.`),!1;let o=!1;for(let[s,a]of n){let l=e.settings?.[s];if(wm(l))continue;if(typeof l!="string"||l.length===0){if(!KJ(a))continue;let u=jJ(e,s,a);if(!await IF(r,u))continue;e.settings[s]=qE(u);for(let[p,f]of Object.entries(e.settings))p!==s&&wm(f)&&f.secretRef===u&&delete e.settings[p];o=!0;continue}let c=await DF(r,e,s,l,void 0,a);c&&(e.settings[s]=qE(c),o=!0)}return o}function WE(r,e){let t=r.settings?.[e];return wm(t)?t.secretRef:void 0}async function ZJ(r,e){if(!Cm(e))return!0;let t=Object.values(e).filter(wm).map(i=>i.secretRef);return(await Promise.all(t.map(i=>FF(r,i)))).every(Boolean)}function*PF(r){if(Cm(r)&&(r.type==="Macro"&&(yield*UE(Er(r.macro))),r.type==="Multi"&&Array.isArray(r.choices)))for(let e of r.choices)yield*PF(e)}function*MF(r){Cm(r)&&(r.type==="UserScript"&&(yield r),yield*UE(r.thenCommands),yield*UE(r.elseCommands),yield*PF(r.choice))}function*UE(r){if(Array.isArray(r))for(let e of r)yield*Array.isArray(e)?UE(e):MF(e)}async function JJ(r,e){let t=!0;for(let n of e)t=await ZJ(r,n.settings)&&t;return t}async function jE(r,e){return JJ(r,MF(e))}function eee(r,e){let t=r.path;if(typeof t=="string")return e?.secretOptionNamesByPath?.get(t)}function tee(r,e,t){if(Cm(r))for(let[n,i]of Object.entries(r)){if(wm(i)){delete r[n];continue}typeof i=="string"&&(e===null||e?.has(n)||e===void 0&&t?.stripUnknownStringSettings===!0)&&delete r[n]}}function pU(r,e){for(let t of r)tee(t.settings,eee(t,e),e)}function fU(r,e){pU(MF(r),e)}function GE(r,e){pU(PF(r),e)}var VE,cU,aU,zJ,Ml=E(()=>{Ie();nU();un();VE="quickadd-user-script",cU="__quickaddSecret",aU=64,zJ=8});function Em(r,e){if(e.options)for(let t in e.options){let n=r[t]===void 0,i="defaultValue"in e.options[t]&&e.options[t].defaultValue!==void 0;n&&i&&!xm(e.options[t])&&(r[t]=e.options[t].defaultValue)}}var YE=E(()=>{Ml()});function Ui(r){if(r.length===0)return 0;let e=new TextEncoder().encode(r).length,t=!1;for(let i=0;i<r.length;i++)if(r.charCodeAt(i)>127){t=!0;break}return Math.max(1,Math.ceil(e/(t?3:4)))}function hU(r){return!Number.isFinite(r)||r<=0?1:Math.max(1,Math.floor(r*.45))}var Wy=E(()=>{});function bU(){return X.getState().ai.providers.flatMap(e=>e.models).map(e=>e.name)}function RF(){return X.getState().ai.providers}function gU(r,e){for(let t of r){let n=t.models.find(i=>i.name===e);if(n)return{provider:t,model:n}}}function OF(r){let e=RF();return e.filter(t=>t.models.some(n=>n.name===r)).map(t=>{let n=`${t.id??t.name}/${r}`;return e.some(o=>o.models.some(s=>s.name===n))?`{ name: "${r}", provider: "${t.id??t.name}" } (the string "${n}" is itself a model id on another provider)`:n})}function yU(r,e){vU.has(r)||(vU.add(r),I.logWarning(e))}function Gd(r,e){let t=RF(),n=e?.silent===!0;if(r==null)return;if(typeof r!="string"){let s=t.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=gU(t,r.name);return l?(n||yU(`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=gU(t,r);if(i){let s=OF(r);return s.length>1&&!n&&yU(`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 wU(r.slice(0,o),r.slice(o+1))}function wU(r,e){let t=RF(),n=r.trim().toLowerCase(),i=t.find(s=>s.id?.toLowerCase()===n)??t.find(s=>s.name.trim().toLowerCase()===n),o=i?.models.find(s=>s.name===e);if(i&&o)return{provider:i,model:o}}function jy(r){let e=typeof r=="string"?r:r?.name;if(!e)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 t=typeof r!="string"&&r.provider?wU(r.provider,e):Gd(e);if(!t){let n=e.includes("/")?e.slice(e.indexOf("/")+1):e,i=[...OF(e),...n!==e?OF(n):[]],o=i.length?` Did you mean ${i.join(" or ")}?`:" Add it under Edit providers in QuickAdd's AI Assistant settings (the sparkles button below the choice list), or enable auto-sync for that provider.";throw new Error(`Model '${typeof r=="string"?r:`${r.provider??""}/${e}`}' not found in configured providers.${o}`)}return t}var vU,Tm=E(()=>{Ie();dt();vU=new Set});var eT=E(()=>{});var ho=E(()=>{});var Pn,$l=E(()=>{Ss();Pn=class{constructor(e,t){this.name=e,this.type=t,this.id=Kt()}}});var _t,Rs=E(()=>{vr();$l();ys();Ie();_t=class extends Pn{constructor(e){super(e,"EditorCommand"),this.editorCommandType=e}static getSelectedText(e){return this.getActiveMarkdownView(e).editor.getSelection()}static getActiveMarkdownView(e){let t=xn(e);if(!t)throw I.logError("no active markdown editor."),new Error("no active markdown editor.");return t}}});var Sm,BF=E(()=>{ho();Rs();Sm=class extends _t{constructor(){super("Copy")}static async run(e){let t=_t.getSelectedText(e);await navigator.clipboard.writeText(t)}}});var _m,qF=E(()=>{ho();Rs();Ie();_m=class extends _t{constructor(){super("Cut")}static async run(e){let t=_t.getSelectedText(e),n=_t.getActiveMarkdownView(e);if(!t){I.logError("nothing selected.");return}await navigator.clipboard.writeText(t),n.editor.replaceSelection("")}}});var Am,UF=E(()=>{ho();Ie();Rs();Am=class extends _t{constructor(){super("Paste")}static async run(e){let t=await navigator.clipboard.readText(),n=_t.getActiveMarkdownView(e);if(!n){I.logError("no active markdown view.");return}n.editor.replaceSelection(t)}}});var kU,Im,HF=E(()=>{kU=require("obsidian");Ie();Rs();ho();Im=class extends _t{constructor(){super("Paste with format")}static async run(e){let t=_t.getActiveMarkdownView(e);if(!t){I.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,kU.htmlToMarkdown)(l),o=!0;break}o||(n=await navigator.clipboard.readText())}else n=await navigator.clipboard.readText();t.editor.replaceSelection(n)}catch(i){I.logWarning(`Formatted paste failed. Falling back to plain text: ${i}`);try{let o=await navigator.clipboard.readText();t.editor.replaceSelection(o)}catch(o){I.logError(`Failed to read clipboard text: ${o}`)}}}}});var Dm,zF=E(()=>{ho();Rs();Dm=class extends _t{constructor(){super("Select active line")}static run(e){let t=_t.getActiveMarkdownView(e),{line:n}=t.editor.getCursor(),o=t.editor.getLine(n).length;t.editor.setSelection({line:n,ch:0},{line:n,ch:o})}}});var Fm,WF=E(()=>{Rs();ho();Xe();Ie();Fm=class extends _t{constructor(){super("Select link on active line")}static run(e){let t=_t.getActiveMarkdownView(e),{line:n}=t.editor.getCursor(),i=t.editor.getLine(n),o=gN.exec(i);if(!o){I.logError(`no internal link found on line ${n}.`);return}let s=o.index,a=o[0].length+s;t.editor.setSelection({line:n,ch:s},{line:n,ch:a})}}});var Pm,jF=E(()=>{Rs();ho();Pm=class extends _t{constructor(){super("Move cursor to file start")}static run(e){_t.getActiveMarkdownView(e).editor.setCursor({line:0,ch:0})}}});var Mm,GF=E(()=>{Rs();ho();Mm=class extends _t{constructor(){super("Move cursor to file end")}static run(e){let t=_t.getActiveMarkdownView(e),n=t.editor.lastLine(),i=t.editor.getLine(n).length;t.editor.setCursor({line:n,ch:i})}}});var $m,YF=E(()=>{Rs();ho();$m=class extends _t{constructor(){super("Move cursor to line start")}static run(e){let t=_t.getActiveMarkdownView(e),{line:n}=t.editor.getCursor();t.editor.setCursor({line:n,ch:0})}}});var Om,KF=E(()=>{Rs();ho();Om=class extends _t{constructor(){super("Move cursor to line end")}static run(e){let t=_t.getActiveMarkdownView(e),{line:n}=t.editor.getCursor(),i=t.editor.getLine(n).length;t.editor.setCursor({line:n,ch:i})}}});var DU,Nm,ZF=E(()=>{DU=require("obsidian");Ie();rn();ur();Nm=class extends DU.FuzzySuggestModal{constructor(t,n,i,o,s){super(t);this.warnedOnEmptyDisplay=!1;this.warnRenderItemFailure=ff("Custom renderItem threw an error; falling back to default rendering");this.renderItem=o,this.items=i,this.displayItems=n.map(a=>kn(a)),this.promise=new Promise((a,l)=>{this.resolvePromise=a,this.rejectPromise=l}),s?.skippable&&XL(this,()=>this.skip()),this.inputEl.addEventListener("keydown",a=>{if(a.code!=="Tab"||!("chooser"in this))return;let{values:l,selectedItem:c}=this.chooser,{value:u}=this.inputEl;this.inputEl.value=l[c]?.item??u}),this.displayItems.length!==this.items.length&&(this.displayItems=this.items.map((a,l)=>{let c=this.displayItems[l];return kn(c??a)}))}getItemText(t){let n=this.items.indexOf(t),i=n>=0?this.displayItems[n]:void 0;return kn(i??t)}getItems(){return this.items}getSuggestions(t){let n=Ac(t);return super.getSuggestions(n)}selectSuggestion(t,n){this.resolved=!0,super.selectSuggestion(t,n)}renderSuggestion(t,n){if(!this.renderItem){super.renderSuggestion(t,n);return}try{n.empty(),this.renderItem(t.item,n)}catch(i){this.warnRenderItemFailure(i),n.empty(),super.renderSuggestion(t,n)}}renderDefaultSuggestion(t,n){super.renderSuggestion(t,n)}onChooseItem(t,n){this.resolved=!0,this.resolvePromise(t)}skip(){this.resolved=!0,this.resolvePromise(""),this.close()}onClose(){super.onClose(),this.resolved||this.rejectPromise(Rr())}warnIfEmptyDisplay(){if(this.warnedOnEmptyDisplay)return;this.displayItems.some(n=>n.length===0)&&(this.warnedOnEmptyDisplay=!0,I.logWarning("QuickAdd suggester received empty display values. Check your displayItems mapping."))}}});var FU,Mr,Ol=E(()=>{FU=require("obsidian");rn();ZF();Mr=class r extends Nm{constructor(t,n,i,o={}){super(t,n,i,o.renderItem,o);this.warnCustomValueFailure=ff("Custom create-row rendering threw an error; falling back to default rendering");this.allowCustomValue=!0;this.searchItems=o.searchItems?.map(s=>kn(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)=>kn(this.searchItems[a]??this.displayItems[a]??s))),this.warnIfEmptyDisplay(),this.open()}static Suggest(t,n,i,o={}){return new r(t,n,i,o).promise}getItemText(t){if(t===this.inputEl.value)return t;let n=this.items.indexOf(t),i=n>=0?this.searchItems[n]:void 0;return kn(i??t)}getSuggestions(t){let n=super.getSuggestions(t);if(!this.allowCustomValue)return n;let i=Ac(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(t,n){if(this.customValueLabel&&t.match.score===Number.NEGATIVE_INFINITY){this.renderCustomValue(t.item,n);return}super.renderSuggestion(t,n)}renderCustomValue(t,n){try{n.empty(),n.addClass("mod-complex"),n.createDiv({cls:"suggestion-content"}).createDiv({cls:"suggestion-title",text:this.customValueLabel?.(t)??t});let o=n.createDiv({cls:"suggestion-aux"});(0,FU.setIcon)(o.createSpan({cls:"suggestion-flair"}),"file-plus")}catch(i){this.warnCustomValueFailure(i),n.empty(),this.renderDefaultSuggestion({item:t,match:{score:0,matches:[]}},n)}}}});function GU(r,e=new Set){if(r==null||e.has(r))return[];if(e.add(r),typeof r=="string")return[r];if(typeof r!="object")return[String(r)];let t=r,n=[];for(let i of Nee){let o=t[i];o!==void 0&&n.push(...GU(o,e))}return n}function xT(r){return Number(r.replace(/,/g,""))}function Lee(r){let e=r.match(/context (?:length|window)(?:\s+is)?(?:\s+of)?\s*(\d[\d,]*)/i);return e?xT(e[1]):null}function Vee(r){let e=r.match(/(\d[\d,]*)\s*(?:tokens?\s+)?in the completion\b/i);if(e){let n=xT(e[1]),i=Lee(r);return i===null?"input":n>=i?"output":"input"}let t=r.match(/input length and max_tokens exceed context limit:?\s*(\d[\d,]*)\s*\+\s*(\d[\d,]*)(?:\s*>\s*(\d[\d,]*))?/i);if(t){let n=xT(t[2]),i=t[3]?xT(t[3]):null;return i===null?"input":n>=i?"output":"input"}return null}function eb(r){let e=GU(r).join(" "),t=Vee(e);return t==="output"?"output_budget":t==="input"?"input_context":Ree.some(n=>n.test(e))?"output_budget":Oee.some(n=>n.test(e))?"input_context":"other"}function YU(r){return eb(r)==="input_context"}function ET(r,e){let t="",n="",i;try{i=e.json}catch{i=void 0}if(i&&typeof i=="object"){let s=i,a=s.error??s;t=String(a.message??s.message??""),n=String(a.code??a.type??a.status??"")}t||(t=typeof e.text=="string"&&e.text.length>0?e.text:`HTTP ${e.status}`);let o=new Error(`${r} request failed (HTTP ${e.status})${n?` [${n}]`:""}: ${t}`);return o.status=e.status,n&&(o.providerCode=n),o}var Oee,Ree,Nee,Um=E(()=>{Oee=[/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],Ree=[/max_tokens/i,/max_completion_tokens/i,/max(?:imum)? output tokens/i,/output token limit/i],Nee=["message","code","type","status","statusText","providerCode","error","response","json","cause"]});function Qee(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"provider"}function Xee(r){let e=r.name?.trim()||"provider";return`${Kee}-${Qee(e)}`}async function ZU(r,e){if(!r?.secretStorage?.getSecret)return null;try{return await Promise.resolve(r.secretStorage.getSecret(e))}catch(t){return I.logWarning(`Failed to read SecretStorage entry "${e}": ${t.message??t}`),null}}async function Ca(r,e){let t=e.apiKeyRef?.trim();if(t){let n=await ZU(r,t);if(n)return n}return e.apiKey??""}async function JU(r,e,t){let n=t?.trim();if(!n||!r?.secretStorage?.getSecret||!r.secretStorage?.setSecret)return null;let i=Xee(e),o=i,s=1;for(;;){let a=await ZU(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 I.logWarning(`Failed to write SecretStorage entry "${o}": ${a.message??a}`),null}}var Kee,Yd=E(()=>{Ie();Kee="quickadd-ai"});function VH(r){try{let e=window.require;return e?e(r):null}catch{return null}}async function Km(r,e){let t=r.vault.adapter;if(typeof EP.FileSystemAdapter!="function"||!(t instanceof EP.FileSystemAdapter))return;let n=VH("fs"),i=VH("path");if(!n?.promises||!i)return;let o=await n.promises.realpath(t.getBasePath()),a=t.getFullPath(e);for(;!sre(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 nb(`Refusing to write to "${e}": it resolves through an unresolvable (dangling) symlink.`)}let c=i.relative(o,l);if(c===".."||c.startsWith(`..${i.sep}`)||i.isAbsolute(c))throw new nb(`Refusing to write to "${e}": it resolves (via a symlink) outside the vault.`);if(c.split(i.sep).some(p=>p.startsWith(".")))throw new nb(`Refusing to write to "${e}": it resolves (via a symlink) into a config/hidden directory.`)}function sre(r,e){try{return r.lstatSync(e),!0}catch{return!1}}var EP,nb,TP=E(()=>{EP=require("obsidian"),nb=class extends Error{constructor(e){super(e),this.name="VaultWriteEscapeError"}}});async function cb(r,e,t){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;)e.setMessage(t[0],`${t[1]} (${((Date.now()-n)/1e3).toFixed(2)}s)`),await sleep(100);return e.setMessage("finished",`Took ${((Date.now()-n)/1e3).toFixed(2)}s.`),await r}function ub(r,e){return{[r]:e,[`${r}-quoted`]:("> "+e).replace(/\n/g,`
> `)}}var XP=E(()=>{});var ye,Yn=E(()=>{Ni();ye=class extends yt{}});var Xt,Zo=E(()=>{ZF();Xt=class r extends Nm{static Suggest(e,t,n,i,o,s){let a=new r(e,t,n,o,s);return i&&a.setPlaceholder(i),a.promise}constructor(e,t,n,i,o){super(e,t,n,i,o),this.warnIfEmptyDisplay(),this.open()}}});function $n(r,e){if(!r)throw new Error(typeof e=="function"?e():e)}var Jm=E(()=>{});function eh(r){return ZP.filter(e=>typeof r[e]=="number")}function ok(r){let e={...r};for(let t of ZP)delete e[t];return e}function JP(r,e){return r.supportsTemperature===!1&&eh(e).length>0?ok(e):e}function vz(r,e){return e.length===0?!1:Mne.some(t=>t.test(r))}function e0(r){let e=r.map(t=>Pne[t]);return e.length<=1?e.join(""):e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`}function db(r,e){let t={};return typeof e.temperature=="number"&&(t.temperature=e.temperature),typeof e.top_p=="number"&&(t[r==="gemini"?"topP":"top_p"]=e.top_p),t}var ZP,Pne,ik,Mne,sk=E(()=>{ZP=["temperature","top_p","frequency_penalty","presence_penalty"],Pne={temperature:"Temperature",top_p:"Top P",frequency_penalty:"Frequency penalty",presence_penalty:"Presence penalty"};ik=ZP.join("|"),Mne=[new RegExp(`unsupported (?:parameter|value)[^.]{0,40}['\`"]?(?:${ik})['\`"]?`,"i"),new RegExp(`['\`"]?(?:${ik})['\`"]?[^.]{0,40}(?:is deprecated|is not supported|not supported|does not support)`,"i"),new RegExp(`unrecognized request argument[^.]{0,40}(?:${ik})`,"i"),new RegExp(`(?:${ik})[^.]{0,40}extra inputs are not permitted`,"i")]});function t0(r){return{...r,modelOptions:{...r.modelOptions},usage:r.usage?{...r.usage}:void 0}}function r0(r){let e=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,t=Date.now();return Jo.push({...r,modelOptions:{...r.modelOptions??{}},id:e,createdAt:t,status:"pending"}),bz(),e}function pb(r,e){let t=Jo.find(n=>n.id===r);t&&(t.status=e.status,t.durationMs=e.durationMs,t.usage=e.usage,t.errorMessage=e.errorMessage,bz())}function yz(r=10){Number.isFinite(r)||(r=10);let e=Math.floor(r);return e<=0?[]:Jo.slice(-e).map(t0).reverse()}function bz(){if(Jo.length<=25)return;let r=Jo.length-25;for(;r>0;){let e=Jo.findIndex(t=>t.status!=="pending");if(e===-1)break;Jo.splice(e,1),r-=1}}function wz(r){let e=Jo.find(t=>t.id===r);return e?t0(e):null}function Cz(){let r=Jo[Jo.length-1];return r?t0(r):null}function xz(){Jo.splice(0,Jo.length)}var Jo,n0=E(()=>{Jo=[]});function ak(r){let e=r.workspace.activeEditor?.editor?.getCursor(),t=r.workspace.activeEditor?.editor?.listSelections();return()=>{e&&r.workspace.activeEditor?.editor?.setCursor(e),t&&r.workspace.activeEditor?.editor?.setSelections(t)}}var i0=E(()=>{});function fb(r){let e=Array.isArray(r)?r:{...r},t=e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")||e.properties!==void 0;if(e.properties){let n={};for(let[i,o]of Object.entries(e.properties))n[i]=fb(o);e.properties=n}return e.items&&!Array.isArray(e.items)&&(e.items=fb(e.items)),t&&(e.additionalProperties=!1,e.required=e.properties?Object.keys(e.properties):[]),e}function $ne(r){let e=[];for(let t of r)if(t.role==="system")e.push({role:"system",content:t.content});else if(t.role==="user")e.push({role:"user",content:t.content});else if(t.role==="assistant"){let n={role:"assistant",content:t.content??""};t.toolCalls&&t.toolCalls.length>0&&(n.tool_calls=t.toolCalls.map(i=>({id:i.id,type:"function",function:{name:i.name,arguments:i.rawArgs??JSON.stringify(i.args??{})}}))),e.push(n)}else for(let n of t.results)e.push({role:"tool",tool_call_id:n.toolCallId,content:n.isError?`ERROR: ${n.content}`:n.content});return e}function One(r){return r.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.strict?fb(e.parameters):e.parameters,...e.strict?{strict:!0}:{}}}))}function Rne(r){return typeof r=="string"?r:{type:"function",function:{name:r.name}}}function Lne(r,e){let t={model:r,...e.modelParams??{},messages:$ne(e.messages)};return e.tools&&e.tools.length>0&&(t.tools=One(e.tools),e.toolChoice&&(t.tool_choice=Rne(e.toolChoice)),e.disableParallel&&(t.parallel_tool_calls=!1)),e.maxOutputTokens!==void 0&&(Nne.test(r)?t.max_completion_tokens=e.maxOutputTokens:t.max_tokens=e.maxOutputTokens),e.responseFormat&&(t.response_format=e.responseFormat.schema?{type:"json_schema",json_schema:{name:e.responseFormat.name??"response",strict:e.responseFormat.strict??!0,schema:e.responseFormat.strict??!0?fb(e.responseFormat.schema):e.responseFormat.schema}}:{type:"json_object"}),t}function Vne(r){let e=r.choices?.[0]??{},t=e.message??{},i=(t.tool_calls??[]).map(a=>Bne(a)),o=String(e.finish_reason??""),s=r.usage??{};return{content:t.content??"",toolCalls:i,normalizedStopReason:i.length>0||o==="tool_calls"?"tool_calls":o==="length"?"length":o==="stop"?"stop":"other",rawStopReason:o,usage:{promptTokens:s.prompt_tokens??0,completionTokens:s.completion_tokens??0,totalTokens:s.total_tokens??0}}}function Ez(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function Bne(r){let e=r.function.arguments;if(typeof e=="string")try{let n=Ez(JSON.parse(e||"{}"));if(!n)throw new Error("tool arguments are not a JSON object");return{id:r.id,name:r.function.name,args:n,rawArgs:e}}catch{return{id:r.id,name:r.function.name,args:null,rawArgs:e,parseError:!0}}let t=Ez(e);return t?{id:r.id,name:r.function.name,args:t}:{id:r.id,name:r.function.name,args:null,rawArgs:typeof e=="string"?e:JSON.stringify(e??{}),parseError:!0}}function qne(r,e,t){let n=[],i=[];for(let s of e.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:e.maxOutputTokens??t,messages:i};return n.length>0&&(o.system=n.join(`
`)),Object.assign(o,db("anthropic",e.modelParams??{})),e.tools&&e.tools.length>0&&(o.tools=e.tools.map(s=>({name:s.name,description:s.description,input_schema:s.parameters})),e.toolChoice?o.tool_choice=Une(e.toolChoice,e.disableParallel):e.disableParallel&&(o.tool_choice={type:"auto",disable_parallel_tool_use:!0})),e.responseFormat?.schema&&(o.output_config={format:{type:"json_schema",schema:fb(e.responseFormat.schema)}}),o}function Une(r,e){let t=e?{disable_parallel_tool_use:!0}:{};return typeof r=="string"?r==="required"?{type:"any",...t}:r==="none"?{type:"none"}:{type:"auto",...t}:{type:"tool",name:r.name,...t}}function Hne(r){let e=r.content??[],t=e.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:e.filter(a=>a.type==="text").map(a=>a.text??"").join(""),toolCalls:t,normalizedStopReason:n==="tool_use"||t.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 zne(r,e){let t=[],n=[];for(let s of e.messages)if(s.role==="system")s.content&&t.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};t.length>0&&(i.systemInstruction={role:"system",parts:[{text:t.join(`
`)}]}),e.tools&&e.tools.length>0&&(i.tools=[{functionDeclarations:e.tools.map(s=>({name:s.name,description:s.description,parameters:s.parameters}))}],e.toolChoice&&(i.toolConfig=Wne(e.toolChoice)));let o=db("gemini",e.modelParams??{});return e.maxOutputTokens!==void 0&&(o.maxOutputTokens=e.maxOutputTokens),e.responseFormat?.schema&&(o.responseMimeType="application/json",o.responseSchema=e.responseFormat.schema),Object.keys(o).length>0&&(i.generationConfig=o),i}function Wne(r){return typeof r=="string"?{functionCallingConfig:{mode:r==="required"?"ANY":r==="none"?"NONE":"AUTO"}}:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[r.name]}}}function jne(r){let e=r.candidates?.[0]??{},n=(e.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(e.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 o0(r,e,t,n=8192){switch(r){case"anthropic":return qne(e,t,n);case"gemini":return zne(e,t);default:return Lne(e,t)}}function Tz(r,e){switch(r){case"anthropic":return Hne(e);case"gemini":return jne(e);default:return Vne(e)}}var Nne,kz=E(()=>{sk();Nne=/^(?:o[1-9]|gpt-(?:[5-9]|\d\d))/i});async function mb({kind:r,apiKey:e,provider:t,model:n,body:i,afterRequest:o}){let s={"Content-Type":"application/json"},a;switch(r){case"anthropic":a="/v1/messages",s["x-api-key"]=e,s["anthropic-version"]="2023-06-01";break;case"gemini":a=`/v1beta/models/${encodeURIComponent(n.name)}:generateContent`,s["x-goog-api-key"]=e;break;default:a="/chat/completions",s.Authorization=`Bearer ${e}`}let l=(0,Sz.requestUrl)({url:t.endpoint+a,method:"POST",headers:s,body:JSON.stringify(i),throw:!1});o?.();let c=await l;if(c.status>=400)throw ET(t.name,c);return c.json}function Gne(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 Yne(r){return{id:r.id,model:r.model,content:r.content.filter(e=>e.type==="text").map(e=>e.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 hb(r){if(typeof r.maxOutputTokens=="number"&&Number.isFinite(r.maxOutputTokens)&&r.maxOutputTokens>0)return Math.floor(r.maxOutputTokens);let e=4096;return Number.isFinite(r.maxTokens)&&r.maxTokens>0?Math.min(e,r.maxTokens):e}function Kne(r,e,t,n,i){if(r!=="anthropic"&&r!=="gemini")return{model:e.name,...n,messages:[{role:"system",content:t},{role:"user",content:i}]};let o=db(r,n);return r==="anthropic"?{model:e.name,max_tokens:hb(e),messages:[{role:"user",content:i}],...t&&t.trim().length>0?{system:t}:{},...o}:{contents:[{role:"user",parts:[{text:i}]}],...t&&t.trim().length>0?{systemInstruction:{role:"system",parts:[{text:t}]}}:{},...Object.keys(o).length?{generationConfig:o}:{}}}async function _z({kind:r,systemPrompt:e,params:t,prompt:n,...i}){let o=Kne(r,i.model,e,t,n),s={...i,kind:r,body:o};switch(r){case"anthropic":return Yne(await mb(s));case"gemini":return Qne(await mb(s));default:return Gne(await mb(s))}}function Qne(r){let e=r.candidates?.[0],n=(e?.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:e?.finishReason??"",stopSequence:null,created:Date.now()}}var Sz,s0=E(()=>{Sz=require("obsidian");Um();sk()});function gb(r,e,t,n,i,o={}){return async function(a){if(X.getState().disableOnlineFeatures)throw new Error("Blocking request: Online features are disabled in settings.");let l=Ui(a)+Ui(i),c=Date.now(),u=r0({provider:n.name,endpoint:n.endpoint,model:t.name,systemPrompt:i,prompt:a,modelOptions:o});I.logMessage(`[AI Request ${u}] Started ${n.name}/${t.name}`),Number.isFinite(t.maxTokens)&&t.maxTokens>0&&l>t.maxTokens&&I.logMessage(`[AI Request ${u}] Estimated prompt size is ${l} tokens, above the configured ${t.maxTokens} token context. Sending anyway; the provider will enforce the exact limit.`);try{let d=ak(r),p=Eg(n),f=b=>_z({kind:p,apiKey:e,model:t,provider:n,systemPrompt:i,params:b,prompt:a,afterRequest:d}),m=JP(t,o),g=eh(m);g.length===0&&eh(o).length>0&&I.logMessage(`[AI Request ${u}] ${t.name} uses fixed sampling; not sending ${e0(eh(o))}.`);let v=await Iz(()=>f(m),()=>f(ok(m)),{sentKeys:g,model:t,provider:n,logPrefix:`AI Request ${u}`,advancedSettings:!0}),y=Date.now()-c;return pb(u,{status:"success",durationMs:y,usage:v.usage}),I.logMessage(`[AI Request ${u}] Success in ${y}ms`),v}catch(d){let p=d.message??String(d),f=Date.now()-c;pb(u,{status:"error",durationMs:f,errorMessage:p}),I.logMessage(`[AI Request ${u}] Failed in ${f}ms: ${p}`);let m=eb(d)==="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.":"",g=new Error(`Error while making request to ${n.name}: ${p}${m}`,{cause:d});throw Ze(g),g}}}async function a0(r,e,t,n,i,o){if(X.getState().disableOnlineFeatures)throw new Error("Blocking request: Online features are disabled in settings.");let s=Eg(n),a={...i,modelParams:JP(t,i.modelParams??{})},l=eh(a.modelParams??{}),c=o0(s,t.name,a,hb(t)),u=i.messages.find(m=>m.role==="system"),d=[...i.messages].reverse().find(m=>m.role==="user"),p=Date.now(),f=r0({provider:n.name,endpoint:n.endpoint,model:t.name,systemPrompt:u&&u.role==="system"?u.content:"",prompt:d&&d.role==="user"?d.content:"[tool-calling turn]",modelOptions:i.modelParams??{}});try{let m=b=>mb({kind:s,apiKey:e,provider:n,model:t,body:b,afterRequest:o}),g=await Iz(()=>m(c),()=>m(o0(s,t.name,{...a,modelParams:ok(a.modelParams??{})},hb(t))),{sentKeys:l,model:t,provider:n,logPrefix:`AI Chat ${f}`}),v=Tz(s,g),y=Date.now()-p;return pb(f,{status:"success",durationMs:y,usage:v.usage}),I.logMessage(`[AI Chat ${f}] Success in ${y}ms`),{id:g.id??`${Date.now()}`,model:t.name,content:v.content,usage:v.usage,stopReason:v.rawStopReason,stopSequence:null,created:Date.now(),toolCalls:v.toolCalls,normalizedStopReason:v.normalizedStopReason,providerRaw:v.providerRaw}}catch(m){let g=m.message??String(m),v=Date.now()-p;pb(f,{status:"error",durationMs:v,errorMessage:g});let y=new Error(`Error while making request to ${n.name}: ${g}`,{cause:m});throw Ze(y),y}}async function Iz(r,e,t){try{return await r()}catch(n){let i=n.message??String(n),{sentKeys:o,model:s,provider:a,logPrefix:l,advancedSettings:c}=t;if(!vz(i,o))throw n;let u=e0(o),d=o.length>1?"them":"it";return I.logMessage(`[${l}] ${a.name} rejected ${u}; retrying without sampling parameters.`),new Az.Notice(`${s.name} doesn't accept the ${u} setting${o.length>1?"s":""}, so QuickAdd retried without ${d}.`+(c?` You can remove ${d} from this command's advanced settings.`:"")),e()}}var Az,lk=E(()=>{Az=require("obsidian");sk();dt();n0();i0();xt();ro();kz();Ie();Wy();Um();s0();s0()});function Kd(r){if(r){let e=new Fz.Notice(Dz("starting",""),1e6);return{setMessage:(t,n)=>{e.setMessage(Dz(t,n))},hide:()=>e.hide()}}return{setMessage:()=>{},hide:()=>{}}}var Fz,Dz,ck=E(()=>{Fz=require("obsidian"),Dz=(r,e)=>`${r==="dead"?"AI request failed.":`Assistant is ${r}.`}${e?`
${e}`:""}`});function Zne(){return Array.from(new Set([l0,...["kebab","snake","camel","pascal","title","lower","upper","slug"].map(r=>_v(l0,r))])).filter(Boolean)}function Mz(r){if(r.length<=1)return null;let e=Math.floor(r.length/2),t=[`
`,`
`,". "," "],n=-1,i=Number.POSITIVE_INFINITY;for(let a of t){let l=r.lastIndexOf(a,e),c=r.indexOf(a,e),u=[l,c].filter(d=>d>0);for(let d of u){let p=d+a.length;if(p<=0||p>=r.length)continue;let f=Math.abs(p-e);f<i&&(i=f,n=p)}}if(n>0&&n<r.length)return[r.slice(0,n),r.slice(n)];let o=e,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 Jne(r){let e=new RegExp(od.source,"gi"),t;for(;(t=e.exec(r))!==null;)if(t[1].split("|")[0].trim().toLowerCase()==="chunk")return!0;return!1}function eie(r){return Oo.test(r)||hc.test(r)||dC.test(r)||tl.test(r)}function tie(r){return Pz.some(e=>r.includes(e))}function rie(r){return Pz.slice().sort((e,t)=>t.length-e.length).reduce((e,t)=>e.split(t).join(" "),r)}function $z(r){if(r>dk)throw new Error(`QuickAdd would split this chunked AI request into more than ${dk} prompts, which exceeds the safety limit. Increase the chunk size, use a larger chunk separator, or reduce the input text.`)}function nie(r,e,t){let n=Math.max(1,Math.floor(e)),i=[r],o=0;for(;i.length>0;){let s=i.pop(),l=Ui(s)<=n?null:Mz(s);if(!l){t.push(s),o+=1,$z(o);continue}i.push(l[1],l[0])}}function iie(r){let e=r.flags.replace(/[gy]/g,"");return new RegExp(r.source+"|",e).exec("").length-1}function sie(r,e){if(typeof e=="string"){let s=r.split(e);return{chunks:s,separators:new Array(Math.max(0,s.length-1)).fill(e)}}if(iie(e)>0||oie.test(e.source))return{chunks:r.split(e),separators:null};let t=new RegExp(`(${e.source})`,e.flags),n=r.split(t),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 aie(r,e,t,n){let i=[];if(r.forEach((l,c)=>{let u=[];nie(l,t,u),u.forEach((d,p)=>{i.push({text:d,joiner:p===0&&c>0?e?.[c-1]??"":""})})}),!n)return i.map(l=>l.text);let o=[],s="",a=0;for(let l of i){let c=Ui(l.text)+Math.max(1,Ui(l.joiner));s!==""&&a+c>=t&&(o.push(s),s="",a=0),s+=s===""?l.text:l.joiner+l.text,a+=c}return s!==""&&o.push(s),o}function lie(r,e){let t=Math.max(1,Math.floor(r));if(e!==void 0&&Number.isFinite(e)&&e>0){let n=Math.floor(e);return{budget:Math.min(t,n),clamped:n>t}}return{budget:t,clamped:!1}}async function c0(r,e,t){if(X.getState().disableOnlineFeatures)throw new Error("Online features are disabled in settings. Enable them to use the AI Assistant.");let n=Kd(e.showAssistantMessages);try{let{apiKey:i,model:o,provider:s,outputVariableName:a,systemPrompt:l,promptTemplate:c,text:u,modelOptions:d}=e;n.setMessage("chunking","Creating prompt chunks with text and prompt template");let p=e.chunkSeparator||/\n/g,{chunks:f,separators:m}=sie(u,p),g=await t(c,{chunk:l0});if(!(Jne(c)||eie(c)&&tie(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 y=o.maxTokens,b=hU(y),x=rie(g),w=Ui(l)+Ui(x);if(w>=y)throw new Error(`The estimated prompt overhead (${w} tokens) exceeds the model's entire context window (${y} tokens). Shorten the system prompt or prompt template, or use a model with a larger context window.`);let{budget:T,clamped:C}=lie(b-w,e.maxChunkTokens);C&&I.logMessage(`[ChunkedPrompt] Requested max chunk tokens (${e.maxChunkTokens}) exceeds this model's estimated input budget; using ${T} estimated tokens per chunk instead.`);let S=e.shouldMerge??!0,A=aie(f,m,T,S);$z(A.length);let D=gb(r,i,o,s,l,d),P=["prompting",`${A.length} prompts being sent.`];n.setMessage(P[0],P[1]);let U=new uk(5,1e3*30),K=!1,W=0,ee=Promise.resolve(),me=G=>{let ie=ee.then(()=>{if(K)throw new Error("Chunked prompt stopped after an earlier failure.");return t(c,{chunk:G})});return ee=ie.then(()=>{},()=>{}),ie},O=async(G,ie=0)=>{if(K)throw new Error("Chunked prompt stopped after an earlier failure.");let xe;try{xe=await me(G)}catch(ue){throw K=!0,ue}try{return[(await U.add(()=>{if(K)throw new Error("Chunked prompt stopped after an earlier failure.");if(W+=1,W>dk)throw new Error(`Chunked AI request exceeded the safety limit of ${dk} provider requests.`);return D(xe)})).content]}catch(ue){let be=Mz(G);if(ie>=Xne||!be||!YU(ue))throw K=!0,ue;n.setMessage("prompting","Provider rejected a prompt for context length. Retrying with smaller chunks.");let[Ke,Oe]=be,Ee=await O(Ke,ie+1),He=await O(Oe,ie+1);return[...Ee,...He]}},H=Promise.all(A.map(G=>O(G))),z=(await cb(H,n,P)).flat().join(e.resultJoiner);return window.setTimeout(()=>n.hide(),5e3),ub(a,z)}catch(i){throw n.setMessage("dead",i.message),window.setTimeout(()=>n.hide(),5e3),i}}var uk,Xne,dk,l0,Pz,oie,Oz=E(()=>{dt();lk();Um();ck();Wy();Ie();Xe();Ax();XP();uk=class{constructor(e,t){this.maxRequests=e;this.intervalMs=t;this.queue=[];this.startTimes=[]}add(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{t(await e())}catch(i){n(i instanceof Error?i:new Error(String(i)))}}),this.schedule()})}schedule(){if(this.queue.length===0)return;let e=Date.now();if(this.startTimes=this.startTimes.filter(i=>e-i<this.intervalMs),this.startTimes.length>=this.maxRequests){let i=this.startTimes[0],o=Math.max(0,this.intervalMs-(e-i));window.setTimeout(()=>this.schedule(),o+1);return}let t=this.queue.shift();if(!t)return;this.startTimes.push(e);let n=t();window.setTimeout(()=>this.schedule(),this.intervalMs),this.schedule()}},Xne=12,dk=500,l0="quickadd_chunk_probe_123456789";Pz=Zne();oie=/(?:^|[^\\])(?:\\\\)*\\[1-9]/});async function cie(r,e,t,n=!0,i){let o;if(e.enable)o=t.find(c=>c.path.endsWith(e.name));else{let c=t.map(u=>u.basename);if(i)o=await i.suggester(c,t,"Select a prompt template");else if(n)o=await Xt.Suggest(r,c,t);else throw new ye("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.")}$n(o,"Prompt template does not exist");let s=o.path,a=r.vault.getAbstractFileByPath(s);$n(a instanceof Rz.TFile,`${s} is not a file`);let l=await r.vault.cachedRead(a);return[o.basename,l]}async function Nz(r,e,t){if(X.getState().disableOnlineFeatures)throw new Error("Online features are disabled in settings. Enable them to use the AI Assistant.");let n=Kd(e.showAssistantMessages);try{let{apiKey:i,model:o,provider:s,outputVariableName:a,promptTemplate:l,systemPrompt:c,promptTemplateFolder:u}=e,d=Bo(r,u),[p,f]=await cie(r,l,d,e.interactive??!0,e.promptProvider);n.setMessage("waiting","QuickAdd is formatting the prompt template.");let m=await t(f),g=["prompting",`Using prompt template "${p}".`];n.setMessage(g[0],g[1]);let y=gb(r,i,o,s,c,e.modelOptions)(m),x=(await cb(y,n,g)).content;return window.setTimeout(()=>n.hide(),5e3),ub(a,x)}catch(i){throw n.setMessage("dead",i.message),window.setTimeout(()=>n.hide(),5e3),ot(i)?new at("Input cancelled by user"):i}}async function Lz(r,e,t){if(X.getState().disableOnlineFeatures)throw new Error("Online features are disabled in settings. Enable them to use the AI Assistant.");let n=Kd(e.showAssistantMessages);try{let{apiKey:i,model:o,provider:s,outputVariableName:a,systemPrompt:l,prompt:c,modelOptions:u}=e;n.setMessage("waiting","QuickAdd is formatting the prompt template.");let d=await t(c),p=["prompting","Using custom prompt."];n.setMessage(p[0],p[1]);let m=gb(r,i,o,s,l,u)(d),v=(await cb(m,n,p)).content;return window.setTimeout(()=>n.hide(),5e3),ub(a,v)}catch(i){throw n.setMessage("dead",i.message),window.setTimeout(()=>n.hide(),5e3),i}}var Rz,u0=E(()=>{XP();Rz=require("obsidian");ur();Yn();Zo();dt();ht();Jm();xt();lk();ck();n0();Oz()});function uie(r,e,t,n={}){let i=n.tab??" ";if(e===t){let d=e+i.length;return{regionStart:e,regionEnd:e,replacement:i,selectionStart:d,selectionEnd:d}}let o=e===0?0:r.lastIndexOf(`
`,e-1)+1,a=r.slice(o,t).split(`
`),l=a.length-1,c=0,u=a.map((d,p)=>p===l&&d===""?d:(c+=i.length,i+d));return{regionStart:o,regionEnd:t,replacement:u.join(`
`),selectionStart:e+i.length,selectionEnd:t+c}}function die(r,e){r.setSelectionRange(e.regionStart,e.regionEnd);let t=r.ownerDocument,n=!1;try{n=typeof t.execCommand=="function"&&t.execCommand("insertText",!1,e.replacement)}catch{n=!1}if(!n){let i=r.value;r.value=i.slice(0,e.regionStart)+e.replacement+i.slice(e.regionEnd),r.setSelectionRange(e.selectionStart,e.selectionEnd),r.dispatchEvent(new Event("input",{bubbles:!0}));return}r.setSelectionRange(e.selectionStart,e.selectionEnd)}function Vz(r,e={}){let t=i=>{if(i.key!=="Tab"||i.shiftKey||i.ctrlKey||i.metaKey||i.altKey||i.isComposing||i.defaultPrevented)return;i.preventDefault();let o=r.selectionStart??r.value.length,s=r.selectionEnd??o;die(r,uie(r.value,o,s,e))};r.addEventListener("keydown",t);let n=!1;return()=>{n||(n=!0,r.removeEventListener("keydown",t))}}var Bz=E(()=>{});var qz,cu,d0=E(()=>{qz=require("obsidian");nD();Bz();cu=class r extends xf{static Prompt(e,t,n,i,o,s){return new r(e,t,n,i,void 0,o,s).waitForClose}static PromptWithContext(e,t,n,i,o,s,a){return new r(e,t,n,i,o,s,a).waitForClose}getPromptKind(){return"multi"}createInputField(e,t,n){let i=new qz.TextAreaComponent(e);return i.inputEl.classList.add("wideInputPromptInputEl"),i.inputEl.setAttribute("dir","auto"),this.disposeIndent=Vz(i.inputEl),this.configureInput(i,t,n)}shouldSubmit(e){return(e.ctrlKey||e.metaKey)&&e.key==="Enter"}disposeInput(){this.disposeIndent?.()}}});var vb,Uz=E(()=>{Ds();uo();vb=class r extends ar{supportsPeek(){return!1}static Prompt(e,t,n,i,o,s){return new r(e,t,n,i,void 0,o,s).waitForClose}static PromptWithContext(e,t,n,i,o,s,a){return new r(e,t,n,i,o,s,a).waitForClose}createInputField(e,t,n){let i=super.createInputField(e,t,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(e){return this.options?.numeric?e===""&&this.isOptionalPrompt?"":Go(e,this.options.numeric):e}}});var p0,yb,Hz=E(()=>{Ds();uo();p0={min:0,max:100,step:1},yb=class r extends ar{supportsPeek(){return!1}static Prompt(e,t,n,i,o,s){return new r(e,t,n,i,void 0,o,s).waitForClose}static PromptWithContext(e,t,n,i,o,s,a){return new r(e,t,n,i,o,s,a).waitForClose}createInputField(e,t,n){let i=this.options?.slider??p0,o=this.isOptionalPrompt&&!n,s=Ff(n,i);this.sliderEl=e.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(e,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 e=this.numberEl.value;if(e===""&&this.isOptionalPrompt){this.onInputChanged("");return}let t=Go(e,this.options?.slider??p0);t!==""&&(this.sliderEl.value=t),this.onInputChanged(e)}transformInputOnSubmit(e){return e===""&&this.isOptionalPrompt?"":Ff(e,this.options?.slider??p0)}}});var Qd,f0=E(()=>{d0();Ds();Uz();Hz();_s();Qd=class{factory(e){return e==="multiline"?cu:e==="number"?vb:e==="slider"?yb:on().settings.inputPrompt==="multi-line"?cu:ar}}});function zz(r){return r.normalize("NFKD").toLowerCase()}var pie,Xd,m0=E(()=>{pie=0;Xd=class{constructor(e,t){this.options=t;this.instanceId=++pie;this.indexedItems=[];this.renderedRows=[];this.query="";this.rootEl=e.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:t.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}if(i.key==="ArrowUp"){i.preventDefault(),this.renderedRows.at(-1)?.input.focus();return}i.key==="Escape"&&this.query&&(i.preventDefault(),i.stopPropagation(),this.query="",this.searchInputEl.value="",this.renderList())}),this.setItems(t.items)}setItems(e){this.indexedItems=e.map((t,n)=>({item:t,index:n,searchableText:zz(`${t.label} ${t.searchText??""}`)})),this.searchInputEl.disabled=e.length===0,this.renderList()}focusSearchOnOpen(){document.body.classList.contains("is-mobile")||this.searchInputEl.focus()}refreshSelection(){for(let{item:e,input:t}of this.renderedRows)t.checked=this.options.isSelected(e),t.closest("label")?.classList.toggle("is-selected",t.checked);this.updateSummary()}getMatchingItems(){let e=zz(this.query.trim()).split(/\s+/).filter(Boolean);return e.length===0?this.indexedItems:this.indexedItems.filter(({searchableText:t})=>e.every(n=>t.includes(n)))}getVisibleItems(e){if(e.length<=200)return e;let t=[],n=[];for(let i of e)(this.options.isSelected(i.item)?t:n).push(i);return[...t,...n].slice(0,200)}renderList(){this.listEl.replaceChildren(),this.renderedRows=[];let e=this.getMatchingItems(),t=this.getVisibleItems(e);if(t.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 t)this.renderRow(n);if(e.length>t.length){let n=this.listEl.createDiv({cls:"qa-searchable-multi-select__limit"});n.setAttribute("role","status"),n.textContent=`Showing ${t.length} of ${e.length} options. Refine your search to see the rest.`}this.updateSummary(e.length)}renderRow(e){let{item:t,index:n}=e,i=this.listEl.createEl("label",{cls:"qa-searchable-multi-select__option"});i.createSpan({cls:"qa-searchable-multi-select__option-label",text:t.label});let o=i.createEl("input",{type:"checkbox"});o.name=`qa-multi-select-${this.instanceId}`,o.id=`qa-multi-select-${this.instanceId}-${n}`,o.checked=this.options.isSelected(t),i.htmlFor=o.id,i.classList.toggle("is-selected",o.checked),o.addEventListener("change",()=>{this.options.onToggle(t,o.checked),this.refreshSelection()}),o.addEventListener("keydown",s=>{this.handleOptionKeydown(s,o)}),this.renderedRows.push({item:t,input:o})}handleOptionKeydown(e,t){let n=this.renderedRows.findIndex(i=>i.input===t);if(e.key==="ArrowDown"){e.preventDefault(),this.renderedRows[n+1]?.input.focus();return}if(e.key==="ArrowUp"){e.preventDefault(),n===0?this.searchInputEl.focus():this.renderedRows[n-1]?.input.focus();return}if(e.key==="Home"){e.preventDefault(),this.renderedRows[0]?.input.focus();return}if(e.key==="End"){e.preventDefault(),this.renderedRows.at(-1)?.input.focus();return}if(e.key==="Enter"||e.key===" "){e.preventDefault(),t.checked=!t.checked,t.dispatchEvent(new Event("change",{bubbles:!0}));return}e.key==="/"&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&(e.preventDefault(),this.searchInputEl.focus())}updateSummary(e=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()){this.summaryEl.textContent=`${n} \xB7 ${this.indexedItems.length} options`;return}this.summaryEl.textContent=`${n} \xB7 ${e} matches`}}});var uu,du,h0=E(()=>{uu=require("obsidian");rn();ur();m0();du=class r extends uu.Modal{constructor(t,n,i,o={}){super(t);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(t,n,i,o={}){return new r(t,n,i,o).waitForClose}selectValue(t){!this.items.includes(t)&&!this.customValues.includes(t)&&this.customValues.push(t),this.selected.add(t)}seedPreselection(t){if(t?.length)for(let n of t){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:t}=this;t.empty();let n=t.createDiv({cls:"qa-multi-list"});this.picker=new Xd(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 uu.Setting(t).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 uu.Setting(t);i.settingEl.addClass("qa-multi-actions"),i.addButton(o=>o.setButtonText("Done").setCta().onClick(()=>this.submit())),i.addButton(o=>o.setButtonText("Cancel").onClick(()=>this.close())),this.opts.skippable&&i.addButton(o=>o.setButtonText("Skip").setTooltip("Leave empty").onClick(()=>{this.skipped=!0,this.didSubmit=!0,this.close()}))}getSearchableItems(){return[...this.items.map((t,n)=>({key:t,value:t,label:kn(this.displayItems[n]??t),searchText:t})),...this.customValues.map(t=>({key:t,value:t,label:t}))]}commitDraft(){let t=this.draft.trim();return t?(this.items.includes(t)||this.customValues.includes(t))&&this.selected.has(t)?(new uu.Notice(`"${t}" is already added.`),!1):(this.selectValue(t),this.draft="",this.render(),this.focusCustomInput(),!0):(new uu.Notice("Enter a value to add."),!1)}focusCustomInput(){this.contentEl.querySelector(".qa-multi-custom-input")?.focus()}submit(){if(this.opts.allowCustomValue&&this.draft.trim()){let t=this.draft.trim();this.selectValue(t),this.draft=""}this.didSubmit=!0,this.close()}collectResult(){return[...this.items,...this.customValues].filter(t=>this.selected.has(t))}onClose(){super.onClose(),this.didSubmit?this.resolvePromise(this.skipped?[]:this.collectResult()):this.rejectPromise(Rr())}}});var y0,pu,fie,mie,hie,jz,g0,bb,v0,Wz,pk,b0=E(()=>{y0=require("obsidian"),pu=r=>r.toString().padStart(2,"0"),fie=r=>{if(typeof r=="number"&&r>=0&&r<=6)return r;let t=window.moment?.localeData?.()?.firstDayOfWeek?.();return typeof t=="number"&&t>=0&&t<=6?t:0},mie=r=>{let e=new Intl.DateTimeFormat(void 0,{weekday:"short"}),t=new Date(2021,7,1),n=Array.from({length:7},(i,o)=>{let s=new Date(t.getFullYear(),t.getMonth(),t.getDate()+o);return e.format(s)});return n.slice(r).concat(n.slice(0,r))},hie=(r,e)=>new Intl.DateTimeFormat(void 0,{month:"long",year:"numeric"}).format(new Date(r,e,1)),jz=(r,e,t)=>`${r}-${pu(e+1)}-${pu(t)}`,g0=r=>jz(r.getFullYear(),r.getMonth(),r.getDate()),bb=r=>{if(!r)return null;let e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);if(e){let[,n,i,o]=e;return new Date(Number.parseInt(n,10),Number.parseInt(i,10)-1,Number.parseInt(o,10))}let t=new Date(r);return Number.isNaN(t.getTime())?null:t},v0=(r,e,t,n)=>{let i=jz(r,e,t);return n?`${i}T${pu(n.hour)}:${pu(n.minute)}:00`:i},Wz=r=>{if(!r)return null;let e=/[T ](\d{2}):(\d{2})/.exec(r);if(!e)return null;let t=Number.parseInt(e[1],10),n=Number.parseInt(e[2],10);return Number.isNaN(t)||Number.isNaN(n)||t<0||t>23||n<0||n>59?null:{hour:t,minute:n}},pk=r=>{let e=fie(r.weekStartsOn),t=mie(e),n=bb(r.initialIso)??new Date,i=n.getFullYear(),o=n.getMonth(),s=r.initialIso,a=r.withTime===!0,l=a?Wz(r.initialIso)??{hour:0,minute:0}:null,c=r.container.createDiv({cls:"qa-date-picker"}),u=c.createDiv({cls:"qa-date-picker__header"}),d=u.createEl("button",{cls:"qa-date-picker__nav clickable-icon"});(0,y0.setIcon)(d,"chevron-left"),d.type="button",d.setAttr("aria-label","Previous month");let p=u.createDiv({cls:"qa-date-picker__label"}),f=u.createEl("button",{cls:"qa-date-picker__nav clickable-icon"});(0,y0.setIcon)(f,"chevron-right"),f.type="button",f.setAttr("aria-label","Next month");let m=c.createDiv({cls:"qa-date-picker__weekdays"});t.forEach(A=>{let D=m.createDiv({cls:"qa-date-picker__weekday"});D.textContent=A});let g=c.createDiv({cls:"qa-date-picker__grid"}),v=c.createDiv({cls:"qa-date-picker__actions"}),y=v.createEl("button",{cls:"qa-date-picker__action",text:"Today"});y.type="button";let b=v.createEl("button",{cls:"qa-date-picker__action",text:"Clear"});b.type="button";let x;if(a){let A=c.createDiv({cls:"qa-date-picker__time"});A.createEl("label",{cls:"qa-date-picker__time-label",text:"Time"}),x=A.createEl("input",{cls:"qa-date-picker__time-input"}),x.type="time",l&&(x.value=`${pu(l.hour)}:${pu(l.minute)}`)}let w=A=>{o+=A,o>11?(o=0,i+=1):o<0&&(o=11,i-=1),S()},T=(A,D)=>{s=A,r.onSelect(A,D),S()},C=A=>{s=void 0,r.onSelect(null,A),S()};d.addEventListener("click",()=>w(-1)),f.addEventListener("click",()=>w(1)),y.addEventListener("click",()=>{let A=new Date,D=v0(A.getFullYear(),A.getMonth(),A.getDate(),l);i=A.getFullYear(),o=A.getMonth(),T(D,"action")}),b.addEventListener("click",()=>C("action")),x&&x.addEventListener("change",()=>{if(x.value.trim()==="")l={hour:0,minute:0};else{let[A,D]=x.value.split(":").map(P=>Number.parseInt(P,10));if(Number.isNaN(A)||Number.isNaN(D))return;l={hour:A,minute:D}}if(s){let A=bb(s);A&&T(v0(A.getFullYear(),A.getMonth(),A.getDate(),l),"picker")}});let S=()=>{p.textContent=hie(i,o),g.empty();let D=(new Date(i,o,1).getDay()-e+7)%7,P=new Date(i,o,1-D),U=g0(new Date),K=s?bb(s):null,W=K?g0(K):void 0,ee=new Intl.DateTimeFormat(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric"});for(let me=0;me<42;me+=1){let O=new Date(P);O.setDate(P.getDate()+me);let H=g0(O),ce=O.getMonth()!==o,te=H===U,z=W&&H===W,G=g.createEl("button",{cls:"qa-date-picker__day",text:String(O.getDate())});G.type="button",G.setAttr("aria-label",ee.format(O)),ce&&G.addClass("is-outside"),te&&G.addClass("is-today"),z&&(G.addClass("is-selected"),G.setAttr("aria-pressed","true")),G.addEventListener("click",()=>{let ie=v0(O.getFullYear(),O.getMonth(),O.getDate(),l);T(ie,"picker")})}};return S(),{setSelectedIso:(A,{updateView:D}={})=>{if(s=A,A&&D!==!1){let P=bb(A);P&&(i=P.getFullYear(),o=P.getMonth())}if(a&&A){let P=Wz(A);P&&(l=P,x&&(x.value=`${pu(P.hour)}:${pu(P.minute)}`))}S()},setViewFromIso:A=>{let D=bb(A);D&&(i=D.getFullYear(),o=D.getMonth(),S())},destroy:()=>{c.remove()}}}});function fu(r,e,t=Qo,n){if(!r||!r.trim())return{isValid:!1,error:"Empty input"};try{let i=n??X.getState().dateAliases,o=kg(r,i),s=t.parseDate(o);if(s?.moment?.isValid()){let a=s.moment.toISOString(),l=e?s.moment.format(e):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 Us(r,e){if(!window.moment)return null;try{let t=window.moment(r);if(t.isValid())return t.format(e)}catch{}return null}var Zd=E(()=>{Ld();dt();td()});var rh,th,Rl,fk=E(()=>{rh=require("obsidian");Ds();b0();Zd();dt();td();th=class th extends ar{constructor(t,n,i,o,s,a,l){super(t,n,i,o??"",void 0,void 0,a);this.isOpen=!0;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.updatePreviewDebounced=(0,rh.debounce)(this.updatePreview.bind(this),250,!0),this.updatePreview()}supportsPeek(){return!1}static Prompt(t,n,i,o,s,a,l){return new th(t,n,i,o,s,a,l).waitForClose}createInputField(t,n,i){t.addClass("qa-date-input");let o=new rh.TextComponent(t);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=t.createDiv({cls:"qa-date-picker-container"}),this.createPreviewElement(t),o}mountDatePicker(){this.datePicker=pk({container:this.pickerHostEl,initialIso:this.selectedIso,withTime:this.withTime,onSelect:t=>{t?this.applyPickerSelection(t):this.clearPickerSelection()}})}createPreviewElement(t){let n=t.createDiv("vdate-preview-container");n.createDiv({text:"Preview:",cls:"vdate-preview-label"}),this.previewEl=n.createDiv({cls:"vdate-preview-text"}),this.previewEl.textContent=th.PREVIEW_PLACEHOLDER;let i=Sg(X.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=aC(X.getState().dateAliases)}}updatePreview(){if(!this.isOpen)return;let t=this.currentInput.trim();if(!t&&this.defaultValue&&!this.isOptionalPrompt){this.renderPreviewFromInput(this.defaultValue);return}if(!t){this.selectedIso=void 0,this.lastPickerDisplayValue=void 0,this.syncPickerSelection(),this.setPreviewText(this.isOptionalPrompt?"Will be left empty":th.PREVIEW_PLACEHOLDER,!1);return}if(t.startsWith("@date:")){let n=t.slice(6).trim();if(n){this.selectedIso=n,this.lastPickerDisplayValue=void 0,this.syncPickerSelection(n),this.renderPreviewFromIso(n);return}}if(this.selectedIso&&this.lastPickerDisplayValue&&t===this.lastPickerDisplayValue){this.syncPickerSelection(this.selectedIso,!1),this.renderPreviewFromIso(this.selectedIso);return}this.renderPreviewFromInput(t)}formatIsoForInput(t){let n=Us(t,this.dateFormat);return n||(t.length>=10?t.slice(0,10):t)}syncPickerSelection(t,n=!0){this.datePicker?.setSelectedIso(t,{updateView:n})}applyPickerSelection(t){let n=this.formatIsoForInput(t);this.selectedIso=t,this.lastPickerDisplayValue=n,this.inputComponent?.inputEl&&(this.inputComponent.inputEl.value=n),this.onInputChanged(n),this.currentInput=n,this.syncPickerSelection(t),this.renderPreviewFromIso(t)}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(t){this.setPreviewText(this.formatIsoForInput(t),!1)}renderPreviewFromInput(t){let n=fu(t,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(t,n){this.previewEl.textContent=t,this.previewEl.toggleClass("is-error",n)}onOpen(){super.onOpen()}transformInputOnSubmit(t){let n=t.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=fu(this.defaultValue,this.dateFormat);if(i.isValid&&i.isoString)return`@date:${i.isoString}`}if(n){let i=fu(n,this.dateFormat);if(i.isValid&&i.isoString)return`@date:${i.isoString}`;new rh.Notice(`QuickAdd: "${n}" could not be parsed as a date; using it as-is.`)}return t}onClose(){this.isOpen=!1,this.updatePreviewDebounced.cancel(),!this.input.trim()&&this.defaultValue&&!this.isOptionalPrompt&&(this.input=this.defaultValue),super.onClose()}};th.PREVIEW_PLACEHOLDER="Preview will appear here";Rl=th});async function Gz(r,e,t){let n=r.executor?.promptProvider;if(n)return t?.type==="VDATE"?await n.datePrompt(e??t.label??"Enter date",{defaultValue:t.defaultValue,dateFormat:t.dateFormat??"YYYY-MM-DD",withTime:t.withTime}):t?.inputTypeOverride==="checkbox"?String(await n.suggester(["true","false"],["true","false"],t.description??e??t.label??"Choose value",!1)):await n.inputPrompt(e??t?.label??"Enter value",t?.placeholder,t?.defaultValue);r.assertInteractivePrompt(e?`{{VALUE:${e}}}`:"a template variable");try{let i=e??t?.label??"Enter value",o=Ex(r.scope),s=kf(r.runContext,i,{showDestination:o}),a=kf(r.runContext,i,{elide:!1,showDestination:o});return t?.type==="VDATE"?await Rl.Prompt(r.app,e??t.label??"Enter date",t.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')",t.defaultValue,t.dateFormat??"YYYY-MM-DD",{optional:t.optional,contextLine:s,contextLineFull:a,draftScopeId:r.runContext?.draftScopeId},t.withTime):t?.inputTypeOverride==="checkbox"?await Xt.Suggest(r.app,["true","false"],["true","false"],t.description??e??t.label??"Choose value",void 0,t.optional?{skippable:!0}:void 0):await new Qd().factory(t?.inputTypeOverride).Prompt(r.app,i,t?.placeholder??(t?.defaultValue?t.defaultValue:void 0),t?.defaultValue,t?.description,r.buildInputPromptOptions(t,s,a))}catch(i){throw ot(i)?new at("Input cancelled by user"):i}}async function Yz(r,e,t=!1,n){let i=r.executor?.promptProvider;if(i)return String(await i.suggester(n?.displayValues??e,e,n?.placeholder,t));r.assertInteractivePrompt(n?.variableKey?`{{VALUE:${n.variableKey}}}`:"a value choice");try{let o=n?.displayValues??e;return t?await Mr.Suggest(r.app,o,e,{...n?.placeholder?{placeholder:n.placeholder}:{},...n?.optional?{skippable:!0}:{}}):await Xt.Suggest(r.app,o,e,n?.placeholder,void 0,n?.optional?{skippable:!0}:void 0)}catch(o){throw ot(o)?new at("Input cancelled by user"):o}}async function Kz(r,e,t=!1,n){let i=n?.displayValues??e,o=r.executor?.promptProvider;if(o)return await o.suggesterMulti(i,e,{placeholder:n?.placeholder,allowCustomInput:t});r.assertInteractivePrompt(n?.variableKey?`{{VALUE:${n.variableKey}}}`:"a multi-select value");try{return await du.Suggest(r.app,i,e,{...n?.placeholder?{placeholder:n.placeholder}:{},allowCustomValue:t,...n?.optional?{skippable:!0}:{}})}catch(s){throw ot(s)?new at("Input cancelled by user"):s}}var Qz=E(()=>{Sf();f0();Ol();Zo();h0();fk();ur();xt()});var A3=R4(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});require("obsidian");var Ll=class extends Error{},A0=class extends Ll{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},I0=class extends Ll{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},D0=class extends Ll{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},tp=class extends Ll{},xk=class extends Ll{constructor(e){super(`Invalid unit ${e}`)}},zi=class extends Ll{},Ea=class extends Ll{constructor(){super("Zone is an abstract class")}},_e="numeric",js="short",bo="long",Ek={year:_e,month:_e,day:_e},AW={year:_e,month:js,day:_e},gie={year:_e,month:js,day:_e,weekday:js},IW={year:_e,month:bo,day:_e},DW={year:_e,month:bo,day:_e,weekday:bo},FW={hour:_e,minute:_e},PW={hour:_e,minute:_e,second:_e},MW={hour:_e,minute:_e,second:_e,timeZoneName:js},$W={hour:_e,minute:_e,second:_e,timeZoneName:bo},OW={hour:_e,minute:_e,hourCycle:"h23"},RW={hour:_e,minute:_e,second:_e,hourCycle:"h23"},NW={hour:_e,minute:_e,second:_e,hourCycle:"h23",timeZoneName:js},LW={hour:_e,minute:_e,second:_e,hourCycle:"h23",timeZoneName:bo},VW={year:_e,month:_e,day:_e,hour:_e,minute:_e},BW={year:_e,month:_e,day:_e,hour:_e,minute:_e,second:_e},qW={year:_e,month:js,day:_e,hour:_e,minute:_e},UW={year:_e,month:js,day:_e,hour:_e,minute:_e,second:_e},vie={year:_e,month:js,day:_e,weekday:js,hour:_e,minute:_e},HW={year:_e,month:bo,day:_e,hour:_e,minute:_e,timeZoneName:js},zW={year:_e,month:bo,day:_e,hour:_e,minute:_e,second:_e,timeZoneName:js},WW={year:_e,month:bo,day:_e,weekday:bo,hour:_e,minute:_e,timeZoneName:bo},jW={year:_e,month:bo,day:_e,weekday:bo,hour:_e,minute:_e,second:_e,timeZoneName:bo},ip=class{get type(){throw new Ea}get name(){throw new Ea}get ianaName(){return this.name}get isUniversal(){throw new Ea}offsetName(e,t){throw new Ea}formatOffset(e,t){throw new Ea}offset(e){throw new Ea}equals(e){throw new Ea}get isValid(){throw new Ea}},w0=null,Tk=class r extends ip{static get instance(){return w0===null&&(w0=new r),w0}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return YW(e,t,n)}formatOffset(e,t){return kb(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}},wk={};function yie(r){return wk[r]||(wk[r]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:r,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),wk[r]}var bie={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function wie(r,e){let t=r.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(t),[,i,o,s,a,l,c,u]=n;return[s,i,o,a,l,c,u]}function Cie(r,e){let t=r.formatToParts(e),n=[];for(let i=0;i<t.length;i++){let{type:o,value:s}=t[i],a=bie[o];o==="era"?n[a]=s:wt(a)||(n[a]=parseInt(s,10))}return n}var mk={},vu=class r extends ip{static create(e){return mk[e]||(mk[e]=new r(e)),mk[e]}static resetCache(){mk={},wk={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=r.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return YW(e,t,n,this.name)}formatOffset(e,t){return kb(this.offset(e),t)}offset(e){let t=new Date(e);if(isNaN(t))return NaN;let n=yie(this.name),[i,o,s,a,l,c,u]=n.formatToParts?Cie(n,t):wie(n,t);a==="BC"&&(i=-Math.abs(i)+1);let p=Mk({year:i,month:o,day:s,hour:l===24?0:l,minute:c,second:u,millisecond:0}),f=+t,m=f%1e3;return f-=m>=0?m:1e3+m,(p-f)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}},Xz={};function xie(r,e={}){let t=JSON.stringify([r,e]),n=Xz[t];return n||(n=new Intl.ListFormat(r,e),Xz[t]=n),n}var F0={};function P0(r,e={}){let t=JSON.stringify([r,e]),n=F0[t];return n||(n=new Intl.DateTimeFormat(r,e),F0[t]=n),n}var M0={};function Eie(r,e={}){let t=JSON.stringify([r,e]),n=M0[t];return n||(n=new Intl.NumberFormat(r,e),M0[t]=n),n}var $0={};function Tie(r,e={}){let{base:t,...n}=e,i=JSON.stringify([r,n]),o=$0[i];return o||(o=new Intl.RelativeTimeFormat(r,e),$0[i]=o),o}var Eb=null;function kie(){return Eb||(Eb=new Intl.DateTimeFormat().resolvedOptions().locale,Eb)}function Sie(r){let e=r.indexOf("-x-");e!==-1&&(r=r.substring(0,e));let t=r.indexOf("-u-");if(t===-1)return[r];{let n,i;try{n=P0(r).resolvedOptions(),i=r}catch{let l=r.substring(0,t);n=P0(l).resolvedOptions(),i=l}let{numberingSystem:o,calendar:s}=n;return[i,o,s]}}function _ie(r,e,t){return(t||e)&&(r.includes("-u-")||(r+="-u"),t&&(r+=`-ca-${t}`),e&&(r+=`-nu-${e}`)),r}function Aie(r){let e=[];for(let t=1;t<=12;t++){let n=pt.utc(2009,t,1);e.push(r(n))}return e}function Iie(r){let e=[];for(let t=1;t<=7;t++){let n=pt.utc(2016,11,13+t);e.push(r(n))}return e}function hk(r,e,t,n){let i=r.listingMode();return i==="error"?null:i==="en"?t(e):n(e)}function Die(r){return r.numberingSystem&&r.numberingSystem!=="latn"?!1:r.numberingSystem==="latn"||!r.locale||r.locale.startsWith("en")||new Intl.DateTimeFormat(r.intl).resolvedOptions().numberingSystem==="latn"}var O0=class{constructor(e,t,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:i,floor:o,...s}=n;if(!t||Object.keys(s).length>0){let a={useGrouping:!1,...n};n.padTo>0&&(a.minimumIntegerDigits=n.padTo),this.inf=Eie(e,a)}}format(e){if(this.inf){let t=this.floor?Math.floor(e):e;return this.inf.format(t)}else{let t=this.floor?Math.floor(e):K0(e,3);return Ur(t,this.padTo)}}},R0=class{constructor(e,t,n){this.opts=n,this.originalZone=void 0;let i;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let s=-1*(e.offset/60),a=s>=0?`Etc/GMT+${s}`:`Etc/GMT${s}`;e.offset!==0&&vu.create(a).valid?(i=a,this.dt=e):(i="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,i=e.zone.name):(i="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let o={...this.opts};o.timeZone=o.timeZone||i,this.dtf=P0(t,o)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(t=>{if(t.type==="timeZoneName"){let n=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...t,value:n}}else return t}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},N0=class{constructor(e,t,n){this.opts={style:"long",...n},!t&&GW()&&(this.rtf=Tie(e,n))}format(e,t){return this.rtf?this.rtf.format(e,t):jie(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}},_r=class r{static fromOpts(e){return r.create(e.locale,e.numberingSystem,e.outputCalendar,e.defaultToEN)}static create(e,t,n,i=!1){let o=e||Sr.defaultLocale,s=o||(i?"en-US":kie()),a=t||Sr.defaultNumberingSystem,l=n||Sr.defaultOutputCalendar;return new r(s,a,l,o)}static resetCache(){Eb=null,F0={},M0={},$0={}}static fromObject({locale:e,numberingSystem:t,outputCalendar:n}={}){return r.create(e,t,n)}constructor(e,t,n,i){let[o,s,a]=Sie(e);this.locale=o,this.numberingSystem=t||s||null,this.outputCalendar=n||a||null,this.intl=_ie(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=Die(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&t?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:r.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,t=!1){return hk(this,e,XW,()=>{let n=t?{month:e,day:"numeric"}:{month:e},i=t?"format":"standalone";return this.monthsCache[i][e]||(this.monthsCache[i][e]=Aie(o=>this.extract(o,n,"month"))),this.monthsCache[i][e]})}weekdays(e,t=!1){return hk(this,e,e3,()=>{let n=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},i=t?"format":"standalone";return this.weekdaysCache[i][e]||(this.weekdaysCache[i][e]=Iie(o=>this.extract(o,n,"weekday"))),this.weekdaysCache[i][e]})}meridiems(){return hk(this,void 0,()=>t3,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[pt.utc(2016,11,13,9),pt.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return hk(this,e,r3,()=>{let t={era:e};return this.eraCache[e]||(this.eraCache[e]=[pt.utc(-40,1,1),pt.utc(2017,1,1)].map(n=>this.extract(n,t,"era"))),this.eraCache[e]})}extract(e,t,n){let i=this.dtFormatter(e,t),o=i.formatToParts(),s=o.find(a=>a.type.toLowerCase()===n);return s?s.value:null}numberFormatter(e={}){return new O0(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new R0(e,this.intl,t)}relFormatter(e={}){return new N0(this.intl,this.isEnglish(),e)}listFormatter(e={}){return xie(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}},C0=null,rs=class r extends ip{static get utcInstance(){return C0===null&&(C0=new r(0)),C0}static instance(e){return e===0?r.utcInstance:new r(e)}static parseSpecifier(e){if(e){let t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new r($k(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${kb(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${kb(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return kb(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}},L0=class extends ip{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function gu(r,e){if(wt(r)||r===null)return e;if(r instanceof ip)return r;if(Fie(r)){let t=r.toLowerCase();return t==="default"?e:t==="local"||t==="system"?Tk.instance:t==="utc"||t==="gmt"?rs.utcInstance:rs.parseSpecifier(t)||vu.create(r)}else return np(r)?rs.instance(r):typeof r=="object"&&"offset"in r&&typeof r.offset=="function"?r:new L0(r)}var Zz=()=>Date.now(),Jz="system",eW=null,tW=null,rW=null,nW=60,iW,Sr=class{static get now(){return Zz}static set now(e){Zz=e}static set defaultZone(e){Jz=e}static get defaultZone(){return gu(Jz,Tk.instance)}static get defaultLocale(){return eW}static set defaultLocale(e){eW=e}static get defaultNumberingSystem(){return tW}static set defaultNumberingSystem(e){tW=e}static get defaultOutputCalendar(){return rW}static set defaultOutputCalendar(e){rW=e}static get twoDigitCutoffYear(){return nW}static set twoDigitCutoffYear(e){nW=e%100}static get throwOnInvalid(){return iW}static set throwOnInvalid(e){iW=e}static resetCaches(){_r.resetCache(),vu.resetCache()}};function wt(r){return typeof r>"u"}function np(r){return typeof r=="number"}function Pk(r){return typeof r=="number"&&r%1===0}function Fie(r){return typeof r=="string"}function Pie(r){return Object.prototype.toString.call(r)==="[object Date]"}function GW(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Mie(r){return Array.isArray(r)?r:[r]}function oW(r,e,t){if(r.length!==0)return r.reduce((n,i)=>{let o=[e(i),i];return n&&t(n[0],o[0])===n[0]?n:o},null)[1]}function $ie(r,e){return e.reduce((t,n)=>(t[n]=r[n],t),{})}function lh(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Nl(r,e,t){return Pk(r)&&r>=e&&r<=t}function Oie(r,e){return r-e*Math.floor(r/e)}function Ur(r,e=2){let t=r<0,n;return t?n="-"+(""+-r).padStart(e,"0"):n=(""+r).padStart(e,"0"),n}function hu(r){if(!(wt(r)||r===null||r===""))return parseInt(r,10)}function Jd(r){if(!(wt(r)||r===null||r===""))return parseFloat(r)}function Y0(r){if(!(wt(r)||r===null||r==="")){let e=parseFloat("0."+r)*1e3;return Math.floor(e)}}function K0(r,e,t=!1){let n=10**e;return(t?Math.trunc:Math.round)(r*n)/n}function Ab(r){return r%4===0&&(r%100!==0||r%400===0)}function Tb(r){return Ab(r)?366:365}function kk(r,e){let t=Oie(e-1,12)+1,n=r+(e-t)/12;return t===2?Ab(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function Mk(r){let e=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second,r.millisecond);return r.year<100&&r.year>=0&&(e=new Date(e),e.setUTCFullYear(r.year,r.month-1,r.day)),+e}function Sk(r){let e=(r+Math.floor(r/4)-Math.floor(r/100)+Math.floor(r/400))%7,t=r-1,n=(t+Math.floor(t/4)-Math.floor(t/100)+Math.floor(t/400))%7;return e===4||n===3?53:52}function V0(r){return r>99?r:r>Sr.twoDigitCutoffYear?1900+r:2e3+r}function YW(r,e,t,n=null){let i=new Date(r),o={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(o.timeZone=n);let s={timeZoneName:e,...o},a=new Intl.DateTimeFormat(t,s).formatToParts(i).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function $k(r,e){let t=parseInt(r,10);Number.isNaN(t)&&(t=0);let n=parseInt(e,10)||0,i=t<0||Object.is(t,-0)?-n:n;return t*60+i}function KW(r){let e=Number(r);if(typeof r=="boolean"||r===""||Number.isNaN(e))throw new zi(`Invalid unit value ${r}`);return e}function _k(r,e){let t={};for(let n in r)if(lh(r,n)){let i=r[n];if(i==null)continue;t[e(n)]=KW(i)}return t}function kb(r,e){let t=Math.trunc(Math.abs(r/60)),n=Math.trunc(Math.abs(r%60)),i=r>=0?"+":"-";switch(e){case"short":return`${i}${Ur(t,2)}:${Ur(n,2)}`;case"narrow":return`${i}${t}${n>0?`:${n}`:""}`;case"techie":return`${i}${Ur(t,2)}${Ur(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Ok(r){return $ie(r,["hour","minute","second","millisecond"])}var Rie=["January","February","March","April","May","June","July","August","September","October","November","December"],QW=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Nie=["J","F","M","A","M","J","J","A","S","O","N","D"];function XW(r){switch(r){case"narrow":return[...Nie];case"short":return[...QW];case"long":return[...Rie];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var ZW=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],JW=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Lie=["M","T","W","T","F","S","S"];function e3(r){switch(r){case"narrow":return[...Lie];case"short":return[...JW];case"long":return[...ZW];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var t3=["AM","PM"],Vie=["Before Christ","Anno Domini"],Bie=["BC","AD"],qie=["B","A"];function r3(r){switch(r){case"narrow":return[...qie];case"short":return[...Bie];case"long":return[...Vie];default:return null}}function Uie(r){return t3[r.hour<12?0:1]}function Hie(r,e){return e3(e)[r.weekday-1]}function zie(r,e){return XW(e)[r.month-1]}function Wie(r,e){return r3(e)[r.year<0?0:1]}function jie(r,e,t="always",n=!1){let i={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},o=["hours","minutes","seconds"].indexOf(r)===-1;if(t==="auto"&&o){let d=r==="days";switch(e){case 1:return d?"tomorrow":`next ${i[r][0]}`;case-1:return d?"yesterday":`last ${i[r][0]}`;case 0:return d?"today":`this ${i[r][0]}`}}let s=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,c=i[r],u=n?l?c[1]:c[2]||c[1]:l?i[r][0]:r;return s?`${a} ${u} ago`:`in ${a} ${u}`}function sW(r,e){let t="";for(let n of r)n.literal?t+=n.val:t+=e(n.val);return t}var Gie={D:Ek,DD:AW,DDD:IW,DDDD:DW,t:FW,tt:PW,ttt:MW,tttt:$W,T:OW,TT:RW,TTT:NW,TTTT:LW,f:VW,ff:qW,fff:HW,ffff:WW,F:BW,FF:UW,FFF:zW,FFFF:jW},vo=class r{static create(e,t={}){return new r(e,t)}static parseFormat(e){let t=null,n="",i=!1,o=[];for(let s=0;s<e.length;s++){let a=e.charAt(s);a==="'"?(n.length>0&&o.push({literal:i||/^\s+$/.test(n),val:n}),t=null,n="",i=!i):i||a===t?n+=a:(n.length>0&&o.push({literal:/^\s+$/.test(n),val:n}),n=a,t=a)}return n.length>0&&o.push({literal:i||/^\s+$/.test(n),val:n}),o}static macroTokenToFormatOpts(e){return Gie[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...t}).format()}dtFormatter(e,t={}){return this.loc.dtFormatter(e,{...this.opts,...t})}formatDateTime(e,t){return this.dtFormatter(e,t).format()}formatDateTimeParts(e,t){return this.dtFormatter(e,t).formatToParts()}formatInterval(e,t){return this.dtFormatter(e.start,t).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,t){return this.dtFormatter(e,t).resolvedOptions()}num(e,t=0){if(this.opts.forceSimple)return Ur(e,t);let n={...this.opts};return t>0&&(n.padTo=t),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,t){let n=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",o=(f,m)=>this.loc.extract(e,f,m),s=f=>e.isOffsetFixed&&e.offset===0&&f.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,f.format):"",a=()=>n?Uie(e):o({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(f,m)=>n?zie(e,f):o(m?{month:f}:{month:f,day:"numeric"},"month"),c=(f,m)=>n?Hie(e,f):o(m?{weekday:f}:{weekday:f,month:"long",day:"numeric"},"weekday"),u=f=>{let m=r.macroTokenToFormatOpts(f);return m?this.formatWithSystemDefault(e,m):f},d=f=>n?Wie(e,f):o({era:f},"era"),p=f=>{switch(f){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return s({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return s({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return s({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return i?o({day:"numeric"},"day"):this.num(e.day);case"dd":return i?o({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return c("short",!0);case"cccc":return c("long",!0);case"ccccc":return c("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return c("short",!1);case"EEEE":return c("long",!1);case"EEEEE":return c("narrow",!1);case"L":return i?o({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return i?o({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return i?o({month:"numeric"},"month"):this.num(e.month);case"MM":return i?o({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return i?o({year:"numeric"},"year"):this.num(e.year);case"yy":return i?o({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return i?o({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return i?o({year:"numeric"},"year"):this.num(e.year,6);case"G":return d("short");case"GG":return d("long");case"GGGGG":return d("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return u(f)}};return sW(r.parseFormat(t),p)}formatDurationFromString(e,t){let n=l=>{switch(l[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},i=l=>c=>{let u=n(c);return u?this.num(l.get(u),c.length):c},o=r.parseFormat(t),s=o.reduce((l,{literal:c,val:u})=>c?l:l.concat(u),[]),a=e.shiftTo(...s.map(n).filter(l=>l));return sW(o,i(a))}},yo=class{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}},n3=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function ch(...r){let e=r.reduce((t,n)=>t+n.source,"");return RegExp(`^${e}$`)}function uh(...r){return e=>r.reduce(([t,n,i],o)=>{let[s,a,l]=o(e,i);return[{...t,...s},a||n,l]},[{},null,1]).slice(0,2)}function dh(r,...e){if(r==null)return[null,null];for(let[t,n]of e){let i=t.exec(r);if(i)return n(i)}return[null,null]}function i3(...r){return(e,t)=>{let n={},i;for(i=0;i<r.length;i++)n[r[i]]=hu(e[t+i]);return[n,null,t+i]}}var o3=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,Yie=`(?:${o3.source}?(?:\\[(${n3.source})\\])?)?`,Q0=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,s3=RegExp(`${Q0.source}${Yie}`),X0=RegExp(`(?:T${s3.source})?`),Kie=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Qie=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Xie=/(\d{4})-?(\d{3})/,Zie=i3("weekYear","weekNumber","weekDay"),Jie=i3("year","ordinal"),eoe=/(\d{4})-(\d\d)-(\d\d)/,a3=RegExp(`${Q0.source} ?(?:${o3.source}|(${n3.source}))?`),toe=RegExp(`(?: ${a3.source})?`);function sh(r,e,t){let n=r[e];return wt(n)?t:hu(n)}function roe(r,e){return[{year:sh(r,e),month:sh(r,e+1,1),day:sh(r,e+2,1)},null,e+3]}function ph(r,e){return[{hours:sh(r,e,0),minutes:sh(r,e+1,0),seconds:sh(r,e+2,0),milliseconds:Y0(r[e+3])},null,e+4]}function Ib(r,e){let t=!r[e]&&!r[e+1],n=$k(r[e+1],r[e+2]),i=t?null:rs.instance(n);return[{},i,e+3]}function Db(r,e){let t=r[e]?vu.create(r[e]):null;return[{},t,e+1]}var noe=RegExp(`^T?${Q0.source}$`),ioe=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function ooe(r){let[e,t,n,i,o,s,a,l,c]=r,u=e[0]==="-",d=l&&l[0]==="-",p=(f,m=!1)=>f!==void 0&&(m||f&&u)?-f:f;return[{years:p(Jd(t)),months:p(Jd(n)),weeks:p(Jd(i)),days:p(Jd(o)),hours:p(Jd(s)),minutes:p(Jd(a)),seconds:p(Jd(l),l==="-0"),milliseconds:p(Y0(c),d)}]}var soe={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Z0(r,e,t,n,i,o,s){let a={year:e.length===2?V0(hu(e)):hu(e),month:QW.indexOf(t)+1,day:hu(n),hour:hu(i),minute:hu(o)};return s&&(a.second=hu(s)),r&&(a.weekday=r.length>3?ZW.indexOf(r)+1:JW.indexOf(r)+1),a}var aoe=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function loe(r){let[,e,t,n,i,o,s,a,l,c,u,d]=r,p=Z0(e,i,n,t,o,s,a),f;return l?f=soe[l]:c?f=0:f=$k(u,d),[p,new rs(f)]}function coe(r){return r.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var uoe=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,doe=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,poe=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function aW(r){let[,e,t,n,i,o,s,a]=r;return[Z0(e,i,n,t,o,s,a),rs.utcInstance]}function foe(r){let[,e,t,n,i,o,s,a]=r;return[Z0(e,a,t,n,i,o,s),rs.utcInstance]}var moe=ch(Kie,X0),hoe=ch(Qie,X0),goe=ch(Xie,X0),voe=ch(s3),l3=uh(roe,ph,Ib,Db),yoe=uh(Zie,ph,Ib,Db),boe=uh(Jie,ph,Ib,Db),woe=uh(ph,Ib,Db);function Coe(r){return dh(r,[moe,l3],[hoe,yoe],[goe,boe],[voe,woe])}function xoe(r){return dh(coe(r),[aoe,loe])}function Eoe(r){return dh(r,[uoe,aW],[doe,aW],[poe,foe])}function Toe(r){return dh(r,[ioe,ooe])}var koe=uh(ph);function Soe(r){return dh(r,[noe,koe])}var _oe=ch(eoe,toe),Aoe=ch(a3),Ioe=uh(ph,Ib,Db);function Doe(r){return dh(r,[_oe,l3],[Aoe,Ioe])}var lW="Invalid Duration",c3={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},Foe={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...c3},es=146097/400,nh=146097/4800,Poe={years:{quarters:4,months:12,weeks:es/7,days:es,hours:es*24,minutes:es*24*60,seconds:es*24*60*60,milliseconds:es*24*60*60*1e3},quarters:{months:3,weeks:es/28,days:es/4,hours:es*24/4,minutes:es*24*60/4,seconds:es*24*60*60/4,milliseconds:es*24*60*60*1e3/4},months:{weeks:nh/7,days:nh,hours:nh*24,minutes:nh*24*60,seconds:nh*24*60*60,milliseconds:nh*24*60*60*1e3},...c3},rp=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],Moe=rp.slice(0).reverse();function mu(r,e,t=!1){let n={values:t?e.values:{...r.values,...e.values||{}},loc:r.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||r.conversionAccuracy,matrix:e.matrix||r.matrix};return new je(n)}function u3(r,e){let t=e.milliseconds??0;for(let n of Moe.slice(1))e[n]&&(t+=e[n]*r[n].milliseconds);return t}function cW(r,e){let t=u3(r,e)<0?-1:1;rp.reduceRight((n,i)=>{if(wt(e[i]))return n;if(n){let o=e[n]*t,s=r[i][n],a=Math.floor(o/s);e[i]+=a*t,e[n]-=a*s*t}return i},null),rp.reduce((n,i)=>{if(wt(e[i]))return n;if(n){let o=e[n]%1;e[n]-=o,e[i]+=o*r[n][i]}return i},null)}function $oe(r){let e={};for(let[t,n]of Object.entries(r))n!==0&&(e[t]=n);return e}var je=class r{constructor(e){let t=e.conversionAccuracy==="longterm"||!1,n=t?Poe:Foe;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||_r.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(e,t){return r.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new zi(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new r({values:_k(e,r.normalizeUnit),loc:_r.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(np(e))return r.fromMillis(e);if(r.isDuration(e))return e;if(typeof e=="object")return r.fromObject(e);throw new zi(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){let[n]=Toe(e);return n?r.fromObject(n,t):r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){let[n]=Soe(e);return n?r.fromObject(n,t):r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new zi("need to specify a reason the Duration is invalid");let n=e instanceof yo?e:new yo(e,t);if(Sr.throwOnInvalid)throw new D0(n);return new r({invalid:n})}static normalizeUnit(e){let t={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!t)throw new xk(e);return t}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,t={}){let n={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?vo.create(this.loc,n).formatDurationFromString(this,e):lW}toHuman(e={}){if(!this.isValid)return lW;let t=rp.map(n=>{let i=this.values[n];return wt(i)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(i)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(t)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=K0(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},pt.fromMillis(t,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}toMillis(){return this.isValid?u3(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let t=r.fromDurationLike(e),n={};for(let i of rp)(lh(t.values,i)||lh(this.values,i))&&(n[i]=t.get(i)+this.get(i));return mu(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let t=r.fromDurationLike(e);return this.plus(t.negate())}mapUnits(e){if(!this.isValid)return this;let t={};for(let n of Object.keys(this.values))t[n]=KW(e(this.values[n],n));return mu(this,{values:t},!0)}get(e){return this[r.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let t={...this.values,..._k(e,r.normalizeUnit)};return mu(this,{values:t})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:n,matrix:i}={}){let s={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:i,conversionAccuracy:n};return mu(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return cW(this.matrix,e),mu(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=$oe(this.normalize().shiftToAll().toObject());return mu(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(s=>r.normalizeUnit(s));let t={},n={},i=this.toObject(),o;for(let s of rp)if(e.indexOf(s)>=0){o=s;let a=0;for(let c in n)a+=this.matrix[c][s]*n[c],n[c]=0;np(i[s])&&(a+=i[s]);let l=Math.trunc(a);t[s]=l,n[s]=(a*1e3-l*1e3)/1e3}else np(i[s])&&(n[s]=i[s]);for(let s in n)n[s]!==0&&(t[o]+=s===o?n[s]:n[s]/this.matrix[o][s]);return cW(this.matrix,t),mu(this,{values:t},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return mu(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function t(n,i){return n===void 0||n===0?i===void 0||i===0:n===i}for(let n of rp)if(!t(this.values[n],e.values[n]))return!1;return!0}},ih="Invalid Interval";function Ooe(r,e){return!r||!r.isValid?ah.invalid("missing or invalid start"):!e||!e.isValid?ah.invalid("missing or invalid end"):e<r?ah.invalid("end before start",`The end of an interval must be after its start, but you had start=${r.toISO()} and end=${e.toISO()}`):null}var ah=class r{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,t=null){if(!e)throw new zi("need to specify a reason the Interval is invalid");let n=e instanceof yo?e:new yo(e,t);if(Sr.throwOnInvalid)throw new I0(n);return new r({invalid:n})}static fromDateTimes(e,t){let n=Cb(e),i=Cb(t),o=Ooe(n,i);return o??new r({start:n,end:i})}static after(e,t){let n=je.fromDurationLike(t),i=Cb(e);return r.fromDateTimes(i,i.plus(n))}static before(e,t){let n=je.fromDurationLike(t),i=Cb(e);return r.fromDateTimes(i.minus(n),i)}static fromISO(e,t){let[n,i]=(e||"").split("/",2);if(n&&i){let o,s;try{o=pt.fromISO(n,t),s=o.isValid}catch{s=!1}let a,l;try{a=pt.fromISO(i,t),l=a.isValid}catch{l=!1}if(s&&l)return r.fromDateTimes(o,a);if(s){let c=je.fromISO(i,t);if(c.isValid)return r.after(o,c)}else if(l){let c=je.fromISO(n,t);if(c.isValid)return r.before(a,c)}}return r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds"){if(!this.isValid)return NaN;let t=this.start.startOf(e),n=this.end.startOf(e);return Math.floor(n.diff(t,e).get(e))+(n.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:t}={}){return this.isValid?r.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];let t=e.map(Cb).filter(s=>this.contains(s)).sort(),n=[],{s:i}=this,o=0;for(;i<this.e;){let s=t[o]||this.e,a=+s>+this.e?this.e:s;n.push(r.fromDateTimes(i,a)),i=a,o+=1}return n}splitBy(e){let t=je.fromDurationLike(e);if(!this.isValid||!t.isValid||t.as("milliseconds")===0)return[];let{s:n}=this,i=1,o,s=[];for(;n<this.e;){let a=this.start.plus(t.mapUnits(l=>l*i));o=+a>+this.e?this.e:a,s.push(r.fromDateTimes(n,o)),n=o,i+=1}return s}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let t=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return t>=n?null:r.fromDateTimes(t,n)}union(e){if(!this.isValid)return this;let t=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return r.fromDateTimes(t,n)}static merge(e){let[t,n]=e.sort((i,o)=>i.s-o.s).reduce(([i,o],s)=>o?o.overlaps(s)||o.abutsStart(s)?[i,o.union(s)]:[i.concat([o]),s]:[i,s],[[],null]);return n&&t.push(n),t}static xor(e){let t=null,n=0,i=[],o=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),s=Array.prototype.concat(...o),a=s.sort((l,c)=>l.time-c.time);for(let l of a)n+=l.type==="s"?1:-1,n===1?t=l.time:(t&&+t!=+l.time&&i.push(r.fromDateTimes(t,l.time)),t=null);return r.merge(i)}difference(...e){return r.xor([this].concat(e)).map(t=>this.intersection(t)).filter(t=>t&&!t.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:ih}toLocaleString(e=Ek,t={}){return this.isValid?vo.create(this.s.loc.clone(t),e).formatInterval(this):ih}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:ih}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:ih}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:ih}toFormat(e,{separator:t=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:ih}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):je.invalid(this.invalidReason)}mapEndpoints(e){return r.fromDateTimes(e(this.s),e(this.e))}},oh=class{static hasDST(e=Sr.defaultZone){let t=pt.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return vu.isValidZone(e)}static normalizeZone(e){return gu(e,Sr.defaultZone)}static months(e="long",{locale:t=null,numberingSystem:n=null,locObj:i=null,outputCalendar:o="gregory"}={}){return(i||_r.create(t,n,o)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:n=null,locObj:i=null,outputCalendar:o="gregory"}={}){return(i||_r.create(t,n,o)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:n=null,locObj:i=null}={}){return(i||_r.create(t,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:n=null,locObj:i=null}={}){return(i||_r.create(t,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return _r.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return _r.create(t,null,"gregory").eras(e)}static features(){return{relative:GW()}}};function uW(r,e){let t=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=t(e)-t(r);return Math.floor(je.fromMillis(n).as("days"))}function Roe(r,e,t){let n=[["years",(l,c)=>c.year-l.year],["quarters",(l,c)=>c.quarter-l.quarter+(c.year-l.year)*4],["months",(l,c)=>c.month-l.month+(c.year-l.year)*12],["weeks",(l,c)=>{let u=uW(l,c);return(u-u%7)/7}],["days",uW]],i={},o=r,s,a;for(let[l,c]of n)t.indexOf(l)>=0&&(s=l,i[l]=c(r,e),a=o.plus(i),a>e?(i[l]--,r=o.plus(i),r>e&&(a=r,i[l]--,r=o.plus(i))):r=a);return[r,i,a,s]}function Noe(r,e,t,n){let[i,o,s,a]=Roe(r,e,t),l=e-i,c=t.filter(d=>["hours","minutes","seconds","milliseconds"].indexOf(d)>=0);c.length===0&&(s<e&&(s=i.plus({[a]:1})),s!==i&&(o[a]=(o[a]||0)+l/(s-i)));let u=je.fromObject(o,n);return c.length>0?je.fromMillis(l,n).shiftTo(...c).plus(u):u}var J0={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},dW={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Loe=J0.hanidec.replace(/[\[|\]]/g,"").split("");function Voe(r){let e=parseInt(r,10);if(isNaN(e)){e="";for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);if(r[t].search(J0.hanidec)!==-1)e+=Loe.indexOf(r[t]);else for(let i in dW){let[o,s]=dW[i];n>=o&&n<=s&&(e+=n-o)}}return parseInt(e,10)}else return e}function Hs({numberingSystem:r},e=""){return new RegExp(`${J0[r||"latn"]}${e}`)}var Boe="missing Intl.DateTimeFormat.formatToParts support";function Mt(r,e=t=>t){return{regex:r,deser:([t])=>e(Voe(t))}}var qoe="\xA0",d3=`[ ${qoe}]`,p3=new RegExp(d3,"g");function Uoe(r){return r.replace(/\./g,"\\.?").replace(p3,d3)}function pW(r){return r.replace(/\./g,"").replace(p3," ").toLowerCase()}function zs(r,e){return r===null?null:{regex:RegExp(r.map(Uoe).join("|")),deser:([t])=>r.findIndex(n=>pW(t)===pW(n))+e}}function fW(r,e){return{regex:r,deser:([,t,n])=>$k(t,n),groups:e}}function gk(r){return{regex:r,deser:([e])=>e}}function Hoe(r){return r.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function zoe(r,e){let t=Hs(e),n=Hs(e,"{2}"),i=Hs(e,"{3}"),o=Hs(e,"{4}"),s=Hs(e,"{6}"),a=Hs(e,"{1,2}"),l=Hs(e,"{1,3}"),c=Hs(e,"{1,6}"),u=Hs(e,"{1,9}"),d=Hs(e,"{2,4}"),p=Hs(e,"{4,6}"),f=v=>({regex:RegExp(Hoe(v.val)),deser:([y])=>y,literal:!0}),g=(v=>{if(r.literal)return f(v);switch(v.val){case"G":return zs(e.eras("short"),0);case"GG":return zs(e.eras("long"),0);case"y":return Mt(c);case"yy":return Mt(d,V0);case"yyyy":return Mt(o);case"yyyyy":return Mt(p);case"yyyyyy":return Mt(s);case"M":return Mt(a);case"MM":return Mt(n);case"MMM":return zs(e.months("short",!0),1);case"MMMM":return zs(e.months("long",!0),1);case"L":return Mt(a);case"LL":return Mt(n);case"LLL":return zs(e.months("short",!1),1);case"LLLL":return zs(e.months("long",!1),1);case"d":return Mt(a);case"dd":return Mt(n);case"o":return Mt(l);case"ooo":return Mt(i);case"HH":return Mt(n);case"H":return Mt(a);case"hh":return Mt(n);case"h":return Mt(a);case"mm":return Mt(n);case"m":return Mt(a);case"q":return Mt(a);case"qq":return Mt(n);case"s":return Mt(a);case"ss":return Mt(n);case"S":return Mt(l);case"SSS":return Mt(i);case"u":return gk(u);case"uu":return gk(a);case"uuu":return Mt(t);case"a":return zs(e.meridiems(),0);case"kkkk":return Mt(o);case"kk":return Mt(d,V0);case"W":return Mt(a);case"WW":return Mt(n);case"E":case"c":return Mt(t);case"EEE":return zs(e.weekdays("short",!1),1);case"EEEE":return zs(e.weekdays("long",!1),1);case"ccc":return zs(e.weekdays("short",!0),1);case"cccc":return zs(e.weekdays("long",!0),1);case"Z":case"ZZ":return fW(new RegExp(`([+-]${a.source})(?::(${n.source}))?`),2);case"ZZZ":return fW(new RegExp(`([+-]${a.source})(${n.source})?`),2);case"z":return gk(/[a-z_+-/]{1,256}?/i);case" ":return gk(/[^\S\n\r]/);default:return f(v)}})(r)||{invalidReason:Boe};return g.token=r,g}var Woe={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function joe(r,e,t){let{type:n,value:i}=r;if(n==="literal"){let l=/^\s+$/.test(i);return{literal:!l,val:l?" ":i}}let o=e[n],s=n;n==="hour"&&(e.hour12!=null?s=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?s="hour12":s="hour24":s=t.hour12?"hour12":"hour24");let a=Woe[s];if(typeof a=="object"&&(a=a[o]),a)return{literal:!1,val:a}}function Goe(r){return[`^${r.map(t=>t.regex).reduce((t,n)=>`${t}(${n.source})`,"")}$`,r]}function Yoe(r,e,t){let n=r.match(e);if(n){let i={},o=1;for(let s in t)if(lh(t,s)){let a=t[s],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(i[a.token.val[0]]=a.deser(n.slice(o,o+l))),o+=l}return[n,i]}else return[n,{}]}function Koe(r){let e=o=>{switch(o){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},t=null,n;return wt(r.z)||(t=vu.create(r.z)),wt(r.Z)||(t||(t=new rs(r.Z)),n=r.Z),wt(r.q)||(r.M=(r.q-1)*3+1),wt(r.h)||(r.h<12&&r.a===1?r.h+=12:r.h===12&&r.a===0&&(r.h=0)),r.G===0&&r.y&&(r.y=-r.y),wt(r.u)||(r.S=Y0(r.u)),[Object.keys(r).reduce((o,s)=>{let a=e(s);return a&&(o[a]=r[s]),o},{}),t,n]}var x0=null;function Qoe(){return x0||(x0=pt.fromMillis(1555555555555)),x0}function Xoe(r,e){if(r.literal)return r;let t=vo.macroTokenToFormatOpts(r.val),n=h3(t,e);return n==null||n.includes(void 0)?r:n}function f3(r,e){return Array.prototype.concat(...r.map(t=>Xoe(t,e)))}function m3(r,e,t){let n=f3(vo.parseFormat(t),r),i=n.map(s=>zoe(s,r)),o=i.find(s=>s.invalidReason);if(o)return{input:e,tokens:n,invalidReason:o.invalidReason};{let[s,a]=Goe(i),l=RegExp(s,"i"),[c,u]=Yoe(e,l,a),[d,p,f]=u?Koe(u):[null,null,void 0];if(lh(u,"a")&&lh(u,"H"))throw new tp("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:l,rawMatches:c,matches:u,result:d,zone:p,specificOffset:f}}}function Zoe(r,e,t){let{result:n,zone:i,specificOffset:o,invalidReason:s}=m3(r,e,t);return[n,i,o,s]}function h3(r,e){if(!r)return null;let n=vo.create(e,r).dtFormatter(Qoe()),i=n.formatToParts(),o=n.resolvedOptions();return i.map(s=>joe(s,r,o))}var g3=[0,31,59,90,120,151,181,212,243,273,304,334],v3=[0,31,60,91,121,152,182,213,244,274,305,335];function ts(r,e){return new yo("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${r}, which is invalid`)}function y3(r,e,t){let n=new Date(Date.UTC(r,e-1,t));r<100&&r>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let i=n.getUTCDay();return i===0?7:i}function b3(r,e,t){return t+(Ab(r)?v3:g3)[e-1]}function w3(r,e){let t=Ab(r)?v3:g3,n=t.findIndex(o=>o<e),i=e-t[n];return{month:n+1,day:i}}function B0(r){let{year:e,month:t,day:n}=r,i=b3(e,t,n),o=y3(e,t,n),s=Math.floor((i-o+10)/7),a;return s<1?(a=e-1,s=Sk(a)):s>Sk(e)?(a=e+1,s=1):a=e,{weekYear:a,weekNumber:s,weekday:o,...Ok(r)}}function mW(r){let{weekYear:e,weekNumber:t,weekday:n}=r,i=y3(e,1,4),o=Tb(e),s=t*7+n-i-3,a;s<1?(a=e-1,s+=Tb(a)):s>o?(a=e+1,s-=Tb(e)):a=e;let{month:l,day:c}=w3(a,s);return{year:a,month:l,day:c,...Ok(r)}}function E0(r){let{year:e,month:t,day:n}=r,i=b3(e,t,n);return{year:e,ordinal:i,...Ok(r)}}function hW(r){let{year:e,ordinal:t}=r,{month:n,day:i}=w3(e,t);return{year:e,month:n,day:i,...Ok(r)}}function Joe(r){let e=Pk(r.weekYear),t=Nl(r.weekNumber,1,Sk(r.weekYear)),n=Nl(r.weekday,1,7);return e?t?n?!1:ts("weekday",r.weekday):ts("week",r.week):ts("weekYear",r.weekYear)}function ese(r){let e=Pk(r.year),t=Nl(r.ordinal,1,Tb(r.year));return e?t?!1:ts("ordinal",r.ordinal):ts("year",r.year)}function C3(r){let e=Pk(r.year),t=Nl(r.month,1,12),n=Nl(r.day,1,kk(r.year,r.month));return e?t?n?!1:ts("day",r.day):ts("month",r.month):ts("year",r.year)}function x3(r){let{hour:e,minute:t,second:n,millisecond:i}=r,o=Nl(e,0,23)||e===24&&t===0&&n===0&&i===0,s=Nl(t,0,59),a=Nl(n,0,59),l=Nl(i,0,999);return o?s?a?l?!1:ts("millisecond",i):ts("second",n):ts("minute",t):ts("hour",e)}var T0="Invalid DateTime",gW=864e13;function vk(r){return new yo("unsupported zone",`the zone "${r.name}" is not supported`)}function k0(r){return r.weekData===null&&(r.weekData=B0(r.c)),r.weekData}function ep(r,e){let t={ts:r.ts,zone:r.zone,c:r.c,o:r.o,loc:r.loc,invalid:r.invalid};return new pt({...t,...e,old:t})}function E3(r,e,t){let n=r-e*60*1e3,i=t.offset(n);if(e===i)return[n,e];n-=(i-e)*60*1e3;let o=t.offset(n);return i===o?[n,i]:[r-Math.min(i,o)*60*1e3,Math.max(i,o)]}function yk(r,e){r+=e*60*1e3;let t=new Date(r);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),millisecond:t.getUTCMilliseconds()}}function Ck(r,e,t){return E3(Mk(r),e,t)}function vW(r,e){let t=r.o,n=r.c.year+Math.trunc(e.years),i=r.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,o={...r.c,year:n,month:i,day:Math.min(r.c.day,kk(n,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},s=je.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=Mk(o),[l,c]=E3(a,t,r.zone);return s!==0&&(l+=s,c=r.zone.offset(l)),{ts:l,o:c}}function wb(r,e,t,n,i,o){let{setZone:s,zone:a}=t;if(r&&Object.keys(r).length!==0||e){let l=e||a,c=pt.fromObject(r,{...t,zone:l,specificOffset:o});return s?c:c.setZone(a)}else return pt.invalid(new yo("unparsable",`the input "${i}" can't be parsed as ${n}`))}function bk(r,e,t=!0){return r.isValid?vo.create(_r.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(r,e):null}function S0(r,e){let t=r.c.year>9999||r.c.year<0,n="";return t&&r.c.year>=0&&(n+="+"),n+=Ur(r.c.year,t?6:4),e?(n+="-",n+=Ur(r.c.month),n+="-",n+=Ur(r.c.day)):(n+=Ur(r.c.month),n+=Ur(r.c.day)),n}function yW(r,e,t,n,i,o){let s=Ur(r.c.hour);return e?(s+=":",s+=Ur(r.c.minute),(r.c.millisecond!==0||r.c.second!==0||!t)&&(s+=":")):s+=Ur(r.c.minute),(r.c.millisecond!==0||r.c.second!==0||!t)&&(s+=Ur(r.c.second),(r.c.millisecond!==0||!n)&&(s+=".",s+=Ur(r.c.millisecond,3))),i&&(r.isOffsetFixed&&r.offset===0&&!o?s+="Z":r.o<0?(s+="-",s+=Ur(Math.trunc(-r.o/60)),s+=":",s+=Ur(Math.trunc(-r.o%60))):(s+="+",s+=Ur(Math.trunc(r.o/60)),s+=":",s+=Ur(Math.trunc(r.o%60)))),o&&(s+="["+r.zone.ianaName+"]"),s}var T3={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},tse={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},rse={ordinal:1,hour:0,minute:0,second:0,millisecond:0},k3=["year","month","day","hour","minute","second","millisecond"],nse=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],ise=["year","ordinal","hour","minute","second","millisecond"];function bW(r){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[r.toLowerCase()];if(!e)throw new xk(r);return e}function wW(r,e){let t=gu(e.zone,Sr.defaultZone),n=_r.fromObject(e),i=Sr.now(),o,s;if(wt(r.year))o=i;else{for(let c of k3)wt(r[c])&&(r[c]=T3[c]);let a=C3(r)||x3(r);if(a)return pt.invalid(a);let l=t.offset(i);[o,s]=Ck(r,l,t)}return new pt({ts:o,zone:t,loc:n,o:s})}function CW(r,e,t){let n=wt(t.round)?!0:t.round,i=(s,a)=>(s=K0(s,n||t.calendary?0:2,!0),e.loc.clone(t).relFormatter(t).format(s,a)),o=s=>t.calendary?e.hasSame(r,s)?0:e.startOf(s).diff(r.startOf(s),s).get(s):e.diff(r,s).get(s);if(t.unit)return i(o(t.unit),t.unit);for(let s of t.units){let a=o(s);if(Math.abs(a)>=1)return i(a,s)}return i(r>e?-0:0,t.units[t.units.length-1])}function xW(r){let e={},t;return r.length>0&&typeof r[r.length-1]=="object"?(e=r[r.length-1],t=Array.from(r).slice(0,r.length-1)):t=Array.from(r),[e,t]}var pt=class r{constructor(e){let t=e.zone||Sr.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new yo("invalid input"):null)||(t.isValid?null:vk(t));this.ts=wt(e.ts)?Sr.now():e.ts;let i=null,o=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[i,o]=[e.old.c,e.old.o];else{let a=t.offset(this.ts);i=yk(this.ts,a),n=Number.isNaN(i.year)?new yo("invalid input"):null,i=n?null:i,o=n?null:a}this._zone=t,this.loc=e.loc||_r.create(),this.invalid=n,this.weekData=null,this.c=i,this.o=o,this.isLuxonDateTime=!0}static now(){return new r({})}static local(){let[e,t]=xW(arguments),[n,i,o,s,a,l,c]=t;return wW({year:n,month:i,day:o,hour:s,minute:a,second:l,millisecond:c},e)}static utc(){let[e,t]=xW(arguments),[n,i,o,s,a,l,c]=t;return e.zone=rs.utcInstance,wW({year:n,month:i,day:o,hour:s,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,t={}){let n=Pie(e)?e.valueOf():NaN;if(Number.isNaN(n))return r.invalid("invalid input");let i=gu(t.zone,Sr.defaultZone);return i.isValid?new r({ts:n,zone:i,loc:_r.fromObject(t)}):r.invalid(vk(i))}static fromMillis(e,t={}){if(np(e))return e<-gW||e>gW?r.invalid("Timestamp out of range"):new r({ts:e,zone:gu(t.zone,Sr.defaultZone),loc:_r.fromObject(t)});throw new zi(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(np(e))return new r({ts:e*1e3,zone:gu(t.zone,Sr.defaultZone),loc:_r.fromObject(t)});throw new zi("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};let n=gu(t.zone,Sr.defaultZone);if(!n.isValid)return r.invalid(vk(n));let i=Sr.now(),o=wt(t.specificOffset)?n.offset(i):t.specificOffset,s=_k(e,bW),a=!wt(s.ordinal),l=!wt(s.year),c=!wt(s.month)||!wt(s.day),u=l||c,d=s.weekYear||s.weekNumber,p=_r.fromObject(t);if((u||a)&&d)throw new tp("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(c&&a)throw new tp("Can't mix ordinal dates with month/day");let f=d||s.weekday&&!u,m,g,v=yk(i,o);f?(m=nse,g=tse,v=B0(v)):a?(m=ise,g=rse,v=E0(v)):(m=k3,g=T3);let y=!1;for(let A of m){let D=s[A];wt(D)?y?s[A]=g[A]:s[A]=v[A]:y=!0}let b=f?Joe(s):a?ese(s):C3(s),x=b||x3(s);if(x)return r.invalid(x);let w=f?mW(s):a?hW(s):s,[T,C]=Ck(w,o,n),S=new r({ts:T,zone:n,o:C,loc:p});return s.weekday&&u&&e.weekday!==S.weekday?r.invalid("mismatched weekday",`you can't specify both a weekday of ${s.weekday} and a date of ${S.toISO()}`):S}static fromISO(e,t={}){let[n,i]=Coe(e);return wb(n,i,t,"ISO 8601",e)}static fromRFC2822(e,t={}){let[n,i]=xoe(e);return wb(n,i,t,"RFC 2822",e)}static fromHTTP(e,t={}){let[n,i]=Eoe(e);return wb(n,i,t,"HTTP",t)}static fromFormat(e,t,n={}){if(wt(e)||wt(t))throw new zi("fromFormat requires an input string and a format");let{locale:i=null,numberingSystem:o=null}=n,s=_r.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0}),[a,l,c,u]=Zoe(s,e,t);return u?r.invalid(u):wb(a,l,n,`format ${t}`,e,c)}static fromString(e,t,n={}){return r.fromFormat(e,t,n)}static fromSQL(e,t={}){let[n,i]=Doe(e);return wb(n,i,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new zi("need to specify a reason the DateTime is invalid");let n=e instanceof yo?e:new yo(e,t);if(Sr.throwOnInvalid)throw new A0(n);return new r({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){let n=h3(e,_r.fromObject(t));return n?n.map(i=>i?i.val:null).join(""):null}static expandFormat(e,t={}){return f3(vo.parseFormat(e),_r.fromObject(t)).map(i=>i.val).join("")}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?k0(this).weekYear:NaN}get weekNumber(){return this.isValid?k0(this).weekNumber:NaN}get weekday(){return this.isValid?k0(this).weekday:NaN}get ordinal(){return this.isValid?E0(this.c).ordinal:NaN}get monthShort(){return this.isValid?oh.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?oh.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?oh.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?oh.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,t=6e4,n=Mk(this.c),i=this.zone.offset(n-e),o=this.zone.offset(n+e),s=this.zone.offset(n-i*t),a=this.zone.offset(n-o*t);if(s===a)return[this];let l=n-s*t,c=n-a*t,u=yk(l,s),d=yk(c,a);return u.hour===d.hour&&u.minute===d.minute&&u.second===d.second&&u.millisecond===d.millisecond?[ep(this,{ts:l}),ep(this,{ts:c})]:[this]}get isInLeapYear(){return Ab(this.year)}get daysInMonth(){return kk(this.year,this.month)}get daysInYear(){return this.isValid?Tb(this.year):NaN}get weeksInWeekYear(){return this.isValid?Sk(this.weekYear):NaN}resolvedLocaleOptions(e={}){let{locale:t,numberingSystem:n,calendar:i}=vo.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:n,outputCalendar:i}}toUTC(e=0,t={}){return this.setZone(rs.instance(e),t)}toLocal(){return this.setZone(Sr.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:n=!1}={}){if(e=gu(e,Sr.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(t||n){let o=e.offset(this.ts),s=this.toObject();[i]=Ck(s,o,e)}return ep(this,{ts:i,zone:e})}else return r.invalid(vk(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:n}={}){let i=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:n});return ep(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let t=_k(e,bW),n=!wt(t.weekYear)||!wt(t.weekNumber)||!wt(t.weekday),i=!wt(t.ordinal),o=!wt(t.year),s=!wt(t.month)||!wt(t.day),a=o||s,l=t.weekYear||t.weekNumber;if((a||i)&&l)throw new tp("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(s&&i)throw new tp("Can't mix ordinal dates with month/day");let c;n?c=mW({...B0(this.c),...t}):wt(t.ordinal)?(c={...this.toObject(),...t},wt(t.day)&&(c.day=Math.min(kk(c.year,c.month),c.day))):c=hW({...E0(this.c),...t});let[u,d]=Ck(c,this.o,this.zone);return ep(this,{ts:u,o:d})}plus(e){if(!this.isValid)return this;let t=je.fromDurationLike(e);return ep(this,vW(this,t))}minus(e){if(!this.isValid)return this;let t=je.fromDurationLike(e).negate();return ep(this,vW(this,t))}startOf(e){if(!this.isValid)return this;let t={},n=je.normalizeUnit(e);switch(n){case"years":t.month=1;case"quarters":case"months":t.day=1;case"weeks":case"days":t.hour=0;case"hours":t.minute=0;case"minutes":t.second=0;case"seconds":t.millisecond=0;break}if(n==="weeks"&&(t.weekday=1),n==="quarters"){let i=Math.ceil(this.month/3);t.month=(i-1)*3+1}return this.set(t)}endOf(e){return this.isValid?this.plus({[e]:1}).startOf(e).minus(1):this}toFormat(e,t={}){return this.isValid?vo.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):T0}toLocaleString(e=Ek,t={}){return this.isValid?vo.create(this.loc.clone(t),e).formatDateTime(this):T0}toLocaleParts(e={}){return this.isValid?vo.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:t=!1,suppressMilliseconds:n=!1,includeOffset:i=!0,extendedZone:o=!1}={}){if(!this.isValid)return null;let s=e==="extended",a=S0(this,s);return a+="T",a+=yW(this,s,t,n,i,o),a}toISODate({format:e="extended"}={}){return this.isValid?S0(this,e==="extended"):null}toISOWeekDate(){return bk(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:n=!0,includePrefix:i=!1,extendedZone:o=!1,format:s="extended"}={}){return this.isValid?(i?"T":"")+yW(this,s==="extended",t,e,n,o):null}toRFC2822(){return bk(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return bk(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?S0(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:n=!0}={}){let i="HH:mm:ss.SSS";return(t||e)&&(n&&(i+=" "),t?i+="z":e&&(i+="ZZ")),bk(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():T0}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let t={...this.c};return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,t="milliseconds",n={}){if(!this.isValid||!e.isValid)return je.invalid("created by diffing an invalid DateTime");let i={locale:this.locale,numberingSystem:this.numberingSystem,...n},o=Mie(t).map(je.normalizeUnit),s=e.valueOf()>this.valueOf(),a=s?this:e,l=s?e:this,c=Noe(a,l,o,i);return s?c.negate():c}diffNow(e="milliseconds",t={}){return this.diff(r.now(),e,t)}until(e){return this.isValid?ah.fromDateTimes(this,e):this}hasSame(e,t){if(!this.isValid)return!1;let n=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(t)<=n&&n<=i.endOf(t)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let t=e.base||r.fromObject({},{zone:this.zone}),n=e.padding?this<t?-e.padding:e.padding:0,i=["years","months","days","hours","minutes","seconds"],o=e.unit;return Array.isArray(e.unit)&&(i=e.unit,o=void 0),CW(t,this.plus(n),{...e,numeric:"always",units:i,unit:o})}toRelativeCalendar(e={}){return this.isValid?CW(e.base||r.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(r.isDateTime))throw new zi("min requires all arguments be DateTimes");return oW(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(r.isDateTime))throw new zi("max requires all arguments be DateTimes");return oW(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,n={}){let{locale:i=null,numberingSystem:o=null}=n,s=_r.fromOpts({locale:i,numberingSystem:o,defaultToEN:!0});return m3(s,e,t)}static fromStringExplain(e,t,n={}){return r.fromFormatExplain(e,t,n)}static get DATE_SHORT(){return Ek}static get DATE_MED(){return AW}static get DATE_MED_WITH_WEEKDAY(){return gie}static get DATE_FULL(){return IW}static get DATE_HUGE(){return DW}static get TIME_SIMPLE(){return FW}static get TIME_WITH_SECONDS(){return PW}static get TIME_WITH_SHORT_OFFSET(){return MW}static get TIME_WITH_LONG_OFFSET(){return $W}static get TIME_24_SIMPLE(){return OW}static get TIME_24_WITH_SECONDS(){return RW}static get TIME_24_WITH_SHORT_OFFSET(){return NW}static get TIME_24_WITH_LONG_OFFSET(){return LW}static get DATETIME_SHORT(){return VW}static get DATETIME_SHORT_WITH_SECONDS(){return BW}static get DATETIME_MED(){return qW}static get DATETIME_MED_WITH_SECONDS(){return UW}static get DATETIME_MED_WITH_WEEKDAY(){return vie}static get DATETIME_FULL(){return HW}static get DATETIME_FULL_WITH_SECONDS(){return zW}static get DATETIME_HUGE(){return WW}static get DATETIME_HUGE_WITH_SECONDS(){return jW}};function Cb(r){if(pt.isDateTime(r))return r;if(r&&r.valueOf&&np(r.valueOf()))return pt.fromJSDate(r);if(r&&typeof r=="object")return pt.fromObject(r);throw new zi(`Unknown datetime argument: ${r}, of type ${typeof r}`)}var eM={renderNullAs:"\\-",taskCompletionTracking:!1,taskCompletionUseEmojiShorthand:!1,taskCompletionText:"completion",taskCompletionDateFormat:"yyyy-MM-dd",recursiveSubTaskCompletion:!1,warnOnEmptyResult:!0,refreshEnabled:!0,refreshInterval:2500,defaultDateFormat:"MMMM dd, yyyy",defaultDateTimeFormat:"h:mm a - MMMM dd, yyyy",maxRecursiveRenderDepth:4,tableIdColumnName:"File",tableGroupColumnName:"Group",showResultCount:!0},ose={allowHtml:!0};({...eM,...ose});var q0=class r{constructor(e){he(this,"value");he(this,"successful");this.value=e,this.successful=!0}map(e){return new r(e(this.value))}flatMap(e){return e(this.value)}mapErr(e){return this}bimap(e,t){return this.map(e)}orElse(e){return this.value}cast(){return this}orElseThrow(e){return this.value}},U0=class r{constructor(e){he(this,"error");he(this,"successful");this.error=e,this.successful=!1}map(e){return this}flatMap(e){return this}mapErr(e){return new r(e(this.error))}bimap(e,t){return this.mapErr(t)}orElse(e){return e}cast(){return this}orElseThrow(e){throw e?new Error(e(this.error)):new Error(""+this.error)}},Ak;(function(r){function e(o){return new q0(o)}r.success=e;function t(o){return new U0(o)}r.failure=t;function n(o,s,a){return o.successful?s.successful?a(o.value,s.value):t(s.error):t(o.error)}r.flatMap2=n;function i(o,s,a){return n(o,s,(l,c)=>e(a(l,c)))}r.map2=i})(Ak||(Ak={}));var sse=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ik={exports:{}};Ik.exports;(function(r,e){(function(t,n){r.exports=n()})(typeof self<"u"?self:sse,function(){return(function(t){var n={};function i(o){if(n[o])return n[o].exports;var s=n[o]={i:o,l:!1,exports:{}};return t[o].call(s.exports,s,s.exports,i),s.l=!0,s.exports}return i.m=t,i.c=n,i.d=function(o,s,a){i.o(o,s)||Object.defineProperty(o,s,{configurable:!1,enumerable:!0,get:a})},i.r=function(o){Object.defineProperty(o,"__esModule",{value:!0})},i.n=function(o){var s=o&&o.__esModule?function(){return o.default}:function(){return o};return i.d(s,"a",s),s},i.o=function(o,s){return Object.prototype.hasOwnProperty.call(o,s)},i.p="",i(i.s=0)})([function(t,n,i){function o(k){if(!(this instanceof o))return new o(k);this._=k}var s=o.prototype;function a(k,R){for(var q=0;q<k;q++)R(q)}function l(k,R,q){return(function(J,se){a(se.length,function(oe){J(se[oe],oe,se)})})(function(J,se,oe){R=k(R,J,se,oe)},q),R}function c(k,R){return l(function(q,J,se,oe){return q.concat([k(J,se,oe)])},[],R)}function u(k,R){var q={v:0,buf:R};return a(k,function(){var J;q={v:q.v<<1|(J=q.buf,J[0]>>7),buf:(function(se){var oe=l(function(de,$e,vt,nr){return de.concat(vt===nr.length-1?Buffer.from([$e,0]).readUInt16BE(0):nr.readUInt16BE(vt))},[],se);return Buffer.from(c(function(de){return(de<<1&65535)>>8},oe))})(q.buf)}}),q}function d(){return typeof Buffer<"u"}function p(){if(!d())throw new Error("Buffer global does not exist; please use webpack if you need to parse Buffers in the browser.")}function f(k){p();var R=l(function(oe,de){return oe+de},0,k);if(R%8!=0)throw new Error("The bits ["+k.join(", ")+"] add up to "+R+" which is not an even number of bytes; the total should be divisible by 8");var q,J=R/8,se=(q=function(oe){return oe>48},l(function(oe,de){return oe||(q(de)?de:oe)},null,k));if(se)throw new Error(se+" bit range requested exceeds 48 bit (6 byte) Number max.");return new o(function(oe,de){var $e=J+de;return $e>oe.length?A(de,J.toString()+" bytes"):S($e,l(function(vt,nr){var lr=u(nr,vt.buf);return{coll:vt.coll.concat(lr.v),buf:lr.buf}},{coll:[],buf:oe.slice(de,$e)},k).coll)})}function m(k,R){return new o(function(q,J){return p(),J+R>q.length?A(J,R+" bytes for "+k):S(J+R,q.slice(J,J+R))})}function g(k,R){if(typeof(q=R)!="number"||Math.floor(q)!==q||R<0||R>6)throw new Error(k+" requires integer length in range [0, 6].");var q}function v(k){return g("uintBE",k),m("uintBE("+k+")",k).map(function(R){return R.readUIntBE(0,k)})}function y(k){return g("uintLE",k),m("uintLE("+k+")",k).map(function(R){return R.readUIntLE(0,k)})}function b(k){return g("intBE",k),m("intBE("+k+")",k).map(function(R){return R.readIntBE(0,k)})}function x(k){return g("intLE",k),m("intLE("+k+")",k).map(function(R){return R.readIntLE(0,k)})}function w(k){return k instanceof o}function T(k){return{}.toString.call(k)==="[object Array]"}function C(k){return d()&&Buffer.isBuffer(k)}function S(k,R){return{status:!0,index:k,value:R,furthest:-1,expected:[]}}function A(k,R){return T(R)||(R=[R]),{status:!1,index:-1,value:null,furthest:k,expected:R}}function D(k,R){if(!R||k.furthest>R.furthest)return k;var q=k.furthest===R.furthest?(function(J,se){if((function(){if(o._supportsSet!==void 0)return o._supportsSet;var Xn=typeof Set<"u";return o._supportsSet=Xn,Xn})()&&Array.from){for(var oe=new Set(J),de=0;de<se.length;de++)oe.add(se[de]);var $e=Array.from(oe);return $e.sort(),$e}for(var vt={},nr=0;nr<J.length;nr++)vt[J[nr]]=!0;for(var lr=0;lr<se.length;lr++)vt[se[lr]]=!0;var Wr=[];for(var Wt in vt)({}).hasOwnProperty.call(vt,Wt)&&Wr.push(Wt);return Wr.sort(),Wr})(k.expected,R.expected):R.expected;return{status:k.status,index:k.index,value:k.value,furthest:R.furthest,expected:q}}var P={};function U(k,R){if(C(k))return{offset:R,line:-1,column:-1};k in P||(P[k]={});for(var q=P[k],J=0,se=0,oe=0,de=R;de>=0;){if(de in q){J=q[de].line,oe===0&&(oe=q[de].lineStart);break}(k.charAt(de)===`
`||k.charAt(de)==="\r"&&k.charAt(de+1)!==`
`)&&(se++,oe===0&&(oe=de+1)),de--}var $e=J+se,vt=R-oe;return q[R]={line:$e,lineStart:oe},{offset:R,line:$e+1,column:vt+1}}function K(k){if(!w(k))throw new Error("not a parser: "+k)}function W(k,R){return typeof k=="string"?k.charAt(R):k[R]}function ee(k){if(typeof k!="number")throw new Error("not a number: "+k)}function me(k){if(typeof k!="function")throw new Error("not a function: "+k)}function O(k){if(typeof k!="string")throw new Error("not a string: "+k)}var H=2,ce=3,te=8,z=5*te,G=4*te,ie=" ";function xe(k,R){return new Array(R+1).join(k)}function ue(k,R,q){var J=R-k.length;return J<=0?k:xe(q,J)+k}function be(k,R,q,J){return{from:k-R>0?k-R:0,to:k+q>J?J:k+q}}function Ke(k,R){var q,J,se,oe,de,$e=R.index,vt=$e.offset,nr=1;if(vt===k.length)return"Got the end of the input";if(C(k)){var lr=vt-vt%te,Wr=vt-lr,Wt=be(lr,z,G+te,k.length),Xn=c(function(ir){return c(function(La){return ue(La.toString(16),2,"0")},ir)},(function(ir,La){var Xl=ir.length,Va=[],Ys=0;if(Xl<=La)return[ir.slice()];for(var Ba=0;Ba<Xl;Ba++)Va[Ys]||Va.push([]),Va[Ys].push(ir[Ba]),(Ba+1)%La==0&&Ys++;return Va})(k.slice(Wt.from,Wt.to).toJSON().data,te));oe=(function(ir){return ir.from===0&&ir.to===1?{from:ir.from,to:ir.to}:{from:ir.from/te,to:Math.floor(ir.to/te)}})(Wt),J=lr/te,q=3*Wr,Wr>=4&&(q+=1),nr=2,se=c(function(ir){return ir.length<=4?ir.join(" "):ir.slice(0,4).join(" ")+" "+ir.slice(4).join(" ")},Xn),(de=(8*(oe.to>0?oe.to-1:oe.to)).toString(16).length)<2&&(de=2)}else{var Gs=k.split(/\r\n|[\n\r\u2028\u2029]/);q=$e.column-1,J=$e.line-1,oe=be(J,H,ce,Gs.length),se=Gs.slice(oe.from,oe.to),de=oe.to.toString().length}var Hh=J-oe.from;return C(k)&&(de=(8*(oe.to>0?oe.to-1:oe.to)).toString(16).length)<2&&(de=2),l(function(ir,La,Xl){var Va,Ys=Xl===Hh,Ba=Ys?"> ":ie;return Va=C(k)?ue((8*(oe.from+Xl)).toString(16),de,"0"):ue((oe.from+Xl+1).toString(),de," "),[].concat(ir,[Ba+Va+" | "+La],Ys?[ie+xe(" ",de)+" | "+ue("",q," ")+xe("^",nr)]:[])},[],se).join(`
`)}function Oe(k,R){return[`
`,"-- PARSING FAILED "+xe("-",50),`
`,Ke(k,R),`
`,(q=R.expected,q.length===1?`Expected:
`+q[0]:`Expected one of the following:
`+q.join(", ")),`
`].join("");var q}function Ee(k){return k.flags!==void 0?k.flags:[k.global?"g":"",k.ignoreCase?"i":"",k.multiline?"m":"",k.unicode?"u":"",k.sticky?"y":""].join("")}function He(){for(var k=[].slice.call(arguments),R=k.length,q=0;q<R;q+=1)K(k[q]);return o(function(J,se){for(var oe,de=new Array(R),$e=0;$e<R;$e+=1){if(!(oe=D(k[$e]._(J,se),oe)).status)return oe;de[$e]=oe.value,se=oe.index}return D(S(se,de),oe)})}function Le(){var k=[].slice.call(arguments);if(k.length===0)throw new Error("seqMap needs at least one argument");var R=k.pop();return me(R),He.apply(null,k).map(function(q){return R.apply(null,q)})}function At(){var k=[].slice.call(arguments),R=k.length;if(R===0)return Je("zero alternates");for(var q=0;q<R;q+=1)K(k[q]);return o(function(J,se){for(var oe,de=0;de<k.length;de+=1)if((oe=D(k[de]._(J,se),oe)).status)return oe;return oe})}function mr(k,R){return zr(k,R).or(Fe([]))}function zr(k,R){return K(k),K(R),Le(k,R.then(k).many(),function(q,J){return[q].concat(J)})}function ge(k){O(k);var R="'"+k+"'";return o(function(q,J){var se=J+k.length,oe=q.slice(J,se);return oe===k?S(se,oe):A(J,R)})}function ve(k,R){(function(se){if(!(se instanceof RegExp))throw new Error("not a regexp: "+se);for(var oe=Ee(se),de=0;de<oe.length;de++){var $e=oe.charAt(de);if($e!=="i"&&$e!=="m"&&$e!=="u"&&$e!=="s")throw new Error('unsupported regexp flag "'+$e+'": '+se)}})(k),arguments.length>=2?ee(R):R=0;var q=(function(se){return RegExp("^(?:"+se.source+")",Ee(se))})(k),J=""+k;return o(function(se,oe){var de=q.exec(se.slice(oe));if(de){if(0<=R&&R<=de.length){var $e=de[0],vt=de[R];return S(oe+$e.length,vt)}return A(oe,"valid match group (0 to "+de.length+") in "+J)}return A(oe,J)})}function Fe(k){return o(function(R,q){return S(q,k)})}function Je(k){return o(function(R,q){return A(q,k)})}function mt(k){if(w(k))return o(function(R,q){var J=k._(R,q);return J.index=q,J.value="",J});if(typeof k=="string")return mt(ge(k));if(k instanceof RegExp)return mt(ve(k));throw new Error("not a string, regexp, or parser: "+k)}function Ft(k){return K(k),o(function(R,q){var J=k._(R,q),se=R.slice(q,J.index);return J.status?A(q,'not "'+se+'"'):S(q,null)})}function Qe(k){return me(k),o(function(R,q){var J=W(R,q);return q<R.length&&k(J)?S(q+1,J):A(q,"a character/byte matching "+k)})}function zt(k,R){arguments.length<2&&(R=k,k=void 0);var q=o(function(J,se){return q._=R()._,q._(J,se)});return k?q.desc(k):q}function rr(){return Je("fantasy-land/empty")}s.parse=function(k){if(typeof k!="string"&&!C(k))throw new Error(".parse must be called with a string or Buffer as its argument");var R,q=this.skip(De)._(k,0);return R=q.status?{status:!0,value:q.value}:{status:!1,index:U(k,q.furthest),expected:q.expected},delete P[k],R},s.tryParse=function(k){var R=this.parse(k);if(R.status)return R.value;var q=Oe(k,R),J=new Error(q);throw J.type="ParsimmonError",J.result=R,J},s.assert=function(k,R){return this.chain(function(q){return k(q)?Fe(q):Je(R)})},s.or=function(k){return At(this,k)},s.trim=function(k){return this.wrap(k,k)},s.wrap=function(k,R){return Le(k,this,R,function(q,J){return J})},s.thru=function(k){return k(this)},s.then=function(k){return K(k),He(this,k).map(function(R){return R[1]})},s.many=function(){var k=this;return o(function(R,q){for(var J=[],se=void 0;;){if(!(se=D(k._(R,q),se)).status)return D(S(q,J),se);if(q===se.index)throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause");q=se.index,J.push(se.value)}})},s.tieWith=function(k){return O(k),this.map(function(R){if((function(se){if(!T(se))throw new Error("not an array: "+se)})(R),R.length){O(R[0]);for(var q=R[0],J=1;J<R.length;J++)O(R[J]),q+=k+R[J];return q}return""})},s.tie=function(){return this.tieWith("")},s.times=function(k,R){var q=this;return arguments.length<2&&(R=k),ee(k),ee(R),o(function(J,se){for(var oe=[],de=void 0,$e=void 0,vt=0;vt<k;vt+=1){if($e=D(de=q._(J,se),$e),!de.status)return $e;se=de.index,oe.push(de.value)}for(;vt<R&&($e=D(de=q._(J,se),$e),de.status);vt+=1)se=de.index,oe.push(de.value);return D(S(se,oe),$e)})},s.result=function(k){return this.map(function(){return k})},s.atMost=function(k){return this.times(0,k)},s.atLeast=function(k){return Le(this.times(k),this.many(),function(R,q){return R.concat(q)})},s.map=function(k){me(k);var R=this;return o(function(q,J){var se=R._(q,J);return se.status?D(S(se.index,k(se.value)),se):se})},s.contramap=function(k){me(k);var R=this;return o(function(q,J){var se=R.parse(k(q.slice(J)));return se.status?S(J+q.length,se.value):se})},s.promap=function(k,R){return me(k),me(R),this.contramap(k).map(R)},s.skip=function(k){return He(this,k).map(function(R){return R[0]})},s.mark=function(){return Le(Qn,this,Qn,function(k,R,q){return{start:k,value:R,end:q}})},s.node=function(k){return Le(Qn,this,Qn,function(R,q,J){return{name:k,value:q,start:R,end:J}})},s.sepBy=function(k){return mr(this,k)},s.sepBy1=function(k){return zr(this,k)},s.lookahead=function(k){return this.skip(mt(k))},s.notFollowedBy=function(k){return this.skip(Ft(k))},s.desc=function(k){T(k)||(k=[k]);var R=this;return o(function(q,J){var se=R._(q,J);return se.status||(se.expected=k),se})},s.fallback=function(k){return this.or(Fe(k))},s.ap=function(k){return Le(k,this,function(R,q){return R(q)})},s.chain=function(k){var R=this;return o(function(q,J){var se=R._(q,J);return se.status?D(k(se.value)._(q,se.index),se):se})},s.concat=s.or,s.empty=rr,s.of=Fe,s["fantasy-land/ap"]=s.ap,s["fantasy-land/chain"]=s.chain,s["fantasy-land/concat"]=s.concat,s["fantasy-land/empty"]=s.empty,s["fantasy-land/of"]=s.of,s["fantasy-land/map"]=s.map;var Qn=o(function(k,R){return S(R,U(k,R))}),di=o(function(k,R){return R>=k.length?A(R,"any character/byte"):S(R+1,W(k,R))}),Z=o(function(k,R){return S(k.length,k.slice(R))}),De=o(function(k,R){return R<k.length?A(R,"EOF"):S(R,null)}),Pt=ve(/[0-9]/).desc("a digit"),It=ve(/[0-9]*/).desc("optional digits"),pi=ve(/[a-z]/i).desc("a letter"),Di=ve(/[a-z]*/i).desc("optional letters"),Au=ve(/\s*/).desc("optional whitespace"),wp=ve(/\s+/).desc("whitespace"),Cp=ge("\r"),xp=ge(`
`),Iu=ge(`\r
`),we=At(Iu,xp,Cp).desc("newline"),qe=At(we,De);o.all=Z,o.alt=At,o.any=di,o.cr=Cp,o.createLanguage=function(k){var R={};for(var q in k)({}).hasOwnProperty.call(k,q)&&(function(J){R[J]=zt(function(){return k[J](R)})})(q);return R},o.crlf=Iu,o.custom=function(k){return o(k(S,A))},o.digit=Pt,o.digits=It,o.empty=rr,o.end=qe,o.eof=De,o.fail=Je,o.formatError=Oe,o.index=Qn,o.isParser=w,o.lazy=zt,o.letter=pi,o.letters=Di,o.lf=xp,o.lookahead=mt,o.makeFailure=A,o.makeSuccess=S,o.newline=we,o.noneOf=function(k){return Qe(function(R){return k.indexOf(R)<0}).desc("none of '"+k+"'")},o.notFollowedBy=Ft,o.of=Fe,o.oneOf=function(k){for(var R=k.split(""),q=0;q<R.length;q++)R[q]="'"+R[q]+"'";return Qe(function(J){return k.indexOf(J)>=0}).desc(R)},o.optWhitespace=Au,o.Parser=o,o.range=function(k,R){return Qe(function(q){return k<=q&&q<=R}).desc(k+"-"+R)},o.regex=ve,o.regexp=ve,o.sepBy=mr,o.sepBy1=zr,o.seq=He,o.seqMap=Le,o.seqObj=function(){for(var k,R={},q=0,J=(k=arguments,Array.prototype.slice.call(k)),se=J.length,oe=0;oe<se;oe+=1){var de=J[oe];if(!w(de)){if(T(de)&&de.length===2&&typeof de[0]=="string"&&w(de[1])){var $e=de[0];if(Object.prototype.hasOwnProperty.call(R,$e))throw new Error("seqObj: duplicate key "+$e);R[$e]=!0,q++;continue}throw new Error("seqObj arguments must be parsers or [string, parser] array pairs.")}}if(q===0)throw new Error("seqObj expects at least one named parser, found zero");return o(function(vt,nr){for(var lr,Wr={},Wt=0;Wt<se;Wt+=1){var Xn,Gs;if(T(J[Wt])?(Xn=J[Wt][0],Gs=J[Wt][1]):(Xn=null,Gs=J[Wt]),!(lr=D(Gs._(vt,nr),lr)).status)return lr;Xn&&(Wr[Xn]=lr.value),nr=lr.index}return D(S(nr,Wr),lr)})},o.string=ge,o.succeed=Fe,o.takeWhile=function(k){return me(k),o(function(R,q){for(var J=q;J<R.length&&k(W(R,J));)J++;return S(J,R.slice(q,J))})},o.test=Qe,o.whitespace=wp,o["fantasy-land/empty"]=rr,o["fantasy-land/of"]=Fe,o.Binary={bitSeq:f,bitSeqObj:function(k){p();var R={},q=0,J=c(function(oe){if(T(oe)){var de=oe;if(de.length!==2)throw new Error("["+de.join(", ")+"] should be length 2, got length "+de.length);if(O(de[0]),ee(de[1]),Object.prototype.hasOwnProperty.call(R,de[0]))throw new Error("duplicate key in bitSeqObj: "+de[0]);return R[de[0]]=!0,q++,de}return ee(oe),[null,oe]},k);if(q<1)throw new Error("bitSeqObj expects at least one named pair, got ["+k.join(", ")+"]");var se=c(function(oe){return oe[0]},J);return f(c(function(oe){return oe[1]},J)).map(function(oe){return l(function(de,$e){return $e[0]!==null&&(de[$e[0]]=$e[1]),de},{},c(function(de,$e){return[de,oe[$e]]},se))})},byte:function(k){if(p(),ee(k),k>255)throw new Error("Value specified to byte constructor ("+k+"=0x"+k.toString(16)+") is larger in value than a single byte.");var R=(k>15?"0x":"0x0")+k.toString(16);return o(function(q,J){var se=W(q,J);return se===k?S(J+1,se):A(J,R)})},buffer:function(k){return m("buffer",k).map(function(R){return Buffer.from(R)})},encodedString:function(k,R){return m("string",R).map(function(q){return q.toString(k)})},uintBE:v,uint8BE:v(1),uint16BE:v(2),uint32BE:v(4),uintLE:y,uint8LE:y(1),uint16LE:y(2),uint32LE:y(4),intBE:b,int8BE:b(1),int16BE:b(2),int32BE:b(4),intLE:x,int8LE:x(1),int16LE:x(2),int32LE:x(4),floatBE:m("floatBE",4).map(function(k){return k.readFloatBE(0)}),floatLE:m("floatLE",4).map(function(k){return k.readFloatLE(0)}),doubleBE:m("doubleBE",8).map(function(k){return k.readDoubleBE(0)}),doubleLE:m("doubleLE",8).map(function(k){return k.readDoubleLE(0)})},t.exports=o}])})})(Ik,Ik.exports);var $=Ik.exports,tM=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26F9(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC3\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC08\uDC26](?:\u200D\u2B1B)?|[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC2\uDECE-\uDEDB\uDEE0-\uDEE8]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;function S3(r){return r==null?r:r.shiftToAll().normalize()}function EW(r){return r.includes("/")&&(r=r.substring(r.lastIndexOf("/")+1)),r.endsWith(".md")&&(r=r.substring(0,r.length-3)),r}$.alt($.regex(new RegExp(tM(),"")),$.regex(/[0-9\p{Letter}_-]+/u).map(r=>r.toLocaleLowerCase()),$.whitespace.map(r=>"-"),$.any.map(r=>"")).many().map(r=>r.join(""));var ase=$.alt($.regex(new RegExp(tM(),"")),$.regex(/[0-9\p{Letter}_-]+/u),$.whitespace.map(r=>" "),$.any.map(r=>" ")).many().map(r=>r.join("").split(/\s+/).join(" ").trim());function lse(r){return ase.tryParse(r)}function cse(r){return r=S3(r),r=je.fromObject(Object.fromEntries(Object.entries(r.toObject()).filter(([,e])=>e!=0))),r.toHuman()}var Sb;(function(r){function e(w,T=eM,C=!1){let S=t(w);if(!S)return T.renderNullAs;switch(S.type){case"null":return T.renderNullAs;case"string":return S.value;case"number":case"boolean":return""+S.value;case"html":return S.value.outerHTML;case"widget":return S.value.markdown();case"link":return S.value.markdown();case"function":return"<function>";case"array":let A="";return C&&(A+="["),A+=S.value.map(D=>e(D,T,!0)).join(", "),C&&(A+="]"),A;case"object":return"{ "+Object.entries(S.value).map(D=>D[0]+": "+e(D[1],T,!0)).join(", ")+" }";case"date":return S.value.second==0&&S.value.hour==0&&S.value.minute==0?S.value.toFormat(T.defaultDateFormat):S.value.toFormat(T.defaultDateTimeFormat);case"duration":return cse(S.value)}}r.toString=e;function t(w){return p(w)?{type:"null",value:w}:c(w)?{type:"number",value:w}:l(w)?{type:"string",value:w}:m(w)?{type:"boolean",value:w}:d(w)?{type:"duration",value:w}:u(w)?{type:"date",value:w}:v(w)?{type:"widget",value:w}:f(w)?{type:"array",value:w}:g(w)?{type:"link",value:w}:x(w)?{type:"function",value:w}:y(w)?{type:"html",value:w}:b(w)?{type:"object",value:w}:void 0}r.wrapValue=t;function n(w,T){if(b(w)){let C={};for(let[S,A]of Object.entries(w))C[S]=n(A,T);return C}else if(f(w)){let C=[];for(let S of w)C.push(n(S,T));return C}else return T(w)}r.mapLeaves=n;function i(w,T,C){if(w===void 0&&(w=null),T===void 0&&(T=null),w===null&&T===null)return 0;if(w===null)return-1;if(T===null)return 1;let S=t(w),A=t(T);if(S===void 0&&A===void 0)return 0;if(S===void 0)return-1;if(A===void 0)return 1;if(S.type!=A.type)return S.type.localeCompare(A.type);if(S.value===A.value)return 0;switch(S.type){case"string":return S.value.localeCompare(A.value);case"number":return S.value<A.value?-1:S.value==A.value?0:1;case"null":return 0;case"boolean":return S.value==A.value?0:S.value?1:-1;case"link":let D=S.value,P=A.value,U=C??(G=>G),K=U(D.path).localeCompare(U(P.path));if(K!=0)return K;let W=D.type.localeCompare(P.type);return W!=0?W:D.subpath&&!P.subpath?1:!D.subpath&&P.subpath?-1:!D.subpath&&!P.subpath?0:(D.subpath??"").localeCompare(P.subpath??"");case"date":return S.value<A.value?-1:S.value.equals(A.value)?0:1;case"duration":return S.value<A.value?-1:S.value.equals(A.value)?0:1;case"array":let ee=S.value,me=A.value;for(let G=0;G<Math.min(ee.length,me.length);G++){let ie=i(ee[G],me[G]);if(ie!=0)return ie}return ee.length-me.length;case"object":let O=S.value,H=A.value,ce=Array.from(Object.keys(O)),te=Array.from(Object.keys(H));ce.sort(),te.sort();let z=i(ce,te);if(z!=0)return z;for(let G of ce){let ie=i(O[G],H[G]);if(ie!=0)return ie}return 0;case"widget":case"html":case"function":return 0}}r.compareValue=i;function o(w){return t(w)?.type}r.typeOf=o;function s(w){let T=t(w);if(!T)return!1;switch(T.type){case"number":return T.value!=0;case"string":return T.value.length>0;case"boolean":return T.value;case"link":return!!T.value.path;case"date":return T.value.toMillis()!=0;case"duration":return T.value.as("seconds")!=0;case"object":return Object.keys(T.value).length>0;case"array":return T.value.length>0;case"null":return!1;case"html":case"widget":case"function":return!0}}r.isTruthy=s;function a(w){if(w==null)return w;if(r.isArray(w))return[].concat(w.map(T=>a(T)));if(r.isObject(w)){let T={};for(let[C,S]of Object.entries(w))T[C]=a(S);return T}else return w}r.deepCopy=a;function l(w){return typeof w=="string"}r.isString=l;function c(w){return typeof w=="number"}r.isNumber=c;function u(w){return w instanceof pt}r.isDate=u;function d(w){return w instanceof je}r.isDuration=d;function p(w){return w==null}r.isNull=p;function f(w){return Array.isArray(w)}r.isArray=f;function m(w){return typeof w=="boolean"}r.isBoolean=m;function g(w){return w instanceof Dk}r.isLink=g;function v(w){return w instanceof _b}r.isWidget=v;function y(w){return typeof HTMLElement<"u"?w instanceof HTMLElement:!1}r.isHtml=y;function b(w){return typeof w=="object"&&!y(w)&&!v(w)&&!f(w)&&!d(w)&&!u(w)&&!g(w)&&w!==void 0&&!p(w)}r.isObject=b;function x(w){return typeof w=="function"}r.isFunction=x})(Sb||(Sb={}));var TW;(function(r){function e(i){return Sb.isObject(i)&&Object.keys(i).length==2&&"key"in i&&"rows"in i}r.isElementGroup=e;function t(i){for(let o of i)if(!e(o))return!1;return!0}r.isGrouping=t;function n(i){if(t(i)){let o=0;for(let s of i)o+=n(s.rows);return o}else return i.length}r.count=n})(TW||(TW={}));var Dk=class r{constructor(e){he(this,"path");he(this,"display");he(this,"subpath");he(this,"embed");he(this,"type");Object.assign(this,e)}static file(e,t=!1,n){return new r({path:e,embed:t,display:n,subpath:void 0,type:"file"})}static infer(e,t=!1,n){if(e.includes("#^")){let i=e.split("#^");return r.block(i[0],i[1],t,n)}else if(e.includes("#")){let i=e.split("#");return r.header(i[0],i[1],t,n)}else return r.file(e,t,n)}static header(e,t,n,i){return new r({path:e,embed:n,display:i,subpath:lse(t),type:"header"})}static block(e,t,n,i){return new r({path:e,embed:n,display:i,subpath:t,type:"block"})}static fromObject(e){return new r(e)}equals(e){return e==null||e==null?!1:this.path==e.path&&this.type==e.type&&this.subpath==e.subpath}toString(){return this.markdown()}toObject(){return{path:this.path,type:this.type,subpath:this.subpath,display:this.display,embed:this.embed}}withPath(e){return new r(Object.assign({},this,{path:e}))}withDisplay(e){return new r(Object.assign({},this,{display:e}))}withHeader(e){return r.header(this.path,e,this.embed,this.display)}toFile(){return r.file(this.path,this.embed,this.display)}toEmbed(){if(this.embed)return this;{let e=new r(this);return e.embed=!0,e}}fromEmbed(){if(this.embed){let e=new r(this);return e.embed=!1,e}else return this}markdown(){let e=(this.embed?"!":"")+"[["+this.obsidianLink();return this.display?e+="|"+this.display:(e+="|"+EW(this.path),(this.type=="header"||this.type=="block")&&(e+=" > "+this.subpath)),e+="]]",e}obsidianLink(){let e=this.path.replaceAll("|","\\|");return this.type=="header"?e+"#"+this.subpath?.replaceAll("|","\\|"):this.type=="block"?e+"#^"+this.subpath?.replaceAll("|","\\|"):e}fileName(){return EW(this.path).replace(".md","")}},_b=class{constructor(e){he(this,"$widget");this.$widget=e}},H0=class extends _b{constructor(t,n){super("dataview:list-pair");he(this,"key");he(this,"value");this.key=t,this.value=n}markdown(){return`${Sb.toString(this.key)}: ${Sb.toString(this.value)}`}},z0=class extends _b{constructor(t,n){super("dataview:external-link");he(this,"url");he(this,"display");this.url=t,this.display=n}markdown(){return`[${this.display??this.url}](${this.url})`}},kW;(function(r){function e(s,a){return new H0(s,a)}r.listPair=e;function t(s,a){return new z0(s,a)}r.externalLink=t;function n(s){return s.$widget==="dataview:list-pair"}r.isListPair=n;function i(s){return s.$widget==="dataview:external-link"}r.isExternalLink=i;function o(s){return n(s)||i(s)}r.isBuiltin=o})(kW||(kW={}));var kr;(function(r){function e(p){return{type:"variable",name:p}}r.variable=e;function t(p){return{type:"literal",value:p}}r.literal=t;function n(p,f,m){return{type:"binaryop",left:p,op:f,right:m}}r.binaryOp=n;function i(p,f){return{type:"index",object:p,index:f}}r.index=i;function o(p){let f=p.split("."),m=r.variable(f[0]);for(let g=1;g<f.length;g++)m=r.index(m,r.literal(f[g]));return m}r.indexVariable=o;function s(p,f){return{type:"lambda",arguments:p,value:f}}r.lambda=s;function a(p,f){return{type:"function",func:p,arguments:f}}r.func=a;function l(p){return{type:"list",values:p}}r.list=l;function c(p){return{type:"object",values:p}}r.object=c;function u(p){return{type:"negated",child:p}}r.negate=u;function d(p){return p=="<="||p=="<"||p==">"||p==">="||p=="!="||p=="="}r.isCompareOp=d,r.NULL=r.literal(null)})(kr||(kr={}));var Ta;(function(r){function e(u){return{type:"tag",tag:u}}r.tag=e;function t(u){return{type:"csv",path:u}}r.csv=t;function n(u){return{type:"folder",folder:u}}r.folder=n;function i(u,d){return{type:"link",file:u,direction:d?"incoming":"outgoing"}}r.link=i;function o(u,d,p){return{type:"binaryop",left:u,op:d,right:p}}r.binaryOp=o;function s(u,d){return{type:"binaryop",left:u,op:"&",right:d}}r.and=s;function a(u,d){return{type:"binaryop",left:u,op:"|",right:d}}r.or=a;function l(u){return{type:"negate",child:u}}r.negate=l;function c(){return{type:"empty"}}r.empty=c})(Ta||(Ta={}));var SW=new RegExp(tM(),""),W0={year:je.fromObject({years:1}),years:je.fromObject({years:1}),yr:je.fromObject({years:1}),yrs:je.fromObject({years:1}),month:je.fromObject({months:1}),months:je.fromObject({months:1}),mo:je.fromObject({months:1}),mos:je.fromObject({months:1}),week:je.fromObject({weeks:1}),weeks:je.fromObject({weeks:1}),wk:je.fromObject({weeks:1}),wks:je.fromObject({weeks:1}),w:je.fromObject({weeks:1}),day:je.fromObject({days:1}),days:je.fromObject({days:1}),d:je.fromObject({days:1}),hour:je.fromObject({hours:1}),hours:je.fromObject({hours:1}),hr:je.fromObject({hours:1}),hrs:je.fromObject({hours:1}),h:je.fromObject({hours:1}),minute:je.fromObject({minutes:1}),minutes:je.fromObject({minutes:1}),min:je.fromObject({minutes:1}),mins:je.fromObject({minutes:1}),m:je.fromObject({minutes:1}),second:je.fromObject({seconds:1}),seconds:je.fromObject({seconds:1}),sec:je.fromObject({seconds:1}),secs:je.fromObject({seconds:1}),s:je.fromObject({seconds:1})},j0={now:()=>pt.local(),today:()=>pt.local().startOf("day"),yesterday:()=>pt.local().startOf("day").minus(je.fromObject({days:1})),tomorrow:()=>pt.local().startOf("day").plus(je.fromObject({days:1})),sow:()=>pt.local().startOf("week"),"start-of-week":()=>pt.local().startOf("week"),eow:()=>pt.local().endOf("week"),"end-of-week":()=>pt.local().endOf("week"),soy:()=>pt.local().startOf("year"),"start-of-year":()=>pt.local().startOf("year"),eoy:()=>pt.local().endOf("year"),"end-of-year":()=>pt.local().endOf("year"),som:()=>pt.local().startOf("month"),"start-of-month":()=>pt.local().startOf("month"),eom:()=>pt.local().endOf("month"),"end-of-month":()=>pt.local().endOf("month")},G0=["FROM","WHERE","LIMIT","GROUP","FLATTEN"];function use(r){let e=-1;for(;(e=r.indexOf("|",e+1))>=0;)if(!(e>0&&r[e-1]=="\\"))return[r.substring(0,e).replace(/\\\|/g,"|"),r.substring(e+1)];return[r.replace(/\\\|/g,"|"),void 0]}function dse(r){let[e,t]=use(r);return Dk.infer(e,!1,t)}function xb(r,e,t){return $.seqMap(r,$.seq($.optWhitespace,e,$.optWhitespace,r).many(),(n,i)=>{if(i.length==0)return n;let o=t(n,i[0][1],i[0][3]);for(let s=1;s<i.length;s++)o=t(o,i[s][1],i[s][3]);return o})}function pse(r,...e){return $.custom((t,n)=>(i,o)=>{let s=r._(i,o);if(!s.status)return s;for(let a of e){let l=a(s.value)._(i,s.index);if(!l.status)return s;s=l}return s})}var Ws=$.createLanguage({number:r=>$.regexp(/-?[0-9]+(\.[0-9]+)?/).map(e=>Number.parseFloat(e)).desc("number"),string:r=>$.string('"').then($.alt(r.escapeCharacter,$.noneOf('"\\')).atLeast(0).map(e=>e.join(""))).skip($.string('"')).desc("string"),escapeCharacter:r=>$.string("\\").then($.any).map(e=>e==='"'?'"':e==="\\"?"\\":"\\"+e),bool:r=>$.regexp(/true|false|True|False/).map(e=>e.toLowerCase()=="true").desc("boolean ('true' or 'false')"),tag:r=>$.seqMap($.string("#"),$.alt($.regexp(/[^\u2000-\u206F\u2E00-\u2E7F'!"#$%&()*+,.:;<=>?@^`{|}~\[\]\\\s]/).desc("text")).many(),(e,t)=>e+t.join("")).desc("tag ('#hello/stuff')"),identifier:r=>$.seqMap($.alt($.regexp(/\p{Letter}/u),$.regexp(SW).desc("text")),$.alt($.regexp(/[0-9\p{Letter}_-]/u),$.regexp(SW).desc("text")).many(),(e,t)=>e+t.join("")).desc("variable identifier"),link:r=>$.regexp(/\[\[([^\[\]]*?)\]\]/u,1).map(e=>dse(e)).desc("file link"),embedLink:r=>$.seqMap($.string("!").atMost(1),r.link,(e,t)=>(e.length>0&&(t.embed=!0),t)).desc("file link"),binaryPlusMinus:r=>$.regexp(/\+|-/).map(e=>e).desc("'+' or '-'"),binaryMulDiv:r=>$.regexp(/\*|\/|%/).map(e=>e).desc("'*' or '/' or '%'"),binaryCompareOp:r=>$.regexp(/>=|<=|!=|>|<|=/).map(e=>e).desc("'>=' or '<=' or '!=' or '=' or '>' or '<'"),binaryBooleanOp:r=>$.regexp(/and|or|&|\|/i).map(e=>e.toLowerCase()=="and"?"&":e.toLowerCase()=="or"?"|":e).desc("'and' or 'or'"),rootDate:r=>$.seqMap($.regexp(/\d{4}/),$.string("-"),$.regexp(/\d{2}/),(e,t,n)=>pt.fromObject({year:Number.parseInt(e),month:Number.parseInt(n)})).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"),dateShorthand:r=>$.alt(...Object.keys(j0).sort((e,t)=>t.length-e.length).map($.string)),date:r=>pse(r.rootDate,e=>$.seqMap($.string("-"),$.regexp(/\d{2}/),(t,n)=>e.set({day:Number.parseInt(n)})),e=>$.seqMap($.string("T"),$.regexp(/\d{2}/),(t,n)=>e.set({hour:Number.parseInt(n)})),e=>$.seqMap($.string(":"),$.regexp(/\d{2}/),(t,n)=>e.set({minute:Number.parseInt(n)})),e=>$.seqMap($.string(":"),$.regexp(/\d{2}/),(t,n)=>e.set({second:Number.parseInt(n)})),e=>$.alt($.seqMap($.string("."),$.regexp(/\d{3}/),(t,n)=>e.set({millisecond:Number.parseInt(n)})),$.succeed(e)),e=>$.alt($.seqMap($.string("+").or($.string("-")),$.regexp(/\d{1,2}(:\d{2})?/),(t,n)=>e.setZone("UTC"+t+n,{keepLocalTime:!0})),$.seqMap($.string("Z"),()=>e.setZone("utc",{keepLocalTime:!0})),$.seqMap($.string("["),$.regexp(/[0-9A-Za-z+-\/]+/u),$.string("]"),(t,n,i)=>e.setZone(n,{keepLocalTime:!0})))).assert(e=>e.isValid,"valid date").desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"),datePlus:r=>$.alt(r.dateShorthand.map(e=>j0[e]()),r.date).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS] or in shorthand"),durationType:r=>$.alt(...Object.keys(W0).sort((e,t)=>t.length-e.length).map($.string)),duration:r=>$.seqMap(r.number,$.optWhitespace,r.durationType,(e,t,n)=>W0[n].mapUnits(i=>i*e)).sepBy1($.string(",").trim($.optWhitespace).or($.optWhitespace)).map(e=>e.reduce((t,n)=>t.plus(n))).desc("duration like 4hr2min"),rawNull:r=>$.string("null"),tagSource:r=>r.tag.map(e=>Ta.tag(e)),csvSource:r=>$.seqMap($.string("csv(").skip($.optWhitespace),r.string,$.string(")"),(e,t,n)=>Ta.csv(t)),linkIncomingSource:r=>r.link.map(e=>Ta.link(e.path,!0)),linkOutgoingSource:r=>$.seqMap($.string("outgoing(").skip($.optWhitespace),r.link,$.string(")"),(e,t,n)=>Ta.link(t.path,!1)),folderSource:r=>r.string.map(e=>Ta.folder(e)),parensSource:r=>$.seqMap($.string("("),$.optWhitespace,r.source,$.optWhitespace,$.string(")"),(e,t,n,i,o)=>n),negateSource:r=>$.seqMap($.alt($.string("-"),$.string("!")),r.atomSource,(e,t)=>Ta.negate(t)),atomSource:r=>$.alt(r.parensSource,r.negateSource,r.linkOutgoingSource,r.linkIncomingSource,r.folderSource,r.tagSource,r.csvSource),binaryOpSource:r=>xb(r.atomSource,r.binaryBooleanOp.map(e=>e),Ta.binaryOp),source:r=>r.binaryOpSource,variableField:r=>r.identifier.chain(e=>G0.includes(e.toUpperCase())?$.fail("Variable fields cannot be a keyword ("+G0.join(" or ")+")"):$.succeed(kr.variable(e))).desc("variable"),numberField:r=>r.number.map(e=>kr.literal(e)).desc("number"),stringField:r=>r.string.map(e=>kr.literal(e)).desc("string"),boolField:r=>r.bool.map(e=>kr.literal(e)).desc("boolean"),dateField:r=>$.seqMap($.string("date("),$.optWhitespace,r.datePlus,$.optWhitespace,$.string(")"),(e,t,n,i,o)=>kr.literal(n)).desc("date"),durationField:r=>$.seqMap($.string("dur("),$.optWhitespace,r.duration,$.optWhitespace,$.string(")"),(e,t,n,i,o)=>kr.literal(n)).desc("duration"),nullField:r=>r.rawNull.map(e=>kr.NULL),linkField:r=>r.link.map(e=>kr.literal(e)),listField:r=>r.field.sepBy($.string(",").trim($.optWhitespace)).wrap($.string("[").skip($.optWhitespace),$.optWhitespace.then($.string("]"))).map(e=>kr.list(e)).desc("list ('[1, 2, 3]')"),objectField:r=>$.seqMap(r.identifier.or(r.string),$.string(":").trim($.optWhitespace),r.field,(e,t,n)=>({name:e,value:n})).sepBy($.string(",").trim($.optWhitespace)).wrap($.string("{").skip($.optWhitespace),$.optWhitespace.then($.string("}"))).map(e=>{let t={};for(let n of e)t[n.name]=n.value;return kr.object(t)}).desc("object ('{ a: 1, b: 2 }')"),atomInlineField:r=>$.alt(r.date,r.duration.map(e=>S3(e)),r.string,r.tag,r.embedLink,r.bool,r.number,r.rawNull),inlineFieldList:r=>r.atomInlineField.sepBy($.string(",").trim($.optWhitespace).lookahead(r.atomInlineField)),inlineField:r=>$.alt($.seqMap(r.atomInlineField,$.string(",").trim($.optWhitespace),r.inlineFieldList,(e,t,n)=>[e].concat(n)),r.atomInlineField),atomField:r=>$.alt(r.embedLink.map(e=>kr.literal(e)),r.negatedField,r.linkField,r.listField,r.objectField,r.lambdaField,r.parensField,r.boolField,r.numberField,r.stringField,r.dateField,r.durationField,r.nullField,r.variableField),indexField:r=>$.seqMap(r.atomField,$.alt(r.dotPostfix,r.indexPostfix,r.functionPostfix).many(),(e,t)=>{let n=e;for(let i of t)switch(i.type){case"dot":n=kr.index(n,kr.literal(i.field));break;case"index":n=kr.index(n,i.field);break;case"function":n=kr.func(n,i.fields);break}return n}),negatedField:r=>$.seqMap($.string("!"),r.indexField,(e,t)=>kr.negate(t)).desc("negated field"),parensField:r=>$.seqMap($.string("("),$.optWhitespace,r.field,$.optWhitespace,$.string(")"),(e,t,n,i,o)=>n),lambdaField:r=>$.seqMap(r.identifier.sepBy($.string(",").trim($.optWhitespace)).wrap($.string("(").trim($.optWhitespace),$.string(")").trim($.optWhitespace)),$.string("=>").trim($.optWhitespace),r.field,(e,t,n)=>({type:"lambda",arguments:e,value:n})),dotPostfix:r=>$.seqMap($.string("."),r.identifier,(e,t)=>({type:"dot",field:t})),indexPostfix:r=>$.seqMap($.string("["),$.optWhitespace,r.field,$.optWhitespace,$.string("]"),(e,t,n,i,o)=>({type:"index",field:n})),functionPostfix:r=>$.seqMap($.string("("),$.optWhitespace,r.field.sepBy($.string(",").trim($.optWhitespace)),$.optWhitespace,$.string(")"),(e,t,n,i,o)=>({type:"function",fields:n})),binaryMulDivField:r=>xb(r.indexField,r.binaryMulDiv,kr.binaryOp),binaryPlusMinusField:r=>xb(r.binaryMulDivField,r.binaryPlusMinus,kr.binaryOp),binaryCompareField:r=>xb(r.binaryPlusMinusField,r.binaryCompareOp,kr.binaryOp),binaryBooleanField:r=>xb(r.binaryCompareField,r.binaryBooleanOp,kr.binaryOp),binaryOpField:r=>r.binaryBooleanField,field:r=>r.binaryOpField});function fse(r){try{return Ak.success(Ws.field.tryParse(r))}catch(e){return Ak.failure(""+e)}}var Fk;(function(r){function e(n,i){return{name:n,field:i}}r.named=e;function t(n,i){return{field:n,direction:i}}r.sortBy=t})(Fk||(Fk={}));function mse(r){return $.custom((e,t)=>(n,i)=>{let o=r._(n,i);return o.status?Object.assign({},o,{value:[o.value,n.substring(i,o.index)]}):o})}function hse(r){return r.split(/[\r\n]+/).map(e=>e.trim()).join("")}function _W(r,e){return $.eof.map(r).or($.whitespace.then(e))}var _3=$.createLanguage({queryType:r=>$.alt($.regexp(/TABLE|LIST|TASK|CALENDAR/i)).map(e=>e.toLowerCase()).desc("query type ('TABLE', 'LIST', 'TASK', or 'CALENDAR')"),explicitNamedField:r=>$.seqMap(Ws.field.skip($.whitespace),$.regexp(/AS/i).skip($.whitespace),Ws.identifier.or(Ws.string),(e,t,n)=>Fk.named(n,e)),comment:()=>$.Parser((r,e)=>{let t=r.substring(e);if(!t.startsWith("//"))return $.makeFailure(e,"Not a comment");t=t.split(`
`)[0];let n=t.substring(2).trim();return $.makeSuccess(e+t.length,n)}),namedField:r=>$.alt(r.explicitNamedField,mse(Ws.field).map(([e,t])=>Fk.named(hse(t),e))),sortField:r=>$.seqMap(Ws.field.skip($.optWhitespace),$.regexp(/ASCENDING|DESCENDING|ASC|DESC/i).atMost(1),(e,t)=>{let n=t.length==0?"ascending":t[0].toLowerCase();return n=="desc"&&(n="descending"),n=="asc"&&(n="ascending"),{field:e,direction:n}}),headerClause:r=>r.queryType.chain(e=>{switch(e){case"table":return _W(()=>({type:e,fields:[],showId:!0}),$.seqMap($.regexp(/WITHOUT\s+ID/i).skip($.optWhitespace).atMost(1),$.sepBy(r.namedField,$.string(",").trim($.optWhitespace)),(t,n)=>({type:e,fields:n,showId:t.length==0})));case"list":return _W(()=>({type:e,format:void 0,showId:!0}),$.seqMap($.regexp(/WITHOUT\s+ID/i).skip($.optWhitespace).atMost(1),Ws.field.atMost(1),(t,n)=>({type:e,format:n.length==1?n[0]:void 0,showId:t.length==0})));case"task":return $.succeed({type:e});case"calendar":return $.whitespace.then($.seqMap(r.namedField,t=>({type:e,showId:!0,field:t})));default:return $.fail(`Unrecognized query type '${e}'`)}}).desc("TABLE or LIST or TASK or CALENDAR"),fromClause:r=>$.seqMap($.regexp(/FROM/i),$.whitespace,Ws.source,(e,t,n)=>n),whereClause:r=>$.seqMap($.regexp(/WHERE/i),$.whitespace,Ws.field,(e,t,n)=>({type:"where",clause:n})).desc("WHERE <expression>"),sortByClause:r=>$.seqMap($.regexp(/SORT/i),$.whitespace,r.sortField.sepBy1($.string(",").trim($.optWhitespace)),(e,t,n)=>({type:"sort",fields:n})).desc("SORT field [ASC/DESC]"),limitClause:r=>$.seqMap($.regexp(/LIMIT/i),$.whitespace,Ws.field,(e,t,n)=>({type:"limit",amount:n})).desc("LIMIT <value>"),flattenClause:r=>$.seqMap($.regexp(/FLATTEN/i).skip($.whitespace),r.namedField,(e,t)=>({type:"flatten",field:t})).desc("FLATTEN <value> [AS <name>]"),groupByClause:r=>$.seqMap($.regexp(/GROUP BY/i).skip($.whitespace),r.namedField,(e,t)=>({type:"group",field:t})).desc("GROUP BY <value> [AS <name>]"),clause:r=>$.alt(r.fromClause,r.whereClause,r.sortByClause,r.limitClause,r.groupByClause,r.flattenClause),query:r=>$.seqMap(r.headerClause.trim(_0),r.fromClause.trim(_0).atMost(1),r.clause.trim(_0).many(),(e,t,n)=>({header:e,source:t.length==0?Ta.folder(""):t[0],operations:n,settings:eM}))}),_0=$.alt($.whitespace,_3.comment).many().map(r=>r.join("")),gse=r=>r?r.plugins.plugins.dataview?.api:window.DataviewAPI,vse=r=>r.plugins.enabledPlugins.has("dataview");ka.DATE_SHORTHANDS=j0;ka.DURATION_TYPES=W0;ka.EXPRESSION=Ws;ka.KEYWORDS=G0;ka.QUERY_LANGUAGE=_3;ka.getAPI=gse;ka.isPluginEnabled=vse;ka.parseField=fse});function Rk(r){if(!r.includes(",")){let o=r.trim();return o?[o]:[]}let e=[],t="",n=!1;for(let o=0;o<r.length;o++){let s=r[o],a=r[o+1];if(s==="["&&a==="["){n=!0,t+=s;continue}if(s==="]"&&a==="]"){n=!1,t+=s;continue}if(s===","&&!n){let l=t.trim();l&&e.push(l),t="";continue}t+=s}let i=t.trim();return i&&e.push(i),e}var rM=E(()=>{});function Nk(r){return r.replace(/[\\"]/g,"\\$&")}function yse(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function I3(r){return Nk(yse(r))}function D3(r){return typeof r=="object"&&r!==null&&"path"in r&&typeof r.path=="string"}var nM,Fb,F3=E(()=>{nM=z$(A3());Ie();rM();Fb=class{static getDataviewAPI(e){let t=(0,nM.getAPI)(e);return t||(I.logMessage("Dataview plugin is not installed or enabled"),null)}static async getFieldValues(e,t){return this.queryFieldValues(e,t)}static async getFieldValuesWithFilter(e,t,n={}){return this.queryFieldValues(e,t,n)}static async queryFieldValues(e,t,n){let i=new Set,o=this.getDataviewAPI(e);if(!o)return i;try{let a=`field("${Nk(t)}")`,l=[a],c=(n?.folders?.length?n.folders:n?.folder?[n.folder]:[]).map(g=>g.replace(/^\/+|\/+$/g,"")).filter(Boolean);if(c.length>0){let g=c.map(v=>`regexmatch("^${I3(v)}/", file.path)`);l.push(`(${g.join(" OR ")})`)}n?.tags?.length&&n.tags.forEach(g=>{let v=g.startsWith("#")?g:`#${g}`;l.push(`contains(file.tags, "${Nk(v)}")`)}),n?.excludeFolders?.length&&n.excludeFolders.forEach(g=>{let v=g.replace(/^\/+|\/+$/g,"");l.push(`!regexmatch("^${I3(v)}/", file.path)`)}),n?.excludeTags?.length&&n.excludeTags.forEach(g=>{let v=g.startsWith("#")?g:`#${g}`;l.push(`!contains(file.tags, "${Nk(v)}")`)});let u=l.join(" AND "),d=`TABLE ${a} WHERE ${u}`,p=await o.query(d),f=n?.excludeFiles??[],m=g=>{if(f.length===0)return!1;let v=g[0],y=v&&typeof v.path=="string"?v.path:null;if(!y)return!1;let b=y.split("/").pop()??y;return f.some(x=>x===y||x===b)};if(p.successful&&p.value.values)for(let g of p.value.values){if(m(g))continue;let v=g[1];Array.isArray(v)?v.forEach(y=>{y&&typeof y=="string"?i.add(y.trim()):D3(y)?i.add(y.path):y&&typeof y!="object"&&i.add(String(y).trim())}):D3(v)?i.add(v.path):v&&typeof v=="string"?Rk(v).forEach(y=>i.add(y)):v&&typeof v!="object"&&i.add(String(v).trim())}}catch(s){I.logError(new Error(`Failed to query Dataview for field ${t}${n?" with filters":""}: ${s}`))}return i}static isAvailable(e){return(0,nM.getAPI)(e)!==null}}});var Vl,Lk=E(()=>{Vl=class r{constructor(){this.cache=new Map;this.TTL=300*1e3;this.MAX_CACHE_ENTRIES=100;this.MAX_VALUES_PER_ENTRY=1e3;this.cleanupInterval=null;this.revision=0}static getInstance(){return r.instance||(r.instance=new r),r.instance}startAutomaticCleanup(e){if(this.cleanupInterval===null&&typeof window<"u"){let t=window.setInterval(()=>{this.cleanExpired()},6e4);this.cleanupInterval=e(t)}}registerInvalidationListeners(e,t){let n=()=>this.clear();t(e.metadataCache.on("changed",n)),t(e.metadataCache.on("deleted",n)),t(e.vault.on("rename",n))}get(e,t){let n=this.makeKey(e,t),i=this.cache.get(n);return i?Date.now()-i.timestamp>this.TTL?(this.cache.delete(n),null):new Set(i.values):null}set(e,t,n){let i=this.makeKey(e,n),o=new Set;for(let s of t){if(o.size>=this.MAX_VALUES_PER_ENTRY)break;o.add(s)}this.cache.size>=this.MAX_CACHE_ENTRIES&&!this.cache.has(i)&&this.evictOldestEntries(1),this.cache.set(i,{fieldName:e,values:o,timestamp:Date.now()})}getRevision(){return this.revision}setIfRevision(e,t,n,i){return this.revision!==i?!1:(this.set(e,t,n),!0)}evictOldestEntries(e){let t=Array.from(this.cache.entries()).sort(([,n],[,i])=>n.timestamp-i.timestamp).slice(0,e);for(let[n]of t)this.cache.delete(n)}clear(e){if(this.revision++,!e){this.cache.clear();return}for(let[t,n]of this.cache)n.fieldName===e&&this.cache.delete(t)}cleanExpired(){let e=Date.now();for(let[t,n]of this.cache)e-n.timestamp>this.TTL&&this.cache.delete(t)}getStats(){return{size:this.cache.size,maxSize:this.MAX_CACHE_ENTRIES,cleanupInterval:this.cleanupInterval}}destroy(){this.cleanupInterval=null,this.clear()}makeKey(e,t){return JSON.stringify([e,t||null])}}});var Vk,P3=E(()=>{Vk=class{static deduplicate(e,t=!1){let n=new Map;for(let o of e){let s=t?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)=>t?o.localeCompare(s):o.toLowerCase().localeCompare(s.toLowerCase())),{values:i,duplicatesRemoved:e.length-i.length}}}});var Sa,iM=E(()=>{Xe();P3();Sa=class{static processValues(e,t){let n=e.size,i=Array.from(e).filter(l=>!this.isUnresolvedFieldToken(l)),o=Vk.deduplicate(i,t.caseSensitive);i=o.values;let{processedValues:s,hasDefault:a}=this.applyDefaultValues(i,t);return i=s,{values:i,hasDefaultValue:a,duplicatesRemoved:o.duplicatesRemoved,totalProcessed:n}}static isUnresolvedFieldToken(e){return this.unresolvedFieldTokenRegex.test(e.trim())}static applyDefaultValues(e,t){if(!t.defaultValue)return{processedValues:e,hasDefault:!1};let n=t.defaultValue,i=[...e],o=!1,s=a=>t.caseSensitive?a===n:this.normalizeForComparison(a)===this.normalizeForComparison(n);return t.defaultAlways?(i=i.filter(a=>!s(a)),i.unshift(n),o=!0):t.defaultEmpty&&e.length===0?(i=[n],o=!0):!t.defaultEmpty&&!t.defaultAlways&&(i.some(s)||(i.unshift(n),o=!0)),{processedValues:i,hasDefault:o}}static promoteValueToFront(e,t,n=!1){let i=o=>n?o===t:this.normalizeForComparison(o)===this.normalizeForComparison(t);return[t,...e.filter(o=>!i(o))]}static canonicalizeAgainst(e,t,n=!1){if(n)return t;let i=this.normalizeForComparison(t);return e.find(o=>this.normalizeForComparison(o)===i)??t}static normalizeForComparison(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}static getSmartDefaults(e,t){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=e.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(t.length>0){let o=new Map;for(let s of t)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[]}};Sa.unresolvedFieldTokenRegex=new RegExp(`^${cC.source}$`,"i")});var Bl,fh,oM=E(()=>{rM();Bl=class Bl{static parseInlineFields(e,t){let n=new Map,i=this.removeCodeBlocksAndFrontmatter(e,t),o;for(;(o=Bl.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 Rk(a))n.get(s)?.add(l)}}return Bl.INLINE_FIELD_REGEX.lastIndex=0,n}static removeCodeBlocksAndFrontmatter(e,t){return e=e.replace(this.FRONTMATTER_REGEX,""),e=this.filterFencedCodeBlocks(e,t?.includeCodeBlocks),e.replace(this.INLINE_CODE_SPAN_REGEX,"")}static filterFencedCodeBlocks(e,t){if(!e.includes("```"))return e;let n=new Set((t??[]).map(a=>a.trim().toLowerCase()).filter(a=>a.length>0)),i=e.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 u=1;u<s.lines.length;u++)o.push(s.lines[u]);s=null}else s.lines.push(a)}if(s)for(let a of s.lines)o.push(a);return o.join(`
`)}static matchFenceOpen(e){let t=this.FENCE_OPEN_REGEX.exec(this.stripTrailingCarriage(e));return t?{length:t[1].length,info:t[2]}:null}static matchFenceClose(e,t){let n=this.FENCE_CLOSE_REGEX.exec(this.stripTrailingCarriage(e));return n!==null&&n[1].length>=t}static stripTrailingCarriage(e){return e.endsWith("\r")?e.slice(0,-1):e}static getFieldValues(e,t,n){return this.parseInlineFields(e,n).get(t)||new Set}};Bl.INLINE_FIELD_REGEX=/(?:^|[\n\r])(?![ \t]*[-*+][ \t]+\[[ xX]\])([^:\n\r]+?)::[ \t]*(.*)$/gmu,Bl.FRONTMATTER_REGEX=/^---\r?\n[\s\S]*?\r?\n---\r?\n/,Bl.INLINE_CODE_SPAN_REGEX=/`[^`]*`/g,Bl.FENCE_OPEN_REGEX=/^[ \t]*(`{3,})([^`]*)$/,Bl.FENCE_CLOSE_REGEX=/^[ \t]*(`{3,})[ \t]*$/;fh=Bl});function sM(r){let e=[];return r.folder&&e.push(`folder:${r.folder}`),r.folders?.length&&e.push(`folders:${r.folders.join(",")}`),r.tags&&e.push(`tags:${r.tags.join(",")}`),r.inline&&e.push("inline:true"),r.inlineCodeBlocks?.length&&e.push(`inline-code-blocks:${r.inlineCodeBlocks.join(",")}`),r.caseSensitive&&e.push("case-sensitive:true"),r.excludeFolders&&e.push(`exclude-folders:${r.excludeFolders.join(",")}`),r.excludeTags&&e.push(`exclude-tags:${r.excludeTags.join(",")}`),r.excludeFiles&&e.push(`exclude-files:${r.excludeFiles.join(",")}`),r.defaultValue&&e.push(`default:${r.defaultValue}`),r.defaultEmpty&&e.push("default-empty:true"),r.defaultAlways&&e.push("default-always:true"),e.join("|")}async function M3(r,e,t){return(await aM(r,e,t)).values}async function aM(r,e,t){let n=await bse(r,e,t),i=Sa.processValues(n,t);return{values:i.values,hasDefaultValue:i.hasDefaultValue}}async function bse(r,e,t){let n=Vl.getInstance(),i=sM(t),o=n.get(e,i);if(o)return o;let s=n.getRevision(),a=await lM(r,e,t);return n.setIfRevision(e,a,i,s),a}async function lM(r,e,t){let n=e.trim().toLowerCase();if(n==="tags"||n==="tag"){let i=await wse(r,t);if(i.size>0)return i}try{if(!t.inline&&Fb.isAvailable(r)){let i=await Fb.getFieldValuesWithFilter(r,e,t);if(i.size>0)return i}}catch{}return await Ese(r,e,t)}async function wse(r,e){if(!(!!e.folder||!!e.folders?.length||!!e.tags?.length||!!e.excludeFolders?.length||!!e.excludeTags?.length||!!e.excludeFiles?.length)){let n=Cse(r);if(n.size>0)return n}return await xse(r,e)}function Cse(r){let e=new Set;try{let t=r.metadataCache.getTags?.();if(!t)return e;for(let n of Object.keys(t)){let o=(n.startsWith("#")?n.substring(1):n).trim();o&&e.add(o)}}catch{}return e}function Pb(r,e){if(e!=null)for(let t of Array.isArray(e)?e:[e]){let n=String(t).trim();n&&r.add(n)}}async function $3(r,e,t){let n=new Set,i=xi.filterFiles(r.vault.getMarkdownFiles(),e,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 t(a,l)}catch{}return l}));for(let a of s)for(let l of a)n.add(l)}return n}async function xse(r,e){return $3(r,e,(t,n)=>{let i=r.metadataCache.getFileCache(t);Pb(n,i?.frontmatter?.tags),Pb(n,i?.frontmatter?.tag);for(let o of i?.tags??[]){let s=String(o.tag??"").trim().replace(/^#/,"");s&&n.add(s)}})}async function Ese(r,e,t){return $3(r,t,async(n,i)=>{let o=r.metadataCache.getFileCache(n)?.frontmatter?.[e];if(Array.isArray(o)?o.forEach(s=>Pb(i,[s])):typeof o!="object"&&Pb(i,o),t.inline){let s=await r.vault.read(n);Pb(i,[...fh.getFieldValues(s,e,{includeCodeBlocks:t.inlineCodeBlocks})])}})}var Bk=E(()=>{F3();pd();Lk();iM();oM()});function Tse(r,e){let t=e.trim();if(!t||!r)return null;let n=r[t];if(n===void 0){let i=t.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=O3(o);s!==null&&i.push(s)}return i.length>0?i:null}return O3(n)}function qk(r,e,t){if(!e||e.extension!=="md")return null;let n=r.metadataCache.getFileCache(e)?.frontmatter;return Tse(n,t)}function O3(r){if(r==null)return null;let e=typeof r;if(e==="string"||e==="number"||e==="boolean"){let t=String(r).trim();return t.length>0?t:null}return null}var cM=E(()=>{});async function R3({app:r,executor:e,getSourcePath:t},n){let i=e?.promptProvider;try{let{fieldName:o,filters:s,multiSelect:a}=oi.parse(n),l=s.defaultFrom==="active"?qk(r,e?.triggerContext?.activeFile??null,o):null,{values:c,hasDefaultValue:u}=await aM(r,o,s),d=c,p=u,f=s.defaultValue;!a&&typeof l=="string"?(d=Sa.promoteValueToFront(d,l,s.caseSensitive),f=l,p=!0):!a&&Array.isArray(l)&&l.length>0&&I.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 m=a?`Select values for ${o}`:`Enter value for ${o}`;if(p&&f&&(m=a?`Select values for ${o} (default: ${f})`:`Enter value for ${o} (default: ${f})`),a){let g=d;if(d.length===0&&!s.defaultValue){let y=Sa.getSmartDefaults(o,[]);y.length>0&&(g=y)}let v=l===null?void 0:(Array.isArray(l)?l:[l]).map(y=>Sa.canonicalizeAgainst(g,y,s.caseSensitive));return i?await i.suggesterMulti(g,g,{placeholder:m,allowCustomInput:!0,preselected:v&&v.length>0?v:void 0}):await du.Suggest(r,g,g,{placeholder:m,allowCustomValue:!0,...v&&v.length>0?{preselected:v}:{}})}if(d.length===0){let g="No existing values were found in your vault.";if(!s.defaultValue){let v=Sa.getSmartDefaults(o,[]);v.length>0&&(g+=`
Suggested values for ${o}: ${v.slice(0,3).join(", ")}`)}return i?await i.inputPrompt(`Enter value for ${o}`,g):await ar.PromptWithContext(r,`Enter value for ${o}`,g,void 0,t()??void 0,void 0,{allowPeek:!0})}return i?String(await i.suggester(d,d,m,!0)):await Mr.Suggest(r,d,d,{placeholder:m})}catch(o){throw ot(o)?new at("Input cancelled by user"):o}}async function N3({app:r,executor:e,getSourcePath:t},n){let i=e?.promptProvider;try{let o=xi.filterFiles(r.vault.getMarkdownFiles(),n.filter,u=>r.metadataCache.getFileCache(u)),s=n.label??`Select a file from ${n.folderPath}`;if(o.length===0){let u=`No markdown files found in "${n.folderPath}". Type a value or leave empty.`,d=i?await i.inputPrompt(s,u):await ar.Prompt(r,s,u,void 0,void 0,{optional:n.optional||void 0,allowPeek:!0});return n.multiSelect?d?[`${As}${d}`]:[]:d?`${As}${d}`:""}let a=$c(o,u=>r.metadataCache.getFileCache(u)),l=o.map(u=>`${Pc}${u.path}`);if(n.multiSelect)return(i?await i.suggesterMulti(a,l,{placeholder:s,allowCustomInput:n.allowCustomInput}):await du.Suggest(r,a,l,{placeholder:s,allowCustomValue:n.allowCustomInput,...n.optional?{skippable:!0}:{}})).map(d=>l.includes(d)?d:`${As}${d}`);if(i){let u=String(await i.suggester(a,l,s,n.allowCustomInput));return u?l.includes(u)?u:`${As}${u}`:""}if(n.allowCustomInput){let u=new Set(o.map(f=>f.basename.toLowerCase())),d=new Set(a.map(f=>f.toLowerCase())),p=await Mr.Suggest(r,a,l,{placeholder:s,valueExists:f=>u.has(f.toLowerCase())||d.has(f.toLowerCase()),...n.optional?{skippable:!0}:{}});return p?l.includes(p)?p:`${As}${p}`:""}return await Xt.Suggest(r,a,l,s,void 0,n.optional?{skippable:!0}:void 0)??""}catch(o){throw ot(o)?new at("Input cancelled by user"):o}}var L3=E(()=>{Ds();Ol();h0();Zo();hl();pd();Bk();iM();cM();lo();ur();xt();Ie()});function _se(r){return`\\begin{${r}}
\u261A
\\end{${r}}\u261A`}var kse,Sse,V3,uM=E(()=>{kse=["\\!","\\,","\\:","\\>","\\;","\\#","\\$","\\%","\\&","\\","_","{ }","|","^{\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"],Sse=["align","align*","alignat","alignat*","array","Bmatrix","bmatrix","cases","eqnarray","eqnarray*","equation","equation*","gather","gather*","matrix","pmatrix","smallmatrix","subarray","Vmatrix","vmatrix"];V3=[...kse,...Sse.map(_se)]});function Ise(r){if(dM.has(r))return dM.get(r)??null;let e=null;try{e=(0,B3.renderMath)(r,!0)}catch{e=null}return dM.set(r,e),e}function Dse(r){return pM===null&&(pM=new Fc(r,{findAllMatches:!0,threshold:.8})),pM}var B3,Ase,dM,pM,Uk,q3=E(()=>{ks();XC();B3=require("obsidian");uM();_s();Ase=new RegExp(/\\([a-z{}A-Z0-9]*)$/),dM=new Map,pM=null;Uk=class extends xr{constructor(t){super(on().app,t);this.inputEl=t;this.lastInput="";this.symbols=Object.assign([],V3)}getSuggestions(t){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=t.slice(0,n),o=i.lastIndexOf("\\"),s=i.slice(o),a=Ase.exec(s),l=[];a&&(this.lastInput=a[1],l=this.symbols.filter(d=>d.toLowerCase().contains(this.lastInput)));let c=new Set(l);return Dse(this.symbols).search(this.lastInput).map(d=>d.item).filter(d=>c.has(d))}renderSuggestion(t,n){if(t){n.setText(t);let i=Ise(t);i&&n.append(i.cloneNode(!0))}}selectSuggestion(t){if(this.inputEl.selectionStart===null)return;let n=this.inputEl.selectionStart,i=this.lastInput.length,o=this.inputEl.value,s=0,a=t.replace(/\\\\/g,"\\");if(this.inputEl.value=`${o.slice(0,n-i-1)}${a}${o.slice(n)}`,s=n-i+t.length-1,this.inputEl.trigger("input"),this.close(),t.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 Wi,Hk,U3=E(()=>{Wi=require("obsidian");_s();uM();q3();ur();Hk=class r extends Wi.Modal{constructor(){super(on().app);this.didSubmit=!1;this.keybindListener=t=>{(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&this.submit(),t.key==="Tab"&&(t.preventDefault(),this.cursorToGoTo())};this.submitClickCallback=t=>this.submit();this.cancelClickCallback=t=>this.cancel();this.open(),this.display(),this.waitForClose=new Promise((t,n)=>{this.resolvePromise=t,this.rejectPromise=n}),new Uk(this.inputEl),this.inputEl.focus(),this.inputEl.select()}static Prompt(){return new r().waitForClose}display(){this.containerEl.addClass("quickAddModal","qaMathModal"),this.contentEl.empty();let t=this.contentEl.createDiv();t.className="math math-block is-loaded";let n=new Wi.TextAreaComponent(this.contentEl);n.inputEl.setCssStyles({width:"100%",height:"10rem"}),this.inputEl=n.inputEl,n.onChange((0,Wi.debounce)(async o=>await this.mathjaxLoop(t,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,Wi.loadMathJax)()}async mathjaxLoop(t,n){let i=(0,Wi.renderMath)(n,!0);await(0,Wi.finishRenderMath)(),t.empty(),t.append(i)}cursorToGoTo(){if(this.inputEl.value.contains("\u261A")){let t=this.inputEl.value.indexOf("\u261A");this.inputEl.value=this.inputEl.value.replace("\u261A",""),this.inputEl.setSelectionRange(t,t)}}createButton(t,n,i){let o=new Wi.ButtonComponent(t);return o.setButtonText(n).onClick(i),o}createButtonBar(t){let n=t.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 t=this.inputEl.value.replace(/\\n/g,"\\\\n").replace(new RegExp("\u261A","g"),"");this.didSubmit?this.resolvePromise(t):this.rejectPromise(Rr())}submit(){this.didSubmit=!0,this.close()}cancel(){this.close()}onClose(){super.onClose(),this.resolveInput(),this.removeInputListeners()}}});function Mb(r){return r.replace(Fse," ").replace(/\s+/g," ").trim()}function H3(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 z3(r){let e=[],t=!1,n="",i=0;for(let o=0;o<r.length;o++){let s=r[o];if(o===0&&/^---\s*$/.test(s)){let c=o+1;for(;c<r.length&&!/^---\s*$/.test(r[c]);)c++;o=c;continue}if(t){let c=s.match(/^ {0,3}(`{3,}|~{3,})\s*$/);c&&c[1][0]===n&&c[1].length>=i&&(t=!1,n="",i=0);continue}else{let c=s.match(/^ {0,3}(`{3,}|~{3,})/);if(c){t=!0,n=c[1][0],i=c[1].length;continue}}let a=s.match(/^ {0,3}(#{1,6})[ \t]+(.*)$/);if(a){e.push({heading:a[2],level:a[1].length,line:o});continue}let l=s.match(/^ {0,3}(=+|-+)\s*$/);if(l&&o>0){let c=r[o-1],u=e.length>0&&e[e.length-1].line===o-1,d=o<2||!H3(r[o-2]);!u&&d&&H3(c)&&e.push({heading:c.trim(),level:l[1][0]==="="?1:2,line:o-1});continue}}return e}function Pse(r,e){let t=[],n=Mb(r[e].heading);n&&t.push(n);let i=r[e].level;for(let o=e-1;o>=0&&i>1;o--)if(r[o].level<i){i=r[o].level;let s=Mb(r[o].heading);s&&t.unshift(s)}return t}function W3(r,e){if(r.length===0)return null;let t=-1;for(let u=0;u<r.length&&r[u].line<=e;u++)t=u;if(t===-1)return null;let n=Mb(r[t].heading);if(!n)return null;let i=n.toLowerCase();if(!r.some((u,d)=>d!==t&&Mb(u.heading).toLowerCase()===i))return`#${n}`;let s=Pse(r,t);if(s.length<2)return null;let a=s.join("#"),l=a.toLowerCase();return Mse(r).some((u,d)=>d!==t&&u===l)?null:`#${a}`}function Mse(r){let e=new Array(r.length),t=[];for(let n=0;n<r.length;n++){for(;t.length>0&&r[t[t.length-1]].level>=r[n].level;)t.pop();let i=t.length>0?e[t[t.length-1]]:[],o=Mb(r[n].heading);e[n]=o?[...i,o]:i,t.push(n)}return e.map(n=>n.join("#").toLowerCase())}var Fse,j3=E(()=>{Fse=/[!"#$%&()*+,.:;<=>?@^`{|}~/[\]\\\r\n]/g});async function zk(r,e,t,n){return await zE(r,t,n)&&await e.saveSettings?.(),dU(r,t,n)}var fM=E(()=>{Ml()});function bu(r,{logPrefix:e,noticePrefix:t=e,defaultReason:n}){if(!(r instanceof yt))return!1;let i=typeof r.message=="string"&&r.message.trim().length>0?r.message:n;return I.logMessage(`${e}: ${i}`),(!(r instanceof at||typeof r.message=="string"&&r.message.toLowerCase().includes("cancelled by user"))||X.getState().showInputCancellationNotification)&&new G3.Notice(`${t}: ${i}`),!0}var G3,$b=E(()=>{G3=require("obsidian");Ni();ur();dt();Ie()});var Y3={};fw(Y3,{SingleMacroEngine:()=>mM});function Ose(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 $se,mM,K3=E(()=>{Ie();vr();ht();bt();YE();fM();Ob();$b();un();Ni();$se=new Set(["settings","entry","quickadd"]);mM=class{constructor(e,t,n,i,o){this.app=e;this.plugin=t;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(e,t){this.emittedConflictNotice=!1;let{basename:n,memberAccess:i}=dd(e),o=c=>(c??"").trim(),s=nn(this.choices).find(c=>c.type==="Macro"&&o(c.name)===o(n));if(!s){let c=d=>o(d).toLowerCase(),u=nn(this.choices).filter(d=>d.type==="Macro"&&c(d.name)===c(n));if(u.length>1)throw I.logError(`Ambiguous macro reference '${e}'. Multiple choices match when ignoring case.`),new Error(`Ambiguous macro reference '${e}'. Please disambiguate by renaming macros.`);s=u[0]}if(!s)throw I.logError(`macro '${e}' does not exist.`),new Error(`macro '${e}' does not exist.`);let a=new _a(this.app,this.plugin,s,this.choiceExecutor,this.variables,void 0,t?.label);if(i?.length){let c=await this.tryExecuteExport(a,s,i);if(this.ensureNotAborted(),c.executed)return this.formatResult(c.result)}await a.run(),this.ensureNotAborted();let l=a.getOutput();if(i?.length){let c=this.resolveMemberAccess(l,i);c.found||I.logWarning(`Macro '${s.name}' was asked for member '${i.join("::")}', but it has no user script exporting it; the result is empty.`),l=c.value}return typeof l=="function"?l=await l():l&&typeof l=="object"&&(l=JSON.stringify(l)),Ose(l)}getVariables(){return this.variables}async tryExecuteExport(e,t,n){let i=Ht(t.macro?.commands);if(!i.length)return{executed:!1};let o=i.map((c,u)=>({command:c,index:u})).filter(c=>qr(c.command)&&c.command.type==="UserScript");if(o.length===0)return{executed:!1};let s=await this.selectUserScriptCandidate(t,o,n),a=s.candidate.command.id,l=i.slice(0,s.candidate.index);try{l.length&&(await e.runSubset(l),this.ensureNotAborted());let c=t.macro?.commands,u=zy(c)?c:i,d;a!==void 0?d=u.findIndex(w=>qr(w)&&w.id===a&&w.type==="UserScript"):d=s.candidate.index;let p=d>=0?u[d]:void 0;if(!p||p.type!=="UserScript")throw new yt(`Could not resolve the member-access script for '${t.name}'.`);let f=p;f.settings||(f.settings={});let m=s.candidate.exportsRef!==void 0?s.candidate.exportsRef:await Lo(f,this.app);if(m==null)throw new yt(`Macro '${t.name}' could not load '${f.name}' for member access.`);let g=typeof m=="object"||typeof m=="function"?m.settings:void 0;g&&typeof g=="object"&&Em(f.settings,g);let v=s.candidate.resolvedMember??this.resolveMemberAccess(m,s.memberAccess);if(!v.found)throw new yt(`Macro '${t.name}' routes member access to '${f.name}', but that script does not export '${s.memberAccess.join("::")}'.`);let y=u.slice(d+1),b=f.settings;typeof v.value=="function"&&(b=await zk(this.app,this.plugin,f,g&&typeof g=="object"?g:void 0));let x=await this.executeResolvedMember(v.value,e,b);return this.ensureNotAborted(),e.setOutput(x),this.syncVariablesFromParams(e),y.length&&(await e.runSubset(y),this.ensureNotAborted()),{executed:!0,result:x}}catch(c){throw bu(c,{logPrefix:"Macro execution aborted",noticePrefix:"Macro execution aborted",defaultReason:"Macro execution aborted"})&&this.choiceExecutor.signalAbort?.(c),c}}resolveMemberAccess(e,t){let n=e;for(let i of t){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(e,t,n){return typeof e=="function"?await e(t.params,n):e}async selectUserScriptCandidate(e,t,n){if(t.length===1)return{candidate:{command:t[0].command,index:t[0].index},memberAccess:n};let i=this.resolveScriptSelector(e,t,n);if(i)return{candidate:{command:i.command,index:i.index},memberAccess:i.memberAccess};let o=[];for(let l of t){let c=await Lo(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 yt(`Macro '${e.name}' could not find '${n.join("::")}' in any user script.`);if($se.has(n[0])){let l=s[0];return this.warnReservedKeyConflict(e,n,l,s),{candidate:l,memberAccess:n}}let a=s.map(l=>`'${l.command.name}'`).join(", ");throw new yt(`Macro '${e.name}' has multiple user scripts exporting '${n.join("::")}': ${a}. Disambiguate with '{{MACRO:${e.name}::<Script Name>::${n.join("::")}}}'.`)}warnReservedKeyConflict(e,t,n,i){if(this.emittedConflictNotice)return;this.emittedConflictNotice=!0;let o=i.map(s=>`'${s.command.name}'`).join(", ");I.logWarning(`Macro '${e.name}': multiple user scripts export '${t.join("::")}' (${o}); using '${n.command.name}'. Disambiguate with '{{MACRO:${e.name}::<Script Name>::${t.join("::")}}}'.`)}resolveScriptSelector(e,t,n){if(n.length<2)return null;let i=n[0]?.trim(),o=t.filter(s=>s.command.name.trim()===i);if(o.length===0)return null;if(o.length>1)throw new yt(`Macro '${e.name}' has multiple user scripts named '${i}'. Rename one of them before using '{{MACRO:${e.name}::${i}::${n.slice(1).join("::")}}}'.`);return{command:o[0].command,index:o[0].index,memberAccess:n.slice(1)}}syncVariablesFromParams(e){Object.keys(e.params.variables).forEach(t=>{this.choiceExecutor.variables.set(t,e.params.variables[t])})}formatResult(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return e.toString();if(typeof e=="object")try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}return String(e)}ensureNotAborted(){let e=this.choiceExecutor.consumeAbortSignal?.();if(e)throw e}}});function ql(r){let e=(0,X3.getFrontMatterInfo)(r);return e.exists?e.contentStart:0}function Nse(r,e){let t=ql(r);if(t===0)return 0;if(Q3.test(e))return t;let n=Q3.exec(r.slice(t));return n?t+n[0].length:t}function op(r,e){if(e.length===0)return{content:r,insertedStartOffset:null,insertedEndOffset:null};let t=Nse(r,e),n=r.slice(0,t),i=r.slice(t),o=n.length>0&&!n.endsWith(`
`)&&!Rse.test(e)?`
`:"",s=i.length>0&&!e.endsWith(`
`)?`
`:"",a=n.length+o.length,l=a+e.length;return{content:`${n}${o}${e}${s}${i}`,insertedStartOffset:a,insertedEndOffset:l}}function Z3(r,e){return op(r,e).content}var X3,Q3,Rse,wu=E(()=>{X3=require("obsidian"),Q3=/^[^\S\r\n]*\r?\n/,Rse=/^\r?\n/});function Rb(r){let e=ql(r),t=/\{\{CURSOR\}\}/i.exec(r.slice(e));return{content:zn(r),offsets:t?[zn(r.slice(0,e)).length+t.index]:[]}}function hM(r,e){if(r.content===e)return r;let t=ql(r.content),n=ql(e);return r.offsets.some(i=>i<t)||r.content.slice(t)!==e.slice(n)?null:{content:e,offsets:r.offsets.map(i=>i+n-t)}}var gM=E(()=>{wl();wu()});var Nb,mh,vM=E(()=>{Nb=require("obsidian");Xe();Ie();ht();la();mh=class{constructor(e){this.app=e}async createFolder(e){await this.app.vault.adapter.exists(e)||await this.app.vault.createFolder(e)}stripLeadingSlash(e){return e.replace(/^\/+/,"")}normalizeMarkdownFilePath(e,t){let n=this.stripLeadingSlash(e),i=n?`${n}/`:"",o=this.stripLeadingSlash(t).replace(Nt,"");return`${i}${o}.md`}async fileExists(e){return await this.app.vault.adapter.exists(e)}getFileByPath(e){let t=this.app.vault.getAbstractFileByPath(e);if(!t)throw I.logError(`${e} not found`),new Error(`${e} not found`);if(t instanceof Nb.TFolder)throw I.logError(`${e} found but it's a folder`),new Error(`${e} found but it's a folder`);if(!(t instanceof Nb.TFile))throw new Error(`${e} is not a file`);return t}async createFileWithInput(e,t,n={}){if(Dr(e))throw new Error(`Refusing to create a file outside the vault: "${e}".`);let i=e.match(/(.*)[/\\]/),o="";i&&(o=i[1]);let s=this.app.vault.getAbstractFileByPath(o);(!s||!(s instanceof Nb.TFolder))&&await this.createFolder(o);let a=()=>this.app.vault.create(e,t);return n.suppressTemplaterOnCreate&&e.toLowerCase().endsWith(".md")?await OA(this.app,e,a):await a()}}});async function wo(r,e){try{return r.promptProvider?await e.remote(r.promptProvider):r.interactive===!1?await e.headless():await e.app()}catch(t){throw ot(t)?new at("Input cancelled by user"):t}}var sp=E(()=>{ur();xt()});async function Co(r,e){let t=e.items.map((s,a)=>`${Lse}${a}`),n=await r.suggester(e.items.map(s=>s.title),t,e.placeholder,e.allowCustomInput??!1),i=n==null?"":String(n),o=t.indexOf(i);if(o!==-1)return e.items[o].value;if(i==="")throw new at("Input cancelled by user");if(e.allowCustomInput)return i;throw new Error(`A reply to ${e.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 Lse,ap=E(()=>{ur();Lse="\0qa-eng:"});function yM(r){let e=r.map(n=>n||"/");return`Folder must be under: ${e.length>3?`${e.slice(0,3).join(", ")}...`:e.join(", ")}`}var Wk,Vse,Aa,jk,J3=E(()=>{Wk=require("obsidian");vM();Zo();Ol();wv();Ni();Yn();sp();ap();Vse=3,Aa=class extends Error{constructor(e){super(e),this.name="InvalidFolderPathError"}},jk=class extends mh{async getOrCreateFolder(e,t){let n=this.buildFolderSelectionContext(e,{...t,topItems:e.length>0?[]:t.topItems??[]});if(!this.shouldPromptForFolder(n))return await this.handleSingleSelection(n);let i=this.buildFolderSelectionContext(e,t),o=await this.promptUntilAllowed(i,t.executor);return o.isEmpty?"":o.resolved}buildFolderSelectionContext(e,t){let n=t.allowCreate??!1,i=t.allowedRoots?.map(s=>this.normalizeFolderPath(s))??[];return{...this.buildFolderSuggestions(e,t.topItems??[],i.length>0?i:void 0),allowCreate:n,allowedRoots:i,placeholder:t.placeholder}}shouldPromptForFolder(e){return e.items.length>1||e.allowCreate&&e.items.length===0}async promptForFolder(e,t){let n=e.placeholder??"Choose a folder or type to create one";return String(await wo(t,{remote:i=>Co(i,{items:e.items.map((o,s)=>({value:o,title:e.displayItems[s]??o})),placeholder:n,allowCustomInput:e.allowCreate,what:"the folder chooser"}),headless:()=>{throw new ye("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:()=>e.allowCreate?Mr.Suggest(this.app,e.displayItems,e.items,{placeholder:n,renderItem:(i,o)=>{this.renderFolderSuggestion(i,o,e.canonicalByNormalized,e.displayByNormalized)}}):Xt.Suggest(this.app,e.displayItems,e.items,e.placeholder)}))}async resolveSelection(e,t){let n=this.normalizeFolderPath(e),i=n.length===0,o=t.canonicalByNormalized.get(n),s=o??n,a=i?!1:o!==void 0||await this.app.vault.adapter.exists(s),l=t.allowedRoots.length===0?!0:this.isPathAllowed(i?"":s,t.allowedRoots);return{raw:e,normalized:n,resolved:s,exists:a,isAllowed:l,isEmpty:i}}async promptUntilAllowed(e,t){let n=t.promptProvider?Vse:0,i=null;for(;;){if(t.promptProvider&&n--<=0)throw new ye(i??yM(e.allowedRoots));let o=await this.promptForFolder(e,t),s=await this.resolveSelection(o,e);if(!s.isAllowed){i=yM(e.allowedRoots),this.showFolderNotAllowedNotice(e.allowedRoots);continue}if(s.isEmpty)return s;try{this.validateFolderPath(s.resolved)}catch(a){if(a instanceof Aa){i=a.message,new Wk.Notice(a.message);continue}throw a}return await this.ensureFolderExists(s),s}}async ensureFolderExists(e){e.isEmpty||e.exists||await this.createFolder(e.resolved)}async handleSingleSelection(e){let t=e.items[0]??"",n=await this.resolveSelection(t,e);if(n.isEmpty)return"";if(!n.isAllowed)throw this.showFolderNotAllowedNotice(e.allowedRoots),new yt("Selected folder not allowed.");if(n.resolved)try{this.validateFolderPath(n.resolved)}catch(i){if(i instanceof Aa)return new Wk.Notice(i.message),"";throw i}return await this.ensureFolderExists(n),n.resolved}normalizeFolderPath(e){return e.trim().replace(/^\/+/,"").replace(/\/+$/,"")}validateFolderPath(e){let t=e.trim();if(!t)return;let n=t.split("/");for(let i of n)this.validateFolderSegment(i)}validateFolderSegment(e){if(!e)throw new Aa("Folder name cannot be empty.");if(e==="."||e==="..")throw new Aa("Folder name cannot be '.' or '..'.");if(vv.test(e))throw new Aa("Folder name cannot contain control characters.");if(yv.test(e))throw new Aa('Folder name cannot contain any of the following characters: \\ / : * ? " < > |');if(bv.test(e))throw new Aa("Folder name cannot end with a space or a period.");let t=e.split(".")[0]??"";if(t&&kd(t))throw new Aa("Folder name cannot be a reserved name like CON, PRN, AUX, NUL, COM1-9, or LPT1-9.")}isPathAllowed(e,t){let n=this.normalizeFolderPath(e);for(let i of t)if(!i||n===i||n.startsWith(`${i}/`))return!0;return!1}showFolderNotAllowedNotice(e){new Wk.Notice(yM(e))}buildFolderSuggestions(e,t,n){let i=[],o=[],s=new Map,a=new Map,l=(c,u)=>{let d=this.normalizeFolderPath(c);s.has(d)||n&&n.length>0&&!this.isPathAllowed(d,n)||(i.push(c),o.push(u??c),s.set(d,c),u&&a.set(d,u))};for(let c of t)l(c.path,c.label);for(let c of e)l(c);return{items:i,displayItems:o,canonicalByNormalized:s,displayByNormalized:a}}renderFolderSuggestion(e,t,n,i){t.empty(),t.classList.add("mod-complex");let o=this.normalizeFolderPath(e),s=i.get(o),a=e||"/",l=n.has(o),c="";s==="<current folder>"?c="Current folder":l||(c="Create folder"),t.createDiv("suggestion-content").createDiv("suggestion-title").createSpan({text:a}),c&&t.createDiv("suggestion-aux").createEl("kbd",{cls:"suggestion-hotkey",text:c})}}});function qse(r){let e=[],t=[];for(let[n,i]of r){let o=wM(n,i,new Set,0);e.push(...o.warnings),t.push(...o.errors)}return{isValid:t.length===0,warnings:e,errors:t}}function wM(r,e,t,n){let i=[],o=[];if(typeof e=="function")return o.push(`Variable "${r}" contains a function, which cannot be serialized to YAML`),{warnings:i,errors:o};if(typeof e=="symbol")return o.push(`Variable "${r}" contains a symbol, which cannot be serialized to YAML`),{warnings:i,errors:o};if(typeof e=="bigint")return i.push(`Variable "${r}" contains a BigInt, which will be converted to a string`),{warnings:i,errors:o};if(e==null)return{warnings:i,errors:o};if(typeof e!="object")return{warnings:i,errors:o};if(t.has(e))return o.push(`Variable "${r}" contains a circular reference`),{warnings:i,errors:o};if(n>=bM.MAX_NESTING_DEPTH)return o.push(`Variable "${r}" exceeds maximum nesting depth of ${bM.MAX_NESTING_DEPTH}`),{warnings:i,errors:o};t.add(e);try{if(Array.isArray(e))for(let s=0;s<e.length;s++){let a=wM(`${r}[${s}]`,e[s],t,n+1);i.push(...a.warnings),o.push(...a.errors)}else for(let[s,a]of Object.entries(e)){let l=wM(`${r}.${s}`,a,t,n+1);i.push(...l.warnings),o.push(...l.errors)}}finally{t.delete(e)}return{warnings:i,errors:o}}function hh(r,e){return Bse.includes(r.extension)&&e.size>0}async function gh(r,e,t){let n=qse(t);if(n.warnings.length>0)for(let i of n.warnings)I.logWarning(`Structured variable validation warning: ${i}`);if(!n.isValid){let i=n.errors.join("; ");I.logError(`Cannot post-process front matter for file ${e.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 ${bM.MAX_NESTING_DEPTH}, or contain unsupported types (functions, symbols).`);return}try{I.logMessage(`Post-processing front matter for ${e.path} with ${t.size} structured variables`),I.logMessage(`Variable types: ${Array.from(t.entries()).map(([i,o])=>`${i}:${typeof o}`).join(", ")}`),await r.fileManager.processFrontMatter(e,i=>{for(let[o,s]of t){let a=o.includes(co.PATH_SEPARATOR)?o.split(co.PATH_SEPARATOR):[o],l=Af(s);Lb(i,a,l)}}),I.logMessage(`Successfully post-processed front matter for ${e.path}`)}catch(i){I.logError(`Failed to post-process front matter for file ${e.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 CM(r){return r.some((e,t)=>e==="__proto__"?!0:!(t===r.length-1)&&Use.has(e))}function Lb(r,e,t){if(e.length===0)return;if(CM(e)){I.logWarning(`Skipping front matter assignment for unsafe key path "${e.join(".")}" to avoid prototype pollution.`);return}let n=r;for(let i=0;i<e.length-1;i++){let o=e[i],s=n[o];(typeof s!="object"||s===null||Array.isArray(s))&&(n[o]={}),n=n[o]}n[e[e.length-1]]=t}var bM,Bse,Use,Gk=E(()=>{Ie();If();Sv();bM={MAX_NESTING_DEPTH:10},Bse=["md"];Use=new Set(["prototype","constructor"])});function Ia(r){return((0,xM.normalizePath)(r).split("/").pop()??"").replace(/\.(md|canvas|base)$/i,"")}function Ai(r){let e=(0,xM.normalizePath)(r),t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}var xM,Cu=E(()=>{xM=require("obsidian")});function Vb(r){let e=Md(r);if(e.length!==0)throw new ye(aV(e,r))}function ej(r){return Md(r).length===0}var Yk=E(()=>{Yn();da()});function EM(r){return r instanceof yt||!!r&&typeof r=="object"&&"name"in r&&r.name==="MacroAbortError"}var tj,xu,Kk=E(()=>{gM();wl();wu();Bg();J3();Gk();lp();tj=require("obsidian");ht();Xe();xt();da();la();Cu();Ni();Ie();Yk();xu=class extends jk{constructor(t,n,i,o){super(t);this.plugin=n;this.cursorPlacement=null;this.templaterCursorHandled=!1;this.lastTemplateFileFailure=null;this.templater=yC(t),this.formatter=new ji(t,n,i),o&&this.formatter.setTemplateInclusionState(o)}hasTemplaterHandledCursor(){return this.templaterCursorHandled}async finishTemplateContent(t){if(this.cursorPlacement=null,t.extension!=="md")return;let n=No(this.app,t),i=null;if(n){let o=n.editor.getValue();i=Rb(o);let s=[...o.matchAll(/\{\{CURSOR\}\}/gi)].map(a=>({from:n.editor.offsetToPos(a.index),to:n.editor.offsetToPos(a.index+a[0].length),text:""}));s.length>0&&(n.editor.transaction({changes:s}),await n.save())}else await this.app.vault.process(t,o=>(i=Rb(o),i.content));this.cursorPlacement=i,this.cursorPlacement?.offsets.length===0&&(this.cursorPlacement=null)}getCursorPlacement(){return this.cursorPlacement}placeCursor(t,n){let i=No(this.app,t)?.editor;if(this.cursorPlacement&&i)for(let o of[this.cursorPlacement,n]){if(!o)continue;let s=hM(o,i.getValue())??o;if(Vg(this.app,t,s.offsets,s.content))return}}async rebaseCursorAfterFileChanges(t){if(this.cursorPlacement)try{this.cursorPlacement=hM(this.cursorPlacement,await this.app.vault.read(t))}catch{this.cursorPlacement=null,I.logMessage(`Unable to verify cursor position in '${t.path}'.`)}}stripDuplicateFolderPrefix(t,n){let i=this.stripLeadingSlash(n),o=this.stripLeadingSlash(t);return i?o.startsWith(`${i}/`)?{fileName:o.slice(i.length+1),strippedPrefix:!0}:{fileName:o,strippedPrefix:!1}:{fileName:o,strippedPrefix:!1}}shouldTreatFormattedNameAsVaultRelativePath(t,n,i){if(i||n)return!1;let o=t.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 tj.TFolder:!1}getTemplateExtension(t){return cr.test(t)?".canvas":wn.test(t)?".base":".md"}normalizeTemplateFilePath(t,n,i){let o=this.stripLeadingSlash(t),s=o?`${o}/`:"",a=this.getTemplateExtension(i),l=Wn(this.stripLeadingSlash(n),"File name"),c=Wn(l.replace(Nt,"").replace(cr,"").replace(wn,""),"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 d=`${s}${c}${a}`;if(Dr(d))throw new Error(`Refusing to build a file path outside the vault: "${d}".`);return d}noteTemplateFileFailure(t,n){this.lastTemplateFileFailure=t instanceof Error&&t.message?t.message:n}setTemplateDestination(t,n){this.formatter.setTitle(n),this.formatter.setTargetFolderPath(Ai(t)),this.formatter.setPromptRunContext({destination:t,destinationKind:"file"})}async prepareTemplateBody(t,n,i,o){this.setTemplateDestination(n,i);let s=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.withPromptScope("noteBody",t,()=>n.toLowerCase().endsWith(".md")?this.formatter.formatTemplateContent(t):this.formatter.formatFileContent(t))),a=this.formatter.getAndClearTemplatePropertyVars();I.logMessage(`TemplateEngine.${o}: Collected ${a.size} template property variables for ${n}`),a.size>0&&I.logMessage(`Variables: ${Array.from(a.keys()).join(", ")}`),this.cursorPlacement=null,this.templaterCursorHandled=!1;let l=ql(s);return{content:n.toLowerCase().endsWith(".md")?zn(s.slice(0,l))+s.slice(l):zn(s),variables:a}}async createFileWithTemplate(t,n){this.lastTemplateFileFailure=null,Vb(t);try{let i=await this.getTemplateContent(n),{content:o,variables:s}=await this.prepareTemplateBody(i,t,Ia(t),"createFileWithTemplate"),a=t.toLowerCase().endsWith(".md"),l=await this.createFileWithInput(t,o,{suppressTemplaterOnCreate:a}),c=!1;try{hh(l,s)&&await gh(this.app,l,s),this.templaterCursorHandled=await yc(this.app,l),c=!0}finally{await this.finishTemplateContent(l).catch(u=>{if(c)throw u;I.logWarning(`Unable to clean cursor markers in '${l.path}': ${String(u)}`)})}return l}catch(i){if(EM(i))throw i;return this.noteTemplateFileFailure(i,`Could not create file with template at ${t}`),Ze(i,`Could not create file with template at ${t}`),null}}setLinkToCurrentFileBehavior(t){this.formatter.setLinkToCurrentFileBehavior(t)}setTargetFolderPath(t){this.formatter.setTargetFolderPath(t)}setPromptRunContext(t){this.formatter.setPromptRunContext(t)}async resolveTemplateSourcePath(t){return this.formatter.formatTemplateFilePath(t)}async overwriteFileWithTemplate(t,n){this.lastTemplateFileFailure=null;try{let i=await this.getTemplateContent(n),{content:o,variables:s}=await this.prepareTemplateBody(i,t.path,t.basename,"overwriteFileWithTemplate");await this.app.vault.modify(t,o);let a=!1;try{hh(t,s)&&await gh(this.app,t,s),this.templaterCursorHandled=await yc(this.app,t),a=!0}finally{await this.finishTemplateContent(t).catch(l=>{if(a)throw l;I.logWarning(`Unable to clean cursor markers in '${t.path}': ${String(l)}`)})}return t}catch(i){if(EM(i))throw i;return this.noteTemplateFileFailure(i,"Could not overwrite file with template"),Ze(i,"Could not overwrite file with template"),null}}async appendToFileWithTemplate(t,n,i){this.lastTemplateFileFailure=null;try{let o=await this.getTemplateContent(n);this.setTemplateDestination(t.path,t.basename);let s=await this.formatter.withPromptScope("noteBody",o,()=>this.formatter.formatFileContent(o));t.extension==="md"&&(s=await il(this.app,s,t));let a=await this.app.vault.cachedRead(t),l=i==="top"?`${s}
${a}`:`${a}
${s}`;return await this.app.vault.modify(t,l),t}catch(o){if(EM(o))throw o;return this.noteTemplateFileFailure(o,"Could not append to file with template"),Ze(o,"Could not append to file with template"),null}}async getTemplateContent(t){let n=Vn(this.app,t);if(!n)throw new Error(`Template file not found at path "${t}".`);return await this.app.vault.cachedRead(n)}}});var rj={};fw(rj,{SingleTemplateEngine:()=>vh});var vh,TM=E(()=>{Kk();Ie();Cu();vh=class extends xu{constructor(t,n,i,o,s){super(t,n,o,s);this.templatePath=i;this.promptScope="noteBody";this.preserveCursorMarkers=!1}setPreserveCursorMarkers(t){this.preserveCursorMarkers=t}setPromptScope(t){this.promptScope=t}setDestinationPath(t){this.formatter.setTitle(Ia(t)),this.formatter.setTargetFolderPath(Ai(t))}async run(){let t=await this.resolveTemplateSourcePath(this.templatePath),n=await this.getTemplateContent(t);return n||I.logError(`Template ${t} not found.`),n=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.withPromptScope(this.promptScope,n,()=>this.preserveCursorMarkers?this.formatter.formatTemplateContent(n):this.formatter.formatFileContent(n))),n}getAndClearTemplatePropertyVars(){return this.formatter.getAndClearTemplatePropertyVars()}}});var nj={};fw(nj,{SingleInlineScriptEngine:()=>kM});var kM,ij=E(()=>{Ob();kM=class extends _a{constructor(e,t,n,i){super(e,t,null,n,i)}async runAndGetOutput(e){let t=Object.getPrototypeOf(async function(){}).constructor;return await new t(e).bind(this.params,this).call()}}});var oj,ji,lp=E(()=>{wl();Qz();L3();$v();oj=require("obsidian");Xe();Zo();f0();U3();Ld();hl();lo();uo();Bk();ys();Pd();Sf();j3();ur();Yn();xt();ji=class extends Lc{constructor(t,n,i,o){super(t);this.app=t;this.plugin=n;this.choiceExecutor=i;this.contentValuePromptsAcceptImagePaste=!1;this.preserveTemplateCursorMarkers=!1;this.skipPropertyExpansion=!1;this.dateParser=o||Qo,i&&(this.variables=i?.variables)}runClocks(){return this.choiceExecutor?.clocks??this.clocks}async format(t){let n=t;return n=await this.replaceInlineJavascriptInString(n),n=await this.replaceMacrosInString(n),n=await this.replaceTemplateInString(n),n=await this.replaceGlobalVarInString(n),this.formatScalarTokens(n)}async formatScalarTokens(t){let n=t;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.skipPropertyExpansion||(n=this.replacePropertyInString(n)),this.promptScope==="captureText"||this.promptScope==="noteBody"&&this.preserveTemplateCursorMarkers?n:zn(n)}async replaceGlobalVarInString(t){return Bc(t,this.plugin?.settings?.globalVariables)}async formatFileName(t,n="generic"){if(Ro.test(t))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,t,()=>this.format(t));if(Ro.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"}),i}async formatPropertyName(t){return await this.withPromptScope("propertyName",t,async()=>this.replaceCurrentFileTokensInString(await this.format(t),{links:!0,fileName:!0,folder:!0,activeFolder:"content",title:!0}))}async formatPropertyValue(t){let n=await this.preserveSingleTokenValue(t,()=>this.withPromptScope("propertyValue",t,async()=>{this.skipPropertyExpansion=!0;let i;try{i=await this.format(t)}finally{this.skipPropertyExpansion=!1}return i=this.replaceCurrentFileTokensInString(i,{links:!0,fileName:!0,folder:!0,activeFolder:"content",title:!0}),this.replacePropertyInString(i)}));return typeof n=="string"?zn(n):Array.isArray(n)?n.map(i=>typeof i=="string"?zn(i):i):n}async formatTemplateContent(t){return this.formatContentWithCursorMarkers(t,!0)}async formatFileContent(t){return this.formatContentWithCursorMarkers(t,!1)}async formatContentWithCursorMarkers(t,n){let i=t,o=this.preserveTemplateCursorMarkers;this.preserveTemplateCursorMarkers=n;let s=this.contentValuePromptsAcceptImagePaste;this.contentValuePromptsAcceptImagePaste=!xx(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}),i}async formatFolderPath(t){if(Ro.test(t))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",t,()=>this.format(t));if(Ro.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.");return this.replaceCurrentFileTokensInString(n,{folder:!0,activeFolder:"path"}).replace(/^\/+/,"")}async formatTemplateFilePath(t){if(Ro.test(t))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=t;if(n=await this.replaceGlobalVarInString(n),Ro.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",t,()=>this.formatScalarTokens(n)),n.trim()}async formatLocationString(t){let n=await this.withPromptScope("lineTarget",t,()=>this.format(t));return n=this.replaceCurrentFileTokensInString(n,{links:!0,fileName:!0,title:!0}),n}getCurrentFileLink(){let t=this.app.workspace.getActiveFile();return t?this.app.fileManager.generateMarkdownLink(t,""):null}getCurrentFileName(){let t=this.app.workspace.getActiveFile();return t?t.basename:null}getCurrentFolderPath(){let t=this.app.workspace.getActiveFile();if(!t)return null;let n=t.parent?.path??"";return n==="/"?"":n}getCurrentFileLinkToSection(){let t=this.app.workspace.getActiveFile();if(!t)return null;let n=this.getLinkSourcePath()??"",i=null;try{i=this.getActiveHeadingSubpath(t)}catch{i=null}return i?this.app.fileManager.generateMarkdownLink(t,n,i):this.app.fileManager.generateMarkdownLink(t,n)}getActiveHeadingSubpath(t){let n=this.app.workspace.getActiveViewOfType(oj.MarkdownView);if(!n||n.file?.path!==t.path||n.getMode()==="preview")return null;let i=n.editor,o=i?.getCursor();if(!i||!o)return null;let s=z3(i.getValue().split(/\r?\n/));return W3(s,o.line)}getVariableValue(t){return this.variables.get(t)??""}shouldUseSelectionForValue(){return!0}async getSelectedTextForValue(){return await this.getSelectedText()}assertInteractivePrompt(t){if(this.choiceExecutor?.interactive===!1)throw new ye(`This run is non-interactive but a value for ${t} was not provided up front. Pass it (e.g. a value- flag) or re-run with the ui flag.`)}describeAnonymousValuePrompt(){let t=Tx(this.promptScope,this.promptScopeSoleValue),n=t.title??(this.promptRunContext?.choiceName?.trim()||"Enter value"),i=Ex(this.promptScope);return{title:n,placeholder:t.placeholder,contextLine:kf(this.promptRunContext,n,{showDestination:i}),contextLineFull:kf(this.promptRunContext,n,{elide:!1,showDestination:i})}}async promptForValue(t){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.valuePromptContext.description??this.describeAnonymousValuePrompt().title,!1)),this.value;try{return this.value=await Xt.Suggest(this.app,["true","false"],["true","false"],this.valuePromptContext.description??this.describeAnonymousValuePrompt().title,void 0,this.valuePromptContext.optional?{skippable:!0}:void 0),this.value}catch(s){throw ot(s)?new at("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 Qd().factory(this.valuePromptContext?.inputTypeOverride),a=this.valuePromptContext?.defaultValue,l=this.valuePromptContext?.description,c=this.buildInputPromptOptions(this.valuePromptContext,n.contextLine,n.contextLineFull),u=this.valuePromptContext?.placeholder??n.placeholder;o?this.value=await s.PromptWithContext(this.app,n.title,u,a,o,l,c):this.value=await s.Prompt(this.app,n.title,u,a,l,c)}catch(o){throw ot(o)?new at("Input cancelled by user"):o}}return this.value}normalizeSelectedTextForPrompt(t){let n=this.valuePromptContext;if(n?.inputTypeOverride==="checkbox"){let s=t.trim().toLowerCase();return s==="true"||s==="false"?s:void 0}if(n?.inputTypeOverride!=="number"&&n?.inputTypeOverride!=="slider")return t;let i=n.sliderConfig??n.numericConfig,o=Go(t,i);return o===""?void 0:o}buildInputPromptOptions(t,n,i){let o=this.contentValuePromptsAcceptImagePaste&&t?.inputTypeOverride!=="number"&&t?.inputTypeOverride!=="slider"?{sourcePath:this.getLinkSourcePath()??""}:void 0,s=this.promptRunContext?.draftScopeId;return{optional:t?.optional,numeric:t?.numericConfig,slider:t?.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:t=>this.assertInteractivePrompt(t),buildInputPromptOptions:(t,n,i)=>this.buildInputPromptOptions(t,n,i)}}async promptForVariable(t,n){return Gz(this.promptRuntime(),t,n)}async promptForMathValue(){let t=this.choiceExecutor?.promptProvider;if(t)return await t.inputPrompt("Enter a math expression");this.assertInteractivePrompt("a {{MVALUE}} math expression");try{return await Hk.Prompt()}catch(n){throw ot(n)?new at("Input cancelled by user"):n}}async suggestForValue(t,n=!1,i){return Yz(this.promptRuntime(),t,n,i)}async suggestForValueMulti(t,n=!1,i){return Kz(this.promptRuntime(),t,n,i)}async suggestForField(t){return this.assertInteractivePrompt(`{{FIELD:${t}}}`),R3({app:this.app,executor:this.choiceExecutor,getSourcePath:()=>this.getLinkSourcePath()},t)}generateCacheKey(t){return sM(t)}async suggestForFile(t){return this.assertInteractivePrompt(`{{FILE}} (pick a file from ${t.folderPath})`),N3({app:this.app,executor:this.choiceExecutor,getSourcePath:()=>this.getLinkSourcePath()},t)}async getMacroValue(t,n){let{SingleMacroEngine:i}=await Promise.resolve().then(()=>(K3(),Y3)),o=new i(this.app,this.plugin,this.plugin.settings.choices,this.choiceExecutor,this.variables),s=await o.runAndGetOutput(t,n)??"";return o.getVariables().forEach((a,l)=>{this.variables.set(l,a)}),s}async getTemplateContent(t){let{SingleTemplateEngine:n}=await Promise.resolve().then(()=>(TM(),rj));this.templateInclusion??(this.templateInclusion={visited:new Set,depth:0});let i={visited:this.templateInclusion.visited,depth:this.templateInclusion.depth+1},o=new n(this.app,this.plugin,t,this.choiceExecutor,i);o.setTargetFolderPath(this.targetFolderPath),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??""}#${t}`});let s=await o.run();return this.mergeTemplatePropertyVars(o.getAndClearTemplatePropertyVars()),s}async getSelectedText(){let t=xn(this.app);return t?t.editor.getSelection():""}async getClipboardContent(){try{return await navigator.clipboard.readText()}catch{return""}}isTemplatePropertyTypesEnabled(){return this.plugin.settings.enableTemplatePropertyTypes}async replaceInlineJavascriptInString(t){let n=t;for(;tl.test(n);){let i=tl.exec(n);if(!i)break;let o=i.at(1)?.trim();if(o){let{SingleInlineScriptEngine:s}=await Promise.resolve().then(()=>(ij(),nj)),a=new s(this.app,this.plugin,this.choiceExecutor,this.variables),l=await a.runAndGetOutput(o);for(let u in a.params.variables)this.variables.set(u,a.params.variables[u]);let c="";typeof l=="string"?c=l:(typeof l=="number"||typeof l=="boolean"||Array.isArray(l))&&(c=this.renderCollectedOrArrayValue({input:n,matchStart:i.index,matchEnd:i.index+i[0].length,rawValue:l,fallbackKey:"inlineScript",heuristicEnabled:this.isTemplatePropertyTypesEnabled()})??String(l)),n=this.replacer(n,tl,c)}else n=this.replacer(n,tl,"")}return n}async collectValuesManually(t,n){return await lM(this.app,t,n)}}});async function sj(r,e,t,n,i){if(X.getState().disableOnlineFeatures)throw new Error("Blocking request: Online features are disabled in settings.");let o=X.getState().ai,s;if(n.model==="Ask me")s=await i();else if(s=Gd(pc(n.model,n.modelRef)??n.model),!s)throw new Error(`Model ${n.model} not found with any provider.`);let{model:a,provider:l}=s,c=new ji(r,on(),t);c.setPromptRunContext({choiceName:e?.name,draftScopeId:`${e?.id??"macro"}#aiAssistant:${n.id}`});let u=await Ca(r,l),d=await Nz(r,{apiKey:u,model:a,provider:l,outputVariableName:n.outputVariableName,promptTemplate:n.promptTemplate,promptTemplateFolder:o.promptTemplatesFolderPath,systemPrompt:n.systemPrompt,showAssistantMessages:o.showAssistant,modelOptions:n.modelParameters,interactive:t.interactive,promptProvider:t.promptProvider},async p=>c.formatFileContent(p));for(let p in d)t.variables.set(p,d[p])}async function aj(r,e){let n=X.getState().ai.providers.flatMap(o=>o.models.map(s=>({label:`${s.name} (${o.name})`,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=e.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(e.interactive===!1)throw new ye('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 Xt.Suggest(r,n.map(o=>o.label),n.map(o=>o.resolved),"Select a model")}catch(o){throw ot(o)?new at("Input cancelled by user"):o}}var lj=E(()=>{u0();Yd();dt();lp();_s();Tm();ro();xt();Yn();ur();Zo()});function cp(r,e){try{return r.getChoiceById(e)}catch{return null}}var Qk=E(()=>{});function pj(r){return Bb.some(e=>e.id===r)}function cj(r){let e=(0,Xk.getFrontMatterInfo)(r);return e.exists?{frontmatterYaml:e.frontmatter,body:r.slice(e.contentStart)}:{frontmatterYaml:null,body:r}}function Hse(r,e,t){if(t==="bottom"){let n=`${r}
${e}`;return{content:n,insertedStartOffset:r.length+1,insertedEndOffset:n.length}}return op(r,`${e}
`)}function zse(r){return r==null||r===""||Array.isArray(r)&&r.length===0}function uj(r){return typeof r=="string"?r.length>0?[r]:[]:!Array.isArray(r)||!r.every(e=>typeof e=="string")?null:r}function dj(r,e){let t=uj(r),n=uj(e);if(t===null||n===null)return;let i=[],o=new Set(t);for(let s of n)s.length===0||o.has(s)||(o.add(s),i.push(s));if(i.length!==0)return[...t,...i]}var Xk,Bb,yh,Zk=E(()=>{Xk=require("obsidian");Ie();ht();Gk();Jm();Sv();If();Cu();wu();Bg();gM();Kk();da();_f();Bb=[{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."}];yh=class extends xu{constructor(t,n,i,o,s,a,l){super(t,n,a);this.targetFile=i;this.templatePath=o;this.mode=s;this.cursorView=null;this.resolvedTemplatePath=l??null}placeCursor(t){this.mode==="cursor"&&No(this.app,t)!==this.cursorView||super.placeCursor(t)}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,$n(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(t){let n=t.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(t.fileNameFormat?.enabled&&t.fileNameFormat.format){this.formatter.setTargetFolderPath(i);let a=await this.formatter.formatFileName(t.fileNameFormat.format,"generic"),l=Wn(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(t){let{formatted:n,templatePropertyVars:i}=await this.formatTemplateForTargetFile(),{frontmatterYaml:o,body:s}=cj(n),a=this.cursorPlacement;return(s.trim().length>0||a)&&await this.app.vault.process(this.targetFile,l=>{let c=Hse(l,s,t);if(a&&c.insertedStartOffset!==null){let u=c.insertedStartOffset-(n.length-s.length);this.cursorPlacement={content:c.content,offsets:a.offsets.map(d=>u+d)}}return c.content}),await this.mergeFrontmatterProperties(o,i),await this.rebaseCursorAfterFileChanges(this.targetFile),this.targetFile}async insertTemplateAtCursor(){let t=No(this.app,this.targetFile);$n(t,"Cannot insert at cursor: the note is not open in the active editor."),this.cursorView=t;let n=t.editor,{formatted:i,templatePropertyVars:o}=await this.formatTemplateForTargetFile();$n(t.file===this.targetFile&&t.editor===n&&this.app.workspace.getLeavesOfType("markdown").some(c=>c.view===t),"Cannot insert at cursor: the original editor was closed or changed notes.");let{frontmatterYaml:s,body:a}=cj(i),l=this.cursorPlacement?.offsets[0];return l!==void 0?this.cursorPlacement=NA({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 t.save(),await this.mergeFrontmatterProperties(s,o),s&&await this.rebaseCursorAfterFileChanges(this.targetFile),this.targetFile}async formatTemplateForTargetFile(){let t=await this.getTemplateContent(await this.getResolvedTemplatePath());this.formatter.setTitle(this.targetFile.basename),this.formatter.setTargetFolderPath(Ai(this.targetFile.path));let n=await this.formatter.withTemplatePropertyCollection(()=>this.formatter.withPromptScope("noteBody",t,()=>this.targetFile.extension==="md"?this.formatter.formatTemplateContent(t):this.formatter.formatFileContent(t))),i=this.formatter.getAndClearTemplatePropertyVars();this.targetFile.extension==="md"&&(n=await il(this.app,n,this.targetFile));let o=Rb(n);return this.cursorPlacement=this.targetFile.extension==="md"&&o.offsets.length>0?o:null,{formatted:o.content,templatePropertyVars:i}}async mergeFrontmatterProperties(t,n){if(!t||this.targetFile.extension!=="md")return;let i;try{i=(0,Xk.parseYaml)(t)}catch(o){I.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(co.PATH_SEPARATOR)?o.split(co.PATH_SEPARATOR):[o];Lb(i,a,Af(s))}await this.app.fileManager.processFrontMatter(this.targetFile,o=>{for(let[s,a]of Object.entries(i)){if(CM([s])){I.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=p2(this.app,s);if(zse(l)){c&&Array.isArray(a)?o[s]=dj([],a)??[]:o[s]=a;continue}if(c){let u=dj(l,a);u!==void 0&&(o[s]=u)}}})}}}});function Wse(r){return r.trim().length===0}function wh(r){return!cr.test(r)&&!wn.test(r)}function jse(r){return r.kind==="choice"?`Choice: ${r.choice.name}`:`Template: ${r.path}`}function fj(r){let e=r.replace(/^\/+/,"").toLowerCase();return/\.(md|canvas|base)$/.test(e)?e:`${e}.md`}function Gse(r,e){let t=nn(r).filter(o=>o.type==="Template"&&!!o.templatePath&&wh(o.templatePath)),n=new Set(t.map(o=>fj(o.templatePath))),i=t.map(o=>({kind:"choice",choice:o}));for(let o of e)wh(o)&&(n.has(fj(o))||i.push({kind:"file",path:o}));return i}async function qb(r,e,t){let n=t.file??r.workspace.getActiveFile();if(!n||n.extension!=="md")return new bh.Notice("QuickAdd: No active markdown note to apply a template to."),null;let i=t.choiceExecutor.triggerContext;i==null&&(t.choiceExecutor.triggerContext={activeFile:n});try{let o=!t.templatePath,s;if(t.templatePath)s={kind:"file",path:t.templatePath};else{let m=await Yse(r,e);if(!m)return null;s=m}let a=s.kind==="choice"?s.choice.templatePath:s.path;if(!wh(a))return new bh.Notice("QuickAdd: Only markdown templates can be applied to a note. Canvas and base templates create their own file types."),null;let l=await r.vault.cachedRead(n),c=Wse(l),u;if(t.mode)u=t.mode;else if(c)u="replace";else if(!o)u="bottom";else{let m=await Kse(r,n);if(!m)return null;u=m}t.choiceExecutor.variables.has("value")||t.choiceExecutor.variables.set("value",n.basename);let d=new yh(r,e,n,a,u,t.choiceExecutor);d.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 d.getResolvedTemplatePath();return wh(p)?await d.apply()?(o&&s.kind==="choice"&&(d.setPromptRunContext({destination:void 0,destinationKind:void 0}),await Qse(r,d,s.choice,n)),!d.hasTemplaterHandledCursor()&&!await ol(r,n)&&d.placeCursor(n),new bh.Notice(`Applied template to '${n.basename}'.`),n):null:(new bh.Notice("QuickAdd: Only markdown templates can be applied to a note. Canvas and base templates create their own file types."),null)}catch(o){return ot(o)||mj(o)||Ze(o,"Error applying template to note"),null}finally{t.choiceExecutor.triggerContext=i}}function mj(r){return!!r&&typeof r=="object"&&r.name==="MacroAbortError"}async function Yse(r,e){let t=Gse(e.settings.choices,e.getTemplateFiles().map(n=>n.path));if(t.length===0)return new bh.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 Xt.Suggest(r,t.map(jse),t,"Apply template to note")}catch(n){if(ot(n))return null;throw n}}async function Kse(r,e){let t=!!No(r,e),n=Bb.filter(i=>i.id!=="cursor"||t);try{return await Xt.Suggest(r,n.map(i=>i.label),n.map(i=>i.id),"How should the template be applied?")}catch(i){if(ot(i))return null;throw i}}async function Qse(r,e,t,n){try{let i=await e.computeChoiceTargetPath(t);if(!i||i===n.path||await r.vault.adapter.exists(i)||!ej(i)||!await Si.Prompt(r,"Move note to match choice settings?",`'${t.name}' creates notes at '${i}'. Move '${n.path}' there? Links to the note will be updated.`))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(ot(i)||mj(i))return;I.logWarning(`Could not move note to match choice settings: ${i}`)}}var bh,SM=E(()=>{bh=require("obsidian");Xe();Zo();Wd();Ie();ht();bt();Yk();xt();Zk()});function Xse(r,e,t){return window.moment(r).add(e,t).startOf("day").toDate()}function Ub(r){if(r instanceof Date&&!Number.isNaN(r.getTime()))return r;if(typeof r!="string")return;let e=r.trim();if(!e)return;if(e.toLowerCase().startsWith("@date:")){let n=e.slice(6),i=window.moment(n);return i.isValid()?i.toDate():void 0}let t=fu(e,void 0,Qo);if(t.isValid&&t.isoString){let n=window.moment(t.isoString);return n.isValid()?n.toDate():void 0}}function Jk(r){if(r.clocks?.date)return{status:"inherit"};if(r.reservedSeed!==void 0){let o=Ub(r.reservedSeed);return o?{status:"set",date:o}:{status:"error",message:"Could not parse the seeded date origin."}}let e=r.setting;if(!e||e.kind==="now")return{status:"inherit"};if(e.kind==="ask")return{status:"ask",defaultValue:e.defaultValue};if(e.kind==="relative"){let o=r.clocks?.now??new Date;return{status:"set",date:Xse(o,e.offset,e.unit)}}let t=r.variables;if(!t)return{status:"error",message:`Date origin variable "${e.name}" is not available.`};let n=Rc(t,e.name);if(!n)return{status:"error",message:`Date origin variable "${e.name}" is not set.`};let i=Ub(t.get(n));return i?{status:"set",date:i}:{status:"error",message:`Date origin variable "${e.name}" is not a date.`}}function Ch(r,e){if(e==null||typeof e=="string"&&!e.trim())return!0;if(BB(e))return r.pickDate=!0,!0;let t=Ub(e);return t?(r.clocks={now:r.clocks?.now??new Date,date:t},!0):!1}var xh=E(()=>{Ld();Kc();Zd();uo()});var eS,Hb,hj=E(()=>{eS=require("obsidian"),Hb=class r extends eS.Modal{constructor(t,n,i){super(t);this.header=n;this.text=i;this.waitForClose=new Promise(o=>{this.resolvePromise=o}),this.open(),this.display()}static Show(t,n,i){return new r(t,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 t=this.contentEl.createDiv(),n=new eS.ButtonComponent(t).setButtonText("OK").onClick(()=>this.close());Object.assign(t.style,{display:"flex",justifyContent:"flex-end"}),n.buttonEl.focus()}onClose(){super.onClose(),this.resolvePromise()}}});var zb,Eh,gj=E(()=>{zb=require("obsidian");ur();m0();Eh=class r extends zb.Modal{constructor(t,n,i=[],o){super(t);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(t,n,i,o){return new r(t,n,i,o).promise}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(Rr())}addSearchableOptions(){this.picker=new Xd(this.contentEl,{items:this.items.map(t=>({key:t,value:t,label:t})),isSelected:({value:t})=>this._selectedItems.includes(t),onToggle:({value:t},n)=>{if(n){this._selectedItems.includes(t)||this._selectedItems.push(t);return}this._selectedItems=this._selectedItems.filter(i=>i!==t)},getSelectedCount:()=>new Set(this._selectedItems).size})}addSubmitButton(){let t=this.contentEl.createDiv("submitButtonContainer");new zb.ButtonComponent(t).setButtonText("Submit").setCta().onClick(()=>{this.resolved=!0,this.resolvePromise(this._selectedItems),this.close()}),new zb.ButtonComponent(t).setButtonText("Cancel").onClick(()=>{this.close()})}}});function Da(r){throw r instanceof yt?r:ot(r)?new at(vc):r}var Fa,_M=E(()=>{Ds();d0();Wd();hj();Zo();gj();Ol();fk();rn();Ni();ur();xt();Zd();Fa=class{static async inputPrompt(e,t,n,i,o){try{return await ar.Prompt(e,t,n,i,void 0,{allowPeek:!0,...o})}catch(s){Da(s)}}static async datePrompt(e,t,n){try{let i=await Rl.Prompt(e,t,n?.placeholder,n?.defaultValue,n?.dateFormat);if(i&&i.startsWith("@date:")){let o=i.slice(6);return(n?.dateFormat?Us(o,n.dateFormat):null)??o}return i}catch(i){Da(i)}}static async wideInputPrompt(e,t,n,i,o){try{return await cu.Prompt(e,t,n,i,void 0,{allowPeek:!0,...o})}catch(s){Da(s)}}static async yesNoPrompt(e,t,n){let i;try{i=await Si.Ask(e,t,n)}catch(o){Da(o)}if(i===null)throw new at(vc);return i}static async infoDialog(e,t,n){try{return await Hb.Show(e,t,n)}catch(i){Da(i)}}static async suggester(e,t,n,i,o=!1,s){try{let a;return typeof t=="function"?a=n.map((l,c,u)=>kn(t(l,c,u))):a=t.map(l=>kn(l)),o?await Mr.Suggest(e,a,n,{...i?{placeholder:i}:{},...s?.renderItem?{renderItem:s.renderItem}:{}}):await Xt.Suggest(e,a,n,i,s?.renderItem)}catch(a){Da(a)}}static async checkboxPrompt(e,t,n,i){try{return await(i===void 0?Eh.Open(e,t,n):Eh.Open(e,t,n,i))}catch(o){Da(o)}}}});var tS,vj=E(()=>{rn();hl();Bk();ks();tS=class extends xr{constructor(e,t,n){super(e,t),this.fieldInput=n;let i=oi.parse(n);this.fieldName=i.fieldName,this.filters=i.filters}async getSuggestions(e){let t=await M3(this.app,this.fieldName,this.filters),n=(e||"").toLowerCase();return n?t.filter(i=>i.toLowerCase().includes(n)).slice(0,200):t.slice(0,200)}renderSuggestion(e,t){this.renderMatch(t,e,this.getCurrentQuery())}selectSuggestion(e){this.inputEl.value=e,Cd(this.inputEl),this.close()}}});var yj,AM,rS,bj=E(()=>{rn();yj=require("obsidian");ks();AM=200,rS=class extends xr{constructor(t,n,i,o,s,a,l){super(t,n);this.getOptions=i;this.isSelected=o;this.onSelect=s;this.multiSelect=a;this.allowCustomInput=l;a&&n.setAttribute("aria-multiselectable","true")}getSuggestions(t){let n=t.trim(),i=this.getOptions().filter(u=>!this.isSelected(u.value));if(!n)return i.slice(0,AM);let o=(0,yj.prepareFuzzySearch)(n),s=i.map(u=>({option:u,match:o(`${u.label} ${u.path}`)})).filter(u=>u.match!==null).sort((u,d)=>d.match.score-u.match.score).slice(0,AM).map(({option:u})=>u);if(!this.allowCustomInput)return s;let a=n.toLocaleLowerCase(),l=this.getOptions().some(u=>u.label.toLocaleLowerCase()===a||u.path.toLocaleLowerCase()===a),c=this.isSelected(n);return l||c?s:[{value:n,label:`Use \u201C${n}\u201D`,path:"Custom value",isCustom:!0},...s].slice(0,AM)}renderSuggestion(t,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"});t.isCustom?o.setText(t.label):this.renderMatch(o,t.label,this.getCurrentQuery().trim()),i.createDiv({cls:"qa-onepage-file-suggestion__path",text:t.path})}selectSuggestion(t){if(this.onSelect(t),this.inputEl.value="",!this.multiSelect){this.close();return}Cd(this.inputEl,!0),this.inputEl.focus()}}});var nS,wj=E(()=>{rn();ks();rn();nS=class extends xr{constructor(e,t,n,i=!1,o=!1,s){super(e,t),this.options=n.map(a=>kn(a)),this.caseSensitive=i,this.multiSelect=o,this.onSelect=s,this.multiSelect&&this.inputEl.setAttribute("aria-multiselectable","true")}parseMultiSelectInput(e){if(!this.multiSelect)return{alreadySelected:[],activeTerm:e};let t=e.split(",").map(n=>n.trim());return{alreadySelected:t.slice(0,-1).filter(Boolean),activeTerm:t[t.length-1]||""}}getRemainingOptions(e){return this.options.filter(t=>!e.includes(t))}getSuggestions(e){let t=Ac(e),{alreadySelected:n,activeTerm:i}=this.parseMultiSelectInput(t),o=this.caseSensitive?i:i.toLowerCase(),s=this.getRemainingOptions(n);return o?s.filter(a=>(this.caseSensitive?a:a.toLowerCase()).includes(o)).slice(0,200):s.slice(0,200)}renderSuggestion(e,t){this.renderMatch(t,e,this.getCurrentQuery())}selectSuggestion(e){this.multiSelect?this.selectMultipleItem(e):this.selectSingleItem(e)}selectSingleItem(e){this.inputEl.value=e,Cd(this.inputEl),this.close()}selectMultipleItem(e){let{alreadySelected:t}=this.parseMultiSelectInput(this.inputEl.value);t.push(e),this.onSelect?.(e);let n=this.getRemainingOptions(t).length>0;this.inputEl.value=n?t.join(", ")+", ":t.join(", "),this.inputEl.setSelectionRange(this.inputEl.value.length,this.inputEl.value.length),Cd(this.inputEl,n),n?this.inputEl.focus():this.close()}}});function Cj(r,e,t){return t?e.get(r)??r:r}function xj(r,e){return e.length===0?r:r===""?e[0]??"":e.includes(r)?r:e[0]??""}var Ej=E(()=>{});var Ii,iS,Tj=E(()=>{Ii=require("obsidian");Xe();b0();vj();bj();wj();Zd();td();dt();uo();lo();Ej();iS=class{constructor(e,t,n){this.app=e;this.contentEl=t;this.host=n}setting(e,t=!0){let n=new Ii.Setting(this.contentEl).setName(this.host.decorateLabel(e));return t&&e.description&&n.setDesc(e.description),n}render(e){let t=this.host.controlFor(e),n=(o,s)=>{t.value=s,this.host.publish(t),this.host.updatePreview()},i=this.host.initialValue(e.id)??e.defaultValue??"";switch(t.value=i,e.type){case"textarea":case"text":{let o=this.setting(e),s=e.type==="textarea"?new Ii.TextAreaComponent(o.controlEl):new Ii.TextComponent(o.controlEl);s.setPlaceholder(e.placeholder??"").setValue(i).onChange(a=>n(e.id,a)),e.type==="textarea"&&s.inputEl.addClass("qa-onepage-textarea"),this.host.attachFreeText(e,s.inputEl,o);break}case"number":{let o=this.setting(e),s=new Ii.TextComponent(o.controlEl);s.inputEl.type="number",s.inputEl.inputMode="decimal",e.numericConfig?.min!==void 0&&(s.inputEl.min=String(e.numericConfig.min)),e.numericConfig?.max!==void 0&&(s.inputEl.max=String(e.numericConfig.max)),s.inputEl.step=e.numericConfig?.step!==void 0?String(e.numericConfig.step):"any";let a=e.numericConfig?Go(i,e.numericConfig):i;s.setPlaceholder(e.placeholder??"").setValue(a).onChange(l=>n(e.id,e.numericConfig?Go(l,e.numericConfig):l)),n(e.id,a);break}case"slider":{let o=this.setting(e);o.controlEl.parentElement?.addClass("qa-onepage-slider-setting");let s=e.sliderConfig??{min:0,max:100,step:1},a=e.optional&&i==="",l=Ff(i,s),c=o.controlEl.createDiv({cls:"qa-onepage-slider"}),u=c.createEl("input");u.type="range",u.min=String(s.min),u.max=String(s.max),u.step=String(s.step),u.value=l;let d=new Ii.TextComponent(c);d.inputEl.type="number",d.inputEl.inputMode="decimal",d.inputEl.min=String(s.min),d.inputEl.max=String(s.max),d.inputEl.step=String(s.step),d.setValue(a?"":l),n(e.id,a?"":l),u.addEventListener("input",()=>{d.inputEl.value=u.value,n(e.id,u.value)}),d.onChange(p=>{if(p===""&&e.optional){n(e.id,"");return}let f=Go(p,s);f!==""&&(u.value=f,d.inputEl.value=f,n(e.id,f))});break}case"dropdown":{let o=this.setting(e),s=new Ii.DropdownComponent(o.controlEl),a=e.options??[],l=e.displayOptions??a;if(a.length>0){e.optional&&s.addOption("","Skip (leave empty)"),a.forEach((u,d)=>{let p=l[d]??u;s.addOption(u,p)});let c=xj(i,a);s.setValue(c),n(e.id,c),s.onChange(u=>n(e.id,u))}else s.setDisabled(!0),o.controlEl.createDiv({text:e.placeholder||"No options available"}).addClass("qa-onepage-dropdown-note");break}case"date":{let o=this.setting(e);o.settingEl.addClass("qa-onepage-date-setting");let s=o.controlEl.createDiv({cls:"qa-date-input"}),a=new Ii.TextComponent(s),l="Enter a date (e.g., 'today', 'next friday', '2025-12-25')",c,u=i;i?.startsWith("@date:")&&(c=i.slice(6),u=(e.dateFormat?Us(c,e.dateFormat):void 0)??(c.length>=10?c.slice(0,10):c)),a.setPlaceholder(l).setValue(u??"");let d=s.createDiv();d.addClass("qa-date-preview-text");let p=s.createDiv({cls:"qa-date-picker-container"}),f=pk({container:p,initialIso:c,withTime:e.withTime===!0,onSelect:C=>{C?b(C):x()}});t.dispose.push(()=>f.destroy());let m=Sg(X.getState().dateAliases);if(m.length>0){let C=s.createEl("details");C.addClass("qa-date-alias-details"),C.createEl("summary",{text:`Aliases (${m.length})`}).addClass("qa-date-alias-summary");let A=C.createDiv();A.textContent=aC(X.getState().dateAliases),A.addClass("qa-date-alias-list")}let g=C=>{if(e.dateFormat){let S=Us(C,e.dateFormat);if(S)return S}return C.length>=10?C.slice(0,10):C},v=(C,S)=>{d.setText(C),d.toggleClass("is-error",S)},y=C=>{f.setSelectedIso(C)},b=C=>{t.dateParseError=!1;let S=g(C);a.inputEl.value=S,n(e.id,`@date:${C}`),v(S,!1),y(C)},x=()=>{a.inputEl.value="",T("")},w=C=>{let S=fu(C,e.dateFormat),A=S.isValid?S.isoString:void 0;t.dateParseError=!A,n(e.id,A?`@date:${A}`:""),y(A),v(A?S.formatted??g(A):S.error||"Unable to parse date",!A)},T=C=>{let S=(C??"").trim();if(!S&&e.defaultValue&&!e.optional){w(e.defaultValue);return}if(!S){t.dateParseError=!1,n(e.id,""),y(),v(e.optional?"Will be left empty":"Preview will appear here",!1);return}if(S.startsWith("@date:")){let A=S.slice(6).trim();if(A){b(A);return}}w(S)};a.onChange(C=>T(C)),c?b(c):T(u??"");break}case"field-suggest":{let o=this.setting(e),s=new Ii.TextComponent(o.controlEl);s.setPlaceholder(e.placeholder??"").setValue(i).onChange(l=>n(e.id,l));let a=e.id.startsWith(sd)?e.id.slice(sd.length):e.id;try{t.suggesters.push(new tS(this.app,s.inputEl,a))}catch{}break}case"suggester":{let o=this.setting(e),s=e.options??[],a=e.displayOptions??s,l=new Map,c=new Map;s.forEach((p,f)=>{let m=a[f]??p;l.set(m,p),c.has(p)||c.set(p,m)});let u=c.get(i)??i,d=new Ii.TextComponent(o.controlEl);if(d.setPlaceholder(e.placeholder??"Type to search...").setValue(u).onChange(p=>n(e.id,p)),d.inputEl.addEventListener("input",p=>{let f=!!p.fromCompletion,m=d.inputEl.value,g=Cj(m,l,f);(g!==m||f)&&n(e.id,g)}),a.length>0)try{let p=e.suggesterConfig?.caseSensitive??!1,f=e.suggesterConfig?.multiSelect??!1;t.suggesters.push(new nS(this.app,d.inputEl,a,p,f,f?m=>{let g=t.multiSelections??[];g.push(m),t.multiSelections=g,this.host.publish(t)}:void 0))}catch{}break}case"file-picker":{this.renderFilePickerField(e,i,n);break}default:{let o=this.setting(e,!1),s=new Ii.TextComponent(o.controlEl);s.setPlaceholder(e.placeholder??"").setValue(i).onChange(a=>n(e.id,a)),this.host.attachFreeText(e,s.inputEl,o)}}this.host.publish(t)}renderFilePickerField(e,t,n){let i=this.setting(e);i.settingEl.addClass("qa-onepage-file-picker-setting");let o=e.options??[],s=e.displayOptions??o,a=o.map((w,T)=>{let C=Td(w);return{value:w,label:s[T]??w,path:C.kind==="file"?C.path:w}}),l=new Map(a.map(w=>[w.value,w])),c=e.suggesterConfig?.multiSelect??!1,u=e.suggesterConfig?.allowCustomInput??!1,d=new Set,p=new Map,f=w=>{let T=p.get(w);if(T)return T;let C={value:w,label:w,path:"Custom value",isCustom:!0};return p.set(w,C),C};if(t&&l.has(t))d.add(t);else if(t&&u){let w=Td(t),T=w.kind==="custom"?w.text:t;f(T),d.add(T)}else!c&&a.length>0&&d.add(a[0].value);let m=i.controlEl.createDiv({cls:"qa-onepage-file-picker"}),g=m.createDiv({cls:"qa-onepage-file-picker__selection"});g.setAttribute("aria-live","polite");let v=new Ii.TextComponent(m);v.inputEl.addClass("qa-onepage-file-picker__input"),v.setPlaceholder(e.placeholder??(c?"Search and add files...":"Search files...")),v.inputEl.setAttribute("aria-label",c?`Add files for ${e.label}`:`Choose file for ${e.label}`);let y=()=>{let w=a.filter(T=>d.has(T.value));for(let T of p.values())d.has(T.value)&&w.push(T);return w},b=()=>{let w=y(),T=w.map(C=>C.value);this.host.controlFor(e).fileSelections=T,n(e.id,c?T.join(", "):T[0]??""),g.empty(),g.toggleClass("qa-hidden",w.length===0);for(let C of w){let S=g.createDiv({cls:"qa-onepage-file-picker__chip"});S.setAttribute("title",C.path),S.createSpan({cls:"qa-onepage-file-picker__chip-label",text:C.label});let A=S.createEl("button",{cls:"qa-onepage-file-picker__remove",text:"\xD7"});A.type="button",A.setAttribute("aria-label",`Remove ${C.label}`),A.addEventListener("click",()=>{d.delete(C.value),b(),v.inputEl.focus()})}},x=w=>{let T=w.isCustom?f(w.value):w;c||d.clear(),d.add(T.value),b()};v.inputEl.addEventListener("keydown",w=>{if(w.key==="Backspace"&&v.inputEl.value===""&&d.size>0){let T=y().at(-1);if(!T)return;w.preventDefault(),d.delete(T.value),b()}});try{let w=new rS(this.app,v.inputEl,()=>[...a,...p.values()],T=>d.has(T),x,c,u);this.host.controlFor(e).suggesters.push(w)}catch{v.setDisabled(!0)}b()}}});function kj(r,e){r.empty(),r.toggleClass("qa-hidden",e.length===0);for(let t of e){let n=t.diagnostics.filter(l=>l.severity==="error"),o=n.some(l=>l.kind!=="path")?"Unresolved":n.length>0?"Won't be created":t.label,s=r.createDiv({cls:"qa-onepage-preview-row"});s.createDiv({text:`${o}:`,cls:"qa-preview-key"}),s.createDiv({text:t.text,cls:"qa-preview-val"}).setAttribute("title",t.text);for(let l of t.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 Sj=E(()=>{});function Th(r,e={}){let{openedAtOf:t,recentRankOf:n,isExcluded:i}=e;return r.map(o=>({file:o,name:o.basename||o.path,excluded:i?.(o.path)??!1,openedAt:t?.(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,u=s.recentRank??Number.POSITIVE_INFINITY;return c!==u?c-u:o.name.localeCompare(s.name)}).map(o=>o.file)}var oS=E(()=>{});function kh(r){let e=r.workspace?.getLastOpenFiles?.(),t=Array.isArray(e)?e:[],n=new Map;t.forEach((s,a)=>{n.has(s)||n.set(s,a)});let i;try{i=gf.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 sS=E(()=>{VI()});function Zse(r){return`${IM}${r}`}function Jse(r){return`${DM}${r}`}function eae(r){return r.startsWith(IM)}function tae(r){return r.startsWith(DM)}function rae(r){return r.slice(IM.length)}function nae(r){return r.slice(DM.length)}function xo(r){return r.trim().replace(/\.md$/i,"").toLowerCase()}function Aj(r){return r.trim().replace(/^\/+/,"")}function iae(r){return r.trim().length>0&&!r.includes("{{")}function oae(r){if(!iae(r.templatePath))return new Set;let e=Aj(r.templatePath),t=/\.md$/i.test(e)?e:`${e}.md`;return new Set([t.toLowerCase()])}function sae(r,e,t){let n=e.replace(/\.md$/i,"");r.add(xo(e)),r.add(xo(n)),r.add(xo(t))}function aae(r,e){let t=r.metadataCache.getFileCache(e)?.frontmatter;if(!t)return[];let n=[];for(let[i,o]of Object.entries(t)){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 lae(r){let n=((r.split("|")[0]?.trim()??"").split("#")[0]?.trim()??"").replace(/\.md$/i,"").trim();return!n||n==="/"||Dr(n)?null:n}function cae(r){let e=r.metadataCache.unresolvedLinks??{},t=new Map;for(let n of Object.values(e))for(let i of Object.keys(n)){let o=lae(i);if(!o)continue;let s=xo(o);t.has(s)||t.set(s,o)}return[...t.values()].sort((n,i)=>n.localeCompare(i))}function aS(r,e){let t=new Set,n=oae(e),i=Th(r.vault.getMarkdownFiles(),kh(r)),o=[];for(let s of i){if(n.has(Aj(s.path).toLowerCase()))continue;sae(t,s.path,s.basename);let a=aae(r,s);for(let c of a)t.add(xo(c));let l=[s.basename,s.path,...a].join(" ");o.push({item:Zse(s.path),exactKeys:[s.basename,s.path,...a].map(xo),display:l,title:a[0]?`${s.basename} (${s.path})`:s.path,renderPath:s.path,renderAlias:a[0]})}for(let s of cae(r)){let a=xo(s);t.has(a)||o.push({item:Jse(s),exactKeys:[xo(s)],display:s,title:`${s} (unresolved link)`,unresolvedTitle:s})}return{candidates:o,existingKeys:t}}function Wb(r){return eae(r)?{kind:"existing",path:rae(r)}:Pa(tae(r)?nae(r):r)}function Pa(r){let e=Wn(r,"Note title");return{kind:"create",title:e,...e.includes("/")?{vaultRelativePath:e}:{}}}function FM(r,e){let t=Wb(e);return jb(r,t),t}function jb(r,e){if(e.kind==="existing"){let n=r.vault.getAbstractFileByPath(e.path);if(!(n instanceof _j.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 t=Wn(e.title,"Note title");return{kind:"create",title:t,...t.includes("/")?{vaultRelativePath:t}:{}}}var _j,IM,DM,Sh=E(()=>{_j=require("obsidian");oS();sS();da();la();IM="@quickadd-existing-note:",DM="@quickadd-unresolved-note:"});var cS,lS,Ij=E(()=>{cS=require("obsidian");Dl();Sh();ks();lS=class extends xr{constructor(t,n,i,o,s){let{candidates:a,existingKeys:l}=aS(t,i);super(t,n,s);this.obsidianApp=t;this.onSelect=o;this.existingKeys=l;let c=Zc(i.existingNoteAction);this.options=a.map(u=>({item:u.item,exactKeys:u.exactKeys,label:u.renderPath?`${c==="Open"?"":`${c}: `}${u.renderPath.split("/").at(-1)?.replace(/\.md$/i,"")}`:u.unresolvedTitle??u.title,detail:u.renderPath??"Unresolved link",search:u.display}))}getSuggestions(t){let n=t.trim();if(!n)return this.options.slice(0,100);let i=xo(n),o=(0,cS.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(t){let n=xo(t),i=this.options.find(o=>o.exactKeys.includes(n));return i?FM(this.obsidianApp,i.item):Pa(t)}renderSuggestion(t,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:t.label}),t.detail&&i.createDiv({cls:"qa-onepage-file-suggestion__path",text:t.detail})}selectSuggestion(t){try{let n=this.options.includes(t)?FM(this.obsidianApp,t.item):Pa(t.item);this.inputEl.value="",this.close(),this.onSelect(n)}catch(n){new cS.Notice(n instanceof Error?n.message:"Could not select this note."),this.inputEl.focus()}}}});function PM(r=null){return{collect:{kind:"none"},opaque:null,deferred:r}}function MM(r){return{collect:{kind:"none"},opaque:r,deferred:r}}function Ma(r){return r.type==="Template"}function $M(r){return r.type==="Capture"}function Dj(r){if(!r)return PM("unresolvableChoice");switch(r.type){case"Template":case"Capture":return Ma(r)||$M(r)?{collect:{kind:"scanChoice",choice:r},opaque:null,deferred:null}:PM("unresolvableChoice");case"Macro":return MM("nestedMacroGroup");case"Multi":return MM("interactivePicker");default:return r.type}}function _h(r,e){switch(r.type){case"NestedChoice":return Dj(r.choice??null);case"Choice":return Dj(e(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 MM("conditionalBranch");case"Obsidian":case"EditorCommand":case"Wait":case"OpenFile":return PM();default:return r.type}}var Ah=E(()=>{vr()});function OM(r,e){return r.onePageInput==="never"&&Ma(r)&&nu(r,r.fileNameFormat.enabled?r.fileNameFormat.format:Or,e)}function uae(r){return{id:r.id,label:r.name}}function dae(r){return{id:r.id,label:r.name}}function Gb(r,e,t){let n=[],i=[],o=!1,s=!1;for(let a of Ht(e.macro?.commands)){if(!qr(a))continue;let l=_h(a,r);if(s){i.push({label:a.name,reason:"afterOpaqueStep"});continue}if(l.collect.kind==="scanChoice"){let c=l.collect.choice;s=OM(c,t),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:uae(c)})}else l.collect.kind==="scriptInputs"?n.push({kind:"script",occurrenceId:a.id,command:l.collect.command,group:dae(l.collect.command)}):l.deferred&&i.push({label:a.name,reason:l.deferred});l.opaque&&(o=!0)}return{members:n,deferred:i}}var uS=E(()=>{un();Xe();zd();Ah()});function dS(r,e){switch(e.kind){case"filter":return jg(r,e.filter);case"property":return Gg(r,e.field,e.value,e.filter);case"tag":return KA(r,e.tag);case"folder":return Bo(r,e.folderPathSlash)}}function Fj(r,e){let t=Th(e,kh(r)),n=t.map(s=>s.path),i=$c(t,s=>r.metadataCache.getFileCache(s)),o=n.map((s,a)=>`${i[a]??s} ${s}`);return{paths:n,labels:i,search:o}}var RM=E(()=>{ht();oS();sS();lo()});function fae(r){return typeof r=="string"&&pae.includes(r)}function Pj(r){if(!r||typeof r!="object")return null;let e=r,t=e.id,n=e.type;if(typeof t!="string"||!fae(n))return null;let i=mae(e.numericConfig),o=hae(e.sliderConfig),s=n==="slider"&&!o?"number":n;return{id:t,label:typeof e.label=="string"?e.label:t,type:s,placeholder:typeof e.placeholder=="string"?e.placeholder:void 0,defaultValue:typeof e.defaultValue=="string"?e.defaultValue:void 0,numericConfig:o??i,sliderConfig:o,options:Array.isArray(e.options)?e.options.filter(a=>typeof a=="string"):void 0,dateFormat:typeof e.dateFormat=="string"?e.dateFormat:void 0,description:typeof e.description=="string"?e.description:void 0,optional:typeof e.optional=="boolean"?e.optional:void 0,source:"script"}}function mae(r){if(!r||typeof r!="object")return;let e=r,t=typeof e.min=="number"&&Number.isFinite(e.min)?e.min:void 0,n=typeof e.max=="number"&&Number.isFinite(e.max)?e.max:void 0,i=typeof e.step=="number"&&Number.isFinite(e.step)&&e.step>0?e.step:void 0;if(t!==void 0&&n!==void 0&&n<t)return i===void 0?void 0:{step:i};let o={};return t!==void 0&&(o.min=t),n!==void 0&&(o.max=n),i!==void 0&&(o.step=i),Object.keys(o).length>0?o:void 0}function hae(r){if(!r||typeof r!="object")return;let e=r,t=typeof e.min=="number"?e.min:void 0,n=typeof e.max=="number"?e.max:void 0,i=e.step===void 0?1:typeof e.step=="number"?e.step:void 0;if(!(t===void 0||n===void 0||i===void 0||!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(i)||n<=t||i<=0))return{min:t,max:n,step:i}}function Mj(r){if(!r||typeof r!="object"&&typeof r!="function")return[];let e=r.quickadd;if(!e||typeof e!="object")return[];let t=e.inputs;return Array.isArray(t)?t:[]}var pae,$j=E(()=>{pae=["text","number","textarea","dropdown","slider","date","field-suggest","file-picker","suggester"]});function pS(r){return`${r.replace(/^\/+/,"").replace(Nt,"")}.md`}function fS(r,e,t){if(t)return null;let n=(e??"").trim().replace(/^\/+/,"");if(cl(n))return null;let i=Zf(n),o=!!i&&!!i.field,s=o?null:Xf(n),a=!!s&&!s.multiSelect,l=!o&&!s&&n.startsWith("#"),c=n.endsWith("/"),u=!l&&!o&&!a&&!c&&(Nt.test(n)||cr.test(n)||wn.test(n)),d=n.replace(/\/+$/,""),p=!l&&!o&&!a&&!u&&(n===""||r.isFolder(d)&&!r.markdownFileExists(d)),f=!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||f){let m=d;return{kind:"folder",folderPathSlash:m===""?"":`${m}/`}}return null}var NM=E(()=>{Xe();Kg();fE();pE()});function LM(r){let e=/^\{\{VALUE:([^{}]+)\}\}$/i.exec(r);if(e){let i=Ad(e[1]);return i&&!i.inputTypeOverride&&!i.hasOptions&&!i.caseStyle?i.variableKey:null}let t=/^\{\{(?:VALUE|NAME)(\|[^{}]+)?\}\}$/i.exec(r);if(!t)return null;let n=Dv(t[1]??"");return!n.inputTypeOverride&&!n.caseStyle?"value":null}function mS(r,e){let t=e==="boolean"?"checkbox":e;return t!=="number"&&t!=="checkbox"||LM(r)===null?r:`${r.slice(0,-2)}|type:${t}}}`}var VM=E(()=>{uo()});var Yb,Oj=E(()=>{$v();Xe();Pd();Sf();Ld();uo();Pv();pd();hl();cM();lo();Yb=class extends Lc{constructor(t,n,i){super(t);this.app=t;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.scanningSoleValue=!1;this.dateParser=Qo,i&&(this.variables=new Map(i.variables))}warn(){}reportProblem(){}async scanString(t,n=!1,i="generic"){let o=this.scanningPathContext,s=this.scanningScope,a=this.scanningSoleValue;this.scanningPathContext=n,this.scanningScope=i,this.scanningSoleValue=Cx(i,t);try{let l=await this.replaceGlobalVarInString(t);if(this.scanVariableTokens(l),this.scanDateTokens(l),this.scanFileTokens(l),n){if(new RegExp(el.source,"i").test(l)){let c=this.requirements.get("value");c&&(c.pathContext=!0)}if(new RegExp(pC.source,"i").test(l)){let c=this.requirements.get("mvalue");c&&(c.pathContext=!0)}}await this.format(l)}finally{this.scanningPathContext=o,this.scanningScope=s,this.scanningSoleValue=a}}markScanContext(t){this.scanningPathContext&&(t.pathContext=!0)}async format(t){let n=t;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(Oo.source,"gi"),o;for(;(o=i.exec(n))!==null;){let s=o[1];s&&this.templatesToScan.add(s)}}return n}async replaceGlobalVarInString(t){return Bc(t,this.plugin?.settings?.globalVariables)}scanVariableTokens(t){let n=new RegExp(od.source,"gi"),i;for(;(i=n.exec(t))!==null;){let o=(i[1]??"").trim();if(!o)continue;let s=Ad(o,{warn:this.warnSink});if(!s)continue;let{variableName:a,variableKey:l,label:c,defaultValue:u,displayValues:d,hasOptions:p}=s;if(!a)continue;let f=p&&c?c:a,m=!p&&c?c:void 0,g=l;if(this.requirements.has(g)){let v=this.requirements.get(g);if(this.markScanContext(v),p&&!this.hasOptionList(v)&&(v.type=this.optionFieldType(s),v.label=f,this.applyOptionFields(v,s),v.defaultValue!==void 0&&!s.allowCustomInput)){let y=Av(v.defaultValue);v.defaultValue=s.suggestedValues.includes(y)?y:void 0}u&&v.defaultValue===void 0&&(v.defaultValue=u),!v.displayOptions&&d&&(v.displayOptions=d),v.optional=(v.optional??!1)&&s.optional}else{let v=this.inputFieldType(s),y={id:g,label:f,type:p?this.optionFieldType(s):v,description:m,optional:s.optional};p?this.applyOptionFields(y,s):v==="dropdown"?y.options=["true","false"]:v==="number"?y.numericConfig=s.numericConfig:v==="slider"&&(y.numericConfig=s.numericConfig,y.sliderConfig=s.sliderConfig),u&&(y.defaultValue=u),this.markScanContext(y),this.requirements.set(g,y)}}}inputFieldType(t){switch(t?.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(t){return t.allowCustomInput||t.multiSelect?"suggester":"dropdown"}hasOptionList(t){return Array.isArray(t.options)&&t.options.length>0}applyOptionFields(t,n){t.options=n.suggestedValues,n.displayValues&&(t.displayOptions=n.displayValues),n.multiSelect?t.multiEmit=n.multiEmit??"text":delete t.multiEmit,n.allowCustomInput||n.multiSelect?t.suggesterConfig={allowCustomInput:n.allowCustomInput,caseSensitive:!1,multiSelect:n.multiSelect??!1}:delete t.suggesterConfig}scanDateTokens(t){let n=new RegExp(mc.source,"gi"),i;for(;(i=n.exec(t))!==null;){let o=i[1]?.trim();if(!o)continue;let{defaultValue:s,optional:a,withTime:l}=Fv(i[3]),c=i[2]?.trim()||(l?"YYYY-MM-DD HH:mm":"YYYY-MM-DD"),u=this.requirements.get(o);u?(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:o,type:"date",defaultValue:s,dateFormat:c,withTime:l,optional:a,source:"collected"})}}async promptForValue(t){let n="value";if(!this.requirements.has(n)){let i=this.inputFieldType(this.valuePromptContext),o=Tx(this.scanningScope,this.scanningSoleValue);this.requirements.set(n,{id:n,label:o.title||t||"Enter value",type:i,description:this.valuePromptContext?.description,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(t,n){if(!t)return"";let i=n?.variableKey??t;if(n?.type==="VDATE")return n.defaultValue??"@date:1970-01-01T00:00:00.000Z";if(!this.requirements.has(i)){let o=_d(t).map(c=>c.trim()).filter(Boolean),s=o.length>1,a=s?"dropdown":this.inputFieldType(n),l={id:i,label:t,type:a,description:n?.description,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 t="mvalue";return this.requirements.has(t)||this.requirements.set(t,{id:t,label:"Math expression",type:"text",placeholder:"e.g., 2+2*3"}),this.markScanContext(this.requirements.get(t)),""}async suggestForField(t){let n=oi.parse(t),i=`${sd}${t}`;if(!this.requirements.has(i)){let o={id:i,label:n.fieldName||t,type:"field-suggest",source:"collected",runtimeOnly:n.multiSelect};if(!n.multiSelect&&n.filters.defaultFrom==="active"){let s=qk(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(t){let n=new RegExp(uC.source,"gi"),i;for(;(i=n.exec(t))!==null;){let o=ax(i[1]??"");o&&this.recordFileRequirement(o)}}recordFileRequirement(t){let n=t.variableKey,i=this.requirements.get(n);if(i){i.optional=(i.optional??!1)&&t.optional,i.type="file-picker",i.suggesterConfig={allowCustomInput:(i.suggesterConfig?.allowCustomInput??!1)||t.allowCustomInput,caseSensitive:!1,multiSelect:(i.suggesterConfig?.multiSelect??!1)||t.multiSelect};return}let o=xi.filterFiles(this.app.vault.getMarkdownFiles(),t.filter,u=>this.app.metadataCache.getFileCache(u)),s=o.map(u=>`${Pc}${u.path}`),a=$c(o,u=>this.app.metadataCache.getFileCache(u)),l=t.allowCustomInput||s.length===0,c=t.mode==="name"?`File from ${t.folderPath}`:`File from ${t.folderPath} (${t.mode})`;this.requirements.set(n,{id:n,label:t.label??c,type:"file-picker",source:"collected",options:s,displayOptions:a,optional:t.optional,suggesterConfig:{allowCustomInput:l,caseSensitive:!1,multiSelect:t.multiSelect}})}suggestForFile(t){return""}async suggestForValue(t,n,i){return""}getVariableValue(t){return""}async getTemplateContent(t){return""}async getSelectedText(){return""}async getClipboardContent(){return""}getCurrentFileLink(){return null}getCurrentFileName(){return null}async getMacroValue(t,n){return""}isTemplatePropertyTypesEnabled(){return!1}}});function qM(r){return`${BM}${r}`}function Ih(r){return r.startsWith(BM)&&r.length>BM.length}function UM(r){return r===Ig||Ih(r)}function Rj(r,e){let t=Rc(r,e);return t?r.get(t)==null?null:t:null}function gae(r){let e=0;for(let t of r.keys())Ih(t)&&e++;return e}function Nj(r,e){if(!r)return;let t=r.get(qM(e));if(typeof t=="string"&&t.length>0)return t;if(gae(r)>1)return;let n=r.get(Ig);if(typeof n=="string"&&n.length>0)return n}function Lj(r,e){return UM(e)?Rj(r,e):null}function Vj(r,e,t){return t!==1||!Ih(e)?!1:Rj(r,Ig)!==null}var BM,HM=E(()=>{Xe();uo();BM=`${Ig}.`});async function qj(r,e){let t=Vn(r,e);return t?await r.vault.cachedRead(t):""}function vae(r){let e=new Set,t=new RegExp(Oo.source,"gi"),n;for(;(n=t.exec(r))!==null;)n[1]&&e.add(n[1]);return e}async function Ul(r,e,t,n="generic",i=new Set,o=0){let s=xx(n),a=vae(t);e.templatesToScan.clear(),await e.scanString(t,s,n);let l=[...e.templatesToScan].filter(c=>a.has(c));if(e.templatesToScan.clear(),!(o>=$x))for(let c of l){if(i.has(c))continue;let u=`${s?"path":"content"}:${c}`,d=e.scannedTemplateRefDepths.get(u);if(!(d!==void 0&&d<=o)){e.scannedTemplateRefDepths.set(u,o),i.add(c);try{await Ul(r,e,await qj(r,c),n,i,o+1)}finally{i.delete(c)}}}}async function Uj(r,e,t){if(await e.scanString(t,!0,"templatePath"),cl(t)){I.logMessage(`Preflight: template path "${t}" uses format syntax; its body's prompts are collected at run time, not in the one-page form.`);return}await Ul(r,e,await qj(r,t),"noteBody",new Set([t]))}async function Hj(r,e,t,n){let i=new Yb(r,e,t);if(n.fileNameFormat?.enabled&&await Ul(r,i,n.fileNameFormat.format,"noteTitle"),n.folder?.enabled)for(let s of n.folder.folders??[])await Ul(r,i,s,"folder");n.templatePath&&await Uj(r,i,n.templatePath);let o=n.fileNameFormat?.enabled?n.fileNameFormat.format:Or;if(bF(n,o)){let s=i.requirements.get("value");s&&(s.runtimeOnly=!0)}return i}async function zj(r,e,t,n,i){let o=new Yb(r,e,t);await Ul(r,o,n.captureTo,"captureTarget"),n.propertyCapture?.property.kind==="named"&&await Ul(r,o,n.propertyCapture.property.format,"propertyName");let s=n.format?.enabled?n.format.format:Or,a=n.propertyCapture?.property.kind==="named"?n.propertyCapture.property.format.trim():null,l=a&&!cl(a)?ca(r,a,{registeredOnly:!0}):null;if((n.format?.enabled||n.propertyCapture)&&await Ul(r,o,n.propertyCapture?mS(s,l):s,n.propertyCapture?"propertyValue":"captureText"),n.propertyCapture&&l===null){let d=LM(s),p=d===null?void 0:o.requirements.get(d);p&&(p.runtimeOnly=!0)}!n.propertyCapture&&n.insertAfter?.enabled&&!n.insertAfter.promptHeading&&await Ul(r,o,n.insertAfter.after,"lineTarget"),!n.propertyCapture&&n.insertBefore?.enabled&&await Ul(r,o,n.insertBefore.before,"lineTarget");let c=n.createFileIfItDoesntExist;c?.enabled&&c.createWithTemplate&&c.template&&await Uj(r,o,c.template);let u=fS({isFolder:d=>tf(r,d),markdownFileExists:d=>r.vault.getAbstractFileByPath(pS(d))instanceof Bj.TFile},n.captureTo??"",n.captureToActiveFile);if(u){let d=dS(r,u),p=Th(d,kh(r)),f=p.map(y=>y.path),m=$c(p,y=>r.metadataCache?.getFileCache(y)??null),g=n.createFileIfItDoesntExist?.enabled??!1,v=qM(n.id);f.length===0&&g?o.requirements.set(v,{id:v,label:"Select capture target file",type:"file-picker",source:"collected",options:f,displayOptions:m,runtimeOnly:!0,placeholder:"Type a new note name in the capture target picker"}):o.requirements.set(v,{id:v,label:"Select capture target file",type:"dropdown",options:f,displayOptions:m,placeholder:f.length?void 0:"No files found in target scope"})}if(i){let d=n.useSelectionAsCaptureValue,p=e.settings.useSelectionAsCaptureValue??!0;if(typeof d=="boolean"?d:p){let m=t.variables.get("value");if(m==null){let g=sl(r);g.trim().length>0&&t.variables.set("value",g)}}}return o}async function yae(r,e,t){let n=[];try{let i=AC(e),o=i!==void 0?t?.get(i):void 0;o===void 0&&(o=await Lo(e,r,{reportLoadErrors:!1}),i!==void 0&&o!==void 0&&t?.set(i,o));let s=Mj(o);for(let a of s){let l=Pj(a);l&&n.push(l)}}catch(i){let o=e.path??e.id,s=i instanceof Error?i.message:String(i);if(GN(i))return I.logMessage(`QuickAdd preflight could not inspect user script '${o}': ${s}`),n;I.logWarning(`Preflight could not inspect user script '${o}': ${s}`)}return n}function bae(r){return r.type==="Macro"}async function wae(r,e,t,n,i){let o=Gb(l=>cp(e,l),n,t.variables.get("value")),s=new Map,a=i?.seedCaptureSelectionAsValue??!1;for(let l of o.members){let c=l.kind==="script"?await yae(r,l.command,i?.preloadedUserScripts):Ma(l.choice)?Array.from((await Hj(r,e,t,l.choice)).requirements.values()):Array.from((await zj(r,e,t,l.choice,a)).requirements.values());for(let u of c){let d=s.get(u.id);if(d){d.optional=(d.optional??!1)&&(u.optional??!1),u.pathContext&&(d.pathContext=!0),u.runtimeOnly&&(d.runtimeOnly=!0);continue}s.set(u.id,{...u,group:l.group})}}return Cae(t.variables,s),Array.from(s.values())}function Cae(r,e){let t=[];for(let n of e.values())Ih(n.id)&&t.push(n.id);if(!(t.length<2))for(let n of t)r.has(n)||r.set(n,null)}function xae(r,e){let t=e.pickDate?Qf(_l(r.dateOrigin)):_l(r.dateOrigin);if(!(t?.kind!=="ask"||e.clocks?.date))return{id:rl,label:`Date for ${r.name}`,type:"date",dateFormat:"YYYY-MM-DD",defaultValue:t.defaultValue,source:"collected"}}function Eae(r,e,t){let n=xae(r,e);return n?[n,...t.filter(i=>i.id!==rl)]:t}async function $a(r,e,t,n,i){let o;if(bae(n))o=await wae(r,e,t,n,i);else if(Ma(n))o=[...(await Hj(r,e,t,n)).requirements.values()];else if(n.type==="Capture")o=[...(await zj(r,e,t,n,i?.seedCaptureSelectionAsValue??!1)).requirements.values()];else return[];return Eae(n,t,o)}function Wj(r,e,t){return Gb(n=>cp(r,n),e,t).deferred}function Hl(r,e){let t=r.filter(n=>Ih(n.id)).length;return r.filter(n=>{if(UM(n.id))return Lj(e,n.id)!==null?!1:!Vj(e,n.id,t);let i=Rc(e,n.id);return i?e.get(i)==null:!0})}var Bj,Kb=E(()=>{RM();$j();Qk();Bj=require("obsidian");ys();Pd();Xe();Kf();Kc();zd();ht();Ie();IC();Kg();NM();oS();lo();sS();uo();VM();_f();Oj();Sf();HM();Ah();uS()});function jj(){return{pending:new Map,active:null,discoveryMacros:new Set}}function Gj(r,e){r.preparedInputs.discoveryMacros.add(e)}function Yj(r,e){return r.preparedInputs.discoveryMacros.has(e)}function Kj(r,e,t){r.preparedInputs.pending.set(e,t)}function Qj(r,e){return r.preparedInputs.active?.choiceId===e}function hS(r,e){let t=r.preparedInputs.active;return t?.choiceId===e?t.discovery:null}function Xj(r){r.preparedInputs.pending.clear(),r.preparedInputs.discoveryMacros.clear(),r.preparedInputs.active=null}async function Qb(r,e,t){let n=r.preparedInputs,i=n.pending.get(e);if(!i)return t();n.pending.delete(e);let o=n.active;n.active=i;let s=r.variables.has("value"),a=r.variables.get("value"),l=!1;for(let[c,u]of i.values)r.variables.get(c)==null&&(r.variables.set(c,u),c==="value"&&(l=!0));try{return await t()}finally{l&&r.variables.get("value")===i.values.get("value")&&(s?r.variables.set("value",a):r.variables.delete("value")),n.active=o}}var Dh=E(()=>{});function Zj(r,e){let t=r.flatMap(n=>{if(n.kind==="always")return[n.metadata];let i=e.get(n.noteId);return i?.kind==="create"?[n.create]:i?.kind==="existing"&&n.existing?[n.existing]:[]});return t.length===0?null:{...t[0],optional:t.length>0&&t.every(n=>n.optional),pathContext:t.some(n=>n.pathContext),runtimeOnly:t.some(n=>n.runtimeOnly)}}function gS(r){return{...r}}function jM(r,e){let t=e.get(r.noteId);return t?.kind==="create"||r.includeExisting&&t?.kind==="existing"}function zM(r){return r.type==="Macro"}function WM(r,e){return Ma(r)&&nu(r,r.fileNameFormat.enabled?r.fileNameFormat.format:Or,e.variables.get("value"))}async function Jj(r,e,t,n){let i=u=>cp(e,u),o;if(zM(n)){for(let u of Ht(n.macro?.commands)){if(!qr(u))continue;let d=_h(u,i);d.collect.kind==="scanChoice"&&WM(d.collect.choice,t)&&Gj(t,n.id)}if(!Yj(t,n.id))return null;o=Gb(i,n,t.variables.get("value")).members}else if(WM(n,t))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(zM(n)){let u={...n,macro:{...n.macro,commands:[]}},d=Hl(await $a(r,e,t,u),t.variables);if(d.length>0){let p=new Map;for(let f of d)s.set(f.id,f),p.set(f.id,{variable:f.id,condition:null}),a.set(f.id,[null]),l.fieldUsages.set(f.id,[{kind:"always",metadata:gS(f)}]);c.push({occurrenceId:n.id,choiceId:n.id,noteId:null,bindings:p})}}for(let u of o){let d={...u.group,id:u.occurrenceId},p=u.kind==="choice"?u.choice:null,f=p!==null&&WM(p,t)?p:null,m=f?`__qa.note.${u.occurrenceId}`:null,g={occurrenceId:u.occurrenceId,choiceId:p?.id??u.occurrenceId,noteId:m,bindings:new Map};c.push(g),f&&m&&(l.notes.push({id:m,choice:f,group:d}),s.set(m,{id:m,label:"Note",type:"text",pathContext:!0,group:d}));let v=p??(zM(n)&&u.kind==="script"?{...n,macro:{...n.macro,commands:[u.command]}}:null);if(!v)continue;let y=Hl(await $a(r,e,t,v,{preloadedUserScripts:t.preloadedUserScripts}),t.variables),b=new Map;if(f&&yE(f.existingNoteAction)!=="open"){let w={...f,fileNameFormat:{enabled:!1,format:""},folder:{...f.folder,enabled:!1}};for(let T of await $a(r,e,t,w))b.set(T.id,T)}let x=p&&$M(p)&&(p.useSelectionAsCaptureValue??e.settings.useSelectionAsCaptureValue??!0)?sl(r):"";for(let w of y){if(f&&w.id==="value")continue;let T=w.id==="value"?`__qa.value.${u.occurrenceId}`:w.id,C=m?{noteId:m,includeExisting:b.has(w.id)}:null;g.bindings.set(T,{variable:w.id,condition:C});let S=l.fieldUsages.get(T)??[],A=b.get(w.id),D={...w,id:T,group:d,...w.id==="value"&&x.trim()?{defaultValue:x}:{}};S.push(m?{kind:"note",noteId:m,create:gS(D),existing:A?gS(A):null}:{kind:"always",metadata:gS(D)}),l.fieldUsages.set(T,S);let P=s.get(T);P?(P.optional=!!(P.optional&&w.optional),w.pathContext&&(P.pathContext=!0),w.runtimeOnly&&(P.runtimeOnly=!0)):s.set(T,D);let U=a.get(T)??[];U.push(C),a.set(T,U)}}for(let[u,d]of a)d.includes(null)||l.visibleForNotes.set(u,d.filter(p=>p!==null));return{requirements:[...s.values()],config:l,steps:c}}function eG(r,e,t,n){for(let i of e.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||jM(c,n))&&t.has(a)&&s.set(l,t.get(a));Kj(r,i.occurrenceId,{choiceId:i.choiceId,values:s,discovery:o})}}var GM=E(()=>{Qk();Xe();zd();Dl();un();ys();Ah();uS();Kb();Dh()});function Tae(r){let e=[];for(let t of r){let n=e.at(-1);n&&n.group?.id===t.group?.id?n.fields.push(t):e.push({group:t.group,fields:[t]})}return e}function kae(r){let e=new Set;for(let t of r)t.group&&e.add(t.group.id);return e.size>=2}function vS(r){return JSON.stringify(Object.entries(r).filter(([e,t])=>t!==void 0&&!["id","group","optional","pathContext","runtimeOnly"].includes(e)).sort(([e],[t])=>e.localeCompare(t)))}var Kn,Fh,YM=E(()=>{Tj();Kn=require("obsidian");tD();rD();Ev();qI();UI();hx();ur();Sj();Ij();Sh();GM();Dl();Fh=class extends Kn.Modal{constructor(t,n,i,o,s){super(t);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,Kn.debounce)(this.updatePreviews.bind(this),150,!0),this.peek=new Cf({app:t,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"),vx(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")),kae(this.requirements))for(let s of Tae(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();let n=this.contentEl.createDiv({cls:"qa-prompt-actions"}),i=n.createDiv({cls:"qa-prompt-actions-primary"});new Kn.ButtonComponent(i).setButtonText("Submit").setCta().onClick(()=>this.submit()),new Kn.ButtonComponent(i).setButtonText("Cancel").onClick(()=>this.cancel());let o=n.createDiv({cls:"qa-prompt-actions-secondary"});yx(new Kn.ButtonComponent(o).setButtonText("Peek at note").onClick(()=>this.peek.peek()))}onOpen(){this.peek.onHostOpened();let t=this.scope;typeof t?.register=="function"&&(t.register(["Mod"],"Enter",()=>(this.submit(),!1)),t.register(["Mod","Shift"],xv,()=>(this.peek.peek(),!1)))}renderField(t){let n=new Set(this.contentEl.children),i=this.discoveryForm?.notes.find(s=>s.id===t.id);i?this.renderNoteField(i):this.renderFieldControl(t);let o=Array.from(this.contentEl.children).filter(s=>s.instanceOf(HTMLElement)&&!n.has(s));if(this.fieldElements.set(t.id,o),!i){this.controlFor(t).elements=o;let s=this.fieldAnchors.get(t.id);s||(s=this.contentEl.ownerDocument.createComment(t.id),this.contentEl.append(s),this.fieldAnchors.set(t.id,s));for(let a of o)this.contentEl.insertBefore(a,s)}}controlFor(t){let n=this.fieldControls.get(t);return n||(n={requirement:t,elements:[],value:"",dateParseError:!1,suggesters:[],dispose:[]},this.fieldControls.set(t,n)),n}publishControl(t){let n=t.requirement;this.settled||!this.requirements.includes(n)||(this.result.set(n.id,t.value),t.multiSelections?this.multiSelections.set(n.id,t.multiSelections):this.multiSelections.delete(n.id),t.fileSelections?this.fileSelections.set(n.id,t.fileSelections):this.fileSelections.delete(n.id),t.dateParseError?this.dateParseErrors.add(n.id):this.dateParseErrors.delete(n.id))}get activeRequirements(){return this.requirements.filter(t=>this.isFieldVisible(t.id))}isFieldVisible(t){if(this.requirements.find(i=>i.id===t)?.runtimeOnly)return!1;let n=this.discoveryForm?.visibleForNotes.get(t);return!n||n.some(i=>jM(i,this.discoverySelections))}updateFieldVisibility(t=!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);t&&this.updatePreviewDebounced()}updateFieldMetadata(){for(let t=0;t<this.requirements.length;t++){let n=this.requirements[t],i=this.discoveryForm?.fieldUsages.get(n.id);if(!i)continue;let o=Zj(i,this.discoverySelections);if(!o)continue;let s={...o,id:n.id,group:n.group};if(!this.fieldElements.has(n.id)){this.requirements[t]=s;continue}if(vS(n)!==vS(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&&vS(c.requirement)===vS(s));if(n=l?.requirement??s,this.requirements[t]=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(u=>u.value==="");if(n.optional&&!c)l.createEl("option",{value:"",text:"Skip (leave empty)",prepend:!0});else if(!n.optional&&c){c.remove();let u=this.controlFor(n);u.value=l.value,this.publishControl(u)}}}}renderNoteField(t){let n=new Kn.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 Kn.TextComponent(i).setPlaceholder("Search notes or create new note");s.inputEl.addClass("qa-onepage-file-picker__input"),s.inputEl.setAttribute("aria-label",`Note for ${t.choice.name}`);let a,l=c=>{a?.close(),this.discoverySelections.set(t.id,c),o.empty();let u=Zc(t.choice.existingNoteAction),d=c.kind==="existing"?`${u==="Open"?"":`${u}: `}${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:d});let f=p.createEl("button",{cls:"qa-onepage-file-picker__remove",text:"\xD7"});f.type="button",f.setAttribute("aria-label","Change note"),f.addEventListener("click",()=>{this.discoverySelections.delete(t.id),o.empty(),s.inputEl.hidden=!1,this.updateFieldVisibility(),s.inputEl.focus()}),s.inputEl.hidden=!0,this.updateFieldVisibility(),f.focus()};try{a=new lS(this.app,s.inputEl,t.choice,l,this.scope),this.discoverySuggesters.push(a)}catch{new Kn.Notice("Note search is unavailable. Type a new note title.")}this.discoveryInputs.set(t.id,{input:s.inputEl,select:l,resolve:()=>a?a.resolveInput(s.inputEl.value):Pa(s.inputEl.value)})}renderFieldControl(t){new iS(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,o)=>{this.enableImagePaste(n,i),this.attachFreeTextBehaviors(n,i,o)}}).render(t)}attachFreeTextBehaviors(t,n,i){let o=t.id;i.nameEl.id||(i.nameEl.id=`qa-onepage-label-${o}`),n.setAttribute("aria-labelledby",i.nameEl.id);let s={id:o,el:n,fileSuggester:new vf(this.app,n),tagSuggester:new yf(this.app,n,{refreshIndex:this.freeTextFields.length===0})};this.freeTextFields.push(s),this.controlFor(t).suggesters.push(s.fileSuggester,s.tagSuggester),n.addEventListener("focus",()=>{this.lastFocusedFreeText=s})}insertTarget(){return this.lastFocusedFreeText&&this.contentEl.contains(this.lastFocusedFreeText.el)&&this.isFieldVisible(this.lastFocusedFreeText.id)?this.lastFocusedFreeText:this.freeTextFields.find(t=>this.contentEl.contains(t.el)&&this.isFieldVisible(t.id))}enableImagePaste(t,n){this.imagePasteInputs.set(t,n),this.syncImagePaste(t,n)}syncImagePaste(t,n){let i=this.imagePasteHandles.get(t);if(this.settled||t.pathContext||!this.requirements.includes(t)||!this.isFieldVisible(t.id)){if(!this.settled&&!t.pathContext&&i?.isBusy()){i.whenIdle().then(()=>this.syncImagePaste(t,n));return}i?.detach(),this.imagePasteHandles.delete(t)}else i||this.imagePasteHandles.set(t,mx(this.app,n,{}))}decorateLabel(t){if(!t.optional)return t.label;let n=this.contentEl.ownerDocument,i=n.win.createFragment();return i.appendChild(n.createTextNode(t.label)),i.createSpan({text:" (optional)",cls:"qa-onepage-optional-badge"}),i}submit(){if(this.settled)return;let t=new Set(this.requirements.filter(a=>!this.isFieldVisible(a.id)).map(a=>a.id));for(let a of this.discoveryForm?.notes??[]){if(this.discoverySelections.has(a.id))continue;let l=this.discoveryInputs.get(a.id);if(l){if(!l.input.value.trim()){new Kn.Notice("Enter a note title or choose an existing note."),l.input.focus();return}try{l.select(l.resolve())}catch(c){new Kn.Notice(c instanceof Error?c.message:"Could not select this note."),l.input.focus();return}}}let n=this.requirements.find(a=>t.has(a.id)&&this.isFieldVisible(a.id)&&!a.optional&&!(this.result.get(a.id)??this.initialValues.get(a.id)??a.defaultValue));if(n){this.fieldElements.get(n.id)?.[0]?.querySelector("input, textarea, select")?.focus();return}let i=Array.from(this.imagePasteHandles.values()).find(a=>a.isBusy());if(i){i.whenIdle().then(()=>this.submit());return}let o={},s=this.requirements.find(a=>this.isFieldVisible(a.id)&&a.type==="date"&&!a.optional&&this.dateParseErrors.has(a.id));if(s){new Kn.Notice(`QuickAdd: "${s.label}" is not a valid date. Fix it or clear it before submitting.`);return}for(let[a,l]of this.multiSelections){let c=(this.result.get(a)??"").replace(/,\s*$/,"").trim();l.join(", ")!==c&&this.multiSelections.delete(a)}Object.assign(o,this.collectAnswers()),this.settled=!0,this.close(),this.resolvePromise(o)}collectAnswers(){let t=new Map(this.requirements.map(i=>[i.id,i])),n={};return this.result.forEach((i,o)=>{if(!this.isFieldVisible(o))return;let s=t.get(o);if(s?.type==="date"&&i===""){let a=this.dateParseErrors.has(o);if(!s.optional||a)return}n[o]=i}),n}collectPreviewAnswers(){let t=this.collectAnswers(),n=new Map(this.requirements.map(i=>[i.id,i]));for(let[i,o]of this.fileSelections)this.isFieldVisible(i)&&(t[i]=n.get(i)?.suggesterConfig?.multiSelect?[...o]:o[0]??"");return t}cancel(){this.settled=!0,this.close(),this.rejectPromise(Rr())}onClose(){this.peek.onHostClosed();for(let t of this.imagePasteHandles.values())t.detach();this.imagePasteHandles.clear(),this.imagePasteInputs.clear();for(let t of this.fieldControls.values()){for(let n of t.suggesters)n.destroy();for(let n of t.dispose)n()}this.freeTextFields.length=0,this.lastFocusedFreeText=void 0;for(let t of this.discoverySuggesters)t.destroy();this.discoverySuggesters.length=0,this.settled||(this.settled=!0,this.rejectPromise(Rr()))}async updatePreviews(){if(!this.computePreview||!this.previewContainerEl)return;let t=++this.previewToken;try{let n=await this.computePreview(this.collectPreviewAnswers());if(t!==this.previewToken||!this.previewContainerEl)return;kj(this.previewContainerEl,n)}catch{}}}});function Sae(r){if(!r||typeof r!="object")return;let e={};return typeof r.min=="number"&&Number.isFinite(r.min)&&(e.min=r.min),typeof r.max=="number"&&Number.isFinite(r.max)&&(e.max=r.max),e.min!==void 0&&e.max!==void 0&&e.max<e.min&&(delete e.min,delete e.max),typeof r.step=="number"&&Number.isFinite(r.step)&&r.step>0&&(e.step=r.step),Object.keys(e).length>0?e:void 0}function _ae(r){if(!r||typeof r!="object")return;let{min:e,max:t}=r,n=r.step??1;if(!(typeof e!="number"||typeof t!="number"||typeof n!="number"||!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)||t<=e||n<=0))return{min:e,max:t,step:n}}async function tG(r,e,t){let n={},i=[];for(let l of t){let c=e.variables.get(l.id);if(c!=null){n[l.id]=String(c);continue}let u=_ae(l.sliderConfig),d=u??Sae(l.numericConfig),p=l.type==="slider"&&!u?"number":l.type;i.push({id:l.id,label:l.label??l.id,type:p,placeholder:l.placeholder,defaultValue:l.defaultValue,numericConfig:d,sliderConfig:u,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=e?.promptProvider;if(l)try{let c=await l.requestInputs(i);o=Object.fromEntries(Object.entries(c).map(([u,d])=>[u,Array.isArray(d)?d.join(", "):d]))}catch(c){Da(c)}else{let c=new Fh(r,i,e.variables);try{o=await c.waitForClose}catch(u){Da(u)}}}let s={...n,...o};for(let l of t)s[l.id]===void 0&&(s[l.id]="");Object.entries(s).forEach(([l,c])=>e.variables.set(l,c));let a={};for(let l of t){let c=s[l.id];if(c===void 0)continue;let u=c;if(l.type==="date"&&l.dateFormat&&typeof c=="string"&&c.startsWith("@date:")){let d=c.slice(6),p=Us(d,l.dateFormat);p&&(u=p)}a[l.id]=u}return a}var rG=E(()=>{YM();Zd();_M()});function up(r){return new TextEncoder().encode(r).length}function Aae(r){let e=0;for(let t of r){if(t.role==="tool"){for(let n of t.results)e+=up(n.content);continue}if(e+=up(t.content),t.role==="assistant"&&t.toolCalls){for(let n of t.toolCalls)if(typeof n.rawArgs=="string")e+=up(n.rawArgs);else if(n.args)try{e+=up(JSON.stringify(n.args))}catch{}}}return e}function Iae(r,e){let t;if(typeof r=="string")t=r;else if(r==null)t='{"ok":true}';else try{t=JSON.stringify(r)}catch{return{content:"tool returned a value that could not be serialized",isError:!0}}if(up(t)>e){let n=" \u2026[truncated]",i=Math.max(0,e-up(n)),o=Math.min(t.length,i);for(;o>0&&up(t.slice(0,o))>i;)o=Math.floor(o*.9)||o-1;t=t.slice(0,o)+n}return{content:t,isError:!1}}async function nG(r){let e=r.maxResultBytes??32768,t=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 f=0;f<n;f++){if(f>0&&r.isOnlineDisabled?.())return u("aborted");let m=f===n-1,g=l||m,v={...r.request,messages:i,...g?{toolChoice:"none"}:{}};a+=Aae(i);let y;try{y=await r.dispatch(v,{isFinalStep:g})}catch(x){if(r.isContextOverflow?.(x))return u("context-overflow");throw x}if(c=y,s.promptTokens+=y.usage.promptTokens,s.completionTokens+=y.usage.completionTokens,s.totalTokens+=y.usage.totalTokens,y.normalizedStopReason!=="tool_calls"||y.toolCalls.length===0||g){o.push({stepNumber:f,text:y.content,toolCalls:y.toolCalls,toolResults:[],finishReason:y.rawStopReason,usage:y.usage}),await r.onStepFinish?.(o[o.length-1]);let x=y.normalizedStopReason==="length"?"length":m&&!l&&f>0?"max-steps":"stop";return u(x)}i.push({role:"assistant",content:y.content,toolCalls:y.toolCalls,providerRaw:y.providerRaw});let b=[];for(let x of y.toolCalls)b.push(await d(x));i.push({role:"tool",results:b}),o.push({stepNumber:f,text:y.content,toolCalls:y.toolCalls,toolResults:b,finishReason:y.rawStopReason,usage:y.usage}),await r.onStepFinish?.(o[o.length-1]),a>t&&(l=!0),r.shouldStop?.({steps:o})&&(l=!0)}return u("max-steps");function u(f){return{text:c?.content??"",steps:o,finishReason:f,usage:s,messages:i,finalTurn:c??{content:"",toolCalls:[],normalizedStopReason:"stop",rawStopReason:"",usage:{promptTokens:0,completionTokens:0,totalTokens:0}}}}async function d(f){if(f.parseError)return p(f,"could not parse the tool arguments as JSON");let m=r.getTool(f.name);if(!m)return p(f,`unknown tool "${f.name}"`);let g=f.args??{},v=r.validateArgs(m,g);if(v)return p(f,`invalid arguments: ${v}`);if(!await r.confirm(f,m))return p(f,"tool call denied by user");let b;try{b=await m.execute(g,{toolCallId:f.id,toolName:f.name})}catch(T){if(r.isAbortError(T))throw T;return p(f,`tool execution failed: ${T instanceof Error?T.message:String(T)}`)}let{content:x,isError:w}=Iae(b,e);return{toolCallId:f.id,name:f.name,content:x,isError:w}}function p(f,m){return{toolCallId:f.id,name:f.name,content:m,isError:!0}}}var iG=E(()=>{});function bS(r,e="schema"){if(r===null||typeof r!="object"||Array.isArray(r))throw new zl(`${e} must be a JSON Schema object.`);for(let t of Object.keys(r))if(!oG.has(t))throw new zl(`${e} uses unsupported JSON Schema keyword "${t}". QuickAdd tool schemas support only: ${[...oG].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 t=Array.isArray(r.type)?r.type:[r.type];for(let n of t)if(!Dae.has(n))throw new zl(`${e} has invalid type "${String(n)}".`)}if(r.properties!==void 0){if(r.properties===null||typeof r.properties!="object"||Array.isArray(r.properties))throw new zl(`${e}.properties must be an object.`);for(let[t,n]of Object.entries(r.properties))bS(n,`${e}.properties.${t}`)}if(r.required!==void 0&&(!Array.isArray(r.required)||r.required.some(t=>typeof t!="string")))throw new zl(`${e}.required must be an array of strings.`);if(r.items!==void 0){if(Array.isArray(r.items))throw new zl(`${e}.items as an array (tuple validation) is not supported in QuickAdd's schema subset.`);bS(r.items,`${e}.items`)}if(r.enum!==void 0&&!Array.isArray(r.enum))throw new zl(`${e}.enum must be an array.`)}function yS(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 Fae(r,e){let t=yS(r);return t===e||e==="number"&&t==="integer"}function Xb(r,e,t="$"){if(e.type!==void 0){let n=Array.isArray(e.type)?e.type:[e.type];if(!n.some(i=>Fae(r,i)))return`${t}: expected ${n.join(" | ")}, got ${yS(r)}`}if(Array.isArray(e.enum)&&!e.enum.some(i=>wS(i,r)))return`${t}: value is not one of the allowed enum values`;if("const"in e&&!wS(e.const,r))return`${t}: value does not equal the required const`;if(yS(r)==="object"){let n=r;if(Array.isArray(e.required)){for(let i of e.required)if(!Object.prototype.hasOwnProperty.call(n,i))return`${t}.${i}: required property is missing`}if(e.properties){for(let[i,o]of Object.entries(e.properties))if(i in n){let s=Xb(n[i],o,`${t}.${i}`);if(s)return s}}}if(yS(r)==="array"&&e.items&&!Array.isArray(e.items)){let n=r;for(let i=0;i<n.length;i++){let o=Xb(n[i],e.items,`${t}[${i}]`);if(o)return o}}return null}function wS(r,e){if(r===e)return!0;if(typeof r!=typeof e)return!1;if(r===null||e===null)return r===e;if(Array.isArray(r)&&Array.isArray(e))return r.length===e.length&&r.every((t,n)=>wS(t,e[n]));if(typeof r=="object"&&typeof e=="object"){let t=Object.keys(r),n=Object.keys(e);return t.length!==n.length?!1:t.every(i=>wS(r[i],e[i]))}return!1}var oG,Dae,zl,sG=E(()=>{oG=new Set(["type","properties","required","items","enum","const","description","title"]),Dae=new Set(["object","array","string","number","integer","boolean","null"]),zl=class extends Error{constructor(e){super(e),this.name="ToolSchemaError"}}});function CS(r){return r.toLowerCase().startsWith(fC)}var KM=E(()=>{Xe()});function xS(r){let e=r.trim();if(!e)throw new Error("assignToVariable cannot be empty.");if(new Set(["value","title","text","meta"]).has(e.toLowerCase()))throw new Error(`assignToVariable "${e}" is reserved (it would hijack a built-in formatter token).`);if(e.toLowerCase().endsWith("-quoted"))throw new Error(`assignToVariable "${e}" cannot end with "-quoted" (collides with the quoted output variable).`);if(CS(e))throw new Error(`assignToVariable "${e}" uses the reserved "__qa." prefix for QuickAdd internal variables.`);if(/[|,]/.test(e))throw new Error(`assignToVariable "${e}" contains characters unreachable by {{VALUE:name}}.`)}var QM=E(()=>{KM()});function Pae(r,e){if(!e||typeof e!="object")return"";let t=e,n=typeof t.path=="string"?t.path.trim():"",i=typeof t.heading=="string"?t.heading.trim():"";if(!n&&!i)return"";let o=[];return n&&o.push(`Target: ${n}`),i&&o.push(`Heading: ${i}`),o.join(" \xB7 ")}function Mae(r){try{return JSON.stringify(r,null,2)??String(r)}catch{return String(r)}}function $ae(r){r.forEach(e=>{e.addEventListener("keydown",t=>{if(t.key==="ArrowRight"||t.key==="ArrowLeft"){let i=(r.indexOf(e)+(t.key==="ArrowRight"?1:-1)+r.length)%r.length;r[i].focus(),t.preventDefault()}})})}var dp,Zb,aG=E(()=>{dp=require("obsidian"),Zb=class r extends dp.Modal{constructor(t,n,i){super(t);this.toolName=n;this.args=i;this.outcome=null;this.waitForClose=new Promise(o=>{this.resolvePromise=o}),this.open(),this.display()}static Prompt(t,n,i){return new r(t,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 t=Pae(this.toolName,this.args);t&&this.contentEl.createEl("p",{cls:"qaAIToolSummary",text:t});let n=this.contentEl.createEl("pre",{cls:"qaAIToolArgs"});n.textContent=Mae(this.args),n.setCssStyles({whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:"16rem",overflowY:"auto"});let i=this.contentEl.createDiv({cls:"yesNoPromptButtonContainer"}),o=new dp.ButtonComponent(i).setButtonText("Abort run").onClick(()=>this.submit("abort")),s=new dp.ButtonComponent(i).setButtonText("Deny").onClick(()=>this.submit("deny")),a=new dp.ButtonComponent(i).setButtonText("Approve all this run").onClick(()=>this.submit("allow-all")),l=new dp.ButtonComponent(i).setButtonText("Approve").onClick(()=>this.submit("allow"));s.buttonEl.focus(),$ae([o.buttonEl,s.buttonEl,a.buttonEl,l.buttonEl])}submit(t){this.outcome=t,this.close()}onClose(){super.onClose(),this.resolvePromise(this.outcome??"deny")}}});function Nae(r){return r instanceof yt}function Lae(r){return{content:r.content,toolCalls:r.toolCalls??[],normalizedStopReason:r.normalizedStopReason??"stop",rawStopReason:r.stopReason,usage:r.usage,providerRaw:r.providerRaw}}function Vae(r){if(r)return typeof r=="string"?r:{name:r.toolName}}function Bae(r){return{toolCallId:r.id,toolName:r.name,input:r.args}}function qae(r){return{toolCallId:r.toolCallId,toolName:r.name,output:r.content,isError:r.isError??!1}}function cG(r,e){let t;try{t=JSON.parse(Uae(r))}catch(i){return{ok:!1,error:`not valid JSON (${i instanceof Error?i.message:String(i)})`}}let n=Xb(t,e);return n?{ok:!1,error:n}:{ok:!0,value:t}}function Uae(r){let e=r.trim(),t=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);return t?t[1]:e}var lG,Oae,Rae,XM,ES,uG=E(()=>{dt();lp();ck();Yn();Ni();Tm();Yd();Um();i0();lk();iG();sG();QM();aG();lG=/^[a-zA-Z0-9_-]{1,64}$/,Oae=20,Rae=100,XM=new WeakSet;ES=class{constructor(e,t,n,i){this.app=e;this.plugin=t;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(!lG.test(s))throw new Error(`Invalid tool name "${s}". Tool names must match ${lG}.`);if(o.has(s))throw new Error(`Duplicate tool name "${s}".`);o.add(s),bS(a.inputSchema,`tool "${s}".inputSchema`)}}async generate(e={}){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 t=typeof e.assignToVariable=="string"&&e.assignToVariable.length>0;if(t&&(this.assertAssignableName(e.assignToVariable),XM.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,t&&XM.add(this.choiceExecutor);let n=ak(this.app);try{return await this.run(e,n)}finally{this.running=!1,t&&XM.delete(this.choiceExecutor);try{n()}catch{}}}async run(e,t){this.approveAllThisRun=!1;let n=X.getState();if(n.disableOnlineFeatures)throw new Error("Rejecting AI request: Online features are disabled in settings.");let{model:i,provider:o}=jy(this.config.model),s=await Ca(this.app,o),a=await this.buildSeedMessages(e),l=this.buildToolDefinitions(),c=this.buildRegistry(),u=e.schema?{schema:e.schema,name:"response",strict:!0}:void 0,d={messages:a,...l.length>0?{tools:l}:{},toolChoice:Vae(e.toolChoice??this.config.toolChoice)??"auto",maxOutputTokens:e.maxOutputTokens??this.config.maxOutputTokens,modelParams:this.config.modelOptions},p=Math.max(1,Math.min(this.config.maxSteps??Oae,Rae)),f=Kd(n.ai.showAssistant);f.setMessage("starting","QuickAdd is running the AI agent.");try{let m=await nG({request:d,maxSteps:p,dispatch:async(v,y)=>{let b=this.buildTurnRequest(v,y.isFinalStep,u),x=await a0(this.app,s,i,o,b,t);return Lae(x)},getTool:v=>c.get(v),confirm:(v,y)=>this.confirm(v,y),validateArgs:(v,y)=>Xb(y,v.definition.parameters),isAbortError:Nae,isContextOverflow:v=>eb(v)==="input_context",isOnlineDisabled:()=>X.getState().disableOnlineFeatures,shouldStop:this.buildShouldStop(),onStepFinish:v=>this.reportStep(f,v)}),g=this.toGenerateResult(m);return e.schema&&(g.object=await this.resolveStructuredObject(m,d,i,o,s,e.schema,t)),typeof e.assignToVariable=="string"&&e.assignToVariable&&this.assignVariable(e.assignToVariable,g.text),f.setMessage("finished",`Ran ${g.steps.length} step${g.steps.length===1?"":"s"}.`),window.setTimeout(()=>f.hide(),5e3),g}catch(m){throw f.setMessage("dead",m?.message??""),window.setTimeout(()=>f.hide(),5e3),m}}reportStep(e,t){let n=t.toolCalls.map(o=>o.name),i=n.length>0?`Step ${t.stepNumber+1}: running ${n.join(", ")}.`:`Step ${t.stepNumber+1}: generating a response.`;e.setMessage("thinking",i)}async buildSeedMessages(e){let t=[],n=e.system??this.config.system??X.getState().ai.defaultSystemPrompt;n&&n.trim().length>0&&t.push({role:"system",content:n});let i=e.prompt??"",o=i?await new ji(this.app,this.plugin,this.choiceExecutor).formatFileContent(i):"";return t.push({role:"user",content:o}),t}buildToolDefinitions(){return Object.entries(this.config.tools??{}).map(([e,t])=>({name:e,description:t.description,parameters:t.inputSchema,...t.strict?{strict:!0}:{}}))}buildRegistry(){let e=new Map;for(let[t,n]of Object.entries(this.config.tools??{}))e.set(t,{definition:{name:t,description:n.description,parameters:n.inputSchema,strict:n.strict},execute:(i,o)=>n.execute(i,o),readOnly:n.readOnly});return e}buildShouldStop(){let e=this.config.stopWhen?Array.isArray(this.config.stopWhen)?this.config.stopWhen:[this.config.stopWhen]:[];if(e.length!==0)return({steps:t})=>{let n=t.flatMap(i=>i.toolCalls.map(o=>o.name));return e.some(i=>i({stepNumber:t.length,toolCallNames:n}))}}buildTurnRequest(e,t,n){return!!(e.tools&&e.tools.length>0)&&!t?{...e,responseFormat:void 0}:{...e,tools:void 0,toolChoice:t?"none":e.toolChoice,responseFormat:n}}async confirm(e,t){let n=e.args??{},i=await this.resolvePerToolApproval(t,n);if(!(i||this.needsGlobalConfirmation(t))||this.approveAllThisRun&&!i)return!0;if(this.choiceExecutor.interactive===!1)throw new ye(`'${e.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 Zb.Prompt(this.app,e.name,e.args??{});if(s==="abort")throw new yt("AI tool run aborted by user");return s==="allow-all"?(this.approveAllThisRun=!0,!0):s==="allow"}async resolvePerToolApproval(e,t){let i=this.config.tools?.[e.definition.name]?.needsApproval;return typeof i=="function"?await i({args:t}):i===!0}needsGlobalConfirmation(e){let t=X.getState().ai.confirmToolCalls??"destructive";return t==="always"?!0:t==="destructive"?e.readOnly!==!0:!1}async resolveStructuredObject(e,t,n,i,o,s,a){let l=cG(e.finalTurn.content,s);if(l.ok)return l.value;if(e.finishReason==="aborted"||e.finishReason==="context-overflow"||X.getState().disableOnlineFeatures)return;let c=[...e.messages,{role:"assistant",content:e.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.`}],u={...t,messages:c,tools:void 0,toolChoice:"none",responseFormat:{schema:s,name:"response",strict:!0}};try{let d=await a0(this.app,o,n,i,u,a),p=cG(d.content,s);return p.ok?p.value:void 0}catch{return}}toGenerateResult(e){let t=e.steps.map(i=>({stepNumber:i.stepNumber,text:i.text,toolCalls:i.toolCalls.map(Bae),toolResults:i.toolResults.map(qae),finishReason:i.finishReason})),n=t[t.length-1];return{text:e.text,steps:t,toolCalls:n?.toolCalls??[],toolResults:n?.toolResults??[],usage:{inputTokens:e.usage.promptTokens,outputTokens:e.usage.completionTokens,totalTokens:e.usage.totalTokens},finishReason:e.finishReason}}assignVariable(e,t){let n=e.trim(),i=("> "+t).replace(/\n/g,`
> `);this.choiceExecutor.variables.set(n,t),this.choiceExecutor.variables.set(`${n}-quoted`,i)}assertAssignableName(e){xS(e)}}});function ZM(r){return(r??"").trim().replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+|\/+$/g,"").normalize("NFC")}function JM(r,e){return e.some(t=>r===t||r.startsWith(`${t}/`))}function pp(r,e){let t=(e??[]).map(n=>ZM(n)).filter(n=>n.length>0);return t.length===0?!0:r?JM(r.normalize("NFC"),t):!1}var TS=E(()=>{});function fp(r,e={}){let t=(r??"").trim();if(!t)throw new ns("Path is empty.");let n=t.replace(/\\/g,"/").normalize("NFC");if(n.startsWith("/")||/^[a-zA-Z]:/.test(n))throw new ns(`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 ns("Path is empty after normalization.");for(let a of o){if(a==="."||a==="..")throw new ns(`Refusing path with a traversal segment ("${a}"): "${i}".`);if(a.startsWith("."))throw new ns(`Refusing to write into a dot/config path segment ("${a}"): "${i}".`);Hae(a,i)}let s=(e.allowedRoots??[]).map(a=>ZM(a)).filter(a=>a.length>0);if(s.length>0&&!JM(i,s))throw new ns(`Path "${i}" is not under an allowed root (${s.join(", ")}).`);return i}function Hae(r,e){if(vv.test(r))throw new ns(`Path segment "${r}" contains control characters: "${e}".`);if(yv.test(r))throw new ns(`Path segment "${r}" contains an illegal character (\\ : * ? " < > |): "${e}".`);if(bv.test(r))throw new ns(`Path segment "${r}" cannot end with a space or a period: "${e}".`);let t=r.split(".")[0]??"";if(t&&kd(t))throw new ns(`Path segment "${r}" is a reserved device name: "${e}".`)}var ns,dG=E(()=>{wv();TS();ns=class extends Error{constructor(e){super(e),this.name="UnsafeVaultPathError"}}});function Ph(r,e){let t=Object.entries(r),n=new Set(t.map(([o])=>o));if(pG(e.only,n,"only"),pG(e.exclude,n,"exclude"),e.only){let o=new Set(e.only);t=t.filter(([s])=>o.has(s))}if(e.exclude){let o=new Set(e.exclude);t=t.filter(([s])=>!o.has(s))}let i=e.prefix??"";return Object.fromEntries(t.map(([o,s])=>[i+o,s]))}function Jb(r){return{...r,__qaTool:!0}}function pG(r,e,t){if(!r)return;let n=r.filter(i=>!e.has(i));n.length!==0&&I.logWarning(`AI tools: ${t} listed unknown tool name(s) ${n.map(i=>`"${i}"`).join(", ")}. Valid names: ${[...e].join(", ")}.`)}var kS=E(()=>{Ie()});function bG(r,e={}){let t=e.allowedRoots,n={read_note:mp({description:"Read a note's full markdown content by vault path.",inputSchema:hp({path:is("Vault path to the note, e.g. Notes/Foo.md")},["path"]),readOnly:!0,execute:async({path:i})=>{let o=fp(String(i),{allowedRoots:t}),s=r.vault.getAbstractFileByPath(o);if(!(s instanceof t$.TFile))return{found:!1,path:o};let a=await r.vault.cachedRead(s);return{found:!0,path:o,content:a.length>fG?a.slice(0,fG)+`
\u2026[truncated]`:a}}}),list_notes:mp({description:"List markdown notes, optionally within a folder.",inputSchema:hp({folder:is("Folder to list (omit for the whole vault)."),limit:mG("Max results (default 100, capped at 200).")},[]),readOnly:!0,execute:async({folder:i,limit:o})=>{let s=i?fp(String(i),{allowedRoots:t}):"",a=vG(gG(o,zae),1,Wae),l=Bo(r,s).filter(c=>pp(c.path,t));return{total:l.length,notes:l.slice(0,a).map(c=>({path:c.path,basename:c.basename}))}}}),search_notes:mp({description:"Search notes by name and/or content. Returns matching paths with a short snippet.",inputSchema:hp({query:is("Text to search for."),in:hG(["name","content","both"],"Where to search (default both)."),limit:mG("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=vG(gG(s,jae),1,Gae),u=r.vault.getMarkdownFiles().filter(m=>pp(m.path,t)),d=[],p=0,f=!1;for(let m of u){if(d.length>=c)break;if(l!=="content"&&m.basename.toLowerCase().includes(a)){d.push({path:m.path});continue}if(l!=="name"){if(p>=Yae){f=!0;continue}p++;let v=await r.vault.cachedRead(m),y=v.toLowerCase().indexOf(a);y>=0&&d.push({path:m.path,snippet:Qae(v,y)})}}return{results:d,scannedFiles:p,truncated:d.length>=c||f}}}),get_property_values:mp({description:"List the distinct values a frontmatter property takes across the vault (e.g. existing tags or statuses).",inputSchema:hp({field:is("Frontmatter property name."),folder:is("Optional folder scope.")},["field"]),readOnly:!0,execute:async({field:i,folder:o})=>{let s=o?fp(String(o),{allowedRoots:t}):"",a=(o?Bo(r,s):r.vault.getMarkdownFiles()).filter(c=>pp(c.path,t)),l=new Set;for(let c of a){let d=r.metadataCache.getFileCache(c)?.frontmatter?.[String(i)];if(d!=null){for(let p of Array.isArray(d)?d:[d])if(typeof p!="object"){let f=String(p).trim();f&&l.add(f)}}}return{field:String(i),values:[...l].sort().slice(0,200)}}}),create_note:mp({description:"Create a new markdown note. Fails if the path already exists.",inputSchema:hp({path:is("Vault path for the new note."),content:is("Initial markdown content.")},["path"]),needsApproval:!0,execute:async({path:i,content:o})=>{let s=fp(e$(String(i)),{allowedRoots:t});return await Km(r,s),await Kae(r,s),{created:!0,path:(await r.vault.create(s,String(o??""))).path}}}),append_to_note:mp({description:"Append text to an existing note (frontmatter-aware for top inserts).",inputSchema:hp({path:is("Vault path to the existing note."),content:is("Markdown to append."),position:hG(["top","bottom"],"Where to add it (default bottom).")},["path","content"]),needsApproval:!0,execute:async({path:i,content:o,position:s})=>{let a=fp(e$(String(i)),{allowedRoots:t}),l=yG(r,a);await Km(r,a);let c=await r.vault.read(l),u=String(o),d=s==="top"?Z3(c,u.endsWith(`
`)?u:u+`
`):`${c}${c.endsWith(`
`)||c.length===0?"":`
`}${u}`;return await r.vault.modify(l,d),{appended:!0,path:a}}}),insert_under_heading:mp({description:"Insert markdown under an existing heading (matched exactly). Errors if the heading is not found.",inputSchema:hp({path:is("Vault path to the existing note."),heading:is("Exact heading text (without the # markers)."),content:is("Markdown to insert under the heading.")},["path","heading","content"]),needsApproval:!0,execute:async({path:i,heading:o,content:s})=>{let a=fp(e$(String(i)),{allowedRoots:t}),l=yG(r,a);await Km(r,a);let c=r.metadataCache.getFileCache(l)?.headings??[],u=c.find(f=>f.heading===String(o));if(!u)throw new Error(`Heading "${o}" not found in ${a}`);let d=await r.vault.read(l),p=Xae(d,u.position.start.line,u.level,String(s),c);return await r.vault.modify(l,p),{inserted:!0,path:a,heading:String(o)}}})};return Ph(n,e)}function mp(r){return{...r,__qaTool:!0}}function hp(r,e){return{type:"object",properties:r,required:e}}function is(r){return{type:"string",description:r}}function mG(r){return{type:"integer",description:r}}function hG(r,e){return{type:"string",enum:r,description:e}}function gG(r,e){let t=Number(r);return Number.isFinite(t)?Math.floor(t):e}function vG(r,e,t){return Math.max(e,Math.min(t,r))}function e$(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 yG(r,e){let t=r.vault.getAbstractFileByPath(e);if(!(t instanceof t$.TFile))throw new Error(`Note not found: ${e}`);return t}async function Kae(r,e){let t=e.lastIndexOf("/");if(t<=0)return;let n=e.slice(0,t);if(!r.vault.getAbstractFileByPath(n))try{await r.vault.createFolder(n)}catch{}}function Qae(r,e){let t=Math.max(0,e-40);return r.slice(t,e+80).replace(/\s+/g," ").trim()}function Xae(r,e,t,n,i){let o=r.split(`
`),s=o.length;for(let u of i)if(u.position.start.line>e&&u.level<=t){s=u.position.start.line;break}let a=n.endsWith(`
`)?n:n+`
`,l=o.slice(0,s),c=o.slice(s);for(;l.length>e+1&&l[l.length-1].trim()==="";)l.pop();return[...l,a.replace(/\n$/,""),...c].join(`
`)}var t$,fG,zae,Wae,jae,Gae,Yae,wG=E(()=>{t$=require("obsidian");ht();wu();TS();dG();TP();kS();fG=16e3,zae=100,Wae=200,jae=25,Gae=50,Yae=400});function xG(r,e={}){let t=e.allowedRoots,n=()=>{let s=r.workspace.getActiveFile();return!(s instanceof SS.TFile)||s.extension!=="md"?null:pp(s.path,t)?s:null},i=()=>{let s=r.workspace.getActiveViewOfType(SS.MarkdownView);return s&&pp(s.file?.path,t)?s:null},o={get_active_note:Jb({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>CG?a.slice(0,CG)+`
\u2026[truncated]`:a}}}}),get_selection:Jb({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 Ph(o,e)}var SS,CG,EG=E(()=>{SS=require("obsidian");TS();kS();CG=16e3});function TG(r={}){let e={get_date:Jb({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:t,offset:n})=>({date:aa({format:t!=null?String(t):void 0,offset:n!=null?Number(n):void 0})})})};return Ph(e,r)}var kG=E(()=>{ht();kS()});function _G(r,e,t,n){async function i(s,a){let l=X.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:u}=jy(s),d=await Ca(r,u);return a?.assignToVariable&&xS(a.assignToVariable),{model:c,provider:u,apiKey:d,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 Ze(new Error("AI Assistant returned null"),l),{};if(a?.shouldAssignVariables||a?.assignToVariable)for(let[c,u]of Object.entries(s))t.variables.set(c,u);return s}return{prompt:async(s,a,l)=>{let c=await Lz(r,{...await i(a,l),prompt:s},(u,d)=>n(u,d,!1));return o(c,l,"AI Prompt error")},chunkedPrompt:async(s,a,l,c,u)=>{let d=await c0(r,{...await i(l,c),text:s,promptTemplate:a,chunkSeparator:c?.chunkSeparator??/\n/,resultJoiner:c?.chunkJoiner??`
`,shouldMerge:c?.shouldMerge??!0,maxChunkTokens:c?.maxChunkTokens},(p,f)=>n(p,{...u,...f},!1));return o(d,c,"Chunked AI Prompt error")},getModels:()=>bU(),getMaxTokens:s=>jy(s).model.maxTokens,estimateTokens(s){return Ui(s)},countTokens(s,a){return SG||(SG=!0,I.logMessage("quickAddApi.ai.countTokens is deprecated and now returns a provider-agnostic estimate (the model argument is ignored). Use estimateTokens(text) instead.")),Ui(s)},getRequestLogs(s=10){return yz(s)},getRequestLogById(s){return wz(s)},getLastRequestLog(){return Cz()},clearRequestLogs(){xz()},agent:s=>new ES(r,e,t,s),tool:s=>({...s,__qaTool:!0}),stepCountIs:s=>({stepNumber:a})=>a>=s,hasToolCall:s=>({toolCallNames:a})=>a.includes(s),tools:{vault:s=>bG(r,s),workspace:s=>xG(r,s),system:s=>TG(s)}}}var SG,AG=E(()=>{u0();Tm();Yd();Wy();uG();QM();wG();EG();kG();dt();xt();Ie();SG=!1});function IG(r){return{getFieldValues:async(e,t)=>{let n=t?.includeInlineCodeBlocks?.map(a=>a.trim().toLowerCase()).filter(a=>a.length>0),i={folder:t?.folder,folders:t?.folders,tags:t?.tags,inline:t?.includeInline??!1,inlineCodeBlocks:n},o=r.vault.getMarkdownFiles();o=xi.filterFiles(o,i,a=>r.metadataCache.getFileCache(a));let s=new Set;for(let a of o){let c=r.metadataCache.getFileCache(a)?.frontmatter?.[e];if(c!=null){if(Array.isArray(c))c.forEach(u=>{if(u==null||typeof u=="object")return;let d=String(u).trim();d&&s.add(d)});else if(typeof c!="object"){let u=String(c).trim();u&&s.add(u)}}if(i.inline)try{let u=await r.vault.read(a);fh.getFieldValues(u,e,{includeCodeBlocks:n}).forEach(p=>s.add(p))}catch{}}return Array.from(s).sort()},clearCache:e=>{Vl.getInstance().clear(e)}}}var DG=E(()=>{Lk();pd();oM()});function FG(r){return Array.from(r.entries())}function PG(r,e){r.clear();for(let[t,n]of e)r.set(t,n)}var ci,Mh,r$=E(()=>{lp();SM();Zk();ys();xh();xt();ht();_M();rG();AG();DG();ci=class ci{static GetApi(e,t,n){let i=async(o,s,a=!0)=>{let l=a?FG(n.variables):null;s&&Object.keys(s).forEach(u=>{n.variables.set(u,s[u])});let c=await new ji(e,t,n).formatFileContent(o);return a&&l&&PG(n.variables,l),c};return{requestInputs:o=>tG(e,n,o),inputPrompt:(o,s,a,l)=>{let c=n?.promptProvider;return c?c.inputPrompt(o,s,a):ci.inputPrompt(e,o,s,a,l)},datePrompt:(o,s)=>{let a=n?.promptProvider;return a?a.datePrompt(o,s):ci.datePrompt(e,o,s)},wideInputPrompt:(o,s,a,l)=>{let c=n?.promptProvider;return c?c.wideInputPrompt(o,s,a):ci.wideInputPrompt(e,o,s,a,l)},yesNoPrompt:(o,s)=>{let a=n?.promptProvider;return a?a.yesNoPrompt(o,s):ci.yesNoPrompt(e,o,s)},infoDialog:(o,s)=>{let a=n?.promptProvider;return a?a.infoDialog(o,s):ci.infoDialog(e,o,s)},suggester:(o,s,a,l=!1,c)=>{let u=n?.promptProvider;return u?u.suggester(o,s,a,l):ci.suggester(e,o,s,a,l,c)},checkboxPrompt:(o,s,a)=>{let l=n?.promptProvider;return l?l.checkboxPrompt(o,s,a):ci.checkboxPrompt(e,o,s,a)},executeChoice:async(o,s,a)=>{let l;try{l=t.getChoiceByName(o)}catch{l=void 0}if(!l){Ze(new Error(`Choice named '${o}' not found`),"API executeChoice error");return}if(!Ch(n,a?.date)){Ze(new Error(`Could not parse date origin '${String(a?.date)}'`),"API executeChoice error");return}s&&Object.keys(s).forEach(u=>{n.variables.set(u,s[u])}),await n.execute(l);let c=n.consumeAbortSignal?.();if(n.variables.clear(),c)throw c},applyTemplateToActiveFile:async(o,s)=>{if(!o)throw new Error("applyTemplateToActiveFile requires a template path.");if(!wh(o))throw new Error("applyTemplateToActiveFile only supports markdown templates. Canvas and base templates cannot be applied to a markdown note.");if(s?.mode!==void 0&&!pj(s.mode))throw new Error(`Invalid mode '${String(s.mode)}'. Valid modes: ${Bb.map(l=>l.id).join(", ")}.`);let a=FG(n.variables);try{return await qb(e,t,{templatePath:o,mode:s?.mode,choiceExecutor:n})}finally{PG(n.variables,a)}},format:i,ai:_G(e,t,n,i),utility:{getClipboard:async()=>await navigator.clipboard.readText(),setClipboard:async o=>await navigator.clipboard.writeText(o),getSelection:()=>sl(e),getSelectedText:()=>{let o=xn(e);return o?o.editor.somethingSelected()?o.editor.getSelection():(Ze(new Error("No text selected"),"Could not get selected text"),""):(Ze(new Error("No active Markdown editor"),"Could not get selected text"),"")}},date:{now:(o,s)=>aa({format:o,offset:s}),tomorrow:o=>aa({format:o,offset:1}),yesterday:o=>aa({format:o,offset:-1})},fieldSuggestions:IG(e)}}};ci.inputPrompt=Fa.inputPrompt,ci.datePrompt=Fa.datePrompt,ci.wideInputPrompt=Fa.wideInputPrompt,ci.yesNoPrompt=Fa.yesNoPrompt,ci.infoDialog=Fa.infoDialog,ci.suggester=Fa.suggester,ci.checkboxPrompt=Fa.checkboxPrompt;Mh=ci});function n$(r){return r!==null&&typeof r=="object"}function MG(r){return typeof r=="function"}async function $G(r,e){let{app:t,plugin:n,choiceName:i,params:o,executor:s,preloadedUserScripts:a,promptLabel:l}=e,c=AC(r),u=c===void 0?void 0:a.get(c);if(c!==void 0&&u!==void 0&&a.delete(c),u===void 0&&(u=await Lo(r,t)),!u){I.logError(`failed to load user script ${r.path}.`);return}r.settings||(r.settings={});let d=n$(u)?u.settings:void 0,p=n$(d)?d:void 0;p&&Em(r.settings,p);async function f(g){let v=await zk(t,n,r,p);return{output:await g(o,v)}}async function m(g){if(MG(g))return f(g);if(n$(g)){if(Object.keys(g).length===0)throw new Error(`user script in macro for '${i}' is an empty object`);if(MG(g.entry))return f(g.entry);let v=Object.keys(g);try{let y=String(await wo(s,{remote:b=>Co(b,{items:v.map(x=>({value:x,title:x})),placeholder:l,what:"the user-script member picker"}),headless:()=>{if(v.length===1)return Promise.resolve(v[0]);throw new ye("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:()=>Xt.Suggest(t,v,v,l)}));if(!Object.hasOwn(g,y))throw new Error(`This macro's user script does not export a member named "${y}".`);return await m(g[y])}catch(y){throw y instanceof yt?y:ot(y)?new at("Input cancelled by user"):y}}switch(typeof g){case"bigint":case"boolean":case"number":case"string":return{output:g.toString()};case"object":return;default:I.logError(`user script in macro for '${i}' is invalid`)}}try{return await m(u)}catch(g){throw g instanceof yt||Ze(g,`Failed to run user script ${r.name} in "${i}"`),g}}var OG=E(()=>{ht();IC();YE();fM();Ie();xt();Ni();Yn();ur();Zo();sp();ap()});var $h,i$=E(()=>{vM();$h=class extends mh{}});function RG(r){return new Promise(e=>window.setTimeout(e,r))}function Eu(r){return r.split(`
`)}var ew=E(()=>{});async function LG(r,e){return r.mode==="script"?await e.evaluateScriptCondition(r):Zae(r,e.variables)}function Zae(r,e){let t=r.variableName?.trim();if(!t)return I.logWarning("Conditional command skipped: No variable name configured."),!1;if(!(t in e))return I.logWarning(`Conditional command skipped: Variable '${t}' is not defined.`),!1;let n=e[t];switch(r.operator){case"isTruthy":return!!n;case"isFalsy":return!n}if(Nc(r.operator)){let i=I2(r);return i===void 0?(I.logWarning(`Conditional command: Operator '${r.operator}' requires a comparison value.`),!1):r.operator==="contains"?NG(n,i,r):r.operator==="notContains"?!NG(n,i,r):Jae(n,i,r)}return!1}function NG(r,e,t){if(r==null)return!1;if(typeof e=="string"&&e.length===0)return I.logWarning("Conditional command: 'contains' operator requires a non-empty comparison value."),!1;if(Array.isArray(r))return r.map(o=>mD(o,t.valueType)).some(o=>o===e);if(typeof r=="string")return r.includes(ua(e));if(typeof r=="number"&&typeof e=="number")return r===e;let n=ua(r),i=ua(e);return typeof n=="string"&&n.includes(i)}function Jae(r,e,t){let n=mD(r,t.valueType);switch(t.operator){case"equals":return n===e;case"notEquals":return n!==e;case"lessThan":return _S(n,e,(i,o)=>i<o);case"lessThanOrEqual":return _S(n,e,(i,o)=>i<=o);case"greaterThan":return _S(n,e,(i,o)=>i>o);case"greaterThanOrEqual":return _S(n,e,(i,o)=>i>=o);default:return!1}}function _S(r,e,t){let n=Number(r),i=Number(e);return Number.isNaN(n)||Number.isNaN(i)?(I.logWarning("Conditional command numeric comparison failed: non-numeric value encountered."),!1):t(n,i)}var VG=E(()=>{Ie();Id()});function BG(r,e=void 0){return r==="horizontal"?"horizontal":r==="vertical"?"vertical":e}function Tu(r,e,t){return t?{location:r,direction:t,focus:e,mode:"default"}:{location:r,focus:e,mode:"default"}}function qG(r){let e=r.focus??!0;if(r.location)switch(r.location){case"reuse":return Tu("reuse",e);case"tab":return Tu("tab",e);case"split":return Tu("split",e,BG(r.direction,"vertical"));case"window":return Tu("window",e);case"left-sidebar":return Tu("left-sidebar",e);case"right-sidebar":return Tu("right-sidebar",e);default:break}let t=r.openInNewTab??!1,n=BG(r.direction);return t?Tu("split",e,n??"vertical"):Tu("reuse",e)}var UG=E(()=>{eT()});function HG(r){let e={hasOwnProperty:t=>r.has(t)};return new Proxy(e,{get(t,n){if(n==="hasOwnProperty")return e.hasOwnProperty;if(typeof n=="string")return r.get(n)},set(t,n,i){return typeof n!="string"||r.set(n,i),!0},deleteProperty(t,n){return typeof n!="string"||r.delete(n),!0},has(t,n){return typeof n=="string"&&r.has(n)},ownKeys(){return Array.from(r.keys())},getOwnPropertyDescriptor(t,n){if(n==="hasOwnProperty")return{value:e.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 zG=E(()=>{});function WG(r,e="command"){if(typeof r!="string"||!r.trim())return`the saved entry has no ${e} type, so QuickAdd cannot tell what it was meant to do. It is in .obsidian/plugins/quickadd/data.json.`;let t=e==="command"?tle.get(r):void 0;return t||`QuickAdd does not recognise the ${e} type '${r}'. It can come from a newer version of QuickAdd, an imported package, or a hand-edited .obsidian/plugins/quickadd/data.json.`}function jG(r){return`${r.scriptPath}::${r.exportName??"default"}`}var ele,GG,tle,_a,Ob=E(()=>{lj();Qk();ele=z$(require("obsidian"));Ie();xt();vr();r$();OG();i$();_s();ht();ho();qF();BF();UF();HF();zF();WF();jF();GF();YF();KF();ew();lp();ht();GG=require("obsidian");Ni();VG();$b();UG();zG();un();Ah();uS();Dh();tle=new Map([["InfiniteAIAssistant",'QuickAdd has removed the "Infinite AI Assistant" command type - 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.']]);_a=class extends $h{constructor(t,n,i,o,s,a,l,c=null){super(t);this.originLeaf=c;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(t,n,o,u)}buildParams(t,n,i,o){let s=HG(o),a={app:t,quickAddApi:Mh.GetApi(t,n,i),obsidian:ele,abort:l=>{throw new yt(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(([u])=>typeof u=="string"):l&&typeof l=="object"?Object.entries(l):null;c&&(o.clear(),c?.forEach(([u,d])=>o.set(u,d)))},enumerable:!0,configurable:!1}),a}initSharedVariables(t,n){let i=t.variables;return n?(i&&n!==i&&i.forEach((o,s)=>{n.has(s)||n.set(s,o)}),n):i??new Map}async run(){if(sr(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 t=Ht(this.macro?.commands);if(t.length===0){zy(this.macro?.commands)||I.logError(`No commands in the macro for choice '${this.choice.name}'`);return}await this.executeCommands(t)}getOutput(){return this.output}async executeCommands(t){try{for(let[n,i]of t.entries()){if(!i)continue;let o=i.type==="Choice"||i.type==="NestedChoice"?_h(i,a=>cp(this.plugin,a)):null,s=o?.collect.kind==="scanChoice"&&OM(o.collect.choice,this.choiceExecutor.variables.get("value"));await Qb(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 RG(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 a=i.type;this.reportUnrunnableCommand(i,WG(a));break}}}),s&&await this.choiceExecutor.prepareMacroInputs(this.choice,t.slice(n+1))}}catch(n){if(bu(n,{logPrefix:"Macro execution aborted",noticePrefix:"Macro execution aborted",defaultReason:"Macro execution aborted"})){this.choiceExecutor.signalAbort?.(n);return}throw n}}reportUnrunnableCommand(t,n){let i=typeof t?.name=="string"&&t.name.trim()?`'${t.name}'`:"an unnamed command";I.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(t){let n=await $G(t,{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(t){let n=this.app.commands.commands;if(n&&!n[t.commandId]){I.logError(`Obsidian command '${t.name}' is no longer available.`);return}this.app.commands.executeCommandById(t.commandId)}async executeChoice(t){let n;try{n=this.plugin.getChoiceById(t.choiceId)}catch(o){let s=o instanceof Error?o.message:String(o);if(!/not found/i.test(s))throw o;I.logError(`choice '${t.name}' could not be found.`);return}await this.choiceExecutor.execute(n);let i=this.choiceExecutor.consumeAbortSignal?.();if(i)throw i}async executeNestedChoice(t){let n=t.choice;if(!n){I.logError(`choice in ${t.name} is invalid`);return}await this.choiceExecutor.execute(n);let i=this.choiceExecutor.consumeAbortSignal?.();if(i)throw i}async executeEditorCommand(t){switch(t.editorCommandType){case"Cut":await _m.run(this.app);break;case"Copy":await Sm.run(this.app);break;case"Paste":await Am.run(this.app);break;case"Paste with format":await Im.run(this.app);break;case"Select active line":Dm.run(this.app);break;case"Select link on active line":Fm.run(this.app);break;case"Move cursor to file start":Pm.run(this.app);break;case"Move cursor to file end":Mm.run(this.app);break;case"Move cursor to line start":$m.run(this.app);break;case"Move cursor to line end":Om.run(this.app);break;default:{let n=t.editorCommandType;this.reportUnrunnableCommand(t,WG(n,"editor command"))}}}async executeAIAssistant(t){return sj(this.app,this.choice,this.choiceExecutor,t,()=>this.pickModelInteractively())}async pickModelInteractively(){return aj(this.app,this.choiceExecutor)}async executeConditional(t){let n=await LG(t.condition,{variables:this.params.variables,evaluateScriptCondition:async s=>await this.evaluateScriptCondition(s)}),i=n?t.thenCommands:t.elseCommands;if(sr(i))throw new Error(`Could not read the ${n?"then":"else"} commands for '${t.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(t){t?.length&&await this.executeCommands(t)}setOutput(t){this.output=t}async evaluateScriptCondition(t){let n=jG(t),i=this.conditionalScriptCache.get(n);if(!i){if(i=await this.loadConditionalScript(t),!i)return!1;this.conditionalScriptCache.set(n,i)}let o;try{o=await i()}catch(s){throw Ze(s,`Failed to evaluate conditional script '${t.scriptPath}'.`),s}return typeof o!="boolean"?(I.logWarning(`Conditional script '${t.scriptPath}' must return a boolean result.`),!1):o}async loadConditionalScript(t){try{let n=await Lo(this.buildConditionalUserScript(t),this.app);return n==null?void 0:typeof n=="function"?async()=>await n(this.params):async()=>n}catch(n){throw Ze(n,`Failed to load conditional script '${t.scriptPath}'.`),n}}buildConditionalUserScript(t){return{id:`conditional-script-${jG(t)}`,name:t.exportName?`${t.scriptPath}::${t.exportName}`:t.scriptPath,type:"UserScript",path:t.scriptPath,settings:{}}}async executeOpenFile(t){try{let n=new ji(this.app,on(),this.choiceExecutor);n.setPromptRunContext({choiceName:this.choice?.name,draftScopeId:`${this.choice?.id??"macro"}#openFile:${t.id}`});let o=(await n.formatFileName(t.filePath,"filePath")).replace(/\\/g,"/"),s=o.split("/");if(s.some((u,d)=>u===".."||u===""&&d!==0&&d!==s.length-1)){I.logError(`OpenFile: Path traversal not allowed in '${o}'`);return}let l=this.app.vault.getAbstractFileByPath(o);if(!l||!(l instanceof GG.TFile)){I.logError(`OpenFile: '${o}' does not exist or is not a file`);return}let c=qG(t);await Hg(this.app,l,{...c,originLeaf:this.originLeaf})}catch(n){I.logError(`OpenFile: Failed to open file '${t.filePath}': ${n.message}`)}}}});var Vce={};fw(Vce,{default:()=>l_});module.exports=N4(Vce);var c_=require("obsidian");var lu=require("obsidian");var W$;typeof window<"u"&&((W$=window.__svelte??(window.__svelte={})).v??(W$.v=new Set)).add("5");var qa={};var jt=Symbol("uninitialized"),To=Symbol("filename");var mw="http://www.w3.org/1999/xhtml";var hw=!0;var j$=globalThis.process?.env?.NODE_ENV,Q=j$&&!j$.toLowerCase().startsWith("prod");var ko=Array.isArray,G$=Array.prototype.indexOf,Jl=Array.prototype.includes,Ep=Array.from,h_=Object.keys,pn=Object.defineProperty,Fi=Object.getOwnPropertyDescriptor,gw=Object.getOwnPropertyDescriptors,vw=Object.prototype,Y$=Array.prototype,ec=Object.getPrototypeOf,g_=Object.isExtensible;function v_(r){return typeof r=="function"}var Ct=()=>{};function yw(r){for(var e=0;e<r.length;e++)r[e]()}function bw(){var r,e,t=new Promise((n,i)=>{r=n,e=i});return{promise:t,resolve:r,reject:e}}var On=Symbol("$state"),ww=Symbol("component"),Wh=Symbol("legacy props"),K$=Symbol(""),Cw=Symbol("proxy path"),xw=Symbol("attributes"),jh=Symbol("class"),Gh=Symbol("style"),Yh=Symbol("text"),tc=Symbol("form reset"),y_=Symbol("hmr anchor"),Ua=new class extends Error{constructor(){super(...arguments);he(this,"name","StaleReactionError");he(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}},Ew=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml");var Du=3,Gi=8;var Ha="font-weight: bold",za="font-weight: normal";function Q$(r){Q?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`,Ha,za):console.warn("https://svelte.dev/e/await_reactivity_loss")}function X$(r,e){Q?console.warn(`%c[svelte] await_waterfall
%cAn async derived, \`${r}\` (${e}) 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`,Ha,za):console.warn("https://svelte.dev/e/await_waterfall")}function Z$(){Q?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`,Ha,za):console.warn("https://svelte.dev/e/derived_inert")}function J$(r,e,t){Q?console.warn(`%c[svelte] hydration_attribute_changed
%cThe \`${r}\` attribute on \`${e}\` changed its value between server and client renders. The client value, \`${t}\`, will be ignored in favour of the server value
https://svelte.dev/e/hydration_attribute_changed`,Ha,za):console.warn("https://svelte.dev/e/hydration_attribute_changed")}function Fu(r){Q?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`,Ha,za):console.warn("https://svelte.dev/e/hydration_mismatch")}function eO(){Q?console.warn(`%c[svelte] lifecycle_double_unmount
%cTried to unmount a component that was not mounted
https://svelte.dev/e/lifecycle_double_unmount`,Ha,za):console.warn("https://svelte.dev/e/lifecycle_double_unmount")}function tO(){Q?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",Ha,za):console.warn("https://svelte.dev/e/select_multiple_invalid_value")}function Tw(r){Q?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`,Ha,za):console.warn("https://svelte.dev/e/state_proxy_equality_mismatch")}function rO(){Q?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",Ha,za):console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}var Me=!1;function jr(r){Me=r}var Ye;function Vt(r){if(r===null)throw Fu(),qa;return Ye=r}function fn(){return Vt(Nn(Ye))}function N(r){if(Me){if(Nn(Ye)!==null)throw Fu(),qa;Ye=r}}function Gr(r=1){if(Me){for(var e=r,t=Ye;e--;)t=Nn(t);Ye=t}}function Ks(r=!0){for(var e=0,t=Ye;;){if(t.nodeType===Gi){var n=t.data;if(n==="]"){if(e===0)return t;e-=1}else(n==="["||n==="[!"||n[0]==="["&&!isNaN(Number(n.slice(1))))&&(e+=1)}var i=Nn(t);r&&t.remove(),t=i}}function Qh(r){if(!r||r.nodeType!==Gi)throw Fu(),qa;return r.data}function kw(r){return r===this.v}function Sw(r,e){return r!=r?e==e:r!==e||r!==null&&typeof r=="object"||typeof r=="function"}function _w(r){return!Sw(r,this.v)}function nO(r){if(Q){let e=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 e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/invariant_violation")}function Aw(r){if(Q){let e=new Error(`lifecycle_outside_component
\`${r}(...)\` can only be used during component initialisation
https://svelte.dev/e/lifecycle_outside_component`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function oO(){if(Q){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 b_(){if(Q){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 sO(){if(Q){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 w_(r,e,t){if(Q){let n=new Error(`each_key_duplicate
${t?`Keyed each block has duplicate key \`${t}\` at indexes ${r} and ${e}`:`Keyed each block has duplicate key at indexes ${r} and ${e}`}
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 aO(r,e,t){if(Q){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 \`${e}\` but is now \`${t}\`. 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 lO(r){if(Q){let e=new Error(`effect_in_teardown
\`${r}\` cannot be used inside an effect cleanup function
https://svelte.dev/e/effect_in_teardown`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/effect_in_teardown")}function cO(){if(Q){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 uO(r){if(Q){let e=new Error(`effect_orphan
\`${r}\` can only be used inside an effect (e.g. during component initialisation)
https://svelte.dev/e/effect_orphan`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/effect_orphan")}function dO(){if(Q){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 pO(){if(Q){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 fO(){if(Q){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 mO(r){if(Q){let e=new Error(`props_invalid_value
Cannot do \`bind:${r}={undefined}\` when \`${r}\` has a fallback value
https://svelte.dev/e/props_invalid_value`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/props_invalid_value")}function hO(r){if(Q){let e=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 e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/rune_outside_svelte")}function gO(){if(Q){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 vO(){if(Q){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 yO(){if(Q){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 bO(){if(Q){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 Ar=!1,Wa=!1,ss=!1;var V4="font-weight: bold",B4="font-weight: normal";function C_(r){Q?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`,V4,B4):console.warn("https://svelte.dev/e/state_snapshot_uncloneable")}var q4=[];function Pu(r,e=!1,t=!1){if(Q&&!e){let n=[],i=Xh(r,new Map,"",n,null,t);if(n.length===1&&n[0]==="")C_();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`),C_(a)}return i}return Xh(r,new Map,"",q4,null,t)}function Xh(r,e,t,n,i=null,o=!1){if(typeof r=="object"&&r!==null){var s=e.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(ko(r)){var a=Array(r.length);e.set(r,a),i!==null&&e.set(i,a);for(var l=0;l<r.length;l+=1){var c=r[l];l in r&&(a[l]=Xh(c,e,Q?`${t}[${l}]`:t,n,null,o))}return a}if(ec(r)===vw){a={},e.set(r,a),i!==null&&e.set(i,a);for(var u of Object.keys(r))a[u]=Xh(r[u],e,Q?`${t}.${u}`:t,n,null,o);return a}if(r instanceof Date)return r.getTime(),structuredClone(r);if(typeof r.toJSON=="function"&&!o)return Xh(r.toJSON(),e,Q?`${t}.toJSON()`:t,n,r)}if(r instanceof EventTarget)return r;try{return structuredClone(r)}catch{return Q&&n.push(t),r}}var Zh=null;function Zn(r,e){return r.label=e,Iw(r.v,e),r}function Iw(r,e){return r?.[Cw]?.(e),r}function as(r){let e=new Error,t=U4();return t.length===0?null:(t.unshift(`
`),pn(e,"stack",{value:t.join(`
`)}),pn(e,"name",{value:r}),e)}function U4(){let r=Error.stackTraceLimit;Error.stackTraceLimit=1/0;let e=new Error().stack;if(Error.stackTraceLimit=r,!e)return[];let t=e.split(`
`),n=[];for(let i=0;i<t.length;i++){let o=t[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 CO(r,e){if(!Q)throw new Error("invariant(...) was not guarded by if (DEV)");r||nO(e)}var ct=null;function ja(r){ct=r}var Qs=null;function Sp(r){Qs=r}var ls=null;function Dw(r){ls=r}function pe(r,e=!1,t){ct={p:ct,i:!1,c:null,e:null,s:r,x:null,r:Pe,l:Wa&&!e?{s:null,u:null,$:[]}:null},Q&&(ct.function=t,ls=t)}function fe(r){var e=ct,t=e.e;if(t!==null){e.e=null;for(var n of t)x_(n)}return r!==void 0&&(e.x=r),e.i=!0,ct=e.p,Q&&(ls=ct?.function??null),Jh(r)}function Jh(r={}){return pn(r,ww,{value:!0}),r}function cs(){return!Wa||ct!==null&&ct.l===null}var Mu=[];function xO(){var r=Mu;Mu=[],yw(r)}function yr(r){if(Mu.length===0&&!$u){var e=Mu;queueMicrotask(()=>{e===Mu&&xO()})}Mu.push(r)}function EO(){for(;Mu.length>0;)xO()}var H4=-7169;function Bt(r,e){r.f=r.f&H4|e}function _p(r){(r.f&512)!==0||r.deps===null?Bt(r,1024):Bt(r,4096)}function TO(r){if(r!==null)for(let e of r)(e.f&2)===0||(e.f&65536)===0||(e.f^=65536,TO(e.deps))}function Fw(r,e,t){(r.f&2048)!==0?e.add(r):(r.f&4096)!==0&&t.add(r),TO(r.deps),Bt(r,1024)}var kO=!1,Pw=!1;function E_(r){var e=Pw;try{return Pw=!1,[r(),Pw]}finally{Pw=e}}function Nu(r){Me&&gn(r)!==null&&Ip(r)}var SO=!1;function Mw(){SO||(SO=!0,document.addEventListener("reset",r=>{Promise.resolve().then(()=>{if(!r.defaultPrevented)for(let e of r.target.elements)e[tc]?.()})},{capture:!0}))}function Ao(r){var e=ze,t=Pe;Qr(null),Xr(null);try{return r()}finally{Qr(e),Xr(t)}}function $w(r,e,t,n=t){r.addEventListener(e,()=>Ao(t));let i=r[tc];i?r[tc]=()=>{i(),n(!0)}:r[tc]=()=>n(!0),Mw()}function Ow(r,e,t,n){let i=cs()?nc:Lu;var o=r.filter(f=>!f.settled),s=e.map(i);if(Q&&s.forEach((f,m)=>{f.label=e[m].toString().replace("() => ","").replaceAll("$.eager(() => ","$state.eager(").replace(/\$\.get\((.+?)\)/g,(g,v)=>v)}),t.length===0&&o.length===0){n(s);return}var a=Pe,l=_O(),c=o.length===1?o[0].promise:o.length>1?Promise.all(o.map(f=>f.promise)):null;function u(f){if((a.f&16384)===0){l();try{n([...s,...f])}catch(m){Mi(m,a)}Dp()}}var d=T_();if(t.length===0){c.then(()=>u([])).finally(d);return}function p(){Promise.all(t.map(f=>S_(f))).then(u).catch(f=>Mi(f,a)).finally(d)}c?c.then(()=>{l(),p(),Dp()}):p()}function _O(){var r=Pe,e=ze,t=ct,n=Ne;if(Q)var i=Qs;return function(s=!0){Xr(r),Qr(e),ja(t),s&&(r.f&16384)===0&&(n?.activate(),n?.apply()),Q&&(k_(null),Sp(i))}}var W4=!1;function Dp(r=!0){W4=!1,Xr(null),Qr(null),ja(null),r&&Ne?.deactivate(),Q&&(k_(null),Sp(null))}function T_(){var r=Pe,e=r.b,t=Ne,n=!!e?.is_rendered();return e?.update_pending_count(1,t),t.increment(n,r),()=>{e?.update_pending_count(-1,t),t.decrement(n,r)}}var $i=null;function k_(r){$i=r}var tg=new Set;function nc(r){var e=2050;Pe!==null&&(Pe.f|=524288);let t={ctx:ct,deps:null,effects:null,equals:kw,f:e,fn:r,reactions:null,rv:0,v:jt,wv:0,parent:Pe,ac:null};return Q&&ss&&(t.created=as("created at")),t}var Fp=Symbol("obsolete");function S_(r,e,t){let n=Pe;n===null&&oO();var i=void 0,o=ti(jt);Q&&(o.label=e??r.toString());var s=!ze,a=new Set;return DO(()=>{var l=Pe;Q&&($i={effect:l,effect_deps:new Set,warned:!1});var c=bw();i=c.promise;try{Promise.resolve(r()).then(c.resolve,f=>{f!==Ua&&c.reject(f)}).finally(Dp)}catch(f){c.reject(f),Dp()}if(Q){if($i){if(l.deps!==null)for(let f=0;f<fi;f+=1)$i.effect_deps.add(l.deps[f]);if(vn!==null)for(let f=0;f<vn.length;f+=1)$i.effect_deps.add(vn[f])}$i=null}var u=Ne;if(s){if((l.f&32768)!==0)var d=T_();if(n.b?.is_rendered())u.async_deriveds.get(l)?.reject(Fp);else for(let f of a.values())f.reject(Fp);a.add(c),u.async_deriveds.set(l,c)}let p=(f,m=void 0)=>{Q&&($i=null),d?.(),a.delete(c),m!==Fp&&(u.activate(),m?(o.f|=8388608,ds(o,m)):((o.f&8388608)!==0&&(o.f^=8388608),Q&&t!==void 0&&!o.equals(f)&&(tg.add(o),setTimeout(()=>{tg.has(o)&&(l.f&16384)===0&&(X$(o.label,t),tg.delete(o))})),ds(o,f)),u.deactivate())};c.promise.then(p,f=>p(null,f||"unknown"))}),hn(()=>{for(let l of a)l.reject(Fp)}),Q&&(o.f|=4194304),new Promise(l=>{function c(u){function d(){u===i?l(o):c(i)}u.then(d,d)}c(i)})}function F(r){let e=nc(r);return Ar||Lw(e),e}function Lu(r){let e=nc(r);return e.equals=_w,e}function AO(r){var e=r.effects;if(e!==null){r.effects=null;for(var t=0;t<e.length;t+=1)br(e[t])}}var __=[];function rg(r){var e,t=Pe,n=r.parent;if(!Yi&&n!==null&&r.v!==jt&&(n.f&24576)!==0)return Z$(),r.v;if(Xr(n),Q){let i=Vu;Rw(new Set);try{Jl.call(__,r)&&sO(),__.push(r),r.f&=-65537,AO(r),e=Nw(r)}finally{Xr(t),Rw(i),__.pop()}}else try{r.f&=-65537,AO(r),e=Nw(r)}finally{Xr(t)}return e}function A_(r){var e=rg(r);if(!r.equals(e)&&(r.wv=Pp(),(!Ne?.is_fork||r.deps===null)&&(Ne!==null?(Ne.capture(r,e,!0),Xs?.capture(r,e,!0)):r.v=e,r.deps===null))){Bt(r,1024);return}Yi||(yn!==null?(rc()||Ne?.is_fork)&&yn.set(r,e):_p(r))}function IO(r){if(r.effects!==null)for(let e of r.effects)(e.teardown||e.ac)&&(e.teardown?.(),e.ac!==null&&Ao(()=>{e.ac.abort(Ua),e.ac=null}),e.fn!==null&&(e.teardown=Ct),Bu(e,0),ng(e))}function I_(r){if(r.effects!==null)for(let e of r.effects)e.teardown&&e.fn!==null&&Zs(e)}var Vw=null,Mp=null,Ne=null,Xs=null,yn=null,P_=null,$u=!1,D_=!1,qu=null,sg=null,FO=0,F_=new Set,Y4=1,Op,Ka,Qa,Rp,Np,Lp,Xa,Vp,mi,ag,Za,ps,Js,Bp,ic,$t,M_,ig,$_,MO,$O,$p,OO,og,Bw=class Bw{constructor(){rt(this,$t);he(this,"id",Y4++);rt(this,Op,!1);he(this,"linked",!0);rt(this,Ka,null);rt(this,Qa,null);he(this,"async_deriveds",new Map);he(this,"current",new Map);he(this,"previous",new Map);rt(this,Rp,new Set);rt(this,Np,new Set);rt(this,Lp,0);rt(this,Xa,new Map);rt(this,Vp,null);rt(this,mi,[]);rt(this,ag,[]);rt(this,Za,new Set);rt(this,ps,new Set);rt(this,Js,new Map);rt(this,Bp,new Set);he(this,"is_fork",!1);rt(this,ic,!1);Mp===null?Vw=Mp=this:(Ge(Mp,Qa,this),Ge(this,Ka,Mp)),Mp=this}skip_effect(e){V(this,Js).has(e)||V(this,Js).set(e,{d:[],m:[]}),V(this,Bp).delete(e)}unskip_effect(e,t=n=>this.schedule(n)){var n=V(this,Js).get(e);if(n){V(this,Js).delete(e);for(var i of n.d)Bt(i,2048),t(i);for(i of n.m)Bt(i,4096),t(i)}V(this,Bp).add(e)}capture(e,t,n=!1){e.v!==jt&&!this.previous.has(e)&&this.previous.set(e,e.v),(e.f&8388608)===0&&(this.current.set(e,[t,n]),yn?.set(e,t)),this.is_fork||(e.v=t)}activate(){Ne=this}deactivate(){Ne=null,yn=null}flush(){try{Q&&F_.clear(),D_=!0,Ne=this,lt(this,$t,ig).call(this)}finally{if(FO=0,P_=null,qu=null,sg=null,D_=!1,Ne=null,yn=null,Do.clear(),Q)for(let e of F_)e.updated=null}}discard(){for(let e of V(this,Np))e(this);V(this,Np).clear();for(let e of this.async_deriveds.values())e.reject(Fp);lt(this,$t,og).call(this),V(this,Vp)?.resolve()}register_created_effect(e){V(this,ag).push(e)}increment(e,t){if(Ge(this,Lp,V(this,Lp)+1),e){let n=V(this,Xa).get(t)??0;V(this,Xa).set(t,n+1)}}decrement(e,t){if(Ge(this,Lp,V(this,Lp)-1),e){let n=V(this,Xa).get(t)??0;n===1?V(this,Xa).delete(t):V(this,Xa).set(t,n-1)}V(this,ic)||(Ge(this,ic,!0),yr(()=>{Ge(this,ic,!1),this.linked&&this.flush()}))}transfer_effects(e,t){for(let n of e)V(this,Za).add(n);for(let n of t)V(this,ps).add(n);e.clear(),t.clear()}oncommit(e){V(this,Rp).add(e)}ondiscard(e){V(this,Np).add(e)}settled(){return(V(this,Vp)??Ge(this,Vp,bw())).promise}static ensure(){if(Ne===null){let e=Ne=new Bw;!D_&&!$u&&yr(()=>{V(e,Op)||e.flush()})}return Ne}apply(){if(!Ar||!this.is_fork&&V(this,Ka)===null&&V(this,Qa)===null){yn=null;return}yn=new Map;for(let[t,[n]]of this.current)yn.set(t,n);for(let t=Vw;t!==null;t=V(t,Qa))if(!(t===this||t.is_fork)){var e=!1;if(t.id<this.id){for(let[n,[,i]]of t.current)if(!i&&this.current.has(n)){e=!0;break}}if(!e)for(let[n,i]of t.previous)yn.has(n)||yn.set(n,i)}}schedule(e){if(P_=e,e.b?.is_pending&&(e.f&16777228)!==0&&(e.f&32768)===0){e.b.defer_effect(e);return}for(var t=e;t.parent!==null;){t=t.parent;var n=t.f;if(qu!==null&&t===Pe&&(Ar||(ze===null||(ze.f&2)===0)&&!kO))return;if((n&96)!==0){if((n&1024)===0)return;t.f^=1024}}V(this,mi).push(t)}};Op=new WeakMap,Ka=new WeakMap,Qa=new WeakMap,Rp=new WeakMap,Np=new WeakMap,Lp=new WeakMap,Xa=new WeakMap,Vp=new WeakMap,mi=new WeakMap,ag=new WeakMap,Za=new WeakMap,ps=new WeakMap,Js=new WeakMap,Bp=new WeakMap,ic=new WeakMap,$t=new WeakSet,M_=function(){if(this.is_fork)return!0;for(let n of V(this,Xa).keys()){for(var e=n,t=!1;e.parent!==null;){if(V(this,Js).has(e)){t=!0;break}e=e.parent}if(!t)return!0}return!1},ig=function(){var l,c,u;if(Ge(this,Op,!0),FO++>1e3&&(lt(this,$t,og).call(this),K4()),Q)for(let d of this.current.keys())F_.add(d);for(let d of V(this,Za))V(this,ps).delete(d),Bt(d,2048),this.schedule(d);for(let d of V(this,ps))Bt(d,4096),this.schedule(d);let e=V(this,mi);Ge(this,mi,[]),this.apply();var t=qu=[],n=[],i=sg=[];for(let d of e)try{lt(this,$t,$_).call(this,d,t,n)}catch(p){throw LO(d),lt(this,$t,M_).call(this)||this.discard(),p}if(Ne=null,i.length>0){var o=Bw.ensure();for(let d of i)o.schedule(d)}if(qu=null,sg=null,lt(this,$t,M_).call(this)){lt(this,$t,$p).call(this,n),lt(this,$t,$p).call(this,t);for(let[d,p]of V(this,Js))NO(d,p);i.length>0&&lt(l=Ne,$t,ig).call(l);return}let s=lt(this,$t,MO).call(this);if(s){lt(this,$t,$p).call(this,n),lt(this,$t,$p).call(this,t),lt(c=s,$t,$O).call(c,this);return}V(this,Za).clear(),V(this,ps).clear();for(let d of V(this,Rp))d(this);V(this,Rp).clear(),Xs=this,PO(n),PO(t),Xs=null,V(this,Vp)?.resolve();var a=Ne;if(V(this,Lp)===0&&(V(this,mi).length===0||a!==null)&&(lt(this,$t,og).call(this),Ar&&(lt(this,$t,OO).call(this),Ne=a)),V(this,mi).length>0)if(a!==null){let d=a;V(d,mi).push(...V(this,mi).filter(p=>!V(d,mi).includes(p)))}else a=this;a!==null&&(Do.clear(),lt(u=a,$t,ig).call(u))},$_=function(e,t,n){e.f^=1024;for(var i=e.first;i!==null;){var o=i.f,s=(o&96)!==0,a=s&&(o&1024)!==0,l=a||(o&8192)!==0||V(this,Js).has(i);if(!l&&i.fn!==null){s?i.f^=1024:(o&4)!==0?t.push(i):Ar&&(o&16777224)!==0?n.push(i):oc(i)&&((o&16)!==0&&V(this,ps).add(i),Zs(i));var c=i.first;if(c!==null){i=c;continue}}for(;i!==null;){var u=i.next;if(u!==null){i=u;break}i=i.parent}}},MO=function(){for(var e=V(this,Ka);e!==null;){if(!e.is_fork){for(let[t,[,n]]of this.current)if(e.current.has(t)&&!n)return e}e=V(e,Ka)}return null},$O=function(e){var n;for(let[i,o]of e.current)!this.previous.has(i)&&e.previous.has(i)&&this.previous.set(i,e.previous.get(i)),this.current.set(i,o);for(let[i,o]of e.async_deriveds){let s=this.async_deriveds.get(i);s&&o.promise.then(s.resolve).catch(s.reject)}e.async_deriveds.clear(),this.transfer_effects(V(e,Za),V(e,ps));let t=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)t(l);else{var a=l;s&4194320&&!this.async_deriveds.has(a)&&(V(this,ps).delete(a),Bt(a,2048),this.schedule(a))}}};for(let i of this.current.keys())t(i);this.oncommit(()=>e.discard()),lt(n=e,$t,og).call(n),Ne=this,lt(this,$t,ig).call(this)},$p=function(e){for(var t=0;t<e.length;t+=1)Fw(e[t],V(this,Za),V(this,ps))},OO=function(){var d;for(let p=Vw;p!==null;p=V(p,Qa)){var e=p.id<this.id,t=[];for(let[f,[m,g]]of this.current){if(p.current.has(f)){var n=p.current.get(f)[0];if(e&&m!==n)p.current.set(f,[m,g]);else continue}t.push(f)}if(e)for(let[f,m]of this.async_deriveds){let g=p.async_deriveds.get(f);g&&m.promise.then(g.resolve).catch(g.reject)}var i=[...p.current.keys()].filter(f=>!p.current.get(f)[1]);if(!(!V(p,Op)||i.length===0)){var o=i.filter(f=>!this.current.has(f));if(o.length===0)e&&p.discard();else if(t.length>0){if(Q&&!V(p,ic)&&CO(V(p,mi).length===0,"Batch has scheduled roots"),e)for(let f of V(this,Bp))p.unskip_effect(f,m=>{var g;(m.f&4194320)!==0?p.schedule(m):lt(g=p,$t,$p).call(g,[m])});p.activate();var s=new Set,a=new Map;for(var l of t)RO(l,o,s,a);a=new Map;var c=[...p.current].filter(([f,m])=>{let g=this.current.get(f);return g?g[0]!==m[0]||g[1]!==m[1]:!0}).map(([f])=>f);if(c.length>0)for(let f of V(this,ag))(f.f&155648)===0&&O_(f,c,a)&&((f.f&4194320)!==0?(Bt(f,2048),p.schedule(f)):V(p,Za).add(f));if(V(p,mi).length>0&&!V(p,ic)){p.apply();for(var u of V(p,mi))lt(d=p,$t,$_).call(d,u,[],[]);Ge(p,mi,[])}p.deactivate()}}}},og=function(){if(this.linked){var e=V(this,Ka),t=V(this,Qa);e===null?Vw=t:Ge(e,Qa,t),t===null?Mp=e:Ge(t,Ka,e),this.linked=!1}};var Ki=Bw;function zu(r){var e=$u;$u=!0;try{var t;for(r&&(Ne!==null&&!Ne.is_fork&&Ne.flush(),t=r());;){if(EO(),Ne===null)return t;Ne.flush()}}finally{$u=e}}function K4(){if(Q){var r=new Map;for(let t of Ne.current.keys())for(let[n,i]of t.updated??[]){var e=r.get(n);e||(e={error:i.error,count:0},r.set(n,e)),e.count+=i.count}for(let t of r.values())t.error&&console.error(t.error)}try{dO()}catch(t){Q&&pn(t,"stack",{value:""}),Mi(t,P_)}}var Io=null;function PO(r){var e=r.length;if(e!==0){for(var t=0;t<e;){var n=r[t++];if((n.f&24576)===0&&oc(n)&&(Io=new Set,Zs(n),n.deps===null&&n.first===null&&n.nodes===null&&n.teardown===null&&n.ac===null&&R_(n),Io?.size>0)){Do.clear();for(let i of Io){if((i.f&24576)!==0)continue;let o=[i],s=i.parent;for(;s!==null;)Io.has(s)&&(Io.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&&Zs(l)}}Io.clear()}}Io=null}}function RO(r,e,t,n){if(!t.has(r)&&(t.add(r),r.reactions!==null))for(let i of r.reactions){let o=i.f;(o&2)!==0?RO(i,e,t,n):(o&4194320)!==0&&(o&2048)===0&&O_(i,e,n)&&(Bt(i,2048),lg(i))}}function O_(r,e,t){let n=t.get(r);if(n!==void 0)return n;if(r.deps!==null)for(let i of r.deps){if(Jl.call(e,i))return!0;if((i.f&2)!==0&&O_(i,e,t))return t.set(i,!0),!0}return t.set(r,!1),!1}function lg(r){Ne.schedule(r)}function NO(r,e){if(!((r.f&32)!==0&&(r.f&1024)!==0)){(r.f&2048)!==0?e.d.push(r):(r.f&4096)!==0&&e.m.push(r),Bt(r,1024);for(var t=r.first;t!==null;)NO(t,e),t=t.next}}function LO(r){Bt(r,1024);for(var e=r.first;e!==null;)LO(e),e=e.next}var Vu=new Set,Do=new Map;function Rw(r){Vu=r}var N_=!1;function BO(){N_=!0}function ti(r,e){var t={f:0,v:r,reactions:null,equals:kw,rv:0,wv:0};return Q&&ss&&(t.created=e??as("created at"),t.updated=null,t.set_during_effect=!1,t.trace=null),t}function Ce(r,e){let t=ti(r,e);return Lw(t),t}function Ou(r,e=!1,t=!0){var i;let n=ti(r);return e||(n.equals=_w),Wa&&t&&ct!==null&&ct.l!==null&&((i=ct.l).s??(i.s=[])).push(n),n}function j(r,e,t=!1){ze!==null&&(!hi||(ze.f&131072)!==0)&&cs()&&(ze.f&4325394)!==0&&(Fo===null||!Fo.has(r))&&yO();let n=t?ut(e):e;return Q&&Iw(n,r.label),ds(r,n,sg)}function ds(r,e,t=null){if(!r.equals(e)){Yi?Do.set(r,e):Do.has(r)||Do.set(r,r.v);var n=Ki.ensure();if(n.capture(r,e),Q){if(ss||Pe!==null){r.updated??(r.updated=new Map);let i=(r.updated.get("")?.count??0)+1;if(r.updated.set("",{error:null,count:i}),ss||i>5){let o=as("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++}}}Pe!==null&&(r.set_during_effect=!0)}if((r.f&2)!==0){let i=r;(r.f&2048)!==0&&rg(i),yn===null&&_p(i)}r.wv=Pp(),qO(r,2048,t),cs()&&Pe!==null&&(Pe.f&1024)!==0&&(Pe.f&96)===0&&(Qi===null?UO([r]):Qi.push(r)),!n.is_fork&&Vu.size>0&&!N_&&qw()}return e}function qw(){N_=!1;for(let r of Vu){(r.f&1024)!==0&&Bt(r,4096);let e;try{e=oc(r)}catch{e=!0}e&&Zs(r)}Vu.clear()}function L_(r,e=1){var t=h(r);return j(r,e===1?++t:--t)}function Wu(r){j(r,r.v+1)}function qO(r,e,t){var n=r.reactions;if(n!==null)for(var i=cs(),o=n.length,s=0;s<o;s++){var a=n[s],l=a.f;if(!(!i&&a===Pe)){var c=(l&2048)===0;if(c&&Bt(a,e),(l&131072)!==0)Vu.add(a);else if((l&2)!==0){var u=a;yn?.delete(u),(l&65536)===0&&(l&512&&(Pe===null||(Pe.f&2097152)===0)&&(a.f|=65536),qO(u,4096,t))}else if(c){var d=a;(l&16)!==0&&Io!==null&&Io.add(d),t!==null?t.push(d):lg(d)}}}}var X4=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;function ut(r){if(typeof r!="object"||r===null||On in r||ww in r)return r;let e=ec(r);if(e!==vw&&e!==Y$)return r;var t=new Map,n=ko(r),i=Ce(0),o=Q&&ss?as("created at"):null,s=sc,a=d=>{if(sc===s)return d();var p=ze,f=sc;Qr(null),V_(s);var m=d();return Qr(p),V_(f),m};n&&(t.set("length",Ce(r.length,o)),Q&&(r=J4(r)));var l="";let c=!1;function u(d){if(!c){c=!0,l=d,Zn(i,`${l} version`);for(let[p,f]of t)Zn(f,ju(l,p));c=!1}}return new Proxy(r,{defineProperty(d,p,f){(!("value"in f)||f.configurable===!1||f.enumerable===!1||f.writable===!1)&&gO();var m=t.get(p);return m===void 0?a(()=>{var g=Ce(f.value,o);return t.set(p,g),Q&&typeof p=="string"&&Zn(g,ju(l,p)),g}):j(m,f.value,!0),!0},deleteProperty(d,p){var f=t.get(p);if(f===void 0){if(p in d){let m=a(()=>Ce(jt,o));t.set(p,m),Wu(i),Q&&Zn(m,ju(l,p))}}else j(f,jt),Wu(i);return!0},get(d,p,f){if(p===On)return r;if(Q&&p===Cw)return u;var m=t.get(p),g=p in d;if(m===void 0&&(!g||Fi(d,p)?.writable)&&(m=a(()=>{var y=ut(g?d[p]:jt),b=Ce(y,o);return Q&&Zn(b,ju(l,p)),b}),t.set(p,m)),m!==void 0){var v=h(m);return v===jt?void 0:v}return Reflect.get(d,p,f)},getOwnPropertyDescriptor(d,p){var f=Reflect.getOwnPropertyDescriptor(d,p);if(f&&"value"in f){var m=t.get(p);m&&(f.value=h(m))}else if(f===void 0){var g=t.get(p),v=g?.v;if(g!==void 0&&v!==jt)return{enumerable:!0,configurable:!0,value:v,writable:!0}}return f},has(d,p){if(p===On)return!0;var f=t.get(p),m=f!==void 0&&f.v!==jt||Reflect.has(d,p);if(f!==void 0||Pe!==null&&(!m||Fi(d,p)?.writable)){f===void 0&&(f=a(()=>{var v=m?ut(d[p]):jt,y=Ce(v,o);return Q&&Zn(y,ju(l,p)),y}),t.set(p,f));var g=h(f);if(g===jt)return!1}return m},set(d,p,f,m){var g=t.get(p),v=p in d;if(n&&p==="length")for(var y=f;y<g.v;y+=1){var b=t.get(y+"");b!==void 0?j(b,jt):y in d&&(b=a(()=>Ce(jt,o)),t.set(y+"",b),Q&&Zn(b,ju(l,y)))}if(g===void 0)(!v||Fi(d,p)?.writable)&&(g=a(()=>Ce(void 0,o)),Q&&Zn(g,ju(l,p)),j(g,ut(f)),t.set(p,g));else{v=g.v!==jt;var x=a(()=>ut(f));j(g,x)}var w=Reflect.getOwnPropertyDescriptor(d,p);if(w?.set&&w.set.call(m,f),!v){if(n&&typeof p=="string"){var T=t.get("length"),C=Number(p);Number.isInteger(C)&&C>=T.v&&j(T,C+1)}Wu(i)}return!0},ownKeys(d){h(i);var p=Reflect.ownKeys(d).filter(g=>{var v=t.get(g);return v===void 0||v.v!==jt});for(var[f,m]of t)m.v!==jt&&!(f in d)&&p.push(f);return p},setPrototypeOf(){vO()}})}function ju(r,e){return typeof e=="symbol"?`${r}[Symbol(${e.description??""})]`:X4.test(e)?`${r}.${e}`:/^\d+$/.test(e)?`${r}[${e}]`:`${r}['${e}']`}function Up(r){try{if(r!==null&&typeof r=="object"&&On in r)return r[On]}catch{}return r}function Uw(r,e){return Object.is(Up(r),Up(e))}var Z4=new Set(["copyWithin","fill","pop","push","reverse","shift","sort","splice","unshift"]);function J4(r){return new Proxy(r,{get(e,t,n){var i=Reflect.get(e,t,n);return Z4.has(t)?function(...o){BO();var s=i.apply(this,o);return qw(),s}:i}})}function HO(){let r=Array.prototype,e=Array.__svelte_cleanup;e&&e();let{indexOf:t,lastIndexOf:n,includes:i}=r;r.indexOf=function(o,s){let a=t.call(this,o,s);if(a===-1){for(let l=s??0;l<this.length;l+=1)if(Up(this[l])===o){Tw("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(Up(this[l])===o){Tw("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(Up(this[l])===o){Tw("array.includes(...)");break}}return a},Array.__svelte_cleanup=()=>{r.indexOf=t,r.lastIndexOf=n,r.includes=i}}var B_,zO,cg,WO,jO;function Hw(){if(B_===void 0){B_=window,zO=document,cg=/Firefox/.test(navigator.userAgent);var r=Element.prototype,e=Node.prototype,t=Text.prototype;WO=Fi(e,"firstChild").get,jO=Fi(e,"nextSibling").get,g_(r)&&(r[jh]=void 0,r[xw]=null,r[Gh]=void 0,r.__e=void 0),g_(t)&&(t[Yh]=void 0),Q&&(r.__svelte_meta=null,HO())}}function wr(r=""){return document.createTextNode(r)}function gn(r){return WO.call(r)}function Nn(r){return jO.call(r)}function B(r,e){if(!Me)return gn(r);var t=gn(Ye);if(t===null)t=Ye.appendChild(wr());else if(e&&t.nodeType!==Du){var n=wr();return t?.before(n),Vt(n),n}return e&&ug(t),Vt(t),t}function Te(r,e=!1){if(!Me){var t=gn(r);return t instanceof Comment&&t.data===""?Nn(t):t}if(e){if(Ye?.nodeType!==Du){var n=wr();return Ye?.before(n),Vt(n),n}ug(Ye)}return Ye}function le(r,e=!1){if(!Me)return gn(r);var t=B(r,e);return N(r),t}function _(r,e=1,t=!1){let n=Me?Ye:r;for(var i;e--;)i=n,n=Nn(n);if(!Me)return n;if(t){if(n?.nodeType!==Du){var o=wr();return n===null?i?.after(o):n.before(o),Vt(o),o}ug(n)}return Vt(n),n}function Ip(r){r.textContent=""}function zw(){if(!Ar||Io!==null)return!1;var r=Pe.f;return(r&32768)!==0}function fs(r,e,t){return e==null||e===mw?t?document.createElement(r,{is:t}):document.createElement(r):t?document.createElementNS(e,r,{is:t}):document.createElementNS(e,r)}function ug(r){if(r.nodeValue.length<65536)return;let e=r.nextSibling;for(;e!==null&&e.nodeType===Du;)e.remove(),r.nodeValue+=e.nodeValue,e=r.nextSibling}var q_=new WeakMap;function GO(r){var e=Pe;if(e===null)return ze.f|=8388608,r;if(Q&&r instanceof Error&&!q_.has(r)&&q_.set(r,eY(r,e)),(e.f&32768)===0&&(e.f&4)===0)throw Q&&!e.parent&&r instanceof Error&&YO(r),r;Mi(r,e)}function Mi(r,e){if(!(e!==null&&(e.f&16384)!==0)){for(;e!==null;){if((e.f&128)!==0&&(e.f&33570816)===0){if((e.f&32768)===0)throw r;try{e.b.error(r);return}catch(t){r=t}}e=e.parent}throw Q&&r instanceof Error&&YO(r),r}}function eY(r,e){let t=Fi(r,"message");if(!(t&&!t.configurable)){for(var n=cg?" ":" ",i=`
${n}in ${e.fn?.name||"<unknown>"}`,o=e.ctx;o!==null;)i+=`
${n}in ${o.function?.[To].split("/").pop()}`,o=o.p;return{message:r.message+`
${i}
`,stack:r.stack?.split(`
`).filter(s=>!s.includes("svelte/src/internal")).join(`
`)}}}function YO(r){let e=q_.get(r);e&&(pn(r,"message",{value:e.message}),pn(r,"stack",{value:e.stack}))}function QO(r){Pe===null&&(ze===null&&uO(r),cO()),Yi&&lO(r)}function rY(r,e){var t=e.last;t===null?e.last=e.first=r:(t.next=r,r.prev=t,e.last=r)}function ea(r,e){var t=Pe;if(Q)for(;t!==null&&(t.f&131072)!==0;)t=t.parent;t!==null&&(t.f&8192)!==0&&(r|=8192);var n={ctx:ct,deps:null,nodes:null,f:r|2048|512,first:null,fn:e,last:null,next:null,parent:t,b:t&&t.b,prev:null,teardown:null,wv:0,ac:null};Q&&(n.component_function=ls),Ne?.register_created_effect(n);var i=n;if((r&4)!==0)qu!==null?qu.push(n):Ki.ensure().schedule(n);else if(e!==null){try{Zs(n)}catch(s){throw br(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=t,t!==null&&rY(i,t),ze!==null&&(ze.f&2)!==0&&(r&64)===0)){var o=ze;(o.effects??(o.effects=[])).push(i)}return n}function rc(){return ze!==null&&!hi}function hn(r){let e=ea(8,null);return Bt(e,1024),e.teardown=r,e}function Yt(r){QO("$effect"),Q&&pn(r,"name",{value:"$effect"});var e=Pe.f,t=!ze&&(e&32)!==0&&ct!==null&&!ct.i;if(t){var n=ct;(n.e??(n.e=[])).push(r)}else return x_(r)}function x_(r){return ea(1048580,r)}function z_(r){Ki.ensure();let e=ea(524352,r);return()=>{br(e)}}function XO(r){Ki.ensure();let e=ea(524352,r);return(t={})=>new Promise(n=>{t.outro?ta(e,()=>{br(e),n(void 0)}):(br(e),n(void 0))})}function $r(r){return ea(4,r)}function DO(r){return ea(4718592,r)}function bn(r,e=0){return ea(8|e,r)}function re(r,e=[],t=[],n=[]){Ow(n,e,t,i=>{ea(8,()=>{r(...i.map(h))})})}function gi(r,e=0){var t=ea(16|e,r);return Q&&(t.dev_stack=Qs),t}function Zr(r){return ea(524320,r)}function W_(r){var e=r.teardown;if(e!==null){let t=Yi,n=ze;U_(!0),Qr(null);try{e.call(null)}catch(i){Mi(i,r.parent)}finally{U_(t),Qr(n)}}}function ng(r,e=!1){var t=r.first;for(r.first=r.last=null;t!==null;){let i=t.ac;i!==null&&Ao(()=>{i.abort(Ua)});var n=t.next;(t.f&64)!==0?t.parent=null:br(t,e),t=n}}function ZO(r){for(var e=r.first;e!==null;){var t=e.next;(e.f&32)===0&&br(e),e=t}}function br(r,e=!0){var t=!1;(e||(r.f&262144)!==0)&&r.nodes!==null&&r.nodes.end!==null&&(JO(r.nodes.start,r.nodes.end),t=!0),r.f|=33554432,ng(r,e&&!t),Bu(r,0);var n=r.nodes&&r.nodes.t;if(n!==null)for(let o of n)o.stop();W_(r),r.f^=33554432,r.f|=16384;var i=r.parent;i!==null&&i.first!==null&&R_(r),Q&&(r.component_function=null),r.next=r.prev=r.teardown=r.ctx=r.deps=r.fn=r.nodes=r.ac=r.b=null}function JO(r,e){for(;r!==null;){var t=r===e?null:Nn(r);r.remove(),r=t}}function R_(r){var e=r.parent,t=r.prev,n=r.next;t!==null&&(t.next=n),n!==null&&(n.prev=t),e!==null&&(e.first===r&&(e.first=n),e.last===r&&(e.last=t))}function ta(r,e,t=!0){var n=[];r.f|=256,eR(r,n,!0);var i=()=>{t&&br(r),e&&e()},o=n.length;if(o>0){var s=()=>--o||i();for(var a of n)a.out(s)}else i()}function eR(r,e,t){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||t)&&e.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;eR(i,e,s?t:!1)}i=o}}}function Hp(r){r.f&=-257,tR(r,!0)}function tR(r,e){if((r.f&256)===0&&(r.f&8192)!==0){r.f^=8192,(r.f&1024)===0&&(Bt(r,2048),Ki.ensure().schedule(r));for(var t=r.first;t!==null;){var n=t.next,i=(t.f&65536)!==0||(t.f&32)!==0;tR(t,i?e:!1),t=n}var o=r.nodes&&r.nodes.t;if(o!==null)for(let s of o)(s.is_global||e)&&s.in()}}function zp(r,e){if(r.nodes)for(var t=r.nodes.start,n=r.nodes.end;t!==null;){var i=t===n?null:Nn(t);e.append(t),t=i}}var rR=null;var Ww=!1,Yi=!1;function U_(r){Yi=r}var ze=null,hi=!1;function Qr(r){ze=r}var Pe=null;function Xr(r){Pe=r}var Fo=null;function Lw(r){ze!==null&&(!Ar||(ze.f&2)!==0)&&(Fo??(Fo=new Set)).add(r)}var vn=null,fi=0,Qi=null;function UO(r){Qi=r}var iR=1,Gu=0,sc=Gu;function V_(r){sc=r}function Pp(){return++iR}function oc(r){var e=r.f;if((e&2048)!==0)return!0;if(e&2&&(r.f&=-65537),(e&4096)!==0){for(var t=r.deps,n=t.length,i=0;i<n;i++){var o=t[i];if(oc(o)&&A_(o),o.wv>r.wv)return!0}(e&512)!==0&&yn===null&&Bt(r,1024)}return!1}function oR(r,e,t=!0){var n=r.reactions;if(n!==null&&!(!Ar&&Fo!==null&&Fo.has(r)))for(var i=0;i<n.length;i++){var o=n[i];(o.f&2)!==0?oR(o,e,!1):e===o&&(t?Bt(o,2048):(o.f&1024)!==0&&Bt(o,4096),lg(o))}}function Nw(r){var e=vn,t=fi,n=Qi,i=ze,o=Fo,s=ct,a=hi,l=sc,c=r.f;vn=null,fi=0,Qi=null,ze=(c&96)===0?r:null,Fo=null,ja(r.ctx),hi=!1,sc=++Gu,r.ac!==null&&(Ao(()=>{r.ac.abort(Ua)}),r.ac=null);try{r.f|=2097152;var u=r.fn,d=u();r.f|=32768;var p=nR(r);if(cs()&&Qi!==null&&!hi&&p!==null&&(r.f&6146)===0)for(var f=0;f<Qi.length;f++)oR(Qi[f],r);if(i!==null&&i!==r){if(Gu++,i.deps!==null)for(let m=0;m<t;m+=1)i.deps[m].rv=Gu;if(e!==null)for(let m of e)m.rv=Gu;Qi!==null&&(n===null?n=Qi:n.push(...Qi))}return(r.f&8388608)!==0&&(r.f^=8388608),d}catch(m){return nR(r),GO(m)}finally{r.f^=2097152,vn=e,fi=t,Qi=n,ze=i,Fo=o,ja(s),hi=a,sc=l}}function nR(r){var i;var e=r.deps,t=Ne?.is_fork;if(vn!==null){var n;if(t||Bu(r,fi),e!==null&&fi>0)for(e.length=fi+vn.length,n=0;n<vn.length;n++)e[fi+n]=vn[n];else r.deps=e=vn;if(rc()&&(r.f&512)!==0)for(n=fi;n<e.length;n++)((i=e[n]).reactions??(i.reactions=[])).push(r)}else!t&&e!==null&&fi<e.length&&(Bu(r,fi),e.length=fi);return e}function nY(r,e){let t=e.reactions;if(t!==null){var n=G$.call(t,r);if(n!==-1){var i=t.length-1;i===0?t=e.reactions=null:(t[n]=t[i],t.pop())}}if(t===null&&(e.f&2)!==0&&(vn===null||!Jl.call(vn,e))){var o=e;(o.f&512)!==0&&(o.f^=512,o.f&=-65537),o.v!==jt&&_p(o),o.ac!==null&&Ao(()=>{o.ac.abort(Ua),o.ac=null,Bt(o,2048)}),IO(o),Bu(o,0)}}function Bu(r,e){var t=r.deps;if(t!==null)for(var n=e;n<t.length;n++)nY(r,t[n])}function Zs(r){var e=r.f;if((e&16384)===0){Bt(r,1024);var t=Pe,n=Ww;if(Pe=r,Ww=(e&96)===0,Q){var i=ls;Dw(r.component_function);var o=Qs;Sp(r.dev_stack??Qs)}try{(e&16777232)!==0?ZO(r):ng(r),W_(r);var s=Nw(r);if(r.teardown=typeof s=="function"?s:null,r.wv=iR,Q&&ss&&(r.f&2048)!==0&&r.deps!==null)for(var a of r.deps)a.set_during_effect&&(a.wv=Pp(),a.set_during_effect=!1)}finally{Ww=n,Pe=t,Q&&(Dw(i),Sp(o))}}}async function ac(){if(Ar)return new Promise(r=>{requestAnimationFrame(()=>r()),setTimeout(()=>r())});await Promise.resolve(),zu()}function h(r){var e=r.f,t=(e&2)!==0;if(rR?.add(r),ze!==null&&!hi){var n=Pe!==null&&(Pe.f&16384)!==0;if(!n&&(Fo===null||!Fo.has(r))){var i=ze.deps;if((ze.f&2097152)!==0)r.rv<Gu&&(r.rv=Gu,vn===null&&i!==null&&i[fi]===r?fi++:vn===null?vn=[r]:vn.push(r));else{ze.deps??(ze.deps=[]),Jl.call(ze.deps,r)||ze.deps.push(r);var o=r.reactions;o===null?r.reactions=[ze]:Jl.call(o,ze)||o.push(ze)}}}if(Q){if(!hi&&$i&&Ne===null&&Xs===null&&!$i.warned&&($i.effect.f&2097152)===0&&!$i.effect_deps.has(r)){$i.warned=!0,Q$(r.label);var s=as("traced at");s&&console.warn(s)}if(tg.delete(r),ss&&!hi&&Zh!==null&&ze!==null&&Zh.reaction===ze){if(r.trace)r.trace();else if(s=as("traced at"),s){var a=Zh.entries.get(r);a===void 0&&(a={traces:[]},Zh.entries.set(r,a));var l=a.traces[a.traces.length-1];s.stack!==l?.stack&&a.traces.push(s)}}}if(Yi&&Do.has(r))return Do.get(r);if(t){var c=r;if(Yi){var u=c.v;return((c.f&1024)===0&&c.reactions!==null||aR(c))&&(u=rg(c)),Do.set(c,u),u}var d=(c.f&512)===0&&!hi&&ze!==null&&(Ww||(ze.f&512)!==0),p=(c.f&32768)===0;oc(c)&&(d&&(c.f|=512),A_(c)),d&&!p&&(I_(c),sR(c))}if(yn?.has(r))return yn.get(r);if((r.f&8388608)!==0)throw r.v;return r.v}function sR(r){if(r.f|=512,r.deps!==null)for(let e of r.deps)(e.reactions??(e.reactions=[])).push(r),(e.f&2)!==0&&(e.f&512)===0&&(I_(e),sR(e))}function aR(r){if(r.v===jt)return!0;if(r.deps===null)return!1;for(let e of r.deps)if(Do.has(e)||(e.f&2)!==0&&aR(e))return!0;return!1}function kt(r){var e=hi;try{return hi=!0,r()}finally{hi=e}}function Gw(r){if(!(typeof r!="object"||!r||r instanceof EventTarget)){if(On in r)jw(r);else if(!Array.isArray(r))for(let e in r){let t=r[e];typeof t=="object"&&t&&On in t&&jw(t)}}}function jw(r,e=new Set){if(typeof r=="object"&&r!==null&&!(r instanceof EventTarget)&&!e.has(r)){e.add(r),r instanceof Date&&r.getTime();for(let n in r)try{jw(r[n],e)}catch{}let t=ec(r);if(t!==Object.prototype&&t!==Array.prototype&&t!==Map.prototype&&t!==Set.prototype&&t!==Date.prototype){let n=gw(t);for(let i in n){let o=n[i].get;if(o)try{o.call(r)}catch{}}}}}var Yu=Symbol("events"),Y_=new Set,Yw=new Set;function lR(r,e,t,n={}){function i(o){if(n.capture||Kw.call(e,o),!o.cancelBubble)return Ao(()=>t?.call(this,o))}return r.startsWith("pointer")||r.startsWith("touch")||r==="wheel"?yr(()=>{e.addEventListener(r,i,n)}):e.addEventListener(r,i,n),i}function Po(r,e,t,n,i){var o={capture:n,passive:i},s=lR(r,e,t,o);(e===document.body||e===window||e===document||e instanceof HTMLMediaElement)&&hn(()=>{e.removeEventListener(r,s,o)})}function Ae(r,e,t){(e[Yu]??(e[Yu]={}))[r]=t}function nt(r){for(var e=0;e<r.length;e++)Y_.add(r[e]);for(var t of Yw)t(r)}var j_=null,G_=!1;function Kw(r){var e=this,t=e.ownerDocument,n=r.type,i=r.composedPath?.()||[],o=i[0]||r.target;j_=r,G_||(G_=!0,setTimeout(()=>{G_=!1,j_=null}));var s=0,a=j_===r&&r[Yu];if(a){var l=i.indexOf(a);if(l!==-1&&(e===document||e===window)){r[Yu]=e;return}var c=i.indexOf(e);if(c===-1)return;l<=c&&(s=l)}if(o=i[s]||r.target,o!==e){pn(r,"currentTarget",{configurable:!0,get(){return o||t}});var u=ze,d=Pe;Qr(null),Xr(null);try{for(var p,f=[];o!==null&&o!==e;){try{var m=o[Yu]?.[n];m!=null&&(!o.disabled||r.target===o)&&m.call(o,r)}catch(g){p?f.push(g):p=g}if(r.cancelBubble)break;s++,o=s<i.length?i[s]:null}if(p){for(let g of f)queueMicrotask(()=>{throw g});throw p}}finally{r[Yu]=e,delete r.currentTarget,Qr(u),Xr(d)}}}var iY=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:r=>r});function cR(r){return iY?.createHTML(r)??r}function K_(r){var e=fs("template");return e.innerHTML=cR(r.replaceAll("<!>","<!---->")),e.content}function Xi(r,e){var t=Pe;t.nodes===null&&(t.nodes={start:r,end:e,a:null,t:null})}function L(r,e){var t=(e&1)!==0,n=(e&2)!==0,i,o=!r.startsWith("<!>");return()=>{if(Me)return Xi(Ye,null),Ye;i===void 0&&(i=K_(o?r:"<!>"+r),t||(i=gn(i)));var s=n||cg?document.importNode(i,!0):i.cloneNode(!0);if(t){var a=gn(s),l=s.lastChild;Xi(a,l)}else Xi(s,s);return s}}function ra(r=""){if(!Me){var e=wr(r+"");return Xi(e,e),e}var t=Ye;return t.nodeType!==Du?(t.before(t=wr()),Vt(t)):ug(t),Xi(t,t),t}function or(){if(Me)return Xi(Ye,null),Ye;var r=document.createDocumentFragment(),e=document.createComment(""),t=wr();return r.append(e,t),Xi(e,t),r}function M(r,e){if(Me){var t=Pe;((t.f&32768)===0||t.nodes.end===null)&&(t.nodes.end=Ye),fn();return}r!==null&&r.before(e)}function Ku(){var r;if(Me&&Ye&&Ye.nodeType===Gi&&Ye.textContent?.startsWith("$")){let e=Ye.textContent.substring(1);return fn(),e}return(r=window.__svelte??(window.__svelte={})).uid??(r.uid=1),`c${window.__svelte.uid++}`}var uY=["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 pme=[...uY,"formNoValidate","isMap","noModule","playsInline","readOnly","value","volume","defaultValue","defaultChecked","srcObject","noValidate","allowFullscreen","disablePictureInPicture","disableRemotePlayback"];var dY=["touchstart","touchmove"];function uR(r){return dY.includes(r)}var pY=["$state","$state.raw","$derived","$derived.by"],fme=[...pY,"$state.eager","$state.snapshot","$props","$props.id","$bindable","$effect","$effect.pre","$effect.tracking","$effect.root","$effect.pending","$inspect","$inspect().with","$inspect.trace","$host"];function dR(r){let e=0,t=ti(0),n;return Q&&Zn(t,"createSubscriber version"),()=>{rc()&&(h(t),bn(()=>(e===0&&(n=kt(()=>r(()=>Wu(t)))),e+=1,()=>{yr(()=>{e-=1,e===0&&(n?.(),n=void 0,Wu(t))})})))}}var fY=589824;function hg(r,e,t,n){new X_(r,e,t,n)}var Zi,pg,Mo,Qu,vi,Ji,yi,eo,na,Xu,lc,Wp,fg,mg,ia,Xw,Ut,fR,mR,Z_,hR,J_,dg,Qw,eA,tA,X_=class{constructor(e,t,n,i){rt(this,Ut);he(this,"parent");he(this,"is_pending",!1);he(this,"transform_error");rt(this,Zi);rt(this,pg,Me?Ye:null);rt(this,Mo);rt(this,Qu);rt(this,vi);rt(this,Ji,null);rt(this,yi,null);rt(this,eo,null);rt(this,na,null);rt(this,Xu,0);rt(this,lc,0);rt(this,Wp,!1);rt(this,fg,new Set);rt(this,mg,new Set);rt(this,ia,null);rt(this,Xw,dR(()=>(Ge(this,ia,ti(V(this,Xu))),Q&&Zn(V(this,ia),"$effect.pending()"),()=>{Ge(this,ia,null)})));Ge(this,Zi,e),Ge(this,Mo,t),Ge(this,Qu,o=>{var s=Pe;s.b=this,s.f|=128,n(o)}),this.parent=Pe.b,this.transform_error=i??this.parent?.transform_error??(o=>o),Ge(this,vi,gi(()=>{if(Me){let o=V(this,pg);fn();let s=o.data==="[!";if(o.data.startsWith("[?")){let l=JSON.parse(o.data.slice("[?".length));lt(this,Ut,mR).call(this,l)}else s?lt(this,Ut,hR).call(this):lt(this,Ut,fR).call(this)}else lt(this,Ut,J_).call(this)},fY)),Me&&Ge(this,Zi,Ye)}defer_effect(e){Fw(e,V(this,fg),V(this,mg))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!V(this,Mo).pending}update_pending_count(e,t){lt(this,Ut,eA).call(this,e,t),Ge(this,Xu,V(this,Xu)+e),!(!V(this,ia)||V(this,Wp))&&(Ge(this,Wp,!0),yr(()=>{Ge(this,Wp,!1),V(this,ia)&&ds(V(this,ia),V(this,Xu))}))}get_effect_pending(){return V(this,Xw).call(this),h(V(this,ia))}error(e){if(!V(this,Mo).onerror&&!V(this,Mo).failed)throw e;Ne?.is_fork?(V(this,Ji)&&Ne.skip_effect(V(this,Ji)),V(this,yi)&&Ne.skip_effect(V(this,yi)),V(this,eo)&&Ne.skip_effect(V(this,eo)),Ne.oncommit(()=>{lt(this,Ut,tA).call(this,e)})):lt(this,Ut,tA).call(this,e)}};Zi=new WeakMap,pg=new WeakMap,Mo=new WeakMap,Qu=new WeakMap,vi=new WeakMap,Ji=new WeakMap,yi=new WeakMap,eo=new WeakMap,na=new WeakMap,Xu=new WeakMap,lc=new WeakMap,Wp=new WeakMap,fg=new WeakMap,mg=new WeakMap,ia=new WeakMap,Xw=new WeakMap,Ut=new WeakSet,fR=function(){try{Ge(this,Ji,Zr(()=>V(this,Qu).call(this,V(this,Zi))))}catch(e){this.error(e)}},mR=function(e){let t=V(this,Mo).failed,{reset:n,invoke_onerror:i}=lt(this,Ut,Z_).call(this,e);yr(i),t&&Ge(this,eo,Zr(()=>{t(V(this,Zi),()=>e,()=>n)}))},Z_=function(e){var t=!1,n=!1;let i=()=>{if(t){rO();return}t=!0,n&&bO(),V(this,eo)!==null&&ta(V(this,eo),()=>{Ge(this,eo,null)}),lt(this,Ut,Qw).call(this,()=>{lt(this,Ut,J_).call(this)})};return{reset:i,invoke_onerror:()=>{try{n=!0,V(this,Mo).onerror?.(e,i),n=!1}catch(s){Mi(s,V(this,vi)&&V(this,vi).parent)}}}},hR=function(){let e=V(this,Mo).pending;e&&(this.is_pending=!0,Ge(this,yi,Zr(()=>e(V(this,Zi)))),yr(()=>{var t=Ge(this,na,document.createDocumentFragment()),n=wr(),i=!1;if(t.append(n),Ge(this,Ji,lt(this,Ut,Qw).call(this,()=>{try{return Zr(()=>V(this,Qu).call(this,n))}catch(o){try{this.error(o),i=!0}catch(s){Mi(s,V(this,vi).parent)}return null}})),V(this,Ji)===null){Ge(this,na,null),i&&lt(this,Ut,dg).call(this,Ne);return}V(this,lc)===0&&(V(this,Zi).before(t),Ge(this,na,null),ta(V(this,yi),()=>{Ge(this,yi,null)}),lt(this,Ut,dg).call(this,Ne))}))},J_=function(){try{if(this.is_pending=this.has_pending_snippet(),Ge(this,lc,0),Ge(this,Xu,0),Ge(this,Ji,Zr(()=>{V(this,Qu).call(this,V(this,Zi))})),V(this,lc)>0){var e=Ge(this,na,document.createDocumentFragment());zp(V(this,Ji),e);let t=V(this,Mo).pending;Ge(this,yi,Zr(()=>t(V(this,Zi))))}else lt(this,Ut,dg).call(this,Ne)}catch(t){this.error(t)}},dg=function(e){this.is_pending=!1,e.transfer_effects(V(this,fg),V(this,mg))},Qw=function(e){var t=Pe,n=ze,i=ct;Xr(V(this,vi)),Qr(V(this,vi)),ja(V(this,vi).ctx);try{return Ki.ensure(),e()}finally{Xr(t),Qr(n),ja(i)}},eA=function(e,t){var n;if(!this.has_pending_snippet()){this.parent&&lt(n=this.parent,Ut,eA).call(n,e,t);return}Ge(this,lc,V(this,lc)+e),V(this,lc)===0&&(lt(this,Ut,dg).call(this,t),V(this,yi)&&ta(V(this,yi),()=>{Ge(this,yi,null)}),V(this,na)&&(V(this,Zi).before(V(this,na)),Ge(this,na,null)))},tA=function(e){V(this,Ji)&&(br(V(this,Ji)),Ge(this,Ji,null)),V(this,yi)&&(br(V(this,yi)),Ge(this,yi,null)),V(this,eo)&&(br(V(this,eo)),Ge(this,eo,null)),Me&&(Vt(V(this,pg)),Gr(),Vt(Ks()));let t=V(this,Mo).failed,n=i=>{let{reset:o,invoke_onerror:s}=lt(this,Ut,Z_).call(this,i);s(),t&&Ge(this,eo,lt(this,Ut,Qw).call(this,()=>{try{return Zr(()=>{var a=Pe;a.b=this,a.f|=128,t(V(this,Zi),()=>i,()=>o)})}catch(a){return Mi(a,V(this,vi).parent),null}}))};yr(()=>{var i;try{i=this.transform_error(e)}catch(o){Mi(o,V(this,vi)&&V(this,vi).parent);return}i!==null&&typeof i=="object"&&typeof i.then=="function"?i.then(n,o=>Mi(o,V(this,vi)&&V(this,vi).parent)):n(i)})};var rA=!0;function ae(r,e){var n;var t=e==null?"":typeof e=="object"?`${e}`:e;t!==(r[n=Yh]??(r[n]=r.nodeValue))&&(r[Yh]=t,r.nodeValue=`${t}`)}function Zu(r,e){return gR(r,e)}function iA(r,e){Hw(),e.intro=e.intro??!1;let t=e.target,n=Me,i=Ye;try{for(var o=gn(t);o&&(o.nodeType!==Gi||o.data!=="[");)o=Nn(o);if(!o)throw qa;jr(!0),Vt(o);let s=gR(r,{...e,anchor:o});return jr(!1),s}catch(s){if(s instanceof Error&&s.message.split(`
`).some(a=>a.startsWith("https://svelte.dev/e/")))throw s;return s!==qa&&console.warn("Failed to hydrate: ",s),e.recover===!1&&pO(),Hw(),Ip(t),jr(!1),Zu(r,e)}finally{jr(n),Vt(i)}}var Zw=new Map;function gR(r,{target:e,anchor:t,props:n={},events:i,context:o,intro:s=!0,transformError:a}){Hw();var l=void 0,c=XO(()=>{var u=t??e.appendChild(wr());hg(u,{pending:()=>{}},f=>{pe({});var m=ct;if(o&&(m.c=o),i&&(n.$$events=i),Me&&Xi(f,null),rA=s,l=r(f,n)||Jh(),rA=!0,Me&&(Pe.nodes.end=Ye,Ye===null||Ye.nodeType!==Gi||Ye.data!=="]"))throw Fu(),qa;fe()},a);var d=new Set,p=f=>{for(var m=0;m<f.length;m++){var g=f[m];if(!d.has(g)){d.add(g);var v=uR(g);for(let x of[e,document]){var y=Zw.get(x);y===void 0&&(y=new Map,Zw.set(x,y));var b=y.get(g);b===void 0?(x.addEventListener(g,Kw,{passive:v}),y.set(g,1)):y.set(g,b+1)}}}};return p(Ep(Y_)),Yw.add(p),()=>{for(var f of d)for(let v of[e,document]){var m=Zw.get(v),g=m.get(f);--g==0?(v.removeEventListener(f,Kw),m.delete(f),m.size===0&&Zw.delete(v)):m.set(f,g)}Yw.delete(p),u!==t&&u.parentNode?.removeChild(u)}});return nA.set(l,c),l}var nA=new WeakMap;function jp(r,e){let t=nA.get(r);return t?(nA.delete(r),t(e)):(Q&&eO(),Promise.resolve())}var ms,oa,to,Ju,gg,vg,Jw,hs=class{constructor(e,t=!0){he(this,"anchor");rt(this,ms,new Map);rt(this,oa,new Map);rt(this,to,new Map);rt(this,Ju,new Set);rt(this,gg,!0);rt(this,vg,e=>{if(V(this,ms).has(e)){var t=V(this,ms).get(e),n=V(this,oa).get(t);if(n)Hp(n),V(this,Ju).delete(t);else{var i=V(this,to).get(t);i&&(Hp(i.effect),V(this,oa).set(t,i.effect),V(this,to).delete(t),Q&&(i.fragment.lastChild[y_]=this.anchor),i.fragment.lastChild.remove(),this.anchor.before(i.fragment),n=i.effect)}for(let[o,s]of V(this,ms)){if(V(this,ms).delete(o),o===e)break;let a=V(this,to).get(s);a&&(br(a.effect),V(this,to).delete(s))}for(let[o,s]of V(this,oa)){if(o===t||V(this,Ju).has(o))continue;let a=()=>{if(Array.from(V(this,ms).values()).includes(o)){var c=document.createDocumentFragment();zp(s,c),c.append(wr()),V(this,to).set(o,{effect:s,fragment:c})}else br(s);V(this,Ju).delete(o),V(this,oa).delete(o)};V(this,gg)||!n?(V(this,Ju).add(o),ta(s,a,!1)):a()}}});rt(this,Jw,e=>{V(this,ms).delete(e);let t=Array.from(V(this,ms).values());for(let[n,i]of V(this,to))t.includes(n)||(br(i.effect),V(this,to).delete(n))});this.anchor=e,Ge(this,gg,t)}ensure(e,t){var n=Ne,i=zw();if(t&&!V(this,oa).has(e)&&!V(this,to).has(e))if(i){var o=document.createDocumentFragment(),s=wr();o.append(s),V(this,to).set(e,{effect:Zr(()=>t(s)),fragment:o})}else V(this,oa).set(e,Zr(()=>t(this.anchor)));if(V(this,ms).set(n,e),i){for(let[a,l]of V(this,oa))a===e?n.unskip_effect(l):n.skip_effect(l);for(let[a,l]of V(this,to))a===e?n.unskip_effect(l.effect):n.skip_effect(l.effect);n.oncommit(V(this,vg)),n.ondiscard(V(this,Jw))}else Me&&(this.anchor=Ye),V(this,vg).call(this,n)}};ms=new WeakMap,oa=new WeakMap,to=new WeakMap,Ju=new WeakMap,gg=new WeakMap,vg=new WeakMap,Jw=new WeakMap;function yg(r,e,...t){var n=new hs(r);gi(()=>{let i=e()??null;Q&&i==null&&fO(),n.ensure(i,i&&(o=>i(o,...t)))},65536)}if(Q){let r=function(e){if(!(e in globalThis)){let t;Object.defineProperty(globalThis,e,{configurable:!0,get:()=>{if(t!==void 0)return t;hO(e)},set:n=>{t=n}})}};r("$state"),r("$effect"),r("$derived"),r("$inspect"),r("$props"),r("$bindable")}function eC(r){ct===null&&Aw("onMount"),Wa&&ct.l!==null?gY(ct).m.push(r):Yt(()=>{let e=kt(r);if(typeof e=="function")return e})}function gY(r){var e=r.l;return e.u??(e.u={a:[],b:[],m:[]})}var bR=new Map;function wR(r,e){var t=bR.get(r);t||(t=new Set,bR.set(r,t)),t.add(e)}function Y(r,e,t=!1){var n;Me&&(n=Ye,fn());var i=new hs(r),o=t?65536:0;function s(a,l){if(Me){var c=Qh(n);if(a!==parseInt(c.substring(1))){var u=Ks();Vt(u),i.anchor=u,jr(!1),i.ensure(a,l),jr(!0);return}}i.ensure(a,l)}gi(()=>{var a=!1;e((l,c=0)=>{a=!0,s(c,l)}),a||s(-1,null)},o)}var wY=Symbol("NaN");function bg(r,e,t){Me&&fn();var n=new hs(r),i=!cs();gi(()=>{var o=e();o!==o&&(o=wY),i&&o!==null&&typeof o=="object"&&(o={}),n.ensure(o,t)})}function xg(r,e){return e}function kY(r,e,t){for(var n=[],i=e.length,o,s=e.length,a=0;a<i;a++){let d=e[a];ta(d,()=>{if(o){if(o.pending.delete(d),o.done.add(d),o.pending.size===0){var p=r.outrogroups;oA(r,Ep(o.done)),p.delete(o),p.size===0&&(r.outrogroups=null)}}else s-=1},!1)}if(s===0){var l=n.length===0&&t!==null&&r.pending.size===0;if(l){var c=t,u=c.parentNode;Ip(u),u.append(c),r.items.clear()}oA(r,e,!l)}else o={pending:new Set(e),done:new Set},(r.outrogroups??(r.outrogroups=new Set)).add(o)}function oA(r,e,t=!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<e.length;i++){var o=e[i];if(n?.has(o)){o.f|=33554432;let s=document.createDocumentFragment();zp(o,s)}else br(e[i],t)}}var tC;function Ot(r,e,t,n,i,o=null){var s=r,a=new Map,l=(e&4)!==0;if(l){var c=r;s=Me?Vt(gn(c)):c.appendChild(wr())}Me&&fn();var u=null,d=Lu(()=>{var x=t();return ko(x)?x:x==null?[]:Ep(x)});Q&&Zn(d,"{#each ...}");var p,f=new Map,m=!0;function g(x){(b.effect.f&16384)===0&&(b.pending.delete(x),b.fallback=u,SY(b,p,s,e,n),u!==null&&(p.length===0?(u.f&33554432)===0?Hp(u):(u.f^=33554432,Cg(u,null,s)):ta(u,()=>{u=null})))}function v(x){b.pending.delete(x)}var y=gi(()=>{p=h(d);var x=p.length;let w=!1;if(Me){var T=Qh(s)==="[!";T!==(x===0)&&(s=Ks(),Vt(s),jr(!1),w=!0)}for(var C=new Set,S=Ne,A=zw(),D=0;D<x;D+=1){Me&&Ye.nodeType===Gi&&Ye.data==="]"&&(s=Ye,w=!0,jr(!1));var P=p[D],U=n(P,D);if(Q){var K=n(P,D);U!==K&&aO(String(D),String(U),String(K))}var W=m?null:a.get(U);W?(W.v&&ds(W.v,P),W.i&&ds(W.i,D),A&&S.unskip_effect(W.e)):(W=_Y(a,m?s:tC??(tC=wr()),P,U,D,i,e,t),m||(W.e.f|=33554432),a.set(U,W)),C.add(U)}if(x===0&&o&&!u&&(m?u=Zr(()=>o(s)):(u=Zr(()=>o(tC??(tC=wr()))),u.f|=33554432)),x>C.size&&(Q?AY(p,n):w_("","","")),Me&&x>0&&Vt(Ks()),!m)if(f.set(S,C),A){for(let[ee,me]of a)C.has(ee)||S.skip_effect(me.e);S.oncommit(g),S.ondiscard(v)}else g(S);w&&jr(!0),h(d)}),b={effect:y,flags:e,items:a,pending:f,outrogroups:null,fallback:u};m=!1,Me&&(s=Ye)}function wg(r){for(;r!==null&&(r.f&32)===0;)r=r.next;return r}function SY(r,e,t,n,i){var o=(n&8)!==0,s=e.length,a=r.items,l=wg(r.effect.first),c,u=null,d,p=[],f=[],m,g,v,y;if(o)for(y=0;y<s;y+=1)m=e[y],g=i(m,y),v=a.get(g).e,(v.f&33554432)===0&&(v.nodes?.a?.measure(),(d??(d=new Set)).add(v));for(y=0;y<s;y+=1){if(m=e[y],g=i(m,y),v=a.get(g).e,r.outrogroups!==null)for(let P of r.outrogroups)P.pending.delete(v),P.done.delete(v);if((v.f&8192)!==0&&(Hp(v),o&&(v.nodes?.a?.unfix(),(d??(d=new Set)).delete(v))),(v.f&33554432)!==0)if(v.f^=33554432,v===l)Cg(v,null,t);else{var b=u?u.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),cc(r,u,v),cc(r,v,b),Cg(v,b,t),u=v,p=[],f=[],l=wg(u.next);continue}if(v!==l){if(c!==void 0&&c.has(v)){if(p.length<f.length){var x=f[0],w;u=x.prev;var T=p[0],C=p[p.length-1];for(w=0;w<p.length;w+=1)Cg(p[w],x,t);for(w=0;w<f.length;w+=1)c.delete(f[w]);cc(r,T.prev,C.next),cc(r,u,T),cc(r,C,x),l=x,u=C,y-=1,p=[],f=[]}else c.delete(v),Cg(v,l,t),cc(r,v.prev,v.next),cc(r,v,u===null?r.effect.first:u.next),cc(r,u,v),u=v;continue}for(p=[],f=[];l!==null&&l!==v;)(c??(c=new Set)).add(l),f.push(l),l=wg(l.next);if(l===null)continue}(v.f&33554432)===0&&p.push(v),u=v,l=wg(v.next)}if(r.outrogroups!==null){for(let P of r.outrogroups)P.pending.size===0&&(oA(r,Ep(P.done)),r.outrogroups?.delete(P));r.outrogroups.size===0&&(r.outrogroups=null)}if(l!==null||c!==void 0){var S=[];if(c!==void 0)for(v of c)(v.f&8192)===0&&S.push(v);for(;l!==null;)(l.f&8192)===0&&l!==r.fallback&&S.push(l),l=wg(l.next);var A=S.length;if(A>0){var D=(n&4)!==0&&s===0?t:null;if(o){for(y=0;y<A;y+=1)S[y].nodes?.a?.measure();for(y=0;y<A;y+=1)S[y].nodes?.a?.fix()}kY(r,S,D)}}o&&yr(()=>{if(d!==void 0)for(v of d)v.nodes?.a?.apply()})}function _Y(r,e,t,n,i,o,s,a){var l=(s&1)!==0?(s&16)===0?Ou(t,!1,!1):ti(t):null,c=(s&2)!==0?ti(i):null;return Q&&l&&(l.trace=()=>{a()[c?.v??i]}),{v:l,i:c,e:Zr(()=>(o(e,l??t,c??i,a),()=>{r.delete(n)}))}}function Cg(r,e,t){if(r.nodes)for(var n=r.nodes.start,i=r.nodes.end,o=e&&(e.f&33554432)===0?e.nodes.start:t;n!==null;){var s=Nn(n);if(o.before(n),n===i)return;n=s}}function cc(r,e,t){e===null?r.effect.first=t:e.next=t,t===null?r.effect.last=e:t.prev=e}function AY(r,e){let t=new Map,n=r.length;for(let i=0;i<n;i++){let o=e(r[i],i);if(t.has(o)){let s=String(t.get(o)),a=String(i),l=String(o);l.startsWith("[object ")&&(l=null),w_(s,a,l)}t.set(o,i)}}var IY=hw?()=>performance.now():()=>Date.now(),gs={tick:r=>(hw?requestAnimationFrame:Ct)(r),now:()=>IY(),tasks:new Set};function xR(){let r=gs.now();gs.tasks.forEach(e=>{e.c(r)||(gs.tasks.delete(e),e.f())}),gs.tasks.size!==0&&gs.tick(xR)}function ER(r){let e;return gs.tasks.size===0&&gs.tick(xR),{promise:new Promise(t=>{gs.tasks.add(e={c:r,f:t})}),abort(){gs.tasks.delete(e)}}}function DY(r){if(r==="float")return"cssFloat";if(r==="offset")return"cssOffset";if(r.startsWith("--"))return r;let e=r.split("-");return e.length===1?e[0]:e[0]+e.slice(1).map(t=>t[0].toUpperCase()+t.slice(1)).join("")}function TR(r){let e={},t=r.split(";");for(let n of t){let[i,o]=n.split(":");if(!i||o===void 0)break;let s=DY(i.trim());e[s]=o.trim()}return e}var FY=r=>r,PY=null;function sA(r,e,t){var n=PY??Pe,i=n.nodes,o,s,a,l=null;i.a??(i.a={element:r,measure(){o=this.element.getBoundingClientRect()},apply(){if(a?.abort(),s=this.element.getBoundingClientRect(),o.left!==s.left||o.right!==s.right||o.top!==s.top||o.bottom!==s.bottom){let c=e()(this.element,{from:o,to:s},t?.());a=kR(this.element,c,void 0,1,()=>{},()=>{a?.abort(),a=void 0})}},fix(){if(!r.getAnimations().length){var{position:c,width:u,height:d}=getComputedStyle(r);if(c!=="absolute"&&c!=="fixed"){var p=r.style;l={position:p.position,width:p.width,height:p.height,transform:p.transform},p.position="absolute",p.width=u,p.height=d;var f=r.getBoundingClientRect();if(o.left!==f.left||o.top!==f.top){var m=`translate(${o.left-f.left}px, ${o.top-f.top}px)`;p.transform=p.transform?`${p.transform} ${m}`:m}}}},unfix(){if(l){var c=r.style;c.position=l.position,c.width=l.width,c.height=l.height,c.transform=l.transform}}}),i.a.element=r}function kR(r,e,t,n,i,o){var s=n===1,a=!1;if(v_(e)){var l;return yr(()=>{if(!a){var g=e({direction:s?"in":"out"});l=kR(r,g,t,n,i,o)}}),{abort:()=>{a=!0,l?.abort()},deactivate:()=>l.deactivate(),reset:()=>l.reset(),t:()=>l.t()}}if(t?.deactivate(),!e?.duration&&!e?.delay)return i(),o(),{abort:Ct,deactivate:Ct,reset:Ct,t:()=>n};let{delay:c=0,css:u,tick:d,easing:p=FY}=e;var f,m=()=>1-n;return yr(()=>{if(!a){var g=[];if(s&&t===void 0&&(d&&d(0,1),u)){var v=TR(u(0,1));g.push(v,v)}f=r.animate(g,{duration:c,fill:"forwards"}),f.onfinish=()=>{f.cancel(),i();var y=t?.t()??1-n;t?.abort();var b=n-y,x=e.duration*Math.abs(b),w=[];if(x>0){var T=!1;if(u)for(var C=Math.ceil(x/16.666666666666668),S=0;S<=C;S+=1){var A=y+b*p(S/C),D=TR(u(A,1-A));w.push(D),T||(T=D.overflow==="hidden")}T&&(r.style.overflow="hidden"),m=()=>{var P=f.currentTime;return y+b*p(P/x)},d&&ER(()=>{if(f.playState!=="running")return!1;var P=m();return d(P,1-P),!0})}f=r.animate(w,{duration:x,fill:"forwards"}),f.onfinish=()=>{m=()=>n,d?.(n,1-n),o()}}}}),{abort:()=>{a=!0,f&&(f.cancel(),f.effect=null,f.onfinish=Ct)},deactivate:()=>{o=Ct},reset:()=>{n===0&&d?.(1,0)},t:()=>m()}}function We(r,e){$r(()=>{r=Pe?.parent?.nodes?.start??r;var t=r.getRootNode(),n=t.host?t:t.head??t.ownerDocument.head;if(!n.querySelector("#"+e.hash)){let i=fs("style");i.id=e.hash,i.textContent=e.code,n.appendChild(i),Q&&wR(e.hash,i)}})}function Jt(r,e,t){$r(()=>{var n=kt(()=>e(r,t?.())||{});if(t&&n?.update){var i=!1,o={};bn(()=>{var s=t();Gw(s),i&&Sw(o,s)&&(o=s,n.update(s))}),i=!0}if(n?.destroy)return()=>n.destroy()})}var SR=[...`
\r\f\xA0\v\uFEFF`];function AR(r,e,t){var n=r==null?"":""+r;if(e&&(n=n?n+" "+e:e),t){for(var i of Object.keys(t))if(t[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||SR.includes(n[s-1]))&&(a===n.length||SR.includes(n[a]))?n=(s===0?"":n.substring(0,s))+n.substring(a+1):s=a}}return n===""?null:n}function _R(r,e=!1){var t=e?" !important;":";",n="";for(var i of Object.keys(r)){var o=r[i];o!=null&&o!==""&&(n+=" "+i+": "+o+t)}return n}function aA(r){return r[0]!=="-"||r[1]!=="-"?r.toLowerCase():r}function IR(r,e){if(e){var t="",n,i;if(Array.isArray(e)?(n=e[0],i=e[1]):n=e,r){r=String(r).replaceAll(/\/\*.*?\*\//g,"").trim();var o=!1,s=0,a=!1,l=[];n&&l.push(...Object.keys(n).map(aA)),i&&l.push(...Object.keys(i).map(aA));var c=0,u=-1;let g=r.length;for(var d=0;d<g;d++){var p=r[d];if(a?p==="/"&&r[d-1]==="*"&&(a=!1):o?o===p&&(o=!1):p==="/"&&r[d+1]==="*"?a=!0:p==='"'||p==="'"?o=p:p==="("?s++:p===")"&&s--,!a&&o===!1&&s===0){if(p===":"&&u===-1)u=d;else if(p===";"||d===g-1){if(u!==-1){var f=aA(r.substring(c,u).trim());if(!l.includes(f)){p!==";"&&d++;var m=r.substring(c,d).trim();t+=" "+m+";"}}c=d+1,u=-1}}}}return n&&(t+=_R(n)),i&&(t+=_R(i,!0)),t=t.trim(),t===""?null:t}return r==null?null:String(r)}function it(r,e,t,n,i,o){var s=r[jh];if(Me||s!==t||s===void 0){var a=AR(t,n,o);(!Me||a!==r.getAttribute("class"))&&(a==null?r.removeAttribute("class"):e?r.className=a:r.setAttribute("class",a)),r[jh]=t}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 lA(r,e={},t,n){for(var i in t){var o=t[i];e[i]!==o&&(t[i]==null?r.style.removeProperty(i):r.style.setProperty(i,o,n))}}function Gp(r,e,t,n){var i=r[Gh];if(Me||i!==e){var o=IR(e,n);(!Me||o!==r.getAttribute("style"))&&(o==null?r.removeAttribute("style"):r.style.cssText=o),r[Gh]=e}else n&&(Array.isArray(n)?(lA(r,t?.[0],n[0]),lA(r,t?.[1],n[1],"important")):lA(r,t,n));return n}function cA(r,e){e?r.hasAttribute("selected")||r.setAttribute("selected",""):r.removeAttribute("selected")}function $Y(r,e){var t=r.__defaultValue,n=r.multiple,i=n?t??[]:null;if(!(n&&!ko(i))){var o=r.selectedIndex,s=e&&n?new Set(r.selectedOptions):null;for(var a of r.options){var l=Yp(a);cA(a,n?i.includes(l):Uw(l,t))}if(e)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 uc(r,e,t=!1){if(r.multiple){if(e==null)return;if(!ko(e))return tO();for(var n of r.options)n.selected=e.includes(Yp(n));return}for(n of r.options){var i=Yp(n);if(Uw(i,e)){n.selected=!0;return}}(!t||e!==void 0)&&(r.selectedIndex=-1)}function dc(r){var e=new MutationObserver(t=>{t.every(OY)||("__defaultValue"in r&&$Y(r,!1),"__value"in r&&uc(r,r.__value))});e.observe(r,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]}),hn(()=>{e.disconnect()})}function uA(r,e,t=e){var n=new WeakSet,i=!0;$w(r,"change",o=>{var s=o?"[selected]":":checked",a;if(r.multiple)a=[].map.call(r.querySelectorAll(s),Yp);else{var l=r.querySelector(s)??r.querySelector("option:not([disabled])");a=l&&Yp(l)}t(a),r.__value=a,Ne!==null&&n.add(Ne)}),$r(()=>{var o=e();if(r===document.activeElement){var s=Ar?Xs:Ne;if(n.has(s))return}if(uc(r,o,i),i&&o===void 0){var a=r.querySelector(":checked");a!==null&&(o=Yp(a),t(o))}r.__value=o,i=!1})}function Yp(r){return"__value"in r?r.__value:r.value}function OY(r){if(r.target.closest("selectedcontent")!==null)return!0;if(r.type==="childList"){var e=[...r.addedNodes,...r.removedNodes];return e.length>0&&e.every(t=>t.nodeName==="SELECTEDCONTENT")}return!1}var VY=Symbol("is custom element"),BY=Symbol("is html"),qY=Ew?"link":"LINK";var UY=Ew?"progress":"PROGRESS";function Rt(r){if(Me){var e=!1,t=()=>{if(!e){if(e=!0,r.hasAttribute("value")){var n=r.value;ke(r,"value",null),r.value=n}if(r.hasAttribute("checked")){var i=r.checked;ke(r,"checked",null),r.checked=i}}};r[tc]=t,yr(t),Mw()}}function bi(r,e){var t=pA(r);t.value===(t.value=e??void 0)||r.value===e&&(e!==0||r.nodeName!==UY)||(r.value=e??"")}function ed(r,e){var t=pA(r);t.checked!==(t.checked=e??void 0)&&(r.checked=e)}function ke(r,e,t,n){var i=pA(r);if(Me&&(i[e]=r.getAttribute(e),e==="src"||e==="srcset"||e==="href"&&r.nodeName===qY)){n||zY(r,e,t??"");return}i[e]!==(i[e]=t)&&(e==="loading"&&(r[K$]=t),t==null?r.removeAttribute(e):typeof t!="string"&&HY(r).has(e)?r[e]=t:r.setAttribute(e,t))}function pA(r){var e;return r[e=xw]??(r[e]={[VY]:r.nodeName.includes("-"),[BY]:r.namespaceURI===mw})}var DR=new Map;function HY(r){var e=r.getAttribute("is")||r.nodeName,t=DR.get(e);if(t)return t;DR.set(e,t=new Set);for(var n,i=r,o=Element.prototype;o!==i;){n=gw(i);for(var s in n)n[s].set&&s!=="innerHTML"&&s!=="textContent"&&s!=="innerText"&&t.add(s);i=ec(i)}return t}function zY(r,e,t){Q&&(e==="srcset"&&WY(r,t)||dA(r.getAttribute(e)??"",t)||J$(e,r.outerHTML.replace(r.innerHTML,r.innerHTML&&"..."),String(t)))}function dA(r,e){return r===e?!0:new URL(r,document.baseURI).href===new URL(e,document.baseURI).href}function FR(r){return r.split(",").map(e=>e.trim().split(" ").filter(Boolean))}function WY(r,e){var t=FR(r.srcset),n=FR(e);return n.length===t.length&&n.every(([i,o],s)=>o===t[s][1]&&(dA(t[s][0],i)||dA(i,t[s][0])))}function wi(r,e,t=e){var n=new WeakSet;$w(r,"input",async i=>{Q&&r.type==="checkbox"&&b_();var o=i?r.defaultValue:r.value;if(o=fA(r)?mA(o):o,t(o),Ne!==null&&n.add(Ne),await ac(),o!==(o=e())){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))}}}),(Me&&r.defaultValue!==r.value||kt(e)==null&&r.value)&&(t(fA(r)?mA(r.value):r.value),Ne!==null&&n.add(Ne)),bn(()=>{Q&&r.type==="checkbox"&&b_();var i=e();if(r===document.activeElement){var o=Ar?Xs:Ne;if(n.has(o))return}fA(r)&&i===mA(r.value)||r.type==="date"&&!i&&!r.value||i!==r.value&&(r.value=i??"")})}function fA(r){var e=r.type;return e==="number"||e==="range"}function mA(r){return r===""?null:+r}function hA(r,e){return r===e||r?.[On]===e}function Ci(r=Jh(),e,t,n){var i=ct.r,o=Pe;return $r(()=>{var s,a;return bn(()=>{s=a,a=n?.()||[],kt(()=>{hA(t(...a),r)||(e(r,...a),s&&hA(t(...s),r)&&e(null,...s))})}),()=>{let l=o;for(;l!==i&&l.parent!==null&&l.parent.f&33554432;)l=l.parent;let c=()=>{a&&hA(t(...a),r)&&e(null,...a)},u=l.teardown;l.teardown=()=>{c(),u?.()}}}),r}function ne(r,e,t,n){var i=!Wa||(t&2)!==0,o=(t&8)!==0,s=(t&16)!==0,a=n,l=!0,c=void 0,u=()=>s&&i?(c??(c=nc(n)),h(c)):(l&&(l=!1,a=s?kt(n):n),a);let d;if(o){var p=On in r||Wh in r;d=Fi(r,e)?.set??(p&&e in r?w=>r[e]=w:void 0)}var f,m=!1;o?[f,m]=E_(()=>r[e]):f=r[e],f===void 0&&n!==void 0&&(f=u(),d&&(i&&mO(e),d(f)));var g;if(i?g=()=>{var w=r[e];return w===void 0?u():(l=!0,w)}:g=()=>{var w=r[e];return w!==void 0&&(a=void 0),w===void 0?a:w},i&&(t&4)===0)return g;if(d){var v=r.$$legacy;return(function(w,T){return arguments.length>0?((!i||!T||v||m)&&d(T?g():w),w):g()})}var y=!1,b=((t&1)!==0?nc:Lu)(()=>(y=!1,g()));Q&&(b.label=e),o&&h(b);var x=Pe;return(function(w,T){if(arguments.length>0){let C=T?h(b):i&&o?ut(w):w;return j(b,C),y=!0,a!==void 0&&(a=C),w}return Yi&&y||(x.f&16384)!==0?b.v:h(b)})}function MR(r){return new vA(r)}var Ja,$o,vA=class{constructor(e){rt(this,Ja);rt(this,$o);var t=new Map,n=(o,s)=>{var a=Ou(s,!1,!1);return t.set(o,a),a};let i=new Proxy({...e.props||{},$$events:{}},{get(o,s){return h(t.get(s)??n(s,Reflect.get(o,s)))},has(o,s){return s===Wh?!0:(h(t.get(s)??n(s,Reflect.get(o,s))),Reflect.has(o,s))},set(o,s,a){return j(t.get(s)??n(s,a),a),Reflect.set(o,s,a)}});Ge(this,$o,(e.hydrate?iA:Zu)(e.component,{target:e.target,anchor:e.anchor,props:i,context:e.context,intro:e.intro??!1,recover:e.recover,transformError:e.transformError})),!Ar&&(!e?.props?.$$host||e.sync===!1)&&zu(),Ge(this,Ja,i.$$events);for(let o of Object.keys(V(this,$o)))o==="$set"||o==="$destroy"||o==="$on"||pn(this,o,{get(){return V(this,$o)[o]},set(s){V(this,$o)[o]=s},enumerable:!0});V(this,$o).$set=o=>{Object.assign(i,o)},V(this,$o).$destroy=()=>{jp(V(this,$o))}}$set(e){V(this,$o).$set(e)}$on(e,t){V(this,Ja)[e]=V(this,Ja)[e]||[];let n=(...i)=>t.call(this,...i);return V(this,Ja)[e].push(n),()=>{V(this,Ja)[e]=V(this,Ja)[e].filter(i=>i!==n)}}$destroy(){V(this,$o).$destroy()}};Ja=new WeakMap,$o=new WeakMap;var i8;typeof HTMLElement=="function"&&(i8=class extends HTMLElement{constructor(e,t,n){super();he(this,"$$ctor");he(this,"$$s");he(this,"$$c");he(this,"$$cn",!1);he(this,"$$d",{});he(this,"$$r",!1);he(this,"$$p_d",{});he(this,"$$l",{});he(this,"$$l_u",new Map);he(this,"$$me");he(this,"$$shadowRoot",null);this.$$ctor=e,this.$$s=t,n&&(this.$$shadowRoot=this.attachShadow(n))}addEventListener(e,t,n){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(t),this.$$c){let i=this.$$c.$on(e,t);this.$$l_u.set(t,i)}super.addEventListener(e,t,n)}removeEventListener(e,t,n){if(super.removeEventListener(e,t,n),this.$$c){let i=this.$$l_u.get(t);i&&(i(),this.$$l_u.delete(t))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let e=function(i){return o=>{let s=fs("slot");i!=="default"&&(s.name=i),M(o,s)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;let t={},n=o8(this);for(let i of this.$$s)i in n&&(i==="default"&&!this.$$d.children?(this.$$d.children=e(i),t.default=!0):t[i]=e(i));for(let i of this.attributes){let o=this.$$g_p(i.name);o in this.$$d||(this.$$d[o]=yA(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=MR({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:t,$$host:this}}),this.$$me=z_(()=>{bn(()=>{this.$$r=!0;for(let i of h_(this.$$c)){if(!this.$$p_d[i]?.reflect)continue;this.$$d[i]=this.$$c[i];let o=yA(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(e,t,n){this.$$r||(e=this.$$g_p(e),this.$$d[e]=yA(e,n,this.$$p_d,"toProp"),this.$$c?.$set({[e]:this.$$d[e]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{!this.$$cn&&this.$$c&&(this.$$c.$destroy(),this.$$me(),this.$$c=void 0)})}$$g_p(e){return h_(this.$$p_d).find(t=>this.$$p_d[t].attribute===e||!this.$$p_d[t].attribute&&t.toLowerCase()===e)||e}});function yA(r,e,t,n){let i=t[r]?.type;if(e=i==="Boolean"&&typeof e!="boolean"?e!=null:e,!n||!t[r])return e;if(n==="toAttribute")switch(i){case"Object":case"Array":return e==null?null:JSON.stringify(e);case"Boolean":return e?"":null;case"Number":return e??null;default:return e}else switch(i){case"Object":case"Array":return e&&JSON.parse(e);case"Boolean":return e;case"Number":return e!=null?+e:e;default:return e}}function o8(r){let e={};return r.childNodes.forEach(t=>{e[t.slot||"default"]=!0}),e}var yH=require("obsidian");dt();Ie();var MU=require("obsidian");Xe();var Dg={location:"tab",direction:"vertical",mode:"default",focus:!0};function Cn(r,e){if(!(e?.fillMissingOnly??!0))return{...Dg,...r??{}};let n={...r??{}};return n.location==null&&(n.location=Dg.location),n.direction==null&&(n.direction=Dg.direction),n.mode==null&&(n.mode=Dg.mode),n.focus==null&&(n.focus=Dg.focus),n}var vN=require("obsidian");Xe();function Qp(r){return r.trim().replace(/^\/+/,"")}function gc(r){return r.trim().toLowerCase().endsWith(".canvas")}function FA(r,e){let t=Qp(e);if(!t||t.includes("{{"))return null;let n=r.vault.getAbstractFileByPath(t);return!n||!(n instanceof vN.TFile)||n.extension!=="canvas"?null:n}function yN(r,e){let n=r.workspace.getMostRecentLeaf?.()?.view;if(!n||n.getViewType?.()!=="canvas")return null;let i=Qp(e),o=Qp(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 u8(r){return typeof r=="string"?r:r&&typeof r=="object"&&"path"in r&&typeof r.path=="string"?r.path:"(missing file path)"}function d8(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 DA(r,e){return r.length<=e?r:r.slice(0,e-1)+"\u2026"}async function bN(r,e){try{let t=await r.vault.cachedRead(e),n=JSON.parse(t);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=d8(a);if(l==="text"){let m=(typeof a.text=="string"?a.text:"").split(`
`).map(b=>b.trim()).filter(b=>b.length>0),g=DA(m[0]??"(empty text card)",90),v=[`${m.length} line${m.length===1?"":"s"}`];c&&v.push(c);let y=v.join(" \xB7 ");return{id:a.id,type:l,title:g,subtitle:y,searchText:`${a.id} ${g} ${y}`.toLowerCase(),capturable:!0,capturableReason:""}}if(l==="file"){let f=u8(a.file),m=Nt.test(f),g=m?"":"Canvas file cards must link to markdown files (.md).",v=DA(f.split("/").pop()??f,90),y=[DA(f,120)];c&&y.push(c),m||y.push("Not capturable in this version");let b=y.join(" \xB7 ");return{id:a.id,type:l,title:v,subtitle:b,searchText:`${a.id} ${v} ${b}`.toLowerCase(),capturable:m,capturableReason:g}}let d=`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:d,subtitle:p,searchText:`${a.id} ${d} ${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[]}}ht();Kg();ks();rn();bt();Xe();var Q5=["noteContent","propertyValue","captureTarget","fileName","lineTarget"],X5=["captureTarget","fileName"],Un=Q5,o1=3;function Be(r,e,t=r.endsWith(":}}")?2:0){return{insert:r,description:e,caretOffset:t}}var Z5=[{regex:KR,contexts:Un,suggestion:Be("{{VALUE}}","Asks you for text when the choice runs")},{regex:QR,contexts:Un,suggestion:Be("{{VALUE:}}","Asks once and reuses the answer by name, or lists options to pick from"),expansions:()=>[Be("{{VALUE:title}}",'Asks once, then reuses the answer as "title"'),Be("{{VALUE:option1,option2,option3}}","Asks you to pick one of these options"),Be("{{VALUE:option1,option2,option3|custom}}","Same, but you can also type your own"),Be("{{VALUE:title|label:Note title}}","Words the prompt yourself"),Be("{{VALUE:option1,option2|label:Pick one}}","A list with your own prompt text"),Be("{{VALUE:title|label:Note title|default:Untitled}}","Opens the prompt with an answer already filled in"),Be("{{VALUE:<items>|text:<display items>}}","Shows one label in the list and inserts another"),Be("{{VALUE:option1,option2|name:category}}","Names the pick, so {{VALUE:category}} reuses it"),Be("{{VALUE:title|case:kebab}}","Reshapes the answer; type |case: for every style"),Be("{{VALUE:title|trim}}","Trims whitespace off the answer"),Be("{{VALUE:title|optional}}","Lets the prompt be skipped, leaving it empty")]},{regex:YR,contexts:Un,suggestion:Be("{{NAME}}","Another name for {{VALUE}}; they do the same thing")},{regex:XR,contexts:Un,suggestion:Be("{{VDATE:}}",'Asks you for a date; "tomorrow" works'),expansions:()=>[Be("{{VDATE:date,YYYY-MM-DD}}",'Asks for a date, reused by name as "date"'),Be("{{VDATE:date,YYYY-MM-DD|today}}","Same, with today filled in"),Be("{{VDATE:dueDate,YYYY-MM-DD|next monday}}","Same, starting at next Monday"),Be("{{VDATE:dueDate,YYYY-MM-DD|optional}}","Same, but skippable"),Be("{{VDATE:date,dddd, MMMM Do, YYYY|case:lower}}","Lowercases the picked date after formatting")]},{regex:nN,contexts:Un,suggestion:Be("{{FIELD:}}","Suggests values a property already has in your vault, like {{FIELD:project}}")},{regex:lN,contexts:["noteContent","propertyValue"],suggestion:Be("{{PROPERTY}}","Inserts the property's current value (property Captures only)")},{regex:cN,contexts:["noteContent"],suggestion:Be("{{CURSOR}}","Places the cursor here (Capture and Template bodies)")},{regex:rN,contexts:Un,suggestion:Be("{{FILE:}}","Picks a note from a folder"),expansions:({context:r})=>{let e=[Be("{{FILE:<folder>}}","Picks a note from that folder and inserts its name")];return X5.includes(r)||e.push(Be("{{FILE:<folder>|link}}","Same, but inserts a link to the note"),Be("{{FILE:<folder>|path}}","Same, but inserts its full path"),Be("{{FILE:<folder>|optional}}","Same, but skippable")),e.push(Be("{{FILE:<folder>|custom}}","Same, but you can also type a name that is not there yet")),e}},{regex:sN,contexts:Un,suggestion:Be("{{MVALUE}}","Asks you for a math formula (LaTeX), with a live preview")},{regex:jR,contexts:Un,suggestion:Be("{{DATE}}","Today's date, as YYYY-MM-DD")},{regex:GR,contexts:Un,suggestion:Be("{{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(e=>Be(`{{DATE:${e}}}`,r(e))),Be("{{DATE+7}}","Seven days from today"),Be("{{DATE:YYYY-MM-DD|startof:week}}","Snapped to the start of the week, month, quarter or year"),Be("{{DATE:dddd, MMMM Do, YYYY|case:lower}}","Lowercases the formatted date")]},{regex:mN,contexts:Un,suggestion:Be("{{TIME}}","The current time, as HH:mm")},{regex:hN,contexts:Un,suggestion:Be("{{TIME:}}","The current time in a format you choose, like {{TIME:HH.mm}}"),expansions:()=>[Be("{{TIME:A|case:lower}}","Lowercases formatted text, such as AM to am")]},{regex:ZR,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Be("{{LINKCURRENT}}","A link to that note: [[That note]]")},{regex:JR,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Be("{{LINKSECTION}}","A link to the section your cursor is in")},{regex:eN,contexts:["noteContent","propertyValue","captureTarget","fileName","lineTarget"],suggestion:Be("{{FILENAMECURRENT}}","That note's file name")},{regex:IA,contexts:["noteContent","propertyValue","captureTarget"],suggestion:Be("{{FOLDERCURRENT}}","That note's folder")},{regex:IA,contexts:["fileName"],suggestion:Be("{{FOLDERCURRENT|name}}","That note's folder name, without the path")},{regex:uN,contexts:Un,suggestion:Be("{{SELECTED}}","The text you had selected in the editor")},{regex:aN,contexts:["noteContent","propertyValue","lineTarget"],suggestion:Be("{{TITLE}}","The new note's file name")},{regex:tN,contexts:["fileName"],suggestion:Be("{{FOLDER|name}}","The name of the folder the new note lands in")},{regex:dN,contexts:Un,suggestion:Be("{{CLIPBOARD}}","Whatever you copied last")},{regex:iN,contexts:Un,suggestion:Be("{{TEMPLATE:}}","The contents of a template file"),expansions:({templatePaths:r})=>r.map(e=>Be(`{{TEMPLATE:${e}}}`,"Inserts this template's contents"))},{regex:oN,contexts:Un,suggestion:Be("{{MACRO:}}","Whatever a macro returns"),expansions:({macroNames:r})=>[...r.map(e=>Be(`{{MACRO:${e}}}`,`Runs your "${e}" macro`)),Be("{{MACRO:MyMacro|label:Label}}","Word the macro's own prompt yourself")]},{regex:fN,contexts:Un,suggestion:Be("{{GLOBAL_VAR:}}","A snippet you defined in QuickAdd's settings"),expansions:({globalVariableNames:r})=>r.map(e=>Be(`{{GLOBAL_VAR:${e}}}`,`Inserts your "${e}" snippet`))},{regex:pN,contexts:Un,suggestion:Be("{{RANDOM:}}","A random ID of the length you give, like {{RANDOM:6}}")}],s1=[{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 a1(r){return Z5.filter(e=>e.contexts.includes(r))}var J5=/^\{\{(VALUE|NAME|DATE|TIME|VDATE)([^\n\r}]*)\|case:([a-z-]*)$/i,eK=new Set(["DATE","TIME","VDATE"]),tK=/<[^<>\n\r]+>/,Sn=class extends xr{constructor(t,n,i,o="noteContent"){super(t,n);this.app=t;this.inputEl=n;this.plugin=i;this.context=o;this.replaceFrom=0;this.matchedQuery="";this.macroNames=nn(this.plugin.settings.choices).filter(s=>s.type==="Macro").map(s=>s.name),this.templatePaths=this.plugin.getTemplateFiles().map(s=>s.path)}getSuggestions(t){if(this.inputEl.selectionStart===null)return[];let n=this.inputEl.selectionStart,i=t.lastIndexOf("{{",n-1);if(i===-1)return[];let o=t.slice(i,n);if(o.includes("}}"))return[];let s=o.match(J5);if(s){let m=s[1]?.toUpperCase()??"",g=s[2]??"";if(eK.has(m)&&g.lastIndexOf("[")>g.lastIndexOf("]"))return[];let v=s[3]??"";this.matchedQuery=v,this.replaceFrom=n-v.length;let y=v.toLowerCase();return s1.filter(b=>b.insert.startsWith(y)).map(b=>({...b}))}if(o.includes(":"))return[];let a=[],l=new Set,c=m=>{l.has(m.insert)||(l.add(m.insert),a.push(m))};this.replaceFrom=i,this.matchedQuery=o.slice(2);let u=a1(this.context).filter(m=>{let g=m.regex.exec(o);return g!==null&&g.index+g[0].length===o.length}),d=this.matchedQuery.toLowerCase(),p=m=>m.suggestion.insert.slice(2).toLowerCase().startsWith(d),f=[...u.filter(p),...u.filter(m=>!p(m))];for(let m of f)if(c(m.suggestion),!!m.expansions&&!(this.matchedQuery.length<o1))for(let g of m.expansions({templatePaths:this.templatePaths,macroNames:this.macroNames,globalVariableNames:Object.keys(this.plugin?.settings?.globalVariables??{}),context:this.context,formatDate:v=>typeof window.moment=="function"?window.moment().format(v):v}))c(g);return a}selectSuggestion(t){if(this.inputEl.selectionStart===null)return;let n=this.inputEl.selectionStart,i=this.replaceFrom;HC(this.inputEl,i,n,t.insert,{fromCompletion:!0});let o=tK.exec(t.insert);if(o){let s=i+o.index;this.inputEl.setSelectionRange(s,s+o[0].length)}else if(t.caretOffset>0){let s=i+t.insert.length-t.caretOffset;this.inputEl.setSelectionRange(s,s)}this.close()}renderSuggestion(t,n){if(!t)return;n.classList.add("qa-format-suggestion");let i=n.createSpan({cls:t.isFragment?"qa-format-suggestion-token qa-format-suggestion-token-fragment":"qa-format-suggestion-token"});this.renderMatch(i,t.insert,this.matchedQuery),n.createSpan({cls:"qa-format-suggestion-description",text:t.description})}};var rK=L('<label class="setting-item-name"> </label>'),nK=L('<div class="setting-item-name"> </div>'),iK=L('<div class="setting-item-description"> </div>'),oK=L('<div><div class="setting-item-info"><!> <!></div> <div class="setting-item-control"><!></div></div>');function Se(r,e){let t=ne(e,"name",3,void 0),n=ne(e,"desc",3,void 0),i=ne(e,"heading",3,!1),o=ne(e,"labelFor",3,void 0),s=ne(e,"control",3,void 0),a=ne(e,"children",3,void 0);var l=oK();let c;var u=B(l),d=B(u);{var p=y=>{var b=or(),x=Te(b);{var w=C=>{var S=rK(),A=le(S,!0);re(()=>{ke(S,"for",o()),ae(A,t())}),M(C,S)},T=C=>{var S=nK(),A=le(S,!0);re(()=>ae(A,t())),M(C,S)};Y(x,C=>{o()?C(w):C(T,-1)})}M(y,b)};Y(d,y=>{t()&&y(p)})}var f=_(d,2);{var m=y=>{var b=iK(),x=le(b,!0);re(()=>ae(x,n())),M(y,b)};Y(f,y=>{n()&&y(m)})}N(u);var g=_(u,2),v=B(g);yg(v,()=>s()??a()??Ct),N(g),N(l),re(()=>c=it(l,1,"setting-item",null,c,{"setting-item-heading":i()})),M(r,l)}var sK=L('<div role="switch"><input type="checkbox" tabindex="-1" aria-hidden="true" class="svelte-1bigjf0"/></div>'),aK={hash:"svelte-1bigjf0",code:`
/* Let clicks fall through to the container so a single handler owns toggling. */.checkbox-container.svelte-1bigjf0 > input:where(.svelte-1bigjf0) {pointer-events:none;}`};function St(r,e){pe(e,!0),We(r,aK);let t=ne(e,"checked",15),n=ne(e,"disabled",3,!1),i=ne(e,"ariaLabel",3,void 0),o=ne(e,"onchange",3,void 0),s=F(()=>t()??!1);function a(){n()||(t(!h(s)),o()?.(t()))}function l(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),a())}var c=sK();let u;var d=B(c);Rt(d),N(c),re(()=>{u=it(c,1,"checkbox-container svelte-1bigjf0",null,u,{"is-enabled":h(s),"is-disabled":n()}),ke(c,"aria-checked",h(s)),ke(c,"aria-label",i()),ke(c,"tabindex",n()?-1:0),ed(d,h(s))}),Ae("click",c,a),Ae("keydown",c,l),M(r,c),fe()}nt(["click","keydown"]);var lK=L("<option> </option>"),cK=L('<select class="dropdown"></select>');function ft(r,e){pe(e,!0);let t=ne(e,"value",15,""),n=ne(e,"disabled",3,!1),i=ne(e,"ariaLabel",3,void 0),o=ne(e,"onchange",3,void 0);var s=cK();Ot(s,21,()=>e.options,a=>a.value,(a,l)=>{var c=lK(),u=le(c,!0),d={};re(()=>{ae(u,h(l).label),d!==(d=h(l).value)&&(c.value=(c.__value=d)??"")}),M(a,c)}),N(s),dc(s),re(()=>{s.disabled=n(),ke(s,"aria-label",i())}),Ae("change",s,()=>o()?.(t())),uA(s,t),M(r,s),fe()}nt(["change"]);var l1=require("obsidian"),uK=L('<span class="quickadd-icon svelte-1fiwm9k"></span>'),dK={hash:"svelte-1fiwm9k",code:".quickadd-icon.svelte-1fiwm9k {display:inline-flex;align-items:center;}.quickadd-icon.svelte-1fiwm9k svg {display:inline-block;vertical-align:middle;}"};function Et(r,e){pe(e,!0),We(r,dK);let t=ne(e,"size",3,16),n=Ce(void 0);Yt(()=>{if(!h(n)||!e.iconId)return;(0,l1.setIcon)(h(n),e.iconId);let o=h(n).querySelector("svg");o&&(o.setAttribute("width",`${t()}`),o.setAttribute("height",`${t()}`))});var i=uK();Ci(i,o=>j(n,o),()=>h(n)),M(r,i),fe()}Ds();Ie();xt();function Ef(r){return r==="Multi"?"folder":"choice"}function u2(r){return r==="Multi"?"Folder":"Choice"}function VQ(r){return`${u2(r)} name`}async function wx(r,e,t){try{let i=(await ar.Prompt(r,VQ(t),void 0,e)).trim();return!i||i===e?null:i}catch(n){return ot(n)||I.logError(nl(n,"Could not rename")),null}}var BQ=L('<h2 class="choiceNameHeader"><button type="button" class="choiceNameHeaderButton qa-rename-title-button"><span class="choiceNameHeaderText"> </span> <span class="choiceNameHeaderIcon" aria-hidden="true"><!></span></button></h2>');function kv(r,e){pe(e,!0);let t=ne(e,"name",15);async function n(){let u=await wx(e.app,t());u&&t(u)}var i=BQ(),o=B(i),s=B(o),a=le(s,!0),l=_(s,2),c=B(l);Et(c,{iconId:"pencil",size:16}),N(l),N(o),N(i),re(()=>{ke(o,"aria-label",`Rename ${t()}`),ae(a,t())}),Ae("click",o,n),M(r,i),fe()}nt(["click"]);ks();rn();var si=class extends xr{constructor(t,n,i,o=1/0){super(t,n);this.app=t;this.inputEl=n;this.items=i;this.maxSuggestions=o;this.items=i.map(s=>kn(s))}getSuggestions(t){let n=Ac(t).toLowerCase(),i=this.items.filter(s=>s.toLowerCase().includes(n));return i.length===0&&this.close(),i.slice(0,this.maxSuggestions)}selectSuggestion(t){this.inputEl.value=t,this.inputEl.trigger("input"),this.close()}renderSuggestion(t,n){if(!t)return;let i=iv(t),o=iv(this.getCurrentQuery());t.toLowerCase().endsWith(".md")&&o.toLowerCase().startsWith(`${i.toLowerCase()}.`)&&(o=i),this.renderMatch(n,i,o)}getCurrentQuery(){return this.inputEl.value}};function qQ(r){return r?Array.isArray(r)?r:[r]:[]}function Sd(r,e){let t=qQ(e(r));return{destroy(){t.forEach(n=>n.destroy())}}}var UQ=L("<textarea></textarea>"),HQ=L('<input type="text"/>'),zQ=L('<!> <div aria-live="polite"> </div>',1);function sn(r,e){pe(e,!0);let t=ne(e,"value",15,""),n=ne(e,"placeholder",3,void 0),i=ne(e,"inputKind",3,"text"),o=ne(e,"required",3,!1),s=ne(e,"requiredMessage",3,"This field is required"),a=ne(e,"disabled",3,!1),l=ne(e,"validator",3,void 0),c=ne(e,"trim",3,!0),u=ne(e,"suggestions",3,void 0),d=ne(e,"maxSuggestions",3,1/0),p=ne(e,"makeSuggesters",19,()=>[]),f=ne(e,"app",3,void 0),m=ne(e,"id",3,void 0),g=ne(e,"ariaLabel",3,void 0),v=ne(e,"onChange",3,void 0),y=Ce(!1),b=Ce(""),x=Ce("neutral"),w=0,T=!1,C=`qa-hint-${Math.random().toString(36).slice(2)}`,S=te=>c()?te.trim():te;function A(te,z=!1,G="neutral"){j(y,z,!0),j(b,te??"",!0),j(x,z?"neutral":G,!0)}async function D(te){if(o()&&S(te).length===0)return A(s(),!0),!1;if(!l())return A(void 0),!0;let z=++w,G=await Promise.resolve(l()(te));return z!==w||T?!0:typeof G=="boolean"?(A(G?void 0:"Invalid value",!G),G):typeof G=="string"?(A(G,!0),!1):(A(G.message??(G.valid?void 0:"Invalid value"),!G.valid,G.valid?G.variant??"neutral":"neutral"),G.valid)}function P(te){let z=te.currentTarget.value;t(z),v()?.(z)}Yt(()=>{o();let te=t();D(te)}),Yt(()=>()=>{T=!0});function U(te){let z=[];f()&&u()&&u().length&&z.push(new si(f(),te,u(),d()));for(let G of p()){let ie=G(te);ie&&z.push(ie)}return z}var K=zQ(),W=Te(K);{var ee=te=>{var z=UQ();Nu(z);let G;Jt(z,(ie,xe)=>Sd?.(ie,xe),()=>U),re(()=>{G=it(z,1,"qa-validated-input-full-width qa-validated-input-margin-8 qa-validated-input-textarea",null,G,{"is-invalid":h(y),"is-valid":!h(y)&&h(x)==="success"&&h(b).length>0}),ke(z,"id",m()),ke(z,"placeholder",n()),z.disabled=a(),ke(z,"aria-label",g()),ke(z,"aria-invalid",h(y)),ke(z,"aria-describedby",C),bi(z,t())}),Ae("input",z,P),M(te,z)},me=te=>{var z=HQ();Rt(z);let G;Jt(z,(ie,xe)=>Sd?.(ie,xe),()=>U),re(()=>{G=it(z,1,"qa-validated-input-full-width qa-validated-input-margin-8",null,G,{"is-invalid":h(y),"is-valid":!h(y)&&h(x)==="success"&&h(b).length>0}),ke(z,"id",m()),ke(z,"placeholder",n()),z.disabled=a(),ke(z,"aria-label",g()),ke(z,"aria-invalid",h(y)),ke(z,"aria-describedby",C),bi(z,t())}),Ae("input",z,P),M(te,z)};Y(W,te=>{i()==="textarea"?te(ee):te(me,-1)})}var O=_(W,2);let H;var ce=le(O,!0);re(()=>{H=it(O,1,"qa-field-hint",null,H,{"qa-field-hint--neutral":!h(y)&&h(x)==="neutral","qa-field-hint--success":!h(y)&&h(x)==="success"}),ke(O,"id",C),ae(ce,h(b))}),M(r,K),fe()}nt(["input"]);var WQ=L('<div class="qa-field-body"><!></div>'),jQ=L('<div class="qa-field"><!> <!></div>');function Ti(r,e){let t=Ku(),n=ne(e,"desc",3,void 0),i=ne(e,"control",3,void 0),o=ne(e,"bodyVisible",3,!0);var s=jQ(),a=B(s);{let u=F(()=>o()?t:void 0);Se(a,{get name(){return e.name},get desc(){return n()},get control(){return i()},get labelFor(){return h(u)}})}var l=_(a,2);{var c=u=>{var d=WQ(),p=B(d);yg(p,()=>e.children,()=>t),N(d),M(u,d)};Y(l,u=>{o()&&u(c)})}N(s),M(r,s)}wl();Pd();xt();var Vc=class{constructor(){this.entries=[];this.seen=new Set}add(e,t,n){let i=IX(t).trim();if(!i)return;let o=`${e} ${i}`;this.seen.has(o)||(this.seen.add(o),this.entries.push({severity:e,message:i,...n?{kind:n}:{}}))}list(){return this.entries}get hasError(){return this.entries.some(e=>e.severity==="error")}};function IX(r){return r.replace(/^\[(QuickAdd:[\s\S]*)\]$/i,"$1").replace(/^QuickAdd:\s*/i,"")}function Of(r){if(ot(r))return null;if(!(r instanceof Error))return rV;let e=r.message??"";return ot(e)?null:e.startsWith("Unable to parse variable")?"This token is incomplete. {{VALUE:}} needs a name, for example {{VALUE:title}}.":e.trim()?e:rV}var rV="Preview unavailable - this format could not be resolved.";da();var OX={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"},RX={clipboard:"clipboard_content",date:"formatted_date",time:"current_time",random:"random_value",uuid:"unique_id"},NX=[{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 Ox(r){let e=r.toLowerCase(),t=OX[e];return t||`${r}_example`}function Rx(r){return RX[r.toLowerCase()]||`${r}_output`}function Nx(r){for(let{pattern:e,example:t}of NX)if(e.test(r))return t;return`${r}_value`}function Lx(r){return r.length>0?`${r[0]} (${r.length} options)`:"suggestion_list"}function Rf(r,e){return Md(r).length>0?e:r}function Vx(r){let e=r.fieldName.trim();return e?`${e}_field_value`:"field_value"}function pV(r){return r?.path?r.basename:"current_file"}function Nf(r){return`${r?.path?r.basename:"current_file"}#Section`}function fV(r){return r?.basename||"current_filename"}function mV(r){if(!r)return"current_folder";let e=r.parent?.path??"";return e==="/"?"":e}var pa=class{static generate(e,t=new Date){let n=t.getFullYear(),i=this.getWeekNumber(t),o=t.getDate(),s=[["YYYY",n.toString()],["YY",n.toString().slice(-2)],["MMMM",this.MONTH_NAMES[t.getMonth()]],["MMM",this.MONTH_NAMES_SHORT[t.getMonth()]],["MM",(t.getMonth()+1).toString().padStart(2,"0")],["M",(t.getMonth()+1).toString()],["dddd",this.DAY_NAMES[t.getDay()]],["ddd",this.DAY_NAMES_SHORT[t.getDay()]],["Do",`${o}${this.ordinalSuffix(o)}`],["DD",t.getDate().toString().padStart(2,"0")],["D",o.toString()],["HH",t.getHours().toString().padStart(2,"0")],["H",t.getHours().toString()],["mm",t.getMinutes().toString().padStart(2,"0")],["m",t.getMinutes().toString()],["ss",t.getSeconds().toString().padStart(2,"0")],["s",t.getSeconds().toString()],["ww",i.toString().padStart(2,"0")],["w",i.toString()]],a="",l=0;for(;l<e.length;){let c=!1;for(let[u,d]of s)if(e.startsWith(u,l)){a+=d,l+=u.length,c=!0;break}c||(a+=e[l],l+=1)}return a}static ordinalSuffix(e){let t=e%100;if(t>=11&&t<=13)return"th";switch(e%10){case 1:return"st";case 2:return"nd";case 3:return"rd";default:return"th"}}static getWeekNumber(e){let t=new Date(e.getFullYear(),0,1),n=(e.getTime()-t.getTime())/864e5;return Math.ceil((n+t.getDay()+1)/7)}};pa.MONTH_NAMES=["January","February","March","April","May","June","July","August","September","October","November","December"],pa.MONTH_NAMES_SHORT=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],pa.DAY_NAMES=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],pa.DAY_NAMES_SHORT=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];pd();lo();var Lf=class extends Lc{constructor(){super(...arguments);this.diagnostics=new Vc}warn(t){this.diagnostics.add("warning",t)}reportProblem(t){this.diagnostics.add("error",t)}getCurrentFileLink(){return this.app?pV(this.app.workspace.getActiveFile()):null}getCurrentFileName(){return this.app?fV(this.app.workspace.getActiveFile()):"current_filename"}getCurrentFolderPath(){return this.app?mV(this.app.workspace.getActiveFile()):"current_folder"}promptForMathValue(){return Promise.resolve("calculation_result")}async getSelectedText(){return"selected_text"}async getClipboardContent(){return"clipboard_content"}suggestForFile(t){let n=this.app?xi.filterFiles(this.app.vault.getMarkdownFiles(),t.filter,i=>this.app.metadataCache.getFileCache(i)):[];return n.length>0?`${Pc}${n[0].path}`:`${As}${t.folderPath||"file"}`}isTemplatePropertyTypesEnabled(){return!1}};$v();Pd();qg();Xe();Ld();uo();Pv();Yg();function Yx(r){let e=new Date;return r?rf(window.moment(e),r).toDate():e}var jf=class extends Lf{constructor(t,n,i,o={}){super(t);this.plugin=n;this.opts=o;this.dateParser=i||Qo}async format(t){this.diagnostics=new Vc;try{return zn(await this.formatInternal(t,{expandLinebreakEscapes:!0}))}catch(n){let i=Of(n);return i&&this.diagnostics.add("error",i),zn(t)}}async formatInternal(t,{expandLinebreakEscapes:n}){let i=t;return i=await this.replaceGlobalVarInString(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(t){return Bc(t,this.plugin?.settings?.globalVariables)}promptForValue(t){return t||"user input"}getVariableValue(t){let n=this.variables.get(t);if(typeof n=="string")return n;let i=Iv(t);return Ox(i)}getCurrentFileLinkToSection(){return this.app?Nf(this.app.workspace.getActiveFile()):Nf(null)}suggestForValue(t,n=!1,i){return Lx(i?.displayValues??t)}getMacroValue(t,n){return Rx(t)}promptForVariable(t,n){return Promise.resolve(Nx(t))}async getTemplateContent(t){let n=this.app;if(!n)return this.reportProblem(`Template preview unavailable: ${t}`),`[QuickAdd: template preview unavailable] ${t}`;let i=Vn(n,t);if(!i)return this.reportProblem(`Template not found: ${t}`),`[QuickAdd: template not found] ${t}`;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=Of(o);return s&&this.diagnostics.add("error",s),`[QuickAdd: template preview failed] ${t}`}finally{this.templateInclusion.depth--}}async suggestForField(t,n){return Promise.resolve(Vx(n))}async replaceDateVariableInString(t){let n=t;return n=n.replace(new RegExp(mc.source,"gi"),(i,o,s,a)=>{let l=o?.trim(),{options:c,error:u}=Px(a);u&&this.reportProblem(u);let{defaultValue:d,optional:p,withTime:f,snap:m,caseStyle:g}=c,v=s?.trim()||Mf(f);if(!l)return i;let y=$f(this.variables.get(l),v,m,this.dateParser);if(y)return this.applyCaseOption(y.text,g,i);let b;try{b=this.applyCaseOption(pa.generate(v,Yx(m)),g,i)}catch{b=`[${v} format]`}return d&&(b+=` (default: ${d})`),p&&(b+=" (optional)"),b}),n}replaceRandomInString(t){let n=t;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}};wl();$v();Pd();Pv();var Gf=require("obsidian");Xe();Ld();da();qg();uo();var RB=25;function n9(r){let e=r.lastIndexOf("{{");return e===-1?!1:r.indexOf("}}",e+2)===-1}function i9(r){let e=Dd(r);if(e.length===0)return r;let t="",n=0;for(let i of e)t+=r.slice(n,i.start),n=i.end;return t+r.slice(n)}var Yf=class extends Lf{constructor(t,n,i){super(t);this.plugin=n;this.templateIncludeBudget=RB;this.dateParser=i||Qo}setRunClocks(t){this.clocks=t}async format(t){let n=t;this.diagnostics=new Vc,this.templateIncludeBudget=RB;try{n=zn(await this.formatInternal(t,{included:!1}))}catch(o){let s=Of(o);return s&&this.diagnostics.add("error",s),zn(t)}this.reportCircularTitle(t,n);let i=uV(n);for(let o of i.problems)this.diagnostics.add("error",o,"path");return this.reportIllegalChars(t,n),i.path}reportCircularTitle(t,n){!Ro.test(t)&&!Ro.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(t,n){if(this.diagnostics.hasError||n9(t)||yD(t))return;let i=Md(i9(n));i.length!==0&&(this.existsInVault(n)||this.diagnostics.add("error",sV(i),"path"))}existsInVault(t){let n=this.app?.vault;if(typeof n?.getAbstractFileByPath!="function")return!1;let i=t.trim();return i?i.endsWith("/")?n.getAbstractFileByPath(i.slice(0,-1))instanceof Gf.TFolder:n.getAbstractFileByPath(i)instanceof Gf.TFile||n.getAbstractFileByPath(`${i}.md`)instanceof Gf.TFile?!0:n.getAbstractFileByPath(i)instanceof Gf.TFolder:!1}async formatInternal(t,{included:n}){let i=t;return i=await this.replaceTemplateOutsideScripts(i),i=await this.replaceGlobalVarInString(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(t){return Bc(t,this.plugin?.settings?.globalVariables)}promptForValue(t){return Rf(t||"user input","user input")}getVariableValue(t){let n=this.variables.get(t);if(typeof n=="string")return n;let i=Iv(t);return Rf(Ox(i),"user input")}suggestForValue(t,n=!1,i){return t[0]??Lx(t)}getMacroValue(t,n){return Rf(Rx(t),"macro_output")}async promptForVariable(t,n){return Rf(Nx(t),"user input")}async replaceTemplateOutsideScripts(t){let n=Dd(t);if(n.length===0)return this.replaceTemplateInString(t);let i="",o=0;for(let s of n)i+=await this.replaceTemplateInString(t.slice(o,s.start)),i+=t.slice(s.start,s.end),o=s.end;return i+await this.replaceTemplateInString(t.slice(o))}async getTemplateContent(t){let n=this.app;if(!n)return this.reportProblem(`Template preview unavailable: ${t}`),`[QuickAdd: template preview unavailable] ${t}`;if(this.templateIncludeBudget<=0){let o="[QuickAdd: too many template includes to preview]";return this.reportProblem(o),o}let i=Vn(n,t);if(!i)return this.reportProblem(`Template not found: ${t}`),`[QuickAdd: template not found] ${t}`;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(t,s),s}catch(o){let s=Of(o);return s&&this.diagnostics.add("error",s),`[QuickAdd: template preview failed] ${t}`}finally{this.templateInclusion.depth--}}resolveTitleInIncludedBody(t){if(!Ro.test(t))return t;let n=this.variables.get("title"),i=typeof n=="string"?n:"";return t.replace(new RegExp(Ro.source,"gi"),()=>i)}warnIfJoinedIntoOneLine(t,n){let i=n.split(/\r?\n/).filter(o=>o.trim());i.length<2||this.warn(`Template "${t}" is ${i.length} lines; a file name is one line, so they are joined with spaces.`)}getCurrentFileLinkToSection(){return this.app?Nf(this.app.workspace.getActiveFile()):Nf(null)}async suggestForField(t,n){return Rf(Vx(n),"field_value")}async replaceDateVariableInString(t){let n=t;return n=n.replace(new RegExp(mc.source,"gi"),(i,o,s,a)=>{let l=o?.trim();if(!l)return i;let{options:c,error:u}=Px(a);u&&this.reportProblem(u);let{withTime:d,snap:p,caseStyle:f}=c,m=s?.trim()||Mf(d),g=$f(this.variables.get(l),m,p,this.dateParser);if(g)return this.applyCaseOption(g.text,f,i);try{return this.applyCaseOption(pa.generate(m,Yx(p)),f,i)}catch{return`[${m}]`}}),n}replaceRandomInString(t){let n=t;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 o9=L('<div><span class="qa-visually-hidden"> </span> </div>'),s9=L('<div class="qa-preview-issues"></div>'),a9=L('<div><span class="qa-preview-label"> </span><span class="qa-preview-value" aria-live="polite"> </span></div> <!>',1);function fo(r,e){pe(e,!0);let t=ne(e,"formatterKind",3,"format"),n=500,i=Ce(""),o=Ce(ut([])),s=Ce(!1),a=0,l=F(()=>e.value.trim().length>0),c=F(()=>e.hideWhen?e.hideWhen(h(i))&&!h(o).some(v=>v.severity==="error"&&v.kind!=="path"):!1),u=F(()=>h(s)?h(o).filter(v=>v.severity==="error"):[]),d=F(()=>h(u).some(v=>v.kind!=="path")),p=F(()=>!h(d)&&h(u).length>0);Yt(()=>{let v=e.value;if(!v.trim()){a++,j(i,""),j(o,[],!0);return}let y=t()==="fileName"?new Yf(e.app,e.plugin):new jf(e.app,e.plugin,void 0,{resolveActiveFolder:t()!=="lineTarget"});y.setTargetFolderPath(e.targetFolderPath===null?null:e.targetFolderPath?.trim()?e.targetFolderPath:"Folder/Name");let b=++a;(async()=>{try{let x=await y.format(v);if(b!==a)return;j(i,x,!0),j(o,y.diagnostics.list(),!0)}catch{if(b!==a)return;j(i,v,!0),j(o,[{severity:"error",message:"Preview unavailable."}],!0)}})()}),Yt(()=>{e.value,j(s,!1);let v=setTimeout(()=>{j(s,!0)},n);return()=>clearTimeout(v)});var f=or(),m=Te(f);{var g=v=>{var y=a9(),b=Te(y);let x;var w=B(b),T=le(w,!0),C=_(w),S=le(C,!0);N(b);var A=_(b,2);{var D=P=>{var U=s9();Ot(U,21,()=>h(o),K=>K.severity+K.message,(K,W)=>{var ee=o9();let me;var O=B(ee),H=le(O,!0),ce=_(O,1,!0);N(ee),re(()=>{me=it(ee,1,"qa-preview-issue",null,me,{"qa-preview-issue--error":h(W).severity==="error"}),ke(ee,"title",h(W).message),ae(H,h(W).severity==="error"?"Error: ":"Warning: "),ae(ce,h(W).message)}),M(K,ee)}),N(U),M(P,U)};Y(A,P=>{h(s)&&h(o).length>0&&P(D)})}re(()=>{x=it(b,1,"qa-preview-row",null,x,{"qa-preview-row--one-line":t()==="fileName"}),ke(b,"title",t()==="fileName"?h(i):void 0),ae(T,h(d)?"Unresolved: ":h(p)?"Won't be created: ":"Preview: "),ae(S,h(i))}),M(v,y)};Y(m,v=>{h(l)&&!h(c)&&v(g)})}M(r,f),fe()}bs();Ie();var py="https://quickadd.obsidian.guide",Ms={gettingStarted:`${py}/docs/`,formatSyntax:`${py}/docs/FormatSyntax/`,onePageInputs:`${py}/docs/Advanced/onePageInputs/`,userScripts:`${py}/docs/Choices/MacroChoice/#user-scripts`,packages:`${py}/docs/Choices/Packages/`};function NB(r,e){try{(e?Rg(e):window).open(r,"_blank","noopener,noreferrer")}catch(t){I.logError(`QuickAdd: Failed to open documentation (${r}): ${t}`)}}function Kx(r,e,t){let n=er(r,"a");return n.textContent=t,n.href=e,n.target="_blank",n.rel="noopener noreferrer",n.classList.add("quickadd-docs-link"),r.append(n),n}var l9=L('<div class="qa-token-hint">Type <code>&#123;&#123;</code> to insert a token &middot; <a class="quickadd-docs-link" target="_blank" rel="noopener noreferrer">Format syntax</a></div>');function Vd(r,e){pe(e,!0);let t=F(()=>!e.value.includes("{{"));var n=or(),i=Te(n);{var o=s=>{var a=l9(),l=_(B(a),3);N(a),re(()=>ke(l,"href",Ms.formatSyntax)),M(s,a)};Y(i,s=>{h(t)&&s(o)})}M(r,n),fe()}var LB=require("obsidian");wc();Og();var c9=L('<input type="text" class="text-input" aria-label="Frontmatter property" placeholder="related" required=""/>'),LD=L("<!> <!>",1),u9=L("<!> <!> <!> <!>",1);function fy(r,e){pe(e,!0);let t=ne(e,"appendLink",15),n=ne(e,"app",3,void 0),i=F(()=>bc(t())),o=F(()=>h(i).linkType??"link"),s=F(()=>h(i).displayText),a=F(()=>h(i).frontmatterHandling??ud),l=F(()=>h(i).destination.type==="specifiedFile"?h(i).destination.path:""),c=F(()=>h(i).enabled?h(i).requireActiveFile?"required":"optional":"disabled"),u=F(()=>h(i).destination.type),d=F(()=>n()?n().vault.getMarkdownFiles().map(O=>O.path):[]),p=[{value:"required",label:"Enabled (strict)"},{value:"optional",label:"Enabled (skip if unavailable)"},{value:"disabled",label:"Disabled"}],f=[{value:"activeFile",label:"Current note"},{value:"specifiedFile",label:"Specified note"}],m=[{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"}],y=[{value:"alwaysAppend",label:"Create or convert"},{value:"createProperty",label:"Create if missing"},{value:"error",label:"Require list"}];function b(O){let H=t(),ce=typeof H=="boolean"?h(i):H,te=O.placement??ce.placement,z=O.destination??ce.destination??h(i).destination,G=z.type==="activeFile"&&Zp(te)?O.linkType??ce.linkType??h(o):"link",ie=z.type==="activeFile"&&wC(te)&&G==="link"?O.displayText??h(s):"none";return{enabled:O.enabled??!0,placement:te,requireActiveFile:O.requireActiveFile??ce.requireActiveFile??h(i).requireActiveFile,linkType:G,displayText:ie,destination:z,frontmatterProperty:O.frontmatterProperty??ce.frontmatterProperty,frontmatterHandling:O.frontmatterHandling??ce.frontmatterHandling}}function x(O){switch(O){case"disabled":t(b({enabled:!1}));break;case"required":t(b({requireActiveFile:!0}));break;case"optional":t(b({requireActiveFile:!1}));break}}function w(O){t(b({placement:O}))}function T(O){t(b({linkType:O}))}function C(O){t(b({displayText:O}))}function S(O){t(b({frontmatterProperty:O.currentTarget.value}))}function A(O){t(b({frontmatterHandling:O}))}function D(O){let H=O==="specifiedFile"?{type:"specifiedFile",path:h(l)}:{type:"activeFile"};t(b({destination:H}))}function P(O){t(b({destination:{type:"specifiedFile",path:O.trim()}}))}function U(O){let H=O.trim();if(!H)return"Destination file is required";if(!n())return!0;let ce=n().vault.getAbstractFileByPath(RA(H));return ce instanceof LB.TFile&&ce.extension==="md"?!0:"Markdown file not found"}var K=LD(),W=Te(K);{let O=te=>{ft(te,{get value(){return h(c)},get options(){return p},onchange:x})},H=F(()=>`Link to ${e.fileLabel} file`),ce=F(()=>`Choose whether QuickAdd should insert a link to the ${e.fileLabel} file.`);Se(W,{get name(){return h(H)},get desc(){return h(ce)},control:O,$$slots:{control:!0}})}var ee=_(W,2);{var me=O=>{var H=LD(),ce=Te(H);{let ie=ue=>{ft(ue,{get value(){return h(u)},get options(){return f},onchange:D})},xe=F(()=>`Where QuickAdd writes the link to the ${e.fileLabel} file.`);Se(ce,{name:"Link destination",get desc(){return h(xe)},control:ie,$$slots:{control:!0}})}var te=_(ce,2);{var z=ie=>{var xe=u9(),ue=Te(xe);Se(ue,{name:"Link placement",desc:"Where to place the link when appending",control:ve=>{ft(ve,{get value(){return h(i).placement},get options(){return m},onchange:w})},$$slots:{control:!0}});var be=_(ue,2);{var Ke=ge=>{Se(ge,{name:"Link type",desc:"Choose whether to insert a link or an embed. Embeds transclude the note's contents at the placement position.",control:Fe=>{ft(Fe,{get value(){return h(o)},get options(){return g},onchange:T})},$$slots:{control:!0}})},Oe=F(()=>Zp(h(i).placement));Y(be,ge=>{h(Oe)&&ge(Ke)})}var Ee=_(be,2);{var He=ge=>{Se(ge,{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:Fe=>{ft(Fe,{get value(){return h(s)},get options(){return v},onchange:C})},$$slots:{control:!0}})},Le=F(()=>wC(h(i).placement)&&h(o)==="link");Y(Ee,ge=>{h(Le)&&ge(He)})}var At=_(Ee,2);{var mr=ge=>{var ve=LD(),Fe=Te(ve);Se(Fe,{name:"Frontmatter property",desc:"Required property to insert the link into.",control:Ft=>{var Qe=c9();Rt(Qe),re(zt=>{bi(Qe,h(i).frontmatterProperty??""),ke(Qe,"aria-invalid",zt)},[()=>!h(i).frontmatterProperty?.trim()]),Ae("input",Qe,S),M(Ft,Qe)},$$slots:{control:!0}});var Je=_(Fe,2);Se(Je,{name:"Property handling",desc:"Choose how strict QuickAdd should be when the property is missing or not a list.",control:Ft=>{ft(Ft,{get value(){return h(a)},get options(){return y},onchange:A})},$$slots:{control:!0}}),M(ge,ve)},zr=F(()=>al(h(i).placement));Y(At,ge=>{h(zr)&&ge(mr)})}M(ie,xe)},G=ie=>{Se(ie,{name:"Destination file",desc:"Existing Markdown note that receives the link at the bottom.",control:ue=>{sn(ue,{get value(){return h(l)},placeholder:"Index.md",get app(){return n()},get suggestions(){return h(d)},maxSuggestions:50,required:!0,requiredMessage:"Destination file is required",validator:U,ariaLabel:"Append link destination file",onChange:P})},$$slots:{control:!0}})};Y(te,ie=>{h(u)==="activeFile"?ie(z):ie(G,-1)})}M(O,H)};Y(ee,O=>{h(c)!=="disabled"&&O(me)})}M(r,K),fe()}nt(["input"]);function my(r,e){pe(e,!0);let t=ne(e,"openFile",15);Se(r,{name:"Open",get desc(){return e.description},control:i=>{St(i,{get checked(){return t()},set checked(o){t(o)}})},$$slots:{control:!0}}),fe()}var d9=L("<!> <!> <!> <!>",1);function hy(r,e){pe(e,!0);let t=ne(e,"fileOpening",15);t(Cn(t()));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=F(()=>typeof t().mode=="string"?t().mode:"default");var a=d9(),l=Te(a);{let m=v=>{ft(v,{get value(){return t().location},get options(){return n},onchange:y=>t(t().location=y,!0)})},g=F(()=>`Where to open the ${e.contextLabel} file`);Se(l,{name:"File opening location",get desc(){return h(g)},control:m,$$slots:{control:!0}})}var c=_(l,2);{var u=m=>{Se(m,{name:"Split direction",desc:"How to arrange the new pane relative to the current one",control:v=>{ft(v,{get value(){return t().direction},get options(){return i},onchange:y=>t(t().direction=y,!0)})},$$slots:{control:!0}})};Y(c,m=>{t().location==="split"&&m(u)})}var d=_(c,2);Se(d,{name:"View mode",desc:"How to display the opened file",control:g=>{ft(g,{get value(){return h(s)},get options(){return o},onchange:v=>t(t().mode=v,!0)})},$$slots:{control:!0}});var p=_(d,2);{var f=m=>{Se(m,{name:"Focus new pane",desc:"Focus the opened tab immediately after opening",control:v=>{St(v,{get checked(){return t().focus},set checked(y){t(t().focus=y,!0)}})},$$slots:{control:!0}})};Y(p,m=>{t().location!=="reuse"&&m(f)})}M(r,a),fe()}function gy(r,e){pe(e,!0);let t=ne(e,"onePageInput",15),n=[{value:"",label:"Follow global setting"},{value:"always",label:"Always"},{value:"never",label:"Never"}],i=F(()=>t()??"");function o(s){t(s==="always"||s==="never"?s:void 0)}Se(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=>{ft(a,{get value(){return h(i)},get options(){return n},onchange:o})},$$slots:{control:!0}}),fe()}Kf();Kc();var m9=L('<input type="text" class="qa-validated-input-full-width" placeholder="-2"/> <!>',1),h9=L('<input type="text" class="qa-validated-input-full-width" placeholder="day"/>'),g9=L("<!> <!> <!> <!>",1);function xy(r,e){pe(e,!0);let t=ne(e,"dateOrigin",15),n=vy.map(S=>({value:S,label:S})),i=F(()=>Al(t())),o=F(()=>t()?.kind==="ask"?t():void 0),s=F(()=>h(i)==="custom"&&t()?.kind==="relative"?t():void 0),a=F(()=>t()?.kind==="variable"?t():void 0),l=F(()=>Cy(h(o)?.defaultValue)),c=F(()=>sE(h(o)?.defaultValue));function u(S){iE(S)&&t(oE({preset:S,previous:t()}))}function d(S){if(t()?.kind!=="ask")return;let A=aE(S,t().defaultValue);t(A?{kind:"ask",defaultValue:A}:{kind:"ask"})}function p(S){if(t()?.kind!=="relative")return;let A=S.trim();/^[+-]?\d+$/.test(A)&&t({...t(),offset:Number(A)})}function f(S){t()?.kind==="relative"&&yy(S)&&t({...t(),unit:S})}function m(S){t()?.kind==="variable"&&t({kind:"variable",name:S})}var g=g9(),v=Te(g);Se(v,{get name(){return Qx},get desc(){return Xx},control:A=>{ft(A,{get value(){return h(i)},get options(){return rE},onchange:u})},$$slots:{control:!0}});var y=_(v,2);{var b=S=>{Se(S,{get name(){return Zx},get desc(){return Jx},control:D=>{ft(D,{get value(){return h(l)},get options(){return h(c)},onchange:d})},$$slots:{control:!0}})};Y(y,S=>{h(o)&&S(b)})}var x=_(y,2);{var w=S=>{Se(S,{get name(){return by},get desc(){return eE},control:D=>{var P=m9(),U=Te(P);Rt(U);var K=_(U,2);ft(K,{get value(){return h(s).unit},get options(){return n},onchange:f}),re(W=>{bi(U,W),ke(U,"aria-label",by)},[()=>String(h(s).offset)]),Ae("input",U,W=>{let ee=W.currentTarget;ee instanceof HTMLInputElement&&p(ee.value)}),M(D,P)},$$slots:{control:!0}})};Y(x,S=>{h(s)&&S(w)})}var T=_(x,2);{var C=S=>{Se(S,{get name(){return wy},get desc(){return tE},control:D=>{var P=h9();Rt(P),re(()=>{bi(P,h(a).name),ke(P,"aria-label",wy)}),Ae("input",P,U=>{let K=U.currentTarget;K instanceof HTMLInputElement&&m(K.value)}),M(D,P)},$$slots:{control:!0}})};Y(T,S=>{h(a)&&S(C)})}M(r,g),fe()}nt(["input"]);Kc();var Ey="Add to command palette",lE="Run this choice from the command palette or a hotkey.",cE="A second command that asks which day first. Your hotkey for the main command still uses Which day.";function Ty(r){return`Also add "${qD(r)}"`}function uE(r){return`choice:${r}`}function BD(r){return`${uE(r)}:pick-day`}function qD(r){return`${r} (pick a day)`}function ky(r){return Al(r)!=="ask"}function qB(r){return!!r.enabled&&ky(r.origin)}var v9=L("<!> <!>",1);function Sy(r,e){pe(e,!0);let t=ne(e,"command",15),n=ne(e,"pickDayCommand",15),i=F(()=>t()&&ky(e.dateOrigin));var o=v9(),s=Te(o);Se(s,{get name(){return Ey},get desc(){return lE},control:u=>{St(u,{get ariaLabel(){return Ey},get checked(){return t()},set checked(d){t(d)}})},$$slots:{control:!0}});var a=_(s,2);{var l=c=>{{let u=p=>{{let f=F(()=>Ty(e.name));St(p,{get ariaLabel(){return h(f)},get checked(){return n()},set checked(m){n(m)}})}},d=F(()=>Ty(e.name));Se(c,{get name(){return h(d)},get desc(){return cE},control:u,$$slots:{control:!0}})}};Y(a,c=>{h(i)&&c(l)})}M(r,o),fe()}ht();var y9=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),b9=new Intl.Collator(void 0,{numeric:!0,sensitivity:"variant"});function dE(r){return r.trim().replace(/^\/+/,"").replace(/\/+$/,"")}function w9(r,e){let t=dE(r),n=dE(e);if(t===n)return 0;let i=t===""?[]:t.split("/"),o=n===""?[]:n.split("/"),s=Math.min(i.length,o.length);for(let a=0;a<s;a++){let l=y9.compare(i[a],o[a]);if(l!==0)return l;let c=b9.compare(i[a],o[a]);if(c!==0)return c}return i.length-o.length}function Il(r){return[...r].sort(w9)}function C9(r,e){let t=dE(r),n=dE(e);return n?t===n||t.startsWith(`${n}/`):!0}function UB(r,e){let t=[],n=new Set;for(let i of e)for(let o of r)n.has(o)||C9(o,i)&&(t.push(o),n.add(o));return t}var Qc=require("obsidian");var x9=L('<div class="qa-canvas-node-empty"> </div>'),E9=L('<div class="qa-canvas-node-empty">No nodes match the current filter.</div>'),T9=L('<button type="button"> </button>'),k9=L('<button type="button" disabled="">Unavailable</button>'),S9=L('<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>'),_9=L('<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 UD(r,e){pe(e,!0);let t=ne(e,"nodeId",15),n=Ce(ut([])),i=Ce("loading"),o=Ce(""),s=Ce(""),a=F(()=>{let W=h(s).trim().toLowerCase();return W.length?h(n).filter(ee=>ee.searchText.includes(W)):h(n)}),l=F(()=>(t()??"").trim()),c=F(()=>h(i)==="ready"?`Showing ${h(a).length} of ${h(n).length} nodes`:h(i)==="empty"?h(o):"Loading canvas nodes\u2026");eC(()=>{(async()=>{let W=FA(e.app,e.canvasTargetPath);if(!W){j(o,"Node picker works for direct .canvas paths that already exist in your vault. Format syntax paths cannot be listed here."),j(i,"empty");return}if(j(n,await bN(e.app,W),!0),h(n).length===0){j(o,"No selectable nodes found in the target canvas."),j(i,"empty");return}j(i,"ready")})()});function u(W){t(W)}function d(){let W=FA(e.app,e.canvasTargetPath);if(!W){new Qc.Notice("Target canvas file was not found.");return}e.app.workspace.getLeaf(!0).openFile(W).catch(()=>new Qc.Notice("Could not open target canvas."))}function p(){let W=yN(e.app,e.canvasTargetPath);if(!W){new Qc.Notice("Open the target canvas and select exactly one card to use this action.");return}let ee=h(n).find(me=>me.id===W);if(!ee){new Qc.Notice(h(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(!ee.capturable){new Qc.Notice(ee.capturableReason);return}u(W)}function f(W){(async()=>{try{await navigator.clipboard.writeText(W),new Qc.Notice(`Copied node id ${W}`)}catch{new Qc.Notice("Could not copy node id automatically.")}})()}function m(W){return W==="text"?"TEXT":W==="file"?"FILE":"NODE"}var g=_9(),v=B(g),y=B(v),b=_(y,2),x=_(b,2);N(v);var w=_(v,2),T=B(w);Rt(T),N(w);var C=_(w,2),S=le(C,!0),A=_(C,2),D=B(A);{var P=W=>{var ee=x9(),me=le(ee,!0);re(()=>ae(me,h(o))),M(W,ee)},U=W=>{var ee=E9();M(W,ee)},K=W=>{var ee=or(),me=Te(ee);Ot(me,17,()=>h(a),O=>O.id,(O,H)=>{let ce=F(()=>h(l)===h(H).id);var te=S9();let z;var G=B(te),ie=B(G),xe=le(ie,!0),ue=_(ie,2),be=le(ue,!0);N(G);var Ke=_(G,2),Oe=le(Ke,!0),Ee=_(Ke,2),He=B(Ee),Le=le(He,!0);N(Ee);var At=_(Ee,2),mr=B(At);{var zr=Fe=>{var Je=T9();let mt;var Ft=le(Je,!0);re(()=>{mt=it(Je,1,"",null,mt,{"mod-cta":h(ce)}),ae(Ft,h(ce)?"Selected":"Use node")}),Ae("click",Je,()=>u(h(H).id)),M(Fe,Je)},ge=Fe=>{var Je=k9();re(()=>ke(Je,"title",h(H).capturableReason)),M(Fe,Je)};Y(mr,Fe=>{h(H).capturable?Fe(zr):Fe(ge,-1)})}var ve=_(mr,2);N(At),N(te),re(Fe=>{z=it(te,1,"qa-canvas-node-item",null,z,{"is-selected":h(ce)}),it(ie,1,`qa-canvas-node-type is-${h(H).type??""}`),ae(xe,Fe),ae(be,h(H).title),ae(Oe,h(H).subtitle),ae(Le,h(H).id)},[()=>m(h(H).type)]),Ae("click",ve,()=>f(h(H).id)),M(O,te)}),M(W,ee)};Y(D,W=>{h(i)==="empty"?W(P):h(i)==="ready"&&h(a).length===0?W(U,1):W(K,-1)})}N(A),N(g),re(()=>ae(S,h(c))),Ae("click",y,d),Ae("click",b,p),Ae("click",x,()=>u("")),wi(T,()=>h(s),W=>j(s,W)),M(r,g),fe()}nt(["click"]);pE();fE();function F9(r){return r.trim().replace(/^\/+/,"")}function _y(r){return[...new Set((r??[]).map(e=>e.trim()).filter(Boolean))]}function Ay(r,e="or"){return r.length<=1?r[0]??"":e==="+"?r.join(" + "):r.length===2?`${r[0]} ${e} ${r[1]}`:`${r.slice(0,-1).join(", ")}, ${e} ${r[r.length-1]}`}function WB(r){let e=_y(r.folders??(r.folder?[r.folder]:[])),t=_y(r.tags),n=_y(r.excludeFolders),i=_y(r.excludeTags),o=_y(r.excludeFiles),s=[];return e.length>0&&s.push(`${e.length===1?"folder":"folders"} ${Ay(e)}`),t.length>0&&s.push(`${t.length===1?"tag":"tags"} ${Ay(t,"+")}`),n.length>0&&s.push(`excluding ${n.length===1?"folder":"folders"} ${Ay(n)}`),i.length>0&&s.push(`excluding ${i.length===1?"tag":"tags"} ${Ay(i,"+")}`),o.length>0&&s.push(`excluding ${o.length===1?"file":"files"} ${Ay(o)}`),s.length>0?s.join("; "):"all notes"}function Iy(r){let e=F9(r),t=Zf(e);if(t){if(!t.field)return{recognized:!0,valid:!1,variant:"error",message:"Property capture target needs a field name, e.g. property:type=draft."};let i=t.value?`frontmatter ${t.field} = ${t.value}`:`frontmatter field ${t.field}`,o=WB(t.filter),s=o==="all notes"?"":`; ${o}`;return{recognized:!0,valid:!0,variant:"success",message:`Recognized property target: ${i}${s}.`}}let n=Xf(e);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: ${WB(n.filter)}.`}:null}var P9=L("<!> <!> <!>",1),M9=L('<!> <div class="qa-canvas-node-helper">Tip: open this canvas and select one card to grab its id instantly.</div> <!>',1),jB=L("<!> <!>",1);function HD(r,e){pe(e,!0);let t=ne(e,"choice",15),n=F(()=>{let v=Il(Vo(e.app)).filter(x=>x.length>0).map(x=>x.endsWith("/")?x:x+"/"),y=e.app.vault.getMarkdownFiles().map(x=>x.path),b=e.app.vault.getFiles().filter(x=>x.extension==="canvas").map(x=>x.path);return Array.from(new Set([...v,...y,...b]))}),i=[v=>new Sn(e.app,v,e.plugin,"captureTarget")],o=F(()=>Iy(t().captureTo??"")),s=F(()=>h(o)!==null),a=v=>Iy(v)!==null,l=F(()=>!h(s)&&gc(t().captureTo));function c(v){let y=!!t().captureToActiveFile&&t().activeFileWritePosition==="bottom";t(t().captureToActiveFile=v,!0),!v&&y&&t(t().prepend=!0,!0),!v&&t().newLineCapture?.enabled&&t(t().newLineCapture.enabled=!1,!0)}function u(v){let y=Qp(t().captureTo),b=gc(t().captureTo),x=Iy(v)!==null;t(t().captureTo=v,!0);let w=Qp(v),T=gc(v);(x||!T||b&&T&&y!==w)&&t(t().captureToCanvasNodeId="",!0)}function d(v){let y=Iy(v);return y?{valid:y.valid,message:y.message,variant:y.valid?"success":void 0}:v.trim()?!0:{valid:!0,message:"Leave empty to pick the note each time this choice runs."}}var p=jB(),f=Te(p);Se(f,{name:"Capture to active file",desc:"Capture into whichever note is open when the choice runs, instead of a fixed target.",control:y=>{St(y,{get checked(){return t().captureToActiveFile},onchange:c})},$$slots:{control:!0}});var m=_(f,2);{var g=v=>{var y=jB(),b=Te(y);Ti(b,{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.",children:(C,S=Ct)=>{var A=P9(),D=Te(A);sn(D,{get id(){return S()},get value(){return t().captureTo},placeholder:"Daily/{{DATE}}.md",get app(){return e.app},get suggestions(){return h(n)},maxSuggestions:50,get makeSuggesters(){return i},validator:d,onChange:u});var P=_(D,2);Vd(P,{get value(){return t().captureTo}});var U=_(P,2);{var K=W=>{fo(W,{get value(){return t().captureTo},formatterKind:"fileName",get app(){return e.app},get plugin(){return e.plugin},hideWhen:a})};Y(U,W=>{h(s)||W(K)})}M(C,A)},$$slots:{default:!0}});var x=_(b,2);{var w=T=>{var C=M9(),S=Te(C);Se(S,{name:"Target canvas node",desc:"Choose a card from the canvas below, or paste an exact node id.",control:P=>{{let U=F(()=>t().captureToCanvasNodeId??"");sn(P,{get value(){return h(U)},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:K=>t(t().captureToCanvasNodeId=K.trim(),!0)})}},$$slots:{control:!0}});var A=_(S,4);bg(A,()=>t().captureTo,D=>{UD(D,{get canvasTargetPath(){return t().captureTo},get app(){return e.app},get nodeId(){return t().captureToCanvasNodeId},set nodeId(P){t(t().captureToCanvasNodeId=P,!0)}})}),M(T,C)};Y(x,T=>{h(l)&&T(w)})}M(v,y)};Y(m,v=>{t().captureToActiveFile||v(g)})}M(r,p),fe()}var QB=require("obsidian");var KB=require("obsidian");Xe();function zD(r){let t=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(t)return t;let i=r.match(/\{\{VDATE:[^,}]+,([^}\n\r]*)\}\}/i)?.[1]?.split("|")[0]?.trim();if(i)return i}var $9=L(`<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>`),GB=L("<!> <!>",1),O9=L(`<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>`),YB=L("<!> <!> <!>",1),R9=L(`<div class="setting-item-description">No sorting: newest-first prepends the new section above existing ones;
oldest-first appends it below.</div>`),N9=L(`<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>`),L9=L(`<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),V9=L("<!> <!> <!> <!> <!>",1);function WD(r,e){pe(e,!0);let t=ne(e,"insertAfter",15);t().inline===void 0&&t(t().inline=!1,!0),t().replaceExisting===void 0&&t(t().replaceExisting=!1,!0),t().promptHeading===void 0&&t(t().promptHeading=!1,!0),t().insertAtEnd===void 0&&t(t().insertAtEnd=!1,!0),t().considerSubsections===void 0&&t(t().considerSubsections=!1,!0),t().blankLineAfterMatchMode||t(t().blankLineAfterMatchMode="auto",!0),t().createIfNotFound||t(t().createIfNotFound=!1,!0),t().createIfNotFoundLocation||t(t().createIfNotFoundLocation=no,!0);let n=[O=>new Sn(e.app,O,e.plugin,"lineTarget")],i=[{value:"auto",label:"Auto (headings only)"},{value:"skip",label:"Always skip"},{value:"none",label:"Never skip"}],o=F(()=>t().inline?[{value:no,label:"Top"},{value:nd,label:"Bottom"},{value:id,label:"Cursor"}]:[{value:no,label:"Top"},{value:nd,label:"Bottom"},{value:id,label:"Cursor"},{value:vs,label:"Ordered (place new section 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 existing unparseable headings to bottom"},{value:"top",label:"Sort existing unparseable headings to top"}],c=Ce(!!t().orderBy),u=F(()=>t().createIfNotFoundLocation===vs),d=F(()=>t().createIfNotFound&&h(u)),p=F(()=>new jf(e.app,e.plugin)),f=Ce(!1);Yt(()=>{let O=t().after??"",H=h(p);if(!t().inline||O===""){j(f,!1);return}let ce=!1;return H.format(O).then(te=>{ce||j(f,/[\n\r]/.test(te),!0)}).catch(()=>{ce||j(f,!1)}),()=>{ce=!0}});let m=F(()=>t().orderBy??{by:"insertion",direction:"desc",unparseable:"bottom"}),g=F(()=>/\{\{V?DATE\b/i.test(t().after??"")),v=F(()=>h(d)&&t().orderBy?.by==="insertion"&&h(g)&&!zD(t().after??""));Yt(()=>{if(!h(d))return;let O=zD(t().after??"");if(!t().orderBy){t(t().orderBy={by:O?"date":"insertion",direction:"desc",dateFormat:O,unparseable:"bottom"},!0);return}!h(c)&&(t().orderBy.by==="insertion"||t().orderBy.by==="date")&&(t(t().orderBy.by=O?"date":"insertion",!0),t(t().orderBy.dateFormat=O,!0))});function y(O){t(t().createIfNotFoundLocation=O,!0),O===vs?t(t().inline=!1,!0):(t(t().orderBy=void 0,!0),j(c,!1))}function b(O){j(c,!0),t().orderBy&&t(t().orderBy.by=O,!0)}function x(O){t().promptHeading||O&&!t().after.startsWith("#")&&(t(t().considerSubsections=!1,!0),new KB.Notice("Consider subsections requires the target to be a heading (starts with #)"))}function w(O){O&&(t(t().inline=!1,!0),t(t().replaceExisting=!1,!0))}var T=V9(),C=Te(T);Se(C,{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:H=>{St(H,{onchange:w,get checked(){return t().promptHeading},set checked(ce){t(t().promptHeading=ce,!0)}})},$$slots:{control:!0}});var S=_(C,2);{var A=O=>{var H=$9();M(O,H)},D=O=>{var H=YB(),ce=Te(H);Ti(ce,{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:(xe,ue=Ct)=>{var be=GB(),Ke=Te(be);sn(Ke,{get id(){return ue()},placeholder:"Insert after",required:!0,requiredMessage:"Insert after text is required",get makeSuggesters(){return n},get value(){return t().after},set value(Ee){t(t().after=Ee,!0)}});var Oe=_(Ke,2);fo(Oe,{get value(){return t().after},formatterKind:"lineTarget",get app(){return e.app},get plugin(){return e.plugin}}),M(xe,be)},$$slots:{default:!0}});var te=_(ce,2);{let ie=ue=>{St(ue,{get disabled(){return h(u)},get checked(){return t().inline},set checked(be){t(t().inline=be,!0)}})},xe=F(()=>h(u)?"Inline insertion can't be combined with ordered placement.":"Insert captured content on the same line, immediately after the matched text (no newline added).");Se(te,{name:"Inline insertion",get desc(){return h(xe)},control:ie,$$slots:{control:!0}})}var z=_(te,2);{var G=ie=>{var xe=O9();M(ie,xe)};Y(z,ie=>{h(f)&&ie(G)})}M(O,H)};Y(S,O=>{t().promptHeading?O(A):O(D,-1)})}var P=_(S,2);{var U=O=>{Se(O,{name:"Replace existing value",desc:"Replace everything after the matched text up to end-of-line.",control:ce=>{St(ce,{get checked(){return t().replaceExisting},set checked(te){t(t().replaceExisting=te,!0)}})},$$slots:{control:!0}})},K=O=>{var H=YB(),ce=Te(H);Se(ce,{name:"Insert at end of section",desc:"Place the text at the end of the matched section instead of the top.",control:ie=>{St(ie,{get checked(){return t().insertAtEnd},set checked(xe){t(t().insertAtEnd=xe,!0)}})},$$slots:{control:!0}});var te=_(ce,2);{let G=xe=>{{let ue=F(()=>t().blankLineAfterMatchMode??"auto");ft(xe,{get value(){return h(ue)},get options(){return i},get disabled(){return t().insertAtEnd},onchange:be=>t(t().blankLineAfterMatchMode=be,!0)})}},ie=F(()=>t().insertAtEnd?"Not used when inserting at end of section.":"Controls whether Insert After skips existing blank lines after the matched line.");Se(te,{name:"Blank lines after match",get desc(){return h(ie)},control:G,$$slots:{control:!0}})}var z=_(te,2);{let G=xe=>{{let ue=F(()=>!t().insertAtEnd);St(xe,{get disabled(){return h(ue)},onchange:x,get checked(){return t().considerSubsections},set checked(be){t(t().considerSubsections=be,!0)}})}},ie=F(()=>t().insertAtEnd?t().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.");Se(z,{name:"Consider subsections",get desc(){return h(ie)},control:G,$$slots:{control:!0}})}M(O,H)};Y(P,O=>{t().inline?O(U):O(K,-1)})}var W=_(P,2);Se(W,{name:"Create line if not found",desc:"Creates the 'insert after' line if it is not found.",control:H=>{var ce=GB(),te=Te(ce);St(te,{get checked(){return t().createIfNotFound},set checked(G){t(t().createIfNotFound=G,!0)}});var z=_(te,2);{let G=F(()=>t().createIfNotFoundLocation||no);ft(z,{get value(){return h(G)},get options(){return h(o)},onchange:y})}M(H,ce)},$$slots:{control:!0}});var ee=_(W,2);{var me=O=>{var H=L9(),ce=_(Te(H),2);Se(ce,{name:"Sort sections by",control:He=>{ft(He,{get value(){return h(m).by},get options(){return s},onchange:b})},$$slots:{control:!0}});var te=_(ce,2);Se(te,{name:"Section order",control:He=>{ft(He,{get value(){return h(m).direction},get options(){return a},onchange:Le=>{t().orderBy&&t(t().orderBy.direction=Le,!0)}})},$$slots:{control:!0}});var z=_(te,2);{var G=Ee=>{Se(Ee,{name:"Date format",desc:"Moment format used to parse existing heading dates for sorting (e.g. YYYY-MM-DD).",control:Le=>{{let At=F(()=>h(m).dateFormat??"");sn(Le,{get value(){return h(At)},placeholder:"YYYY-MM-DD",ariaLabel:"Date format",onChange:mr=>{j(c,!0),t().orderBy&&t(t().orderBy.dateFormat=mr,!0)}})}},$$slots:{control:!0}})};Y(z,Ee=>{h(m).by==="date"&&Ee(G)})}var ie=_(z,2);{var xe=Ee=>{Se(Ee,{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:Le=>{{let At=F(()=>h(m).unparseable??"bottom");ft(Le,{get value(){return h(At)},get options(){return l},onchange:mr=>{t().orderBy&&t(t().orderBy.unparseable=mr,!0)}})}},$$slots:{control:!0}})};Y(ie,Ee=>{(h(m).by==="date"||h(m).by==="numeric"||h(m).by==="semver")&&Ee(xe)})}var ue=_(ie,2);{var be=Ee=>{var He=R9();M(Ee,He)};Y(ue,Ee=>{h(m).by==="insertion"&&Ee(be)})}var Ke=_(ue,2);{var Oe=Ee=>{var He=N9();M(Ee,He)};Y(Ke,Ee=>{h(v)&&Ee(Oe)})}M(O,H)};Y(ee,O=>{h(d)&&t().orderBy&&O(me)})}M(r,T),fe()}Xe();var jD=L("<!> <!>",1);function GD(r,e){pe(e,!0);let t=ne(e,"insertBefore",15);t().createIfNotFound===void 0&&t(t().createIfNotFound=!1,!0),t().createIfNotFoundLocation||t(t().createIfNotFoundLocation=no,!0);let n=[l=>new Sn(e.app,l,e.plugin,"lineTarget")],i=[{value:no,label:"Top"},{value:nd,label:"Bottom"},{value:id,label:"Cursor"}];var o=jD(),s=Te(o);Ti(s,{name:"Insert before",desc:"Insert capture before specified text. Accepts format syntax.",children:(c,u=Ct)=>{var d=jD(),p=Te(d);sn(p,{get id(){return u()},placeholder:"Insert before",required:!0,requiredMessage:"Insert before text is required",get makeSuggesters(){return n},get value(){return t().before},set value(m){t(t().before=m,!0)}});var f=_(p,2);fo(f,{get value(){return t().before},formatterKind:"lineTarget",get app(){return e.app},get plugin(){return e.plugin}}),M(c,d)},$$slots:{default:!0}});var a=_(s,2);Se(a,{name:"Create line if not found",desc:"Creates the 'insert before' line if it is not found.",control:c=>{var u=jD(),d=Te(u);St(d,{get checked(){return t().createIfNotFound},set checked(f){t(t().createIfNotFound=f,!0)}});var p=_(d,2);{let f=F(()=>t().createIfNotFoundLocation||no);ft(p,{get value(){return h(f)},get options(){return i},onchange:m=>t(t().createIfNotFoundLocation=m,!0)})}M(c,u)},$$slots:{control:!0}}),M(r,o),fe()}var B9=L("<!> <!> <!>",1);function YD(r,e){pe(e,!0);let t=ne(e,"config",15),n=[c=>new Sn(e.app,c,e.plugin)],i="";var o=B9(),s=Te(o);{let c=p=>{ft(p,{get value(){return t().property.kind},options:[{value:"named",label:"Named property"},{value:"prompt",label:"Choose when capturing"}],onchange:f=>{t().property.kind==="named"&&(i=t().property.format),t(t().property=f==="prompt"?{kind:"prompt"}:{kind:"named",format:i},!0)}})},u=(p,f=Ct)=>{var m=or(),g=Te(m);{var v=y=>{sn(y,{get id(){return f()},placeholder:"Property name",required:!0,requiredMessage:"Property name is required",get makeSuggesters(){return n},get value(){return t().property.format},set value(b){t(t().property.format=b,!0)}})};Y(g,y=>{t().property.kind==="named"&&y(v)})}M(p,m)},d=F(()=>t().property.kind==="named");Ti(s,{name:"Property",get bodyVisible(){return h(d)},control:c,children:u,$$slots:{control:!0,default:!0}})}var a=_(s,2);{let c=d=>{ft(d,{get value(){return t().action},options:[{value:"set",label:"Set value"},{value:"addToList",label:"Add to list"}],onchange:p=>{t(t().action=p==="addToList"?"addToList":"set",!0)}})},u=F(()=>t().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.");Se(a,{name:"Action",get desc(){return h(u)},control:c,$$slots:{control:!0}})}var l=_(a,2);Se(l,{name:"Create property if missing",control:u=>{St(u,{get checked(){return t().createIfMissing},set checked(d){t(t().createIfMissing=d,!0)}})},$$slots:{control:!0}}),M(r,o),fe()}var q9=L(`<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>`),U9=L("<!> <!> <!> <!> <!>",1);function KD(r,e){pe(e,!0);let t=ne(e,"choice",15),n=F(()=>!!t().captureToActiveFile),i=F(()=>t().propertyCapture?"property":t().insertAfter?.enabled?"after":t().insertBefore?.enabled?"before":t().newLineCapture?.enabled?t().newLineCapture.direction==="above"?"newLineAbove":"newLineBelow":h(n)?t().activeFileWritePosition==="top"?"activeTop":t().activeFileWritePosition==="bottom"||t().prepend?"bottom":"top":t().prepend?"bottom":"top"),o=F(()=>[{value:"top",label:h(n)?"At cursor":"Top of file"},...h(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(b){if(b==="property"){t().propertyCapture??t(t().propertyCapture={property:{kind:"named",format:""},action:"set",createIfMissing:!0},!0);return}if(delete t().propertyCapture,t(t().prepend=!1,!0),t(t().insertAfter.enabled=!1,!0),t(t().insertAfter.promptHeading=!1,!0),t(t().insertAfter.inline=!1,!0),t(t().insertAfter.replaceExisting=!1,!0),t().insertBefore||t(t().insertBefore={enabled:!1,before:"",createIfNotFound:!1,createIfNotFoundLocation:"top"},!0),t(t().insertBefore.enabled=!1,!0),t().newLineCapture||t(t().newLineCapture={enabled:!1,direction:"below"},!0),t(t().newLineCapture.enabled=!1,!0),t(t().activeFileWritePosition="cursor",!0),b==="top"){h(n)||t(t().prepend=!1,!0);return}if(b==="activeTop"){h(n)&&t(t().activeFileWritePosition="top",!0);return}if(b==="bottom"){h(n)?t(t().activeFileWritePosition="bottom",!0):t(t().prepend=!0,!0);return}if(b==="newLineAbove"){t(t().newLineCapture.enabled=!0,!0),t(t().newLineCapture.direction="above",!0);return}if(b==="newLineBelow"){t(t().newLineCapture.enabled=!0,!0),t(t().newLineCapture.direction="below",!0);return}if(b==="before"){t(t().insertBefore.enabled=!0,!0);return}t(t().insertAfter.enabled=!0,!0)}let a=F(()=>{if(t().propertyCapture)return!1;let b=typeof t().captureTo=="string"&&gc(t().captureTo),x=e.app.workspace.getActiveViewOfType(QB.FileView)?.getViewType()==="canvas",w=h(n)&&!t().insertAfter.enabled&&!t().insertBefore?.enabled&&!t().newLineCapture?.enabled&&(t().activeFileWritePosition??"cursor")==="cursor"&&!t().prepend;return!(!(t().newLineCapture?.enabled||w)||(h(n)?!x:!b))});var l=U9(),c=Te(l);{let b=w=>{ft(w,{get value(){return h(i)},get options(){return h(o)},onchange:s})},x=F(()=>h(n)?"Where to place the capture in the current file.":"Where to place the capture in the target file.");Se(c,{name:"Write position",get desc(){return h(x)},control:b,$$slots:{control:!0}})}var u=_(c,2);{var d=b=>{YD(b,{get app(){return e.app},get plugin(){return e.plugin},get config(){return t().propertyCapture},set config(x){t(t().propertyCapture=x,!0)}})};Y(u,b=>{t().propertyCapture&&b(d)})}var p=_(u,2);{var f=b=>{WD(b,{get app(){return e.app},get plugin(){return e.plugin},get insertAfter(){return t().insertAfter},set insertAfter(x){t(t().insertAfter=x,!0)}})};Y(p,b=>{!t().propertyCapture&&t().insertAfter.enabled&&b(f)})}var m=_(p,2);{var g=b=>{GD(b,{get app(){return e.app},get plugin(){return e.plugin},get insertBefore(){return t().insertBefore},set insertBefore(x){t(t().insertBefore=x,!0)}})};Y(m,b=>{!t().propertyCapture&&t().insertBefore?.enabled&&b(g)})}var v=_(m,2);{var y=b=>{var x=q9();M(b,x)};Y(v,b=>{h(a)&&b(y)})}M(r,l),fe()}var H9=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"]),mE=Array.from(H9);bt();var z9=L('<div class="qa-choice-icon-setting-control svelte-p1gcdx"><span class="qa-choice-icon-setting-preview svelte-p1gcdx" aria-hidden="true"><!></span> <input type="text" class="qa-choice-icon-input svelte-p1gcdx" aria-label="Choice icon"/></div>'),W9={hash:"svelte-p1gcdx",code:".qa-choice-icon-setting-control.svelte-p1gcdx {display:flex;align-items:center;gap:8px;min-width:min(18rem, 100%);}.qa-choice-icon-setting-preview.svelte-p1gcdx {display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--text-muted);}.qa-choice-icon-input.svelte-p1gcdx {width:100%;min-width:0;}"};function Dy(r,e){pe(e,!0),We(r,W9);let t=ne(e,"icon",15),n=F(()=>hf(e.type)),i=F(()=>typeof t()=="string"?t():""),o=F(()=>h(i).trim()||h(n));function s(l){return new si(e.app,l,mE,50)}function a(l){let c=l.currentTarget.value.trim();t(c||void 0)}{let l=u=>{var d=z9(),p=B(d),f=B(p);Et(f,{get iconId(){return h(o)},size:18}),N(p);var m=_(p,2);Rt(m),Jt(m,(g,v)=>Sd?.(g,v),()=>s),N(d),re(()=>{bi(m,h(i)),ke(m,"placeholder",h(n))}),Ae("input",m,a),M(u,d)},c=F(()=>`Lucide/Obsidian icon id. Leave empty to use ${h(n)}.`);Se(r,{name:"Icon",get desc(){return h(c)},control:l,$$slots:{control:!0}})}fe()}nt(["input"]);var XB=L("<!> <!>",1),j9=L("<!> <!> <!>",1),G9=L("<!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!>",1);function QD(r,e){pe(e,!0);let t=ne(e,"choice",15),n=F(()=>e.plugin.getTemplateFiles().map(z=>z.path)),i=F(()=>t().propertyCapture?"propertyValue":"noteContent"),o=F(()=>{let z=h(i);return[G=>new Sn(e.app,G,e.plugin,z)]});function s(z){let G=z.trim();return G?cl(G)?{valid:!0,message:"Contains format syntax \u2014 resolved at run time."}:Vn(e.app,G)!==null||"Template not found":!0}let a=[{value:"",label:"Follow global setting"},{value:"enabled",label:"Use selection"},{value:"disabled",label:"Ignore selection"}],l=F(()=>typeof t().useSelectionAsCaptureValue=="boolean"?t().useSelectionAsCaptureValue?"enabled":"disabled":"");function c(z){if(z===""){t(t().useSelectionAsCaptureValue=void 0,!0);return}t(t().useSelectionAsCaptureValue=z==="enabled",!0)}function u(z){t().templater||t(t().templater={},!0),t(t().templater.afterCapture=z?"wholeFile":"none",!0)}var d=G9(),p=Te(d);kv(p,{get app(){return e.app},get name(){return t().name},set name(z){t(t().name=z,!0)}});var f=_(p,2);Se(f,{name:"Location",heading:!0});var m=_(f,2);HD(m,{get app(){return e.app},get plugin(){return e.plugin},get choice(){return t()},set choice(z){t(z)}});var g=_(m,2);{var v=z=>{var G=XB(),ie=Te(G);Se(ie,{name:"Create file if it doesn't exist",control:Ke=>{St(Ke,{get checked(){return t().createFileIfItDoesntExist.enabled},set checked(Oe){t(t().createFileIfItDoesntExist.enabled=Oe,!0)}})},$$slots:{control:!0}});var xe=_(ie,2);{var ue=be=>{Ti(be,{name:"Create file with a template",desc:"Path to the template QuickAdd applies to the new file.",get bodyVisible(){return t().createFileIfItDoesntExist.createWithTemplate},control:Ee=>{St(Ee,{get checked(){return t().createFileIfItDoesntExist.createWithTemplate},set checked(He){t(t().createFileIfItDoesntExist.createWithTemplate=He,!0)}})},children:(Ee,He=Ct)=>{sn(Ee,{get id(){return He()},get value(){return t().createFileIfItDoesntExist.template},placeholder:"Template path",get app(){return e.app},get suggestions(){return h(n)},maxSuggestions:50,validator:s,onChange:Le=>t(t().createFileIfItDoesntExist.template=Le.trim(),!0)})},$$slots:{control:!0,default:!0}})};Y(xe,be=>{t().createFileIfItDoesntExist.enabled&&be(ue)})}M(z,G)};Y(g,z=>{t().captureToActiveFile||z(v)})}var y=_(g,2);Se(y,{name:"Position",heading:!0});var b=_(y,2);KD(b,{get app(){return e.app},get plugin(){return e.plugin},get choice(){return t()},set choice(z){t(z)}});var x=_(b,2);Se(x,{name:"Linking",heading:!0});var w=_(x,2);fy(w,{fileLabel:"captured",get app(){return e.app},get appendLink(){return t().appendLink},set appendLink(z){t(t().appendLink=z,!0)}});var T=_(w,2);Se(T,{name:"Copy link to clipboard",desc:"Copy a link to the captured file after the Capture choice runs.",control:G=>{{let ie=F(()=>t().copyLinkToClipboard??!1);St(G,{get checked(){return h(ie)},onchange:xe=>t(t().copyLinkToClipboard=xe,!0)})}},$$slots:{control:!0}});var C=_(T,2);Se(C,{name:"Content",heading:!0});var S=_(C,2);{var A=z=>{Se(z,{name:"Task",desc:"Formats the value as a task.",control:ie=>{St(ie,{get checked(){return t().task},set checked(xe){t(t().task=xe,!0)}})},$$slots:{control:!0}})};Y(S,z=>{t().propertyCapture||z(A)})}var D=_(S,2);Ti(D,{name:"Capture format",desc:"Set the format of the capture. When off, QuickAdd captures {{VALUE}} on its own - what you type at the prompt, or the current selection.",get bodyVisible(){return t().format.enabled},control:ie=>{St(ie,{get checked(){return t().format.enabled},set checked(xe){t(t().format.enabled=xe,!0)}})},children:(ie,xe=Ct)=>{var ue=j9(),be=Te(ue);bg(be,()=>h(i),Ee=>{{let He=F(()=>t().propertyCapture?.action==="addToList"?"One item per line":"Format");sn(Ee,{get id(){return xe()},inputKind:"textarea",get placeholder(){return h(He)},required:!0,requiredMessage:"Capture format is required when enabled",get makeSuggesters(){return h(o)},get value(){return t().format.format},set value(Le){t(t().format.format=Le,!0)}})}});var Ke=_(be,2);Vd(Ke,{get value(){return t().format.format}});var Oe=_(Ke,2);fo(Oe,{get value(){return t().format.format},get app(){return e.app},get plugin(){return e.plugin}}),M(ie,ue)},$$slots:{control:!0,default:!0}});var P=_(D,2);Se(P,{name:"Behavior",heading:!0});var U=_(P,2);{var K=z=>{var G=XB(),ie=Te(G);my(ie,{description:"Open the captured file.",get openFile(){return t().openFile},set openFile(be){t(t().openFile=be,!0)}});var xe=_(ie,2);{var ue=be=>{hy(be,{contextLabel:"captured",get fileOpening(){return t().fileOpening},set fileOpening(Ke){t(t().fileOpening=Ke,!0)}})};Y(xe,be=>{t().openFile&&be(ue)})}M(z,G)};Y(U,z=>{t().captureToActiveFile||z(K)})}var W=_(U,2);Se(W,{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=>{ft(G,{get value(){return h(l)},get options(){return a},onchange:c})},$$slots:{control:!0}});var ee=_(W,2);{var me=z=>{Se(z,{name:"Run Templater on entire destination file after capture",desc:"Advanced / legacy: this executes any <% %> anywhere in the destination file (including inside code blocks).",control:ie=>{{let xe=F(()=>t().templater?.afterCapture==="wholeFile");St(ie,{get checked(){return h(xe)},onchange:u})}},$$slots:{control:!0}})};Y(ee,z=>{t().propertyCapture||z(me)})}var O=_(ee,2);xy(O,{get dateOrigin(){return t().dateOrigin},set dateOrigin(z){t(t().dateOrigin=z,!0)}});var H=_(O,2);gy(H,{get onePageInput(){return t().onePageInput},set onePageInput(z){t(t().onePageInput=z,!0)}});var ce=_(H,2);Sy(ce,{get name(){return t().name},get dateOrigin(){return t().dateOrigin},get command(){return t().command},set command(z){t(t().command=z,!0)},get pickDayCommand(){return t().pickDayCommand},set pickDayCommand(z){t(t().pickDayCommand=z,!0)}});var te=_(ce,2);Dy(te,{get type(){return t().type},get app(){return e.app},get icon(){return t().icon},set icon(z){t(t().icon=z,!0)}}),M(r,d),fe()}function Xc(r){return Pu(r)}function hE(r){return ut({...r,choice:Xc(r.choice)})}var ZB=hE;var JB=require("obsidian");xt();var Y9=L('<pre class="qaMountFailedDetail svelte-bhgeqn"> </pre>'),K9=L(`<div class="qaMountFailed svelte-bhgeqn"><div class="qaMountFailedHead svelte-bhgeqn"><!> <span class="qaMountFailedTitle svelte-bhgeqn"> </span></div> <p class="qaMountFailedBody svelte-bhgeqn">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>`),Q9={hash:"svelte-bhgeqn",code:".qaMountFailed.svelte-bhgeqn {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-bhgeqn {display:flex;align-items:center;gap:8px;color:var(--text-warning, var(--text-normal));}.qaMountFailedTitle.svelte-bhgeqn {font-weight:var(--font-semibold);color:var(--text-normal);}.qaMountFailedBody.svelte-bhgeqn {margin:8px 0 0;color:var(--text-muted);font-size:var(--font-ui-small, 13px);max-width:68ch;}.qaMountFailedDetail.svelte-bhgeqn {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 XD(r,e){We(r,Q9);let t=ne(e,"detail",3,"");var n=K9(),i=B(n),o=B(i);Et(o,{iconId:"alert-triangle",size:16});var s=_(o,2),a=le(s);N(i);var l=_(i,4);{var c=u=>{var d=Y9(),p=le(d,!0);re(()=>ae(p,t())),M(u,d)};Y(l,u=>{t()&&u(c)})}N(n),re(()=>ae(a,`QuickAdd couldn't display ${e.what??""}`)),M(r,n)}var X9="this part of QuickAdd";function Li(r,e,t,n={}){let i=new Set(r.childNodes),o;try{o=Zu(e,{target:r,props:t})}catch(a){return Z9(r,i,nl(a),n)}let s=!1;return{ok:!0,destroy(){s||(s=!0,jp(o))}}}function Z9(r,e,t,n){let i=n.what??X9;for(let l of Array.from(r.childNodes))e.has(l)||l.remove();Ze(t,`Couldn't display ${i}`);let o=r.createDiv({cls:"qa-mount-failed-host"}),s=null;try{s=Zu(n.fallbackComponent??XD,{target:o,props:{what:i,detail:t.message}})}catch{o.textContent=`QuickAdd couldn't display ${i}.`}let a=!1;return{ok:!1,destroy(){a||(a=!0,s&&jp(s),o.remove())}}}function gE(r,e){if(r.containerEl.addClass("qa-choice-builder"),r.modalEl.querySelector(".qa-builder-footer"))return;let t=r.modalEl.createDiv({cls:"qa-builder-footer"});t.createSpan({cls:"qa-builder-footer-note",text:`Changes to this ${e} are saved automatically`}),t.createEl("button",{type:"button",cls:"mod-cta",text:"Done"}).addEventListener("click",()=>r.close())}var Jf=class extends JB.Modal{constructor(t){super(t);this.svelteElements=[];this.waitForClose=new Promise(n=>{this.resolvePromise=n}),this.containerEl.addClass("quickAddModal"),gE(this,"choice"),this.open()}mountForm(t,n,i){let o=Li(this.contentEl,t,n,{what:i});return this.svelteElements.push(o),o.ok?n:void 0}destroySvelteElements(){this.svelteElements.forEach(t=>t.destroy()),this.svelteElements=[]}getResultChoice(){return this.choice}onClose(){super.onClose(),this.destroySvelteElements(),this.resolvePromise(Xc(this.getResultChoice()))}};var em=class extends Jf{constructor(t,n,i){super(t);this.plugin=i;this.choice=n,this.normalizeChoice(),this.display()}normalizeChoice(){this.choice.insertBefore||(this.choice.insertBefore={enabled:!1,before:"",createIfNotFound:!1,createIfNotFoundLocation:no}),this.choice.activeFileWritePosition||(this.choice.activeFileWritePosition="cursor"),this.choice.createFileIfItDoesntExist||(this.choice.createFileIfItDoesntExist={enabled:!1,createWithTemplate:!1,template:""}),!this.choice.captureToActiveFile&&!gc(this.choice.captureTo)&&(this.choice.captureToCanvasNodeId=""),this.choice.openFile&&(this.choice.fileOpening=Cn(this.choice.fileOpening))}display(){this.containerEl.addClass("captureChoiceBuilder"),this.formProps=this.mountForm(QD,ZB({choice:this.choice,app:this.app,plugin:this.plugin}),"this capture choice's settings")}getResultChoice(){return this.formProps?.choice??this.choice}};Dl();Ie();ht();Kg();ks();var bE=class extends xr{constructor(t,n,i,o){super(t,n);this.app=t;this.inputEl=n;this.suggestItems=i;this.currentItems=o}updateCurrentItems(t){this.currentItems=t}getSuggestions(t){return this.suggestItems.filter(n=>n.contains(t))}selectSuggestion(t){this.inputEl.value=t,this.inputEl.trigger("input"),this.close()}renderSuggestion(t,n){t&&n.setText(t)}};var jq=require("obsidian");function dq(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Ry(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?dq(Object(t),!0).forEach(function(n){am(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):dq(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function rm(r){"@babel/helpers - typeof";return rm=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},rm(r)}function am(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function iZ(r,e){if(r==null)return{};var t={},n=Object.keys(r),i,o;for(o=0;o<n.length;o++)i=n[o],!(e.indexOf(i)>=0)&&(t[i]=r[i]);return t}function oZ(r,e){if(r==null)return{};var t=iZ(r,e),n,i;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(r);for(i=0;i<o.length;i++)n=o[i],!(e.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(r,n)&&(t[n]=r[n])}return t}function sZ(r,e){return lZ(r)||uZ(r,e)||uF(r,e)||pZ()}function Xo(r){return aZ(r)||cZ(r)||uF(r)||dZ()}function aZ(r){if(Array.isArray(r))return tF(r)}function lZ(r){if(Array.isArray(r))return r}function cZ(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function uZ(r,e){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var n=[],i=!0,o=!1,s,a;try{for(t=t.call(r);!(i=(s=t.next()).done)&&(n.push(s.value),!(e&&n.length===e));i=!0);}catch(l){o=!0,a=l}finally{try{!i&&t.return!=null&&t.return()}finally{if(o)throw a}}return n}}function uF(r,e){if(r){if(typeof r=="string")return tF(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return tF(r,e)}}function tF(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function dZ(){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 pZ(){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 Ud(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=uF(r))||e&&r&&typeof r.length=="number"){t&&(r=t);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(){t=t.call(r)},n:function(){var l=t.next();return o=l.done,l},e:function(l){s=!0,a=l},f:function(){try{!o&&t.return!=null&&t.return()}finally{if(s)throw a}}}}var fZ="finalize",mZ="consider";function lm(r,e,t){r.dispatchEvent(new CustomEvent(fZ,{detail:{items:e,info:t}}))}function ru(r,e,t){r.dispatchEvent(new CustomEvent(mZ,{detail:{items:e,info:t}}))}var DE="draggedEntered",Ly="draggedLeft",FE="draggedOverIndex",dF="draggedLeftDocument",EE={LEFT_FOR_ANOTHER:"leftForAnother",OUTSIDE_OF_ANY:"outsideOfAny"};function hZ(r,e,t){r.dispatchEvent(new CustomEvent(DE,{detail:{indexObj:e,draggedEl:t}}))}function gZ(r,e,t){r.dispatchEvent(new CustomEvent(Ly,{detail:{draggedEl:e,type:EE.LEFT_FOR_ANOTHER,theOtherDz:t}}))}function vZ(r,e){r.dispatchEvent(new CustomEvent(Ly,{detail:{draggedEl:e,type:EE.OUTSIDE_OF_ANY}}))}function yZ(r,e,t){r.dispatchEvent(new CustomEvent(FE,{detail:{indexObj:e,draggedEl:t}}))}function bZ(r){window.dispatchEvent(new CustomEvent(dF,{detail:{draggedEl:r}}))}var jn={DRAG_STARTED:"dragStarted",DRAGGED_ENTERED:DE,DRAGGED_ENTERED_ANOTHER:"dragEnteredAnother",DRAGGED_OVER_INDEX:FE,DRAGGED_LEFT:Ly,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"},wZ={space:[" "],enter:["Enter"],space_or_enter:[" ","Enter"]},Eq="space_or_enter",CZ={space:"space-bar",enter:"enter",space_or_enter:"space-bar or enter"},dm="isDndShadowItem",PE="data-is-dnd-shadow-item-internal",xZ="data-is-dnd-shadow-item-hint",Vy="id:dnd-shadow-placeholder-0000",EZ="dnd-action-dragged-el",gr="id",rF=0;function Tq(){rF++}function kq(){if(rF===0)throw new Error("Bug! trying to decrement when there are no dropzones");rF--}var pF=typeof window>"u",st=function(){};function nF(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,t,n=e?_Z(r):r.getBoundingClientRect(),i=getComputedStyle(r),o=i.transform;if(o){var s,a,l,c;if(o.startsWith("matrix3d("))t=o.slice(9,-1).split(/, /),s=+t[0],a=+t[5],l=+t[12],c=+t[13];else if(o.startsWith("matrix("))t=o.slice(7,-1).split(/, /),s=+t[0],a=+t[3],l=+t[4],c=+t[5];else return n;var u=i.transformOrigin,d=n.left-l-(1-s)*parseFloat(u),p=n.top-c-(1-a)*parseFloat(u.slice(u.indexOf(" ")+1)),f=s?n.width/s:r.offsetWidth,m=a?n.height/a:r.offsetHeight;return{x:d,y:p,width:f,height:m,top:p,right:d+f,bottom:p+m,left:d}}else return n}function iF(r){var e=nF(r);return{top:e.top+window.scrollY,bottom:e.bottom+window.scrollY,left:e.left+window.scrollX,right:e.right+window.scrollX}}function TZ(r){var e=r.getBoundingClientRect();return{top:e.top+window.scrollY,bottom:e.bottom+window.scrollY,left:e.left+window.scrollX,right:e.right+window.scrollX}}function Sq(r){return{x:(r.left+r.right)/2,y:(r.top+r.bottom)/2}}function kZ(r,e){return Math.sqrt(Math.pow(r.x-e.x,2)+Math.pow(r.y-e.y,2))}function $y(r,e){return r.y<=e.bottom&&r.y>=e.top&&r.x>=e.left&&r.x<=e.right}function _q(r){return Sq(TZ(r))}function pq(r,e){var t=_q(e);return kZ(r,t)}function SZ(r){var e=r.ownerDocument,t=e.defaultView||window,n=r.getBoundingClientRect(),i=n.top+t.scrollY,o=n.left+t.scrollX;return n.right+t.scrollX<0||o>e.documentElement.scrollWidth||n.bottom+t.scrollY<0||i>e.documentElement.scrollHeight}function _Z(r){for(var e=r.getBoundingClientRect(),t={top:e.top,bottom:e.bottom,left:e.left,right:e.right},n=!1,i=!1,o=r.parentElement;o&&o!==document.body;){var s=window.getComputedStyle(o),a=s.overflowY,l=s.overflowX,c=a==="scroll"||a==="auto",u=l==="scroll"||l==="auto";if(c||u){var d=o.getBoundingClientRect();if(c){var p=Math.max(t.top,d.top),f=Math.min(t.bottom,d.bottom);(p!==t.top||f!==t.bottom)&&(n=!0),t.top=p,t.bottom=f}if(u){var m=Math.max(t.left,d.left),g=Math.min(t.right,d.right);(m!==t.left||g!==t.right)&&(i=!0),t.left=m,t.right=g}}o=o.parentElement}return n||i?{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)}:{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)}}var im;function fF(){st(function(){return"resetting indexes cache"}),im=new Map}fF();function AZ(r){var e=Array.from(r.children).findIndex(function(t){return t.getAttribute(PE)});if(e>=0)return im.has(r)||im.set(r,new Map),im.get(r).set(e,iF(r.children[e])),e}function IZ(r,e){var t=iF(e);if(!$y(r,t))return null;var n=e.children;if(n.length===0)return{index:0,isProximityBased:!0};for(var i=AZ(e),o=0;o<n.length;o++){var s=iF(n[o]);if($y(r,s)){var a=im.has(e)&&im.get(e).get(o);return a&&!$y(r,a)?{index:i,isProximityBased:!1}:{index:o,isProximityBased:!1}}}for(var l=Number.MAX_VALUE,c=void 0,u=0;u<n.length;u++){var d=pq(r,n[u]);d<l&&(l=d,c=u)}if(n.length>0){var p=n.length,f=n[p-1],m=f.cloneNode(!1);m.style.visibility="hidden",m.style.pointerEvents="none",e.appendChild(m);var g=pq(r,m);g<l&&(c=p),e.removeChild(m)}return{index:c,isProximityBased:!0}}function $s(r){return JSON.stringify(r,null,2)}function TE(r){if(!r)throw new Error("cannot get depth of a falsy node");return Aq(r,0)}function Aq(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return r.parentElement?Aq(r.parentElement,e+1):e-1}function DZ(r,e){if(Object.keys(r).length!==Object.keys(e).length)return!1;for(var t in r)if(!{}.hasOwnProperty.call(e,t)||e[t]!==r[t])return!1;return!0}function FZ(r,e){if(r.length!==e.length)return!1;for(var t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}var PZ=200,fq=10,oF;function MZ(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:PZ,n=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0,o,s,a=!1,l,c=Array.from(e).sort(function(d,p){return TE(p)-TE(d)});function u(){var d=i(),p=n.multiScrollIfNeeded();if(!p&&l&&Math.abs(l.x-d.x)<fq&&Math.abs(l.y-d.y)<fq){oF=window.setTimeout(u,t);return}if(SZ(r)){st(function(){return"off document"}),bZ(r);return}l=d;var f=!1,m=Ud(c),g;try{for(m.s();!(g=m.n()).done;){var v=g.value;p&&fF();var y=IZ(d,v);if(y!==null){var b=y.index;f=!0,v!==o?(o&&gZ(o,r,v),hZ(v,y,r),o=v):b!==s&&(yZ(v,y,r),s=b);break}}}catch(x){m.e(x)}finally{m.f()}!f&&a&&o?(vZ(o,r),o=void 0,s=void 0,a=!1):a=!0,oF=window.setTimeout(u,t)}u()}function $Z(){st(function(){return"unobserving"}),clearTimeout(oF),fF()}var Fy=30;function OZ(){var r;function e(){r={directionObj:void 0,stepPx:0}}e();function t(o){var s=r,a=s.directionObj,l=s.stepPx;if(a){o.scrollBy(a.x*l,a.y*l);var c=o.ownerDocument.defaultView||window;c.requestAnimationFrame(function(){return t(o)})}}function n(o){return Fy-o}function i(o,s){if(!s)return!1;var a=RZ(o,s),l=!!r.directionObj;if(a===null)return l&&e(),!1;var c=!1,u=!1;return s.scrollHeight>s.clientHeight&&(a.bottom<Fy?(c=!0,r.directionObj={x:0,y:1},r.stepPx=n(a.bottom)):a.top<Fy&&(c=!0,r.directionObj={x:0,y:-1},r.stepPx=n(a.top)),!l&&c)||s.scrollWidth>s.clientWidth&&(a.right<Fy?(u=!0,r.directionObj={x:1,y:0},r.stepPx=n(a.right)):a.left<Fy&&(u=!0,r.directionObj={x:-1,y:0},r.stepPx=n(a.left)),!l&&u)?(t(s),!0):(e(),!1)}return{scrollIfNeeded:i,resetScrolling:e}}function RZ(r,e){var t=e===document.scrollingElement?{top:0,bottom:window.innerHeight,left:0,right:window.innerWidth}:e.getBoundingClientRect();return $y(r,t)?{top:r.y-t.top,bottom:t.bottom-r.y,left:r.x-t.left,right:t.right-r.x}:null}function NZ(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1?arguments[1]:void 0;st(function(){return"creating multi-scroller"});var t=VZ(r),n=Array.from(t).sort(function(l,c){return TE(c)-TE(l)}),i=OZ(),o=i.scrollIfNeeded,s=i.resetScrolling;function a(){var l=e();if(!l||!n)return!1;for(var c=n.filter(function(p){return $y(l,p.getBoundingClientRect())||p===document.scrollingElement}),u=0;u<c.length;u++){var d=o(l,c[u]);if(d)return!0}return!1}return{multiScrollIfNeeded:t.size>0?a:function(){return!1},destroy:function(){return s()}}}function LZ(r){if(!r)return[];for(var e=[],t=r;t;){var n=window.getComputedStyle(t),i=n.overflow;i.split(" ").some(function(o){return o.includes("auto")||o.includes("scroll")})&&e.push(t),t=t.parentElement}return e}function VZ(r){var e=new Set,t=Ud(r),n;try{for(t.s();!(n=t.n()).done;){var i=n.value;LZ(i).forEach(function(o){return e.add(o)})}}catch(o){t.e(o)}finally{t.f()}return(document.scrollingElement.scrollHeight>document.scrollingElement.clientHeight||document.scrollingElement.scrollWidth>document.scrollingElement.clientHeight)&&e.add(document.scrollingElement),e}function BZ(r){var e=r.cloneNode(!0),t=[],n=r.tagName==="SELECT",i=n?[r]:Xo(r.querySelectorAll("select")),o=Ud(i),s;try{for(o.s();!(s=o.n()).done;){var a=s.value;t.push(a.value)}}catch(x){o.e(x)}finally{o.f()}if(i.length>0)for(var l=n?[e]:Xo(e.querySelectorAll("select")),c=0;c<l.length;c++){var u=l[c],d=t[c],p=u.querySelector('option[value="'.concat(d,'"'));p&&p.setAttribute("selected",!0)}var f=r.tagName==="CANVAS",m=f?[r]:Xo(r.querySelectorAll("canvas"));if(m.length>0)for(var g=f?[e]:Xo(e.querySelectorAll("canvas")),v=0;v<g.length;v++){var y=m[v],b=g[v];b.width=y.width,b.height=y.height,y.width>0&&y.height>0&&b.getContext("2d").drawImage(y,0,0)}return e}var Ny=Object.freeze({USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT:"USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT"}),qZ=am({},Ny.USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT,!1);function Iq(r){if(!Ny[r])throw new Error("Can't get non existing feature flag ".concat(r,"! Supported flags: ").concat(Object.keys(Ny)));return qZ[r]}var UZ=.2;function Bd(r){return"".concat(r," ").concat(UZ,"s ease")}function Dq(r){var e=r.style.transitionProperty.split(",").map(function(t){return t.trim()});e.includes("all")||(e.includes("width")||(r.style.transition+=", ".concat(Bd("width"))),e.includes("height")||(r.style.transition+=", ".concat(Bd("height"))))}function HZ(r,e){var t=r.getBoundingClientRect(),n=BZ(r);Fq(r,n),n.id=EZ,n.style.position="fixed";var i=t.top,o=t.left;if(n.style.top="".concat(i,"px"),n.style.left="".concat(o,"px"),e){var s=Sq(t);i-=s.y-e.y,o-=s.x-e.x,window.setTimeout(function(){n.style.top="".concat(i,"px"),n.style.left="".concat(o,"px")},0)}return n.style.margin="0",n.style.boxSizing="border-box",n.style.height="".concat(t.height,"px"),n.style.width="".concat(t.width,"px"),n.style.transition="".concat(Bd("top"),", ").concat(Bd("left"),", ").concat(Bd("background-color"),", ").concat(Bd("opacity"),", ").concat(Bd("color")," "),window.setTimeout(function(){return Dq(n)},0),n.style.zIndex="9999",n.style.cursor="grabbing",n}function zZ(r){r.style.cursor="grab"}function WZ(r,e,t,n){Dq(r),Fq(e,r);var i=e.getBoundingClientRect(),o=r.getBoundingClientRect(),s=window.getComputedStyle(r),a=parseFloat(s.left),l=parseFloat(s.top),c=i.width-o.width,u=i.height-o.height;if(c||u){var d={left:o.width?(t-o.left)/o.width:0,top:o.height?(n-o.top)/o.height:0};Iq(Ny.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-d.left*c,"px"),r.style.top="".concat(l-d.top*u,"px")}}function Fq(r,e){var t=window.getComputedStyle(r);Array.from(t).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"||Iq(Ny.USE_COMPUTED_STYLE_INSTEAD_OF_BOUNDING_RECT)&&(n==="width"||n==="height")}).forEach(function(n){return e.style.setProperty(n,t.getPropertyValue(n),t.getPropertyPriority(n))})}function jZ(r,e){r.draggable=!1,r.ondragstart=function(){return!1},e?(r.style.userSelect="",r.style.WebkitUserSelect="",r.style.cursor=""):(r.style.userSelect="none",r.style.WebkitUserSelect="none",r.style.cursor="grab")}function Pq(r){r.style.display="none",r.style.position="fixed",r.style.zIndex="-5"}function GZ(r){r.style.visibility="hidden",r.setAttribute(PE,"true")}function YZ(r){r.style.visibility="",r.removeAttribute(PE)}function xE(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){},t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:function(){return[]};r.forEach(function(n){var i=e(n);Object.keys(i).forEach(function(o){n.style[o]=i[o]}),t(n).forEach(function(o){return n.classList.add(o)})})}function kE(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){},t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:function(){return[]};r.forEach(function(n){var i=e(n);Object.keys(i).forEach(function(o){n.style[o]=""}),t(n).forEach(function(o){return n.classList.contains(o)&&n.classList.remove(o)})})}function KZ(r){var e=r.style.minHeight;r.style.minHeight=window.getComputedStyle(r).getPropertyValue("height");var t=r.style.minWidth;return r.style.minWidth=window.getComputedStyle(r).getPropertyValue("width"),function(){r.style.minHeight=e,r.style.minWidth=t}}var QZ="--any--",XZ=100,ZZ=20,wE=3,JZ=80,mq={outline:"rgba(255, 255, 102, 0.7) solid 2px"},hq="data-is-dnd-original-dragged-item",An,Br,Bi,mF,pr,ME,tu,Dn,ha,In,Fl=!1,SE=!1,hF,By=!1,nm=[],Oy,ga,My=!1,gF=!1,ma,Jc=new Set,Pl=new Map,Pr=new Map,Py=new WeakMap;function eJ(r,e){st(function(){return"registering drop-zone if absent"}),Pl.has(e)||Pl.set(e,new Set),Pl.get(e).has(r)||(Pl.get(e).add(r),Tq())}function gq(r,e){var t=Pl.get(e);!t||!t.delete(r)||(kq(),t.size===0&&Pl.delete(e))}function tJ(){st(function(){return"watching dragged element"});var r=Pl.get(mF);if(!(!r||r.size===0)){Jc.size>0&&sF(),Jc=new Set(r);var e=Ud(Jc),t;try{for(e.s();!(t=e.n()).done;){var n=t.value;n.addEventListener(DE,Mq),n.addEventListener(Ly,$q),n.addEventListener(FE,Oq)}}catch(a){e.e(a)}finally{e.f()}window.addEventListener(dF,cm);var i=Math.max.apply(Math,Xo(Array.from(Jc).map(function(a){return Pr.get(a).dropAnimationDurationMs}))),o=i===0?ZZ:Math.max(i,XZ);Oy=NZ(Jc,function(){return In});var s=gF?function(){return{x:In.x+window.scrollX,y:In.y+window.scrollY}}:function(){return _q(Br)};MZ(Br,Jc,o*1.07,Oy,s)}}function sF(){st(function(){return"unwatching dragged element"});var r=Ud(Jc),e;try{for(r.s();!(e=r.n()).done;){var t=e.value;t.removeEventListener(DE,Mq),t.removeEventListener(Ly,$q),t.removeEventListener(FE,Oq)}}catch(n){r.e(n)}finally{r.f()}Jc=new Set,window.removeEventListener(dF,cm),Oy&&(Oy.destroy(),Oy=void 0),$Z()}function $E(r){return r.findIndex(function(e){return!!e[dm]})}function rJ(r){var e;return Ry(Ry({},r),{},(e={},am(e,dm,!0),am(e,gr,Vy),e))}function Mq(r){st(function(){return["dragged entered",r.currentTarget,r.detail]});var e=Pr.get(r.currentTarget),t=e.items,n=e.dropFromOthersDisabled;if(n&&r.currentTarget!==pr){st(function(){return"ignoring dragged entered because drop is currently disabled"});return}if(By=!1,t=t.filter(function(a){return a[gr]!==tu[gr]&&a[gr]!==Vy}),st(function(){return"dragged entered items ".concat($s(t))}),pr!==r.currentTarget){var i=Pr.get(pr).items,o=i.filter(function(a){return!a[dm]});ru(pr,o,{trigger:jn.DRAGGED_ENTERED_ANOTHER,id:Bi[gr],source:Fn.POINTER})}var s=r.detail.indexObj.index;Dn=r.currentTarget,t.splice(s,0,tu),ru(r.currentTarget,t,{trigger:jn.DRAGGED_ENTERED,id:Bi[gr],source:Fn.POINTER})}function $q(r){if(Fl){st(function(){return["dragged left",r.currentTarget,r.detail]});var e=Pr.get(r.currentTarget),t=e.items,n=e.dropFromOthersDisabled;if(n&&r.currentTarget!==pr&&r.currentTarget!==Dn){st(function(){return"drop is currently disabled"});return}var i=Xo(t),o=$E(i);o!==-1&&i.splice(o,1);var s=Dn;Dn=void 0;var a=r.detail,l=a.type,c=a.theOtherDz;if(l===EE.OUTSIDE_OF_ANY||l===EE.LEFT_FOR_ANOTHER&&c!==pr&&Pr.get(c).dropFromOthersDisabled){st(function(){return"dragged left all, putting shadow element back in the origin dz"}),By=!0,Dn=pr;var u=s===pr?i:Xo(Pr.get(pr).items);u.splice(ME,0,tu),ru(pr,u,{trigger:jn.DRAGGED_LEFT_ALL,id:Bi[gr],source:Fn.POINTER})}ru(r.currentTarget,i,{trigger:jn.DRAGGED_LEFT,id:Bi[gr],source:Fn.POINTER})}}function Oq(r){st(function(){return["dragged is over index",r.currentTarget,r.detail]});var e=Pr.get(r.currentTarget),t=e.items,n=e.dropFromOthersDisabled;if(n&&r.currentTarget!==pr){st(function(){return"drop is currently disabled"});return}var i=Xo(t);By=!1;var o=r.detail.indexObj.index,s=$E(i);s!==-1&&i.splice(s,1),i.splice(o,0,tu),ru(r.currentTarget,i,{trigger:jn.DRAGGED_OVER_INDEX,id:Bi[gr],source:Fn.POINTER})}function _E(r){r.preventDefault();var e=r.touches?r.touches[0]:r;In={x:e.clientX,y:e.clientY},Br.style.transform="translate3d(".concat(In.x-ha.x,"px, ").concat(In.y-ha.y,"px, 0)")}function cm(){st(function(){return"dropped"}),SE=!0,window.removeEventListener("mousemove",_E),window.removeEventListener("touchmove",_E),window.removeEventListener("mouseup",cm),window.removeEventListener("touchend",cm),sF(),zZ(Br),Dn||(st(function(){return"element was dropped right after it left origin but before entering somewhere else"}),Dn=pr),st(function(){return["dropped in dz",Dn]});var r=Pr.get(Dn),e=r.items,t=r.type;kE(Pl.get(t),function(o){return Pr.get(o).dropTargetStyle},function(o){return Pr.get(o).dropTargetClasses});var n=$E(e);n===-1&&Dn===pr&&(n=ME),e=e.map(function(o){return o[dm]?Bi:o});function i(){sF(),hF(),lm(Dn,e,{trigger:By?jn.DROPPED_OUTSIDE_OF_ANY:jn.DROPPED_INTO_ZONE,id:Bi[gr],source:Fn.POINTER}),Dn!==pr&&lm(pr,Pr.get(pr).items,{trigger:jn.DROPPED_INTO_ANOTHER,id:Bi[gr],source:Fn.POINTER});var o=Array.from(Dn.children).find(function(s){return s.getAttribute(PE)});o&&YZ(o),oJ()}Pr.get(Dn).dropAnimationDisabled?i():nJ(n,i)}function nJ(r,e){var t=r>-1?nF(Dn.children[r],!1):nF(Dn,!1),n={x:t.left-parseFloat(Br.style.left),y:t.top-parseFloat(Br.style.top)},i=Pr.get(Dn),o=i.dropAnimationDurationMs,s="transform ".concat(o,"ms ease");Br.style.transition=Br.style.transition?Br.style.transition+","+s:s,Br.style.transform="translate3d(".concat(n.x,"px, ").concat(n.y,"px, 0)"),window.setTimeout(e,o)}function iJ(r,e){var t={dz:r,destroy:e};nm.push(t),window.requestAnimationFrame(function(){nm.includes(t)&&(Pq(r),document.body.appendChild(r))})}function oJ(){Br&&Br.remove&&Br.remove(),An&&An.remove&&An.remove(),Br=void 0,An=void 0,Bi=void 0,mF=void 0,pr=void 0,ME=void 0,tu=void 0,Dn=void 0,ha=void 0,In=void 0,Fl=!1,SE=!1,hF=void 0,By=!1,ga&&clearTimeout(ga),ga=void 0,My=!1,gF=!1,ma=void 0,nm.length&&(st(function(){return["will destroy zones that were removed during drag",nm]}),nm.forEach(function(r){var e=r.dz,t=r.destroy;t(),e.remove()}),nm=[])}function sJ(r,e){var t=!1,n=!1,i={items:void 0,type:void 0,flipDurationMs:0,dragDisabled:!1,morphDisabled:!1,dropFromOthersDisabled:!1,dropTargetStyle:mq,dropTargetClasses:[],transformDraggedElement:function(){},centreDraggedOnCursor:!1,useCursorForDetection:!1,dropAnimationDisabled:!1,delayTouchStartMs:0};st(function(){return["dndzone good to go options: ".concat($s(e),", config: ").concat($s(i)),{node:r}]});var o=new Map;function s(){window.addEventListener("mousemove",u,{passive:!1}),window.addEventListener("touchmove",u,{passive:!1,capture:!1}),window.addEventListener("mouseup",c,{passive:!1}),window.addEventListener("touchend",c,{passive:!1})}function a(){window.removeEventListener("mousemove",u),window.removeEventListener("touchmove",u),window.removeEventListener("mouseup",c),window.removeEventListener("touchend",c),ga&&(clearTimeout(ga),ga=void 0,My=!1)}function l(){ma===r&&(a(),ma=void 0,An=void 0,ha=void 0,In=void 0)}function c(m){if(ma===r&&(l(),m.type==="touchend")){var g=new Event("click",{bubbles:!0,cancelable:!0});m.target.dispatchEvent(g)}}function u(m){if(!(n||ma!==r)){var g=!!m.touches,v=g?m.touches[0]:m;if(g&&i.delayTouchStartMs>0&&!My){In={x:v.clientX,y:v.clientY},(Math.abs(In.x-ha.x)>=wE||Math.abs(In.y-ha.y)>=wE)&&(ga&&(clearTimeout(ga),ga=void 0),c(m));return}m.preventDefault(),In={x:v.clientX,y:v.clientY},(Math.abs(In.x-ha.x)>=wE||Math.abs(In.y-ha.y)>=wE)&&p()}}function d(m){if(m.target!==m.currentTarget&&(m.target.value!==void 0||m.target.isContentEditable)){st(function(){return"won't initiate drag on a nested input element"});return}if(m.button){st(function(){return"ignoring none left click button: ".concat(m.button)});return}if(n||Fl||ma){st(function(){return"cannot start a new drag before finalizing the current drag or pending gesture"});return}var g=!!m.touches,v=g&&i.delayTouchStartMs>0;v||m.preventDefault(),m.stopPropagation(),ma=r;var y=g?m.touches[0]:m;if(ha={x:y.clientX,y:y.clientY},In=Ry({},ha),An=m.currentTarget,v){var b=An;My=!1,ga=window.setTimeout(function(){n||ma!==r||An!==b||(My=!0,p())},i.delayTouchStartMs)}s()}function p(){var m;if(n||ma!==r||Fl||!((m=An)!==null&&m!==void 0&&m.parentElement)){l();return}a(),ma=void 0,st(function(){return["drag start config: ".concat($s(i)),An]}),Fl=!0;var g=o.get(An);ME=g,pr=An.parentElement;var v=pr.closest("dialog")||pr.closest("[popover]")||pr.getRootNode(),y=v.body||v,b=i.items,x=i.type,w=i.centreDraggedOnCursor,T=i.useCursorForDetection,C=Xo(b);Bi=C[g],mF=x,tu=rJ(Bi),gF=T,Br=HZ(An,w&&In),y.appendChild(Br);var S=An.ownerDocument.defaultView||window;function A(){!Br||SE||(An.parentElement?S.requestAnimationFrame(A):(An.setAttribute(hq,!0),y.appendChild(An),tJ(),Pq(An),tu[gr]=Bi[gr],Br.focus()))}S.requestAnimationFrame(A),xE(Array.from(Pl.get(i.type)).filter(function(D){return D===pr||!Pr.get(D).dropFromOthersDisabled}),function(D){return Pr.get(D).dropTargetStyle},function(D){return Pr.get(D).dropTargetClasses}),C.splice(g,1,tu),hF=KZ(pr),ru(pr,C,{trigger:jn.DRAG_STARTED,id:Bi[gr],source:Fn.POINTER}),window.addEventListener("mousemove",_E,{passive:!1}),window.addEventListener("touchmove",_E,{passive:!1,capture:!1}),window.addEventListener("mouseup",cm,{passive:!1}),window.addEventListener("touchend",cm,{passive:!1})}function f(m){var g=m.items,v=g===void 0?void 0:g,y=m.flipDurationMs,b=y===void 0?0:y,x=m.type,w=x===void 0?QZ:x,T=m.dragDisabled,C=T===void 0?!1:T,S=m.morphDisabled,A=S===void 0?!1:S,D=m.dropFromOthersDisabled,P=D===void 0?!1:D,U=m.dropTargetStyle,K=U===void 0?mq:U,W=m.dropTargetClasses,ee=W===void 0?[]:W,me=m.transformDraggedElement,O=me===void 0?function(){}:me,H=m.centreDraggedOnCursor,ce=H===void 0?!1:H,te=m.useCursorForDetection,z=te===void 0?!1:te,G=m.dropAnimationDisabled,ie=G===void 0?!1:G,xe=m.delayTouchStart,ue=xe===void 0?!1:xe;i.dropAnimationDurationMs=b;var be=0;ue===!0?be=JZ:typeof ue=="number"&&isFinite(ue)&&ue>=0&&(be=ue),i.delayTouchStartMs=be,i.type&&w!==i.type&&gq(r,i.type),i.type=w,i.items=Xo(v),i.dragDisabled=C,i.morphDisabled=A,i.transformDraggedElement=O,i.centreDraggedOnCursor=ce,i.useCursorForDetection=z,i.dropAnimationDisabled=ie,t&&Fl&&!SE&&(!DZ(K,i.dropTargetStyle)||!FZ(ee,i.dropTargetClasses))&&(kE([r],function(){return i.dropTargetStyle},function(){return ee}),xE([r],function(){return K},function(){return ee})),i.dropTargetStyle=K,i.dropTargetClasses=Xo(ee);function Ke(Le,At){return Pr.get(Le)?Pr.get(Le)[At]:i[At]}t&&Fl&&i.dropFromOthersDisabled!==P&&(P?kE([r],function(Le){return Ke(Le,"dropTargetStyle")},function(Le){return Ke(Le,"dropTargetClasses")}):xE([r],function(Le){return Ke(Le,"dropTargetStyle")},function(Le){return Ke(Le,"dropTargetClasses")})),i.dropFromOthersDisabled=P,Pr.set(r,i),eJ(r,w);for(var Oe=Fl?$E(i.items):-1,Ee=0;Ee<r.children.length;Ee++){var He=r.children[Ee];if(jZ(He,C),Ee===Oe){A||WZ(Br,He,In.x,In.y),i.transformDraggedElement(Br,Bi,Ee),GZ(He);continue}He.removeEventListener("mousedown",Py.get(He)),He.removeEventListener("touchstart",Py.get(He)),C||(He.addEventListener("mousedown",d),He.addEventListener("touchstart",d),Py.set(He,d)),o.set(He,Ee),t||(t=!0)}}return f(e),{update:function(g){st(function(){return"pointer dndzone will update newOptions: ".concat($s(g))}),f(g)},destroy:function(){if(n)return;n=!0,l();var g=Ud(r.children),v;try{for(g.s();!(v=g.n()).done;){var y=v.value;y.removeEventListener("mousedown",Py.get(y)),y.removeEventListener("touchstart",Py.get(y))}}catch(x){g.e(x)}finally{g.f()}function b(){st(function(){return"pointer dndzone will destroy"});var x=Pr.get(r);x&&(gq(r,x.type),Pr.delete(r))}Fl&&!r.closest("[".concat(hq,"]"))?(st(function(){return"pointer dndzone will be scheduled for destruction"}),iJ(r,b)):b()}}}var CE,aF={DND_ZONE_ACTIVE:"dnd-zone-active",DND_ZONE_DRAG_DISABLED:"dnd-zone-drag-disabled"},Rq=(CE={},am(CE,aF.DND_ZONE_ACTIVE,"zoneActiveInstruction"),am(CE,aF.DND_ZONE_DRAG_DISABLED,"zoneDragDisabledInstruction"),CE),Nq={dragStarted:function(e){var t=e.itemLabel,n=e.zoneLabel,i=e.canMoveBetweenZones;return"Started dragging item ".concat(t,". 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(e){var t=e.itemLabel,n=e.zoneLabel,i=e.position;return"Moved item ".concat(t," to position ").concat(i," in the list ").concat(n)},movedToZoneEnd:function(e){var t=e.itemLabel,n=e.zoneLabel;return"Moved item ".concat(t," to the end of the list ").concat(n)},movedToZoneStart:function(e){var t=e.itemLabel,n=e.zoneLabel;return"Moved item ".concat(t," to the beginning of the list ").concat(n)},dropped:function(e){var t=e.itemLabel;return"Stopped dragging item ".concat(t)},zoneActiveInstruction:function(e){var t=e.keyboardDragTrigger;return"Tab to one the items and press ".concat(CZ[t]," to start dragging it")},zoneDragDisabledInstruction:"This is a disabled drag and drop list"};var aJ=Ry({},Nq),lJ={keyboardDragTrigger:Eq},cJ="dnd-action-aria-alert",Vr;function lF(){Vr||(Vr=document.createElement("div"),(function(){Vr.id=cJ,Vr.style.position="fixed",Vr.style.bottom="0",Vr.style.left="0",Vr.style.zIndex="-5",Vr.style.opacity="0",Vr.style.height="0",Vr.style.width="0",Vr.setAttribute("role","alert")})(),document.body.prepend(Vr),Object.entries(Rq).forEach(function(r){var e=sZ(r,2),t=e[0],n=e[1];return document.body.prepend(pJ(t,Lq(n,lJ)))}))}function uJ(){return pF?null:(document.readyState==="complete"?lF():window.addEventListener("DOMContentLoaded",lF),Ry({},aF))}function dJ(){pF||!Vr||(Object.keys(Rq).forEach(function(r){var e;return(e=document.getElementById(r))===null||e===void 0?void 0:e.remove()}),Vr.remove(),Vr=void 0)}function pJ(r,e){var t=document.createElement("div");return t.id=r,fJ(t,e),t.style.display="none",t.style.position="fixed",t.style.zIndex="-5",t}function fJ(r,e){r.replaceChildren();var t=document.createElement("p");t.textContent=e,r.appendChild(t)}function Hd(r){if(!pF){Vr||lF(),Vr.innerHTML="";var e=document.createTextNode(r);Vr.appendChild(e),Vr.style.display="none",Vr.style.display="inline"}}function vq(r,e,t){var n=r[e];return typeof n=="function"?n(t):n}function Lq(r,e){try{return vq(aJ,r,e)}catch(t){st(function(){return['aria string formatter for "'.concat(r,'" threw, falling back to the default'),t]});try{return vq(Nq,r,e)}catch(n){return st(function(){return['default aria string formatter for "'.concat(r,'" also threw'),n]}),""}}}function om(r,e){Hd(Lq(r,e))}var mJ=Eq;function hJ(r){return wZ[mJ].includes(r)}var gJ="--any--",yq={outline:"rgba(255, 255, 102, 0.7) solid 2px"},Vi=!1,sm,li,va="",qd,mo,eu="",AE=new WeakSet,JD=new WeakMap,eF=new WeakMap,cF=new Map,ln=new Map,ya=new Map,IE;function vJ(r,e){st(function(){return"registering drop-zone if absent"}),ya.size===0&&(st(function(){return"adding global keydown and click handlers"}),IE=uJ(),window.addEventListener("keydown",Vq),window.addEventListener("click",Bq)),ya.has(e)||ya.set(e,new Set),ya.get(e).has(r)||(ya.get(e).add(r),Tq())}function bq(r,e){st(function(){return"unregistering drop-zone"}),Vi&&li===r&&um();var t=ya.get(e);!t||!t.delete(r)||(kq(),t.size===0&&ya.delete(e),ya.size===0&&(st(function(){return"removing global keydown and click handlers"}),window.removeEventListener("keydown",Vq),window.removeEventListener("click",Bq),IE=void 0,dJ()))}function Vq(r){Vi&&r.key==="Escape"&&um()}function Bq(){Vi&&(AE.has(document.activeElement)||(st(function(){return"clicked outside of any draggable"}),um()))}function qq(r,e){return r===li||qd.contains(r)||e.dropFromOthersDisabled||e.type!==sm?-1:0}function yJ(){ln.forEach(function(r,e){e.tabIndex=qq(e,r)})}function bJ(){var r=ln.get(li);return r!=null&&r.items.some(function(e){return e[gr]===mo})?!0:(st(function(){return"dragged item is gone, dropping"}),um(),!1)}function wq(r){if(st(function(){return"zone focus"}),!!Vi){var e=r.currentTarget;if(e!==li&&bJ()){va=e.getAttribute("aria-label")||"";var t=ln.get(li),n=t.items,i=n.find(function(p){return p[gr]===mo}),o=n.indexOf(i),s=n.splice(o,1)[0],a=ln.get(e),l=a.items,c=a.autoAriaDisabled;e.getBoundingClientRect().top<li.getBoundingClientRect().top||e.getBoundingClientRect().left<li.getBoundingClientRect().left?(l.push(s),c||om("movedToZoneEnd",{itemLabel:eu,zoneLabel:va,position:l.length,count:l.length})):(l.unshift(s),c||om("movedToZoneStart",{itemLabel:eu,zoneLabel:va,position:1,count:l.length}));var u=li,d=mo;li=e,lm(u,n,{trigger:jn.DROPPED_INTO_ANOTHER,id:d,source:Fn.KEYBOARD}),ln.has(e)&&lm(e,l,{trigger:jn.DROPPED_INTO_ZONE,id:d,source:Fn.KEYBOARD})}}}function Uq(){cF.forEach(function(r,e){var t=r.update;return t(ln.get(e))})}function um(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;if(!(!Vi||!li)){st(function(){return"drop"});var e=li,t=ln.get(e),n=mo,i=sm;if(t){if(!t.autoAriaDisabled){var o=t.items,s=o.findIndex(function(l){return l[gr]===n});om("dropped",{itemLabel:eu,zoneLabel:va,position:(s<0?0:s)+1,count:o.length})}AE.has(document.activeElement)&&document.activeElement.blur(),qd=null,mo=null,eu="",sm=null,li=null,va="",Vi=!1,r&&ru(e,t.items,{trigger:jn.DRAG_STOPPED,id:n,source:Fn.KEYBOARD});var a=ya.get(i);a&&kE(a,function(l){return ln.get(l).dropTargetStyle},function(l){return ln.get(l).dropTargetClasses}),Uq()}}}function wJ(r,e){var t=!1,n={items:void 0,type:void 0,dragDisabled:!1,zoneTabIndex:0,zoneItemTabIndex:0,dropFromOthersDisabled:!1,dropTargetStyle:yq,dropTargetClasses:[],autoAriaDisabled:!1};function i(d,p,f){d.length<=1||d.splice(f,1,d.splice(p,1,d[f])[0])}function o(d){switch(st(function(){return["handling key down",d.key]}),d.key){case"Enter":case" ":{if(!hJ(d.key)||(d.target.disabled!==void 0||d.target.href||d.target.isContentEditable)&&!AE.has(d.target))return;d.preventDefault(),d.stopPropagation(),Vi?um():s(d);break}case"ArrowDown":case"ArrowRight":{if(!Vi)return;d.preventDefault(),d.stopPropagation();var p=ln.get(r),f=p.items,m=Array.from(r.children),g=m.indexOf(d.currentTarget);st(function(){return["arrow down",g]}),g<m.length-1&&(n.autoAriaDisabled||om("movedToPosition",{itemLabel:eu,zoneLabel:va,position:g+2,count:f.length}),i(f,g,g+1),lm(r,f,{trigger:jn.DROPPED_INTO_ZONE,id:mo,source:Fn.KEYBOARD}));break}case"ArrowUp":case"ArrowLeft":{if(!Vi)return;d.preventDefault(),d.stopPropagation();var v=ln.get(r),y=v.items,b=Array.from(r.children),x=b.indexOf(d.currentTarget);st(function(){return["arrow up",x]}),x>0&&(n.autoAriaDisabled||om("movedToPosition",{itemLabel:eu,zoneLabel:va,position:x,count:y.length}),i(y,x,x-1),lm(r,y,{trigger:jn.DROPPED_INTO_ZONE,id:mo,source:Fn.KEYBOARD}));break}}}function s(d){st(function(){return"drag start"}),l(d.currentTarget),li=r,va=r.getAttribute("aria-label")||"",sm=n.type,Vi=!0;var p=Array.from(ya.get(n.type)).filter(function(g){return g===li||!ln.get(g).dropFromOthersDisabled});if(xE(p,function(g){return ln.get(g).dropTargetStyle},function(g){return ln.get(g).dropTargetClasses}),!n.autoAriaDisabled){var f=ln.get(r).items,m=f.findIndex(function(g){return g[gr]===mo});om("dragStarted",{itemLabel:eu,zoneLabel:va,position:(m<0?0:m)+1,count:f.length,canMoveBetweenZones:p.length>1})}ru(r,ln.get(r).items,{trigger:jn.DRAG_STARTED,id:mo,source:Fn.KEYBOARD}),Uq()}function a(d){Vi&&d.currentTarget!==qd&&(d.stopPropagation(),um(!1),s(d))}function l(d){var p=ln.get(r),f=p.items,m=Array.from(r.children),g=m.indexOf(d);qd=d,qd.tabIndex=n.zoneItemTabIndex,mo=f[g][gr],eu=m[g].getAttribute("aria-label")||""}function c(d){var p=d.items,f=p===void 0?[]:p,m=d.type,g=m===void 0?gJ:m,v=d.dragDisabled,y=v===void 0?!1:v,b=d.zoneTabIndex,x=b===void 0?0:b,w=d.zoneItemTabIndex,T=w===void 0?0:w,C=d.dropFromOthersDisabled,S=C===void 0?!1:C,A=d.dropTargetStyle,D=A===void 0?yq:A,P=d.dropTargetClasses,U=P===void 0?[]:P,K=d.autoAriaDisabled,W=K===void 0?!1:K;n.items=Xo(f),n.dragDisabled=y,n.dropFromOthersDisabled=S,n.zoneTabIndex=x,n.zoneItemTabIndex=T,n.dropTargetStyle=D,n.dropTargetClasses=U,n.autoAriaDisabled=W,n.type&&g!==n.type&&bq(r,n.type),n.type=g,vJ(r,g),W||(r.setAttribute("role","list"),r.setAttribute("aria-describedby",y?IE.DND_ZONE_DRAG_DISABLED:IE.DND_ZONE_ACTIVE)),ln.set(r,n);var ee=!1;Vi?(ee=n.type===sm&&n.items.some(function(H){return H[gr]===mo})&&r!==li,ee&&(li=r,va=r.getAttribute("aria-label")||""),r.tabIndex=qq(r,n)):r.tabIndex=n.zoneTabIndex,r.addEventListener("focus",wq);for(var me=function(ce){var te,z=r.children[ce];AE.add(z),z.tabIndex=Vi?-1:n.zoneItemTabIndex,W||z.setAttribute("role","listitem"),z.removeEventListener("keydown",JD.get(z)),z.removeEventListener("click",eF.get(z)),y||(z.addEventListener("keydown",o),JD.set(z,o),z.addEventListener("click",a),eF.set(z,a)),Vi&&n.type===sm&&((te=n.items[ce])===null||te===void 0?void 0:te[gr])===mo&&(st(function(){return["focusing on",{i:ce,focusedItemId:mo}]}),qd=z,qd.tabIndex=n.zoneItemTabIndex,z.focus())},O=0;O<r.children.length;O++)me(O);ee&&yJ()}c(e);var u={update:function(p){st(function(){return"keyboard dndzone will update newOptions: ".concat($s(p))}),c(p)},destroy:function(){if(!t){t=!0,st(function(){return"keyboard dndzone will destroy"}),r.removeEventListener("focus",wq);var p=Ud(r.children),f;try{for(p.s();!(f=p.n()).done;){var m=f.value;m.removeEventListener("keydown",JD.get(m)),m.removeEventListener("click",eF.get(m))}}catch(g){p.e(g)}finally{p.f()}bq(r,n.type),ln.delete(r),cF.delete(r)}}};return cF.set(r,u),u}var CJ=["items","flipDurationMs","type","dragDisabled","morphDisabled","dropFromOthersDisabled","zoneTabIndex","zoneItemTabIndex","dropTargetStyle","dropTargetClasses","transformDraggedElement","autoAriaDisabled","centreDraggedOnCursor","useCursorForDetection","delayTouchStart","dropAnimationDisabled"];function pm(r,e){if(xJ(r))return{update:function(){},destroy:function(){}};Cq(e);var t=sJ(r,e),n=wJ(r,e);return{update:function(o){Cq(o),t.update(o),n.update(o)},destroy:function(){t.destroy(),n.destroy()}}}function xJ(r){return!!r.closest("[".concat(xZ,'="true"]'))}function Cq(r){var e=r.items;r.flipDurationMs,r.type,r.dragDisabled,r.morphDisabled,r.dropFromOthersDisabled;var t=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=oZ(r,CJ);if(Object.keys(s).length>0&&console.warn("dndzone will ignore unknown options",s),!e)throw new Error("no 'items' key provided to dndzone");var a=e.find(function(u){return!{}.hasOwnProperty.call(u,gr)});if(a)throw new Error("missing '".concat(gr,"' property for item ").concat($s(a)));if(i&&!Array.isArray(i))throw new Error("dropTargetClasses should be an array but instead it is a ".concat(rm(i),", ").concat($s(i)));if(t&&!xq(t))throw new Error("zoneTabIndex should be a number but instead it is a ".concat(rm(t),", ").concat($s(t)));if(n&&!xq(n))throw new Error("zoneItemTabIndex should be a number but instead it is a ".concat(rm(n),", ").concat($s(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(rm(o),", ").concat($s(o)))}}function xq(r){return!isNaN(r)&&(function(e){return(e|0)===e})(parseFloat(r))}function Hq(r){var e=r,t=new Set;return{get:function(){return e},set:function(i){e=i,Array.from(t).forEach(function(o){return o(e)})},subscribe:function(i){t.add(i),i(e)},unsubscribe:function(i){t.delete(i)}}}var _Ve=Hq(!0),AVe=Hq(!1);var EJ=[[9,5],[9,12],[9,19],[15,5],[15,12],[15,19]];function zq(r,e,t=!1){if(!r)return;r.classList.add("qa-drag-clone"),r.dataset.qaMulti=t?"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 EJ)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!==e&&(i.textContent=e)}function qi(r){return r.filter(e=>e.id!==Vy)}function fm(r,e){let t=r.findIndex(i=>i.id===Vy);if(t===-1)return null;let n={...r[t]};return delete n[dm],{item:{...n,id:e},index:t}}function Wq(r,e){return r.map(t=>t.id===e.id?e:t)}function mm(r,e,t){let n=r.findIndex(a=>a.id===e);if(n===-1)return null;let i=n+t;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}function hm(r){let e=r.resolveLabel??(t=>t.name??"");return{items:r.items,dragDisabled:r.dragDisabled,flipDurationMs:r.flipDurationMs??0,morphDisabled:!0,useCursorForDetection:!0,centreDraggedOnCursor:!1,transformDraggedElement:(t,n)=>zq(t,n?e(n):"",n?.type==="Multi"),dropTargetStyle:{},dropTargetClasses:r.dropTargetClasses??[],dropAnimationDisabled:!0,autoAriaDisabled:!0,zoneItemTabIndex:-1,delayTouchStart:200,...r.type?{type:r.type}:{}}}function gm(){let r=Ce(!1),e=!1;function t(){j(r,!0),e=!1;let n=()=>{window.removeEventListener("pointerup",n,!0),window.removeEventListener("pointercancel",n,!0),e||j(r,!1)};window.addEventListener("pointerup",n,!0),window.addEventListener("pointercancel",n,!0)}return{get armed(){return h(r)},markStarted(){e=!0},reset(){j(r,!1),e=!1},startDrag:t}}async function vm(r,e){if(await ac(),!r)return;r.querySelector(`button[aria-label="${CSS.escape(e)}"]`)?.focus()}var TJ=L('<button type="button"><!></button>');function cn(r,e){pe(e,!0);let t=ne(e,"size",3,16),n=F(()=>!!(e.onMoveUp||e.onMoveDown));function i(l){l.key==="ArrowUp"&&e.onMoveUp?(l.preventDefault(),l.stopPropagation(),e.onMoveUp()):l.key==="ArrowDown"&&e.onMoveDown&&(l.preventDefault(),l.stopPropagation(),e.onMoveDown())}var o=TJ();let s;var a=B(o);Et(a,{iconId:"grip-vertical",get size(){return t()}}),N(o),re(()=>{s=it(o,1,"qa-icon-button qa-drag-handle",null,s,{"qa-drag-handle-ready":e.dragDisabled,"qa-drag-handle-active":!e.dragDisabled}),ke(o,"aria-label",e.label),ke(o,"aria-keyshortcuts",h(n)?"ArrowUp ArrowDown":void 0),ke(o,"tabindex",e.dragDisabled?0:-1)}),Ae("pointerdown",o,()=>e.onDragStart()),Ae("keydown",o,i),M(r,o),fe()}nt(["pointerdown","keydown"]);function OE(r){let e=t=>t.stopPropagation();return r.addEventListener("mousedown",e),r.addEventListener("touchstart",e,{passive:!0}),{destroy(){r.removeEventListener("mousedown",e),r.removeEventListener("touchstart",e)}}}var kJ=L('<button type="button"><!></button>');function Lt(r,e){let t=ne(e,"size",3,16),n=ne(e,"extraClass",3,""),i=ne(e,"disabled",3,!1);var o=kJ();let s;var a=B(o);Et(a,{get iconId(){return e.iconId},get size(){return t()}}),N(o),Jt(o,l=>OE?.(l)),re(()=>{s=it(o,1,`qa-icon-button ${n()}`,null,s,{"is-pressed":e.ariaPressed===!0}),ke(o,"aria-label",e.label),ke(o,"aria-pressed",e.ariaPressed),ke(o,"aria-haspopup",e.ariaHasPopup),ke(o,"title",e.title),o.disabled=i()}),Ae("click",o,function(...l){e.onclick?.apply(this,l)}),M(r,o)}nt(["click"]);var SJ=L('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!></div></li>'),_J=L('<ol class="qa-folder-list svelte-ee11ws"></ol>'),AJ={hash:"svelte-ee11ws",code:".qa-folder-list.svelte-ee11ws {display:grid;grid-template-columns:auto;width:auto;margin:12px 0;padding:0;list-style:none;}"};function vF(r,e){let t=Ku();pe(e,!0),We(r,AJ);let n=`folder:${t}`,i=jq.Platform.isMobile,o=gm(),s=F(()=>!i&&!o.armed),a=Ce(void 0);function l(b){return b.map(x=>({id:x}))}let c=Ce(null),u=F(()=>h(c)??l(e.folders)),d=null;function p(b){o.markStarted();let x=b.detail.items;d=fm(x,b.detail.info.id)??d,j(c,qi(x),!0)}function f(b){let x=qi(b.detail.items),w=b.detail.info.id;d?.item.id===w&&!x.some(T=>T.id===w)&&(x=[...x],x.splice(Math.min(d.index,x.length),0,d.item)),e.onChange(x.map(T=>T.id)),j(c,null),d=null,b.detail.info.source===Fn.POINTER&&o.reset()}function m(b,x){let w=document.activeElement?.getAttribute("aria-label"),T=mm(l(e.folders),b,x);if(!T)return;e.onChange(T.map(S=>S.id));let C=T.findIndex(S=>S.id===b);Hd(`Moved ${b} to position ${C+1} of ${T.length}`),w&&vm(h(a),w)}function g(b){e.onChange(e.folders.filter(x=>x!==b))}let v=()=>{o.startDrag()};var y=_J();Ot(y,21,()=>qi(h(u)),b=>b.id,(b,x)=>{var w=SJ(),T=B(w),C=le(T,!0),S=_(T,2),A=B(S);{let P=F(()=>`Remove folder ${h(x).id}`);Lt(A,{iconId:"trash-2",get label(){return h(P)},onclick:()=>g(h(x).id)})}var D=_(A,2);{let P=F(()=>`Reorder ${h(x).id}`);cn(D,{get label(){return h(P)},get dragDisabled(){return h(s)},onDragStart:v,onMoveUp:()=>m(h(x).id,-1),onMoveDown:()=>m(h(x).id,1)})}N(S),N(w),re(()=>ae(C,h(x).id)),M(b,w)}),N(y),Ci(y,b=>j(a,b),()=>h(a)),Jt(y,(b,x)=>pm?.(b,x),()=>hm({items:h(u),dragDisabled:h(s),type:n,resolveLabel:b=>b.id})),Po("consider",y,p),Po("finalize",y,f),M(r,y),fe()}function Gq(r){return r.enabled?r.chooseWhenCreatingNote?"prompt":r.createInSameFolderAsActiveFile?"active-file":"specified":"obsidian-default"}function Yq(r,e){switch(e){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 Kq=[{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"}],Qq={"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."};Xe();zd();Xe();function RE(r){if(!r?.enabled||r.chooseWhenCreatingNote||r.chooseFromSubfolders||r.createInSameFolderAsActiveFile)return;let e=r.folders??[];if(e.length!==1)return;let t=e[0]?.trim();if(t&&!t.includes("{{")&&!tl.test(t))return t}var IJ=L("<!> <!> <!>",1),DJ=L(`<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>`),FJ=L('<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),PJ=L("<!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!>",1);function wF(r,e){pe(e,!0);let t=ne(e,"choice",15),n=F(()=>e.plugin.getTemplateFiles().map(ge=>ge.path)),i=F(()=>Il(Vo(e.app)));function o(ge){let ve=ge.trim();return ve?cl(ve)?{valid:!0,message:"Contains format syntax \u2014 resolved at run time."}:Vn(e.app,ve)!==null||"Template not found":!0}let s=[ge=>new Sn(e.app,ge,e.plugin,"fileName")],a=F(()=>yF(t(),t().fileNameFormat.enabled?t().fileNameFormat.format:Or)),l=F(()=>h(a)?"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}}."),c=F(()=>Gq(t().folder)),u=F(()=>Qq[h(c)]),d=F(()=>h(c)==="specified"&&t().folder.folders.length===0);function p(ge){t(t().folder=Yq(t().folder,ge),!0)}let f=Ce(""),m;function g(ge){return m=new bE(e.app,ge,h(i),t().folder.folders),m}Yt(()=>{m?.updateCurrentItems(t().folder.folders)});function v(){let ge=h(f).trim();if(ge){if(t().folder.folders.some(ve=>ve===ge)){I.logWarning("cannot add same folder twice.");return}t().folder.folders.push(ge),j(f,"")}}function y(ge){ge.key==="Enter"&&v()}let b=F(()=>sq(t().fileExistsBehavior)),x=F(()=>h(b)!=="prompt"&&h(b)!=="keep"),w=F(()=>nq(h(b)==="update"?"update":"create")),T=F(()=>t().fileExistsBehavior.kind==="apply"?t().fileExistsBehavior.mode:h(w)[0].id);function C(ge){t(t().fileExistsBehavior=aq(ge,t().fileExistsBehavior),!0)}function S(ge){t(t().fileExistsBehavior={kind:"apply",mode:ge},!0)}var A=PJ(),D=Te(A);kv(D,{get app(){return e.app},get name(){return t().name},set name(ge){t(t().name=ge,!0)}});var P=_(D,2);Se(P,{name:"Template",heading:!0});var U=_(P,2);Ti(U,{name:"Template path",desc:"Path to the template this choice creates notes from.",children:(ve,Fe=Ct)=>{sn(ve,{get id(){return Fe()},get value(){return t().templatePath},placeholder:"Template path",get app(){return e.app},get suggestions(){return h(n)},maxSuggestions:50,validator:o,onChange:Je=>t(t().templatePath=Je.trim(),!0)})},$$slots:{default:!0}});var K=_(U,2);Ti(K,{name:"File name format",desc:"Set the file name format. When off, QuickAdd asks for the note title.",get bodyVisible(){return t().fileNameFormat.enabled},control:Fe=>{St(Fe,{get checked(){return t().fileNameFormat.enabled},set checked(Je){t(t().fileNameFormat.enabled=Je,!0)}})},children:(Fe,Je=Ct)=>{var mt=IJ(),Ft=Te(mt);sn(Ft,{get id(){return Je()},placeholder:"File name format",get makeSuggesters(){return s},get value(){return t().fileNameFormat.format},set value(rr){t(t().fileNameFormat.format=rr,!0)}});var Qe=_(Ft,2);Vd(Qe,{get value(){return t().fileNameFormat.format}});var zt=_(Qe,2);{let rr=F(()=>RE(t().folder));fo(zt,{get value(){return t().fileNameFormat.format},formatterKind:"fileName",get targetFolderPath(){return h(rr)},get app(){return e.app},get plugin(){return e.plugin}})}M(Fe,mt)},$$slots:{control:!0,default:!0}});var W=_(K,2);Se(W,{name:"Location",heading:!0});var ee=_(W,2);Se(ee,{name:"New note location",get desc(){return h(u)},control:ve=>{ft(ve,{get value(){return h(c)},get options(){return Kq},ariaLabel:"New note location",onchange:p})},$$slots:{control:!0}});var me=_(ee,2);{var O=ge=>{var ve=FJ(),Fe=Te(ve),Je=B(Fe),mt=B(Je);vF(mt,{get folders(){return t().folder.folders},onChange:Z=>t(t().folder.folders=Z,!0)}),N(Je);var Ft=_(Je,2),Qe=B(Ft);Rt(Qe),$r(()=>wi(Qe,()=>h(f),Z=>j(f,Z))),Jt(Qe,(Z,De)=>Sd?.(Z,De),()=>g);var zt=_(Qe,2);N(Ft),N(Fe);var rr=_(Fe,2);{var Qn=Z=>{var De=DJ();M(Z,De)};Y(rr,Z=>{h(d)&&Z(Qn)})}var di=_(rr,2);Se(di,{name:"Include subfolders",desc:"Get prompted to choose from both the selected folders and their subfolders when creating the note.",control:De=>{St(De,{get checked(){return t().folder.chooseFromSubfolders},set checked(Pt){t(t().folder.chooseFromSubfolders=Pt,!0)}})},$$slots:{control:!0}}),Po("keypress",Qe,y),Ae("click",zt,v),M(ge,ve)};Y(me,ge=>{h(c)==="specified"&&ge(O)})}var H=_(me,2);Se(H,{name:"Linking",heading:!0});var ce=_(H,2);fy(ce,{fileLabel:"created",get app(){return e.app},get appendLink(){return t().appendLink},set appendLink(ge){t(t().appendLink=ge,!0)}});var te=_(ce,2);Se(te,{name:"Copy link to clipboard",desc:"Copy a link to the created file after the Template choice runs.",control:ve=>{{let Fe=F(()=>t().copyLinkToClipboard??!1);St(ve,{get checked(){return h(Fe)},onchange:Je=>t(t().copyLinkToClipboard=Je,!0)})}},$$slots:{control:!0}});var z=_(te,2);Se(z,{name:"Behavior",heading:!0});var G=_(z,2);Se(G,{name:"Search existing notes before creating",get desc(){return h(l)},control:ve=>{{let Fe=F(()=>h(a)?t().discoverExistingNotesBeforeCreate??!1:!1),Je=F(()=>!h(a));St(ve,{get checked(){return h(Fe)},get disabled(){return h(Je)},onchange:mt=>t(t().discoverExistingNotesBeforeCreate=mt,!0)})}},$$slots:{control:!0}});var ie=_(G,2);{var xe=ge=>{Se(ge,{name:"When selecting an existing note",control:Fe=>{{let Je=F(()=>t().existingNoteAction??"open"),mt=F(()=>vE.map(Ft=>({value:Ft.id,label:Ft.label})));ft(Fe,{get value(){return h(Je)},get options(){return h(mt)},onchange:Ft=>{let Qe=vE.find(zt=>zt.id===Ft);Qe&&t(t().existingNoteAction=Qe.id,!0)}})}},$$slots:{control:!0}})};Y(ie,ge=>{h(a)&&t().discoverExistingNotesBeforeCreate&&ge(xe)})}var ue=_(ie,2);{let ge=Fe=>{{let Je=F(()=>tq.map(mt=>({value:mt.id,label:mt.label})));ft(Fe,{get value(){return h(b)},get options(){return h(Je)},onchange:C})}},ve=F(()=>h(a)&&t().discoverExistingNotesBeforeCreate?"If a new note's path already exists":"If the target file already exists");Se(ue,{get name(){return h(ve)},desc:"Choose whether QuickAdd should ask what to do, update the existing file, create another file, or keep the existing file.",control:ge,$$slots:{control:!0}})}var be=_(ue,2);{var Ke=ge=>{{let ve=mt=>{{let Ft=F(()=>h(w).map(Qe=>({value:Qe.id,label:Qe.label})));ft(mt,{get value(){return h(T)},get options(){return h(Ft)},onchange:S})}},Fe=F(()=>h(b)==="update"?"Update action":"New file naming"),Je=F(()=>tm(h(T)).description);Se(ge,{get name(){return h(Fe)},get desc(){return h(Je)},control:ve,$$slots:{control:!0}})}};Y(be,ge=>{h(x)&&ge(Ke)})}var Oe=_(be,2);my(Oe,{description:"Open the created file.",get openFile(){return t().openFile},set openFile(ge){t(t().openFile=ge,!0)}});var Ee=_(Oe,2);{var He=ge=>{hy(ge,{contextLabel:"created",get fileOpening(){return t().fileOpening},set fileOpening(ve){t(t().fileOpening=ve,!0)}})};Y(Ee,ge=>{t().openFile&&ge(He)})}var Le=_(Ee,2);xy(Le,{get dateOrigin(){return t().dateOrigin},set dateOrigin(ge){t(t().dateOrigin=ge,!0)}});var At=_(Le,2);gy(At,{get onePageInput(){return t().onePageInput},set onePageInput(ge){t(t().onePageInput=ge,!0)}});var mr=_(At,2);Sy(mr,{get name(){return t().name},get dateOrigin(){return t().dateOrigin},get command(){return t().command},set command(ge){t(t().command=ge,!0)},get pickDayCommand(){return t().pickDayCommand},set pickDayCommand(ge){t(t().pickDayCommand=ge,!0)}});var zr=_(mr,2);Dy(zr,{get type(){return t().type},get app(){return e.app},get icon(){return t().icon},set icon(ge){t(t().icon=ge,!0)}}),M(r,A),fe()}nt(["click"]);var Xq=hE;var ym=class extends Jf{constructor(t,n,i){super(t);this.plugin=i;this.choice=n,this.normalizeChoice(),this.display()}normalizeChoice(){var t,n,i,o,s,a,l,c,u,d,p;(t=this.choice).fileExistsBehavior??(t.fileExistsBehavior={kind:"prompt"}),this.choice.fileOpening=Cn(this.choice.fileOpening),(n=this.choice).templatePath??(n.templatePath=""),(i=this.choice).fileNameFormat??(i.fileNameFormat={enabled:!1,format:""}),(o=this.choice.fileNameFormat).enabled??(o.enabled=!1),(s=this.choice.fileNameFormat).format??(s.format=""),(a=this.choice).folder??(a.folder={enabled:!1,folders:[],chooseWhenCreatingNote:!1,createInSameFolderAsActiveFile:!1,chooseFromSubfolders:!1}),(l=this.choice.folder).enabled??(l.enabled=!1),(c=this.choice.folder).folders??(c.folders=[]),(u=this.choice.folder).chooseWhenCreatingNote??(u.chooseWhenCreatingNote=!1),(d=this.choice.folder).createInSameFolderAsActiveFile??(d.createInSameFolderAsActiveFile=!1),(p=this.choice.folder).chooseFromSubfolders??(p.chooseFromSubfolders=!1)}display(){this.containerEl.addClass("templateChoiceBuilder"),this.formProps=this.mountForm(wF,Xq({choice:this.choice,app:this.app,plugin:this.plugin}),"this template choice's settings")}getResultChoice(){return this.formProps?.choice??this.choice}};Wd();var Ls=require("obsidian");Ds();var Hi=require("obsidian");var TU=require("obsidian");_s();vr();Id();function jd(r){if(r.type==="Choice")try{return on().getChoiceById(r.choiceId).name}catch{return"(missing choice)"}if(r.type==="Conditional"){let e=r.condition;return`If ${Pf(e)}`}return r.name}var $J=L('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!></div></li>');function CF(r,e){pe(e,!0);var t=$J(),n=B(t),i=le(n,!0),o=_(n,2),s=B(o);{let l=F(()=>`Delete ${jd(e.command)}`);Lt(s,{iconId:"trash-2",get label(){return h(l)},extraClass:"clickable",onclick:()=>e.onDeleteCommand(e.command.id)})}var a=_(s,2);{let l=F(()=>`Reorder ${jd(e.command)}`);cn(a,{get label(){return h(l)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.startDrag},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}N(o),N(t),re(l=>ae(i,l),[()=>jd(e.command)]),M(r,t),fe()}vr();var OJ=L('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> <input type="number" min="0" placeholder=" " class="dotInput svelte-1h5tx3b" aria-label="Wait duration in milliseconds"/>ms</span> <div class="quickAddCommandControls"><!> <!></div></li>'),RJ={hash:"svelte-1h5tx3b",code:".dotInput.svelte-1h5tx3b {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-1h5tx3b:hover {background-color:transparent;}"};function xF(r,e){pe(e,!0),We(r,RJ);let t=Ce(void 0),n=Ce(ut(kt(()=>e.command.time)));function i(){if(!h(t))return;let f=String(h(t).value).length;h(t).style.setProperty("--qa-wait-input-width",`${f===0?2:f}ch`)}function o(f){let m=f.currentTarget.valueAsNumber;j(n,Number.isNaN(m)||m<0?0:m,!0),i(),e.onUpdateCommand({...e.command,time:h(n)})}eC(i);var s=OJ(),a=B(s),l=B(a),c=_(l);Rt(c),Ci(c,f=>j(t,f),()=>h(t)),Gr(),N(a);var u=_(a,2),d=B(u);{let f=F(()=>`Delete ${e.command.name}`);Lt(d,{iconId:"trash-2",get label(){return h(f)},extraClass:"clickable",onclick:()=>e.onDeleteCommand(e.command.id)})}var p=_(d,2);{let f=F(()=>`Reorder ${e.command.name}`);cn(p,{get label(){return h(f)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.startDrag},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}N(u),N(s),re(()=>{ae(l,`${e.command.name??""} for `),bi(c,h(n))}),Ae("input",c,o),M(r,s),fe()}nt(["input"]);var NJ=L('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function EF(r,e){pe(e,!0);var t=NJ(),n=B(t),i=le(n,!0),o=_(n,2),s=B(o);{let c=F(()=>`Configure ${e.command.name}`);Lt(s,{iconId:"settings",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onConfigureChoice(e.command)})}var a=_(s,2);{let c=F(()=>`Delete ${e.command.name}`);Lt(a,{iconId:"trash-2",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onDeleteCommand(e.command.id)})}var l=_(a,2);{let c=F(()=>`Reorder ${e.command.name}`);cn(l,{get label(){return h(c)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.startDrag},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}N(o),N(t),re(()=>ae(i,e.command.name)),M(r,t),fe()}var LJ=L('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function TF(r,e){pe(e,!0);var t=LJ(),n=B(t),i=le(n,!0),o=_(n,2),s=B(o);{let c=F(()=>`Configure ${e.command.name}`);Lt(s,{iconId:"settings",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onConfigureScript(e.command)})}var a=_(s,2);{let c=F(()=>`Delete ${e.command.name}`);Lt(a,{iconId:"trash-2",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onDeleteCommand(e.command.id)})}var l=_(a,2);{let c=F(()=>`Reorder ${e.command.name}`);cn(l,{get label(){return h(c)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.startDrag},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}N(o),N(t),re(()=>ae(i,e.command.name)),M(r,t),fe()}var Gn=require("obsidian");_s();function Jq(r,e){let t=r.createDiv({cls:"qa-format-preview-host"}),n=ut({value:e.value,app:e.app,plugin:e.plugin,targetFolderPath:null}),i=Li(t,fo,n,{what:"the preview for this field"}),o=!1;return{setValue(s){o||(n.value=s)},destroy(){o||(o=!0,i.destroy(),t.remove())}}}function eU(r){r.addEventListener("focus",()=>{r.type="text"}),r.addEventListener("blur",()=>{r.type="password"}),r.type="password"}YE();Ml();function ree(r){return typeof r=="string"?r:r==null?"":String(r)}function mU(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 KE=class extends Gn.Modal{constructor(t,n,i,o){super(t);this.command=n;this.settings=i;this.onCommandChange=o;this.previewHandles=[];this.command.settings||(this.command.settings={}),Em(this.command.settings,this.settings),this.display(),this.migrateSecretSettings()}display(){this.containerEl.addClass("quickAddModal","userScriptSettingsModal"),this.destroyPreviews(),this.contentEl.empty();let t=mU(this.settings?.name??this.command.name),n=mU(this.settings?.author);this.titleEl.innerText=`${t}${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(xm(s)){let u=this.addSecretInput(o,"placeholder"in s?s.placeholder:void 0);s.description&&u.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(t,n,i,o){return new Gn.Setting(this.contentEl).setName(t).addText(s=>{s.setValue(n).onChange(a=>{this.command.settings[t]=a,this.onCommandChange?.()}).setPlaceholder(i??""),o&&eU(s.inputEl)})}addSecretInput(t,n){let i=new Gn.Setting(this.contentEl).setName(t),o="",s,a=()=>{let c=this.command.settings?.[t];return WE(this.command,t)!==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(u=>{o=u}),c.inputEl.type="password",c.inputEl.addClass("qa-user-script-secret-input"),c.inputEl.setAttribute("aria-label",t),s=c.inputEl,l()}),i.addButton(c=>{c.setIcon("save").setTooltip("Save secret").onClick(async()=>{if(o.length===0){new Gn.Notice("Paste a secret before saving.");return}let u=await DF(this.app,this.command,t,o,WE(this.command,t),this.settings.options?.[t]);if(!u){new Gn.Notice("SecretStorage is unavailable. Secret was not saved.");return}this.command.settings[t]=qE(u),o="",s&&(s.value=""),l(),this.onCommandChange?.(),new Gn.Notice("Secret saved.")}),c.buttonEl.setAttribute("aria-label",`Save ${t}`)}),i.addButton(c=>{c.setIcon("trash-2").setTooltip("Clear secret").onClick(async()=>{let u=WE(this.command,t);if(u&&!await FF(this.app,u)){new Gn.Notice("SecretStorage is unavailable. Secret was not cleared.");return}delete this.command.settings[t],o="",s&&(s.value=""),l(),this.onCommandChange?.(),new Gn.Notice("Secret cleared.")}),c.buttonEl.setAttribute("aria-label",`Clear ${t}`)}),i}addTextArea(t,n,i){return new Gn.Setting(this.contentEl).setName(t).addTextArea(o=>{o.setValue(n).onChange(s=>{this.command.settings[t]=s,this.onCommandChange?.()}).setPlaceholder(i??""),o.inputEl.addClass("qa-user-script-argument-textarea")})}addToggle(t,n){return new Gn.Setting(this.contentEl).setName(t).addToggle(i=>i.setValue(n).onChange(o=>{this.command.settings[t]=o,this.onCommandChange?.()}))}addDropdown(t,n,i){return new Gn.Setting(this.contentEl).setName(t).addDropdown(o=>{n.forEach(s=>{o.addOption(s,s)}),o.setValue(i),o.onChange(s=>{this.command.settings[t]=s,this.onCommandChange?.()})})}addFormatInput(t,n,i){let o=new Gn.Setting(this.contentEl).setName(t),s=ree(n),a=new Gn.TextAreaComponent(this.contentEl);new Sn(this.app,a.inputEl,on()),a.inputEl.addClass("qa-user-script-format-textarea"),a.inputEl.setAttribute("aria-label",t);let l=Jq(this.contentEl,{app:this.app,plugin:on(),value:s});return this.previewHandles.push(l),a.setValue(s).onChange(c=>{this.command.settings[t]=c,l.setValue(c),this.onCommandChange?.()}).setPlaceholder(i??""),o}destroyPreviews(){for(let t of this.previewHandles)t.destroy();this.previewHandles=[]}onClose(){this.destroyPreviews(),super.onClose()}async migrateSecretSettings(){await zE(this.app,this.command,this.settings)&&(this.onCommandChange?.(),this.display())}};Ie();ht();var nee=L('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function $F(r,e){pe(e,!0);var t=nee(),n=B(t),i=le(n,!0),o=_(n,2),s=B(o);{let c=F(()=>`Configure ${e.command.name}`);Lt(s,{iconId:"settings",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onConfigureAssistant(e.command)})}var a=_(s,2);{let c=F(()=>`Delete ${e.command.name}`);Lt(a,{iconId:"trash-2",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onDeleteCommand(e.command.id)})}var l=_(a,2);{let c=F(()=>`Reorder ${e.command.name}`);cn(l,{get label(){return h(c)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.startDrag},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}N(o),N(t),re(()=>ae(i,e.command.name)),M(r,t),fe()}var _i=require("obsidian");var iee="QuickAdd sends the system prompt to the model as written - format syntax like {{DATE}} is not resolved here. Only the prompt template is formatted.",oee=0;function QE(r,e,t){let n=r.createDiv({text:iee,cls:"qa-literal-format-note"}),i=`qa-literal-format-note-${++oee}`;n.id=i;let o=s=>{let a=s.includes("{{");n.classList.toggle("qa-literal-format-note--shown",a),a?e.setAttribute("aria-describedby",i):e.removeAttribute("aria-describedby")};return o(t),o}ht();dt();Ds();Wy();var CU=require("obsidian");Tm();var uee=[{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 xU(r,e,t,n){let i=Gd(t,{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 uee){let s=typeof e[o.key]=="number";new CU.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(e[o.key]??o.fallback),a.onChange(l=>{e[o.key]=l})}).addExtraButton(a=>{a.setIcon("rotate-ccw"),a.setTooltip("Reset to provider default"),a.setDisabled(!s),a.onClick(()=>{delete e[o.key],n()})})}}Tm();ro();dt();var km="Ask me",XE="__qa-missing-model__";function ZE(r,e,t){let n=X.getState().ai.providers,i=r.selectEl;e={model:e.model,modelRef:pc(e.model,e.modelRef)},r.addOption(km,km);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 u of l.models){let d=`${l.id??l.name}/${u.name}:${s++}`;o.set(d,{providerId:l.id,modelName:u.name}),c.createEl("option",{value:d,text:u.name})}}let a=dee(e,o);if(a)r.setValue(a);else{let l=e.modelRef?`${e.modelRef.providerId}/${e.modelRef.name}`:e.model;r.addOption(XE,`(missing) ${l}`);let c=Array.from(i.options).find(u=>u.value===XE);c&&(c.disabled=!0),r.setValue(XE)}r.onChange(l=>{if(l===XE)return;if(l===km){t({model:km,modelRef:void 0});return}let c=o.get(l);c&&t({model:c.modelName,modelRef:c.providerId?{providerId:c.providerId,name:c.modelName}:void 0})})}function dee(r,e){if(!r.model||r.model===km)return km;let t=r.modelRef?void 0:Gd(r.model,{silent:!0}),n=r.modelRef??(t&&{providerId:t.provider.id,name:t.model.name});if(n){for(let[i,o]of e)if(o.providerId===n.providerId&&o.modelName===n.name)return i}}ro();var JE=class extends _i.Modal{constructor(t,n){super(t);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 Ui(this.settings.systemPrompt)}resolve(t){this.isResolved||(this.isResolved=!0,this.resolvePromise(t))}cloneSettings(t){return{...t,promptTemplate:{...t.promptTemplate},modelParameters:{...t.modelParameters}}}restoreOriginal(){let t=this.cloneSettings(this.originalSettings);Object.assign(this.settings,t),this.settings.promptTemplate=t.promptTemplate,this.settings.modelParameters=t.modelParameters}display(){let t=this.contentEl.createEl("h2");t.addClass("qa-clickable-modal-title"),t.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 ar.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={}),xU(this.contentEl,this.settings.modelParameters,pc(this.settings.model,this.settings.modelRef)??this.settings.model,()=>this.reload())),this.addSystemPromptSetting(this.contentEl),this.addButtonBar(this.contentEl)}addButtonBar(t){let n=t.createDiv({cls:"qa-command-button-row"});new _i.ButtonComponent(n).setButtonText("Cancel").onClick(()=>{this.restoreOriginal(),this.resolve(null),this.close()}),new _i.ButtonComponent(n).setButtonText("Save").setCta().onClick(()=>{this.resolve(this.settings),this.close()})}reload(){this.contentEl.empty(),this.display()}addPromptTemplateSetting(t){let n=X.getState().ai.promptTemplatesFolderPath,i=Bo(this.app,n).map(o=>o.name);new _i.Setting(t).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 si(this.app,o.inputEl,i)})}addModelSetting(t){new _i.Setting(t).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(n=>{ZE(n,this.settings,i=>{this.settings.model=i.model,this.settings.modelRef=i.modelRef,this.reload()})})}addOutputVariableNameSetting(t){new _i.Setting(t).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(t){new _i.Setting(t).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 _i.TextAreaComponent(t);s.inputEl.addClass("qa-ai-prompt-textarea"),s.inputEl.setAttribute("aria-label","System prompt");let a=QE(t,s.inputEl,this.settings.systemPrompt??""),l=(0,_i.debounce)(()=>{i.innerText=`Estimated tokens: ${this.systemPromptTokenLength}`},50);s.setValue(this.settings.systemPrompt).onChange(c=>{this.settings.systemPrompt=c,a(c),l()}),l()}addShowAdvancedSettingsToggle(t){new _i.Setting(t).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 pee=L('<li class="quickAddCommandListItem"><span class="quickAddCommandLabel"> </span> <div class="quickAddCommandControls"><!> <!> <!></div></li>');function NF(r,e){pe(e,!0);var t=pee(),n=B(t),i=le(n,!0),o=_(n,2),s=B(o);{let c=F(()=>`Configure ${e.command.name}`);Lt(s,{iconId:"settings",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onConfigureOpenFile(e.command)})}var a=_(s,2);{let c=F(()=>`Delete ${e.command.name}`);Lt(a,{iconId:"trash-2",get label(){return h(c)},extraClass:"clickable",onclick:()=>e.onDeleteCommand(e.command.id)})}var l=_(a,2);{let c=F(()=>`Reorder ${e.command.name}`);cn(l,{get label(){return h(c)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.startDrag},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}N(o),N(t),re(()=>ae(i,e.command.name)),M(r,t),fe()}var ba=require("obsidian");eT();vr();var tT=class extends ba.Modal{constructor(t,n){super(t);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(t){this.isResolved||(this.resolvePromise(t),this.isResolved=!0)}display(){this.containerEl.addClass("quickAddModal","openFileCommandSettingsModal"),this.contentEl.empty();let t=this.contentEl.createEl("h2");t.textContent="Open file command settings",t.addClass("qa-modal-title"),this.addFilePathSetting(),this.addOpenLocationSetting(),this.addFocusSetting(),this.addButtonBar()}addFilePathSetting(){new ba.Setting(this.contentEl).setName("File path").setDesc("Path to the file. Supports formatting like {{DATE}}, {{VALUE}}, etc.").addText(t=>t.setPlaceholder("{{DATE}}todo.md").setValue(this.command.filePath).onChange(n=>{this.command.filePath=n,this.command.name=`Open file: ${n}`}))}addOpenLocationSetting(){let t=[{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 ba.Setting(this.contentEl).setName("Where to open").setDesc("Choose tab, split, window, or sidebar").addDropdown(n=>{for(let{value:i,label:o}of t)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(t){switch(t){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 ba.Setting(this.contentEl).setName("Split direction").setDesc("How to arrange the new pane relative to the current one").addDropdown(t=>{t.addOption("vertical","Split right").addOption("horizontal","Split down").setValue(this.command.direction??"vertical").onChange(n=>{this.command.direction=n})})}addFocusSetting(){new ba.Setting(this.contentEl).setName("Focus opened file").setDesc("Bring the opened file to the foreground").addToggle(t=>t.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 t=this.contentEl.createDiv({cls:"qa-command-button-row qa-command-button-row-compact"});new ba.ButtonComponent(t).setButtonText("Cancel").onClick(()=>{this.resolveWithGuard(null),this.close()}),new ba.ButtonComponent(t).setButtonText("Save").setCta().onClick(()=>{this.resolveWithGuard(this.command),this.close()})}reload(){this.display()}};Id();un();var fee=L('<li class="quickAddCommandListItem conditionalCommand svelte-p3uofi"><div class="quickAddCommandLabel"><div class="conditionalSummary svelte-p3uofi"> </div> <div class="conditionalBranches svelte-p3uofi"><span> </span> <span> </span></div></div> <div class="quickAddCommandControls"><!> <!> <!> <!> <!></div></li>'),mee={hash:"svelte-p3uofi",code:".conditionalCommand.svelte-p3uofi {flex-wrap:wrap;}.conditionalSummary.svelte-p3uofi {font-weight:600;margin-bottom:4px;}.conditionalBranches.svelte-p3uofi {display:flex;gap:12px;font-size:0.9em;opacity:0.8;}"};function LF(r,e){pe(e,!0),We(r,mee);let t=F(()=>Pf(e.command.condition)),n=F(()=>Ht(e.command.thenCommands).length),i=F(()=>Ht(e.command.elseCommands).length);var o=fee(),s=B(o),a=B(s),l=le(a,!0),c=_(a,2),u=B(c),d=le(u),p=_(u,2),f=le(p);N(c),N(s);var m=_(s,2),g=B(m);{let w=F(()=>`Edit condition for ${h(t)}`);Lt(g,{iconId:"settings",get label(){return h(w)},extraClass:"clickable",onclick:()=>e.onConfigureCondition(e.command)})}var v=_(g,2);{let w=F(()=>`Edit then branch for ${h(t)}`);Lt(v,{iconId:"corner-down-right",get label(){return h(w)},extraClass:"clickable",onclick:()=>e.onEditThenBranch(e.command)})}var y=_(v,2);{let w=F(()=>`Edit else branch for ${h(t)}`);Lt(y,{iconId:"corner-down-left",get label(){return h(w)},extraClass:"clickable",onclick:()=>e.onEditElseBranch(e.command)})}var b=_(y,2);{let w=F(()=>`Delete ${e.command.name}`);Lt(b,{iconId:"trash-2",get label(){return h(w)},extraClass:"clickable",onclick:()=>e.onDeleteCommand(e.command.id)})}var x=_(b,2);{let w=F(()=>`Reorder ${e.command.name}`);cn(x,{get label(){return h(w)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.startDrag},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}N(m),N(o),re(()=>{ae(l,h(t)),ae(d,`Then: ${h(n)??""}`),ae(f,`Else: ${h(i)??""}`)}),M(r,o),fe()}var hee=L('<ol class="quickAddCommandList svelte-16btmqx"></ol>'),gee={hash:"svelte-16btmqx",code:".quickAddCommandList.svelte-16btmqx {display:grid;grid-template-columns:auto;width:auto;border:0 solid black;overflow-y:auto;height:auto;margin-bottom:8px;padding:20px;}"};function VF(r,e){let t=Ku();pe(e,!0),We(r,gee);let n=ne(e,"commands",31,()=>ut([])),i=F(()=>{let O=new Set;return Array.isArray(n())?n().filter(H=>{if(typeof H!="object"||H===null)return!1;let ce=H.id;return typeof ce!="string"||ce===""||O.has(ce)?!1:(O.add(ce),!0)}):[]}),o=`command:${t}`,s=TU.Platform.isMobile,a=gm(),l=F(()=>!s&&!a.armed),c=Ce(void 0),u=O=>O,d=O=>O,p=O=>O,f=O=>O,m=O=>O,g=O=>O;function v(){e.saveCommands(Xc(n()))}let y=null;function b(O){a.markStarted();let H=O.detail.items;y=fm(H,O.detail.info.id)??y,n(qi(H))}function x(O){let H=qi(O.detail.items),ce=O.detail.info.id;y?.item.id===ce&&!H.some(te=>te.id===ce)&&(H=[...H],H.splice(Math.min(y.index,H.length),0,y.item)),y=null,n(H),O.detail.info.source===Fn.POINTER&&a.reset(),v()}let w=()=>{a.startDrag()};function T(O,H){let ce=document.activeElement?.getAttribute("aria-label"),te=qi(h(i)),z=mm(te,O,H);if(!z)return;let G=z.findIndex(xe=>xe.id===O),ie=z[G];n(z),v(),Hd(`Moved ${jd(ie)} to position ${G+1} of ${z.length}`),ce&&vm(h(c),ce)}function C(O){n(Wq(h(i),O)),v()}async function S(O){await e.onConfigureCondition?.(O)&&C(O)}async function A(O){await e.onEditThenBranch?.(O)&&C(O)}async function D(O){await e.onEditElseBranch?.(O)&&C(O)}async function P(O){let H=await U(O.choice)?.waitForClose;if(!H)return;let ce={...O,choice:H,name:H.name};C(ce)}function U(O){switch(O.type){case"Template":return new ym(e.app,O,e.plugin);case"Capture":return new em(e.app,O,e.plugin);default:break}}async function K(O){let H=await Lo(O,e.app);if(!H){I.logWarning(`${O.name} could not be loaded.`);return}let ce=H.settings??{};new KE(e.app,O,ce,()=>v()).open()}async function W(O){await new JE(e.app,O).waitForClose&&C(O)}async function ee(O){let H=await new tT(e.app,O).waitForClose;H&&C(H)}var me=hee();Ot(me,21,()=>qi(h(i)),O=>O.id,(O,H)=>{var ce=or(),te=Te(ce);{var z=Oe=>{{let Ee=F(()=>u(h(H)));xF(Oe,{get command(){return h(Ee)},get dragDisabled(){return h(l)},startDrag:w,get onDeleteCommand(){return e.deleteCommand},onUpdateCommand:C,onMoveUp:()=>T(h(H).id,-1),onMoveDown:()=>T(h(H).id,1)})}},G=Oe=>{{let Ee=F(()=>d(h(H)));EF(Oe,{get command(){return h(Ee)},get dragDisabled(){return h(l)},startDrag:w,get onDeleteCommand(){return e.deleteCommand},onConfigureChoice:P,onMoveUp:()=>T(h(H).id,-1),onMoveDown:()=>T(h(H).id,1)})}},ie=Oe=>{{let Ee=F(()=>p(h(H)));TF(Oe,{get command(){return h(Ee)},get dragDisabled(){return h(l)},startDrag:w,get onDeleteCommand(){return e.deleteCommand},onConfigureScript:K,onMoveUp:()=>T(h(H).id,-1),onMoveDown:()=>T(h(H).id,1)})}},xe=Oe=>{{let Ee=F(()=>f(h(H)));$F(Oe,{get command(){return h(Ee)},get dragDisabled(){return h(l)},startDrag:w,get onDeleteCommand(){return e.deleteCommand},onConfigureAssistant:W,onMoveUp:()=>T(h(H).id,-1),onMoveDown:()=>T(h(H).id,1)})}},ue=Oe=>{{let Ee=F(()=>m(h(H)));NF(Oe,{get command(){return h(Ee)},get dragDisabled(){return h(l)},startDrag:w,get onDeleteCommand(){return e.deleteCommand},onConfigureOpenFile:ee,onMoveUp:()=>T(h(H).id,-1),onMoveDown:()=>T(h(H).id,1)})}},be=Oe=>{{let Ee=F(()=>g(h(H)));LF(Oe,{get command(){return h(Ee)},get dragDisabled(){return h(l)},startDrag:w,get onDeleteCommand(){return e.deleteCommand},onConfigureCondition:S,onEditThenBranch:A,onEditElseBranch:D,onMoveUp:()=>T(h(H).id,-1),onMoveDown:()=>T(h(H).id,1)})}},Ke=Oe=>{CF(Oe,{get command(){return h(H)},get dragDisabled(){return h(l)},startDrag:w,get onDeleteCommand(){return e.deleteCommand},onMoveUp:()=>T(h(H).id,-1),onMoveDown:()=>T(h(H).id,1)})};Y(te,Oe=>{h(H).type==="Wait"?Oe(z):h(H).type==="NestedChoice"?Oe(G,1):h(H).type==="UserScript"?Oe(ie,2):h(H).type==="AIAssistant"?Oe(xe,3):h(H).type==="OpenFile"?Oe(ue,4):h(H).type==="Conditional"?Oe(be,5):Oe(Ke,-1)})}M(O,ce)}),N(me),Ci(me,O=>j(c,O),()=>h(c)),Jt(me,(O,H)=>pm?.(O,H),()=>hm({items:h(i),dragDisabled:h(l),type:o,resolveLabel:jd})),Po("consider",me,b),Po("finalize",me,x),M(r,me),fe()}ho();BF();qF();UF();HF();zF();WF();jF();GF();YF();KF();var QF=new Map(Object.entries({Copy:Sm,Cut:_m,Paste:Am,"Paste with format":Im,"Select active line":Dm,"Select link on active line":Fm,"Move cursor to file start":Pm,"Move cursor to file end":Mm,"Move cursor to line start":$m,"Move cursor to line end":Om}));function SU(r){return ut(r)}$l();vr();Ss();var Gy=class extends Pn{constructor(t,n){super(t,"Obsidian");this.generateId=()=>this.id=Kt();this.commandId=n}};$l();vr();var rT=class extends Pn{constructor(e,t){super(e,"Choice"),this.choiceId=t}};$l();vr();var nT=class extends Pn{constructor(e){super("Wait","Wait"),this.time=e}};vr();$l();var iT=class extends Pn{constructor(e){super(e.name,"NestedChoice"),this.choice=e}};Ss();var wa=class{constructor(e,t){this.id=Kt(),this.name=e,this.type=t,this.command=!1,this.onePageInput=void 0}};Xe();function oT(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 e=r.property;if(e.kind==="prompt")return{property:{kind:"prompt"},action:r.action,createIfMissing:r.createIfMissing};if(e.kind==="named"&&"format"in e&&typeof e.format=="string")return{property:{kind:"named",format:e.format},action:r.action,createIfMissing:r.createIfMissing};throw new Error("Invalid property capture selector.")}var Rm=class extends wa{constructor(e){super(e,"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:!1,considerSubsections:!1,createIfNotFound:!1,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=Cn(),this.templater={afterCapture:"none"}}static Load(e){let t=e;return t.propertyCapture!==void 0&&(t.propertyCapture=oT(t.propertyCapture)),t.activeFileWritePosition!=="cursor"&&t.activeFileWritePosition!=="top"&&t.activeFileWritePosition!=="bottom"&&(t.activeFileWritePosition="cursor"),typeof t.captureToCanvasNodeId!="string"&&(t.captureToCanvasNodeId=""),t.insertBefore||(t.insertBefore={enabled:!1,before:"",createIfNotFound:!1,createIfNotFoundLocation:"top"}),t.captureToActiveFile&&t.prepend&&!t.insertAfter?.enabled&&!t.insertBefore.enabled&&!t.newLineCapture?.enabled&&(t.activeFileWritePosition!=="top"&&(t.activeFileWritePosition="bottom"),t.prepend=!1),t.templater||(t.templater={afterCapture:"none"}),t.templater.afterCapture!=="wholeFile"&&(t.templater.afterCapture="none"),t.insertAfter&&!t.insertAfter.blankLineAfterMatchMode&&(t.insertAfter.blankLineAfterMatchMode="auto"),t.insertAfter&&t.insertAfter.inline===void 0&&(t.insertAfter.inline=!1),t.insertAfter&&t.insertAfter.replaceExisting===void 0&&(t.insertAfter.replaceExisting=!1),t.insertAfter&&t.insertAfter.promptHeading===void 0&&(t.insertAfter.promptHeading=!1),t.insertAfter?.createIfNotFoundLocation===vs&&(t.insertAfter.createIfNotFound&&!t.insertAfter.orderBy&&(t.insertAfter.orderBy={by:"insertion",direction:"desc",unparseable:"bottom"}),t.insertAfter.inline=!1),t}};var ou=class extends wa{constructor(e){super(e,"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=Cn(),this.fileExistsBehavior={kind:"prompt"}}static Load(e){return e}};var _U=require("obsidian");Xe();zg();function sT(r){let e=[];for(let t of r.vault.getFiles())kA.test(t.path)?e.push({file:t,isMarkdown:!1}):Nt.test(t.path)&&vee(r,t)&&e.push({file:t,isMarkdown:!0});return e}function vee(r,e){return r.metadataCache.getFileCache(e)?.sections?.some(n=>n.type==="code")??!1}function AU(r,e,t){let n=e.find(s=>s.file.path===t);if(n)return n;let i=e.find(s=>!s.isMarkdown&&s.file.basename===t);if(i)return i;let o=r.vault.getAbstractFileByPath(t);if(o instanceof _U.TFile){if(kA.test(o.path))return{file:o,isMarkdown:!1};if(Nt.test(o.path))return{file:o,isMarkdown:!0}}return null}async function Yy(r,e){let t=await r.vault.read(e),{code:n,error:i}=ll(t);return n!==null&&n.length>0?null:i??"No ```js code block found in the note."}function XF(r){return r.isMarkdown?r.file.path:r.file.basename}$l();vr();var Ky=class extends Pn{constructor(e,t){super(e,"UserScript"),this.path=t,this.settings={}}};Wd();var IU=require("obsidian");function aT(r){let t=new IU.Notice("",1e4).messageEl;t.replaceChildren(),t.createDiv({text:"No scripts found",cls:"quickadd-notice-title"});let n=t.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"),Kx(n,Ms.userScripts,"View documentation")}Ol();Ie();$l();vr();dt();ro();var lT=class extends Pn{constructor(){super("AI Assistant","AIAssistant");let e=X.getState().ai;this.model=e.defaultModel;let t=pc(e.defaultModel,e.defaultModelRef);this.modelRef=t?{...t}:void 0,this.systemPrompt=e.defaultSystemPrompt,this.outputVariableName="output",this.promptTemplate={enable:!1,name:""},this.modelParameters={}}};dt();vr();Ss();eT();var cT=class{constructor(e="{{DATE}}.md",t=!1,n,i,o=!0){this.filePath=e;this.type="OpenFile";this.id=Kt();this.openInNewTab=t,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}}};ht();$l();vr();function yee(){return{mode:"variable",variableName:"",operator:"isTruthy",valueType:"string"}}function bee(r){return r.mode==="variable"?{...r}:{...r}}var uT=class extends Pn{constructor(e){super(e?.name??"If condition","Conditional"),this.condition=e?.condition?bee(e.condition):yee(),this.thenCommands=e?.thenCommands?[...e.thenCommands]:[],this.elseCommands=e?.elseCommands?[...e.elseCommands]:[]}};Ml();un();var wee=L(`<div class="qaDataUnreadable svelte-ktqmtm"><div class="qaDataUnreadableHead svelte-ktqmtm"><!> <span class="qaDataUnreadableTitle svelte-ktqmtm"> </span></div> <p class="qaDataUnreadableBody svelte-ktqmtm">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-ktqmtm">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>`),Cee={hash:"svelte-ktqmtm",code:".qaDataUnreadable.svelte-ktqmtm {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-ktqmtm {display:flex;align-items:center;gap:8px;color:var(--text-warning, var(--text-normal));}.qaDataUnreadableTitle.svelte-ktqmtm {font-weight:var(--font-semibold);color:var(--text-normal);}.qaDataUnreadableBody.svelte-ktqmtm {margin:8px 0 0;color:var(--text-muted);font-size:var(--font-ui-small, 13px);max-width:68ch;}"};function JF(r,e){We(r,Cee);var t=wee(),n=B(t),i=B(n);Et(i,{iconId:"alert-triangle",size:16});var o=_(i,2),s=le(o);N(n),Gr(4),N(t),re(()=>ae(s,`QuickAdd couldn't read ${e.what??""}`)),M(r,t)}var Lm=class{constructor(e){this.obsidianCommands=[];this.scriptCandidates=[];this.commandListHandle=null;this.commandListProps=null;this.containerEl=null;this.unreadableCardHandle=null;this.app=e.app,this.plugin=e.plugin,this.unreadable=sr(e.commands),this.commandsRef=SF(e.commands).commands,this.choices=e.choices,this.onCommandsChange=e.onCommandsChange,this.conditionalHandlers=e.conditionalHandlers,this.loadObsidianCommands(),this.loadScriptCandidates()}render(e){return this.destroy(),this.containerEl=e,e.empty(),e.addClass("quickAddCommandEditor"),this.unreadable?(this.renderUnreadableCard(e),!1):this.renderCommandList(e)?(this.renderCommandBar(e),this.renderAddObsidianCommandSetting(e),this.renderAddEditorCommandSetting(e),this.renderAddUserScriptSetting(e),this.renderAddChoiceSetting(e),!0):!1}renderUnreadableCard(e){let t=e.createDiv("commandList");this.unreadableCardHandle=Li(t,JF,{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(e=>{let t=this.app.commands.commands[e];this.obsidianCommands.push(new Gy(t.name,t.id))})}loadScriptCandidates(){this.scriptCandidates=sT(this.app)}renderCommandList(e){let t=e.createDiv("commandList");return this.commandListProps=SU({app:this.app,plugin:this.plugin,commands:this.commandsRef,deleteCommand:async n=>{let i=this.commandsRef.find(a=>a.id===n);if(!i)throw I.logError("command not found"),new Error("command not found");if(!await Si.Prompt(this.app,"Are you sure you wish to delete this command?",`If you click yes, you will delete '${i.name}'.`))return;if(!await jE(this.app,i)){new Hi.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=Li(t,VF,this.commandListProps,{what:"this macro's commands"}),this.commandListHandle.ok}renderCommandBar(e){let t=e.createDiv("quickCommandContainer");this.addChoiceButton(t,"Capture",Rm),this.addChoiceButton(t,"Template",ou),this.addCommandButton(t,"file-search","Add open file command",()=>new cT),this.addCommandButton(t,"clock","Add wait command",()=>new nT(100)),this.addCommandButton(t,"git-branch","Add conditional command",()=>new uT),X.getState().disableOnlineFeatures||this.addCommandButton(t,"bot","Add AI Assistant command",()=>new lT)}renderAddObsidianCommandSetting(e){let t,n=()=>{let i=t.getValue(),o=this.obsidianCommands.find(a=>a.name===i);if(!o){I.logError(`Could not find Obsidian command with name "${i}"`);return}let s=new Gy(o.name,o.commandId);s.generateId(),this.addCommand(s),t.setValue("")};new Hi.Setting(e).setName("Obsidian command").setDesc("Add an Obsidian command").addText(i=>{t=this.configureSuggestedInput(i,"Obsidian command",this.obsidianCommands.map(o=>o.name),n)}).addButton(i=>i.setCta().setButtonText("Add").onClick(n))}renderAddEditorCommandSetting(e){let t,n=()=>{let i=QF.get(t.getValue());if(!i)throw I.logError("invalid editor command type"),new Error("invalid editor command type");this.addCommand(new i),t.setValue("")};new Hi.Setting(e).setName("Editor commands").setDesc("Add editor command").addDropdown(i=>{t=i,i.selectEl.addClass("qa-command-sequence-input"),i.addOption("","Select command");for(let o of QF.keys())i.addOption(o,o)}).addButton(i=>i.setCta().setButtonText("Add").onClick(n))}renderAddUserScriptSetting(e){let t,n=null,i=async()=>{this.loadScriptCandidates();let o=t.getValue().trim();if(!o)return;let s=dd(o).basename??o,a=AU(this.app,this.scriptCandidates,s);if(!a){new Hi.Notice(`QuickAdd: No script or js-block note named "${o}" found.`);return}if(a.isMarkdown){let l=await Yy(this.app,a.file);if(l){new Hi.Notice(`QuickAdd: "${a.file.path}" \u2014 ${l}`);return}}this.addCommand(new Ky(o,a.file.path)),t.setValue(""),n&&n.buttonEl.addClass("qa-hidden")};new Hi.Setting(e).setName("User scripts").setDesc("Add a .js file or a note with a ```js code block - type the name or click Browse").addText(o=>{t=this.configureSuggestedInput(o,"Start typing script name...",this.scriptCandidates.map(XF),i)}).addButton(o=>o.setButtonText("Browse").setTooltip("Browse and select a script (.js file or note)").onClick(async()=>{let s=await this.showScriptPicker();if(s){let a=s.isMarkdown?s.file.path:s.file.basename;this.addCommand(new Ky(a,s.file.path))}})).addButton(o=>{n=o,o.setButtonText("Add").setCta().onClick(()=>{i()}),o.buttonEl.addClass("qa-hidden")}),t.onChange(o=>{n&&n.buttonEl.toggleClass("qa-hidden",o.trim().length===0)})}renderAddChoiceSetting(e){let t,n=()=>{let i=t.getValue(),o=this.choices.find(s=>s.name===i);if(!o){new Hi.Notice(`QuickAdd: No choice named "${i}".`);return}this.addCommand(new rT(o.name,o.id)),t.setValue("")};new Hi.Setting(e).setName("Choices").setDesc("Add existing choice").addText(i=>{t=this.configureSuggestedInput(i,"Choice",this.choices.map(o=>o.name),n)}).addButton(i=>i.setCta().setButtonText("Add").onClick(n))}configureSuggestedInput(e,t,n,i){return e.inputEl.addClass("qa-command-sequence-input"),e.setPlaceholder(t),new si(this.app,e.inputEl,n),e.inputEl.addEventListener("keypress",o=>{o.key==="Enter"&&i()}),e}addChoiceButton(e,t,n){new Hi.ButtonComponent(e).setButtonText(t).setTooltip(`Add ${t} choice`).onClick(()=>{let o=new n(`Untitled ${t} Choice`);this.addCommand(new iT(o))})}addCommandButton(e,t,n,i){new Hi.ButtonComponent(e).setIcon(t).setTooltip(n).onClick(()=>this.addCommand(i()))}async showScriptPicker(){if(this.loadScriptCandidates(),this.scriptCandidates.length===0)return aT(this.app),null;let e=this.scriptCandidates.map(o=>o.file.path),t=this.scriptCandidates.map(o=>XF(o)),n=await Mr.Suggest(this.app,t,e,{placeholder:"Select a script (.js file or note with a ```js block)",emptyStateText:"No scripts found in your vault"});if(!n)return null;let i=this.scriptCandidates.find(o=>o.file.path===n);if(!i)return null;if(i.isMarkdown){let o=await Yy(this.app,i.file);if(o)return new Hi.Notice(`QuickAdd: "${i.file.path}" \u2014 ${o}`),null}return i}addCommand(e){this.commandsRef=[...this.commandsRef,e],this.emitCommandsChanged()}emitCommandsChanged(){this.commandListProps&&(this.commandListProps.commands=[...this.commandsRef]),this.onCommandsChange?.(this.commandsRef)}};var Mn=require("obsidian");Id();Ol();function PU(r){return r.mode==="variable"?{...r}:{...r}}function xee(){return{mode:"variable",variableName:"",operator:"isTruthy",valueType:"boolean"}}function Eee(){return{mode:"script",scriptPath:""}}var dT=class extends Mn.Modal{constructor(t,n){super(t);this.isResolved=!1;this.scriptCandidates=[];this.originalCommand=n,this.workingCommand={...n,condition:PU(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(t){this.isResolved||(this.isResolved=!0,this.resolvePromise(t))}loadScriptCandidates(){this.scriptCandidates=sT(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 Mn.Setting(this.contentEl).setName("Condition type").setDesc("Choose how this condition should be evaluated.").addDropdown(t=>{t.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"?xee():Eee(),this.reload())})})}renderVariableConfiguration(t){this.renderVariableNameSetting(t),this.renderOperatorSetting(t),this.renderValueTypeSetting(t),Nc(t.operator)&&this.renderExpectedValueSetting(t)}renderVariableNameSetting(t){new Mn.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(t.variableName).onChange(i=>{t.variableName=i.trim()}))}renderOperatorSetting(t){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 Mn.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(t.operator),i.onChange(o=>{t.operator=o,t.valueType=A2(t.operator),Nc(t.operator)||delete t.expectedValue,this.reload()})})}renderValueTypeSetting(t){new Mn.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(t.valueType).onChange(i=>{t.valueType=i,this.reload()})})}renderExpectedValueSetting(t){if(t.valueType==="boolean"){new Mn.Setting(this.contentEl).setName("Expected value").setDesc("Choose true or false.").addDropdown(n=>{n.addOption("true","True").addOption("false","False").setValue(t.expectedValue??"true").onChange(i=>{t.expectedValue=i})});return}new Mn.Setting(this.contentEl).setName("Expected value").setDesc("Value to compare against.").addText(n=>{n.setPlaceholder("Enter comparison value").setValue(t.expectedValue??"").onChange(i=>{t.expectedValue=i})})}renderScriptConfiguration(t){this.renderScriptPathSetting(t),this.renderScriptExportSetting(t)}renderScriptPathSetting(t){let n;new Mn.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(t.scriptPath).onChange(o=>{t.scriptPath=o.trim()})}).addButton(i=>i.setButtonText("Browse").setTooltip("Select a script (.js file or note)").onClick(async()=>{if(this.loadScriptCandidates(),this.scriptCandidates.length===0){aT(this.app);return}let o=this.scriptCandidates.map(l=>l.file.path),s=await Mr.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 Yy(this.app,a.file);if(l){new Mn.Notice(`QuickAdd: "${a.file.path}" \u2014 ${l}`);return}}t.scriptPath=s,n.setValue(s)}))}renderScriptExportSetting(t){new Mn.Setting(this.contentEl).setName("Export name").setDesc("Optional export or member to call (use :: to access nested members).").addText(n=>n.setPlaceholder("default").setValue(t.exportName??"").onChange(i=>{t.exportName=i.trim()||void 0}))}renderButtonBar(){let t=this.contentEl.createDiv({cls:"qa-command-button-row"});new Mn.ButtonComponent(t).setButtonText("Cancel").onClick(()=>{this.resolve(null),this.close()}),new Mn.ButtonComponent(t).setCta().setButtonText("Save").onClick(()=>{this.validateCondition()&&(this.applyChanges(),this.resolve(this.originalCommand),this.close())})}validateCondition(){let t=this.workingCommand.condition;return t.mode==="variable"?t.variableName.trim()?!0:(new Mn.Notice("QuickAdd: Enter a variable name before saving."),!1):t.scriptPath.trim()?!0:(new Mn.Notice("QuickAdd: Enter a script path before saving."),!1)}applyChanges(){this.originalCommand.condition=PU(this.workingCommand.condition);let t=Pf(this.originalCommand.condition);this.originalCommand.name=`If ${t}`}};var Vm=require("obsidian");Jr();un();var pT=class extends Vm.Modal{constructor(t){super(t.app);this.commandEditor=null;this.isResolved=!1;this.plugin=t.plugin,this.choices=t.choices,this.conditionalHandlers=t.conditionalHandlers,this.workingCommands=Ve(t.commands),this.waitForClose=new Promise(n=>{this.resolvePromise=n}),this.display(t.title),this.open()}onClose(){super.onClose(),this.commandEditor?.destroy(),this.isResolved||this.resolve(null)}resolve(t){this.isResolved||(this.isResolved=!0,this.resolvePromise(t))}display(t){this.containerEl.addClass("quickAddModal","conditionalBranchModal"),this.contentEl.empty(),this.contentEl.createEl("h2",{text:t}).addClass("qa-modal-title");let i=this.contentEl.createDiv("branchCommandEditor");this.commandEditor=new Lm({app:this.app,plugin:this.plugin,commands:this.workingCommands,choices:this.choices,onCommandsChange:s=>{this.workingCommands=s},conditionalHandlers:this.conditionalHandlers});let o=this.commandEditor.render(i);this.renderButtonBar(o)}renderButtonBar(t){let n=this.contentEl.createDiv({cls:"qa-command-button-row"});if(!t){new Vm.ButtonComponent(n).setCta().setButtonText("Close").onClick(()=>{this.resolve(null),this.close()});return}new Vm.ButtonComponent(n).setButtonText("Cancel").onClick(()=>{this.resolve(null),this.close()}),new Vm.ButtonComponent(n).setCta().setButtonText("Save").onClick(()=>{this.resolve(Ht(this.workingCommands)),this.close()})}};var fT=require("obsidian");bt();bs();function Tee(r){let e=r.trim();return e||void 0}function kee(r){return(typeof r.icon=="string"?r.icon.trim():"")||hf(r.type)}function mT(r,e,t,n){let i=hf(t.type),o=new fT.Setting(e).setName("Icon").setDesc(`Lucide/Obsidian icon id. Leave empty to use ${i}.`);o.settingEl.addClass("qa-choice-icon-setting");let s=er(e,"span");s.classList.add("qa-choice-icon-setting-preview"),s.setAttribute("aria-hidden","true"),o.controlEl.appendChild(s);function a(){s.replaceChildren(),(0,fT.setIcon)(s,kee(t))}o.addText(l=>{l.setPlaceholder(i),l.setValue(typeof t.icon=="string"?t.icon:""),l.inputEl.addClass("qa-choice-icon-input"),l.inputEl.setAttribute("aria-label","Choice icon"),new si(r,l.inputEl,mE,50),l.onChange(c=>{let u=Tee(c);t.icon=u,n(u),a()})}),a()}bt();un();Ss();Kf();Kc();function See(r){let e=[],t=n=>{n.forEach(i=>{Ue(i)&&(i.type==="Multi"?t(et(i)):e.push(i))})};return t(Lr(r)),e}var hT=class extends Ls.Modal{constructor(t,n,i,o){super(t);this.choices=[];this.commandEditor=null;this.choice=i,this.macro=i.macro,this.choices=See(o),this.plugin=n,this.waitForClose=new Promise(s=>{this.resolvePromise=s}),this.display(),gE(this,"macro"),this.open()}onClose(){super.onClose(),this.resolvePromise(this.choice),this.commandEditor?.destroy(),this.commandEditor=null}display(){this.containerEl.addClass("quickAddModal","macroBuilder"),this.contentEl.empty(),this.addCenteredHeader(this.choice.name),this.addCommandEditor(),this.addOnePageInputSetting(),this.addDateOriginSetting(),this.addRunOnStartupSetting(),this.addCommandPaletteSettings(),this.addIconSetting()}addCenteredHeader(t){let n=this.contentEl.createEl("h2");n.addClass("qa-clickable-modal-title"),n.createEl("button",{cls:"qa-rename-title-button",text:t,attr:{type:"button","aria-label":`Rename ${t}`}}).addEventListener("click",()=>{(async()=>{try{let o=await ar.Prompt(this.app,`Update name for ${this.choice.name}`,this.choice.name,this.choice.name);if(!o)return;this.choice.name=o,iu(this.macro)&&(this.macro.name=o),this.reload()}catch{}})()})}addOnePageInputSetting(){new Ls.Setting(this.contentEl).setName("One-page input override").addDropdown(t=>{t.addOption("","Follow global setting").addOption("always","Always").addOption("never","Never").setValue(this.choice.onePageInput??"").onChange(n=>{this.choice.onePageInput=n==="always"||n==="never"?n:void 0})})}addDateOriginSetting(){let t=this.choice.dateOrigin,n=Al(t);if(new Ls.Setting(this.contentEl).setName(Qx).setDesc(Xx).addDropdown(i=>{for(let o of rE)i.addOption(o.value,o.label);i.setValue(n),i.onChange(o=>{iE(o)&&(this.choice.dateOrigin=oE({preset:o,previous:this.choice.dateOrigin}),this.reload())})}),n==="ask"){let i=t?.kind==="ask"?t.defaultValue:void 0;new Ls.Setting(this.contentEl).setName(Zx).setDesc(Jx).addDropdown(o=>{for(let s of sE(i))o.addOption(s.value,s.label);o.setValue(Cy(i)),o.onChange(s=>{let a=aE(s,i);this.choice.dateOrigin=a?{kind:"ask",defaultValue:a}:{kind:"ask"}})})}if(n==="custom"&&t?.kind==="relative"&&new Ls.Setting(this.contentEl).setName(by).setDesc(eE).addText(i=>{i.setValue(String(t.offset)),i.setPlaceholder("-2"),i.onChange(o=>{let s=this.choice.dateOrigin;if(s?.kind!=="relative")return;let a=o.trim();/^[+-]?\d+$/.test(a)&&(this.choice.dateOrigin={...s,offset:Number(a)})})}).addDropdown(i=>{for(let o of vy)i.addOption(o,o);i.setValue(t.unit),i.onChange(o=>{let s=this.choice.dateOrigin;s?.kind==="relative"&&yy(o)&&(this.choice.dateOrigin={...s,unit:o})})}),n==="variable"){let i=t?.kind==="variable"?t.name:"";new Ls.Setting(this.contentEl).setName(wy).setDesc(tE).addText(o=>{o.setValue(i),o.setPlaceholder("day"),o.onChange(s=>{this.choice.dateOrigin={kind:"variable",name:s}})})}}addCommandPaletteSettings(){new Ls.Setting(this.contentEl).setName(Ey).setDesc(lE).addToggle(t=>{t.setValue(this.choice.command).onChange(n=>{this.choice.command=n,this.reload()})}),this.choice.command&&ky(this.choice.dateOrigin)&&new Ls.Setting(this.contentEl).setName(Ty(this.choice.name)).setDesc(cE).addToggle(t=>{t.setValue(this.choice.pickDayCommand??!1).onChange(n=>{this.choice.pickDayCommand=n})})}addRunOnStartupSetting(){new Ls.Setting(this.contentEl).setName("Run on startup").setDesc("Execute this macro when Obsidian starts").addToggle(t=>t.setValue(this.choice.runOnStartup).onChange(n=>{this.choice.runOnStartup=n}))}addIconSetting(){mT(this.app,this.contentEl,this.choice,t=>{this.choice.icon=t})}reload(){this.commandEditor?.destroy(),this.commandEditor=null,this.display()}macroCommandsValue(){return Er(this.macro)}setMacroCommands(t){if(!iu(this.macro)){this.macro={id:Kt(),name:this.choice.name,commands:t},this.choice.macro=this.macro;return}this.macro.commands=t}addCommandEditor(){let t=this.contentEl.createDiv("macroBuilder__editor");this.commandEditor=new Lm({app:this.app,plugin:this.plugin,commands:this.macroCommandsValue(),choices:this.choices,onCommandsChange:n=>{this.setMacroCommands(n)},conditionalHandlers:this.buildConditionalHandlers()}),this.commandEditor.render(t)}buildConditionalHandlers(){return{configureCondition:t=>this.configureConditionalCondition(t),editThenBranch:t=>this.configureConditionalBranch(t,"then"),editElseBranch:t=>this.configureConditionalBranch(t,"else")}}async configureConditionalCondition(t){return await new dT(this.app,t).waitForClose!==null}async configureConditionalBranch(t,n){let i=n==="then"?"Then branch":"Else branch",s=await new pT({app:this.app,plugin:this.plugin,choices:this.choices,title:`Edit ${i} commands`,commands:n==="then"?t.thenCommands:t.elseCommands,conditionalHandlers:this.buildConditionalHandlers()}).waitForClose;return s?(n==="then"?t.thenCommands=s:t.elseCommands=s,!0):!1}};var su=require("obsidian");ur();var gT=class extends su.Modal{constructor(t,n){super(t);this.choice=n;this.didSubmit=!1;this.name=n.name,this.placeholder=n.placeholder??"",this.icon=typeof n.icon=="string"?n.icon:void 0,this.waitForClose=new Promise((i,o)=>{this.resolvePromise=i,this.rejectPromise=o}),this.containerEl.addClass("quickAddModal","qaMultiChoiceSettingsModal"),this.display(),this.open()}display(){this.contentEl.empty(),this.titleEl.setText("Edit folder"),new su.Setting(this.contentEl).setName("Name").addText(n=>{n.setValue(this.name).onChange(i=>{this.name=i})}),new su.Setting(this.contentEl).setName("Placeholder").setDesc("Shown in the choice picker search box when this folder opens. Leave blank to use the folder name.").addText(n=>{n.setPlaceholder("Defaults to the folder name"),n.setValue(this.placeholder).onChange(i=>{this.placeholder=i})}),mT(this.app,this.contentEl,{type:this.choice.type,icon:this.icon},n=>{this.icon=n});let t=this.contentEl.createDiv();new su.ButtonComponent(t).setButtonText("Save").setCta().onClick(()=>this.submit()),new su.ButtonComponent(t).setButtonText("Cancel").onClick(()=>this.cancel()),t.addClass("qa-modal-button-row")}submit(){this.didSubmit||(this.didSubmit=!0,this.close())}cancel(){this.close()}onClose(){if(super.onClose(),!this.didSubmit){this.rejectPromise(Rr());return}let t=this.placeholder.trim(),n={...this.choice,name:this.name.trim()||this.choice.name,placeholder:t||void 0,icon:this.icon};this.resolvePromise(n)}};dt();Ss();var vT=class{constructor(e){this.name=e,this.id=Kt(),this.commands=[]}};var Bm=class extends wa{constructor(t){super(t,"Macro");this.runOnStartup=!1;this.macro=new vT(t)}};var qm=class extends wa{constructor(t){super(t,"Multi");this.choices=[];this.collapsed=!1}addChoice(t){return this.choices.push(t),this}addChoices(t){return this.choices.push(...t),this}};un();bt();Jr();function eP(r,e){let t=Ve(r);for(let n of e)delete t[n];return t}Jr();Ml();Ie();la();var _ee={Template:ou,Capture:Rm,Macro:Bm,Multi:qm};function rP(r,e){let t=_ee[r];if(!t)throw new Error(`Unknown choice type: ${r}`);return new t(e)}function $U(r,e){let t=rP(r.type,`${r.name} (copy)`);if(r.type==="Multi"){let n=t,i=r;return Object.assign(n,eP(i,["id","name","choices"])),ml(i)?n.choices=et(i).filter(Ue).map(o=>$U(o,e)):n.choices=i.choices,n}return Object.assign(t,eP(r,["id","name"])),r.type==="Macro"&&(t.macro=Ve(r.macro),iU(t.macro),GE(t,e)),t}async function OU(r,e){let t=await Aee(e,r);return $U(r,{secretOptionNamesByPath:t,stripUnknownStringSettings:!0})}function RU(r){return r!==null&&typeof r=="object"}function tP(r,e){if(RU(r)){if(r.type==="UserScript"&&typeof r.path=="string"&&e.add(r.path),Array.isArray(r.thenCommands))for(let t of r.thenCommands)tP(t,e);if(Array.isArray(r.elseCommands))for(let t of r.elseCommands)tP(t,e);nP(r.choice,e)}}function nP(r,e){if(RU(r)){if(r.type==="Macro"){let t=Er(r.macro);if(Array.isArray(t))for(let n of t)tP(n,e)}if(r.type==="Multi"&&Array.isArray(r.choices))for(let t of r.choices)nP(t,e)}}async function Aee(r,e){let t=new Set;nP(e,t);let n=new Map;for(let i of t)try{if(Dr(i)||!await r.vault.adapter.exists(i))continue;let s=Hy(await r.vault.adapter.read(i),i);n.set(i,s.foundSecretOptions&&s.names.size===0?null:s.names)}catch(o){I.logWarning(`QuickAdd could not inspect user-script settings '${i}' while duplicating choice: ${o?.message??o}`)}return n}function Iee(r,e,t){let i={Template:()=>new ym(e,r,t),Capture:()=>new em(e,r,t),Macro:()=>new hT(e,t,r,X.getState().choices),Multi:()=>{}}[r.type];return typeof i=="function"?i():void 0}async function NU(r,e){let t=r.type==="Multi",n=r.type==="Macro",i=l=>{if(jo(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=nn(et(l));if(c.length===0)return"";let u=c.filter(f=>f.type==="Multi").length,d=c.length-u,p=[];return d>0&&p.push(`${d} ${d===1?"choice":"choices"}`),u>0&&p.push(`${u} ${u===1?"folder":"folders"}`),`Deleting this folder will also delete everything inside it: ${p.join(" and ")}.`},o=l=>sr(Er(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}'?`,t?i(r):"",n?o(r):""].filter(Boolean).join(" ");return await Si.Prompt(e,`Delete ${Ef(r.type)}`,s)?(n||t)&&!await jE(e,{type:"NestedChoice",choice:r})?(new MU.Notice(`Could not clear user script secrets. The ${Ef(r.type)} was not deleted.`),!1):!0:!1}async function LU(r,e,t){if(r.type==="Multi")try{return await new gT(e,r).waitForClose}catch{return}let n=Iee(r,e,t);if(!n)throw new Error("Invalid choice type");return await n.waitForClose}function VU(r){return{...r,command:!r.command}}var yT=class{constructor(e){this.plugin=e}enableCommand(e){this.plugin.addCommandForChoice(e)}disableCommand(e,t){t?this.plugin.removeCommandForChoice(e,t):this.plugin.removeCommandForChoice(e)}updateCommand(e,t){this.plugin.removeCommandForChoice(e),this.plugin.addCommandForChoice(t)}};function BU(r,e,t){if(!e||!t)return r;let n=Qy(r,e),i=Qy(r,t);if(!n||!i||i.type!=="Multi"||n.type==="Multi"&&(n.id===i.id||Dee(n).has(i.id)))return r;let{updated:o,removed:s}=Xy(r,e);return s?iP(o,t,s)??r:r}function qU(r,e){if(!e||r.some(i=>Ue(i)&&i.id===e))return r;let{updated:t,removed:n}=Xy(r,e);return n?[...t,n]:r}function Qy(r,e){for(let t of r){if(!Ue(t))continue;if(t.id===e)return t;let n=Qy(et(t),e);if(n)return n}}function Dee(r){let e=new Set,t=n=>{Ue(n)&&(e.add(n.id),et(n).forEach(t))};return et(r).forEach(t),e}function Xy(r,e){let t;return{updated:r.map(i=>{if(!Ue(i))return i;if(i.id===e){t=i;return}if(!ml(i))return i;let o=Xy(et(i),e);return o.removed&&(t=o.removed),o.removed?{...i,choices:o.updated}:i}).filter(Boolean),removed:t}}function iP(r,e,t){let n=!1,i=r.map(o=>{if(!Ue(o))return o;if(o.id===e&&o.type==="Multi"){if(jo(o))return o;n=!0;let a=o;return{...a,choices:[...et(a),t]}}if(!ml(o))return o;let s=iP(et(o),e,t);return s?(n=!0,{...o,choices:s}):o});return n?i:void 0}function oP(r,e,t){let n=r.findIndex(s=>Ue(s)&&s.id===e);if(n!==-1){let s=[...r];return s.splice(n+1,0,t),s}let i=!1,o=r.map(s=>{if(!Ue(s)||!ml(s))return s;let a=oP(et(s),e,t);return a?(i=!0,{...s,choices:a}):s});return i?o:void 0}function UU(r,e,t){if(!t)return[...r,e];let n=iP(r,t,e)??[...r,e];return Fee(n,t)}function sP(r,e,t){return r.map(n=>{if(!Ue(n)||n.type!=="Multi")return n;let i=n;return i.id===e?t(i):ml(i)?{...i,choices:sP(et(i),e,t)}:n})}function aP(r,e,t){return sP(r,e,n=>({...n,collapsed:t}))}function Fee(r,e){return aP(r,e,!1)}function HU(r,e,t){return sP(r,e,n=>({...n,choices:t}))}var Vs=require("obsidian");var bT=require("obsidian");function wT(r,e,t){return new bT.Setting(r).setName("API key").setDesc(t.hasLegacyKey?"Legacy API key detected. Select a SecretStorage entry to migrate.":"Select a secret from SecretStorage").addComponent(n=>new bT.SecretComponent(e,n).setValue(t.value).onChange(t.onChange))}var Tr=require("obsidian");ro();var zU=require("obsidian");dt();var CT=null,Pee=1440*60*1e3;async function lP(){if(CT&&Date.now()-CT.fetchedAt<Pee)return CT.data;if(X.getState().disableOnlineFeatures)throw new Error("Fetching models directory is disabled: Online features are turned off.");let e=await(await(0,zU.requestUrl)({url:"https://models.dev/api.json",method:"GET"})).json;return CT={data:e,fetchedAt:Date.now()},e}function Mee(r){for(let e of[r,`https://${r}`])try{let t=new URL(e).hostname.toLowerCase();if(t)return t}catch{}return""}function Zy(r){let e=r.toLowerCase(),t=Mee(r),n=i=>t===i||t.endsWith(`.${i}`);return n("openai.com")?"openai":n("openrouter.ai")?"openrouter":n("generativelanguage.googleapis.com")?"google":e.includes("anthropic")?"anthropic":n("groq.com")?"groq":n("together.ai")||n("together.xyz")?"togetherai":e.includes("huggingface")?"huggingface":e.includes("github")&&e.includes("models")?"github-models":e.includes("bedrock")||e.includes("aws")?"amazon-bedrock":e.includes("modelscope")?"modelscope":e.includes("dashscope")?"alibaba":n("fireworks.ai")?"fireworks-ai":e.includes("vercel")?"vercel":n("inference.net")?"inference":n("z.ai")||e.includes("zhipu")?"zhipuai":n("deepseek.com")?"deepseek":n("mistral.ai")?"mistral":e.includes("cerebras")?"cerebras":n("venice.ai")?"venice":n("upstage.ai")?"upstage":n("llama.com")?"llama":e.includes("morphllm")?"morph":n("inceptionlabs.ai")?"inception":e.includes("deepinfra")?"deepinfra":n("opencode.ai")?"opencode":n("inference.wandb.ai")?"wandb":n("githubcopilot.com")?"github-copilot":null}function $ee(r){let e=r.modalities?.output;if(Array.isArray(e)&&!e.includes("text"))return!1;let t=r.limit??{};if(typeof t.context=="number"&&t.context<=0||typeof t.output=="number"&&t.output<=1)return!1;let n=(r.family??"").toLowerCase(),i=r.id.toLowerCase();return!(n.includes("embedding")||i.includes("embedding"))}function WU(r){return r.filter($ee).map(e=>{let t={name:e.id,maxTokens:Math.max(1,Math.floor(e.limit?.context??128e3))};return typeof e.limit?.output=="number"&&e.limit.output>0&&(t.maxOutputTokens=Math.floor(e.limit.output)),typeof e.temperature=="boolean"&&(t.supportsTemperature=e.temperature),t})}async function jU(r,e){let t=Zy(r);if(!t)return e;let n;try{n=await lP()}catch{return e}let i=n[t]?.models;return i?e.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),a}):e}function Jy(r,e){let t=new Map(e.map(s=>[s.name,s])),n=r.map(s=>{let a=t.get(s.name);return a?{...s,maxTokens:a.maxTokens,maxOutputTokens:a.maxOutputTokens??s.maxOutputTokens,supportsTemperature:a.supportsTemperature??s.supportsTemperature}:s}),i=new Set(r.map(s=>s.name)),o=e.filter(s=>!i.has(s.name));return n.concat(o)}Ie();dt();var XU=require("obsidian");ro();Um();dt();var TT=128e3;async function kT(r,e){let t=r.modelSource??"providerApi";if(t==="modelsDev")return KU(r);if(t==="providerApi")return QU(r,e);try{return await QU(r,e)}catch(n){if(!Zy(r.endpoint))throw n;return KU(r,n)}}async function KU(r,e){try{let t=await lP(),n=Zy(r.endpoint);if(!n||!(n in t))throw new Error(`models.dev does not list a provider that matches ${r.endpoint}.`);let i=Object.values(t[n].models);return WU(i)}catch(t){throw e?new Error(`Provider API failed (${e.message}). Fallback to models.dev also failed: ${t.message}`):t}}async function QU(r,e){let{disableOnlineFeatures:t}=X.getState();if(t)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=e??r.apiKey??"",i=Eg(r),o=i==="anthropic"?await Hee(r,n):i==="gemini"?await zee(r,n):await Uee(r,n);if(!o.length)throw new Error("The provider's models endpoint did not include any usable models.");let s=await jU(r.endpoint,o);return Bee(r.endpoint,s)}function Bee(r,e){let t=Zy(r);if(t!=="openai"&&t!=="google"&&t!=="anthropic")return e;let n=new Map(Tg[t].map(i=>[i.name,i]));return e.map(i=>{let o=n.get(i.name);return o?{...i,maxTokens:i.maxTokens===TT?o.maxTokens:i.maxTokens,maxOutputTokens:i.maxOutputTokens??o.maxOutputTokens,supportsTemperature:i.supportsTemperature??o.supportsTemperature}:i})}async function cP(r,e,t){try{let n=await(0,XU.requestUrl)({url:e,headers:t,throw:!1});if(n.status>=400)throw ET(r.name,n);return await n.json}catch(n){throw new Error(`Provider rejected the models request: ${n.message}`)}}var qee=/(whisper|-tts|tts-|embed|dall-e|image|moderation|transcribe|realtime|rerank)/i;async function Uee(r,e){let t=r.endpoint.replace(/\/+$/,""),n=t.endsWith("/v1")?`${t}/models`:`${t}/v1/models`,i={};e&&(i.Authorization=`Bearer ${e}`);let o=await cP(r,n,i),s=Wee(o),a=[];for(let l of s){let c=jee(l);c&&!qee.test(c.name)&&a.push(c)}return a}async function Hee(r,e){let t=r.endpoint.replace(/\/+$/,""),n={"anthropic-version":"2023-06-01"};e&&(n["x-api-key"]=e);let i=[],o=null;for(let s=0;s<10;s++){let a=`${t}/v1/models?limit=1000`+(o?`&after_id=${encodeURIComponent(o)}`:""),l=await cP(r,a,n);for(let c of l.data??[])c.id&&i.push({name:c.id,maxTokens:TT});if(!l.has_more||!l.last_id)break;o=l.last_id}return i}async function zee(r,e){let t=r.endpoint.replace(/\/+$/,""),n={};e&&(n["x-goog-api-key"]=e);let i=[],o=null;for(let s=0;s<10;s++){let a=`${t}/v1beta/models?pageSize=1000`+(o?`&pageToken=${encodeURIComponent(o)}`:""),l=await cP(r,a,n);for(let c of l.models??[]){if(!c.name)continue;let u=c.supportedGenerationMethods;if(Array.isArray(u)&&!u.includes("generateContent"))continue;let d={name:c.name.replace(/^models\//,""),maxTokens:typeof c.inputTokenLimit=="number"&&c.inputTokenLimit>0?c.inputTokenLimit:TT};typeof c.outputTokenLimit=="number"&&c.outputTokenLimit>0&&(d.maxOutputTokens=c.outputTokenLimit),i.push(d)}if(!l.nextPageToken)break;o=l.nextPageToken}return i}function Wee(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 jee(r){let e=r.id??r.name;return e?{name:e,maxTokens:Gee(r)}:null}function Gee(r){let e=[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 t of e){let n=Yee(t);if(n&&n>0)return Math.floor(n)}return TT}function Yee(r){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"){let e=Number(r);if(Number.isFinite(e))return e}return null}Yd();var Zee=1440*60*1e3;function Jee(r,e){let t=new Map(r.map(i=>[i.name,JSON.stringify(i)])),n=0;for(let i of e){let o=t.get(i.name);o!==void 0&&o!==JSON.stringify(i)&&(n+=1)}return n}async function Hm(r,e){let t=await Ca(r,e),n=await kT(e,t),i=e.models;return e.models=Jy(e.models,n),{added:e.models.length-i.length,updated:Jee(i,e.models)}}function eH(r){return`${(r.name??"").trim().toLowerCase()}\0${(r.endpoint??"").trim().toLowerCase().replace(/\/+$/,"")}`}async function tH(r,e={}){let t=X.getState();if(t.disableOnlineFeatures)return[];let n=t.ai.providers.filter(l=>l.autoSyncModels);if(n.length===0)return[];let i=t.ai.lastModelAutoSyncAt??0;if(!e.ignoreThrottle&&Date.now()-i<Zee)return[];let o=[],s=new Map;for(let l of n){let c={...l,models:l.models.map(u=>({...u}))};try{let{added:u,updated:d}=await Hm(r,c);o.push({provider:c.name,added:u,updated:d}),s.set(eH(c),c)}catch(u){o.push({provider:c.name,added:0,updated:0,error:u.message??String(u)})}}let a=o.some(l=>!l.error);X.setState(l=>({...l,ai:{...l.ai,providers:l.ai.providers.map(c=>{let u=s.get(eH(c));return u?{...c,models:Jy(c.models,u.models)}:c}),lastModelAutoSyncAt:a?Date.now():l.ai.lastModelAutoSyncAt}}));for(let l of o)l.error?I.logMessage(`[Model auto-sync] ${l.provider}: failed (${l.error})`):(l.added>0||l.updated>0)&&I.logMessage(`[Model auto-sync] ${l.provider}: ${l.added} new model(s), ${l.updated} updated.`);return o}dt();var xa=require("obsidian");Yd();var ST=class extends xa.Modal{constructor(t,n){super(t);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 t=await Ca(this.app,this.provider);this.allModels=await kT(this.provider,t),this.filtered=this.allModels.slice(),this.loadError=null}catch(t){this.loadError=`${t.message??t}`,new xa.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 xa.Setting(this.contentEl).setName("Search").addText(t=>{t.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(t=>{t.setIcon("check"),t.setTooltip("Select all"),t.onClick(()=>{this.filtered.forEach(n=>this.selectedIds.add(n.name)),this.renderList()})}).addExtraButton(t=>{t.setIcon("x"),t.setTooltip("Clear selection"),t.onClick(()=>{this.selectedIds.clear(),this.renderList()})}),new xa.Setting(this.contentEl).setName("Import mode").setDesc("Add will append new models. Replace will overwrite existing models with the selected list.").addDropdown(t=>{t.addOption("add","Add only"),t.addOption("replace","Replace existing"),t.setValue(this.mode),t.onChange(n=>this.mode=n)}).addButton(t=>{t.setButtonText("Import selected").setCta().onClick(()=>this.importSelected())}),this.contentEl.createDiv({cls:"qa-model-directory"}),this.renderList()}renderList(){let t=this.contentEl.querySelector(".qa-model-directory");if(t){if(t.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.";t.createDiv({text:n,cls:"qa-model-directory-empty"});return}for(let n of this.filtered){let i=t.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 xa.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 xa.Notice("No models selected to import.");return}this.resolved=!0,this.resolvePromise({imported:n,mode:this.mode}),this.close()}catch(t){new xa.Notice(`Import failed: ${t.message??t}`)}}onClose(){this.resolved||this.resolvePromise(null),super.onClose()}};Jr();Ds();var go=require("obsidian");ro();var rH=[{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 _T=class extends go.Modal{constructor(e,t){super(e),this.providers=t,this.waitForClose=new Promise((n,i)=>{this.resolvePromise=n,this.rejectPromise=i}),this.open(),this.display()}addHeader(e){e.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 e=this.contentEl.createDiv({cls:"qa-provider-grid"});for(let t of rH){let n=e.createDiv({cls:"qa-provider-card"});if(n.createDiv({text:t.name,cls:"qa-provider-card-title"}),n.createDiv({text:t.endpoint,cls:"qa-provider-card-endpoint"}),t.doc){let s=n.createEl("a",{text:"Docs",href:t.doc});s.target="_blank",s.rel="noopener noreferrer"}let i="",o=wT(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(t.endpoint)}catch{new go.Notice(`Invalid endpoint URL for ${t.name}.`);return}let l=t.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(m=>l.includes(m))&&!a){new go.Notice(`${t.name} requires an API key.`);return}let u=m=>m.trim().toLowerCase(),d=m=>m.trim().toLowerCase().replace(/\/+$/,"");if(this.providers.some(m=>u(m.name)===u(t.name)&&d(m.endpoint)===d(t.endpoint))){new go.Notice(`${t.name} is already configured.`);return}let f={name:t.name,endpoint:t.endpoint,id:nC(t.id,this.providers),kind:t.kind,apiKey:"",apiKeyRef:a,models:[],modelSource:t.modelSource??"auto",autoSyncModels:!0};s.setButtonText("Connecting..."),s.setDisabled(!0),await this.importInitialModels(f,t),this.providers.push(f),this.close()}catch(a){s.setButtonText("Connect"),s.setDisabled(!1),new go.Notice(`Failed to add provider: ${a.message??a}`)}})})}new go.Setting(this.contentEl).setName("Custom provider").setDesc("Create any custom endpoint (OpenAI-compatible or otherwise)").addButton(t=>{t.setButtonText("Add custom...").onClick(()=>{let n={id:nC("custom",this.providers),name:"Custom",endpoint:"",apiKey:"",apiKeyRef:"",models:[],modelSource:"providerApi"};this.providers.push(n),new go.Notice("Custom provider added. Click Edit to configure."),this.close()})})}async importInitialModels(e,t){try{await Hm(this.app,e),new go.Notice(`${t.name} connected with ${e.models.length} models.`)}catch(n){let i=n.message??String(n);t.seedKey?(e.models=oC(t.seedKey),new go.Notice(`${t.name} added with its built-in model list. Live model loading failed: ${i}`)):new go.Notice(`${t.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()}};Wd();var AT=class extends Tr.Modal{constructor(e,t){super(t),this.providers=e,iC(this.providers),this.waitForClose=new Promise((n,i)=>{this.rejectPromise=i,this.resolvePromise=n}),this.open(),this.display(),this.autoSyncOnOpen()}async autoSyncOnOpen(){if(X.getState().disableOnlineFeatures)return;let e=!1;for(let t of this.providers)if(t.autoSyncModels)try{let{added:n}=await Hm(this.app,t);e=e||n>0}catch{}e&&!this.selectedProvider&&this.reload()}display(){let e=this.selectedProvider?`${this.selectedProvider.name}`:"Providers";if(this.contentEl.createEl("h2",{text:e,cls:"qa-modal-title"}),this.selectedProvider){this.addProviderSetting(this.contentEl);return}this.addProvidersSetting(this.contentEl)}reload(){this.contentEl.empty(),this.display()}addProvidersSetting(e){new Tr.Setting(e).setName("Providers").setDesc("Providers for the AI Assistant").addButton(n=>{n.setButtonText("Add provider").onClick(async()=>{await new _T(this.app,this.providers).waitForClose,this.reload()}),n.setCta()});let t=e.createDiv({cls:"providers-container qa-ai-list-container"});this.providers.forEach((n,i)=>{new Tr.Setting(t).setName(n.name).setDesc(n.endpoint).addButton(o=>this.addDeleteButton(o,n.name,()=>this.providers.splice(i,1))).addButton(o=>{o.setButtonText("Edit").onClick(()=>{this.selectedProvider=n,this._selectedProviderClone=Ve(n),this.reload()})})})}addDeleteButton(e,t,n){e.setDestructive(),e.setIcon("trash"),e.onClick(async()=>{await Si.Prompt(this.app,`Are you sure you want to delete ${t}?`)&&(n(),this.reload())})}addProviderSetting(e){this.addNameSetting(e),this.addEndpointSetting(e),this.addApiKeySetting(e),this.addKindSetting(e),this.addModelSourceSetting(e),this.addProviderModelsSetting(e),this.addImportModelsFromDirectorySetting(e),this.addAutoSyncSetting(e),this.addProviderSettingButtonRow(this.contentEl)}addNameSetting(e){let t=this.selectedProvider.id;new Tr.Setting(e).setName("Name").setDesc(t?`The display name of the provider. Its stable ID is "${t}" \u2014 use that to qualify models in scripts, e.g. ai.prompt with "${t}/model-name".`:"The display name of the provider").addText(n=>{n.setValue(this.selectedProvider.name).onChange(i=>{this.selectedProvider.name=i})})}addEndpointSetting(e){new Tr.Setting(e).setName("Endpoint").setDesc("The endpoint for the AI Assistant").addText(t=>{t.setValue(this.selectedProvider.endpoint).onChange(n=>{this.selectedProvider.endpoint=n})})}addApiKeySetting(e){let t=!!this.selectedProvider?.apiKey&&!this.selectedProvider?.apiKeyRef;wT(e,this.app,{value:this.selectedProvider?.apiKeyRef??"",hasLegacyKey:t,onChange:n=>{this.selectedProvider&&(this.selectedProvider.apiKeyRef=n,this.selectedProvider.apiKey="")}})}addKindSetting(e){new Tr.Setting(e).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(t=>{t.addOption("","Auto-detect"),t.addOption("openai","OpenAI-compatible"),t.addOption("anthropic","Anthropic"),t.addOption("gemini","Gemini"),t.setValue(this.selectedProvider?.kind??""),t.onChange(n=>{this.selectedProvider&&(this.selectedProvider.kind=n||void 0)})})}addModelSourceSetting(e){let t=this.selectedProvider;new Tr.Setting(e).setName("Model source").setDesc("Choose where QuickAdd looks when browsing or syncing models for this provider.").addDropdown(n=>{n.addOption("providerApi","Provider models endpoint (requires API key)"),n.addOption("modelsDev","models.dev directory"),n.addOption("auto","Automatic (try provider, fallback to models.dev)");let i=t?.modelSource??"providerApi";n.setValue(i),n.onChange(o=>{this.selectedProvider&&(this.selectedProvider.modelSource=o,this.reload())})})}addProviderModelsSetting(e){let t=e.createDiv({cls:"models-container qa-ai-list-container"});this.selectedProvider.models.forEach((n,i)=>{let o=[`Context: ${n.maxTokens.toLocaleString()} tokens`];n.maxOutputTokens&&o.push(`Output: ${n.maxOutputTokens.toLocaleString()} tokens`),n.supportsTemperature===!1&&o.push("Fixed sampling (no temperature)"),new Tr.Setting(t).setName(n.name).setDesc(o.join(" \xB7 ")).addButton(s=>this.addDeleteButton(s,n.name,()=>this.selectedProvider.models.splice(i,1)))}),new Tr.Setting(t).setName("Add model").addButton(n=>{n.setButtonText("Add model").onClick(async()=>{let i,o;try{i=await ar.Prompt(this.app,"Model name"),o=await ar.Prompt(this.app,"Max tokens")}catch{return}let s=i.trim();if(!s){new Tr.Notice("Model name cannot be empty.");return}let a=o.trim();if(!/^[1-9]\d*$/.test(a)){new Tr.Notice("Max tokens must be a positive number.");return}let l=Number(a);this.selectedProvider.models.push({name:s,maxTokens:l}),this.reload()}),n.setCta()})}addImportModelsFromDirectorySetting(e){let t=this.describeModelSource(this.selectedProvider);new Tr.Setting(e).setName("Import models").setDesc(`Browse and import models from ${t}.`).addButton(n=>{n.setButtonText("Browse models").onClick(async()=>{let i=await new ST(this.app,this.selectedProvider).waitForClose;if(!i)return;let{imported:o,mode:s}=i;s==="replace"?this.selectedProvider.models=o:this.selectedProvider.models=Jy(this.selectedProvider.models,o),new Tr.Notice(`Imported ${o.length} models${s==="replace"?" (replaced)":" (added)"}.`),this.reload()}),n.setCta()})}addAutoSyncSetting(e){let t=this.describeModelSource(this.selectedProvider);new Tr.Setting(e).setName("Auto-sync models").setDesc(`Keep this provider's models current automatically: QuickAdd imports new models and refreshed context limits from ${t} once a day and when these settings open.`).addToggle(n=>{let i=!!this.selectedProvider?.autoSyncModels;n.setValue(i).onChange(o=>{this.selectedProvider&&(this.selectedProvider.autoSyncModels=o)})}).addButton(n=>{n.setButtonText("Sync now").onClick(async()=>{try{let{added:i,updated:o}=await Hm(this.app,this.selectedProvider);new Tr.Notice(i>0||o>0?`Synced from ${t}: ${i} new model(s), ${o} updated.`:`Synced from ${t}: already up to date.`),this.reload()}catch(i){new Tr.Notice(`Sync failed: ${i.message??i}`)}}),n.setCta()})}restoreSelectedProviderFromClone(){if(!this.selectedProvider||!this._selectedProviderClone)return;let e=this.providers.indexOf(this.selectedProvider);e!==-1&&(this.providers[e]=this._selectedProviderClone),this.selectedProvider=null,this._selectedProviderClone=null}addProviderSettingButtonRow(e){let t=e.createDiv({cls:"button-row qa-ai-provider-button-row"}),n=new Tr.ButtonComponent(t);n.setButtonText("Cancel"),n.setDestructive(),n.onClick(()=>{this.restoreSelectedProviderFromClone(),this.reload()});let i=new Tr.ButtonComponent(t);i.setButtonText("Save"),i.setCta(),i.onClick(()=>{this.selectedProvider=null,this.reload()})}describeModelSource(e){switch(e?.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"}}onClose(){this.restoreSelectedProviderFromClone(),this.resolvePromise(this.providers),super.onClose()}};ht();var IT=class extends Vs.Modal{constructor(e,t){super(e),this.settings=t,this.waitForClose=new Promise((n,i)=>{this.rejectPromise=i,this.resolvePromise=n}),this.open(),this.display()}display(){this.modalEl.addClass("qa-ai-wide-modal"),this.contentEl.addClass("qa-ai-scroll-content"),this.contentEl.createEl("h2",{text:"AI Assistant settings",cls:"qa-modal-title"}),this.addProvidersSetting(this.contentEl),this.addDefaultModelSetting(this.contentEl),this.addPromptTemplateFolderPathSetting(this.contentEl),this.addShowAssistantSetting(this.contentEl),this.addConfirmToolCallsSetting(this.contentEl),this.addDefaultSystemPromptSetting(this.contentEl)}reload(){this.contentEl.empty(),this.display()}addProvidersSetting(e){new Vs.Setting(e).setName("Providers").setDesc("The providers for the AI Assistant").addButton(t=>{t.setButtonText("Edit providers").onClick(()=>{new AT(this.settings.providers,this.app).waitForClose.then(()=>{this.reload()})})})}addDefaultModelSetting(e){new Vs.Setting(e).setName("Default model").setDesc("The default model for the AI Assistant").addDropdown(t=>{ZE(t,{model:this.settings.defaultModel,modelRef:this.settings.defaultModelRef},n=>{this.settings.defaultModel=n.model,this.settings.defaultModelRef=n.modelRef})})}addPromptTemplateFolderPathSetting(e){new Vs.Setting(e).setName("Prompt template folder path").setDesc("Path to your folder with prompt templates").addText(t=>{t.setValue(this.settings.promptTemplatesFolderPath).onChange(n=>{this.settings.promptTemplatesFolderPath=n}),new si(this.app,t.inputEl,Vo(this.app))})}addShowAssistantSetting(e){new Vs.Setting(e).setName("Show assistant").setDesc("Show status messages from the AI Assistant").addToggle(t=>{t.setValue(this.settings.showAssistant),t.onChange(n=>{this.settings.showAssistant=n})})}addConfirmToolCallsSetting(e){new Vs.Setting(e).setName("Confirm AI tool calls").setDesc("When an AI agent runs script-defined or built-in tools, ask before executing. 'Destructive only' confirms tools not marked read-only; 'Always' confirms every tool; 'Never' defers to each tool's own setting. A tool that requires approval is always confirmed regardless.").addDropdown(t=>{t.addOption("destructive","Destructive tools only (recommended)"),t.addOption("always","Always confirm every tool"),t.addOption("never","Never (use each tool's own setting)"),t.setValue(this.settings.confirmToolCalls??"destructive"),t.onChange(n=>{this.settings.confirmToolCalls=n})})}addDefaultSystemPromptSetting(e){new Vs.Setting(e).setName("Default system prompt").setDesc("The default system prompt for the AI Assistant");let t=new Vs.TextAreaComponent(e);t.inputEl.addClass("qa-ai-prompt-textarea"),t.inputEl.setAttribute("aria-label","Default system prompt");let n=QE(e,t.inputEl,this.settings.defaultSystemPrompt??"");t.setValue(this.settings.defaultSystemPrompt).onChange(i=>{this.settings.defaultSystemPrompt=i,n(i)})}onClose(){this.resolvePromise(this.settings),super.onClose()}};var oH=require("obsidian");bt();var nH=[{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 DT(r){switch(r){case"Template":return"New template";case"Capture":return"New capture";case"Macro":return"New macro";case"Multi":return"New folder"}}function iH(r,e){let t=DT(r),n=new Set(nn(e).map(o=>o.name));if(!n.has(t))return t;let i=2;for(;n.has(`${t} ${i}`);)i++;return`${t} ${i}`}var ete=L('<div><button type="button" class="qaNewFolderBtn svelte-a7rp4h"><!> <span> </span></button> <button type="button" aria-haspopup="menu"><!> <span> </span> <!></button></div>'),tte={hash:"svelte-a7rp4h",code:`.qaAddChoiceControls.svelte-a7rp4h {display:flex;flex-direction:row;align-items:center;gap:0.5rem;}.qaAddChoiceControls.svelte-a7rp4h button:where(.svelte-a7rp4h) {display:inline-flex;align-items:center;gap:0.35em;}
/* The chevron sits tighter to the label than the leading plus. */.qaNewChoiceBtn.svelte-a7rp4h 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-a7rp4h {gap:1rem;}.qaAddChoiceControls.compact.svelte-a7rp4h button:where(.svelte-a7rp4h) {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-a7rp4h button:where(.svelte-a7rp4h):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-a7rp4h {flex:1;}.qaAddChoiceControls.fill.svelte-a7rp4h button:where(.svelte-a7rp4h) {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-a7rp4h:not(.compact):not(.fill) {flex-direction:column;align-items:stretch;}
}`};function zm(r,e){pe(e,!0),We(r,tte);let t=ne(e,"targetFolderId",3,void 0),n=ne(e,"targetFolderName",3,void 0),i=ne(e,"compact",3,!1),o=ne(e,"fill",3,!1),s=Ce(!1);function a(P){let U=new oH.Menu;for(let W of nH)U.addItem(ee=>ee.setTitle(`${W.label} \u2014 ${W.description}`).setIcon(W.iconId).onClick(me=>{let O=me.altKey===!0;e.onAddChoice(DT(W.type),W.type,t(),O)}));j(s,!0),U.onHide(()=>{j(s,!1)});let K=P.target?.closest("button");if(K){let W=K.getBoundingClientRect();U.showAtPosition({x:W.left,y:W.bottom+4})}else U.showAtMouseEvent(P)}function l(){e.onAddChoice(DT("Multi"),"Multi",t(),!0)}let c=F(()=>i()?"Add choice":"New choice"),u=F(()=>i()?"Add folder":"New folder"),d=F(()=>n()?`Add choice to ${n()}`:h(c)),p=F(()=>n()?`Add folder to ${n()}`:h(u));var f=ete();let m;var g=B(f),v=B(g);Et(v,{iconId:"folder-plus",size:14});var y=_(v,2),b=le(y,!0);N(g);var x=_(g,2);let w;var T=B(x);Et(T,{iconId:"plus",size:14});var C=_(T,2),S=le(C,!0),A=_(C,2);{var D=P=>{Et(P,{iconId:"chevron-down",size:12})};Y(A,P=>{i()||P(D)})}N(x),N(f),re(()=>{m=it(f,1,"qaAddChoiceControls svelte-a7rp4h",null,m,{compact:i(),fill:o()&&!i()}),ke(g,"aria-label",h(p)),ke(g,"title",i()?h(p):void 0),ae(b,h(u)),w=it(x,1,"qaNewChoiceBtn svelte-a7rp4h",null,w,{"mod-cta":!i()}),ke(x,"aria-expanded",h(s)),ke(x,"aria-label",h(d)),ke(x,"title",i()?h(d):void 0),ae(S,h(c))}),Ae("click",g,l),Ae("click",x,a),M(r,f),fe()}nt(["click"]);var rte=L('<div class="rightButtonsContainer svelte-1es4f02"><!> <!> <!> <!> <!> <!></div>'),nte={hash:"svelte-1es4f02",code:`.rightButtonsContainer.svelte-1es4f02 {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 tb(r,e){pe(e,!0),We(r,nte);let t=ne(e,"showConfigureButton",3,!0),n=ne(e,"showDuplicateButton",3,!0),i=ne(e,"commandEnabled",3,!1),o=ne(e,"choiceName",3,"");var s=rte(),a=B(s);{var l=v=>{{let y=F(()=>`Configure${o()?" "+o():""}`);Lt(v,{iconId:"settings",get label(){return h(y)},extraClass:"qa-row-secondary-action",get onclick(){return e.onConfigureChoice}})}};Y(a,v=>{t()&&v(l)})}var c=_(a,2);{var u=v=>{{let y=F(()=>`Duplicate${o()?" "+o():""}`);Lt(v,{iconId:"copy",get label(){return h(y)},extraClass:"qa-row-secondary-action",get onclick(){return e.onDuplicateChoice}})}};Y(c,v=>{n()&&v(u)})}var d=_(c,2);{let v=F(()=>`Delete${o()?" "+o():""}`);Lt(d,{iconId:"trash-2",get label(){return h(v)},extraClass:"qa-row-secondary-action",get onclick(){return e.onDeleteChoice}})}var p=_(d,2);{var f=v=>{{let y=F(()=>`More options${o()?" for "+o():""}`);Lt(v,{iconId:"more-vertical",ariaHasPopup:"menu",get label(){return h(y)},onclick:b=>e.onOpenMenu?.(b.currentTarget)})}};Y(p,v=>{e.onOpenMenu&&v(f)})}var m=_(p,2);{let v=F(()=>`Command palette${o()?": "+o():""}`);Lt(m,{iconId:"zap",get ariaPressed(){return i()},get label(){return h(v)},extraClass:"qa-row-secondary-action",get onclick(){return e.onToggleCommand}})}var g=_(m,2);{let v=F(()=>`Reorder${o()?" "+o():""}`);cn(g,{get label(){return h(v)},get dragDisabled(){return e.dragDisabled},get onDragStart(){return e.onDragHandleDown},get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown}})}N(s),M(r,s),fe()}var $T=require("obsidian");var sH=require("obsidian");bt();var uP="quickadd:move-to-root";function ite(r,e){let t=Lr(e);if(t.some(i=>Ue(i)&&i.id===r.id))return!1;let n=i=>{for(let o of i){if(!Ue(o))continue;let s=et(o);if(s.some(a=>a?.id===r.id)||n(s))return!0}return!1};return n(t)}function ote(r,e){let t=[],n=Array.isArray(e)?e:[],i=(o,s=[])=>{for(let a of o){if(!Ue(a))continue;let l=a.name??"";if(a.type==="Multi"){let c=[...s,l];ste(r,a)||t.push({id:a.id,path:c.join(" / ")}),i(et(a),[...s,l])}}};return i(n,[]),t}function ste(r,e){if(e.type!=="Multi"||r.id===e.id||jo(e))return!0;if(r.type==="Multi"){let t=new Set,n=i=>{Ue(i)&&(t.add(i.id),et(i).forEach(n))};if(et(r).forEach(n),t.has(e.id))return!0}return!1}function aH(r,e,t,n){let i=new sH.Menu;i.addItem(s=>s.setTitle(e.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(),ite(e,t)&&i.addItem(s=>s.setTitle("Move to: (root)").setIcon("folder-up").onClick(()=>n.onMove(uP)));let o=ote(e,t);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 FT(r,e,t,n,i){e.preventDefault(),aH(r,t,n,i).showAtMouseEvent(e)}function PT(r,e,t,n,i){let o=e.getBoundingClientRect();aH(r,t,n,i).showAtPosition({x:o.left,y:o.bottom})}var lH=require("obsidian");function MT(r,e,t,n){e.replaceChildren(),lH.MarkdownRenderer.render(n,r,e,"/",t)}bt();var ate=L('<div class="choiceListItem"><span class="qaChoiceRowIcon" aria-hidden="true"><!></span> <span class="choiceListItemName"></span> <!></div>'),lte={hash:"svelte-1aljzaf",code:""};function dP(r,e){pe(e,!0),We(r,lte);let t=!0,n=Ce(void 0),i=new $T.Component;Yt(()=>{h(n)&&MT(e.choice.name,h(n),i,e.app)}),Yt(()=>()=>i.unload());let o=()=>({onRename:()=>e.actions.onRenameChoice(e.choice),onToggle:()=>e.actions.onToggleCommand(e.choice),onConfigure:()=>e.actions.onConfigureChoice(e.choice),onDuplicate:()=>e.actions.onDuplicateChoice(e.choice),onDelete:()=>e.actions.onDeleteChoice(e.choice),onMove:f=>e.actions.onMoveChoice(e.choice,f)});function s(f){FT(e.app,f,e.choice,e.roots,o())}function a(f){PT(e.app,f,e.choice,e.roots,o())}var l=ate(),c=B(l),u=B(c);{let f=F(()=>xd(e.choice));Et(u,{get iconId(){return h(f)},size:15})}N(c);var d=_(c,2);Ci(d,f=>j(n,f),()=>h(n));var p=_(d,2);tb(p,{get onDragHandleDown(){return e.startDrag},onDeleteChoice:()=>e.actions.onDeleteChoice(e.choice),onConfigureChoice:()=>e.actions.onConfigureChoice(e.choice),onToggleCommand:()=>e.actions.onToggleCommand(e.choice),onDuplicateChoice:()=>e.actions.onDuplicateChoice(e.choice),onOpenMenu:a,get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown},get choiceName(){return e.choice.name},get commandEnabled(){return e.choice.command},showConfigureButton:t,get dragDisabled(){return e.dragDisabled},showDuplicateButton:!0}),N(l),re(()=>ke(l,"data-choice-id",e.choice.id)),Ae("contextmenu",l,s),Ae("dblclick",l,f=>{$T.Platform.isMobile||f.target.closest("button, a")||e.actions.onConfigureChoice(e.choice)}),M(r,l),fe()}nt(["contextmenu","dblclick"]);var OT=require("obsidian");bt();var cte=L('<span class="qaFolderCount svelte-1jxjn06" aria-hidden="true"> </span>'),ute=L(`<p class="qaUnreadableFolder svelte-1jxjn06">QuickAdd couldn't read this folder's contents. They're still
in <code class="svelte-1jxjn06">data.json</code>.</p>`),dte=L('<div class="nestedAddRow svelte-1jxjn06"><!></div>'),pte=L("<!> <!>",1),fte=L('<div class="nestedChoiceList svelte-1jxjn06"><!></div>'),mte=L('<div><div class="multiChoiceListItem"><button type="button" class="multiChoiceListItemName svelte-1jxjn06"><span aria-hidden="true"><!></span> <span class="choiceListItemName"></span> <!></button> <!></div> <!></div>'),hte={hash:"svelte-1jxjn06",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-1jxjn06 {transition:transform 150ms ease;}.multiChoiceCollapseIcon.is-collapsed.svelte-1jxjn06 {transform:rotate(-90deg);}
@media (prefers-reduced-motion: reduce) {.multiChoiceCollapseIcon.svelte-1jxjn06 {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-1jxjn06 {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-1jxjn06 .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-1jxjn06 {margin:0;padding:6px 8px 8px;color:var(--text-faint);font-size:var(--font-ui-smaller, 12px);line-height:1.4;}.qaUnreadableFolder.svelte-1jxjn06 code:where(.svelte-1jxjn06) {font-size:inherit;}.qaFolderCount.svelte-1jxjn06 {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-1jxjn06: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-1jxjn06 {position:relative;padding-left:26px;}.nestedChoiceList.svelte-1jxjn06::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-1jxjn06 {margin:2px 0 4px 0;padding:0 8px;}`};function pP(r,e){pe(e,!0),We(r,hte);let t=ne(e,"choice",7),n=ne(e,"forceDragDisabled",3,!1),i=F(()=>et(t())),o=F(()=>jo(t())),s=!0,a=Ce(void 0),l=new OT.Component;Yt(()=>{h(a)&&MT(t().name,h(a),l,e.app)}),Yt(()=>()=>l.unload());let c=()=>({onRename:()=>e.actions.onRenameChoice(t()),onToggle:()=>e.actions.onToggleCommand(t()),onConfigure:()=>e.actions.onConfigureChoice(t()),onDuplicate:()=>e.actions.onDuplicateChoice(t()),onDelete:()=>e.actions.onDeleteChoice(t()),onMove:P=>e.actions.onMoveChoice(t(),P)});function u(P){FT(e.app,P,t(),e.roots,c())}function d(P){PT(e.app,P,t(),e.roots,c())}let p={...kt(()=>e.actions),onReorderChoices:P=>{t().choices=P,e.actions.onCommitFolder(t().id,P)}};function f(){n()||e.actions.onToggleCollapsed(t())}var m=mte(),g=B(m),v=B(g),y=B(v);let b;var x=B(y);Et(x,{iconId:"chevron-down",size:16}),N(y);var w=_(y,2);Ci(w,P=>j(a,P),()=>h(a));var T=_(w,2);{var C=P=>{var U=cte(),K=le(U,!0);re(()=>ae(K,h(i).length)),M(P,U)};Y(T,P=>{t().collapsed&&h(i).length>0&&P(C)})}N(v),Jt(v,P=>OE?.(P));var S=_(v,2);tb(S,{get onDragHandleDown(){return e.startDrag},onDeleteChoice:()=>e.actions.onDeleteChoice(t()),onConfigureChoice:()=>e.actions.onConfigureChoice(t()),onToggleCommand:()=>e.actions.onToggleCommand(t()),onDuplicateChoice:()=>e.actions.onDuplicateChoice(t()),onOpenMenu:d,get onMoveUp(){return e.onMoveUp},get onMoveDown(){return e.onMoveDown},showConfigureButton:s,get dragDisabled(){return e.dragDisabled},get choiceName(){return t().name},get commandEnabled(){return t().command},showDuplicateButton:!0}),N(g);var A=_(g,2);{var D=P=>{var U=or(),K=Te(U);{var W=ee=>{var me=fte(),O=B(me);{var H=te=>{var z=ute();M(te,z)},ce=te=>{var z=pte(),G=Te(z);{let ue=F(()=>h(i).length===0),be=F(()=>e.rootReorder??e.actions.onReorderChoices);Wm(G,{get app(){return e.app},get roots(){return e.roots},get choices(){return h(i)},nested:!0,get isEmptyFolder(){return h(ue)},get forceDragDisabled(){return n()},get rootReorder(){return h(be)},get actions(){return p}})}var ie=_(G,2);{var xe=ue=>{var be=dte(),Ke=B(be);zm(Ke,{compact:!0,get targetFolderId(){return t().id},get targetFolderName(){return t().name},get onAddChoice(){return e.actions.onAddChoice}}),N(be),M(ue,be)};Y(ie,ue=>{n()||ue(xe)})}M(te,z)};Y(O,te=>{h(o)?te(H):te(ce,-1)})}N(me),M(ee,me)};Y(K,ee=>{t().collapsed||ee(W)})}M(P,U)};Y(A,P=>{(!e.collapseId||e.collapseId&&t().id!==e.collapseId)&&P(D)})}N(m),re(()=>{ke(g,"data-choice-id",t().id),ke(v,"aria-expanded",!t().collapsed),ke(v,"aria-label",`Toggle ${t().name}`),b=it(y,1,"qaChoiceRowIcon multiChoiceCollapseIcon svelte-1jxjn06",null,b,{"is-collapsed":t().collapsed})}),Ae("contextmenu",g,u),Ae("click",g,P=>{OT.Platform.isMobile||P.target.closest("button, a")||f()}),Ae("click",v,f),M(r,m),fe()}nt(["contextmenu","click"]);function cH(r){let e=r-1;return e*e*e+1}function uH(r,{from:e,to:t},n={}){var{delay:i=0,duration:o=C=>Math.sqrt(C)*120,easing:s=cH}=n,a=getComputedStyle(r),l=a.transform==="none"?"":a.transform,[c,u]=a.transformOrigin.split(" ").map(parseFloat);c/=r.clientWidth,u/=r.clientHeight;var d=gte(r),p=r.clientWidth/t.width/d,f=r.clientHeight/t.height/d,m=e.left+e.width*c,g=e.top+e.height*u,v=t.left+t.width*c,y=t.top+t.height*u,b=(m-v)*p,x=(g-y)*f,w=e.width/t.width,T=e.height/t.height;return{delay:i,duration:typeof o=="function"?o(Math.sqrt(b*b+x*x)):o,easing:s,css:(C,S)=>{var A=S*b,D=S*x,P=C+S*w,U=C+S*T;return`transform: ${l} translate(${A}px, ${D}px) scale(${P}, ${U});`}}}function gte(r){if("currentCSSZoom"in r)return r.currentCSSZoom;for(var e=r,t=1;e!==null;)t*=+getComputedStyle(e).zoom,e=e.parentElement;return t}var dH=require("obsidian");bt();var vte=L("<div><!></div>"),yte=L("<div></div>"),bte={hash:"svelte-2ry05y",code:`.choiceList.svelte-2ry05y {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-2ry05y:not(.qa-nested) {padding-bottom:0.5rem;}.choiceList.qa-nested.svelte-2ry05y {
/* 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-2ry05y::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-2ry05y.qa-folder-droptarget {background-color:var(--background-modifier-hover);}.choiceList.qa-nested.svelte-2ry05y.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-2ry05y {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-2ry05y::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-2ry05y,
.choiceList.qa-nested.svelte-2ry05y::before {transition:none;}
}`};function Wm(r,e){pe(e,!0),We(r,bte);let t=ne(e,"choices",31,()=>ut([])),n=ne(e,"forceDragDisabled",3,!1),i=ne(e,"isEmptyFolder",3,!1),o=ne(e,"nested",3,!1),s=F(()=>{let T=new Set;return Lr(t()).filter(C=>{if(!Ue(C))return!1;let S=C.id;return typeof S!="string"||S===""||T.has(S)?!1:(T.add(S),!0)})}),a=F(()=>e.rootReorder??e.actions.onReorderChoices),l=0,c=dH.Platform.isMobile,u=Ce(""),d=gm(),p=F(()=>n()||!c&&!d.armed),f=Ce(void 0),m=null;function g(T){if(n())return;d.markStarted();let C=T.detail.items;m=fm(C,T.detail.info.id)??m,j(u,T.detail.info.id,!0),t(qi(C))}function v(T){if(n())return;j(u,"");let C=qi(T.detail.items),S=T.detail.info.id;T.detail.info.trigger===jn.DROPPED_INTO_ANOTHER?C=C.filter(A=>A.id!==S):m?.item.id===S&&!C.some(A=>A.id===S)&&(C=[...C],C.splice(Math.min(m.index,C.length),0,m.item)),m=null,t(C),d.reset(),e.actions.onReorderChoices(t())}let y=()=>{n()||d.startDrag()};function b(T,C){if(n())return;let S=document.activeElement?.getAttribute("aria-label"),A=qi(h(s)),D=mm(A,T.id,C);if(!D)return;let P=D.findIndex(U=>U.id===T.id);t(D),e.actions.onReorderChoices(t()),Hd(`Moved ${T.name} to position ${P+1} of ${D.length}`),S&&vm(h(f),S)}var x=yte();let w;Ot(x,29,()=>qi(h(s)),T=>T.id,(T,C)=>{var S=vte(),A=B(S);{var D=U=>{{let K=F(()=>e.roots??t()),W=F(()=>n()?void 0:()=>b(h(C),-1)),ee=F(()=>n()?void 0:()=>b(h(C),1));dP(U,{get app(){return e.app},get roots(){return h(K)},get dragDisabled(){return h(p)},startDrag:y,get actions(){return e.actions},get choice(){return h(C)},get onMoveUp(){return h(W)},get onMoveDown(){return h(ee)}})}},P=U=>{{let K=F(()=>e.roots??t()),W=F(()=>n()?void 0:()=>b(h(C),-1)),ee=F(()=>n()?void 0:()=>b(h(C),1));pP(U,{get app(){return e.app},get roots(){return h(K)},get dragDisabled(){return h(p)},startDrag:y,get actions(){return e.actions},get collapseId(){return h(u)},get forceDragDisabled(){return n()},get rootReorder(){return h(a)},get choice(){return h(C)},get onMoveUp(){return h(W)},get onMoveDown(){return h(ee)}})}};Y(A,U=>{h(C).type!=="Multi"?U(D):U(P,-1)})}N(S),sA(S,()=>uH,()=>({duration:l})),M(T,S)}),N(x),Ci(x,T=>j(f,T),()=>h(f)),Jt(x,(T,C)=>pm?.(T,C),()=>hm({items:h(s),dragDisabled:h(p),flipDurationMs:l,dropTargetClasses:o()?["qa-folder-droptarget"]:[]})),re(()=>w=it(x,1,"choiceList svelte-2ry05y",null,w,{"qa-nested":o(),"qa-folder-empty":i(),"qa-empty":h(s).length===0})),Po("consider",x,g),Po("finalize",x,v),M(r,x),fe()}var wte=L('<pre class="qaChoicesUnavailableDetail svelte-1fs8ikt"> </pre>'),Cte=L(`<div class="qaChoicesUnavailable svelte-1fs8ikt"><div class="qaChoicesUnavailableHead svelte-1fs8ikt"><!> <span class="qaChoicesUnavailableTitle svelte-1fs8ikt"> </span></div> <p class="qaChoicesUnavailableBody svelte-1fs8ikt">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-1fs8ikt">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>`),xte={hash:"svelte-1fs8ikt",code:".qaChoicesUnavailable.svelte-1fs8ikt {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-1fs8ikt {display:flex;align-items:center;gap:8px;color:var(--text-warning, var(--text-normal));}.qaChoicesUnavailableTitle.svelte-1fs8ikt {font-weight:var(--font-semibold);color:var(--text-normal);}.qaChoicesUnavailableBody.svelte-1fs8ikt {margin:8px 0 0;color:var(--text-muted);font-size:var(--font-ui-small, 13px);max-width:68ch;}.qaChoicesUnavailableDetail.svelte-1fs8ikt {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 jm(r,e){We(r,xte);let t=ne(e,"what",3,"your choices"),n=ne(e,"detail",3,"");var i=Cte(),o=B(i),s=B(o);Et(s,{iconId:"alert-triangle",size:16});var a=_(s,2),l=le(a);N(o);var c=_(o,6);{var u=d=>{var p=wte(),f=le(p,!0);re(()=>ae(f,n())),M(d,p)};Y(c,d=>{n()&&d(u)})}N(i),re(()=>ae(l,`QuickAdd couldn't display ${t()??""}`)),M(r,i)}xt();var gH=require("obsidian");Ie();xt();var mH=require("obsidian");bt();Ie();bt();var fP=new WeakMap;function pH(r){let e=fP.get(r);if(e)return e;let t=i1(r);return fP.set(r,t),t}function fH(r){return fP.has(r)}function mP(r,e){if(!Array.isArray(r))return r;let t=fH(r),{choices:n,repaired:i}=pH(r);if(t)return n;for(let{choice:o}of i)if(o.command)try{e.enableCommand(o)}catch(s){I.logError(`Could not register a command for the repaired choice "${o.name}": ${s instanceof Error?s.message:String(s)}`)}return n}function hH(r,e){let t=e.trim();if(!t)return r;let n=(0,mH.prepareFuzzySearch)(t),i=o=>{if(!Ue(o))return null;let s=!!n(o.name??"");if(o.type!=="Multi")return s?o:null;let a=et(o).map(l=>i(l)).filter(l=>l!==null);return s||a.length>0?{...o,collapsed:!1,choices:a}:null};return r.map(o=>i(o)).filter(o=>o!==null)}function hP(r){return Ue(r)?r.command?!0:et(r).some(hP):!1}function rb(r,e){if(!Ue(r))return r;if(r.id===e.id)return{...r,...e};if(ml(r)){let t=et(r).map(i=>rb(i,e));return{...r,choices:t}}return r}function vH(r){function e(){r.saveChoices(Xc(r.choices))}async function t(g,v,y,b=!1){let x=iH(v,r.choices),w=rP(v,x);if(r.choices=UU(r.choices,w,y),!y&&r.filterQuery.trim().length>0&&(r.filterQuery=""),e(),v==="Multi")await a(w);else if(!b)try{await s(w)}catch(T){I.logError(`Failed to configure the new choice: ${T instanceof Error?T.message:String(T)}`),e()}await n(w.id)}async function n(g){await ac();try{document.querySelector(`[data-choice-id="${g}"]`)?.scrollIntoView({block:"nearest"})}catch{}}function i(g){return Qy(r.choices,g.id)??g}async function o(g){let v=i(g);await NU(v,r.app)&&(r.choices=Xy(r.choices,g.id).updated,r.commandRegistry.disableCommand(v,{recursive:!0}),e())}async function s(g){let v=i(g),y=await LU(v,r.app,r.plugin);y&&(r.choices=r.choices.map(b=>rb(b,y)),r.commandRegistry.updateCommand(v,y),e())}async function a(g){if(!g)return;let v=await wx(r.app,g.name,g.type);if(!v)return;let y=i(g),b={...y,name:v};r.choices=r.choices.map(x=>rb(x,b)),r.commandRegistry.updateCommand(y,b),e()}function l(g){let v=VU(i(g));r.choices=r.choices.map(y=>rb(y,v)),v.command?r.commandRegistry.enableCommand(v):r.commandRegistry.disableCommand(v),e()}async function c(g){let v=await OU(i(g),r.app);r.choices=oP(r.choices,g.id,v)??[...r.choices,v],hP(v)&&r.commandRegistry.enableCommand(v),e(),new gH.Notice(`Duplicated "${g.name}".`),await n(v.id)}function u(g,v){r.choices=v===uP?qU(r.choices,g.id):BU(r.choices,g.id,v),e()}function d(g){r.choices=g,e()}function p(g,v){r.choices=HU(r.choices,g,v),e()}function f(g){r.choices=aP(r.choices,g.id,!g.collapsed),e()}function m(g,v){return(y,...b)=>{let x=Ef(y?.type),w=y?.name?`the ${x} \u201C${y.name}\u201D`:`that ${x}`;ld(`Couldn't ${g} ${w}`,v)(y,...b)}}return{onDeleteChoice:m("delete",o),onConfigureChoice:m("open the settings for",s),onToggleCommand:m("update the command palette entry for",l),onDuplicateChoice:m("duplicate",c),onRenameChoice:m("rename",a),onMoveChoice:m("move",u),onToggleCollapsed:m("open or close",f),onReorderChoices:ld("Couldn't save the new order",d),onCommitFolder:ld("Couldn't save that folder's contents",p),onAddChoice:(g,v,y,b)=>ld(`Couldn't add that ${Ef(v)}`,t)(g,v,y,b)}}var Ete=L(`<div class="choiceEmptyState svelte-1r4uuo1"><!> <div class="choiceEmptyTitle svelte-1r4uuo1">No choices yet</div> <p class="choiceEmptyBody svelte-1r4uuo1">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-1r4uuo1"><!></div></div>`),Tte=L('<button class="search-input-clear-button qaFilterClearButton svelte-1r4uuo1" aria-label="Clear filter"></button>'),kte=L('<div class="choiceFilterEmpty svelte-1r4uuo1">No choices match your filter.</div>'),Ste=L('<button type="button" class="qaAIAssistantBtn clickable-icon svelte-1r4uuo1" aria-label="Configure AI Assistant" title="Configure AI Assistant"><!></button>'),_te=L('<div class="choiceFilterBar svelte-1r4uuo1"><div class="search-input-container choiceFilterInput svelte-1r4uuo1"><input type="search" placeholder="Filter choices..." autocapitalize="off" autocorrect="off" enterkeyhint="search"/> <!></div></div> <!> <div class="choiceViewBottomBar svelte-1r4uuo1"><!> <!></div>',1),Ate=L("<div><!></div>"),Ite={hash:"svelte-1r4uuo1",code:`.choiceViewBottomBar.svelte-1r4uuo1 {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-1r4uuo1 {flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;color:var(--text-muted);}.qaAIAssistantBtn.svelte-1r4uuo1:hover {color:var(--text-normal);}.choiceEmptyState.svelte-1r4uuo1 {display:flex;flex-direction:column;align-items:center;text-align:center;gap:0.5rem;padding:2.5rem 1rem;color:var(--text-muted);}.choiceEmptyTitle.svelte-1r4uuo1 {font-weight:var(--font-semibold);color:var(--text-normal);}.choiceEmptyBody.svelte-1r4uuo1 {margin:0;max-width:42ch;}.choiceEmptyActions.svelte-1r4uuo1 {margin-top:0.5rem;}.choiceFilterBar.svelte-1r4uuo1 {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-1r4uuo1 {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-1r4uuo1 {background:transparent;border:none;box-shadow:none;padding:0;margin:0;cursor:var(--cursor, pointer);}.choiceFilterEmpty.svelte-1r4uuo1 {color:var(--text-faint);font-size:var(--font-ui-small, 13px);padding:12px 8px 16px;}`};function gP(r,e){pe(e,!0),We(r,Ite);let t=ne(e,"choices",31,()=>ut([])),n=Ce(""),i=F(()=>!Array.isArray(t())),o=F(()=>`The "choices" value in data.json is ${t()===null?"null":`of type "${typeof t()}"`}, but QuickAdd expects a list.`),s=yH.Platform.isMobile,a=Ce(ut(X.getState().disableOnlineFeatures)),l=new yT(kt(()=>e.plugin));t(mP(t(),l)),Yt(()=>{let g=X.subscribe(v=>{t(mP(v.choices,l)),j(a,v.disableOnlineFeatures,!0)});return()=>g()});let c=vH({get app(){return e.app},get plugin(){return e.plugin},get choices(){return t()},set choices(g){t(g)},get filterQuery(){return h(n)},set filterQuery(g){j(n,g,!0)},commandRegistry:l,saveChoices:g=>e.saveChoices(g)}),u=ld("Couldn't open the AI assistant settings",async()=>{let g=await new IT(e.app,X.getState().ai).waitForClose;g&&X.setState(v=>({...v,ai:g}))});var d=Ate(),p=B(d);{var f=g=>{jm(g,{get detail(){return h(o)}})},m=g=>{var v=or(),y=Te(v);hg(y,{onerror:x=>I.logError(`QuickAdd could not render the choice list: ${x instanceof Error?x.message:String(x)}`),failed:(x,w=Ct)=>{{let T=F(()=>w()instanceof Error?w().message:String(w()));jm(x,{get detail(){return h(T)}})}}},x=>{var w=or(),T=Te(w);{var C=D=>{var P=Ete(),U=B(P);Et(U,{iconId:"folder-plus",size:28});var K=_(U,4),W=_(B(K));N(K);var ee=_(K,2),me=B(ee);zm(me,{get onAddChoice(){return c.onAddChoice}}),N(ee),N(P),re(()=>ke(W,"href",Ms.gettingStarted)),M(D,P)},S=F(()=>t().length===0&&h(n).trim().length===0),A=D=>{var P=_te(),U=Te(P),K=B(U),W=B(K);Rt(W),ke(W,"spellcheck",!1);var ee=_(W,2);{var me=ue=>{var be=Tte();Ae("click",be,()=>j(n,"")),M(ue,be)};Y(ee,ue=>{h(n)&&ue(me)})}N(K),N(U);var O=_(U,2);{var H=ue=>{Wm(ue,{get app(){return e.app},get roots(){return t()},get actions(){return c},get choices(){return t()},set choices(be){t(be)}})},ce=F(()=>h(n).trim().length===0),te=ue=>{let be=F(()=>hH(t(),h(n)));var Ke=or(),Oe=Te(Ke);{var Ee=Le=>{var At=kte();M(Le,At)},He=Le=>{Wm(Le,{get app(){return e.app},get roots(){return t()},get choices(){return h(be)},forceDragDisabled:!0,get actions(){return c}})};Y(Oe,Le=>{h(be).length===0?Le(Ee):Le(He,-1)})}M(ue,Ke)};Y(O,ue=>{h(ce)?ue(H):ue(te,-1)})}var z=_(O,2),G=B(z);{var ie=ue=>{var be=Ste(),Ke=B(be);Et(Ke,{iconId:"sparkles",size:16}),N(be),Ae("click",be,u),M(ue,be)};Y(G,ue=>{h(a)||ue(ie)})}var xe=_(G,2);zm(xe,{get onAddChoice(){return c.onAddChoice},get fill(){return s}}),N(z),Ae("keydown",W,ue=>{ue.key==="Escape"&&h(n)&&(j(n,""),ue.stopPropagation())}),wi(W,()=>h(n),ue=>j(n,ue)),M(D,P)};Y(T,D=>{h(S)?D(C):D(A,-1)})}M(x,w)}),M(g,v)};Y(p,g=>{h(i)?g(f):g(m,-1)})}N(d),M(r,d),fe()}nt(["keydown","click"]);dt();var Dte=L('<div class="qa-gv__empty svelte-hx6w4t">No global variables yet.</div>'),Fte=L('<div class="qa-gv__row qa-gv__row--head svelte-hx6w4t"><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-hx6w4t">Actions</div></div>'),Pte=L('<div class="qa-gv__row svelte-hx6w4t"><div class="qa-gv__cell qa-gv__name svelte-hx6w4t"><input type="text" placeholder="Name" class="svelte-hx6w4t"/></div> <div class="qa-gv__cell qa-gv__value svelte-hx6w4t"><textarea rows="2" placeholder="Snippet value (supports QuickAdd tokens)" class="svelte-hx6w4t"></textarea></div> <div class="qa-gv__cell qa-gv__ops svelte-hx6w4t"><button class="qa-gv__btn danger svelte-hx6w4t" title="Delete">Delete</button></div></div>'),Mte=L('<div class="qa-gv svelte-hx6w4t"><div class="qa-gv__desc svelte-hx6w4t">Define reusable snippets referenced as <code>&#123;&#123;GLOBAL_VAR:&lt;name&gt;&#125;&#125;</code>. Snippets support other QuickAdd tokens and expand before VALUE/VDATE/etc.</div> <div class="qa-gv__table svelte-hx6w4t"><!> <!></div> <div class="qa-gv__actions svelte-hx6w4t"><button class="mod-cta">Add variable</button></div></div>'),$te={hash:"svelte-hx6w4t",code:`.qa-gv.svelte-hx6w4t {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-hx6w4t {display:flex;justify-content:flex-end;}.qa-gv__desc.svelte-hx6w4t {color:var(--text-muted);font-size:12px;}
/* Mirrors .qa-template-folder-empty, the sibling list's empty state. */.qa-gv__empty.svelte-hx6w4t {color:var(--text-muted);font-size:var(--font-ui-smaller);padding:6px 0;}.qa-gv__table.svelte-hx6w4t {display:grid;gap:8px;}.qa-gv__row.svelte-hx6w4t {display:grid;grid-template-columns:180px 1fr 140px;gap:8px;align-items:start;}.qa-gv__row--head.svelte-hx6w4t {font-weight:600;color:var(--text-muted);}.qa-gv__cell.svelte-hx6w4t input[type="text"]:where(.svelte-hx6w4t) {width:100%;}.qa-gv__cell.svelte-hx6w4t textarea:where(.svelte-hx6w4t) {width:100%;resize:vertical;}.qa-gv__ops.svelte-hx6w4t {display:flex;gap:6px;align-items:center;}.qa-gv__btn.svelte-hx6w4t {padding:4px 8px;}.qa-gv__btn.danger.svelte-hx6w4t {color:var(--text-error);}
@media (max-width: 900px) {.qa-gv__row.svelte-hx6w4t {grid-template-columns:1fr;}.qa-gv__row--head.svelte-hx6w4t {display:none;}
}`};function vP(r,e){pe(e,!0),We(r,$te);let t=Ce(ut([]));function n(w,T){if(!T.has(w))return w;let C=1;for(;T.has(`${w}${C}`);)C++;return`${w}${C}`}function i(){let T=X.getState().globalVariables||{};j(t,Object.keys(T).map(C=>({name:C,value:T[C]??""})),!0)}let o=!1;function s(){let w=h(t).map(A=>A.name.trim()),T=w.some(A=>!A),C=new Set(w).size!==w.length;if(T||C)return;let S={};for(let A of h(t))S[A.name.trim()]=A.value??"";o=!0;try{X.setState({globalVariables:S})}finally{o=!1}}function a(){let w=new Set(h(t).map(C=>C.name)),T=n("NewVar",w);j(t,[...h(t),{name:T,value:""}],!0),s()}function l(w){j(t,h(t).filter((T,C)=>C!==w),!0),s()}function c(w){return new Sn(e.app,w,e.plugin),{destroy(){}}}let u;function d(w){u!==void 0&&window.clearTimeout(u),u=window.setTimeout(()=>{s()},200)}Yt(()=>{let w=X.subscribe(()=>{o||i()});return i(),()=>{u!==void 0&&window.clearTimeout(u),w()}});var p=Mte(),f=_(B(p),2),m=B(f);{var g=w=>{var T=Dte();M(w,T)},v=w=>{var T=Fte();M(w,T)};Y(m,w=>{h(t).length===0?w(g):w(v,-1)})}var y=_(m,2);Ot(y,17,()=>h(t),xg,(w,T,C)=>{var S=Pte(),A=B(S),D=B(A);Rt(D),Jt(D,ee=>c?.(ee)),$r(()=>wi(D,()=>h(T).name,ee=>h(T).name=ee)),N(A);var P=_(A,2),U=B(P);Nu(U),Jt(U,ee=>c?.(ee)),$r(()=>wi(U,()=>h(T).value,ee=>h(T).value=ee)),N(P);var K=_(P,2),W=le(K);N(S),Ae("input",D,()=>{d(h(T))}),Ae("input",U,()=>d(h(T))),Ae("click",W,()=>l(h(t).indexOf(h(T)))),M(w,S)}),N(f);var b=_(f,2),x=le(b);N(p),Ae("click",x,a),M(r,p),fe()}nt(["input","click"]);dt();ht();var LH=require("obsidian");bt();un();vr();var Ote=new Set;function bH(r){return r.type==="Multi"}function wH(r){return r.type==="Macro"}function Rte(r){return r.type==="Template"}function Nte(r){return r.type==="Capture"}function yP(r,e,t){return r?e.has(r.id)?t.has(r.id):!0:!1}function Lte(r,e,t,n){switch(r.type){case"Choice":{let i=r;if(!t.has(i.choiceId))return!0;let o=e.get(i.choiceId);return o&&yP(o.choice,e,t)&&n(o.choice),!0}case"NestedChoice":{let i=r;return i.choice&&yP(i.choice,e,t)&&n(i.choice),!0}default:return!1}}function Vte(r){let e=new Map,t=(n,i,o)=>{for(let s of n){if(!Ue(s))continue;let a=[...o,s.name];e.set(s.id,{choice:s,parentId:i,path:a}),bH(s)&&Array.isArray(s.choices)&&t(s.choices,s.id,a)}};return t(Lr(r),null,[]),e}function CH(r){let e=new Set;for(let t of et(r))Ue(t)&&e.add(t.id);return wH(r)&&bP(r.macro?.commands,e),e}function bP(r,e){for(let t of Ht(r))if(qr(t))switch(t.type){case"Choice":{let n=t;n.choiceId&&e.add(n.choiceId);break}case"Conditional":{let n=t;bP(n.thenCommands,e),bP(n.elseCommands,e);break}case"NestedChoice":{let i=t.choice;if(!i)break;let o=CH(i);for(let s of o)e.add(s);break}default:break}}function RT(r,e,t){let n=Vte(r),i=new Set,o=new Set,s=t?.excludedChoiceIds??Ote,a=e.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 u=n.get(c);if(!u){o.add(c);continue}i.add(c),l.push(c);let d=CH(u.choice);for(let p of d){if(!n.has(p)){o.add(p);continue}s.has(p)||a.push(p)}}return{catalog:n,choiceIds:l,missingChoiceIds:Array.from(o)}}function xH(r,e,t,n){let i=new Set(e),o=new Set,s=l=>{!l||!yP(l,r,i)||o.has(l.id)||(o.add(l.id),t(l),bH(l)&&Array.isArray(l.choices)&&l.choices.forEach(s),wH(l)&&a(l.macro?.commands))},a=l=>{for(let c of Ht(l))if(qr(c)&&!Lte(c,r,i,s)&&(n(c),c.type==="Conditional")){let u=c;a(u.thenCommands),a(u.elseCommands)}};for(let l of e){let c=r.get(l);c&&s(c.choice)}}function NT(r,e){let t=new Set,n=new Set;return xH(r,e,()=>{},i=>{if(i.type==="UserScript"){let o=i;o.path&&t.add(o.path)}else if(i.type==="Conditional"){let{condition:o}=i;o.mode==="script"&&o.scriptPath&&n.add(o.scriptPath)}}),{userScriptPaths:t,conditionalScriptPaths:n}}function LT(r,e){let t=new Set,n=new Set;return xH(r,e,i=>{if(Rte(i)&&i.templatePath&&t.add(i.templatePath),Nte(i)){let o=i.createFileIfItDoesntExist;o?.enabled&&o.createWithTemplate&&o.template&&n.add(o.template)}},()=>{}),{templatePaths:t,captureTemplatePaths:n}}function EH(r,e){let t=e.trim().toLowerCase();return t?r.filter(n=>`${n.path.join(" ")} ${n.choice.type}`.toLowerCase().includes(t)):r}function TH(r,e){let t=[];for(let n of r)e.has(n.id)&&(!n.parentId||!e.has(n.parentId))&&t.push(n.id);return t}function kH(r,e,t){if(e.length===0)return{rootCount:0,totalChoices:0,dependencyCount:0,missingChoiceIds:[],userScripts:0,conditionalScripts:0,templateFiles:0,captureTemplates:0};let n=RT(r,e,{excludedChoiceIds:t}),i=NT(n.catalog,n.choiceIds),o=LT(n.catalog,n.choiceIds);return{rootCount:e.length,totalChoices:n.choiceIds.length,dependencyCount:Math.max(n.choiceIds.length-e.length,0),missingChoiceIds:n.missingChoiceIds,userScripts:i.userScriptPaths.size,conditionalScripts:i.conditionalScriptPaths.size,templateFiles:o.templatePaths.size,captureTemplates:o.captureTemplatePaths.size}}var Bs=require("obsidian");bt();var SH=typeof TextEncoder<"u"?new TextEncoder:void 0,_H=typeof TextDecoder<"u"?new TextDecoder:void 0;function AH(r){return typeof window>"u"?!1:typeof window[r]=="function"}function IH(){if(!(typeof Buffer>"u"))return Buffer}function DH(r){if(SH&&AH("btoa")){let t=SH.encode(r),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return window.btoa(n)}let e=IH();if(e)return e.from(r,"utf8").toString("base64");throw new Error("Base64 encoding is not supported in this environment.")}function au(r){if(_H&&AH("atob")){let t=window.atob(r),n=Uint8Array.from(t,i=>i.charCodeAt(0));return _H.decode(n)}let e=IH();if(e)return e.from(r,"base64").toString("utf8");throw new Error("Base64 decoding is not supported in this environment.")}Ml();Ie();function VT(r,e){let t=new Map;for(let n of r)if(n.kind==="user-script")try{let i=Hy(au(n.content),n.originalPath);t.set(n.originalPath,i.foundSecretOptions&&i.names.size===0?null:i.names)}catch(i){I.logWarning(`QuickAdd ${e} could not inspect user-script settings '${n.originalPath}': ${i?.message??i}`)}return t}var MH=require("obsidian");Wd();Ie();function BT(r){return!!r&&typeof r=="object"}function FH(r){return Array.isArray(r)&&r.every(e=>typeof e=="string")}function Bte(r){return BT(r)?typeof r.id=="string"&&typeof r.name=="string"&&typeof r.type=="string":!1}function qte(r){return BT(r)?Bte(r.choice)&&FH(r.pathHint)&&(r.parentChoiceId===null||typeof r.parentChoiceId=="string"):!1}function Ute(r){if(!BT(r))return!1;let{kind:e,originalPath:t,contentEncoding:n,content:i}=r;return(e==="user-script"||e==="conditional-script"||e==="template"||e==="capture-template")&&typeof t=="string"&&n==="base64"&&typeof i=="string"}function PH(r){if(!BT(r))return!1;let{schemaVersion:e,quickAddVersion:t,createdAt:n,rootChoiceIds:i,choices:o,assets:s}=r;return typeof e=="number"&&Number.isInteger(e)&&e>=1&&typeof t=="string"&&typeof n=="string"&&FH(i)&&Array.isArray(o)&&o.every(qte)&&Array.isArray(s)&&s.every(Ute)}bt();Jr();async function qT(r,e){let t=e.lastIndexOf("/");if(t<0)return;let n=e.slice(0,t);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)}Ml();function $H(){return`QuickAdd Packages/quickadd-package-${new Date().toISOString().replace(/[:.]/g,"-")}.quickadd.json`}async function OH(r,e){let{choices:t,rootChoiceIds:n,quickAddVersion:i}=e,o=new Set(e.excludedChoiceIds??[]),s=e.createdAt??new Date().toISOString(),a=RT(t,n,{excludedChoiceIds:o}),l=new Set(a.choiceIds),c=NT(a.catalog,a.choiceIds),u=LT(a.catalog,a.choiceIds),d=Hte(c,u),p=await zte(r,d),f=VT(p.encodedAssets,"export"),m=a.choiceIds.map(y=>{let b=a.catalog.get(y);if(!b)throw new Error(`Choice '${y}' missing from catalog.`);let x=Ve(b.choice);return RH(x,l),GE(x,{secretOptionNamesByPath:f,stripUnknownStringSettings:!0}),{choice:x,pathHint:[...b.path],parentChoiceId:b.parentId}}),g=n.filter(y=>l.has(y));return{pkg:{schemaVersion:1,quickAddVersion:i,createdAt:s,rootChoiceIds:[...g],choices:m,assets:p.encodedAssets},missingChoiceIds:a.missingChoiceIds,missingAssets:p.missingAssets}}function Hte(r,e){let t=new Map;for(let n of r.userScriptPaths)n&&t.set(n,"user-script");for(let n of r.conditionalScriptPaths)n&&t.set(n,"conditional-script");for(let n of e.templatePaths)n&&(t.has(n)||t.set(n,"template"));for(let n of e.captureTemplatePaths)n&&(t.has(n)||t.set(n,"capture-template"));return Array.from(t.entries()).map(([n,i])=>({path:n,kind:i}))}async function zte(r,e){let t=[],n=[];for(let{path:i,kind:o}of e)try{if(!await r.vault.adapter.exists(i)){n.push({path:i,kind:o}),I.logWarning(`QuickAdd export skipped missing ${o}: ${i}`);continue}let a=await r.vault.adapter.read(i);t.push({kind:o,originalPath:i,contentEncoding:"base64",content:DH(a)})}catch(s){n.push({path:i,kind:o}),I.logWarning(`QuickAdd export failed to read ${o} '${i}': ${s?.message??s}`)}return{encodedAssets:t,missingAssets:n}}function RH(r,e){if(r.type!=="Multi")return;let t=r;if(!Array.isArray(t.choices)||t.choices.length===0){t.choices=[];return}t.choices=t.choices.filter(n=>Ue(n)&&e.has(n.id)).map(n=>(RH(n,e),n))}async function Wte(r,e){return Si.Prompt(r,"Overwrite existing file?",`A file already exists at '${e}'. Saving the package will overwrite it. Continue?`)}async function NH(r,e,t,n={}){let i=(0,MH.normalizePath)(t.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=>Wte(r,c)))(i))throw new Error(`Save cancelled: '${i}' already exists.`);await qT(r,i);let s=JSON.stringify(e,null,2);return await r.vault.adapter.write(i,s),{overwritten:o}}var jte=L('<p class="emptyState svelte-llmxn2">No choices match the current filter.</p>'),Gte=L('<span class="choicePath svelte-llmxn2"> </span>'),Yte=L('<li><label class="svelte-llmxn2"><input type="checkbox"/> <span class="choiceName svelte-llmxn2"> </span> <!> <span class="choiceType svelte-llmxn2"> </span></label></li>'),Kte=L('<ul class="svelte-llmxn2"></ul>'),Qte=L('<div class="warning svelte-llmxn2"><strong>Missing dependencies detected</strong> <p> </p></div>'),Xte=L("<p> </p>"),Zte=L('<li> <span class="assetKind svelte-llmxn2"> </span></li>'),Jte=L('<div><p>Missing assets:</p> <ul class="svelte-llmxn2"></ul></div>'),ere=L('<section class="warning svelte-llmxn2"><h4>Warnings</h4> <!> <!></section>'),tre=L('<div class="exportPackageModal svelte-llmxn2"><header class="svelte-llmxn2"><h2>Export QuickAdd package</h2> <p class="svelte-llmxn2">Select choices to bundle. Dependencies are added automatically.</p></header> <section class="controls svelte-llmxn2"><input type="text" placeholder="Filter choices" autocapitalize="off" autocorrect="off" class="svelte-llmxn2"/> <div class="controlButtons svelte-llmxn2"><button type="button" class="svelte-llmxn2">Select visible</button> <button type="button" class="svelte-llmxn2">Clear selection</button></div></section> <section class="choiceList svelte-llmxn2"><!></section> <section class="summary svelte-llmxn2"><h3 class="svelte-llmxn2">Package summary</h3> <div class="summaryGrid svelte-llmxn2"><div class="svelte-llmxn2"><strong class="svelte-llmxn2"> </strong> <span>Selected choices</span></div> <div class="svelte-llmxn2"><strong class="svelte-llmxn2"> </strong> <span>Total packaged</span></div> <div class="svelte-llmxn2"><strong class="svelte-llmxn2"> </strong> <span>Auto-included</span></div> <div class="svelte-llmxn2"><strong class="svelte-llmxn2"> </strong> <span>Scripts embedded</span></div> <div class="svelte-llmxn2"><strong class="svelte-llmxn2"> </strong> <span>Templates embedded</span></div></div> <!></section> <!> <section class="actions svelte-llmxn2"><div class="actionGroup svelte-llmxn2"><button type="button" class="secondary svelte-llmxn2"><!></button></div> <div class="actionGroup svelte-llmxn2"><label><span>Save to file</span> <div class="saveRow svelte-llmxn2"><input type="text" placeholder="QuickAdd Packages/quickadd-package-YYYY-MM-DD.quickadd.json" class="svelte-llmxn2"/> <button type="button" class="svelte-llmxn2"><!></button></div></label></div></section> <section class="footer svelte-llmxn2"><button type="button" class="secondary svelte-llmxn2">Cancel</button></section></div>'),rre={hash:"svelte-llmxn2",code:`.exportPackageModal.svelte-llmxn2 {display:flex;flex-direction:column;gap:1rem;width:min(640px, 100%);min-width:0;max-height:75vh;}header.svelte-llmxn2 p:where(.svelte-llmxn2) {margin:0;color:var(--text-muted);}.controls.svelte-llmxn2 {display:flex;gap:0.75rem;align-items:center;flex-wrap:wrap;}.controls.svelte-llmxn2 input:where(.svelte-llmxn2) {flex:1;}.controlButtons.svelte-llmxn2 {display:flex;gap:0.5rem;flex-wrap:wrap;justify-content:flex-end;}.choiceList.svelte-llmxn2 {flex:1;min-height:180px;max-height:260px;overflow:auto;border:1px solid var(--background-modifier-border);border-radius:6px;padding:0.5rem;}.choiceList.svelte-llmxn2 ul:where(.svelte-llmxn2) {list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:0.25rem;}.choiceList.svelte-llmxn2 label:where(.svelte-llmxn2) {display:flex;align-items:center;gap:0.5rem;padding:0.25rem 0.5rem;border-radius:4px;}.choiceList.svelte-llmxn2 label:where(.svelte-llmxn2):hover {background:var(--background-modifier-hover);}.choiceName.svelte-llmxn2 {font-weight:600;}.choicePath.svelte-llmxn2 {color:var(--text-muted);font-size:0.8rem;}.choiceType.svelte-llmxn2 {margin-left:auto;font-size:0.75rem;text-transform:uppercase;color:var(--text-faint);}.emptyState.svelte-llmxn2 {margin:0;color:var(--text-muted);text-align:center;}.summary.svelte-llmxn2 {border:1px solid var(--background-modifier-border);border-radius:6px;padding:0.75rem;display:flex;flex-direction:column;gap:0.5rem;}.summary.svelte-llmxn2 h3:where(.svelte-llmxn2) {margin:0 0 0.5rem 0;font-size:1rem;}.summaryGrid.svelte-llmxn2 {display:grid;grid-template-columns:repeat(auto-fit, minmax(140px, 1fr));gap:0.75rem;}.summaryGrid.svelte-llmxn2 div:where(.svelte-llmxn2) {display:flex;flex-direction:column;}.summaryGrid.svelte-llmxn2 strong:where(.svelte-llmxn2) {font-size:1.1rem;}
/* Neutral surface with an amber-tinted border (these are warnings, not
critical danger): ranked, not a blanket-red fill \u2014 matches the import
modal's CapabilityBanner treatment. */.warning.svelte-llmxn2 {border:1px solid var(--qa-sev-warning-border);background:var(--background-secondary);border-radius:var(--radius-m, 8px);padding:0.6rem 0.75rem;color:var(--text-normal);}.warning.svelte-llmxn2 ul:where(.svelte-llmxn2) {margin:0.25rem 0 0 1rem;padding:0;}.assetKind.svelte-llmxn2 {color:var(--text-muted);}.actions.svelte-llmxn2 {display:flex;flex-direction:column;gap:1rem;}.actionGroup.svelte-llmxn2 {display:flex;flex-direction:column;gap:0.5rem;}.saveRow.svelte-llmxn2 {display:flex;gap:0.5rem;}.saveRow.svelte-llmxn2 input:where(.svelte-llmxn2) {flex:1;}.footer.svelte-llmxn2 {display:flex;justify-content:flex-end;gap:0.5rem;margin-top:0.5rem;}.footer.svelte-llmxn2 button.secondary:where(.svelte-llmxn2) {background:transparent;}
@media (max-width: 600px) {.exportPackageModal.svelte-llmxn2 {max-height:90vh;padding-bottom:0.5rem;}.controls.svelte-llmxn2 {flex-direction:column;align-items:stretch;gap:0.5rem;}.controlButtons.svelte-llmxn2 {width:100%;flex-direction:column;gap:0.5rem;align-items:stretch;}.controlButtons.svelte-llmxn2 button:where(.svelte-llmxn2) {width:100%;}.choiceList.svelte-llmxn2 {min-height:160px;max-height:40vh;}.summaryGrid.svelte-llmxn2 {grid-template-columns:1fr;}.actions.svelte-llmxn2 {gap:0.75rem;}.actionGroup.svelte-llmxn2 {align-items:stretch;}.actionGroup.svelte-llmxn2 button:where(.svelte-llmxn2) {width:100%;}.saveRow.svelte-llmxn2 {flex-direction:column;}.saveRow.svelte-llmxn2 button:where(.svelte-llmxn2) {width:100%;}.footer.svelte-llmxn2 {flex-direction:column-reverse;align-items:stretch;}.footer.svelte-llmxn2 button:where(.svelte-llmxn2) {width:100%;}
}`};function wP(r,e){pe(e,!0),We(r,rre);let t={"user-script":"User script","conditional-script":"Conditional script",template:"Template file","capture-template":"Capture template"},n=Ce(""),i=Ce(ut(new Set)),o=Ce(ut(new Set)),s=Ce(ut($H())),a=Ce(null),l=Ce(null),c=F(()=>av(e.allChoices)),u=F(()=>EH(h(c),h(n))),d=F(()=>TH(h(c),h(i))),p=F(()=>kH(e.allChoices,h(d),h(o))),f=F(()=>new Map(h(c).map(we=>[we.id,we.path.join(" / ")])));function m(we){return we.type==="Multi"}function g(we){let qe=[];for(let k of et(we))Ue(k)&&qe.push(k.id,...g(k));return qe}function v(we,qe){let k=[we.id,...g(we)],R=new Set(h(i)),q=new Set(h(o));for(let J of k)qe?(R.add(J),q.delete(J)):(R.delete(J),q.add(J));j(i,R,!0),(!qe||h(o).size>0)&&j(o,q,!0)}function y(we){let qe=h(c).find(R=>R.id===we);if(!qe)return;let k=h(i).has(we);v(qe.choice,!k),j(a,null)}function b(){for(let we of h(u))v(we.choice,!0);j(a,null)}function x(){j(i,new Set,!0),j(o,new Set,!0),j(a,null)}function w(we){let{missingChoiceIds:qe,missingAssets:k}=we;return qe.length===0&&k.length===0?null:{missingChoices:qe,missingAssets:k}}async function T(){if(h(d).length===0)return new Bs.Notice("Select at least one choice to export."),null;try{let we=await OH(e.app,{choices:e.allChoices,rootChoiceIds:h(d),excludedChoiceIds:Array.from(h(o)),quickAddVersion:e.plugin.manifest.version});return j(a,w(we),!0),we}catch(we){return console.error(we),j(a,null),new Bs.Notice(`Export failed: ${we?.message??String(we)}`),null}}async function C(){if(!h(l)){j(l,"copy");try{let we=await T();if(!we)return;let qe=JSON.stringify(we.pkg,null,2);await A(qe),new Bs.Notice(`Copied package (${we.pkg.choices.length} choice${we.pkg.choices.length===1?"":"s"}) to clipboard.`),h(a)?new Bs.Notice("Package copied with warnings. Review details below."):e.close()}catch(we){console.error(we),new Bs.Notice(`Copy failed: ${we?.message??String(we)}`)}finally{j(l,null)}}}async function S(){if(h(l))return;let we=h(s).trim();if(!we){new Bs.Notice("Enter a file path before saving.");return}j(l,"save");try{let qe=await T();if(!qe)return;let{overwritten:k}=await NH(e.app,qe.pkg,we),R=qe.pkg.choices.length,q=`${R} choice${R===1?"":"s"}`;new Bs.Notice(k?`Overwrote package (${q}) at '${we}'.`:`Saved package (${q}) to '${we}'.`),h(a)?new Bs.Notice("Package saved with warnings. Review details below."):e.close()}catch(qe){let k=qe?.message??String(qe);if(k.startsWith("Save cancelled:")){new Bs.Notice("Save cancelled.");return}console.error(qe),new Bs.Notice(`Save failed: ${k}`)}finally{j(l,null)}}async function A(we){if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(we);return}let qe=document.body.createEl("textarea");qe.value=we,qe.setAttribute("readonly","true"),qe.style.position="fixed",qe.style.opacity="0",qe.focus(),qe.select();let k=document.execCommand("copy");if(document.body.removeChild(qe),!k)throw new Error("Clipboard copy is not supported in this environment.")}var D=tre(),P=_(B(D),2),U=B(P);Rt(U),ke(U,"spellcheck",!1);var K=_(U,2),W=B(K),ee=_(W,2);N(K),N(P);var me=_(P,2),O=B(me);{var H=we=>{var qe=jte();M(we,qe)},ce=we=>{var qe=Kte();Ot(qe,21,()=>h(u),k=>k.id,(k,R)=>{var q=Yte(),J=B(q),se=B(J);Rt(se);var oe=_(se,2),de=le(oe,!0),$e=_(oe,2);{var vt=Wr=>{var Wt=Gte(),Xn=le(Wt,!0);re(Gs=>ae(Xn,Gs),[()=>h(R).path.slice(0,-1).join(" \u203A ")]),M(Wr,Wt)};Y($e,Wr=>{h(R).path.length>1&&Wr(vt)})}var nr=_($e,2),lr=le(nr,!0);N(J),N(q),re((Wr,Wt)=>{Gp(q,`padding-left: ${h(R).depth*16}px`),ed(se,Wr),ae(de,Wt),ae(lr,h(R).choice.type)},[()=>h(i).has(h(R).id),()=>h(R).path.at(-1)]),Ae("change",se,()=>y(h(R).id)),M(k,q)}),N(qe),M(we,qe)};Y(O,we=>{h(u).length===0?we(H):we(ce,-1)})}N(me);var te=_(me,2),z=_(B(te),2),G=B(z),ie=B(G),xe=le(ie,!0);Gr(2),N(G);var ue=_(G,2),be=B(ue),Ke=le(be,!0);Gr(2),N(ue);var Oe=_(ue,2),Ee=B(Oe),He=le(Ee,!0);Gr(2),N(Oe);var Le=_(Oe,2),At=B(Le),mr=le(At,!0);Gr(2),N(Le);var zr=_(Le,2),ge=B(zr),ve=le(ge,!0);Gr(2),N(zr),N(z);var Fe=_(z,2);{var Je=we=>{var qe=Qte(),k=_(B(qe),2),R=le(k);N(qe),re(q=>ae(R,`The following choice IDs were referenced but not found:
${q??""}`),[()=>h(p).missingChoiceIds.join(", ")]),M(we,qe)};Y(Fe,we=>{h(p).missingChoiceIds.length>0&&we(Je)})}N(te);var mt=_(te,2);{var Ft=we=>{var qe=ere(),k=_(B(qe),2);{var R=se=>{var oe=Xte(),de=le(oe);re($e=>ae(de,`Missing choices:
${$e??""}`),[()=>h(a).missingChoices.map($e=>h(f).get($e)??$e).join(", ")]),M(se,oe)};Y(k,se=>{h(a).missingChoices.length>0&&se(R)})}var q=_(k,2);{var J=se=>{var oe=Jte(),de=_(B(oe),2);Ot(de,21,()=>h(a).missingAssets,$e=>$e.path,($e,vt)=>{var nr=Zte(),lr=B(nr),Wr=_(lr),Wt=le(Wr);N(nr),re(()=>{ae(lr,`${h(vt).path??""} `),ae(Wt,`(${t[h(vt).kind]??""})`)}),M($e,nr)}),N(de),N(oe),M(se,oe)};Y(q,se=>{h(a).missingAssets.length>0&&se(J)})}N(qe),M(we,qe)};Y(mt,we=>{h(a)&&we(Ft)})}var Qe=_(mt,2),zt=B(Qe),rr=B(zt),Qn=B(rr);{var di=we=>{var qe=ra("Copying\u2026");M(we,qe)},Z=we=>{var qe=ra("Copy JSON");M(we,qe)};Y(Qn,we=>{h(l)==="copy"?we(di):we(Z,-1)})}N(rr),N(zt);var De=_(zt,2),Pt=B(De),It=_(B(Pt),2),pi=B(It);Rt(pi);var Di=_(pi,2),Au=B(Di);{var wp=we=>{var qe=ra("Saving\u2026");M(we,qe)},Cp=we=>{var qe=ra("Save to file");M(we,qe)};Y(Au,we=>{h(l)==="save"?we(wp):we(Cp,-1)})}N(Di),N(It),N(Pt),N(De),N(Qe);var xp=_(Qe,2),Iu=le(xp);N(D),re(()=>{ae(xe,h(p).rootCount),ae(Ke,h(p).totalChoices),ae(He,h(p).dependencyCount),ae(mr,h(p).userScripts+h(p).conditionalScripts),ae(ve,h(p).templateFiles+h(p).captureTemplates),rr.disabled=h(l)!==null,Di.disabled=h(l)!==null,Iu.disabled=h(l)!==null}),wi(U,()=>h(n),we=>j(n,we)),Ae("click",W,b),Ae("click",ee,x),Ae("click",rr,C),wi(pi,()=>h(s),we=>j(s,we)),Ae("click",Di,S),Ae("click",Iu,function(...we){e.close?.apply(this,we)}),M(r,D),fe()}nt(["click","change"]);var HT=class extends LH.Modal{constructor(t,n,i){super(t);this.plugin=n;this.choices=i;this.handle=null}onOpen(){this.modalEl.addClass("quickAddModal","packageExportModal"),this.handle=Li(this.contentEl,wP,{app:this.app,plugin:this.plugin,allChoices:this.choices,close:()=>this.close()},{what:"the package exporter"})}onClose(){this.handle?.destroy(),this.handle=null}};var uz=require("obsidian");var ab=require("obsidian");dt();ht();var LP=require("obsidian");Ss();vr();vr();bt();un();function nre(r){return r.type==="Multi"}function ire(r){return r.type==="Macro"}function CP(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){e.onUnreadable?.();return}if(!t.has(r)){if(t.add(r),e.onChoice?.(r),nre(r))if(Array.isArray(r.choices))for(let n of r.choices)CP(n,e,t);else sr(r.choices)&&e.onUnreadable?.();ire(r)&&zT(Er(r.macro),e,t)}}}function zT(r,e,t){if(!Array.isArray(r)){sr(r)&&e.onUnreadable?.();return}for(let n of r){if(!n||typeof n!="object")continue;if(Array.isArray(n)){e.onUnreadable?.();continue}e.onCommand?.(n);let i=n;(n.type==="Conditional"||Array.isArray(i.thenCommands)||Array.isArray(i.elseCommands))&&(zT(i.thenCommands,e,t),zT(i.elseCommands,e,t));let s=n,a=n.type==="NestedChoice"||s.choice&&typeof s.choice=="object"?s.choice:void 0;a&&CP(a,e,t)}}function xP(r,e){let t=new Set;if(Array.isArray(r.choices))for(let i of r.choices)CP(i,e,t);else e.onUnreadable?.();let n=r.macros;if(Array.isArray(n))for(let i of n)zT(Er(i),e,t);else sr(n)&&e.onUnreadable?.()}function Gm(r){let e=!1;return xP(r,{onUnreadable:()=>{e=!0}}),e}function Ym(r,e){xP(r.settings,{onChoice:e})}function WT(r,e){xP(r,{onCommand:e})}function ore(r){return r.type==="AIAssistant"}function jT(r,e,t){let n=0;return WT({choices:r},i=>{if(!ore(i)||i.modelRef&&i.modelRef.name===i.model&&e.find(l=>l.id===i.modelRef?.providerId)?.models.some(l=>l.name===i.model)||!i.model||i.model==="Ask me")return;let o=e.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++,t?.(i,s)}),n}Ie();bt();Jr();la();TP();Ss();vr();bt();un();Ml();function GT(r,e,t,n){let i=r.id,o=e.get(i)??i;r.id=o;let s=o!==i;if(r.type==="Macro"){let a=r;s&&iu(a.macro)&&(a.macro.id=Kt()),kP(Er(a.macro),e,t,s,n)}if(r.type==="Multi"){let a=r;Array.isArray(a.choices)&&(a.choices=a.choices.filter(l=>Ue(l)&&t.has(l.id)).map(l=>GT(l,e,t,n)))}return r}function kP(r,e,t,n,i){for(let o of Ht(r))if(qr(o))switch(fU(o,i),n&&(o.id=Kt()),o.type){case"Choice":{let s=o,a=e.get(s.choiceId);a&&(s.choiceId=a);break}case"Conditional":{let s=o;kP(s.thenCommands,e,t,n,i),kP(s.elseCommands,e,t,n,i);break}case"NestedChoice":{let s=o;s.choice&&t.has(s.choice.id)&&(s.choice=GT(s.choice,e,t,i));break}default:break}}function _P(r,e){for(let t=0;t<r.length;t++){let n=r[t];if(Ue(n)){if(n.id===e.id)return r.splice(t,1,e),!0;if(_P(et(n),e))return!0}}return!1}function AP(r,e,t){for(let n of r)if(Ue(n)){if(n.id===e&&n.type==="Multi")return IP(n,t);if(AP(et(n),e,t))return!0}return!1}function IP(r,e){if(!Array.isArray(r.choices)){if(jo(r))return!1;r.choices=[]}let t=r.choices.findIndex(n=>Ue(n)&&n.id===e.id);return t!==-1?r.choices.splice(t,1,e):r.choices.push(e),!0}function BH(r,e){if(e.length===0)return null;let t=r,n=null;for(let i of e){let o=t.find(s=>Ue(s)&&s.type==="Multi"&&s.name===i);if(!o)return null;n=o,t=et(o)}return n}function YT(r,e){switch(r.type){case"Macro":{SP(Er(r.macro),e);break}case"Template":{let t=r,n=e.get(t.templatePath);n&&(t.templatePath=n);break}case"Capture":{let t=r,n=t.createFileIfItDoesntExist?.template;if(n){let i=e.get(n);i&&(t.createFileIfItDoesntExist={...t.createFileIfItDoesntExist,template:i})}break}case"Multi":{r.choices?.forEach(n=>YT(n,e));break}default:break}}function SP(r,e){for(let t of Ht(r))if(qr(t))switch(t.type){case"UserScript":{let n=t,i=e.get(n.path);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=t;if(n.condition.mode==="script"&&n.condition.scriptPath){let i=e.get(n.condition.scriptPath);i&&(n.condition={...n.condition,scriptPath:i})}SP(n.thenCommands,e),SP(n.elseCommands,e);break}case"NestedChoice":{let n=t;n.choice&&YT(n.choice,e);break}default:break}}var DP={"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 Qm(r){return DP[r].severity}function FP(r){return DP[r].label}function PP(r){return DP[r].description}Xe();bt();zg();vr();bt();un();var are=new Set(Object.values(fr));function qs(r){return r.filter(e=>!!e).join(" \u203A ")}function lre(r){let e=r.name?.trim();return e&&e.length>0?e:String(r.type)}function cre(r){if(r.mode==="script")return`script: ${r.scriptPath}${r.exportName?` (${r.exportName})`:""}`;let e=r.expectedValue!==void 0?` ${r.expectedValue}`:"";return`${r.variableName} ${r.operator}${e}`}function ure(r){return r.type==="Macro"}function dre(r){return r.type==="Multi"}function pre(r){return r.type==="Template"}function fre(r){return r.type==="Capture"}function mre(r){let e=r.fileExistsBehavior;return!e||e.kind!=="apply"?!1:e.mode==="overwrite"||e.mode==="appendTop"||e.mode==="appendBottom"}function $P(r){let e=[],t=new Set(r.choices.map(n=>n.choice.id));for(let n of r.choices){let i=n.choice,o=qs(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:[]};OP(i,s,[i.name],t,0),e.push(s)}return{choiceWalks:e}}function OP(r,e,t,n,i){if(r.command&&(e.registersCommand=!0,e.flags.add("registers-command")),ure(r)&&(r.runOnStartup&&(e.flags.add("run-on-startup"),e.rows.push({flag:"run-on-startup",severity:"critical",title:"Runs automatically every time Obsidian starts",detail:qs(t)})),MP(Er(r.macro),e,t,n,i)),pre(r)&&(r.templatePath&&e.usages.push({choiceId:e.choiceId,path:r.templatePath,asScript:!1,impliedKind:"template",breadcrumb:qs([...t,"template"])}),mre(r)&&e.flags.add("template-write")),fre(r)){e.flags.add("capture-writes");let o=r.createFileIfItDoesntExist;o?.enabled&&o.createWithTemplate&&o.template&&e.usages.push({choiceId:e.choiceId,path:o.template,asScript:!1,impliedKind:"capture-template",breadcrumb:qs([...t,"new-file template"])})}if(dre(r)&&Array.isArray(r.choices))for(let o of r.choices)Ue(o)&&(n.has(o.id)||OP(o,e,[...t,o.name],n,i))}function MP(r,e,t,n,i){for(let o of Ht(r)){if(!qr(o))continue;let s=lre(o),a=[...t,s],l={name:s,type:o.type,depth:i};switch(e.commands.push(l),o.type){case"UserScript":{let c=o;e.flags.add("user-script"),Object.assign(l,{flag:"user-script",scriptPath:c.path}),c.path&&(e.usages.push({choiceId:e.choiceId,path:c.path,asScript:!0,impliedKind:"user-script",breadcrumb:qs(a)}),e.rows.push({flag:"user-script",severity:"critical",title:"Runs custom JavaScript with full access to your vault and the network",detail:`${qs(a)} (${c.path})`,scriptPath:c.path}));break}case"Conditional":{let c=o,u=c.condition,d=u?cre(u):void 0,p=u?.mode==="script"&&!!u.scriptPath;if(Object.assign(l,{flag:p?"conditional-script":void 0,scriptPath:p?u.scriptPath:void 0,summary:d}),p){let f=u.scriptPath;e.flags.add("conditional-script"),e.usages.push({choiceId:e.choiceId,path:f,asScript:!0,impliedKind:"conditional-script",breadcrumb:qs(a)}),e.rows.push({flag:"conditional-script",severity:"critical",title:"Runs custom JavaScript chosen by a condition",detail:`${qs(a)} (${f})`,scriptPath:f})}MP(c.thenCommands??[],e,[...a,"then"],n,i+1),MP(c.elseCommands??[],e,[...a,"else"],n,i+1);break}case"NestedChoice":{let c=o;c.choice&&OP(c.choice,e,[...a,c.choice.name],n,i+1);break}case"Obsidian":{let c=o;e.flags.add("obsidian-command"),e.rows.push({flag:"obsidian-command",severity:"warning",title:"Triggers another Obsidian command",detail:`${qs(a)}${c.commandId?` (${c.commandId})`:""}`});break}case"AIAssistant":{e.flags.add("ai"),e.rows.push({flag:"ai",severity:"warning",title:"Sends note content to your AI provider over the network",detail:qs(a)});break}case"EditorCommand":{e.flags.add("editor-command");break}case"OpenFile":{e.flags.add("open-file");break}case"Choice":case"Wait":break;default:{l.type=String(o.type),are.has(String(o.type))||(e.flags.add("unknown-command"),l.flag="unknown-command",e.rows.push({flag:"unknown-command",severity:"warning",title:"Unknown capability. Review it manually.",detail:`${qs(a)} (${String(o.type)})`}));break}}}}function UH(r){return r==="user-script"||r==="conditional-script"}function hre(r,e){return UH(r)||!Nt.test(e)}function gre(r,e){if(!Nt.test(r))return!1;let t;try{t=au(e)}catch{return!1}let{code:n}=ll(t);return n!==null&&n.length>0}function vre(r,e){let t;try{t=au(e)}catch{return null}if(Nt.test(r)){let{code:n}=ll(t);return n!==null&&n.length>0?n:null}return t}var yre=/\bai\s*\.\s*(?:tools|agent|tool)\b|\btools\s*\.\s*(?:vault|workspace|system)\s*\(/;function bre(r){return yre.test(r)}var KT={critical:0,warning:1,info:2};function HH(r){let{choiceWalks:e}=$P(r),t=new Set;for(let n of e)for(let i of n.usages)i.path&&t.add(i.path);return Array.from(t)}function wre(r){let e=r.length;if(e===0)return 0;let t=0;return r.endsWith("==")?t=2:r.endsWith("=")&&(t=1),Math.max(0,Math.floor(e*3/4)-t)}function Cre(r,e){return KT[Qm(r)]-KT[Qm(e)]}function zH(r,e,t){let{choiceWalks:n}=$P(e),i=new Set(nn(r).map(C=>C.id)),o=new Map;for(let C of n)for(let S of C.usages){let A=o.get(S.path)??[];A.push(S),o.set(S.path,A)}let s=new Set;for(let[C,S]of o)S.some(A=>A.asScript)&&s.add(C);let a=new Set(e.assets.map(C=>C.originalPath)),l=e.assets.map(C=>{let S=o.get(C.originalPath)??[],A=s.has(C.originalPath),D=A||hre(C.kind,C.originalPath)||gre(C.originalPath,C.content);return{originalPath:C.originalPath,kind:C.kind,bundled:!0,executable:A,requiresReview:D,exists:t.has(C.originalPath),sizeBytes:wre(C.content),orphan:S.length===0,referencedBy:S}}),c=n.map(C=>{let S=i.has(C.choiceId),A=Array.from(C.flags);return S&&A.push("overwrites-existing-choice"),A.sort(Cre),{choiceId:C.choiceId,name:C.name,type:C.type,location:C.location,exists:S,registersCommand:C.registersCommand,flags:A,commands:C.commands}}),u=[];for(let[C,S]of o){if(a.has(C)||t.has(C))continue;let A=S.some(D=>D.asScript);u.push({path:C,asScript:A,breadcrumb:S[0]?.breadcrumb??C})}let d=l.filter(C=>C.orphan).map(C=>C.originalPath),p=[];for(let C of n)for(let S of C.rows)p.push(S);for(let C of l)C.executable&&(UH(C.kind)||p.push({flag:"mislabeled-executable",severity:"critical",title:"Runs a file as code even though it is labeled a template",detail:C.originalPath,scriptPath:C.originalPath}));for(let C of l)C.requiresReview&&(C.executable||p.push({flag:"bundled-script",severity:"critical",title:"Bundles a file that will be written to your vault and can be run as code",detail:C.originalPath,scriptPath:C.originalPath}));for(let C of l){if(!C.requiresReview)continue;let S=e.assets.find(D=>D.originalPath===C.originalPath);if(!S)continue;let A=vre(S.originalPath,S.content);!A||!bre(A)||p.push({flag:"ai-tools",severity:"critical",title:"Lets an AI model read and write your vault",detail:C.originalPath,scriptPath:C.originalPath})}let f=c.filter(C=>C.registersCommand).length;f>0&&p.push({flag:"registers-command",severity:"warning",title:"Adds commands to the command palette",detail:`${f} choice${f===1?"":"s"}`});let m=c.filter(C=>C.exists).length;m>0&&p.push({flag:"overwrites-existing-choice",severity:"warning",title:"Replaces choices that already exist in your vault",detail:`${m} choice${m===1?"":"s"}`});let g=l.filter(C=>C.exists).length;if(g>0&&p.push({flag:"overwrites-existing-file",severity:"warning",title:"Overwrites existing files in your vault",detail:`${g} file${g===1?"":"s"}`}),u.length>0){let C=u.filter(S=>S.asScript).length;p.push({flag:"missing-reference",severity:C>0?"critical":"warning",title:C>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"}`})}p.sort((C,S)=>KT[C.severity]-KT[S.severity]);let v=l.filter(C=>C.requiresReview).map(C=>C.originalPath),y=s.size,b=n.some(C=>C.flags.has("run-on-startup")),x=p.filter(C=>C.severity==="critical").length,w=p.filter(C=>C.severity==="warning").length,T={hasCritical:x>0,hasWarning:w>0,criticalCount:x,warningCount:w,runsOnStartup:b,scriptCount:y,registersCommandCount:f,overwritesChoices:m,overwritesFiles:g,missingCount:u.length};return{quickAddVersion:e.quickAddVersion,createdAt:e.createdAt,choiceCount:e.choices.length,fileCount:e.assets.length,choices:c,files:l,capabilityRows:p,missingReferences:u,orphanAssets:d,criticalScriptPaths:v,summary:T}}var qH=1e5;function xre(r){return typeof TextEncoder<"u"?new TextEncoder().encode(r).length:r.length}function Ere(r){if(r.length<1e3)return!1;let e=0,t=1,n=0;for(let o=0;o<r.length;o++)r[o]===`
`?(n>e&&(e=n),n=0,t++):n++;n>e&&(e=n);let i=r.length/t;return e>1e3||i>250}function QT(r,e){let t=r.assets.find(n=>n.originalPath===e);if(!t)return{found:!1,text:"",truncated:!1,sizeBytes:0,looksMinified:!1,error:"File is not bundled in this package."};try{let n=au(t.content),i=n.length>qH,o=i?n.slice(0,qH):n;return{found:!0,text:o,truncated:i,sizeBytes:xre(n),looksMinified:Ere(o)}}catch(n){return{found:!0,text:"",truncated:!1,sizeBytes:0,looksMinified:!1,error:n instanceof Error?n.message:String(n)}}}function WH(r){return r.summary.hasCritical}function jH(r,e){return r.criticalScriptPaths.every(t=>e.has(t))}var GH=require("obsidian");un();vr();bt();function ib(r){let e;try{e=JSON.parse(r)}catch(o){throw new Error(`Package content is not valid JSON: ${o?.message??o}`)}if(!PH(e))throw new Error("Content is not a valid QuickAdd package.");if(e.schemaVersion>1)throw new Error(`Package schema version ${e.schemaVersion} is newer than this plugin supports (${1}).`);let t=Tre(e.assets);if(t!==null)throw new Error(`Package contains duplicate asset path "${t}". Each asset must have a unique path.`);let n=kre(e.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=Sre(e.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 e}function Tre(r){let e=new Set;for(let t of r){let n=(0,GH.normalizePath)(t.originalPath??"");if(e.has(n))return t.originalPath;e.add(n)}return null}function kre(r){let e=new Map,t=null,n=i=>{if(t!==null||!i||typeof i!="object")return;let o=i.id;if(typeof o=="string"){let s=NP(i),a=e.get(o);if(a===void 0)e.set(o,s);else if(a!==s){t=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"&&RP(Ht(Er(i.macro)),n)};for(let i of r){if(t!==null)break;n(i?.choice)}return t}function RP(r,e){if(Array.isArray(r)){for(let t of r)if(t){if(t.type==="NestedChoice")e(t.choice);else if(t.type==="Conditional"){let n=t;RP(n.thenCommands,e),RP(n.elseCommands,e)}}}}function NP(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(NP).join(",")}]`;let e=r;return`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${NP(e[n])}`).join(",")}}`}function Sre(r){let e=new Map(r.map(t=>[t.choice.id,t]));for(let t of r){let n=t.parentChoiceId;if(n===null)continue;let i=e.get(n);if(!i)continue;let o=i.choice;if(!et(o).some(a=>a?.id===t.choice.id))return t.choice.id}return null}async function YH(r,e){if(Dr(e))throw new Error(`Refusing to read a package outside the vault: "${e}".`);let t=(0,LP.normalizePath)(e.trim());if(!t)throw new Error("Package path cannot be empty.");if(!await r.vault.adapter.exists(t))throw new Error(`Package file not found: ${t}`);let i=await r.vault.adapter.read(t);return{pkg:ib(i),path:t}}async function KH(r,e,t){let n=new Map(nn(e).map(s=>[s.id,s])),i=t.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 t.assets){let a=Dr(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 XT(r,e,t){let n=new Set([...t.assets.map(a=>a.originalPath),...HH(t)]),i=new Set;await Promise.all(Array.from(n,async a=>{a&&(Dr(a)||await XH(r,a)&&i.add(a))}));let o=zH(e,t,i),{summary:s}=o;return I.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 _re(r){let t=(r??"").trim();if(!t)throw new Error("Package asset has an empty destination path.");let n=t.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,LP.normalizePath)(t);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 QH(r){let{app:e,existingChoices:t,pkg:n}=r,i=new Map(r.choiceDecisions.map(D=>[D.choiceId,D.mode])),o=new Map(r.assetDecisions.map(D=>[D.originalPath,D])),s=new Map(n.choices.map(D=>[D.choice.id,D])),a=VT(n.assets,"import"),l=new Set(n.choices.filter(D=>i.get(D.choice.id)!=="skip").map(D=>D.choice.id)),c=new Map,u=new Set,d=new Map,p=D=>{if(!l.has(D))return!1;let P=c.get(D);if(P!==void 0)return P;if(u.has(D))return c.set(D,!1),!1;u.add(D);try{let U=s.get(D)?.parentChoiceId,K=i.get(D)==="duplicate"||!!(U&&(i.get(U)==="duplicate"||l.has(U)&&p(U)));return c.set(D,K),K}finally{u.delete(D)}};for(let D of n.choices){if(!l.has(D.choice.id))continue;let U=p(D.choice.id)?Kt():D.choice.id;d.set(D.choice.id,U)}let f=Ve(t),m=[],g=[],v=[],y=new Map;for(let D of n.choices){if(!l.has(D.choice.id)){v.push(D.choice.id);continue}let P=Ve(D.choice),U=GT(P,d,l,{secretOptionNamesByPath:a,stripUnknownStringSettings:!0});y.set(D.choice.id,U)}r.aiProviders?.length&&jT(Array.from(y.values()),r.aiProviders);let b=new Set;for(let D of n.choices){let P=D.choice.id;if(!l.has(P)||b.has(P))continue;let U=y.get(P);if(!U)continue;let K=U.id,W=i.get(P)??"import",ee=D.parentChoiceId;if(ee&&l.has(ee)?y.get(ee):null){b.add(P);continue}if((W==="overwrite"||W==="import")&&_P(f,U)){g.push(K),b.add(P);continue}if(ee){let H=d.get(ee)??ee;if(AP(f,H,U)){m.push(K),b.add(P);continue}let te=BH(f,D.pathHint.slice(0,-1));if(te&&IP(te,U)){m.push(K),b.add(P);continue}I.logWarning(`QuickAdd import: could not locate parent for '${D.choice.name}'. Adding to root.`)}let O=f.findIndex(H=>Ue(H)&&H.id===K);O!==-1?(f.splice(O,1,U),g.push(K)):(f.push(U),m.push(K)),b.add(P)}let x=new Map,w=[],T=[],C=n.assets.map(D=>{let U=o.get(D.originalPath)?.destinationPath?.trim(),K=_re(U||D.originalPath);return{asset:D,destinationPath:K}}),S=await Are(e),A=new Map;for(let{asset:D,destinationPath:P}of C){if(o.get(D.originalPath)?.mode==="skip")continue;let U=S?P.toLowerCase():P,K=A.get(U);if(K)throw new Error(`Refusing to import: assets "${K.originalPath}" and "${D.originalPath}" resolve to the same destination ("${P}"). Rename one so each imported file is unique.`);A.set(U,{originalPath:D.originalPath,destinationPath:P})}for(let{destinationPath:D}of C)await Km(e,D);for(let{asset:D,destinationPath:P}of C){let U=o.get(D.originalPath),K=await XH(e,P);if((U?.mode??(K?"overwrite":"write"))==="skip"){T.push(P);continue}await qT(e,P);let ee=au(D.content);await e.vault.adapter.write(P,ee),w.push(P),x.set(D.originalPath,P)}for(let D of y.values())YT(D,x);return{updatedChoices:f,addedChoiceIds:m,overwrittenChoiceIds:g,skippedChoiceIds:v,writtenAssets:w,skippedAssets:T}}async function XH(r,e){try{return await r.vault.adapter.exists(e)}catch{return!1}}async function Are(r){let e=r.vault.configDir;if(!e)return!1;let t=e===e.toLowerCase()?e.toUpperCase():e.toLowerCase();if(t===e)return!1;try{return await r.vault.adapter.exists(t)}catch{return!1}}var ZT=require("obsidian");function ob(r,e){return e&&(0,ZT.setTooltip)(r,e),{update(t){(0,ZT.setTooltip)(r,t??"")},destroy(){(0,ZT.setTooltip)(r,"")}}}var Ire=L("<span> </span>"),Dre={hash:"svelte-5jkd35",code:`.qa-import-tag.svelte-5jkd35 {display:inline-flex;align-items:center;padding:0.05rem 0.4rem;border-radius:var(--radius-s, 4px);font-size:0.7rem;font-weight:600;letter-spacing:0.02em;text-transform:uppercase;line-height:1.45;white-space:nowrap;cursor:help;}
/* Critical: darkened red so white text clears WCAG AA (~5:1) at this size,
where Obsidian's stock --color-red (#e93147) lands at ~3.5:1. */.qa-import-tag.critical.svelte-5jkd35 {background:var(--qa-sev-critical-pill);color:#fff;}
/* Warning: amber is medium-luminance in both themes, so near-black text
(~8:1) beats white-on-amber (~2.9:1). Fallback #ff8c00 matches styles.css
and clears AA (~5.9:1) with #1a1a1a. */.qa-import-tag.warning.svelte-5jkd35 {background:var(--color-orange, #ff8c00);color:#1a1a1a;}.qa-import-tag.info.svelte-5jkd35 {background:var(--background-modifier-border);color:var(--text-normal);}`};function sb(r,e){pe(e,!0),We(r,Dre);let t=F(()=>Qm(e.flag)),n=F(()=>FP(e.flag)),i=F(()=>PP(e.flag));var o=Ire();let s;var a=le(o,!0);Jt(o,(l,c)=>ob?.(l,c),()=>h(i)),re(()=>{s=it(o,1,"qa-import-tag svelte-5jkd35",null,s,{critical:h(t)==="critical",warning:h(t)==="warning",info:h(t)==="info"}),ae(a,h(n))}),M(r,o),fe()}var Fre=L('<span class="qa-import-banner-detail svelte-tb9yz"> </span>'),Pre=L('<li><span class="qa-import-banner-tag svelte-tb9yz"><!></span><span class="qa-import-banner-title svelte-tb9yz"> </span> <!></li>'),Mre=L('<p class="qa-import-banner-note svelte-tb9yz">Takes effect after you reload the plugin or restart Obsidian.</p>'),$re=L('<section aria-label="What this package can do"><div class="qa-import-banner-head svelte-tb9yz"><span class="qa-import-banner-icon svelte-tb9yz"><!></span> <h3 class="svelte-tb9yz">What this package can do</h3></div> <ul class="qa-import-banner-rows svelte-tb9yz"></ul> <!></section>'),Ore={hash:"svelte-tb9yz",code:`.qa-import-banner.svelte-tb9yz {background:var(--background-secondary);border:1px solid var(--background-modifier-border);border-radius:var(--radius-m, 8px);padding:0.85rem;display:flex;flex-direction:column;gap:0.5rem;}
/* Critical packages get a red-tinted hairline + red icon, not a blanket-red
fill: severity stays ranked and all text keeps its contrast on the neutral
surface. (A solid colored side-stripe would be the banned pattern.) */.qa-import-banner.critical.svelte-tb9yz {border-color:var(--qa-sev-critical-border);}.qa-import-banner-head.svelte-tb9yz {display:flex;align-items:center;gap:0.5rem;}.qa-import-banner-icon.svelte-tb9yz {display:inline-flex;color:var(--text-warning, var(--text-muted));}.qa-import-banner.critical.svelte-tb9yz .qa-import-banner-icon:where(.svelte-tb9yz) {color:var(--text-error);}.qa-import-banner-head.svelte-tb9yz h3:where(.svelte-tb9yz) {margin:0;font-size:1rem;}.qa-import-banner-rows.svelte-tb9yz {list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:0.25rem;}
/* The pill is an inline lead-in to the sentence (not a fixed left column),
so long titles wrap full-width under it instead of leaving a dead column
of whitespace beside a one-line pill. */.qa-import-banner-rows.svelte-tb9yz li:where(.svelte-tb9yz) {display:block;padding:0.4rem 0.5rem;border-radius:var(--radius-s, 4px);}.qa-import-banner-tag.svelte-tb9yz {display:inline-block;vertical-align:middle;margin:0 0.4rem 0.15rem 0;}
/* Faint per-row severity wash so critical rows read hottest while warnings
recede, without saturating the whole banner. Composited over the banner
surface (not transparent) so the tint is a solid, predictable colour. */.qa-import-banner-rows.svelte-tb9yz li.sev-critical:where(.svelte-tb9yz) {background:var(--qa-sev-critical-wash);}.qa-import-banner-rows.svelte-tb9yz li.sev-warning:where(.svelte-tb9yz) {background:var(--qa-sev-warning-wash);}.qa-import-banner-rows.svelte-tb9yz li.sev-info:where(.svelte-tb9yz) {background:var(--qa-sev-info-wash);}.qa-import-banner-title.svelte-tb9yz {line-height:1.4;}.qa-import-banner-detail.svelte-tb9yz {display:block;margin-top:0.15rem;font-size:var(--font-ui-smaller, 0.8rem);color:var(--text-muted);overflow-wrap:anywhere;}.qa-import-banner-note.svelte-tb9yz {margin:0;font-size:var(--font-ui-smaller, 0.8rem);color:var(--text-muted);}`};function VP(r,e){pe(e,!0),We(r,Ore);let t=F(()=>e.preview.summary.runsOnStartup||e.preview.summary.registersCommandCount>0);var n=$re();let i;var o=B(n),s=B(o),a=B(s);Et(a,{iconId:"alert-triangle",size:17}),N(s),Gr(2),N(o);var l=_(o,2);Ot(l,21,()=>e.preview.capabilityRows,d=>d.flag+d.detail,(d,p)=>{var f=Pre();let m;var g=B(f),v=B(g);sb(v,{get flag(){return h(p).flag}}),N(g);var y=_(g),b=le(y,!0),x=_(y,2);{var w=T=>{var C=Fre(),S=le(C,!0);re(()=>ae(S,h(p).detail)),M(T,C)};Y(x,T=>{h(p).detail&&T(w)})}N(f),re(()=>{m=it(f,1,"svelte-tb9yz",null,m,{"sev-critical":h(p).severity==="critical","sev-warning":h(p).severity==="warning","sev-info":h(p).severity==="info"}),ae(b,h(p).title)}),M(d,f)}),N(l);var c=_(l,2);{var u=d=>{var p=Mre();M(d,p)};Y(c,d=>{h(t)&&d(u)})}N(n),re(()=>i=it(n,1,"qa-import-banner svelte-tb9yz",null,i,{critical:e.preview.summary.hasCritical})),M(r,n),fe()}var Rre=L('<span class="qa-import-file-exec svelte-lmqem5">Executable</span>'),Nre=L('<span class="qa-import-file-reviewed svelte-lmqem5"><!> Reviewed</span>'),Lre=L('<span class="qa-import-file-orphan svelte-lmqem5">Unused</span>'),Vre=L("<option>Overwrite</option>"),Bre=L(`<p class="qa-import-file-skip-warn svelte-lmqem5" 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.</p>`),qre=L('<p class="qa-import-file-error svelte-lmqem5"> </p>'),Ure=L(`<p class="qa-import-file-warn svelte-lmqem5">Minified: cannot be visually reviewed. Import
only if you trust the source.</p>`),Hre=L('<p class="qa-import-file-warn svelte-lmqem5"> </p>'),zre=L('<!> <pre class="qa-import-file-code svelte-lmqem5" tabindex="0" role="region"> </pre> <!>',1),Wre=L('<div class="qa-import-file-preview svelte-lmqem5"><!></div>'),jre=L('<div><div class="qa-import-file-head svelte-lmqem5"><!> <span> </span> <span class="qa-import-file-arrow svelte-lmqem5" aria-hidden="true">\u2192</span> <span class="qa-import-file-dest svelte-lmqem5"> </span></div> <div class="qa-import-file-badges svelte-lmqem5"><!> <!> <!> <span class="qa-import-file-size svelte-lmqem5"> </span></div> <div class="qa-import-file-fields svelte-lmqem5"><label class="qa-import-file-field svelte-lmqem5"><span class="qa-import-file-field-name svelte-lmqem5">Destination</span> <input type="text" placeholder="vault/path/to/file" class="svelte-lmqem5"/></label> <label class="qa-import-file-field svelte-lmqem5"><span class="qa-import-file-field-name svelte-lmqem5">Action</span> <select class="dropdown svelte-lmqem5"><option>Write</option><!><option>Skip</option></select></label></div> <!> <button type="button" class="qa-import-file-toggle svelte-lmqem5"><span><!></span> <span> </span></button> <div><div class="qa-import-file-preview-inner svelte-lmqem5"><!></div></div></div>'),Gre={hash:"svelte-lmqem5",code:`.qa-import-file.svelte-lmqem5 {border:1px solid var(--background-modifier-border);border-radius:var(--radius-m, 8px);padding:0.6rem 0.75rem;display:flex;flex-direction:column;gap:0.5rem;background:var(--background-secondary);}.qa-import-file.overwrite.svelte-lmqem5 {border-color:var(--qa-sev-critical-border);}.qa-import-file-head.svelte-lmqem5 {display:flex;align-items:center;gap:0.4rem;flex-wrap:wrap;}.qa-import-file-status.svelte-lmqem5 {font-size:0.78rem;font-weight:700;letter-spacing:0.01em;color:var(--text-muted);}.qa-import-file-status.overwrite.svelte-lmqem5 {color:var(--text-error);}.qa-import-file-arrow.svelte-lmqem5 {color:var(--text-muted);}.qa-import-file-dest.svelte-lmqem5 {font-family:var(--font-monospace);font-size:0.85rem;overflow-wrap:anywhere;}.qa-import-file-badges.svelte-lmqem5 {display:flex;flex-wrap:wrap;gap:0.35rem;align-items:center;}.qa-import-file-orphan.svelte-lmqem5 {display:inline-flex;padding:0.05rem 0.4rem;border-radius:var(--radius-s, 4px);font-size:0.7rem;background:var(--background-modifier-hover);
/* --text-normal (not --text-muted) so the badge clears AA on the hover
surface in dark themes too. */color:var(--text-normal);cursor:help;}.qa-import-file-exec.svelte-lmqem5 {display:inline-flex;padding:0.05rem 0.4rem;border-radius:var(--radius-s, 4px);font-size:0.7rem;font-weight:700;letter-spacing:0.02em;text-transform:uppercase;background:var(--qa-sev-critical-pill);color:#fff;cursor:help;}.qa-import-file-reviewed.svelte-lmqem5 {display:inline-flex;align-items:center;gap:0.15rem;font-size:0.72rem;color:var(--text-success, var(--color-green, #0aa344));}.qa-import-file-size.svelte-lmqem5 {font-size:0.72rem;color:var(--text-faint);margin-left:auto;}
/* Obsidian Setting-row geometry: field name on the left at --text-normal,
control docked right at its native height \u2014 not a stacked label-above
form field (which read as non-native). */.qa-import-file-fields.svelte-lmqem5 {display:flex;flex-direction:column;gap:0.4rem;}.qa-import-file-field.svelte-lmqem5 {display:flex;align-items:center;gap:1rem;}.qa-import-file-field-name.svelte-lmqem5 {flex:1 1 auto;min-width:0;color:var(--text-normal);}.qa-import-file-field.svelte-lmqem5 input:where(.svelte-lmqem5) {flex:0 1 300px;min-width:0;}.qa-import-file-field.svelte-lmqem5 select:where(.svelte-lmqem5) {flex:0 0 auto;}
/* The native Obsidian input/dropdown focus box-shadow handles focus; no
custom outline (which would read as non-native). */.qa-import-file-field.svelte-lmqem5 input:where(.svelte-lmqem5):disabled {opacity:0.5;cursor:not-allowed;}.qa-import-file-toggle.svelte-lmqem5 {display:inline-flex;align-items:center;gap:0.3rem;align-self:flex-start;background:transparent;border:none;box-shadow:none;padding:0.1rem 0.2rem;margin-left:-0.2rem;cursor:pointer;color:var(--text-accent);font-size:0.85rem;border-radius:var(--radius-s, 4px);}.qa-import-file-toggle.svelte-lmqem5:hover {color:var(--interactive-accent-hover, var(--text-accent));text-decoration:underline;}.qa-import-file-toggle.svelte-lmqem5:focus-visible {outline:2px solid var(--interactive-accent);outline-offset:1px;}.qa-import-file-chevron.svelte-lmqem5 {display:inline-flex;transition:transform 180ms ease;}.qa-import-file-chevron.open.svelte-lmqem5 {transform:rotate(90deg);}.qa-import-file-preview-wrap.svelte-lmqem5 {display:grid;grid-template-rows:0fr;transition:grid-template-rows 200ms ease;}.qa-import-file-preview-wrap.open.svelte-lmqem5 {grid-template-rows:1fr;}.qa-import-file-preview-inner.svelte-lmqem5 {overflow:hidden;min-height:0;}.qa-import-file-preview.svelte-lmqem5 {display:flex;flex-direction:column;gap:0.4rem;padding-top:0.2rem;}.qa-import-file-warn.svelte-lmqem5 {margin:0;color:var(--text-warning, var(--text-muted));font-size:var(--font-ui-smaller, 0.85rem);}.qa-import-file-skip-warn.svelte-lmqem5 {margin:0;padding:0.4rem 0.5rem;border-radius:var(--radius-s, 4px);background:var(--qa-sev-warning-wash);color:var(--text-normal);font-size:var(--font-ui-smaller, 0.85rem);line-height:1.4;}.qa-import-file-error.svelte-lmqem5 {margin:0;color:var(--text-error);font-size:var(--font-ui-smaller, 0.85rem);}.qa-import-file-code.svelte-lmqem5 {margin:0;max-height:240px;overflow:auto;padding:0.5rem 0.6rem;border-radius:var(--radius-s, 4px);background:var(--background-modifier-form-field);border:1px solid var(--background-modifier-border);font-family:var(--font-monospace);font-size:0.8rem;line-height:1.5;white-space:pre;tab-size:4;}.qa-import-file-code.svelte-lmqem5:focus-visible {outline:2px solid var(--interactive-accent);outline-offset:1px;}
@media (max-width: 600px) {
/* Stack control under its name and let it use the full width on narrow
screens, where a right-docked control would be cramped. */.qa-import-file-field.svelte-lmqem5 {flex-wrap:wrap;gap:0.25rem;}.qa-import-file-field.svelte-lmqem5 input:where(.svelte-lmqem5),
.qa-import-file-field.svelte-lmqem5 select:where(.svelte-lmqem5) {flex:1 1 100%;}.qa-import-file-size.svelte-lmqem5 {margin-left:0;}
}.is-mobile .qa-import-file-toggle.svelte-lmqem5 {min-height:36px;padding:0.4rem 0.3rem;}
@media (prefers-reduced-motion: reduce) {.qa-import-file-chevron.svelte-lmqem5,
.qa-import-file-preview-wrap.svelte-lmqem5 {transition:none;}
}`};function BP(r,e){pe(e,!0),We(r,Gre);let t=ne(e,"reviewed",3,!1),n=Ce(!1),i=F(()=>h(n)?QT(e.pkg,e.file.originalPath):null),o=F(()=>`qa-file-preview-${e.file.originalPath.replace(/[^a-zA-Z0-9_-]/g,"-")}`);function s(ve){return ve<1024?`${ve} B`:ve<1024*1024?`${(ve/1024).toFixed(1)} KB`:`${(ve/(1024*1024)).toFixed(1)} MB`}function a(){j(n,!h(n)),h(n)&&e.file.requiresReview&&e.onReviewed(e.file.originalPath)}function l(ve){e.onPathInput(ve.currentTarget.value)}function c(ve){e.onModeChange(ve.currentTarget.value)}var u=jre();let d;var p=B(u),f=B(p);{let ve=F(()=>e.destinationExists?"file-warning":"file-plus");Et(f,{get iconId(){return h(ve)},size:16})}var m=_(f,2);let g;var v=le(m,!0),y=_(m,4),b=le(y,!0);N(p);var x=_(p,2),w=B(x);{var T=ve=>{var Fe=Rre();Jt(Fe,(Je,mt)=>ob?.(Je,mt),()=>"Runs as code when its choice runs. It can read, change, or delete files in your vault and access the network."),M(ve,Fe)};Y(w,ve=>{e.file.executable&&ve(T)})}var C=_(w,2);{var S=ve=>{var Fe=Nre(),Je=B(Fe);Et(Je,{iconId:"check",size:12}),Gr(),N(Fe),M(ve,Fe)};Y(C,ve=>{t()&&e.mode!=="skip"&&e.file.requiresReview&&ve(S)})}var A=_(C,2);{var D=ve=>{var Fe=Lre();Jt(Fe,(Je,mt)=>ob?.(Je,mt),()=>"Bundled in this package but not referenced by any choice."),M(ve,Fe)};Y(A,ve=>{e.file.orphan&&ve(D)})}var P=_(A,2),U=le(P,!0);N(x);var K=_(x,2),W=B(K),ee=_(B(W),2);Rt(ee),N(W);var me=_(W,2),O=_(B(me),2),H=B(O);H.value=H.__value="write";var ce=_(H);{var te=ve=>{var Fe=Vre();Fe.value=Fe.__value="overwrite",M(ve,Fe)};Y(ce,ve=>{e.destinationExists&&ve(te)})}var z=_(ce);z.value=z.__value="skip",N(O);var G;dc(O),N(me),N(K);var ie=_(K,2);{var xe=ve=>{var Fe=Bre();M(ve,Fe)};Y(ie,ve=>{e.file.requiresReview&&e.mode==="skip"&&ve(xe)})}var ue=_(ie,2),be=B(ue);let Ke;var Oe=B(be);Et(Oe,{iconId:"chevron-right",size:14}),N(be);var Ee=_(be,2),He=le(Ee,!0);N(ue);var Le=_(ue,2);let At;var mr=B(Le),zr=B(mr);{var ge=ve=>{var Fe=Wre(),Je=B(Fe);{var mt=Qe=>{var zt=qre(),rr=le(zt);re(()=>ae(rr,`Preview unavailable: ${h(i).error??""}`)),M(Qe,zt)},Ft=Qe=>{var zt=zre(),rr=Te(zt);{var Qn=It=>{var pi=Ure();M(It,pi)};Y(rr,It=>{h(i).looksMinified&&It(Qn)})}var di=_(rr,2),Z=le(di,!0),De=_(di,2);{var Pt=It=>{var pi=Hre(),Di=le(pi);re(()=>ae(Di,`Preview truncated. The full ${e.file.executable?"script will run":"file will be imported"}.`)),M(It,pi)};Y(De,It=>{h(i).truncated&&It(Pt)})}re(()=>{ke(di,"aria-label",`Contents of ${e.file.originalPath??""}`),ae(Z,h(i).text)}),M(Qe,zt)};Y(Je,Qe=>{h(i).error?Qe(mt):Qe(Ft,-1)})}N(Fe),M(ve,Fe)};Y(zr,ve=>{h(i)&&ve(ge)})}N(mr),N(Le),N(u),re(ve=>{d=it(u,1,"qa-import-file svelte-lmqem5",null,d,{overwrite:e.destinationExists}),g=it(m,1,"qa-import-file-status svelte-lmqem5",null,g,{overwrite:e.destinationExists}),ae(v,e.destinationExists?"Will overwrite":"New file"),ae(b,e.destinationPath),ae(U,ve),bi(ee,e.destinationPath),ee.disabled=e.mode==="skip",G!==(G=e.mode)&&(O.value=(O.__value=G)??"",uc(O,G)),ke(ue,"aria-expanded",h(n)),ke(ue,"aria-controls",h(o)),Ke=it(be,1,"qa-import-file-chevron svelte-lmqem5",null,Ke,{open:h(n)}),ae(He,h(n)?"Hide contents":"View contents"),At=it(Le,1,"qa-import-file-preview-wrap svelte-lmqem5",null,At,{open:h(n)}),ke(Le,"id",h(o))},[()=>s(e.file.sizeBytes)]),Ae("input",ee,l),Ae("change",O,c),Ae("click",ue,a),M(r,u),fe()}nt(["input","change","click"]);var Yre=L('<p id="qa-import-ack-hint" class="ackGate-hint svelte-1n28r6s"> </p>'),Kre=L('<section><label class="ackGate-label svelte-1n28r6s"><input id="qa-import-ack-checkbox" type="checkbox" class="svelte-1n28r6s"/> <span> </span></label> <!></section>'),Qre={hash:"svelte-1n28r6s",code:".ackGate.svelte-1n28r6s {display:flex;flex-direction:column;gap:0.4rem;padding:0.75rem;border:1px solid var(--background-modifier-border);border-radius:var(--radius-m, 8px);background:var(--background-secondary);}.ackGate.critical.svelte-1n28r6s {border-color:var(--qa-sev-critical-border);}.ackGate-label.svelte-1n28r6s {display:flex;align-items:flex-start;gap:0.5rem;font-weight:600;cursor:pointer;}.ackGate-label.svelte-1n28r6s:has(input:where(.svelte-1n28r6s):disabled) {cursor:not-allowed;opacity:0.6;}.ackGate-label.svelte-1n28r6s input:where(.svelte-1n28r6s) {margin-top:0.2rem;flex-shrink:0;}.ackGate-label.svelte-1n28r6s input:where(.svelte-1n28r6s):focus-visible {outline:2px solid var(--interactive-accent);outline-offset:2px;}.ackGate-hint.svelte-1n28r6s {margin:0;font-size:var(--font-ui-smaller, 0.8rem);color:var(--text-muted);}"};function qP(r,e){pe(e,!0),We(r,Qre);let t=ne(e,"acknowledged",15,!1),n=F(()=>e.preview?.summary.hasCritical),i=F(()=>e.preview?.criticalScriptPaths.length??0),o=F(()=>e.preview?.missingReferences.some(g=>g.asScript)??!1),s=F(()=>h(i)>0?h(o)?"I have reviewed each bundled script 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.":h(o)?"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 a=Kre();let l;var c=B(a),u=B(c);Rt(u);var d=_(u,2),p=le(d,!0);N(c);var f=_(c,2);{var m=g=>{var v=Yre(),y=le(v);re(()=>ae(y,`Open \u201CView contents\u201D on each of the ${h(i)??""} executable
script${h(i)===1?"":"s"} above to enable this.`)),M(g,v)};Y(f,g=>{h(i)>0&&!e.fullyReviewed&&g(m)})}N(a),re(()=>{l=it(a,1,"ackGate svelte-1n28r6s",null,l,{critical:h(n)}),ed(u,t()),u.disabled=!e.fullyReviewed,ke(u,"aria-describedby",h(i)>0&&!e.fullyReviewed?"qa-import-ack-hint":void 0),ae(p,h(s))}),Ae("change",u,g=>t(g.currentTarget.checked)),M(r,a),fe()}nt(["change"]);var UP=require("obsidian");la();function ZH(r,e){return r==="skip"?r:e&&r==="write"?"overwrite":!e&&r==="overwrite"?"write":r}function HP(r,e){return!e&&r==="overwrite"?"import":r}function JH(r,e,t){let n=e(r),i=r.exists||t(n);return{mode:i?"overwrite":"write",destinationPath:n,destinationExists:i}}function ez(r,e){let t=e(r);return{mode:t?"overwrite":"write",destinationPath:r,destinationExists:t}}function tz(r,e,t){let n=new Map;for(let i of r)n.set(i.originalPath,JH(i,e,t));return n}function rz(r,e,t,n){return r.get(e.originalPath)??JH(e,t,n)}function nz(r){let e=new Map;for(let t of r)e.set(t.choiceId,t.exists?"overwrite":"import");return e}function iz(r,e,t){let n=new Map(r);return n.set(e,t),n}function oz(r,e,t,n){let i=r.get(e)??ez(e,n),o=new Map(r);return o.set(e,{...i,mode:t}),o}function sz(r,e,t,n){let i=r.get(e)??ez(e,n),o=t.trim(),s=o||e,a=o||t,l=n(s),c=new Map(r);return c.set(e,{...i,mode:ZH(i.mode,l),destinationPath:a,destinationExists:l}),{decisions:c,effectivePath:s}}function az(r,e,t){let n=r.get(e);if(!n||n.destinationExists===t)return r;let i=new Map(r);return i.set(e,{...n,destinationExists:t,mode:ZH(n.mode,t)}),i}function lz(r,e){return r.map(t=>({choiceId:t.choiceId,mode:HP(e.get(t.choiceId)??"import",t.exists)}))}function cz(r,e,t){return r.map(n=>{let i=e.get(n.originalPath),o=i?.destinationPath?.trim()||n.originalPath,s=i?.destinationExists??(n.exists||t(o)),a=i?.mode??(s?"overwrite":"write");return{originalPath:n.originalPath,destinationPath:o,mode:a}})}var JT=class{constructor(e){this.app=e;this.tokens=new Map}optimistic(e){let t=e.trim();return!t||Dr(t)?!1:!!this.app.vault.getAbstractFileByPath((0,UP.normalizePath)(t))}async resolve(e){let t=e.trim();if(!t||Dr(t))return!1;try{return await this.app.vault.adapter.exists((0,UP.normalizePath)(t))}catch{return!1}}schedule(e,t,n){let i=(this.tokens.get(e)??0)+1;this.tokens.set(e,i),this.resolve(t).then(o=>{this.tokens.get(e)===i&&n(o)})}};var Xre=L('<span class="macroCommandType svelte-1qj0pve"> </span>'),Zre=L("<code> </code>"),Jre=L('<span class="macroCommandSummary svelte-1qj0pve"> </span>'),ene=L('<li class="svelte-1qj0pve"><span class="macroCommandName svelte-1qj0pve"> </span> <!> <!></li>'),tne=L('<ul class="macroCommands svelte-1qj0pve"></ul>'),rne={hash:"svelte-1qj0pve",code:".macroCommands.svelte-1qj0pve {list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:0.25rem;}.macroCommands.svelte-1qj0pve li:where(.svelte-1qj0pve) {display:flex;flex-wrap:wrap;align-items:center;gap:0.4rem;font-size:var(--font-ui-smaller, 0.85rem);}.macroCommandName.svelte-1qj0pve {font-weight:500;}.macroCommandType.svelte-1qj0pve {color:var(--text-muted);font-size:0.72rem;}.macroCommandSummary.svelte-1qj0pve {color:var(--text-muted);}"};function zP(r,e){We(r,rne);let t={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 t[o]??o}var i=tne();Ot(i,21,()=>e.commands,xg,(o,s)=>{var a=ene(),l=B(a),c=le(l,!0),u=_(l,2);{var d=v=>{sb(v,{get flag(){return h(s).flag}})},p=v=>{var y=Xre(),b=le(y,!0);re(x=>ae(b,x),[()=>n(h(s).type)]),M(v,y)};Y(u,v=>{h(s).flag?v(d):v(p,-1)})}var f=_(u,2);{var m=v=>{var y=Zre(),b=le(y,!0);re(()=>ae(b,h(s).scriptPath)),M(v,y)},g=v=>{var y=Jre(),b=le(y,!0);re(()=>ae(b,h(s).summary)),M(v,y)};Y(f,v=>{h(s).scriptPath?v(m):h(s).summary&&v(g,1)})}N(a),re(()=>{Gp(a,`padding-left:${h(s).depth*1}rem`),ae(c,h(s).name)}),M(o,a)}),N(i),M(r,i)}var nne=L('<p class="svelte-s0203k">No choices found in this package.</p>'),ine=L('<div class="choiceExists svelte-s0203k">already in vault</div>'),one=L('<button type="button" class="macroToggle svelte-s0203k"> </button>'),sne=L('<option class="svelte-s0203k">Overwrite</option>'),ane=L('<tr class="macroRow svelte-s0203k"><td colspan="3" class="svelte-s0203k"><!></td></tr>'),lne=L('<tr class="svelte-s0203k"><td data-label="Name" class="svelte-s0203k"><div class="choiceName svelte-s0203k"> </div> <!> <!></td><td data-label="Location" class="svelte-s0203k"> </td><td data-label="Action" class="svelte-s0203k"><select class="dropdown svelte-s0203k"><option class="svelte-s0203k">Import</option><!><option class="svelte-s0203k">Duplicate</option><option class="svelte-s0203k">Skip</option></select></td></tr> <!>',1),cne=L('<table class="svelte-s0203k"><colgroup class="svelte-s0203k"><col class="colName svelte-s0203k"/><col class="colLocation svelte-s0203k"/><col class="colAction svelte-s0203k"/></colgroup><thead class="svelte-s0203k"><tr class="svelte-s0203k"><th class="svelte-s0203k">Name</th><th class="svelte-s0203k">Location</th><th class="svelte-s0203k">Action</th></tr></thead><tbody class="svelte-s0203k"></tbody></table>'),une=L('<section class="choicesSection svelte-s0203k"><h3 class="svelte-s0203k">Choices</h3> <!></section>'),dne={hash:"svelte-s0203k",code:`.choicesSection.svelte-s0203k {display:flex;flex-direction:column;gap:0.75rem;max-width:100%;}.choicesSection.svelte-s0203k :where(.svelte-s0203k) {box-sizing:border-box;}.choiceName.svelte-s0203k {font-weight:500;}
/* A plain inline text link, not a chrome button: neutralise Obsidian's
default button background/shadow on every state (!important to win over
the global button:hover / :focus rules that paint the grey box). */.macroToggle.svelte-s0203k {display:inline-block;margin-top:0.35rem;padding:0;background:transparent !important;border:none;box-shadow:none !important;color:var(--text-accent);cursor:pointer;font-size:var(--font-ui-smaller, 0.8rem);border-radius:var(--radius-s, 4px);}.macroToggle.svelte-s0203k:hover {color:var(--interactive-accent-hover, var(--text-accent));text-decoration:underline;}.macroToggle.svelte-s0203k:focus-visible {outline:2px solid var(--interactive-accent);outline-offset:2px;}.macroRow.svelte-s0203k td:where(.svelte-s0203k) {background:var(--background-primary-alt, var(--background-secondary));}.choicesSection.svelte-s0203k table:where(.svelte-s0203k) {width:100%;border-collapse:collapse;table-layout:fixed;}.choicesSection.svelte-s0203k col.colName:where(.svelte-s0203k) {width:52%;}.choicesSection.svelte-s0203k col.colLocation:where(.svelte-s0203k) {width:26%;}.choicesSection.svelte-s0203k col.colAction:where(.svelte-s0203k) {width:22%;}.choicesSection.svelte-s0203k th:where(.svelte-s0203k),
.choicesSection.svelte-s0203k td:where(.svelte-s0203k) {padding:0.5rem;border-bottom:1px solid var(--background-modifier-border);text-align:left;word-break:break-word;overflow-wrap:anywhere;white-space:normal;vertical-align:top;}.choicesSection.svelte-s0203k th:where(.svelte-s0203k) {font-size:var(--font-ui-smaller, 0.8rem);color:var(--text-muted);font-weight:600;}.choiceExists.svelte-s0203k {font-size:var(--font-ui-smaller, 0.8rem);color:var(--text-muted);margin-top:0.1rem;}.choicesSection.svelte-s0203k tbody:where(.svelte-s0203k) tr:where(.svelte-s0203k):not(.macroRow):hover td:where(.svelte-s0203k) {background:var(--background-modifier-hover);}.choicesSection.svelte-s0203k select:where(.svelte-s0203k) {max-width:100%;}
/* Narrow viewports (mobile): a 3-column table can't breathe, so each row
becomes a stacked card with the column name as an inline label. */
@media (max-width: 500px) {.choicesSection.svelte-s0203k thead:where(.svelte-s0203k) {display:none;}.choicesSection.svelte-s0203k table:where(.svelte-s0203k),
.choicesSection.svelte-s0203k tbody:where(.svelte-s0203k),
.choicesSection.svelte-s0203k tr:where(.svelte-s0203k),
.choicesSection.svelte-s0203k td:where(.svelte-s0203k) {display:block;width:100%;}.choicesSection.svelte-s0203k tbody:where(.svelte-s0203k) tr:where(.svelte-s0203k):not(.macroRow) {border:1px solid var(--background-modifier-border);border-radius:var(--radius-m, 8px);padding:0.5rem 0.6rem;margin-bottom:0.5rem;}.choicesSection.svelte-s0203k td:where(.svelte-s0203k) {border-bottom:none;padding:0.15rem 0;}.choicesSection.svelte-s0203k td[data-label="Location"]:where(.svelte-s0203k)::before,
.choicesSection.svelte-s0203k td[data-label="Action"]:where(.svelte-s0203k)::before {content:attr(data-label) ": ";font-weight:600;color:var(--text-muted);}.choicesSection.svelte-s0203k td[data-label="Action"]:where(.svelte-s0203k) {display:flex;align-items:center;gap:0.4rem;margin-top:0.25rem;}.choicesSection.svelte-s0203k td[data-label="Action"]:where(.svelte-s0203k) select:where(.svelte-s0203k) {flex:1;}.macroRow.svelte-s0203k td:where(.svelte-s0203k) {padding:0.25rem 0;}
}.is-mobile .macroToggle.svelte-s0203k {min-height:36px;padding:0.4rem 0.3rem;}`};function WP(r,e){pe(e,!0),We(r,dne);function t(a){return!a||a.length===0?"Root":a.slice(0,-1).join(" \u203A ")||"Root"}var n=une(),i=_(B(n),2);{var o=a=>{var l=nne();M(a,l)},s=a=>{var l=cne(),c=_(B(l),2);Ot(c,21,()=>e.conflicts,u=>u.choiceId,(u,d)=>{let p=F(()=>HP(e.choiceDecisions.get(h(d).choiceId)??"import",h(d).exists)),f=F(()=>e.previewChoiceById.get(h(d).choiceId)),m=F(()=>(h(f)?.commands?.length??0)>0);var g=lne(),v=Te(g),y=B(v),b=B(y),x=le(b,!0),w=_(b,2);{var T=G=>{var ie=ine();M(G,ie)};Y(w,G=>{h(d).exists&&G(T)})}var C=_(w,2);{var S=G=>{var ie=one(),xe=le(ie,!0);re((ue,be)=>{ke(ie,"aria-expanded",ue),ae(xe,be)},[()=>e.expandedMacros.has(h(d).choiceId),()=>e.expandedMacros.has(h(d).choiceId)?"Hide macro":"Show macro"]),Ae("click",ie,()=>e.toggleMacro(h(d).choiceId)),M(G,ie)};Y(C,G=>{h(m)&&G(S)})}N(y);var A=_(y),D=le(A,!0),P=_(A),U=B(P),K=B(U);K.value=K.__value="import";var W=_(K);{var ee=G=>{var ie=sne();ie.value=ie.__value="overwrite",M(G,ie)};Y(W,G=>{h(d).exists&&G(ee)})}var me=_(W);me.value=me.__value="duplicate";var O=_(me);O.value=O.__value="skip",N(U);var H;dc(U),N(P),N(v);var ce=_(v,2);{var te=G=>{var ie=ane(),xe=B(ie),ue=B(xe);{let be=F(()=>h(f)?.commands??[]);zP(ue,{get commands(){return h(be)}})}N(xe),N(ie),M(G,ie)},z=F(()=>h(m)&&e.expandedMacros.has(h(d).choiceId));Y(ce,G=>{h(z)&&G(te)})}re(G=>{ae(x,h(d).name),ae(D,G),H!==(H=h(p))&&(U.value=(U.__value=H)??"",uc(U,H))},[()=>t(h(d).pathHint)]),Ae("change",U,G=>e.onChoiceModeChange(h(d).choiceId,G)),M(u,g)}),N(c),N(l),M(a,l)};Y(i,a=>{e.conflicts.length===0?a(o):a(s,-1)})}N(n),M(r,n),fe()}nt(["click","change"]);var pne=L('<li><code> </code> <span class="warnLoc svelte-111ahcq"> </span></li>'),fne=L('<div class="warnItem svelte-111ahcq"><h4 class="svelte-111ahcq">Missing files</h4> <ul class="svelte-111ahcq"></ul></div>'),mne=L(`<li class="svelte-111ahcq"><code> </code>: bundled but not
used by any choice</li>`),hne=L('<div class="warnItem svelte-111ahcq"><h4 class="svelte-111ahcq">Unreferenced files</h4> <ul class="svelte-111ahcq"></ul></div>'),gne=L('<section class="warningsBand svelte-111ahcq"><!> <!></section>'),vne={hash:"svelte-111ahcq",code:`.warningsBand.svelte-111ahcq {display:flex;flex-direction:column;border:1px solid var(--background-modifier-border);border-radius:var(--radius-m, 8px);padding:0.6rem 0.75rem;gap:0.5rem;}.warnItem.svelte-111ahcq h4:where(.svelte-111ahcq) {margin:0;font-size:var(--font-ui-small, 0.9rem);}.warnItem.svelte-111ahcq ul:where(.svelte-111ahcq) {margin:0.25rem 0 0;padding-left:1rem;}.warnItem.svelte-111ahcq li:where(.svelte-111ahcq) {overflow-wrap:anywhere;}
/* A missing SCRIPT reference is an execution-hijack risk, not a broken
link: it runs from whatever exists at that path. Mark it as critical. */.warnItem.svelte-111ahcq li.script:where(.svelte-111ahcq) {padding:0.25rem 0.4rem;border-radius:var(--radius-s, 4px);background:var(--qa-sev-critical-wash);}.warnLoc.svelte-111ahcq {color:var(--text-muted);font-size:var(--font-ui-smaller, 0.8rem);}`};function jP(r,e){pe(e,!0),We(r,vne);var t=or(),n=Te(t);{var i=o=>{var s=gne(),a=B(s);{var l=d=>{var p=fne(),f=_(B(p),2);Ot(f,21,()=>e.preview.missingReferences,m=>m.path,(m,g)=>{var v=pne();let y;var b=B(v),x=le(b,!0),w=_(b),T=_(w),C=le(T,!0);N(v),re(()=>{y=it(v,1,"svelte-111ahcq",null,y,{script:h(g).asScript}),ae(x,h(g).path),ae(w,`:
${h(g).asScript?"not bundled, so it runs from whatever file exists at that path after import":"not bundled and not in your vault"} `),ae(C,h(g).breadcrumb)}),M(m,v)}),N(f),N(p),M(d,p)};Y(a,d=>{e.preview.missingReferences.length>0&&d(l)})}var c=_(a,2);{var u=d=>{var p=hne(),f=_(B(p),2);Ot(f,20,()=>e.preview.orphanAssets,m=>m,(m,g)=>{var v=mne(),y=B(v),b=le(y,!0);Gr(),N(v),re(()=>ae(b,g)),M(m,v)}),N(f),N(p),M(d,p)};Y(c,d=>{e.preview.orphanAssets.length>0&&d(u)})}N(s),M(o,s)};Y(n,o=>{e.preview&&(e.preview.missingReferences.length>0||e.preview.orphanAssets.length>0)&&o(i)})}M(r,t),fe()}var yne=L('<div class="errorMessage svelte-1nd6fqb"> </div>'),bne=L('<div class="info svelte-1nd6fqb">Analyzing package\u2026</div>'),wne=L('<p class="svelte-1nd6fqb">No files bundled with this package.</p>'),Cne=L('<h4> </h4> <div class="fileRows svelte-1nd6fqb"></div>',1),xne=L('<section class="filesSection svelte-1nd6fqb"><h3 class="svelte-1nd6fqb">Files</h3> <!></section> <!>',1),Ene=L('<section class="summary svelte-1nd6fqb"><!> <span class="svelte-1nd6fqb"> </span></section>'),Tne=L('<section class="packageMeta svelte-1nd6fqb"><span class="svelte-1nd6fqb"><span class="metaLabel svelte-1nd6fqb">Version</span> </span> <span class="metaSep svelte-1nd6fqb" aria-hidden="true">\xB7</span> <span class="svelte-1nd6fqb"><span class="metaLabel svelte-1nd6fqb">Created</span> </span> <span class="metaSep svelte-1nd6fqb" aria-hidden="true">\xB7</span> <span class="svelte-1nd6fqb"> </span> <span class="metaSep svelte-1nd6fqb" aria-hidden="true">\xB7</span> <span class="svelte-1nd6fqb"> </span></section> <!> <!> <!> <!>',1),kne=L('<div class="importPackageModal svelte-1nd6fqb"><header class="svelte-1nd6fqb"><h2 class="svelte-1nd6fqb">Import QuickAdd package</h2> <p class="svelte-1nd6fqb">Review what this package adds and runs before importing.</p></header> <section class="pasteSection svelte-1nd6fqb"><label class="svelte-1nd6fqb"><span class="svelte-1nd6fqb">Paste package JSON</span> <textarea placeholder="Paste the contents of a .quickadd.json package here" rows="8" class="svelte-1nd6fqb"></textarea></label> <!></section> <!> <!> <section class="footer svelte-1nd6fqb"><button type="button" class="secondary svelte-1nd6fqb">Cancel</button> <button type="button" class="primary svelte-1nd6fqb"><!></button></section></div>'),Sne={hash:"svelte-1nd6fqb",code:`.importPackageModal.svelte-1nd6fqb {display:flex;flex-direction:column;gap:1rem;width:min(720px, 100%);max-height:80vh;overflow-y:auto;
/* overflow-x:hidden (paired with overflow-y:auto) clips child focus rings
at the flush left/right edges; the inline padding gives the ring room. */overflow-x:hidden;box-sizing:border-box;padding:2px 4px;}.importPackageModal.svelte-1nd6fqb :where(.svelte-1nd6fqb) {box-sizing:border-box;}.importPackageModal.svelte-1nd6fqb > section:where(.svelte-1nd6fqb) {max-width:100%;}.pasteSection.svelte-1nd6fqb label:where(.svelte-1nd6fqb) {display:flex;flex-direction:column;gap:0.5rem;}.pasteSection.svelte-1nd6fqb textarea:where(.svelte-1nd6fqb) {width:100%;font-family:var(--font-monospace);resize:vertical;}.errorMessage.svelte-1nd6fqb {color:var(--text-error);}.info.svelte-1nd6fqb {color:var(--text-muted);}
/* A single compact line that sizes to content and wraps naturally, instead
of a 4-equal-column grid where the date wraps to 3 lines and the rest
leave dead space. */.packageMeta.svelte-1nd6fqb {display:flex;flex-wrap:wrap;align-items:baseline;gap:0.3rem 0.6rem;padding:0.55rem 0.75rem;border:1px solid var(--background-modifier-border);border-radius:var(--radius-m, 8px);width:100%;font-size:var(--font-ui-small, 0.9rem);overflow-wrap:anywhere;}.metaLabel.svelte-1nd6fqb {color:var(--text-muted);}.metaSep.svelte-1nd6fqb {color:var(--text-faint);}.filesSection.svelte-1nd6fqb {display:flex;flex-direction:column;gap:0.75rem;}.filesGroupHeading.svelte-1nd6fqb {margin:0;font-size:var(--font-ui-small, 0.9rem);font-weight:600;color:var(--text-muted);}.filesGroupHeading.overwrite.svelte-1nd6fqb {color:var(--text-error);}.fileRows.svelte-1nd6fqb {display:flex;flex-direction:column;gap:0.5rem;}.summary.svelte-1nd6fqb {display:flex;align-items:center;gap:0.5rem;padding:0.55rem 0.7rem;border-radius:var(--radius-m, 8px);border:1px solid var(--qa-sev-success-border);background:var(--qa-sev-success-wash);color:var(--text-normal);}.summary.svelte-1nd6fqb .quickadd-icon {color:var(--text-success, var(--color-green, #0aa344));flex-shrink:0;}.footer.svelte-1nd6fqb {display:flex;justify-content:flex-end;gap:0.5rem;margin-top:0.5rem;}.footer.svelte-1nd6fqb .primary:where(.svelte-1nd6fqb) {background:var(--interactive-accent);color:var(--text-on-accent);}.footer.svelte-1nd6fqb .primary:where(.svelte-1nd6fqb):hover:not(:disabled) {background:var(--interactive-accent-hover);}.footer.svelte-1nd6fqb .primary:where(.svelte-1nd6fqb):active:not(:disabled),
.footer.svelte-1nd6fqb .secondary:where(.svelte-1nd6fqb):active:not(:disabled) {transform:translateY(1px);}.footer.svelte-1nd6fqb .secondary:where(.svelte-1nd6fqb) {background:transparent;}.footer.svelte-1nd6fqb .secondary:where(.svelte-1nd6fqb):hover:not(:disabled) {background:var(--background-modifier-hover);}.footer.svelte-1nd6fqb .secondary:where(.svelte-1nd6fqb):focus-visible {outline:2px solid var(--interactive-accent);outline-offset:2px;}
/* Accent background needs a light outline to stay visible. */.footer.svelte-1nd6fqb .primary:where(.svelte-1nd6fqb):focus-visible {outline:2px solid var(--text-on-accent);outline-offset:-4px;}
@media (prefers-reduced-motion: reduce) {.footer.svelte-1nd6fqb .primary:where(.svelte-1nd6fqb),
.footer.svelte-1nd6fqb .secondary:where(.svelte-1nd6fqb) {transition:none;}.footer.svelte-1nd6fqb .primary:where(.svelte-1nd6fqb):active:not(:disabled),
.footer.svelte-1nd6fqb .secondary:where(.svelte-1nd6fqb):active:not(:disabled) {transform:none;}
}`};function GP(r,e){pe(e,!0),We(r,Sne);let t;function n(){return t??(t=new JT(e.app))}let i=Ce(null),o=Ce(null),s=Ce(null),a=Ce(!1),l=Ce(ut(new Set)),c=Ce(ut(new Set)),u=Ce(null),d=Ce(!1),p=Ce(null),f=Ce(ut(new Map)),m=Ce(ut(new Map)),g=Ce(""),v=Ce(!1),y=Ce(0),b=Ce(!1),x=F(()=>h(s)?WH(h(s)):!1),w=F(()=>h(s)?jH(h(s),h(l)):!0),T=F(()=>new Map((h(s)?.choices??[]).map(Z=>[Z.choiceId,Z]))),C=F(()=>new Map((h(s)?.files??[]).map(Z=>[Z.originalPath,Z]))),S=F(()=>!!(h(s)&&(h(s).summary.hasCritical||h(s).summary.hasWarning))),A=F(()=>!!(h(i)&&h(o))&&!h(v)&&(!h(x)||h(a)&&h(w))),D=F(()=>{let Z=h(p);if(!Z)return"";let De=[];Z.added&&De.push(`${Z.added} choice${Z.added===1?"":"s"} added`),Z.overwritten&&De.push(`${Z.overwritten} overwritten`),Z.assetsWritten&&De.push(`${Z.assetsWritten} file${Z.assetsWritten===1?"":"s"} written`);let Pt=Z.skipped+Z.assetsSkipped;return Pt&&De.push(`${Pt} skipped`),De.length?`Imported: ${De.join(", ")}.`:"Nothing was imported."});function P(Z){if(h(l).has(Z))return;let De=new Set(h(l));De.add(Z),j(l,De,!0)}function U(Z){let De=new Set(h(c));De.has(Z)?De.delete(Z):De.add(Z),j(c,De,!0)}let K=Z=>n().optimistic(Z),W=F(()=>(h(o)?.assetConflicts??[]).map(Z=>({conflict:Z,state:rz(h(m),Z,O,K),file:h(C).get(Z.originalPath)}))),ee=F(()=>h(W).filter(Z=>!Z.state.destinationExists)),me=F(()=>h(W).filter(Z=>Z.state.destinationExists));function O(Z){let[De]=ri(X.getState().templateFolderPaths),Pt=Z.kind==="template"||Z.kind==="capture-template";if(De&&Pt){let It=Z.originalPath.split("/").pop()??Z.originalPath;return`${De}/${It}`}return Z.originalPath}function H(Z,De){n().schedule(Z,De,Pt=>{j(m,az(h(m),Z,Pt),!0)})}function ce(){if(!h(o)){j(f,new Map,!0),j(m,new Map,!0);return}j(f,nz(h(o).choiceConflicts),!0),j(m,tz(h(o).assetConflicts,O,K),!0);for(let Z of h(o).assetConflicts){let De=h(m).get(Z.originalPath);De&&H(Z.originalPath,De.destinationPath)}}function te(Z,De){j(f,iz(h(f),Z,De),!0)}function z(Z,De){j(m,oz(h(m),Z,De,K),!0)}function G(Z,De){let{decisions:Pt,effectivePath:It}=sz(h(m),Z.originalPath,De,K);j(m,Pt,!0),H(Z.originalPath,It)}function ie(Z,De){let It=De.currentTarget.value;te(Z,It)}function xe(){j(s,null),j(a,!1),j(l,new Set,!0),j(c,new Set,!0)}async function ue(Z){let De=Z.trim(),Pt=L_(y);if(j(p,null),j(b,!1),!De){j(i,null),j(o,null),j(f,new Map,!0),j(m,new Map,!0),xe(),j(u,null);return}j(v,!0);try{let It=ib(De),pi=X.getState().choices,Di=await KH(e.app,pi,It),Au=await XT(e.app,pi,It);if(Pt!==h(y))return;j(i,{pkg:It,path:"[pasted]"},!0),j(o,Di,!0),xe(),j(s,Au,!0),j(u,null),ce()}catch(It){if(Pt!==h(y))return;j(u,It?.message??String(It),!0),j(i,null),j(o,null),j(f,new Map,!0),j(m,new Map,!0),xe()}finally{Pt===h(y)&&j(v,!1)}}function be(Z){let De=Z.currentTarget.value;j(g,De,!0),ue(De)}async function Ke(){if(h(b)){new ab.Notice("This package has already been imported.");return}if(!h(i)||!h(o)){new ab.Notice("Load a package before importing.");return}j(d,!0),j(p,null);try{let Z=await QH({app:e.app,existingChoices:X.getState().choices,aiProviders:X.getState().ai.providers,pkg:h(i).pkg,choiceDecisions:lz(h(o).choiceConflicts,h(f)),assetDecisions:cz(h(o).assetConflicts,h(m),K)});X.setState(De=>({...De,choices:Z.updatedChoices})),j(p,{added:Z.addedChoiceIds.length,overwritten:Z.overwrittenChoiceIds.length,skipped:Z.skippedChoiceIds.length,assetsWritten:Z.writtenAssets.length,assetsSkipped:Z.skippedAssets.length},!0),j(b,!0),new ab.Notice(`Imported ${Z.addedChoiceIds.length+Z.overwrittenChoiceIds.length} choice${Z.addedChoiceIds.length+Z.overwrittenChoiceIds.length===1?"":"s"} successfully.`)}catch(Z){console.error(Z),new ab.Notice(`Import failed: ${Z?.message??Z}`)}finally{j(d,!1)}}var Oe=kne(),Ee=_(B(Oe),2),He=B(Ee),Le=_(B(He),2);Nu(Le),N(He);var At=_(He,2);{var mr=Z=>{var De=yne(),Pt=le(De,!0);re(()=>ae(Pt,h(u))),M(Z,De)},zr=Z=>{var De=bne();M(Z,De)};Y(At,Z=>{h(u)?Z(mr):h(v)&&Z(zr,1)})}N(Ee);var ge=_(Ee,2);{var ve=Z=>{var De=Tne(),Pt=Te(De),It=B(Pt),pi=_(B(It));N(It);var Di=_(It,4),Au=_(B(Di));N(Di);var wp=_(Di,4),Cp=le(wp),xp=_(wp,4),Iu=le(xp);N(Pt);var we=_(Pt,2);{var qe=oe=>{VP(oe,{get preview(){return h(s)}})};Y(we,oe=>{h(S)&&h(s)&&oe(qe)})}var k=_(we,2);WP(k,{get conflicts(){return h(o).choiceConflicts},get choiceDecisions(){return h(f)},get previewChoiceById(){return h(T)},get expandedMacros(){return h(c)},toggleMacro:U,onChoiceModeChange:ie});var R=_(k,2);{var q=oe=>{var de=xne(),$e=Te(de),vt=_(B($e),2);{var nr=Wt=>{var Xn=wne();M(Wt,Xn)},lr=Wt=>{var Xn=or(),Gs=Te(Xn);Ot(Gs,17,()=>[{label:"Added",rows:h(ee),overwrite:!1},{label:"Will overwrite",rows:h(me),overwrite:!0}],Hh=>Hh.label,(Hh,ir)=>{var La=or(),Xl=Te(La);{var Va=Ys=>{var Ba=Cne(),u_=Te(Ba);let V$;var S4=le(u_),B$=_(u_,2);Ot(B$,21,()=>h(ir).rows,d_=>d_.conflict.originalPath,(d_,Zl)=>{var q$=or(),_4=Te(q$);{var A4=p_=>{{let I4=F(()=>h(l).has(h(Zl).file.originalPath));BP(p_,{get file(){return h(Zl).file},get pkg(){return h(i).pkg},get mode(){return h(Zl).state.mode},get destinationPath(){return h(Zl).state.destinationPath},get destinationExists(){return h(Zl).state.destinationExists},onPathInput:f_=>G(h(Zl).conflict,f_),onModeChange:f_=>z(h(Zl).conflict.originalPath,f_),get reviewed(){return h(I4)},onReviewed:P})}};Y(_4,p_=>{h(Zl).file&&p_(A4)})}M(d_,q$)}),N(B$),re(()=>{V$=it(u_,1,"filesGroupHeading svelte-1nd6fqb",null,V$,{overwrite:h(ir).overwrite}),ae(S4,`${h(ir).label??""} (${h(ir).rows.length??""})`)}),M(Ys,Ba)};Y(Xl,Ys=>{h(ir).rows.length>0&&Ys(Va)})}M(Hh,La)}),M(Wt,Xn)};Y(vt,Wt=>{h(W).length===0?Wt(nr):Wt(lr,-1)})}N($e);var Wr=_($e,2);jP(Wr,{get preview(){return h(s)}}),M(oe,de)};Y(R,oe=>{h(i)&&oe(q)})}var J=_(R,2);{var se=oe=>{var de=Ene(),$e=B(de);Et($e,{iconId:"check-circle",size:16});var vt=_($e,2),nr=le(vt,!0);N(de),re(()=>ae(nr,h(D))),M(oe,de)};Y(J,oe=>{h(p)&&oe(se)})}re(oe=>{ae(pi,` ${h(i).pkg.quickAddVersion??""}`),ae(Au,` ${oe??""}`),ae(Cp,`${h(o).choiceConflicts.length??""} choice${h(o).choiceConflicts.length===1?"":"s"}`),ae(Iu,`${h(i).pkg.assets.length??""} file${h(i).pkg.assets.length===1?"":"s"}`)},[()=>new Date(h(i).pkg.createdAt).toLocaleDateString()]),M(Z,De)};Y(ge,Z=>{h(i)&&h(o)&&Z(ve)})}var Fe=_(ge,2);{var Je=Z=>{qP(Z,{get preview(){return h(s)},get fullyReviewed(){return h(w)},get acknowledged(){return h(a)},set acknowledged(De){j(a,De,!0)}})};Y(Fe,Z=>{h(i)&&h(x)&&!h(b)&&Z(Je)})}var mt=_(Fe,2),Ft=B(mt),Qe=_(Ft,2),zt=B(Qe);{var rr=Z=>{var De=ra("Importing\u2026");M(Z,De)},Qn=Z=>{var De=ra("Close");M(Z,De)},di=Z=>{var De=ra("Import package");M(Z,De)};Y(zt,Z=>{h(d)?Z(rr):h(b)?Z(Qn,1):Z(di,-1)})}N(Qe),N(mt),N(Oe),re(()=>{Ft.disabled=h(d),Qe.disabled=h(d)||!h(b)&&!h(A),ke(Qe,"title",!h(b)&&h(x)&&h(w)&&!h(a)?"Confirm the acknowledgement above to continue":void 0)}),Ae("input",Le,be),wi(Le,()=>h(g),Z=>j(g,Z)),Ae("click",Ft,function(...Z){e.close?.apply(this,Z)}),Ae("click",Qe,function(...Z){(h(b)?e.close:Ke)?.apply(this,Z)}),M(r,Oe),fe()}nt(["input","click"]);var ek=class extends uz.Modal{constructor(t){super(t);this.handle=null}onOpen(){this.modalEl.addClass("quickAddModal","packageImportModal"),this.handle=Li(this.contentEl,GP,{app:this.app,close:()=>this.close()},{what:"the package importer"})}onClose(){this.handle?.destroy(),this.handle=null}};bf();td();bs();function YP(r,e,t,n){let i=er(r,"div"),o=er(r,"strong");return o.textContent=e,i.appendChild(o),i.appendChild(Ng(r,` ${t}`)),n?.className&&i.classList.add(n.className),i.classList.add("qa-dev-info-row"),r.appendChild(i),i}function dz(r,e){if(e.branch!==null&&YP(r,"Branch:",e.branch),e.commit!==null&&YP(r,"Commit:",e.commit),e.dirty!==null){let t=e.dirty?"Yes (uncommitted changes)":"No",n=e.dirty?"qa-dev-dirty-status":"qa-dev-clean-status";YP(r,"Uncommitted changes:",t,{className:n})}}var tk="Bundle or import QuickAdd automations as reusable packages.";function pz(r,e){let t=[{type:"group",heading:"Choices & packages",extraButtons:[n=>n.setIcon("help-circle").setTooltip("QuickAdd documentation").onClick(()=>NB(Ms.gettingStarted,n.extraSettingsEl))],items:[{name:"Choices",render:r.choices},{name:"Packages",desc:tk,render:r.packages}]},{type:"group",heading:"Choice picker",items:[{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"}},{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:"Show at the bottom (keeps your top choice first)",top:"Show at the top",off:"Hide"}}}]},{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:"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:"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:"One-page input for choices",desc:KP("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. ",Ms.onePageInputs,"Learn more about one-page inputs"),control:{type:"toggle",key:"onePageInputEnabled"}},{name:"Date aliases",desc:"Shortcodes for natural language date parsing. One per line: alias = phrase. Example: tm = tomorrow.",render:r.dateAliases}]},{type:"group",heading:"Templates & properties",items:[{name:"Template folder paths",desc:"Folders where templates are stored. Used to suggest template files when configuring QuickAdd. Add as many as you like; leave empty to suggest every template file in the vault.",render:r.templateFolders},{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:"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:"Show updates on each new release",major:"Show updates only on major releases (new features, breaking changes)",none:"Don't show"}}},{name:"Show capture notifications",desc:"Display a notification when content is captured successfully to confirm the operation completed.",control:{type:"toggle",key:"showCaptureNotification"}},{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:"Global variables",items:[{name:"Global variables",render:r.globalVariables}]},{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"}},{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"}}]},{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"}}]}];return e&&t.push({type:"group",heading:"Developer",items:[{name:"Development information",desc:"Git information for developers.",render:r.developmentInfo}]}),t}function KP(r,e,t="Learn more"){let n=createFragment();return n.append(document.createTextNode(r)),Kx(n,e,t),n}bt();var rk=class extends lu.PluginSettingTab{constructor(t,n){super(t,n);this.choiceViewHandle=null;this.globalVariablesViewHandle=null;this.packagesUnsubscribe=null;this.plugin=n,this.icon="zap"}getControlValue(t){let n=X.getState();return t==="inputPrompt"?n.inputPrompt==="multi-line":n[t]}setControlValue(t,n){if(t==="inputPrompt"){X.setState({inputPrompt:n?"multi-line":"single-line"});return}if(t==="persistInputPromptDrafts"){let i=!!n;X.setState({persistInputPromptDrafts:i}),i||ii.getInstance().clearAll();return}X.setState({[t]:n})}getSettingDefinitions(){return pz({choices:t=>this.renderChoicesView(t),packages:t=>this.renderPackages(t),dateAliases:t=>this.renderDateAliases(t),templateFolders:t=>this.renderTemplateFolderPaths(t),globalVariables:t=>this.renderGlobalVariablesView(t),developmentInfo:t=>this.renderDevInfo(t)},!1)}hide(){super.hide(),this.destroySettingViews()}destroySettingViews(){this.choiceViewHandle?.destroy(),this.choiceViewHandle=null,this.globalVariablesViewHandle?.destroy(),this.globalVariablesViewHandle=null,this.packagesUnsubscribe?.(),this.packagesUnsubscribe=null}prepareFullWidthSetting(t){t.infoEl.remove(),t.settingEl.addClass("qa-setting-full-width"),t.controlEl.addClass("qa-setting-full-width-control")}mountView(t,n,i){this.prepareFullWidthSetting(t),this[n]?.destroy();let o=i(t.controlEl);return this[n]=o,()=>{o.destroy(),this[n]===o&&(this[n]=null)}}renderChoicesView(t){return this.mountView(t,"choiceViewHandle",n=>Li(n,gP,{app:this.app,plugin:this.plugin,choices:X.getState().choices,saveChoices:i=>{X.setState({choices:i})}},{what:"your choices",fallbackComponent:jm}))}renderGlobalVariablesView(t){return this.mountView(t,"globalVariablesViewHandle",n=>Li(n,vP,{app:this.app,plugin:this.plugin},{what:"your global variables"}))}packagesDesc(t){return KP(t?`${tk} Export becomes available once you have a choice. `:`${tk} `,Ms.packages,"Learn more about packages")}renderPackages(t){let n;t.addButton(a=>{n=a,a.setButtonText("Export package\u2026").onClick(()=>{let l=Lr(X.getState().choices);new HT(this.app,this.plugin,l).open()})}),t.addButton(a=>a.setButtonText("Import package\u2026").onClick(()=>{new ek(this.app).open()}));let i=a=>{t.setDesc(this.packagesDesc(a)),n&&(n.setDisabled(a),a?n.setTooltip("Nothing to export yet"):n.buttonEl.removeAttribute("aria-label"))},o=Lr(X.getState().choices).length===0;i(o),this.packagesUnsubscribe?.();let s=X.subscribe(a=>{let l=Lr(a.choices).length===0;l!==o&&(o=l,i(l))});return this.packagesUnsubscribe=s,()=>{s(),this.packagesUnsubscribe===s&&(this.packagesUnsubscribe=null)}}renderDateAliases(t){t.settingEl.addClass("qa-date-alias-setting"),t.controlEl.addClass("qa-date-alias-control");let n=null;t.addTextArea(i=>{n=i,i.setPlaceholder(`t = today
tm = tomorrow
yd = yesterday`).setValue(bA(X.getState().dateAliases)).onChange(o=>{X.setState({dateAliases:VR(o)})}),i.inputEl.addClass("qa-date-alias-input")}),t.addButton(i=>{i.setButtonText("Reset to defaults").onClick(()=>{X.setState({dateAliases:Kp}),n?.setValue(bA(Kp))}),i.buttonEl.addClass("qa-date-alias-reset")})}renderTemplateFolderPaths(t){t.settingEl.addClass("qa-template-folders-setting");let n=t.controlEl.createDiv("qa-template-folders"),i=n.createDiv("qa-template-folder-list"),o=()=>ri(X.getState().templateFolderPaths),s=f=>{X.setState({templateFolderPaths:f})},a=()=>{i.empty();let f=o();if(f.length===0){i.createDiv({cls:"qa-template-folder-empty",text:"No folders added yet."});return}for(let m of f){let g=i.createDiv("qa-template-folder-row");g.createSpan({cls:"qa-template-folder-name",text:m,attr:{title:m}}),new lu.ExtraButtonComponent(g).setIcon("trash-2").setTooltip(`Remove ${m}`).onClick(()=>{s(o().filter(v=>v!==m)),a()})}},l=n.createDiv("qa-template-folder-input-row"),c=new lu.TextComponent(l);c.setPlaceholder("templates/"),c.inputEl.addClass("qa-template-folder-input");let u=new si(this.app,c.inputEl,Il(Vo(this.app)).filter(f=>f!=="/")),d=()=>{let[f]=ri([c.inputEl.value]);if(c.inputEl.value="",!f)return;let m=o();m.includes(f)||(s([...m,f]),a())},p=f=>{f.key==="Enter"&&(f.preventDefault(),d())};return c.inputEl.addEventListener("keydown",p),new lu.ButtonComponent(l).setCta().setButtonText("Add").onClick(()=>d()),a(),()=>{c.inputEl.removeEventListener("keydown",p),u.destroy()}}renderDevInfo(t){let n=t.settingEl.createDiv();n.addClass("qa-dev-info"),dz(n,{branch:null,commit:null,dirty:null})}};wA();Ie();mC();var Xm=class{formatOutputString(e){return`QuickAdd: (${e.level}) ${e.message}`}getQuickAddError(e,t,n,i){return{message:e,level:t,time:Date.now(),stack:n,originalError:i}}};xt();var lb=class extends Xm{constructor(){super(...arguments);this.ErrorLog=[]}logError(t,n,i){let o=this.getQuickAddError(t,"ERROR",n,i);this.addMessageToErrorLog(o);let s=i||new Error(t);console.error(this.formatOutputString(o),s)}logWarning(t,n,i){let o=this.getQuickAddError(t,"WARNING",n,i);this.addMessageToErrorLog(o);let s=i||new Error(t);console.warn(this.formatOutputString(o),s)}logMessage(t,n,i){let o=this.getQuickAddError(t,"LOG",n,i);this.addMessageToErrorLog(o)}addMessageToErrorLog(t){this.ErrorLog.push(t),this.ErrorLog.length>PA&&(this.ErrorLog=this.ErrorLog.slice(-PA))}clearErrorLog(){this.ErrorLog=[]}};var QP=require("obsidian");mC();var nk=class extends Xm{constructor(t){super();this.plugin=t}logError(t,n,i){let o=this.getQuickAddError(t,"ERROR",n,i);new QP.Notice(this.formatOutputString(o),15e3)}logWarning(t,n,i){let o=this.getQuickAddError(t,"WARNING",n,i);new QP.Notice(this.formatOutputString(o))}logMessage(t,n,i){}};Ie();xt();xt();var fz=1e4,mz=50,_ne=/plugin:([^\s:)]+)/;function Ane(r){let e=r.stack??"",t=`${r.name}: ${r.message}`;return(e.startsWith(t)?e.slice(t.length):e).split(`
`)}function Ine(r){for(let e of Ane(r)){let t=_ne.exec(e);if(t)return{pluginId:t[1],frame:e.trim()}}return null}function Dne(r,e){return`${r.name}@${e}`}function hz(r,e=Date.now){let t=r.manifest.id,n=new Map;r.registerDomEvent(window,"unhandledrejection",i=>{let o=i.reason,s=o instanceof Error?Ine(o):null;if(s?.pluginId!==t)return;if(ot(o)){i.preventDefault();return}let a=o,l=Dne(a,s.frame),c=e(),u=n.get(l);if(n.set(l,c),!(u!==void 0&&c-u<fz)){if(n.size>=mz){for(let[d,p]of n)c-p>=fz&&n.delete(d);if(n.size>=mz){let d=n.keys().next();!d.done&&d.value!==l&&n.delete(d.value)}}Ze(a,"A QuickAdd action failed")&&i.preventDefault()}})}var gz=require("obsidian");Ie();function Fne(r,e){try{let t=r.setting;return!t?.open||!t?.openTabById?(I.logMessage("QuickAdd: Obsidian internal settings API is unavailable."),!1):(t.open(),t.openTabById(e),!0)}catch(t){return I.logMessage(`QuickAdd: Failed to open plugin settings automatically: ${t}`),!1}}function Zm(r,e,t){let n=Fne(r,e);return!n&&t?.notice!==!1&&new gz.Notice("QuickAdd: Unable to open settings automatically. Open Settings \u2192 QuickAdd manually."),n}Ob();bt();xt();var AS=class{constructor(e,t,n,i){this.app=e;this.plugin=t;this.choices=n;this.choiceExecutor=i}async run(){let e=nn(this.choices).filter(t=>t.type==="Macro"&&t.runOnStartup);for(let t of e)try{await new _a(this.app,this.plugin,t,this.choiceExecutor,new Map).run()}catch(n){Ze(n,`Startup macro '${t.name}' failed`)}}};var _6=require("obsidian");Ie();wc();ht();Og();Lg();function IS(r,e){return!e.enabled||e.destination.type!=="specifiedFile"||$g(r,e.destination)?null:`Append link target file not found or is not a Markdown file: ${e.destination.path}`}async function DS(r,e,t,n,i){t.enabled&&(t.destination?.type==="specifiedFile"?await PN(r,e,t,i):n&&!al(t.placement)?await LN(r,n,e):i?await TC(r,e,t,i):await TC(r,e,t))}async function FS(r){try{await MN(r)}catch(e){I.logWarning(`Could not copy link to clipboard for '${r.path}': ${e instanceof Error?e.message:String(e)}`)}}async function gp({app:r,file:e,opening:t,originLeaf:n,forceFocus:i}){let o=Cn(t),s=i??o.focus??!0;return WA(r,e,s)||await Hg(r,e,{...o,...i===void 0?{}:{focus:i},originLeaf:n}),s}var Rh=require("obsidian");Jm();Xe();Zo();Ie();Dl();var $S=require("obsidian");ur();Dl();Sh();var YG=require("obsidian");lo();rn();function PS(r,e,t){let n=e.lastIndexOf("/"),i=n>=0?e.slice(0,n):"",o=iv(n>=0?e.slice(n+1):e),s=t?.vault.getAbstractFileByPath(e),a=t&&s instanceof YG.TFile?GI([s],d=>t.metadataCache.getFileCache(d))[0]:null,l=a?.primary??o,c=a?.secondary??i;r.addClass("mod-complex");let u=r.createDiv({cls:"suggestion-content"});u.createDiv({cls:"suggestion-title",text:l}),c&&u.createDiv({cls:"suggestion-note",text:c})}var MS=class extends $S.FuzzySuggestModal{constructor(t,n,i){super(t);this.settled=!1;this.rows=i.map(o=>({kind:"candidate",candidate:o})),this.action=Zc(n.existingNoteAction),this.promise=new Promise((o,s)=>{this.resolvePromise=o,this.rejectPromise=s}).then(o=>o.kind==="candidate"?Wb(o.candidate.item):Pa(o.title)),this.setPlaceholder(`Search notes or create ${n.name}`),this.open()}getItems(){return this.rows}getItemText(t){return t.kind==="candidate"?t.candidate.display:t.title}getSuggestions(t){let n=t.trim(),i=xo(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:t},n){if(t.kind==="candidate"&&t.candidate.renderPath){let o=t.candidate;PS(n,t.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:t.kind==="create"?`Create new note: ${t.title}`:t.candidate.unresolvedTitle??t.candidate.title}),t.kind==="create"?(0,$S.setIcon)(n.createDiv({cls:"suggestion-aux"}).createSpan({cls:"suggestion-flair"}),"file-plus"):i.createDiv({cls:"suggestion-note",text:"Unresolved link"})}selectSuggestion(t,n){this.settled=!0,super.selectSuggestion(t,n)}onChooseItem(t){this.settled=!0,this.resolvePromise(t)}onClose(){super.onClose(),this.settled||this.rejectPromise(Rr())}};sp();ap();Yn();xt();ur();Dl();Sh();async function KG(r,e,t){let{candidates:n}=aS(r,e),i=`Search notes or create ${e.name}`,o=Zc(e.existingNoteAction);try{let s=await wo(t,{remote:async a=>{let l=await Co(a,{items:n.map(c=>({value:Wb(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"?Pa(l):l},headless:()=>{throw new ye(`'${e.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 MS(r,e,n).promise});return jb(r,s)}catch(s){throw ot(s)?new at("Input cancelled by user"):s}}Sh();zd();Dh();sp();ap();wc();ht();xt();var Oh=class{constructor(e){this.executor=e;this.closed=!1}success(e,t){this.closed=!0,this.executor.recordExecutionResult?.({status:"success",file:e,effect:t})}failure(e){this.closed||this.executor.recordExecutionResult?.({status:"error",reason:e})}};function OS(r){return r instanceof Error?r.message||QG:String(r)||QG}var QG="Choice execution failed.";da();bf();Kk();Zk();Ni();Yn();$b();Cu();function RS(r,e){if(r.content!==e.before)return null;let t=[...e.edits].sort((s,a)=>s.from-a.from),n="",i=0;for(let s of t){if(s.from<i||s.to<s.from||s.to>e.before.length)return null;n+=e.before.slice(i,s.from)+s.text,i=s.to}if(n+=e.before.slice(i),n!==e.after)return null;let o=[];for(let s of r.offsets){let a=0;for(let l of t){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}}qg();var NS=class extends xu{constructor(t,n,i,o,s=null){super(t,n,o);this.originLeaf=s;this.choiceExecutor=o,this.outcome=new Oh(o),this.choice=i,this.formatter.setPromptRunContext({draftScopeId:i.id,choiceName:i.name})}async run(){this.cursorPlacement=null;let t=null,n=null,i=null;try{$n(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=bc(this.choice.appendLink);this.setLinkToCurrentFileBehavior(o.enabled&&!o.requireActiveFile?"optional":"required");let s=this.choice.fileNameFormat.enabled?this.choice.fileNameFormat.format:Or;if(nu(this.choice,s,this.choiceExecutor.variables.get("value"))){let m=hS(this.choiceExecutor,this.choice.id),g=m?jb(this.app,m):await KG(this.app,this.choice,this.choiceExecutor);if(g.kind==="existing"){let v=yE(this.choice.existingNoteAction);if(v==="open"){await this.openDiscoveredExistingNote(g.file),this.outcome.success(g.file,"unchanged");return}i={file:g.file,mode:v},t=this.setTemporaryValueVariable(g.file.basename)}else t=this.setTemporaryValueVariable(g.title),n=g.vaultRelativePath??null}if(!this.validateAppendLinkDestination(o))return;let a=await this.resolveTemplateSourcePath(this.choice.templatePath);if(i&&Vn(this.app,a)?.path===i.file.path)throw new ye("Cannot apply a template to its own template source.");let l=i?.file.path??await this.resolveNewNotePath({templatePath:a,format:s,discoveryVaultRelativePath:n}),c,u=!1,d=!1,p="created";if(i){if(wn.test(a)||cr.test(a))throw new ye("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 m=await this.getSelectedFileExistsMode(),g=tm(m);p=g.resolutionKind==="reuseExisting"?"unchanged":g.resolutionKind==="createNew"?"created":"changed";let v=g.requiresExistingFile?this.findExistingFile(l):null;if(g.requiresExistingFile&&(!(v instanceof Rh.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:u}=await this.applyFileExistsMode(m,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}d=!0}this.outcome.success(c,p);let f=this.cursorPlacement;if(o.enabled&&c)try{await DS(this.app,c,o,this.choiceExecutor.focusedProperty,this.cursorPlacement?m=>{this.cursorPlacement&&m.filePath===c?.path&&(this.cursorPlacement=RS(this.cursorPlacement,m))}:void 0)}catch(m){if(m instanceof yt)throw m;I.logWarning(`Created '${c.basename}' but could not insert the link: ${m instanceof Error?m.message:String(m)}`)}this.choice.copyLinkToClipboard&&c&&await FS(c),(this.choice.openFile||u)&&c?(await gp({app:this.app,file:c,opening:this.choice.fileOpening,originLeaf:this.originLeaf}),!this.templaterCursorHandled&&!await ol(this.app,c)&&this.placeCursor(c,f)):this.cursorPlacement&&No(this.app,c)?!this.templaterCursorHandled&&!await ol(this.app,c)&&this.placeCursor(c,f):d&&!o.enabled&&!this.choice.copyLinkToClipboard&&new Rh.Notice(`Created '${c.basename}'.`)}catch(o){if(bu(o,{logPrefix:"Template execution aborted",noticePrefix:"Template execution aborted",defaultReason:"Template execution aborted"})){this.choiceExecutor.signalAbort?.(o);return}ii.getInstance().markExecutionScopeFailed(),this.outcome.failure(OS(o)),Ze(o,`Error running template choice "${this.choice.name}"`)}finally{t?.()}}failRun(t,n="error"){ii.getInstance().markExecutionScopeFailed(),n==="warning"?I.logWarning(t):n==="error"&&I.logError(t),this.outcome.failure(t)}async resolveNewNotePath({templatePath:t,format:n,discoveryVaultRelativePath:i}){let o="";if(i)o=Ai(i);else if(this.choice.folder.enabled)o=await this.getFolderPath();else{let d=this.app.fileManager.getNewFileParent(this.app.workspace.getActiveFile()?.path??"");o=d===this.app.vault.getRoot()?"":d.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=Wn(s,"File name"),{fileName:l,strippedPrefix:c}=i?{fileName:a,strippedPrefix:!1}:this.stripDuplicateFolderPrefix(a,o),u=this.shouldTreatFormattedNameAsVaultRelativePath(a,c,this.choice.folder.enabled);return this.normalizeTemplateFilePath(i||u?"":o,l,t)}setTemporaryValueVariable(t){let n=this.choiceExecutor.variables,i=n.has("value"),o=n.get("value");return n.set("value",t),()=>{if(i){n.set("value",o);return}n.delete("value")}}validateAppendLinkDestination(t){let n=IS(this.app,t);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 t=oq(),n="If the target file already exists";return await wo(this.choiceExecutor,{remote:o=>Co(o,{items:t.map(s=>({value:s.id,title:s.label})),placeholder:n,what:'the "file already exists" chooser'}),headless:()=>{throw new ye(`'${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:()=>Xt.Suggest(this.app,t.map(o=>o.label),t.map(o=>o.id),n)})}async applyFileExistsMode(t,n,i,o,s){let a=tm(t);switch(a.resolutionKind){case"modifyExisting":return{createdFile:await this.applyExistingFileUpdate(a.id,i,o,s),shouldAutoOpen:!1};case"createNew":{let l=await cq(n,a.id,async u=>await this.app.vault.adapter.exists(u)),c=await this.createFileWithTemplate(l,o);return c&&l!==n&&!this.choice.openFile&&new Rh.Notice(`Created '${c.basename}'.`),{createdFile:c,shouldAutoOpen:!1}}case"reuseExisting":return I.logMessage(`Opening existing file: ${i.path}`),{createdFile:i,shouldAutoOpen:!0}}}async openDiscoveredExistingNote(t){await gp({app:this.app,file:t,opening:this.choice.fileOpening,originLeaf:this.originLeaf,forceFocus:!0})}async applyExistingFileUpdate(t,n,i,o){return t==="overwrite"?this.overwriteFileWithTemplate(n,i):this.appendToExistingFileWithTemplate(n,i,t==="appendTop"?"top":"bottom",o)}async appendToExistingFileWithTemplate(t,n,i,o){if(t.extension==="canvas"||t.extension==="base")return this.lastTemplateFileFailure=`Cannot append to '${t.path}': appending a template to a ${t.extension} file would corrupt it. Use the "Overwrite" file-exists option instead.`,ii.getInstance().markExecutionScopeFailed(),I.logError(this.lastTemplateFileFailure),null;if(t.extension!=="md")return await this.appendToFileWithTemplate(t,n,i);let s=new yh(this.app,this.plugin,t,n,i,this.choiceExecutor,n);s.setPromptRunContext({draftScopeId:this.choice.id,choiceName:this.choice.name,destination:t.path,destinationKind:"file"}),s.setLinkToCurrentFileBehavior(o.enabled&&!o.requireActiveFile?"optional":"required");let a=await this.withAnonymousValueForInsertEngine(()=>s.apply());return this.cursorPlacement=s.getCursorPlacement(),a}async withAnonymousValueForInsertEngine(t){let n=this.formatter.getAnonymousValue(),i=this.choiceExecutor.variables;if(!(n!==void 0&&!i.has("value")))return await t();let s=this.setTemporaryValueVariable(n);try{return await t()}finally{s()}}findExistingFile(t){let n=this.app.vault.getAbstractFileByPath(t);if(n instanceof Rh.TFile)return n;if(n)return null;let i=t.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(", ");I.logError(`Multiple files match '${t}' when ignoring case: ${s}`)}return null}async formatFolderPaths(t){let n=[];for(let i of t)n.push(await this.formatter.formatFolderPath(i));return n}async getFolderPath(){let t=await this.formatFolderPaths([...this.choice.folder.folders]),n=this.getCurrentFolderSuggestion(),i=n?[n]:[],o=this.choice.folder,s=t,a=t;if(o?.chooseWhenCreatingNote)s=Il(Vo(this.app)),a=void 0;else if(o?.createInSameFolderAsActiveFile){let l=this.app.workspace.getActiveFile();if(!l||!l.parent)return I.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 o?.chooseFromSubfolders&&(s=UB(Il(Vo(this.app)),t));return this.getOrCreateFolder(s,{allowCreate:!0,allowedRoots:a,topItems:i,executor:this.choiceExecutor})}getCurrentFolderSuggestion(){let t=this.app.workspace.getActiveFile(),n=t?.parent;return!t||!n?null:{path:n.path??"",label:"<current folder>"}}};wl();Bg();Og();var Ra=require("obsidian");ys();Ol();Jm();var LS=class{isResolved(){return!this.hasConflicts}isConflicted(){return this.hasConflicts}},tw=class r extends LS{constructor(e,t,n){super(),this.left=e,this.base=t,this.right=n,this.hasConflicts=!0}static create(e){return new r(e.left,e.base,e.right)}apply(e){return r.create({left:e(this.left),base:e(this.base),right:e(this.right)})}},os=class r extends LS{constructor(e){super(),this.hasConflicts=!1,this.result=e}combine(e){this.result=this.result.concat(e.result)}apply(e){return new r(e(this.result))}};var Wl=class r{constructor(e,t){this.left=e,this.right=t}static executeDiff(e,t){if(!e.push)throw new Error("Argument is not an array");let n=r.diff(e,t);return new s$(e,t,n).convertToTypedOutput()}static diff(e,t){return new r(e,t).performDiff()}performDiff(){let e=this.identifyUniquePositions();e.sort((o,s)=>s[0]-o[0]);let[t,n]=this.findNextChange(),i=new VS(t,n,[]);return e.forEach(o=>{i=this.getDifferences(i,o)}),i.changeRanges}getDifferences(e,t){let[n,i]=[e.leftChangePos,e.rightChangePos],[o,s]=t;if(o<n||s<i)return e;{let[a,l,c,u]=this.findPrevChange(n,i,o-1,s-1),[d,p]=this.findNextChange(o+1,s+1),f=this.appendChangeRange(e.changeRanges,a,l,c,u);return new VS(d,p,f)}}findNextChange(e=0,t=0){let n=this.left.slice(e)||[],i=this.right.slice(t)||[],o=this.mismatchOffset(n,i);return[e+o,t+o]}findPrevChange(e,t,n,i){if(e>n||t>i)return[e,n,t,i];{let o=this.left.slice(e,n+1).reverse()||[],s=this.right.slice(t,i+1).reverse()||[],a=this.mismatchOffset(o,s);return[e,n-a,t,i-a]}}mismatchOffset(e,t){let n=Math.max(e.length,t.length);for(let i=0;i<n;i++)if(e[i]!==t[i])return i;return Math.min(e.length,t.length)}identifyUniquePositions(){let e=this.findUnique(this.left),t=this.findUnique(this.right),n=new Set(...e.keys()),i=new Set(...t.keys()),s=[...new Set([...n].filter(a=>i.has(a)))].map(a=>[e.get(a),t.get(a)]);return s.unshift([this.left.length,this.right.length]),s}findUnique(e){let t=new Map;e.forEach((i,o)=>{t.set(i,new o$(o,!t.has(i)))});let n=new Map;for(let[i,o]of t.entries())o.unique&&n.set(i,o.pos);return n}appendChangeRange(e,t,n,i,o){return t<=n&&i<=o?e.push(new rw(Oa.change,t+1,n+1,i+1,o+1)):t<=n?e.push(new rw(Oa.remove,t+1,n+1,i+1,i)):i<=o&&e.push(new rw(Oa.add,t+1,t,i+1,o+1)),e}},o$=class{constructor(e,t){this.pos=e,this.unique=t}},Nh=class{constructor(e,t){this.text=e,this.low=t}},s$=class{constructor(e,t,n){this.oldTextArray=e,this.newTextArray=t,this.chunks=n,this.oldText=[],this.newText=[]}convertToTypedOutput(){let e=new a$(0,0);return this.chunks.forEach(t=>{let[n,i]=this.setTextNodeIndexes(t,e.oldIndex,e.newIndex),[o,s]=this.appendChanges(t,e.oldIndex+n,e.newIndex+i);e.oldIndex=o,e.newIndex=s}),this.setTheRemainingTextNodeIndexes(e.oldIndex,e.newIndex),{oldText:this.oldText,newText:this.newText}}setTextNodeIndexes(e,t,n){let i=0;for(;t+i<e.leftLo-1;)this.oldText.push(new Nh(this.oldTextArray[t+i],n+i)),i+=1;let o=0;for(;n+o<e.rightLo-1;)this.newText.push(new Nh(this.newTextArray[n+o],t+o)),o+=1;return[i,o]}appendChanges(e,t,n){for(;t<=e.leftHi-1;)this.oldText.push(this.oldTextArray[t]),t+=1;for(;n<=e.rightHi-1;)this.newText.push(this.newTextArray[n]),n+=1;return[t,n]}setTheRemainingTextNodeIndexes(e,t){let n=0;for(;e+n<this.oldTextArray.length;)this.oldText.push(new Nh(this.oldTextArray[e+n],t+n)),n+=1;for(;t+n<this.newTextArray.length;)this.newText.push(new Nh(this.newTextArray[t+n],e+n)),n+=1}},a$=class{constructor(e,t){this.oldIndex=e,this.newIndex=t}},Oa;(function(r){r.change="change",r.add="add",r.remove="remove"})(Oa||(Oa={}));var rw=class{constructor(e,t,n,i,o){this.action=e,this.leftLo=t,this.leftHi=n,this.rightLo=i,this.rightHi=o}},VS=class{constructor(e,t,n){this.leftChangePos=e,this.rightChangePos=t,this.changeRanges=n}};var BS=class r{constructor(e,t,n,i,o){this.code=e,this.baseLo=t,this.baseHi=n,this.sideLo=i,this.sideHi=o}static fromChangeRange(e){return new r(e.action,e.leftLo,e.leftHi,e.rightLo,e.rightHi)}},Lh=class r{constructor(e,t,n){this.left=e,this.base=t,this.right=n}static executeDiff(e,t,n){return new r(e,t,n).getDifferences()}getDifferences(){let e=Wl.diff(this.base,this.left).map(n=>BS.fromChangeRange(n)),t=Wl.diff(this.base,this.right).map(n=>BS.fromChangeRange(n));return this.collapseDifferences(new qS(e,t))}collapseDifferences(e,t=[]){if(e.isFinished())return t;{let n=new qS,i=e.chooseSide(),o=e.dequeue();return n.enqueue(i,o),e.switchSides(),this.buildResultQueue(e,o.baseHi,n),t.push(this.determineDifference(n,i,e.switchSides())),this.collapseDifferences(e,t)}}buildResultQueue(e,t,n){if(this.queueIsFinished(e.peek(),t))return n;{let i=e.dequeue();return n.enqueue(e.currentSide,i),t<i.baseHi?(e.switchSides(),this.buildResultQueue(e,i.baseHi,n)):this.buildResultQueue(e,t,n)}}queueIsFinished(e,t){return e.length===0||e[0].baseLo>t+1}determineDifference(e,t,n){let i=e.get(t)[0].baseLo,o=e.get(n),s=o[o.length-1].baseHi,[a,l]=this.diffableEndpoints(e.get(dn.left),i,s),[c,u]=this.diffableEndpoints(e.get(dn.right),i,s),d=this.left.slice(a-1,l),p=this.right.slice(c-1,u),f=this.decideAction(e,d,p);return new l$(f,a,l,c,u,i,s)}diffableEndpoints(e,t,n){if(e.length){let i=e[0],o=e[e.length-1],s=i.sideLo-i.baseLo+t,a=o.sideHi-o.baseHi+n;return[s,a]}else return[t,n]}decideAction(e,t,n){return e.isEmpty(dn.left)?jl.chooseRight:e.isEmpty(dn.right)?jl.chooseLeft:t.every((i,o)=>n[o]===i)?jl.noConflictFound:jl.possibleConflict}},l$=class{constructor(e,t,n,i,o,s,a){this.changeType=e,this.leftLo=t,this.leftHi=n,this.rightLo=i,this.rightHi=o,this.baseLo=s,this.baseHi=a}},jl;(function(r){r.chooseRight="choose_right",r.chooseLeft="choose_left",r.possibleConflict="possible_conflict",r.noConflictFound="no_conflict_found"})(jl||(jl={}));var dn;(function(r){r.left="left",r.right="right"})(dn||(dn={}));var qS=class{constructor(e=[],t=[]){this.diffs={left:e,right:t}}dequeue(e=this.currentSide){return this.diffs[e].shift()}peek(e=this.currentSide){return this.diffs[e]}isFinished(){return this.isEmpty(dn.left)&&this.isEmpty(dn.right)}enqueue(e=this.currentSide,t){return this.diffs[e].push(t)}get(e=this.currentSide){return this.diffs[e]}isEmpty(e=this.currentSide){return this.diffs[e].length===0}switchSides(e=this.currentSide){return this.currentSide=e===dn.left?dn.right:dn.left}chooseSide(){return this.isEmpty(dn.left)?this.currentSide=dn.right:this.isEmpty(dn.right)?this.currentSide=dn.left:this.currentSide=this.get(dn.left)[0].baseLo<=this.get(dn.right)[0].baseLo?dn.left:dn.right,this.currentSide}};var nw=class r{static merge(e,t,n){let i=new r(e,t,n);return i.executeThreeWayMerge(),i.result}constructor(e,t,n){this.result=[],this.text3=new c$(e,n,t)}executeThreeWayMerge(){let e=Lh.executeDiff(this.text3.left,this.text3.base,this.text3.right),t=1;e.forEach(i=>{let o=[];for(let s=t;s<i.baseLo;s++)o.push(this.text3.base[s-1]);o.length&&this.result.push(new os(o)),this.interpretChunk(i),t=i.baseHi+1});let n=this.accumulateLines(t,this.text3.base.length,this.text3.base);n.length&&this.result.push(new os(n))}setConflict(e){let t=tw.create({left:this.accumulateLines(e.leftLo,e.leftHi,this.text3.left),base:this.accumulateLines(e.baseLo,e.baseHi,this.text3.base),right:this.accumulateLines(e.rightLo,e.rightHi,this.text3.right)});this.result.push(t)}determineConflict(e,t,n){let i=1;e.forEach(s=>{for(let l=i;l<=s.leftLo;l++)this.result.push(new os(this.accumulateLines(i,l,n)));let a=this.determineOutcome(s,t,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 os(o))}determineOutcome(e,t,n){return e.action===Oa.change?tw.create({left:this.accumulateLines(e.rightLo,e.rightHi,t),right:this.accumulateLines(e.leftLo,e.leftHi,n),base:[]}):e.action===Oa.add?new os(this.accumulateLines(e.rightLo,e.rightHi,t)):null}setText(e,t,n){let i=[];for(let o=t;o<=n;o++)i.push(e[o-1]);return i}_conflictRange(e){let t=this.setText(this.text3.right,e.rightLo,e.rightHi),n=this.setText(this.text3.left,e.leftLo,e.leftHi),i=Wl.diff(t,n);(this._assocRange(i,Oa.change)||this._assocRange(i,Oa.remove))&&e.baseLo<=e.baseHi?this.setConflict(e):this.determineConflict(i,n,t)}interpretChunk(e){if(e.changeType==jl.chooseLeft){let t=this.accumulateLines(e.leftLo,e.leftHi,this.text3.left);t.length&&this.result.push(new os(t))}else if(e.changeType!==jl.possibleConflict){let t=this.accumulateLines(e.rightLo,e.rightHi,this.text3.right);t.length&&this.result.push(new os(t))}else this._conflictRange(e)}_assocRange(e,t){for(let n=0;n<e.length;n++){let i=e[n];if(i.action===t)return i}return null}accumulateLines(e,t,n){let i=[];for(let o=e;o<=t;o++)n[o-1]&&i.push(n[o-1]);return i}},c$=class{constructor(e,t,n){this.left=e,this.right=t,this.base=n}};var vp=class{constructor(e,t,n={}){this.results=e,this.joinFunction=t,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[e,t]=[this.results[0],this.results.slice(1)],n=e;return t.forEach(i=>n.combine(i)),n.apply(this.joinFunction).result}}};var iw=class r{static collateMerge(e,t,n){return e.length?(e=r.combineNonConflicts(e),e.length===1&&e[0].isResolved()?new vp(e,t):new vp(e,t,{conflict:!0,conflictHandler:n})):new vp([new os([])],t)}static combineNonConflicts(e){let t=[];return e.forEach(n=>{t.length&&t[t.length-1].isResolved()&&n.isResolved()?t[t.length-1].combine(n):t.push(n)}),t}};function XG(r,e,t,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,e,c,t].join(`
`)}}).join(`
`)}}var ZG=r=>r.join(""),rle=r=>r.split(/\b/),nle=XG("<<<<<<< YOUR CHANGES","=======",">>>>>>> APP AUTHORS CHANGES",ZG),ile={splitFunction:rle,joinFunction:ZG,conflictFunction:nle};function u$(r,e,t,n={}){n=Object.assign({},ile,n);let[i,o,s]=[r,e,t].map(c=>n.splitFunction.call(n,c)),a=nw.merge(i,o,s);return iw.collateMerge(a,n.joinFunction,n.conflictFunction)}var JG=u$;Xe();function e6(r,e){return r.line===e.line}function Gl(r){let e=[];return r.forEach((t,n)=>{let i=t.match(/^(#+)[\s]+(.*)$/);i&&e.push({level:i[1].length,text:i[2],line:n})}),e}function Yl(r,e,t=!1){let n=Gl(r),i=n.find(c=>c.line===e),o=!!i;if(!o&&t)throw new Error(`Target line ${e} is not a heading, but we are trying to find the end of its section.`);if(!o&&!t){let c=t6(r,e,u=>u.trim()==="");return c!==null&&c>e?c-1:e}let s=r.length-1,a=ole(i,n,r,t),l=lle(r,a,c=>c.trim()!=="");if(l!==null){if(l<e)return e;let c=r[l+1].trim()==="";return l+1===s&&!c?a:l===0?l+1:l}return a}function ole(r,e,t,n){let i=e.findIndex(u=>e6(u,r)),o=i===e.length-1,s=t.length-1;if(o)return s;let[a,l]=sle(r,e);if(l&&a===e.length)return s;if(l&&n)return e[a].line-1;if(l&&!n)return e[i+1].line;if(!n&&!l){let u=ale(r.line,e);return u===null?s:u}return s}function sle(r,e){let t=e.findIndex(i=>e6(i,r)),n=t6(e,t,i=>i.level<=r.level);return n===null?[-1,!1]:[n,!0]}function ale(r,e){let t=e.find(n=>n.line>r);return t?t.line:null}function lle(r,e,t){for(let n=e-1;n>=0;n--)if(t(r[n]))return n;return null}function t6(r,e,t){for(let n=e+1;n<r.length;n++)if(t(r[n]))return n;return null}wl();ew();wu();var cle="\u200B";function ow(r){let e=r.slice(),t=!1,n="",i=0;for(let o=0;o<r.length;o++){let s=r[o].match(/^(\s*)(`{3,}|~{3,})/);if(!t){s&&(t=!0,n=s[2][0],i=s[2].length);continue}e[o]=r[o].replace(/^(\s*)#+(\s)/,`$1${cle}$2`),s&&s[2][0]===n&&s[2].length>=i&&r[o].slice(s[1].length+s[2].length).trim()===""&&(t=!1,n="",i=0)}return e}function r6(r){return(r.match(/^#+\s+(.*)$/)?.[1]??"").trim()}function ule(r){let e=r.match(/^\[?v?(\d+)\.(\d+)\.(\d+)(?:[-+\]].*)?$/i)??r.match(/^\[?v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/i);if(!e)return{value:0,parsed:!1};let t=n=>Math.min(Number(n??"0"),999999);return{value:t(e[1])*1e12+t(e[2])*1e6+t(e[3]),parsed:!0}}function n6(r,e,t){switch(e.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=t?t(r,e.dateFormat||void 0,!1):null;return n&&n.isValid()?{value:n.valueOf(),parsed:!0}:{value:0,parsed:!1}}case"semver":return ule(r);default:return{value:0,parsed:!0}}}function dle(r,e){if(typeof r.value=="string"&&typeof e.value=="string")return r.value<e.value?-1:r.value>e.value?1:0;let t=r.value,n=e.value;return t<n?-1:t>n?1:0}function i6(r,e,t,n,i,o=0){let s=ow(r),a=Gl(s).filter(p=>p.line>=o),l=a.filter(p=>p.level===t),c=n6(r6(e),n,i);if(l.length===0){let p=a.filter(f=>f.level<t).pop();return p?{mode:"after",line:Yl(s,p.line,!0)}:{mode:"bodyStart"}}let u=()=>{let p=l[l.length-1];return{mode:"after",line:Yl(s,p.line,!0)}};if(n.by==="insertion")return n.direction==="desc"?{mode:"before",line:l[0].line}:u();if(!c.parsed)return u();let d=n.unparseable??"bottom";for(let p of l){let f=n6(r6(s[p.line]),n,i),m;if(!f.parsed)m=d==="bottom";else{let g=dle(c,f);m=n.direction==="desc"?g>0:g<0}if(m)return{mode:"before",line:p.line}}return u()}wu();function d$(r){let e=r.split(`
`);for(;e.length>1&&e[e.length-1].trim()==="";)e.pop();return e}function p$(r){return r.length===0||r.length===1&&r[0].trim()===""}function f$(r,e){if(e.length<=1){let t=ple(r,e[0]??"");return{start:t,end:t}}return fle(r,e)}function ple(r,e){let t=e.trimEnd(),n=-1;for(let i=0;i<r.length;i++){let o=r[i].trimStart();if(o===t)return i;if(o.startsWith(t)){let a=o.slice(t.length);if(/^\s*$/.test(a))return i;n===-1&&(n=i);continue}let s=o.indexOf(t);if(s!==-1){let a=o.slice(s+t.length);if(/^\s*$/.test(a))return i;n===-1&&(n=i)}}return n}function fle(r,e){let t=e.length,n=e.map(i=>o6(i));for(let i=0;i+t<=r.length;i++){let o=!0;for(let s=0;s<t;s++)if(o6(r[i+s])!==n[s]){o=!1;break}if(o)return{start:i,end:i+t-1}}return{start:-1,end:-1}}function o6(r){return r.trimEnd()}function US(r,e,t){return r?Gl([e[t]??""]).length>0:!1}function mle(r,e){return r==="skip"?!0:r==="none"?!1:hle(e)}function hle(r){return/^\s{0,3}#{1,6}\s+\S/.test(r)}function HS(r,e,t,n){if(e<0)return e;let i=r[e]??"";if(!mle(n,i))return e;let s=t.endsWith(`
`)?Math.max(r.length-1,0):r.length,a=e;for(let l=e+1;l<s;l++){if(r[l].trim().length===0){a=l;continue}break}return a}function sw(r,e,t,n){if(e<0)return e;let i=e,o=e+1;for(;o<r.length&&r[o].trim().length===0;)i=o,o++;return i===e||o!==r.length||!n.endsWith(`
`)?e:t.endsWith(`
`)?Math.max(e,i-1):i}function s6(r){return r.includes(`
`)||r.includes("\r")}function a6(r,e){let t=r.indexOf(`
`,e);return t===-1?r.length:t>0&&r[t-1]==="\r"?t-1:t}function m$(r){let e=ql(r);return e>0?r.slice(0,e).split(`
`).length-1:0}function l6(r,e){let t=m$(e),n=r.map((i,o)=>o<t?"":i);return ow(n).map(i=>i.replace(/\r$/,""))}function zS(r,e,t,n,i=r.length){let o=e.split(`
`),s=o.slice(0,t+1).join(`
`),a=o.slice(t+1).join(`
`),c=(o[t+1]??"").trim(),u=e.endsWith(`
`)&&t+1===o.length-1,d=t+1<o.length&&!u&&c==="",p=n&&r.endsWith(`
`)&&d?r.slice(0,-1):r,f=!p.endsWith(`
`)&&c!==""?`
`:"";return{content:`${s}
${p}${f}${a}`,insertedEndOffset:s.length+1+Math.min(i,p.length)}}function c6(r,e,t,n=r.length){let i=e.length>0&&!r.endsWith(`
`)?`
`:"",o=Math.max(0,Math.min(n,r.length));if(t<=0)return{content:`${r}${i}${e}`,insertedEndOffset:o};let s=e.split(`
`),a=s.slice(0,t).join(`
`),l=s.slice(t).join(`
`);return{content:`${a}
${r}${i}${l}`,insertedEndOffset:a.length+1+o}}function u6(r,e,t,n,i){let o=n,s=o.includes(`\r
`)?`\r
`:`
`,a=e.mode==="before"?e.line:e.line+1,l=0;for(let x=0;x<a&&x<r.length;x++)l+=r[x].length+1;l>o.length&&(l=o.length);let c=o.slice(0,l),u=o.slice(l),d=a>0?(r[a-1]??"").replace(/\r$/,""):"",p=a<r.length?(r[a]??"").replace(/\r$/,""):"",f=t.split(`
`).map(x=>x.replace(/\r$/,""));f.length>1&&f[f.length-1]===""&&f.pop();let m=[];a>0&&d.trim()!==""&&m.push(""),m.push(...f),a<r.length&&p.trim()!==""&&m.push("");let g=m.join(s),v=c.length>0&&!/\n$/.test(c)?s:"",y=u.length>0||/\n$/.test(o)?s:"",b=c.length+v.length;return{content:`${c}${v}${g}${y}${u}`,insertedEndOffset:b+(i===void 0?g.length:(a>0&&d.trim()!==""?s.length:0)+Math.min(t.slice(0,i).split(`
`).map(x=>x.replace(/\r$/,"")).join(s).length,f.join(s).length))}}function p6({capture:r,targetString:e,fileContent:t,insertAfter:n,task:i}){let o=r.content,s=n?.orderBy??{by:"insertion",direction:"desc",unparseable:"bottom"},a=e.split(/\r?\n/,1)[0],l=Gl([a])[0]?.level??0,c=bl(r,`${e}
`),u=()=>{let w=op(t,c.content);return Oc(c,w.content,w.insertedStartOffset===null||c.cursor.kind==="none"?null:w.insertedStartOffset+c.cursor.value)};if(l===0)return u();let d=Eu(t),p=d.map(w=>w.replace(/\r$/,"")),f=m$(t),m=ow(p),g=a.replace(/\r$/,"").trimEnd(),v=m.findIndex((w,T)=>T>=f&&w.trimEnd()===g);if(v!==-1){let w=n?.insertAtEnd?sw(m,Yl(m,v,US(!!n?.considerSubsections,m,v))??m.length-1,t,o):HS(m,v,t,n?.blankLineAfterMatchMode??"auto"),T=zS(o,t,w,i,r.cursor.kind==="offset"?r.cursor.value:void 0);return Oc(r,T.content,T.insertedEndOffset)}let y=typeof window<"u"?window.moment:void 0,b=i6(p,a,l,s,y,f);if(b.mode==="bodyStart")return u();let x=u6(d,b,c.content,t,c.cursor.kind==="offset"&&c.cursor.source==="marker"?c.cursor.value:void 0);return Oc(c,x.content,x.insertedEndOffset)}ys();ew();Xe();ht();Yn();wl();lp();wu();Cu();dx();var gle=/^[ \t\r\n\f\v]*$/;function vle(r){return gle.test(r)}var WS=class extends ji{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}setDestinationFile(t){this.file=t,this.sourcePath=t.path,this.clipboardAttachmentLink=void 0,this.setTargetFolderPath(Ai(t.path)),this.setPromptRunContext({destination:t.path,destinationKind:"file"})}setDestinationSourcePath(t){this.sourcePath=t,this.file=null,this.clipboardAttachmentLink=void 0,this.setTargetFolderPath(Ai(t)),this.setPromptRunContext({destination:t,destinationKind:"file"})}setUseSelectionAsCaptureValue(t){this.useSelectionAsCaptureValue=t}setInsertAfterTargetOverride(t){this.insertAfterTargetOverride=t}getResolvedInsertAfterHeading(){return this.lastResolvedInsertAfterHeading}consumeCreatedClipboardAttachmentPaths(){let t=this.createdClipboardAttachmentPaths;return this.createdClipboardAttachmentPaths=[],t}shouldUseSelectionForValue(){return this.useSelectionAsCaptureValue}async getSelectedTextForValue(){let t=await this.getSelectedText();return t.trim().length>0?t:""}getLinkSourcePath(){return this.sourcePath??this.file?.path??null}async getClipboardContent(){let t=await super.getClipboardContent();return t.length>0||!this.clipboardImageFallbackEnabled?t:this.clipboardAttachmentLink!==void 0?this.clipboardAttachmentLink??"":(this.clipboardAttachmentLink=await this.saveClipboardImageAsAttachment(),this.clipboardAttachmentLink??"")}async withClipboardImageFallback(t){let n=this.clipboardImageFallbackEnabled;this.clipboardImageFallbackEnabled=!0;try{return await t()}finally{this.clipboardImageFallbackEnabled=n}}async saveClipboardImageAsAttachment(){let t=navigator.clipboard;if(typeof t?.read!="function")return null;let n,i;try{if(n=await this.getFirstClipboardImageItem(t),!n)return null;i=await(await n.clipboardItem.getType(n.mimeType)).arrayBuffer()}catch{return null}let o=this.getLinkSourcePath()??"",s=await cx(this.app,i,n.mimeType,o);return this.createdClipboardAttachmentPaths.push(s.path),ux(this.app,s,o)}async getFirstClipboardImageItem(t){let n=await t.read();for(let i of n){let o=i.types.find(s=>gl[s]!==void 0);if(o)return{clipboardItem:i,mimeType:o}}return null}getCurrentFileLink(){let t=this.app.workspace.getActiveFile();if(!t)return null;let n=this.sourcePath??this.file?.path??"";return this.app.fileManager.generateMarkdownLink(t,n)}async formatContentWithFile(t,n,i,o){if(this.choice=n,this.file=o,this.fileContent=i,!n||!o||i===null)return{content:t,captureContent:t,cursor:{kind:"none"}};this.setTargetFolderPath(Ai(o.path));let s=n.insertAfter.enabled||!!n.insertBefore?.enabled||n.prepend||!n.captureToActiveFile||n.activeFileWritePosition==="top"||n.activeFileWritePosition==="bottom";return await this.formatCapture(t,s)}async formatContent(t,n){return this.choice=n,n?await this.formatFileContent(t):t}async formatFileContent(t,n=!0){return(await this.formatCapture(t,n)).content}async formatCapture(t,n){let i=await this.withClipboardImageFallback(async()=>this.withPromptScope("captureText",t,async()=>super.formatFileContent(await this.expandTemplateLinebreaksOnce(t))));if(n&&this.file&&!this.templaterProcessed){let a=await il(this.app,i,this.file);a&&(i=a),this.templaterProcessed=!0}let o=Tf(i);return{...o.cursor.kind==="none"?{content:this.fileContent,cursor:o.cursor}:await this.insertCapture(o),captureContent:o.content,markerOnly:o.cursor.kind==="none"&&/{{CURSOR}}/i.test(i)}}async insertCapture(t){let n=t.content;if(this.choice.prepend||this.choice.captureToActiveFile&&this.choice.activeFileWritePosition==="bottom"){let o=this.fileContent.length>0&&!this.fileContent.endsWith(`
`)&&!n.startsWith(`
`),s=!this.choice.task||o?`
`:"";return bl(t,this.fileContent+s)}return this.choice.insertAfter.enabled?this.insertAfterHandler(t):this.choice.insertBefore?.enabled?this.insertBeforeHandler(t):this.insertAtNoteBodyStartTracking(t)}async formatContentOnly(t){let n=await this.withClipboardImageFallback(async()=>this.withPromptScope("captureText",t,async()=>super.formatFileContent(await this.expandTemplateLinebreaksOnce(t))));return vle(n)?this.fileContent:n}async expandTemplateLinebreaksOnce(t){return this.linebreaksProcessed?t:(this.linebreaksProcessed=!0,this.expandFormatTemplateEscapes(t))}async expandFormatTemplateEscapes(t){let n=await this.replaceGlobalVarInString(t);return this.expandLinebreakEscapesOutsideTokens(n)}async insertAfterHandler(t){let n=t.content,i=this.insertAfterTargetOverride;if(this.choice.insertAfter?.inline&&i===null){let f=await this.formatLocationString(await this.expandFormatTemplateEscapes(this.choice.insertAfter.after));return await this.insertAfterInlineHandler(t,f)}let o=i??await this.formatLocationString(await this.expandFormatTemplateEscapes(this.choice.insertAfter.after));if(i===null){let f=o.split(`
`,1)[0];this.lastResolvedInsertAfterHeading=/^#+\s+\S/.test(f)?f.trim():null}let s=d$(o);if(p$(s))throw new ye("Insert-after target is empty after formatting.");let a=Eu(this.fileContent),l=this.isOrderedCreate()?l6(a,this.fileContent):a,{start:c,end:u}=f$(l,s);if(c===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInsertAfterIfNotFound(t,o);throw new ye(`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 f=Yl(a,c,this.considerSubsectionsForAnchor(a,c)),m=Math.max(f??a.length-1,u);p=sw(a,m,this.fileContent,n)}else{let f=this.choice.insertAfter?.blankLineAfterMatchMode??"auto";p=HS(a,u,this.fileContent,f)}return this.insertTextAfterPositionInBody(t,this.fileContent,p)}async insertBeforeHandler(t){let n=this.choice.insertBefore;if(!n)throw new ye("Insert-before settings are missing.");let i=await this.formatLocationString(await this.expandFormatTemplateEscapes(n.before)),o=d$(i);if(p$(o))throw new ye("Insert-before target is empty after formatting.");let s=Eu(this.fileContent),{start:a}=f$(s,o);if(a===-1){if(n.createIfNotFound)return await this.createInsertBeforeIfNotFound(t,i);throw new ye(`Insert-before target not found: '${i}'.`)}return this.insertTextBeforePositionInBody(t,this.fileContent,a)}async insertAfterInlineHandler(t,n){if(s6(n))throw new ye("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(t,n);throw new ye(`Inline insert-after target not found: '${n}'.`)}let o=i+n.length,s=this.choice.insertAfter?.replaceExisting?a6(this.fileContent,o):o;return bl(t,this.fileContent.slice(0,o),this.fileContent.slice(s))}async createInsertAfterIfNotFound(t,n){let i=this.choice.insertAfter;if(i?.createIfNotFoundLocation===vs)return this.createInsertAfterOrdered(t,n);let o=bl(t,`${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=Eu(this.fileContent),c=Yl(l,s,this.considerSubsectionsForAnchor(l,s));a=sw(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===vs}considerSubsectionsForAnchor(t,n){return US(!!this.choice.insertAfter?.considerSubsections,t,n)}createInsertAfterOrdered(t,n){return p6({capture:t,targetString:n,fileContent:this.fileContent,insertAfter:this.choice.insertAfter,task:!!this.choice.task})}async createInsertBeforeIfNotFound(t,n){let i=this.choice.insertBefore;if(!i)throw new ye("Insert-before settings are missing.");let o=bl(t,"",`${t.content.endsWith(`
`)||t.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(t,n){let i=bl(t,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:t,location:n,rawTarget:i,insertAtCursor:o}){switch(n){case no:return this.insertAtNoteBodyStartTracking(t);case nd:return bl(t,`${this.fileContent}
`);case id:{let s=xn(this.app);if(!s)throw new ye(`Unable to insert line '${i}' at cursor position: no active markdown editor.`);try{return o(s.editor.getCursor().line)}catch{throw new ye(`Unable to insert line '${i}' at cursor position.`)}}default:throw new ye(`Unknown createIfNotFoundLocation: ${n}`)}}insertAtNoteBodyStartTracking(t){let n=op(this.fileContent,t.content);return Oc(t,n.content,n.insertedStartOffset===null||t.cursor.kind==="none"?null:n.insertedStartOffset+t.cursor.value)}insertTextAfterPositionInBody(t,n,i){let o=zS(t.content,n,i,!!this.choice.task,t.cursor.kind==="offset"?t.cursor.value:void 0);return Oc(t,o.content,o.insertedEndOffset)}insertTextBeforePositionInBody(t,n,i){let o=c6(t.content,n,i,t.cursor.kind==="offset"?t.cursor.value:void 0);return Oc(t,o.content,o.insertedEndOffset)}};ew();Ie();wD();_f();Sv();If();VM();wc();ht();xt();sp();ap();bf();Cu();var h6=require("obsidian");i$();Xe();ht();Ol();Jm();HM();da();la();Cu();sp();ap();Yn();RM();NM();var f6=require("obsidian");Xe();Yn();fE();pE();da();function m6(r,e){let t=r.trim().replace(/^\/+/,"");if(t==="")return{kind:"vault"};let n=Zf(t);if(n){if(!n.field)throw new ye("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=Xf(t);if(i){if(i.multiSelect)throw new ye("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=Wn(t,"Capture target file path");if(wn.test(o))throw new ye(`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(Nt.test(o)||cr.test(o))return{kind:"file",path:o};let l=e.normalizeMarkdownFilePath("",a),u=e.getAbstractFileByPath(l)instanceof f6.TFile;return e.isFolder(a)&&!u?{kind:"folder",folder:a}:{kind:"file",path:o}}var jS=class extends $h{async getFormattedPathToCaptureTo(e){if(e){let s=this.app.workspace.getActiveFile();return $n(s,"Cannot capture to active file - no active file."),s.path}let t=this.getPreselectedCaptureTargetPath();if(t!==void 0){let s=fS({isFolder:a=>tf(this.app,a),markdownFileExists:a=>this.app.vault.getAbstractFileByPath(pS(a))instanceof h6.TFile},this.choice.captureTo??"",!1);if(s){let a=this.confinePreselectedToScope(s,t);if(a!==null)return this.normalizeCaptureFilePath(a)}}let n=this.choice.captureTo,i=await this.formatter.formatFileName(n,"captureTarget"),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 Nj(this.choiceExecutor?.variables,this.choice.id)}confinePreselectedToScope(e,t){let n=this.stripLeadingSlash(t);if(e.kind==="folder")return e.folderPathSlash&&!n.startsWith(e.folderPathSlash)?`${e.folderPathSlash}${n}`:n;if(this.resolveScopeFiles(e).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(e){return dS(this.app,e)}resolveCaptureTarget(e){return m6(e,{getAbstractFileByPath:t=>this.app.vault.getAbstractFileByPath(t),isFolder:t=>tf(this.app,t),normalizeMarkdownFilePath:(t,n)=>this.normalizeMarkdownFilePath(t,n)})}captureTargetExists(e,t){let n=t.startsWith(e)?t:`${e}${t}`,i;try{i=Wn(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(e,t){let n=e.endsWith("/")||t?e:`${e}/`,i=Bo(this.app,n),o=this.choice.createFileIfItDoesntExist?.enabled??!1;$n(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(e){let t=jg(this.app,e);return this.selectFileFromSet(t,"No files matched the capture target filters.")}async selectFileWithProperty(e,t,n){let i=Gg(this.app,e,t,n),o=t!==void 0?`${e}=${t}`:e;return this.selectFileFromSet(i,`No notes with property ${o}.`)}captureTargetAlreadyExists(e,t){let n=e.trim();if(!n)return!1;let i;try{i=Wn(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 t.has(a.toLowerCase())}async selectFileFromSet(e,t){let n=this.choice.createFileIfItDoesntExist?.enabled??!1;$n(n||e.length>0,t);let i=new Set(this.app.vault.getMarkdownFiles().map(s=>s.basename.toLowerCase())),o=await this.chooseCaptureTarget(e,{allowCreate:n,nameIsTaken:s=>this.captureTargetAlreadyExists(s,i),restrictToScope:!0});return await this.formatFilePath(o)}async chooseCaptureTarget(e,t){let{paths:n,labels:i,search:o}=Fj(this.app,e),s=new Set(i.map(u=>u.toLowerCase())),a=u=>s.has(u.toLowerCase())||t.nameIsTaken(u),l=t.allowCreate?"Choose a note or type to create one":void 0,c=String(await wo(this.choiceExecutor,{remote:async u=>{let d=await Co(u,{items:n.map((p,f)=>({value:p,title:i[f]??p})),placeholder:l,allowCustomInput:t.allowCreate,what:"the capture-target picker"});if(t.restrictToScope&&!n.includes(d)&&a(d))throw new Error(`"${d}" 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 d},headless:()=>{throw this.assertInteractiveCaptureTarget(),new Error("unreachable")},app:()=>Mr.Suggest(this.app,i,n,{placeholder:l,emptyStateText:t.allowCreate?"Type a note name to create it":void 0,renderItem:(u,d)=>PS(d,u,this.app),searchItems:o,allowCustomValue:t.allowCreate,customValueLabel:u=>`Create new note: ${u}`,valueExists:a})}));return $n(!!c&&c.length>0,"No file selected for capture."),c}async formatFilePath(e){let t=await this.formatter.formatFileName(e,"captureTarget");return this.normalizeCaptureFilePath(t)}normalizeCaptureFilePath(e){let t=Wn(this.stripLeadingSlash(e),"Capture target file path");if(wn.test(t))throw new ye(`Capture to '.base' files is not supported (${t}). Use a Template choice instead.`);let n=this.normalizeCaptureFilePathExtension(t);if(!Ia(n).trim())throw new ye(`Capture target file name is empty after formatting ('${n}'). Make sure the tokens in 'Capture to' produce a value.`);if(Dr(n))throw new ye(`Refusing to capture to a file outside the vault: "${n}".`);return n}normalizeCaptureFilePathExtension(e){for(let t of[Nt,cr]){let n=e.match(t)?.[0];if(n)return`${Wn(e.replace(t,""),"Capture target file path")}${n}`}return this.normalizeMarkdownFilePath("",e)}assertInteractiveCaptureTarget(){if(this.choiceExecutor.interactive===!1)throw new ye(`'${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.`)}};Gk();Yn();Yk();TM();function g6(r){let e=r.insertAfter.enabled||!!r.insertBefore?.enabled;return r.captureToActiveFile&&!e&&r.newLineCapture?.enabled?r.newLineCapture.direction==="above"?"newLineAbove":"newLineBelow":r.captureToActiveFile&&!e?r.activeFileWritePosition==="top"?"activeFileTop":r.activeFileWritePosition==="bottom"||r.prepend?"append":"currentLine":r.insertAfter.enabled?"insertAfter":r.insertBefore?.enabled?"insertBefore":r.prepend?"prepend":"append"}Xe();Yn();function h$(r){return r?.type==="text"?"text":r?.type==="file"||r?.file?"file":typeof r?.text=="string"?"text":"unsupported"}function yle(r,e){let t=e.id;if(!t)return null;let n=r.getData?.();return n?.nodes?.length?n.nodes.find(i=>i.id===t)??null:null}function v6(r,e){if(r==="text"){if(e==="currentLine")return"Canvas capture does not support 'At cursor' for text cards. Use top, bottom, insert-after, or insert-before placement.";if(e==="newLineAbove"||e==="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"&&(e==="currentLine"||e==="newLineAbove"||e==="newLineBelow")?"Canvas file cards do not support cursor-based capture modes. Use top, bottom, insert-after, or insert-before modes.":null}function ble(r){let e=r.file;return e?typeof e=="string"?e:typeof e=="object"&&"path"in e&&typeof e.path=="string"?e.path:null:null}function g$(r){return!!r&&"path"in r&&"extension"in r}function wle(r){let t=(r.workspace.activeLeaf??r.workspace.getMostRecentLeaf?.()??null)?.view;return!t||t.getViewType?.()!=="canvas"?null:t}function Cle(r,e){let t=e.file??r.workspace.getActiveFile?.();if(!t)throw new ye("Cannot capture to Canvas because no active Canvas file is available.");return t}function xle(r){let e=r.selection?Array.from(r.selection):[];if(e.length!==1)throw new ye("Canvas capture requires exactly one selected node.");return e[0]}function y6(r){let e=ble(r);if(!e)throw new ye("Selected Canvas file card does not have a valid linked file path.");if(!Nt.test(e))throw new ye("Canvas file card targets markdown files only in this version.");return e}function Ele(r,e){let t=y6(e),n=r.vault.getAbstractFileByPath(t);if(!g$(n))throw new ye(`Selected Canvas file card target not found: ${t}`);return n}function Tle(r,e){let t=y6(e),n=r.vault.getAbstractFileByPath(t);if(!n)return{targetPath:t};if(!g$(n))throw new ye(`Selected Canvas file card target not found: ${t}`);return{targetPath:t,targetFile:n}}function kle(r,e){let t;try{t=JSON.parse(r)}catch{throw new ye(`Canvas file is not valid JSON: ${e}`)}if(!t||typeof t!="object")throw new ye(`Canvas file has invalid structure: ${e}`);if(!Array.isArray(t.nodes))throw new ye(`Canvas file has no nodes array: ${e}`);return t}function b6(r,e){let t=r,n=wle(t);if(!n)return null;let i=n.canvas;if(!i)throw new ye("Canvas capture is unavailable in this Obsidian version.");let o=Cle(t,n),s=xle(i),a=yle(i,s),l=h$(s);if(l==="unsupported"&&a&&(l=h$(a)),l==="unsupported")throw new ye("Canvas capture currently supports only text and file cards.");let c=v6(l,e);if(c)throw new ye(c);if(l==="text")return{kind:"text",source:"active",canvas:i,canvasFile:o,node:s,nodeData:a};let u=s.file||!a?.file?s:{...s,file:a.file};return{kind:"file",source:"active",canvasFile:o,node:u,targetFile:Ele(t,u)}}async function w6(r,e,t,n){let i=t.trim();if(!i)throw new ye("Canvas node id is required for Canvas node capture.");let o=r.vault.getAbstractFileByPath(e);if(!g$(o))throw new ye(`Canvas target not found: ${e}`);if(!cr.test(o.path))throw new ye("Canvas node capture requires the target path to be a .canvas file.");let s=await r.vault.read(o),a=kle(s,o.path),l=a.nodes.findIndex(g=>g.id===i);if(l===-1)throw new ye(`Canvas node id '${i}' was not found in ${o.path}.`);let c=a.nodes[l],u=h$(c);if(u==="unsupported")throw new ye("Canvas capture currently supports only text and file cards.");let d=v6(u,n);if(d)throw new ye(d);if(u==="text")return{kind:"text",source:"configured",canvasFile:o,rawCanvas:s,canvasData:a,nodeData:c,nodeIndex:l};let p=r,{targetPath:f,targetFile:m}=Tle(p,c);return{kind:"file",source:"configured",canvasFile:o,nodeData:c,targetPath:f,targetFile:m}}function C6(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 x6(r,e,t){if(e.source==="active"){typeof e.node.setText=="function"?e.node.setText(t):e.node.text=t,e.canvas.requestSave?.();return}if(await r.vault.read(e.canvasFile)!==e.rawCanvas)throw new ye("Canvas target changed while capture was running. Re-run capture to avoid overwriting newer Canvas edits.");e.nodeData.text=t,e.canvasData.nodes[e.nodeIndex]=e.nodeData,await r.vault.modify(e.canvasFile,JSON.stringify(e.canvasData,null," "))}$b();var Vh=4e3,Sle=/^[ \t\r\n\f\v]*$/;function E6(r){return Sle.test(r)}var _le=/\{\{(?:VALUE|FILE|FIELD):[^}]*\|\s*multi\s*(?=[:}|]|$)[^}]*\}\}/gi,Ale=/\|\s*format\s*:\s*(?:inline|spaced|yaml|markdown)\s*(?=\||}})/i;function Ile(r){return Array.from(r.matchAll(_le)).some(e=>!Ale.test(e[0]))}var GS=class extends jS{constructor(t,n,i,o,s=null){super(t);this.choiceExecutor=o;this.originLeaf=s;this.capturePropertyVars=new Map;this.suppressFrontmatterCollection=!1;this.resolvedInsertAfterHeading=null;this.choice=i,this.plugin=n,this.outcome=new Oh(o),this.formatter=new WS(t,n,o),this.formatter.setPromptRunContext({draftScopeId:i.id,choiceName:i.name})}captureResolvedOrderedHeading(){if(this.choice.insertAfter?.enabled&&this.choice.insertAfter.createIfNotFoundLocation===vs){let t=this.formatter.getResolvedInsertAfterHeading();t&&(this.resolvedInsertAfterHeading=t)}}showSuccessNotice(t,{wasNewFile:n,action:i}){let o=`'${t.basename}'`;if(n){new Ra.Notice(`Created and captured to ${o}`,Vh);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 Ra.Notice(a,Vh)}showNothingToCaptureNotice(t,{wasNewFile:n}){let i=`'${t.basename}'`;new Ra.Notice(n?`Created ${i} \u2014 nothing to capture (no content)`:`Nothing to capture \u2014 ${i} unchanged`,Vh)}hasActiveMarkdownCaptureContext(){let t=!!this.app.workspace.getActiveFile(),n=!!xn(this.app);return t&&n}shouldSkipRequiredCanvasLinkInsertion(t,n){return n&&t.destination?.type!=="specifiedFile"&&t.requireActiveFile&&!this.hasActiveMarkdownCaptureContext()}async insertCaptureLink(t,n,{isCanvasTriggered:i,onEditorTextMutation:o}){if(n.enabled){if(n.destination?.type!=="specifiedFile"&&!al(n.placement)&&this.shouldSkipRequiredCanvasLinkInsertion(n,i)){this.plugin.settings.showCaptureNotification&&new Ra.Notice("Canvas capture skipped link insertion because no Markdown editor is focused.",Vh);return}await DS(this.app,t,n,this.choiceExecutor.focusedProperty,o)}}async copyCapturedFileLinkToClipboard(t){this.choice.copyLinkToClipboard&&await FS(t)}validateAppendLinkDestination(t){let n=IS(this.app,t);return n?(this.failRun(n),!1):!0}async run(){let t=!1;try{this.capturePropertyVars.clear();let n=bc(this.choice.appendLink);if(this.formatter.setLinkToCurrentFileBehavior(n.enabled&&!n.requireActiveFile?"optional":"required"),!this.validateAppendLinkDestination(n))return;let i=this.choice.useSelectionAsCaptureValue,o=this.plugin.settings.useSelectionAsCaptureValue??!0,s=typeof i=="boolean"?i:o;this.formatter.setUseSelectionAsCaptureValue(s);let a=this.choice.propertyCapture===void 0?void 0:oT(this.choice.propertyCapture),l=a?"append":g6(this.choice),c=this.choice.captureToActiveFile?b6(this.app,l):null,u=await this.resolveConfiguredCanvasTarget(l),d=c??u;if(d?.kind==="text"){if(a)throw new ye("Property capture requires a Markdown note. Canvas text cards do not have note properties.");await this.handleCanvasTextCapture(d,l,n,()=>{t=!0});return}if(!a&&d?.kind==="file"&&(l==="insertAfter"&&this.choice.insertAfter?.createIfNotFound&&this.choice.insertAfter?.createIfNotFoundLocation==="cursor"||l==="insertBefore"&&this.choice.insertBefore?.createIfNotFound&&this.choice.insertBefore?.createIfNotFoundLocation==="cursor"))throw new ye("Canvas file cards do not support creating missing line targets at cursor. Use top or bottom.");let p=d?.kind==="file"?d.source==="configured"?d.targetFile?.path??d.targetPath:d.targetFile.path:await this.getFormattedPathToCaptureTo(this.choice.captureToActiveFile);if(!d&&!this.choice.captureToActiveFile&&cr.test(p))throw new ye("Capture to a .canvas file requires a target canvas node id.");let f=this.getCaptureContent(),m=await this.fileExists(p);if(!m&&this.choice?.createFileIfItDoesntExist?.enabled&&Vb(p),a){await this.captureToProperty({filePath:p,fileAlreadyExists:m,config:a,linkOptions:n,isCanvasTriggered:!!d,onCommit:()=>{t=!0}});return}this.isInsertAfterHeadingMode()&&!cr.test(p)&&await this.maybeResolveInsertAfterHeading(await this.readNoteBodyForHeadingPicker(p,m));let g=!m&&!!this.choice?.createFileIfItDoesntExist?.enabled&&!this.choice?.createFileIfItDoesntExist?.createWithTemplate;if(this.suppressFrontmatterCollection=!g,this.suppressFrontmatterCollection&&Ile(this.choice?.format?.format??"")&&I.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."),!m&&!this.choice?.createFileIfItDoesntExist?.enabled)throw new ye(`Target file missing: ${p}. Enable "Create file if it doesn't exist" or choose an existing file.`);let v=m?await this.onFileExists(p,f,l==="currentLine"||l==="newLineAbove"||l==="newLineBelow"):await this.onCreateFileIfItDoesntExist(p,f,n);if(v===null){this.plugin.settings.showCaptureNotification&&new Ra.Notice("Nothing to capture (no content)",Vh),this.outcome.success(void 0,"unchanged");return}if(v.markerOnly){t=!m,this.plugin.settings.showCaptureNotification&&this.showNothingToCaptureNotice(v.file,{wasNewFile:!m}),this.outcome.success(v.file,m?"unchanged":"created");return}this.captureResolvedOrderedHeading();let y=await this.commitCapture(v,{action:l,fileAlreadyExists:m,onCommit:()=>{t=!0}});if(!y)return;let{file:b}=v,{captureIsNoOp:x,marked:w}=y,T=y.cursor;this.outcome.success(b,y.effect),this.plugin.settings.showCaptureNotification&&(x?this.showNothingToCaptureNotice(b,{wasNewFile:!m}):this.showSuccessNotice(b,{wasNewFile:!m,action:l})),await this.copyCapturedFileLinkToClipboard(b),T&&n.enabled&&(n.destination.type==="specifiedFile"?$g(this.app,n.destination):al(n.placement)?this.app.workspace.getActiveFile():this.choiceExecutor.focusedProperty?.file)?.path===b.path&&(T=null),await this.insertCaptureLink(b,n,{isCanvasTriggered:!!d,onEditorTextMutation:w&&T&&!al(n.placement)?A=>{w&&T&&A.filePath===b.path&&(T=RS(T,A))}:void 0});let C=Cn(this.choice.fileOpening).focus??!0;this.choice.openFile&&(C=await gp({app:this.app,file:b,opening:this.choice.fileOpening,originLeaf:this.originLeaf}));let S=xn(this.app)?.file?.path===b.path;(this.choice.openFile||w&&S)&&!await ol(this.app,b)&&T&&(C||w&&S)&&(T.offsets.length===1?UA(this.app,b,T.offsets[0],T.content):Vg(this.app,b,T.offsets,T.content))}catch(n){if(t||await this.cleanupCreatedClipboardAttachments(),bu(n,{logPrefix:"Capture execution aborted",noticePrefix:"Capture execution aborted",defaultReason:"Capture aborted"})){this.choiceExecutor.signalAbort?.(n);return}ii.getInstance().markExecutionScopeFailed(),this.outcome.failure(OS(n)),Ze(n,`Error running capture choice "${this.choice.name}"`)}finally{t&&this.formatter.consumeCreatedClipboardAttachmentPaths()}}async commitCapture(t,n){let{file:i,captureContent:o,newFileContent:s,priorContent:a,cursor:l,cursorPlacementSafe:c=!0}=t,u=E6(o),{action:d}=n;if(d==="currentLine"||d==="newLineAbove"||d==="newLineBelow"){let y=u?o:await il(this.app,o,i),b=Tf(y);if(b.cursor.kind==="none"&&/{{CURSOR}}/i.test(y))return this.plugin.settings.showCaptureNotification&&this.showNothingToCaptureNotice(i,{wasNewFile:!n.fileAlreadyExists}),this.outcome.success(i,"unchanged"),null;u=E6(b.content);let x=b.cursor.kind==="offset"&&b.cursor.source==="marker",w=null;return!u&&!(x?(w=VN(b,this.app,i,d))!==null:(d==="currentLine"?LA:d==="newLineAbove"?BA:qA)(b.content,this.app))?(await this.cleanupCreatedClipboardAttachments(),this.failRun(`Capture "${this.choice.name}": no active Markdown editor to insert into.`),null):(n.onCommit(),{effect:u?"unchanged":"changed",captureIsNoOp:u,cursor:w,marked:x})}await this.app.vault.modify(i,s),n.onCommit();let p=this.choice.templater?.afterCapture==="wholeFile";p&&await yc(this.app,i);let f=await this.applyCapturePropertyVars(i),m=p||f,g=n.fileAlreadyExists?s!==a||m?"changed":"unchanged":"created",v=c&&!m&&l.kind==="offset"?{offsets:[l.value],content:s}:null;return{effect:g,captureIsNoOp:u,cursor:v,marked:l.kind==="offset"&&l.source==="marker"}}async captureToProperty(t){let{filePath:n,fileAlreadyExists:i,config:o,linkOptions:s}=t;if(!Nt.test(n))throw new ye("Property capture requires a Markdown note.");if(!i&&!this.choice.createFileIfItDoesntExist.enabled)throw new ye(`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(Ia(n)),this.formatter.setTargetFolderPath(Ai(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?await this.app.vault.read(a):"",c=!a&&this.choice.createFileIfItDoesntExist.createWithTemplate,u=new Map;if(c){let b=new vh(this.app,this.plugin,this.choice.createFileIfItDoesntExist.template,this.choiceExecutor);b.setDestinationPath(n),b.setPromptRunContext({draftScopeId:`${this.choice.id}#${this.choice.createFileIfItDoesntExist.template}`,choiceName:this.choice.name,destination:n,destinationKind:"file"}),s.enabled&&!s.requireActiveFile&&b.setLinkToCurrentFileBehavior("optional"),l=await b.run(),u=b.getAndClearTemplatePropertyVars()}let d=J2(l);for(let[b,x]of u)Lb(d,b.split(co.PATH_SEPARATOR),Af(x));let p=Mv(d,H2(o.property.kind==="named"?await this.formatter.formatPropertyName(o.property.format):await this.promptForCaptureProperty(d,o.createIfMissing))),f=ca(this.app,p,{registeredOnly:!0}),m=Object.prototype.hasOwnProperty.call(d,p)?d[p]:void 0,g=f??(typeof m=="number"?"number":typeof m=="boolean"?"checkbox":null),v=this.choice.format.enabled?this.choice.format.format:Or,y=G2(this.choiceExecutor.variables);try{K2(this.choiceExecutor.variables,p,m),this.formatter.consumePropertyTokenExpanded();let b=await this.formatter.formatPropertyValue(mS(v,g)),x=z2(v)||this.formatter.consumePropertyTokenExpanded(),w=A=>Z2({frontmatter:A,key:p,value:b,config:o,registeredType:ca(this.app,p,{registeredOnly:!0}),compose:x}),T=w(d);if(o.action==="addToList"&&X2(b)){this.outcome.success(a,"unchanged");return}let C="";a?(C=await this.app.vault.read(a),await this.app.fileManager.processFrontMatter(a,A=>{A[Mv(A,p)]=w(A)})):(d[p]=T,a=await this.createFileWithInput(n,eV(l,d),{suppressTemplaterOnCreate:c})),t.onCommit(),!i&&(c||Xp(this.app))&&(c?await yc(this.app,a):await bC(this.app,a),await this.app.fileManager.processFrontMatter(a,A=>{A[Mv(A,p)]=w(A)}));let S=await this.app.vault.read(a);this.outcome.success(a,i?S===C?"unchanged":"changed":"created"),this.plugin.settings.showCaptureNotification&&new Ra.Notice(`Captured to '${p}' in '${a.basename}'`,Vh),await this.copyCapturedFileLinkToClipboard(a),await this.insertCaptureLink(a,s,{isCanvasTriggered:t.isCanvasTriggered}),this.choice.openFile&&await gp({app:this.app,file:a,opening:this.choice.fileOpening,originLeaf:this.originLeaf})}finally{Y2(this.choiceExecutor.variables,y)}}async promptForCaptureProperty(t,n){let i=Object.keys(t).filter(o=>o!=="__proto__").sort((o,s)=>o.localeCompare(s));if(!n&&i.length===0)throw new ye("The capture target has no properties. Enable 'Create property if missing' to add one.");return await wo(this.choiceExecutor,{remote:o=>Co(o,{items:i.map(s=>({value:s,title:s})),placeholder:"Property",allowCustomInput:n,what:"the property picker"}),headless:async()=>{throw new ye("Property capture needs a property selection. Configure a named property or run with the ui flag.")},app:()=>Mr.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(t){ii.getInstance().markExecutionScopeFailed(),I.logError(t),this.outcome.failure(t)}async cleanupCreatedClipboardAttachments(){let t=this.formatter.consumeCreatedClipboardAttachmentPaths();for(let n of t)try{let i=this.app.vault.getAbstractFileByPath(n);i instanceof Ra.TFile&&await this.app.fileManager.trashFile(i)}catch(i){I.logWarning(`QuickAdd: failed to clean up clipboard attachment '${n}': ${String(i)}`)}}async handleCanvasTextCapture(t,n,i,o){if(n==="currentLine"||n==="newLineAbove"||n==="newLineBelow")throw new ye("Canvas text cards support top, bottom, insert-after, and insert-before positions only.");if(n==="insertAfter"&&this.choice.insertAfter?.createIfNotFound&&this.choice.insertAfter?.createIfNotFoundLocation==="cursor"||n==="insertBefore"&&this.choice.insertBefore?.createIfNotFound&&this.choice.insertBefore?.createIfNotFoundLocation==="cursor")throw new ye("Canvas text cards do not support creating missing line targets at cursor. Use top or bottom.");let s=t.canvasFile;this.formatter.setTitle(Ia(s.basename)),this.formatter.setDestinationFile(s);let a=this.getCaptureContent(),l=C6(t);this.isInsertAfterHeadingMode()&&await this.maybeResolveInsertAfterHeading(l);let{content:c,markerOnly:u}=await this.formatter.formatContentWithFile(a,this.choice,l,s);if(u){this.plugin.settings.showCaptureNotification&&this.showNothingToCaptureNotice(s,{wasNewFile:!1}),this.outcome.success(s,"unchanged");return}this.captureResolvedOrderedHeading();let d=c===l;d||await x6(this.app,t,c),o(),this.outcome.success(s,d?"unchanged":"changed"),this.plugin.settings.showCaptureNotification&&(d?this.showNothingToCaptureNotice(s,{wasNewFile:!1}):this.showSuccessNotice(s,{wasNewFile:!1,action:n})),await this.copyCapturedFileLinkToClipboard(s),await this.insertCaptureLink(s,i,{isCanvasTriggered:!0}),this.choice.openFile&&s&&(await gp({app:this.app,file:s,opening:this.choice.fileOpening,originLeaf:this.originLeaf}),await ol(this.app,s))}async resolveConfiguredCanvasTarget(t){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 cr.test(o)?await w6(this.app,o,i,t):null}async maybeResolveInsertAfterHeading(t){let n=this.choice.insertAfter;if(!n?.enabled||!n.promptHeading)return;let i=!!n.createIfNotFound,o=Eu(t),s=Gl(o),a=s.map(f=>o[f.line]),l=s.map(f=>`${" ".repeat(Math.max(0,f.level-1))}${f.text}`),c=s.map(f=>f.text),u="Choose a heading to insert under",d=String(await wo(this.choiceExecutor,{remote:f=>Co(f,{items:a.map((m,g)=>({value:m,title:l[g]??m})),placeholder:u,allowCustomInput:i,what:"the heading picker"}),headless:()=>{throw new ye(`'${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:()=>Mr.Suggest(this.app,l,a,{allowCustomValue:i,placeholder:u,emptyStateText:i?"No headings found \u2014 type a heading to create":"No headings found in the target note",customValueLabel:f=>`Insert after new line: ${f}`})}));$n(!!d&&d.length>0,"No heading selected for capture."),this.formatter.setInsertAfterTargetOverride(d);let p=a.indexOf(d);this.resolvedInsertAfterHeading=p>=0?c[p]:d}isInsertAfterHeadingMode(){return!!this.choice.insertAfter?.enabled&&!!this.choice.insertAfter.promptHeading}async readNoteBodyForHeadingPicker(t,n){if(!n)return"";let i=this.app.vault.getAbstractFileByPath(t);return i instanceof Ra.TFile?await this.app.vault.read(i):""}getCaptureContent(){let t;return this.choice.format.enabled?t=this.choice.format.format:t=Or,this.choice.task&&(t=`- [ ] ${t}
`),t}async onFileExists(t,n,i=!1){let o=this.getFileByPath(t);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));this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());let a=await this.app.vault.read(o);if(/{{CURSOR}}/i.test(s)&&Tf(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.formatContentWithFile(s,this.choice,a,o));if(this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars()),l.markerOnly)return{file:o,newFileContent:a,captureContent:l.captureContent,priorContent:a,cursor:l.cursor,markerOnly:!0};let c=await this.app.vault.read(o),u=l.content,d=!0;if(c!==a){let p=JG(c,a,l.content);$n(p.isSuccess(),()=>`The file ${t} has been modified since the last read.
QuickAdd could not merge the versions two without conflicts, and will not modify the file.
This is in order to prevent data loss.`),u=p.joinedResults(),d=!1}return{file:o,newFileContent:u,captureContent:l.captureContent,priorContent:c,cursor:l.cursor,cursorPlacementSafe:d}}async onCreateFileIfItDoesntExist(t,n,i){Vb(t);let o=Ia(t);this.formatter.setTitle(o),this.formatter.setDestinationSourcePath(t);let s=await this.collectIfFrontmatter(()=>this.formatter.formatContentOnly(n));if(this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars()),/{{CURSOR}}/i.test(s)&&Tf(s).cursor.kind==="none")return null;let a="";if(this.choice.createFileIfItDoesntExist.createWithTemplate){let d=new vh(this.app,this.plugin,this.choice.createFileIfItDoesntExist.template,this.choiceExecutor);i?.enabled&&!i.requireActiveFile&&d.setLinkToCurrentFileBehavior("optional"),d.setTargetFolderPath(Ai(t)),d.setPromptRunContext({draftScopeId:`${this.choice.id}#${this.choice.createFileIfItDoesntExist.template}`,choiceName:this.choice.name,destination:t,destinationKind:"file"}),a=await d.run();let p=d.getAndClearTemplatePropertyVars();I.logMessage(`CaptureChoiceEngine: Collected ${p.size} template property variables`),p.size>0&&I.logMessage(`Variables: ${Array.from(p.keys()).join(", ")}`),this.templatePropertyVars=p}let l=await this.createFileWithInput(t,a,{suppressTemplaterOnCreate:this.choice.createFileIfItDoesntExist.createWithTemplate});this.choice.createFileIfItDoesntExist.createWithTemplate&&this.templatePropertyVars&&hh(l,this.templatePropertyVars)&&await gh(this.app,l,this.templatePropertyVars),this.choice.createFileIfItDoesntExist.createWithTemplate&&a?await yc(this.app,l):Xp(this.app)&&await bC(this.app,l);let c=await this.app.vault.read(l),u=await this.collectIfFrontmatter(()=>this.formatter.formatContentWithFile(s,this.choice,c,l));return this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars()),{file:l,newFileContent:u.content,captureContent:u.captureContent,priorContent:c,cursor:u.cursor,cursorPlacementSafe:!0,markerOnly:u.markerOnly}}collectIfFrontmatter(t){return this.suppressFrontmatterCollection?t():this.formatter.withTemplatePropertyCollection(t)}mergeCapturePropertyVars(t){if(!(!t||t.size===0)){for(let[n,i]of t)this.capturePropertyVars.set(n,i);I.logMessage(`CaptureChoiceEngine: Accumulated ${this.capturePropertyVars.size} structured capture variables`)}}async applyCapturePropertyVars(t){return this.capturePropertyVars.size===0?!1:hh(t,this.capturePropertyVars)?(I.logMessage(`CaptureChoiceEngine: Post-processing front matter with ${this.capturePropertyVars.size} capture variables`),await gh(this.app,t,this.capturePropertyVars),this.capturePropertyVars.clear(),!0):(this.capturePropertyVars.clear(),!1)}};Ob();var Eo=require("obsidian");rn();xt();ur();dt();bt();Lg();var v$=require("obsidian");Xe();Zo();ht();xt();function T6(r){let e=r.split("/").pop()??r,t=e.lastIndexOf(".");return t>0?e.slice(0,t):e}function y$(r){let e=new ou(T6(r));return e.id=`folder-template:${r}`,e.templatePath=r,e.openFile=!0,e.fileNameFormat={enabled:!0,format:Or},e.discoverExistingNotesBeforeCreate=!0,e}function b$(r){return ri(r.settings.templateFolderPaths).length>0}function Dle(r,e){let t=r.lastIndexOf("/"),n=t===-1?"":r.slice(0,t),i=e.createDiv({cls:"suggestion-content"});i.createDiv({cls:"suggestion-title",text:T6(r)}),n&&(e.classList.add("mod-complex"),i.createDiv({cls:"suggestion-note",text:n}))}async function Fle(r,e){let n=[...e].sort((i,o)=>i.path.localeCompare(o.path)).map(i=>i.path);try{return await Xt.Suggest(r,n,n,"New note from template",(i,o)=>Dle(i,o))}catch(i){if(ot(i))return null;throw i}}async function YS(r,e,t){try{let n=t.templatePath?.trim()||void 0;if(!n){if(!b$(e)){new v$.Notice("QuickAdd: Set a template folder in Settings \u2192 QuickAdd \u2192 Templates & properties to use \u201CNew note from template\u201D.",8e3),Zm(r,e.manifest.id,{notice:!1});return}let i=e.getTemplateFiles();if(i.length===0){new v$.Notice("QuickAdd: No template files found in your configured template folder(s).");return}let o=await Fle(r,i);if(!o)return;n=o}await t.choiceExecutor.execute(y$(n))}catch(n){if(ot(n))return;Ze(n,"Error running template from folder")}}bt();bs();var Ple="\u2190 Back",Mle="Select a choice";function lw(r){return jo(r)?`QuickAdd couldn't read the contents of "${r.name}". They're still in data.json.`:`Folder "${r.name}" is empty.`}var $le="Empty",Ole="Unreadable";function Rle(r){return w$(r)?jo(r)?Ole:$le:""}var aw="quickadd:run-template-from-folder",Nle="New note from template\u2026",Bh="quickadd:back";function w$(r){return r.type==="Multi"&&r.id!==Bh&&et(r).length===0}var Lle=.5;function Vle(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 C$(r){return(r.settings.templateFolderLauncherRow??"bottom")!=="off"&&b$(r)}function Ble(){return{id:aw,name:Nle,type:"Template",command:!1}}var yp=class r extends Eo.FuzzySuggestModal{constructor(t,n,i){super(t.app);this.plugin=t;this.choices=n;this.focusedProperty=null;this.triggerContext=null;this.placeholderStack=[];this.selectionDispatched=!1;this.breadcrumbById=new Map;this.markdownComponent=new Eo.Component;this.warnRenderFailure=ff("Could not render a choice name as Markdown; showing it as plain text");if(this.choiceExecutor=i?.choiceExecutor??new Hr(this.app,this.plugin),this.focusedProperty=i&&"focusedProperty"in i?i.focusedProperty??null:xC(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.currentPlaceholder=i?.placeholder?.trim()||Mle,this.setPlaceholder(this.currentPlaceholder),this.markdownComponent.load(),i?.includeTemplateFolderRow){let o=this.plugin.settings.templateFolderLauncherRow??"bottom";if(C$(this.plugin)){let s=Ble();this.choices=o==="top"?[s,...this.choices]:[...this.choices,s]}}}static Open(t,n,i){new r(t,n,i).open()}onClose(){super.onClose(),this.markdownComponent.unload(),this.completion&&!this.selectionDispatched&&this.completion(Rr())}getSuggestions(t){let n=t.trim();if(!n||!X.getState().searchNestedChoices)return super.getSuggestions(n);let i=(0,Eo.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-=Lle),o.push({item:s.choice,match:a}))}return o.sort((s,a)=>a.match.score-s.match.score),o}getNestedSearchCandidates(){if(!this.nestedSearchCandidates){let t=this.choices.filter(n=>n.id!==Bh&&n.id!==aw);this.nestedSearchCandidates=av(t).map(({choice:n,path:i})=>{let o=i.slice(0,-1);o.length>0&&this.breadcrumbById.set(n.id,o.map(Vle).join(" / "));let s=i.join(" / ");return{choice:n,text:s,nameOffset:s.length-n.name.length}})}return this.nestedSearchCandidates}selectSuggestion(t,n){if(w$(t.item)){if("repeat"in n&&n.repeat)return;new Eo.Notice(lw(t.item)),this.inputEl.focus();return}this.selectionDispatched=!0,super.selectSuggestion(t,n)}renderSuggestion(t,n){n.empty(),n.classList.remove("mod-complex");let i=this.breadcrumbById.get(t.item.id),o=n.createDiv({cls:"quickadd-choice-suggestion-content"});this.renderChoiceIcon(t.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"});Eo.MarkdownRenderer.render(this.app,t.item.name,s,"",this.markdownComponent).catch(c=>{s.textContent=t.item.name,this.warnRenderFailure(c)}),n.classList.add("quickadd-choice-suggestion"),t.item.id===Bh&&n.classList.add("quickadd-choice-suggestion-back"),t.item.id===aw&&n.classList.add("quickadd-choice-suggestion-run-template");let a=Rle(t.item),l=a!=="";if(n.classList.toggle("quickadd-choice-suggestion-empty",l),l){n.setAttribute("aria-disabled","true");let c=er(o,"span");c.classList.add("quickadd-choice-suggestion-empty-flair"),c.textContent=a,o.appendChild(c)}else n.removeAttribute("aria-disabled")}renderChoiceIcon(t,n){let i=this.getChoiceSuggestionIcon(t);if(!i)return;let o=er(n,"span");o.classList.add("quickadd-choice-icon"),o.setAttribute("aria-hidden","true"),n.appendChild(o),(0,Eo.setIcon)(o,i)}getChoiceSuggestionIcon(t){if(t.id!==Bh)return t.id===aw?"file-plus":xd(t)}getItemText(t){return t.name}getItems(){return this.choices}settleCompletion(t,n){t.then(()=>this.completion?.(),i=>{let o=typeof i=="string"&&ot(i)?Rr():nl(i);ad(o,n),this.completion?.(o)})}onChooseItem(t,n){if(t.id===aw){this.settleCompletion(YS(this.app,this.plugin,{choiceExecutor:this.choiceExecutor}),"Could not run a template from that folder");return}if(t.type==="Multi")this.onChooseMultiType(t);else{"shiftKey"in n&&n.shiftKey&&(this.choiceExecutor.pickDate=!0);let i=this.choiceExecutor.executeWithFocusedProperty?this.choiceExecutor.executeWithFocusedProperty(t,this.focusedProperty,this.triggerContext):this.choiceExecutor.execute(t);this.settleCompletion(i,`Could not run "${t.name}"`)}}onChooseMultiType(t){let n=t.id===Bh;if(!n&&w$(t)){new Eo.Notice(lw(t)),this.completion?.();return}let i=[...et(t)];if(!n){let a=new qm(Ple).addChoices(this.choices);a.id=Bh,i.push(a)}let o=n?this.placeholderStack[this.placeholderStack.length-1]:t.placeholder?.trim()||t.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})}};dt();Ni();Ie();YM();lo();aD();Kb();Xe();Kf();Kc();xh();GM();Dh();function qle(r,e,t){let n=e.pickDate?Qf(_l(r.dateOrigin)):_l(r.dateOrigin),i=Jk({setting:n,clocks:e.clocks,variables:new Map([...e.variables,...Object.entries(t)]),reservedSeed:n?.kind==="ask"?t[rl]:void 0});return i.status!=="set"?e.clocks:{now:e.clocks?.now??new Date,date:i.date}}function k6(r,e){let t=r.trim();if(!t)return[];let n=Array.from(e.keys()).sort((s,a)=>a.length-s.length),i=[],o=t;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 Ule(r,e,t){let n=r.filter(o=>t||e.includes(o)),i=new Set(n);return[...e.filter(o=>i.has(o)),...n.filter((o,s)=>!e.includes(o)&&n.indexOf(o)===s)]}async function S6(r,e,t,n){try{if(Qj(t,n.id))return!1;let i=t.promptProvider?null:await Jj(r,e,t,n),o=i?.requirements??await $a(r,e,t,n,{seedCaptureSelectionAsValue:!0,preloadedUserScripts:t.preloadedUserScripts});if(o.length===0)return!1;let s=Hl(o,t.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 Yf(r,e);v.setRunClocks(qle(n,t,g));let y=[];if(n.type==="Template"){let b=n;if(b.fileNameFormat?.enabled){v.setTargetFolderPath(RE(b.folder)??"Folder/Name");for(let[x,w]of Object.entries(g))v.variables.set(x,w);y.push({label:"File name",text:await v.format(b.fileNameFormat.format),diagnostics:v.diagnostics.list()})}}return y}catch{return[]}},c=t.promptProvider,u=null,d;c?d=await c.requestInputs(a):(u=new Fh(r,a,t.variables,l,i?.config),d=await u.waitForClose);let p=new Map,f=new Map;for(let g of u?.activeRequirements??a){if(g.id.startsWith(gv)){let v=g.options??[],y=g.displayOptions??v;p.set(g.id,{options:v,displayToValue:new Map(v.map((b,x)=>[(y[x]??b).trim(),b])),allowCustom:g.suggesterConfig?.allowCustomInput??!1,multiSelect:g.suggesterConfig?.multiSelect??!1})}if(g.suggesterConfig?.multiSelect&&!g.id.startsWith(gv)){let v=g.options??[],y=g.displayOptions??v,b=new Map;v.forEach((x,w)=>{b.set((y[w]??x).trim(),x)}),f.set(g.id,{emit:g.multiEmit??"text",allowCustom:g.suggesterConfig.allowCustomInput??!1,displayToValue:b})}}let m=i?new Map:t.variables;return Object.entries(d).forEach(([g,v])=>{let y=p.get(g);if(y!==void 0){let w=u?.fileSelections.get(g)??(Array.isArray(v)?v.map(String):void 0)??(y.multiSelect?k6(String(v),y.displayToValue).map(S=>y.displayToValue.get(S)??S):[String(v)]),C=Ule(w,y.options,y.allowCustom).map(S=>q1(S,y.options));m.set(g,y.multiSelect?C:C[0]??"");return}let b=f.get(g);if(b!==void 0){let w=(u?.multiSelections.get(g)??k6(String(v),b.displayToValue)).filter(T=>b.allowCustom||b.displayToValue.has(T)).map(T=>b.displayToValue.get(T)??T);m.set(g,b.emit==="linklist"?w.map(Ix):w);return}m.set(g,v)}),i&&u&&eG(t,i,m,u.discoverySelections),!0}catch(i){if(i instanceof yt)throw i;return t.promptProvider||I.logWarning(`One-page input failed for choice "${n.name}"; falling back to step-by-step prompts: ${i instanceof Error?i.message:String(i)}`),!1}}Ni();Yn();ur();xt();ht();bf();Lg();Kf();Kc();bt();Xe();fk();xh();Ie();Dh();Ah();zd();var Hr=class{constructor(e,t){this.app=e;this.plugin=t;this.variables=new Map;this.preparedInputs=jj();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}signalAbort(e){this.pendingAbort=e}consumeAbortSignal(){let e=this.pendingAbort;return this.pendingAbort=null,e??null}recordExecutionResult(e){this.pendingResult=e}beginExecutionContext(){this.executionDepth===0&&(this.focusedProperty=this.focusedPropertyOverride!==void 0?this.focusedPropertyOverride:xC(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(),Xj(this))}async execute(e){this.pendingAbort=null;let t=this.pendingResult;this.beginExecutionContext();let n=Ug(this.app),i=ii.getInstance();i.beginExecutionScope();try{await this.runOnePagePreflightIfEnabled(e),await Qb(this,e.id,async()=>{switch(await this.applyDateOrigin(e),e.type){case"Template":{let o=e;await this.onChooseTemplateType(o,n);break}case"Capture":{let o=e;await this.onChooseCaptureType(o,n);break}case"Macro":{let o=e;await this.onChooseMacroType(o,n);break}case"Multi":{let o=e;await this.onChooseMultiType(o);break}default:break}if(this.pendingAbort){i.rollbackExecutionScope();return}i.commitExecutionScope()})}catch(o){throw i.rollbackExecutionScope(),o}finally{this.pendingResult=t,this.endExecutionContext()}}async executeWithFocusedProperty(e,t,n){let i=this.focusedPropertyOverride,o=this.triggerContextOverride;this.focusedPropertyOverride=t,this.triggerContextOverride=n;try{await this.execute(e)}finally{this.focusedPropertyOverride=i,this.triggerContextOverride=o}}async executeWithOutcome(e){this.pendingAbort=null,this.pendingResult=null,this.beginExecutionContext();let t=Ug(this.app),n=ii.getInstance();n.beginExecutionScope();try{return await this.runOnePagePreflightIfEnabled(e),await Qb(this,e.id,async()=>{if(await this.applyDateOrigin(e),e.type==="Template"?await this.onChooseTemplateType(e,t):await this.onChooseCaptureType(e,t),this.pendingAbort){n.rollbackExecutionScope();let o=this.consumeAbortSignal(),s=o instanceof at;return{status:"cancelled",cancelKind:s?"user":"aborted",reason:s?void 0:o?.message}}n.commitExecutionScope();let i=this.pendingResult;return this.pendingResult=null,i??{status:"error"}})}catch(i){return n.rollbackExecutionScope(),i instanceof at?{status:"cancelled",cancelKind:"user"}:i instanceof yt?{status:"cancelled",cancelKind:"aborted",reason:i.message}:(Ze(i,"Error executing choice from URI"),{status:"error",reason:i instanceof Error?i.message:String(i)})}finally{this.endExecutionContext()}}async applyDateOrigin(e){if(Ma(e)&&(e.existingNoteAction??"open")==="open"&&hS(this,e.id)?.kind==="existing"&&nu(e,e.fileNameFormat.enabled?e.fileNameFormat.format:Or,this.variables.get("value")))return;let t=this.pickDate?Qf(_l(e.dateOrigin)):_l(e.dateOrigin),n=t?.kind==="ask"?this.variables.get(rl):void 0,i=Jk({setting:t,clocks:this.clocks,variables:this.variables,reservedSeed:n});if(i.status==="inherit")return;if(i.status==="error")throw I.logError(i.message),new ye(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 ye(`"${e.name}" needs a date. Re-run with date= or the ui flag.`);let o=`Date for ${e.name}`;try{let s=this.promptProvider?await this.promptProvider.datePrompt(o,{defaultValue:i.defaultValue,dateFormat:"YYYY-MM-DD"}):await Rl.Prompt(this.app,o,void 0,i.defaultValue,"YYYY-MM-DD"),a=Ub(s);if(!a)throw new ye("Could not parse the date origin.");this.clocks={now:this.clocks?.now??new Date,date:a}}catch(s){throw ot(s)?new at("Date origin cancelled by user"):s}}async prepareMacroInputs(e,t){if(t.length===0)return;let n={...e,macro:{...e.macro,commands:t}};await this.runOnePagePreflightIfEnabled(n)}async runOnePagePreflightIfEnabled(e){let t=X.getState().onePageInputEnabled,n=e.onePageInput??this.macroOnePageInput,i=this.promptProvider!=null;if((n==="always"||n!=="never"&&(t||i))&&(e.type==="Template"||e.type==="Capture"||e.type==="Macro"))try{await S6(this.app,this.plugin,this,e)}catch(s){throw ot(s)?new at("One-page input cancelled by user"):s}}async onChooseTemplateType(e,t){await new NS(this.app,this.plugin,e,this,t).run()}async onChooseCaptureType(e,t){await new GS(this.app,this.plugin,e,this,t).run()}async onChooseMacroType(e,t){let n=new _a(this.app,this.plugin,e,this,this.variables,this.preloadedUserScripts,void 0,t),i=this.macroOnePageInput;this.macroOnePageInput=e.onePageInput??i;try{await n.run()}finally{this.macroOnePageInput=i}Object.entries(n.params.variables).forEach(([o,s])=>{this.variables.set(o,s)})}async onChooseMultiType(e){let t=et(e);if(this.promptProvider||this.interactive===!1){let n=this.promptProvider?"Run one of its choices directly.":"Run one of its choices directly, or re-run with the ui flag.";this.signalAbort(new ye(t.length===0?lw(e):`"${e.name}" is a folder of choices, and picking from it needs someone at the window. ${n}`));return}if(t.length===0){new _6.Notice(lw(e));return}await new Promise((n,i)=>{yp.Open(this.plugin,t,{choiceExecutor:this,focusedProperty:this.focusedProperty,triggerContext:this.triggerContext,placeholder:e.placeholder?.trim()||e.name,completion:o=>o===void 0?n():i(o)})})}};ht();var A6=require("obsidian");var Hle="QuickAdd: No choices yet. Create your first one in Settings \u2192 QuickAdd.";function KS(r){let e=Array.isArray(r.settings.choices)?r.settings.choices:[];if(!(e.length>0||C$(r))){new A6.Notice(Hle,8e3),Zm(r.app,r.manifest.id,{notice:!1});return}yp.Open(r,e,{includeTemplateFolderRow:!0})}r$();Ie();Ie();ht();var I6={description:"Use QuickAdd template folder instead of Obsidian templates plugin folder / Templater templates folder.",migrate:async r=>{try{let e=r.app.plugins.plugins.templater,t=r.app.internalPlugins.plugins.templates;if(!e&&!t){I.logMessage("No template plugin found. Skipping migration.");return}let n=[];if(t){let s=t.instance.options;s.folder&&(n.push(s.folder),I.logMessage("Migrated template folder path to Obsidian Templates' setting."))}if(e){let s=e.settings;s.template_folder&&(n.push(s.template_folder),I.logMessage("Migrated template folder path to Templaters setting."))}let i=ri(r.settings.templateFolderPaths),o=ri([...i,...n]);o.length>0&&(r.settings.templateFolderPaths=o)}catch(e){throw I.logError("Failed to migrate template folder path."),e}}};Jr();function QS(r){return r===null||typeof r!="object"||!("type"in r)||!("choices"in r)?!1:r.type==="Multi"&&Array.isArray(r.choices)}function XS(r){return r===null||typeof r!="object"||!("choice"in r)?!1:r.choice!==void 0}bt();un();function D6(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="Template"&&"incrementFileName"in r}function F6(r){for(let e of r)QS(e)&&(e.choices=F6(e.choices)),D6(e)&&(e.setFileExistsBehavior=!0,e.fileExistsMode="Increment the file name",delete e.incrementFileName);return r}function zle(r){for(let e of r)for(let t of Ht(Er(e)))XS(t)&&D6(t.choice)&&(t.choice.setFileExistsBehavior=!0,t.choice.fileExistsMode="Increment the file name",delete t.choice.incrementFileName);return r}var Wle={description:"'Increment file name' setting moved to 'Set default behavior if file already exists' setting",migrate:async r=>{let e=r.settings,t=!mf(r.settings.choices)&&!sr(e.macros);if(Array.isArray(r.settings.choices)){let o=Ve(r.settings.choices);r.settings.choices=Ve(F6(o))}let n=Ve(bm(e.macros)),i=zle(n);if(Array.isArray(e.macros)&&(e.macros=i),!t)return{complete:!1}}},P6=Wle;Jr();Dl();function M6(r){return typeof r=="object"&&r!==null&&"type"in r&&r.type==="Template"}function jle(r){return r.fileExistsBehavior?r.fileExistsBehavior:r.setFileExistsBehavior?{kind:"apply",mode:lq(r.fileExistsMode)??"increment"}:r.incrementFileName?{kind:"apply",mode:"increment"}:{kind:"prompt"}}function $6(r){r.fileExistsBehavior=jle(r),delete r.incrementFileName,delete r.setFileExistsBehavior,delete r.fileExistsMode}var Gle={description:"Re-run template file collision normalization for users with older migration state",migrate:async r=>{let e=r.settings,t=!Gm(e);if(Array.isArray(r.settings.choices)&&(r.settings.choices=Ve(r.settings.choices)),Array.isArray(e.macros)&&(e.macros=Ve(e.macros)),Ym(r,n=>{M6(n)&&$6(n)}),!t)return{complete:!1}}},ZS=Gle;var Yle={description:"Repair template file collision settings that may have been left in legacy format",migrate:ZS.migrate},O6=Yle;bt();function x$(r){return Ue(r)&&r.type==="Capture"}Jr();bt();un();function R6(r){for(let e of r)QS(e)&&(e.choices=R6(e.choices)),x$(e)&&e.insertAfter?.enabled&&e.prepend&&(e.prepend=!1);return r}function Kle(r){for(let e of r)for(let t of Ht(Er(e)))XS(t)&&x$(t.choice)&&t.choice.insertAfter?.enabled&&t.choice.prepend&&(t.choice.prepend=!1);return r}var Qle={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 e=r.settings,t=!mf(r.settings.choices)&&!sr(e.macros);if(Array.isArray(r.settings.choices)){let o=Ve(r.settings.choices);r.settings.choices=R6(o)}let n=Ve(bm(e.macros)),i=Kle(n);if(Array.isArray(e.macros)&&(e.macros=i),!t)return{complete:!1}}},N6=Qle;dt();var Xle={description:"Set version to the current plugin version.",migrate:async r=>{X.setState({version:r.manifest.version})}},L6=Xle;ro();dt();Jr();var Zle={description:"Add default AI providers to the settings.",migrate:async r=>{let e=X.getState().ai,t=Ve(sC);if("OpenAIApiKey"in e&&typeof e.OpenAIApiKey=="string"){let n=t.find(i=>i.name==="OpenAI");n&&(n.apiKey=e.OpenAIApiKey)}"OpenAIApiKey"in e&&delete e.OpenAIApiKey,X.setState({ai:{...X.getState().ai,providers:t}})}},V6=Zle;Ie();bt();un();var Jle={description:"Remove macro indirection - embed macros directly in macro choices",migrate:async r=>{let e=r.settings;if(mf(e.choices))return I.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(e.choices))return I.logMessage("QuickAdd could not read the choice list, so legacy macros were left in place to be migrated later."),{complete:!1};if(sr(e.macros))return I.logMessage("QuickAdd could not read the legacy macro list, so it was left in place to be migrated later."),{complete:!1};let t=bm(e.macros),n=new Map,i=nn(e.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 t){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 Bm(o.name);a.macro={id:o.id,name:o.name,commands:o.commands||[]},a.runOnStartup=o.runOnStartup||!1,e.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&&(I.logMessage(`Removing orphaned macroId reference: ${s.macroId}`),delete s.macroId)}"macros"in e&&delete e.macros}},B6=Jle;Ie();function JS(r){if(r==null)return null;if(typeof r=="boolean")return{enabled:r};if(typeof r!="object")return null;let e=r;return{enabled:typeof e.enabled=="boolean"?e.enabled:void 0,direction:e.direction==="horizontal"||e.direction==="vertical"?e.direction:void 0,focus:typeof e.focus=="boolean"?e.focus:void 0}}function e_(r,e){let t=r.direction==="horizontal"?"horizontal":"vertical",n=typeof e=="string"&&e!=="default"?e:"default";return Cn({location:r.enabled?"split":"tab",direction:t,focus:r.focus??!0,mode:n})}var ece={description:"Migrate legacy openFileInNewTab settings to new fileOpening format",migrate:async r=>{I.logMessage("Starting migration of file opening settings...");let e=Gm(r.settings),t=0;if(Ym(r,i=>{if(i.type!=="Template"&&i.type!=="Capture")return;let o=i,s=o.openFileInNewTab,a=o.openFileInMode,l=JS(s);!o.fileOpening&&l&&(o.fileOpening=e_(l,a),t++,I.logMessage(`Migrated file opening settings for choice: ${i.name}`))}),I.logMessage(`Migration complete. Migrated ${t} choices.`),e)return{complete:!1}}},q6=ece;Ie();var tce={description:"Backfill missing file opening defaults for older choices",migrate:async r=>{I.logMessage("Starting file opening defaults backfill...");let e=Gm(r.settings),t=0;if(Ym(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,u=JS(l);(!s||s.location==null||s.direction==null||s.mode==null||s.focus==null)&&(!s&&u?o.fileOpening=e_(u,c):o.fileOpening=Cn(s),t++)}),I.logMessage(`File opening defaults backfill complete. Updated ${t} choice(s).`),e)return{complete:!1}}},U6=tce;dt();Jr();var rce={description:"Ensure every AI provider has a discovery mode so browsing works without models.dev",migrate:async r=>{let t=X.getState().ai.providers??[],n=!1;for(let i of t)i.modelSource||(i.modelSource="auto",n=!0);n&&X.setState(i=>({...i,ai:{...i.ai,providers:Ve(t)}}))}},H6=rce;Jr();Ie();dt();Jr();Yd();var nce={description:"Move AI provider API keys into Obsidian SecretStorage",migrate:async r=>{let e=X.getState().ai.providers??[],t=()=>e.some(o=>(o.apiKey?.trim()??"")!==""),n=r.app?.secretStorage;if(!n?.getSecret||!n?.setSecret)return t()?(I.logWarning("SecretStorage unavailable; deferring AI provider API key migration until it is available."),{complete:!1}):void 0;let i=!1;for(let o of e){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){I.logWarning(`Failed to migrate secret for ${o.name}: ${l.message??l}`)}continue}if(s)try{let l=await JU(r.app,o,s);l&&(o.apiKeyRef=l,o.apiKey="",i=!0)}catch(l){I.logWarning(`Failed to store API key for ${o.name}: ${l.message??l}`)}}if(i&&X.setState(o=>({...o,ai:{...o.ai,providers:Ve(e)}})),t())return{complete:!1}}},z6=nce;ht();var W6={description:"Move the single template folder path into the multi-folder list.",migrate:async r=>{let e=r.settings,t=ri(e.templateFolderPaths);t.length>0?e.templateFolderPaths=t:e.templateFolderPaths=ri([e.templateFolderPath]),delete e.templateFolderPath}};ro();vr();dt();Jr();Ie();function ice(r){for(let e of[r,`https://${r}`])try{let t=new URL(e).hostname.toLowerCase();if(t)return t}catch{}return""}function oce(r){let e=ice(r.endpoint??"");return e==="api.openai.com"?"openai":e==="generativelanguage.googleapis.com"?"google":e==="api.anthropic.com"?"anthropic":null}function sce(r,e,t){let n=new Set(e==="anthropic"?[]:NR[e]);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 Tg[e]){let s=i.get(o.name);s?(s.maxTokens=o.maxTokens,s.maxOutputTokens=o.maxOutputTokens,s.supportsTemperature=o.supportsTemperature):t.has(o.name)||r.models.push({...o})}}var ace={temperature:1,top_p:1,frequency_penalty:0,presence_penalty:0};function lce(r){return r.type==="AIAssistant"}var cce={description:"Refresh built-in AI provider model lists: drop retired models, add the current generation, and turn on auto-sync.",migrate:async r=>{let e=X.getState(),t=Ve(e.ai.providers??[]),n=Ve(e.choices??[]),i=new Set;for(let l of t){let c=oce(l);if(!c)continue;let u=new Set(t.filter(f=>f!==l).flatMap(f=>f.models.map(m=>m.name))),d=l.models.map(f=>f.name);sce(l,c,u);let p=new Set(l.models.map(f=>f.name));for(let f of d)p.has(f)||i.add(f);l.autoSyncModels=!0,c==="openai"&&(l.modelSource="modelsDev")}let o=new Set(t.flatMap(l=>l.models.map(c=>c.name))),s=new Set([...i].filter(l=>!o.has(l)));WT({choices:n},l=>{if(!lce(l))return;l.model&&s.has(l.model)&&(I.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[u,d]of Object.entries(ace))c[u]===d&&delete c[u]});let a=s.has(e.ai.defaultModel)?"Ask me":e.ai.defaultModel;X.setState({choices:n,ai:{...X.getState().ai,defaultModel:a,providers:t}})}},j6=cce;ro();dt();Jr();Ie();function uce(r,e){return r.find(t=>t.models.some(n=>n.name===e))}var dce={description:"Pin AI commands' models to the provider they currently resolve to, and give every provider a stable id.",migrate:async r=>{let e=X.getState(),t=Ve(e.ai.providers??[]),n=Ve(e.choices??[]);iC(t),jT(n,t,(s,a)=>{I.logMessage(`Pinned AI command "${s.name}"'s model to ${a.providerId}/${a.name}.`)});let i,o=e.ai.defaultModel;if(e.ai.defaultModelRef&&e.ai.defaultModelRef.name===o)i=e.ai.defaultModelRef;else if(o&&o!=="Ask me"){let s=uce(t,o);s?.id&&(i={providerId:s.id,name:o},I.logMessage(`Pinned the default model to ${s.id}/${o}.`))}X.setState({choices:n,ai:{...X.getState().ai,providers:t,...i?{defaultModelRef:i}:{}}})}},G6=dce;dt();var E$={useQuickAddTemplateFolder:I6,incrementFileNameSettingMoveToDefaultBehavior:P6,consolidateFileExistsBehavior:ZS,repairTemplateFileExistsBehavior:O6,mutualExclusionInsertAfterAndWriteToBottomOfFile:N6,setVersionAfterUpdateModalRelease:L6,addDefaultAIProviders:V6,removeMacroIndirection:B6,migrateFileOpeningSettings:q6,backfillFileOpeningDefaults:U6,setProviderModelDiscoveryMode:H6,migrateProviderApiKeysToSecretStorage:z6,migrateToMultipleTemplateFolders:W6,refreshStaleDefaultModelSeeds:j6,pinAiModelRefs:G6};async function pce(r){let e=Object.keys(E$).filter(t=>!r.settings.migrations[t]);if(e.length===0){I.logMessage("No migrations to run.");return}X.replaceState(Ve(r.settings));for(let t of e){I.logMessage(`Running migration ${t}: ${E$[t].description}`);let n=Ve(r.settings),i=X.getState();try{let o=await E$[t].migrate(r);X.getState()!==i&&(r.settings=Ve(X.getState()));let s=o?.complete===!1;s||(r.settings.migrations[t]=!0),X.replaceState(Ve(r.settings)),I.logMessage(s?`Migration ${t} incomplete; will retry on a later launch.`:`Migration ${t} successful.`)}catch(o){I.logError(`Migration '${t}' was unsuccessful. Please create an issue with the following error message:
${o}
QuickAdd will now revert to backup.`),r.settings=n,X.replaceState(Ve(r.settings))}}r.saveSettings()}var Y6=pce;dt();var Na=require("obsidian");Ie();async function fce(r,e,t){let n=await(0,Na.requestUrl)({url:`https://api.github.com/repos/${r}/${e}/releases`,throw:!1}),i=n.json;if(n.status>=400||!Array.isArray(i)){let a=typeof i=="object"&&i!==null&&"message"in i&&typeof i.message=="string"?i.message:"Unknown error";throw new Error(`Failed to fetch releases: ${a}`)}let o=i,s=o.findIndex(a=>a.tag_name===t);if(s===-1)throw new Error(`Could not find release with tag ${t}`);return o.slice(0,s).filter(a=>!a.draft&&!a.prerelease)}var T$=/^https:\/\/github\.com\/user-attachments\/assets\/[A-Za-z0-9-]+$/,K6=/^\[!\[[^\]]*\]\(([^)\s"]+)\)\]\((https:\/\/github\.com\/user-attachments\/assets\/[A-Za-z0-9-]+)\)$/,mce=/^<!--\s*poster:\s*(https:\/\/[^\s"'>]+)\s*-->$/;function hce(r,e){let t=e?` poster="${e}"`:"";return`<video controls preload="metadata" playsinline style="width: 100%; border-radius: 8px;" src="${r}"${t}></video>`}function gce(r){let e=r.split(`
`),t=new Set;for(let s of e){let a=s.trim();T$.test(a)&&t.add(a)}let n=new Map;for(let s of e){let a=s.trim().match(K6);a&&t.has(a[2])&&n.set(a[2],a[1])}let i=new Set;for(let s=0;s<e.length;s++)if(T$.test(e[s].trim()))for(let a of[1,-1]){let l=s+a;for(;l>=0&&l<e.length&&e[l].trim()==="";)l+=a;let c=l>=0&&l<e.length?e[l].trim().match(mce):null;if(c){n.set(e[s].trim(),c[1]),i.add(l);break}}let o=[];for(let s=0;s<e.length;s++){let a=e[s],l=a.trim();if(i.has(s))continue;let c=l.match(K6);if(!(c&&t.has(c[2]))){if(T$.test(l)){o.push(hce(l,n.get(l)));continue}o.push(a)}}return o.join(`
`)}function vce(r,e=1){let t=r.split(`
`);for(let n=0;n<t.length;n++)t[n].startsWith("#")&&(t[n]="#".repeat(e)+t[n]);return t.join(`
`)}var t_=class extends Na.Modal{constructor(t,n){super(t);this.markdownComponent=new Na.Component;this.isClosed=!1;this.previousVersion=n,this.releaseNotesPromise=fce("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=>{I.logError(`Failed to fetch release notes: ${i}`)})}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h1",{text:"Fetching release notes..."}),this.addCloseFooter()}addCloseFooter(){let t=this.contentEl.createDiv("quickadd-update-modal-footer");new Na.ButtonComponent(t).setButtonText("Done").setCta().onClick(()=>this.close())}onClose(){let{contentEl:t}=this;this.isClosed=!0,this.markdownComponent.unload(),t.empty()}display(){let{contentEl:t}=this;t.empty(),t.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=t.createDiv("quickadd-update-modal"),a=this.releases.map(d=>gce(d.body??"")).join(`
---
`),l=`And now, here is everything new in QuickAdd since your last update (v${this.previousVersion}):`,u=`${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}
---
${vce(a)}`;this.markdownComponent.load(),Na.MarkdownRenderer.render(this.app,u,s,this.app.vault.getRoot().path,this.markdownComponent),this.addCloseFooter()}};Lk();Jr();Jr();function ui(r,e){if(Object.is(r,e))return!0;if(r===null||e===null)return r===e;if(typeof r!=typeof e)return!1;if(Array.isArray(r)||Array.isArray(e))return!Array.isArray(r)||!Array.isArray(e)||r.length!==e.length?!1:r.every((t,n)=>ui(t,e[n]));if(typeof r=="object"&&typeof e=="object"){let t=r,n=e,i=Object.keys(t),o=Object.keys(n);return i.length!==o.length?!1:i.every(s=>Object.prototype.hasOwnProperty.call(n,s)&&ui(t[s],n[s]))}return!1}function ku(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)&&Object.getPrototypeOf(r)===Object.prototype}function yce(r){return ku(r)&&typeof r.name=="string"&&Array.isArray(r.models)}function bce(r){return ku(r)&&typeof r.name=="string"&&typeof r.maxTokens=="number"&&!Array.isArray(r.models)}function wce(r){if(typeof r.id=="string"&&r.id.trim().length>0)return`id:${r.id.trim().toLowerCase()}`;let e=String(r.name??"").trim().toLowerCase(),t=String(r.endpoint??"").trim().toLowerCase().replace(/\/+$/,"");return`name:${e}\0${t}`}function Cce(r){return String(r.name??"").trim().toLowerCase()}function Q6(r,e){let t=new Map;for(let n of r){if(!ku(n))continue;let i=e(n);!i||i==="id:"||i==="name:\0"||t.has(i)||t.set(i,n)}return t}function xce(r,e,t,n,i){let o=Q6(r??[],n),s=Q6(t,n),a=[],l=new Set;for(let c of e){if(!ku(c)){a.push(Ve(c));continue}let u=n(c);if(l.has(u))continue;l.add(u);let d=o.get(u),p=s.get(u);if(!s.has(u)){(!o.has(u)||!ui(c,d))&&a.push(Ve(c));continue}a.push(qh(d,c,p,i))}for(let c of t){if(!ku(c))continue;let u=n(c);l.has(u)||(l.add(u),o.has(u)||a.push(Ve(c)))}return a}function qh(r,e,t,n=[]){if(ui(e,t))return Ve(e);if(ui(e,r))return Ve(t);if(ui(t,r))return Ve(e);if(ku(r)&&ku(e)&&ku(t)){let a=new Set([...Object.keys(r),...Object.keys(e),...Object.keys(t)]),l={};for(let c of a)l[c]=qh(r[c],e[c],t[c],[...n,c]);return l}let i=Array.isArray(r)?r:void 0,o=Array.isArray(e)?e:void 0,s=Array.isArray(t)?t:void 0;if(o&&s){let a=n[n.length-1],l=[...o,...s,...i??[]],c=a==="providers"&&l.every(yce)?wce:a==="models"&&l.every(bce)?Cce:void 0;if(c)return xce(i,o,s,c,n)}return Ve(e)}function Ece(r,e){return!ui(r,e)}function Tce(r,e,t){return r==null||t==null?{toWrite:e,didMerge:!1}:Ece(r,t)?{toWrite:qh(r,e,t),didMerge:!0}:{toWrite:e,didMerge:!1}}function X6(r){let e=r.local,{toWrite:t,didMerge:n}=Tce(r.base,e,r.disk);ui(r.currentStore,e)||(t=qh(e,r.currentStore,t),e=r.currentStore,n=!0);let i=n&&ui(r.currentStore,e)&&!ui(t,r.currentStore);return{toWrite:t,didMerge:n,local:e,shouldReplaceStore:i}}function Z6(r,e,t){return!ui(r,e)&&ui(e,t)}function k$(r){if(r===!0||r==="true")return!0;if(r===!1||r==="false")return!1}function J6(r,e){if(e.cancelled!==void 0&&typeof e.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(e.cancelled===!0)return null;if(r==="confirm"){let t=e.value;if(k$(t)===void 0)return`A confirm prompt needs a boolean reply, or {"cancelled": true} if the user dismissed it. Got ${S$(t)}.`}return null}function S$(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}ur();Yn();var kce=25e3,Sce=6e4,_ce=3e4,Ace=75e3,Ice=32;function Dce(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r.charCodeAt(n)^e.charCodeAt(n);return t===0}function Fce(r){if(r.origin||r.referer)return!1;let e=(r.host??"").split(":")[0];return e==="127.0.0.1"||e==="localhost"}function Pce(r){try{let e=window.require;return e?e(r):null}catch{return null}}function r_(){let r=window.crypto;if(r?.randomUUID)return r.randomUUID();if(r?.getRandomValues){let e=r.getRandomValues(new Uint8Array(16));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}throw new Error("Interactive prompts require a secure random source (crypto), which is unavailable here.")}var n_="No pending prompt for that requestId",_$="The interactive client disconnected, so the run was ended.",A$=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 e=Pce("http");if(!e)throw new Error("Interactive prompts require desktop Obsidian (Node http is unavailable).");let t=this.generation;return this.startPromise=new Promise((n,i)=>{let o=e.createServer((s,a)=>{this.handle(s,a)});o.on("error",s=>{this.generation===t&&(this.startPromise=null),i(s)}),o.listen(0,"127.0.0.1",()=>{if(this.generation!==t){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>=Ice)throw new Error("Too many active interactive sessions.");let e=r_(),t=r_()+r_(),n={id:e,token:t,queue:[],waiter:null,waiterTimer:null,pending:new Map,finished:!1,aborted:!1,cleanupTimer:null,attached:!1,attachTimer:null,pollWatchdog:null};return n.attachTimer=window.setTimeout(()=>{!n.attached&&!n.finished&&this.finish(n.id,{kind:"error",error:"No client attached to the interactive session."})},_ce),this.sessions.set(e,n),{id:e,token:t}}emitPrompt(e,t){let n=this.sessions.get(e);if(!n)return Promise.reject(new Error("Unknown session"));if(n.finished)return Promise.reject(new ye(_$));if(n.aborted)return Promise.reject(new at(vc));let i=r_();return new Promise((o,s)=>{n.pending.set(i,{resolve:o,reject:s,promptType:t.type}),this.push(n,{kind:"prompt",requestId:i,prompt:t})})}finish(e,t){let n=this.sessions.get(e);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);for(let[,i]of n.pending)i.reject(new ye(_$));n.pending.clear(),this.push(n,t),n.cleanupTimer=window.setTimeout(()=>this.destroySession(n),Sce)}}abortSession(e){let t=this.sessions.get(e);if(!t||t.finished)return null;t.aborted=!0;let n=[...t.pending.values()];t.pending.clear();for(let i of n)i.reject(new at(vc));return t.queue=t.queue.filter(i=>i.kind!=="prompt"),n.length}stop(){this.generation++;for(let e of this.sessions.values()){this.clearSessionTimers(e);for(let[,t]of e.pending)t.reject(new ye("QuickAdd was unloaded during an interactive run."));if(e.waiter){let t=e.waiter;e.waiter=null,t({kind:"error",error:"QuickAdd unloaded"})}}this.sessions.clear(),this.server?.close(),this.server=null,this.port=0,this.startPromise=null}push(e,t){if(e.waiter){let n=e.waiter;e.waiter=null,e.waiterTimer&&(window.clearTimeout(e.waiterTimer),e.waiterTimer=null),n(t)}else e.queue.push(t)}clearSessionTimers(e){for(let t of[e.waiterTimer,e.cleanupTimer,e.attachTimer,e.pollWatchdog])t&&window.clearTimeout(t)}destroySession(e){this.clearSessionTimers(e);for(let[,t]of e.pending)t.reject(new ye(_$));e.pending.clear(),this.sessions.delete(e.id),this.sessions.size===0&&(this.server?.close(),this.server=null,this.port=0,this.startPromise=null)}authed(e,t){return!!e&&!!t&&Dce(e.token,t)}originAllowed(e){return Fce({origin:e.headers.origin,referer:e.headers.referer,host:e.headers.host})}submitReply(e,t,n,i=!1){let o=this.sessions.get(e);if(!o)return!1;let s=o.pending.get(t);return s?(o.pending.delete(t),i===!0?s.promptType==="info"?s.resolve(n):s.reject(new at(vc)):s.resolve(n),!0):!1}pendingPromptType(e,t){return e.pending.get(t)?.promptType}send(e,t,n){let i=JSON.stringify(n);e.writeHead(t,{"content-type":"application/json","cache-control":"no-store"}),e.end(i)}async drainBody(e){let t=0;for await(let n of e)if(t+=n.length,t>1e6)throw new Error("Request body too large")}async readBody(e){let t=[],n=0;for await(let i of e){if(n+=i.length,n>1e6)throw new Error("Request body too large");t.push(i)}return t.length===0?{}:JSON.parse(Buffer.concat(t).toString("utf8"))}async handle(e,t){try{if(!this.originAllowed(e)){this.send(t,403,{ok:!1,error:"Forbidden"});return}let n=new URL(e.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(t,404,{ok:!1,error:"Unknown session or token"});return}if(e.method==="GET"&&n.pathname==="/poll"){this.handlePoll(s,t);return}if(e.method==="POST"&&n.pathname==="/abort"){await this.drainBody(e);let a=this.abortSession(s.id);if(a===null){this.send(t,409,{ok:!1,error:"The interactive session has already ended"});return}this.send(t,200,{ok:!0,interrupted:a});return}if(e.method==="POST"&&n.pathname==="/reply"){let a=await this.readBody(e),l=this.submitWireReply(s.id,a);l.ok?this.send(t,200,{ok:!0}):this.send(t,l.status,{ok:!1,error:l.error});return}this.send(t,404,{ok:!1,error:"Not found"})}catch(n){this.send(t,400,{ok:!1,error:n instanceof Error?n.message:String(n)})}}handlePoll(e,t){e.attached||(e.attached=!0,e.attachTimer&&(window.clearTimeout(e.attachTimer),e.attachTimer=null)),e.pollWatchdog&&window.clearTimeout(e.pollWatchdog),e.pollWatchdog=window.setTimeout(()=>{this.finish(e.id,{kind:"error",error:"Interactive client disconnected."})},Ace);let n=e.queue.shift();if(n){this.send(t,200,n);return}if(e.waiter){this.send(t,200,{kind:"idle"});return}let i=o=>this.send(t,200,o);e.waiter=i,e.waiterTimer=window.setTimeout(()=>{e.waiter===i&&(e.waiter=null,e.waiterTimer=null,this.send(t,200,{kind:"idle"}))},kce),t.on("close",()=>{e.waiter===i&&(e.waiterTimer&&window.clearTimeout(e.waiterTimer),e.waiter=null,e.waiterTimer=null)})}submitWireReply(e,t){let n=this.sessions.get(e);if(!n)return{ok:!1,status:409,error:n_};if(!t.requestId)return{ok:!1,status:409,error:n_};let i=this.pendingPromptType(n,t.requestId);if(!i)return{ok:!1,status:409,error:n_};let o=J6(i,t);return o?{ok:!1,status:400,error:o}:this.submitReply(n.id,t.requestId,t.value,t.cancelled)?{ok:!0}:{ok:!1,status:409,error:n_}}},Kl=new A$;function I$(r){if(!r||typeof r!="string")return null;let e=r.split("-")[0]?.split("+")[0]?.trim();if(!e)return null;let t=e.split(".");if(t.length!==3)return null;let n=Number.parseInt(t[0]??"",10),i=Number.parseInt(t[1]??"",10),o=Number.parseInt(t[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}}bt();Ie();bt();Kb();var D$={choice:{value:"<name>",description:"Choice name"},id:{value:"<id>",description:"Choice id"}},F$={value:"<json>",description:"Variables object as JSON"},e4={description:"Allow interactive prompts"},t4={value:"<when>",description:"Day for {{DATE}} (YYYY-MM-DD, last week, last friday, ask, @date:ISO)"},i_={...D$,vars:F$,ui:e4,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:t4},r4={type:{value:"<Template|Capture|Macro|Multi>",description:"Filter by choice type"},commands:{description:"Only include command-enabled choices"}},P$={path:{value:"<vault-path>",description:"Path to a template file in the vault"},vars:F$,ui:e4,date:t4},M$={...D$,vars:F$,fields:{description:"Include full field metadata (options, defaults, widget config)"}},$$={...D$,vars:{value:"<json>",description:"Variables object as JSON (pre-seeded inputs)"}},n4={path:{value:"<vault-path>",description:"Path to a .quickadd.json package file in the vault"},decode:{description:"Inline decoded contents for each bundled file"}},i4=new Set(Object.keys(i_)),O$=new Set(Object.keys(P$)),o4=new Set(Object.keys(M$)),s4=new Set(Object.keys($$));function Su(r){if(r===void 0)return!1;let e=r.toLowerCase();return e==="true"||e==="1"||e==="yes"||e==="on"}function Mce(r){let e;try{e=JSON.parse(r)}catch(t){throw new Error(`Invalid vars JSON: ${t instanceof Error?t.message:String(t)}`)}if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid vars JSON: expected an object");return e}function Uh(r,e){let t={};typeof r.vars=="string"&&Object.assign(t,Mce(r.vars));for(let[n,i]of Object.entries(r)){if(n.startsWith("value-")){let o=n.slice(6);o&&(t[o]=i);continue}e.has(n)||(t[n]=i)}return t}function cw(r,e){if(typeof e.id=="string"&&e.id.trim().length>0)return r.getChoiceById(e.id);if(typeof e.choice=="string"&&e.choice.trim().length>0)return r.getChoiceByName(e.choice);throw new Error("Missing choice selector. Provide either choice=<name> or id=<id>")}function uw(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 a4(r){return{...uw(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 dw(r,e){for(let[t,n]of Object.entries(e))r.variables.set(t,n)}function bp(r){return{id:r.id,name:r.name,type:r.type}}var $ce=new Set(["template","capture","macro","multi"]);function l4(r,e=[]){let t=[];for(let n of Lr(r)){if(!Ue(n))continue;let i=[...e,n.name],o=i.join(" / "),s=n.type==="Multi";t.push({id:n.id,name:n.name,type:n.type,command:n.command,path:o,runnable:!s}),s&&t.push(...l4(et(n),i))}return t}function c4(r,e){let t=typeof e.type=="string"?e.type.trim():"",n=t.toLowerCase();if(n&&!$ce.has(n))return{ok:!1,error:`Invalid type filter '${t}'.`};let i=l4(r.settings.choices).filter(o=>(!n||o.type.toLowerCase()===n)&&(!Su(e.commands)||o.command));return{ok:!0,count:i.length,choices:i}}async function u4(r,e){let t=cw(r,e);if(t.type==="Multi")return{ok:!1,error:"Multi choices are interactive and cannot be checked via CLI.",choice:bp(t)};let n=Uh(e,o4),i=new Hr(r.app,r);dw(i,n);let o=await $a(r.app,r,i,t),s=Hl(o,i.variables),a=Su(e.fields)?a4:uw;return{ok:s.length===0,choice:bp(t),requiredInputCount:o.length,missingInputCount:s.length,missing:s.map(a),missingFlags:s.map(l=>`value-${l.id}=<value>`),...t.type==="Macro"?{deferred:Wj(r,t,i.variables.get("value"))}:{}}}async function d4(r,e){let t=typeof e.path=="string"?e.path.trim():"";if(!t)return{ok:!1,error:"Missing package path. Provide path=<vault-path>."};let{pkg:n}=await YH(r.app,t),i=await XT(r.app,r.settings.choices,n),o={ok:!0,preview:i};return Su(e.decode)&&(o.contents=i.files.map(s=>({path:s.originalPath,...QT(n,s.originalPath)}))),o}Xe();Zd();var pw="\0qa-idx:";function p4(r,e){let t=String(r);if(t.startsWith(pw)){let n=Number(t.slice(pw.length));if(Number.isInteger(n)&&n>=0&&n<e.length)return e[n]}return t}var o_=class{constructor(e,t=Kl){this.sessionId=e;this.server=t}async suggester(e,t,n,i=!1){let o=typeof e=="function"?t.map((l,c,u)=>String(e(l,c,u))):e.map(l=>String(l)),s=t.map((l,c)=>({title:o[c]??String(l),value:`${pw}${c}`})),a=await this.server.emitPrompt(this.sessionId,{type:"suggester",placeholder:n,allowCustomInput:i,items:s});return a==null?"":p4(a,t)}async suggesterMulti(e,t,n){let i=t.map((a,l)=>({title:e[l]??String(a),value:`${pw}${l}`})),o=[];for(let a of n?.preselected??[]){let l=t.indexOf(a);if(l>=0)o.push(`${pw}${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=>p4(a,t)):[]}async inputPrompt(e,t,n){return this.textPrompt(e,t,n,!1)}async wideInputPrompt(e,t,n){return this.textPrompt(e,t,n,!0)}async textPrompt(e,t,n,i){let o=await this.server.emitPrompt(this.sessionId,{type:"input",header:e,placeholder:t,defaultValue:n,multiline:i});return o==null?"":String(o)}async datePrompt(e,t){let n=await this.server.emitPrompt(this.sessionId,{type:"date",header:e,placeholder:t?.placeholder,defaultValue:t?.defaultValue,dateFormat:t?.dateFormat,withTime:t?.withTime}),i=String(n??"");if(!i)return"";let o=i.startsWith("@date:")?i.slice(6):i,s=t?.dateFormat;return(s?Us(o,s):null)??o}async yesNoPrompt(e,t){let n=await this.server.emitPrompt(this.sessionId,{type:"confirm",header:e,text:t}),i=k$(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 ${S$(n)}.`)}async checkboxPrompt(e,t,n){let i=new Set(t??[]),o=await this.server.emitPrompt(this.sessionId,{type:"checkbox",header:n,items:e.map(s=>({title:String(s),value:String(s),checked:i.has(s)}))});return Array.isArray(o)?o.map(s=>String(s)):[]}async infoDialog(e,t){await this.server.emitPrompt(this.sessionId,{type:"info",header:e,text:Array.isArray(t)?t:[t]})}async requestInputs(e){let t=e.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})),n=await this.server.emitPrompt(this.sessionId,{type:"form",fields:t});if(!n||typeof n!="object")return{};let i=new Set(e.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}};Kb();ht();xh();async function R$(r,e,t){if(t&&(e.type==="Template"||e.type==="Capture")&&typeof r.executeWithOutcome=="function"){let i=await r.executeWithOutcome(e);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."}}}await r.execute(e);let n=r.consumeAbortSignal?.();return n?{ok:!1,aborted:!0,error:n.message||"Choice execution aborted"}:{ok:!0,verified:!1,effect:"unknown"}}async function f4(r,e,t,n,i){let o=Date.now(),s=bp(t);if(t.type==="Multi")return{ok:!1,error:"Multi choices are interactive and cannot be run via CLI.",choice:s};let a=new Hr(r.app,r);if(dw(a,Uh(e,n)),!Ch(a,e.date))return{ok:!1,error:`Could not parse date origin '${e.date}'.`,choice:s};if(a.interactive=Su(e.ui),!a.interactive){let c=await $a(r.app,r,a,t,{preloadedUserScripts:a.preloadedUserScripts}),u=Hl(c,a.variables);if(u.length)return{ok:!1,error:"Missing required inputs for non-interactive CLI run.",choice:s,missing:u.map(uw),missingFlags:u.map(({id:d})=>d===rl?"date=<when>":`value-${d}=<value>`)}}return{...await R$(a,t,i),choice:s,durationMs:Date.now()-o}}function N$(r,e){return f4(r,e,cw(r,e),i4,Su(e.verify))}async function m4(r,e){let t=typeof e.path=="string"?e.path.trim():"";if(!t)return{ok:!1,error:"Missing template path. Provide path=<vault-path>."};let n=Vn(r.app,t);if(!n)return{ok:!1,error:`No template file found at '${t}'.`};let i=y$(n.path);if(!Su(e.ui)){let{value:o}=Uh(e,O$);if(o==null||String(o).trim().length===0)return{ok:!1,error:"Missing required inputs for non-interactive CLI run.",choice:bp(i),missing:[{id:"value",label:"New note name",type:"text",source:"collected",optionCount:0}],missingFlags:["value-value=<value>"]}}return f4(r,e,i,O$,!0)}async function h4(r,e){let t=cw(r,e),n=bp(t);if(t.type==="Multi")return{ok:!1,error:"Multi choices cannot be run interactively via CLI.",choice:n};let i=await Kl.ensureStarted(),{id:o,token:s}=Kl.createSession(),a=new Hr(r.app,r);return dw(a,Uh(e,s4)),a.interactive=!0,a.promptProvider=new o_(o),R$(a,t,!0).then(l=>Kl.finish(o,l.ok?{kind:"done",result:{...l,choice:n}}:{kind:"error",error:l.error})).catch(l=>Kl.finish(o,{kind:"error",error:l instanceof Error?l.message:String(l)})),{ok:!0,choice:n,host:"127.0.0.1",port:i,sessionId:o,token:s,capabilities:["abort","outcome-effect"]}}dx();var s_="quickadd:save-clipboard-image",g4={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"}},Oce=Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="),r=>r.charCodeAt(0));function Rce(r){if(r===void 0||r==="")return;let e=r.toLowerCase();if(e==="true"||e==="1"||e==="yes"||e==="on")return!0;if(e==="false"||e==="0"||e==="no"||e==="off")return!1;throw new Error(`Invalid nameAfterNoteTitle: ${r}. Use true or false.`)}async function v4(r,e){try{let t=typeof e.sourcePath=="string"?e.sourcePath:"",n=Rce(typeof e.nameAfterNoteTitle=="string"?e.nameAfterNoteTitle:void 0),i=await cx(r.app,Oce.buffer,"image/png",t,n===void 0?void 0:{nameAfterNoteTitle:n});return JSON.stringify({ok:!0,command:s_,path:i.path,name:i.name,sourcePath:t||"",nameAfterNoteTitle:n??r.settings.namePastedImagesAfterNoteTitle})}catch(t){return JSON.stringify({ok:!1,command:s_,error:t instanceof Error?t.message:String(t)})}}var _u={runDefault:"quickadd",run:"quickadd:run",runTemplate:"quickadd:run-template",list:"quickadd:list",check:"quickadd:check",preview:"quickadd:package-preview",interactive:"quickadd:interactive",saveClipboardImage:s_};function y4(r){let e=r;if(typeof e.registerCliHandler!="function")return I.logMessage("Skipping QuickAdd CLI handler registration: registerCliHandler is unavailable."),!1;let t=(n,i,o,s)=>e.registerCliHandler.call(e,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 t(_u.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)",i_,n=>N$(r,n)),t(_u.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)",i_,n=>N$(r,n)),t(_u.runTemplate,"Create a new note from a template file (no Template choice required)",P$,n=>m4(r,n)),t(_u.list,"List QuickAdd choices",r4,n=>c4(r,n)),t(_u.check,"Check missing inputs for a QuickAdd choice",M$,n=>u4(r,n)),t(_u.preview,"Preview a QuickAdd package before importing (files + capabilities)",n4,n=>d4(r,n)),t(_u.interactive,"Run a choice interactively: forwards its runtime prompts to the caller over a local server (returns host/port/sessionId/token to attach)",$$,n=>h4(r,n)),e.registerCliHandler.call(e,_u.saveClipboardImage,"Save a 1x1 PNG as a vault attachment using QuickAdd clipboard-image naming",g4,n=>v4(r,n)),I.logMessage("Registered QuickAdd CLI handlers."),!0}var Ql={run:"Run",runTemplateFromFolder:"New note from template",applyTemplate:"Apply template to active note",reloadDev:"Reload (dev)",openSettings:"Open settings",resumePrompt:"Return to prompt"};gx();hx();_s();Ie();xt();KM();xh();var Nce=new Set(["shortcuts:","obsidian:"]);function a_(r){return typeof r=="string"&&r.length>0?r:void 0}function b4(r){let e=a_(r["x-success"]),t=a_(r["x-error"]),n=a_(r["x-cancel"]);if(e||t||n)return{success:e,error:t,cancel:n,any:!0};let i=a_(r["x-callback-url"]);return i?{success:i,cancel:i,any:!0}:{any:!1}}function w4(r){return[r.success,r.error,r.cancel].filter(e=>typeof e=="string"&&e.length>0)}function L$(r){try{let e=new URL(r).protocol.toLowerCase();return Nce.has(e)}catch{return!1}}function C4(r,e){let t=new URL(r);for(let[n,i]of Object.entries(e))t.searchParams.set(n,i);return t.toString()}function x4(r,e){return"obsidian://open?vault="+encodeURIComponent(r)+"&file="+encodeURIComponent(e)}function E4(r,e,t){r.registerObsidianProtocolHandler("quickadd",async c=>{let u=c,d=r.settings.enableUriCallbacks?b4(u):{any:!1};if(!d.any){await n(u);return}let p=w4(d).filter(v=>!L$(v));if(p.length>0){I.logWarning(`QuickAdd URI: ignoring disallowed callback URL(s): ${p.join(", ")}`),d.error&&L$(d.error)&&l(d.error,{status:"error",errorCode:"bad-callback-url"});return}if(!u.choice){I.logWarning("URI was executed without a `choice` parameter."),s(d,"choice-not-found");return}let f=e(u.choice);if(!f){I.logWarning(`URI could not find any choice named '${u.choice}'`),s(d,"choice-not-found");return}if(t(u.choice),f.type!=="Template"&&f.type!=="Capture"){I.logWarning(`QuickAdd URI x-callback supports Template and Capture choices only ('${f.name}' is ${f.type}). A URI with x-* callback params cannot run a ${f.type} choice while "Enable URI callbacks" is on; remove the x-* params to run it on the legacy path.`),s(d,"unsupported-choice-type");return}let m=new Hr(r.app,r);if(!i(m,u)){I.logWarning(`QuickAdd URI: could not parse date origin '${u.date}'.`),s(d,"execution-failed");return}let g=await m.executeWithOutcome(f);switch(g.status){case"success":o(d,g.file,g.effect);break;case"cancelled":g.cancelKind==="user"?a(d):s(d,"execution-aborted");break;case"error":s(d,"execution-failed");break}});async function n(c){if(!c.choice){I.logWarning("URI was executed without a `choice` parameter.");return}let u=e(c.choice);if(!u){Ze(new Error(`URI could not find any choice named '${c.choice}'`),"URI handler error");return}t(c.choice);let d=new Hr(r.app,r);if(!i(d,c)){Ze(new Error(`Could not parse date origin '${c.date}'`),"URI handler error");return}try{await d.execute(u)}catch(p){ad(p,`Could not run "${u.name}"`)}}function i(c,u){return Object.entries(u).filter(([d])=>d.startsWith("value-")).forEach(([d,p])=>{let f=d.slice(6);f&&typeof p=="string"&&!CS(f)&&c.variables.set(f,p)}),!!Ch(c,u.date)}function o(c,u,d){let p={status:"success",effect:d};u&&(p.path=u.path,p.url=x4(r.app.vault.getName(),u.path)),c.success&&l(c.success,p)}function s(c,u){c.error&&l(c.error,{status:"error",errorCode:u})}function a(c){c.cancel&&l(c.cancel,{status:"cancel"})}function l(c,u){EN(()=>{window.open(C4(c,u))},"QuickAdd URI: failed to open callback URL")}}var T4=require("obsidian");SM();gx();function k4(r){r.addCommand({id:"runQuickAdd",name:Ql.run,callback:()=>{KS(r)}}),r.addCommand({id:"resumePrompt",name:Ql.resumePrompt,checkCallback:e=>yl.isPeeking()?(e||yl.getActive()?.resume(),!0):!1}),r.addCommand({id:"runTemplateFromFolder",name:Ql.runTemplateFromFolder,callback:()=>{YS(r.app,r,{choiceExecutor:new Hr(r.app,r)})}}),r.addCommand({id:"applyTemplateToActiveFile",name:Ql.applyTemplate,checkCallback:e=>{let t=r.app.workspace.getActiveFile(),n=t?.extension==="md";if(e)return n;n&&qb(r.app,r,{file:t,choiceExecutor:new Hr(r.app,r)})}}),r.registerEvent(r.app.workspace.on("file-menu",(e,t)=>{t instanceof T4.TFile&&t.extension==="md"&&e.addItem(n=>n.setTitle(`QuickAdd: ${Ql.applyTemplate}`).setIcon("file-plus").onClick(()=>{qb(r.app,r,{file:t,choiceExecutor:new Hr(r.app,r)})}))})),r.addCommand({id:"reloadQuickAdd",name:Ql.reloadDev,checkCallback:e=>{if(e)return r.settings.devMode;let t=r.manifest.id,n=r.app.plugins;n.disablePlugin(t).then(()=>n.enablePlugin(t))}})}var Lce=1e3,l_=class extends c_.Plugin{constructor(){super(...arguments);this.lastPersistedSettings=null;this.suppressSettingsSave=!1;this.persistChain=Promise.resolve();this.requestSave=(0,c_.debounce)(()=>{(async()=>await this.persistSettings())()},Lce)}get api(){return Mh.GetApi(this.app,this,new Hr(this.app,this))}ingestImagesIntoActivePrompt(t){return Q1(t)}async onload(){I.logMessage("Loading QuickAdd"),S1(this),await this.loadSettings(),X.replaceState(this.settings),this.unsubscribeSettingsStore=X.subscribe(o=>{this.settings=o,this.suppressSettingsSave||this.requestSave()}),k4(this);let t=Vl.getInstance();t.startAutomaticCleanup(o=>this.registerInterval(o)),t.registerInvalidationListeners(this.app,o=>this.registerEvent(o)),this.addCommand({id:"openQuickAddSettings",name:Ql.openSettings,callback:()=>{Zm(this.app,this.manifest.id)}}),E4(this,o=>this.getChoice("name",o),o=>this.warnIfChoiceNameAmbiguous(o)),I.register(new lb).register(new nk(this)),hz(this),this.settings.enableRibbonIcon&&this.addRibbonIcon("file-plus","QuickAdd",()=>{KS(this)}),this.addSettingTab(new rk(this.app,this)),this.addCommandsForChoices(this.settings.choices);try{await Y6(this)}catch(o){Ze(o,"QuickAdd could not run its settings migrations")}let n=()=>{try{y4(this)}catch(o){Ze(o,"QuickAdd could not register its CLI handlers")}};this.app.workspace.layoutReady?n():this.app.workspace.onLayoutReady(n);let i=async()=>{try{await new AS(this.app,this,this.settings.choices,new Hr(this.app,this)).run()}catch(o){Ze(o,"QuickAdd could not run its startup macros")}};this.app.workspace.layoutReady?i():this.app.workspace.onLayoutReady(i),this.app.workspace.onLayoutReady(()=>{window.setTimeout(()=>{tH(this.app)},5e3)}),this.announceUpdate()}onunload(){I.logMessage("Unloading QuickAdd"),this.requestSave.run(),this.unsubscribeSettingsStore?.call(this),_g.loggers.forEach(n=>{n instanceof lb&&n.clearErrorLog()}),Vl.getInstance().destroy(),Kl.stop(),yl.getActive()?.cancel()}normalizeLoadedSettings(t){let n=Object.assign({},lC,t??{});return typeof n.announceUpdates=="boolean"&&(n.announceUpdates=n.announceUpdates?"all":"none"),Array.isArray(n.choices)&&(n.choices=n1(n.choices)),n}async loadSettings(){let t=await this.loadData(),n=this.normalizeLoadedSettings(t);this.settings=n,this.lastPersistedSettings=Ve(n)}async saveSettings(){this.requestSave.cancel(),await this.persistSettings()}persistSettings(){let t=async()=>{let n=this.lastPersistedSettings,i=async()=>n?this.normalizeLoadedSettings(await this.loadData()):null,o=await i(),s=d=>{let p=Ve(this.settings);return X6({base:n,disk:d,local:p,currentStore:this.settings})},a=d=>{if(d.shouldReplaceStore&&ui(this.settings,d.local)){this.suppressSettingsSave=!0;try{X.replaceState(d.toWrite),this.settings=d.toWrite}finally{this.suppressSettingsSave=!1}}},l=s(o);if(l.didMerge&&I.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 d=await i();d&&(!o||!ui(d,o))&&(I.logMessage("[Settings] data.json changed again before save; re-merging with the fresher on-disk snapshot."),o=d,l=s(o),a(l))}let c=Ve(this.settings),u=l.toWrite;if(ui(c,l.local)||(u=qh(l.local,c,l.toWrite)),Z6(u,this.settings,c)){this.suppressSettingsSave=!0;try{X.replaceState(u),this.settings=u}finally{this.suppressSettingsSave=!1}}await this.saveData(u),this.lastPersistedSettings=Ve(u)};return this.persistChain=this.persistChain.then(t,t),this.persistChain}addCommandsForChoices(t){for(let n of Lr(t))if(Ue(n))try{this.addCommandForChoice(n)}catch(i){Ze(i,"Could not add a command for a QuickAdd choice")}}addCommandForChoice(t){if(t.type==="Multi"&&this.addCommandsForChoices(et(t)),t.command){let n=t.id;this.addCommand({id:uE(n),name:t.name,icon:xd(t),callback:()=>this.runRegisteredChoice(n,t.name)}),qB({origin:t.dateOrigin,enabled:t.pickDayCommand})&&this.addCommand({id:BD(n),name:qD(t.name),icon:xd(t),callback:()=>this.runRegisteredChoice(n,t.name,!0)})}}async runRegisteredChoice(t,n,i=!1){let o;try{o=this.getChoiceById(t);let s=new Hr(this.app,this);s.pickDate=i,await s.execute(o)}catch(s){ad(s,`Could not run "${o?.name??n}"`)}}getChoiceById(t){let n=this.getChoice("id",t);if(!n)throw new Error(`Choice ${t} not found`);return n}getChoiceByName(t){let n=this.getChoice("name",t);if(!n)throw new Error(`Choice ${t} not found`);return n}getChoice(t,n,i=this.settings.choices){for(let o of Lr(i))if(Ue(o)){if(o[t]===n)return o;if(o.type==="Multi"){let s=this.getChoice(t,n,et(o));if(s)return s}}return null}countChoicesByName(t,n=this.settings.choices){let i=0;for(let o of Lr(n))Ue(o)&&(o.name===t&&i++,o.type==="Multi"&&(i+=this.countChoicesByName(t,et(o))));return i}warnIfChoiceNameAmbiguous(t){let n=this.countChoicesByName(t);n>1&&I.logWarning(`QuickAdd URI: ${n} choices are named '${t}'. Ran the first match \u2014 rename choices to keep names unique so URIs target the right one.`)}removeCommandForChoice(t,n){if(n?.recursive&&t.type==="Multi")for(let i of et(t))Ue(i)&&this.removeCommandForChoice(i,n);DC(this.app,`quickadd:${uE(t.id)}`),DC(this.app,`quickadd:${BD(t.id)}`)}getTemplateFiles(){let t=ri(this.settings.templateFolderPaths);return this.app.vault.getFiles().filter(n=>kC(n.path)).filter(n=>HA(n.path,t))}announceUpdate(){let t=(l,c)=>{let u=I$(l),d=I$(c);return!u||!d?!0:u.major!==d.major?u.major>d.major:u.minor>d.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"&&!t(n,i))&&(s=!1),this.settings.version=n,this.saveSettings(),!s)return;new t_(this.app,i).open()}};
/* nosourcemap */