// Builders for the small JSON files that make up a document on the cloud: // `.metadata` (name, parent, type…) and `.content` (file type, pages…). export const DOCUMENT = 'DocumentType'; export const COLLECTION = 'CollectionType'; export const TRASH = 'trash'; export const ROOT_ID = ''; export const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; export function timestamp () { return String(Date.now()); } export function newMetadata ({ name, type = DOCUMENT, parent = ROOT_ID }) { const now = timestamp(); return { createdTime: now, deleted: false, lastModified: now, lastOpened: '', lastOpenedPage: 0, metadatamodified: false, modified: false, parent, pinned: false, synced: true, type, version: 0, visibleName: name, }; } // Apply `changes` to an existing metadata object the way the tablet expects // a change to look: bump the version, stamp lastModified, flag it modified. export function updateMetadata (meta, changes) { return { ...meta, ...changes, lastModified: timestamp(), version: (Number(meta.version) || 0) + 1, metadatamodified: true, }; } // `.content` for an uploaded PDF or EPUB; the tablet fills in the pages. export function fileContent ({ fileType }) { return { dummyDocument: false, extraMetadata: { LastPen: 'Finelinerv2', LastTool: 'Finelinerv2', LastFinelinerv2Size: '1' }, fileType, fontName: '', lastOpenedPage: 0, lineHeight: -1, margins: 180, orientation: 'portrait', pageCount: 0, pages: [], pageTags: [], redirectionPageMap: [], tags: [], textScale: 1, }; } // Fractional-index value for page i, in the "ba", "bb", … style the tablet uses. export function pageIndexValue (i) { const first = String.fromCharCode('b'.charCodeAt(0) + Math.floor(i / 26)); const second = String.fromCharCode('a'.charCodeAt(0) + (i % 26)); return first + second; } // A page index that sorts after `prev` ("bz" → "ca"); "ba" when there is none. export function pageIndexAfter (prev) { if (!prev) return pageIndexValue(0); const digits = [...prev].map(c => c.charCodeAt(0) - 97); for (let i = digits.length - 1; i >= 0; i--) { if (digits[i] < 25) { digits[i]++; return digits.map(d => String.fromCharCode(97 + d)).join(''); } digits[i] = 0; } return `${prev}a`; } // A page index that sorts between `a` and `b` (either may be null for "no // bound"); null when there is no room, which the tablet's own keys never // leave us with. export function pageIndexBetween (a, b) { if (!a && !b) return pageIndexValue(0); if (!b) return pageIndexAfter(a); const db = [...b].map(c => c.charCodeAt(0) - 97); if (!a) { // one step down from b, at the same length const out = [...db]; for (let i = out.length - 1; i >= 0; i--) { if (out[i] > 0) { out[i]--; return out.map(d => String.fromCharCode(97 + d)).join(''); } out[i] = 25; } return null; } if (a >= b) return null; const da = [...a].map(c => c.charCodeAt(0) - 97); const out = []; let i = 0; while (i < da.length && i < db.length && da[i] === db[i]) out.push(da[i++]); const lo = i < da.length ? da[i] : -1; const hi = i < db.length ? db[i] : 26; if (hi - lo >= 2) { out.push(lo + 1); } else { if (lo < 0) return null; // a is a prefix of b: nothing fits between them // keep a's digit, then go one past a's remainder out.push(lo); let j = i + 1; while (j < da.length && da[j] === 25) out.push(25), j++; if (j < da.length) out.push(da[j] + 1); else out.push(13); } return out.map(d => String.fromCharCode(97 + d)).join(''); } // The tablet writes author UUIDs into `.content` in standard byte order, // while `.rm` files keep the first three fields little-endian (which is how // AuthorIdsBlock spells them); this swaps between the two. It is its own inverse. export function swapUuidEndianness (uuid) { const h = String(uuid).replace(/-/g, ''); if (!/^[0-9a-f]{32}$/i.test(h)) return uuid; // not a UUID: nothing to swap const rev = (s) => s.match(/../g).reverse().join(''); return `${rev(h.slice(0, 8))}-${rev(h.slice(8, 12))}-${rev(h.slice(12, 16))}-${h.slice(16, 20)}-${h.slice(20)}`; } // The page entry of `id` in `content.cPages`, or null. export function findPage (content, id) { return content?.cPages?.pages?.find(p => p && p.id === id) ?? null; } // Record page authors (Map of index → UUID as an AuthorIdsBlock spells it) in // `content.cPages.uuids`, the document-wide author table. export function registerAuthors (content, authors) { if (!content.cPages) return content; const table = content.cPages.uuids ??= []; for (const [index, uuid] of authors) { const first = swapUuidEndianness(uuid); if (table.some(e => e.first === first)) continue; const second = table.some(e => e.second === index) ? Math.max(0, ...table.map(e => e.second)) + 1 : index; table.push({ first, second }); } table.sort((x, y) => x.second - y.second); return content; } // The document-wide author table as a Map of index → UUID in `.rm` spelling. export function contentAuthors (content) { return new Map((content?.cPages?.uuids ?? []).filter(e => e && e.first).map(e => [Number(e.second), swapUuidEndianness(e.first)])); } // `.content` for a notebook made of v6 `.rm` pages (software 3.x: formatVersion // 2, pages listed under `cPages`). `authors` is a Map of author index → UUID as // the pages' AuthorIdsBlocks spell them, so the tablet can map ids back to them // (`authorUuids`, an array, numbers them from 1). export function notebookContent ({ pageIds, authors = null, authorUuids = [], template = 'Blank', sizeInBytes = 0 }) { authors ??= authorUuids; const now = timestamp(); const content = { cPages: { lastOpened: { timestamp: '1:1', value: pageIds[0] ?? '' }, original: { timestamp: '0:0', value: -1 }, pages: pageIds.map((id, i) => ({ id, idx: { timestamp: '1:2', value: pageIndexValue(i) }, modifed: now, // sic: the tablet spells it this way template: { timestamp: '1:1', value: template }, })), uuids: [], }, coverPageNumber: 0, customZoomCenterX: 0, customZoomCenterY: 936, customZoomOrientation: 'portrait', customZoomPageHeight: 1872, customZoomPageWidth: 1404, customZoomScale: 1, documentMetadata: {}, extraMetadata: {}, fileType: 'notebook', fontName: '', formatVersion: 2, lineHeight: -1, orientation: 'portrait', pageCount: pageIds.length, pageTags: [], sizeInBytes: String(sizeInBytes), tags: [], textAlignment: 'justify', textScale: 1, zoomMode: 'bestFit', }; return registerAuthors(content, authors instanceof Map ? authors : new Map([...authors].map((u, i) => [i + 1, u]))); } // Ordered, non-deleted page ids of a document, from either the modern // `cPages` structure or the legacy `pages` array. export function pageIds (content) { const cpages = content?.cPages?.pages; if (Array.isArray(cpages)) { return cpages .filter(p => p && p.id && !(p.deleted && p.deleted.value)) .map(p => ({ id: p.id, idx: p.idx?.value ?? '' })) .sort((a, b) => (a.idx < b.idx ? -1 : a.idx > b.idx ? 1 : 0)) .map(p => p.id); } if (Array.isArray(content?.pages)) return content.pages.filter(Boolean); return []; } export function safeFileName (name) { const cleaned = String(name ?? '') .replace(/[/\\:*?"<>|\u0000-\u001f]/g, '_') .replace(/^\.+/, '_') .trim(); return (cleaned || 'untitled').slice(0, 150); } // What a local file would become on the cloud, by extension. export function uploadKind (filename) { const ext = String(filename).toLowerCase().match(/\.([a-z0-9]+)$/)?.[1]; if (ext === 'pdf' || ext === 'epub' || ext === 'rm') return ext; if (ext === 'md' || ext === 'markdown' || ext === 'txt') return 'text'; return null; }