#!/usr/bin/env node import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { extname, join, basename } from 'node:path'; import { createInterface } from 'node:readline/promises'; import { stdin, stdout } from 'node:process'; import { Command } from 'commander'; import { readBlocks, writeBlocks, simpleTextDocument } from '../lib/scene-stream.js'; import { rmVersion } from '../lib/legacy-lines.js'; import { rmToMarkdown } from '../lib/exporters/markdown.js'; import { rmToSvg } from '../lib/exporters/svg.js'; import { rmsToPdf } from '../lib/exporters/pdf.js'; import { RemarkableCloud, ROOT, TRASH_FOLDER, EXPORT_FORMATS, CONNECT_URL, describeToken, defaultConfigPath, defaultCacheDir, safeFileName, uploadKind, AuthError, } from '../lib/cloud/index.js'; const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url))); const program = new Command(); program .name('notable') .description([ 'Convert reMarkable .rm files, and read, write and mirror the documents in the reMarkable cloud.', '', 'Without a command, `convert` runs. Cloud commands need `notable login` first.', 'Cloud paths look like "Folder/Sub/Document" ("trash/Document" for the trash); a document UUID works too.', ].join('\n')) .version(version) .option('-v, --verbose', 'increase verbosity (repeat for more)', (_, prev) => prev + 1, 0) .option('--config ', `cloud credentials file (default: ${defaultConfigPath()})`) .option('--cache ', `blob cache directory (default: ${defaultCacheDir()})`) .option('--no-cache', 'do not cache cloud blobs on disk'); // ---------------------------------------------------------------- convert program .command('convert', { isDefault: true }) .description('Convert to/from reMarkable .rm files, reading versions 3, 5 and 6 and writing version 6 (FORMATs: rm, markdown, svg, pdf, blocks, blocks-data)') .option('-f, --from ', 'Format to convert from (default: guess from filename)') .option('-t, --to ', 'Format to convert to (default: guess from filename)') .option('-o, --output ', 'Output filename (default: write to stdout)') .argument('[input...]', 'Input files') .action((inputs, opts) => { let fromFmt = opts.from; let toFmt = opts.to; const outputFile = opts.output; if (!fromFmt) { if (!inputs.length) fail('Must specify input filename or --from'); fromFmt = guessFormat(inputs[0]); } if (!toFmt) { if (!outputFile) fail('Must specify --output or --to'); toFmt = guessFormat(outputFile); } if (fromFmt === 'rm') { const isBinary = ['pdf', 'rm'].includes(toFmt); let output = ''; let outputBuf = null; if (toFmt === 'pdf') { // all inputs become pages of a single PDF outputBuf = rmsToPdf(inputs.map(fn => readFileSync(fn))); } else { for (const fn of inputs) { const data = readFileSync(fn); if (toFmt === 'blocks' || toFmt === 'blocks-data') { output += pprintBlocks(data, toFmt !== 'blocks-data') + '\n'; } else if (toFmt === 'markdown') { output += rmToMarkdown(data); } else if (toFmt === 'svg') { output += rmToSvg(data); } else if (toFmt === 'rm') { // a version 6 page passes through; an older one comes out as version 6 outputBuf = rmVersion(data) === 6 ? data : writeBlocks(readBlocks(data)); } else { fail(`Unknown format ${toFmt}`); } } } const result = isBinary ? (outputBuf ?? Buffer.alloc(0)) : output; if (outputFile) { if (isBinary) writeFileSync(outputFile, result); else writeFileSync(outputFile, result, 'utf8'); } else { process.stdout.write(result); } } else if (fromFmt === 'markdown') { const text = inputs.map(fn => readFileSync(fn, 'utf8')).join(''); const buf = writeBlocks(simpleTextDocument(text)); if (outputFile) writeFileSync(outputFile, buf); else process.stdout.write(buf); } else { fail(`Source format ${fromFmt} not implemented`); } }); // ---------------------------------------------------------------- cloud: auth program .command('login') .description(`Pair with the reMarkable cloud using a one-time code from ${CONNECT_URL}`) .argument('[code]', 'the 8-character one-time code (prompted for if omitted)') .option('--host ', 'talk to a self-hosted cloud (e.g. rmfakecloud) instead of reMarkable\'s') .option('--device-desc ', 'how this device is described to the cloud (default: desktop-)') .action(wrap(async (code, opts, cmd) => { const cloud = openCloud(cmd); if (opts.host) cloud.api.config.host = opts.host.replace(/\/+$/, ''); if (!code) { console.log(`Get a one-time code at ${CONNECT_URL}`); const rl = createInterface({ input: stdin, output: stdout }); code = (await rl.question('Code: ')).trim(); rl.close(); } await cloud.api.login(code, opts.deviceDesc ? { deviceDesc: opts.deviceDesc } : {}); const who = describeToken(cloud.api.config.userToken); console.log(`Logged in${who.email ? ` as ${who.email}` : ''}. Credentials saved to ${cloud.api.configPath}`); })); program .command('logout') .description('Forget the stored cloud credentials') .action(wrap(async (opts, cmd) => { const cloud = openCloud(cmd); const path = cloud.api.configPath; cloud.api.logout(); console.log(`Logged out (${path} removed)`); })); program .command('whoami') .description('Show the account we are logged in as and check the connection') .option('--json', 'machine-readable output') .action(wrap(async (opts, cmd) => { const cloud = openCloud(cmd); if (!cloud.api.loggedIn) throw new AuthError('not logged in — run `notable login`'); await cloud.api.token(); const who = describeToken(cloud.api.config.userToken); const root = await cloud.api.getRoot(); const info = { ...who, hosts: cloud.api.hosts, config: cloud.api.configPath, cache: cloud.api.cacheDir, root }; if (opts.json) return console.log(JSON.stringify(info, null, 2)); console.log(`account: ${who.email ?? who.userId ?? '(unknown)'}${who.name ? ` (${who.name})` : ''}`); console.log(`device: ${who.deviceDesc ?? cloud.api.config.deviceDesc ?? '?'} ${who.deviceId ?? cloud.api.config.deviceId ?? ''}`); console.log(`token until: ${who.expires?.toISOString() ?? '?'}`); console.log(`sync host: ${cloud.api.hosts.syncHost}`); console.log(`root: ${root.hash ? `${root.hash.slice(0, 12)}… generation ${root.generation}` : 'empty account'}`); console.log(`credentials: ${cloud.api.configPath}`); })); // ---------------------------------------------------------------- cloud: reading program .command('ls') .description('List a cloud folder (the root by default; "trash" for the trash)') .argument('[path]', 'folder path or UUID', '') .option('-l, --long', 'show type, modification date and UUID') .option('-R, --recursive', 'descend into sub-folders') .option('--json', 'machine-readable output') .action(wrap(async (path, opts, cmd) => { const cloud = openCloud(cmd); const folder = await cloud.folderOf(path); const rows = []; const walk = (f, prefix) => { for (const d of cloud.tree.children(f.id)) { rows.push({ doc: d, label: prefix + d.name + (d.isFolder ? '/' : '') }); if (opts.recursive && d.isFolder) walk(d, `${prefix}${d.name}/`); } }; walk(folder, ''); if (opts.json) return console.log(JSON.stringify(rows.map(r => ({ ...r.doc.toJSON(), path: cloud.tree.path(r.doc) })), null, 2)); for (const { doc, label } of rows) { console.log(opts.long ? `${doc.isFolder ? 'd' : '-'} ${fmtDate(doc.lastModified)} ${doc.id} ${label}` : label); } })); program .command('tree') .description('Print the folder tree') .argument('[path]', 'folder path or UUID', '') .action(wrap(async (path, opts, cmd) => { const cloud = openCloud(cmd); const folder = await cloud.folderOf(path); console.log(folder.isRoot ? '/' : `${cloud.tree.path(folder)}/`); const walk = (f, indent) => { const kids = cloud.tree.children(f.id); kids.forEach((d, i) => { const last = i === kids.length - 1; console.log(`${indent}${last ? '└── ' : '├── '}${d.name}${d.isFolder ? '/' : ''}`); if (d.isFolder) walk(d, `${indent}${last ? ' ' : '│ '}`); }); }; walk(folder, ''); })); program .command('info') .description('Show a document\'s metadata, pages and files') .argument('', 'document path or UUID') .option('--json', 'machine-readable output') .action(wrap(async (path, opts, cmd) => { const cloud = openCloud(cmd); const doc = await cloud.docOf(path); const content = await cloud.content(doc); const pages = doc.isFolder ? [] : await cloud.pages(doc); if (opts.json) return console.log(JSON.stringify({ ...doc.toJSON(), path: cloud.tree.path(doc), content, pages: pages.map(p => ({ id: p.id, annotated: Boolean(p.file) })) }, null, 2)); console.log(`path: ${cloud.tree.path(doc)}`); console.log(`id: ${doc.id}`); console.log(`type: ${doc.isFolder ? 'folder' : content.fileType || 'document'}`); console.log(`modified: ${fmtDate(doc.lastModified)}`); console.log(`size: ${doc.size} bytes in ${doc.files.length} files`); if (!doc.isFolder) console.log(`pages: ${pages.length} (${pages.filter(p => p.file).length} with ink or typed text)`); if (doc.pinned) console.log('pinned: yes'); console.log('files:'); for (const f of doc.files) console.log(` ${f.hash.slice(0, 12)} ${String(f.size).padStart(9)} ${f.name}`); })); program .command('get') .description('Download documents: their raw files (tablet layout) or, with --to, a converted copy') .argument('', 'document paths or UUIDs') .option('-o, --output ', 'where to write (default: the current directory)') .option('-t, --to ', `convert to ${EXPORT_FORMATS.join(', ')} instead of downloading raw files`) .option('--stdout', 'with --to: write the converted document to stdout') .action(wrap(async (paths, opts, cmd) => { const cloud = openCloud(cmd); if (opts.stdout && !opts.to) fail('--stdout needs --to'); const singleFile = paths.length === 1 && opts.output && /\.(md|markdown|svg|pdf)$/i.test(opts.output); for (const path of paths) { const doc = await cloud.docOf(path); if (doc.isFolder) fail(`${cloud.tree.path(doc)} is a folder; get wants documents (try sync)`); if (!opts.to) { const dir = opts.output ?? '.'; const files = await cloud.download(doc, dir); console.log(`${cloud.tree.path(doc)} → ${dir}/ (${files.length} files)`); continue; } const result = await cloud.export(doc, opts.to); const datas = Array.isArray(result.data) ? result.data : [result.data]; if (!result.pages || datas.every(d => !d)) { console.error(`${cloud.tree.path(doc)}: no handwritten or typed pages to convert`); continue; } if (opts.stdout) { for (const d of datas) process.stdout.write(d); continue; } const dir = singleFile ? '.' : (opts.output ?? '.'); mkdirSync(dir, { recursive: true }); const base = singleFile ? opts.output.replace(/\.[^.]+$/, '') : join(dir, safeFileName(doc.name)); const names = datas.length === 1 ? [`${base}.${result.ext}`] : datas.map((_, i) => `${base}-p${String(i + 1).padStart(2, '0')}.${result.ext}`); names.forEach((n, i) => writeFileSync(n, datas[i])); console.log(`${cloud.tree.path(doc)} → ${names.join(', ')}`); } })); // ---------------------------------------------------------------- cloud: writing program .command('put') .description('Upload files: .pdf and .epub as documents, .rm pages and .md/.txt text as notebooks') .argument('', 'local files') .option('-d, --dest ', 'destination folder (default: the root; created if missing)') .option('-n, --name ', 'name on the tablet (default: the file name without extension)') .option('-p, --pages', 'combine all inputs as the pages of one notebook') .action(wrap(async (files, opts, cmd) => { const cloud = openCloud(cmd); let parent = ROOT; if (opts.dest) { await cloud.refresh(); parent = cloud.tree.resolve(opts.dest); if (!parent) { parent = await cloud.mkdir(opts.dest); console.log(`created folder ${cloud.tree.path(parent)}/`); } else if (!parent.isFolder) { fail(`${opts.dest} is not a folder`); } } if (opts.pages) { const pages = files.map(f => { const kind = uploadKind(f); if (kind === 'rm') return readFileSync(f); if (kind === 'text') return writeBlocks(simpleTextDocument(readFileSync(f, 'utf8'))); return fail(`${f}: only .rm and text files can be combined into a notebook`); }); const name = opts.name ?? basename(files[0]).replace(/\.[^.]+$/, ''); const doc = await cloud.uploadPages(pages, { parent, name }); console.log(`${cloud.tree.path(doc)} (${pages.length} pages, ${doc.id})`); return; } if (opts.name && files.length > 1) fail('--name only makes sense with a single file (or with --pages)'); for (const f of files) { const doc = await cloud.upload(f, { parent, name: opts.name }); console.log(`${cloud.tree.path(doc)} (${doc.id})`); } })); program .command('mkdir') .description('Create folders (and any missing parents)') .argument('', 'folder paths') .action(wrap(async (paths, opts, cmd) => { const cloud = openCloud(cmd); for (const p of paths) { const f = await cloud.mkdir(p); console.log(`${cloud.tree.path(f)}/ (${f.id})`); } })); program .command('mv') .description('Move documents or folders into a folder ("/" for the root)') .argument('', 'source paths followed by the destination folder') .action(wrap(async (args, opts, cmd) => { if (args.length < 2) fail('mv needs at least one source and a destination folder'); const cloud = openCloud(cmd); const dest = args.pop(); for (const src of args) { const doc = await cloud.move(src, dest); console.log(`${src} → ${cloud.tree.path(doc)}`); } })); program .command('rename') .description('Rename a document or folder') .argument('', 'document path or UUID') .argument('', 'the new name') .action(wrap(async (path, name, opts, cmd) => { const cloud = openCloud(cmd); const doc = await cloud.rename(path, name); console.log(`${path} → ${cloud.tree.path(doc)}`); })); program .command('rm') .description('Move documents or folders to the trash (or delete them for good with --purge)') .argument('', 'document paths or UUIDs') .option('--purge', 'remove from the cloud permanently instead of trashing (folders: recursively)') .action(wrap(async (paths, opts, cmd) => { const cloud = openCloud(cmd); for (const p of paths) { if (opts.purge) { const victims = await cloud.purge(p); console.log(`${p}: removed ${victims.length} item${victims.length === 1 ? '' : 's'} for good`); } else { const doc = await cloud.trash(p); console.log(`${p} → ${cloud.tree.path(doc)}`); } } })); program .command('restore') .description('Move documents out of the trash') .argument('', '"trash/Name" paths or UUIDs') .option('-d, --dest ', 'destination folder (default: the root)', '') .action(wrap(async (paths, opts, cmd) => { const cloud = openCloud(cmd); for (const p of paths) { const doc = await cloud.restore(p, opts.dest || ROOT); console.log(`${p} → ${cloud.tree.path(doc)}`); } })); program .command('sync') .description('Mirror the cloud into a local directory (only changed documents are fetched)') .argument('', 'the mirror directory') .option('-t, --to ', `also write converted copies: comma-separated ${EXPORT_FORMATS.join(', ')}`, (v) => v.split(',').map(s => s.trim()).filter(Boolean)) .option('--no-raw', 'skip the raw document files (only useful with --to)') .option('--trash', 'include trashed documents under trash/') .option('--no-prune', 'keep local copies of documents that vanished from the cloud') .option('-n, --dry-run', 'report what would change without touching the directory') .action(wrap(async (dir, opts, cmd) => { const cloud = openCloud(cmd); const formats = opts.to ?? []; if (!opts.raw && !formats.length) fail('--no-raw needs --to, otherwise there is nothing to write'); const summary = await cloud.sync(dir, { formats, raw: opts.raw, trash: opts.trash, prune: opts.prune, dryRun: opts.dryRun, onEvent: (e) => { const name = e.doc ? cloud.tree.path(e.doc) : e.name ?? e.path; if (e.type === 'download') console.log(`↓ ${name}`); else if (e.type === 'export') console.log(`→ ${e.files.join(', ')}`); else if (e.type === 'move') console.log(`↪ ${e.from} → ${e.to}`); else if (e.type === 'prune') console.log(`✗ ${name}`); else if (e.type === 'skip') console.log(`- ${name}: ${e.reason} (${e.format} skipped)`); }, }); console.log(`${opts.dryRun ? '(dry run) ' : ''}${summary.downloaded} downloaded, ${summary.exported} exported, ${summary.moved} moved, ${summary.pruned} pruned, ${summary.unchanged} unchanged`); })); program.parseAsync(process.argv).catch(err => { console.error(`error: ${err.message}`); process.exit(1); }); // ---------------------------------------------------------------- helpers function fail (message) { console.error(`error: ${message}`); process.exit(1); } function wrap (fn) { return async (...args) => { const cmd = args[args.length - 1]; try { await fn(...args); } catch (err) { const verbose = cmd?.optsWithGlobals?.().verbose; console.error(verbose ? err : `error: ${err.message}`); if (err instanceof AuthError && !/not logged in/.test(err.message)) console.error('hint: run `notable login` again'); process.exit(1); } }; } function openCloud (cmd) { const g = cmd.optsWithGlobals(); return RemarkableCloud.open({ configPath: g.config ?? defaultConfigPath(), cacheDir: g.cache === false ? null : (g.cache ?? defaultCacheDir()), log: g.verbose ? (m) => console.error(`[notable] ${m}`) : null, }); } function fmtDate (d) { if (!d) return ' '; const p = (n) => String(n).padStart(2, '0'); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`; } function guessFormat (p) { const ext = extname(p).toLowerCase(); if (ext === '.rm') return 'rm'; if (ext === '.svg') return 'svg'; if (ext === '.pdf') return 'pdf'; if (ext === '.md' || ext === '.markdown') return 'markdown'; return 'blocks'; } function pprintBlocks (data, withData = true) { const blocks = [...readBlocks(data)]; return blocks.map(b => { if (withData) return JSON.stringify(blockToObj(b), jsonReplacer, 2); const obj = blockToObj(b); return JSON.stringify({ type: obj.type }, null, 2); }).join('\n'); } function blockToObj (b) { return { type: b.constructor.name, ...Object.fromEntries( Object.entries(b).filter(([k]) => !k.startsWith('_')) )}; } function jsonReplacer (key, value) { if (typeof value === 'bigint') return value.toString(); if (Buffer.isBuffer(value)) return value.toString('hex'); if (value instanceof Map) return Object.fromEntries(value); return value; }