// AN ITEM OF ANOTHER PROJECT, INTO A TAKE (slice C of "the apps do the work",
// 4 Nov; it replaces mid-assemble's sources.json and the hand links):
//
// umtool take
--id --import-item :[,…] [--import-item …]
// [--after | --before ] [--as ] [--dry-run] [--json]
//
// The entry is CLONED from the source project's manifest as it is now -- its
// card, its context, its knobs, its narration with its takes and its pick --
// into take 's timeline (its patch, takeEdit.mjs editTakeManifest: one undo
// point of the take's, `umtool timeline
--take undo`). The source
// project is only read.
's manifest is never touched.
//
// THE FILES IT NAMES come too, HARD-LINKED into
's dir at the same relative
// path, so the take's render (and the lint) finds them beside
's manifest:
// every string of the entry that is a project-relative path to a file of the
// source (a narration take, its parts' cache files, an attachment, a context
// post's media), a narration take's sidecars (`take-.*` beside it: its parts
// meta), and the picture of each author it draws that the take has none for
// (the source's `postAvatars`, added to the take's).
//
// the path free in
linked (copied when the two are on other filesystems)
// the same file there (inode or bytes) left as it is
// ANOTHER file there linked under imports// instead, and the
// clone names that path (never written over)
// a directory of
that leads out of refused: a link there would write into somebody else's
// it (a symlink) tree
//
// PLACEMENT: --after/--before an entry of the take; several items keep the
// order they are named in, one after the other. Without either: by the post's
// date when the take's posts are in date order (each before the first post
// that is later), else at the end.
//
// AGAIN: an item already in the take (by its id, or --as's) is UPDATED in place
// from the source as it is now (its files linked again as above) -- moved only
// when --after/--before is given -- and an update that changes nothing writes
// nothing (`unchanged`): re-running an import is safe.
import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";
import { copyFile, link, lstat, mkdir, readFile, readdir, realpath, stat } from "node:fs/promises";
import path from "node:path";
import { handleKey } from "umtool-report-to-video/post-avatars";
import { applyStructural, editDraftStructure, manifestToken } from "./manifest.mjs";
import { editTakeManifest, takeToken } from "./takeEdit.mjs";
import { resolveTakeManifest } from "./takeManifest.mjs";
export const IMPORTS_DIR = "imports";
export class ImportRefused extends Error {
/** @param {string} message */
constructor(message) {
super(message);
this.name = "ImportRefused";
}
}
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
const clone = (v) => JSON.parse(JSON.stringify(v));
/**
* `:[,…]` → `{ project, items }` (the LAST colon splits: a project id has slashes, never a
* colon). null when it is not that shape.
* @param {string} ref
*/
export function parseImportRef(ref) {
const s = String(ref ?? "");
const i = s.lastIndexOf(":");
if (i <= 0 || i === s.length - 1) return null;
const items = s.slice(i + 1).split(",").map((x) => x.trim()).filter(Boolean);
return items.length ? { project: s.slice(0, i), items } : null;
}
/**
* The argv of `umtool timeline import-item …` for a page's ask (POST /api/report/takes/tools, op
* "import" with no take), every word CHECKED: the refs are split on whitespace, and a word that starts with "-" is
* refused -- a flag smuggled in the refs ("p:1 --take t1" would take the take-patch path, "--as x" rename the
* item) -- as is any word that is not `:[,…]`. The anchor is an entry id. Throws
* ImportRefused (the route's 400) saying which word and why.
*
* @param {string} projectId
* @param {{ refs?: unknown, after?: unknown, before?: unknown, dryRun?: unknown }} ask
* @returns {string[]}
*/
export function draftImportArgv(projectId, { refs, after = null, before = null, dryRun = false }) {
const words = typeof refs === "string" ? refs.trim().split(/\s+/).filter(Boolean) : [];
if (!words.length) throw new ImportRefused("import needs :[,…]");
for (const w of words) {
if (w.startsWith("-")) throw new ImportRefused(`"${w}" is a flag, not an item: the refs are :[,…] only`);
if (!parseImportRef(w)) throw new ImportRefused(`"${w}" is not :[,…]`);
}
const anchor = (v, name) => {
if (v === null || v === undefined || v === "") return null;
const a = String(v);
if (!/^[A-Za-z0-9._:-]{1,120}$/.test(a) || a.startsWith("-")) throw new ImportRefused(`${name} "${a}" is not an entry id`);
return a;
};
const a = anchor(after, "after");
const b = anchor(before, "before");
if (a && b) throw new ImportRefused("after or before, not both");
return [projectId, "import-item", ...words, ...(a ? ["--after", a] : b ? ["--before", b] : []), ...(dryRun ? ["--dry-run"] : []), "--json"];
}
/** The entry `ref` names in a timeline: its id, its post's id, or `p-`. */
export function findEntry(timeline, ref) {
const r = String(ref ?? "");
const tl = Array.isArray(timeline) ? timeline : [];
return tl.find((e) => isObj(e) && e.id === r) ?? tl.find((e) => isObj(e) && (String(e.post ?? "").split("/")[1] === r || e.id === `p-${r}`)) ?? null;
}
/** A string that may name a file of the project: relative, no `..`, no scheme, a directory in it, one line. */
const pathLike = (s) =>
typeof s === "string" && s.length < 512 && s.includes("/") && !/[\n\r\t]/.test(s) && !/^[a-z][a-z0-9+.-]*:/i.test(s) && !s.startsWith("/") && !s.startsWith("~") && !s.split("/").includes("..") && !s.split("/").includes("");
/** Every path-like string in `v`, deep. */
function pathStrings(v, out = new Set()) {
if (Array.isArray(v)) v.forEach((x) => pathStrings(x, out));
else if (isObj(v)) Object.values(v).forEach((x) => pathStrings(x, out));
else if (pathLike(v)) out.add(v);
return out;
}
/** `v` with each string `map` names replaced, deep. */
function renamePaths(v, map) {
if (!map.size) return v;
if (Array.isArray(v)) return v.map((x) => renamePaths(x, map));
if (isObj(v)) return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, renamePaths(x, map)]));
return typeof v === "string" && map.has(v) ? map.get(v) : v;
}
/** The handles an entry draws: its own, its context posts', its quoted post's, its links'. */
export function entryHandles(e) {
const hs = [e?.handle, e?.quoted?.handle, ...(Array.isArray(e?.parents) ? e.parents.map((p) => p?.handle) : []), ...(Array.isArray(e?.links) ? e.links.map((l) => l?.handle) : [])];
return [...new Set(hs.filter((h) => typeof h === "string" && h.trim()).map(handleKey))];
}
async function sha256(file) {
const h = createHash("sha256");
for await (const chunk of createReadStream(file)) h.update(chunk);
return h.digest("hex");
}
/** Are two files the same file, or the same bytes? */
async function sameFile(a, b) {
const [x, y] = await Promise.all([stat(a), stat(b)]);
if (x.dev === y.dev && x.ino === y.ino) return "inode";
if (x.size !== y.size) return null;
return (await sha256(a)) === (await sha256(b)) ? "bytes" : null;
}
/** The project dir `rel`'s directory would be written in, refused when a link in it leads out of the project. */
async function assertInside(projectDir, rel) {
const root = await realpath(projectDir);
// The nearest directory of the path that exists: a link there is where the write would land.
let dir = path.dirname(path.join(projectDir, rel));
while (!(await lstat(dir).catch(() => null))) dir = path.dirname(dir);
const real = await realpath(dir);
if (real !== root && !real.startsWith(root + path.sep)) {
throw new ImportRefused(`${path.relative(projectDir, dir) || "."} leads out of the project (a link, to ${real}) -- not linking ${rel} through it`);
}
}
/**
* A narration take's sidecars: the other `take-.*` files beside `rel` in the source (its parts meta, its words).
* @param {string} srcDir
* @param {string} rel
*/
async function sidecarsOf(srcDir, rel) {
const m = /^(narration\/posts\/[^/]+)\/(take-\d+)\.[^/]+$/.exec(rel);
if (!m) return [];
const names = await readdir(path.join(srcDir, m[1])).catch(() => []);
return names.filter((n) => n.startsWith(`${m[2]}.`)).map((n) => `${m[1]}/${n}`).filter((r) => r !== rel);
}
/**
* The plan for one file: `{ rel, to, how }` -- how is "link" (free), "same" (that file is there), or "renamed"
* (another file there: linked under imports//), or null when the source has no such file.
*/
async function planFile(srcDir, dstDir, rel, sourceSlug) {
const from = path.join(srcDir, rel);
const st = await stat(from).catch(() => null);
if (!st?.isFile()) return null;
for (const to of [rel, `${IMPORTS_DIR}/${sourceSlug}/${rel}`]) {
const at = path.join(dstDir, to);
if (!(await lstat(at).catch(() => null))) return { rel, to, from, how: to === rel ? "link" : "renamed" };
const same = await sameFile(from, at).catch(() => null);
if (same) return { rel, to, from, how: "same", same };
}
throw new ImportRefused(`${rel}: another file is at ${rel} and at ${IMPORTS_DIR}/${sourceSlug}/${rel} in the project -- not writing over either`);
}
/** Link (else copy, across filesystems) one planned file into the project. */
async function placeFile(dstDir, f) {
await assertInside(dstDir, f.to);
const at = path.join(dstDir, f.to);
await mkdir(path.dirname(at), { recursive: true });
try {
await link(f.from, at);
return "linked";
} catch (e) {
if (/** @type {NodeJS.ErrnoException} */ (e).code !== "EXDEV") throw e;
await copyFile(f.from, at);
return "copied";
}
}
/** Is the take rendering now (its own build lock live)? The sentence, or null. */
async function renderingNow(projectDir, take) {
const { BUILD_LOCK, lockIsLive, readBuildLock } = await import("./takePrune.mjs");
const lock = await readBuildLock(path.join(projectDir, "takes", take, BUILD_LOCK));
return lock && lockIsLive(lock) ? `take ${take} is rendering now (pid ${lock.pid}${lock.startedAt ? `, since ${lock.startedAt}` : ""}) -- wait for it, or cancel it` : null;
}
export { renderingNow as takeRenderingNow };
/** Do the take's post items stand in date order (each no earlier than the one before)? */
export function postsInDateOrder(timeline) {
let last = -Infinity;
for (const e of timeline) {
if (!isObj(e) || e.type !== "post") continue;
const t = Date.parse(String(e.date ?? ""));
if (!Number.isFinite(t)) return false;
if (t < last) return false;
last = t;
}
return true;
}
/**
* Items of other projects INTO THE DRAFT -- the project's own manifest, where every edit lands now (umtool
* redesign L3; E1, 9 Nov: the Cut tab's "Add items from another project"). importTakeItems with no take: the
* same clone, the same files linked in, the same placement and the same "again: unchanged", written through the
* draft's structural writer (an undo point of the project's, `umtool timeline
undo`).
*
* @param {{ id: string, dir: string }} project
* @param {Array<{ project: { id: string, dir: string }, item: string, as?: string | null }>} refs
* @param {{ after?: string | null, before?: string | null, dryRun?: boolean, now?: Date }} [opts]
*/
export const importDraftItems = (project, refs, opts = {}) => importTakeItems(project, null, refs, opts);
/**
* IMPORT ITEMS OF OTHER PROJECTS INTO A TAKE (see the head of the file) -- or, `take` null, into the draft
* (importDraftItems).
*
* @param {{ id: string, dir: string }} project the take's project
* @param {string | null} take
* @param {Array<{ project: { id: string, dir: string }, item: string, as?: string | null }>} refs
* @param {{ after?: string | null, before?: string | null, dryRun?: boolean, now?: Date }} [opts]
*/
export async function importTakeItems(project, take, refs, { after = null, before = null, dryRun = false, now = new Date() } = {}) {
if (!refs.length) throw new ImportRefused("nothing to import");
if (after && before) throw new ImportRefused("--after or --before, not both");
const draft = take === null;
const busy = draft ? null : await renderingNow(project.dir, take);
if (busy) throw new ImportRefused(`not imported: ${busy}`);
const takeNow = draft
? { manifest: JSON.parse(await readFile(path.join(project.dir, "video.manifest.json"), "utf8").catch(() => { throw new ImportRefused(`${project.id} has no video.manifest.json`); })) }
: await resolveTakeManifest(project.dir, take); // throws, naming it, when there is no such take
const tl = takeNow.manifest.timeline;
const anchor = after ?? before;
if (anchor && !findEntry(tl, anchor)) {
throw new ImportRefused(
draft
? `the draft has no entry ${anchor} to put the item(s) ${after ? "after" : "before"} (\`umtool timeline ${project.id}\` lists them)`
: `take ${take} has no entry ${anchor} to put the item(s) ${after ? "after" : "before"} (\`umtool timeline ${project.id} --take ${take}\` lists them)`,
);
}
// Each source manifest read once, as it is on disk (never a take of it).
/** @type {Map>} */
const sources = new Map();
const plans = [];
const seen = new Set();
for (const r of refs) {
if (!sources.has(r.project.dir)) {
const text = await readFile(path.join(r.project.dir, "video.manifest.json"), "utf8").catch(() => null);
if (text === null) throw new ImportRefused(`${r.project.id} has no video.manifest.json`);
sources.set(r.project.dir, JSON.parse(text));
}
const src = /** @type {Record} */ (sources.get(r.project.dir));
const e = findEntry(src.timeline, r.item);
if (!e) throw new ImportRefused(`${r.project.id} has no item ${r.item} (its id, or its post's id)`);
const id = r.as ?? e.id;
if (seen.has(id)) throw new ImportRefused(`${id} is named twice -- import it once (or give the second --as )`);
seen.add(id);
const same = path.resolve(r.project.dir) === path.resolve(project.dir);
const slug = r.project.id.replace(/[^A-Za-z0-9._-]+/g, "__");
// The files it names, their sidecars, and the pictures of the authors it draws that the take has none for.
const rels = new Set(pathStrings(e));
for (const rel of [...rels]) for (const s of await sidecarsOf(r.project.dir, rel)) rels.add(s);
const have = isObj(takeNow.manifest.postAvatars) ? takeNow.manifest.postAvatars : {};
const haveKeys = new Set(Object.keys(have).map(handleKey));
const srcAvatars = isObj(src.postAvatars) ? src.postAvatars : {};
const avatars = {};
for (const h of entryHandles(e)) {
if (haveKeys.has(h)) continue;
const k = Object.keys(srcAvatars).find((x) => handleKey(x) === h);
if (!k || !isObj(srcAvatars[k])) continue;
avatars[k] = clone(srcAvatars[k]);
if (pathLike(srcAvatars[k].src)) rels.add(srcAvatars[k].src);
}
const files = [];
const missing = [];
if (!same) {
for (const rel of [...rels].sort()) {
const f = await planFile(r.project.dir, project.dir, rel, slug);
if (f) files.push(f);
else if (/^(narration|posts-media)\//.test(rel)) missing.push(rel);
}
}
const renames = new Map(files.filter((f) => f.to !== f.rel).map((f) => [f.rel, f.to]));
const entry = renamePaths({ ...clone(e), id }, renames);
for (const a of Object.values(avatars)) if (isObj(a) && renames.has(a.src)) a.src = renames.get(a.src);
plans.push({ ref: `${r.project.id}:${r.item}`, source: r.project.id, id, entry, files, missing, avatars });
}
// The files first: a take whose entry names a file not there would render a broken card.
if (!dryRun) {
/** @type {Map} the paths placed by this import (two items naming one file) */
const placedTo = new Map();
for (const p of plans) {
for (const f of p.files) {
if (f.how === "same") continue;
f.done = placedTo.get(f.to) ?? (await placeFile(project.dir, f));
placedTo.set(f.to, f.done);
}
}
}
let placed = [];
/** The placement, over a manifest held in memory (the take's resolved one, or the draft's). */
const place = (mm) => {
placed = [];
const timeline = mm.timeline;
const order = timeline.map((x) => (isObj(x) ? x.id : null)).join("\n");
let cursor = null; // the id the next item goes after (several items keep their order)
for (const p of plans) {
const at = timeline.findIndex((x) => isObj(x) && x.id === p.id);
const was = at >= 0 ? timeline[at] : null;
let action;
if (was && !anchor) {
action = JSON.stringify(was) === JSON.stringify(p.entry) ? "unchanged" : "updated";
timeline[at] = p.entry;
} else {
if (was) timeline.splice(at, 1);
let i;
if (cursor) i = timeline.findIndex((x) => x.id === cursor) + 1;
else if (after) i = timeline.findIndex((x) => x.id === findEntry(timeline, after)?.id) + 1;
else if (before) i = timeline.findIndex((x) => x.id === findEntry(timeline, before)?.id);
else if (postsInDateOrder(timeline) && Number.isFinite(Date.parse(String(p.entry.date ?? "")))) {
const t = Date.parse(String(p.entry.date));
i = timeline.findIndex((x) => isObj(x) && x.type === "post" && Date.parse(String(x.date ?? "")) > t);
if (i < 0) i = timeline.length;
} else i = timeline.length;
if (i < 0) i = timeline.length;
timeline.splice(i, 0, p.entry);
action = was ? (JSON.stringify(was) === JSON.stringify(p.entry) ? "moved" : "updated") : "added";
}
if (anchor) cursor = p.id;
if (Object.keys(p.avatars).length) mm.postAvatars = { ...(isObj(mm.postAvatars) ? mm.postAvatars : {}), ...p.avatars };
placed.push({ id: p.id, action });
}
// Placed where it already stood, as it was: unchanged, not moved.
if (timeline.map((x) => (isObj(x) ? x.id : null)).join("\n") === order) for (const pl of placed) if (pl.action === "moved") pl.action = "unchanged";
// Where each one stands now (a dry run says it too).
for (const pl of placed) {
const i = timeline.findIndex((x) => isObj(x) && x.id === pl.id);
pl.at = { index: i, after: i > 0 ? timeline[i - 1].id : null, before: i + 1 < timeline.length ? timeline[i + 1].id : null };
}
return { ids: plans.map((p) => p.id) };
};
const write = draft
? await writeDraft(project.dir, place, { dryRun })
: await editTakeManifest(project.dir, take, "import-item", await takeToken(project.dir, take), (m) => applyStructural(m, place), { now, dryRun });
const items = plans.map((p) => {
const pl = placed.find((x) => x.id === p.id);
const n = isObj(p.entry.narration) ? p.entry.narration : null;
const takes = Array.isArray(n?.takes) ? n.takes : [];
const pick = Number.isInteger(n?.pick) ? n.pick : takes.length ? 0 : null;
return {
ref: p.ref,
source: p.source,
id: p.id,
action: pl?.action ?? "unchanged",
at: pl?.at ?? null,
narration: n ? { takes: takes.length, pick: pick === null ? null : pick + 1, file: pick === null ? null : takes[pick]?.file ?? null } : null,
files: p.files.map((f) => ({ path: f.to, ...(f.to !== f.rel ? { was: f.rel } : {}), how: f.how === "same" ? "already there" : dryRun ? (f.how === "renamed" ? "would link (renamed)" : "would link") : f.done === "copied" ? "copied" : f.how === "renamed" ? "linked (renamed)" : "linked" })),
missing: p.missing,
avatars: Object.keys(p.avatars),
};
});
return {
project: project.id,
take,
dryRun,
unchanged: write.unchanged,
items,
revision: draft ? write.revision : write.revision ? `takes/${take}/${write.revision.rel}` : null,
token: write.token,
};
}
/**
* The draft's import write: the placement tried on a copy first -- nothing changed (or a dry run) writes nothing --
* then done again inside the draft's structural writer, on the file as it is then. `revision`: its undo point.
*/
async function writeDraft(dir, place, { dryRun }) {
const token = await manifestToken(dir);
const now = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
const tried = clone(now);
applyStructural(tried, place);
if (JSON.stringify(tried) === JSON.stringify(now)) return { unchanged: true, token, revision: null };
if (dryRun) return { unchanged: false, dryRun: true, token, revision: null };
const r = await editDraftStructure(dir, "import-item", token, place);
return { unchanged: false, token: r.token, revision: r.snapshot?.rel && !r.snapshot.skipped ? r.snapshot.rel : null };
}