@kanorio/sdk 0.0.0-stage → 1.1.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 (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +66 -2
  3. package/dist/customer-oauth.d.ts +86 -0
  4. package/dist/customer-oauth.js +112 -0
  5. package/dist/customer.d.ts +176 -0
  6. package/dist/customer.js +125 -0
  7. package/dist/delivery.d.ts +35 -0
  8. package/dist/delivery.js +49 -0
  9. package/dist/edge.d.ts +108 -0
  10. package/dist/edge.js +287 -0
  11. package/dist/forms.d.ts +123 -0
  12. package/dist/forms.js +130 -0
  13. package/dist/generated/customer.d.ts +3157 -0
  14. package/dist/generated/delivery.d.ts +2408 -0
  15. package/dist/generated/management.d.ts +38333 -0
  16. package/dist/http.d.ts +73 -0
  17. package/dist/http.js +162 -0
  18. package/dist/index.d.ts +16 -0
  19. package/dist/index.js +17 -0
  20. package/dist/locales.d.ts +80 -0
  21. package/dist/locales.js +81 -0
  22. package/dist/management.d.ts +19 -0
  23. package/dist/management.js +22 -0
  24. package/dist/paginate.d.ts +18 -0
  25. package/dist/paginate.js +27 -0
  26. package/dist/preview.d.ts +40 -0
  27. package/dist/preview.js +131 -0
  28. package/dist/protection.d.ts +74 -0
  29. package/dist/protection.js +68 -0
  30. package/dist/revalidate.d.ts +84 -0
  31. package/dist/revalidate.js +143 -0
  32. package/dist/seo.d.ts +120 -0
  33. package/dist/seo.js +125 -0
  34. package/dist/server-key.d.ts +71 -0
  35. package/dist/server-key.js +103 -0
  36. package/dist/shared/api/delivery/cache-tags.d.ts +142 -0
  37. package/dist/shared/api/delivery/cache-tags.js +212 -0
  38. package/dist/shared/api/server-key.d.ts +90 -0
  39. package/dist/shared/api/server-key.js +260 -0
  40. package/dist/shared/business-registry/attribution.d.ts +14 -0
  41. package/dist/shared/business-registry/attribution.js +28 -0
  42. package/dist/shared/business-registry/define.d.ts +3 -0
  43. package/dist/shared/business-registry/define.js +4 -0
  44. package/dist/shared/business-registry/formats/eu-vat.d.ts +2 -0
  45. package/dist/shared/business-registry/formats/eu-vat.js +54 -0
  46. package/dist/shared/business-registry/formats/hk-br.d.ts +5 -0
  47. package/dist/shared/business-registry/formats/hk-br.js +23 -0
  48. package/dist/shared/business-registry/formats/jp-trn.d.ts +6 -0
  49. package/dist/shared/business-registry/formats/jp-trn.js +23 -0
  50. package/dist/shared/business-registry/formats/kr-brn.d.ts +6 -0
  51. package/dist/shared/business-registry/formats/kr-brn.js +30 -0
  52. package/dist/shared/business-registry/formats/my.d.ts +7 -0
  53. package/dist/shared/business-registry/formats/my.js +32 -0
  54. package/dist/shared/business-registry/formats/sg-uen.d.ts +1 -0
  55. package/dist/shared/business-registry/formats/sg-uen.js +21 -0
  56. package/dist/shared/business-registry/formats/tw-vat.d.ts +10 -0
  57. package/dist/shared/business-registry/formats/tw-vat.js +32 -0
  58. package/dist/shared/business-registry/index.d.ts +9 -0
  59. package/dist/shared/business-registry/index.js +10 -0
  60. package/dist/shared/business-registry/lookup-wire.d.ts +33 -0
  61. package/dist/shared/business-registry/lookup-wire.js +8 -0
  62. package/dist/shared/business-registry/normalize.d.ts +7 -0
  63. package/dist/shared/business-registry/normalize.js +12 -0
  64. package/dist/shared/business-registry/registry.d.ts +26 -0
  65. package/dist/shared/business-registry/registry.js +67 -0
  66. package/dist/shared/business-registry/types.d.ts +60 -0
  67. package/dist/shared/business-registry/types.js +10 -0
  68. package/dist/shared/localization/locale-path.d.ts +38 -0
  69. package/dist/shared/localization/locale-path.js +76 -0
  70. package/dist/shared/localization/request-locale.d.ts +42 -0
  71. package/dist/shared/localization/request-locale.js +61 -0
  72. package/dist/shared/seo/alternates.d.ts +61 -0
  73. package/dist/shared/seo/alternates.js +71 -0
  74. package/dist/shared/types/forms-logic.d.ts +96 -0
  75. package/dist/shared/types/forms-logic.js +209 -0
  76. package/dist/shared/types/number-input.d.ts +5 -0
  77. package/dist/shared/types/number-input.js +16 -0
  78. package/dist/shared/utils/redirect-matching.d.ts +76 -0
  79. package/dist/shared/utils/redirect-matching.js +181 -0
  80. package/dist/tax-id.d.ts +7 -0
  81. package/dist/tax-id.js +6 -0
  82. package/dist/typed.d.ts +85 -0
  83. package/dist/typed.js +28 -0
  84. package/package.json +86 -3
package/dist/seo.js ADDED
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Helpers for headless SEO and AEO files and JSON-LD:
3
+ * - `seoRewrites({ siteUrl, framework })`: rules to spread into `next.config` `rewrites()`, or a map for `astro.config`
4
+ * - `fetchDeliveryJsonLd({ siteUrl, path })`: fetches a path's Schema.org JSON-LD `@graph` and a safely escaped `<script>` string
5
+ * - `fetchSitemapEntries({ siteUrl })`: `sitemap.xml` as data, for front ends that build their own sitemap and merge it in
6
+ * - `listingRobots(site, key)`: the robots value of a list page, from `listings` in `/api/v1/site`
7
+ */
8
+ import { deliveryBaseUrl, parseDeliveryCacheTags } from "./delivery.js";
9
+ import { buildAlternates, languageSwitcher } from "./locales.js";
10
+ const SEO_REWRITE_PATHS = [
11
+ { source: "/sitemap.xml", apiPath: "/seo/sitemap.xml" },
12
+ { source: "/robots.txt", apiPath: "/seo/robots.txt" },
13
+ { source: "/llms.txt", apiPath: "/seo/llms.txt" },
14
+ { source: "/llms-full.txt", apiPath: "/seo/llms-full.txt" },
15
+ { source: "/feed.xml", apiPath: "/feed" },
16
+ { source: "/rss.xml", apiPath: "/feed" },
17
+ { source: "/feed.atom", apiPath: "/feed.atom" },
18
+ ];
19
+ export function seoRewrites(options) {
20
+ const base = deliveryBaseUrl(options.siteUrl);
21
+ const rules = SEO_REWRITE_PATHS.map((r) => ({
22
+ source: r.source,
23
+ destination: `${base}${r.apiPath}`,
24
+ }));
25
+ if (options.framework === "astro") {
26
+ return Object.fromEntries(rules.map((r) => [r.source, r.destination]));
27
+ }
28
+ // IndexNow requires the key verification file at `https://{host}/{key}.txt`; a dynamic Next.js path
29
+ // source covers every possible key value, without knowing the key in advance (the server matches it and answers).
30
+ // Astro's static source-to-destination map cannot express a dynamic path; there, `createKanorioMiddleware`
31
+ // from `@kanorio/sdk/edge` (`features.indexNow`, on by default) answers at the edge.
32
+ rules.push({
33
+ source: "/:key([a-f0-9]{32}).txt",
34
+ destination: `${base}/seo/indexnow-key.txt`,
35
+ });
36
+ return rules;
37
+ }
38
+ function escapeJsonForScript(json) {
39
+ return json
40
+ .replace(/</g, "\\u003c")
41
+ .replace(/>/g, "\\u003e")
42
+ .replace(/&/g, "\\u0026")
43
+ .replace(/\u2028/g, "\\u2028")
44
+ .replace(/\u2029/g, "\\u2029");
45
+ }
46
+ export async function fetchDeliveryJsonLd(options) {
47
+ const fetchImpl = options.fetch ?? globalThis.fetch;
48
+ const rawPath = (options.path ?? "/").trim();
49
+ const normalizedPath = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
50
+ const url = `${deliveryBaseUrl(options.siteUrl)}/seo/jsonld?path=${encodeURIComponent(normalizedPath)}`;
51
+ const res = await fetchImpl(url);
52
+ if (!res.ok)
53
+ return null;
54
+ const jsonLd = (await res.json());
55
+ return {
56
+ jsonLd,
57
+ scriptJson: escapeJsonForScript(JSON.stringify(jsonLd)),
58
+ cacheTags: parseDeliveryCacheTags(res.headers),
59
+ };
60
+ }
61
+ /**
62
+ * The URLs Kanorio manages (the same list as `/api/v1/seo/sitemap.xml`, as data).
63
+ * A site with only part of its content on Kanorio merges this list with its own URLs in its sitemap generator:
64
+ *
65
+ * ```ts
66
+ * // app/sitemap.ts (Next.js)
67
+ * export default async function sitemap() {
68
+ * const kanorio = await fetchSitemapEntries({ siteUrl });
69
+ * return [...ownUrls, ...(kanorio?.urls ?? []).map((u) => ({ url: u.url, lastModified: u.lastModified }))];
70
+ * }
71
+ * ```
72
+ *
73
+ * Returns null when the origin fetch fails, so the caller can decide whether to output only its own URLs.
74
+ */
75
+ export async function fetchSitemapEntries(options) {
76
+ const fetchImpl = options.fetch ?? globalThis.fetch;
77
+ try {
78
+ const res = await fetchImpl(`${deliveryBaseUrl(options.siteUrl)}/seo/sitemap`);
79
+ if (!res.ok)
80
+ return null;
81
+ const body = (await res.json());
82
+ if (typeof body.siteUrl !== "string" || !Array.isArray(body.urls))
83
+ return null;
84
+ return { siteUrl: body.siteUrl, urls: body.urls, cacheTags: parseDeliveryCacheTags(res.headers) };
85
+ }
86
+ catch {
87
+ // Unreachable, timed out or not JSON: the caller's sitemap must still be able to output its own URLs
88
+ return null;
89
+ }
90
+ }
91
+ /**
92
+ * The robots value a list page (blog index, post category page, shop index, ...) should output, by the same rules as Kanorio's sitemap and IndexNow:
93
+ * - `live` → `"index, follow"`
94
+ * - `empty` (no content yet): `"noindex, follow"`, and the page renders as usual
95
+ * - `off` (hidden by the owner, or not declared in externalListings): `null`; the page should not be served, so answer 404
96
+ *
97
+ * `site` is the `GET /api/v1/site` response. `listings` is missing only in responses cached before the upgrade; the SDK has no content
98
+ * flags to derive it from, so it falls back to `live` to keep the earlier behavior. That fallback is not a defined meaning.
99
+ */
100
+ export function listingRobots(site, key) {
101
+ const state = site.listings?.[key] ?? "live";
102
+ if (state === "off")
103
+ return null;
104
+ return state === "live" ? "index, follow" : "noindex, follow";
105
+ }
106
+ export function createSeoHelpers(options) {
107
+ function rewrites(opts) {
108
+ return seoRewrites({ siteUrl: options.siteUrl, framework: opts.framework });
109
+ }
110
+ return {
111
+ rewrites,
112
+ jsonLd: (path = "/") => fetchDeliveryJsonLd({ siteUrl: options.siteUrl, path, fetch: options.fetch }),
113
+ sitemapEntries: () => fetchSitemapEntries({ siteUrl: options.siteUrl, fetch: options.fetch }),
114
+ };
115
+ }
116
+ export const seo = {
117
+ rewrites: seoRewrites,
118
+ jsonLd: fetchDeliveryJsonLd,
119
+ sitemapEntries: fetchSitemapEntries,
120
+ listingRobots,
121
+ /** A page's canonical and hreflang on multilingual sites (`locales.alternates`) */
122
+ alternates: buildAlternates,
123
+ languageSwitcher,
124
+ create: createSeoHelpers,
125
+ };
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Server key support shared by every client in this package.
3
+ *
4
+ * A server key (`knr_sk_…`, created under Site settings > Developer with the purpose "Website server") lets
5
+ * **your server** call the visitor-facing write endpoints on behalf of a visitor: submit a form, exchange a
6
+ * customer sign-in code, report an AI crawler hit. Without it, Kanorio's edge treats server-to-server writes
7
+ * as automated traffic and answers with a challenge page.
8
+ *
9
+ * Rules enforced here:
10
+ * - Never in a browser. The key is a secret; passing it in browser code throws.
11
+ * - HTTPS only (localhost is allowed for development).
12
+ * - Redirects are not followed: `fetch` strips `Authorization` on a cross-origin redirect but keeps custom
13
+ * headers, so following one would hand the key to another host.
14
+ */
15
+ import { SERVER_KEY_HEADER, SERVER_KEY_VISITOR_IP_HEADER } from "./shared/api/server-key.js";
16
+ export { SERVER_KEY_HEADER, SERVER_KEY_VISITOR_IP_HEADER };
17
+ export type VisitorIpSource = string | null | undefined | (() => string | null | undefined | Promise<string | null | undefined>);
18
+ export interface ServerKeyOptions {
19
+ /**
20
+ * Server key (`knr_sk_…`). Server-side only: read it from an environment variable such as
21
+ * `KANORIO_SERVER_KEY`. Required when your server writes on behalf of a visitor.
22
+ */
23
+ serverKey?: string;
24
+ /**
25
+ * The visitor's IP address for this request, so Kanorio can rate-limit and score each visitor separately.
26
+ * Pass it whenever the request is caused by a visitor. Without it, all your visitors look like one source
27
+ * and share one rate limit. `visitorIpFromRequest(request)` reads it from the incoming request on
28
+ * Cloudflare, Vercel, Netlify and Fly.io; elsewhere pass the IP your platform gives you.
29
+ */
30
+ visitorIp?: VisitorIpSource;
31
+ }
32
+ /**
33
+ * Headers and fetch options for a request that carries a server key. Returns `null` when no key is set.
34
+ * Throws when called in a browser or against a non-HTTPS URL.
35
+ */
36
+ export declare function serverKeyRequest(options: ServerKeyOptions, targetUrl: string): Promise<{
37
+ headers: Record<string, string>;
38
+ redirect: "error";
39
+ } | null>;
40
+ export interface VisitorIpOptions {
41
+ /**
42
+ * A header that **your own** reverse proxy sets to the visitor's IP and overwrites on every request
43
+ * (for example `x-real-ip` behind nginx). Use this on hosts the SDK does not recognise. Never name a
44
+ * header the visitor can set, such as `x-forwarded-for` behind a proxy that only appends to it.
45
+ */
46
+ trustedHeader?: string;
47
+ }
48
+ /**
49
+ * The visitor's IP from an incoming request. The SDK detects the hosting platform (Cloudflare, Vercel,
50
+ * Netlify, Fly.io) and reads only the header that platform sets itself, so a visitor cannot choose their
51
+ * own IP. On any other host it returns `undefined` unless you pass `trustedHeader`. It also returns
52
+ * `undefined` when the value is not a public address.
53
+ *
54
+ * `x-forwarded-for` is never read by default: on most platforms its leftmost entry is whatever the
55
+ * visitor sent.
56
+ */
57
+ export declare function visitorIpFromRequest(request: {
58
+ headers: {
59
+ get(name: string): string | null;
60
+ };
61
+ }, options?: VisitorIpOptions): string | undefined;
62
+ /** True when the response is Kanorio's edge challenge page instead of an API response. */
63
+ export declare function isEdgeChallenge(response: {
64
+ status: number;
65
+ headers: {
66
+ get(name: string): string | null;
67
+ };
68
+ }): boolean;
69
+ export declare const EDGE_CHALLENGE_CODE = "EDGE_CHALLENGE";
70
+ /** What to tell the developer (or their AI tool) when a request was challenged at the edge. */
71
+ export declare function edgeChallengeMessage(hasServerKey: boolean): string;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Server key support shared by every client in this package.
3
+ *
4
+ * A server key (`knr_sk_…`, created under Site settings > Developer with the purpose "Website server") lets
5
+ * **your server** call the visitor-facing write endpoints on behalf of a visitor: submit a form, exchange a
6
+ * customer sign-in code, report an AI crawler hit. Without it, Kanorio's edge treats server-to-server writes
7
+ * as automated traffic and answers with a challenge page.
8
+ *
9
+ * Rules enforced here:
10
+ * - Never in a browser. The key is a secret; passing it in browser code throws.
11
+ * - HTTPS only (localhost is allowed for development).
12
+ * - Redirects are not followed: `fetch` strips `Authorization` on a cross-origin redirect but keeps custom
13
+ * headers, so following one would hand the key to another host.
14
+ */
15
+ import { SERVER_KEY_HEADER, SERVER_KEY_VISITOR_IP_HEADER, normalizeVisitorIp } from "./shared/api/server-key.js";
16
+ export { SERVER_KEY_HEADER, SERVER_KEY_VISITOR_IP_HEADER };
17
+ const LOCAL_HOST_RE = /^(localhost|127\.0\.0\.1|\[::1\])$/i;
18
+ function isBrowser() {
19
+ return typeof window !== "undefined" && typeof document !== "undefined";
20
+ }
21
+ /**
22
+ * Headers and fetch options for a request that carries a server key. Returns `null` when no key is set.
23
+ * Throws when called in a browser or against a non-HTTPS URL.
24
+ */
25
+ export async function serverKeyRequest(options, targetUrl) {
26
+ const key = options.serverKey?.trim();
27
+ if (!key)
28
+ return null;
29
+ if (isBrowser()) {
30
+ throw new Error("@kanorio/sdk: `serverKey` must never be used in the browser. Call Kanorio from your server (route handler, server action, middleware) and keep the key in an environment variable.");
31
+ }
32
+ const url = new URL(targetUrl);
33
+ if (url.protocol !== "https:" && !LOCAL_HOST_RE.test(url.hostname)) {
34
+ throw new Error("@kanorio/sdk: `serverKey` requires an https site URL.");
35
+ }
36
+ const headers = { [SERVER_KEY_HEADER]: key };
37
+ const raw = typeof options.visitorIp === "function" ? await options.visitorIp() : options.visitorIp;
38
+ const visitorIp = normalizeVisitorIp(raw);
39
+ if (visitorIp)
40
+ headers[SERVER_KEY_VISITOR_IP_HEADER] = visitorIp;
41
+ return { headers, redirect: "error" };
42
+ }
43
+ /**
44
+ * Which header carries the visitor's IP on each platform. Only the platform the code is actually running
45
+ * on is consulted: a header such as `cf-connecting-ip` is trustworthy on Cloudflare, where the edge
46
+ * overwrites it, but on any other host it is whatever the visitor sent.
47
+ */
48
+ const PLATFORM_IP_HEADERS = {
49
+ cloudflare: ["cf-connecting-ip"],
50
+ vercel: ["x-vercel-forwarded-for", "x-real-ip"],
51
+ netlify: ["x-nf-client-connection-ip"],
52
+ fly: ["fly-client-ip"],
53
+ };
54
+ function detectHostingPlatform() {
55
+ const scope = globalThis;
56
+ const env = scope.process?.env ?? {};
57
+ if (env.VERCEL)
58
+ return "vercel";
59
+ if (env.NETLIFY || scope.Netlify !== undefined)
60
+ return "netlify";
61
+ if (env.FLY_APP_NAME)
62
+ return "fly";
63
+ if (scope.navigator?.userAgent === "Cloudflare-Workers")
64
+ return "cloudflare";
65
+ return null;
66
+ }
67
+ /**
68
+ * The visitor's IP from an incoming request. The SDK detects the hosting platform (Cloudflare, Vercel,
69
+ * Netlify, Fly.io) and reads only the header that platform sets itself, so a visitor cannot choose their
70
+ * own IP. On any other host it returns `undefined` unless you pass `trustedHeader`. It also returns
71
+ * `undefined` when the value is not a public address.
72
+ *
73
+ * `x-forwarded-for` is never read by default: on most platforms its leftmost entry is whatever the
74
+ * visitor sent.
75
+ */
76
+ export function visitorIpFromRequest(request, options = {}) {
77
+ const platform = options.trustedHeader ? null : detectHostingPlatform();
78
+ const names = options.trustedHeader ? [options.trustedHeader] : platform ? PLATFORM_IP_HEADERS[platform] : [];
79
+ for (const name of names) {
80
+ const value = request.headers.get(name);
81
+ if (!value)
82
+ continue;
83
+ // x-vercel-forwarded-for can be a list when the project sits behind another proxy; the first entry is the client
84
+ const ip = normalizeVisitorIp(value.split(",")[0]);
85
+ if (ip)
86
+ return ip;
87
+ }
88
+ return undefined;
89
+ }
90
+ /** True when the response is Kanorio's edge challenge page instead of an API response. */
91
+ export function isEdgeChallenge(response) {
92
+ return response.headers.get("cf-mitigated") === "challenge";
93
+ }
94
+ export const EDGE_CHALLENGE_CODE = "EDGE_CHALLENGE";
95
+ /** What to tell the developer (or their AI tool) when a request was challenged at the edge. */
96
+ export function edgeChallengeMessage(hasServerKey) {
97
+ if (isBrowser()) {
98
+ return "Kanorio's edge challenged this request. In a browser this usually clears after the visitor passes the check; retry the request.";
99
+ }
100
+ return hasServerKey
101
+ ? "Kanorio's edge challenged this server-side request even though a server key was sent. Check that the key is a server key (starts with knr_sk_, purpose \"Website server\") and that it is sent to the site's own hostname."
102
+ : "Kanorio's edge challenged this server-side request. Server-side writes need a server key: create one under Site settings > Developer (purpose \"Website server\"), store it as KANORIO_SERVER_KEY, and pass `serverKey` to the client. Do not paste the key into chat or commit it.";
103
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Cache tags of the Content Delivery API (the single source of truth).
3
+ *
4
+ * A response's tags say which content it used; an event's tags say which content changed. Both come from the functions in this file,
5
+ * and a contract matrix in Kanorio's tests checks every pairing: what should be cleared is cleared, and what should not is never touched.
6
+ *
7
+ * Layers (one response carries both broad and narrow tags, like CDN surrogate keys):
8
+ * - Site `site:{id}`: on every response; sent only by events for a full-site publish and for changes to the locale set (enabled, disabled, removed, prefix changed, primary changed)
9
+ * - Locale `locale:{code}`: on every response of a secondary locale; sent when a full-site translation finishes or translated site settings go live
10
+ * - Content `page:{id}`, `item:{id}`, `product:{id}`, `form:{id}`: on the response in every locale; sent when primary-locale content goes live (untranslated fields fall back to the primary locale, so every locale is cleared)
11
+ * - Content plus locale `page:{id}@en-US`: only on that locale's response; sent when that locale's translation goes live, leaving other locales alone
12
+ * - Lists `pages`, `collection:{key}`, `products` (plus locale): on list responses only, not per item (events send the list tags anyway, and Next.js allows at most 128 tags per cache entry);
13
+ * single-item responses do not carry list tags, so another item going live does not clear them. `collection:{key}:items` is every single-item response of the collection (all replaced when the field structure changes)
14
+ * - Derived `search`, `seo`, `redirects`: search, SEO files and the redirect table; sent along with content events that change them
15
+ *
16
+ * Tags use the locale code, not the URL prefix (owners can change the prefix); the locale is appended with `@`, apart from the colon of `type:id`.
17
+ * `revalidateTag` matches literally, with no wildcards, so events must list concrete tags. Pure functions with no server-only dependency, shared by Kanorio's server, its edge worker and the SDK
18
+ * (the SDK's copy is made by `pnpm --filter @kanorio/sdk gen`, and a contract test keeps the two identical).
19
+ */
20
+ export declare const DELIVERY_CACHE_TAGS_HEADER = "x-kanorio-cache-tags";
21
+ /** Maximum tags per response: Next.js caps a cache entry at 128, leaving room for the external front end's own tags */
22
+ export declare const DELIVERY_CACHE_TAG_LIMIT = 100;
23
+ /** Separator between a tag and its locale: `item:abc@en-US` */
24
+ export declare const CACHE_TAG_LOCALE_SEPARATOR = "@";
25
+ /** Namespace the SDK adds when handing tags to a framework (Next.js `revalidateTag`, `next.tags`), to avoid clashing with the site's own tags such as `pages` or `seo` */
26
+ export declare const DEFAULT_CACHE_TAG_PREFIX = "kanorio:";
27
+ /** The tag vocabulary; strings are only assembled here */
28
+ export declare const cacheTag: {
29
+ readonly site: (siteId: string) => string;
30
+ readonly locale: (locale: string) => string;
31
+ readonly pages: () => string;
32
+ readonly page: (pageId: string) => string;
33
+ readonly globals: () => string;
34
+ readonly header: (key: string) => string;
35
+ readonly footer: () => string;
36
+ readonly collections: () => string;
37
+ readonly collection: (key: string) => string;
38
+ /** Every single-item response of the collection: used when the field structure changes or a batch exceeds the limit */
39
+ readonly collectionItems: (key: string) => string;
40
+ readonly item: (itemId: string) => string;
41
+ readonly products: () => string;
42
+ readonly product: (productId: string) => string;
43
+ readonly form: (formId: string) => string;
44
+ readonly search: () => string;
45
+ readonly seo: () => string;
46
+ readonly redirects: () => string;
47
+ readonly aiCrawlerRules: () => string;
48
+ readonly reviews: () => string;
49
+ };
50
+ export declare function isSiteCacheTag(tag: string): boolean;
51
+ export declare function isLocaleCacheTag(tag: string): boolean;
52
+ /** `item:abc` → `item:abc@en-US` */
53
+ export declare function localizeCacheTag(tag: string, locale: string): string;
54
+ /**
55
+ * The locale dimension of a response: the primary locale (`locale` is null) is left as is; a secondary locale gets the locale appended to every content and list tag (not to `site:`), plus `locale:{code}`.
56
+ * The edge calls this with the request's normalized locale code (omitted and explicitly primary are both null); the server only declares content dependencies.
57
+ */
58
+ export declare function localizeCacheTags(tags: readonly string[], locale: string | null | undefined): string[];
59
+ /** Over the limit, single-content tags are dropped first (list tags stay, since events send them anyway); if still over, only the first `limit` are kept */
60
+ export declare function capCacheTags(tags: readonly string[], limit?: number): string[];
61
+ /** `X-Kanorio-Cache-Tags` is space-separated */
62
+ export declare function parseCacheTagsHeader(raw: string | null | undefined): string[];
63
+ export declare function formatCacheTagsHeader(tags: readonly string[]): string;
64
+ /** Adds the namespace before handing tags to a framework; an empty `prefix` leaves them as is */
65
+ export declare function prefixCacheTags(tags: readonly string[], prefix?: string): string[];
66
+ export interface PageResponseDeps {
67
+ pageId: string;
68
+ /** Ancestor pages in the breadcrumb (titles follow the ancestors) */
69
+ ancestorIds?: readonly string[];
70
+ /** The header assigned to the page (`primary` or a custom key); given when the page response includes header data */
71
+ headerKey?: string | null;
72
+ /** Given when the page response includes footer data */
73
+ withFooter?: boolean;
74
+ }
75
+ export interface ItemsResponseDeps {
76
+ /** Collection keys of references expanded with `expand` (authors, categories, ...): when items in those collections change, the list must change too */
77
+ expandedCollectionKeys?: readonly string[];
78
+ }
79
+ export interface ItemResponseDeps extends ItemsResponseDeps {
80
+ /** Ids of the reference items expanded with `expand` */
81
+ expandedItemIds?: readonly string[];
82
+ }
83
+ export declare const responseCacheTags: {
84
+ readonly site: (siteId: string) => string[];
85
+ readonly pages: (siteId: string) => string[];
86
+ readonly page: (siteId: string, deps: PageResponseDeps) => string[];
87
+ readonly header: (siteId: string, key: string) => string[];
88
+ readonly footer: (siteId: string) => string[];
89
+ readonly collections: (siteId: string) => string[];
90
+ readonly items: (siteId: string, collectionKey: string, deps?: ItemsResponseDeps) => string[];
91
+ readonly item: (siteId: string, collectionKey: string, itemId: string, deps?: ItemResponseDeps) => string[];
92
+ readonly products: (siteId: string) => string[];
93
+ readonly product: (siteId: string, productId: string) => string[];
94
+ readonly form: (siteId: string, formId: string) => string[];
95
+ readonly search: (siteId: string) => string[];
96
+ readonly seo: (siteId: string, options?: {
97
+ robots?: boolean;
98
+ }) => string[];
99
+ readonly feed: (siteId: string) => string[];
100
+ readonly redirects: (siteId: string) => string[];
101
+ readonly reviews: (siteId: string, productId: string | null) => string[];
102
+ };
103
+ /** Translatable record types (the same strings as Kanorio's translatable-fields registry; not imported here, so the SDK's copy stands alone) */
104
+ export type TranslationCacheScope = "page" | "global_sections" | "site_settings" | "store_settings" | "post" | "post_category" | "post_tag" | "author" | "product" | "product_option" | "pricing_tier" | "product_category" | "deliverable" | "deliverable_unit" | "form" | "top_bar_banner" | "modal_announcement" | "floating_widget" | "collection_item";
105
+ export interface TranslationEventInput {
106
+ entityType: TranslationCacheScope;
107
+ entityId: string;
108
+ locale: string;
109
+ /** The collection key a `collection_item` belongs to (looked up by the caller) */
110
+ collectionKey?: string | null;
111
+ }
112
+ export declare const eventCacheTags: {
113
+ /** Full-site publish: pages, header and footer, redirects and SEO files may all change */
114
+ readonly sitePublished: (siteId: string) => string[];
115
+ /** A single page going live, updated, taken offline or deleted: `site:` is not sent, so other pages stay; a changed URL also sends `redirects` */
116
+ readonly pageChanged: (input: {
117
+ pageId: string;
118
+ renamed?: boolean;
119
+ }) => string[];
120
+ readonly itemChanged: (input: {
121
+ collectionKey: string;
122
+ itemId: string;
123
+ }) => string[];
124
+ /** Bulk: items are listed one by one when their tags fit; otherwise every single-item response of the collection is cleared (list tags are always sent) */
125
+ readonly itemsBulkChanged: (input: {
126
+ collectionKey: string;
127
+ itemIds: readonly string[];
128
+ }) => string[];
129
+ /** The field structure changed: the collection list, the item list and every single-item response of the collection (projected fields changed) */
130
+ readonly schemaChanged: (input: {
131
+ collectionKey: string;
132
+ }) => string[];
133
+ /** The locale set changed (enabled, disabled, removed, prefix, order, primary): the language switcher and hreflang are on every page */
134
+ readonly localeChanged: (siteId: string) => string[];
135
+ /** A full-site translation finished: every response in that locale */
136
+ readonly translationJobCompleted: (locale: string) => string[];
137
+ /**
138
+ * One record's translation in one locale went live or was deleted: only locale-specific tags are sent, so the caches of other locales and the primary locale stay.
139
+ * Site settings and site announcements frame the whole locale, hence `locale:{code}`; product options, categories and course outlines have no single product id, hence `products@{code}`.
140
+ */
141
+ readonly translationChanged: (input: TranslationEventInput) => string[];
142
+ };
@@ -0,0 +1,212 @@
1
+ // Copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`. Do not edit by hand; a contract test keeps the two copies identical.
2
+ /**
3
+ * Cache tags of the Content Delivery API (the single source of truth).
4
+ *
5
+ * A response's tags say which content it used; an event's tags say which content changed. Both come from the functions in this file,
6
+ * and a contract matrix in Kanorio's tests checks every pairing: what should be cleared is cleared, and what should not is never touched.
7
+ *
8
+ * Layers (one response carries both broad and narrow tags, like CDN surrogate keys):
9
+ * - Site `site:{id}`: on every response; sent only by events for a full-site publish and for changes to the locale set (enabled, disabled, removed, prefix changed, primary changed)
10
+ * - Locale `locale:{code}`: on every response of a secondary locale; sent when a full-site translation finishes or translated site settings go live
11
+ * - Content `page:{id}`, `item:{id}`, `product:{id}`, `form:{id}`: on the response in every locale; sent when primary-locale content goes live (untranslated fields fall back to the primary locale, so every locale is cleared)
12
+ * - Content plus locale `page:{id}@en-US`: only on that locale's response; sent when that locale's translation goes live, leaving other locales alone
13
+ * - Lists `pages`, `collection:{key}`, `products` (plus locale): on list responses only, not per item (events send the list tags anyway, and Next.js allows at most 128 tags per cache entry);
14
+ * single-item responses do not carry list tags, so another item going live does not clear them. `collection:{key}:items` is every single-item response of the collection (all replaced when the field structure changes)
15
+ * - Derived `search`, `seo`, `redirects`: search, SEO files and the redirect table; sent along with content events that change them
16
+ *
17
+ * Tags use the locale code, not the URL prefix (owners can change the prefix); the locale is appended with `@`, apart from the colon of `type:id`.
18
+ * `revalidateTag` matches literally, with no wildcards, so events must list concrete tags. Pure functions with no server-only dependency, shared by Kanorio's server, its edge worker and the SDK
19
+ * (the SDK's copy is made by `pnpm --filter @kanorio/sdk gen`, and a contract test keeps the two identical).
20
+ */
21
+ export const DELIVERY_CACHE_TAGS_HEADER = "x-kanorio-cache-tags";
22
+ /** Maximum tags per response: Next.js caps a cache entry at 128, leaving room for the external front end's own tags */
23
+ export const DELIVERY_CACHE_TAG_LIMIT = 100;
24
+ /** Separator between a tag and its locale: `item:abc@en-US` */
25
+ export const CACHE_TAG_LOCALE_SEPARATOR = "@";
26
+ /** Namespace the SDK adds when handing tags to a framework (Next.js `revalidateTag`, `next.tags`), to avoid clashing with the site's own tags such as `pages` or `seo` */
27
+ export const DEFAULT_CACHE_TAG_PREFIX = "kanorio:";
28
+ /** The tag vocabulary; strings are only assembled here */
29
+ export const cacheTag = {
30
+ site: (siteId) => `site:${siteId}`,
31
+ locale: (locale) => `locale:${locale}`,
32
+ pages: () => "pages",
33
+ page: (pageId) => `page:${pageId}`,
34
+ globals: () => "globals",
35
+ header: (key) => `header:${key}`,
36
+ footer: () => "footer",
37
+ collections: () => "collections",
38
+ collection: (key) => `collection:${key}`,
39
+ /** Every single-item response of the collection: used when the field structure changes or a batch exceeds the limit */
40
+ collectionItems: (key) => `collection:${key}:items`,
41
+ item: (itemId) => `item:${itemId}`,
42
+ products: () => "products",
43
+ product: (productId) => `product:${productId}`,
44
+ form: (formId) => `form:${formId}`,
45
+ search: () => "search",
46
+ seo: () => "seo",
47
+ redirects: () => "redirects",
48
+ aiCrawlerRules: () => "ai-crawler-rules",
49
+ reviews: () => "reviews",
50
+ };
51
+ export function isSiteCacheTag(tag) {
52
+ return tag.startsWith("site:");
53
+ }
54
+ export function isLocaleCacheTag(tag) {
55
+ return tag.startsWith("locale:");
56
+ }
57
+ /** `item:abc` → `item:abc@en-US` */
58
+ export function localizeCacheTag(tag, locale) {
59
+ return `${tag}${CACHE_TAG_LOCALE_SEPARATOR}${locale}`;
60
+ }
61
+ function unique(tags) {
62
+ const out = [];
63
+ const seen = new Set();
64
+ for (const tag of tags) {
65
+ const trimmed = tag.trim();
66
+ if (!trimmed || seen.has(trimmed))
67
+ continue;
68
+ seen.add(trimmed);
69
+ out.push(trimmed);
70
+ }
71
+ return out;
72
+ }
73
+ /**
74
+ * The locale dimension of a response: the primary locale (`locale` is null) is left as is; a secondary locale gets the locale appended to every content and list tag (not to `site:`), plus `locale:{code}`.
75
+ * The edge calls this with the request's normalized locale code (omitted and explicitly primary are both null); the server only declares content dependencies.
76
+ */
77
+ export function localizeCacheTags(tags, locale) {
78
+ const base = unique(tags);
79
+ if (!locale)
80
+ return base;
81
+ const localized = base.filter((tag) => !isSiteCacheTag(tag) && !isLocaleCacheTag(tag)).map((tag) => localizeCacheTag(tag, locale));
82
+ return unique([...base, ...localized, cacheTag.locale(locale)]);
83
+ }
84
+ const NARROW_PREFIXES = ["item:", "page:", "product:"];
85
+ function isNarrowCacheTag(tag) {
86
+ return NARROW_PREFIXES.some((prefix) => tag.startsWith(prefix));
87
+ }
88
+ /** Over the limit, single-content tags are dropped first (list tags stay, since events send them anyway); if still over, only the first `limit` are kept */
89
+ export function capCacheTags(tags, limit = DELIVERY_CACHE_TAG_LIMIT) {
90
+ const all = unique(tags);
91
+ if (all.length <= limit)
92
+ return all;
93
+ const wide = all.filter((tag) => !isNarrowCacheTag(tag));
94
+ return wide.length <= limit ? wide : wide.slice(0, limit);
95
+ }
96
+ /** `X-Kanorio-Cache-Tags` is space-separated */
97
+ export function parseCacheTagsHeader(raw) {
98
+ if (!raw)
99
+ return [];
100
+ return unique(raw.split(/\s+/));
101
+ }
102
+ export function formatCacheTagsHeader(tags) {
103
+ return unique(tags).join(" ");
104
+ }
105
+ /** Adds the namespace before handing tags to a framework; an empty `prefix` leaves them as is */
106
+ export function prefixCacheTags(tags, prefix = DEFAULT_CACHE_TAG_PREFIX) {
107
+ return unique(tags).map((tag) => `${prefix}${tag}`);
108
+ }
109
+ export const responseCacheTags = {
110
+ site: (siteId) => [cacheTag.site(siteId), cacheTag.aiCrawlerRules()],
111
+ pages: (siteId) => [cacheTag.site(siteId), cacheTag.pages()],
112
+ page: (siteId, deps) => unique([
113
+ cacheTag.site(siteId),
114
+ cacheTag.page(deps.pageId),
115
+ ...(deps.ancestorIds ?? []).map((id) => cacheTag.page(id)),
116
+ ...(deps.headerKey || deps.withFooter ? [cacheTag.globals()] : []),
117
+ ...(deps.headerKey ? [cacheTag.header(deps.headerKey)] : []),
118
+ ...(deps.withFooter ? [cacheTag.footer()] : []),
119
+ ]),
120
+ header: (siteId, key) => [cacheTag.site(siteId), cacheTag.globals(), cacheTag.header(key)],
121
+ footer: (siteId) => [cacheTag.site(siteId), cacheTag.globals(), cacheTag.footer()],
122
+ collections: (siteId) => [cacheTag.site(siteId), cacheTag.collections()],
123
+ items: (siteId, collectionKey, deps = {}) => unique([cacheTag.site(siteId), cacheTag.collection(collectionKey), ...(deps.expandedCollectionKeys ?? []).map((key) => cacheTag.collection(key))]),
124
+ item: (siteId, collectionKey, itemId, deps = {}) => unique([
125
+ cacheTag.site(siteId),
126
+ cacheTag.collectionItems(collectionKey),
127
+ cacheTag.item(itemId),
128
+ ...(deps.expandedCollectionKeys ?? []).map((key) => cacheTag.collection(key)),
129
+ ...(deps.expandedItemIds ?? []).map((id) => cacheTag.item(id)),
130
+ ]),
131
+ products: (siteId) => [cacheTag.site(siteId), cacheTag.products()],
132
+ product: (siteId, productId) => [cacheTag.site(siteId), cacheTag.products(), cacheTag.product(productId)],
133
+ form: (siteId, formId) => [cacheTag.site(siteId), cacheTag.form(formId)],
134
+ search: (siteId) => [cacheTag.site(siteId), cacheTag.search()],
135
+ seo: (siteId, options = {}) => [cacheTag.site(siteId), cacheTag.seo(), ...(options.robots ? [cacheTag.aiCrawlerRules()] : [])],
136
+ feed: (siteId) => [cacheTag.site(siteId), cacheTag.collection("blog")],
137
+ redirects: (siteId) => [cacheTag.site(siteId), cacheTag.redirects()],
138
+ reviews: (siteId, productId) => [cacheTag.site(siteId), cacheTag.reviews(), ...(productId ? [cacheTag.product(productId)] : [])],
139
+ };
140
+ /** System collections: when an article-like record's translation changes, the collection item has changed */
141
+ const SYSTEM_COLLECTION_OF_ENTITY = {
142
+ post: "blog",
143
+ post_category: "blog_categories",
144
+ post_tag: "blog_tags",
145
+ author: "authors",
146
+ };
147
+ export const eventCacheTags = {
148
+ /** Full-site publish: pages, header and footer, redirects and SEO files may all change */
149
+ sitePublished: (siteId) => [cacheTag.site(siteId), cacheTag.pages(), cacheTag.globals(), cacheTag.redirects(), cacheTag.seo()],
150
+ /** A single page going live, updated, taken offline or deleted: `site:` is not sent, so other pages stay; a changed URL also sends `redirects` */
151
+ pageChanged: (input) => [cacheTag.pages(), cacheTag.page(input.pageId), cacheTag.seo(), cacheTag.search(), ...(input.renamed ? [cacheTag.redirects()] : [])],
152
+ itemChanged: (input) => [cacheTag.collection(input.collectionKey), cacheTag.item(input.itemId), cacheTag.seo(), cacheTag.search()],
153
+ /** Bulk: items are listed one by one when their tags fit; otherwise every single-item response of the collection is cleared (list tags are always sent) */
154
+ itemsBulkChanged: (input) => {
155
+ const wide = [cacheTag.collection(input.collectionKey), cacheTag.seo(), cacheTag.search()];
156
+ const narrow = input.itemIds.map((id) => cacheTag.item(id));
157
+ if (wide.length + narrow.length <= DELIVERY_CACHE_TAG_LIMIT)
158
+ return [...wide, ...narrow];
159
+ return [...wide, cacheTag.collectionItems(input.collectionKey)];
160
+ },
161
+ /** The field structure changed: the collection list, the item list and every single-item response of the collection (projected fields changed) */
162
+ schemaChanged: (input) => [cacheTag.collections(), cacheTag.collection(input.collectionKey), cacheTag.collectionItems(input.collectionKey)],
163
+ /** The locale set changed (enabled, disabled, removed, prefix, order, primary): the language switcher and hreflang are on every page */
164
+ localeChanged: (siteId) => [cacheTag.site(siteId)],
165
+ /** A full-site translation finished: every response in that locale */
166
+ translationJobCompleted: (locale) => [cacheTag.locale(locale)],
167
+ /**
168
+ * One record's translation in one locale went live or was deleted: only locale-specific tags are sent, so the caches of other locales and the primary locale stay.
169
+ * Site settings and site announcements frame the whole locale, hence `locale:{code}`; product options, categories and course outlines have no single product id, hence `products@{code}`.
170
+ */
171
+ translationChanged: (input) => {
172
+ const l = (tag) => localizeCacheTag(tag, input.locale);
173
+ switch (input.entityType) {
174
+ case "page":
175
+ return [l(cacheTag.pages()), l(cacheTag.page(input.entityId)), l(cacheTag.seo()), l(cacheTag.search())];
176
+ case "global_sections":
177
+ return [l(cacheTag.globals())];
178
+ case "site_settings":
179
+ case "top_bar_banner":
180
+ case "modal_announcement":
181
+ case "floating_widget":
182
+ return [cacheTag.locale(input.locale)];
183
+ case "post":
184
+ case "post_category":
185
+ case "post_tag":
186
+ case "author": {
187
+ const key = SYSTEM_COLLECTION_OF_ENTITY[input.entityType];
188
+ return [l(cacheTag.collection(key)), l(cacheTag.item(input.entityId)), ...(input.entityType === "post" ? [l(cacheTag.seo())] : []), l(cacheTag.search())];
189
+ }
190
+ case "product":
191
+ return [l(cacheTag.products()), l(cacheTag.product(input.entityId)), l(cacheTag.seo()), l(cacheTag.search())];
192
+ case "product_option":
193
+ case "pricing_tier":
194
+ case "store_settings":
195
+ case "product_category":
196
+ case "deliverable":
197
+ case "deliverable_unit":
198
+ return [l(cacheTag.products()), l(cacheTag.search())];
199
+ case "form":
200
+ return [l(cacheTag.form(input.entityId))];
201
+ case "collection_item":
202
+ return [
203
+ ...(input.collectionKey ? [l(cacheTag.collection(input.collectionKey))] : []),
204
+ l(cacheTag.item(input.entityId)),
205
+ l(cacheTag.seo()),
206
+ l(cacheTag.search()),
207
+ ];
208
+ default:
209
+ return [cacheTag.locale(input.locale)];
210
+ }
211
+ },
212
+ };