Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448/** * Seed script: write sample MySTmd documents as pub.oxa.document records. * * Uses the obsidian-myst pipeline: * MySTmd → parseMyst() → convertMystToOxa() → oxaToAtproto() → PDS write * * Usage: * PDS_URL=https://your-pds.example DID=did:plc:xxx ACCESS_TOKEN=xxx npx tsx scripts/seed-docs.ts * * Or with an app password: * PDS_URL=https://your-pds.example DID=did:plc:xxx APP_PASSWORD=xxx HANDLE=handle.bsky.social npx tsx scripts/seed-docs.ts */
// We import from the obsidian-myst plugin which is a sibling repo.// For this to work, the obsidian-myst repo must be at /home/nandi/code/obsidian-myst// and its dependencies installed.//// Alternatively, we construct the records directly using the ATProto flat model// since we know the lexicon shape.
const PDS_URL = process.env.PDS_URL || "";const DID = process.env.DID || "";const ACCESS_TOKEN = process.env.ACCESS_TOKEN || "";const APP_PASSWORD = process.env.APP_PASSWORD || "";const HANDLE = process.env.HANDLE || "";
// ---------------------------------------------------------------------------// Sample MySTmd documents// ---------------------------------------------------------------------------
const docs = [ { rkey: "math-intro", title: "Introduction to Category Theory", markdown: `---title: Introduction to Category Theory---
## Motivation
Category theory provides a unified framework for studying mathematical structures and the relationships between them. Originally developed by Saunders Mac Lane and Samuel Eilenberg in the 1940s, it has become foundational in mathematics, computer science, and physics.
## Basic Definitions
A **category** $\mathcal{C}$ consists of:
- A collection of **objects** $\text{Ob}(\mathcal{C})$- For each pair of objects $A, B$, a set of **morphisms** $\text{Hom}(A, B)$- For each object $A$, an **identity morphism** $\text{id}_A \in \text{Hom}(A, A)$- A **composition** operation: if $f \in \text{Hom}(A, B)$ and $g \in \text{Hom}(B, C)$, then $g \circ f \in \text{Hom}(A, C)$
subject to the **associativity** and **identity** laws:
$$\begin{aligned}h \circ (g \circ f) &= (h \circ g) \circ f \\\text{id}_B \circ f &= f = f \circ \text{id}_A\end{aligned}$$
## Functors
A **functor** $F: \mathcal{C} \to \mathcal{D}$ between categories maps objects to objects and morphisms to morphisms, preserving structure:
$$F(g \circ f) = F(g) \circ F(f)$$$$F(\text{id}_A) = \text{id}_{F(A)}$$
Functors are the natural notion of "structure-preserving map" between categories, analogous to homomorphisms between algebraic structures.
## Natural Transformations
Given functors $F, G: \mathcal{C} \to \mathcal{D}$, a **natural transformation** $\alpha: F \Rightarrow G$ assigns to each object $A$ in $\mathcal{C}$ a morphism $\alpha_A: F(A) \to G(A)$ such that for every $f: A \to B$:
$$\alpha_B \circ F(f) = G(f) \circ \alpha_A$$
This is the key insight: the "morphism between functors" is itself a structured object, leading to higher categories and the Yoneda lemma.`, }, { rkey: "rust-patterns", title: "Rust Ownership and Borrowing Patterns", markdown: `---title: Rust Ownership and Borrowing Patterns---
## The Ownership Model
Rust's ownership system ensures memory safety without garbage collection. Every value has a single **owner**, and when the owner goes out of scope, the value is dropped.
\`\`\`rustfn main() { let s1 = String::from("hello"); let s2 = s1; // s1 is moved to s2 // println!("{}", s1); // ERROR: s1 no longer valid println!("{}", s2); // OK}\`\`\`
## Borrowing Rules
At any given time, you can have **either**:
- One mutable reference (\`&mut T\`)- Any number of immutable references (\`&T\`)
But not both simultaneously.
\`\`\`rustfn borrowing() { let mut data = vec![1, 2, 3]; let first = &data[0]; // immutable borrow // data.push(4); // ERROR: cannot mutate while borrowed println!("first: {}", first); data.push(4); // OK: borrow ended}\`\`\`
## Lifetimes
Lifetimes annotate how long references are valid. The compiler can often infer them, but explicit annotations are needed when multiple lifetimes interact:
\`\`\`rustfn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y }}\`\`\`
## Interior Mutability
The \`RefCell<T>\` type provides interior mutability — runtime-checked borrow rules for cases where the compiler cannot verify safety statically:
\`\`\`rustuse std::cell::RefCell;
let data = RefCell::new(vec![1, 2, 3]);data.borrow_mut().push(4); // mutable at runtimeprintln!("{:?}", data.borrow()); // immutable at runtime\`\`\``, }, { rkey: "atproto-intro", title: "AT Protocol: A Technical Overview", markdown: `---title: AT Protocol - A Technical Overview---
## What is AT Protocol?
The Authenticated Transfer Protocol (AT Protocol) is a decentralized social networking protocol. It specifies how data is stored, shared, and authenticated across a federated network of servers called **Personal Data Servers (PDS)**.
## Core Concepts
### DIDs and Handles
Every user has a **DID** (Decentralized Identifier) — a permanent, globally unique identifier like \`did:plc:ewvi7nxzy7lk2pg3z4...\`. DIDs are resolved to DID documents, which point to the user's PDS.
**Handles** are human-readable names (like \`alice.bsky.social\`) that map to DIDs via DNS or the PLC directory. This provides a verification layer: if a handle resolves to your DID, you control that domain.
### Repositories
Each user has a **MST-based repository** (a Merkle Search Tree) that stores their data as a collection of records. Records are typed via **lexicons** — JSON Schema-like definitions that specify the structure of each record type.
### Firehose
The **firehose** is a real-time event stream of all repository changes across the network. Appviews subscribe to the firehose to index data and build aggregated views.
## Data Flow
1. A user writes a record to their PDS via XRPC2. The PDS emits a commit event on the firehose3. Appviews and labelers subscribe and index the event4. Clients query appviews for aggregated views
## XRPC
XRPC (Cross-Server Remote Procedure Call) is the protocol's RPC framework. Procedures are defined by lexicons and accessed via HTTP endpoints like:
\`GET /xrpc/app.bsky.feed.getTimeline\`\`POST /xrpc/com.atproto.repo.createRecord\`
This is the foundation for all client-server and server-server communication in the network.`, },];
// ---------------------------------------------------------------------------// Build pub.oxa.document records directly (ATProto flat model)// ---------------------------------------------------------------------------
// Since we can't easily import the obsidian-myst pipeline from here// (it's an Obsidian plugin with DOM dependencies), we construct the// records directly using the ATProto flat model.//// For a full MySTmd → OXA → ATProto pipeline, use the obsidian-myst// plugin's publishNoteToPds() function from within Obsidian.
function buildRecord(doc: { title: string; markdown: string }): any { // Parse the markdown into simple blocks for the ATProto record. // This is a simplified parser that handles headings, paragraphs, // code blocks, and math blocks — enough for the seed docs. const lines = doc.markdown.split("\n"); const blocks: any[] = []; let i = 0;
// Skip frontmatter if (lines[0] === "---") { i = 1; while (i < lines.length && lines[i] !== "---") i++; i++; // skip closing --- }
while (i < lines.length) { const line = lines[i];
// Empty line if (!line.trim()) { i++; continue; }
// Heading const headingMatch = line.match(/^(#{1,6})\s+(.+)$/); if (headingMatch) { const level = headingMatch[1].length; const text = headingMatch[2].replace(/\*\*(.+?)\*\*/g, "$1").replace(/\*(.+?)\*/g, "$1"); blocks.push({ $type: "pub.oxa.blocks.defs#heading", level, text, facets: extractFacets(headingMatch[2]), }); i++; continue; }
// Code block if (line.startsWith("```")) { const lang = line.slice(3).trim() || undefined; const codeLines: string[] = []; i++; while (i < lines.length && !lines[i].startsWith("```")) { codeLines.push(lines[i]); i++; } i++; // skip closing ``` const record: any = { $type: "pub.oxa.blocks.defs#code", value: codeLines.join("\n"), }; if (lang) record.language = lang; blocks.push(record); continue; }
// Math block ($$...$$) if (line.trim().startsWith("$$")) { const mathLines: string[] = []; if (line.trim() === "$$") { i++; while (i < lines.length && lines[i].trim() !== "$$") { mathLines.push(lines[i]); i++; } i++; // skip closing $$ } else { // Single-line display math: $$ E = mc^2 $$ const content = line.trim().slice(2, -2).trim(); mathLines.push(content); i++; } // Math isn't in the current lexicon block union, but the union is // closed: false so it'll pass. We emit it as a code block with // language "math" as a fallback. blocks.push({ $type: "pub.oxa.blocks.defs#code", value: mathLines.join("\n"), language: "math", }); continue; }
// Thematic break if (line.trim() === "---" || line.trim() === "***" || line.trim() === "___") { blocks.push({ $type: "pub.oxa.blocks.defs#thematicBreak" }); i++; continue; }
// List items if (line.match(/^\s*[-*]\s+/) || line.match(/^\s*\d+\.\s+/)) { const listItems: any[] = []; const ordered = !!line.match(/^\s*\d+\.\s+/); while (i < lines.length) { const listLine = lines[i]; if (!listLine.match(/^\s*[-*]\s+/) && !listLine.match(/^\s*\d+\.\s+/)) break; const text = listLine.replace(/^\s*(?:[-*]|\d+\.)\s+/, ""); listItems.push({ $type: "pub.oxa.blocks.defs#paragraph", text: text.replace(/\*\*(.+?)\*\*/g, "$1").replace(/\*(.+?)\*/g, "$1"), facets: extractFacets(text), }); i++; } // Lists aren't in the current lexicon block union either. // Emit as separate paragraphs for now. for (const item of listItems) { blocks.push(item); } continue; }
// Paragraph (collect consecutive non-empty, non-special lines) const paraLines: string[] = []; while (i < lines.length && lines[i].trim() && !lines[i].startsWith("#") && !lines[i].startsWith("```") && !lines[i].trim().startsWith("$$")) { paraLines.push(lines[i]); i++; } if (paraLines.length > 0) { const text = paraLines.join("\n").replace(/\*\*(.+?)\*\*/g, "$1").replace(/\*(.+?)\*/g, "$1"); blocks.push({ $type: "pub.oxa.blocks.defs#paragraph", text, facets: extractFacets(paraLines.join("\n")), }); } }
return { $type: "pub.oxa.document", title: { text: doc.title, facets: [] }, children: blocks, createdAt: new Date().toISOString(), };}
function extractFacets(text: string): any[] { const facets: any[] = []; const encoder = new TextEncoder();
// Bold: **text** let match; const boldRe = /\*\*(.+?)\*\*/g; while ((match = boldRe.exec(text)) !== null) { const before = text.slice(0, match.index); const byteStart = encoder.encode(before).byteLength; const byteEnd = byteStart + encoder.encode(match[1]).byteLength; facets.push({ index: { byteStart, byteEnd }, features: [{ $type: "pub.oxa.richtext.facet#strong" }], }); }
// Italic: *text* (but not inside bold) const italicRe = /(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g; while ((match = italicRe.exec(text)) !== null) { const before = text.slice(0, match.index); const byteStart = encoder.encode(before).byteLength; const byteEnd = byteStart + encoder.encode(match[1]).byteLength; facets.push({ index: { byteStart, byteEnd }, features: [{ $type: "pub.oxa.richtext.facet#emphasis" }], }); }
// Inline code: `text` const codeRe = /`([^`]+)`/g; while ((match = codeRe.exec(text)) !== null) { const before = text.slice(0, match.index); const byteStart = encoder.encode(before).byteLength; const byteEnd = byteStart + encoder.encode(match[1]).byteLength; facets.push({ index: { byteStart, byteEnd }, features: [{ $type: "pub.oxa.richtext.facet#inlineCode", value: match[1] }], }); }
return facets;}
// ---------------------------------------------------------------------------// Write records to PDS// ---------------------------------------------------------------------------
async function getAccessToken(): Promise<string> { if (ACCESS_TOKEN) return ACCESS_TOKEN;
if (APP_PASSWORD && HANDLE && PDS_URL) { // Create a session via com.atproto.server.createSession const res = await fetch(`${PDS_URL}/xrpc/com.atproto.server.createSession`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ identifier: HANDLE, password: APP_PASSWORD }), }); if (!res.ok) { const err = await res.text(); throw new Error(`Failed to create session: ${err}`); } const data = await res.json(); return data.accessJwt; }
throw new Error("Provide ACCESS_TOKEN or APP_PASSWORD+HANDLE+PDS_URL");}
async function putRecord(rkey: string, record: any, token: string): Promise<void> { const body = { repo: DID, collection: "pub.oxa.document", rkey, record, validate: false, };
const res = await fetch(`${PDS_URL}/xrpc/com.atproto.repo.putRecord`, { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, body: JSON.stringify(body), });
if (!res.ok) { const err = await res.text(); throw new Error(`putRecord failed for ${rkey}: ${err}`); }
const data = await res.json(); console.log(`Wrote ${rkey}: ${data.uri}`);}
async function main() { if (!PDS_URL || !DID) { console.error("Usage: PDS_URL=<url> DID=<did> [ACCESS_TOKEN=<token> | APP_PASSWORD=<pw> HANDLE=<handle>] npx tsx scripts/seed-docs.ts"); process.exit(1); }
const token = await getAccessToken();
for (const doc of docs) { const record = buildRecord(doc); await putRecord(doc.rkey, record, token); }
console.log(`\nSeeded ${docs.length} documents.`);}
main().catch(console.error);