@kanorio/sdk 0.0.0-stage → 1.0.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 +116 -0
  7. package/dist/delivery.d.ts +35 -0
  8. package/dist/delivery.js +49 -0
  9. package/dist/edge.d.ts +104 -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 +2380 -0
  15. package/dist/generated/management.d.ts +38248 -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 +86 -0
  39. package/dist/shared/api/server-key.js +252 -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 +67 -0
  79. package/dist/shared/utils/redirect-matching.js +148 -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
+ * Headless SEO/AEO 衍生檔與 JSON-LD 輔助工具(階段 6/PR-4h):
3
+ * - `seoRewrites({ siteUrl, framework })`:回傳可直接展開進 `next.config` `rewrites()` 或 `astro.config` 的規則陣列/映射
4
+ * - `fetchDeliveryJsonLd({ siteUrl, path })`:抓取指定路徑的 Schema.org JSON-LD `@graph` 與安全轉義後的 `<script>` 字串
5
+ * - `fetchSitemapEntries({ siteUrl })`:`sitemap.xml` 的資料版,給自己組 sitemap 的前端合併用
6
+ * - `listingRobots(site, key)`:依 `/api/v1/site` 的 `listings` 決定列表頁的 robots 值
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 要求金鑰驗證檔可從 `https://{host}/{key}.txt` 取得;用 Next.js 的動態路徑
29
+ // source 一次涵蓋所有可能的金鑰值,不需要事先知道金鑰內容(內容由伺服器端比對、回應)。
30
+ // Astro 的靜態 source→destination 映射表達不了動態路徑,改以 `@kanorio/sdk/edge` 的
31
+ // `createKanorioMiddleware`(`features.indexNow`,預設啟用)在邊緣直接回應。
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
+ * Kanorio 管的網址清單(與 `/api/v1/seo/sitemap.xml` 同一份,資料格式)。
63
+ * 只有部分內容在 Kanorio 的站,在自己的 sitemap 產生器把這份清單和自己的網址合在一起:
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
+ * 回源失敗回 null,由呼叫端決定要不要只輸出自己的網址。
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
+ // 連不上、逾時或回的不是 JSON:呼叫端的 sitemap 仍要能輸出自己的網址
88
+ return null;
89
+ }
90
+ }
91
+ /**
92
+ * 列表頁(部落格首頁、文章分類頁、商店首頁…)該輸出的 robots 值,與 Kanorio 的 sitemap/IndexNow 同一套判斷:
93
+ * - `live` → `"index, follow"`
94
+ * - `empty`(還沒有內容)→ `"noindex, follow"`,頁面照常渲染
95
+ * - `off`(站主隱藏,或沒有在 externalListings 宣告)→ `null`:這頁不該對外提供,請回 404
96
+ *
97
+ * `site` 是 `GET /api/v1/site` 的回應。缺 `listings` 只會發生在升級前就快取的舊回應;SDK 端沒有內容
98
+ * 旗標可推導,退回 `live` 以維持升級前的行為,不是正式語意。
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
+ /** 多語網站一頁的 canonical 與 hreflang(`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_sa_…`, 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_sa_…`). 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_sa_…`, 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_sa_, 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
+ * Content Delivery API 的快取標籤(SSOT;ADR-0010 決策 13 修訂二)。
3
+ *
4
+ * 標籤記的是「這個回應用到了哪些內容」,事件送的是「這次哪些內容變了」;兩邊由這一份函式產生,
5
+ * `apps/main/__tests__/shared/api/delivery-cache-tags.test.ts` 的契約矩陣逐一檢查:該清的一定清到、不該清的一定碰不到。
6
+ *
7
+ * 分層(一個回應同時帶寬窄兩種標籤,與 CDN surrogate key 的慣例相同):
8
+ * - 整站 `site:{id}`:所有回應都帶;只有整站發布與語系集合變動(上線、下線、移除、改前綴、換主語系)的事件送它
9
+ * - 語系 `locale:{code}`:次語系的所有回應都帶;整站翻譯完成、網站設定譯文上線送它
10
+ * - 內容 `page:{id}`、`item:{id}`、`product:{id}`、`form:{id}`:所有語系的回應都帶;主語系內容上線的事件送它(未翻譯的欄位沿用主語系,所以所有語系一起清)
11
+ * - 內容+語系 `page:{id}@en-US`:只有該語系的回應帶;該語系的譯文上線時送它,其他語系不動
12
+ * - 列表 `pages`、`collection:{key}`、`products`(+語系):只有列表回應帶,不逐項帶(事件本來就會一起送列表標籤;Next.js 一筆快取最多 128 個標籤);
13
+ * 單筆回應不帶列表標籤,別的項目上線才不會清到它。`collection:{key}:items` 是該集合所有單筆回應(欄位結構變了要一起換)
14
+ * - 衍生 `search`、`seo`、`redirects`:搜尋、SEO 衍生檔、轉址表;會改變它們的內容事件一起送
15
+ *
16
+ * 標籤用語系碼不用網址前綴(前綴站主可以改);語系以 `@` 接在後面,與 `type:id` 的冒號分得開。
17
+ * `revalidateTag` 逐字比對、沒有萬用字元,所以事件必須列出具體標籤。純函式、無 server-only,main、邊緣 Worker 與 SDK 共用
18
+ * (SDK 的副本 `packages/sdk/src/cache-tags.ts` 由 `pnpm --filter @kanorio/sdk gen` 複製,契約測試鎖兩份相同)。
19
+ */
20
+ export declare const DELIVERY_CACHE_TAGS_HEADER = "x-kanorio-cache-tags";
21
+ /** 一個回應最多幾個標籤:Next.js 一筆快取上限 128,留餘裕給外部前端自己的標籤 */
22
+ export declare const DELIVERY_CACHE_TAG_LIMIT = 100;
23
+ /** 語系接在標籤後面的分隔符:`item:abc@en-US` */
24
+ export declare const CACHE_TAG_LOCALE_SEPARATOR = "@";
25
+ /** SDK 交給框架(Next.js `revalidateTag`、`next.tags`)時加的命名空間,避免與網站自己的 `pages`、`seo` 這類標籤撞名 */
26
+ export declare const DEFAULT_CACHE_TAG_PREFIX = "kanorio:";
27
+ /** 標籤字彙;只在這裡拼字串 */
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
+ /** 該集合所有單筆回應:欄位結構變更、整批超過上限時用 */
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
+ * 回應的語系維度:主語系(`locale` 為 null)原樣;次語系在每個內容與列表標籤後面接語系(`site:` 不接),再加 `locale:{code}`。
56
+ * 邊緣以請求正規化後的語系碼呼叫(省略與指定主語系都是 null),main 只需要說明內容依賴。
57
+ */
58
+ export declare function localizeCacheTags(tags: readonly string[], locale: string | null | undefined): string[];
59
+ /** 超過上限時先丟單筆內容的標籤(列表層的標籤留著,事件本來就會送列表標籤),仍超過就只留前 `limit` 個 */
60
+ export declare function capCacheTags(tags: readonly string[], limit?: number): string[];
61
+ /** `X-Kanorio-Cache-Tags` 以空白分隔 */
62
+ export declare function parseCacheTagsHeader(raw: string | null | undefined): string[];
63
+ export declare function formatCacheTagsHeader(tags: readonly string[]): string;
64
+ /** 交給框架前加命名空間;`prefix` 為空字串時原樣 */
65
+ export declare function prefixCacheTags(tags: readonly string[], prefix?: string): string[];
66
+ export interface PageResponseDeps {
67
+ pageId: string;
68
+ /** 麵包屑裡的祖先頁(標題跟著祖先頁變) */
69
+ ancestorIds?: readonly string[];
70
+ /** 頁面指派的頁首(`primary` 或自訂 key);頁面回應帶頁首資料時給 */
71
+ headerKey?: string | null;
72
+ /** 頁面回應帶頁尾資料時給 */
73
+ withFooter?: boolean;
74
+ }
75
+ export interface ItemsResponseDeps {
76
+ /** `expand` 展開的參照所屬的集合 key(作者、分類…):那些集合的項目改了,列表也要換 */
77
+ expandedCollectionKeys?: readonly string[];
78
+ }
79
+ export interface ItemResponseDeps extends ItemsResponseDeps {
80
+ /** `expand` 展開的參照項目 id */
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
+ /** 可翻譯的紀錄型別(與 `packages/shared/localization/translatable-fields.ts` 同一組字串;這裡不 import,SDK 的副本才能獨立) */
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
+ /** `collection_item` 所屬的集合 key(呼叫端查好帶進來) */
110
+ collectionKey?: string | null;
111
+ }
112
+ export declare const eventCacheTags: {
113
+ /** 整站發布:頁面、頁首頁尾、轉址、SEO 衍生檔都可能變 */
114
+ readonly sitePublished: (siteId: string) => string[];
115
+ /** 單頁上線、更新、下線、刪除:不送 `site:`,別的頁不動;改網址另送 `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
+ /** 批次:項目標籤放得下才逐一列;放不下就改清該集合所有單筆(列表標籤一定在) */
125
+ readonly itemsBulkChanged: (input: {
126
+ collectionKey: string;
127
+ itemIds: readonly string[];
128
+ }) => string[];
129
+ /** 欄位結構變了:集合清單、列表與該集合所有單筆(投影的欄位變了) */
130
+ readonly schemaChanged: (input: {
131
+ collectionKey: string;
132
+ }) => string[];
133
+ /** 語系集合變了(上線、下線、移除、改前綴、順序、換主語系):語言切換與 hreflang 在每一頁都有 */
134
+ readonly localeChanged: (siteId: string) => string[];
135
+ /** 整站翻譯完成:該語系所有回應 */
136
+ readonly translationJobCompleted: (locale: string) => string[];
137
+ /**
138
+ * 一筆紀錄在一個語系的譯文上線或刪除:只送帶語系的標籤,其他語系與主語系的快取不動。
139
+ * 網站設定與站上公告是整個語系的外框 → `locale:{code}`;商品的規格、分類、課程大綱沒有單一商品 id → `products@{code}`。
140
+ */
141
+ readonly translationChanged: (input: TranslationEventInput) => string[];
142
+ };
@@ -0,0 +1,212 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ /**
3
+ * Content Delivery API 的快取標籤(SSOT;ADR-0010 決策 13 修訂二)。
4
+ *
5
+ * 標籤記的是「這個回應用到了哪些內容」,事件送的是「這次哪些內容變了」;兩邊由這一份函式產生,
6
+ * `apps/main/__tests__/shared/api/delivery-cache-tags.test.ts` 的契約矩陣逐一檢查:該清的一定清到、不該清的一定碰不到。
7
+ *
8
+ * 分層(一個回應同時帶寬窄兩種標籤,與 CDN surrogate key 的慣例相同):
9
+ * - 整站 `site:{id}`:所有回應都帶;只有整站發布與語系集合變動(上線、下線、移除、改前綴、換主語系)的事件送它
10
+ * - 語系 `locale:{code}`:次語系的所有回應都帶;整站翻譯完成、網站設定譯文上線送它
11
+ * - 內容 `page:{id}`、`item:{id}`、`product:{id}`、`form:{id}`:所有語系的回應都帶;主語系內容上線的事件送它(未翻譯的欄位沿用主語系,所以所有語系一起清)
12
+ * - 內容+語系 `page:{id}@en-US`:只有該語系的回應帶;該語系的譯文上線時送它,其他語系不動
13
+ * - 列表 `pages`、`collection:{key}`、`products`(+語系):只有列表回應帶,不逐項帶(事件本來就會一起送列表標籤;Next.js 一筆快取最多 128 個標籤);
14
+ * 單筆回應不帶列表標籤,別的項目上線才不會清到它。`collection:{key}:items` 是該集合所有單筆回應(欄位結構變了要一起換)
15
+ * - 衍生 `search`、`seo`、`redirects`:搜尋、SEO 衍生檔、轉址表;會改變它們的內容事件一起送
16
+ *
17
+ * 標籤用語系碼不用網址前綴(前綴站主可以改);語系以 `@` 接在後面,與 `type:id` 的冒號分得開。
18
+ * `revalidateTag` 逐字比對、沒有萬用字元,所以事件必須列出具體標籤。純函式、無 server-only,main、邊緣 Worker 與 SDK 共用
19
+ * (SDK 的副本 `packages/sdk/src/cache-tags.ts` 由 `pnpm --filter @kanorio/sdk gen` 複製,契約測試鎖兩份相同)。
20
+ */
21
+ export const DELIVERY_CACHE_TAGS_HEADER = "x-kanorio-cache-tags";
22
+ /** 一個回應最多幾個標籤:Next.js 一筆快取上限 128,留餘裕給外部前端自己的標籤 */
23
+ export const DELIVERY_CACHE_TAG_LIMIT = 100;
24
+ /** 語系接在標籤後面的分隔符:`item:abc@en-US` */
25
+ export const CACHE_TAG_LOCALE_SEPARATOR = "@";
26
+ /** SDK 交給框架(Next.js `revalidateTag`、`next.tags`)時加的命名空間,避免與網站自己的 `pages`、`seo` 這類標籤撞名 */
27
+ export const DEFAULT_CACHE_TAG_PREFIX = "kanorio:";
28
+ /** 標籤字彙;只在這裡拼字串 */
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
+ /** 該集合所有單筆回應:欄位結構變更、整批超過上限時用 */
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
+ * 回應的語系維度:主語系(`locale` 為 null)原樣;次語系在每個內容與列表標籤後面接語系(`site:` 不接),再加 `locale:{code}`。
75
+ * 邊緣以請求正規化後的語系碼呼叫(省略與指定主語系都是 null),main 只需要說明內容依賴。
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
+ /** 超過上限時先丟單筆內容的標籤(列表層的標籤留著,事件本來就會送列表標籤),仍超過就只留前 `limit` 個 */
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` 以空白分隔 */
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
+ /** 交給框架前加命名空間;`prefix` 為空字串時原樣 */
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
+ /** 系統集合:文章類紀錄的譯文變了,等於該集合項目變了 */
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
+ /** 整站發布:頁面、頁首頁尾、轉址、SEO 衍生檔都可能變 */
149
+ sitePublished: (siteId) => [cacheTag.site(siteId), cacheTag.pages(), cacheTag.globals(), cacheTag.redirects(), cacheTag.seo()],
150
+ /** 單頁上線、更新、下線、刪除:不送 `site:`,別的頁不動;改網址另送 `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
+ /** 批次:項目標籤放得下才逐一列;放不下就改清該集合所有單筆(列表標籤一定在) */
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
+ /** 欄位結構變了:集合清單、列表與該集合所有單筆(投影的欄位變了) */
162
+ schemaChanged: (input) => [cacheTag.collections(), cacheTag.collection(input.collectionKey), cacheTag.collectionItems(input.collectionKey)],
163
+ /** 語系集合變了(上線、下線、移除、改前綴、順序、換主語系):語言切換與 hreflang 在每一頁都有 */
164
+ localeChanged: (siteId) => [cacheTag.site(siteId)],
165
+ /** 整站翻譯完成:該語系所有回應 */
166
+ translationJobCompleted: (locale) => [cacheTag.locale(locale)],
167
+ /**
168
+ * 一筆紀錄在一個語系的譯文上線或刪除:只送帶語系的標籤,其他語系與主語系的快取不動。
169
+ * 網站設定與站上公告是整個語系的外框 → `locale:{code}`;商品的規格、分類、課程大綱沒有單一商品 id → `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
+ };