@blogmcp/sdk 0.3.1 → 0.6.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 (63) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/client-types.d.ts +7 -1
  3. package/dist/core/client.d.ts +25 -1
  4. package/dist/core/client.js +38 -34
  5. package/dist/core/consultation-adapter.d.ts +90 -0
  6. package/dist/core/consultation-adapter.js +200 -0
  7. package/dist/core/consultations.d.ts +108 -0
  8. package/dist/core/consultations.js +95 -0
  9. package/dist/core/errors.d.ts +52 -0
  10. package/dist/core/errors.js +73 -0
  11. package/dist/core/index.d.ts +7 -1
  12. package/dist/core/index.js +80 -64
  13. package/dist/core/queries.d.ts +16 -1
  14. package/dist/core/queries.js +198 -61
  15. package/dist/core/review/format.d.ts +30 -0
  16. package/dist/core/review/format.js +78 -0
  17. package/dist/core/review/index.d.ts +6 -0
  18. package/dist/core/review/index.js +9 -0
  19. package/dist/core/review/types.d.ts +176 -0
  20. package/dist/core/review/types.js +9 -0
  21. package/dist/core/server-only.d.ts +12 -0
  22. package/dist/core/server-only.js +11 -0
  23. package/dist/core/types.d.ts +295 -0
  24. package/dist/packages/mdx-render-vue/dist/composables/useTripMap.js +21 -25
  25. package/dist/packages/mdx-render-vue/dist/edit/TripMapEdit.vue.js +1 -0
  26. package/dist/packages/mdx-render-vue/dist/render/tripmap/TripMapDefault.vue.js +105 -94
  27. package/dist/packages/mdx-schema/dist/metadata/index.js +12 -3
  28. package/dist/packages/mdx-schema/dist/styles/index.js +9 -1
  29. package/dist/packages/mdx-schema/dist/tripmap.js +81 -35
  30. package/dist/packages/tripmap-core/dist/attribution.js +121 -6
  31. package/dist/packages/tripmap-core/dist/css.js +149 -20
  32. package/dist/packages/tripmap-core/dist/detail.js +51 -0
  33. package/dist/packages/tripmap-core/dist/engine.js +367 -174
  34. package/dist/packages/tripmap-core/dist/export.js +72 -0
  35. package/dist/packages/tripmap-core/dist/filmstrip.js +30 -17
  36. package/dist/packages/tripmap-core/dist/framing.js +30 -30
  37. package/dist/packages/tripmap-core/dist/generated/maplibre-worker.bundle.js +1 -1
  38. package/dist/packages/tripmap-core/dist/heading.js +8 -0
  39. package/dist/packages/tripmap-core/dist/href.js +18 -0
  40. package/dist/packages/tripmap-core/dist/index.js +60 -36
  41. package/dist/packages/tripmap-core/dist/lightbox.js +96 -0
  42. package/dist/packages/tripmap-core/dist/line.js +6 -6
  43. package/dist/packages/tripmap-core/dist/markers.js +60 -51
  44. package/dist/packages/tripmap-core/dist/nodes.js +56 -43
  45. package/dist/packages/tripmap-core/dist/playback.js +20 -16
  46. package/dist/packages/tripmap-core/dist/preload.js +44 -0
  47. package/dist/packages/tripmap-core/dist/theme.js +21 -21
  48. package/dist/{node_modules → packages/tripmap-core/node_modules}/maplibre-gl/dist/maplibre-gl.js +2006 -1791
  49. package/dist/{node_modules → packages/tripmap-core/node_modules}/pmtiles/dist/esm/index.js +1 -1
  50. package/package.json +8 -3
  51. package/src/core/client-types.ts +13 -2
  52. package/src/core/client.ts +40 -5
  53. package/src/core/consultation-adapter.ts +408 -0
  54. package/src/core/consultations.ts +224 -0
  55. package/src/core/errors.ts +145 -0
  56. package/src/core/index.ts +68 -0
  57. package/src/core/queries.ts +167 -3
  58. package/src/core/review/format.ts +138 -0
  59. package/src/core/review/index.ts +22 -0
  60. package/src/core/review/types.ts +168 -0
  61. package/src/core/server-only.ts +20 -0
  62. package/src/core/types.ts +337 -0
  63. /package/dist/{node_modules → packages/tripmap-core/node_modules}/maplibre-gl/dist/maplibre-gl-shared.js +0 -0
@@ -1,4 +1,4 @@
1
- import { decompressSync as k } from "../../../fflate/esm/browser.js";
1
+ import { decompressSync as k } from "../../../../../../node_modules/fflate/esm/browser.js";
2
2
  var K = Object.defineProperty, F = Math.pow, h = (i, t) => K(i, "name", { value: t, configurable: !0 }), g = (i, t, e) => new Promise((r, n) => {
3
3
  var s = (l) => {
4
4
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blogmcp/sdk",
3
- "version": "0.3.1",
3
+ "version": "0.6.0",
4
4
  "description": "Headless SDK for Knowledge Base blog — core client, Vue composables, Nuxt adapter",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -27,6 +27,10 @@
27
27
  "./react/server": {
28
28
  "types": "./dist/react/server/index.d.ts",
29
29
  "import": "./dist/react/server/index.js"
30
+ },
31
+ "./review": {
32
+ "types": "./dist/core/review/index.d.ts",
33
+ "import": "./dist/core/review/index.js"
30
34
  }
31
35
  },
32
36
  "main": "./dist/core/index.js",
@@ -61,8 +65,8 @@
61
65
  }
62
66
  },
63
67
  "dependencies": {
64
- "@blogmcp/mdx-schema": "^0.4.0",
65
- "@blogmcp/sanitize": "^0.3.0",
68
+ "@blogmcp/mdx-schema": "^0.6.0",
69
+ "@blogmcp/sanitize": "^0.6.0",
66
70
  "marked": "^15.0.7"
67
71
  },
68
72
  "optionalDependencies": {
@@ -75,6 +79,7 @@
75
79
  "@types/react-dom": "^18.3.0",
76
80
  "@vitejs/plugin-vue": "^6.0.0",
77
81
  "@vue/test-utils": "^2.4.0",
82
+ "graphql": "^16.12.0",
78
83
  "happy-dom": "^17.4.0",
79
84
  "react": "^18.3.0",
80
85
  "react-dom": "^18.3.0",
@@ -5,7 +5,11 @@
5
5
  * and token storage, making the SDK framework-agnostic.
6
6
  */
7
7
 
8
- /** Function that performs HTTP requests. Compatible with native fetch, $fetch, axios, etc. */
8
+ /**
9
+ * Function that performs HTTP requests and returns the parsed GraphQL response
10
+ * body. Compatible with native fetch, $fetch, axios, etc. Pass `errors` through
11
+ * as the server sent them: `extensions.code` becomes `KbGraphQLError.code`.
12
+ */
9
13
  export type Fetcher = (
10
14
  url: string,
11
15
  init: {
@@ -13,7 +17,14 @@ export type Fetcher = (
13
17
  headers: Record<string, string>
14
18
  body: string
15
19
  },
16
- ) => Promise<{ data?: unknown; errors?: Array<{ message: string }> }>
20
+ ) => Promise<{
21
+ data?: unknown
22
+ errors?: Array<{
23
+ message: string
24
+ path?: ReadonlyArray<string | number>
25
+ extensions?: Record<string, unknown>
26
+ }>
27
+ }>
17
28
 
18
29
  /** Pluggable token storage. Implement for localStorage, cookies, or custom stores. */
19
30
  export interface TokenStorage {
@@ -29,6 +29,13 @@ import type {
29
29
  import type { NavNode } from './navigation'
30
30
  import * as Q from './queries'
31
31
  import { createMemoryTokenStorage } from './auth'
32
+ import { KbGraphQLError } from './errors'
33
+ import {
34
+ createConsultationsApi,
35
+ createConsultationSessionApi,
36
+ type KbConsultationsApi,
37
+ type KbConsultationSessionApi,
38
+ } from './consultations'
32
39
 
33
40
  /** Default fetcher using native fetch */
34
41
  function createDefaultFetcher(): Fetcher {
@@ -42,7 +49,11 @@ function createDefaultFetcher(): Fetcher {
42
49
  }
43
50
  }
44
51
 
45
- /** Execute a GraphQL query and return typed data */
52
+ /**
53
+ * Execute a GraphQL query and return typed data. A response with `errors`
54
+ * throws KbGraphQLError (an Error with the first error's message and its
55
+ * `extensions.code`).
56
+ */
46
57
  async function executeGraphQL<T>(
47
58
  config: {
48
59
  endpoint: string
@@ -72,7 +83,7 @@ async function executeGraphQL<T>(
72
83
  })
73
84
 
74
85
  if (result.errors?.length) {
75
- throw new Error(result.errors[0].message)
86
+ throw new KbGraphQLError(result.errors)
76
87
  }
77
88
 
78
89
  return (result as { data: T }).data
@@ -164,10 +175,21 @@ export interface KbClient {
164
175
  navigation: {
165
176
  get(params?: { scope?: string; locale?: string }): Promise<{ kbNavigation: NavNode[] }>
166
177
  }
178
+ /**
179
+ * Editorial access to translation ROWS — INTERNAL tokens only (a server client holding a
180
+ * kb_* internal key). The server refuses every other caller: a translation row carries the
181
+ * working copy, which for an article with unpublished edits is unpublished text.
182
+ *
183
+ * A reader (public or member token, a storefront, a headless blog) gets an article in a
184
+ * language through `articles.getWithTranslation` / `articles.getWithTranslationById`, which
185
+ * serve the published text with the best available translation.
186
+ */
167
187
  translations: {
168
- list(sourceFilename: string): Promise<{
188
+ /** All translations of one article, by its immutable id (0.3 wrongly took a filename). Internal tokens only. */
189
+ list(articleId: string): Promise<{
169
190
  listArticleTranslations: Translation[]
170
191
  }>
192
+ /** One translation row, working copy included. Internal tokens only. */
171
193
  get(
172
194
  sourceFilename: string,
173
195
  languageCode: string,
@@ -231,6 +253,18 @@ export interface KbClient {
231
253
  input: UpdateReportSettingsInput,
232
254
  ): Promise<{ updateMyReportSettings: ReportSettings }>
233
255
  }
256
+ /**
257
+ * Reader consultations for a reader identity in the token storage (a
258
+ * delegated storefront token, or a signed-in KB reader account). Results are
259
+ * returned unwrapped; mutations resolve to `{success, code, error, ...}` and
260
+ * do not throw on domain errors.
261
+ */
262
+ consultations: KbConsultationsApi
263
+ /**
264
+ * Reader consultations through a magic-link session. SERVER-ONLY: every
265
+ * method rejects in a browser, so a session never reaches page JavaScript.
266
+ */
267
+ consultationSession: KbConsultationSessionApi
234
268
  /** Raw GraphQL execution for escape hatch */
235
269
  executeGraphQL<T = unknown>(
236
270
  query: string,
@@ -282,8 +316,7 @@ export function createKbClient(config: KbClientConfig): KbClient {
282
316
  get: (params) => exec(Q.KB_NAVIGATION, params ?? {}),
283
317
  },
284
318
  translations: {
285
- list: (sourceFilename) =>
286
- exec(Q.ARTICLE_TRANSLATIONS, { sourceFilename }),
319
+ list: (articleId) => exec(Q.ARTICLE_TRANSLATIONS, { articleId }),
287
320
  get: (sourceFilename, languageCode) =>
288
321
  exec(Q.GET_TRANSLATION, { sourceFilename, languageCode }),
289
322
  },
@@ -320,6 +353,8 @@ export function createKbClient(config: KbClientConfig): KbClient {
320
353
  update: (input) =>
321
354
  exec(Q.UPDATE_MY_REPORT_SETTINGS, input as Record<string, unknown>),
322
355
  },
356
+ consultations: createConsultationsApi(exec),
357
+ consultationSession: createConsultationSessionApi(exec),
323
358
  executeGraphQL: exec,
324
359
  }
325
360
  }
@@ -0,0 +1,408 @@
1
+ /**
2
+ * Reader consultations — a typed client for the tenant adapter REST contract
3
+ * (docs/internal/reader-consultations.md §8.3; KB side:
4
+ * apps/knowledge-base/api/src/routes/consultations-adapter.ts).
5
+ *
6
+ * A tenant adapter (e.g. a shop backend) holds a scoped adapter key minted in
7
+ * the KB admin (`createConsultationAdapterKey`). With it the adapter:
8
+ *
9
+ * ingest stores a reader's message (idempotent by channel + externalMessageId)
10
+ * lease/ack/fail sends the KB's content-free notices (the outbox)
11
+ * stats reads outbox health
12
+ * erase erases everything under a deleted customer's ref
13
+ * ownerRefs lists the refs the KB holds data for (nightly reconcile)
14
+ * threadOwner checks who owns a thread before importing an e-mail
15
+ * threadByNotice finds the thread a notice's Message-ID belongs to
16
+ *
17
+ * SERVER-ONLY: `createConsultationAdapterClient` throws in a browser — the key
18
+ * is a server-side secret. The client never logs: request and response bodies
19
+ * carry reader text, addresses and link tokens. Errors are
20
+ * `ConsultationAdapterError` with the contract's `{code}` and the HTTP status;
21
+ * their message names the operation, status and code only, never a body.
22
+ */
23
+
24
+ import type { KbErrorCode } from './errors'
25
+ import { assertServerOnly } from './server-only'
26
+ import type {
27
+ ConsultationAckInput,
28
+ ConsultationEraseInput,
29
+ ConsultationEraseResult,
30
+ ConsultationFailInput,
31
+ ConsultationIngestInput,
32
+ ConsultationIngestResult,
33
+ ConsultationLeaseInput,
34
+ ConsultationLeaseResult,
35
+ ConsultationOkResult,
36
+ ConsultationOutboxStats,
37
+ ConsultationOwnerRefsInput,
38
+ ConsultationOwnerRefsResult,
39
+ ConsultationThreadByNotice,
40
+ ConsultationThreadOwner,
41
+ } from './types'
42
+
43
+ export interface ConsultationAdapterClientConfig {
44
+ /**
45
+ * The KB API base URL: `https://<tenant host>/api` through the ingress, or
46
+ * the in-cluster `http://<kb-api>:5070`. The client appends
47
+ * `/consultations/adapter/<route>`; a base that already ends in
48
+ * `/consultations/adapter` is used as it is.
49
+ */
50
+ baseUrl: string
51
+ /** The scoped adapter key. Server-side secret. */
52
+ apiKey: string
53
+ /** Custom fetch implementation (tests / non-global-fetch runtimes). */
54
+ fetch?: typeof fetch
55
+ /**
56
+ * Abort a request (including reading its response) after this many ms.
57
+ * Default 10 000; 0 disables. Ingest runs on a reader's form submit, so a
58
+ * hung KB must not hang the form: on a timeout the adapter falls back.
59
+ */
60
+ timeoutMs?: number
61
+ }
62
+
63
+ export type ConsultationAdapterOperation =
64
+ | 'ingest'
65
+ | 'lease'
66
+ | 'ack'
67
+ | 'fail'
68
+ | 'stats'
69
+ | 'erase'
70
+ | 'ownerRefs'
71
+ | 'threadOwner'
72
+ | 'threadByNotice'
73
+
74
+ /** A failed adapter call. */
75
+ export class ConsultationAdapterError extends Error {
76
+ readonly operation: ConsultationAdapterOperation
77
+ /** HTTP status; 0 when no response arrived (network error, timeout). */
78
+ readonly status: number
79
+ /**
80
+ * The contract's `{code}` (e.g. SENDER_MISMATCH, STALE_LEASE, QUOTA_EXCEEDED),
81
+ * or null when there was no response or its body was not the contract's
82
+ * (e.g. a proxy's 502 page, or a malformed success body).
83
+ */
84
+ readonly code: KbErrorCode | null
85
+
86
+ constructor(
87
+ operation: ConsultationAdapterOperation,
88
+ status: number,
89
+ code: KbErrorCode | null,
90
+ reason: string,
91
+ options?: { cause?: unknown },
92
+ ) {
93
+ super(`[blogmcp-sdk] consultation adapter ${operation} ${reason}`, options)
94
+ this.name = 'ConsultationAdapterError'
95
+ this.operation = operation
96
+ this.status = status
97
+ this.code = code
98
+ }
99
+ }
100
+
101
+ export function isConsultationAdapterError(err: unknown): err is ConsultationAdapterError {
102
+ return (
103
+ err instanceof ConsultationAdapterError ||
104
+ (err instanceof Error &&
105
+ err.name === 'ConsultationAdapterError' &&
106
+ typeof (err as { status?: unknown }).status === 'number')
107
+ )
108
+ }
109
+
110
+ export interface ConsultationAdapterClient {
111
+ /**
112
+ * Store a reader's message. `created` (HTTP 201) the first time, `duplicate`
113
+ * (200) on an identical replay; the same externalMessageId with a different
114
+ * payload is IDEMPOTENCY_CONFLICT. `clientIp` is the reader's IP, forwarded
115
+ * for the KB's per-IP quota: ONE IPv4/IPv6 address (not a raw
116
+ * X-Forwarded-For list, no zone id). Anything else is not sent, and the KB
117
+ * then buckets the reader under the adapter's own IP.
118
+ */
119
+ ingest(input: ConsultationIngestInput, opts?: { clientIp?: string }): Promise<ConsultationIngestResult>
120
+ /** Lease due notices of a channel. Tokens in the response exist nowhere else: use, never store or log. */
121
+ lease(input: ConsultationLeaseInput): Promise<ConsultationLeaseResult>
122
+ /** A leased notice went out. Idempotent for the same lease; otherwise STALE_LEASE (409). */
123
+ ack(deliveryId: string, input: ConsultationAckInput): Promise<ConsultationOkResult>
124
+ /** A leased notice did not go out: retried with backoff, or failed for good. */
125
+ fail(deliveryId: string, input: ConsultationFailInput): Promise<ConsultationOkResult>
126
+ /** Outbox counts for a channel (default `email`). */
127
+ stats(channel?: string): Promise<ConsultationOutboxStats>
128
+ /** Erase everything the KB holds under a ref. Works while the module is off; RETRY_LATER (503) is retryable. */
129
+ erase(input: ConsultationEraseInput): Promise<ConsultationEraseResult>
130
+ /** One page of the refs the KB holds data for, under the key's prefix. */
131
+ ownerRefs(input?: ConsultationOwnerRefsInput): Promise<ConsultationOwnerRefsResult>
132
+ /** Who owns a thread (no content). NOT_FOUND for a thread outside the key's prefix. */
133
+ threadOwner(threadId: string): Promise<ConsultationThreadOwner>
134
+ /** The thread whose notice went out with this Message-ID (`In-Reply-To` matching). */
135
+ threadByNotice(messageId: string): Promise<ConsultationThreadByNotice>
136
+ }
137
+
138
+ const ADAPTER_PATH = '/consultations/adapter'
139
+ const CLIENT_IP_HEADER = 'X-Blogmcp-Client-Ip'
140
+ const DEFAULT_TIMEOUT_MS = 10_000
141
+ /** A contract code; anything else in an error body (a proxy's text) is not trusted into the error. */
142
+ const CODE_RE = /^[A-Z][A-Z0-9_]{0,63}$/
143
+ /**
144
+ * A key that is safe as an HTTP header value: visible ASCII, no whitespace.
145
+ * Checked up front because fetch's own header error QUOTES the value
146
+ * (`Headers.append: "Bearer kb_…" is an invalid header value`), and that error
147
+ * would travel on as the `cause` of a ConsultationAdapterError into a log.
148
+ */
149
+ const HEADER_TOKEN_RE = /^[\x21-\x7E]+$/
150
+ /**
151
+ * The characters of one IPv4 or IPv6 address (no zone id, no list). Anything
152
+ * else is not sent: the KB ignores a malformed value anyway (it falls back to
153
+ * the transport IP), and fetch would quote it in a header error.
154
+ */
155
+ const CLIENT_IP_RE = /^[0-9A-Fa-f.:]{2,45}$/
156
+
157
+ function adapterBase(baseUrl: string): string {
158
+ let url: URL
159
+ try {
160
+ url = new URL(baseUrl)
161
+ } catch {
162
+ throw new Error('[blogmcp-sdk] consultation adapter baseUrl must be an absolute http(s) URL')
163
+ }
164
+ if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.search || url.hash) {
165
+ throw new Error('[blogmcp-sdk] consultation adapter baseUrl must be an http(s) URL without a query or fragment')
166
+ }
167
+ const path = url.pathname.replace(/\/+$/, '')
168
+ return url.origin + (path.endsWith(ADAPTER_PATH) ? path : path + ADAPTER_PATH)
169
+ }
170
+
171
+ /**
172
+ * Deterministic JSON: object keys sorted at every level, null and undefined
173
+ * members dropped (the KB treats them as absent), Dates as ISO strings. The KB
174
+ * hashes the ingest payload for idempotency and sorts only the top-level keys,
175
+ * so a retry must serialise nested objects (`newThread`, `sender`) exactly as
176
+ * the first attempt did, whatever key order the caller built them in.
177
+ */
178
+ function canonical(value: unknown): unknown {
179
+ if (value instanceof Date) return value.toISOString()
180
+ if (Array.isArray(value)) return value.map(canonical)
181
+ if (value !== null && typeof value === 'object') {
182
+ const out: Record<string, unknown> = {}
183
+ for (const key of Object.keys(value).sort()) {
184
+ const v = (value as Record<string, unknown>)[key]
185
+ if (v === undefined || v === null) continue
186
+ out[key] = canonical(v)
187
+ }
188
+ return out
189
+ }
190
+ return value
191
+ }
192
+
193
+ function isRecord(v: unknown): v is Record<string, unknown> {
194
+ return v !== null && typeof v === 'object' && !Array.isArray(v)
195
+ }
196
+
197
+ const legal = (l: { version: string; locale: string } | undefined) =>
198
+ l ? { version: l.version, locale: l.locale } : undefined
199
+
200
+ /**
201
+ * The ingest body, field by field (§8.3): only the contract's fields leave the
202
+ * process, so a caller passing a richer object (a whole customer record as the
203
+ * owner, say) cannot ship more than the contract asks for.
204
+ */
205
+ function ingestBody(input: ConsultationIngestInput): Record<string, unknown> {
206
+ const nt = input.newThread
207
+ const owner = nt?.owner as { externalRef?: string; email?: string } | undefined
208
+ return {
209
+ channel: input.channel,
210
+ externalMessageId: input.externalMessageId,
211
+ body: input.body,
212
+ languageCode: input.languageCode,
213
+ sentAt: input.sentAt,
214
+ threadId: input.threadId,
215
+ sender: input.sender ? { email: input.sender.email, externalRef: input.sender.externalRef } : undefined,
216
+ newThread: nt
217
+ ? {
218
+ owner: owner ? { externalRef: owner.externalRef, email: owner.email } : undefined,
219
+ displayName: nt.displayName,
220
+ externalThreadRef: nt.externalThreadRef,
221
+ legalBasis: nt.legalBasis,
222
+ notice: legal(nt.notice),
223
+ consent: nt.consent
224
+ ? { version: nt.consent.version, locale: nt.consent.locale, givenAt: nt.consent.givenAt }
225
+ : undefined,
226
+ }
227
+ : undefined,
228
+ }
229
+ }
230
+
231
+ interface RequestSpec {
232
+ method: 'GET' | 'POST'
233
+ path: string
234
+ query?: Record<string, string | number | undefined>
235
+ body?: unknown
236
+ headers?: Record<string, string>
237
+ /** Minimal shape check of a success body. */
238
+ valid?: (payload: Record<string, unknown>) => boolean
239
+ }
240
+
241
+ export function createConsultationAdapterClient(
242
+ config: ConsultationAdapterClientConfig,
243
+ ): ConsultationAdapterClient {
244
+ assertServerOnly(
245
+ 'createConsultationAdapterClient',
246
+ 'it holds an adapter API key that must never reach the browser.',
247
+ )
248
+ if (!config?.baseUrl) throw new Error('[blogmcp-sdk] consultation adapter baseUrl is required')
249
+ // A key read from a secret file often ends in a newline; keys never contain whitespace.
250
+ const apiKey = typeof config.apiKey === 'string' ? config.apiKey.trim() : ''
251
+ if (!apiKey) throw new Error('[blogmcp-sdk] consultation adapter apiKey is required')
252
+ if (!HEADER_TOKEN_RE.test(apiKey)) {
253
+ // Never echo the key.
254
+ throw new Error('[blogmcp-sdk] consultation adapter apiKey contains characters not allowed in an HTTP header')
255
+ }
256
+ const base = adapterBase(config.baseUrl)
257
+ const fetchImpl = config.fetch ?? globalThis.fetch
258
+ if (typeof fetchImpl !== 'function') throw new Error('[blogmcp-sdk] no fetch implementation available')
259
+ const timeoutMs = Math.max(0, config.timeoutMs ?? DEFAULT_TIMEOUT_MS)
260
+
261
+ async function request<T>(operation: ConsultationAdapterOperation, spec: RequestSpec): Promise<T> {
262
+ const params = new URLSearchParams()
263
+ for (const [k, v] of Object.entries(spec.query ?? {})) {
264
+ if (v !== undefined && v !== '') params.set(k, String(v))
265
+ }
266
+ const qs = params.toString()
267
+ const url = `${base}${spec.path}${qs ? `?${qs}` : ''}`
268
+
269
+ const headers: Record<string, string> = {
270
+ ...(spec.headers ?? {}),
271
+ Accept: 'application/json',
272
+ Authorization: `Bearer ${apiKey}`,
273
+ }
274
+ if (spec.body !== undefined) headers['Content-Type'] = 'application/json'
275
+
276
+ const controller = timeoutMs > 0 ? new AbortController() : null
277
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null
278
+ let status = 0
279
+ let text: string
280
+ try {
281
+ const res = await fetchImpl(url, {
282
+ method: spec.method,
283
+ headers,
284
+ body: spec.body === undefined ? undefined : JSON.stringify(canonical(spec.body)),
285
+ signal: controller?.signal,
286
+ // The contract never redirects. Following one would re-send the key
287
+ // to wherever it points (and turn a POST into a body-less GET), so a
288
+ // redirect is a failed request, never a silent retarget.
289
+ redirect: 'error',
290
+ })
291
+ status = res.status
292
+ text = await res.text()
293
+ if (!res.ok) {
294
+ const code = errorCodeOf(text)
295
+ throw new ConsultationAdapterError(operation, status, code, `failed: HTTP ${status}${code ? ` ${code}` : ''}`)
296
+ }
297
+ } catch (err) {
298
+ if (err instanceof ConsultationAdapterError) throw err
299
+ // The cause is kept for the caller; this module never logs it.
300
+ const reason = controller?.signal.aborted ? `timed out after ${timeoutMs} ms` : 'request failed'
301
+ throw new ConsultationAdapterError(operation, status, null, reason, { cause: err })
302
+ } finally {
303
+ if (timer) clearTimeout(timer)
304
+ }
305
+
306
+ let payload: unknown
307
+ try {
308
+ payload = JSON.parse(text)
309
+ } catch {
310
+ payload = undefined
311
+ }
312
+ if (!isRecord(payload) || (spec.valid && !spec.valid(payload))) {
313
+ throw new ConsultationAdapterError(operation, status, null, `returned a malformed response (HTTP ${status})`)
314
+ }
315
+ return payload as T
316
+ }
317
+
318
+ const ok = (p: Record<string, unknown>) => p.ok === true
319
+ const id = (v: string) => encodeURIComponent(v)
320
+
321
+ return {
322
+ ingest: (input, opts) =>
323
+ request('ingest', {
324
+ method: 'POST',
325
+ path: '/ingest',
326
+ body: ingestBody(input),
327
+ headers:
328
+ typeof opts?.clientIp === 'string' && CLIENT_IP_RE.test(opts.clientIp.trim())
329
+ ? { [CLIENT_IP_HEADER]: opts.clientIp.trim() }
330
+ : undefined,
331
+ valid: (p) =>
332
+ (p.status === 'created' || p.status === 'duplicate') &&
333
+ typeof p.threadId === 'string' &&
334
+ typeof p.messageId === 'string',
335
+ }),
336
+ lease: (input) =>
337
+ request('lease', {
338
+ method: 'POST',
339
+ path: '/outbox/lease',
340
+ body: { channel: input.channel, max: input.max, leaseSeconds: input.leaseSeconds },
341
+ valid: (p) => Array.isArray(p.items),
342
+ }),
343
+ ack: (deliveryId, input) =>
344
+ request('ack', {
345
+ method: 'POST',
346
+ path: `/outbox/${id(deliveryId)}/ack`,
347
+ body: { leaseId: input.leaseId, providerMessageId: input.providerMessageId, channel: input.channel },
348
+ valid: ok,
349
+ }),
350
+ fail: (deliveryId, input) =>
351
+ request('fail', {
352
+ method: 'POST',
353
+ path: `/outbox/${id(deliveryId)}/fail`,
354
+ body: {
355
+ leaseId: input.leaseId,
356
+ errorCode: input.errorCode,
357
+ retryable: input.retryable,
358
+ channel: input.channel,
359
+ },
360
+ valid: ok,
361
+ }),
362
+ stats: (channel) =>
363
+ request('stats', {
364
+ method: 'GET',
365
+ path: '/outbox/stats',
366
+ query: { channel },
367
+ valid: (p) => typeof p.pending === 'number',
368
+ }),
369
+ erase: (input) =>
370
+ request('erase', {
371
+ method: 'POST',
372
+ path: '/erase',
373
+ body: { externalRef: input.externalRef, dryRun: input.dryRun },
374
+ valid: (p) => typeof p.requestId === 'string',
375
+ }),
376
+ ownerRefs: (input) =>
377
+ request('ownerRefs', {
378
+ method: 'GET',
379
+ path: '/owner-refs',
380
+ query: { prefix: input?.prefix, after: input?.after, limit: input?.limit },
381
+ valid: (p) => Array.isArray(p.refs),
382
+ }),
383
+ threadOwner: (threadId) =>
384
+ request('threadOwner', {
385
+ method: 'GET',
386
+ path: `/threads/${id(threadId)}/owner`,
387
+ valid: (p) => typeof p.ownerKind === 'string',
388
+ }),
389
+ threadByNotice: (messageId) =>
390
+ request('threadByNotice', {
391
+ method: 'GET',
392
+ path: '/threads/by-notice',
393
+ query: { messageId },
394
+ valid: (p) => typeof p.threadId === 'string',
395
+ }),
396
+ }
397
+ }
398
+
399
+ /** The `{code}` of an error body, when it is a contract code. */
400
+ function errorCodeOf(text: string): KbErrorCode | null {
401
+ try {
402
+ const body = JSON.parse(text) as unknown
403
+ const code = isRecord(body) ? body.code : undefined
404
+ return typeof code === 'string' && CODE_RE.test(code) ? code : null
405
+ } catch {
406
+ return null
407
+ }
408
+ }