@nextgensoftwares/folio-sync
Loading and saving: chunked progressive loading, step-based sync, offline outbox (IndexedDB), localStorage snapshots, server-verified checksums. Guides: Loading & saving, Real networks.
Entries
@nextgensoftwares/folio-sync: everything below: the client's entry. Since 0.5@nextgensoftwares/folio-editoris an optional peer (the client has it); servers use/server.@nextgensoftwares/folio-sync/server: all butassembleDocument/appendLoaded/restoreOutboxand the client stores (which build aFolioEditoror touch IndexedDB): the protocol,MemoryDocumentServer, wire, chunking, authority, schema checks, retries,createHttpApi,memoryApi,chunkForPage,layoutReport,docChecksum,nodeHash. No editor, ProseMirror view or DOM in its import graph, for Node servers (folio-server-node uses it).
Protocol types
interface ChunkRef { hash: string; from: number; to: number; bytes: number; pageStart?: number; pages?: number }
interface Manifest {
docId: string; version: number; attrs?: Attrs; blockCount: number; chunks: ChunkRef[];
estimatedPages?: number; checksum: string;
firstChunk?: Chunk; // only when requested with inlineFirst
epoch?: string; // document lineage; changes when the server resets or restores the history
}
interface RequestOptions { signal?: AbortSignal; reload?: boolean; inlineFirst?: boolean }
interface Chunk { hash: string; blocks: FolioNode[] }
interface PushOptions { confirm?: boolean; checksum?: string }
interface PushResult { ok: boolean; version: number; rejected?: 'mass-delete' | 'diverged' | 'unsupported' | 'forbidden'; error?: string; retryAfterMs?: number }
// retryAfterMs: not applied for now (the document's write queue is full or its storage write failed); REST: 503 + Retry-After
interface PullResult { version: number; steps: unknown[]; clientIDs: string[]; epoch?: string }
interface LayoutReport { version: number; totalPages: number; chunks: { hash: string; pageStart: number; pages: number }[] }
interface DocumentApi {
manifest(docId: string, opts?: RequestOptions): Promise<Manifest>;
chunk(docId: string, ref: ChunkRef, opts?: RequestOptions): Promise<Chunk>;
push(docId: string, version: number, steps: unknown[], clientID: string, opts?: PushOptions): Promise<PushResult>;
pull(docId: string, since: number): Promise<PullResult>;
reportLayout?(docId: string, report: LayoutReport): Promise<void>;
create?(docId: string, doc: FolioDocument, opts?: CreateOptions): Promise<{ docId: string; version: number }>;
list?(opts?: RequestOptions): Promise<DocInfo[]>;
}
interface DocInfo { docId: string; version: number; title?: string }
interface CreateOptions { title?: string; signal?: AbortSignal }| Export | Description |
|---|---|
class IntegrityError | loaded content doesn't match its content address |
class OfflineError | thrown by transports when the network is unavailable (drives offline mode) |
isOffline(e) | OfflineError, or a fetch/network TypeError |
class HttpError | a non-success status other than the protocol's 409/422 (status) |
class ChunkLoadError | a chunk could not be loaded after retries (index, ref, cause): the load stops, assembleDocument rejects |
type DocInfo | one document a server lists (DocumentApi.list): docId, version, optional title |
type CreateOptions | options of DocumentApi.create: title (display title, returned in manifests and listings) and signal (abort) |
type RequestOptions | signal (abort), reload (bypass HTTP/CDN caches: refetch after a corrupt response), inlineFirst (manifest only: ask for chunk 0 inline) |
Transports and reference server
| Export | Signature | Description |
|---|---|---|
createHttpApi | (opts: HttpApiOptions) => DocumentApi | REST client; 409 = behind, 422 = refused. Reads retry with backoff + jitter on network errors, timeouts, 408/429/5xx (honouring Retry-After); every request has a timeout and follows signal; GETs send no Content-Type (no CORS preflight per chunk) |
type HttpApiOptions | baseUrl, headers?() (per request), fetch?, stats?: TransportStats, credentials?, plus RetryOptions | |
withRetry | (attempt: (signal) => Promise<T>, opts?: RetryOptions, signal?) => Promise<T> | per-attempt timeout + exponential backoff with full jitter; a final timeout becomes OfflineError |
type RetryOptions | retries (3), baseDelayMs (300), maxDelayMs (8000), timeoutMs (30000) | |
isRetryable | (e) => boolean | network errors, timeouts, 408, 421 (not the document's owner: a retry may reach it), 429, 5xx |
class RetryAfterError | an HttpError carrying the server's Retry-After (retryAfterMs) | |
class MemoryDocumentServer | new (schema: PMSchema, docs?: Record<string, FolioDocument>, opts?: ServerOptions) | reference backend (extends DocumentStore): put, submit(docId, version, steps, clientID, opts?: SubmitOptions) => MaybePromise<PushResult> (the authority's write path: version check, validatePush, the protected committed hook, then the in-memory apply and onCommit listeners; throws StepError), push (the same, synchronous: only for servers whose committed is synchronous), pendingWrites(docId), onCommit(fn: CommitListener). committed may return a Promise: the push is applied, acknowledged and broadcast only after it resolves, later writes to that document queue behind it (over maxQueuedPushes: retryAfterMs), and a rejection refuses the push with nothing changed (@nextgensoftwares/folio-server-node appends to storage there) |
MemoryDocumentServer.edit | (docId, fn: (tr: Transform, doc) => void | false, opts?: EditOptions) => MaybePromise<EditResult> | a server-side edit as steps (publish, AI edit, migration, admin fix): fn adds steps to a Transform of the current document (false or no steps = nothing); they take the same path as a client push (version, validatePush, committed, onCommit broadcast), queued with pushes, authored by opts.origin. Clients rebase over them like over anyone's steps. originUser(clientID) returns the user an origin was labelled with |
type EditOptions, type EditResult | { origin? ('server'), user? ({ id, name, color }: how collaborators and history show it), confirm? (true: may delete most of a large document) }; PushResult + steps (how many it made) | |
findBlock, replaceBlock, setBlockAttrs, insertBlocks, deleteBlocks, replaceDocument | (tr, ...) | edit helpers by block id (BLOCK_ID_ATTR): replaceBlock(tr, id, json | json[]), setBlockAttrs(tr, id, attrs), insertBlocks(tr, index | { before: id } | { after: id }, json | json[]), deleteBlocks(tr, ids), replaceDocument(tr, doc) (one replace step plus doc-attr steps, never a reset); content is Folio JSON parsed with the server schema; a missing id throws |
class DocumentStore | the read side MemoryDocumentServer extends: has (in memory), version, list, title/setTitle, manifest, chunkIndex, hasChunk, chunkBody (current or recently superseded chunks), pull(docId, since, limit?), oldestVersion(docId), reportLayout, document; protected restore, unload, compactSteps | |
type SubmitOptions | PushOptions + policy? (PushPolicy), userId? | |
type CommitListener | (docId, from, steps: StepEntry[]) => void: called after every accepted change is applied (broadcast it) | |
class DocQueue, isPromise, type MaybePromise | per-document serialisation that stays synchronous until a run is asynchronous (run(docId, task), depth(docId), idle()); MaybePromise<T> = T | Promise<T> | |
type ServerOptions | ChunkingOptions + GuardOptions + maxQueuedPushes (64 per document) + now (clock for StepEntry.at, default Date.now) | |
type StepEntry | { json, clientID, at? }: one accepted step in the log (at: when the server accepted it, ms) | |
class HistoryGoneError | pull(since) asked for steps older than the server keeps: reopen the document | |
validatePush | (schema, base: PMNode, steps: unknown, opts: { confirm?, checksum? }, guard?: GuardOptions) => GuardResult | the storage-agnostic push validation every backend shares: parse + apply steps to the server's copy, compare the result checksum, mass-delete guard; nothing is mutated |
type GuardOptions | massDeleteGuardSize (2000, PM size), requireChecksum (true), maxStepsPerPush (5000) | |
type GuardResult | { ok: true, doc } | { ok: false, rejected: 'mass-delete' | 'diverged' } | |
class StepError | steps that don't parse (kind: 'malformed', HTTP 400), don't apply ('unapplicable', treated as diverged) or use nodes/marks/attrs the server's schema lacks ('unsupported': push returns { rejected: 'unsupported', error }, HTTP 422; the message names them) | |
collectGaps, stepGaps, describeGaps | (schema, json) => SchemaGaps, (schema, stepJson, doc?) => SchemaGaps, (gaps) => string | null | what a document or step uses that a schema doesn't declare, and the readable refusal; PersistentDocumentServer.create uses them too |
class ChunkIndex | new (opts?: ChunkingOptions) | incremental chunking: update(doc) walks the blocks once and re-serializes/re-hashes only chunks whose blocks changed (lastUpdate: { hashed, reused, ms }); has(hash), body(hash) for current and retained chunks |
type ChunkingOptions | minChunkBlocks (100), maxChunkBlocks (1000), retainChunks (512 superseded chunks stay fetchable) | |
type ChunkSpan | { hash, from, to, bytes } | |
memoryApi | (server, network: () => NetworkProfile, stats?) => DocumentApi & { stats } | the server behind a simulated network (latency, bandwidth, offline) with real JSON round-trips |
NETWORKS | Record<'lan' | 'wifi' | '4g' | '3g', NetworkProfile> | presets |
type NetworkProfile | { latencyMs, bytesPerSecond, offline? } | |
type TransportStats | { requests, bytesDown, bytesUp } | |
hashString | (s: string) => string | content hash used for chunk ids (two 32-bit FNV-style hashes, base 36) |
compact | (node: PMNode) => Record<string, unknown> | node JSON without default-valued attrs (the wire format) |
blockWire | (node: PMNode) => string | compact JSON string of a block, memoized by node identity |
Chunks are cut at the next H1 once they hold minChunkBlocks blocks, and hard-cut at maxChunkBlocks. Chunk JSON is compact (default-valued attrs omitted).
Roles
What someone may do in a session is decided by the host (its auth hook, e.g. server-node's roleOf) and enforced by the server on every push. Also in /server.
| Export | Signature | Description |
|---|---|---|
type DocRole, DOC_ROLES | 'editor' | 'suggester' | 'commenter' | 'viewer': edits directly; edits become suggestions (tracked changes); comments only, text read-only; read-only view. DOC_ROLES lists them | |
isDocRole | (v: unknown) => v is DocRole | type guard for a role from a token or request |
canWrite, canComment, canReview | (r: DocRole) => boolean | pushes steps (editor, suggester); adds and replies to comments (all but viewer); accepts/rejects suggestions and resolves anyone's comments (editor) |
rolePolicy | (role, o?: { suggestions?: PushPolicy }) => PushPolicy | null | the push policy for a role (pass it as SubmitOptions.policy): null for editors (anything goes); commenters and viewers are refused every push; suggesters get o.suggestions (a policy that accepts only suggestion steps; server-node's and the collab room's suggestions option), and without one can't push at all |
roleRefusal | (role: DocRole) => string | the message a commenter or viewer gets ("You can comment on this document but not edit it", "You can view…"); '' for roles that can push |
type PushPolicy | (ctx: PushContext) => string | null | why a push is refused (shown to the user), or null to accept it |
type PushContext | { before, after, steps, clientID, userId? }: the server's document before and after the steps, the steps, and who sent them (userId when known: suggestions must carry it as their author) |
Loading
| Export | Signature | Description |
|---|---|---|
openDocument | (api, docId, opts?: LoadOptions) => Promise<LoadSession> | manifest (cached when offline), then chunks cache-first, concurrency (6) in parallel, delivered in order, each verified against its hash |
type LoadOptions | cache?, concurrency?, firstChunk?, manifest? (e.g. an outbox's base), signal? (aborts delivery and in-flight requests), staleWhileRevalidate? (open from the cached manifest, revalidate in the background), firstChunkAlone? (fetch chunk 0 before the others; for HTTP/2) | |
type LoadSession | { manifest, offline, chunks: AsyncGenerator<LoadedChunk>, revalidated? } | |
type LoadedChunk | { index, ref, chunk, fromCache } | |
chunkForPage | (manifest, page) => number | null | chunk containing a page, from the last layout report |
assembleDocument | (session, opts: AssembleOptions) => { ready: Promise<FolioEditor>; complete: Promise<FolioEditor> } | editor after the first chunk; the rest appended in ≤100 ms batches; outbox restored at the end |
type AssembleOptions | EditorOptions minus doc/plugins, plus clientID, outbox?, epoch?, onStaleOutbox?(rec), onProgress?(loaded, total, editor) | |
appendLoaded | (editor, blocks) => void | append blocks outside undo history and outside collab's unconfirmed steps |
restoreOutbox | (editor, rec: OutboxRecord, opts?: { epoch?, onStale? }) => boolean | replay confirmed steps, then unconfirmed local ones; with epoch, a record from another epoch is refused (onStale(rec), returns false) |
outboxMatches | (rec, epoch) => boolean | whether an outbox may be replayed onto a document whose lineage is epoch (true when either side has none) |
outboxEpoch | (rec) => string | undefined | the record's epoch (its own, else its manifest's) |
layoutReport | (manifest, layout) => LayoutReport | page each chunk starts on, for the server |
storedDocumentSearch | (o: StoredSearchOptions) => (query, options, signal) => Promise<StoredHit[]> | find in what the editor hasn't loaded yet: stored chunks (cache first, then the server) from block loaded() on, matched like the editor's find. Give it to the find bar as its host search while assembleDocument appends chunks; loaded blocks are searched in the editor |
type StoredSearchOptions | { api, docId, manifest, cache?, loaded(): number, limit? (200) } | |
type StoredHit | { id, block, context: { before, match, after }, label, page? } (page: where its chunk starts, from the last layout report) |
Saving
type SyncState = 'synced' | 'saving' | 'offline' | 'error' | 'needs-confirmation' | 'diverged';
// status.reason === 'unsupported': state 'error', sync stopped for good (the server's schema lacks a plugin); edits stay in the outbox
// status.reason === 'gone': state 'diverged', the server no longer keeps the steps since this copy's version (pull 410): reopen
// status.reason === 'epoch': state 'diverged', a pull reported another Manifest.epoch (history reset/restored): reopen; the outbox keeps the old epoch
// a push answered 503 / retryAfterMs (server busy, storage write failed) is retried on the backoff schedule
interface SyncStatus { state: SyncState; version: number; pending: number; lastSavedAt?: number; error?: string }
interface SyncOptions {
manifest: Manifest; // what the editor was loaded from
outbox?: Outbox; // durable outbox (IndexedDB)
debounceMs?: number; // default 400
pollMs?: number; // default 2000
confirmed?: { steps: unknown[]; clientIDs: string[] }; // when restored from an outbox
epoch?: string; // document lineage (default manifest.epoch): recorded in the outbox, checked on pulls
}class SyncClient | Description |
|---|---|
new SyncClient(editor, api, docId, clientID, opts) | the editor must have been created with the collab plugin (assembleDocument does this) |
start(): this | warm the checksum memo, subscribe to the editor, start polling, sync once |
stop() | unsubscribe, remove the page-hide listeners and clear timers |
persistNow(): Promise<void> | write pending edits to the outbox now (no 150 ms debounce); also done on pagehide and when the tab is hidden |
subscribe(fn: (s: SyncStatus) => void) | status listener |
sync(): Promise<void> | pull, then push pending steps with a result checksum; repeat until in sync (max 5 rounds) |
confirmPending(): Promise<void> | resend a push the server refused as a mass delete, with confirm: true |
discardPending(): Promise<void> | drop the edits the server hasn't confirmed (the user discarded a held change): undone in one transaction, also while read-only, and removed from undo history; then syncing resumes (diverged stays: reopen) |
status: SyncStatus | current status |
Sync schedule
SyncClient takes ScheduleOptions (all optional): pollMs (first poll interval, default 2 s, growing ×1.5 per quiet poll; false = never poll, e.g. when a realtime socket carries steps), maxPollMs (30 s), retryBaseMs (1 s, doubling per failure with jitter) and maxRetryMs (60 s). Hidden tabs and offline browsers aren't polled; coming back online, showing the tab or client.retryNow() syncs at once. status.retryAt says when the next automatic retry runs. Saves cost one request (push); the client pulls only when the server says it's behind.
SyncSchedule is the scheduler itself (new SyncSchedule(run, options, env?) with start, stop, now, succeeded(remoteChanged), failed, backingOff, retryAt), exported for hosts building their own sync loop.
Integrity
| Export | Signature | Description |
|---|---|---|
docChecksum | (doc: PMNode) => string | order-sensitive checksum of the top-level blocks (+ doc attrs and child count); attrs at their schema default are skipped, so a plugin-extended client schema and the server's base schema agree; memoized per document node |
nodeHash | (node: PMNode) => number | 32-bit structural hash of a node, memoized by node identity |
Stores
interface ChunkCache { getManifest(docId); putManifest(m); getChunk(hash); putChunk(chunk) }
interface Outbox { getOutbox(docId); putOutbox(rec); clearOutbox(docId) }
interface OutboxRecord {
docId: string; clientID: string; manifest: Manifest; baseVersion: number;
confirmed: unknown[]; confirmedClientIDs: string[]; unconfirmed: unknown[]; updatedAt: number;
epoch?: string; // lineage the edits belong to (outboxMatches)
}
interface Snapshot { version: number; doc: FolioDocument; savedAt: number }| Export | Description |
|---|---|
class IndexedDbStore implements ChunkCache, Outbox | new IndexedDbStore(name = 'folio-sync', idb = indexedDB); stores manifests, chunks, outbox; clear() |
class LocalStorageStore | whole-document snapshots for small docs: load, save(docId, doc, version?) (returns { ok, bytes }, keeps the previous snapshot), previous, remove |
class IndexedDbSnapshotStore | whole-document snapshots in IndexedDB for books (structured clone, no JSON string, browser storage quota instead of ~5 MB): async load, save(docId, doc, version?) (resolves { ok: true } or { ok: false, error }, never rejects; keeps the previous snapshot), previous, remove. The playground's local mode uses localStorage for small documents and falls back to this automatically. |