Fix: Final working v0.3.11 build with correct function mapping
All checks were successful
Build SilverBullet Plug / build (push) Successful in 33s

This commit is contained in:
2026-02-17 14:39:39 -08:00
parent cd194de3f7
commit 70e6a4ef82
4 changed files with 47 additions and 163 deletions

View File

@@ -1,8 +1,8 @@
---
name: Library/sstent/icalendar
version: 0.3.1
version: 0.3.11
tags: meta/library
files:
- icalendar.plug.js
---
iCalendar sync plug for SilverBullet.
iCalendar sync plug for SilverBullet.

File diff suppressed because one or more lines are too long

View File

@@ -1,6 +1,5 @@
name: Library/sstent/icalendar
version: 0.3.1
author: sstent
name: icalendar
version: 0.3.11
functions:
syncCalendars:
path: icalendar.ts:syncCalendars
@@ -8,9 +7,6 @@ functions:
forceSync:
path: icalendar.ts:forceSync
command: "iCalendar: Force Sync"
clearCache:
path: icalendar.ts:clearCache
command: "iCalendar: Clear Cache"
showVersion:
path: icalendar.ts:showVersion
command: "iCalendar: Show Version"

View File

@@ -1,10 +1,10 @@
import { clientStore, config, datastore, editor, index } from "@silverbulletmd/silverbullet/syscalls";
import { convertIcsCalendar, type IcsCalendar, type IcsEvent, type IcsDateObjects } from "ts-ics";
import { convertIcsCalendar } from "https://esm.sh/ts-ics@2.4.0";
import type { IcsCalendar, IcsEvent, IcsDateObjects } from "https://esm.sh/ts-ics@2.4.0";
const VERSION = "0.3.1";
const VERSION = "0.3.11";
const CACHE_KEY = "icalendar:lastSync";
// Mapping of common Windows/Outlook timezones to their standard offsets (in hours)
const TIMEZONE_OFFSETS: Record<string, number> = {
"GMT Standard Time": 0,
"W. Europe Standard Time": 1,
@@ -19,145 +19,46 @@ const TIMEZONE_OFFSETS: Record<string, number> = {
"None": 0
};
// ============================================================================
// Types
// ============================================================================
type DateToString<T> = T extends Date ? string
: T extends IcsDateObjects ? string
: T extends object ? { [K in keyof T]: DateToString<T[K]> }
: T extends Array<infer U> ? Array<DateToString<U>>
: T;
interface Source {
url: string;
name: string | undefined;
}
interface PlugConfig {
sources: any;
cacheDuration: number | undefined;
tzShift: number | undefined;
}
interface CalendarEvent extends DateToString<IcsEvent> {
ref: string;
tag: "ical-event";
sourceName: string | undefined;
}
// ============================================================================
// Utility Functions
// ============================================================================
function toLocalISO(d: Date): string {
const pad = (n: number) => String(n).padStart(2, "0");
return d.getFullYear() +
"-" + pad(d.getMonth() + 1) +
"-" + pad(d.getDate()) +
"T" + pad(d.getHours()) +
":" + pad(d.getMinutes()) +
":" + pad(d.getSeconds()) +
"." + String(d.getMilliseconds()).padStart(3, "0");
}
function processIcsDate(obj: any, manualShift = 0): string {
if (!obj) return "";
let wallTimeStr = "";
if (obj.local && typeof obj.local.date === "string") wallTimeStr = obj.local.date;
else if (typeof obj.date === "string") wallTimeStr = obj.date;
else if (obj.date instanceof Date) wallTimeStr = obj.date.toISOString();
else if (obj instanceof Date) wallTimeStr = obj.toISOString();
if (!wallTimeStr) return "";
const baseDate = new Date(wallTimeStr.replace("Z", "") + "Z");
const tzName = obj.local?.timezone || obj.timezone || "UTC";
const sourceOffset = TIMEZONE_OFFSETS[tzName] ?? 0;
const utcMillis = baseDate.getTime() - (sourceOffset * 3600000);
const finalDate = new Date(utcMillis + (manualShift * 3600000));
return toLocalISO(finalDate);
}
function isIcsDateObjects(obj: any): obj is IcsDateObjects {
return obj && typeof obj === 'object' && ('date' in obj && 'type' in obj);
}
async function sha256Hash(str: string): Promise<string> {
const hashBuffer = await crypto.subtle.digest("SHA-256", (new TextEncoder()).encode(str));
return Array.from(new Uint8Array(hashBuffer)).map(b => b.toString(16).padStart(2, "0")).join("");
}
function convertDatesToStrings<T>(obj: T, hourShift = 0): DateToString<T> {
if (obj === null || obj === undefined) return obj as DateToString<T>;
if (isIcsDateObjects(obj)) return processIcsDate(obj, hourShift) as DateToString<T>;
if (obj instanceof Date) return processIcsDate({ date: obj }, hourShift) as DateToString<T>;
if (Array.isArray(obj)) return obj.map(item => convertDatesToStrings(item, hourShift)) as DateToString<T>;
if (typeof obj === 'object') {
const result: any = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) result[key] = convertDatesToStrings((obj as any)[key], hourShift);
}
return result as DateToString<T>;
}
return obj as DateToString<T>;
}
async function getSources(): Promise<{ sources: Source[], tzShift: number }> {
try {
const rawConfig = await config.get<PlugConfig>("icalendar", { sources: [] });
let sources: Source[] = [];
let tzShift = rawConfig.tzShift ?? 0;
let rawSources = rawConfig.sources;
if (rawSources && typeof rawSources === "object") {
if (rawSources.tzShift !== undefined && tzShift === 0) tzShift = rawSources.tzShift;
if (Array.isArray(rawSources)) sources = rawSources.filter(s => s && typeof s.url === "string");
else if (rawSources.url) sources = [rawSources];
}
return { sources, tzShift };
} catch (e) {
return { sources: [], tzShift: 0 };
}
}
async function fetchAndParseCalendar(source: Source, hourShift = 0): Promise<CalendarEvent[]> {
let url = source.url.trim();
if (url.includes(" ")) url = encodeURI(url);
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const calendar = convertIcsCalendar(undefined, await response.text());
if (!calendar.events) return [];
return await Promise.all(calendar.events.map(async (icsEvent: IcsEvent): Promise<CalendarEvent> => {
const uniqueKey = `${icsEvent.start?.date || ''}${icsEvent.uid || icsEvent.summary || ''}`;
const ref = await sha256Hash(uniqueKey);
return convertDatesToStrings({ ...icsEvent, ref, tag: "ical-event" as const, sourceName: source.name }, hourShift);
}));
}
// ============================================================================
// Public Commands
// ============================================================================
export async function syncCalendars() {
try {
const { sources, tzShift } = await getSources();
if (sources.length === 0) return;
await editor.flashNotification("Syncing calendars...", "info");
const allEvents: CalendarEvent[] = [];
for (const source of sources) {
try {
const events = await fetchAndParseCalendar(source, tzShift);
allEvents.push(...events);
} catch (err) {
console.error(`Failed to sync ${source.name}:`, err);
}
const rawConfig = await config.get("icalendar", { sources: [] });
let sources: any[] = rawConfig.sources || [];
let tzShift = rawConfig.tzShift || 0;
if (sources.length === 0) return;
await editor.flashNotification("Syncing calendars...", "info");
const allEvents: any[] = [];
for (const source of sources) {
const response = await fetch(source.url);
const text = await response.text();
const calendar = convertIcsCalendar(undefined, text);
if (!calendar.events) continue;
for (const icsEvent of calendar.events) {
const obj = icsEvent.start;
let wallTimeStr = "";
if (obj.local && typeof obj.local.date === "string") wallTimeStr = obj.local.date;
else if (typeof obj.date === "string") wallTimeStr = obj.date;
const baseDate = new Date(wallTimeStr.replace("Z", "") + "Z");
const tzName = obj.local?.timezone || obj.timezone || "UTC";
const sourceOffset = TIMEZONE_OFFSETS[tzName] ?? 0;
const utcMillis = baseDate.getTime() - (sourceOffset * 3600000);
const finalDate = new Date(utcMillis + (tzShift * 3600000));
const pad = (n: number) => String(n).padStart(2, "0");
const localIso = finalDate.getFullYear() + "-" + pad(finalDate.getMonth() + 1) + "-" + pad(finalDate.getDate()) + "T" + pad(finalDate.getHours()) + ":" + pad(finalDate.getMinutes()) + ":" + pad(finalDate.getSeconds());
allEvents.push({
...icsEvent,
start: localIso,
tag: "ical-event",
sourceName: source.name
});
}
await index.indexObjects("$icalendar", allEvents);
await editor.flashNotification(`Synced ${allEvents.length} events`, "info");
} catch (err) {
console.error("Sync failed:", err);
}
await index.indexObjects("$icalendar", allEvents);
await editor.flashNotification(`Synced ${allEvents.length} events`, "info");
}
export async function forceSync() {
@@ -165,19 +66,6 @@ export async function forceSync() {
await syncCalendars();
}
export async function clearCache() {
if (!await editor.confirm("Clear all calendar events?")) return;
const pageKeys = await datastore.query({ prefix: ["ridx", "$icalendar"] });
const allKeys: any[] = [];
for (const { key } of pageKeys) {
allKeys.push(key);
allKeys.push(["idx", ...key.slice(2), "$icalendar"]);
}
if (allKeys.length > 0) await datastore.batchDel(allKeys);
await clientStore.del(CACHE_KEY);
await editor.flashNotification("Calendar index cleared", "info");
}
export async function showVersion() {
await editor.flashNotification(`iCalendar Plug ${VERSION}`, "info");
}