ReviewOS

also looking at this

stacks/postline

Bluesky publishing v2: rich-text facets + image upload

#9
Merged glennmichael123 wants to merge feat/bluesky-publishing-v2 into main
8 files +347 -12
storage/framework/core/socials/src/drivers/bluesky.tsmodified+136-0
Changes to storage/framework/core/socials/src/drivers/bluesky.ts
@@ -40,6 +40,66 @@ interface CreateRecordResponse {
4040 cid?: string
4141}
4242
43interface FacetCandidate {
44 byteStart: number
45 byteEnd: number
46 type: 'link' | 'tag' | 'mention'
47 value: string
48}
49
50const utf8 = new TextEncoder()
51
52function byteLength(value: string): number {
53 return utf8.encode(value).length
54}
55
56/**
57 * Find link/hashtag/mention spans in post text with UTF-8 byte offsets
58 * (ATProto facet ranges are byte-indexed, not character-indexed).
59 * Mentions still need their DID resolved before they become facets.
60 */
61export function detectFacetCandidates(text: string): FacetCandidate[] {
62 const candidates: FacetCandidate[] = []
63
64 const linkPattern = /https?:\/\/[^\s<>"']+/g
65 for (const match of text.matchAll(linkPattern)) {
66 const value = match[0].replace(/[),.;!?]+$/, '')
67 candidates.push({
68 byteStart: byteLength(text.slice(0, match.index)),
69 byteEnd: byteLength(text.slice(0, match.index)) + byteLength(value),
70 type: 'link',
71 value,
72 })
73 }
74
75 const insideLink = (start: number, end: number): boolean =>
76 candidates.some(candidate => candidate.type === 'link' && start < candidate.byteEnd && end > candidate.byteStart)
77
78 const tagPattern = /(^|\s)(#[A-Za-z0-9_]+)/g
79 for (const match of text.matchAll(tagPattern)) {
80 const tag = match[2]
81 if (/^#\d+$/.test(tag)) continue
82 const charStart = (match.index ?? 0) + match[1].length
83 const byteStart = byteLength(text.slice(0, charStart))
84 const byteEnd = byteStart + byteLength(tag)
85 if (insideLink(byteStart, byteEnd)) continue
86 candidates.push({ byteStart, byteEnd, type: 'tag', value: tag.slice(1) })
87 }
88
89 // Handles are domain-shaped (user.bsky.social), so require a dot.
90 const mentionPattern = /(^|\s)(@[a-z0-9][a-z0-9.-]*\.[a-z]{2,})/gi
91 for (const match of text.matchAll(mentionPattern)) {
92 const handle = match[2]
93 const charStart = (match.index ?? 0) + match[1].length
94 const byteStart = byteLength(text.slice(0, charStart))
95 const byteEnd = byteStart + byteLength(handle)
96 if (insideLink(byteStart, byteEnd)) continue
97 candidates.push({ byteStart, byteEnd, type: 'mention', value: handle.slice(1).replace(/\.+$/, '') })
98 }
99
100 return candidates.sort((a, b) => a.byteStart - b.byteStart)
101}
102
43103export class BlueskyPublishingDriver implements SocialPublishingDriver {
44104 readonly provider: 'bluesky' = 'bluesky'
45105 characterLimit = 300
@@ -111,6 +171,10 @@ export class BlueskyPublishingDriver implements SocialPublishingDriver {
111171
112172 if (post.langs?.length) record.langs = post.langs
113173 if (post.reply) record.reply = post.reply
174
175 const facets = post.facets ?? await this.buildFacets(post.text)
176 if (facets.length) record.facets = facets
177
114178 if (post.external) {
115179 record.embed = {
116180 $type: 'app.bsky.embed.external',
@@ -122,6 +186,18 @@ export class BlueskyPublishingDriver implements SocialPublishingDriver {
122186 }
123187 }
124188
189 // Bluesky records hold a single embed; attached images win over a link
190 // card (the link is still clickable via its facet).
191 const imageMedia = (post.media || []).filter(item => item.bytes?.length).slice(0, 4)
192 if (imageMedia.length) {
193 const images = []
194 for (const item of imageMedia) {
195 const blob = await this.uploadBlob(identity, item.bytes!, item.mimeType || 'image/jpeg')
196 images.push({ image: blob, alt: item.altText || '' })
197 }
198 record.embed = { $type: 'app.bsky.embed.images', images }
199 }
200
125201 const payload = await this.post<CreateRecordResponse>(
126202 '/xrpc/com.atproto.repo.createRecord',
127203 {
@@ -205,6 +281,66 @@ export class BlueskyPublishingDriver implements SocialPublishingDriver {
205281 })
206282 }
207283
284 /**
285 * Resolve link/tag/mention candidates into ATProto facets. Mentions that
286 * fail handle→DID resolution are dropped rather than failing the post.
287 */
288 protected async buildFacets(text: string): Promise<Array<Record<string, unknown>>> {
289 const facets: Array<Record<string, unknown>> = []
290 for (const candidate of detectFacetCandidates(text)) {
291 let feature: Record<string, unknown> | null = null
292 if (candidate.type === 'link')
293 feature = { $type: 'app.bsky.richtext.facet#link', uri: candidate.value }
294 else if (candidate.type === 'tag')
295 feature = { $type: 'app.bsky.richtext.facet#tag', tag: candidate.value }
296 else if (candidate.type === 'mention') {
297 const did = await this.resolveHandle(candidate.value)
298 if (did) feature = { $type: 'app.bsky.richtext.facet#mention', did }
299 }
300 if (feature) {
301 facets.push({
302 index: { byteStart: candidate.byteStart, byteEnd: candidate.byteEnd },
303 features: [feature],
304 })
305 }
306 }
307 return facets
308 }
309
310 /** Handle → DID, or null when the handle doesn't resolve. */
311 protected async resolveHandle(handle: string): Promise<string | null> {
312 try {
313 const url = new URL(`${this.service}/xrpc/com.atproto.identity.resolveHandle`)
314 url.searchParams.set('handle', handle)
315 const payload = await this.request<{ did?: string }>(url, {})
316 return payload.did || null
317 }
318 catch {
319 return null
320 }
321 }
322
323 /** Upload raw image bytes and return the blob ref for embeds. */
324 async uploadBlob(identity: SocialIdentityCredentials, bytes: Uint8Array, mimeType: string): Promise<unknown> {
325 if (!identity.accessToken) throw new Error('Bluesky access token is missing for this identity.')
326 if (bytes.length > 1_000_000)
327 throw new Error('Bluesky images must be 1MB or smaller.')
328
329 const payload = await this.request<{ blob: unknown }>(
330 new URL(`${this.service}/xrpc/com.atproto.repo.uploadBlob`),
331 {
332 method: 'POST',
333 headers: {
334 'content-type': mimeType,
335 'authorization': `Bearer ${identity.accessToken}`,
336 },
337 body: bytes,
338 },
339 )
340
341 return payload.blob
342 }
343
208344 protected async post<T>(path: string, body?: unknown, headers: Record<string, string> = {}): Promise<T> {
209345 return await this.request<T>(new URL(`${this.service}${path}`), {
210346 method: 'POST',