Spaces:
Runtime error
Runtime error
File size: 12,476 Bytes
cd8bd0a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 | import { getDbInstance } from "@/lib/db/core";
const DEFAULT_OBSIDIAN_BASE_URL = "http://127.0.0.1:27123";
const MAX_RETRIES = 2;
const TIMEOUT_MS = 30000;
export class ObsidianAuthError extends Error {
constructor(msg: string) {
super(msg);
this.name = "ObsidianAuthError";
}
}
export class ObsidianNotFoundError extends Error {
constructor(msg: string) {
super(msg);
this.name = "ObsidianNotFoundError";
}
}
export class ObsidianServerError extends Error {
constructor(msg: string) {
super(msg);
this.name = "ObsidianServerError";
}
}
export class ObsidianTimeoutError extends Error {
constructor(msg: string) {
super(msg);
this.name = "ObsidianTimeoutError";
}
}
type ObsidianResult = {
content: Array<{ type: "text"; text: string }>;
isError?: boolean;
};
function classifyObsidianError(status: number, message: string): Error {
switch (status) {
case 401:
case 403:
return new ObsidianAuthError(message);
case 404:
return new ObsidianNotFoundError(message);
default:
if (status >= 500) return new ObsidianServerError(message);
return new Error(`Obsidian API error (${status}): ${message}`);
}
}
function obsidianFetch(
path: string,
apiKey: string,
baseUrl: string,
options: RequestInit = {}
): Promise<unknown> {
const url = `${baseUrl}${path}`;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);
const mergedSignal = options.signal
? combineSignals(options.signal, controller.signal)
: controller.signal;
let lastError: Error | null = null;
const attempt = async (retryCount: number): Promise<unknown> => {
try {
const response = await fetch(url, {
...options,
headers: {
Authorization: `Bearer ${apiKey}`,
...(options.headers as Record<string, string>),
},
signal: mergedSignal,
});
clearTimeout(timeout);
if (!response.ok) {
const body = await response.json().catch(() => ({})) as Record<string, unknown>;
const msg = (body?.message as string) ?? `HTTP ${response.status}`;
const error = classifyObsidianError(response.status, msg);
if (error instanceof ObsidianServerError && retryCount < MAX_RETRIES - 1) {
lastError = error;
await sleep(Math.pow(2, retryCount) * 200);
return attempt(retryCount + 1);
}
throw error;
}
const ct = response.headers.get("content-type") ?? "";
if (ct.includes("application/json")) {
return response.json();
}
return response.text();
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
clearTimeout(timeout);
throw new ObsidianTimeoutError("Obsidian API request timed out after 30s");
}
if (err instanceof ObsidianAuthError || err instanceof ObsidianNotFoundError) {
clearTimeout(timeout);
throw err;
}
if (err instanceof TypeError && err.message === "fetch failed") {
clearTimeout(timeout);
throw new ObsidianServerError(
`Cannot reach Obsidian at ${baseUrl}. Ensure the Local REST API plugin is running ` +
`and using the correct port. The REST API uses HTTP on port 27123 — do not use ` +
`port 27124 (that is a separate MCP endpoint with HTTPS). If connecting via ` +
`Tailscale, use http://<tailscale-ip>:27123.`
);
}
if (retryCount < MAX_RETRIES - 1) {
lastError = err instanceof Error ? err : new ObsidianServerError(String(err));
await sleep(Math.pow(2, retryCount) * 200);
return attempt(retryCount + 1);
}
clearTimeout(timeout);
throw err;
}
};
return attempt(0);
}
function combineSignals(...signals: AbortSignal[]): AbortSignal {
const controller = new AbortController();
for (const signal of signals) {
if (signal.aborted) {
controller.abort(signal.reason);
return controller.signal;
}
signal.addEventListener("abort", () => controller.abort(signal.reason), { once: true });
}
return controller.signal;
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function encodePath(segments: string): string {
return segments.split("/").map(encodeURIComponent).join("/");
}
export type PatchOperation = "append" | "prepend" | "replace";
export type TargetType = "heading" | "block" | "frontmatter";
export function createObsidianClient(apiKey: string, baseUrl?: string) {
const resolvedBaseUrl = baseUrl ?? DEFAULT_OBSIDIAN_BASE_URL;
const client = {
async checkStatus(): Promise<unknown> {
return obsidianFetch("/", apiKey, resolvedBaseUrl);
},
async searchSimple(query: string, contextLength = 100): Promise<unknown> {
const params = new URLSearchParams();
params.set("query", query);
params.set("contextLength", String(contextLength));
return obsidianFetch(`/search/simple/?${params}`, apiKey, resolvedBaseUrl, {
method: "POST",
});
},
async searchStructured(jsonLogic: unknown): Promise<unknown> {
return obsidianFetch("/search/", apiKey, resolvedBaseUrl, {
method: "POST",
headers: { "Content-Type": "application/vnd.olrapi.jsonlogic+json" },
body: JSON.stringify(jsonLogic),
});
},
async readNote(
path: string,
targetType?: TargetType,
target?: string
): Promise<unknown> {
const headers: Record<string, string> = {};
if (targetType) headers["Target-Type"] = targetType;
if (target) headers["Target"] = encodeURIComponent(target);
return obsidianFetch(`/vault/${encodePath(path)}`, apiKey, resolvedBaseUrl, { headers });
},
async listVault(path = ""): Promise<unknown> {
const suffix = path ? `/${encodePath(path)}/` : "/";
return obsidianFetch(`/vault${suffix}`, apiKey, resolvedBaseUrl);
},
async getDocumentMap(path: string): Promise<unknown> {
return obsidianFetch(`/vault/${encodePath(path)}`, apiKey, resolvedBaseUrl, {
headers: { Accept: "application/vnd.olrapi.document-map+json" },
});
},
async getNoteMetadata(path: string): Promise<unknown> {
return obsidianFetch(`/vault/${encodePath(path)}`, apiKey, resolvedBaseUrl, {
headers: { Accept: "application/vnd.olrapi.note+json" },
});
},
async getActiveFile(): Promise<unknown> {
return obsidianFetch("/active/", apiKey, resolvedBaseUrl);
},
async getPeriodicNote(
period: string,
year?: number,
month?: number,
day?: number
): Promise<unknown> {
let url: string;
if (year && month && day) {
url = `/periodic/${period}/${year}/${month}/${day}/`;
} else {
url = `/periodic/${period}/`;
}
return obsidianFetch(url, apiKey, resolvedBaseUrl);
},
async getTags(): Promise<unknown> {
return obsidianFetch("/tags/", apiKey, resolvedBaseUrl);
},
async commandList(): Promise<unknown> {
return obsidianFetch("/commands/", apiKey, resolvedBaseUrl);
},
async writeNote(path: string, content: string): Promise<void> {
await obsidianFetch(`/vault/${encodePath(path)}`, apiKey, resolvedBaseUrl, {
method: "PUT",
headers: { "Content-Type": "text/markdown" },
body: content,
});
},
async appendNote(
path: string,
content: string,
targetType?: TargetType,
target?: string
): Promise<void> {
const headers: Record<string, string> = { "Content-Type": "text/markdown" };
if (targetType) headers["Target-Type"] = targetType;
if (target) headers["Target"] = encodeURIComponent(target);
await obsidianFetch(`/vault/${encodePath(path)}`, apiKey, resolvedBaseUrl, {
method: "POST",
headers,
body: content,
});
},
async patchNote(
path: string,
operation: PatchOperation,
targetType: TargetType,
target: string,
content: string,
createTargetIfMissing = false
): Promise<unknown> {
const headers: Record<string, string> = {
Operation: operation,
"Target-Type": targetType,
Target: encodeURIComponent(target),
"Content-Type": "text/markdown",
};
if (createTargetIfMissing) headers["Create-Target-If-Missing"] = "true";
return obsidianFetch(`/vault/${encodePath(path)}`, apiKey, resolvedBaseUrl, {
method: "PATCH",
headers,
body: content,
});
},
async deleteNote(path: string): Promise<void> {
await obsidianFetch(`/vault/${encodePath(path)}`, apiKey, resolvedBaseUrl, {
method: "DELETE",
});
},
async moveNote(path: string, destination: string): Promise<void> {
await obsidianFetch(`/vault/${encodePath(path)}`, apiKey, resolvedBaseUrl, {
method: "MOVE",
headers: { Destination: encodeURIComponent(destination) },
});
},
async executeCommand(commandId: string): Promise<void> {
await obsidianFetch(`/commands/${encodeURIComponent(commandId)}/`, apiKey, resolvedBaseUrl, {
method: "POST",
});
},
async openFile(path: string): Promise<void> {
await obsidianFetch(`/open/${encodePath(path)}`, apiKey, resolvedBaseUrl, {
method: "POST",
});
},
};
return client;
}
export type ObsidianClient = ReturnType<typeof createObsidianClient>;
const DEFAULT_SYNC_SERVER_URL = "http://127.0.0.1:27781";
const SYNC_TOKEN_KEY = "omniroute_sync_token";
export function getSyncToken(): string | null {
try {
const db = getDbInstance();
const row = db.prepare("SELECT value FROM key_value WHERE namespace = ? AND key = ?").get("sync", SYNC_TOKEN_KEY) as { value?: string } | undefined;
return typeof row?.value === "string" ? JSON.parse(row.value) : null;
} catch { return null; }
}
export function setSyncToken(token: string | null): void {
try {
const db = getDbInstance();
if (token === null) {
db.prepare("DELETE FROM key_value WHERE namespace = ? AND key = ?").run("sync", SYNC_TOKEN_KEY);
} else {
const existing = db.prepare("SELECT value FROM key_value WHERE namespace = ? AND key = ?").get("sync", SYNC_TOKEN_KEY);
if (existing) {
db.prepare("UPDATE key_value SET value = ? WHERE namespace = ? AND key = ?").run(JSON.stringify(token), "sync", SYNC_TOKEN_KEY);
} else {
db.prepare("INSERT INTO key_value (namespace, key, value) VALUES (?, ?, ?)").run("sync", SYNC_TOKEN_KEY, JSON.stringify(token));
}
}
} catch { /* ignore */ }
}
export interface SyncServerStatus {
running: boolean;
uptime: number;
port: number;
vaultName: string;
lastSync: { ok: boolean; pulled: number; pushed: number; deleted: number; conflicts: number };
}
export interface SyncConflict {
path: string;
conflictPath: string;
detectedAt: number;
}
export function createSyncServerClient(syncToken: string, baseUrl?: string) {
const resolvedBaseUrl = baseUrl ?? DEFAULT_SYNC_SERVER_URL;
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${resolvedBaseUrl}${path}`, {
...init,
headers: {
"Content-Type": "application/json",
...(syncToken ? { Authorization: `Bearer ${syncToken}` } : {}),
...init?.headers,
},
});
if (!res.ok) {
const body = await res.text();
throw new Error(`Sync server ${res.status}: ${body}`);
}
return res.json() as Promise<T>;
}
return {
async getStatus(): Promise<SyncServerStatus> {
return request<SyncServerStatus>("/vault/sync/status");
},
async triggerSync(): Promise<{ ok: boolean; pulled: number; pushed: number; deleted: number; conflicts: number }> {
return request("/vault/sync/trigger", { method: "POST" });
},
async getConflicts(): Promise<{ conflicts: SyncConflict[] }> {
return request("/vault/sync/conflicts");
},
async resolveConflict(path: string, resolution: "local" | "remote" | "keep-both"): Promise<unknown> {
return request("/vault/sync/resolve", {
method: "POST",
body: JSON.stringify({ path, resolution }),
});
},
};
}
export type SyncServerClient = ReturnType<typeof createSyncServerClient>;
|