@blogmcp/sdk 0.6.1 → 0.7.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 (136) hide show
  1. package/dist/consultations/channel-text.d.ts +118 -0
  2. package/dist/consultations/channel-text.js +40 -0
  3. package/dist/consultations/index.d.ts +28 -0
  4. package/dist/consultations/index.js +60 -0
  5. package/dist/consultations/messages.cs.d.ts +149 -0
  6. package/dist/consultations/messages.cs.js +143 -0
  7. package/dist/consultations/messages.d.ts +34 -0
  8. package/dist/consultations/messages.en.d.ts +143 -0
  9. package/dist/consultations/messages.en.js +141 -0
  10. package/dist/consultations/messages.js +48 -0
  11. package/dist/consultations/outcome.d.ts +121 -0
  12. package/dist/consultations/outcome.js +161 -0
  13. package/dist/consultations/public-config.d.ts +71 -0
  14. package/dist/consultations/public-config.js +104 -0
  15. package/dist/consultations/reader.d.ts +83 -0
  16. package/dist/consultations/reader.js +128 -0
  17. package/dist/consultations/routes.d.ts +214 -0
  18. package/dist/consultations/routes.js +149 -0
  19. package/dist/consultations/server/client-ip.d.ts +50 -0
  20. package/dist/consultations/server/client-ip.js +44 -0
  21. package/dist/consultations/server/contact.d.ts +23 -0
  22. package/dist/consultations/server/contact.js +138 -0
  23. package/dist/consultations/server/context.d.ts +246 -0
  24. package/dist/consultations/server/context.js +152 -0
  25. package/dist/consultations/server/cookie.d.ts +60 -0
  26. package/dist/consultations/server/cookie.js +57 -0
  27. package/dist/consultations/server/env.d.ts +20 -0
  28. package/dist/consultations/server/env.js +35 -0
  29. package/dist/consultations/server/http.d.ts +59 -0
  30. package/dist/consultations/server/http.js +64 -0
  31. package/dist/consultations/server/index.d.ts +37 -0
  32. package/dist/consultations/server/index.js +19 -0
  33. package/dist/consultations/server/origin.d.ts +39 -0
  34. package/dist/consultations/server/origin.js +31 -0
  35. package/dist/consultations/server/server.d.ts +106 -0
  36. package/dist/consultations/server/server.js +122 -0
  37. package/dist/consultations/server/session.d.ts +38 -0
  38. package/dist/consultations/server/session.js +210 -0
  39. package/dist/consultations/server/transport.d.ts +69 -0
  40. package/dist/consultations/server/transport.js +117 -0
  41. package/dist/consultations/server/turnstile.d.ts +44 -0
  42. package/dist/consultations/server/turnstile.js +31 -0
  43. package/dist/consultations/site.d.ts +100 -0
  44. package/dist/consultations/site.js +60 -0
  45. package/dist/consultations/submit-new.d.ts +103 -0
  46. package/dist/consultations/submit-new.js +72 -0
  47. package/dist/core/auth.d.ts +2 -2
  48. package/dist/core/client.d.ts +25 -4
  49. package/dist/core/client.js +35 -30
  50. package/dist/core/consultation-adapter.d.ts +2 -2
  51. package/dist/core/consultations.d.ts +1 -1
  52. package/dist/core/errors.d.ts +1 -1
  53. package/dist/core/errors.js +16 -15
  54. package/dist/core/index.d.ts +31 -31
  55. package/dist/core/index.js +35 -34
  56. package/dist/core/markdown.d.ts +1 -1
  57. package/dist/core/queries.d.ts +4 -1
  58. package/dist/core/queries.js +131 -86
  59. package/dist/core/review/format.d.ts +1 -1
  60. package/dist/core/review/index.d.ts +2 -2
  61. package/dist/core/seo.d.ts +1 -1
  62. package/dist/core/translations/cs.json.js +1 -1
  63. package/dist/core/translations/en.json.js +1 -1
  64. package/dist/core/types.d.ts +50 -1
  65. package/dist/core/view-model.d.ts +12 -2
  66. package/dist/core/view-model.js +40 -34
  67. package/dist/{packages/tripmap-core/node_modules → node_modules}/pmtiles/dist/esm/index.js +1 -1
  68. package/dist/nuxt/composables/useAsyncKb.d.ts +4 -4
  69. package/dist/nuxt/index.d.ts +1 -1
  70. package/dist/packages/tripmap-core/dist/engine.js +3 -3
  71. package/dist/packages/tripmap-core/dist/generated/maplibre-worker.bundle.js +1 -1
  72. package/dist/react/KbMdxContent.d.ts +1 -1
  73. package/dist/react/context.d.ts +4 -4
  74. package/dist/react/hooks/useImageRenderer.d.ts +1 -1
  75. package/dist/react/hooks/useKbClient.d.ts +1 -1
  76. package/dist/react/hooks/useKbContext.d.ts +1 -1
  77. package/dist/react/hooks/useKbI18n.d.ts +1 -1
  78. package/dist/react/hooks/useKbLanguage.d.ts +1 -1
  79. package/dist/react/hooks/useKbSearch.d.ts +1 -1
  80. package/dist/react/hooks/useMdxContent.d.ts +1 -1
  81. package/dist/react/index.d.ts +15 -15
  82. package/dist/react/provider.d.ts +2 -2
  83. package/dist/react/server/index.d.ts +2 -2
  84. package/dist/vue/components/KbAccessGate.vue.d.ts +4 -1
  85. package/dist/vue/components/KbAccessGate.vue.js +42 -32
  86. package/dist/vue/components/KbArticleCard.vue.d.ts +3 -1
  87. package/dist/vue/components/KbArticleCard.vue.js +67 -39
  88. package/dist/vue/composables/useArticles.d.ts +1 -1
  89. package/dist/vue/composables/useImageRenderer.d.ts +1 -1
  90. package/dist/vue/composables/useKbAuth.d.ts +1 -1
  91. package/dist/vue/composables/useKbClient.d.ts +1 -1
  92. package/dist/vue/composables/useKbComments.d.ts +1 -1
  93. package/dist/vue/composables/useKbI18n.d.ts +1 -1
  94. package/dist/vue/composables/useKbLanguage.d.ts +1 -1
  95. package/dist/vue/composables/useNavigation.d.ts +1 -1
  96. package/dist/vue/composables/useSearch.d.ts +1 -1
  97. package/dist/vue/composables/useTags.d.ts +1 -1
  98. package/dist/vue/index.d.ts +19 -19
  99. package/dist/vue/plugin.d.ts +4 -4
  100. package/package.json +15 -5
  101. package/src/consultations/channel-text.ts +168 -0
  102. package/src/consultations/index.ts +87 -0
  103. package/src/consultations/messages.cs.ts +175 -0
  104. package/src/consultations/messages.en.ts +171 -0
  105. package/src/consultations/messages.ts +91 -0
  106. package/src/consultations/outcome.ts +278 -0
  107. package/src/consultations/public-config.ts +246 -0
  108. package/src/consultations/reader.ts +281 -0
  109. package/src/consultations/routes.ts +341 -0
  110. package/src/consultations/server/client-ip.ts +106 -0
  111. package/src/consultations/server/contact.ts +267 -0
  112. package/src/consultations/server/context.ts +403 -0
  113. package/src/consultations/server/cookie.ts +129 -0
  114. package/src/consultations/server/env.ts +66 -0
  115. package/src/consultations/server/http.ts +148 -0
  116. package/src/consultations/server/index.ts +55 -0
  117. package/src/consultations/server/origin.ts +71 -0
  118. package/src/consultations/server/server.ts +322 -0
  119. package/src/consultations/server/session.ts +414 -0
  120. package/src/consultations/server/transport.ts +196 -0
  121. package/src/consultations/server/turnstile.ts +98 -0
  122. package/src/consultations/site.ts +183 -0
  123. package/src/consultations/submit-new.ts +266 -0
  124. package/src/core/auth.ts +1 -1
  125. package/src/core/client.ts +32 -1
  126. package/src/core/errors.ts +5 -2
  127. package/src/core/index.ts +3 -0
  128. package/src/core/queries.ts +56 -0
  129. package/src/core/translations/cs.json +2 -1
  130. package/src/core/translations/en.json +2 -1
  131. package/src/core/types.ts +51 -0
  132. package/src/core/view-model.ts +18 -0
  133. package/src/vue/components/KbAccessGate.vue +14 -1
  134. package/src/vue/components/KbArticleCard.vue +25 -0
  135. /package/dist/{packages/tripmap-core/node_modules → node_modules}/maplibre-gl/dist/maplibre-gl-shared.js +0 -0
  136. /package/dist/{packages/tripmap-core/node_modules → node_modules}/maplibre-gl/dist/maplibre-gl.js +0 -0
@@ -0,0 +1,246 @@
1
+ /**
2
+ * The KB's public consultation config (`consultationPublicConfig(locale)`),
3
+ * memoised per locale.
4
+ *
5
+ * It is the same for everyone, and every reader page needs it: the reader-site
6
+ * gate (`readerSiteStatus`), the contact form's text, the new-question page in
7
+ * notice mode. One memo per server instance (or per browser tab) keeps that
8
+ * at one KB call per locale per five minutes.
9
+ *
10
+ * - A success is remembered for 5 minutes, a failure for 30 seconds: a KB
11
+ * outage must not switch the pages off for five minutes.
12
+ * - Concurrent requests for one locale share one load.
13
+ * - `fresh` always loads — an action checking that the reader saw the CURRENT
14
+ * text — and a success replaces the memo, so the next page view shows the
15
+ * new text at once. A failed `fresh` load never replaces a good memo.
16
+ * - Only an allowlisted, frozen copy is kept: a field the KB (or a proxy in
17
+ * between) adds is never cached and never handed out.
18
+ * - The locale is checked first; nothing is loaded for a malformed one, and at
19
+ * most `maxLocales` locales are kept (least recently used goes first).
20
+ *
21
+ * `get` never throws. `peek` answers from the memo alone, synchronously —
22
+ * for a status that must not wait for the KB. Load it with an identity-free
23
+ * client (the reader-proxy key, no reader IP, no reader JWT): the answer is
24
+ * shared by everyone, so whoever triggered the load must not matter.
25
+ */
26
+
27
+ import type { ConsultationChannelConfig, ConsultationLegalText, ConsultationPublicConfig } from '../core/types'
28
+ import {
29
+ consultationFailureOf,
30
+ isConsultationTransportError,
31
+ isLoggedConsultationOutcome,
32
+ type ConsultationLogger,
33
+ type ConsultationOutcome,
34
+ } from './outcome'
35
+ import { LOCALE_RE } from './routes'
36
+ import { isKbGraphQLError } from '../core/errors'
37
+
38
+ export interface PublicConfigCache {
39
+ /** The config in `locale`; `fresh` skips the memo (and refreshes it on success). Never throws. */
40
+ get(locale: string, o?: { fresh?: boolean }): Promise<ConsultationOutcome<ConsultationPublicConfig>>
41
+ /**
42
+ * What is remembered for `locale` right now — a config or a failure, while
43
+ * its TTL lasts — without loading and without waiting: `undefined` when
44
+ * nothing is remembered (never loaded, expired, a load still in flight) or
45
+ * the locale is malformed. A peek does not count as a use for the
46
+ * least-recently-used order.
47
+ */
48
+ peek(locale: string): ConsultationOutcome<ConsultationPublicConfig> | undefined
49
+ /** Forget everything remembered (loads still in flight are not remembered either). */
50
+ clear(): void
51
+ }
52
+
53
+ export interface PublicConfigCacheOptions {
54
+ /** How long a loaded config is used. Default 5 minutes. */
55
+ ttlMs?: number
56
+ /** How long a failure is remembered. Default 30 seconds. */
57
+ failureTtlMs?: number
58
+ /** How many locales are kept. Default 8. */
59
+ maxLocales?: number
60
+ /** The clock (tests). */
61
+ now?: () => number
62
+ /** Told about failures that are outages or unexpected (`unavailable`, `submit`). */
63
+ logger?: ConsultationLogger
64
+ }
65
+
66
+ const DEFAULT_TTL_MS = 5 * 60 * 1000
67
+ const DEFAULT_FAILURE_TTL_MS = 30 * 1000
68
+ const DEFAULT_MAX_LOCALES = 8
69
+
70
+ const UNAVAILABLE: ConsultationOutcome<ConsultationPublicConfig> = Object.freeze({ ok: false, code: 'unavailable' })
71
+ const INVALID_LOCALE: ConsultationOutcome<ConsultationPublicConfig> = Object.freeze({ ok: false, code: 'invalid' })
72
+
73
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
74
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
75
+ }
76
+
77
+ function legalTextOf(raw: unknown): ConsultationLegalText | null {
78
+ if (!isPlainObject(raw)) return null
79
+ const { purpose, version, locale, body } = raw
80
+ if (purpose !== 'notice' && purpose !== 'consent') return null
81
+ if (typeof version !== 'string' || typeof locale !== 'string' || typeof body !== 'string') return null
82
+ return Object.freeze({ purpose, version, locale, body })
83
+ }
84
+
85
+ function channelOf(raw: unknown): ConsultationChannelConfig | null {
86
+ if (!isPlainObject(raw)) return null
87
+ const { channel, mode, text } = raw
88
+ if (typeof channel !== 'string' || channel === '') return null
89
+ // A mode this SDK does not know (a newer KB) is dropped: the channel then simply has no form.
90
+ if (mode !== 'notice' && mode !== 'consent') return null
91
+ return Object.freeze({ channel, mode, text: legalTextOf(text) })
92
+ }
93
+
94
+ /**
95
+ * The public config reduced to what the SDK uses, as a frozen copy: `enabled`,
96
+ * `readerSiteUrl`, `emailNotices`, and `channels[].{channel, mode, text{purpose,
97
+ * version, locale, body}}` — nothing else. Null when the answer is malformed
98
+ * (not an object, `enabled` or `emailNotices` not booleans, `readerSiteUrl`
99
+ * neither a string nor null, `channels` not a list). A channel of an unknown
100
+ * shape or mode is dropped, and a malformed text becomes no text; the rest of
101
+ * the config stays usable.
102
+ */
103
+ export function sanitizePublicConfig(raw: unknown): ConsultationPublicConfig | null {
104
+ if (!isPlainObject(raw)) return null
105
+ const { enabled, readerSiteUrl, emailNotices, channels } = raw
106
+ if (typeof enabled !== 'boolean' || typeof emailNotices !== 'boolean') return null
107
+ if (readerSiteUrl !== null && typeof readerSiteUrl !== 'string') return null
108
+ if (!Array.isArray(channels)) return null
109
+ const kept = channels.map(channelOf).filter((c): c is ConsultationChannelConfig => c !== null)
110
+ return Object.freeze({
111
+ enabled,
112
+ readerSiteUrl,
113
+ emailNotices,
114
+ channels: Object.freeze(kept) as ConsultationChannelConfig[],
115
+ })
116
+ }
117
+
118
+ type Memo = {
119
+ outcome: ConsultationOutcome<ConsultationPublicConfig>
120
+ expiresAt: number
121
+ /** Which load produced it: an older load never replaces a newer answer. */
122
+ seq: number
123
+ }
124
+
125
+ function positive(value: number | undefined, fallback: number): number {
126
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback
127
+ }
128
+
129
+ /**
130
+ * A memo of the public config per locale. `load` asks the KB, e.g.
131
+ * `(locale) => client.consultations.publicConfig(locale)`; whatever it throws
132
+ * becomes a code (`consultationFailureOf`), whatever it returns is sanitised.
133
+ */
134
+ export function createPublicConfigCache(
135
+ load: (locale: string) => Promise<unknown>,
136
+ o: PublicConfigCacheOptions = {},
137
+ ): PublicConfigCache {
138
+ const ttlMs = positive(o.ttlMs, DEFAULT_TTL_MS)
139
+ const failureTtlMs = positive(o.failureTtlMs, DEFAULT_FAILURE_TTL_MS)
140
+ const maxLocales = Math.max(1, Math.floor(positive(o.maxLocales, DEFAULT_MAX_LOCALES)))
141
+ const now = o.now ?? Date.now
142
+ const logger = o.logger
143
+
144
+ const memo = new Map<string, Memo>()
145
+ const pending = new Map<string, Promise<ConsultationOutcome<ConsultationPublicConfig>>>()
146
+ let seq = 0
147
+ /** Bumped by `clear()`: a load started before it does not write afterwards. */
148
+ let epoch = 0
149
+
150
+ function log(outcome: ConsultationOutcome<ConsultationPublicConfig>, err?: unknown): void {
151
+ if (outcome.ok || !logger || !isLoggedConsultationOutcome(outcome.code)) return
152
+ try {
153
+ logger({
154
+ op: 'publicConfig',
155
+ outcome: outcome.code,
156
+ kbCode: isKbGraphQLError(err) ? err.code : null,
157
+ status: isConsultationTransportError(err) ? err.status : null,
158
+ })
159
+ } catch {
160
+ // A logger that throws must not turn a handled failure into an unhandled one.
161
+ }
162
+ }
163
+
164
+ async function fetchOutcome(locale: string): Promise<ConsultationOutcome<ConsultationPublicConfig>> {
165
+ let raw: unknown
166
+ try {
167
+ raw = await load(locale)
168
+ } catch (err) {
169
+ const failure = consultationFailureOf(err)
170
+ const outcome = Object.freeze({ ok: false as const, ...failure })
171
+ log(outcome, err)
172
+ return outcome
173
+ }
174
+ const value = sanitizePublicConfig(raw)
175
+ if (!value) {
176
+ log(UNAVAILABLE)
177
+ return UNAVAILABLE
178
+ }
179
+ return Object.freeze({ ok: true as const, value })
180
+ }
181
+
182
+ function remember(locale: string, entry: Memo): void {
183
+ memo.delete(locale)
184
+ memo.set(locale, entry)
185
+ while (memo.size > maxLocales) {
186
+ const oldest = memo.keys().next().value as string
187
+ memo.delete(oldest)
188
+ }
189
+ }
190
+
191
+ /** Runs one load and applies the memo rules to its result. */
192
+ function start(locale: string, fresh: boolean): Promise<ConsultationOutcome<ConsultationPublicConfig>> {
193
+ const mySeq = ++seq
194
+ const myEpoch = epoch
195
+ return fetchOutcome(locale)
196
+ .then((outcome) => {
197
+ if (myEpoch !== epoch) return outcome
198
+ const current = memo.get(locale)
199
+ if (outcome.ok) {
200
+ // A success replaces any failure and any OLDER success.
201
+ if (!current || !current.outcome.ok || current.seq < mySeq) {
202
+ remember(locale, { outcome, expiresAt: now() + ttlMs, seq: mySeq })
203
+ }
204
+ } else if (!fresh) {
205
+ // A failure is remembered briefly — but never over a config that is still good.
206
+ const goodUntil = current?.outcome.ok ? current.expiresAt : -Infinity
207
+ if (goodUntil <= now()) remember(locale, { outcome, expiresAt: now() + failureTtlMs, seq: mySeq })
208
+ }
209
+ return outcome
210
+ })
211
+ .catch(() => UNAVAILABLE) // only a throwing clock gets here; the caller still gets an envelope
212
+ }
213
+
214
+ return {
215
+ get(locale, opts = {}) {
216
+ if (typeof locale !== 'string' || !LOCALE_RE.test(locale)) return Promise.resolve(INVALID_LOCALE)
217
+ if (opts.fresh) return start(locale, true)
218
+ const cached = memo.get(locale)
219
+ if (cached && cached.expiresAt > now()) {
220
+ remember(locale, cached) // least recently USED goes first
221
+ return Promise.resolve(cached.outcome)
222
+ }
223
+ const inFlight = pending.get(locale)
224
+ if (inFlight) return inFlight
225
+ const promise = start(locale, false).finally(() => {
226
+ if (pending.get(locale) === promise) pending.delete(locale)
227
+ })
228
+ pending.set(locale, promise)
229
+ return promise
230
+ },
231
+ peek(locale) {
232
+ if (typeof locale !== 'string' || !LOCALE_RE.test(locale)) return undefined
233
+ try {
234
+ const cached = memo.get(locale)
235
+ return cached && cached.expiresAt > now() ? cached.outcome : undefined
236
+ } catch {
237
+ return undefined // only a throwing clock gets here
238
+ }
239
+ },
240
+ clear() {
241
+ epoch++
242
+ memo.clear()
243
+ pending.clear()
244
+ },
245
+ }
246
+ }
@@ -0,0 +1,281 @@
1
+ /**
2
+ * "My consultations" for a signed-in reader: the list, a thread, a reply, an
3
+ * erasure, the reader's consent and its withdrawal, and a new question on the
4
+ * `web` channel (docs/internal/reader-consultations.md §6.1, §8.1).
5
+ *
6
+ * It runs wherever the reader's own identity is: in the browser with the
7
+ * reader's KB token through the blog's `/api` proxy, or on a server with a
8
+ * delegated token. It uses `client.consultations` ONLY — never
9
+ * `consultationSession` (a magic-link session is server-only and has its own
10
+ * handlers in `@blogmcp/sdk/consultations/server`).
11
+ *
12
+ * Every method resolves to a `ConsultationOutcome` and never throws: a KB
13
+ * outage, a KB code, a malformed answer and a bad argument all end as a code.
14
+ * What can be decided without the KB is decided first, so a malformed id, an
15
+ * empty message or a bad key costs neither a request nor a unit of quota.
16
+ *
17
+ * Nothing here logs a body, an address, a token or an id: the logger gets the
18
+ * operation, the outcome, the KB code and the HTTP status.
19
+ */
20
+
21
+ import type { KbClient } from '../core/client'
22
+ import { isKbGraphQLError } from '../core/errors'
23
+ import type {
24
+ CreateMyConsultationInput,
25
+ ConsultationMessageInput,
26
+ ReaderConsultation,
27
+ ReaderConsultationConsent,
28
+ ReaderConsultationSummary,
29
+ } from '../core/types'
30
+ import { CONSULTATION_CHANNELS, channelTextFrom, webAskFrom, type ChannelText, type WebAskStatus } from './channel-text'
31
+ import {
32
+ consultationFailureOf,
33
+ consultationOutcomeOf,
34
+ isConsultationTransportError,
35
+ isLoggedConsultationOutcome,
36
+ type ConsultationLogger,
37
+ type ConsultationOutcome,
38
+ type ConsultationUiCode,
39
+ } from './outcome'
40
+ import type { PublicConfigCache } from './public-config'
41
+ import { CLIENT_REQUEST_ID_RE, CONSULTATION_ID_RE, LEGAL_VERSION_RE, LOCALE_RE, READER_BODY_MAX, normalizeBody } from './routes'
42
+
43
+ /** A new question on the `web` channel: what the reader wrote and which legal text the page showed. */
44
+ export interface NewQuestion {
45
+ /** The question (checked against the KB limit; the page applies its own, shorter one first). */
46
+ body: string
47
+ /** The page's language — the KB picks the notice e-mails' language by it. */
48
+ languageCode: string
49
+ /**
50
+ * The text the page showed: in `consent` mode the reader ticked it, in
51
+ * `notice` mode they saw it. It goes as `consent` OR `notice`, never both.
52
+ * `null`: nothing was shown — the reader's consent already covers new
53
+ * questions, and the KB links the question to it by itself (a consent sent
54
+ * anyway would be ignored; one that stopped covering answers CONSENT_REQUIRED).
55
+ */
56
+ legal: { mode: 'consent' | 'notice'; version: string; locale: string } | null
57
+ /** The idempotency key of this attempt (a retry reuses it: see `submitNewConsultation`). */
58
+ clientRequestId: string
59
+ }
60
+
61
+ export interface ReaderConsultations {
62
+ /** The reader's consultations, newest activity first (`limit` 1..100, default 100). */
63
+ list(o?: { limit?: number }): Promise<ConsultationOutcome<ReaderConsultationSummary[]>>
64
+ /** One of the reader's consultations. A foreign, missing or malformed id is `notFound` (a malformed one without asking). */
65
+ get(id: string): Promise<ConsultationOutcome<ReaderConsultation>>
66
+ /** Write in one of the reader's consultations (reopens an answered one). `duplicate`: a replay of the same key. */
67
+ post(id: string, m: ConsultationMessageInput): Promise<ConsultationOutcome<{ duplicate: boolean }>>
68
+ /** Close a consultation now; it is deleted after the tenant's grace period. The reader's consent stays. */
69
+ requestErasure(id: string): Promise<ConsultationOutcome<null>>
70
+ /** The reader's own consent and whether their next question needs one (read afresh every time). */
71
+ consent(locale: string): Promise<ConsultationOutcome<ReaderConsultationConsent>>
72
+ /** What the new-question page offers this reader (`webAskFrom`); `fresh` reads the notice text past the memo. */
73
+ webAsk(locale: string, o?: { fresh?: boolean }): Promise<ConsultationOutcome<WebAskStatus>>
74
+ /** Open a consultation on the `web` channel. The reply's id is checked: only a UUID is ever returned. */
75
+ create(q: NewQuestion): Promise<ConsultationOutcome<{ id: string; duplicate: boolean }>>
76
+ /**
77
+ * Withdraw the reader's consent: every question that relied on it closes now.
78
+ * "There was nothing to withdraw" (`NOTHING_TO_DO`, e.g. done in another
79
+ * window) is the reader's wish fulfilled: `ok` with `alreadyWithdrawn`.
80
+ */
81
+ withdrawConsent(): Promise<ConsultationOutcome<{ threadsClosed: number | null; alreadyWithdrawn: boolean }>>
82
+ }
83
+
84
+ const DEFAULT_LIST_LIMIT = 100
85
+
86
+ const INVALID = Object.freeze({ ok: false as const, code: 'invalid' as const })
87
+ const NOT_FOUND = Object.freeze({ ok: false as const, code: 'notFound' as const })
88
+ const UNAVAILABLE = Object.freeze({ ok: false as const, code: 'unavailable' as const })
89
+
90
+ const isConsultationId = (id: unknown): id is string => typeof id === 'string' && CONSULTATION_ID_RE.test(id)
91
+ const isKey = (key: unknown): key is string => typeof key === 'string' && CLIENT_REQUEST_ID_RE.test(key)
92
+ const isLocale = (locale: unknown): locale is string => typeof locale === 'string' && LOCALE_RE.test(locale)
93
+
94
+ function listLimit(limit: unknown): number {
95
+ if (typeof limit !== 'number' || !Number.isFinite(limit)) return DEFAULT_LIST_LIMIT
96
+ return Math.min(DEFAULT_LIST_LIMIT, Math.max(1, Math.floor(limit)))
97
+ }
98
+
99
+ /** A count only when it really is one — otherwise the page leaves the sentence with the number out. */
100
+ function countOrNull(value: unknown): number | null {
101
+ return typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : null
102
+ }
103
+
104
+ /** The legal record for `createMyConsultation`: `consent` OR `notice`, or neither — an absent key, never `null`. */
105
+ function legalInputOf(legal: NewQuestion['legal']): Pick<CreateMyConsultationInput, 'consent' | 'notice'> | null {
106
+ if (legal === null || legal === undefined) return {}
107
+ if (typeof legal !== 'object') return null
108
+ const { mode, version, locale } = legal
109
+ if (mode !== 'consent' && mode !== 'notice') return null
110
+ if (typeof version !== 'string' || !LEGAL_VERSION_RE.test(version) || !isLocale(locale)) return null
111
+ const shown = { version, locale }
112
+ return mode === 'consent' ? { consent: shown } : { notice: shown }
113
+ }
114
+
115
+ export function createReaderConsultations(
116
+ client: Pick<KbClient, 'consultations'>,
117
+ o: { publicConfig: PublicConfigCache; logger?: ConsultationLogger },
118
+ ): ReaderConsultations {
119
+ const { publicConfig, logger } = o
120
+
121
+ function report(op: string, outcome: ConsultationUiCode, kbCode: string | null = null, status: number | null = null): void {
122
+ if (!logger || !isLoggedConsultationOutcome(outcome)) return
123
+ try {
124
+ logger({ op, outcome, kbCode, status })
125
+ } catch {
126
+ // A logger that throws must not turn an envelope into an exception.
127
+ }
128
+ }
129
+
130
+ /** Runs one KB call; whatever it throws becomes a code. The only way out of this module. */
131
+ async function run<T>(op: string, call: () => Promise<ConsultationOutcome<T>>): Promise<ConsultationOutcome<T>> {
132
+ try {
133
+ return await call()
134
+ } catch (err) {
135
+ const failure = consultationFailureOf(err)
136
+ report(op, failure.code, isKbGraphQLError(err) ? err.code : null, isConsultationTransportError(err) ? err.status : null)
137
+ return { ok: false, ...failure }
138
+ }
139
+ }
140
+
141
+ /** A mutation's `{success, code}` → an envelope. */
142
+ function fromMutation<R extends { success: boolean; code?: string | null }, T>(
143
+ op: string,
144
+ result: R | null | undefined,
145
+ value: (r: R) => T,
146
+ ): ConsultationOutcome<T> {
147
+ if (!result || typeof result !== 'object') {
148
+ report(op, 'unavailable')
149
+ return UNAVAILABLE
150
+ }
151
+ if (result.success === true) return { ok: true, value: value(result) }
152
+ const kbCode = typeof result.code === 'string' ? result.code : null
153
+ const code = consultationOutcomeOf(kbCode)
154
+ report(op, code, kbCode)
155
+ return { ok: false, code }
156
+ }
157
+
158
+ /** The `web` channel's notice text from the public config (only notice mode needs it). */
159
+ async function webNotice(locale: string, fresh: boolean): Promise<ConsultationOutcome<ChannelText>> {
160
+ const cfg = await publicConfig.get(locale, { fresh })
161
+ return cfg.ok ? { ok: true, value: channelTextFrom(cfg.value, CONSULTATION_CHANNELS.web, locale) } : cfg
162
+ }
163
+
164
+ const reader: ReaderConsultations = {
165
+ list: (opts = {}) =>
166
+ run('list', async () => {
167
+ const list = await client.consultations.mine({ limit: listLimit(opts?.limit) })
168
+ return { ok: true, value: Array.isArray(list) ? list : [] }
169
+ }),
170
+
171
+ get: (id) => {
172
+ if (!isConsultationId(id)) return Promise.resolve(NOT_FOUND)
173
+ return run('get', async () => {
174
+ const consultation = await client.consultations.get(id)
175
+ if (!consultation || typeof consultation !== 'object') {
176
+ report('get', 'unavailable')
177
+ return UNAVAILABLE
178
+ }
179
+ return { ok: true, value: consultation }
180
+ })
181
+ },
182
+
183
+ post: (id, m) => {
184
+ if (!isConsultationId(id)) return Promise.resolve(NOT_FOUND)
185
+ const body = normalizeBody(m?.body, READER_BODY_MAX)
186
+ if (!body.ok) return Promise.resolve({ ok: false, code: body.code })
187
+ if (!isKey(m.clientRequestId)) return Promise.resolve(INVALID)
188
+ const message = { body: body.body, clientRequestId: m.clientRequestId }
189
+ return run('post', async () =>
190
+ fromMutation('post', await client.consultations.post(id, message), (r) => ({ duplicate: r.duplicate === true })),
191
+ )
192
+ },
193
+
194
+ requestErasure: (id) => {
195
+ if (!isConsultationId(id)) return Promise.resolve(NOT_FOUND)
196
+ return run('requestErasure', async () =>
197
+ fromMutation('requestErasure', await client.consultations.requestErasure(id), () => null),
198
+ )
199
+ },
200
+
201
+ consent: (locale) => {
202
+ if (!isLocale(locale)) return Promise.resolve(INVALID)
203
+ return run('consent', async () => {
204
+ const consent = await client.consultations.consent(locale)
205
+ if (!consent || typeof consent !== 'object') {
206
+ report('consent', 'unavailable')
207
+ return UNAVAILABLE
208
+ }
209
+ return { ok: true, value: consent }
210
+ })
211
+ },
212
+
213
+ /**
214
+ * The reader's consent status is one call with their own identity, never
215
+ * memoised (it belongs to one person and changes with their own actions).
216
+ * The public config is read only in notice mode, for the notice text. Not
217
+ * `fresh`: from the memo — but when the memo holds no notice text, once
218
+ * more past it: a channel switched from consent to notice a minute ago
219
+ * would otherwise keep this page closed for five.
220
+ */
221
+ webAsk: async (locale, opts = {}) => {
222
+ try {
223
+ const consent = await reader.consent(locale)
224
+ if (!consent.ok) return consent
225
+ if (consent.value.mode !== 'notice') return { ok: true, value: webAskFrom(consent.value, locale) }
226
+ const fresh = opts?.fresh === true
227
+ let notice = await webNotice(locale, fresh)
228
+ if (notice.ok && !fresh && !(notice.value.enabled && notice.value.mode === 'notice')) {
229
+ notice = await webNotice(locale, true)
230
+ }
231
+ if (!notice.ok) return notice
232
+ return { ok: true, value: webAskFrom(consent.value, locale, notice.value) }
233
+ } catch {
234
+ // Only a custom PublicConfigCache that throws gets here.
235
+ report('webAsk', 'unavailable')
236
+ return UNAVAILABLE
237
+ }
238
+ },
239
+
240
+ create: (q) => {
241
+ const body = normalizeBody(q?.body, READER_BODY_MAX)
242
+ if (!body.ok) return Promise.resolve({ ok: false, code: body.code })
243
+ if (!isKey(q.clientRequestId) || !isLocale(q.languageCode)) return Promise.resolve(INVALID)
244
+ const legal = legalInputOf(q.legal)
245
+ if (!legal) return Promise.resolve(INVALID)
246
+ // Only the fields of CreateMyConsultationInput, and `consent` / `notice` only when sent.
247
+ const input: CreateMyConsultationInput = {
248
+ body: body.body,
249
+ languageCode: q.languageCode,
250
+ ...legal,
251
+ clientRequestId: q.clientRequestId,
252
+ }
253
+ return run('create', async () => {
254
+ const outcome = fromMutation('create', await client.consultations.create(input), (r) => ({
255
+ id: typeof r.consultation?.id === 'string' ? r.consultation.id : '',
256
+ duplicate: r.duplicate === true,
257
+ }))
258
+ // The page redirects to the new thread: never build that path from anything but a UUID.
259
+ // (The question may exist in the KB — the reader finds it in the list.)
260
+ if (outcome.ok && !isConsultationId(outcome.value.id)) {
261
+ report('create', 'unavailable')
262
+ return UNAVAILABLE
263
+ }
264
+ return outcome
265
+ })
266
+ },
267
+
268
+ withdrawConsent: () =>
269
+ run<{ threadsClosed: number | null; alreadyWithdrawn: boolean }>('withdrawConsent', async () => {
270
+ const result = await client.consultations.withdrawConsent()
271
+ if (result && typeof result === 'object' && result.success !== true && result.code === 'NOTHING_TO_DO') {
272
+ return { ok: true, value: { threadsClosed: 0, alreadyWithdrawn: true } }
273
+ }
274
+ return fromMutation('withdrawConsent', result, (r) => ({
275
+ threadsClosed: countOrNull(r.threadsClosed),
276
+ alreadyWithdrawn: false,
277
+ }))
278
+ }),
279
+ }
280
+ return reader
281
+ }