@blogmcp/sdk 0.10.1 → 0.12.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 (59) hide show
  1. package/dist/community/channels.d.ts +3 -2
  2. package/dist/community/client.d.ts +130 -3
  3. package/dist/community/client.js +232 -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 +164 -3
  11. package/dist/community/messages.cs.js +184 -3
  12. package/dist/community/messages.d.ts +19 -1
  13. package/dist/community/messages.en.d.ts +154 -3
  14. package/dist/community/messages.en.js +167 -3
  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 +649 -7
  30. package/dist/community/shapes.js +92 -61
  31. package/dist/community/store.d.ts +27 -0
  32. package/dist/community/store.js +84 -80
  33. package/dist/community/topic.d.ts +173 -0
  34. package/dist/community/topic.js +225 -0
  35. package/dist/nuxt/composables/useAsyncKb.d.ts +10 -4
  36. package/dist/packages/mdx-render-vue/dist/render/gallery/GalleryLightbox.vue.js +2 -2
  37. package/dist/packages/mdx-render-vue/dist/render/tripmap/TripMapDefault.vue.js +36 -36
  38. package/package.json +3 -3
  39. package/src/community/channels.ts +3 -2
  40. package/src/community/client.ts +212 -7
  41. package/src/community/forum.ts +209 -0
  42. package/src/community/index.ts +146 -2
  43. package/src/community/links.ts +64 -4
  44. package/src/community/messages.cs.ts +185 -3
  45. package/src/community/messages.en.ts +168 -3
  46. package/src/community/messages.ts +25 -2
  47. package/src/community/outcome.ts +47 -1
  48. package/src/community/poll.ts +79 -17
  49. package/src/community/realtime/index.ts +124 -48
  50. package/src/community/routes.ts +42 -1
  51. package/src/community/server/bff.ts +89 -30
  52. package/src/community/server/host-routes.ts +20 -0
  53. package/src/community/server/index.ts +5 -1
  54. package/src/community/shapes.ts +677 -6
  55. package/src/community/store.ts +25 -7
  56. package/src/community/topic.ts +521 -0
  57. package/src/core/markdown.ts +1 -1
  58. package/src/nuxt/composables/useAsyncKb.ts +11 -4
  59. package/src/nuxt/nuxt-imports.d.ts +2 -2
@@ -9,6 +9,11 @@
9
9
  * const session = createRealtimeSession({ client, store }) // after the first discussions/list
10
10
  * // on unmount: session.stop()
11
11
  *
12
+ * M3 (m3-contracts.md §3.5, §5.2): a forum topic's store (createTopicStore) works the same way — the session re-reads
13
+ * the topic (refreshTopic) where it re-reads a discussion, and falls back to pollTopicHead. The channel is the topic's
14
+ * conversation's; kb-api mints its token only for an onboarded member or an interactive team session (a visitor's
15
+ * host session is refused `notFound`, so it polls — and `forum/topics/head` stops that poller with `membersOnly`).
16
+ *
12
17
  * What it does:
13
18
  * - asks `me/realtime/token` for a connection token AND the URL to connect to — the only source of that URL (this
14
19
  * entry builds none from configuration: the endpoints are `${url}/connection/websocket`, `${url}/connection/
@@ -38,9 +43,10 @@
38
43
 
39
44
  import type { CommunityCallOptions, CommunityClient } from '../client'
40
45
  import { COMMUNITY_CHANNELS } from '../channels'
41
- import { pollDiscussionHead, type DiscussionHeadPoller, type PollDiscussionHeadOptions } from '../poll'
46
+ import { pollDiscussionHead, pollTopicHead, type DiscussionHeadPoller, type PollDiscussionHeadOptions, type PollTopicHeadOptions } from '../poll'
42
47
  import type { RealtimeEvent, RealtimeToken } from '../shapes'
43
- import { refreshDiscussion, type DiscussionStore } from '../store'
48
+ import { refreshDiscussion, type DiscussionStore, type RealtimeEventOutcome } from '../store'
49
+ import { isTopicStore, refreshTopic, type TopicStore } from '../topic'
44
50
 
45
51
  // ───────────────────────── the part of centrifuge this entry uses ─────────────────────────
46
52
 
@@ -76,9 +82,8 @@ export interface CentrifugeModuleLike {
76
82
 
77
83
  export type RealtimeMode = 'connecting' | 'live' | 'polling' | 'stopped'
78
84
 
79
- export interface RealtimeSessionOptions {
80
- client: Pick<CommunityClient, 'discussions' | 'me' | 'realtime'>
81
- store: DiscussionStore
85
+ /** What every session takes besides its client and store. */
86
+ export interface RealtimeSessionCommonOptions {
82
87
  /**
83
88
  * `disc:<conversationId>`; default the store's conversation (a discussion without one polls until it has one). The id
84
89
  * is used in lower case (kb-api publishes to, and mints tokens for, the lower-case channel).
@@ -98,6 +103,20 @@ export interface RealtimeSessionOptions {
98
103
  signal?: AbortSignal
99
104
  }
100
105
 
106
+ /** An article's discussion: its store (createDiscussionStore) and a client that reads discussions. */
107
+ export interface DiscussionRealtimeSessionOptions extends RealtimeSessionCommonOptions {
108
+ client: Pick<CommunityClient, 'discussions' | 'me' | 'realtime'>
109
+ store: DiscussionStore
110
+ }
111
+
112
+ /** M3: a forum topic: its store (createTopicStore) and a client that reads the forum. */
113
+ export interface TopicRealtimeSessionOptions extends RealtimeSessionCommonOptions {
114
+ client: Pick<CommunityClient, 'forum' | 'me' | 'realtime'>
115
+ store: TopicStore
116
+ }
117
+
118
+ export type RealtimeSessionOptions = DiscussionRealtimeSessionOptions | TopicRealtimeSessionOptions
119
+
101
120
  export interface RealtimeSession {
102
121
  readonly mode: RealtimeMode
103
122
  /** Re-reads the discussion now (coalesced with one already on its way). */
@@ -149,20 +168,93 @@ export function realtimeEndpointsOf(url: string): { endpoints: RealtimeTransport
149
168
  }
150
169
  }
151
170
 
152
- async function loadCentrifuge(option: RealtimeSessionOptions['centrifuge']): Promise<CentrifugeModuleLike | null> {
171
+ /** Said once per page: a missing client is a build or install gap, not a condition of the server. */
172
+ let warnedMissing = false
173
+
174
+ async function loadCentrifuge(option: RealtimeSessionCommonOptions['centrifuge']): Promise<CentrifugeModuleLike | null> {
175
+ let mod: CentrifugeModuleLike | null = null
153
176
  try {
154
- if (typeof option === 'function') return await option()
155
- if (option) return option
177
+ if (typeof option === 'function') mod = await option()
178
+ else if (option) mod = option
156
179
  // The optional peer dependency: absent, the import fails and the session polls.
157
- const mod = (await import('centrifuge')) as unknown as CentrifugeModuleLike
158
- return mod && typeof mod.Centrifuge === 'function' ? mod : null
180
+ else mod = (await import('centrifuge')) as unknown as CentrifugeModuleLike
159
181
  } catch {
160
- return null
182
+ mod = null
183
+ }
184
+ if (mod && typeof mod.Centrifuge === 'function') return mod
185
+ if (!warnedMissing) {
186
+ warnedMissing = true
187
+ // The server offered live updates (`me/realtime/token` is asked only then), the page cannot take them: the
188
+ // module is not installed, or a bundler could not resolve it from this package (a linked workspace copy of the
189
+ // SDK: Vite then ships an optional-peer stub — resolve `centrifuge` from the app's root, e.g. `resolve.dedupe`).
190
+ console.warn('[community] live updates are off on this page: the "centrifuge" module could not be loaded (not installed, or not resolvable from the SDK at build time); the discussion polls instead.')
191
+ }
192
+ return null
193
+ }
194
+
195
+ /** The one thing a session follows — an article's discussion or a forum topic — as far as the session uses it. */
196
+ interface Thread {
197
+ /** What the re-reads and the head poller name: the article's id, or the topic's conversation id; null before one. */
198
+ key(): string | null
199
+ conversationId(): string | null
200
+ viewerMember(): string | null
201
+ subscribe(listener: () => void): () => void
202
+ applyEvent(event: RealtimeEvent): RealtimeEventOutcome
203
+ /** Re-reads what is loaded (refreshDiscussion, refreshTopic). */
204
+ read(key: string, call: CommunityCallOptions): Promise<unknown>
205
+ /** The head poller over `key`; `onNewer` when a head is newer than what is loaded. */
206
+ poll(key: string, options: { visible: () => boolean; signal: AbortSignal; intervalMs?: number; onNewer: () => void }): DiscussionHeadPoller
207
+ }
208
+
209
+ function threadOf(options: RealtimeSessionOptions): Thread {
210
+ const languageCode = options.languageCode ?? null
211
+ if (isTopicStore(options.store)) {
212
+ const { store, client } = options as TopicRealtimeSessionOptions
213
+ return {
214
+ key: () => store.getState().conversationId,
215
+ conversationId: () => store.getState().conversationId,
216
+ viewerMember: () => store.getState().viewer.memberId,
217
+ subscribe: (listener) => store.subscribe(() => listener()),
218
+ applyEvent: (event) => store.applyEvent(event),
219
+ read: (key, call) => refreshTopic(store, client, { conversationId: key, languageCode }, call),
220
+ poll(key, o) {
221
+ const pollOptions: PollTopicHeadOptions = {
222
+ visible: o.visible,
223
+ signal: o.signal,
224
+ onChange: (heads) => {
225
+ if (heads.some((h) => store.applyHead(h))) o.onNewer()
226
+ },
227
+ }
228
+ if (o.intervalMs !== undefined) pollOptions.intervalMs = o.intervalMs
229
+ return pollTopicHead(client, [key], pollOptions)
230
+ },
231
+ }
232
+ }
233
+ const { store, client } = options as DiscussionRealtimeSessionOptions
234
+ return {
235
+ key: () => store.getState().articleId,
236
+ conversationId: () => store.getState().conversationId,
237
+ viewerMember: () => store.getState().viewer.memberId,
238
+ subscribe: (listener) => store.subscribe(() => listener()),
239
+ applyEvent: (event) => store.applyEvent(event),
240
+ read: (key, call) => refreshDiscussion(store, client, { articleId: key, languageCode }, call),
241
+ poll(key, o) {
242
+ const pollOptions: PollDiscussionHeadOptions = {
243
+ visible: o.visible,
244
+ signal: o.signal,
245
+ onChange: (heads) => {
246
+ if (heads.some((h) => store.applyHead(h))) o.onNewer()
247
+ },
248
+ }
249
+ if (o.intervalMs !== undefined) pollOptions.intervalMs = o.intervalMs
250
+ return pollDiscussionHead(client, [key], pollOptions)
251
+ },
161
252
  }
162
253
  }
163
254
 
164
255
  export function createRealtimeSession(options: RealtimeSessionOptions): RealtimeSession {
165
- const { client, store } = options
256
+ const { client } = options
257
+ const thread = threadOf(options)
166
258
  const visible = options.visible ?? ((): boolean => typeof document === 'undefined' || document.visibilityState !== 'hidden')
167
259
  let mode: RealtimeMode = 'connecting'
168
260
  let stopped = false
@@ -182,7 +274,7 @@ export function createRealtimeSession(options: RealtimeSessionOptions): Realtime
182
274
  let readAgain = false
183
275
  /** The connect attempt that is current: an older one still on its way (a token, the module) gives up. */
184
276
  let attempt = 0
185
- let viewerMember: string | null = store.getState().viewer.memberId
277
+ let viewerMember: string | null = thread.viewerMember()
186
278
  let unsubscribeViewer: (() => void) | null = null
187
279
  const controller = new AbortController()
188
280
  const call: CommunityCallOptions = { signal: controller.signal }
@@ -197,12 +289,10 @@ export function createRealtimeSession(options: RealtimeSessionOptions): Realtime
197
289
  }
198
290
  }
199
291
 
200
- const articleId = (): string | null => store.getState().articleId
201
-
202
292
  async function readOnce(): Promise<void> {
203
- const id = articleId()
204
- if (!id || stopped) return
205
- await refreshDiscussion(store, client, { articleId: id, languageCode: options.languageCode ?? null }, call)
293
+ const key = thread.key()
294
+ if (!key || stopped) return
295
+ await thread.read(key, call)
206
296
  }
207
297
 
208
298
  function resync(): Promise<void> {
@@ -247,19 +337,15 @@ export function createRealtimeSession(options: RealtimeSessionOptions): Realtime
247
337
  }
248
338
  }
249
339
 
250
- /** The head poller over the store's article, when there is one and none runs yet. */
340
+ /** A head poller over the thread's key: a newer head re-reads it. */
341
+ const headPoller = (key: string): DiscussionHeadPoller =>
342
+ thread.poll(key, { visible, signal: controller.signal, intervalMs: options.pollIntervalMs, onNewer: () => void resync() })
343
+
344
+ /** The head poller over the store's article (or topic), when there is one and none runs yet. */
251
345
  function startPoller(): void {
252
- const id = articleId()
253
- if (!id || poller || stopped) return
254
- const pollOptions: PollDiscussionHeadOptions = {
255
- visible,
256
- signal: controller.signal,
257
- onChange: (heads) => {
258
- if (heads.some((h) => store.applyHead(h))) void resync()
259
- },
260
- }
261
- if (options.pollIntervalMs !== undefined) pollOptions.intervalMs = options.pollIntervalMs
262
- poller = pollDiscussionHead(client, [id], pollOptions)
346
+ const key = thread.key()
347
+ if (!key || poller || stopped) return
348
+ poller = headPoller(key)
263
349
  }
264
350
 
265
351
  /** Polling for good: the socket goes, the head poller runs (once the store names its article). */
@@ -269,7 +355,7 @@ export function createRealtimeSession(options: RealtimeSessionOptions): Realtime
269
355
  setMode('polling')
270
356
  if (poller) return
271
357
  startPoller()
272
- if (!poller && !unsubscribeStore) unsubscribeStore = store.subscribe(() => startPoller())
358
+ if (!poller && !unsubscribeStore) unsubscribeStore = thread.subscribe(() => startPoller())
273
359
  }
274
360
 
275
361
  /**
@@ -324,7 +410,7 @@ export function createRealtimeSession(options: RealtimeSessionOptions): Realtime
324
410
 
325
411
  const channelOf = (): string | null => {
326
412
  if (typeof options.channel === 'string' && options.channel !== '') return options.channel.toLowerCase()
327
- const id = store.getState().conversationId
413
+ const id = thread.conversationId()
328
414
  return id ? COMMUNITY_CHANNELS.discussion(id) : null
329
415
  }
330
416
 
@@ -410,7 +496,7 @@ export function createRealtimeSession(options: RealtimeSessionOptions): Realtime
410
496
  if (s !== sub || stopped) return
411
497
  const data = isRecord(ctx) ? ctx.data : undefined
412
498
  if (!isRecord(data)) return
413
- if (store.applyEvent(data as unknown as RealtimeEvent) === 'resync') void resync()
499
+ if (thread.applyEvent(data as unknown as RealtimeEvent) === 'resync') void resync()
414
500
  })
415
501
  s.on('subscribed', () => {
416
502
  if (s !== sub || stopped) return
@@ -430,7 +516,7 @@ export function createRealtimeSession(options: RealtimeSessionOptions): Realtime
430
516
  if (channel) subscribe(channel)
431
517
  else {
432
518
  // No conversation yet: poll until the first message creates one, then subscribe.
433
- const wait = store.subscribe(() => {
519
+ const wait = thread.subscribe(() => {
434
520
  const next = channelOf()
435
521
  if (!next || c !== centrifuge || stopped) return
436
522
  wait()
@@ -443,18 +529,8 @@ export function createRealtimeSession(options: RealtimeSessionOptions): Realtime
443
529
  wait()
444
530
  previous?.()
445
531
  }
446
- const id = articleId()
447
- if (id) {
448
- const pollOptions: PollDiscussionHeadOptions = {
449
- visible,
450
- signal: controller.signal,
451
- onChange: (heads) => {
452
- if (heads.some((h) => store.applyHead(h))) void resync()
453
- },
454
- }
455
- if (options.pollIntervalMs !== undefined) pollOptions.intervalMs = options.pollIntervalMs
456
- poller = pollDiscussionHead(client, [id], pollOptions)
457
- }
532
+ const key = thread.key()
533
+ if (key) poller = headPoller(key)
458
534
  }
459
535
  c.connect()
460
536
  }
@@ -503,8 +579,8 @@ export function createRealtimeSession(options: RealtimeSessionOptions): Realtime
503
579
  if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisibility)
504
580
  if (typeof window !== 'undefined') window.addEventListener('online', onOnline)
505
581
  options.signal?.addEventListener('abort', stop, { once: true })
506
- unsubscribeViewer = store.subscribe((state) => {
507
- const next = state.viewer.memberId
582
+ unsubscribeViewer = thread.subscribe(() => {
583
+ const next = thread.viewerMember()
508
584
  if (next === viewerMember) return
509
585
  viewerMember = next
510
586
  reconnect()
@@ -10,7 +10,8 @@
10
10
  * A host serves the operations under ONE relative base (the blog's proxy, a headless site's BFF): the public ones
11
11
  * at `${base}/v1/public/<resource>/<verb>`, the notice form's at `${base}/trust/v1/notices/<verb>`
12
12
  * (`communityOpPath`). The private surfaces have no operation here: their client is its own entry, later
13
- * (community.md §3.7).
13
+ * (community.md §3.7). M3 (m3-contracts.md §3.9): the forum's, the follows' and a category moderator's operations
14
+ * are the public router's too — and no operation of the team router is here (the KB admin calls those itself).
14
15
  *
15
16
  * Browser-safe: nothing here takes a key, and nothing imports `node:*`.
16
17
  */
@@ -74,6 +75,26 @@ export const COMMUNITY_OPS = Object.freeze({
74
75
  'me.erase': op('me.erase', 'public', '/community/v1/public/me/erase'),
75
76
  'me.cancelErase': op('me.cancelErase', 'public', '/community/v1/public/me/erase/cancel'),
76
77
  'legal.current': op('legal.current', 'public', '/community/v1/public/legal/current'),
78
+ // M3 F2–F3 (m3-contracts.md §3.2–§3.3): the forum — its categories, topics, the polling head, a new topic and search;
79
+ // the member's follows of a topic, an article discussion or a category.
80
+ 'forum.categories.list': op('forum.categories.list', 'public', '/community/v1/public/forum/categories/list'),
81
+ 'forum.topics.list': op('forum.topics.list', 'public', '/community/v1/public/forum/topics/list'),
82
+ 'forum.topics.get': op('forum.topics.get', 'public', '/community/v1/public/forum/topics/get'),
83
+ 'forum.topics.head': op('forum.topics.head', 'public', '/community/v1/public/forum/topics/head'),
84
+ 'forum.topics.create': op('forum.topics.create', 'public', '/community/v1/public/forum/topics/create'),
85
+ 'forum.search': op('forum.search', 'public', '/community/v1/public/forum/search'),
86
+ 'me.follows.set': op('me.follows.set', 'public', '/community/v1/public/me/follows/set'),
87
+ 'me.follows.list': op('me.follows.list', 'public', '/community/v1/public/me/follows/list'),
88
+ // M3 F4 (§3.4): a category moderator's operations — a member session with an active appointment; anyone else NOT_FOUND.
89
+ 'moderation.queue': op('moderation.queue', 'public', '/community/v1/public/moderation/queue'),
90
+ 'moderation.getCase': op('moderation.getCase', 'public', '/community/v1/public/moderation/cases/get'),
91
+ 'moderation.decide': op('moderation.decide', 'public', '/community/v1/public/moderation/decide'),
92
+ 'moderation.remove': op('moderation.remove', 'public', '/community/v1/public/moderation/remove'),
93
+ 'moderation.escalate': op('moderation.escalate', 'public', '/community/v1/public/moderation/escalate'),
94
+ 'moderation.setTopicState': op('moderation.setTopicState', 'public', '/community/v1/public/moderation/topics/set-state'),
95
+ 'moderation.moveTopic': op('moderation.moveTopic', 'public', '/community/v1/public/moderation/topics/move'),
96
+ 'moderation.pinTopic': op('moderation.pinTopic', 'public', '/community/v1/public/moderation/topics/pin'),
97
+ 'moderation.reviewPremod': op('moderation.reviewPremod', 'public', '/community/v1/public/moderation/premod/review'),
77
98
  'notices.submit': op('notices.submit', 'notice', '/trust/v1/notices/submit'),
78
99
  'notices.status': op('notices.status', 'notice', '/trust/v1/notices/status'),
79
100
  'notices.appeal': op('notices.appeal', 'notice', '/trust/v1/notices/appeal'),
@@ -124,6 +145,26 @@ export const COMMUNITY_PAGE_SIZE = 50
124
145
  /** Replies one top-level message carries before `repliesTruncated`. */
125
146
  export const COMMUNITY_REPLIES_MAX = 200
126
147
 
148
+ // ───────────────────────── the forum's limits (M3, m3-contracts.md §2.1, §3.2–§3.3, §4.4, Appendix B choice 12) ─────────────────────────
149
+
150
+ /** A topic's title, in characters (`community.topics.title`'s CHECK; `forum/topics/create`, `messages/edit { title }`). */
151
+ export const COMMUNITY_TOPIC_TITLE_MAX = 200
152
+ /** Topics one `forum/topics/list` page holds by default, and at most (`limit` 1..50). */
153
+ export const COMMUNITY_TOPICS_PAGE_SIZE = 30
154
+ export const COMMUNITY_TOPICS_PAGE_MAX = 50
155
+ /** Topics one `forum/topics/head` asks about. */
156
+ export const COMMUNITY_HEAD_TOPICS_MAX = 50
157
+ /** A search query, in characters after trimming (VALIDATION outside it). */
158
+ export const COMMUNITY_SEARCH_QUERY_MIN = 2
159
+ export const COMMUNITY_SEARCH_QUERY_MAX = 200
160
+ /** Results one `forum/search` page holds, and the deepest page (no deeper paging: no bulk read, §4.4). */
161
+ export const COMMUNITY_SEARCH_PAGE_SIZE = 20
162
+ export const COMMUNITY_SEARCH_PAGES_MAX = 5
163
+ /** Follows one member may hold (FOLLOW_LIMIT above it). */
164
+ export const COMMUNITY_FOLLOWS_MAX = 500
165
+ /** A category's slug (`community.forum_categories.slug`'s CHECK): the path segment of its page. */
166
+ export const COMMUNITY_CATEGORY_SLUG_RE = /^[a-z0-9][a-z0-9-]{0,62}$/
167
+
127
168
  /** The Turnstile action the notice form's widget declares; kb-api refuses a token issued for any other. */
128
169
  export const COMMUNITY_NOTICE_TURNSTILE_ACTION = 'community_notice'
129
170
 
@@ -37,6 +37,15 @@
37
37
  * which the page reads as "sign in"); it only lets kb-api count the visitor by their own IP. A 401 is therefore
38
38
  * the key's refusal on a notice route only.
39
39
  *
40
+ * Per request (M3 FX3; m3-contracts.md §5.2, §16.1), `handle(http, options)` takes two options. `serverInitiated`: a read
41
+ * the site's SERVER makes on its own behalf — a tenant-wide state that is the same for every reader, such as the forum's
42
+ * switch the storefront's chrome reads for every page — rather than a visitor's request: no visitor IP is forwarded
43
+ * (`X-Blogmcp-Client-Ip` is left out, whatever the request carries; kb-api counts the call on the site server's own
44
+ * address, as any call without one), the "request without a client IP" warning is not logged for it, and the host's
45
+ * session is not asked (`memberToken` is not called): the site's notice key, else no credential. `signal`: the caller's
46
+ * deadline — aborting it aborts the upstream call beside `timeoutMs`; the answer is then 503 UNAVAILABLE, not logged as
47
+ * an outage (the caller gave up and logs its own timeout); a signal already aborted calls nothing.
48
+ *
40
49
  * kb-api's status and body pass through, with the BFF's own headers (`Cache-Control: private, no-store`,
41
50
  * `Referrer-Policy: same-origin`, `X-Robots-Tag: noindex`, `X-Frame-Options: DENY`, nosniff, JSON) and kb-api's
42
51
  * `Retry-After`. The BFF's own refusals are kb-api's envelope `{ ok: false, code, message }`. UNAVAILABLE (503)
@@ -126,9 +135,24 @@ export interface CommunityBffConfig {
126
135
  logger?: (e: CommunityBffLogEvent) => void
127
136
  }
128
137
 
138
+ /** Per-request options of `CommunityBff.handle` (M3 FX3; the module doc says what each changes). */
139
+ export interface CommunityBffRequestOptions {
140
+ /**
141
+ * A read the site's server makes on its own behalf — a tenant-wide state, the same for every reader (the forum's
142
+ * switch read for every page) —, never a visitor's request: no visitor IP forwarded and no warning for its absence,
143
+ * the host's session not asked (the site's notice key, else no credential). Default false: a visitor's request.
144
+ */
145
+ serverInitiated?: boolean
146
+ /** The caller's deadline: aborting it aborts the upstream call (503 UNAVAILABLE, not logged as an outage). */
147
+ signal?: AbortSignal
148
+ }
149
+
129
150
  export interface CommunityBff {
130
- /** One request of the page's client: its answer, never a throw. */
131
- handle(http: CommunityHttp): Promise<CommunityResponse>
151
+ /**
152
+ * One request of the page's client — or, with `options.serverInitiated`, a read the site's server makes on its own
153
+ * behalf: its answer, never a throw.
154
+ */
155
+ handle(http: CommunityHttp, options?: CommunityBffRequestOptions): Promise<CommunityResponse>
132
156
  }
133
157
 
134
158
  /** The BFF's own refusals (kb-api's envelope); the client maps them like kb-api's codes. */
@@ -298,6 +322,29 @@ function refusal(code: CommunityBffCode): CommunityResponse {
298
322
  return respond(status, JSON.stringify({ ok: false, code, message }))
299
323
  }
300
324
 
325
+ /**
326
+ * The upstream call's signal: the BFF's own timeout and, when the caller gave one, its deadline — whichever fires first.
327
+ * `release` drops the listeners on the caller's signal once the call is done (a caller's signal may outlive it).
328
+ */
329
+ function upstreamSignal(timeoutMs: number, caller: AbortSignal | undefined): { signal: AbortSignal; release(): void } {
330
+ const timeout = AbortSignal.timeout(timeoutMs)
331
+ if (!caller) return { signal: timeout, release: () => {} }
332
+ const controller = new AbortController()
333
+ const abort = (): void => controller.abort()
334
+ if (caller.aborted || timeout.aborted) controller.abort()
335
+ else {
336
+ caller.addEventListener('abort', abort, { once: true })
337
+ timeout.addEventListener('abort', abort, { once: true })
338
+ }
339
+ return {
340
+ signal: controller.signal,
341
+ release: () => {
342
+ caller.removeEventListener('abort', abort)
343
+ timeout.removeEventListener('abort', abort)
344
+ },
345
+ }
346
+ }
347
+
301
348
  /** `notice`: the site's notice key — on a public route kb-api reads the call as anonymous (see the module doc). */
302
349
  type Credential =
303
350
  | { kind: 'member' | 'notice'; token: string }
@@ -392,10 +439,11 @@ export function createCommunityBff(c: CommunityBffConfig): CommunityBff {
392
439
 
393
440
  /**
394
441
  * Whose call this is: the member when the host has a session; else the site's notice key on every route when it
395
- * is configured; else nobody — or, on a notice route without either, nothing the BFF can send.
442
+ * is configured; else nobody — or, on a notice route without either, nothing the BFF can send. A server-initiated
443
+ * read (M3 FX3) is no visitor's: the host's session is not asked.
396
444
  */
397
- async function credentialOf(http: CommunityHttp, noticeRoute: boolean): Promise<Credential> {
398
- const token: unknown = await memberToken(http)
445
+ async function credentialOf(http: CommunityHttp, noticeRoute: boolean, serverInitiated: boolean): Promise<Credential> {
446
+ const token: unknown = serverInitiated ? null : await memberToken(http)
399
447
  if (token !== null && token !== undefined && token !== '') {
400
448
  if (typeof token === 'string' && HEADER_TOKEN_RE.test(token) && token.length <= TOKEN_MAX) {
401
449
  return { kind: 'member', token }
@@ -415,7 +463,7 @@ export function createCommunityBff(c: CommunityBffConfig): CommunityBff {
415
463
  return { kind: 'unavailable' }
416
464
  }
417
465
 
418
- /** Step 5: the upstream call and its answer. */
466
+ /** Step 5: the upstream call and its answer. `caller`: the caller's deadline (M3 FX3), beside the BFF's own timeout. */
419
467
  async function forward(
420
468
  op: string,
421
469
  upstreamPath: string,
@@ -423,29 +471,37 @@ export function createCommunityBff(c: CommunityBffConfig): CommunityBff {
423
471
  credential: { kind: 'member' | 'notice'; token: string } | { kind: 'anonymous' },
424
472
  noticeRoute: boolean,
425
473
  clientIp: string | null,
474
+ caller: AbortSignal | undefined,
426
475
  ): Promise<CommunityResponse> {
427
476
  const headers: Record<string, string> = { 'Content-Type': 'application/json' }
428
477
  if (credential.kind !== 'anonymous') headers.Authorization = `Bearer ${credential.token}`
429
478
  if (clientIp) headers[KB_CLIENT_IP_HEADER] = clientIp
479
+ // A caller that gave up is no outage of kb-api: answered UNAVAILABLE, never logged (the caller logs its timeout).
480
+ const gaveUp = (): boolean => caller?.aborted === true
481
+ const upstream = upstreamSignal(timeoutMs, caller)
430
482
  let res: Response
431
- try {
432
- res = await fetchFn()(`${base}${upstreamPath}`, {
433
- method: 'POST',
434
- headers,
435
- body: bytes,
436
- redirect: 'error',
437
- cache: 'no-store',
438
- signal: AbortSignal.timeout(timeoutMs),
439
- })
440
- } catch {
441
- // The cause is dropped on purpose: a fetch header error quotes the header's value (a key, a token).
442
- return unavailable(op)
443
- }
444
483
  let text: string
445
484
  try {
446
- text = await res.text()
447
- } catch {
448
- return unavailable(op, null, res.status)
485
+ try {
486
+ res = await fetchFn()(`${base}${upstreamPath}`, {
487
+ method: 'POST',
488
+ headers,
489
+ body: bytes,
490
+ redirect: 'error',
491
+ cache: 'no-store',
492
+ signal: upstream.signal,
493
+ })
494
+ } catch {
495
+ // The cause is dropped on purpose: a fetch header error quotes the header's value (a key, a token).
496
+ return gaveUp() ? refusal('UNAVAILABLE') : unavailable(op)
497
+ }
498
+ try {
499
+ text = await res.text()
500
+ } catch {
501
+ return gaveUp() ? refusal('UNAVAILABLE') : unavailable(op, null, res.status)
502
+ }
503
+ } finally {
504
+ upstream.release()
449
505
  }
450
506
  // kb-api answers a JSON object on every one of these routes; anything else came from something in between
451
507
  // (a gateway's error page, a truncated body) and is not passed on.
@@ -471,7 +527,7 @@ export function createCommunityBff(c: CommunityBffConfig): CommunityBff {
471
527
  return respond(res.status, text, retryAfter === null ? {} : { 'Retry-After': String(retryAfter) })
472
528
  }
473
529
 
474
- async function serve(http: CommunityHttp, request: { op: string }): Promise<CommunityResponse> {
530
+ async function serve(http: CommunityHttp, request: { op: string }, options: CommunityBffRequestOptions): Promise<CommunityResponse> {
475
531
  // 1. The method.
476
532
  const method = typeof http.method === 'string' ? http.method.toUpperCase() : ''
477
533
  if (method !== 'POST') return communityUnknownPath()
@@ -497,13 +553,16 @@ export function createCommunityBff(c: CommunityBffConfig): CommunityBff {
497
553
  if (body === null) return unavailable(request.op)
498
554
  if (!body.ok) return refusal(body.code)
499
555
 
500
- // 5. The upstream call.
556
+ // 5. The upstream call — none for a caller that already gave up (M3 FX3: its deadline passed; nothing to log).
501
557
  if (base === null) return unavailable(request.op)
558
+ if (options.signal?.aborted === true) return refusal('UNAVAILABLE')
559
+ const serverInitiated = options.serverInitiated === true
502
560
  const noticeRoute = isNoticeRoute(decision.upstreamPath)
503
- const credential = await credentialOf(http, noticeRoute)
561
+ const credential = await credentialOf(http, noticeRoute, serverInitiated)
504
562
  if (credential.kind === 'unavailable') return unavailable(request.op)
505
- const clientIp = clientIpFrom(http, { header: clientIpHeader })
506
- if (clientIp === null) {
563
+ // A server-initiated read concerns no visitor: no IP forwarded, and its absence is no misconfiguration (M3 FX3).
564
+ const clientIp = serverInitiated ? null : clientIpFrom(http, { header: clientIpHeader })
565
+ if (clientIp === null && !serverInitiated) {
507
566
  warnOnce(
508
567
  'client_ip',
509
568
  '[community] a request without a client IP (no valid edge header or X-Forwarded-For) — check clientIpHeader ' +
@@ -511,14 +570,14 @@ export function createCommunityBff(c: CommunityBffConfig): CommunityBff {
511
570
  "member token or the site's notice key; without one the call is counted on the site server's own IP.",
512
571
  )
513
572
  }
514
- return forward(request.op, decision.upstreamPath, body.bytes, credential, noticeRoute, clientIp)
573
+ return forward(request.op, decision.upstreamPath, body.bytes, credential, noticeRoute, clientIp, options.signal)
515
574
  }
516
575
 
517
576
  return {
518
- async handle(http: CommunityHttp): Promise<CommunityResponse> {
577
+ async handle(http: CommunityHttp, options?: CommunityBffRequestOptions): Promise<CommunityResponse> {
519
578
  const request = { op: 'bff' }
520
579
  try {
521
- return await serve(http, request)
580
+ return await serve(http, request, options && typeof options === 'object' ? options : {})
522
581
  } catch {
523
582
  // An adapter or a memberToken that throws, or a bug: an outage, never a throw (nothing of the error is logged).
524
583
  return unavailable(request.op)
@@ -9,6 +9,9 @@
9
9
  * unknown path through every host, a stale one would forward to a path kb-api no longer serves. The team, adapter
10
10
  * and platform surfaces are never in it (the team is not a host session; the others call kb-api themselves), nor
11
11
  * is either closed surface — route-decision.ts refuses those whatever this list says.
12
+ *
13
+ * M3 (m3-contracts.md §3.9, §5.2): the forum's public operations and a category moderator's (`forum/…`,
14
+ * `me/follows/…`, `moderation/…`) — seventeen, kb-api's since the wave 2 integration (F2, F3, F4).
12
15
  */
13
16
 
14
17
  import type { CommunityHostRoute } from './route-decision'
@@ -19,6 +22,12 @@ export const COMMUNITY_HOST_ROUTES: readonly CommunityHostRoute[] = Object.freez
19
22
  Object.freeze({ method: 'POST', path: '/community/v1/public/blocks/set' }),
20
23
  Object.freeze({ method: 'POST', path: '/community/v1/public/discussions/head' }),
21
24
  Object.freeze({ method: 'POST', path: '/community/v1/public/discussions/list' }),
25
+ Object.freeze({ method: 'POST', path: '/community/v1/public/forum/categories/list' }),
26
+ Object.freeze({ method: 'POST', path: '/community/v1/public/forum/search' }),
27
+ Object.freeze({ method: 'POST', path: '/community/v1/public/forum/topics/create' }),
28
+ Object.freeze({ method: 'POST', path: '/community/v1/public/forum/topics/get' }),
29
+ Object.freeze({ method: 'POST', path: '/community/v1/public/forum/topics/head' }),
30
+ Object.freeze({ method: 'POST', path: '/community/v1/public/forum/topics/list' }),
22
31
  Object.freeze({ method: 'POST', path: '/community/v1/public/legal/current' }),
23
32
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/appeals/file' }),
24
33
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/appeals/list' }),
@@ -29,6 +38,8 @@ export const COMMUNITY_HOST_ROUTES: readonly CommunityHostRoute[] = Object.freez
29
38
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/erase' }),
30
39
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/erase/cancel' }),
31
40
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/export' }),
41
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/follows/list' }),
42
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/follows/set' }),
32
43
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/get' }),
33
44
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/mutes/list' }),
34
45
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/mutes/set' }),
@@ -50,6 +61,15 @@ export const COMMUNITY_HOST_ROUTES: readonly CommunityHostRoute[] = Object.freez
50
61
  Object.freeze({ method: 'POST', path: '/community/v1/public/messages/edit' }),
51
62
  Object.freeze({ method: 'POST', path: '/community/v1/public/messages/post' }),
52
63
  Object.freeze({ method: 'POST', path: '/community/v1/public/messages/report' }),
64
+ Object.freeze({ method: 'POST', path: '/community/v1/public/moderation/cases/get' }),
65
+ Object.freeze({ method: 'POST', path: '/community/v1/public/moderation/decide' }),
66
+ Object.freeze({ method: 'POST', path: '/community/v1/public/moderation/escalate' }),
67
+ Object.freeze({ method: 'POST', path: '/community/v1/public/moderation/premod/review' }),
68
+ Object.freeze({ method: 'POST', path: '/community/v1/public/moderation/queue' }),
69
+ Object.freeze({ method: 'POST', path: '/community/v1/public/moderation/remove' }),
70
+ Object.freeze({ method: 'POST', path: '/community/v1/public/moderation/topics/move' }),
71
+ Object.freeze({ method: 'POST', path: '/community/v1/public/moderation/topics/pin' }),
72
+ Object.freeze({ method: 'POST', path: '/community/v1/public/moderation/topics/set-state' }),
53
73
  Object.freeze({ method: 'POST', path: '/community/v1/public/profile/get' }),
54
74
  Object.freeze({ method: 'POST', path: '/community/v1/public/reactions/set' }),
55
75
  Object.freeze({ method: 'POST', path: '/community/v1/public/realtime/subscribe-token' }),
@@ -24,6 +24,10 @@
24
24
  * return respond(await bff.handle(http))
25
25
  * }
26
26
  *
27
+ * // A read the site's server makes on its own behalf (M3 FX3) — a tenant-wide state, the same for every reader, such
28
+ * // as the forum's switch for the page's chrome: no visitor IP forwarded, no session asked; the page's deadline aborts it.
29
+ * const state = await bff.handle(seam, { serverInitiated: true, signal: AbortSignal.timeout(1_500) })
30
+ *
27
31
  * // A proxy that forwards on its own (the managed blogs): before its other rules, before any cookie or Bearer work.
28
32
  * const decision = communityRouteDecision(request.method, path)
29
33
  * if (decision.kind === 'deny') {
@@ -47,7 +51,7 @@ export { COMMUNITY_UNKNOWN_PATH_BODY, communityUnknownPath } from './unknown-pat
47
51
  export type { CommunityUnknownPathAnswer } from './unknown-path'
48
52
 
49
53
  export { createCommunityBff } from './bff'
50
- export type { CommunityBff, CommunityBffCode, CommunityBffConfig, CommunityBffLogEvent } from './bff'
54
+ export type { CommunityBff, CommunityBffCode, CommunityBffConfig, CommunityBffLogEvent, CommunityBffRequestOptions } from './bff'
51
55
 
52
56
  export { communityServerEnv } from './env'
53
57
  export type { CommunityServerEnv } from './env'