@kanorio/sdk 1.1.0 → 1.3.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.
package/README.md CHANGED
@@ -23,7 +23,7 @@ const customer = createCustomerClient({
23
23
  });
24
24
  ```
25
25
 
26
- When your own server writes on a visitor's behalf (submitting a form, exchanging a customer sign-in code, reporting crawler hits from middleware), pass a server key and the visitor's IP. Without the key, server-to-server writes are stopped by an edge challenge and the SDK throws `KanorioEdgeChallengeError`.
26
+ When your own server writes on a visitor's behalf (submitting a form, exchanging a customer sign-in code, reporting crawler hits from middleware), pass a server key and the visitor's IP. Without the key the write still reaches the API, but as an anonymous visitor at your server's IP address (all your visitors share one rate limit and one spam reputation), and crawler reports are refused with `401 SERVER_KEY_REQUIRED`.
27
27
 
28
28
  ```ts
29
29
  import { createFormsHelpers, visitorIpFromRequest } from "@kanorio/sdk";
@@ -39,6 +39,75 @@ A server key is refused in browser code, requires HTTPS, and cannot call the Man
39
39
 
40
40
  Errors throw `KanorioApiError` with `code`, `status` and `details`. Deprecated operations surface through the `onDeprecation` callback (the `Deprecation`, `Sunset` and `Link` response headers).
41
41
 
42
+ ## Images and page metadata
43
+
44
+ `image` turns an image field into something you can render, and an image URL into the size you need. `seo.metadata` builds a page's `<head>` values by the rules the hosted site uses, so your front end and a Kanorio-hosted site share the same SEO behavior:
45
+
46
+ ```ts
47
+ import { image, seo } from "@kanorio/sdk";
48
+
49
+ const { item, assets } = await delivery.get("/collections/{key}/items/{slug}", { params: { key: "blog", slug } });
50
+
51
+ // The cover is optional: an asset id, looked up in `assets`
52
+ const cover = image.resolve(item.fieldData.cover_image, assets);
53
+ if (cover) {
54
+ cover.url; // the original
55
+ image.url(cover, { width: 800 }); // resized by Kanorio's edge, never enlarged
56
+ image.url(cover, { width: 400, height: 400 }); // cropped to a square around the focal point the owner set
57
+ image.srcSet(cover); // 400w, 800w, 1200w, 1600w
58
+ cover.placeholder; // a tiny blurred preview, for Next.js `blurDataURL`
59
+ cover.focus; // { x, y } from 0 to 1, for `object-position` when CSS crops
60
+ cover.edgeColor; // the color around the photo, for the background behind `object-fit: contain`
61
+ }
62
+
63
+ const meta = seo.metadata(item, { siteUrl: "https://www.example.com", site });
64
+ meta.canonical; // the author's canonical on the primary locale, else the page's own URL
65
+ meta.robots; // { index, follow }
66
+ meta.openGraph.image; // { url, alt, source, width, height }: the share image, already cropped the way the author framed it
67
+ ```
68
+
69
+ The share image comes from `fieldData.share_image`, which Kanorio resolves on the server: the image the author chose for sharing, else a post's cover, the generated title card, or the first image in the body. Pass `site` (the `GET /site` response) on multilingual sites to get hreflang and the right canonical for translated pages.
70
+
71
+ For Next.js, `@kanorio/sdk/next` adapts these without depending on `next`:
72
+
73
+ ```ts
74
+ import { seoMetadata } from "@kanorio/sdk";
75
+ import { toNextMetadata } from "@kanorio/sdk/next";
76
+
77
+ export async function generateMetadata({ params }) {
78
+ const data = await loadPost((await params).slug);
79
+ return data ? toNextMetadata(seoMetadata(data.item, { siteUrl: SITE_URL, site })) : {};
80
+ }
81
+ ```
82
+
83
+ `kanorioImageLoader` lets Kanorio's edge resize `next/image` (`kanorioRemotePatterns` allows Kanorio's image host when you let Next.js resize instead). A loader is a function, so pass it from a Client Component, or set it for the whole app with `images.loaderFile`:
84
+
85
+ ```tsx
86
+ "use client";
87
+
88
+ import Image from "next/image";
89
+ import { kanorioImageLoader } from "@kanorio/sdk/next";
90
+
91
+ export function CoverImage({ src, alt, width, height }: { src: string; alt: string; width: number; height: number }) {
92
+ return <Image loader={kanorioImageLoader} src={src} alt={alt} width={width} height={height} />;
93
+ }
94
+ ```
95
+
96
+ The [Next.js guide](https://kanorio.com/en/developers/guides/nextjs) has a complete component that also shows the blurred preview and keeps the owner's focal point.
97
+
98
+ To use `next/image` without the loader, allow Kanorio's image host in `next.config.ts`:
99
+
100
+ ```ts
101
+ import type { NextConfig } from "next";
102
+ import { kanorioRemotePatterns } from "@kanorio/sdk/next";
103
+
104
+ const nextConfig: NextConfig = {
105
+ images: { remotePatterns: kanorioRemotePatterns },
106
+ };
107
+
108
+ export default nextConfig;
109
+ ```
110
+
42
111
  ## Tax id validation
43
112
 
44
113
  `@kanorio/sdk/tax-id` validates tax ids the way the hosted checkout and forms do, without a network call:
package/dist/edge.d.ts CHANGED
@@ -50,9 +50,10 @@ export interface KanorioMiddlewareOptions {
50
50
  };
51
51
  fetch?: typeof globalThis.fetch;
52
52
  /**
53
- * Server key (`knr_sk_…`, from an environment variable). Required for crawler hit reporting: the report is a
54
- * server-to-server write, and without a key Kanorio's edge challenges it and the hit is lost. The visitor's
55
- * (crawler's) IP is read from the incoming request with `visitorIpFromRequest`.
53
+ * Server key (`knr_sk_…`, from an environment variable). Required for crawler hit reporting: Kanorio only
54
+ * accepts crawler reports from your server with a key (`401 SERVER_KEY_REQUIRED` without one), so without it
55
+ * the middleware does not send them and warns once. Redirects and crawler blocking work either way. The
56
+ * visitor's (crawler's) IP is read from the incoming request with `visitorIpFromRequest`.
56
57
  */
57
58
  serverKey?: string;
58
59
  }
package/dist/edge.js CHANGED
@@ -11,7 +11,7 @@
11
11
  * and in-site targets get the same prefix back; an allowed decision carries `locale` (locale and unprefixed path) for the front end's routing
12
12
  */
13
13
  import { deliveryBaseUrl } from "./delivery.js";
14
- import { serverKeyRequest, visitorIpFromRequest } from "./server-key.js";
14
+ import { edgeChallengeMessage, isEdgeChallenge, serverKeyRequest, visitorIpFromRequest } from "./server-key.js";
15
15
  import { localeRootPath, resolveRequestLocale } from "./shared/localization/request-locale.js";
16
16
  import { canonicalRedirectPath, matchLocalizedRedirect } from "./shared/utils/redirect-matching.js";
17
17
  export const CRAWLER_LIST_VERSION = "2026-10-22";
@@ -154,10 +154,33 @@ export function createKanorioMiddleware(options) {
154
154
  })();
155
155
  return inflight;
156
156
  }
157
+ const reportWarned = new Set();
158
+ function warnReportsLost(cause, reason) {
159
+ if (reportWarned.has(cause))
160
+ return;
161
+ reportWarned.add(cause);
162
+ console.warn(`@kanorio/sdk: AI crawler hits are not being recorded. ${reason} Redirects and crawler blocking are not affected.`);
163
+ }
164
+ function warnReportRejected(response) {
165
+ if (response.ok)
166
+ return;
167
+ const hasKey = Boolean(options.serverKey?.trim());
168
+ if (isEdgeChallenge(response))
169
+ return warnReportsLost("edge-challenge", edgeChallengeMessage(hasKey));
170
+ if (response.status === 401) {
171
+ return warnReportsLost("key-rejected", "Kanorio rejected the server key. Keys that start with knr_sa_ are no longer server keys, and a revoked key is rejected too: create a new one under Site settings > Developer (purpose \"Website server\") and store it as KANORIO_SERVER_KEY.");
172
+ }
173
+ warnReportsLost("other", `Kanorio answered ${response.status}.`);
174
+ }
157
175
  function reportBotHit(request, pathname, bot, blocked, event) {
176
+ // Kanorio only accepts crawler reports with a server key: without one, sending would only earn a 401 on every crawler hit
177
+ if (!options.serverKey?.trim()) {
178
+ warnReportsLost("no-key", "Crawler reports need a server key: create one under Site settings > Developer (purpose \"Website server\"), store it as KANORIO_SERVER_KEY and pass `serverKey` to createKanorioMiddleware. Do not paste the key into chat or commit it.");
179
+ return;
180
+ }
158
181
  const userAgent = request.headers.get("user-agent") ?? bot.uaToken;
159
182
  const url = `${apiBase}/analytics/bot-hit`;
160
- // Sends the server key and the visitor IP (read only from headers the platform guarantees); without a key it is still sent, the edge blocks it and the report is lost without affecting the request
183
+ // Sends the server key and the visitor IP (read only from headers the platform guarantees)
161
184
  const promise = serverKeyRequest({ serverKey: options.serverKey, visitorIp: visitorIpFromRequest(request) }, url)
162
185
  .then((viaServerKey) => f(url, {
163
186
  method: "POST",
@@ -170,6 +193,7 @@ export function createKanorioMiddleware(options) {
170
193
  }),
171
194
  ...(viaServerKey ? { redirect: viaServerKey.redirect } : {}),
172
195
  }))
196
+ .then(warnReportRejected)
173
197
  .catch(() => undefined);
174
198
  if (event?.waitUntil) {
175
199
  event.waitUntil(promise);
package/dist/forms.d.ts CHANGED
@@ -7,8 +7,17 @@
7
7
  */
8
8
  import { type ServerKeyOptions } from "./server-key.js";
9
9
  import type { TaxIdLookupResponse } from "./shared/business-registry/lookup-wire.js";
10
+ import type { components as DeliveryComponents } from "./generated/delivery.js";
10
11
  import { resolveVisibleFieldIds } from "./shared/types/forms-logic.js";
11
12
  import { type ProtectionChallenge, type ProtectionFields } from "./protection.js";
13
+ /**
14
+ * The form definition from `GET /forms/{id}`: status, questions, settings and the consent text to show.
15
+ * It grows over time: skip question types you do not know and ignore keys you do not recognise.
16
+ */
17
+ export type FormDefinition = DeliveryComponents["schemas"]["Form"];
18
+ /** One question; narrow on `type` to read the keys of that question type */
19
+ export type FormField = DeliveryComponents["schemas"]["FormField"];
20
+ export type FormSettings = DeliveryComponents["schemas"]["FormSettings"];
12
21
  /** `GET /forms/{id}/challenge`: the built-in ALTCHA challenge, or the parameters of the third-party widget the site chose */
13
22
  export type FormChallengeResponse = ProtectionChallenge;
14
23
  /** Protection fields sent with submissions and uploads (`_hp`, `_wp` and `_co` are honeypots, always empty strings) */
@@ -42,7 +51,15 @@ export interface FormSubmitInput {
42
51
  protection?: FormProtectionFields | Record<string, unknown>;
43
52
  consent?: "checked" | "submit_statement";
44
53
  consentTextId?: string;
54
+ /** The visitor's language, kept on the submission and the contact (for example `navigator.language`). Defaults to the helpers' `locale`. */
45
55
  locale?: string;
56
+ /**
57
+ * The site locale of the page the form is on: a code from `locales[]` of `GET /api/v1/site` (`th`, `en-US`) or its URL prefix.
58
+ * A redirect after submit to a path on the site gets this locale's URL prefix. Defaults to the helpers' `locale`; `null` sends
59
+ * none. Without it, Kanorio reads the locale from `pagePath`.
60
+ */
61
+ pageLocale?: string | null;
62
+ /** Path of the page the form is on, kept on the submission record */
46
63
  pagePath?: string;
47
64
  /** Where this visit came from (kept on the submission record): UTM and ad-click parameters, external referrer host, landing path. */
48
65
  attribution?: {
@@ -53,13 +70,30 @@ export interface FormSubmitInput {
53
70
  }
54
71
  export type FormSubmitResult = {
55
72
  ok: true;
73
+ /** Present when the form did not take the submission because of its own state; nothing was saved */
56
74
  state?: "closed" | "not_open" | "full";
75
+ /** Id of this submission; absent when `state` is present */
76
+ submissionId?: string;
77
+ /**
78
+ * Where to send the visitor now, when the form has a redirect after submit: a path on the site or an https URL (it can be another site).
79
+ * Answers and the submission id are already filled in. Navigate to it as is, for example `window.location.assign(result.redirectUrl)`.
80
+ */
81
+ redirectUrl?: string;
57
82
  } | {
58
83
  ok: false;
59
84
  error: FormApiError;
60
85
  };
61
86
  export interface FormsHelpers {
62
- get(formId: string): Promise<unknown>;
87
+ /**
88
+ * The form's definition. With `locale` (or the helpers' `locale`), question labels, options, the button and the success message
89
+ * are in that locale; text without a translation falls back to the primary locale. `locale: null` reads the primary locale
90
+ * even when the helpers have a `locale`.
91
+ */
92
+ get(formId: string, options?: {
93
+ locale?: string | null;
94
+ }): Promise<{
95
+ form: FormDefinition;
96
+ }>;
63
97
  challenge(formId: string): Promise<FormChallengeResponse>;
64
98
  requestUpload(formId: string, input: FormUploadTicketRequest): Promise<FormUploadTicketResponse>;
65
99
  /**
@@ -99,11 +133,19 @@ export declare function uploadProtectionFromChallenge(formId: string, challenge:
99
133
  export interface FormsHelpersOptions extends ServerKeyOptions {
100
134
  siteUrl: string;
101
135
  fetch?: typeof globalThis.fetch;
136
+ /**
137
+ * The locale of the page the form is on: a code from `locales[]` of `GET /api/v1/site` (`th`, `en-US`) or its URL prefix. `get()` reads
138
+ * the form in it, and `submit()` sends it as the submission's `pageLocale` and `locale` (an input's own values win), so the form's text
139
+ * and the redirect after submit follow the page's language. Omit it for the primary locale.
140
+ */
141
+ locale?: string | null;
102
142
  }
103
143
  /**
104
144
  * Pass `serverKey` (and `visitorIp`) when your **server** submits on behalf of a visitor. The key proves the
105
145
  * request comes from your server; it does not replace form protection, so the submission still needs the
106
- * `protection` fields the visitor's browser obtained.
146
+ * `protection` fields the visitor's browser obtained. Submitting from a server without a key works, but warns
147
+ * once per process (all visitors would share your server's IP). Once per process and not per helpers object: a server
148
+ * action usually creates the helpers inside each request, because the visitor IP differs per request.
107
149
  */
108
150
  export declare function createFormsHelpers(options: FormsHelpersOptions): FormsHelpers;
109
151
  /**
package/dist/forms.js CHANGED
@@ -5,7 +5,8 @@
5
5
  * Responses follow the contract shared by the three APIs: success is the object itself, failure is `{ error: { code, message, details? } }`.
6
6
  * Here both become `{ ok: true, ... }` or `{ ok: false, error }`, so a form UI does not have to read HTTP statuses.
7
7
  */
8
- import { EDGE_CHALLENGE_CODE, edgeChallengeMessage, isEdgeChallenge, serverKeyRequest } from "./server-key.js";
8
+ import { EDGE_CHALLENGE_CODE, edgeChallengeMessage, isEdgeChallenge, runsOnServer, serverKeyRequest } from "./server-key.js";
9
+ import { warnOnce } from "./warn-once.js";
9
10
  import { deliveryBaseUrl } from "./delivery.js";
10
11
  import { resolveVisibleFieldIds } from "./shared/types/forms-logic.js";
11
12
  import { protectionFromChallenge as protectionFieldsFromChallenge, uploadProtectionFromChallenge as uploadFieldsFromChallenge } from "./protection.js";
@@ -26,7 +27,7 @@ export function uploadProtectionFromChallenge(formId, challenge, renderedAt, sol
26
27
  return uploadFieldsFromChallenge(challenge, { context: formId, renderedAt, solved });
27
28
  }
28
29
  async function readFormError(res, hasServerKey) {
29
- // The edge's challenge page (a server call without a server key): return an error that says what to do next
30
+ // The edge's challenge page instead of an API response: return an error that says what to check next
30
31
  if (isEdgeChallenge(res))
31
32
  return { code: EDGE_CHALLENGE_CODE, message: edgeChallengeMessage(hasServerKey) };
32
33
  const body = (await res.json().catch(() => null));
@@ -42,10 +43,13 @@ async function readFormError(res, hasServerKey) {
42
43
  }
43
44
  return { code: res.status === 429 ? "RATE_LIMITED" : "UPSTREAM_UNAVAILABLE", message: `HTTP ${res.status}` };
44
45
  }
46
+ const SERVER_SUBMIT_WITHOUT_KEY_WARNING = "@kanorio/sdk: forms are being submitted from your server without a server key, so Kanorio sees every visitor as your server's IP address: they share one rate limit and one spam reputation, and a busy day can block real visitors. Create a server key under Site settings > Developer (purpose \"Website server\"), store it as KANORIO_SERVER_KEY, and pass `serverKey` and `visitorIp` to createFormsHelpers. Do not paste the key into chat or commit it.";
45
47
  /**
46
48
  * Pass `serverKey` (and `visitorIp`) when your **server** submits on behalf of a visitor. The key proves the
47
49
  * request comes from your server; it does not replace form protection, so the submission still needs the
48
- * `protection` fields the visitor's browser obtained.
50
+ * `protection` fields the visitor's browser obtained. Submitting from a server without a key works, but warns
51
+ * once per process (all visitors would share your server's IP). Once per process and not per helpers object: a server
52
+ * action usually creates the helpers inside each request, because the visitor IP differs per request.
49
53
  */
50
54
  export function createFormsHelpers(options) {
51
55
  const apiBase = deliveryBaseUrl(options.siteUrl);
@@ -53,6 +57,8 @@ export function createFormsHelpers(options) {
53
57
  const post = async (path, body) => {
54
58
  const url = `${apiBase}${path}`;
55
59
  const viaServerKey = await serverKeyRequest(options, url);
60
+ if (!viaServerKey && runsOnServer())
61
+ warnOnce("forms:no-server-key", SERVER_SUBMIT_WITHOUT_KEY_WARNING);
56
62
  return f(url, {
57
63
  method: "POST",
58
64
  headers: { "Content-Type": "application/json", Accept: "application/json", ...(viaServerKey?.headers ?? {}) },
@@ -62,8 +68,11 @@ export function createFormsHelpers(options) {
62
68
  };
63
69
  const readError = (res) => readFormError(res, Boolean(options.serverKey));
64
70
  return {
65
- async get(formId) {
66
- const res = await f(`${apiBase}/forms/${encodeURIComponent(formId)}`, { headers: { Accept: "application/json" } });
71
+ async get(formId, getOptions) {
72
+ // An explicit null reads the primary locale even when the helpers have a locale
73
+ const locale = getOptions?.locale !== undefined ? getOptions.locale : (options.locale ?? null);
74
+ const query = locale ? `?locale=${encodeURIComponent(locale)}` : "";
75
+ const res = await f(`${apiBase}/forms/${encodeURIComponent(formId)}${query}`, { headers: { Accept: "application/json" } });
67
76
  if (!res.ok)
68
77
  throw new Error(`Failed to fetch form ${formId}: HTTP ${res.status}`);
69
78
  return res.json();
@@ -104,14 +113,24 @@ export function createFormsHelpers(options) {
104
113
  return { ok: true, ...wire };
105
114
  },
106
115
  async submit(formId, input) {
107
- const { protection, ...rest } = input;
108
- const res = await post(`/forms/${encodeURIComponent(formId)}/submit`, { ...rest, ...(protection ?? {}) }).catch(() => null);
116
+ const { protection, pageLocale: ownPageLocale, ...rest } = input;
117
+ const locale = rest.locale ?? options.locale ?? undefined;
118
+ // The page's locale decides the redirect's URL prefix; an explicit null on the input sends none (Kanorio then reads it from pagePath)
119
+ const pageLocale = ownPageLocale !== undefined ? ownPageLocale : (options.locale ?? null);
120
+ const body = { ...rest, ...(locale ? { locale } : {}), ...(pageLocale ? { pageLocale } : {}), ...(protection ?? {}) };
121
+ const res = await post(`/forms/${encodeURIComponent(formId)}/submit`, body).catch(() => null);
109
122
  if (!res)
110
123
  return { ok: false, error: { code: "UPSTREAM_UNAVAILABLE", message: "Network error" } };
111
124
  if (!res.ok)
112
125
  return { ok: false, error: await readError(res) };
113
126
  const data = (await res.json().catch(() => ({})));
114
- return data.state ? { ok: true, state: data.state } : { ok: true };
127
+ if (data.state)
128
+ return { ok: true, state: data.state };
129
+ return {
130
+ ok: true,
131
+ ...(typeof data.submissionId === "string" ? { submissionId: data.submissionId } : {}),
132
+ ...(typeof data.redirectUrl === "string" ? { redirectUrl: data.redirectUrl } : {}),
133
+ };
115
134
  },
116
135
  };
117
136
  }