Connector API Reference
This is the reference for connector contract 0.4. The single source of truth is src/connector/def.ts in the plugin repository; the SDK’s index.d.ts is generated from it, so the two cannot drift.
Companion npm package: @sync-vault/connector-sdk (types and local debugging tools only, no runtime code).
npm install --save-dev @sync-vault/connector-sdkVersioning and compatibility
Section titled “Versioning and compatibility”- Current contract version:
0.4. - Compatibility checks only the first segment of
apiVersion: the host is0.4, so0.4.xand0.2.9are both compatible;1.xis not. - 0.3 added the parts-related fields and 0.4 added the
audio-sourcetype. Both only added optional capabilities, so older connectors need no changes.
Directory and loading
Section titled “Directory and loading”<vault>/.obsidian/plugins/sync-vault-ce/connectors/<connector id>/├── manifest.json Required├── main.js Required└── settings.json Optional; read/written by ctx.getSettings / saveSettings- The plugin scans once on startup. Afterwards, run Reload user connectors from the command palette.
- Scanning is in ascending directory-name order, which is also registration and match order.
- One failing connector does not affect other connectors or plugin startup. The failure reason appears in the Connectors widget and in the log.
- Reloading calls
dispose()on the old instance before creating the new one. Disabling the plugin disposes every connector. - Disabling uses a
.disabledmarker inside the directory: files and settings are kept, but the connector is not evaluated or matched. Uninstalling deletes the whole directory.
manifest.json
Section titled “manifest.json”| Field | Required | Description |
|---|---|---|
id | Yes | Unique identifier; must match the directory name; [a-z0-9-_], starting with a letter or digit |
name | Yes | Display name |
version | Yes | The connector’s own version |
apiVersion | Yes | Target contract version, e.g. 0.4 |
type | Yes | video-source, audio-source, or agent-session |
description | No | One-line description |
author | No | Author |
homepage | No | Repository or homepage URL |
A missing field, an invalid id, an id that does not match the directory, an unsupported type, or a mismatched apiVersion first segment all cause an explicit load failure.
main.js
Section titled “main.js”Must be a single CommonJS file:
module.exports = { create(ctx) { return { // Implement the methods required by your type }; },};- ESM
import/exportis not supported; the host evaluates the file as CommonJS. - There is no
requireat runtime:node_modulesand Node built-ins are unavailable. Get every capability fromctx. - Top-level code runs once at load;
create(ctx)may beasync. - With TypeScript or multiple source files, bundle dependencies into a single
main.js(the SDK’stemplates/tshas a ready-made setup).
ctx: host-injected capabilities
Section titled “ctx: host-injected capabilities”| Member | Description |
|---|---|
id | This connector’s id |
dir | This connector’s directory inside the vault |
platform | { isDesktop, isMobile } for per-platform behavior |
request(options) | Network requests through the host channel, not subject to browser CORS |
log | debug / info / warn / error, written to the Sync Vault log |
getSettings<T>() | Reads settings.json; returns null when the file does not exist |
saveSettings(obj) | Writes settings.json (JSON with 2-space indentation) |
desktop | Desktop-only file channel outside the vault; undefined on mobile |
request
Section titled “request”const resp = await ctx.request({ url: 'https://api.example.com/x', method: 'GET', // Optional, defaults to GET headers: { 'Referer': 'https://example.com' }, // Optional body: JSON.stringify(payload), // Optional, string | ArrayBuffer});
resp.status; // numberresp.headers; // Record<string, string>, keys lowercasedresp.text; // stringresp.json; // any, parsed on accessresp.arrayBuffer; // ArrayBuffer- Non-2xx responses do not throw: check
statusyourself. Only network-layer failures (offline, DNS) throw. - Response bodies are read lazily. Do not assume a large body can be read twice.
settings.json
Section titled “settings.json”Suitable for tokens and cookies. It is an ordinary file in the vault, stored in plain text, and travels with sync and sharing. Do not hard-code long-lived secrets in main.js.
video-source
Section titled “video-source”interface VideoSourceConnector { match(url: string): boolean; resolve(url: string, onProgress?: (message: string) => void): Promise<MediaStreamInfo>; dispose?(): void | Promise<void>;}match(url): whether this connector handles the address. The host calls it synchronously, so it must be cheap — no network requests.- When multiple connectors match, the first in ascending directory-name order wins, and that connector owns the address entirely.
resolve(url, onProgress): resolves a playable stream.onProgressmessages are shown in the player’s loading state.- A failed resolve must throw an explicit error. The host will not fall back to built-in parsing, try another connector, or silently treat the address as a direct link.
- When the URL expires, the host calls
resolveagain with the same URL, so the implementation must be repeatable.
MediaStreamInfo
Section titled “MediaStreamInfo”| Field | Required | Description |
|---|---|---|
url | Yes | The address to play |
urlType | Yes | direct for a single address; m3u8-list for an HLS playlist |
mediaType | Yes | raw for a direct link; hls for hls.js / native HLS |
mediaInfo | Yes | Available qualities, at least one item |
headers | No | Headers to send while playing |
proxy | No | true routes direct links through the host’s local proxy; requires headers to take effect |
coverUrl | No | Cover image |
cursor | No | Last playback position in seconds |
parts | No | Part list |
currentPartIndex | No | Index of the part this result represents; defaults to 0 |
cleanup | No | Called when this stream is replaced or the player is destroyed |
Each mediaInfo item:
| Field | Required | Description |
|---|---|---|
url | Yes | Address for this quality |
resolution | Yes | Display name such as 1080P or Auto |
width / height | Yes | Pixel dimensions for the player’s initial aspect ratio; use 0 when unknown |
| Others | No | duration / codec / frameRate / audioCodec / sampleRate / fileSize |
Conventions:
streamInfo.urlshould equal onemediaInfo[].url; that item’sresolutionbecomes the current quality.resolution: '原画'is special: selecting this quality takes the direct-link path (hls.js is torn down and the URL is set on<video>directly). Do not use原画for HLS streams, or that quality will not play through HLS.
return { url: current.playUrl, urlType: 'm3u8-list', mediaType: 'hls', mediaInfo: [{ url: current.playUrl, width: 0, height: 0, resolution: 'Auto' }], parts: [ { name: 'P1 Intro', url: 'https://www.bilibili.com/video/BV1xx411c7mD?p=1' }, { name: 'P2 Main', url: 'https://www.bilibili.com/video/BV1xx411c7mD?p=2' }, ], currentPartIndex: 1,};- Parts are shown only when there are at least 2 items; a single part can be omitted.
- The host re-invokes
resolvewith a part’surlwhen switching, so every URL must be handled bymatch/resolve. currentPartIndexidentifies the part this result represents. If an invalid?p=fell back to a different part, return the index actually played.- Parts are independent entries in the host: each keeps its own progress and annotation anchors, and the next part auto-continues when one ends.
Expiry reloads and cleanup
Section titled “Expiry reloads and cleanup”Playback URLs from platforms usually expire (signed CDN links and similar). The host compensates:
- On 401 / 403 / 404 / 410 during playback, it calls
resolveagain with the same URL, then resumes from the previous position. - Each player reloads at most 2 times; the quota is restored if playback runs for 1 minute without expiring again.
- When a
MediaStreamInfois replaced (expiry reload, video switch) or the player is destroyed, the host calls itscleanup(). Put one-shot resources (timers, local servers, temporary subscriptions) incleanup; resources that must span multiple streams belong in the instance’sdispose.
Audio sources currently have no expiry reloads — see the next section.
audio-source
Section titled “audio-source”interface AudioSourceConnector { match(url: string): boolean; resolve(url: string, onProgress?: (message: string) => void): Promise<MediaStreamInfo>; dispose?(): void | Promise<void>;}The method shape, match order, and error semantics are identical to video sources; the host uses its audio player for the result. Differences:
- Audio has no resolution. Set
width: 0andheight: 0in everymediaInfoitem and use原画or a display name forresolution. - If an address matches both a video source and an audio source, it is treated as video: video sources are asked first, and audio sources only when none match.
- No expiry reloads: if the URL stops working during playback, the host will not call
resolveagain. Return an address that remains valid long enough. partsplay in order. The part list appears in the player sidebar (right-click an audio block and choose Open sidebar); the embedded player has no part selector.cleanupfollows the same timing as video sources.
agent-session
Section titled “agent-session”Exports an agent’s local sessions into the managed repository so another device can restore them and continue. The host owns the managed repository, version cursors, and cross-device distribution; the connector only knows that agent’s storage layout and restore procedure.
interface AgentSessionConnector { probe(): Promise<AgentSessionProbeResult>; discover(): Promise<AgentSessionRef[]>; export(ref: AgentSessionRef): Promise<AgentSessionBundle>; stage(bundle: AgentSessionBundle, env: DeviceEnv): Promise<ResumePlan>; watch?(ref: AgentSessionRef, onChange: () => void): () => void;}- All four of
probe/discover/export/stageare required; a missing one rejects the connector. stage(bundle, env)writes the bundle back to the correct local location and returns aResumePlan(resume command, suggested cwd, notes). It never executes commands.- Bundle paths are relative to the session directory; entries containing
.., absolute paths, or backslashes are rejected by the host. watchis an optional enhancement; without it, the host detects changes by comparing thenativeMtime/nativeSizecursors.- Desktop only: files outside the vault must go through
ctx.desktop, which isundefinedon mobile. Mobile can only view sessions already added to sync.
See examples/qoder in the SDK for a complete implementation.
Proxy, headers, and CORS
Section titled “Proxy, headers, and CORS”For addresses behind anti-hotlink checks (requiring Referer and similar), return proxy: true together with headers:
- Desktop: direct links go through a local
127.0.0.1proxy that adds the headers and CORS response headers. - Mobile: there is no local proxy.
proxy: truedegrades to a direct connection, headers for direct links are not applied, and addresses that require them will fail with 403. Detect this inresolveand throw an explicit error. - HLS: when
headersare set, the host prefers hls.js and loads playlists and segments through its own request channel, so headers are applied on both desktop and mobile. If hls.js is unavailable, native HLS is used and headers cannot be applied.
CORS requirements:
- Direct video is loaded through
<video crossorigin="anonymous">, so the origin must returnAccess-Control-Allow-Origin; otherwise playback fails withMEDIA_ELEMENT_ERROR: Format error— which looks like an encoding problem but is a CORS rejection. On desktop,proxy: truelets the local proxy add the headers; on mobile there is no proxy. - Direct audio is loaded through
<audio>withoutcrossorigin, so the origin does not need CORS headers. - HLS playlists and segments fetched through the host request channel are not subject to browser CORS.
To test an origin, run curl -H 'Origin: app://obsidian.md' -I <url> and check for access-control-allow-origin.
Hard constraints
Section titled “Hard constraints”- Mobile compatibility: connectors are loaded and executed on iOS / Android too. Node built-ins (
fs,path,http, …) and Electron-only APIs are unavailable; use Web standards such ascrypto.subtlefor randomness or digests. - File access: inside the vault, use only
getSettings/saveSettings. Local files outside the vault are available only toagent-sessionconnectors, and only throughctx.desktopon desktop. - No sandbox: connectors run with the plugin’s privileges and can make network requests and read/write their own settings. Install only trusted sources.
- Do not block: keep
matchsynchronous and cheap; put slow work inresolve.
Debugging
Section titled “Debugging”# Video / audio: load → match → resolvenpx sync-vault-connector-mock ./my-connector "https://example.com/video/1"
# agent-session: load → probe → discovernpx sync-vault-connector-mock ./my-connectorThe mock validates and evaluates exactly like the host, catching manifest field errors, ESM syntax, missing require, and similar issues early.
After installing into the vault:
- Run Reload user connectors and check the “N loaded, M failed” notice.
- When playback fails, search the log for
[connector.<id>]; errors thrown byresolveare recorded there.