File
Blob: src/shared/doc-messages.ts
| 1 | /** Custom messages sent between clients and DocSync via y-partyserver's custom message channel. */ |
| 2 | |
| 3 | export type PageMetadataRefresh = { |
| 4 | type: "page-metadata-refresh"; |
| 5 | }; |
| 6 | |
| 7 | export type PageMetadataUpdated = { |
| 8 | type: "page-metadata-updated"; |
| 9 | pageId: string; |
| 10 | icon: string | null; |
| 11 | cover_url: string | null; |
| 12 | }; |
| 13 | |
| 14 | export type DocCustomMessage = PageMetadataRefresh | PageMetadataUpdated; |
| 15 | |
| 16 | function isRecord(value: unknown): value is Record<string, unknown> { |
| 17 | return !!value && typeof value === "object" && !Array.isArray(value); |
| 18 | } |
| 19 | |
| 20 | function isStringOrNull(value: unknown): value is string | null { |
| 21 | return typeof value === "string" || value === null; |
| 22 | } |
| 23 | |
| 24 | export function parseDocMessage(raw: string): DocCustomMessage | null { |
| 25 | try { |
| 26 | const parsed = JSON.parse(raw); |
| 27 | if (!isRecord(parsed) || typeof parsed.type !== "string") { |
| 28 | return null; |
| 29 | } |
| 30 | |
| 31 | if (parsed.type === "page-metadata-refresh") { |
| 32 | return { type: "page-metadata-refresh" }; |
| 33 | } |
| 34 | |
| 35 | if ( |
| 36 | parsed.type === "page-metadata-updated" && |
| 37 | typeof parsed.pageId === "string" && |
| 38 | isStringOrNull(parsed.icon) && |
| 39 | isStringOrNull(parsed.cover_url) |
| 40 | ) { |
| 41 | return { |
| 42 | type: "page-metadata-updated", |
| 43 | pageId: parsed.pageId, |
| 44 | icon: parsed.icon, |
| 45 | cover_url: parsed.cover_url, |
| 46 | }; |
| 47 | } |
| 48 | |
| 49 | return null; |
| 50 | } catch { |
| 51 | return null; |
| 52 | } |
| 53 | } |