// High-level reMarkable cloud client: a local picture of the account's // document tree, path resolution, and the mutations (create, move, rename, // trash, purge) expressed as root-index transactions that retry on // generation conflicts. Also download, export, and a directory mirror. import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync, readdirSync, renameSync } from 'node:fs'; import { join, dirname, basename } from 'node:path'; import { randomUUID } from 'node:crypto'; import { CloudApi } from './api.js'; import { parseIndex, docIndex, rootIndex, sha256 } from './index-file.js'; import { DOCUMENT, COLLECTION, TRASH, ROOT_ID, UUID_RE, newMetadata, updateMetadata, fileContent, notebookContent, pageIds, safeFileName, uploadKind, timestamp, findPage, registerAuthors, pageIndexBetween, pageIndexAfter, } from './documents.js'; import { readBlocks, writeBlocks, simpleTextDocument, AuthorIdsBlock } from '../scene-stream.js'; import { blankPage } from '../scene-edit.js'; import { rmToMarkdown } from '../exporters/markdown.js'; import { rmToSvg } from '../exporters/svg.js'; import { rmsToPdf } from '../exporters/pdf.js'; import { AmbiguousPathError, CloudError, GenerationConflictError, NotFoundError } from './errors.js'; export const SYNC_STATE_FILE = '.notable-sync.json'; export const EXPORT_FORMATS = ['markdown', 'svg', 'pdf']; // Pseudo-folders: the root and the trash are not documents on the cloud. export const ROOT = Object.freeze({ id: ROOT_ID, name: '', parent: null, isFolder: true, isRoot: true, isTrash: false, isTrashed: false, isDeleted: false }); export const TRASH_FOLDER = Object.freeze({ id: TRASH, name: 'trash', parent: null, isFolder: true, isRoot: false, isTrash: true, isTrashed: false, isDeleted: false }); // Map of author index → UUID from a page's AuthorIdsBlock. function pageAuthors (data) { for (const block of readBlocks(data)) if (block instanceof AuthorIdsBlock) return new Map(block.authorUuids); return new Map(); } export async function pmap (items, limit, fn) { const out = new Array(items.length); let next = 0; const worker = async () => { while (next < items.length) { const i = next++; out[i] = await fn(items[i], i); } }; await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, worker)); return out; } function cmpName (a, b) { return a.name.localeCompare(b.name, undefined, { sensitivity: 'base', numeric: true }) || (a.id < b.id ? -1 : 1); } export class Doc { constructor (id) { this.id = id; this.hash = ''; this.size = 0; this.files = []; // [{ name, hash, size, data? }] this.metadata = {}; this._content = undefined; } get name () { return this.metadata.visibleName ?? ''; } get parent () { return this.metadata.parent ?? ROOT_ID; } get type () { return this.metadata.type ?? DOCUMENT; } get isFolder () { return this.type === COLLECTION; } get isRoot () { return false; } get isTrash () { return false; } get isTrashed () { return this.parent === TRASH; } // directly in the trash; see Tree#isTrashed get isDeleted () { return Boolean(this.metadata.deleted); } get pinned () { return Boolean(this.metadata.pinned); } get lastModified () { const raw = String(this.metadata.lastModified ?? ''); if (!/^\d+$/.test(raw)) return null; const n = raw.length > 15 ? Number(raw) / 1e6 : Number(raw); // some old files carry nanoseconds return Number.isFinite(n) && n > 0 ? new Date(n) : null; } file (suffix) { return this.files.find(f => f.name === `${this.id}${suffix}`) ?? null; } // The main file of an uploaded PDF/EPUB, if any. get sourceFile () { return this.file('.pdf') ?? this.file('.epub') ?? null; } toJSON () { return { id: this.id, name: this.name, type: this.type, parent: this.parent, hash: this.hash, size: this.size, pinned: this.pinned, lastModified: this.lastModified?.toISOString() ?? null, files: this.files.map(f => ({ name: f.name, hash: f.hash, size: f.size })), }; } } export class Tree { constructor () { this.hash = ''; this.generation = 0; this.schemaVersion = null; this.docs = new Map(); this.loaded = false; } get (id) { return this.docs.get(id) ?? null; } // Live children of a folder id ('' for the root, 'trash' for the trash), // folders first, then by name. children (parentId = ROOT_ID) { const out = []; for (const d of this.docs.values()) if (d.parent === parentId && !d.isDeleted) out.push(d); return out.sort((a, b) => (a.isFolder === b.isFolder ? cmpName(a, b) : a.isFolder ? -1 : 1)); } // Folders above a document, root-most first. ancestors (doc) { const out = []; const seen = new Set([doc.id]); let p = this.get(doc.parent); while (p && !seen.has(p.id)) { out.unshift(p); seen.add(p.id); p = this.get(p.parent); } return out; } // In the trash, directly or through a trashed ancestor. isTrashed (doc) { if (doc.isTrashed) return true; const anc = this.ancestors(doc); return anc.length ? anc[0].isTrashed : false; } path (doc) { if (doc.isRoot) return ''; if (doc.isTrash) return 'trash'; const parts = [...this.ancestors(doc), doc].map(d => d.name); return (this.isTrashed(doc) ? ['trash', ...parts] : parts).join('/'); } descendants (folder) { const out = []; const walk = (id) => { for (const c of this.children(id)) { out.push(c); if (c.isFolder) walk(c.id); } }; walk(folder.id); return out; } // Resolve "Folder/Sub/Name", "trash/Name", a UUID, "" (root) or "trash". // Returns null when nothing matches; throws AmbiguousPathError when a // segment matches several live items. resolve (spec) { if (spec == null || typeof spec === 'object') return spec ?? ROOT; const s = String(spec).trim().replace(/^\/+|\/+$/g, ''); if (s === '' || s === '.') return ROOT; if (UUID_RE.test(s)) return this.get(s.toLowerCase()); const segments = s.split('/').map(x => x.trim()).filter(x => x && x !== '.'); let current = ROOT; if (segments[0].toLowerCase() === 'trash') { segments.shift(); current = TRASH_FOLDER; if (!segments.length) return current; } for (let i = 0; i < segments.length; i++) { const seg = segments[i]; const last = i === segments.length - 1; const candidates = this.children(current.id).filter(d => last || d.isFolder); let matches = candidates.filter(d => d.name === seg); if (!matches.length) matches = candidates.filter(d => d.name.toLowerCase() === seg.toLowerCase()); if (!matches.length) return null; if (matches.length > 1) throw new AmbiguousPathError(segments.slice(0, i + 1).join('/'), matches); current = matches[0]; } return current; } } export class RemarkableCloud { // options: everything CloudApi takes, plus `concurrency` (parallel blob fetches). constructor (api, { concurrency = 8, log = null } = {}) { this.api = api; this.concurrency = concurrency; this.log = log ?? api.log ?? null; this.tree = new Tree(); } static open (options = {}) { return new RemarkableCloud(new CloudApi(options), options); } // ---- reading the tree ------------------------------------------------- // Re-read the root; only documents whose hash changed are fetched again. async refresh ({ force = false } = {}) { const root = await this.api.getRoot(); if (!force && this.tree.loaded && root.hash === this.tree.hash) return this.tree; const next = new Tree(); next.hash = root.hash; next.generation = root.generation; next.schemaVersion = root.schemaVersion; if (root.hash) { const { entries } = parseIndex((await this.api.getBlob(root.hash, 'root.docSchema')).toString('utf8')); await pmap(entries, this.concurrency, async (e) => { const prev = this.tree.get(e.name); next.docs.set(e.name, prev && prev.hash === e.hash ? prev : await this.loadDoc(e)); }); } next.loaded = true; this.tree = next; return next; } async loadDoc (entry) { const doc = new Doc(entry.name); doc.hash = entry.hash; doc.size = entry.size; const { entries } = parseIndex((await this.api.getBlob(entry.hash, `${entry.name}.docSchema`)).toString('utf8')); doc.files = entries.map(f => ({ name: f.name, hash: f.hash, size: f.size })); const meta = doc.file('.metadata'); if (meta) { try { doc.metadata = JSON.parse((await this.api.getBlob(meta.hash, meta.name)).toString('utf8')); } catch (err) { this.log?.(`unreadable metadata for ${doc.id}: ${err.message}`); } } return doc; } // Parsed `.content` (fetched once per document hash). async content (doc) { if (doc._content === undefined) { const f = doc.file('.content'); let parsed = {}; if (f) { const text = (await this.api.getBlob(f.hash, f.name)).toString('utf8').trim(); try { parsed = text ? JSON.parse(text) : {}; } catch { parsed = {}; } } doc._content = parsed; } return doc._content; } async blob (doc, name) { const f = doc.files.find(x => x.name === name); if (!f) throw new NotFoundError(`${name} is not part of ${doc.id}`); return this.api.getBlob(f.hash, f.name); } // Resolve a path/UUID/Doc to a document, refreshing first. async docOf (spec) { await this.refresh(); const d = this.tree.resolve(spec); if (!d) throw new NotFoundError(`no such document: ${spec}`); if (d.isRoot || d.isTrash) throw new CloudError(`${d.isRoot ? 'the root' : 'the trash'} is not a document`); return d; } async folderOf (spec) { await this.refresh(); const d = this.tree.resolve(spec); if (!d) throw new NotFoundError(`no such folder: ${spec}`); if (!d.isFolder) throw new CloudError(`${this.tree.path(d)} is not a folder`); return d; } async list (spec = ROOT) { const folder = await this.folderOf(spec); return this.tree.children(folder.id); } // ---- pages, download, export ------------------------------------------ // [{ id, file, data }] in reading order; `data` is null for pages that have // no `.rm` (unannotated pages of a PDF/EPUB). async pages (doc) { const content = await this.content(doc); let ids = pageIds(content); if (!ids.length) { ids = doc.files .filter(f => f.name.startsWith(`${doc.id}/`) && f.name.endsWith('.rm')) .map(f => basename(f.name, '.rm')) .sort(); } return pmap(ids, this.concurrency, async (id) => { const file = doc.files.find(f => f.name === `${doc.id}/${id}.rm`) ?? null; return { id, file, data: file ? await this.api.getBlob(file.hash, file.name) : null }; }); } // Write all of a document's files under `dir`, in the tablet's own layout // (`.metadata`, `.content`, `/.rm`, …). With `clean`, // files under `dir` that are not part of the document are removed. async download (doc, dir, { clean = false } = {}) { const written = []; for (const f of doc.files) { if (!f.name.startsWith(doc.id) || f.name.includes('..') || f.name.startsWith('/')) { throw new CloudError(`refusing to write suspicious file name ${f.name}`); } } await pmap(doc.files, this.concurrency, async (f) => { const data = await this.api.getBlob(f.hash, f.name); const target = join(dir, ...f.name.split('/')); mkdirSync(dirname(target), { recursive: true }); writeFileSync(target, data); written.push(target); }); if (clean && existsSync(dir)) { const keep = new Set(written); const walk = (d) => { for (const entry of readdirSync(d, { withFileTypes: true })) { const p = join(d, entry.name); if (entry.isDirectory()) { walk(p); if (!readdirSync(p).length) rmSync(p, { recursive: true, force: true }); } else if (!keep.has(p)) { rmSync(p, { force: true }); } } }; walk(dir); } return written.sort(); } // Convert the document's handwritten/typed pages. Returns { ext, pages, data } // where data is a string (markdown), a Buffer (pdf) or an array of strings // (svg, one per page); `data` is null/empty when there are no pages. async export (doc, format) { const pages = (await this.pages(doc)).filter(p => p.data); const buffers = pages.map(p => p.data); switch (format) { case 'markdown': case 'md': return { ext: 'md', pages: pages.length, data: buffers.map(b => rmToMarkdown(b)).filter(s => s.trim()).join('\n\n') }; case 'svg': return { ext: 'svg', pages: pages.length, data: buffers.map(b => rmToSvg(b)) }; case 'pdf': return { ext: 'pdf', pages: pages.length, data: buffers.length ? rmsToPdf(buffers) : null }; default: throw new CloudError(`unknown export format "${format}" (use ${EXPORT_FORMATS.join(', ')})`); } } // ---- writing ---------------------------------------------------------- // Run `mutate(tree)` against a fresh tree, then publish the resulting root. // If someone else published in between (HTTP 412), the tree is re-read and // `mutate` is run again, so it must be safe to repeat. async commit (mutate, { broadcast = true, attempts = 8 } = {}) { for (let attempt = 1; ; attempt++) { await this.refresh(); const result = await mutate(this.tree); const docs = [...this.tree.docs.values()].map(d => ({ id: d.id, hash: d.hash, subfiles: d.files.length, size: d.size })); const root = rootIndex(docs); if (root.hash === this.tree.hash) return result; await this.api.putBlob(root.hash, 'root.docSchema', Buffer.from(root.text)); try { const res = await this.api.putRoot(root.hash, this.tree.generation, broadcast); this.tree.hash = res.hash; this.tree.generation = res.generation; return result; } catch (err) { if (!(err instanceof GenerationConflictError) || attempt >= attempts) throw err; this.log?.(`root changed under us, retrying (${attempt}/${attempts})`); } } } replaceFile (doc, name, data) { const buf = Buffer.isBuffer(data) ? data : Buffer.from(data); const file = { name, hash: sha256(buf), size: buf.length, data: buf }; const i = doc.files.findIndex(f => f.name === name); if (i >= 0) doc.files[i] = file; else doc.files.push(file); doc._content = undefined; } // Upload pending file blobs and the document index; refresh doc.hash/size. async putDoc (doc) { for (const f of doc.files) { if (f.data) { await this.api.putBlob(f.hash, f.name, f.data); delete f.data; } } const idx = docIndex(doc.files); await this.api.putBlob(idx.hash, `${doc.id}.docSchema`, Buffer.from(idx.text)); doc.hash = idx.hash; doc.size = idx.size; } async setMetadata (doc, changes) { doc.metadata = updateMetadata(doc.metadata, changes); this.replaceFile(doc, `${doc.id}.metadata`, JSON.stringify(doc.metadata)); await this.putDoc(doc); return doc; } checkParent (tree, parentId) { if (parentId === ROOT_ID || parentId === TRASH) return; const p = tree.get(parentId); if (!p || !p.isFolder || p.isDeleted) throw new NotFoundError(`destination folder ${parentId} no longer exists`); } // files: [{ name: '.pdf' | '/.rm' …, data }] async createDocument ({ id = randomUUID(), name, parent = ROOT, type = DOCUMENT, files = [], content = {} }) { const folder = typeof parent === 'string' ? await this.folderOf(parent) : parent; const parentId = folder.id; if (!name) throw new CloudError('a document needs a name'); return this.commit(async (tree) => { this.checkParent(tree, parentId); const doc = new Doc(id); doc.metadata = newMetadata({ name, type, parent: parentId }); for (const f of files) this.replaceFile(doc, f.name, f.data); this.replaceFile(doc, `${id}.metadata`, JSON.stringify(doc.metadata)); this.replaceFile(doc, `${id}.content`, JSON.stringify(content)); await this.putDoc(doc); tree.docs.set(id, doc); return doc; }); } async createFolder (name, parent = ROOT) { return this.createDocument({ name, parent, type: COLLECTION, content: {} }); } // Create every missing folder along `path` (like mkdir -p); returns the last one. async mkdir (path, parent = ROOT) { let current = await this.folderOf(parent); const segments = String(path).split('/').map(s => s.trim()).filter(s => s && s !== '.'); for (const seg of segments) { const existing = this.tree.children(current.id).filter(d => d.isFolder && d.name === seg); if (existing.length > 1) throw new AmbiguousPathError(seg, existing); current = existing[0] ?? await this.createFolder(seg, current); } return current; } // A notebook made of v6 `.rm` page buffers. async uploadPages (pages, { parent = ROOT, name = 'Untitled', template = 'Blank' } = {}) { if (!pages.length) throw new CloudError('a notebook needs at least one page'); const id = randomUUID(); const ids = pages.map(() => randomUUID()); const authors = new Map(); for (const data of pages) for (const [index, uuid] of pageAuthors(data)) if (!authors.has(index)) authors.set(index, uuid); const files = pages.map((data, i) => ({ name: `${id}/${ids[i]}.rm`, data })); const content = notebookContent({ pageIds: ids, authors, template, sizeInBytes: pages.reduce((s, p) => s + p.length, 0), }); return this.createDocument({ id, name, parent, files, content }); } // A new notebook with one blank page. createNotebook ({ name, parent = ROOT, template = 'Blank', authorUuid = null } = {}) { return this.uploadPages([blankPage({ authorUuid })], { parent, name, template }); } // Upload a local file (path) or { data, kind, name }. PDFs and EPUBs become // documents; `.rm` pages become one-page notebooks; `.md`/`.txt` become // notebooks with the text typed in. async upload (source, { parent = ROOT, name = null, template } = {}) { let data, kind, baseName; if (typeof source === 'string') { data = readFileSync(source); kind = uploadKind(source); baseName = basename(source).replace(/\.[^.]+$/, ''); } else { ({ data, kind } = source); baseName = source.name ?? 'Untitled'; } if (!kind) throw new CloudError(`unsupported file type: ${typeof source === 'string' ? source : baseName} (use .pdf, .epub, .rm, .md or .txt)`); name = name || baseName; if (kind === 'pdf' || kind === 'epub') { const id = randomUUID(); return this.createDocument({ id, name, parent, files: [{ name: `${id}.${kind}`, data }], content: fileContent({ fileType: kind }) }); } const page = kind === 'rm' ? data : writeBlocks(simpleTextDocument(data.toString('utf8'))); return this.uploadPages([page], { parent, name, template }); } async rename (spec, name) { if (!name) throw new CloudError('a name is required'); const { id } = await this.docOf(spec); return this.commit(async (tree) => { const d = tree.get(id); if (!d) throw new NotFoundError(`document ${id} vanished`); return this.setMetadata(d, { visibleName: name }); }); } async move (spec, folderSpec = ROOT) { const doc = await this.docOf(spec); const folder = folderSpec === TRASH_FOLDER || folderSpec === TRASH ? TRASH_FOLDER : await this.folderOf(folderSpec); if (folder.id === doc.id || (doc.isFolder && !folder.isTrash && this.tree.ancestors(folder).some(a => a.id === doc.id))) { throw new CloudError('cannot move a folder into itself'); } const { id } = doc; return this.commit(async (tree) => { const d = tree.get(id); if (!d) throw new NotFoundError(`document ${id} vanished`); this.checkParent(tree, folder.id); return this.setMetadata(d, { parent: folder.id }); }); } trash (spec) { return this.move(spec, TRASH_FOLDER); } restore (spec, folderSpec = ROOT) { return this.move(spec, folderSpec); } // Remove a document (and, for a folder, everything in it) from the cloud // for good. Unlike trash, this cannot be undone. async purge (spec) { const { id } = await this.docOf(spec); return this.commit(async (tree) => { const d = tree.get(id); if (!d) return []; const victims = d.isFolder ? [d, ...tree.descendants(d)] : [d]; for (const v of victims) tree.docs.delete(v.id); return victims; }); } // ---- editing a document's files and pages ----------------------------- // Change a document's files and `.content` in one commit. `mutate` gets // { doc, content, put(name, data), remove(name), tree }; `content` is a copy // it may change, written back afterwards with the page count and size // brought up to date, and the metadata is bumped as the tablet does on an // edit. Returns the document. async editDocument (spec, mutate) { const { id } = await this.docOf(spec); return this.commit(async (tree) => { const d = tree.get(id); if (!d) throw new NotFoundError(`document ${id} vanished`); const content = structuredClone(await this.content(d)); const put = (name, data) => this.replaceFile(d, name, data); const remove = (name) => { d.files = d.files.filter(f => f.name !== name); }; await mutate({ doc: d, content, put, remove, tree }); if (content.cPages) content.pageCount = pageIds(content).length; if ('sizeInBytes' in content) { content.sizeInBytes = String(d.files.filter(f => f.name.startsWith(`${id}/`)).reduce((s, f) => s + (f.size || 0), 0)); } this.replaceFile(d, `${id}.content`, JSON.stringify(content)); d._content = content; await this.setMetadata(d, {}); return d; }); } // Store a page's `.rm` (and, when given, its PNG thumbnail), stamping the // page and recording its authors in the document. savePage (spec, pageId, data, { thumbnail = null } = {}) { return this.editDocument(spec, ({ doc, content, put }) => { const page = findPage(content, pageId); if (!page) throw new NotFoundError(`page ${pageId} is not in ${doc.id}`); page.modifed = timestamp(); registerAuthors(content, pageAuthors(data)); put(`${doc.id}/${pageId}.rm`, data); if (thumbnail) put(`${doc.id}.thumbnails/${pageId}.png`, thumbnail); }); } // Add a page after `after` (a page id; at the end when null), blank unless // `data` gives its `.rm`. Returns { doc, pageId }. async addPage (spec, { after = null, template = null, data = null, authorUuid = null } = {}) { const pageId = randomUUID(); const doc = await this.editDocument(spec, ({ doc, content, put }) => { if (!content.cPages) throw new CloudError(`${doc.id} has no page list yet; open it on the tablet once first`); const bytes = data ?? blankPage({ authorUuid }); const pages = content.cPages.pages ??= []; const ordered = pageIds(content); const pos = after ? ordered.indexOf(after) : ordered.length - 1; if (after && pos < 0) throw new NotFoundError(`page ${after} is not in ${doc.id}`); const prevId = pos >= 0 ? ordered[pos] : null; const nextId = ordered[pos + 1] ?? null; const idxOf = (id) => findPage(content, id)?.idx?.value ?? null; const idx = pageIndexBetween(prevId ? idxOf(prevId) : null, nextId ? idxOf(nextId) : null) ?? pageIndexAfter(idxOf(ordered[ordered.length - 1])); const tpl = template ?? (prevId ? findPage(content, prevId)?.template?.value : null) ?? 'Blank'; pages.push({ id: pageId, idx: { timestamp: '1:2', value: idx }, modifed: timestamp(), template: { timestamp: '1:1', value: tpl } }); registerAuthors(content, pageAuthors(bytes)); put(`${doc.id}/${pageId}.rm`, bytes); }); return { doc, pageId }; } // Delete a page: flagged deleted in the page list (so copies merge), its files dropped. removePage (spec, pageId) { return this.editDocument(spec, ({ doc, content, remove }) => { const page = findPage(content, pageId); if (!page) throw new NotFoundError(`page ${pageId} is not in ${doc.id}`); if (pageIds(content).length <= 1) throw new CloudError('a notebook keeps at least one page'); page.deleted = { timestamp: '1:1', value: 1 }; for (const f of [...doc.files]) { if (f.name.startsWith(`${doc.id}/${pageId}`) || f.name === `${doc.id}.thumbnails/${pageId}.png`) remove(f.name); } }); } // Set a page's template (the ruled, grid, … background the tablet draws). setPageTemplate (spec, pageId, template) { return this.editDocument(spec, ({ doc, content }) => { const page = findPage(content, pageId); if (!page) throw new NotFoundError(`page ${pageId} is not in ${doc.id}`); page.template = { timestamp: '1:1', value: template }; }); } // ---- mirror ----------------------------------------------------------- // Mirror the cloud into `dir`: every document as a directory of its raw // files (unless raw:false), plus converted copies for each of `formats`. // Only documents whose hash changed are downloaded again; documents that // vanished from the cloud are pruned (unless prune:false). Trashed // documents are skipped unless trash:true (they go under `trash/`). async sync (dir, { formats = [], raw = true, trash = false, prune = true, dryRun = false, onEvent = null } = {}) { for (const f of formats) if (!EXPORT_FORMATS.includes(f) && f !== 'md') throw new CloudError(`unknown export format "${f}"`); const emit = (type, info = {}) => onEvent?.({ type, ...info }); await this.refresh(); const tree = this.tree; const statePath = join(dir, SYNC_STATE_FILE); let state = { version: 1, docs: {} }; if (existsSync(statePath)) { try { const loaded = JSON.parse(readFileSync(statePath, 'utf8')); if (loaded.version === 1 && loaded.docs) state = loaded; } catch { /* start over */ } } const live = [...tree.docs.values()].filter(d => !d.isDeleted && (trash || !tree.isTrashed(d))); const liveIds = new Set(live.map(d => d.id)); // Local names: sanitised visible names, disambiguated among siblings. const siblings = new Map(); for (const d of live) { const key = `${d.parent}/${safeFileName(d.name).toLowerCase()}`; siblings.set(key, (siblings.get(key) ?? 0) + 1); } const localName = (d) => { const safe = safeFileName(d.name); return siblings.get(`${d.parent}/${safe.toLowerCase()}`) > 1 ? `${safe} [${d.id.slice(0, 8)}]` : safe; }; const relCache = new Map(); const relPath = (d) => { if (relCache.has(d.id)) return relCache.get(d.id); let parentPath = ''; if (d.parent === TRASH) parentPath = 'trash'; else if (d.parent && liveIds.has(d.parent)) parentPath = relPath(tree.get(d.parent)); else if (d.parent && tree.get(d.parent)) parentPath = relPath(tree.get(d.parent)); // trashed ancestor const rel = parentPath ? `${parentPath}/${localName(d)}` : localName(d); relCache.set(d.id, rel); return rel; }; const abs = (rel) => join(dir, ...rel.split('/')); const exportPaths = (rel, fmt, pages) => { if (fmt === 'markdown' || fmt === 'md') return [`${rel}.md`]; if (fmt === 'pdf') return [`${rel}.pdf`]; if (pages <= 1) return [`${rel}.svg`]; return Array.from({ length: pages }, (_, i) => `${rel}-p${String(i + 1).padStart(2, '0')}.svg`); }; const moveFile = (fromRel, toRel) => { const from = abs(fromRel); const to = abs(toRel); if (!existsSync(from) || from === to) return false; if (!dryRun) { mkdirSync(dirname(to), { recursive: true }); rmSync(to, { recursive: true, force: true }); renameSync(from, to); } return true; }; const summary = { downloaded: 0, exported: 0, moved: 0, pruned: 0, unchanged: 0, skipped: 0 }; const folders = live.filter(d => d.isFolder); if (!dryRun) { mkdirSync(dir, { recursive: true }); for (const f of folders) mkdirSync(abs(relPath(f)), { recursive: true }); } for (const doc of live.filter(d => !d.isFolder)) { const rel = relPath(doc); const prev = state.docs[doc.id]; const changed = !prev || prev.hash !== doc.hash; const moved = Boolean(prev && prev.path !== rel); const entry = { hash: doc.hash, path: rel, name: tree.path(doc), exports: {} }; if (moved) { if (raw && moveFile(prev.path, rel)) summary.moved++; for (const [fmt, paths] of Object.entries(prev.exports ?? {})) { const next = exportPaths(rel, fmt, paths.length); paths.forEach((p, i) => moveFile(p, next[i])); } emit('move', { doc, from: prev.path, to: rel }); } if (raw) { if (changed || !existsSync(abs(rel))) { if (!dryRun) await this.download(doc, abs(rel), { clean: true }); summary.downloaded++; emit('download', { doc, path: rel }); } } else if (prune && existsSync(abs(rel)) && prev?.raw !== false) { if (!dryRun) rmSync(abs(rel), { recursive: true, force: true }); } entry.raw = raw; for (const fmt of formats) { const key = fmt === 'md' ? 'markdown' : fmt; // undefined: never attempted; []: attempted, nothing to export. let previous = prev?.exports?.[key]; if (moved && previous?.length) previous = exportPaths(rel, key, previous.length); const stale = changed || previous === undefined || previous.some(p => !existsSync(abs(p))); if (!stale) { entry.exports[key] = previous; continue; } const result = await this.export(doc, key); const empty = !result.pages || (Array.isArray(result.data) ? !result.data.length : !result.data); for (const p of previous ?? []) if (!dryRun) rmSync(abs(p), { force: true }); if (empty) { entry.exports[key] = []; summary.skipped++; emit('skip', { doc, path: rel, format: key, reason: 'no handwritten or typed pages' }); continue; } const outs = exportPaths(rel, key, result.pages); if (!dryRun) { const datas = Array.isArray(result.data) ? result.data : [result.data]; outs.forEach((p, i) => { mkdirSync(dirname(abs(p)), { recursive: true }); writeFileSync(abs(p), datas[i]); }); } entry.exports[key] = outs; summary.exported++; emit('export', { doc, path: rel, format: key, files: outs }); } if (!changed && !moved) summary.unchanged++; state.docs[doc.id] = entry; } for (const [id, prev] of Object.entries(state.docs)) { if (liveIds.has(id)) continue; if (prune) { if (!dryRun) { rmSync(abs(prev.path), { recursive: true, force: true }); for (const paths of Object.values(prev.exports ?? {})) for (const p of paths) rmSync(abs(p), { force: true }); } summary.pruned++; emit('prune', { path: prev.path, name: prev.name }); } delete state.docs[id]; } if (prune && !dryRun && existsSync(dir)) { // Directories left behind by renamed or pruned folders. const wanted = new Set(folders.map(f => abs(relPath(f)))); const sweep = (d) => { for (const entry of readdirSync(d, { withFileTypes: true })) { if (!entry.isDirectory()) continue; const p = join(d, entry.name); sweep(p); if (!wanted.has(p) && !readdirSync(p).length) rmSync(p, { recursive: true, force: true }); } }; sweep(dir); } state.rootHash = tree.hash; state.generation = tree.generation; state.syncedAt = new Date().toISOString(); if (!dryRun) { mkdirSync(dir, { recursive: true }); writeFileSync(statePath, JSON.stringify(state, null, 2) + '\n'); } return summary; } }