// The scene note, as a record and as a file — the same shape both ways. // // This mirrors `corliss/scene_notes.py` on purpose. Two implementations of one // lexicon is exactly the test the lexicon needs: if these disagree about what a // note is, a second app built by someone else will disagree worse. export const COLLECTION = "network.sharedcomputer.notes"; /** markpub's flavour. `ofm` is the ask; until it lands, GFM plus an extension. */ export const FLAVOUR = "gfm"; export const EXTENSIONS = ["obsidian"]; export const RENDERING_RULES = "obsidian-markdown"; export interface SceneNote { rkey: string; title: string; /** The note's text without its front matter. */ body: string; /** Front matter, split off — key order preserved. */ properties: [string, string][]; tags: string[]; updated: string; createdAt: string; path: string; record: Record; } // --- YAML, shallow by design --------------------------------------------- // // The same cases the Python side handles: `key: value`, `key: a, b`, and a // block list under a key. Anything else is ignored rather than guessed at, and // a note with no front matter is never lost because its metadata was odd. const FM_LINE = /^([A-Za-z0-9_.-]+):\s*(.*)$/; const H1 = /^#\s+(.+)$/m; function parseBlock(lines: string[]): [string, string][] { const out: [string, string][] = []; let key: string | null = null; for (const line of lines) { if (!line.trim() || line.trimStart().startsWith("#")) continue; if ((line.startsWith(" ") || line.startsWith("\t")) && key) { const item = line.trim().replace(/^-/, "").trim().replace(/^['"]|['"]$/g, ""); if (item) { const found = out.find(([k]) => k === key); if (found) found[1] = found[1] ? `${found[1]}, ${item}` : item; } continue; } const match = FM_LINE.exec(line); if (!match) continue; key = match[1]; out.push([key, match[2].trim()]); } return out; } export function splitFrontmatter(text: string): { properties: [string, string][]; body: string } { const normalised = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); if (normalised.startsWith("---\n")) { const end = normalised.indexOf("\n---", 4); if (end === -1) return { properties: [], body: text }; return { properties: parseBlock(normalised.slice(4, end).split("\n")), body: normalised.slice(end + 4).replace(/^\n+/, ""), }; } // A block that lost its opening fence — pasting from somewhere eats the first // line often enough to be worth recovering: `key: value` lines, then `---`. const lines = normalised.split("\n"); for (let index = 0; index < Math.min(lines.length, 40); index += 1) { if (lines[index].trim() !== "---") continue; const candidate = lines.slice(0, index); const looksLikeMetadata = candidate.length > 0 && candidate.every((l) => !l.trim() || FM_LINE.test(l) || l.startsWith(" ") || l.startsWith("\t")) && candidate.some((l) => FM_LINE.test(l)); if (looksLikeMetadata) { return { properties: parseBlock(candidate), body: lines.slice(index + 1).join("\n").replace(/^\n+/, ""), }; } break; } return { properties: [], body: text }; } export function compose(properties: [string, string][], body: string): string { const lines = properties .filter(([key]) => key.trim()) .map(([key, value]) => (value === "" ? `${key}:` : `${key}: ${value}`)); if (lines.length === 0) return body; return `---\n${lines.join("\n")}\n---\n\n${body}`; } export function tagsOf(properties: [string, string][], body: string): string[] { const fromFront = properties .filter(([key]) => key === "tags") .flatMap(([, value]) => value.split(",").map((v) => v.trim().replace(/^#/, ""))); const inline = [...body.matchAll(/(?:^|\s)#([A-Za-z][\w-]{0,49})/g)].map((m) => m[1]); return [...new Set([...fromFront, ...inline].filter(Boolean))].slice(0, 32); } export function displayTitle(properties: [string, string][], body: string, fallback: string): string { const front = properties.find(([key]) => key === "title")?.[1]?.trim(); if (front) return front.replace(/^['"]|['"]$/g, ""); const heading = H1.exec(body)?.[1]?.trim(); return heading || fallback || "Untitled"; } // --- record ↔ note -------------------------------------------------------- export function bodyOf(record: Record): string { const body = record.body as { text?: { markdown?: unknown } } | undefined; const markdown = body?.text?.markdown; return typeof markdown === "string" ? markdown : ""; } export function noteFromRecord(rkey: string, record: Record): SceneNote { const raw = bodyOf(record); const { properties, body } = splitFrontmatter(raw); return { rkey, title: displayTitle(properties, body, String(record.title ?? "")), body, properties, tags: tagsOf(properties, body), updated: String(record.updatedAt ?? record.createdAt ?? ""), createdAt: String(record.createdAt ?? ""), path: String(record.path ?? `${slug(String(record.title ?? "untitled"))}.md`), record, }; } /** * A stable id for a note that only exists on disk. * * A file has no record to carry a `noteId`, so one is derived from its name: * short, deterministic, and the same on every visit — which is what the * Automerge document needs in order to hold the unsaved text between them. A * rename changes it; that is the price of not having a record to put it in. */ export function localNoteId(name: string): string { let hash = 2166136261; for (const character of name.toLowerCase()) { hash ^= character.codePointAt(0) ?? 0; hash = Math.imul(hash, 16777619); } return `l${(hash >>> 0).toString(36)}`; } export function slug(title: string): string { const value = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""); return value.slice(0, 80) || "untitled"; } export function textHash(text: string): Promise { // WebCrypto has no synchronous digest, and the hash is only a cheap // equality check — so a SHA-256 over the UTF-8 bytes, awaited. return crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)).then((buffer) => [...new Uint8Array(buffer)].map((b) => b.toString(16).padStart(2, "0")).join(""), ); } export async function buildRecord( existing: Record | undefined, title: string, properties: [string, string][], body: string, ): Promise> { const text = compose(properties, body); const now = new Date().toISOString(); return { $type: COLLECTION, noteId: existing?.noteId ?? newTid(), path: existing?.path ?? `${slug(title)}.md`, title, body: { $type: "at.markpub.markdown", flavor: FLAVOUR, extensions: EXTENSIONS, renderingRules: RENDERING_RULES, text: { $type: "at.markpub.text", markdown: text }, }, createdAt: existing?.createdAt ?? now, updatedAt: now, textHash: await textHash(text), tags: tagsOf(properties, body), status: "live", }; } const B32 = "234567abcdefghijklmnopqrstuvwxyz"; /** A TID, the same layout the Corliss side mints: microseconds + clock id. */ export function newTid(): string { let n = BigInt(Date.now()) * 1000n * (1n << 11n); n |= BigInt(Math.floor(Math.random() * 2048)); const out: string[] = []; for (let i = 0; i < 13; i += 1) { out.push(B32[Number(n & 31n)]); n >>= 5n; } return out.reverse().join(""); } // --- file form ------------------------------------------------------------ // // The mirror is the same note with its front matter intact, so the folder is a // plain markdown vault: open it in Obsidian and it is notes, not an export. export function toMarkdown(note: { properties: [string, string][]; body: string }): string { return compose(note.properties, note.body); } export function filenameOf(note: SceneNote): string { const name = note.path.split("/").pop() ?? ""; return name.endsWith(".md") ? name : `${slug(note.title)}.md`; }