forked from
stevedylan.dev/sequoia
A CLI for publishing standard.site documents to ATProto
1import { Agent, AtpAgent } from "@atproto/api";
2import * as mimeTypes from "mime-types";
3import * as fs from "node:fs/promises";
4import * as path from "node:path";
5import { stripMarkdownForText, resolvePostPath } from "./markdown";
6import { getOAuthClient } from "./oauth-client";
7import type {
8 BlobObject,
9 BlogPost,
10 Credentials,
11 PublicationRecord,
12 PublisherConfig,
13 StrongRef,
14} from "./types";
15import { isAppPasswordCredentials, isOAuthCredentials } from "./types";
16
17/**
18 * Type guard to check if a record value is a DocumentRecord
19 */
20function isDocumentRecord(value: unknown): value is DocumentRecord {
21 if (!value || typeof value !== "object") return false;
22 const v = value as Record<string, unknown>;
23 return (
24 v.$type === "site.standard.document" &&
25 typeof v.title === "string" &&
26 typeof v.site === "string" &&
27 typeof v.path === "string" &&
28 typeof v.textContent === "string" &&
29 typeof v.publishedAt === "string"
30 );
31}
32
33async function fileExists(filePath: string): Promise<boolean> {
34 try {
35 await fs.access(filePath);
36 return true;
37 } catch {
38 return false;
39 }
40}
41
42/**
43 * Resolve a handle to a DID
44 */
45export async function resolveHandleToDid(handle: string): Promise<string> {
46 if (handle.startsWith("did:")) {
47 return handle;
48 }
49
50 // Try to resolve handle via Bluesky API
51 const resolveUrl = `https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`;
52 const resolveResponse = await fetch(resolveUrl);
53 if (!resolveResponse.ok) {
54 throw new Error("Could not resolve handle");
55 }
56 const resolveData = (await resolveResponse.json()) as { did: string };
57 return resolveData.did;
58}
59
60export async function resolveHandleToPDS(handle: string): Promise<string> {
61 // First, resolve the handle to a DID
62 const did = await resolveHandleToDid(handle);
63
64 // Now resolve the DID to get the PDS URL from the DID document
65 let pdsUrl: string | undefined;
66
67 if (did.startsWith("did:plc:")) {
68 // Fetch DID document from plc.directory
69 const didDocUrl = `https://plc.directory/${did}`;
70 const didDocResponse = await fetch(didDocUrl);
71 if (!didDocResponse.ok) {
72 throw new Error("Could not fetch DID document");
73 }
74 const didDoc = (await didDocResponse.json()) as {
75 service?: Array<{ id: string; type: string; serviceEndpoint: string }>;
76 };
77
78 // Find the PDS service endpoint
79 const pdsService = didDoc.service?.find(
80 (s) => s.id === "#atproto_pds" || s.type === "AtprotoPersonalDataServer",
81 );
82 pdsUrl = pdsService?.serviceEndpoint;
83 } else if (did.startsWith("did:web:")) {
84 // For did:web, fetch the DID document from the domain
85 const domain = did.replace("did:web:", "");
86 const didDocUrl = `https://${domain}/.well-known/did.json`;
87 const didDocResponse = await fetch(didDocUrl);
88 if (!didDocResponse.ok) {
89 throw new Error("Could not fetch DID document");
90 }
91 const didDoc = (await didDocResponse.json()) as {
92 service?: Array<{ id: string; type: string; serviceEndpoint: string }>;
93 };
94
95 const pdsService = didDoc.service?.find(
96 (s) => s.id === "#atproto_pds" || s.type === "AtprotoPersonalDataServer",
97 );
98 pdsUrl = pdsService?.serviceEndpoint;
99 }
100
101 if (!pdsUrl) {
102 throw new Error("Could not find PDS URL for user");
103 }
104
105 return pdsUrl;
106}
107
108export interface CreatePublicationOptions {
109 url: string;
110 name: string;
111 description?: string;
112 iconPath?: string;
113 showInDiscover?: boolean;
114}
115
116export async function createAgent(credentials: Credentials): Promise<Agent> {
117 if (isOAuthCredentials(credentials)) {
118 // OAuth flow - restore session from stored tokens
119 const client = await getOAuthClient();
120 try {
121 const oauthSession = await client.restore(credentials.did);
122 // Wrap the OAuth session in an Agent which provides the atproto API
123 return new Agent(oauthSession);
124 } catch (error) {
125 if (error instanceof Error) {
126 // Check for common OAuth errors
127 if (
128 error.message.includes("expired") ||
129 error.message.includes("revoked")
130 ) {
131 throw new Error(
132 `OAuth session expired or revoked. Please run 'sequoia login' to re-authenticate.`,
133 );
134 }
135 }
136 throw error;
137 }
138 }
139
140 // App password flow
141 if (!isAppPasswordCredentials(credentials)) {
142 throw new Error("Invalid credential type");
143 }
144 const agent = new AtpAgent({ service: credentials.pdsUrl });
145
146 await agent.login({
147 identifier: credentials.identifier,
148 password: credentials.password,
149 });
150
151 return agent;
152}
153
154export async function uploadImage(
155 agent: Agent,
156 imagePath: string,
157): Promise<BlobObject | undefined> {
158 if (!(await fileExists(imagePath))) {
159 return undefined;
160 }
161
162 try {
163 const imageBuffer = await fs.readFile(imagePath);
164 const mimeType = mimeTypes.lookup(imagePath) || "application/octet-stream";
165
166 const response = await agent.com.atproto.repo.uploadBlob(
167 new Uint8Array(imageBuffer),
168 {
169 encoding: mimeType,
170 },
171 );
172
173 return {
174 $type: "blob",
175 ref: {
176 $link: response.data.blob.ref.toString(),
177 },
178 mimeType,
179 size: imageBuffer.byteLength,
180 };
181 } catch (error) {
182 console.error(`Error uploading image ${imagePath}:`, error);
183 return undefined;
184 }
185}
186
187export async function resolveImagePath(
188 ogImage: string,
189 imagesDir: string | undefined,
190 contentDir: string,
191): Promise<string | null> {
192 // Try multiple resolution strategies
193
194 // 1. If imagesDir is specified, look there
195 if (imagesDir) {
196 // Get the base name of the images directory (e.g., "blog-images" from "public/blog-images")
197 const imagesDirBaseName = path.basename(imagesDir);
198
199 // Check if ogImage contains the images directory name and extract the relative path
200 // e.g., "/blog-images/other/file.png" with imagesDirBaseName "blog-images" -> "other/file.png"
201 const imagesDirIndex = ogImage.indexOf(imagesDirBaseName);
202 let relativePath: string;
203
204 if (imagesDirIndex !== -1) {
205 // Extract everything after "blog-images/"
206 const afterImagesDir = ogImage.substring(
207 imagesDirIndex + imagesDirBaseName.length,
208 );
209 // Remove leading slash if present
210 relativePath = afterImagesDir.replace(/^[/\\]/, "");
211 } else {
212 // Fall back to just the filename
213 relativePath = path.basename(ogImage);
214 }
215
216 const imagePath = path.join(imagesDir, relativePath);
217 if (await fileExists(imagePath)) {
218 const stat = await fs.stat(imagePath);
219 if (stat.size > 0) {
220 return imagePath;
221 }
222 }
223 }
224
225 // 2. Try the ogImage path directly (if it's absolute)
226 if (path.isAbsolute(ogImage)) {
227 return ogImage;
228 }
229
230 // 3. Try relative to content directory
231 const contentRelative = path.join(contentDir, ogImage);
232 if (await fileExists(contentRelative)) {
233 const stat = await fs.stat(contentRelative);
234 if (stat.size > 0) {
235 return contentRelative;
236 }
237 }
238
239 return null;
240}
241
242export async function createDocument(
243 agent: Agent,
244 post: BlogPost,
245 config: PublisherConfig,
246 coverImage?: BlobObject,
247): Promise<string> {
248 const postPath = resolvePostPath(
249 post,
250 config.pathPrefix,
251 config.pathTemplate,
252 );
253 const publishDate = new Date(post.frontmatter.publishDate);
254
255 // Determine textContent: use configured field from frontmatter, or fallback to markdown body
256 let textContent: string;
257 if (
258 config.textContentField &&
259 post.rawFrontmatter?.[config.textContentField]
260 ) {
261 textContent = String(post.rawFrontmatter[config.textContentField]);
262 } else {
263 textContent = stripMarkdownForText(post.content);
264 }
265
266 const record: Record<string, unknown> = {
267 $type: "site.standard.document",
268 title: post.frontmatter.title,
269 site: config.publicationUri,
270 path: postPath,
271 textContent: textContent.slice(0, 10000),
272 publishedAt: publishDate.toISOString(),
273 canonicalUrl: `${config.siteUrl}${postPath}`,
274 };
275
276 if (post.frontmatter.description) {
277 record.description = post.frontmatter.description;
278 }
279
280 if (coverImage) {
281 record.coverImage = coverImage;
282 }
283
284 if (post.frontmatter.tags && post.frontmatter.tags.length > 0) {
285 record.tags = post.frontmatter.tags;
286 }
287
288 const response = await agent.com.atproto.repo.createRecord({
289 repo: agent.did!,
290 collection: "site.standard.document",
291 record,
292 });
293
294 return response.data.uri;
295}
296
297export async function updateDocument(
298 agent: Agent,
299 post: BlogPost,
300 atUri: string,
301 config: PublisherConfig,
302 coverImage?: BlobObject,
303): Promise<void> {
304 // Parse the atUri to get the collection and rkey
305 // Format: at://did:plc:xxx/collection/rkey
306 const uriMatch = atUri.match(/^at:\/\/([^/]+)\/([^/]+)\/(.+)$/);
307 if (!uriMatch) {
308 throw new Error(`Invalid atUri format: ${atUri}`);
309 }
310
311 const [, , collection, rkey] = uriMatch;
312
313 const postPath = resolvePostPath(
314 post,
315 config.pathPrefix,
316 config.pathTemplate,
317 );
318 const publishDate = new Date(post.frontmatter.publishDate);
319
320 // Determine textContent: use configured field from frontmatter, or fallback to markdown body
321 let textContent: string;
322 if (
323 config.textContentField &&
324 post.rawFrontmatter?.[config.textContentField]
325 ) {
326 textContent = String(post.rawFrontmatter[config.textContentField]);
327 } else {
328 textContent = stripMarkdownForText(post.content);
329 }
330
331 const record: Record<string, unknown> = {
332 $type: "site.standard.document",
333 title: post.frontmatter.title,
334 site: config.publicationUri,
335 path: postPath,
336 textContent: textContent.slice(0, 10000),
337 publishedAt: publishDate.toISOString(),
338 canonicalUrl: `${config.siteUrl}${postPath}`,
339 };
340
341 if (post.frontmatter.description) {
342 record.description = post.frontmatter.description;
343 }
344
345 if (coverImage) {
346 record.coverImage = coverImage;
347 }
348
349 if (post.frontmatter.tags && post.frontmatter.tags.length > 0) {
350 record.tags = post.frontmatter.tags;
351 }
352
353 await agent.com.atproto.repo.putRecord({
354 repo: agent.did!,
355 collection: collection!,
356 rkey: rkey!,
357 record,
358 });
359}
360
361export function parseAtUri(
362 atUri: string,
363): { did: string; collection: string; rkey: string } | null {
364 const match = atUri.match(/^at:\/\/([^/]+)\/([^/]+)\/(.+)$/);
365 if (!match) return null;
366 return {
367 did: match[1]!,
368 collection: match[2]!,
369 rkey: match[3]!,
370 };
371}
372
373export interface DocumentRecord {
374 $type: "site.standard.document";
375 title: string;
376 site: string;
377 path: string;
378 textContent: string;
379 publishedAt: string;
380 canonicalUrl?: string;
381 description?: string;
382 coverImage?: BlobObject;
383 tags?: string[];
384 location?: string;
385}
386
387export interface ListDocumentsResult {
388 uri: string;
389 cid: string;
390 value: DocumentRecord;
391}
392
393export async function listDocuments(
394 agent: Agent,
395 publicationUri?: string,
396): Promise<ListDocumentsResult[]> {
397 const documents: ListDocumentsResult[] = [];
398 let cursor: string | undefined;
399
400 do {
401 const response = await agent.com.atproto.repo.listRecords({
402 repo: agent.did!,
403 collection: "site.standard.document",
404 limit: 100,
405 cursor,
406 });
407
408 for (const record of response.data.records) {
409 if (!isDocumentRecord(record.value)) {
410 continue;
411 }
412
413 // If publicationUri is specified, only include documents from that publication
414 if (publicationUri && record.value.site !== publicationUri) {
415 continue;
416 }
417
418 documents.push({
419 uri: record.uri,
420 cid: record.cid,
421 value: record.value,
422 });
423 }
424
425 cursor = response.data.cursor;
426 } while (cursor);
427
428 return documents;
429}
430
431export async function createPublication(
432 agent: Agent,
433 options: CreatePublicationOptions,
434): Promise<string> {
435 let icon: BlobObject | undefined;
436
437 if (options.iconPath) {
438 icon = await uploadImage(agent, options.iconPath);
439 }
440
441 const record: Record<string, unknown> = {
442 $type: "site.standard.publication",
443 url: options.url,
444 name: options.name,
445 createdAt: new Date().toISOString(),
446 };
447
448 if (options.description) {
449 record.description = options.description;
450 }
451
452 if (icon) {
453 record.icon = icon;
454 }
455
456 if (options.showInDiscover !== undefined) {
457 record.preferences = {
458 showInDiscover: options.showInDiscover,
459 };
460 }
461
462 const response = await agent.com.atproto.repo.createRecord({
463 repo: agent.did!,
464 collection: "site.standard.publication",
465 record,
466 });
467
468 return response.data.uri;
469}
470
471export interface GetPublicationResult {
472 uri: string;
473 cid: string;
474 value: PublicationRecord;
475}
476
477export async function getPublication(
478 agent: Agent,
479 publicationUri: string,
480): Promise<GetPublicationResult | null> {
481 const parsed = parseAtUri(publicationUri);
482 if (!parsed) {
483 return null;
484 }
485
486 try {
487 const response = await agent.com.atproto.repo.getRecord({
488 repo: parsed.did,
489 collection: parsed.collection,
490 rkey: parsed.rkey,
491 });
492
493 return {
494 uri: publicationUri,
495 cid: response.data.cid!,
496 value: response.data.value as unknown as PublicationRecord,
497 };
498 } catch {
499 return null;
500 }
501}
502
503export interface UpdatePublicationOptions {
504 url?: string;
505 name?: string;
506 description?: string;
507 iconPath?: string;
508 showInDiscover?: boolean;
509}
510
511export async function updatePublication(
512 agent: Agent,
513 publicationUri: string,
514 options: UpdatePublicationOptions,
515 existingRecord: PublicationRecord,
516): Promise<void> {
517 const parsed = parseAtUri(publicationUri);
518 if (!parsed) {
519 throw new Error(`Invalid publication URI: ${publicationUri}`);
520 }
521
522 // Build updated record, preserving createdAt and $type
523 const record: Record<string, unknown> = {
524 $type: existingRecord.$type,
525 url: options.url ?? existingRecord.url,
526 name: options.name ?? existingRecord.name,
527 createdAt: existingRecord.createdAt,
528 };
529
530 // Handle description - can be cleared with empty string
531 if (options.description !== undefined) {
532 if (options.description) {
533 record.description = options.description;
534 }
535 // If empty string, don't include description (clears it)
536 } else if (existingRecord.description) {
537 record.description = existingRecord.description;
538 }
539
540 // Handle icon - upload new if provided, otherwise keep existing
541 if (options.iconPath) {
542 const icon = await uploadImage(agent, options.iconPath);
543 if (icon) {
544 record.icon = icon;
545 }
546 } else if (existingRecord.icon) {
547 record.icon = existingRecord.icon;
548 }
549
550 // Handle preferences
551 if (options.showInDiscover !== undefined) {
552 record.preferences = {
553 showInDiscover: options.showInDiscover,
554 };
555 } else if (existingRecord.preferences) {
556 record.preferences = existingRecord.preferences;
557 }
558
559 await agent.com.atproto.repo.putRecord({
560 repo: parsed.did,
561 collection: parsed.collection,
562 rkey: parsed.rkey,
563 record,
564 });
565}
566
567// --- Bluesky Post Creation ---
568
569export interface CreateBlueskyPostOptions {
570 title: string;
571 description?: string;
572 canonicalUrl: string;
573 coverImage?: BlobObject;
574 publishedAt: string; // Used as createdAt for the post
575}
576
577/**
578 * Count graphemes in a string (for Bluesky's 300 grapheme limit)
579 */
580function countGraphemes(str: string): number {
581 // Use Intl.Segmenter if available, otherwise fallback to spread operator
582 if (typeof Intl !== "undefined" && Intl.Segmenter) {
583 const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
584 return [...segmenter.segment(str)].length;
585 }
586 return [...str].length;
587}
588
589/**
590 * Truncate a string to a maximum number of graphemes
591 */
592function truncateToGraphemes(str: string, maxGraphemes: number): string {
593 if (typeof Intl !== "undefined" && Intl.Segmenter) {
594 const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
595 const segments = [...segmenter.segment(str)];
596 if (segments.length <= maxGraphemes) return str;
597 return `${segments
598 .slice(0, maxGraphemes - 3)
599 .map((s) => s.segment)
600 .join("")}...`;
601 }
602 // Fallback
603 const chars = [...str];
604 if (chars.length <= maxGraphemes) return str;
605 return `${chars.slice(0, maxGraphemes - 3).join("")}...`;
606}
607
608/**
609 * Create a Bluesky post with external link embed
610 */
611export async function createBlueskyPost(
612 agent: Agent,
613 options: CreateBlueskyPostOptions,
614): Promise<StrongRef> {
615 const { title, description, canonicalUrl, coverImage, publishedAt } = options;
616
617 // Build post text: title + description + URL
618 // Max 300 graphemes for Bluesky posts
619 const MAX_GRAPHEMES = 300;
620
621 let postText: string;
622 const urlPart = `\n\n${canonicalUrl}`;
623 const urlGraphemes = countGraphemes(urlPart);
624
625 if (description) {
626 // Try: title + description + URL
627 const fullText = `${title}\n\n${description}${urlPart}`;
628 if (countGraphemes(fullText) <= MAX_GRAPHEMES) {
629 postText = fullText;
630 } else {
631 // Truncate description to fit
632 const availableForDesc =
633 MAX_GRAPHEMES -
634 countGraphemes(title) -
635 countGraphemes("\n\n") -
636 urlGraphemes -
637 countGraphemes("\n\n");
638 if (availableForDesc > 10) {
639 const truncatedDesc = truncateToGraphemes(
640 description,
641 availableForDesc,
642 );
643 postText = `${title}\n\n${truncatedDesc}${urlPart}`;
644 } else {
645 // Just title + URL
646 postText = `${title}${urlPart}`;
647 }
648 }
649 } else {
650 // Just title + URL
651 postText = `${title}${urlPart}`;
652 }
653
654 // Final truncation if still too long (shouldn't happen but safety check)
655 if (countGraphemes(postText) > MAX_GRAPHEMES) {
656 postText = truncateToGraphemes(postText, MAX_GRAPHEMES);
657 }
658
659 // Calculate byte indices for the URL facet
660 const encoder = new TextEncoder();
661 const urlStartInText = postText.lastIndexOf(canonicalUrl);
662 const beforeUrl = postText.substring(0, urlStartInText);
663 const byteStart = encoder.encode(beforeUrl).length;
664 const byteEnd = byteStart + encoder.encode(canonicalUrl).length;
665
666 // Build facets for the URL link
667 const facets = [
668 {
669 index: {
670 byteStart,
671 byteEnd,
672 },
673 features: [
674 {
675 $type: "app.bsky.richtext.facet#link",
676 uri: canonicalUrl,
677 },
678 ],
679 },
680 ];
681
682 // Build external embed
683 const embed: Record<string, unknown> = {
684 $type: "app.bsky.embed.external",
685 external: {
686 uri: canonicalUrl,
687 title: title.substring(0, 500), // Max 500 chars for title
688 description: (description || "").substring(0, 1000), // Max 1000 chars for description
689 },
690 };
691
692 // Add thumbnail if coverImage is available
693 if (coverImage) {
694 (embed.external as Record<string, unknown>).thumb = coverImage;
695 }
696
697 // Create the post record
698 const record: Record<string, unknown> = {
699 $type: "app.bsky.feed.post",
700 text: postText,
701 facets,
702 embed,
703 createdAt: new Date(publishedAt).toISOString(),
704 };
705
706 const response = await agent.com.atproto.repo.createRecord({
707 repo: agent.did!,
708 collection: "app.bsky.feed.post",
709 record,
710 });
711
712 return {
713 uri: response.data.uri,
714 cid: response.data.cid,
715 };
716}
717
718/**
719 * Add bskyPostRef to an existing document record
720 */
721export async function addBskyPostRefToDocument(
722 agent: Agent,
723 documentAtUri: string,
724 bskyPostRef: StrongRef,
725): Promise<void> {
726 const parsed = parseAtUri(documentAtUri);
727 if (!parsed) {
728 throw new Error(`Invalid document URI: ${documentAtUri}`);
729 }
730
731 // Fetch existing record
732 const existingRecord = await agent.com.atproto.repo.getRecord({
733 repo: parsed.did,
734 collection: parsed.collection,
735 rkey: parsed.rkey,
736 });
737
738 // Add bskyPostRef to the record
739 const updatedRecord = {
740 ...(existingRecord.data.value as Record<string, unknown>),
741 bskyPostRef,
742 };
743
744 // Update the record
745 await agent.com.atproto.repo.putRecord({
746 repo: parsed.did,
747 collection: parsed.collection,
748 rkey: parsed.rkey,
749 record: updatedRecord,
750 });
751}