@blogmcp/sdk 0.8.1 → 0.9.1

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 (89) hide show
  1. package/dist/community/channels.d.ts +12 -0
  2. package/dist/community/channels.js +7 -0
  3. package/dist/community/client.d.ts +211 -0
  4. package/dist/community/client.js +188 -0
  5. package/dist/community/index.d.ts +34 -0
  6. package/dist/community/index.js +93 -0
  7. package/dist/community/links.d.ts +73 -0
  8. package/dist/community/links.js +85 -0
  9. package/dist/community/messages.cs.d.ts +331 -0
  10. package/dist/community/messages.cs.js +342 -0
  11. package/dist/community/messages.d.ts +40 -0
  12. package/dist/community/messages.en.d.ts +315 -0
  13. package/dist/community/messages.en.js +313 -0
  14. package/dist/community/messages.js +66 -0
  15. package/dist/community/outcome.d.ts +96 -0
  16. package/dist/community/outcome.js +211 -0
  17. package/dist/community/poll.d.ts +35 -0
  18. package/dist/community/poll.js +70 -0
  19. package/dist/community/routes.d.ts +110 -0
  20. package/dist/community/routes.js +66 -0
  21. package/dist/community/server/bff.d.ts +123 -0
  22. package/dist/community/server/bff.js +214 -0
  23. package/dist/community/server/env.d.ts +20 -0
  24. package/dist/community/server/env.js +16 -0
  25. package/dist/community/server/host-routes.d.ts +15 -0
  26. package/dist/community/server/host-routes.js +35 -0
  27. package/dist/community/server/http.d.ts +64 -0
  28. package/dist/community/server/http.js +90 -0
  29. package/dist/community/server/index.d.ts +45 -0
  30. package/dist/community/server/index.js +19 -0
  31. package/dist/community/server/route-decision.d.ts +70 -0
  32. package/dist/community/server/route-decision.js +89 -0
  33. package/dist/community/server/unknown-path.d.ts +21 -0
  34. package/dist/community/server/unknown-path.js +11 -0
  35. package/dist/community/shapes.d.ts +472 -0
  36. package/dist/community/shapes.js +63 -0
  37. package/dist/community/store.d.ts +183 -0
  38. package/dist/community/store.js +423 -0
  39. package/dist/community/transport.d.ts +42 -0
  40. package/dist/community/transport.js +59 -0
  41. package/dist/core/client.d.ts +17 -0
  42. package/dist/core/client.js +58 -55
  43. package/dist/core/comments-legacy.d.ts +19 -0
  44. package/dist/core/comments-legacy.js +18 -0
  45. package/dist/core/index.d.ts +3 -0
  46. package/dist/core/index.js +107 -101
  47. package/dist/core/queries.d.ts +46 -0
  48. package/dist/core/queries.js +128 -84
  49. package/dist/core/seo.js +40 -39
  50. package/dist/core/translations/cs.json.js +6 -6
  51. package/dist/core/translations/en.json.js +1 -1
  52. package/dist/core/types.d.ts +23 -1
  53. package/dist/core/view-model.d.ts +7 -0
  54. package/dist/core/view-model.js +29 -25
  55. package/dist/packages/tripmap-core/dist/generated/maplibre-worker.bundle.js +1 -1
  56. package/dist/react/KbMdxContent.js +4 -3
  57. package/dist/vue/components/KbMdxContent.vue2.js +3 -2
  58. package/dist/vue/composables/useKbComments.d.ts +8 -0
  59. package/package.json +13 -4
  60. package/src/community/channels.ts +12 -0
  61. package/src/community/client.ts +437 -0
  62. package/src/community/index.ts +192 -0
  63. package/src/community/links.ts +174 -0
  64. package/src/community/messages.cs.ts +371 -0
  65. package/src/community/messages.en.ts +341 -0
  66. package/src/community/messages.ts +112 -0
  67. package/src/community/outcome.ts +317 -0
  68. package/src/community/poll.ts +154 -0
  69. package/src/community/routes.ts +139 -0
  70. package/src/community/server/bff.ts +530 -0
  71. package/src/community/server/env.ts +42 -0
  72. package/src/community/server/host-routes.ts +48 -0
  73. package/src/community/server/http.ts +175 -0
  74. package/src/community/server/index.ts +55 -0
  75. package/src/community/server/route-decision.ts +226 -0
  76. package/src/community/server/unknown-path.ts +32 -0
  77. package/src/community/shapes.ts +541 -0
  78. package/src/community/store.ts +786 -0
  79. package/src/community/transport.ts +111 -0
  80. package/src/core/client.ts +24 -1
  81. package/src/core/comments-legacy.ts +39 -0
  82. package/src/core/index.ts +8 -0
  83. package/src/core/queries.ts +93 -0
  84. package/src/core/seo.ts +5 -1
  85. package/src/core/translations/cs.json +3 -1
  86. package/src/core/translations/en.json +3 -1
  87. package/src/core/types.ts +19 -1
  88. package/src/core/view-model.ts +12 -1
  89. package/src/vue/composables/useKbComments.ts +8 -0
@@ -4,6 +4,7 @@ import { stripFrontmatter as y, HAS_MDX_RE as g, extractMdxComponents as b } fro
4
4
  import { sanitizeHtml as d } from "@blogmcp/sanitize";
5
5
  import { defaultImageHtml as k } from "../core/markdown.js";
6
6
  import { prepareProps as v } from "@blogmcp/mdx-schema/prepareProps";
7
+ import "@blogmcp/mdx-schema/title";
7
8
  import { getComponentMetadata as M } from "@blogmcp/mdx-schema/metadata";
8
9
  function c(m) {
9
10
  return new h({
@@ -69,7 +70,7 @@ function u(m, t, r) {
69
70
  return s(l, { key: o, ...e.props }, a);
70
71
  });
71
72
  }
72
- function N({
73
+ function S({
73
74
  content: m,
74
75
  components: t = {},
75
76
  imageRenderer: r
@@ -88,6 +89,6 @@ function N({
88
89
  );
89
90
  }
90
91
  export {
91
- N as KbMdxContent,
92
- N as default
92
+ S as KbMdxContent,
93
+ S as default
93
94
  };
@@ -2,9 +2,10 @@ import { defineComponent as R, withAsyncContext as k, inject as E, computed as C
2
2
  import { KB_IMAGE_RENDERER_KEY as D } from "../plugin.js";
3
3
  import { defaultImageHtml as S, createMarkedInstance as T, parseMarkdownSafe as F } from "../../core/markdown.js";
4
4
  import { prepareProps as I } from "@blogmcp/mdx-schema/prepareProps";
5
+ import "@blogmcp/mdx-schema/title";
5
6
  import { getComponentMetadata as K } from "@blogmcp/mdx-schema/metadata";
6
7
  import { sanitizeHtml as P } from "@blogmcp/sanitize";
7
- const W = { class: "mdx-content" }, X = ["innerHTML"], Z = /* @__PURE__ */ R({
8
+ const W = { class: "mdx-content" }, X = ["innerHTML"], $ = /* @__PURE__ */ R({
8
9
  __name: "KbMdxContent",
9
10
  props: {
10
11
  content: {}
@@ -74,5 +75,5 @@ const W = { class: "mdx-content" }, X = ["innerHTML"], Z = /* @__PURE__ */ R({
74
75
  }
75
76
  });
76
77
  export {
77
- Z as default
78
+ $ as default
78
79
  };
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { type Ref, type DeepReadonly } from 'vue';
9
9
  import type { Comment, CommentResult } from '../../core/types.js';
10
+ /** @deprecated Since 0.9.0, removed in 1.0 — see {@link useKbComments}. */
10
11
  export interface UseKbCommentsReturn {
11
12
  comments: DeepReadonly<Ref<Comment[]>>;
12
13
  totalCount: DeepReadonly<Ref<number>>;
@@ -34,4 +35,11 @@ export interface UseKbCommentsReturn {
34
35
  }) => void;
35
36
  clearState: () => void;
36
37
  }
38
+ /**
39
+ * The legacy comment thread of an article.
40
+ *
41
+ * @deprecated Since 0.9.0, removed in 1.0: discussions are Comments 2.0 — the `<blogmcp-discussion>` element of
42
+ * `@blogmcp/community` (`<KbDiscussion>` in Vue) over `@blogmcp/sdk/community`. Reads keep working through kb-api's
43
+ * compatible layer; writes answer `COMMENTS_FROZEN` / `COMMENTS_MOVED` during and after the tenant's cutover.
44
+ */
37
45
  export declare function useKbComments(): UseKbCommentsReturn;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blogmcp/sdk",
3
- "version": "0.8.1",
3
+ "version": "0.9.1",
4
4
  "description": "Headless SDK for Knowledge Base blog — core client, Vue composables, Nuxt adapter",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -39,6 +39,14 @@
39
39
  "./consultations/server": {
40
40
  "types": "./dist/consultations/server/index.d.ts",
41
41
  "import": "./dist/consultations/server/index.js"
42
+ },
43
+ "./community": {
44
+ "types": "./dist/community/index.d.ts",
45
+ "import": "./dist/community/index.js"
46
+ },
47
+ "./community/server": {
48
+ "types": "./dist/community/server/index.d.ts",
49
+ "import": "./dist/community/server/index.js"
42
50
  }
43
51
  },
44
52
  "main": "./dist/core/index.js",
@@ -74,8 +82,8 @@
74
82
  }
75
83
  },
76
84
  "dependencies": {
77
- "@blogmcp/mdx-schema": "^0.8.1",
78
- "@blogmcp/sanitize": "^0.8.1",
85
+ "@blogmcp/mdx-schema": "^0.9.1",
86
+ "@blogmcp/sanitize": "^0.9.1",
79
87
  "marked": "^15.0.7"
80
88
  },
81
89
  "optionalDependencies": {
@@ -106,7 +114,8 @@
106
114
  "vue",
107
115
  "nuxt",
108
116
  "graphql",
109
- "consultations"
117
+ "consultations",
118
+ "community"
110
119
  ],
111
120
  "license": "MIT"
112
121
  }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The realtime channel names, reserved now so the later realtime (M2) adds on without renaming anything
3
+ * (docs/internal/m1-contracts.md §10.2; community.md §3.7, §7.4). Constants only: M1 opens no socket — a
4
+ * discussion is kept fresh by pollDiscussionHead.
5
+ *
6
+ * `d:<conversationId>` carries a public discussion's projection; `u:inbox` is the member's own channel (ids and
7
+ * codes only, community.md invariant 6).
8
+ */
9
+ export const COMMUNITY_CHANNELS = Object.freeze({
10
+ discussion: (conversationId: string): string => `d:${conversationId}`,
11
+ inbox: 'u:inbox',
12
+ } as const)
@@ -0,0 +1,437 @@
1
+ /**
2
+ * The community's public client (docs/internal/m1-contracts.md §10.2): one method per operation of kb-api's public
3
+ * API and notice form (§7.4, §7.7, §8.3), each a POST of a JSON body through the host — never to kb-api itself.
4
+ *
5
+ * const community = createCommunityClient({ base: '/api/community' })
6
+ * const page = await community.discussions.list({ articleId, languageCode: 'cs' })
7
+ * if (page.ok) store.applyPage(page.value)
8
+ * else show(communityMessage(lang, `error.${page.code}`))
9
+ *
10
+ * Every method resolves to a CommunityOutcome and never throws: a refusal is `{ ok: false, code }` with the page's
11
+ * code (outcome.ts), an unreachable host is `unavailable`. The body sent is built from the fields the operation
12
+ * takes — anything else the caller passed stays home (kb-api refuses unknown fields). The answer is what kb-api sent,
13
+ * typed (shapes.ts); its open enums are the page's to skip (the discussion store does it for a thread).
14
+ *
15
+ * Built once per page (or element): it holds no state but its configuration.
16
+ */
17
+
18
+ import {
19
+ communityFailureOf,
20
+ communityOutcomeOf,
21
+ isLoggedCommunityOutcome,
22
+ type CommunityFailure,
23
+ type CommunityLogger,
24
+ type CommunityOutcome,
25
+ type CommunityUiCode,
26
+ } from './outcome'
27
+ import { COMMUNITY_OPS, type CommunityOpName } from './routes'
28
+ import {
29
+ isKnownNeed,
30
+ type AppealItem,
31
+ type BlockEntry,
32
+ type CommunityPage,
33
+ type CurrentLegalText,
34
+ type DecisionSummary,
35
+ type Discussion,
36
+ type DiscussionHead,
37
+ type DiscussionListInput,
38
+ type KnownNeed,
39
+ type LegalTextKind,
40
+ type MemberExport,
41
+ type MessageEditInput,
42
+ type MessagePostInput,
43
+ type MessageReportInput,
44
+ type MyState,
45
+ type NoticeReceipt,
46
+ type NoticeStatus,
47
+ type NoticeSubmitInput,
48
+ type NotificationItem,
49
+ type OnboardInput,
50
+ type OwnProfile,
51
+ type ProfileUpdateInput,
52
+ type PublicMessage,
53
+ type PublicProfile,
54
+ type ReactionSummary,
55
+ type ReactionTarget,
56
+ type ReportItem,
57
+ type Statement,
58
+ type WriteAnswer,
59
+ } from './shapes'
60
+ import { assertCommunityBase, fetchTransport, type CommunityTransport, type CommunityTransportAnswer } from './transport'
61
+
62
+ export interface CommunityClientConfig {
63
+ /**
64
+ * The HOST's relative base, e.g. `/api/community` (the managed blog's proxy, a headless site's BFF). Never
65
+ * kb-api's origin: an absolute URL throws a TypeError here.
66
+ */
67
+ base: string
68
+ /** The replaceable layer (default `fetchTransport(base)`): a test injects one, a signing transport plugs in later. */
69
+ transport?: CommunityTransport
70
+ /**
71
+ * Per request, in milliseconds (default 10 000): 1 … 2 147 483 647, the range a timer keeps; a fraction is rounded
72
+ * down. Anything else (0, a negative, `Infinity`, `NaN`, past the range) is the default, warned once.
73
+ */
74
+ timeoutMs?: number
75
+ now?: () => number
76
+ /** Sees operation, outcome, kb-api code and status of the failures worth an operator's eye — nothing else. */
77
+ logger?: CommunityLogger
78
+ }
79
+
80
+ /** Per call: a signal that cancels the request (an element that unmounts). */
81
+ export interface CommunityCallOptions {
82
+ signal?: AbortSignal
83
+ }
84
+
85
+ type Call<I, T> = (input: I, options?: CommunityCallOptions) => Promise<CommunityOutcome<T>>
86
+ type CallOptionalInput<I, T> = (input?: I, options?: CommunityCallOptions) => Promise<CommunityOutcome<T>>
87
+ type CallNoInput<T> = (options?: CommunityCallOptions) => Promise<CommunityOutcome<T>>
88
+
89
+ export interface CommunityClient {
90
+ discussions: {
91
+ /** One page of an article's discussion (anonymous allowed); `cursor` is the previous page's `nextCursor`. */
92
+ list: Call<DiscussionListInput, Discussion>
93
+ /** The polling signal of up to COMMUNITY_HEAD_ARTICLES_MAX articles (pollDiscussionHead). */
94
+ head: Call<{ articleIds: readonly string[] }, { heads: DiscussionHead[] }>
95
+ }
96
+ messages: {
97
+ post: Call<MessagePostInput, WriteAnswer>
98
+ edit: Call<MessageEditInput, WriteAnswer>
99
+ /** The member's own message becomes a tombstone (a placeholder only while it has visible replies). */
100
+ delete: Call<{ conversationId: string; seq: number }, { message: PublicMessage }>
101
+ report: Call<MessageReportInput, { caseId: string }>
102
+ }
103
+ reactions: {
104
+ /** `emoji: null` removes the member's reaction. */
105
+ set: Call<{ target: ReactionTarget; emoji: string | null }, { target: ReactionTarget; reactions: ReactionSummary }>
106
+ }
107
+ blocks: {
108
+ /** Silent: the blocked member learns of it from nothing. Their messages come back `collapsed`. */
109
+ set: Call<{ memberId: string; blocked: boolean }, { memberId: string; blocked: boolean }>
110
+ list: CallNoInput<{ blocks: BlockEntry[] }>
111
+ }
112
+ profile: {
113
+ /** A signed-in viewer only; an unknown id or handle, an erased member are the same `notFound`. */
114
+ get: Call<{ memberId: string } | { handle: string }, PublicProfile>
115
+ }
116
+ me: {
117
+ /** Anonymous: `{ member: null, needs: ['sign_in'] }`. */
118
+ get: CallNoInput<MyState>
119
+ /** The light onboarding: the age band, the rules (and the consent when asked), the profile. */
120
+ onboard: Call<OnboardInput, MyState>
121
+ updateProfile: Call<ProfileUpdateInput, { profile: OwnProfile }>
122
+ notifications: {
123
+ list: CallOptionalInput<{ cursor?: string | null }, CommunityPage<NotificationItem>>
124
+ markRead: Call<{ ids: readonly string[] }, { updated: number }>
125
+ }
126
+ decisions: {
127
+ list: CallOptionalInput<{ cursor?: string | null }, CommunityPage<DecisionSummary>>
128
+ /** The statement of reasons; a decision about someone else is `notFound`. */
129
+ get: Call<{ decisionId: string }, Statement>
130
+ }
131
+ appeals: {
132
+ file: Call<{ decisionId: string; body: string }, { appealId: string; submittedAt: string }>
133
+ withdraw: Call<{ appealId: string }, { appealId: string; status: 'withdrawn' }>
134
+ list: CallNoInput<{ items: AppealItem[] }>
135
+ }
136
+ reports: {
137
+ list: CallNoInput<{ items: ReportItem[] }>
138
+ }
139
+ consents: {
140
+ /** As easy as giving it; later writes ask for it again where the tenant requires it. */
141
+ withdraw: CallOptionalInput<{ kind: 'art9_consent' }, { kind: 'art9_consent'; state: string }>
142
+ }
143
+ /** Every section of the member's data, `providerEntity` on every row: offer it as a JSON download. */
144
+ export: CallNoInput<MemberExport>
145
+ /** The profile's deletion, after the grace period (`purgeAfter`); writes are refused meanwhile. */
146
+ erase: CallNoInput<{ status: 'deletion_requested'; purgeAfter: string }>
147
+ cancelErase: CallNoInput<{ status: 'active' | 'read_only' }>
148
+ }
149
+ legal: {
150
+ current: Call<{ kind: LegalTextKind; locale: string }, CurrentLegalText>
151
+ }
152
+ notices: {
153
+ /** Anyone, with or without a session; `confirmations` must hold COMMUNITY_GOOD_FAITH. */
154
+ submit: Call<NoticeSubmitInput, NoticeReceipt>
155
+ status: Call<{ receipt: string }, NoticeStatus>
156
+ appeal: Call<{ receipt: string; body: string }, { appealId: string; submittedAt: string }>
157
+ withdrawAppeal: Call<{ receipt: string }, { appealId: string; status: 'withdrawn'; resolvedAt: string }>
158
+ }
159
+ }
160
+
161
+ const DEFAULT_TIMEOUT_MS = 10_000
162
+ /**
163
+ * The longest delay a timer keeps (a signed 32-bit one): past it `setTimeout` fires at once (and `Infinity` is 0), so
164
+ * every request would abort before its answer — an outage that looks like the host's.
165
+ */
166
+ const TIMEOUT_MAX_MS = 2_147_483_647
167
+
168
+ /** Whether the timeout warning was given (once per page: every element builds its own client). */
169
+ let timeoutWarned = false
170
+
171
+ /** The per-request timeout a timer keeps, as the BFF's (server/bff.ts `timeoutOf`): else the default, one warning. */
172
+ function timeoutOf(value: unknown): number {
173
+ if (value === undefined) return DEFAULT_TIMEOUT_MS
174
+ const ms = typeof value === 'number' ? Math.floor(value) : Number.NaN
175
+ if (ms >= 1 && ms <= TIMEOUT_MAX_MS) return ms
176
+ if (!timeoutWarned) {
177
+ timeoutWarned = true
178
+ // Value-free: the configured number is not echoed.
179
+ console.warn('[community] timeoutMs is not a number of milliseconds from 1 to 2147483647 — the default 10 s is used.')
180
+ }
181
+ return DEFAULT_TIMEOUT_MS
182
+ }
183
+
184
+ type Rec = Record<string, unknown>
185
+ const isRecord = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)
186
+ const isString = (v: unknown): v is string => typeof v === 'string'
187
+ const isArray = Array.isArray
188
+
189
+ /** The kind of a field an answer must hold. */
190
+ export type CommunityAnswerField = 'string' | 'number' | 'boolean' | 'array' | 'record'
191
+
192
+ const IS_FIELD: Readonly<Record<CommunityAnswerField, (v: unknown) => boolean>> = Object.freeze({
193
+ string: isString,
194
+ number: (v: unknown) => typeof v === 'number',
195
+ boolean: (v: unknown) => typeof v === 'boolean',
196
+ array: isArray,
197
+ record: isRecord,
198
+ })
199
+
200
+ const fieldsOfAnswer = (f: Readonly<Record<string, CommunityAnswerField>>): Readonly<Record<string, CommunityAnswerField>> => Object.freeze({ ...f })
201
+
202
+ /**
203
+ * What each operation's answer must hold to count as one (else `unavailable`: the host did not answer as the API
204
+ * does), field by field. test/community/ops-drift.spec.ts pins every field to kb-api's declaration of the answer.
205
+ */
206
+ export const COMMUNITY_ANSWER_FIELDS: Readonly<Record<CommunityOpName, Readonly<Record<string, CommunityAnswerField>>>> = Object.freeze({
207
+ 'discussions.list': fieldsOfAnswer({ articleId: 'string', messages: 'array', viewer: 'record' }),
208
+ 'discussions.head': fieldsOfAnswer({ heads: 'array' }),
209
+ 'messages.post': fieldsOfAnswer({ message: 'record', warnings: 'array' }),
210
+ 'messages.edit': fieldsOfAnswer({ message: 'record', warnings: 'array' }),
211
+ 'messages.delete': fieldsOfAnswer({ message: 'record' }),
212
+ 'messages.report': fieldsOfAnswer({ caseId: 'string' }),
213
+ 'reactions.set': fieldsOfAnswer({ reactions: 'record' }),
214
+ 'blocks.set': fieldsOfAnswer({ blocked: 'boolean' }),
215
+ 'blocks.list': fieldsOfAnswer({ blocks: 'array' }),
216
+ 'profile.get': fieldsOfAnswer({ author: 'record' }),
217
+ 'me.get': fieldsOfAnswer({ needs: 'array' }),
218
+ 'me.onboard': fieldsOfAnswer({ needs: 'array' }),
219
+ 'me.updateProfile': fieldsOfAnswer({ profile: 'record' }),
220
+ 'me.notifications.list': fieldsOfAnswer({ items: 'array' }),
221
+ 'me.notifications.markRead': fieldsOfAnswer({ updated: 'number' }),
222
+ 'me.decisions.list': fieldsOfAnswer({ items: 'array' }),
223
+ 'me.decisions.get': fieldsOfAnswer({ decisionId: 'string' }),
224
+ 'me.appeals.file': fieldsOfAnswer({ appealId: 'string' }),
225
+ 'me.appeals.withdraw': fieldsOfAnswer({ appealId: 'string' }),
226
+ 'me.appeals.list': fieldsOfAnswer({ items: 'array' }),
227
+ 'me.reports.list': fieldsOfAnswer({ items: 'array' }),
228
+ 'me.consents.withdraw': fieldsOfAnswer({ state: 'string' }),
229
+ 'me.export': fieldsOfAnswer({ generatedAt: 'string' }),
230
+ 'me.erase': fieldsOfAnswer({ purgeAfter: 'string' }),
231
+ 'me.cancelErase': fieldsOfAnswer({ status: 'string' }),
232
+ 'legal.current': fieldsOfAnswer({ textId: 'string' }),
233
+ 'notices.submit': fieldsOfAnswer({ caseId: 'string', receipt: 'string' }),
234
+ 'notices.status': fieldsOfAnswer({ status: 'string' }),
235
+ 'notices.appeal': fieldsOfAnswer({ appealId: 'string' }),
236
+ 'notices.withdrawAppeal': fieldsOfAnswer({ appealId: 'string' }),
237
+ })
238
+
239
+ const isAnswerOf = (name: CommunityOpName, v: Rec): boolean =>
240
+ Object.entries(COMMUNITY_ANSWER_FIELDS[name]).every(([field, kind]) => IS_FIELD[kind](v[field]))
241
+
242
+ /** The fields of `input` the operation takes; an `undefined` one is left out (kb-api's schemas are strict). */
243
+ function pick(input: unknown, keys: readonly string[]): Rec {
244
+ const out: Rec = {}
245
+ if (!isRecord(input)) return out
246
+ for (const key of keys) if (input[key] !== undefined) out[key] = input[key]
247
+ return out
248
+ }
249
+
250
+ /** A target's own fields, by the field that names it (a message, a member by id or by handle, an article). */
251
+ function targetOf(target: unknown): unknown {
252
+ if (!isRecord(target)) return target
253
+ if ('conversationId' in target) return pick(target, ['conversationId', 'seq'])
254
+ if ('memberId' in target) return pick(target, ['memberId'])
255
+ if ('handle' in target) return pick(target, ['handle'])
256
+ return pick(target, ['articleId'])
257
+ }
258
+
259
+ const CODE_RE = /^[A-Za-z0-9_.:-]{1,64}$/
260
+ const MAX_LIST = 20
261
+
262
+ function codesOf(value: unknown): string[] | undefined {
263
+ if (!isArray(value)) return undefined
264
+ return value.filter((c): c is string => isString(c) && CODE_RE.test(c)).slice(0, MAX_LIST)
265
+ }
266
+
267
+ function needsOf(value: unknown): KnownNeed[] | undefined {
268
+ return isArray(value) ? value.filter(isKnownNeed).slice(0, MAX_LIST) : undefined
269
+ }
270
+
271
+ /** VALIDATION's `issues: [{ path }]` as field paths (kb-api sends paths only, never values). */
272
+ function fieldsOf(value: unknown): string[] | undefined {
273
+ if (!isArray(value)) return undefined
274
+ const paths = value.map((i) => (isRecord(i) ? i.path : i)).filter((p): p is string => isString(p) && p.length <= 128)
275
+ return paths.slice(0, MAX_LIST)
276
+ }
277
+
278
+ function secondsOf(value: unknown): number | undefined {
279
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.ceil(value) : undefined
280
+ }
281
+
282
+ /** A refusal in kb-api's envelope (`{ ok: false, code, … }`), with what it may carry. */
283
+ function refusalOf(body: Rec, answer: CommunityTransportAnswer): CommunityFailure {
284
+ const out: CommunityFailure = { ok: false, code: communityOutcomeOf(body.code as string) }
285
+ const retryAfterS = secondsOf(body.retryAfterS) ?? secondsOf(answer.retryAfterS)
286
+ if (retryAfterS !== undefined) out.retryAfterS = retryAfterS
287
+ const needs = needsOf(body.needs)
288
+ if (needs) out.needs = needs
289
+ const codes = codesOf(body.codes)
290
+ if (codes) out.codes = codes
291
+ if (isString(body.until)) out.until = body.until
292
+ const fields = fieldsOf(body.issues)
293
+ if (fields) out.fields = fields
294
+ return out
295
+ }
296
+
297
+ /**
298
+ * The client. Throws a TypeError for a base that is not relative — the one throw, at construction (a page that
299
+ * passes kb-api's URL has a bug to fix, not an outcome to show).
300
+ */
301
+ export function createCommunityClient(config: CommunityClientConfig): CommunityClient {
302
+ assertCommunityBase(config?.base)
303
+ const transport = config.transport ?? fetchTransport(config.base, config.now ? { now: config.now } : {})
304
+ const timeoutMs = timeoutOf(config.timeoutMs)
305
+ const logger = config.logger
306
+
307
+ const log = (name: CommunityOpName, outcome: CommunityUiCode, kbCode: string | null, status: number | null): void => {
308
+ if (!logger || !isLoggedCommunityOutcome(outcome)) return
309
+ try {
310
+ logger({ op: name, outcome, kbCode, status })
311
+ } catch {
312
+ // A logger that throws must not turn an outcome into a crash.
313
+ }
314
+ }
315
+
316
+ async function call<T>(name: CommunityOpName, body: Rec, options?: CommunityCallOptions): Promise<CommunityOutcome<T>> {
317
+ const op = COMMUNITY_OPS[name]
318
+ const controller = new AbortController()
319
+ const outer = options?.signal
320
+ const onAbort = (): void => controller.abort()
321
+ if (outer?.aborted) controller.abort()
322
+ else outer?.addEventListener('abort', onAbort, { once: true })
323
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
324
+
325
+ let answer: CommunityTransportAnswer
326
+ try {
327
+ answer = await transport(op, body, controller.signal)
328
+ } catch (err) {
329
+ const failure = communityFailureOf(err)
330
+ // A cancelled call is nobody's outage: its caller has gone.
331
+ if (!outer?.aborted) log(name, failure.code, null, null)
332
+ return failure
333
+ } finally {
334
+ clearTimeout(timer)
335
+ outer?.removeEventListener('abort', onAbort)
336
+ }
337
+
338
+ const status = typeof answer?.status === 'number' ? answer.status : 0
339
+ const payload = answer?.body
340
+ if (isRecord(payload) && payload.ok === false && isString(payload.code) && payload.code !== '') {
341
+ const failure = refusalOf(payload, answer)
342
+ log(name, failure.code, payload.code.slice(0, 64), status)
343
+ return failure
344
+ }
345
+ if (status >= 200 && status < 300 && isRecord(payload) && payload.ok === true) {
346
+ const { ok: _ok, ...value } = payload
347
+ if (isAnswerOf(name, value)) return { ok: true, value: value as T }
348
+ log(name, 'unavailable', null, status)
349
+ return { ok: false, code: 'unavailable' }
350
+ }
351
+ // No envelope: a host's own error page, an edge in front of it, the uniform unknown-path answer.
352
+ if (status === 429) {
353
+ const retryAfterS = secondsOf(answer.retryAfterS)
354
+ return retryAfterS === undefined ? { ok: false, code: 'fast' } : { ok: false, code: 'fast', retryAfterS }
355
+ }
356
+ log(name, 'unavailable', null, status)
357
+ const retryAfterS = status === 503 ? secondsOf(answer.retryAfterS) : undefined
358
+ return retryAfterS === undefined ? { ok: false, code: 'unavailable' } : { ok: false, code: 'unavailable', retryAfterS }
359
+ }
360
+
361
+ const fields =
362
+ <I, T>(name: CommunityOpName, keys: readonly string[]): CallOptionalInput<I, T> =>
363
+ (input, options) =>
364
+ call<T>(name, pick(input, keys), options)
365
+ const empty =
366
+ <T>(name: CommunityOpName): CallNoInput<T> =>
367
+ (options) =>
368
+ call<T>(name, {}, options)
369
+
370
+ return {
371
+ discussions: {
372
+ list: fields('discussions.list', ['articleId', 'languageCode', 'cursor']),
373
+ head: (input, options) =>
374
+ call('discussions.head', { articleIds: isRecord(input) && isArray(input.articleIds) ? [...input.articleIds] : [] }, options),
375
+ },
376
+ messages: {
377
+ post: fields('messages.post', ['articleId', 'body', 'replyToSeq', 'clientMsgId', 'languageCode', 'confirmations']),
378
+ edit: fields('messages.edit', ['conversationId', 'seq', 'body', 'confirmations']),
379
+ delete: fields('messages.delete', ['conversationId', 'seq']),
380
+ report: fields('messages.report', ['conversationId', 'seq', 'category', 'ruleId', 'note']),
381
+ },
382
+ reactions: {
383
+ set: (input, options) => call('reactions.set', { target: targetOf(input?.target), emoji: input?.emoji ?? null }, options),
384
+ },
385
+ blocks: {
386
+ set: fields('blocks.set', ['memberId', 'blocked']),
387
+ list: empty('blocks.list'),
388
+ },
389
+ profile: {
390
+ get: (input, options) =>
391
+ call('profile.get', isRecord(input) && 'handle' in input ? pick(input, ['handle']) : pick(input, ['memberId']), options),
392
+ },
393
+ me: {
394
+ get: empty('me.get'),
395
+ onboard: fields('me.onboard', ['ageBand', 'rulesTextId', 'art9TextId', 'displayName', 'handle', 'avatarPreset']),
396
+ updateProfile: fields('me.updateProfile', ['displayName', 'handle', 'avatarPreset', 'bio']),
397
+ notifications: {
398
+ list: fields('me.notifications.list', ['cursor']),
399
+ markRead: (input, options) =>
400
+ call('me.notifications.markRead', { ids: isRecord(input) && isArray(input.ids) ? [...input.ids] : [] }, options),
401
+ },
402
+ decisions: {
403
+ list: fields('me.decisions.list', ['cursor']),
404
+ get: fields('me.decisions.get', ['decisionId']),
405
+ },
406
+ appeals: {
407
+ file: fields('me.appeals.file', ['decisionId', 'body']),
408
+ withdraw: fields('me.appeals.withdraw', ['appealId']),
409
+ list: empty('me.appeals.list'),
410
+ },
411
+ reports: {
412
+ list: empty('me.reports.list'),
413
+ },
414
+ consents: {
415
+ withdraw: (_input, options) => call('me.consents.withdraw', { kind: 'art9_consent' }, options),
416
+ },
417
+ export: empty('me.export'),
418
+ erase: empty('me.erase'),
419
+ cancelErase: empty('me.cancelErase'),
420
+ },
421
+ legal: {
422
+ current: fields('legal.current', ['kind', 'locale']),
423
+ },
424
+ notices: {
425
+ submit: (input, options) => {
426
+ const body = pick(input, ['category', 'target', 'description', 'ruleId', 'turnstileToken', 'confirmations'])
427
+ if (body.target !== undefined) body.target = targetOf(body.target)
428
+ if (isRecord(input?.notifier)) body.notifier = pick(input.notifier, ['name', 'email', 'locale'])
429
+ else if (input?.notifier === null) body.notifier = null
430
+ return call('notices.submit', body, options)
431
+ },
432
+ status: fields('notices.status', ['receipt']),
433
+ appeal: fields('notices.appeal', ['receipt', 'body']),
434
+ withdrawAppeal: fields('notices.withdrawAppeal', ['receipt']),
435
+ },
436
+ }
437
+ }