@blogmcp/sdk 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/community/channels.d.ts +3 -2
  2. package/dist/community/client.d.ts +129 -2
  3. package/dist/community/client.js +231 -161
  4. package/dist/community/forum.d.ts +82 -0
  5. package/dist/community/forum.js +96 -0
  6. package/dist/community/index.d.ts +14 -7
  7. package/dist/community/index.js +185 -121
  8. package/dist/community/links.d.ts +38 -0
  9. package/dist/community/links.js +98 -71
  10. package/dist/community/messages.cs.d.ts +160 -1
  11. package/dist/community/messages.cs.js +178 -1
  12. package/dist/community/messages.d.ts +19 -1
  13. package/dist/community/messages.en.d.ts +150 -1
  14. package/dist/community/messages.en.js +161 -1
  15. package/dist/community/messages.js +37 -28
  16. package/dist/community/outcome.d.ts +8 -3
  17. package/dist/community/outcome.js +61 -20
  18. package/dist/community/poll.d.ts +28 -4
  19. package/dist/community/poll.js +70 -47
  20. package/dist/community/realtime/index.d.ts +19 -3
  21. package/dist/community/realtime/index.js +175 -145
  22. package/dist/community/routes.d.ts +36 -1
  23. package/dist/community/routes.js +51 -21
  24. package/dist/community/server/bff.d.ts +25 -2
  25. package/dist/community/server/bff.js +135 -118
  26. package/dist/community/server/host-routes.d.ts +3 -0
  27. package/dist/community/server/host-routes.js +17 -0
  28. package/dist/community/server/index.d.ts +5 -1
  29. package/dist/community/shapes.d.ts +634 -7
  30. package/dist/community/shapes.js +92 -61
  31. package/dist/community/store.d.ts +15 -0
  32. package/dist/community/store.js +65 -61
  33. package/dist/community/topic.d.ts +173 -0
  34. package/dist/community/topic.js +225 -0
  35. package/package.json +3 -3
  36. package/src/community/channels.ts +3 -2
  37. package/src/community/client.ts +209 -5
  38. package/src/community/forum.ts +209 -0
  39. package/src/community/index.ts +146 -2
  40. package/src/community/links.ts +64 -4
  41. package/src/community/messages.cs.ts +179 -1
  42. package/src/community/messages.en.ts +162 -1
  43. package/src/community/messages.ts +25 -2
  44. package/src/community/outcome.ts +47 -1
  45. package/src/community/poll.ts +79 -17
  46. package/src/community/realtime/index.ts +124 -48
  47. package/src/community/routes.ts +42 -1
  48. package/src/community/server/bff.ts +89 -30
  49. package/src/community/server/host-routes.ts +20 -0
  50. package/src/community/server/index.ts +5 -1
  51. package/src/community/shapes.ts +662 -6
  52. package/src/community/store.ts +11 -5
  53. package/src/community/topic.ts +521 -0
@@ -182,8 +182,12 @@ const DELETED_AUTHOR: KnownAuthor = Object.freeze({
182
182
  })
183
183
  const SYSTEM_AUTHOR: KnownAuthor = Object.freeze({ kind: 'system' })
184
184
 
185
- /** A known author kind as the store renders it (a member short of its fields is the deleted placeholder); else null. */
186
- function authorOf(raw: unknown): KnownAuthor | null {
185
+ /**
186
+ * A known author kind as the store renders it (a member short of its fields is the deleted placeholder); else null.
187
+ * M3: a member's `moderator: true` (a moderator's message in a category they moderate, §3.5) is kept, nothing else.
188
+ * The topic store (topic.ts) reads a topic's author through it too.
189
+ */
190
+ export function authorOf(raw: unknown): KnownAuthor | null {
187
191
  if (!isRecord(raw) || !isKnownAuthorKind(raw.kind)) return null
188
192
  if (raw.kind === 'system') return SYSTEM_AUTHOR
189
193
  if (raw.kind === 'staff') {
@@ -193,7 +197,7 @@ function authorOf(raw: unknown): KnownAuthor | null {
193
197
  const handle = str(raw.handle)
194
198
  const displayName = str(raw.displayName)
195
199
  if (memberId === null || handle === null || displayName === null || raw.deleted === true) return DELETED_AUTHOR
196
- return Object.freeze({ kind: 'member', memberId, handle, displayName, avatarPreset: str(raw.avatarPreset) })
200
+ return Object.freeze({ kind: 'member', memberId, handle, displayName, avatarPreset: str(raw.avatarPreset), ...(raw.moderator === true ? { moderator: true as const } : {}) })
197
201
  }
198
202
 
199
203
  function codesOf(raw: unknown): readonly string[] | undefined {
@@ -240,6 +244,8 @@ function messageOf(raw: unknown, topLevel: boolean): DiscussionMessage | null {
240
244
  ...(notes && notes.length > 0 ? { notes } : {}),
241
245
  // Only as kb-api sends it: true, on a `held` message (the author's own, held back by the art. 9 policy).
242
246
  ...(raw.hiddenUntilConsent === true && raw.state === 'held' ? { hiddenUntilConsent: true } : {}),
247
+ // M3 (§4.2): the author's own message waiting in pre-moderation — true on a `held` row only, as kb-api sends it.
248
+ ...(raw.premoderated === true && raw.state === 'held' ? { premoderated: true } : {}),
243
249
  replies: ordered(replies),
244
250
  ...(topLevel && raw.repliesTruncated === true ? { repliesTruncated: true } : {}),
245
251
  })
@@ -832,9 +838,9 @@ type ListClient = Pick<CommunityClient, 'discussions'>
832
838
  /**
833
839
  * Where a store is (its generation, the article it shows), so a loader can tell whether it moved on — reset(), a
834
840
  * page of another article — while a page was on its way. A store of another make has no generation: the article
835
- * it shows is the sign.
841
+ * it shows is the sign. Internal: the topic store (topic.ts) tracks its own discussion store with it.
836
842
  */
837
- function placeOf(store: DiscussionStore): { moved(): boolean; mark(): void } {
843
+ export function placeOf(store: DiscussionStore): { moved(): boolean; mark(): void } {
838
844
  const generation = generations.get(store)
839
845
  let at = generation?.()
840
846
  let articleId = store.getState().articleId
@@ -0,0 +1,521 @@
1
+ /**
2
+ * One forum topic as an immutable two-level tree (m3-contracts.md §5.2, §3.2): the discussion store
3
+ * (createDiscussionStore) under the topic's header. A topic IS a discussion — a `community.conversations` row whose
4
+ * opening post is seq 1 and whose replies are two levels deep, as under an article — so every rule of the
5
+ * discussion store holds unchanged: the cursor pages, the optimistic writes under a `clientMsgId`, the viewer's
6
+ * blocks, the open enums (a message of an unknown author kind or state is skipped), and M2's live updates by `rev`
7
+ * with their `resync` (m2-contracts.md §3.5).
8
+ *
9
+ * What the topic adds:
10
+ * applyPage a `forum/topics/get` page: the messages as a discussion page, the header (`topic`) and the viewer's
11
+ * `moderator` beside them — one change, one notification;
12
+ * applyTopic a newer header of the topic shown: the answer of a title edit (`messages/edit { title }`), of a
13
+ * moderator's lock, move or pin, or a follow's new `following`;
14
+ * applyHead a `forum/topics/head` answer (pollTopicHead): true when newer than what is loaded (→ refreshTopic);
15
+ * applyEvent a `disc:<conversationId>` publication, as the discussion store applies it — and `resync` after a
16
+ * change of the opening post (seq 1), whose title travels in the header, not in the message;
17
+ * the opening post's own delete (its `confirm`) clears the header's title, as the database does („Smazané téma").
18
+ *
19
+ * A null title is not always a deletion (m3-contracts.md §3.1, B06): kb-api withholds it from a viewer while the opening
20
+ * post is held, removed or held back and a reply keeps the topic readable — topicTitleOf tells the two apart by the
21
+ * opening post's state, and a re-read (a resync, a released hold) may bring the title back.
22
+ *
23
+ * A write addressed by the topic's conversation id that comes back `notFound` may be any refusal of the forum's gate
24
+ * (A11): settleTopicFailure re-reads the topic, whose answer names the surface's own code.
25
+ *
26
+ * One store may show one topic after another (reset(), or a page of another topic); an answer that outlives the
27
+ * switch changes nothing, exactly as in the discussion store.
28
+ */
29
+
30
+ import type { CommunityCallOptions, CommunityClient } from './client'
31
+ import type { CommunityFailure, CommunityOutcome } from './outcome'
32
+ import {
33
+ isKnownTopicState,
34
+ type Discussion,
35
+ type DiscussionHead,
36
+ type ForumTopicItem,
37
+ type KnownAuthor,
38
+ type KnownMessageState,
39
+ type ReactionSummary,
40
+ type RealtimeEvent,
41
+ type Topic,
42
+ type TopicHead,
43
+ type TopicState,
44
+ type TopicThread,
45
+ } from './shapes'
46
+ import {
47
+ authorOf,
48
+ createDiscussionStore,
49
+ placeOf,
50
+ type DiscussionMessage,
51
+ type DiscussionState,
52
+ type DiscussionStore,
53
+ type DiscussionViewer,
54
+ type MessageChange,
55
+ type RealtimeEventOutcome,
56
+ } from './store'
57
+
58
+ /** The topic's header as the store keeps it: a known author (a deleted member's placeholder otherwise). */
59
+ export interface TopicHeader {
60
+ readonly conversationId: string
61
+ /** The category the topic lives in (it follows a move); null when kb-api named none. */
62
+ readonly category: { readonly id: string; readonly slug: string; readonly name: string } | null
63
+ /**
64
+ * null once the opening post was deleted, or while kb-api withholds it from the viewer (§3.1): render it through
65
+ * topicTitleOf — „Smazané téma" (`topic.deleted`) for a deleted opening post, `topic.withheld` otherwise.
66
+ */
67
+ readonly title: string | null
68
+ readonly state: TopicState
69
+ readonly pinned: boolean
70
+ readonly createdAt: string
71
+ readonly author: KnownAuthor
72
+ /** The viewer follows the topic. */
73
+ readonly following: boolean
74
+ }
75
+
76
+ /** The viewer of a topic: the discussion's viewer, and whether they moderate the topic's category. */
77
+ export interface TopicViewer extends DiscussionViewer {
78
+ readonly moderator: boolean
79
+ }
80
+
81
+ export interface TopicStoreState {
82
+ /** The topic shown (as kb-api answers it), or null before the first page. */
83
+ readonly conversationId: string | null
84
+ /** Its header, or null before the first page. */
85
+ readonly topic: TopicHeader | null
86
+ /** The messages everyone is shown. */
87
+ readonly count: number
88
+ readonly lastSeq: number
89
+ readonly lastChangeAt: string | null
90
+ /** The loaded top-level messages, oldest first (the opening post is seq 1); an optimistic post comes last. */
91
+ readonly messages: readonly DiscussionMessage[]
92
+ /**
93
+ * The opening post's state as the store has it — its loaded row's (a placeholder's for another member), or
94
+ * `deleted` once the viewer's own delete of it was confirmed (a tombstone without replies leaves the list) — or null
95
+ * while it is not loaded. topicTitleOf reads a missing title by it.
96
+ */
97
+ readonly openingState: KnownMessageState | null
98
+ /** Where „load more" continues, or null when the end is loaded. */
99
+ readonly nextCursor: number | null
100
+ readonly reactionSet: readonly string[]
101
+ readonly preset: string | null
102
+ readonly viewer: TopicViewer
103
+ /** A page was applied. */
104
+ readonly loaded: boolean
105
+ /** A head newer than the loaded pages arrived: refresh. */
106
+ readonly stale: boolean
107
+ }
108
+
109
+ export interface TopicStore {
110
+ getState(): TopicStoreState
111
+ /** Called after every change with the new state; returns the unsubscribe. */
112
+ subscribe(listener: (state: TopicStoreState) => void): () => void
113
+ /** A page of `forum/topics/get`; `cursor` is the one it was asked with (null or absent: the first page). */
114
+ applyPage(page: TopicThread, options?: { cursor?: number | null }): void
115
+ /** A newer header of the topic shown (another topic's is ignored). */
116
+ applyTopic(topic: Topic): void
117
+ /** An optimistic post (`replyToSeq` for a reply), edit or delete, and how it settles — as the discussion store. */
118
+ applyMessage(change: MessageChange): void
119
+ /** True when the head is newer than the loaded pages (the state turns `stale`): refresh. */
120
+ applyHead(head: TopicHead): boolean
121
+ /** A message's reaction summary (a topic has no reactions of its own: the opening post's are seq 1's). */
122
+ applyReaction(target: { readonly conversationId: string; readonly seq: number }, reactions: ReactionSummary): void
123
+ /** The viewer blocked (true) or unblocked (false) a member. */
124
+ collapse(memberId: string, blocked: boolean): void
125
+ /** A publication of the topic's `disc:` channel (`@blogmcp/sdk/community/realtime` hands each one over). */
126
+ applyEvent(event: RealtimeEvent): RealtimeEventOutcome
127
+ /** Back to the empty state (another topic); the answers still on their way are dropped when they come. */
128
+ reset(): void
129
+ }
130
+
131
+ // ───────────────────────── sanitising what the server sent ─────────────────────────
132
+
133
+ type Rec = Record<string, unknown>
134
+ const isRecord = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)
135
+ const str = (v: unknown): string | null => (typeof v === 'string' ? v : null)
136
+
137
+ const NO_REACTIONS: ReactionSummary = Object.freeze({ counts: Object.freeze({}), mine: null })
138
+ const DELETED_AUTHOR: KnownAuthor = Object.freeze({
139
+ kind: 'member',
140
+ memberId: null,
141
+ handle: null,
142
+ displayName: null,
143
+ avatarPreset: null,
144
+ deleted: true,
145
+ })
146
+
147
+ function categoryOf(raw: unknown): TopicHeader['category'] {
148
+ if (!isRecord(raw)) return null
149
+ const id = str(raw.id)
150
+ const slug = str(raw.slug)
151
+ const name = str(raw.name)
152
+ return id === null || slug === null || name === null ? null : Object.freeze({ id, slug, name })
153
+ }
154
+
155
+ /** kb-api's topic as the store keeps it, or null without a conversation id (no topic to show). */
156
+ export function topicHeaderOf(raw: unknown): TopicHeader | null {
157
+ if (!isRecord(raw)) return null
158
+ const conversationId = str(raw.conversationId)
159
+ if (conversationId === null || conversationId === '') return null
160
+ return Object.freeze({
161
+ conversationId,
162
+ category: categoryOf(raw.category),
163
+ title: str(raw.title),
164
+ // An open enum: an unknown state is kept as kb-api sent it (isTopicOpen reads it as closed).
165
+ state: str(raw.state) ?? 'open',
166
+ pinned: raw.pinned === true,
167
+ createdAt: str(raw.createdAt) ?? '',
168
+ author: authorOf(raw.author) ?? DELETED_AUTHOR,
169
+ following: raw.following === true,
170
+ })
171
+ }
172
+
173
+ const sameCategory = (a: TopicHeader['category'], b: TopicHeader['category']): boolean =>
174
+ a === b || (a !== null && b !== null && a.id === b.id && a.slug === b.slug && a.name === b.name)
175
+
176
+ const sameAuthor = (a: KnownAuthor, b: KnownAuthor): boolean => JSON.stringify(a) === JSON.stringify(b)
177
+
178
+ /** Whether two headers say the same (a page that repeats the header keeps the state's identity). */
179
+ function sameHeader(a: TopicHeader | null, b: TopicHeader | null): boolean {
180
+ if (a === b) return true
181
+ if (a === null || b === null) return false
182
+ return (
183
+ a.conversationId === b.conversationId &&
184
+ a.title === b.title &&
185
+ a.state === b.state &&
186
+ a.pinned === b.pinned &&
187
+ a.createdAt === b.createdAt &&
188
+ a.following === b.following &&
189
+ sameCategory(a.category, b.category) &&
190
+ sameAuthor(a.author, b.author)
191
+ )
192
+ }
193
+
194
+ const OPENING_SEQ = 1
195
+
196
+ // ───────────────────────── the store ─────────────────────────
197
+
198
+ /** Each topic store's discussion store, for the loaders below (where it is: its generation and topic). */
199
+ const inners = new WeakMap<TopicStore, DiscussionStore>()
200
+
201
+ export function createTopicStore(): TopicStore {
202
+ /** The topic's messages: a discussion whose „article" key is the topic's conversation id (lower case). */
203
+ const inner = createDiscussionStore()
204
+ let header: TopicHeader | null = null
205
+ let moderator = false
206
+ /** The viewer's own delete of the opening post was confirmed (its row may have left the list); a page decides again. */
207
+ let openingDeleted = false
208
+ const listeners = new Set<(state: TopicStoreState) => void>()
209
+
210
+ /** The last derived state and what it was derived from: an unchanged source keeps the state's identity. */
211
+ let derived: { from: DiscussionState; header: TopicHeader | null; moderator: boolean; openingDeleted: boolean; state: TopicStoreState } | null = null
212
+ let viewerCache: { from: DiscussionViewer; moderator: boolean; viewer: TopicViewer } | null = null
213
+
214
+ const viewerOf = (v: DiscussionViewer): TopicViewer => {
215
+ if (viewerCache && viewerCache.from === v && viewerCache.moderator === moderator) return viewerCache.viewer
216
+ const viewer: TopicViewer = Object.freeze({ ...v, moderator })
217
+ viewerCache = { from: v, moderator, viewer }
218
+ return viewer
219
+ }
220
+
221
+ const stateOf = (): TopicStoreState => {
222
+ const s = inner.getState()
223
+ if (derived && derived.from === s && derived.header === header && derived.moderator === moderator && derived.openingDeleted === openingDeleted) return derived.state
224
+ const opening = s.messages.find((m) => m.seq === OPENING_SEQ)
225
+ const state: TopicStoreState = Object.freeze({
226
+ conversationId: s.loaded ? s.conversationId : null,
227
+ topic: s.loaded ? header : null,
228
+ count: s.count,
229
+ lastSeq: s.lastSeq,
230
+ lastChangeAt: s.lastChangeAt,
231
+ messages: s.messages,
232
+ openingState: opening ? opening.state : openingDeleted && s.loaded ? 'deleted' : null,
233
+ nextCursor: s.nextCursor,
234
+ reactionSet: s.reactionSet,
235
+ preset: s.preset,
236
+ viewer: viewerOf(s.viewer),
237
+ loaded: s.loaded,
238
+ stale: s.stale,
239
+ })
240
+ derived = { from: s, header, moderator, openingDeleted, state }
241
+ return state
242
+ }
243
+
244
+ let last = stateOf()
245
+ /** While one change of the topic runs (a page: the header and the messages), the notification waits for its end. */
246
+ let batching = false
247
+
248
+ const emit = (): void => {
249
+ if (batching) return
250
+ const next = stateOf()
251
+ if (next === last) return
252
+ last = next
253
+ for (const listener of [...listeners]) {
254
+ try {
255
+ listener(next)
256
+ } catch {
257
+ // One view's bug must not stop the others from rendering.
258
+ }
259
+ }
260
+ }
261
+ inner.subscribe(emit)
262
+
263
+ const batch = <T>(change: () => T): T => {
264
+ batching = true
265
+ try {
266
+ return change()
267
+ } finally {
268
+ batching = false
269
+ emit()
270
+ }
271
+ }
272
+
273
+ /** The topic shown, lower case (the discussion store's key), or null. */
274
+ const shownId = (): string | null => inner.getState().articleId
275
+
276
+ function applyPage(page: TopicThread, options: { cursor?: number | null } = {}): void {
277
+ if (!isRecord(page)) return
278
+ const topic = topicHeaderOf(page.topic)
279
+ // A page without its topic names no topic to show.
280
+ if (topic === null) return
281
+ const id = topic.conversationId.toLowerCase()
282
+ const asDiscussion = {
283
+ articleId: id,
284
+ conversationId: topic.conversationId,
285
+ count: page.count,
286
+ lastSeq: page.lastSeq,
287
+ lastChangeAt: page.lastChangeAt,
288
+ messages: page.messages,
289
+ nextCursor: page.nextCursor,
290
+ articleReactions: NO_REACTIONS,
291
+ reactionSet: page.reactionSet,
292
+ preset: page.preset,
293
+ viewer: page.viewer,
294
+ } as Discussion
295
+ batch(() => {
296
+ // Another topic, or a page that carries the opening post: the page says what the opening post is now.
297
+ const another = shownId() !== id
298
+ const hasOpening = Array.isArray(page.messages) && page.messages.some((m) => isRecord(m) && m.seq === OPENING_SEQ)
299
+ if (another || hasOpening) openingDeleted = false
300
+ if (!sameHeader(header, topic)) header = topic
301
+ moderator = isRecord(page.viewer) && page.viewer.moderator === true
302
+ inner.applyPage(asDiscussion, options)
303
+ })
304
+ }
305
+
306
+ function applyTopic(raw: Topic): void {
307
+ const topic = topicHeaderOf(raw)
308
+ const id = shownId()
309
+ if (topic === null || id === null || topic.conversationId.toLowerCase() !== id || sameHeader(header, topic)) return
310
+ header = topic
311
+ emit()
312
+ }
313
+
314
+ /** The opening post's title goes with it: a delete of seq 1 leaves the topic without one (the database's rule). */
315
+ function titleCleared(): void {
316
+ openingDeleted = true
317
+ if (header === null || header.title === null) return
318
+ header = Object.freeze({ ...header, title: null })
319
+ }
320
+
321
+ function applyMessage(change: MessageChange): void {
322
+ if (!isRecord(change)) return
323
+ batch(() => {
324
+ const before = inner.getState()
325
+ inner.applyMessage(change)
326
+ if (change.type !== 'confirm' || inner.getState() === before) return
327
+ const row = isRecord(change.message) ? change.message : null
328
+ if (row !== null && row.seq === OPENING_SEQ && row.state === 'deleted') titleCleared()
329
+ })
330
+ }
331
+
332
+ function applyHead(head: TopicHead): boolean {
333
+ if (!isRecord(head) || typeof head.conversationId !== 'string') return false
334
+ const asDiscussion = { articleId: head.conversationId, count: head.count, lastSeq: head.lastSeq, lastChangeAt: head.lastChangeAt } as DiscussionHead
335
+ return inner.applyHead(asDiscussion)
336
+ }
337
+
338
+ function applyReaction(target: { readonly conversationId: string; readonly seq: number }, reactions: ReactionSummary): void {
339
+ // Only a message's: a topic has no reactions of its own (the article's `{ articleId }` target names none here).
340
+ if (!isRecord(target) || typeof target.conversationId !== 'string') return
341
+ inner.applyReaction({ conversationId: target.conversationId, seq: target.seq }, reactions)
342
+ }
343
+
344
+ function applyEvent(event: RealtimeEvent): RealtimeEventOutcome {
345
+ if (!isRecord(event)) return 'dropped'
346
+ // An article's own reactions (no seq): no such thing on a topic.
347
+ if (event.kind === 'reaction' && event.seq === undefined) return 'dropped'
348
+ const outcome = batch(() => inner.applyEvent(event))
349
+ const message = isRecord(event.message) ? event.message : null
350
+ const opening = message !== null && message.seq === OPENING_SEQ && (event.kind === 'edit' || event.kind === 'delete' || event.kind === 'message')
351
+ // The opening post changed (an edit, a removal, a delete): its title travels in the header — read the topic again.
352
+ return outcome === 'applied' && opening ? 'resync' : outcome
353
+ }
354
+
355
+ const store: TopicStore = {
356
+ getState: stateOf,
357
+ subscribe(listener) {
358
+ listeners.add(listener)
359
+ return () => {
360
+ listeners.delete(listener)
361
+ }
362
+ },
363
+ applyPage,
364
+ applyTopic,
365
+ applyMessage,
366
+ applyHead,
367
+ applyReaction,
368
+ collapse: (memberId, blocked) => inner.collapse(memberId, blocked),
369
+ applyEvent,
370
+ reset() {
371
+ batch(() => {
372
+ header = null
373
+ moderator = false
374
+ openingDeleted = false
375
+ inner.reset()
376
+ })
377
+ },
378
+ }
379
+ inners.set(store, inner)
380
+ return store
381
+ }
382
+
383
+ // ───────────────────────── selectors ─────────────────────────
384
+
385
+ /**
386
+ * Whether the topic takes new messages: an `open` topic. `locked` and `archived` do not (TOPIC_LOCKED), and neither
387
+ * does a state this SDK does not know — offer no composer; kb-api's `viewer.canPost` still has the last word.
388
+ */
389
+ export function isTopicOpen(topic: Pick<TopicHeader, 'state'> | Pick<Topic, 'state'> | null | undefined): boolean {
390
+ return topic !== null && topic !== undefined && isKnownTopicState(topic.state) && topic.state === 'open'
391
+ }
392
+
393
+ /**
394
+ * How a topic's title reads (m3-contracts.md §3.1, §3.2, §5.2; B06): `shown` with its text; `deleted` — the opening
395
+ * post was deleted and its title went with it („Smazané téma", `topic.deleted`); `withheld` — kb-api keeps the title
396
+ * from this viewer while the opening post is held, removed or held back (`topic.withheld`). A null title is never read
397
+ * as a deletion without the opening post's own word for it.
398
+ */
399
+ export type TopicTitle =
400
+ | { readonly kind: 'shown'; readonly text: string }
401
+ | { readonly kind: 'deleted' }
402
+ | { readonly kind: 'withheld' }
403
+
404
+ const TITLE_DELETED: TopicTitle = Object.freeze({ kind: 'deleted' })
405
+ const TITLE_WITHHELD: TopicTitle = Object.freeze({ kind: 'withheld' })
406
+
407
+ function titleFrom(title: unknown, openingState: unknown): TopicTitle {
408
+ if (typeof title === 'string' && title.trim() !== '') return Object.freeze({ kind: 'shown', text: title })
409
+ return openingState === 'deleted' ? TITLE_DELETED : TITLE_WITHHELD
410
+ }
411
+
412
+ /**
413
+ * The title of a topic as it reads — from a topic store's state (its header's title, and its opening post, seq 1, for
414
+ * why a title is missing) or from anything that carries `title` and `openingState`: a category's row, a forum search
415
+ * hit, a moderator's package item of an opening post (M3 FX2, S12). `withheld` for anything else.
416
+ */
417
+ export function topicTitleOf(source: TopicStoreState | Pick<ForumTopicItem, 'title' | 'openingState'> | null | undefined): TopicTitle {
418
+ if (!isRecord(source)) return TITLE_WITHHELD
419
+ if ('messages' in source && 'topic' in source) {
420
+ const { topic, openingState } = source as unknown as Pick<TopicStoreState, 'topic' | 'openingState'>
421
+ return titleFrom(isRecord(topic) ? topic.title : null, openingState)
422
+ }
423
+ const item = source as Pick<ForumTopicItem, 'title' | 'openingState'>
424
+ return titleFrom(item.title, item.openingState)
425
+ }
426
+
427
+ // ───────────────────────── loading through the client ─────────────────────────
428
+
429
+ /** Pages one refresh may read before it stops (the rest stays behind „load more"), as refreshDiscussion. */
430
+ const REFRESH_MAX_PAGES = 20
431
+
432
+ type TopicClient = Pick<CommunityClient, 'forum'>
433
+
434
+ /** Where a topic store is (its discussion store's generation and topic); a store of another make: the topic it shows. */
435
+ function topicPlaceOf(store: TopicStore): { moved(): boolean; mark(): void } {
436
+ const inner = inners.get(store)
437
+ if (inner) return placeOf(inner)
438
+ let id = store.getState().conversationId
439
+ return {
440
+ moved: () => store.getState().conversationId !== id,
441
+ mark() {
442
+ id = store.getState().conversationId
443
+ },
444
+ }
445
+ }
446
+
447
+ const cursorOf = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null)
448
+
449
+ /**
450
+ * Loads the topic, or brings the loaded pages up to date (after a newer head, a `resync`): the first page, then the
451
+ * next ones until the pages loaded before are covered — refreshDiscussion's rules over `forum/topics/get`. The first
452
+ * failure is the outcome (`membersOnly` for a viewer the forum is not open to, `notFound` for a topic they may not
453
+ * see); a page that comes back after the store moved on (reset(), another topic) is not applied.
454
+ */
455
+ export async function refreshTopic(
456
+ store: TopicStore,
457
+ client: TopicClient,
458
+ input: { conversationId: string; languageCode?: string | null },
459
+ options?: CommunityCallOptions,
460
+ ): Promise<CommunityOutcome<TopicStoreState>> {
461
+ const before = store.getState()
462
+ const until = before.loaded ? before.nextCursor : 0
463
+ const place = topicPlaceOf(store)
464
+ let cursor: number | null = null
465
+ for (let page = 0; page < REFRESH_MAX_PAGES; page++) {
466
+ const r = await client.forum.topics.get({ conversationId: input.conversationId, languageCode: input.languageCode ?? null, cursor }, options)
467
+ if (!r.ok) return r
468
+ if (place.moved()) break
469
+ store.applyPage(r.value, { cursor })
470
+ place.mark()
471
+ const next = cursorOf(r.value.nextCursor)
472
+ if (next === null || (until !== null && next >= until) || (cursor !== null && next <= cursor)) break
473
+ cursor = next
474
+ }
475
+ return { ok: true, value: store.getState() }
476
+ }
477
+
478
+ /** The next page after the loaded ones („load more"), as loadMoreDiscussion. */
479
+ export async function loadMoreTopic(
480
+ store: TopicStore,
481
+ client: TopicClient,
482
+ input: { conversationId: string; languageCode?: string | null },
483
+ options?: CommunityCallOptions,
484
+ ): Promise<CommunityOutcome<TopicStoreState>> {
485
+ const cursor = store.getState().nextCursor
486
+ if (cursor === null) return { ok: true, value: store.getState() }
487
+ const place = topicPlaceOf(store)
488
+ const r = await client.forum.topics.get({ conversationId: input.conversationId, languageCode: input.languageCode ?? null, cursor }, options)
489
+ if (!r.ok) return r
490
+ if (!place.moved()) store.applyPage(r.value, { cursor })
491
+ return { ok: true, value: store.getState() }
492
+ }
493
+
494
+ /**
495
+ * What a refused write addressed by the topic's conversation id means (m3-contracts.md §3.1, §5.2; A11). kb-api answers
496
+ * every refusal of the forum's gate on such an operation — the forum switched off, the module dark, a viewer the forum
497
+ * is not open to, a topic the viewer may no longer see — as the one `notFound` an unknown id gets, so a `notFound`
498
+ * re-reads the topic (refreshTopic): its refusal is the surface's own code (`surfaceOff`, `unavailable` for a dark
499
+ * module, `membersOnly` with its `needs`, `notFound` for the topic itself). A topic that reads fine keeps the write's
500
+ * own `notFound` — the message it named is gone, and the store now shows the topic as it is. Any other refusal comes
501
+ * back as it is, nothing read.
502
+ */
503
+ export async function settleTopicFailure(
504
+ store: TopicStore,
505
+ client: TopicClient,
506
+ input: { conversationId: string; languageCode?: string | null },
507
+ failure: CommunityFailure,
508
+ options?: CommunityCallOptions,
509
+ ): Promise<CommunityFailure> {
510
+ if (failure.code !== 'notFound') return failure
511
+ const r = await refreshTopic(store, client, input, options)
512
+ return r.ok ? failure : r
513
+ }
514
+
515
+ /**
516
+ * Whether a store is a topic store (its own `applyTopic`) — how `@blogmcp/sdk/community/realtime` tells a topic from
517
+ * an article discussion. Structural on purpose: a store from another copy of the SDK counts too.
518
+ */
519
+ export function isTopicStore(store: unknown): store is TopicStore {
520
+ return isRecord(store) && typeof (store as Partial<TopicStore>).applyTopic === 'function' && typeof (store as Partial<TopicStore>).getState === 'function'
521
+ }