@life-os/obsidian-web 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # Obsidian Web
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `obsidian-web` opens the Obsidian frontend in an AI client's built-in browser. A browser compatibility layer provides the Electron and Node.js APIs needed to start the editor, access files, and load plugins. The Node.js service listens only on `127.0.0.1`, and edits are saved directly to the selected vault.
4
+
5
+ The npm package is `@life-os/obsidian-web`. Existing scripts can continue using the `vault-ui` command.
6
+
7
+ You can use this CLI and its WorkBuddy Skill on their own. If you already use
8
+ the [LifeOS Skill](https://github.com/quanru/lifeos-skill), ask it to open
9
+ your vault in Obsidian Web. The LifeOS Skill can remember an editor for each
10
+ vault and also supports the Aino Web workspace.
11
+
12
+ ## Installation
13
+
14
+ On macOS or Linux, install the CLI with Node.js 22.16 or later and npm, then prepare the local editor. Setup also installs the WorkBuddy Skill.
15
+
16
+ ```sh
17
+ npm install -g @life-os/obsidian-web
18
+ obsidian-web setup
19
+ obsidian-web --help
20
+ ```
21
+
22
+ For local testing, install a tarball with `npm install -g ./life-os-obsidian-web-0.1.1.tgz`. Build the tarball with `npm pack` from the repository root. The package uses the same `@life-os` scope as the LifeOS CLI. For checkout-based installation, run the following command from the repository root.
23
+
24
+ ```sh
25
+ ./install.mjs
26
+ ```
27
+
28
+ The installer uses a local Obsidian 1.14.4 ASAR if available. If the pinned archive is missing from the cache, setup downloads it concurrently from the [official GitHub release](https://github.com/obsidianmd/obsidian-releases/releases/tag/v1.14.4) and the third-party relays ghfast.top and gh-proxy.com. The first complete download matching the pinned SHA-256 wins. Setup cancels outstanding transfers and caches the verified archive under `~/.local/share/vault-ui/archives/`. The archive is about 8.8 MiB. Later installs can reuse the cache. To supply the runtime yourself, pass a local `.asar` or the official `.asar.gz` to `./install.mjs`.
29
+
30
+ The installer links the CLI and WorkBuddy skill at `~/.local/bin/obsidian-web` and `~/.workbuddy/skills/obsidian-web`. The first setup also downloads build dependencies from npm. With the runtime archive and npm dependencies already cached, use `npm_config_offline=true ./install.mjs` to install without npm network requests. Keep this repository directory in place after installation, then start a new chat in WorkBuddy.
31
+
32
+ Override the runtime and archive cache location with `VAULT_UI_HOME`. Use `VAULT_UI_BIN_DIR` and `VAULT_UI_WORKBUDDY_SKILL_DIR` for isolated installation tests. Rerunning the installer reuses links that already point to this checkout. If a destination is occupied, the installer reports its path.
33
+
34
+ Installation prepares the local runtime. The CLI starts the service on the first `open` and uses the local development resource gate if it is installed. Run `node --test` to check plugin networking and save conflict handling.
35
+
36
+ ## Usage
37
+
38
+ Open a vault in your browser by passing its absolute folder path. Quote paths that contain spaces.
39
+
40
+ ```sh
41
+ obsidian-web "/absolute/path/to/My Notes"
42
+ ```
43
+
44
+ Add `--json` to get the verified address for an embedded browser without opening a separate window.
45
+
46
+ [macOS and WorkBuddy pilot walkthrough](docs/pilot.md)
47
+
48
+ Open your vault folder in WorkBuddy and ask, “Use obsidian-web to open Meetings/Weekly Sync.md in the side panel.” If the service is stopped, WorkBuddy provides the startup command for that vault. Run it once in your system terminal, then return to the chat and ask WorkBuddy to open the note again. WorkBuddy uses `obsidian-web connect` to reuse the running service. You can also open the returned URL in another AI client that supports local web pages.
49
+
50
+ ```sh
51
+ obsidian-web open --vault "/path/to/Notes" --file "Meetings/Weekly Sync.md" --json
52
+ obsidian-web stop --vault "/path/to/Notes"
53
+ ```
54
+
55
+ Omit `--file` to open the entire vault. In your system terminal, `open` starts or reuses the vault's service. `connect` checks an already running service before returning its URL. Obsidian prompts you to trust a vault with existing community plugins on first load. The service runs across chats until you use `stop`. To run it in the foreground, use `serve --vault <directory>`.
56
+
57
+ To switch vaults in the same panel, click the vault name in the lower-left corner and enter the destination folder’s absolute path. A running vault opens directly. For a stopped vault, confirm the same folder in the system picker (macOS or Linux with Zenity), or open the folder from the terminal. Existing local service URLs also work. The switcher saves open Markdown notes before navigating.
58
+
59
+ If WorkBuddy reports that it cannot read files or the side panel stays blank, save any notes that are still editable. Run the `stop` and `open` commands above in your system terminal, then ask WorkBuddy to reconnect. In some WorkBuddy environments, a process started by a chat task may lose file access after the task finishes. The CLI checks that the editor assets and requested note are readable before returning a URL.
60
+
61
+ ## Concurrent edits and recovery
62
+
63
+ When the browser saves a Markdown note it has read, the service checks the file revision used for that edit. If the file on disk has changed, the service keeps that version and writes the browser's changes to a recovery copy under `sessions/<session>/conflicts/` in the runtime directory. The save notice in Obsidian shows the full path to the copy. Open it to recover and merge the changes manually.
64
+
65
+ If an asynchronous Markdown save loses its response, the browser reads the note
66
+ back from the service. Matching bytes confirm the save and its file revision.
67
+ If the contents differ or the service stays unavailable, the save reports an
68
+ error. Append, rename, and delete requests are sent only once.
69
+
70
+ This check applies to browser saves for notes the browser has already read. Native Obsidian and other tools manage their own writes. Keep version history when multiple people or tools edit the same file.
71
+
72
+ ## Plugin networking
73
+
74
+ A local operator can grant read-only CalDAV access to one vault. In its runtime
75
+ session directory (the directory containing that vault's service key), place a
76
+ `read-origins.json` file containing an array of exact HTTPS origins, for example
77
+ `["https://calendar.example.com"]`. Restart that vault's service to apply the
78
+ change. The grant permits GET, HEAD, OPTIONS, PROPFIND and REPORT. A full-access
79
+ origin configured separately also permits writes. In the same directory,
80
+ `sync-origins.json` permits these reads plus POST, PUT and PATCH.
81
+ `full-origins.json` also permits DELETE. Both use the same JSON array format
82
+ and apply only to this vault.
83
+
84
+ The embedded editor runs Obsidian's `requestUrl` through the local service. The primary and fallback LifeOS origins are allowed by default. The bridge forwards the HTTP status, response headers, and binary body. To connect a CalDAV server or another plugin service, set `VAULT_UI_NETWORK_ORIGINS` to a comma-separated list when starting the service. A running service keeps its startup configuration.
85
+
86
+ ```sh
87
+ VAULT_UI_NETWORK_ORIGINS=https://calendar.example.com obsidian-web open --vault "/path/to/Notes" --json
88
+ ```
89
+
90
+ Each entry consists of a protocol, host, and optional port. Plain HTTP is limited to loopback addresses. The bridge forwards explicitly supplied authentication headers, omits browser cookies, and follows only same-origin redirects.
91
+
92
+ The official community plugin and theme catalogs, deprecation list, and statistics
93
+ use anonymous GET or HEAD requests to fixed metadata URLs through the bridge.
94
+ Individual plugin downloads, third-party icon packs, and link-title lookups use
95
+ their own destinations and may require a vault-specific grant. Browser APIs such
96
+ as fetch, XMLHttpRequest, and WebSocket retain their browser networking behavior.
97
+
98
+ ## MVP scope
99
+
100
+ - Supports synchronous, Promise-based, and callback-based file operations on the selected vault. File watching shares native notifications across folders and falls back to polling when native notifications are unavailable. Metadata queries are batched during indexing. Concurrent edits require a manual merge.
101
+ - Plain-text paste uses the browser clipboard and depends on the embedded browser's permissions.
102
+ - Dialogs such as Settings open inside the panel. Native child windows, system keychains, external processes, and native Electron modules are outside current support.
103
+ - Use trusted vaults and plugins. The panel can read and write the selected vault and skips symbolic links.
104
+ - The runtime uses files from Obsidian. Follow [Obsidian's terms](https://obsidian.md/terms) when using those files. The setup script targets macOS and Linux.
package/browser.cjs ADDED
@@ -0,0 +1,527 @@
1
+ const { Buffer } = require('buffer');
2
+ const path = require('path-browserify');
3
+
4
+ function sync(route, data) {
5
+ const request = new XMLHttpRequest();
6
+ request.open(data ? 'POST' : 'GET', '/_local/' + route, false);
7
+ if (data) {
8
+ request.setRequestHeader('Content-Type', 'application/json');
9
+ request.setRequestHeader('X-Vault-UI', '1');
10
+ }
11
+ request.send(data && JSON.stringify(data));
12
+ if (request.status !== 200) throw Error('Local vault service returned ' + request.status);
13
+ return JSON.parse(request.responseText);
14
+ }
15
+
16
+ const { vault, version, metadataBatch, readBatch, nativeWatch, pathSwitch } = sync('config');
17
+ const { createFileQueue, postFileRequest, moveRevisions } = require('./fs-queue.cjs');
18
+ const fs = { constants: { F_OK: 0, R_OK: 4, W_OK: 2 }, promises: {} };
19
+ const markdownRevisions = new Map();
20
+ const operations = ['exists', 'access', 'realpath', 'stat', 'lstat', 'readdir', 'readFile',
21
+ 'writeFile', 'appendFile', 'mkdir', 'rename', 'copyFile', 'unlink', 'rmdir', 'utimes'];
22
+ const decorate = item => ({ ...item, isFile: () => item.file, isDirectory: () => item.directory,
23
+ isSymbolicLink: () => false, mtime: new Date(item.mtimeMs), ctime: new Date(item.ctimeMs),
24
+ birthtime: new Date(item.birthtimeMs) });
25
+
26
+ for (const operation of operations) {
27
+ const requestArgs = args => {
28
+ if (operation === 'writeFile' || operation === 'appendFile') {
29
+ const encoding = typeof args[2] === 'string' ? args[2] : args[2]?.encoding;
30
+ args[1] = Buffer.from(args[1], encoding).toString('base64');
31
+ }
32
+ const expectedRevision = operation === 'writeFile' ? markdownRevisions.get(path.normalize(args[0])) : undefined;
33
+ return { operation, args, expectedRevision };
34
+ };
35
+ const result = ({ value, error, revision }, args) => {
36
+ if (error) throw Object.assign(Error(error.message), { code: error.code });
37
+ if (revision) markdownRevisions.set(path.normalize(args[0]), revision);
38
+ if (operation === 'unlink' || operation === 'appendFile' || operation === 'copyFile') {
39
+ // These operations did not return a revision for the new contents.
40
+ markdownRevisions.delete(path.normalize(operation === 'copyFile' ? args[1] : args[0]));
41
+ }
42
+ if (operation === 'rename') {
43
+ moveRevisions(markdownRevisions, path.resolve(args[0]), path.resolve(args[1]));
44
+ }
45
+ if (operation === 'stat' || operation === 'lstat') return decorate(value);
46
+ if (operation === 'readdir' && args[1]?.withFileTypes) return value.map(decorate);
47
+ if (operation === 'readFile') {
48
+ const encoding = typeof args[1] === 'string' ? args[1] : args[1]?.encoding;
49
+ const buffer = Buffer.from(value, 'base64');
50
+ return encoding ? buffer.toString(encoding) : buffer;
51
+ }
52
+ return value;
53
+ };
54
+ fs[operation + 'Sync'] = (...args) => result(sync('fs', requestArgs(args)), args);
55
+ fs.promises[operation] = async (...args) => {
56
+ const signal = operation === 'readFile' ? args[1]?.signal : undefined;
57
+ return result(await requestFile(requestArgs(args), signal), args);
58
+ };
59
+ fs[operation] = (...args) => {
60
+ const callback = args.pop();
61
+ if (typeof callback !== 'function') throw new TypeError('Expected a filesystem callback');
62
+ fs.promises[operation](...args).then(
63
+ value => operation === 'exists' ? callback(value) : callback(null, value),
64
+ error => operation === 'exists' ? callback(false) : callback(error),
65
+ );
66
+ };
67
+ }
68
+
69
+ const requestFile = createFileQueue(postFileRequest, metadataBatch);
70
+
71
+ // Consecutive Markdown reads may share one adapter queue entry. Every other
72
+ // queued operation closes the group so writes and renames keep their ordering.
73
+ const readGroups = new WeakMap();
74
+ window.vaultWebEndReadGroup = adapter => readGroups.delete(adapter);
75
+ if (readBatch) window.vaultWebRead = (adapter, note) => {
76
+ let group = readGroups.get(adapter);
77
+ if (!group || group.length === 32) {
78
+ group = [];
79
+ const run = adapter.queue(async () => {
80
+ if (readGroups.get(adapter) === group) readGroups.delete(adapter);
81
+ const paths = group.map(item => adapter.getFullPath(item.note));
82
+ const rows = await postFileRequest('read-batch', paths);
83
+ if (rows.length !== paths.length) throw Error('Incomplete vault read');
84
+ await Promise.all(rows.map(async (row, i) => {
85
+ const item = group[i];
86
+ try {
87
+ if (row.error) throw Object.assign(Error(row.error), { code: row.error });
88
+ if (row.single) item.resolve(await fs.promises.readFile(paths[i], 'utf8'));
89
+ else {
90
+ if (row.revision) markdownRevisions.set(path.normalize(paths[i]), row.revision);
91
+ item.resolve(row.text);
92
+ }
93
+ } catch (error) { item.reject(error); }
94
+ }));
95
+ });
96
+ readGroups.set(adapter, group);
97
+ run.catch(error => { for (const item of group) item.reject(error); });
98
+ }
99
+ return new Promise((resolve, reject) => group.push({ note, resolve, reject }));
100
+ };
101
+
102
+ fs.watch = (directory, options, callback = options) => {
103
+ const snapshot = async () => {
104
+ const { value, error } = await requestFile({ operation: 'watchSnapshot', args: [directory, options?.recursive] });
105
+ if (error && error.code !== 'ENOENT') throw Object.assign(Error(error.message), { code: error.code });
106
+ return value ?? {};
107
+ };
108
+ let previous;
109
+ let closed = false;
110
+ let timer;
111
+ let listener = typeof callback === 'function' ? callback : null;
112
+ async function poll() {
113
+ try {
114
+ const current = await snapshot();
115
+ if (!closed && previous) {
116
+ for (const name of new Set([...Object.keys(previous), ...Object.keys(current)])) {
117
+ if (current[name] !== previous[name]) {
118
+ listener?.(Object.hasOwn(current, name) && Object.hasOwn(previous, name) ? 'change' : 'rename', name);
119
+ }
120
+ }
121
+ }
122
+ previous = current;
123
+ } catch {
124
+ // Retry after a transient disconnect or while a directory is being renamed.
125
+ } finally {
126
+ if (!closed) timer = setTimeout(poll, 1000);
127
+ }
128
+ }
129
+ void poll();
130
+ const watcher = {
131
+ close() { closed = true; clearTimeout(timer); },
132
+ on(event, handler) { if (event === 'change') listener = handler; return watcher; },
133
+ };
134
+ return watcher;
135
+ };
136
+
137
+ // Fan out one native event stream to Obsidian's per-directory watchers.
138
+ if (nativeWatch) {
139
+ const poll = fs.watch;
140
+ const listeners = new Map();
141
+ let stream;
142
+ let reconnectTimer;
143
+ let retryDelay = 1000;
144
+ let interrupted = false;
145
+ function dispatch(event, file) {
146
+ let directory = path.dirname(file);
147
+ while (directory === vault || directory.startsWith(vault + '/')) {
148
+ for (const watch of listeners.get(directory) ?? []) {
149
+ const relative = path.relative(directory, file);
150
+ if (watch.recursive || !relative.includes('/')) watch.notify(event, relative);
151
+ }
152
+ directory = path.dirname(directory);
153
+ }
154
+ }
155
+ async function reconcileAfterReconnect(currentVault) {
156
+ const folders = currentVault.getAllLoadedFiles().filter(file => file.children);
157
+ for (const folder of new Set([currentVault.getRoot(), ...folders])) {
158
+ const directory = path.join(vault, folder.path);
159
+ const { value, error } = await requestFile({ operation: 'watchSnapshot', args: [directory, false] });
160
+ if (error?.code === 'ENOENT') continue;
161
+ if (error) throw Error(error.message);
162
+ const children = new Map(folder.children.map(file => [file.name, file]));
163
+ for (const name of new Set([...Object.keys(value), ...children.keys()])) {
164
+ const child = children.get(name);
165
+ const signature = value[name];
166
+ if (signature && child) {
167
+ if (child.children) continue;
168
+ const [mtime, size] = signature.split(':').map(Number);
169
+ if (Math.trunc(mtime) === child.stat.mtime && size === child.stat.size) continue;
170
+ }
171
+ dispatch('rename', path.join(directory, name));
172
+ }
173
+ }
174
+ }
175
+ function events() {
176
+ if (stream || reconnectTimer) return;
177
+ stream = new EventSource('/_local/events');
178
+ stream.onopen = () => {
179
+ retryDelay = 1000;
180
+ if (interrupted) {
181
+ interrupted = false;
182
+ const currentVault = window.app?.vault;
183
+ if (currentVault) void reconcileAfterReconnect(currentVault).catch(console.error);
184
+ }
185
+ };
186
+ stream.onmessage = ({ data }) => {
187
+ const [event, relative] = JSON.parse(data);
188
+ dispatch(event, path.join(vault, relative));
189
+ };
190
+ stream.onerror = () => {
191
+ stream.close();
192
+ stream = null;
193
+ interrupted = true;
194
+ reconnectTimer = setTimeout(() => {
195
+ reconnectTimer = null;
196
+ if (listeners.size) events();
197
+ }, retryDelay);
198
+ retryDelay = Math.min(30000, retryDelay * 2);
199
+ };
200
+ stream.addEventListener('watch-unavailable', () => {
201
+ stream.close();
202
+ stream = null;
203
+ fs.watch = poll;
204
+ for (const [dir, watches] of listeners) {
205
+ for (const watch of watches) watch.fallback = poll(dir, { recursive: watch.recursive }, watch.notify);
206
+ }
207
+ });
208
+ }
209
+ fs.watch = (directory, options, callback = options) => {
210
+ const dir = path.normalize(directory).replace(/\/$/, '');
211
+ if (!listeners.has(dir)) listeners.set(dir, new Set());
212
+ let handler = typeof callback === 'function' ? callback : null;
213
+ const watch = { recursive: !!options?.recursive, notify: (...args) => handler?.(...args),
214
+ on(event, fn) { if (event === 'change') handler = fn; return watch; },
215
+ close() {
216
+ watch.fallback?.close();
217
+ const watches = listeners.get(dir);
218
+ watches?.delete(watch);
219
+ if (!watches?.size) listeners.delete(dir);
220
+ if (!listeners.size) {
221
+ clearTimeout(reconnectTimer);
222
+ reconnectTimer = null;
223
+ stream?.close();
224
+ stream = null;
225
+ retryDelay = 1000;
226
+ interrupted = false;
227
+ }
228
+ },
229
+ };
230
+ listeners.get(dir).add(watch);
231
+ events();
232
+ return watch;
233
+ };
234
+ }
235
+
236
+ const clipboard = navigator.clipboard;
237
+ const readText = clipboard?.readText.bind(clipboard);
238
+ const writeText = clipboard?.writeText.bind(clipboard);
239
+ const ignore = () => {};
240
+ async function pasteText() {
241
+ if (!readText) return;
242
+ const target = document.activeElement;
243
+ try {
244
+ const text = await readText();
245
+ if (document.activeElement === target) document.execCommand('insertText', false, text);
246
+ } catch {
247
+ // Clipboard permission is controlled by the browser host.
248
+ }
249
+ }
250
+ const win = { isFullScreen: () => !!document.fullscreenElement, isFocused: () => document.hasFocus(), setBackgroundColor: ignore, setVibrancy: ignore,
251
+ setTitle: ignore, maximize: ignore, setFrameZoomLevel: ignore, setMinimumSize: ignore, show: ignore, hide: ignore, setRepresentedFilename: ignore, setDocumentEdited: ignore, on: ignore };
252
+ // The browser host owns minimization. Obsidian can still request focus for the page.
253
+ win.isMinimized = () => false;
254
+ win.focus = () => window.focus();
255
+ const nativeTheme = { removeAllListeners: () => nativeTheme, on: ignore,
256
+ get shouldUseDarkColors() { return matchMedia('(prefers-color-scheme: dark)').matches; } };
257
+ const session = { availableSpellCheckerLanguages: [], setSpellCheckerLanguages: ignore,
258
+ setSpellCheckerEnabled: ignore };
259
+ const requestListeners = new Map();
260
+
261
+ async function bridgeRequest(params) {
262
+ const { url, method, headers, contentType, body } = params;
263
+ const bodyBase64 = body == null ? undefined : Buffer.from(body).toString('base64');
264
+ const response = await fetch('/_local/request-url', {
265
+ method: 'POST',
266
+ headers: { 'Content-Type': 'application/json', 'X-Vault-UI': '1' },
267
+ body: JSON.stringify({ url, method, headers, contentType, bodyBase64 }),
268
+ });
269
+ if (!response.ok) throw new Error('Local requestUrl service returned ' + response.status);
270
+ const { value, error } = await response.json();
271
+ if (error) throw new Error(error);
272
+ const bytes = Buffer.from(value.body, 'base64');
273
+ return { status: value.status, headers: value.headers,
274
+ body: bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) };
275
+ }
276
+
277
+ function showVaultSwitcher() {
278
+ if (document.querySelector('dialog[data-vault-switcher]')) return;
279
+ const dialog = document.createElement('dialog');
280
+ dialog.dataset.vaultSwitcher = '';
281
+ dialog.className = 'modal mod-narrow';
282
+ dialog.style.color = 'var(--text-normal)';
283
+ dialog.style.boxShadow = 'var(--shadow-l)';
284
+ dialog.style.fontFamily = 'var(--font-interface)';
285
+ const style = document.createElement('style');
286
+ style.textContent = 'dialog[data-vault-switcher]::backdrop { background: var(--background-modifier-cover); }';
287
+ dialog.append(style);
288
+ dialog.setAttribute('aria-label', 'Switch vault');
289
+ const form = document.createElement('form');
290
+ form.className = 'modal-content';
291
+ const title = document.createElement('div');
292
+ title.className = 'modal-title';
293
+ title.textContent = 'Open another vault';
294
+ const help = document.createElement('p');
295
+ help.style.color = 'var(--text-muted)';
296
+ help.textContent = 'Enter the absolute path to a vault on this computer.';
297
+ const input = document.createElement('input');
298
+ input.type = 'text';
299
+ input.spellcheck = false;
300
+ input.required = true;
301
+ input.style.width = '100%';
302
+ input.placeholder = '/path/to/vault';
303
+ input.setAttribute('aria-label', 'Destination vault path');
304
+ const actions = document.createElement('div');
305
+ actions.className = 'modal-button-container';
306
+ const cancel = document.createElement('button');
307
+ cancel.type = 'button';
308
+ cancel.textContent = 'Cancel';
309
+ cancel.onclick = () => dialog.close();
310
+ const open = document.createElement('button');
311
+ open.textContent = 'Open vault';
312
+ open.className = 'mod-cta';
313
+ actions.append(cancel, open);
314
+ form.append(title, help, input, actions);
315
+ dialog.append(form);
316
+ document.body.append(dialog);
317
+ dialog.addEventListener('close', () => dialog.remove(), { once: true });
318
+ input.oninput = () => input.setCustomValidity('');
319
+ form.onsubmit = async event => {
320
+ event.preventDefault();
321
+ const address = input.value.trim();
322
+ let url;
323
+ if (address.startsWith('/')) {
324
+ if (!pathSwitch) {
325
+ help.textContent = 'Restart the local vault service to enable opening folders by path.';
326
+ return;
327
+ }
328
+ } else {
329
+ url = URL.canParse(address) ? new URL(address) : null;
330
+ if (!url || url.protocol !== 'http:' || url.hostname !== '127.0.0.1' ||
331
+ Number(url.port) < 20000 || Number(url.port) >= 50000 ||
332
+ url.username || url.password || url.pathname !== '/') {
333
+ input.setCustomValidity('Enter an absolute vault folder path.');
334
+ input.reportValidity();
335
+ return;
336
+ }
337
+ }
338
+ open.disabled = true;
339
+ try {
340
+ const saves = [];
341
+ window.app?.workspace?.iterateAllLeaves(leaf => {
342
+ if (leaf.view.getViewType() === 'markdown') saves.push(leaf.view.save());
343
+ });
344
+ await Promise.all(saves);
345
+ if (!url) {
346
+ help.textContent = 'Opening the vault… Confirm the folder if prompted.';
347
+ const response = await fetch('/_local/open-vault', {
348
+ method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Vault-UI': '1' },
349
+ body: JSON.stringify({ folder: address }),
350
+ });
351
+ if (!response.ok) throw Error('The local vault service could not open this folder.');
352
+ const result = await response.json();
353
+ if (result.error) throw Error(result.error);
354
+ url = new URL(result.url);
355
+ }
356
+ if (dialog.open) location.assign(url.href);
357
+ } catch (error) {
358
+ help.textContent = error.message || 'Could not open the vault.';
359
+ open.disabled = false;
360
+ }
361
+ };
362
+ dialog.showModal();
363
+ input.focus();
364
+ }
365
+
366
+ document.addEventListener('click', event => {
367
+ if (event.target.closest?.('.workspace-drawer-vault-switcher')) {
368
+ event.stopPropagation();
369
+ showVaultSwitcher();
370
+ }
371
+ }, true);
372
+
373
+ const electron = {
374
+ ipcRenderer: {
375
+ on: ignore,
376
+ once(channel, listener) { requestListeners.set(channel, listener); },
377
+ removeListener(channel, listener) {
378
+ if (requestListeners.get(channel) === listener) requestListeners.delete(channel);
379
+ },
380
+ send(channel, reply, params) {
381
+ if (channel !== 'request-url') {
382
+ if (channel === 'context-menu') {
383
+ const listener = requestListeners.get(channel);
384
+ requestListeners.delete(channel);
385
+ listener?.(null, null);
386
+ }
387
+ return;
388
+ }
389
+ const listener = requestListeners.get(reply);
390
+ requestListeners.delete(reply);
391
+ if (listener) void bridgeRequest(params).then(
392
+ value => listener(null, value),
393
+ error => listener(null, { error }),
394
+ );
395
+ },
396
+ invoke: async () => null,
397
+ sendSync(channel, arg) {
398
+ switch (channel) {
399
+ case 'starter': showVaultSwitcher(); return null;
400
+ case 'vault': return { id: 'vault-ui', path: vault };
401
+ case 'vault-list': return { 'vault-ui': { path: vault } };
402
+ case 'version': return version;
403
+ case 'disable-update': return true;
404
+ case 'policy': return { plugins: true, themes: true, snippets: true };
405
+ case 'frame': return 'native';
406
+ case 'file-url': return location.origin + '/_local/resource/';
407
+ case 'terms': return 'I understand and agree that I am not allowed to distribute the Obsidian application, in any form, without explicit approval from the Obsidian team. I also understand that Obsidian is a registered trademark, and I cannot use it without explicit permission granted by the Obsidian team.';
408
+ case 'trash':
409
+ try {
410
+ const folder = path.join(vault, '.trash');
411
+ fs.mkdirSync(folder, { recursive: true });
412
+ fs.renameSync(arg, path.join(folder, Date.now() + '-' + path.basename(arg)));
413
+ return true;
414
+ } catch { return false; }
415
+ default: return null;
416
+ }
417
+ },
418
+ },
419
+ remote: {
420
+ nativeTheme,
421
+ safeStorage: { isEncryptionAvailable: () => false },
422
+ app: { getVersion: () => version, getLocale: () => navigator.language, getPreferredSystemLanguages: () => navigator.languages, getPath: () => vault },
423
+ getCurrentWindow: () => win,
424
+ getCurrentWebContents: () => ({ session, copy: () => document.execCommand('copy'),
425
+ cut: () => document.execCommand('cut'), paste: pasteText, showDefinitionForSelection: ignore }),
426
+ },
427
+ clipboard: { readText: () => readText?.() ?? '', writeText: value => writeText?.(value) },
428
+ shell: { openExternal: url => { if (/^https?:/i.test(url)) window.open(url, '_blank', 'noopener'); } },
429
+ };
430
+ const modules = {
431
+ util: { deprecate(fn, message) {
432
+ let warned = false;
433
+ return function(...args) {
434
+ if (!warned) { warned = true; console.warn(message); }
435
+ return new.target ? Reflect.construct(fn, args, new.target) : Reflect.apply(fn, this, args);
436
+ };
437
+ } },
438
+ electron, fs, 'fs/promises': fs.promises, 'original-fs': fs, path,
439
+ url: { pathToFileURL: file => new URL('file://' + file.split('/').map(encodeURIComponent).join('/')) },
440
+ tty: { isatty: () => false },
441
+ os: { hostname: () => 'Local browser', version: () => 'Browser', release: () => '', platform: () => 'linux' },
442
+ crypto: { randomBytes: size => Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(size))) },
443
+ };
444
+ let pluginApi;
445
+ window.vaultWebPluginApi = api => {
446
+ if (!pluginApi) {
447
+ const platform = { ...api.Platform, isDesktopApp: false };
448
+ const exports = Object.getOwnPropertyDescriptors(api);
449
+ exports.Platform = { value: platform, enumerable: true };
450
+ pluginApi = Object.create(Object.getPrototypeOf(api), exports);
451
+ }
452
+ return pluginApi;
453
+ };
454
+ window.Buffer = Buffer;
455
+ // Browser console streams have no terminal, but Node logging libraries probe
456
+ // their descriptors before choosing formatting and color support.
457
+ const consoleStream = (fd, log) => ({
458
+ fd, isTTY: false,
459
+ write(chunk, encoding, callback) {
460
+ log(String(chunk).replace(/\n$/, ''));
461
+ const done = typeof encoding === 'function' ? encoding : callback;
462
+ if (typeof done === 'function') queueMicrotask(done);
463
+ return true;
464
+ },
465
+ });
466
+ window.process = { stdout: consoleStream(1, console.log.bind(console)), stderr: consoleStream(2, console.error.bind(console)), platform: 'linux', versions: { electron: version, node: '22.0.0' }, env: {}, cwd: () => vault };
467
+ window.require = name => modules[name.replace(/^node:/, '')];
468
+
469
+ const browserOpen = window.open.bind(window);
470
+ window.open = (url, target, features) => {
471
+ // Obsidian renders modals inline when the host cannot provide a native child window.
472
+ if (url === 'about:blank' && features?.split(',').includes('popup')) return null;
473
+ return browserOpen(url, target, features);
474
+ };
475
+
476
+ document.addEventListener('versionUpdate', ({ detail }) => {
477
+ const { pluginName, version } = detail ?? {};
478
+ const app = window.app;
479
+ const settings = app?.setting;
480
+ // Obsidian removes the selected plugin settings tab when the plugin is unloaded.
481
+ if (typeof pluginName === 'string' && typeof version === 'string' &&
482
+ settings?.containerEl?.isConnected && !settings.activeTab && settings.lastTabId === pluginName &&
483
+ app.plugins?.plugins?.[pluginName]?.manifest?.version === version) {
484
+ settings.openTabById(pluginName);
485
+ }
486
+ });
487
+
488
+ // In Obsidian 1.14.4, the autosave timer reads getViewData even during IME composition.
489
+ // Let it save completed edits while keeping the candidate text out of the file.
490
+ document.addEventListener('compositionstart', event => {
491
+ const editor = event.target.closest?.('.cm-content');
492
+ const view = window.app?.workspace?.activeLeaf?.view;
493
+ if (!editor || !view?.contentEl?.contains(editor) || view.getViewType() !== 'markdown') return;
494
+
495
+ const file = view.file;
496
+ const getViewData = view.getViewData;
497
+ const previous = getViewData.call(view);
498
+ const readBeforeComposition = () => previous;
499
+ view.getViewData = readBeforeComposition;
500
+
501
+ function restore() {
502
+ editor.removeEventListener('compositionend', restore);
503
+ editor.removeEventListener('blur', restore);
504
+ // CodeMirror handles the final input event before we ask Obsidian to save again.
505
+ setTimeout(() => {
506
+ if (view.getViewData !== readBeforeComposition) return;
507
+ view.getViewData = getViewData;
508
+ if (view.file === file && getViewData.call(view) !== previous) view.requestSave();
509
+ }, 0);
510
+ }
511
+
512
+ editor.addEventListener('compositionend', restore);
513
+ editor.addEventListener('blur', restore);
514
+ }, true);
515
+
516
+ const note = new URLSearchParams(location.search).get('file');
517
+ if (note) {
518
+ const boot = setInterval(() => {
519
+ if (!window.app?.workspace) return;
520
+ clearInterval(boot);
521
+ window.app.workspace.onLayoutReady(() => {
522
+ const file = window.app.vault.getAbstractFileByPath(note);
523
+ if (file?.extension) window.app.workspace.getLeaf().openFile(file);
524
+ });
525
+ }, 50);
526
+ setTimeout(() => clearInterval(boot), 30000);
527
+ }
@@ -0,0 +1,33 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { readFile, rename } from 'node:fs/promises';
4
+ import { promisify } from 'node:util';
5
+
6
+ const [official, destination, expectedHash] = process.argv.slice(2);
7
+ const urls = [official, 'https://ghfast.top/' + official, 'https://gh-proxy.com/' + official];
8
+ const controller = new AbortController();
9
+ const curl = promisify(execFile);
10
+
11
+ async function download(url, index) {
12
+ const file = destination + '.' + index;
13
+ const host = new URL(url).host;
14
+ await curl('curl', [
15
+ '--fail', '--location', '--silent', '--show-error', '--proto', '=https', '--proto-redir', '=https',
16
+ '--connect-timeout', '15', '--max-time', '600', '--speed-limit', '1024', '--speed-time', '45',
17
+ '--max-filesize', '16777216', '--output', file, url,
18
+ ], { signal: controller.signal });
19
+ if (createHash('sha256').update(await readFile(file)).digest('hex') !== expectedHash) {
20
+ throw Error(host + ': SHA-256 mismatch');
21
+ }
22
+ return { file, host };
23
+ }
24
+
25
+ try {
26
+ const winner = await Promise.any(urls.map(download));
27
+ controller.abort();
28
+ await rename(winner.file, destination);
29
+ console.error('Verified runtime downloaded from ' + winner.host);
30
+ } catch (error) {
31
+ console.error((error.errors ?? [error]).map(cause => cause.message).join('\n'));
32
+ process.exitCode = 1;
33
+ }