Files
obsidian-notif/main.js
T
2026-06-27 15:05:31 +08:00

10 lines
24 KiB
JavaScript

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
*/
var V=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var tt=(o,e)=>{for(var t in e)V(o,t,{get:e[t],enumerable:!0})},et=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Q(e))!Z.call(o,s)&&s!==t&&V(o,s,{get:()=>e[s],enumerable:!(n=X(e,s))||n.enumerable});return o};var it=o=>et(V({},"__esModule",{value:!0}),o);var ot={};tt(ot,{default:()=>M});module.exports=it(ot);var m=require("obsidian");var b=require("obsidian");var nt=new Map([["sunday",0],["monday",1],["tuesday",2],["wednesday",3],["thursday",4],["friday",5],["saturday",6]]);function D(o,e=new Date){var a,c,p,w,y,T;let t=o.trim();if(!t)return null;let n=t.match(/^\+(\d+)\s*(m|min|minute|minutes|h|hour|hours|d|day|days)$/i);if(n){let h=Number(n[1]),g=n[2].toLowerCase(),P=g.startsWith("m")?h*6e4:g.startsWith("h")?h*36e5:h*864e5;return new Date(e.getTime()+P)}let s=t.match(/^tomorrow(?:\s+(\d{1,2})(?::(\d{2}))?)?$/i);if(s){let h=new Date(e);return h.setDate(h.getDate()+1),h.setHours(Number((a=s[1])!=null?a:9),Number((c=s[2])!=null?c:0),0,0),h}let i=t.match(/^next\s+(sunday|monday|tuesday|wednesday|thursday|friday|saturday)(?:\s+(\d{1,2})(?::(\d{2}))?)?$/i);if(i){let h=nt.get(i[1].toLowerCase());if(h===void 0)return null;let g=new Date(e),P=h-g.getDay()+7||7;return g.setDate(g.getDate()+P),g.setHours(Number((p=i[2])!=null?p:9),Number((w=i[3])!=null?w:0),0,0),g}let r=t.match(/^(\d{4}-\d{2}-\d{2})(?:[ T](\d{1,2})(?::(\d{2}))?)?$/);if(r){let h=(y=r[2])!=null?y:"9",g=(T=r[3])!=null?T:"0",P=new Date(`${r[1]}T${h.padStart(2,"0")}:${g.padStart(2,"0")}:00`);return Number.isNaN(P.getTime())?null:P}let d=new Date(t);return Number.isNaN(d.getTime())?null:d}function j(o){let e=new Date(o);return Number.isNaN(e.getTime())?o:e.toLocaleString()}var v=class extends b.Modal{constructor(t,n,s=!1){super(t);this.store=n;this.showCompleted=s}onOpen(){this.render()}render(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:this.showCompleted?"All reminders":"Active reminders"}),new b.Setting(t).addButton(i=>i.setButtonText(this.showCompleted?"Show active only":"Show all").onClick(()=>{this.showCompleted=!this.showCompleted,this.render()}));let n=this.showCompleted?this.store.getAll():this.store.getAll().filter(i=>!i.completed&&i.status!=="cancelled"&&i.status!=="sent"&&i.status!=="done");if(!n.length){t.createEl("p",{text:this.showCompleted?"No reminders.":"No active reminders."});return}let s=t.createDiv({cls:"reminder-notifier-list"});for(let i of n){let r=s.createDiv({cls:"reminder-notifier-item"});r.createDiv({cls:"reminder-notifier-item-title",text:i.title}),r.createDiv({cls:"reminder-notifier-item-meta",text:`${j(i.dueAt)} - ${i.status} - ${i.channels.join(", ")||"all enabled"}`}),i.sourceFile&&r.createDiv({cls:"reminder-notifier-item-meta",text:`${i.sourceFile}${i.sourceLine?`:${i.sourceLine}`:""}`}),i.lastError&&r.createDiv({cls:"reminder-notifier-item-meta",text:`Last error: ${i.lastError}`});let d=r.createDiv({cls:"reminder-notifier-actions"});new b.Setting(d).addButton(a=>a.setButtonText("Snooze 15m").onClick(async()=>{await this.store.snooze(i.id,15),this.render()})).addButton(a=>a.setButtonText("Done").onClick(async()=>{await this.store.complete(i.id),this.render()})).addButton(a=>a.setButtonText("Delete").onClick(async()=>{await this.store.remove(i.id),this.render()}))}}};var f=require("obsidian"),S=class extends f.Modal{constructor(t,n,s,i=""){super(t);this.defaultChannels=n;this.onSubmit=s;this.title="";this.body="";this.year="";this.month="";this.day="";this.hour="";this.minute="";this.channels="";let r=new Date(Date.now()+60*60*1e3);this.title=i,this.body=i,this.channels=n.join(", "),this.year=String(r.getFullYear()),this.month=String(r.getMonth()+1).padStart(2,"0"),this.day=String(r.getDate()).padStart(2,"0"),this.hour=String(r.getHours()).padStart(2,"0"),this.minute=String(Math.ceil(r.getMinutes()/5)*5).padStart(2,"0"),this.minute==="60"&&(this.minute="00",this.hour=String((r.getHours()+1)%24).padStart(2,"0"))}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:"Create reminder"}),this.renderReminderRow(t),new f.Setting(t).setName("Details").setDesc("Optional longer message.").addTextArea(n=>{n.setValue(this.body),n.inputEl.rows=3,n.onChange(s=>{this.body=s})}),new f.Setting(t).setName("Channels").setDesc("Comma separated provider IDs or types. Leave empty to use all enabled providers.").addText(n=>n.setValue(this.channels).onChange(s=>{this.channels=s})),new f.Setting(t).addButton(n=>n.setButtonText("Create").setCta().onClick(async()=>{let s=this.getSelectedDate();if(!this.title.trim()||!s){new f.Notice("Title and valid due date are required.");return}await this.onSubmit({title:this.title.trim(),body:this.body.trim(),dueAt:s.toISOString(),channels:this.channels.split(",").map(i=>i.trim()).filter(Boolean)}),this.close()}))}renderReminderRow(t){let n=new f.Setting(t).setName("Reminder").setDesc("Text, date, and time.");n.addText(s=>{s.setPlaceholder("Reminder text"),s.setValue(this.title),s.onChange(i=>{this.title=i,(!this.body||this.body===this.title)&&(this.body=i)})}),n.addDropdown(s=>{for(let i of this.range(new Date().getFullYear(),new Date().getFullYear()+3))s.addOption(String(i),String(i));s.setValue(this.year),s.onChange(i=>{this.year=i,this.ensureValidDay()})}),n.addDropdown(s=>{for(let i of this.range(1,12)){let r=String(i).padStart(2,"0");s.addOption(r,r)}s.setValue(this.month),s.onChange(i=>{this.month=i,this.ensureValidDay()})}),n.addDropdown(s=>{for(let i of this.range(1,31)){let r=String(i).padStart(2,"0");s.addOption(r,r)}s.setValue(this.day),s.onChange(i=>{this.day=i})}),n.addDropdown(s=>{for(let i of this.range(0,23)){let r=String(i).padStart(2,"0");s.addOption(r,r)}s.setValue(this.hour),s.onChange(i=>{this.hour=i})}),n.addDropdown(s=>{for(let i of this.range(0,55,5)){let r=String(i).padStart(2,"0");s.addOption(r,r)}s.setValue(this.minute),s.onChange(i=>{this.minute=i})})}getSelectedDate(){let t=new Date(`${this.year}-${this.month}-${this.day}T${this.hour}:${this.minute}:00`);return Number.isNaN(t.getTime())?null:t}ensureValidDay(){let t=new Date(Number(this.year),Number(this.month),0).getDate();Number(this.day)>t&&(this.day=String(t).padStart(2,"0"))}range(t,n,s=1){let i=[];for(let r=t;r<=n;r+=s)i.push(r);return i}};var L=require("obsidian");var U=/@remind\(([^)]+)\)/gi,W=/(?:\uD83D\uDD14|\[!\s*reminder\s*\])\s*(\d{4}-\d{2}-\d{2}(?:[ T]\d{1,2}(?::\d{2})?)?)/i,R=class{parseMarkdown(e,t){return[...this.parseInline(e,t),...this.parseFrontmatter(e,t),...this.parseReminderBlocks(e,t)]}parseInline(e,t){let n=[];return e.split(/\r?\n/).forEach((i,r)=>{for(let a of i.matchAll(U)){let c=a[1].split(",").map(y=>y.trim()).filter(Boolean),p=D(c[0]);if(!p)continue;let w=i.replace(U,"").replace(/^[-*]\s+\[[ xX]\]\s+/,"").trim();n.push({title:w||"Reminder",body:w,dueAt:p.toISOString(),sourceFile:t,sourceLine:r+1,channels:c.slice(1),priority:this.parsePriority(c)})}let d=i.match(W);if(d){let a=D(d[1]);if(!a)return;let c=i.replace(W,"").replace(/^[-*]\s+\[[ xX]\]\s+/,"").trim();n.push({title:c||"Reminder",body:c,dueAt:a.toISOString(),sourceFile:t,sourceLine:r+1,channels:[],priority:"normal"})}}),n}parseFrontmatter(e,t){let n=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);return n?this.parseYamlLike(n[1],t,1):[]}parseReminderBlocks(e,t){let n=[],s=/```reminder\r?\n([\s\S]*?)```/gi;for(let i of e.matchAll(s)){let r=e.slice(0,i.index).split(/\r?\n/).length;n.push(...this.parseYamlLike(i[1],t,r))}return n}parseYamlLike(e,t,n){return(e.includes("reminders:")?this.parseReminderList(e):[this.parseKeyValueBlock(e)]).flatMap(i=>{var c,p,w,y;let r=(p=(c=i.at)!=null?c:i.date)!=null?p:i.dueAt;if(!r)return[];let d=D(r);if(!d)return[];let a=((y=(w=i.notify)!=null?w:i.channels)!=null?y:"").split(",").map(T=>T.trim()).filter(Boolean);return[{title:i.title||i.message||"Reminder",body:i.message||i.body||i.title||"",dueAt:d.toISOString(),sourceFile:t,sourceLine:n,channels:a,priority:this.normalizePriority(i.priority)}]})}parseReminderList(e){let t=[],n=null;for(let s of e.split(/\r?\n/)){let i=s.match(/^\s*-\s+(\w+):\s*(.+)$/);if(i){n={[i[1]]:i[2].trim()},t.push(n);continue}let r=s.match(/^\s+(\w+):\s*(.+)$/);r&&n&&(n[r[1]]=r[2].trim())}return t}parseKeyValueBlock(e){let t={},n=e.split(/\r?\n/),s=!1,i="";for(let r of n){if(/^\s*reminder:\s*$/.test(r)){s=!0;continue}let d=r.match(/^\s*-\s+(.+)$/);if(d&&i){t[i]=[t[i],d[1].trim()].filter(Boolean).join(",");continue}let a=r.match(/^\s*(\w+):\s*(.*)$/);a&&(s||!r.startsWith(" "))&&(t[a[1]]=a[2].trim(),i=a[1])}return t}parsePriority(e){let t=e.find(n=>/^(low|normal|high)$/i.test(n));return this.normalizePriority(t)}normalizePriority(e){return e==="low"||e==="high"||e==="normal"?e:"normal"}};var k=class{constructor(e,t,n){this.vault=e;this.store=t;this.providers=n;this.timer=null;this.parser=new R}start(){this.stop();let e=Math.max(10,this.store.getSettings().checkIntervalSeconds)*1e3;this.timer=window.setInterval(()=>{this.tick()},e),this.tick()}stop(){this.timer!==null&&(window.clearInterval(this.timer),this.timer=null)}async tick(){for(let e of this.store.getDue())await this.sendReminder(e)}async scanFile(e){let t=await this.vault.read(e),n=this.parser.parseMarkdown(t,e.path);return this.store.addMany(n)}async scanVault(){let e=0,t=this.vault.getMarkdownFiles();for(let n of t)e+=await this.scanFile(n);return e}async sendReminder(e){let t=this.store.getSettings().notificationProviders.filter(i=>i.enabled),n=t.filter(i=>e.channels.includes(i.id)||e.channels.includes(i.type)),s=n.length?n:e.channels.length===0?t:[];if(!s.length){let i=e.channels.length?`Reminder has no matching enabled provider: ${e.title}`:`Reminder has no enabled providers: ${e.title}`;new L.Notice(i),await this.store.markFailed(e.id,i);return}try{for(let i of s){let r=this.providers.get(i.type);if(!r)throw new Error(`Unknown provider: ${i.type}`);await r.send({title:e.title,message:e.body||e.title,sourceFile:e.sourceFile,sourceLine:e.sourceLine,priority:e.priority,dueAt:e.dueAt},i)}await this.store.markSent(e.id)}catch(i){await this.store.markFailed(e.id,i),new L.Notice(`Reminder failed: ${e.title}`)}}};function Y(o){let e=o.join("|"),t=0;for(let n=0;n<e.length;n+=1)t=(t<<5)-t+e.charCodeAt(n)|0;return`rem_${Math.abs(t).toString(36)}`}var N=[{id:"local",type:"local",name:"Local notice",enabled:!0,config:{}},{id:"telegram",type:"telegram",name:"Telegram Bot",enabled:!1,config:{botToken:"123456:ABCDEF_your_bot_token",chatId:"123456789",parseMode:"Markdown"}},{id:"ntfy",type:"ntfy",name:"ntfy.sh",enabled:!1,config:{serverUrl:"https://ntfy.sh",topic:"my-obsidian-reminders",token:"",priority:3,tags:["calendar","obsidian"]}},{id:"discord",type:"discord",name:"Discord Webhook",enabled:!1,config:{webhookUrl:"https://discord.com/api/webhooks/...",username:"Obsidian Reminder"}},{id:"webhook",type:"webhook",name:"Generic Webhook",enabled:!1,config:{method:"POST",url:"https://example.com/reminder",headers:{"Content-Type":"application/json"},bodyTemplate:{title:"{{title}}",message:"{{message}}",dueAt:"{{dueAt}}",sourceFile:"{{sourceFile}}"}}}],rt={defaultChannels:[],scanVaultOnStartup:!0,scanOnFileChange:!0,checkIntervalSeconds:60,afterSend:"mark-sent",reminderSyntax:"@remind(YYYY-MM-DD HH:mm, provider)",notificationProviders:[N[0]]};function B(){return JSON.parse(JSON.stringify(rt))}function J(o){let e=N.find(n=>n.type===o);if(!e)return null;let t=Date.now().toString(36);return{...e,id:`${e.type}-${t}`,config:JSON.parse(JSON.stringify(e.config))}}var A=class{constructor(e){this.plugin=e;this.data={settings:B(),reminders:[]}}async load(){var n,s,i,r;let e=await this.plugin.loadData(),t=B();this.data={settings:{...t,...(n=e==null?void 0:e.settings)!=null?n:{},notificationProviders:(i=(s=e==null?void 0:e.settings)==null?void 0:s.notificationProviders)!=null?i:t.notificationProviders},reminders:(r=e==null?void 0:e.reminders)!=null?r:[]}}async save(){await this.plugin.saveData(this.data)}getSettings(){return this.data.settings}async updateSettings(e){this.data.settings=e,await this.save()}getAll(){return[...this.data.reminders].sort((e,t)=>e.dueAt.localeCompare(t.dueAt))}getDue(e=new Date){return this.data.reminders.filter(t=>(t.status==="pending"||t.status==="snoozed"||t.status==="failed")&&new Date(t.dueAt).getTime()<=e.getTime())}async add(e,t){var r,d,a;let n=new Date().toISOString(),s={id:Y([(r=e.sourceFile)!=null?r:"manual",String((d=e.sourceLine)!=null?d:""),e.title,e.dueAt]),title:e.title,body:e.body,dueAt:e.dueAt,sourceFile:e.sourceFile,sourceLine:e.sourceLine,completed:!1,channels:e.channels.length?e.channels:t,priority:(a=e.priority)!=null?a:"normal",status:"pending",createdAt:n,updatedAt:n},i=this.data.reminders.find(c=>c.id===s.id);return i?(Object.assign(i,{...s,status:i.status,completed:i.completed,createdAt:i.createdAt,updatedAt:n}),await this.save(),i):(this.data.reminders.push(s),await this.save(),s)}async addMany(e){let t=0;for(let n of e)await this.add(n,[]),t+=1;return t}async markSent(e){let t=this.find(e);t&&(t.status=this.data.settings.afterSend==="mark-done"?"done":"sent",t.completed=this.data.settings.afterSend==="mark-done",t.updatedAt=new Date().toISOString(),t.lastError=void 0,await this.save())}async markFailed(e,t){let n=this.find(e);n&&(n.status="failed",n.lastError=t instanceof Error?t.message:String(t),n.updatedAt=new Date().toISOString(),await this.save())}async complete(e){let t=this.find(e);t&&(t.completed=!0,t.status="done",t.updatedAt=new Date().toISOString(),await this.save())}async snooze(e,t){let n=this.find(e);n&&(n.dueAt=new Date(Date.now()+t*6e4).toISOString(),n.status="snoozed",n.updatedAt=new Date().toISOString(),await this.save())}async remove(e){this.data.reminders=this.data.reminders.filter(t=>t.id!==e),await this.save()}find(e){return this.data.reminders.find(t=>t.id===e)}};var l=require("obsidian");var x=class extends l.PluginSettingTab{constructor(t,n){super(t,n);this.plugin=n}display(){let{containerEl:t}=this,n=this.plugin.store.getSettings();t.empty(),t.createEl("h2",{text:"Reminder Notifier"}),new l.Setting(t).setName("Scan vault on startup").addToggle(i=>i.setValue(n.scanVaultOnStartup).onChange(async r=>{n.scanVaultOnStartup=r,await this.plugin.store.updateSettings(n)})),new l.Setting(t).setName("Scan changed notes").addToggle(i=>i.setValue(n.scanOnFileChange).onChange(async r=>{n.scanOnFileChange=r,await this.plugin.store.updateSettings(n)})),new l.Setting(t).setName("Check interval").setDesc("Seconds between reminder checks.").addText(i=>i.setValue(String(n.checkIntervalSeconds)).onChange(async r=>{n.checkIntervalSeconds=Math.max(10,Number(r)||60),await this.plugin.store.updateSettings(n),this.plugin.restartScheduler()})),new l.Setting(t).setName("Default channels").setDesc("Comma separated provider IDs or types. Empty means every enabled provider.").addText(i=>i.setValue(n.defaultChannels.join(", ")).onChange(async r=>{n.defaultChannels=r.split(",").map(d=>d.trim()).filter(Boolean),await this.plugin.store.updateSettings(n)})),new l.Setting(t).setName("After send").addDropdown(i=>i.addOption("mark-sent","Mark as sent").addOption("mark-done","Mark as done").addOption("keep","Keep pending").setValue(n.afterSend).onChange(async r=>{n.afterSend=r,await this.plugin.store.updateSettings(n)})),t.createEl("h3",{text:"Notification providers"});let s=N[0].type;new l.Setting(t).setName("Add from template").addDropdown(i=>{for(let r of N)i.addOption(r.type,r.name);i.onChange(r=>{s=r})}).addButton(i=>i.setButtonText("Add provider").onClick(async()=>{let r=J(s);r&&(n.notificationProviders.push(r),await this.plugin.store.updateSettings(n),this.display())}));for(let i of n.notificationProviders)this.renderProvider(i)}renderProvider(t){let n=this.plugin.store.getSettings(),s=this.containerEl.createDiv({cls:"reminder-notifier-provider"});s.createEl("h4",{text:t.name}),new l.Setting(s).setName("Enabled").addToggle(i=>i.setValue(t.enabled).onChange(async r=>{t.enabled=r,await this.plugin.store.updateSettings(n)})),new l.Setting(s).setName("ID").setDesc("Use this value in @remind(..., provider-id).").addText(i=>i.setValue(t.id).onChange(async r=>{t.id=r.trim(),await this.plugin.store.updateSettings(n)})),new l.Setting(s).setName("Name").addText(i=>i.setValue(t.name).onChange(async r=>{t.name=r,await this.plugin.store.updateSettings(n)})),new l.Setting(s).setName("Config JSON").setDesc("Secrets are stored locally in Obsidian plugin data.").addTextArea(i=>{i.inputEl.addClass("reminder-notifier-json"),i.setValue(JSON.stringify(t.config,null,2)),i.onChange(async r=>{try{t.config=JSON.parse(r),await this.plugin.store.updateSettings(n)}catch(d){}})}),new l.Setting(s).addButton(i=>i.setButtonText("Test notification").onClick(async()=>{try{await this.plugin.testProvider(t),new l.Notice("Test notification sent.")}catch(r){new l.Notice(r instanceof Error?r.message:String(r))}})).addButton(i=>i.setButtonText("Delete").onClick(async()=>{n.notificationProviders=n.notificationProviders.filter(r=>r!==t),await this.plugin.store.updateSettings(n),this.display()}))}};var q=require("obsidian");function C(o,e){var t,n,s,i,r,d;return typeof o=="string"?Object.entries({"{{title}}":e.title,"{{message}}":e.message,"{{body}}":e.message,"{{file}}":(t=e.sourceFile)!=null?t:"","{{sourceFile}}":(n=e.sourceFile)!=null?n:"","{{sourceLine}}":(i=(s=e.sourceLine)==null?void 0:s.toString())!=null?i:"","{{priority}}":(r=e.priority)!=null?r:"normal","{{dueAt}}":e.dueAt,"{{time}}":e.dueAt,"{{url}}":(d=e.url)!=null?d:""}).reduce((a,[c,p])=>a.split(c).join(p),o):Array.isArray(o)?o.map(a=>C(a,e)):o&&typeof o=="object"?Object.fromEntries(Object.entries(o).map(([a,c])=>[a,C(c,e)])):o}function u(o,e=""){return typeof o=="string"?o:e}var O=class{constructor(){this.id="discord";this.name="Discord webhook"}async send(e,t){let n=u(t.config.webhookUrl);if(!n)throw new Error("Discord webhookUrl is required.");await(0,q.requestUrl)({url:n,method:"POST",contentType:"application/json",body:JSON.stringify({username:u(t.config.username,"Obsidian Reminder"),content:`**${e.title}**
${e.message}`}),throw:!0})}async test(e){await this.send({title:"Obsidian Reminder Notifier",message:"Test notification",dueAt:new Date().toISOString()},e)}};var _=require("obsidian"),I=class{constructor(){this.id="local";this.name="Local Obsidian notice"}async send(e){new _.Notice(`${e.title}
${e.message}`,1e4)}async test(e){new _.Notice("Reminder Notifier test notification",5e3)}};var z=require("obsidian");var E=class{constructor(){this.id="ntfy";this.name="ntfy"}async send(e,t){var a;let n=u(t.config.serverUrl,"https://ntfy.sh").replace(/\/$/,""),s=u(t.config.topic);if(!s)throw new Error("ntfy topic is required.");let i={Title:e.title,Priority:String((a=t.config.priority)!=null?a:st(e.priority))},r=u(t.config.token);r&&(i.Authorization=`Bearer ${r}`);let d=t.config.tags;Array.isArray(d)&&(i.Tags=d.join(",")),await(0,z.requestUrl)({url:`${n}/${encodeURIComponent(s)}`,method:"POST",headers:i,body:e.message,throw:!0})}async test(e){await this.send({title:"Obsidian Reminder Notifier",message:"Test notification",dueAt:new Date().toISOString()},e)}};function st(o="normal"){return o==="high"?4:o==="low"?2:3}var H=require("obsidian");var $=class{constructor(){this.id="telegram";this.name="Telegram"}async send(e,t){let n=u(t.config.botToken),s=u(t.config.chatId);if(!n||!s)throw new Error("Telegram botToken and chatId are required.");let i=`*${e.title}*
${e.message}`;await(0,H.requestUrl)({url:`https://api.telegram.org/bot${n}/sendMessage`,method:"POST",contentType:"application/json",body:JSON.stringify({chat_id:s,text:i,parse_mode:u(t.config.parseMode,"Markdown"),disable_web_page_preview:!0}),throw:!0})}async test(e){await this.send({title:"Obsidian Reminder Notifier",message:"Test notification",dueAt:new Date().toISOString()},e)}};var K=require("obsidian");var F=class{constructor(){this.id="webhook";this.name="Generic webhook"}async send(e,t){var d,a;let n=u(t.config.url);if(!n)throw new Error("Webhook URL is required.");let s=u(t.config.method,"POST").toUpperCase();if(!["POST","PUT","PATCH"].includes(s))throw new Error("Webhook method must be POST, PUT, or PATCH.");let i=C((d=t.config.headers)!=null?d:{"Content-Type":"application/json"},e),r=C((a=t.config.bodyTemplate)!=null?a:{title:"{{title}}",message:"{{message}}",dueAt:"{{dueAt}}",sourceFile:"{{sourceFile}}"},e);await(0,K.requestUrl)({url:n,method:s,headers:i,body:typeof r=="string"?r:JSON.stringify(r),throw:!0})}async test(e){await this.send({title:"Obsidian Reminder Notifier",message:"Test notification",dueAt:new Date().toISOString()},e)}};function G(){let o=[new I,new $,new E,new F,new O];return new Map(o.map(e=>[e.id,e]))}var M=class extends m.Plugin{constructor(){super(...arguments);this.providers=G()}async onload(){if(this.store=new A(this),await this.store.load(),this.scheduler=new k(this.app.vault,this.store,this.providers),this.addSettingTab(new x(this.app,this)),this.registerCommands(),this.registerRibbonActions(),this.registerContextMenus(),this.registerFileWatcher(),this.store.getSettings().scanVaultOnStartup){let t=await this.scheduler.scanVault();t>0&&new m.Notice(`Reminder Notifier indexed ${t} reminders.`)}this.scheduler.start()}onunload(){var t;(t=this.scheduler)==null||t.stop()}restartScheduler(){this.scheduler.stop(),this.scheduler.start()}async testProvider(t){let n=this.providers.get(t.type);if(!n)throw new Error(`Unknown provider: ${t.type}`);await n.test(t)}registerCommands(){this.addCommand({id:"create-reminder",name:"Create reminder",callback:()=>{new S(this.app,this.store.getSettings().defaultChannels,async t=>{await this.store.add(t,this.store.getSettings().defaultChannels),new m.Notice("Reminder created.")}).open()}}),this.addCommand({id:"create-reminder-from-selection",name:"Create reminder from selected text",editorCallback:t=>{let n=t.getSelection();new S(this.app,this.store.getSettings().defaultChannels,async s=>{await this.store.add(s,this.store.getSettings().defaultChannels),new m.Notice("Reminder created.")},n).open()}}),this.addCommand({id:"show-active-reminders",name:"Show active reminders",callback:()=>{new v(this.app,this.store,!1).open()}}),this.addCommand({id:"show-all-reminders",name:"Show all reminders",callback:()=>{new v(this.app,this.store,!0).open()}}),this.addCommand({id:"scan-current-note",name:"Scan current note for reminders",checkCallback:t=>{let n=this.app.workspace.getActiveFile();return n?(t||this.scanCurrentFile(n),!0):!1}}),this.addCommand({id:"scan-vault",name:"Scan vault for reminders",callback:async()=>{let t=await this.scheduler.scanVault();new m.Notice(`Indexed ${t} reminders.`)}}),this.addCommand({id:"test-notification-providers",name:"Test notification providers",callback:async()=>{let t=this.store.getSettings().notificationProviders.filter(n=>n.enabled);for(let n of t)await this.testProvider(n);new m.Notice(`Tested ${t.length} providers.`)}})}registerRibbonActions(){this.addRibbonIcon("bell-plus","Create reminder",()=>{new S(this.app,this.store.getSettings().defaultChannels,async t=>{await this.store.add(t,this.store.getSettings().defaultChannels),new m.Notice("Reminder created.")}).open()}),this.addRibbonIcon("list-checks","Show reminders",()=>{new v(this.app,this.store,!0).open()})}registerContextMenus(){this.registerEvent(this.app.workspace.on("editor-menu",(t,n)=>{t.addSeparator(),t.addItem(s=>s.setTitle("Create reminder").setIcon("bell-plus").onClick(()=>{let i=n.getSelection();new S(this.app,this.store.getSettings().defaultChannels,async r=>{await this.store.add(r,this.store.getSettings().defaultChannels),new m.Notice("Reminder created.")},i).open()})),t.addItem(s=>s.setTitle("Show reminders").setIcon("list-checks").onClick(()=>{new v(this.app,this.store,!0).open()}))}))}registerFileWatcher(){this.registerEvent(this.app.vault.on("modify",t=>{!this.store.getSettings().scanOnFileChange||!(t instanceof m.TFile)||t.extension!=="md"||this.scheduler.scanFile(t)}))}async scanCurrentFile(t){var r;let n=this.app.workspace.getActiveViewOfType(m.MarkdownView),s=(r=n==null?void 0:n.file)!=null?r:t,i=await this.scheduler.scanFile(s);new m.Notice(`Indexed ${i} reminders from ${s.basename}.`)}};