@blogmcp/sdk 0.7.0 → 0.8.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.
@@ -0,0 +1,78 @@
1
+ import { REVIEW_ROOT_ATTR as c, REVIEW_FIELD_ATTR as d, REVIEW_IGNORE_ATTR as u } from "./stamp.js";
2
+ function f() {
3
+ return {
4
+ "Cache-Control": "private, no-store",
5
+ "X-Robots-Tag": "noindex, nofollow",
6
+ "Referrer-Policy": "no-referrer",
7
+ "X-Frame-Options": "DENY"
8
+ };
9
+ }
10
+ function m() {
11
+ return { [c]: "" };
12
+ }
13
+ function g(t) {
14
+ return { [d]: t };
15
+ }
16
+ function y() {
17
+ return { [u]: "" };
18
+ }
19
+ const p = {
20
+ en: {
21
+ not_found: { title: "Review link not found", body: "Check that you opened the whole link, or ask for a new one." },
22
+ expired: { title: "This review link has expired", body: "Ask for a new link to review the current draft." },
23
+ revoked: { title: "This review link was closed", body: "Ask for a new link if you still want to review the draft." },
24
+ superseded: { title: "A newer review link replaced this one", body: "Open the newest link you were sent." },
25
+ unavailable: { title: "Reviews are not available right now", body: "Try again later." },
26
+ rate_limited: { title: "Too many requests", body: "Wait a minute and reload the page." },
27
+ network: { title: "The review could not be loaded", body: "Reload the page in a moment." },
28
+ default: { title: "The review could not be loaded", body: "Reload the page in a moment." }
29
+ },
30
+ cs: {
31
+ not_found: { title: "Odkaz na recenzi neexistuje", body: "Zkontrolujte, že jste otevřeli celý odkaz, nebo si řekněte o nový." },
32
+ expired: { title: "Platnost odkazu na recenzi vypršela", body: "Řekněte si o nový odkaz na aktuální koncept." },
33
+ revoked: { title: "Odkaz na recenzi byl zrušen", body: "Pokud chcete koncept ještě projít, řekněte si o nový odkaz." },
34
+ superseded: { title: "Tento odkaz nahradil novější", body: "Otevřete nejnovější odkaz, který jste dostali." },
35
+ unavailable: { title: "Recenze teď nejsou dostupné", body: "Zkuste to prosím později." },
36
+ rate_limited: { title: "Příliš mnoho požadavků", body: "Chvíli počkejte a stránku načtěte znovu." },
37
+ network: { title: "Recenzi se nepodařilo načíst", body: "Za chvíli stránku načtěte znovu." },
38
+ default: { title: "Recenzi se nepodařilo načíst", body: "Za chvíli stránku načtěte znovu." }
39
+ }
40
+ };
41
+ function v(t, e = "en") {
42
+ const n = p[e.toLowerCase().startsWith("cs") ? "cs" : "en"];
43
+ return n[t] ?? n.default;
44
+ }
45
+ function o(t) {
46
+ return t.replace(/[&<>"']/g, (e) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[e]);
47
+ }
48
+ function R(t, e = {}) {
49
+ const n = v(t, e.lang);
50
+ return `<section class="blogmcp-review-status" role="status" data-reason="${o(t)}"><h1>${o(n.title)}</h1><p>${o(n.body)}</p></section>`;
51
+ }
52
+ const k = "https://cdn.jsdelivr.net/npm/@blogmcp/review@0.1.0/dist/blogmcp-review.global.js", s = "blogmcp-review-session";
53
+ function b(t) {
54
+ return JSON.stringify(t).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
55
+ }
56
+ function E(t, e) {
57
+ const n = e.nonce ? ` nonce="${o(e.nonce)}"` : "", r = e.lang ?? t.article.languageCode;
58
+ return `<script type="application/json" id="${s}"${n}>${b(t)}<\/script><blogmcp-review session-id="${s}" token="${o(e.token)}" kb-url="${o(e.kbUrl)}" lang="${o(r)}"` + (e.nonce ? ` csp-nonce="${o(e.nonce)}"` : "") + `></blogmcp-review><script src="${o(e.scriptSrc ?? k)}" defer${n}><\/script>`;
59
+ }
60
+ const w = /(?:https?:\/\/[^\s"'()<>]+?)?\/api\/(?:kb-)?media\/(file|thumb)\/([A-Za-z0-9][A-Za-z0-9._-]*)(\?[^\s"'()<>]*)?/g;
61
+ function T(t, e) {
62
+ return t.replace(w, (n, r, a) => {
63
+ const l = a.lastIndexOf("."), i = e[a] ?? (l > 0 ? e[a.slice(0, l)] : void 0);
64
+ return !i || i.accessLevel === "public" ? n : r === "thumb" ? i.thumbnailUrl : i.url;
65
+ });
66
+ }
67
+ export {
68
+ k as REVIEW_LAYER_SCRIPT_URL,
69
+ s as REVIEW_SESSION_ELEMENT_ID,
70
+ R as renderReviewStatusHtml,
71
+ E as reviewBootstrapHtml,
72
+ T as reviewContentWithMedia,
73
+ g as reviewFieldAttrs,
74
+ y as reviewIgnoreAttrs,
75
+ f as reviewResponseHeaders,
76
+ m as reviewRootAttrs,
77
+ v as reviewStatusText
78
+ };
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The review plan: the working copy's addressable blocks — `mdx-N` id, body-relative
3
+ * `sourceRange`, and what each block should look like once a site has rendered it.
4
+ *
5
+ * The ids come from mdx-schema's `planArticleUnits`, the same split `@blogmcp/render-embed`'s
6
+ * `parseArticle` (the article-review app, md-editor) uses, so a comment's block id means the same
7
+ * block whichever surface produced it. `stampReviewDom` matches the plan against the site's own
8
+ * DOM; the plan itself renders nothing.
9
+ */
10
+ export interface ReviewPlanUnit {
11
+ /** `mdx-N`. */
12
+ nodeId: string;
13
+ /** Offsets into the working copy's body (after the frontmatter). */
14
+ sourceRange: {
15
+ start: number;
16
+ end: number;
17
+ };
18
+ kind: 'markdown' | 'component';
19
+ /** The component name, or the markdown block's type (`heading`, `paragraph`, `list`, `code`, …; `span` when unsplit). */
20
+ type: string;
21
+ /** Element tags (upper case) a site may render this block as; empty = any. Unused for components. */
22
+ tags: readonly string[];
23
+ /** The block's leading text, normalised (`normalizeReviewText`); '' when it has none. */
24
+ text: string;
25
+ }
26
+ export interface ReviewPlan {
27
+ bodyOffset: number;
28
+ units: ReviewPlanUnit[];
29
+ }
30
+ /**
31
+ * Text reduced to what survives any renderer: lower-case letters and digits only (diacritics kept),
32
+ * so markdown punctuation, smart quotes, dashes and whitespace never decide a match.
33
+ */
34
+ export declare function normalizeReviewText(text: string): string;
35
+ /**
36
+ * The plan of an article's working copy (`ReviewArticle.content`, frontmatter included).
37
+ * `bodyOffset` equals the session's `article.bodyOffset`.
38
+ */
39
+ export declare function createReviewPlan(content: string): ReviewPlan;
@@ -0,0 +1,57 @@
1
+ import { Marked as i } from "marked";
2
+ import { planArticleUnits as p } from "@blogmcp/mdx-schema/composables/parsing";
3
+ const o = 48;
4
+ function c(r) {
5
+ return r.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "");
6
+ }
7
+ const l = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
8
+ function g(r) {
9
+ return r.replace(/<!--[\s\S]*?-->/g, "").replace(/!\[[^\]]*\]\([^)]*\)/g, "").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\[([^\]]*)\]\[[^\]]*\]/g, "$1").replace(/<[^>]+>/g, " ").replace(/&(#\d+|#x[0-9a-f]+|[a-z]+);/gi, (e, n) => {
10
+ if (n[0] === "#") {
11
+ const t = n[1] === "x" || n[1] === "X" ? parseInt(n.slice(2), 16) : parseInt(n.slice(1), 10);
12
+ return Number.isFinite(t) ? String.fromCodePoint(t) : e;
13
+ }
14
+ return l[n.toLowerCase()] ?? e;
15
+ });
16
+ }
17
+ function a(r) {
18
+ return c(g(r)).slice(0, o);
19
+ }
20
+ const u = ["H1", "H2", "H3", "H4", "H5", "H6"], d = ["P", "FIGURE", "IMG", "PICTURE"];
21
+ function x(r) {
22
+ if (!r) return { type: "span", tags: [], text: "" };
23
+ const e = r;
24
+ switch (e.type) {
25
+ case "heading":
26
+ return { type: "heading", tags: u, text: a(e.text ?? "") };
27
+ case "paragraph":
28
+ return { type: "paragraph", tags: d, text: a(e.text ?? "") };
29
+ case "list":
30
+ return { type: "list", tags: ["UL", "OL"], text: a(e.items?.[0]?.text ?? "") };
31
+ case "code":
32
+ return { type: "code", tags: ["PRE"], text: c(e.text ?? "").slice(0, o) };
33
+ case "blockquote":
34
+ return { type: "blockquote", tags: ["BLOCKQUOTE"], text: a(e.text ?? "") };
35
+ case "table":
36
+ return { type: "table", tags: ["TABLE"], text: a((e.header ?? []).map((n) => n.text ?? "").join(" ")) };
37
+ case "hr":
38
+ return { type: "hr", tags: ["HR"], text: "" };
39
+ default:
40
+ return { type: e.type, tags: [], text: a(e.raw) };
41
+ }
42
+ }
43
+ let s = null;
44
+ function y(r) {
45
+ s ??= new i();
46
+ const e = s, n = p(r, (t) => e.lexer(t));
47
+ return {
48
+ bodyOffset: n.bodyOffset,
49
+ units: n.units.map(
50
+ (t) => t.kind === "component" ? { nodeId: t.nodeId, sourceRange: t.sourceRange, kind: "component", type: t.name, tags: [], text: "" } : { nodeId: t.nodeId, sourceRange: t.sourceRange, kind: "markdown", ...x(t.token) }
51
+ )
52
+ };
53
+ }
54
+ export {
55
+ y as createReviewPlan,
56
+ c as normalizeReviewText
57
+ };
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Matching the review plan against a site's own rendered article, in the browser.
3
+ *
4
+ * A site renders the working copy with its own article view; the review layer must not change that
5
+ * view's markup. So instead of asking every renderer for a review mode, the layer walks the rendered
6
+ * article once, pairs each plan block with the element that shows it (by tag and leading text, and
7
+ * components by their `data-mdx-component`, which our renderers already emit), and puts ONE
8
+ * attribute on that element: `data-mdx-node-id`. No element is added, moved or wrapped. `restore()`
9
+ * takes the attributes off again.
10
+ *
11
+ * Blocks that cannot be paired (a raw HTML block, a custom component without `data-mdx-component`,
12
+ * a heading the site moved into its own header) just stay unstamped: comments there fall back to
13
+ * quote + context (level 0), which works with any renderer. A renderer that already stamps
14
+ * `data-mdx-node-id` (`@blogmcp/render-embed-*`) is left as it is.
15
+ */
16
+ import { type ReviewPlan } from './plan.js';
17
+ import type { ReviewNodeRef } from './types.js';
18
+ /** Put this on the element that holds the article (`reviewRootAttrs()`). */
19
+ export declare const REVIEW_ROOT_ATTR = "data-blogmcp-review-root";
20
+ /** Put this on the title, description or featured image (`reviewFieldAttrs(…)`). */
21
+ export declare const REVIEW_FIELD_ATTR = "data-blogmcp-review-field";
22
+ /** Elements (and their subtree) the layer must ignore: site chrome inside the article root. */
23
+ export declare const REVIEW_IGNORE_ATTR = "data-blogmcp-review-ignore";
24
+ export interface ReviewStamp {
25
+ /** 1 when at least one block carries an id (comments get block ids and source ranges), else 0. */
26
+ level: 0 | 1;
27
+ matched: number;
28
+ total: number;
29
+ /** The block element of each id that is on the page. */
30
+ elements: ReadonlyMap<string, Element>;
31
+ /** The block a node of the article belongs to, as a comment refers to it. */
32
+ nodeRef(node: Node | null): ReviewNodeRef | null;
33
+ /** Take off every attribute this stamp put on. */
34
+ restore(): void;
35
+ }
36
+ /**
37
+ * Pair the plan with the article under `root` and stamp `data-mdx-node-id` on each paired element.
38
+ * Idempotent: an element that already carries an id keeps it.
39
+ */
40
+ export declare function stampReviewDom(root: Element, plan: ReviewPlan): ReviewStamp;
@@ -0,0 +1,106 @@
1
+ import { normalizeReviewText as O } from "./plan.js";
2
+ const w = "data-blogmcp-review-root", C = "data-blogmcp-review-field", _ = "data-blogmcp-review-ignore", d = "data-mdx-node-id", b = "data-mdx-component", L = /^[A-Za-z0-9_.:-]{1,64}$/;
3
+ function E(t) {
4
+ const e = t.getAttribute(b);
5
+ return e || null;
6
+ }
7
+ const N = /* @__PURE__ */ new Set([
8
+ "P",
9
+ "H1",
10
+ "H2",
11
+ "H3",
12
+ "H4",
13
+ "H5",
14
+ "H6",
15
+ "UL",
16
+ "OL",
17
+ "PRE",
18
+ "BLOCKQUOTE",
19
+ "TABLE",
20
+ "HR",
21
+ "FIGURE",
22
+ "IMG",
23
+ "PICTURE",
24
+ "DL",
25
+ "DETAILS"
26
+ ]), M = /* @__PURE__ */ new Set(["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT", "BLOGMCP-REVIEW"]), x = 6, p = 12;
27
+ function P(t) {
28
+ const e = [], s = (r) => {
29
+ for (const c of Array.from(r.children))
30
+ if (!(c.hasAttribute(_) || c.hasAttribute(C)) && !M.has(c.tagName.toUpperCase())) {
31
+ if (E(c) || N.has(c.tagName.toUpperCase())) {
32
+ e.push(c);
33
+ continue;
34
+ }
35
+ s(c);
36
+ }
37
+ };
38
+ return s(t), e;
39
+ }
40
+ function S(t, e) {
41
+ const s = O(e.textContent ?? "").slice(0, t.length);
42
+ if (!t || !s) return !1;
43
+ const r = Math.min(t.length, s.length, p * 2);
44
+ return r < Math.min(p, t.length) ? !1 : t.slice(0, r) === s.slice(0, r);
45
+ }
46
+ function A(t, e) {
47
+ const s = E(e);
48
+ return t.kind === "component" ? s === t.type : s || t.tags.length > 0 && !t.tags.includes(e.tagName.toUpperCase()) ? !1 : t.text ? S(t.text, e) : t.tags.length > 0 && (t.type === "hr" || !(e.textContent ?? "").trim());
49
+ }
50
+ function R(t) {
51
+ return t.split("/")[0] ?? "";
52
+ }
53
+ function H(t, e) {
54
+ const s = new Map(e.units.map((n) => [n.nodeId, n])), r = /* @__PURE__ */ new Map(), c = [], T = Array.from(t.querySelectorAll(`[${d}]`));
55
+ if (T.length > 0)
56
+ for (const n of T) {
57
+ const o = R(n.getAttribute(d) ?? "");
58
+ s.has(o) && !r.has(o) && r.set(o, n);
59
+ }
60
+ else {
61
+ const n = e.units, o = P(t);
62
+ let i = 0, l = 0;
63
+ for (; i < n.length && l < o.length; ) {
64
+ const a = n[i], u = o[l];
65
+ if (A(a, u)) {
66
+ u.setAttribute(d, a.nodeId), c.push(u), r.set(a.nodeId, u), i++, l++;
67
+ continue;
68
+ }
69
+ let g = null;
70
+ for (let m = 1; m <= x && !g; m++)
71
+ for (let f = 0; f <= m; f++) {
72
+ const h = m - f;
73
+ if (i + f < n.length && l + h < o.length && A(n[i + f], o[l + h])) {
74
+ g = [f, h];
75
+ break;
76
+ }
77
+ }
78
+ g ? (i += g[0], l += g[1]) : i++;
79
+ }
80
+ }
81
+ const I = (n) => {
82
+ let o = n instanceof Element ? n : n?.parentElement ?? null;
83
+ if (o = o?.closest(`[${d}]`) ?? null, !o || !t.contains(o)) return null;
84
+ const i = R(o.getAttribute(d) ?? ""), l = s.get(i);
85
+ if (!l) return null;
86
+ const a = E(o), u = a && L.test(a) ? a : o.tagName.toLowerCase();
87
+ return { id: i, component: u, sourceRange: { ...l.sourceRange } };
88
+ };
89
+ return {
90
+ level: r.size > 0 ? 1 : 0,
91
+ matched: r.size,
92
+ total: e.units.length,
93
+ elements: r,
94
+ nodeRef: I,
95
+ restore() {
96
+ for (const n of c) n.removeAttribute(d);
97
+ c.length = 0;
98
+ }
99
+ };
100
+ }
101
+ export {
102
+ C as REVIEW_FIELD_ATTR,
103
+ _ as REVIEW_IGNORE_ATTR,
104
+ w as REVIEW_ROOT_ATTR,
105
+ H as stampReviewDom
106
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blogmcp/sdk",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Headless SDK for Knowledge Base blog — core client, Vue composables, Nuxt adapter",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -74,8 +74,8 @@
74
74
  }
75
75
  },
76
76
  "dependencies": {
77
- "@blogmcp/mdx-schema": "^0.7.0",
78
- "@blogmcp/sanitize": "^0.7.0",
77
+ "@blogmcp/mdx-schema": "^0.8.0",
78
+ "@blogmcp/sanitize": "^0.8.0",
79
79
  "marked": "^15.0.7"
80
80
  },
81
81
  "optionalDependencies": {
package/src/core/auth.ts CHANGED
@@ -27,7 +27,11 @@ export function decodeJwtUser(token: string): AuthUser | null {
27
27
  try {
28
28
  const parts = token.split('.')
29
29
  if (parts.length !== 3) return null
30
- const payload = JSON.parse(atob(parts[1]!))
30
+ // base64url without padding, UTF-8 inside (RFC 7519): a bare atob threw on
31
+ // "-"/"_" and read non-ASCII names as Latin-1.
32
+ const b64 = parts[1]!.replace(/-/g, '+').replace(/_/g, '/')
33
+ const binary = atob(b64.padEnd(Math.ceil(b64.length / 4) * 4, '='))
34
+ const payload = JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0))))
31
35
  return {
32
36
  id: payload.sub || payload.userId || '',
33
37
  email: payload.email || '',
@@ -0,0 +1,275 @@
1
+ /**
2
+ * The page API client (`/api/review/v1`, docs: "Add review to your frontend").
3
+ *
4
+ * Two entry points:
5
+ * - `getReviewSession(token, …)` for the site's SERVER, which renders the review page: one call,
6
+ * and an outcome the route turns into the page or a status page (`renderReviewStatusHtml`).
7
+ * - `createReviewClient(…)` for the page itself (the review layer): state poll, media library,
8
+ * Send.
9
+ *
10
+ * The token travels only in the `X-Review-Token` header, never in a URL. Nothing here throws: every
11
+ * call answers `{ ok: true, … }` or `{ ok: false, reason, status, … }`.
12
+ */
13
+
14
+ import { isReviewTokenFormat } from './types'
15
+ import type { ReviewMediaItem, ReviewSession, ReviewState, ReviewSubmissionV1 } from './types'
16
+
17
+ /** Why a call failed, in the terms a page shows. */
18
+ export type ReviewFailureReason =
19
+ /** Unknown, malformed or someone else's token (kb-api never says which). */
20
+ | 'not_found'
21
+ | 'expired'
22
+ | 'revoked'
23
+ /** A newer link for the same article replaced this one. */
24
+ | 'superseded'
25
+ /** Review links are switched off on this KB. */
26
+ | 'unavailable'
27
+ | 'rate_limited'
28
+ /** All 20 rounds of this link were sent. */
29
+ | 'submission_limit'
30
+ /** The submission did not validate (`details` says where). */
31
+ | 'invalid'
32
+ | 'too_large'
33
+ /** A picked media item is outside what this link may use (`details.slugs`). */
34
+ | 'media_not_available'
35
+ /** kb-api could not be reached, or the request timed out. */
36
+ | 'network'
37
+ | 'error'
38
+
39
+ export interface ReviewFailure {
40
+ ok: false
41
+ reason: ReviewFailureReason
42
+ /** HTTP status; 0 when the request never got an answer. */
43
+ status: number
44
+ /** kb-api's error code, when it sent one. */
45
+ code?: string
46
+ details?: unknown
47
+ /** Seconds to wait before retrying (429). */
48
+ retryAfter?: number
49
+ }
50
+
51
+ export type ReviewResult<T> = ({ ok: true } & T) | ReviewFailure
52
+
53
+ /** The statuses a review page itself answers with for each reason. */
54
+ export const REVIEW_REASON_STATUS: Readonly<Record<ReviewFailureReason, number>> = Object.freeze({
55
+ not_found: 404,
56
+ expired: 410,
57
+ revoked: 410,
58
+ superseded: 410,
59
+ unavailable: 503,
60
+ rate_limited: 429,
61
+ submission_limit: 409,
62
+ invalid: 400,
63
+ too_large: 413,
64
+ media_not_available: 422,
65
+ network: 502,
66
+ error: 500,
67
+ })
68
+
69
+ const CODE_REASON: Readonly<Record<string, ReviewFailureReason>> = {
70
+ REVIEW_TOKEN_MISSING: 'not_found',
71
+ REVIEW_NOT_FOUND: 'not_found',
72
+ REVIEW_EXPIRED: 'expired',
73
+ REVIEW_REVOKED: 'revoked',
74
+ REVIEW_SUPERSEDED: 'superseded',
75
+ REVIEW_UNAVAILABLE: 'unavailable',
76
+ RATE_LIMITED: 'rate_limited',
77
+ REVIEW_SUBMISSION_LIMIT: 'submission_limit',
78
+ VALIDATION_FAILED: 'invalid',
79
+ PAYLOAD_TOO_LARGE: 'too_large',
80
+ MEDIA_NOT_AVAILABLE: 'media_not_available',
81
+ }
82
+
83
+ /**
84
+ * Without a kb-api `code` the answer came from something in front of kb-api (a proxy during a pod
85
+ * roll, the edge). It never closes a link: a 5xx is treated like a lost connection (the round may or
86
+ * may not have been stored, so it is retried with the same key), anything else is a plain error.
87
+ */
88
+ const STATUS_REASON: Readonly<Record<number, ReviewFailureReason>> = {
89
+ 400: 'invalid',
90
+ 413: 'too_large',
91
+ 429: 'rate_limited',
92
+ }
93
+
94
+ const DEFAULT_TIMEOUT_MS = 15_000
95
+ /** What the review router accepts as a forwarded reviewer address (kb-api checks it again). */
96
+ const CLIENT_IP_RE = /^[0-9A-Fa-f:.]{2,45}$/
97
+
98
+ type FetchLike = (input: string, init?: RequestInit) => Promise<Response>
99
+
100
+ export interface ReviewTransportOptions {
101
+ /** The KB's public origin, e.g. `https://acme.blogmcp.ai` (the API lives under `/api/review/v1`). */
102
+ kbUrl: string
103
+ /** Override the API base entirely (in-cluster: `http://kb-api:5070/review/v1`). */
104
+ apiBase?: string
105
+ fetch?: FetchLike
106
+ /** Per-request timeout; default 15 s. */
107
+ timeoutMs?: number
108
+ }
109
+
110
+ function apiBaseOf(o: ReviewTransportOptions): string {
111
+ return (o.apiBase ?? `${o.kbUrl.replace(/\/+$/, '')}/api/review/v1`).replace(/\/+$/, '')
112
+ }
113
+
114
+ function retryAfterOf(res: Response): number | undefined {
115
+ const raw = res.headers.get('Retry-After')
116
+ if (!raw) return undefined
117
+ const n = Number(raw)
118
+ return Number.isFinite(n) && n >= 0 ? n : undefined
119
+ }
120
+
121
+ async function failureOf(res: Response): Promise<ReviewFailure> {
122
+ let body: { code?: unknown; details?: unknown } = {}
123
+ try {
124
+ body = (await res.json()) as typeof body
125
+ } catch {
126
+ // a proxy's HTML error page, or no body
127
+ }
128
+ const code = typeof body.code === 'string' ? body.code : undefined
129
+ const reason = (code && CODE_REASON[code]) || STATUS_REASON[res.status] || (res.status >= 500 ? 'network' : 'error')
130
+ return {
131
+ ok: false,
132
+ reason,
133
+ status: res.status,
134
+ ...(code ? { code } : {}),
135
+ ...(body.details !== undefined ? { details: body.details } : {}),
136
+ ...(res.status === 429 ? { retryAfter: retryAfterOf(res) } : {}),
137
+ }
138
+ }
139
+
140
+ async function call<T>(
141
+ o: ReviewTransportOptions,
142
+ path: string,
143
+ init: RequestInit,
144
+ ): Promise<ReviewResult<{ data: T; status: number }>> {
145
+ const doFetch: FetchLike = o.fetch ?? ((input, i) => fetch(input, i))
146
+ const controller = typeof AbortController === 'function' ? new AbortController() : null
147
+ const timer = controller ? setTimeout(() => controller.abort(), o.timeoutMs ?? DEFAULT_TIMEOUT_MS) : null
148
+ try {
149
+ const res = await doFetch(`${apiBaseOf(o)}${path}`, {
150
+ ...init,
151
+ // The page API ignores cookies; never send the site's.
152
+ credentials: 'omit',
153
+ cache: 'no-store',
154
+ ...(controller ? { signal: controller.signal } : {}),
155
+ })
156
+ if (!res.ok) return failureOf(res)
157
+ return { ok: true, data: (await res.json()) as T, status: res.status }
158
+ } catch {
159
+ return { ok: false, reason: 'network', status: 0 }
160
+ } finally {
161
+ if (timer) clearTimeout(timer)
162
+ }
163
+ }
164
+
165
+ export interface GetReviewSessionOptions extends ReviewTransportOptions {
166
+ /**
167
+ * The reviewer's IP, as the site's server saw it. kb-api rate-limits and fingerprints per reviewer
168
+ * only when it is forwarded WITH a `credential` it trusts to forward (a service key, a delegated
169
+ * session or an internal token); otherwise every reviewer of the site shares the server's address,
170
+ * and one visitor trying dead links could lock the review page for everyone.
171
+ */
172
+ clientIp?: string | null
173
+ /** Bearer credential that may forward `clientIp` (never sent without it). */
174
+ credential?: string | null
175
+ /** Extra request headers (e.g. the edge's `CF-Connecting-IP` for an in-cluster call). */
176
+ headers?: Record<string, string>
177
+ }
178
+
179
+ /**
180
+ * Load a review link's session, working copy and referenced media, for rendering the review page.
181
+ * Counts as a view of the link. A token of the wrong shape answers `not_found` without a request
182
+ * (kb-api would say the same, and count it against the site's enumeration brake).
183
+ */
184
+ export async function getReviewSession(
185
+ token: string,
186
+ opts: GetReviewSessionOptions,
187
+ ): Promise<ReviewResult<{ session: ReviewSession }>> {
188
+ if (!isReviewTokenFormat(token)) return { ok: false, reason: 'not_found', status: 404 }
189
+ const headers: Record<string, string> = { Accept: 'application/json', ...opts.headers, 'X-Review-Token': token }
190
+ const ip = opts.clientIp?.trim()
191
+ if (ip && opts.credential && CLIENT_IP_RE.test(ip)) {
192
+ headers.Authorization = `Bearer ${opts.credential}`
193
+ headers['X-Blogmcp-Client-Ip'] = ip
194
+ }
195
+ const r = await call<ReviewSession>(opts, '/session', { method: 'GET', headers })
196
+ return r.ok ? { ok: true, session: r.data } : r
197
+ }
198
+
199
+ export interface ReviewMediaQuery {
200
+ q?: string
201
+ type?: 'image' | 'video' | 'audio'
202
+ /** Tag slugs (at most 10). */
203
+ tags?: string[]
204
+ /** 1..50, default 30. */
205
+ limit?: number
206
+ offset?: number
207
+ /** Language of titles/alt texts; default the link's language. */
208
+ lang?: string
209
+ }
210
+
211
+ export interface ReviewSubmitAnswer {
212
+ submissionId: string
213
+ seq: number
214
+ submittedAt: string
215
+ /** True when kb-api had already stored this request (same `Idempotency-Key`). */
216
+ replayed: boolean
217
+ }
218
+
219
+ export interface ReviewClient {
220
+ session(): Promise<ReviewResult<{ session: ReviewSession }>>
221
+ /** Cheap poll: did the working copy change, did the agent take the last round? */
222
+ state(): Promise<ReviewResult<{ state: ReviewState }>>
223
+ /** The library at the link's scope. Do not call with `mediaScope: 'none'` (a 404 that counts as a miss). */
224
+ media(query?: ReviewMediaQuery): Promise<ReviewResult<{ items: ReviewMediaItem[] }>>
225
+ mediaTags(): Promise<ReviewResult<{ tags: Array<{ id: string; slug: string; name: string; color: string | null }> }>>
226
+ /**
227
+ * Send one round. `idempotencyKey` (a UUID) must stay the same across retries of the SAME round,
228
+ * so a retry after a lost answer is stored once.
229
+ */
230
+ submit(payload: ReviewSubmissionV1, idempotencyKey: string): Promise<ReviewResult<ReviewSubmitAnswer>>
231
+ }
232
+
233
+ export interface ReviewClientOptions extends ReviewTransportOptions {
234
+ token: string
235
+ }
236
+
237
+ export function createReviewClient(opts: ReviewClientOptions): ReviewClient {
238
+ const headers = (): Record<string, string> => ({ Accept: 'application/json', 'X-Review-Token': opts.token })
239
+ const get = <T>(path: string) => call<T>(opts, path, { method: 'GET', headers: headers() })
240
+
241
+ return {
242
+ async session() {
243
+ const r = await get<ReviewSession>('/session')
244
+ return r.ok ? { ok: true, session: r.data } : r
245
+ },
246
+ async state() {
247
+ const r = await get<ReviewState>('/state')
248
+ return r.ok ? { ok: true, state: r.data } : r
249
+ },
250
+ async media(query = {}) {
251
+ const p = new URLSearchParams()
252
+ if (query.q) p.set('q', query.q.slice(0, 200))
253
+ if (query.type) p.set('type', query.type)
254
+ if (query.tags?.length) p.set('tags', query.tags.slice(0, 10).join(','))
255
+ if (query.limit != null) p.set('limit', String(query.limit))
256
+ if (query.offset != null) p.set('offset', String(query.offset))
257
+ if (query.lang) p.set('lang', query.lang)
258
+ const qs = p.toString()
259
+ const r = await get<{ items: ReviewMediaItem[] }>(`/media${qs ? `?${qs}` : ''}`)
260
+ return r.ok ? { ok: true, items: r.data.items } : r
261
+ },
262
+ async mediaTags() {
263
+ const r = await get<{ tags: Array<{ id: string; slug: string; name: string; color: string | null }> }>('/media/tags')
264
+ return r.ok ? { ok: true, tags: r.data.tags } : r
265
+ },
266
+ async submit(payload, idempotencyKey) {
267
+ const r = await call<{ submissionId: string; seq: number; submittedAt: string }>(opts, '/submit', {
268
+ method: 'POST',
269
+ headers: { ...headers(), 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey },
270
+ body: JSON.stringify(payload),
271
+ })
272
+ return r.ok ? { ok: true, ...r.data, replayed: r.status === 200 } : r
273
+ },
274
+ }
275
+ }