@inhera/cli 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/bin/inhera.mjs +196 -3
- package/package.json +23 -7
package/README.md
CHANGED
|
@@ -10,6 +10,7 @@ inhera use "Harbor Family"
|
|
|
10
10
|
inhera assets list
|
|
11
11
|
inhera documents upload ~/Desktop/deed.pdf --name "Deed, Harbor Lane" --kind deed
|
|
12
12
|
inhera export --out harbor-$(date +%F).zip
|
|
13
|
+
inhera schedule install export ~/Backups/Inhera --at 02:30 # the nightly backup (the workspace owner approves it)
|
|
13
14
|
```
|
|
14
15
|
|
|
15
16
|
A key acts as you, with your role in each workspace, narrowed to the permissions you ticked when you made it, and optionally to one workspace. The vault is never reachable with a key.
|
|
@@ -19,4 +20,8 @@ A key acts as you, with your role in each workspace, narrowed to the permissions
|
|
|
19
20
|
- The saved key lives in `~/.config/inhera/config.json`, readable by you only.
|
|
20
21
|
- Exit codes: 0 ok, 1 error, 2 usage, 3 not signed in or key refused, 4 permission denied.
|
|
21
22
|
|
|
23
|
+
## The nightly job
|
|
24
|
+
|
|
25
|
+
`inhera schedule install export <folder> [--data-only] [--keep 14] [--at HH:MM] [--wait]` asks Inhera to save a nightly backup of the workspace (the same ZIP as `inhera export`, readable without Inhera) into that folder on this computer, keeping the newest `--keep` backups it made. `inhera schedule install documents <folder> [--kind statement] [--at HH:MM] [--wait]` uploads new files that appear in a folder as documents, each file once (same contents are recognised even if this computer forgets). Nothing is installed until the workspace owner approves the request in Settings → Scheduled jobs (they get a notification and an email naming the computer, the folder and the time). Once approved, the command writes the scheduler entry itself: a Task Scheduler task on Windows, a launchd agent on a Mac, a crontab line on Linux. The entry runs `inhera schedule run <id>`; it carries no key (the key stays in the config file, readable by you only), checks the job is still approved before every run, and removes itself if the owner stops the job. `schedule status`, `schedule test <id>` and `schedule remove` round it out. The key needs the "Install the nightly job" permission plus exports:read (backup) or documents:write (folder). Install with `npm install -g`, not `npx`, so the job survives.
|
|
26
|
+
|
|
22
27
|
Full guide and the REST endpoints: https://inhera.app/developers
|
package/bin/inhera.mjs
CHANGED
|
@@ -10,15 +10,20 @@
|
|
|
10
10
|
// inhera members list|invite
|
|
11
11
|
// inhera votes list|open|ballot
|
|
12
12
|
// inhera activity | export | api <METHOD> <path>
|
|
13
|
+
// inhera schedule install export|documents <folder> [--at HH:MM] [--wait] (the nightly job; the workspace owner approves it)
|
|
14
|
+
// inhera schedule status | remove [id] | run <id> | test <id>
|
|
13
15
|
//
|
|
14
16
|
// Exit codes: 0 ok, 1 error, 2 usage, 3 not signed in / key refused, 4 permission denied.
|
|
15
17
|
|
|
16
18
|
import { createInterface } from "node:readline";
|
|
17
|
-
import { mkdirSync, readFileSync, writeFileSync, existsSync, unlinkSync, chmodSync, statSync } from "node:fs";
|
|
18
|
-
import { homedir } from "node:os";
|
|
19
|
+
import { mkdirSync, readFileSync, writeFileSync, existsSync, unlinkSync, chmodSync, statSync, readdirSync, appendFileSync } from "node:fs";
|
|
20
|
+
import { homedir, hostname, userInfo, platform } from "node:os";
|
|
19
21
|
import { basename, join, resolve } from "node:path";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
import { createHash } from "node:crypto";
|
|
24
|
+
import { spawnSync } from "node:child_process";
|
|
20
25
|
|
|
21
|
-
const VERSION = "0.
|
|
26
|
+
const VERSION = "0.2.0";
|
|
22
27
|
const DEFAULT_API = "https://inhera.app";
|
|
23
28
|
const CONFIG_DIR = process.env.INHERA_CONFIG_DIR || join(homedir(), ".config", "inhera");
|
|
24
29
|
const CONFIG_FILE = join(CONFIG_DIR, "config.json");
|
|
@@ -304,6 +309,16 @@ const commands = {
|
|
|
304
309
|
out(typeof r === "string" ? r : JSON.stringify(r, null, 2));
|
|
305
310
|
},
|
|
306
311
|
|
|
312
|
+
// The nightly job. Nothing touches Task Scheduler, launchd or cron until the workspace owner has approved the job in Settings.
|
|
313
|
+
async schedule() {
|
|
314
|
+
const action = sub || "status";
|
|
315
|
+
if (action === "install") return scheduleInstall();
|
|
316
|
+
if (action === "status") return scheduleStatus();
|
|
317
|
+
if (action === "remove") return scheduleRemove(rest[0]);
|
|
318
|
+
if (action === "run" || action === "test") return scheduleRun(need(rest[0], "a job id (see inhera schedule status)"), action === "test");
|
|
319
|
+
fail(`Unknown: schedule ${action}. Try install, status, remove, run, test.`, 2);
|
|
320
|
+
},
|
|
321
|
+
|
|
307
322
|
version() { out(VERSION); },
|
|
308
323
|
help() {
|
|
309
324
|
out(`inhera ${VERSION}: the Inhera command line.
|
|
@@ -318,12 +333,190 @@ const commands = {
|
|
|
318
333
|
inhera activity [--limit N]
|
|
319
334
|
inhera export [--out file.zip] [--data-only]
|
|
320
335
|
inhera api <METHOD> <path> [--data '{"…":…}']
|
|
336
|
+
inhera schedule install export <folder> [--data-only] [--keep 14] [--at 02:30] [--wait] nightly backup into that folder; the owner approves it
|
|
337
|
+
inhera schedule install documents <folder> [--kind other] [--at 02:30] [--wait] new files in that folder uploaded nightly; the owner approves it
|
|
338
|
+
inhera schedule status | remove [id] | test <id>
|
|
321
339
|
|
|
322
340
|
Everywhere: --json for machine-readable output, --workspace <id|name> for one command, --api <url> for staging.
|
|
323
341
|
Keys: Account → API access & CLI at ${DEFAULT_API}. Guide: ${DEFAULT_API}/developers`);
|
|
324
342
|
},
|
|
325
343
|
};
|
|
326
344
|
|
|
345
|
+
// ---------------------------------------------------------------------------
|
|
346
|
+
// Scheduled jobs: helpers
|
|
347
|
+
// ---------------------------------------------------------------------------
|
|
348
|
+
|
|
349
|
+
const CLI_PATH = fileURLToPath(import.meta.url);
|
|
350
|
+
const SCHEDULER = process.env.INHERA_SCHEDULER || platform(); // darwin | win32 | linux | dry (tests: write the entry, touch nothing)
|
|
351
|
+
const OS_NAME = platform() === "darwin" ? "darwin" : platform() === "win32" ? "win32" : "linux";
|
|
352
|
+
const SCHEDULE_TYPES = ["export", "documents"];
|
|
353
|
+
const jobLog = (id) => join(CONFIG_DIR, `schedule-${id}.log`);
|
|
354
|
+
const logLine = (id, text) => { try { mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); appendFileSync(jobLog(id), `${new Date().toISOString()} ${text}\n`, { mode: 0o600 }); } catch { /* best effort */ } };
|
|
355
|
+
const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
|
|
356
|
+
const parseAt = (v) => { const m = /^(\d{1,2}):(\d{2})$/.exec(String(v || "").trim()); if (!m || Number(m[1]) > 23 || Number(m[2]) > 59) fail("--at takes a 24-hour time like 02:30 or 23:15.", 2); return { hour: Number(m[1]), minute: Number(m[2]) }; };
|
|
357
|
+
const runningFromNpx = () => /[\\/]_npx[\\/]/.test(CLI_PATH);
|
|
358
|
+
const scheduledCommand = (id) => [process.execPath, CLI_PATH, "schedule", "run", id];
|
|
359
|
+
const q = (s) => `"${String(s).replace(/"/g, '\\"')}"`;
|
|
360
|
+
const hhmm = (j) => `${String(j.hour).padStart(2, "0")}:${String(j.minute).padStart(2, "0")}`;
|
|
361
|
+
|
|
362
|
+
/** Writes the OS scheduler entry for an approved job. Returns a short description of what was written. */
|
|
363
|
+
function installEntry(job) {
|
|
364
|
+
const id = job.id; const [node, cli] = scheduledCommand(id); const log = jobLog(id);
|
|
365
|
+
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
|
366
|
+
if (SCHEDULER === "dry") {
|
|
367
|
+
writeFileSync(join(CONFIG_DIR, `scheduler-${id}.txt`), `dry: ${OS_NAME} ${hhmm(job)} ${scheduledCommand(id).join(" ")}\n`, { mode: 0o600 });
|
|
368
|
+
return `dry run: entry written to ${join(CONFIG_DIR, `scheduler-${id}.txt`)} (nothing scheduled)`;
|
|
369
|
+
}
|
|
370
|
+
if (SCHEDULER === "darwin") {
|
|
371
|
+
const dir = join(homedir(), "Library", "LaunchAgents"); mkdirSync(dir, { recursive: true });
|
|
372
|
+
const plist = join(dir, `app.inhera.job.${id}.plist`);
|
|
373
|
+
const esc = (t) => String(t).replace(/&/g, "&").replace(/</g, "<");
|
|
374
|
+
writeFileSync(plist, `<?xml version="1.0" encoding="UTF-8"?>
|
|
375
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
376
|
+
<plist version="1.0"><dict>
|
|
377
|
+
<key>Label</key><string>app.inhera.job.${id}</string>
|
|
378
|
+
<key>ProgramArguments</key><array>${scheduledCommand(id).map((a) => `<string>${esc(a)}</string>`).join("")}</array>
|
|
379
|
+
<key>StartCalendarInterval</key><dict><key>Hour</key><integer>${job.hour}</integer><key>Minute</key><integer>${job.minute}</integer></dict>
|
|
380
|
+
<key>StandardOutPath</key><string>${esc(log)}</string><key>StandardErrorPath</key><string>${esc(log)}</string>
|
|
381
|
+
<key>RunAtLoad</key><false/>
|
|
382
|
+
</dict></plist>
|
|
383
|
+
`, { mode: 0o644 });
|
|
384
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : 501;
|
|
385
|
+
spawnSync("launchctl", ["bootout", `gui/${uid}`, plist], { stdio: "ignore" });
|
|
386
|
+
const r = spawnSync("launchctl", ["bootstrap", `gui/${uid}`, plist], { encoding: "utf8" });
|
|
387
|
+
if (r.status !== 0) { const r2 = spawnSync("launchctl", ["load", "-w", plist], { encoding: "utf8" }); if (r2.status !== 0) fail(`launchd refused the job: ${(r.stderr || r2.stderr || "").trim()}`); }
|
|
388
|
+
return `launchd agent ${plist} (runs daily, catches up after sleep; log: ${log})`;
|
|
389
|
+
}
|
|
390
|
+
if (SCHEDULER === "win32") {
|
|
391
|
+
const name = `Inhera job ${id}`; const st = hhmm(job);
|
|
392
|
+
const r = spawnSync("schtasks", ["/Create", "/F", "/SC", "DAILY", "/ST", st, "/TN", name, "/TR", `${q(node)} ${q(cli)} schedule run ${id}`], { encoding: "utf8" });
|
|
393
|
+
if (r.status !== 0) fail(`Task Scheduler refused the job: ${(r.stderr || r.stdout || "").trim()}`);
|
|
394
|
+
return `Task Scheduler task "${name}" at ${st} (log: ${log})`;
|
|
395
|
+
}
|
|
396
|
+
// linux and anything else: the user's crontab
|
|
397
|
+
const marker = `# inhera:${id}`;
|
|
398
|
+
const current = spawnSync("crontab", ["-l"], { encoding: "utf8" }); const lines = (current.status === 0 ? current.stdout : "").split("\n").filter((l) => l.trim() && !l.includes(marker));
|
|
399
|
+
lines.push(`${job.minute} ${job.hour} * * * ${q(node)} ${q(cli)} schedule run ${id} >> ${q(log)} 2>&1 ${marker}`);
|
|
400
|
+
const w = spawnSync("crontab", ["-"], { input: lines.join("\n") + "\n", encoding: "utf8" });
|
|
401
|
+
if (w.status !== 0) fail(`crontab refused the job: ${(w.stderr || "").trim()}`);
|
|
402
|
+
return `crontab entry (${job.minute} ${job.hour} * * *; log: ${log})`;
|
|
403
|
+
}
|
|
404
|
+
function removeEntry(id) {
|
|
405
|
+
if (SCHEDULER === "dry") { const f = join(CONFIG_DIR, `scheduler-${id}.txt`); if (existsSync(f)) unlinkSync(f); return; }
|
|
406
|
+
if (SCHEDULER === "darwin") {
|
|
407
|
+
const plist = join(homedir(), "Library", "LaunchAgents", `app.inhera.job.${id}.plist`); const uid = typeof process.getuid === "function" ? process.getuid() : 501;
|
|
408
|
+
spawnSync("launchctl", ["bootout", `gui/${uid}`, plist], { stdio: "ignore" }); if (existsSync(plist)) unlinkSync(plist); return;
|
|
409
|
+
}
|
|
410
|
+
if (SCHEDULER === "win32") { spawnSync("schtasks", ["/Delete", "/F", "/TN", `Inhera job ${id}`], { stdio: "ignore" }); return; }
|
|
411
|
+
const marker = `# inhera:${id}`; const current = spawnSync("crontab", ["-l"], { encoding: "utf8" });
|
|
412
|
+
if (current.status === 0) { const lines = current.stdout.split("\n").filter((l) => l.trim() && !l.includes(marker)); spawnSync("crontab", ["-"], { input: lines.join("\n") + (lines.length ? "\n" : ""), encoding: "utf8" }); }
|
|
413
|
+
}
|
|
414
|
+
const savedJobs = () => (config.schedules && typeof config.schedules === "object" ? config.schedules : {});
|
|
415
|
+
const saveJob = (job, extra = {}) => { const all = savedJobs(); all[job.id] = { workspaceId: job.workspaceId, type: job.type, path: job.path, options: job.options, hour: job.hour, minute: job.minute, ...(all[job.id] || {}), ...extra }; writeConfig({ ...config, schedules: all }); };
|
|
416
|
+
const forgetJob = (id) => { const all = savedJobs(); delete all[id]; writeConfig({ ...config, schedules: all }); };
|
|
417
|
+
const statusLine = (j) => (j.status === "approved" ? (j.installedAt ? "approved, installed" : "approved, not installed yet") : j.status);
|
|
418
|
+
const jobUrl = (job, tail = "") => `/api/workspaces/${job.workspaceId}/schedules/${job.id}${tail}`;
|
|
419
|
+
/** The file names a backup job writes, so --keep only ever deletes its own. */
|
|
420
|
+
const backupName = (job, date) => `inhera-backup-${job.workspaceId.slice(0, 8)}-${date}${job.options?.dataOnly ? "-data" : ""}.zip`;
|
|
421
|
+
const backupPattern = (job) => new RegExp(`^inhera-backup-${job.workspaceId.slice(0, 8)}-\\d{4}-\\d{2}-\\d{2}(?:-\\d{6})?${job.options?.dataOnly ? "-data" : ""}\\.zip$`);
|
|
422
|
+
|
|
423
|
+
async function scheduleInstall() {
|
|
424
|
+
const type = need(rest[0], `a job type (${SCHEDULE_TYPES.join(" or ")})`); if (!SCHEDULE_TYPES.includes(type)) fail(`The type is one of ${SCHEDULE_TYPES.join(", ")}.`, 2);
|
|
425
|
+
const target = resolve(need(rest[1], type === "export" ? "the folder to save backups into" : "the folder to watch"));
|
|
426
|
+
if (!existsSync(target) || !statSync(target).isDirectory()) fail(`${target} isn't a folder on this computer. Make it first.`, 2);
|
|
427
|
+
if (runningFromNpx() && !flags["allow-npx"]) fail("Install the command line first so the job survives: npm install -g @inhera/cli (the npx copy can be cleaned away).", 2);
|
|
428
|
+
const { hour, minute } = parseAt(flag("at", "02:30"));
|
|
429
|
+
const options = type === "export" ? { dataOnly: Boolean(flags["data-only"]), keep: Number(flag("keep", "14")) } : { kind: flag("kind", "other") };
|
|
430
|
+
if (type === "export" && !(Number.isInteger(options.keep) && options.keep >= 1 && options.keep <= 365)) fail("--keep is how many backups to keep, 1 to 365.", 2);
|
|
431
|
+
const me = await call("GET", "/api/me");
|
|
432
|
+
if (!me.user.apiKey) fail("Scheduled jobs need an API key sign-in (inhera login --key inh_live_…).", 3);
|
|
433
|
+
const scopes = me.user.apiKey.scopes || [];
|
|
434
|
+
if (!scopes.includes("schedule:write")) fail("This key can't install the nightly job. Make a key with “Install the nightly job” ticked (Account → API access & CLI).", 4);
|
|
435
|
+
if (type === "export" && !scopes.includes("exports:read")) fail("A nightly backup needs the exports:read permission on this key as well.", 4);
|
|
436
|
+
if (type === "documents" && !scopes.includes("documents:write")) fail("A watched folder needs the documents:write permission on this key as well.", 4);
|
|
437
|
+
const wid = await workspaceId();
|
|
438
|
+
const body = { type, path: target, options, hour, minute, machine: hostname().slice(0, 80), os: OS_NAME, username: (() => { try { return userInfo().username; } catch { return ""; } })().slice(0, 80), cliVersion: VERSION };
|
|
439
|
+
const r = await call("POST", `/api/workspaces/${wid}/schedules`, { body });
|
|
440
|
+
let job = r.job;
|
|
441
|
+
if (job.status === "pending") {
|
|
442
|
+
out(`Asked the owner to approve: ${type === "export" ? `a ${options.dataOnly ? "data-only " : ""}backup into ${target}` : `uploading new files from ${target}`} every day at ${hhmm(job)} from ${body.machine}.`);
|
|
443
|
+
out(`Nothing is installed until it's approved in Settings → Scheduled jobs (${r.approveUrl}).`);
|
|
444
|
+
if (!flags.wait) { saveJob(job); emit({ job, installed: false }, () => out("Run this same command again after the approval, or add --wait to keep checking for up to 15 minutes.")); return; }
|
|
445
|
+
const until = Date.now() + 15 * 60_000;
|
|
446
|
+
while (Date.now() < until && job.status === "pending") { await new Promise((ok) => setTimeout(ok, 10_000)); job = (await call("GET", jobUrl(job))).job; }
|
|
447
|
+
}
|
|
448
|
+
if (job.status !== "approved") { saveJob(job); fail(job.status === "pending" ? "Still waiting for the owner's approval. Run the command again once it's approved." : `The owner ${job.status === "revoked" ? "stopped" : job.status} this job; nothing was installed.`, job.status === "pending" ? 1 : 4); }
|
|
449
|
+
const where = installEntry(job);
|
|
450
|
+
await call("POST", jobUrl(job, "/installed"), { body: {} });
|
|
451
|
+
saveJob(job, { installedAt: new Date().toISOString() });
|
|
452
|
+
logLine(job.id, `installed: ${where}`);
|
|
453
|
+
emit({ job, installed: true, where }, () => { out(`Installed: ${where}.`); out(`Every day at ${hhmm(job)} this computer ${type === "export" ? "saves a backup of the workspace" : "uploads new files from the folder"}. Try it now: inhera schedule test ${job.id}`); });
|
|
454
|
+
}
|
|
455
|
+
async function scheduleStatus() {
|
|
456
|
+
const saved = savedJobs(); const jobs = [];
|
|
457
|
+
for (const [id, s] of Object.entries(saved)) { try { jobs.push((await call("GET", `/api/workspaces/${s.workspaceId}/schedules/${id}`)).job); } catch (e) { jobs.push({ id, status: `unknown (${e.message})`, type: s.type, path: s.path, hour: s.hour, minute: s.minute }); } }
|
|
458
|
+
emit({ jobs }, () => { if (!jobs.length) { out("No scheduled jobs on this computer. Set one up: inhera schedule install export ~/Backups/Inhera --at 02:30"); return; } table(jobs, [["id", (j) => j.id.slice(0, 8)], ["type", (j) => j.type], ["folder", (j) => j.path], ["at", (j) => hhmm(j)], ["status", (j) => statusLine(j)], ["last run", (j) => (j.lastRunAt ? `${j.lastOutcome} ${j.lastRunAt}` : "")]]); });
|
|
459
|
+
}
|
|
460
|
+
async function scheduleRemove(idArg) {
|
|
461
|
+
const ids = Object.keys(savedJobs()); const id = idArg ? ids.find((x) => x === idArg || x.startsWith(idArg)) ?? idArg : ids.length === 1 ? ids[0] : null;
|
|
462
|
+
if (!id) fail(ids.length ? `Say which job: ${ids.join(", ")}` : "No scheduled jobs on this computer.", 2);
|
|
463
|
+
removeEntry(id); forgetJob(id); logLine(id, "removed from this computer");
|
|
464
|
+
emit({ ok: true, id }, () => out(`Removed the scheduled job ${id.slice(0, 8)} from this computer. The owner can also stop it in Settings → Scheduled jobs.`));
|
|
465
|
+
}
|
|
466
|
+
async function scheduleRun(idArg, verbose) {
|
|
467
|
+
const saved = savedJobs(); const id = Object.keys(saved).find((x) => x === idArg || x.startsWith(idArg)) ?? idArg;
|
|
468
|
+
const s = saved[id]; if (!s) fail(`No job ${idArg} on this computer. See inhera schedule status.`, 2);
|
|
469
|
+
const url = (tail = "") => `/api/workspaces/${s.workspaceId}/schedules/${id}${tail}`;
|
|
470
|
+
let job;
|
|
471
|
+
try { job = (await call("GET", url())).job; }
|
|
472
|
+
catch (e) { logLine(id, `could not check the job: ${e.message}`); if (e.code === 3 || e.code === 4) { removeEntry(id); forgetJob(id); logLine(id, "key refused: removed the scheduled entry"); } throw e; }
|
|
473
|
+
if (job.status !== "approved") { removeEntry(id); forgetJob(id); logLine(id, `job is ${job.status}: removed the scheduled entry`); fail(`This job is ${job.status === "revoked" ? "stopped" : job.status}; the scheduled entry was removed from this computer.`, 4); }
|
|
474
|
+
const report = (outcome, message, extra = {}) => call("POST", url("/ping"), { body: { outcome, message: String(message).slice(0, 500), ...extra } }).catch((e) => { logLine(id, `report failed: ${e.message}`); if (e.message && /stopped|revoked|declined/.test(e.message)) { removeEntry(id); forgetJob(id); } });
|
|
475
|
+
const W = `/api/workspaces/${job.workspaceId}`;
|
|
476
|
+
try {
|
|
477
|
+
if (!existsSync(job.path) || !statSync(job.path).isDirectory()) throw new CliError(`The folder isn't there: ${job.path}`, 2);
|
|
478
|
+
if (job.type === "export") {
|
|
479
|
+
const res = await call("GET", `${W}/export${job.options?.dataOnly ? "?files=0" : ""}`, { raw: true });
|
|
480
|
+
const date = new Date().toISOString().slice(0, 10);
|
|
481
|
+
let target = join(job.path, backupName(job, date));
|
|
482
|
+
if (existsSync(target)) target = join(job.path, backupName(job, `${date}-${new Date().toISOString().slice(11, 19).replace(/:/g, "")}`));
|
|
483
|
+
writeFileSync(target, Buffer.from(await res.arrayBuffer()), { mode: 0o600 });
|
|
484
|
+
const size = statSync(target).size;
|
|
485
|
+
// Keep the newest N backups this job made; never touch anything else in the folder.
|
|
486
|
+
const mine = readdirSync(job.path).filter((f) => backupPattern(job).test(f)).map((f) => ({ f, t: statSync(join(job.path, f)).mtimeMs })).sort((a, b) => b.t - a.t);
|
|
487
|
+
const pruned = mine.slice(job.options?.keep || 14); for (const p of pruned) { try { unlinkSync(join(job.path, p.f)); } catch { /* leave it */ } }
|
|
488
|
+
const message = `${basename(target)} saved (${(size / 1024 / 1024).toFixed(1)} MB)${pruned.length ? `, ${pruned.length} older backup${pruned.length === 1 ? "" : "s"} removed` : ""}`;
|
|
489
|
+
await report("ok", message, { file: basename(target) });
|
|
490
|
+
logLine(id, message);
|
|
491
|
+
emit({ outcome: "ok", file: target, size, pruned: pruned.length }, () => out(`Saved ${target} (${(size / 1024 / 1024).toFixed(1)} MB).${pruned.length ? ` Removed ${pruned.length} older backup(s), keeping ${job.options?.keep || 14}.` : ""}`));
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
// documents: upload what's new in the folder (top level, no hidden files), skipping contents already in the workspace
|
|
495
|
+
const files = readdirSync(job.path).filter((f) => !f.startsWith(".")).map((f) => join(job.path, f)).filter((f) => { try { return statSync(f).isFile(); } catch { return false; } });
|
|
496
|
+
const existing = new Set(((await call("GET", `${W}/documents`)).documents || []).map((d) => d.sha256).filter(Boolean));
|
|
497
|
+
const ledgerFile = join(CONFIG_DIR, `schedule-${id}-sent.json`); const ledger = (() => { try { return JSON.parse(readFileSync(ledgerFile, "utf8")); } catch { return {}; } })();
|
|
498
|
+
let uploaded = 0, skipped = 0, tooBig = 0; const names = [];
|
|
499
|
+
for (const f of files) {
|
|
500
|
+
if (uploaded >= 50) break; // the rest goes tomorrow night
|
|
501
|
+
const st = statSync(f); if (st.size > 200 * 1024 * 1024) { tooBig++; logLine(id, `skipped ${basename(f)}: over 200 MB`); continue; }
|
|
502
|
+
const buf = readFileSync(f); const hash = sha256(buf);
|
|
503
|
+
if (existing.has(hash) || ledger[hash]) { skipped++; continue; }
|
|
504
|
+
const form = new FormData(); form.append("file", new Blob([buf], { type: mimeOf(f) }), basename(f)); form.append("kind", job.options?.kind || "other");
|
|
505
|
+
const r = await call("POST", `${W}/documents`, { form });
|
|
506
|
+
ledger[hash] = { name: basename(f), at: new Date().toISOString(), documentId: r.document?.id }; writeFileSync(ledgerFile, JSON.stringify(ledger), { mode: 0o600 });
|
|
507
|
+
uploaded++; names.push(basename(f)); logLine(id, `uploaded ${basename(f)}`);
|
|
508
|
+
}
|
|
509
|
+
if (!uploaded) { const why = files.length ? `${skipped} file(s) already in the workspace${tooBig ? `, ${tooBig} over 200 MB` : ""}; nothing new.` : "The folder is empty."; await report("skipped", why); emit({ outcome: "skipped", skipped, tooBig }, () => out(why)); return; }
|
|
510
|
+
const message = `${uploaded} file${uploaded === 1 ? "" : "s"} uploaded (${names.slice(0, 5).join(", ")}${names.length > 5 ? ", …" : ""})${skipped ? `, ${skipped} already there` : ""}${tooBig ? `, ${tooBig} over 200 MB skipped` : ""}`;
|
|
511
|
+
await report("ok", message, { file: names[0] });
|
|
512
|
+
emit({ outcome: "ok", uploaded, skipped, tooBig, files: names }, () => out(message + "."));
|
|
513
|
+
} catch (e) {
|
|
514
|
+
logLine(id, `failed: ${e.message}`);
|
|
515
|
+
await report("failed", e.message);
|
|
516
|
+
if (verbose) throw e; else fail(e.message, e instanceof CliError ? e.code : 1);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
327
520
|
// ---------------------------------------------------------------------------
|
|
328
521
|
|
|
329
522
|
try {
|
package/package.json
CHANGED
|
@@ -1,13 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inhera/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "The Inhera command line: workspaces, assets, documents, contracts, members, votes, activity and exports from a terminal or a script, behind an API key you make in your account.",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "The Inhera command line: workspaces, assets, documents, contracts, members, votes, activity and exports from a terminal or a script, behind an API key you make in your account; plus a nightly backup or watched folder the workspace owner approves.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
|
-
"bin": {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
"
|
|
7
|
+
"bin": {
|
|
8
|
+
"inhera": "bin/inhera.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"bin",
|
|
12
|
+
"README.md"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"inhera",
|
|
19
|
+
"estate",
|
|
20
|
+
"family-office",
|
|
21
|
+
"cli"
|
|
22
|
+
],
|
|
11
23
|
"homepage": "https://inhera.app/developers",
|
|
12
|
-
"repository": {
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "https://github.com/Inhera-App/Inhera-App",
|
|
27
|
+
"directory": "cli"
|
|
28
|
+
}
|
|
13
29
|
}
|