@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,149 @@
1
+ const l = {
2
+ /** The magic-link landing page; the token travels in the fragment (`#t=`), never in the path or query. */
3
+ open: "/consultation/open",
4
+ /** The thread an anonymous reader's session cookie opens (no id in the URL, ever). */
5
+ session: "/consultation",
6
+ /** Ask for a fresh link by e-mail address. */
7
+ newLink: "/consultation/new-link",
8
+ /** A signed-in reader's list ("My consultations"). */
9
+ account: "/my-consultations",
10
+ /** A signed-in reader asks a new question (KB channel `web`). */
11
+ accountNew: "/my-consultations/new",
12
+ /** One of the signed-in reader's threads; build it with `accountThreadPath(id)`. */
13
+ accountThread: "/my-consultations/:id",
14
+ /** The anonymous contact form (KB channel `contact_form`). */
15
+ contact: "/contact"
16
+ }, O = {
17
+ /** Exchange the link token for the session cookie (`intent=exchange&token=…`). */
18
+ access: "/api/consultations/access",
19
+ /** Move the session's thread to the signed-in reader's account. */
20
+ attach: "/api/consultations/attach",
21
+ /** Drop the session cookie. */
22
+ forget: "/api/consultations/forget"
23
+ }, N = "/consultation/open#t={token}", h = "/my-consultations/{id}", u = /^[A-Za-z0-9_-]{43}$/, p = /^[A-Za-z0-9._:-]{1,64}$/, L = /^[A-Za-z0-9._-]{1,40}$/, f = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, R = /^[a-z]{2}(-[A-Za-z0-9]{2,8})?$/, d = 5e3, S = 2e3, m = 2e3, b = 100, _ = 254, C = "consultation_contact", E = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
24
+ function U(e) {
25
+ return typeof e == "string" && e.length <= _ && E.test(e);
26
+ }
27
+ const k = {
28
+ body: "body",
29
+ clientRequestId: "clientRequestId",
30
+ legalMode: "legalMode",
31
+ legalVersion: "legalVersion",
32
+ legalLocale: "legalLocale",
33
+ consent: "consent"
34
+ }, D = {
35
+ intent: "intent",
36
+ body: "body",
37
+ clientRequestId: "clientRequestId",
38
+ token: "token"
39
+ }, M = {
40
+ exchange: "exchange",
41
+ reply: "reply",
42
+ erase: "erase",
43
+ logout: "logout"
44
+ }, w = {
45
+ email: "email",
46
+ honeypot: "website"
47
+ }, $ = {
48
+ name: "name",
49
+ email: "email",
50
+ message: "message",
51
+ messageId: "messageId",
52
+ legalMode: "legalMode",
53
+ legalVersion: "legalVersion",
54
+ legalLocale: "legalLocale",
55
+ consent: "consent",
56
+ honeypot: "website",
57
+ turnstile: "cf-turnstile-response"
58
+ };
59
+ function x(e) {
60
+ return typeof e == "string" && f.test(e) ? l.accountThread.replace(":id", e.toLowerCase()) : l.account;
61
+ }
62
+ function P(e, t) {
63
+ if (typeof e != "string") return { ok: !1, code: "invalid", body: "" };
64
+ const n = e.replace(/\r\n?/g, `
65
+ `), o = n.slice(0, 2 * Math.max(t, d)), s = n.trim();
66
+ return s === "" || s.includes("\0") ? { ok: !1, code: "invalid", body: o } : s.length > t ? { ok: !1, code: "tooLong", body: o } : { ok: !0, body: s };
67
+ }
68
+ function z() {
69
+ const e = globalThis.crypto;
70
+ if (typeof e?.randomUUID == "function") return e.randomUUID();
71
+ const t = e.getRandomValues(new Uint8Array(16));
72
+ t[6] = (t[6] ?? 0) & 15 | 64, t[8] = (t[8] ?? 0) & 63 | 128;
73
+ const n = Array.from(t, (o) => o.toString(16).padStart(2, "0")).join("");
74
+ return `${n.slice(0, 8)}-${n.slice(8, 12)}-${n.slice(12, 16)}-${n.slice(16, 20)}-${n.slice(20)}`;
75
+ }
76
+ function T(e) {
77
+ const n = /^#t=([^&]*)/.exec(typeof e == "string" ? e : "")?.[1] ?? "";
78
+ return u.test(n) ? n : null;
79
+ }
80
+ const i = /* @__PURE__ */ new WeakMap();
81
+ function g() {
82
+ if (typeof window > "u")
83
+ throw new Error(
84
+ "[blogmcp-sdk] readLinkToken reads the address bar — call it in the browser (onMounted / useEffect), never while rendering on the server"
85
+ );
86
+ return window;
87
+ }
88
+ function A(e) {
89
+ if (typeof e != "object" || e === null || Array.isArray(e)) return !1;
90
+ const t = Object.getPrototypeOf(e);
91
+ return t === Object.prototype || t === null;
92
+ }
93
+ function y(e, t, n) {
94
+ let o = e;
95
+ const s = t ? o.indexOf(t) : -1;
96
+ if (s >= 0 && (o = o.slice(0, s)), n !== null)
97
+ for (let c = o.indexOf(n); c >= 0; c = o.indexOf(n)) {
98
+ const a = o.lastIndexOf("#", c);
99
+ o = a >= 0 ? o.slice(0, a) : o.slice(0, c) + o.slice(c + n.length);
100
+ }
101
+ return o;
102
+ }
103
+ function I(e, t, n) {
104
+ if (!A(e)) return e;
105
+ let o = !1;
106
+ const s = { ...e };
107
+ for (const [c, a] of Object.entries(s)) {
108
+ if (typeof a != "string") continue;
109
+ const r = y(a, t, n);
110
+ r !== a && (s[c] = r, o = !0);
111
+ }
112
+ return o ? s : e;
113
+ }
114
+ function F(e = g()) {
115
+ const t = e.location.hash, n = T(t), o = !i.has(e);
116
+ return t && (o || t.startsWith("#t=")) && e.history.replaceState(
117
+ I(e.history.state, t, n),
118
+ "",
119
+ e.location.pathname + e.location.search
120
+ ), (o || n !== null) && i.set(e, n), i.get(e) ?? null;
121
+ }
122
+ export {
123
+ p as CLIENT_REQUEST_ID_RE,
124
+ O as CONSULTATION_API_PATHS,
125
+ f as CONSULTATION_ID_RE,
126
+ M as CONSULTATION_INTENTS,
127
+ N as CONSULTATION_KB_READER_LINK_PATH,
128
+ h as CONSULTATION_KB_READER_THREAD_PATH,
129
+ l as CONSULTATION_ROUTES,
130
+ u as CONSULTATION_SECRET_RE,
131
+ C as CONSULTATION_TURNSTILE_ACTION,
132
+ $ as CONTACT_FIELDS,
133
+ m as CONTACT_MESSAGE_MAX,
134
+ b as CONTACT_NAME_MAX,
135
+ L as LEGAL_VERSION_RE,
136
+ R as LOCALE_RE,
137
+ w as NEW_LINK_FIELDS,
138
+ S as NEW_QUESTION_BODY_MAX,
139
+ k as NEW_QUESTION_FIELDS,
140
+ d as READER_BODY_MAX,
141
+ _ as READER_EMAIL_MAX,
142
+ D as SESSION_FIELDS,
143
+ x as accountThreadPath,
144
+ U as isReaderEmail,
145
+ z as newClientRequestId,
146
+ P as normalizeBody,
147
+ F as readLinkToken,
148
+ T as tokenFromHash
149
+ };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The reader's IP, forwarded to the KB as `X-Blogmcp-Client-Ip`.
3
+ *
4
+ * kb-api believes that header from the blog's credentialed calls (the
5
+ * reader-proxy service key, the reader's own JWT, the adapter key), so the
6
+ * value IS the bucket its per-IP quotas count in. On the anonymous paths —
7
+ * link exchange 30/h, link requests 10/h, session posts 60/h, contact ingest —
8
+ * that cap is the only per-requester limit. It is used to bucket quotas and
9
+ * never for access decisions.
10
+ *
11
+ * Order (reader-consultations F5 §3.4):
12
+ * 1. The adapter's own `clientIp()` (e.g. h3's `getRequestIP`), or the
13
+ * configured edge header (default `cf-connecting-ip`; Cloudflare OVERWRITES
14
+ * it on every proxied request) — when it holds exactly one valid IP.
15
+ * 2. Otherwise the RIGHTMOST `X-Forwarded-For` hop: the one the proxy directly
16
+ * in front of us appended from its own peer address.
17
+ * 3. Otherwise null (the header is then not sent at all).
18
+ *
19
+ * ⚠️ Never the LEFTMOST hop: it is whatever the client sent (Cloudflare and
20
+ * most reverse proxies APPEND to a client-supplied `X-Forwarded-For`). Reading
21
+ * it let `curl -H "X-Forwarded-For: 10.0.$i.1"` in a loop get a fresh KB bucket
22
+ * per request, and fill somebody else's bucket on purpose. An unparseable
23
+ * rightmost hop is null, never "the next one to the left". `X-Real-IP` is
24
+ * never read: depending on the proxy it can echo a header the client sent.
25
+ *
26
+ * Validation is pure JS (no `node:net`, so the entry runs on any runtime) and
27
+ * never looser than kb-api's `net.isIP`: whatever this accepts, kb-api accepts
28
+ * (a parity test holds that). IPv4 is a strict dotted quad; IPv6 goes through
29
+ * the WHATWG URL parser; zone ids (`fe80::1%eth0`) and lists are rejected.
30
+ */
31
+ import type { ConsultationHttp } from './http.js';
32
+ /** The edge header read when the server config names none. */
33
+ export declare const DEFAULT_CLIENT_IP_HEADER = "cf-connecting-ip";
34
+ /** The header kb-api reads the forwarded reader IP from. */
35
+ export declare const KB_CLIENT_IP_HEADER = "X-Blogmcp-Client-Ip";
36
+ /** True for one IPv4 or IPv6 address, as kb-api's `net.isIP` would accept it (no zone id, no list). */
37
+ export declare function isIpAddress(value: string): boolean;
38
+ /** One valid IP from a raw value (trimmed), else null. */
39
+ export declare function singleIp(value: unknown): string | null;
40
+ /** True for a usable header name ('' means "no edge header"). */
41
+ export declare function isHeaderName(name: string): boolean;
42
+ /**
43
+ * The reader's IP for the KB's per-IP quotas, or null when nothing
44
+ * trustworthy is available. `header` names the edge header (default
45
+ * `cf-connecting-ip`; `''` = none, for deployments not fronted by Cloudflare,
46
+ * where every client writes that header itself).
47
+ */
48
+ export declare function clientIpFrom(http: Pick<ConsultationHttp, 'header' | 'clientIp'>, o?: {
49
+ header?: string;
50
+ }): string | null;
@@ -0,0 +1,44 @@
1
+ const u = "cf-connecting-ip", _ = "X-Blogmcp-Client-Ip", s = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)", d = new RegExp(`^${s}(?:\\.${s}){3}$`), l = /^[0-9A-Fa-f:.]{2,45}$/, E = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
2
+ function a(n) {
3
+ if (d.test(n)) return !0;
4
+ if (!n.includes(":") || !l.test(n)) return !1;
5
+ try {
6
+ return new URL(`http://[${n}]/`), !0;
7
+ } catch {
8
+ return !1;
9
+ }
10
+ }
11
+ function c(n) {
12
+ if (typeof n != "string") return null;
13
+ const t = n.trim();
14
+ return t !== "" && a(t) ? t : null;
15
+ }
16
+ function I(n) {
17
+ return E.test(n);
18
+ }
19
+ function p(n, t = {}) {
20
+ const o = typeof n.clientIp == "function" ? c(i(() => n.clientIp())) : null;
21
+ if (o) return o;
22
+ const r = (t.header ?? u).trim();
23
+ if (r !== "" && I(r)) {
24
+ const f = c(i(() => n.header(r)));
25
+ if (f) return f;
26
+ }
27
+ const e = i(() => n.header("x-forwarded-for"));
28
+ return typeof e != "string" || e.trim() === "" ? null : c(e.split(",").at(-1));
29
+ }
30
+ function i(n) {
31
+ try {
32
+ return n();
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+ export {
38
+ u as DEFAULT_CLIENT_IP_HEADER,
39
+ _ as KB_CLIENT_IP_HEADER,
40
+ p as clientIpFrom,
41
+ I as isHeaderName,
42
+ a as isIpAddress,
43
+ c as singleIp
44
+ };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The anonymous contact form (`/contact`, KB channel `contact_form`): the
3
+ * reader's question becomes a thread in the KB through the blog's scoped
4
+ * adapter key (`consultations:ingest:contact_form`, no ref prefix). The reader
5
+ * gets the answer by e-mail with a magic link — so the form exists only while
6
+ * the KB sends e-mail notices (`emailNotices`) and the channel has a usable
7
+ * legal text in the page's language.
8
+ *
9
+ * Order: 1. method, 2. the gate, 3. Origin, 4. the form — honeypot (a filled
10
+ * one gets the ordinary answer and nothing is sent), Turnstile, the fields, the
11
+ * legal text the form showed (a consent box must be ticked, and in consent
12
+ * mode the text must still be the current one), 5. the ingest.
13
+ *
14
+ * Idempotency: the page renders a `messageId` (`blog-contact:<uuid>`) and
15
+ * posts it back. It is the ingest's `externalMessageId`, so a retry after a
16
+ * lost answer lands as a duplicate instead of a second thread: every failure
17
+ * hands back the SAME id, except `conflict` (the first attempt went through
18
+ * with other content), which hands back a new one.
19
+ */
20
+ import { type ContactPageState, type ContactResult, type ServerContext } from './context.js';
21
+ import type { ConsultationHttp, ConsultationResponse } from './http.js';
22
+ export declare function loadContact(ctx: ServerContext, http: ConsultationHttp, locale: string): Promise<ConsultationResponse<ContactPageState>>;
23
+ export declare function handleContact(ctx: ServerContext, http: ConsultationHttp, locale: string): Promise<ConsultationResponse<ContactResult>>;
@@ -0,0 +1,138 @@
1
+ import { isConsultationAdapterError as P } from "../../core/consultation-adapter.js";
2
+ import { CONTACT_FIELDS as u, CONTACT_NAME_MAX as V, normalizeBody as Y, LEGAL_VERSION_RE as Q, LOCALE_RE as X } from "../routes.js";
3
+ import { consultationOutcomeOf as $ } from "../outcome.js";
4
+ import { channelTextFrom as z } from "../channel-text.js";
5
+ import { isPost as B, respond as b, gate as L, readForm as H, fieldOf as c, readerIp as W, logFailure as d, CONTACT_FORM_CHANNEL as F, isGet as q, withRetry as K, statusOf as G, GATE_RETRY_AFTER_S as T, freshKey as Z, GET_ONLY as j, POST_ONLY as J } from "./context.js";
6
+ import { isAllowedOrigin as x } from "./origin.js";
7
+ import { isEmailAddress as ee } from "./session.js";
8
+ import { verifyTurnstile as te } from "./turnstile.js";
9
+ const ne = "blog-contact:", re = /^blog-contact:[A-Za-z0-9._:-]{1,64}$/, oe = /* @__PURE__ */ new Set([
10
+ "NOTICE_REQUIRED",
11
+ "NOTICE_VERSION_UNKNOWN",
12
+ "CONSENT_REQUIRED",
13
+ "CONSENT_VERSION_UNKNOWN"
14
+ ]);
15
+ function _(e) {
16
+ return `${ne}${Z(e)}`;
17
+ }
18
+ function M(e, o) {
19
+ return e.mode === o.mode && e.version === o.version && e.locale === o.locale;
20
+ }
21
+ async function D(e, o) {
22
+ const l = await e.publicConfig.get(o, { fresh: !0 });
23
+ if (!l.ok) return { ok: !1, code: "unavailable", retryAfterS: l.retryAfterS ?? T };
24
+ const a = z(l.value, F, o);
25
+ return a.enabled ? { ok: !0, text: a } : { ok: !1, code: "disabled" };
26
+ }
27
+ async function me(e, o, l) {
28
+ const a = (m, r, y) => b(G(m), K({ state: "error", error: m }, r), {
29
+ retryAfterS: r,
30
+ allow: y
31
+ });
32
+ if (!q(o)) return a("method", void 0, j);
33
+ const t = await L(e, "contactForm", l);
34
+ if (!t.ok) return a(t.code, t.retryAfterS);
35
+ const E = t.status.contactText;
36
+ return E.enabled ? b(200, {
37
+ state: "open",
38
+ text: E,
39
+ messageId: _(e),
40
+ turnstileSiteKey: e.turnstile?.siteKey ?? null,
41
+ maxMessage: e.contactMessageMax
42
+ }) : a("disabled");
43
+ }
44
+ async function ge(e, o, l) {
45
+ let a = null;
46
+ const t = (n, s = {}) => b(
47
+ G(n),
48
+ K(
49
+ {
50
+ done: !1,
51
+ error: n,
52
+ messageId: s.messageId ?? a ?? _(e),
53
+ ...s.text ? { textChanged: !0, text: s.text } : {}
54
+ },
55
+ s.retryAfterS
56
+ ),
57
+ { retryAfterS: s.retryAfterS, allow: s.allow }
58
+ ), E = () => b(200, { done: "stored" });
59
+ if (!B(o)) return t("method", { allow: J });
60
+ const m = await L(e, "contactForm", l);
61
+ if (!m.ok) return t(m.code, { retryAfterS: m.retryAfterS });
62
+ if (!x(o, e.origins)) return t("origin");
63
+ const r = await H(o);
64
+ if (!r) return t("invalid");
65
+ const y = c(r, u.messageId);
66
+ typeof y == "string" && re.test(y) && (a = y);
67
+ const w = c(r, u.honeypot);
68
+ if (typeof w == "string" && w !== "") return E();
69
+ const p = W(e, o);
70
+ if (e.turnstile) {
71
+ const n = await te(c(r, u.turnstile), {
72
+ secret: e.turnstile.secretKey,
73
+ remoteIp: p,
74
+ expectedAction: e.turnstile.action,
75
+ fetch: e.fetch()
76
+ });
77
+ if (!n.ok) return t("captcha");
78
+ if (n.status === "unavailable" && (d(e, "turnstile", { code: "unavailable", kbCode: null, status: null }), !e.turnstile.failOpen))
79
+ return t("unavailable", { retryAfterS: T });
80
+ }
81
+ if (a === null) return t("invalid");
82
+ const C = (c(r, u.name) ?? "").trim();
83
+ if (C.length > V) return t("invalid");
84
+ const R = (c(r, u.email) ?? "").trim();
85
+ if (!ee(R)) return t("invalid");
86
+ const v = Y(c(r, u.message), e.contactMessageMax);
87
+ if (!v.ok) return t(v.code);
88
+ const A = c(r, u.legalMode), I = c(r, u.legalVersion), S = c(r, u.legalLocale);
89
+ if (A !== "notice" && A !== "consent" || typeof I != "string" || !Q.test(I) || typeof S != "string" || !X.test(S))
90
+ return t("invalid");
91
+ const h = { mode: A, version: I, locale: S };
92
+ if (A === "consent") {
93
+ if (c(r, u.consent) !== "on") return t("consent");
94
+ const n = await D(e, l);
95
+ if (!n.ok) return t(n.code, { retryAfterS: n.retryAfterS });
96
+ if (!M(n.text, h)) return t("consent", { text: n.text });
97
+ }
98
+ const N = e.transport && e.adapterKey ? e.transport.adapter(e.adapterKey) : null;
99
+ if (!N)
100
+ return d(e, "contactIngest", { code: "unavailable", kbCode: null, status: null }), t("unavailable", { retryAfterS: T });
101
+ const k = { version: I, locale: S }, U = {
102
+ channel: F,
103
+ externalMessageId: a,
104
+ body: v.body,
105
+ languageCode: l,
106
+ newThread: {
107
+ owner: { email: R },
108
+ ...C !== "" ? { displayName: C } : {},
109
+ externalThreadRef: a,
110
+ ...A === "consent" ? { consent: { ...k, givenAt: new Date(e.now()).toISOString() } } : { notice: k }
111
+ }
112
+ };
113
+ try {
114
+ return await N.client.ingest(U, p ? { clientIp: p } : void 0), E();
115
+ } catch (n) {
116
+ const s = N.retryAfterS() ?? void 0;
117
+ if (!P(n))
118
+ return d(e, "contactIngest", { code: "unavailable", kbCode: null, status: null }), t("unavailable", { retryAfterS: s });
119
+ const i = n.code, g = n.status === 0 ? null : n.status;
120
+ if (i === "QUOTA_EXCEEDED") return t("quota", { retryAfterS: s });
121
+ if (g === 401 || g === 403 || i === "UNAUTHENTICATED" || i === "FORBIDDEN")
122
+ return d(e, "contactIngest", { code: "unavailable", kbCode: i, status: g }), t("unavailable", { retryAfterS: s });
123
+ if (i === "IDEMPOTENCY_CONFLICT") return t("conflict", { messageId: _(e) });
124
+ if (i !== null && oe.has(i)) {
125
+ const f = await D(e, l);
126
+ return f.ok ? M(f.text, h) ? (d(e, "contactIngest", { code: "submit", kbCode: i, status: g }), t("submit")) : t("consent", { text: f.text }) : t(f.code, { retryAfterS: f.retryAfterS });
127
+ }
128
+ if (i !== null) {
129
+ const f = $(i), O = f === "auth" ? "unavailable" : f;
130
+ return d(e, "contactIngest", { code: O, kbCode: i, status: g }), t(O, { retryAfterS: O === "unavailable" ? s : void 0 });
131
+ }
132
+ return d(e, "contactIngest", { code: "unavailable", kbCode: null, status: g }), t("unavailable", { retryAfterS: s });
133
+ }
134
+ }
135
+ export {
136
+ ge as handleContact,
137
+ me as loadContact
138
+ };
@@ -0,0 +1,246 @@
1
+ /**
2
+ * What every consultation handler shares: the resolved configuration, the
3
+ * gate, the response builders and the log hygiene. Internal to the server
4
+ * entry — the public surface is `createConsultationServer`.
5
+ */
6
+ import type { KbClient } from '../../core/client.js';
7
+ import type { ReaderConsultation } from '../../core/types.js';
8
+ import { ConsultationTransportError, type ChannelText, type ConsultationLogger, type ConsultationSiteStatus, type ConsultationUiCode, type PublicConfigCache, type ShownLegalText } from '../index.js';
9
+ import type { ConsultationHttp, ConsultationResponse } from './http.js';
10
+ import type { KbTransport } from './transport.js';
11
+ /** A page the gate decides on (`ConsultationSiteStatus.features`; `links` is for menus and footers, never a gate). */
12
+ export type ConsultationFeature = Exclude<keyof ConsultationSiteStatus['features'], 'links'>;
13
+ /** What a page loader answers when it only needs the gate: 200, 404 (dark) or 503 (the KB could not be asked). */
14
+ export interface ConsultationPageGate {
15
+ status: 200 | 404 | 503;
16
+ headers: Record<string, string>;
17
+ }
18
+ /** `loadSession` — the `/consultation` page. */
19
+ export type SessionPageState =
20
+ /** The thread the session opens; `clientRequestId` goes into the reply form as a hidden field. */
21
+ {
22
+ state: 'open';
23
+ consultation: ReaderConsultation;
24
+ clientRequestId: string;
25
+ }
26
+ /** No session cookie: "open the link from your e-mail". No KB call was made. */
27
+ | {
28
+ state: 'none';
29
+ }
30
+ /** The KB no longer knows the session (the cookie was cleared): offer a new link. */
31
+ | {
32
+ state: 'expired';
33
+ } | {
34
+ state: 'error';
35
+ error: ConsultationUiCode;
36
+ retryAfterS?: number;
37
+ };
38
+ /** `handleAccess` — `POST /api/consultations/access`. The session travels only in `Set-Cookie`. */
39
+ export type AccessResult = {
40
+ success: true;
41
+ } | {
42
+ success: false;
43
+ error: ConsultationUiCode;
44
+ retryAfterS?: number;
45
+ };
46
+ /** `handleSessionAction` — `POST /consultation` (`intent` = `reply` | `erase` | `logout`). */
47
+ export type SessionActionResult = {
48
+ success: true;
49
+ done: 'posted' | 'erased' | 'loggedOut';
50
+ } | {
51
+ success: false;
52
+ error: ConsultationUiCode;
53
+ retryAfterS?: number;
54
+ /** A failed `reply`: the reader's own text back, for the form (line breaks normalised). */
55
+ body?: string;
56
+ /** A failed `reply`: the key to post with the retry — the same one, or a NEW one after `conflict`. */
57
+ clientRequestId?: string;
58
+ };
59
+ /**
60
+ * `handleForget` — `POST /api/consultations/forget`: drop a session cookie the
61
+ * KB no longer accepts (a Next Server Component can render "expired" but cannot
62
+ * clear the cookie). `null` body: 204 when there was no session, 200 when the
63
+ * session is still valid (the cookie is left alone — a fresh session opened in
64
+ * another tab is never closed from here). 410 after clearing an expired one.
65
+ * Never any thread data.
66
+ */
67
+ export type ForgetResult = null | {
68
+ success: false;
69
+ error: ConsultationUiCode;
70
+ retryAfterS?: number;
71
+ };
72
+ /** `handleAttach` — `POST /api/consultations/attach`. */
73
+ export type AttachResult = {
74
+ success: true;
75
+ done: 'attached';
76
+ } | {
77
+ success: false;
78
+ error: ConsultationUiCode;
79
+ retryAfterS?: number;
80
+ };
81
+ /**
82
+ * `handleRequestLink` — `POST /consultation/new-link`. `done` whether or not
83
+ * the address ever wrote in and whether or not the KB answered: a different
84
+ * answer would tell a stranger who wrote to the team.
85
+ */
86
+ export type RequestLinkResult = {
87
+ done: true;
88
+ } | {
89
+ done: false;
90
+ error: ConsultationUiCode;
91
+ retryAfterS?: number;
92
+ };
93
+ /** `loadContact` — the `/contact` page. */
94
+ export type ContactPageState = {
95
+ state: 'open';
96
+ /** The legal text the form shows (a consent text comes with an UNTICKED box). */
97
+ text: ShownLegalText;
98
+ /** The idempotency key of this form; a hidden field, posted back as `messageId`. */
99
+ messageId: string;
100
+ /** Render the Turnstile widget when set (`action` = the server's Turnstile action). */
101
+ turnstileSiteKey: string | null;
102
+ /** The message field's `maxLength`. */
103
+ maxMessage: number;
104
+ } | {
105
+ state: 'error';
106
+ error: ConsultationUiCode;
107
+ retryAfterS?: number;
108
+ };
109
+ /** `handleContact` — `POST /contact`. */
110
+ export type ContactResult = {
111
+ done: 'stored';
112
+ } | {
113
+ done: false;
114
+ error: ConsultationUiCode;
115
+ /**
116
+ * The key to post with the next attempt: the SAME one after an outage (a
117
+ * retry of a question the KB did store lands as a duplicate), a NEW one
118
+ * after `conflict`.
119
+ */
120
+ messageId: string;
121
+ /** The legal text changed since the form was rendered: show `text` (a consent box unticked again). */
122
+ textChanged?: true;
123
+ text?: ShownLegalText;
124
+ retryAfterS?: number;
125
+ };
126
+ export interface ResolvedTurnstile {
127
+ siteKey: string;
128
+ secretKey: string;
129
+ action: string;
130
+ failOpen: boolean;
131
+ }
132
+ export interface ServerContext {
133
+ /** Null when `kbApiUrl` is unusable: every KB call is then an outage. */
134
+ transport: KbTransport | null;
135
+ siteUrls: string[];
136
+ /** The Origin allowlist: the site URLs' origins plus the configured extras. */
137
+ origins: readonly string[];
138
+ proxyKey: string | null;
139
+ adapterKey: string | null;
140
+ clientIpHeader: string;
141
+ cookieName: string;
142
+ turnstile: ResolvedTurnstile | null;
143
+ readerToken: (http: ConsultationHttp) => string | null;
144
+ contactMessageMax: number;
145
+ timeoutMs: number;
146
+ fetch: () => typeof fetch;
147
+ now: () => number;
148
+ randomId: () => string;
149
+ publicConfig: PublicConfigCache;
150
+ logger: ConsultationLogger;
151
+ /** One console warning per server instance and `key` — configuration problems, never reader data. */
152
+ warnOnce(key: string, message: string): void;
153
+ }
154
+ /** The locale the gate asks the KB in when a handler has no page locale (the gate reads no text). */
155
+ export declare const GATE_LOCALE = "en";
156
+ /** How long a page that could not ask the KB tells the client to wait. */
157
+ export declare const GATE_RETRY_AFTER_S = 30;
158
+ /** The KB channel of the contact form. */
159
+ export declare const CONTACT_FORM_CHANNEL = "contact_form";
160
+ /** "Show no text" (a feature that is off). */
161
+ export declare const NO_TEXT: ChannelText;
162
+ /** The outcomes operators see in the log: outages and the unexpected. Everything else is an ordinary reader state. */
163
+ export declare function isLoggedOutcome(code: ConsultationUiCode): boolean;
164
+ /** A ConsultationTransportError, also one from another copy of the SDK. */
165
+ export declare function isTransportError(err: unknown): err is ConsultationTransportError;
166
+ /** The default log line: `[consultations] op=… outcome=… kb_code=… status=…`. */
167
+ export declare const defaultConsultationLogger: ConsultationLogger;
168
+ /**
169
+ * Wraps a logger: only outages and the unexpected (`unavailable`, `submit`)
170
+ * reach it, with the KB code reduced to a code shape and the status to an
171
+ * integer. A throwing logger never breaks a handler.
172
+ */
173
+ export declare function hygienicLogger(logger: ConsultationLogger): ConsultationLogger;
174
+ /**
175
+ * Whether this blog serves the reader pages. The public config comes from the
176
+ * server's memo (identity-free: the proxy key, no reader IP, no JWT). Without
177
+ * the reader-proxy key the answer is `dark` and the KB is not asked at all. A
178
+ * locale the KB would not take never reaches it; the site-level features do
179
+ * not depend on the locale, and the contact form is off for it.
180
+ *
181
+ * `peek`: never wait for the KB — answer from the memo as it is (null when it
182
+ * holds nothing for the locale yet) and let a load run in the background, for
183
+ * menus and footers that must not hold a page up.
184
+ */
185
+ export declare function siteStatusOf(ctx: ServerContext, locale: string): Promise<ConsultationSiteStatus>;
186
+ export declare function siteStatusOf(ctx: ServerContext, locale: string, o: {
187
+ peek: true;
188
+ }): Promise<ConsultationSiteStatus | null>;
189
+ export type GateResult = {
190
+ ok: true;
191
+ status: ConsultationSiteStatus;
192
+ } | {
193
+ ok: false;
194
+ code: 'disabled' | 'unavailable';
195
+ retryAfterS?: number;
196
+ };
197
+ /** The gate of one feature: `dark` (or the feature off) → `disabled`; `unknown` → `unavailable` with `Retry-After: 30`. */
198
+ export declare function gate(ctx: ServerContext, feature: ConsultationFeature, locale?: string): Promise<GateResult>;
199
+ /** Headers of a consultation response: the fixed set, plus `Retry-After` on 503 / a known wait. */
200
+ export declare function responseHeaders(status: number, extra?: {
201
+ retryAfterS?: number;
202
+ allow?: string;
203
+ }): Record<string, string>;
204
+ export declare function respond<B>(status: number, body: B, extra?: {
205
+ retryAfterS?: number;
206
+ allow?: string;
207
+ }): ConsultationResponse<B>;
208
+ /** HTTP status of a reader code. */
209
+ export declare function statusOf(code: ConsultationUiCode): number;
210
+ /** `retryAfterS` only when known (so the body carries no `undefined` member). */
211
+ export declare function withRetry<T extends object>(body: T, retryAfterS: number | undefined): T & {
212
+ retryAfterS?: number;
213
+ };
214
+ export declare const POST_ONLY = "POST";
215
+ export declare const GET_ONLY = "GET, HEAD";
216
+ export declare function isPost(http: ConsultationHttp): boolean;
217
+ export declare function isGet(http: ConsultationHttp): boolean;
218
+ /** The posted form, or null (not a form, too large, malformed, or an adapter that throws). */
219
+ export declare function readForm(http: ConsultationHttp): Promise<Record<string, string> | null>;
220
+ /** One posted string field (own property only). */
221
+ export declare function fieldOf(fields: Record<string, string>, name: string): string | undefined;
222
+ /** The reader's IP for the KB's per-IP quotas; a request without one is announced once. */
223
+ export declare function readerIp(ctx: ServerContext, http: ConsultationHttp): string | null;
224
+ /** A fresh idempotency key (the configured generator, when it yields a valid key). */
225
+ export declare function freshKey(ctx: ServerContext): string;
226
+ /** A GraphQL client for one call, or null when no KB is configured. */
227
+ export declare function kbClient(ctx: ServerContext, o: {
228
+ token: string | null;
229
+ clientIp: string | null;
230
+ }): KbClient | null;
231
+ export interface KbFailure {
232
+ code: ConsultationUiCode;
233
+ retryAfterS?: number;
234
+ kbCode: string | null;
235
+ status: number | null;
236
+ }
237
+ /** A thrown KB error → the reader's code plus what a log line may say about it. */
238
+ export declare function kbFailureOf(err: unknown): KbFailure;
239
+ /**
240
+ * The reader cannot fix a credential the blog holds: an `auth` answer on a
241
+ * call made with the blog's own key (a revoked or wrong reader-proxy or
242
+ * adapter key) is an outage, never "sign in".
243
+ */
244
+ export declare function blogKeyFailure(f: KbFailure): KbFailure;
245
+ /** Logs a failure (outages and the unexpected only; see `hygienicLogger`). */
246
+ export declare function logFailure(ctx: ServerContext, op: string, f: Pick<KbFailure, 'code' | 'kbCode' | 'status'>): void;