@kanorio/sdk 1.0.0 → 1.2.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 (81) hide show
  1. package/README.md +41 -2
  2. package/dist/customer-oauth.d.ts +21 -21
  3. package/dist/customer-oauth.js +12 -12
  4. package/dist/customer.d.ts +22 -22
  5. package/dist/customer.js +20 -11
  6. package/dist/delivery.d.ts +9 -9
  7. package/dist/delivery.js +6 -6
  8. package/dist/edge.d.ts +25 -21
  9. package/dist/edge.js +36 -20
  10. package/dist/forms.d.ts +33 -14
  11. package/dist/forms.js +20 -14
  12. package/dist/generated/delivery.d.ts +564 -13
  13. package/dist/generated/management.d.ts +790 -81
  14. package/dist/http.d.ts +13 -13
  15. package/dist/http.js +8 -8
  16. package/dist/image.d.ts +77 -0
  17. package/dist/image.js +78 -0
  18. package/dist/index.d.ts +2 -1
  19. package/dist/index.js +4 -3
  20. package/dist/locales.d.ts +22 -22
  21. package/dist/locales.js +12 -12
  22. package/dist/management.d.ts +5 -5
  23. package/dist/management.js +3 -3
  24. package/dist/next.d.ts +66 -0
  25. package/dist/next.js +58 -0
  26. package/dist/paginate.d.ts +3 -3
  27. package/dist/paginate.js +3 -3
  28. package/dist/preview.d.ts +13 -13
  29. package/dist/preview.js +11 -11
  30. package/dist/protection.d.ts +18 -18
  31. package/dist/protection.js +11 -11
  32. package/dist/revalidate.d.ts +22 -22
  33. package/dist/revalidate.js +14 -14
  34. package/dist/seo.d.ts +137 -21
  35. package/dist/seo.js +113 -21
  36. package/dist/server-key.d.ts +2 -2
  37. package/dist/server-key.js +2 -2
  38. package/dist/shared/api/delivery/cache-tags.d.ts +41 -39
  39. package/dist/shared/api/delivery/cache-tags.js +36 -34
  40. package/dist/shared/api/server-key.d.ts +32 -28
  41. package/dist/shared/api/server-key.js +41 -33
  42. package/dist/shared/business-registry/attribution.d.ts +5 -5
  43. package/dist/shared/business-registry/attribution.js +4 -4
  44. package/dist/shared/business-registry/define.d.ts +1 -1
  45. package/dist/shared/business-registry/define.js +1 -1
  46. package/dist/shared/business-registry/formats/eu-vat.js +4 -4
  47. package/dist/shared/business-registry/formats/hk-br.d.ts +2 -2
  48. package/dist/shared/business-registry/formats/hk-br.js +4 -4
  49. package/dist/shared/business-registry/formats/jp-trn.d.ts +3 -3
  50. package/dist/shared/business-registry/formats/jp-trn.js +4 -4
  51. package/dist/shared/business-registry/formats/kr-brn.d.ts +2 -2
  52. package/dist/shared/business-registry/formats/kr-brn.js +3 -3
  53. package/dist/shared/business-registry/formats/my.d.ts +3 -3
  54. package/dist/shared/business-registry/formats/my.js +4 -4
  55. package/dist/shared/business-registry/formats/sg-uen.js +4 -4
  56. package/dist/shared/business-registry/formats/tw-vat.d.ts +5 -5
  57. package/dist/shared/business-registry/formats/tw-vat.js +6 -6
  58. package/dist/shared/business-registry/index.js +1 -1
  59. package/dist/shared/business-registry/lookup-wire.d.ts +9 -9
  60. package/dist/shared/business-registry/lookup-wire.js +4 -4
  61. package/dist/shared/business-registry/normalize.d.ts +3 -3
  62. package/dist/shared/business-registry/normalize.js +4 -4
  63. package/dist/shared/business-registry/registry.d.ts +9 -9
  64. package/dist/shared/business-registry/registry.js +13 -13
  65. package/dist/shared/business-registry/types.d.ts +20 -20
  66. package/dist/shared/business-registry/types.js +6 -6
  67. package/dist/shared/localization/locale-path.d.ts +18 -18
  68. package/dist/shared/localization/locale-path.js +18 -18
  69. package/dist/shared/localization/request-locale.d.ts +16 -16
  70. package/dist/shared/localization/request-locale.js +13 -13
  71. package/dist/shared/seo/alternates.d.ts +26 -26
  72. package/dist/shared/seo/alternates.js +18 -18
  73. package/dist/shared/types/forms-logic.d.ts +28 -28
  74. package/dist/shared/types/forms-logic.js +27 -27
  75. package/dist/shared/types/number-input.d.ts +2 -2
  76. package/dist/shared/types/number-input.js +3 -3
  77. package/dist/shared/utils/redirect-matching.d.ts +33 -24
  78. package/dist/shared/utils/redirect-matching.js +73 -40
  79. package/dist/typed.d.ts +5 -5
  80. package/dist/typed.js +3 -3
  81. package/package.json +15 -10
package/dist/seo.d.ts CHANGED
@@ -1,12 +1,14 @@
1
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 值
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
+ * - `seoMetadata(input, options)`: the `<head>` values of a post, a category, tag or author page, or a page, by the rules the hosted site uses
8
+ * - `shareImageOf(input)`: the image for `og:image`, already resolved by Kanorio
7
9
  */
8
10
  import type { components as DeliveryComponents } from "./generated/delivery.js";
9
- import { buildAlternates, languageSwitcher } from "./locales.js";
11
+ import { buildAlternates, languageSwitcher, type SiteLocaleMeta } from "./locales.js";
10
12
  export type ListingState = DeliveryComponents["schemas"]["ListingState"];
11
13
  export type ListingKey = keyof NonNullable<DeliveryComponents["schemas"]["SiteMeta"]["listings"]>;
12
14
  export type SeoRewriteFramework = "next" | "astro";
@@ -15,7 +17,7 @@ export interface NextSeoRewriteRule {
15
17
  destination: string;
16
18
  }
17
19
  export interface SeoRewritesOptions {
18
- /** 站台系統網址或自訂網域(例如 `https://s-k4m9x2p7q8w3.kanorio.com`) */
20
+ /** The site's system URL or custom domain (for example `https://s-k4m9x2p7q8w3.kanorio.com`) */
19
21
  siteUrl: string;
20
22
  framework: SeoRewriteFramework;
21
23
  }
@@ -30,7 +32,7 @@ export declare function seoRewrites(options: {
30
32
  export declare function seoRewrites(options: SeoRewritesOptions): NextSeoRewriteRule[] | Record<string, string>;
31
33
  export interface DeliveryJsonLdResult {
32
34
  jsonLd: Record<string, unknown>;
33
- /** 已將 `<`、`>`、`&` 轉義為 Unicode escape 的 JSON 字串,可安全放入 `<script type="application/ld+json">` */
35
+ /** A JSON string with `<`, `>` and `&` escaped as Unicode escapes, safe inside `<script type="application/ld+json">` */
34
36
  scriptJson: string;
35
37
  cacheTags: string[];
36
38
  }
@@ -39,16 +41,16 @@ export declare function fetchDeliveryJsonLd(options: {
39
41
  path?: string;
40
42
  fetch?: typeof globalThis.fetch;
41
43
  }): Promise<DeliveryJsonLdResult | null>;
42
- /** 一筆 sitemap 項目(`GET /api/v1/seo/sitemap`) */
44
+ /** One sitemap entry (`GET /api/v1/seo/sitemap`) */
43
45
  export interface SitemapEntry {
44
46
  url: string;
45
- /** 站內路徑,以 `/` 開頭 */
47
+ /** In-site path, starting with `/` */
46
48
  path: string;
47
49
  /** YYYY-MM-DD */
48
50
  lastModified: string;
49
51
  changeFrequency: string;
50
52
  priority: number;
51
- /** 這個網址是什麼:page、blog-post、product、collection-item… */
53
+ /** What the URL is: page, blog-post, product, collection-item, ... */
52
54
  kind: string;
53
55
  locale?: string;
54
56
  alternates?: Array<{
@@ -62,35 +64,144 @@ export interface SitemapEntriesResult {
62
64
  cacheTags: string[];
63
65
  }
64
66
  /**
65
- * Kanorio 管的網址清單(與 `/api/v1/seo/sitemap.xml` 同一份,資料格式)。
66
- * 只有部分內容在 Kanorio 的站,在自己的 sitemap 產生器把這份清單和自己的網址合在一起:
67
+ * The URLs Kanorio manages (the same list as `/api/v1/seo/sitemap.xml`, as data).
68
+ * A site with only part of its content on Kanorio merges this list with its own URLs in its sitemap generator:
67
69
  *
68
70
  * ```ts
69
- * // app/sitemap.ts(Next.js)
71
+ * // app/sitemap.ts (Next.js)
70
72
  * export default async function sitemap() {
71
73
  * const kanorio = await fetchSitemapEntries({ siteUrl });
72
74
  * return [...ownUrls, ...(kanorio?.urls ?? []).map((u) => ({ url: u.url, lastModified: u.lastModified }))];
73
75
  * }
74
76
  * ```
75
77
  *
76
- * 回源失敗回 null,由呼叫端決定要不要只輸出自己的網址。
78
+ * Returns null when the origin fetch fails, so the caller can decide whether to output only its own URLs.
77
79
  */
78
80
  export declare function fetchSitemapEntries(options: {
79
81
  siteUrl: string;
80
82
  fetch?: typeof globalThis.fetch;
81
83
  }): Promise<SitemapEntriesResult | null>;
82
84
  /**
83
- * 列表頁(部落格首頁、文章分類頁、商店首頁…)該輸出的 robots 值,與 Kanorio 的 sitemap/IndexNow 同一套判斷:
85
+ * 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:
84
86
  * - `live` → `"index, follow"`
85
- * - `empty`(還沒有內容)→ `"noindex, follow"`,頁面照常渲染
86
- * - `off`(站主隱藏,或沒有在 externalListings 宣告)→ `null`:這頁不該對外提供,請回 404
87
+ * - `empty` (no content yet): `"noindex, follow"`, and the page renders as usual
88
+ * - `off` (hidden by the owner, or not declared in externalListings): `null`; the page should not be served, so answer 404
87
89
  *
88
- * `site` 是 `GET /api/v1/site` 的回應。缺 `listings` 只會發生在升級前就快取的舊回應;SDK 端沒有內容
89
- * 旗標可推導,退回 `live` 以維持升級前的行為,不是正式語意。
90
+ * `site` is the `GET /api/v1/site` response. `listings` is missing only in responses cached before the upgrade; the SDK has no content
91
+ * flags to derive it from, so it falls back to `live` to keep the earlier behavior. That fallback is not a defined meaning.
90
92
  */
91
93
  export declare function listingRobots(site: {
92
94
  listings?: Partial<Record<ListingKey, ListingState>> | null;
93
95
  }, key: ListingKey): "index, follow" | "noindex, follow" | null;
96
+ /** The SEO fields of a blog post, category, tag or author (`fieldData.seo` of a collection item) */
97
+ export interface ItemSeoFields {
98
+ title?: string | null;
99
+ description?: string | null;
100
+ keywords?: readonly string[] | null;
101
+ ogTitle?: string | null;
102
+ ogDescription?: string | null;
103
+ ogImageAlt?: string | null;
104
+ canonical?: string | null;
105
+ robotsIndex?: string | null;
106
+ robotsFollow?: string | null;
107
+ twitterCard?: string | null;
108
+ }
109
+ /** The SEO fields of a page (`page.seo` of `GET /pages/{slug}`). `ogImage` is already the URL to use: the chosen share image, cropped, or the generated title card */
110
+ export interface PageSeoFields {
111
+ seoTitle?: string | null;
112
+ seoDescription?: string | null;
113
+ seoKeywords?: readonly string[] | null;
114
+ ogTitle?: string | null;
115
+ ogDescription?: string | null;
116
+ ogImage?: string | null;
117
+ ogImageAlt?: string | null;
118
+ canonicalUrl?: string | null;
119
+ robotsIndex?: string | null;
120
+ robotsFollow?: string | null;
121
+ twitterCard?: string | null;
122
+ }
123
+ interface LocalizedResponseFields {
124
+ /** Path of the page on the site, in the locale of the response */
125
+ path?: string | null;
126
+ resolvedLocale?: string | null;
127
+ availableLocales?: readonly string[] | null;
128
+ localePaths?: Readonly<Record<string, string>> | null;
129
+ }
130
+ /** A collection item from the Delivery API that has a page of its own: a blog post, a category, a tag or an author */
131
+ export interface SeoItemInput extends LocalizedResponseFields {
132
+ fieldData: {
133
+ title?: unknown;
134
+ name?: unknown;
135
+ excerpt?: unknown;
136
+ seo?: ItemSeoFields | null;
137
+ share_image?: {
138
+ url: string;
139
+ alt?: string | null;
140
+ } | null;
141
+ [key: string]: unknown;
142
+ };
143
+ }
144
+ /** A page from `GET /pages/{slug}` */
145
+ export interface SeoPageInput extends LocalizedResponseFields {
146
+ title?: string | null;
147
+ seo?: PageSeoFields | null;
148
+ }
149
+ export type SeoInput = SeoItemInput | SeoPageInput;
150
+ export interface SeoMetadataOptions {
151
+ /** Your front end's public URL, without a trailing slash (`https://www.example.com`). Without it `canonical` is a path and there is no hreflang */
152
+ siteUrl?: string;
153
+ /** The `GET /api/v1/site` response. Needed on multilingual sites for hreflang and the canonical of a translated page */
154
+ site?: SiteLocaleMeta | null;
155
+ /** The locale in the URL of this request (`locale` from `resolveRequestLocale`); defaults to the locale the content was served in */
156
+ requestLocale?: string | null;
157
+ /**
158
+ * The page's path in the primary locale's space (no locale prefix), when the response does not carry one:
159
+ * an item of a custom collection without `pathTemplate`, or a page you route yourself
160
+ */
161
+ path?: string;
162
+ }
163
+ export interface ShareImage {
164
+ url: string;
165
+ /** Alt text for the image; null when neither the author nor the image has one */
166
+ alt: string | null;
167
+ }
168
+ /** Everything a page's `<head>` needs, as plain values. `toNextMetadata` in `@kanorio/sdk/next` turns it into a Next.js `Metadata` object */
169
+ export interface SeoMetadata {
170
+ /** The page's own title, without the site name: add the site name in your layout */
171
+ title: string | null;
172
+ description: string | null;
173
+ keywords: string[] | null;
174
+ /** The canonical URL (absolute when `siteUrl` is given, otherwise a path); null when the response carries no path and none was passed */
175
+ canonical: string | null;
176
+ /** hreflang to URL, including `x-default`; empty on single-language sites, on pages without a translation, and without `siteUrl` and `site` */
177
+ languages: Record<string, string>;
178
+ robots: {
179
+ index: boolean;
180
+ follow: boolean;
181
+ };
182
+ openGraph: {
183
+ title: string | null;
184
+ description: string | null;
185
+ image: ShareImage | null;
186
+ };
187
+ twitterCard: "summary" | "summary_large_image";
188
+ }
189
+ /**
190
+ * The image to use as `og:image`, already resolved by Kanorio: the share image the author chose (cropped to 1200x630 the way they framed it),
191
+ * else, for a post, its cover, the generated title card or the first image in the body. Same image the hosted site uses.
192
+ * Reads `fieldData.share_image` of a collection item, or `seo.ogImage` of a page. Returns `null` when there is none.
193
+ */
194
+ export declare function shareImageOf(input: SeoInput): ShareImage | null;
195
+ /**
196
+ * The `<head>` values of a blog post, a category, tag or author page, or a page, by the same rules the hosted site uses:
197
+ * - title and description: what the author wrote under SEO, else the item's own title and excerpt
198
+ * - canonical: the address the author set, on the primary locale only (a translated page always points to itself); otherwise the page's own URL
199
+ * - hreflang: every locale that has a published translation (needs `siteUrl` and `site`)
200
+ * - robots: `noindex` and `nofollow` when the author set them
201
+ * - share image: `shareImageOf(input)`; its alt text falls back to the title
202
+ * - share title and description: what the author wrote for sharing, else the SEO title and description
203
+ */
204
+ export declare function seoMetadata(input: SeoInput, options?: SeoMetadataOptions): SeoMetadata;
94
205
  export interface SeoHelpers {
95
206
  rewrites(options: {
96
207
  framework: "next";
@@ -113,8 +224,13 @@ export declare const seo: {
113
224
  readonly jsonLd: typeof fetchDeliveryJsonLd;
114
225
  readonly sitemapEntries: typeof fetchSitemapEntries;
115
226
  readonly listingRobots: typeof listingRobots;
116
- /** 多語網站一頁的 canonical 與 hreflang(`locales.alternates`) */
227
+ /** The `<head>` values of a post, a category, tag or author page, or a page */
228
+ readonly metadata: typeof seoMetadata;
229
+ /** The image for `og:image`, already resolved by Kanorio */
230
+ readonly shareImage: typeof shareImageOf;
231
+ /** A page's canonical and hreflang on multilingual sites (`locales.alternates`) */
117
232
  readonly alternates: typeof buildAlternates;
118
233
  readonly languageSwitcher: typeof languageSwitcher;
119
234
  readonly create: typeof createSeoHelpers;
120
235
  };
236
+ export {};
package/dist/seo.js CHANGED
@@ -1,12 +1,14 @@
1
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 值
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
+ * - `seoMetadata(input, options)`: the `<head>` values of a post, a category, tag or author page, or a page, by the rules the hosted site uses
8
+ * - `shareImageOf(input)`: the image for `og:image`, already resolved by Kanorio
7
9
  */
8
10
  import { deliveryBaseUrl, parseDeliveryCacheTags } from "./delivery.js";
9
- import { buildAlternates, languageSwitcher } from "./locales.js";
11
+ import { buildAlternates, languageSwitcher, requestLocaleOf } from "./locales.js";
10
12
  const SEO_REWRITE_PATHS = [
11
13
  { source: "/sitemap.xml", apiPath: "/seo/sitemap.xml" },
12
14
  { source: "/robots.txt", apiPath: "/seo/robots.txt" },
@@ -25,10 +27,10 @@ export function seoRewrites(options) {
25
27
  if (options.framework === "astro") {
26
28
  return Object.fromEntries(rules.map((r) => [r.source, r.destination]));
27
29
  }
28
- // IndexNow 要求金鑰驗證檔可從 `https://{host}/{key}.txt` 取得;用 Next.js 的動態路徑
29
- // source 一次涵蓋所有可能的金鑰值,不需要事先知道金鑰內容(內容由伺服器端比對、回應)。
30
- // Astro 的靜態 source→destination 映射表達不了動態路徑,改以 `@kanorio/sdk/edge` 的
31
- // `createKanorioMiddleware`(`features.indexNow`,預設啟用)在邊緣直接回應。
30
+ // IndexNow requires the key verification file at `https://{host}/{key}.txt`; a dynamic Next.js path
31
+ // source covers every possible key value, without knowing the key in advance (the server matches it and answers).
32
+ // Astro's static source-to-destination map cannot express a dynamic path; there, `createKanorioMiddleware`
33
+ // from `@kanorio/sdk/edge` (`features.indexNow`, on by default) answers at the edge.
32
34
  rules.push({
33
35
  source: "/:key([a-f0-9]{32}).txt",
34
36
  destination: `${base}/seo/indexnow-key.txt`,
@@ -59,18 +61,18 @@ export async function fetchDeliveryJsonLd(options) {
59
61
  };
60
62
  }
61
63
  /**
62
- * Kanorio 管的網址清單(與 `/api/v1/seo/sitemap.xml` 同一份,資料格式)。
63
- * 只有部分內容在 Kanorio 的站,在自己的 sitemap 產生器把這份清單和自己的網址合在一起:
64
+ * The URLs Kanorio manages (the same list as `/api/v1/seo/sitemap.xml`, as data).
65
+ * A site with only part of its content on Kanorio merges this list with its own URLs in its sitemap generator:
64
66
  *
65
67
  * ```ts
66
- * // app/sitemap.ts(Next.js)
68
+ * // app/sitemap.ts (Next.js)
67
69
  * export default async function sitemap() {
68
70
  * const kanorio = await fetchSitemapEntries({ siteUrl });
69
71
  * return [...ownUrls, ...(kanorio?.urls ?? []).map((u) => ({ url: u.url, lastModified: u.lastModified }))];
70
72
  * }
71
73
  * ```
72
74
  *
73
- * 回源失敗回 null,由呼叫端決定要不要只輸出自己的網址。
75
+ * Returns null when the origin fetch fails, so the caller can decide whether to output only its own URLs.
74
76
  */
75
77
  export async function fetchSitemapEntries(options) {
76
78
  const fetchImpl = options.fetch ?? globalThis.fetch;
@@ -84,18 +86,18 @@ export async function fetchSitemapEntries(options) {
84
86
  return { siteUrl: body.siteUrl, urls: body.urls, cacheTags: parseDeliveryCacheTags(res.headers) };
85
87
  }
86
88
  catch {
87
- // 連不上、逾時或回的不是 JSON:呼叫端的 sitemap 仍要能輸出自己的網址
89
+ // Unreachable, timed out or not JSON: the caller's sitemap must still be able to output its own URLs
88
90
  return null;
89
91
  }
90
92
  }
91
93
  /**
92
- * 列表頁(部落格首頁、文章分類頁、商店首頁…)該輸出的 robots 值,與 Kanorio 的 sitemap/IndexNow 同一套判斷:
94
+ * 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
95
  * - `live` → `"index, follow"`
94
- * - `empty`(還沒有內容)→ `"noindex, follow"`,頁面照常渲染
95
- * - `off`(站主隱藏,或沒有在 externalListings 宣告)→ `null`:這頁不該對外提供,請回 404
96
+ * - `empty` (no content yet): `"noindex, follow"`, and the page renders as usual
97
+ * - `off` (hidden by the owner, or not declared in externalListings): `null`; the page should not be served, so answer 404
96
98
  *
97
- * `site` 是 `GET /api/v1/site` 的回應。缺 `listings` 只會發生在升級前就快取的舊回應;SDK 端沒有內容
98
- * 旗標可推導,退回 `live` 以維持升級前的行為,不是正式語意。
99
+ * `site` is the `GET /api/v1/site` response. `listings` is missing only in responses cached before the upgrade; the SDK has no content
100
+ * flags to derive it from, so it falls back to `live` to keep the earlier behavior. That fallback is not a defined meaning.
99
101
  */
100
102
  export function listingRobots(site, key) {
101
103
  const state = site.listings?.[key] ?? "live";
@@ -103,6 +105,92 @@ export function listingRobots(site, key) {
103
105
  return null;
104
106
  return state === "live" ? "index, follow" : "noindex, follow";
105
107
  }
108
+ const text = (value) => (typeof value === "string" && value.trim() ? value.trim() : null);
109
+ function isItemInput(input) {
110
+ return typeof input.fieldData === "object" && input.fieldData !== null;
111
+ }
112
+ /**
113
+ * The image to use as `og:image`, already resolved by Kanorio: the share image the author chose (cropped to 1200x630 the way they framed it),
114
+ * else, for a post, its cover, the generated title card or the first image in the body. Same image the hosted site uses.
115
+ * Reads `fieldData.share_image` of a collection item, or `seo.ogImage` of a page. Returns `null` when there is none.
116
+ */
117
+ export function shareImageOf(input) {
118
+ if (isItemInput(input)) {
119
+ const image = input.fieldData.share_image;
120
+ const url = text(image?.url);
121
+ return url ? { url, alt: text(image?.alt) ?? text(input.fieldData.seo?.ogImageAlt) } : null;
122
+ }
123
+ const url = text(input.seo?.ogImage);
124
+ return url ? { url, alt: text(input.seo?.ogImageAlt) } : null;
125
+ }
126
+ /**
127
+ * The `<head>` values of a blog post, a category, tag or author page, or a page, by the same rules the hosted site uses:
128
+ * - title and description: what the author wrote under SEO, else the item's own title and excerpt
129
+ * - canonical: the address the author set, on the primary locale only (a translated page always points to itself); otherwise the page's own URL
130
+ * - hreflang: every locale that has a published translation (needs `siteUrl` and `site`)
131
+ * - robots: `noindex` and `nofollow` when the author set them
132
+ * - share image: `shareImageOf(input)`; its alt text falls back to the title
133
+ * - share title and description: what the author wrote for sharing, else the SEO title and description
134
+ */
135
+ export function seoMetadata(input, options = {}) {
136
+ const item = isItemInput(input);
137
+ const itemSeo = item ? input.fieldData.seo ?? {} : {};
138
+ const pageSeo = item ? {} : input.seo ?? {};
139
+ const ownTitle = item ? text(input.fieldData.title) ?? text(input.fieldData.name) : text(input.title);
140
+ const title = (item ? text(itemSeo.title) : text(pageSeo.seoTitle)) ?? ownTitle;
141
+ const description = (item ? text(itemSeo.description) ?? text(input.fieldData.excerpt) : text(pageSeo.seoDescription)) ?? null;
142
+ const keywordList = item ? itemSeo.keywords : pageSeo.seoKeywords;
143
+ const keywords = keywordList && keywordList.length > 0 ? [...keywordList] : null;
144
+ const shared = item ? itemSeo : pageSeo;
145
+ const customCanonical = item ? text(itemSeo.canonical) : text(pageSeo.canonicalUrl);
146
+ const site = options.site ?? null;
147
+ const siteUrl = options.siteUrl ? options.siteUrl.replace(/\/+$/, "") : null;
148
+ const primaryLocale = site?.primaryLocale ?? null;
149
+ const resolvedLocale = input.resolvedLocale ?? null;
150
+ // The author's canonical is an address for the primary-locale page: a translated page ignores it
151
+ const servedInPrimary = !primaryLocale || !resolvedLocale || resolvedLocale === primaryLocale;
152
+ // The path in the primary locale's space: given by the caller, else from `localePaths`, else the response path with its locale prefix removed
153
+ const responsePath = text(input.path);
154
+ const primaryPath = text(options.path) ??
155
+ (primaryLocale ? text(input.localePaths?.[primaryLocale]) : null) ??
156
+ (responsePath ? (site ? requestLocaleOf(responsePath, site).pathname : responsePath) : null);
157
+ let canonical = null;
158
+ let languages = {};
159
+ if (primaryPath && siteUrl && site) {
160
+ const alternates = buildAlternates({
161
+ siteUrl,
162
+ site,
163
+ path: primaryPath,
164
+ requestLocale: options.requestLocale ?? resolvedLocale,
165
+ resolvedLocale,
166
+ availableLocales: input.availableLocales ?? null,
167
+ localePaths: input.localePaths ?? null,
168
+ });
169
+ canonical = alternates.canonical;
170
+ languages = alternates.languages;
171
+ }
172
+ else if (responsePath ?? primaryPath) {
173
+ const path = (responsePath ?? primaryPath);
174
+ canonical = siteUrl ? `${siteUrl}${path === "/" ? "" : path}` : path;
175
+ }
176
+ if (customCanonical && servedInPrimary)
177
+ canonical = customCanonical;
178
+ const image = shareImageOf(input);
179
+ return {
180
+ title,
181
+ description,
182
+ keywords,
183
+ canonical,
184
+ languages,
185
+ robots: { index: text(shared.robotsIndex) !== "noindex", follow: text(shared.robotsFollow) !== "nofollow" },
186
+ openGraph: {
187
+ title: text(shared.ogTitle) ?? title,
188
+ description: text(shared.ogDescription) ?? description,
189
+ image: image ? { url: image.url, alt: image.alt ?? ownTitle } : null,
190
+ },
191
+ twitterCard: text(shared.twitterCard) === "summary" ? "summary" : "summary_large_image",
192
+ };
193
+ }
106
194
  export function createSeoHelpers(options) {
107
195
  function rewrites(opts) {
108
196
  return seoRewrites({ siteUrl: options.siteUrl, framework: opts.framework });
@@ -118,7 +206,11 @@ export const seo = {
118
206
  jsonLd: fetchDeliveryJsonLd,
119
207
  sitemapEntries: fetchSitemapEntries,
120
208
  listingRobots,
121
- /** 多語網站一頁的 canonical 與 hreflang(`locales.alternates`) */
209
+ /** The `<head>` values of a post, a category, tag or author page, or a page */
210
+ metadata: seoMetadata,
211
+ /** The image for `og:image`, already resolved by Kanorio */
212
+ shareImage: shareImageOf,
213
+ /** A page's canonical and hreflang on multilingual sites (`locales.alternates`) */
122
214
  alternates: buildAlternates,
123
215
  languageSwitcher,
124
216
  create: createSeoHelpers,
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Server key support shared by every client in this package.
3
3
  *
4
- * A server key (`knr_sa_…`, created under Site settings > Developer with the purpose "Website server") lets
4
+ * A server key (`knr_sk_…`, created under Site settings > Developer with the purpose "Website server") lets
5
5
  * **your server** call the visitor-facing write endpoints on behalf of a visitor: submit a form, exchange a
6
6
  * customer sign-in code, report an AI crawler hit. Without it, Kanorio's edge treats server-to-server writes
7
7
  * as automated traffic and answers with a challenge page.
@@ -17,7 +17,7 @@ export { SERVER_KEY_HEADER, SERVER_KEY_VISITOR_IP_HEADER };
17
17
  export type VisitorIpSource = string | null | undefined | (() => string | null | undefined | Promise<string | null | undefined>);
18
18
  export interface ServerKeyOptions {
19
19
  /**
20
- * Server key (`knr_sa_…`). Server-side only: read it from an environment variable such as
20
+ * Server key (`knr_sk_…`). Server-side only: read it from an environment variable such as
21
21
  * `KANORIO_SERVER_KEY`. Required when your server writes on behalf of a visitor.
22
22
  */
23
23
  serverKey?: string;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Server key support shared by every client in this package.
3
3
  *
4
- * A server key (`knr_sa_…`, created under Site settings > Developer with the purpose "Website server") lets
4
+ * A server key (`knr_sk_…`, created under Site settings > Developer with the purpose "Website server") lets
5
5
  * **your server** call the visitor-facing write endpoints on behalf of a visitor: submit a form, exchange a
6
6
  * customer sign-in code, report an AI crawler hit. Without it, Kanorio's edge treats server-to-server writes
7
7
  * as automated traffic and answers with a challenge page.
@@ -98,6 +98,6 @@ export function edgeChallengeMessage(hasServerKey) {
98
98
  return "Kanorio's edge challenged this request. In a browser this usually clears after the visitor passes the check; retry the request.";
99
99
  }
100
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."
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
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
103
  }
@@ -1,30 +1,30 @@
1
1
  /**
2
- * Content Delivery API 的快取標籤(SSOT;ADR-0010 決策 13 修訂二)。
2
+ * Cache tags of the Content Delivery API (the single source of truth).
3
3
  *
4
- * 標籤記的是「這個回應用到了哪些內容」,事件送的是「這次哪些內容變了」;兩邊由這一份函式產生,
5
- * `apps/main/__tests__/shared/api/delivery-cache-tags.test.ts` 的契約矩陣逐一檢查:該清的一定清到、不該清的一定碰不到。
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
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 衍生檔、轉址表;會改變它們的內容事件一起送
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
15
  *
16
- * 標籤用語系碼不用網址前綴(前綴站主可以改);語系以 `@` 接在後面,與 `type:id` 的冒號分得開。
17
- * `revalidateTag` 逐字比對、沒有萬用字元,所以事件必須列出具體標籤。純函式、無 server-only,main、邊緣 Worker 與 SDK 共用
18
- * (SDK 的副本 `packages/sdk/src/cache-tags.ts` 由 `pnpm --filter @kanorio/sdk gen` 複製,契約測試鎖兩份相同)。
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
19
  */
20
20
  export declare const DELIVERY_CACHE_TAGS_HEADER = "x-kanorio-cache-tags";
21
- /** 一個回應最多幾個標籤:Next.js 一筆快取上限 128,留餘裕給外部前端自己的標籤 */
21
+ /** Maximum tags per response: Next.js caps a cache entry at 128, leaving room for the external front end's own tags */
22
22
  export declare const DELIVERY_CACHE_TAG_LIMIT = 100;
23
- /** 語系接在標籤後面的分隔符:`item:abc@en-US` */
23
+ /** Separator between a tag and its locale: `item:abc@en-US` */
24
24
  export declare const CACHE_TAG_LOCALE_SEPARATOR = "@";
25
- /** SDK 交給框架(Next.js `revalidateTag`、`next.tags`)時加的命名空間,避免與網站自己的 `pages`、`seo` 這類標籤撞名 */
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
26
  export declare const DEFAULT_CACHE_TAG_PREFIX = "kanorio:";
27
- /** 標籤字彙;只在這裡拼字串 */
27
+ /** The tag vocabulary; strings are only assembled here */
28
28
  export declare const cacheTag: {
29
29
  readonly site: (siteId: string) => string;
30
30
  readonly locale: (locale: string) => string;
@@ -35,7 +35,7 @@ export declare const cacheTag: {
35
35
  readonly footer: () => string;
36
36
  readonly collections: () => string;
37
37
  readonly collection: (key: string) => string;
38
- /** 該集合所有單筆回應:欄位結構變更、整批超過上限時用 */
38
+ /** Every single-item response of the collection: used when the field structure changes or a batch exceeds the limit */
39
39
  readonly collectionItems: (key: string) => string;
40
40
  readonly item: (itemId: string) => string;
41
41
  readonly products: () => string;
@@ -52,32 +52,32 @@ export declare function isLocaleCacheTag(tag: string): boolean;
52
52
  /** `item:abc` → `item:abc@en-US` */
53
53
  export declare function localizeCacheTag(tag: string, locale: string): string;
54
54
  /**
55
- * 回應的語系維度:主語系(`locale` 為 null)原樣;次語系在每個內容與列表標籤後面接語系(`site:` 不接),再加 `locale:{code}`。
56
- * 邊緣以請求正規化後的語系碼呼叫(省略與指定主語系都是 null),main 只需要說明內容依賴。
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
57
  */
58
58
  export declare function localizeCacheTags(tags: readonly string[], locale: string | null | undefined): string[];
59
- /** 超過上限時先丟單筆內容的標籤(列表層的標籤留著,事件本來就會送列表標籤),仍超過就只留前 `limit` 個 */
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
60
  export declare function capCacheTags(tags: readonly string[], limit?: number): string[];
61
- /** `X-Kanorio-Cache-Tags` 以空白分隔 */
61
+ /** `X-Kanorio-Cache-Tags` is space-separated */
62
62
  export declare function parseCacheTagsHeader(raw: string | null | undefined): string[];
63
63
  export declare function formatCacheTagsHeader(tags: readonly string[]): string;
64
- /** 交給框架前加命名空間;`prefix` 為空字串時原樣 */
64
+ /** Adds the namespace before handing tags to a framework; an empty `prefix` leaves them as is */
65
65
  export declare function prefixCacheTags(tags: readonly string[], prefix?: string): string[];
66
66
  export interface PageResponseDeps {
67
67
  pageId: string;
68
- /** 麵包屑裡的祖先頁(標題跟著祖先頁變) */
68
+ /** Ancestor pages in the breadcrumb (titles follow the ancestors) */
69
69
  ancestorIds?: readonly string[];
70
- /** 頁面指派的頁首(`primary` 或自訂 key);頁面回應帶頁首資料時給 */
70
+ /** The header assigned to the page (`primary` or a custom key); given when the page response includes header data */
71
71
  headerKey?: string | null;
72
- /** 頁面回應帶頁尾資料時給 */
72
+ /** Given when the page response includes footer data */
73
73
  withFooter?: boolean;
74
74
  }
75
75
  export interface ItemsResponseDeps {
76
- /** `expand` 展開的參照所屬的集合 key(作者、分類…):那些集合的項目改了,列表也要換 */
76
+ /** Collection keys of references expanded with `expand` (authors, categories, ...): when items in those collections change, the list must change too */
77
77
  expandedCollectionKeys?: readonly string[];
78
78
  }
79
79
  export interface ItemResponseDeps extends ItemsResponseDeps {
80
- /** `expand` 展開的參照項目 id */
80
+ /** Ids of the reference items expanded with `expand` */
81
81
  expandedItemIds?: readonly string[];
82
82
  }
83
83
  export declare const responseCacheTags: {
@@ -100,19 +100,19 @@ export declare const responseCacheTags: {
100
100
  readonly redirects: (siteId: string) => string[];
101
101
  readonly reviews: (siteId: string, productId: string | null) => string[];
102
102
  };
103
- /** 可翻譯的紀錄型別(與 `packages/shared/localization/translatable-fields.ts` 同一組字串;這裡不 import,SDK 的副本才能獨立) */
103
+ /** Translatable record types (the same strings as Kanorio's translatable-fields registry; not imported here, so the SDK's copy stands alone) */
104
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
105
  export interface TranslationEventInput {
106
106
  entityType: TranslationCacheScope;
107
107
  entityId: string;
108
108
  locale: string;
109
- /** `collection_item` 所屬的集合 key(呼叫端查好帶進來) */
109
+ /** The collection key a `collection_item` belongs to (looked up by the caller) */
110
110
  collectionKey?: string | null;
111
111
  }
112
112
  export declare const eventCacheTags: {
113
- /** 整站發布:頁面、頁首頁尾、轉址、SEO 衍生檔都可能變 */
113
+ /** Full-site publish: pages, header and footer, redirects and SEO files may all change */
114
114
  readonly sitePublished: (siteId: string) => string[];
115
- /** 單頁上線、更新、下線、刪除:不送 `site:`,別的頁不動;改網址另送 `redirects` */
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
116
  readonly pageChanged: (input: {
117
117
  pageId: string;
118
118
  renamed?: boolean;
@@ -121,22 +121,24 @@ export declare const eventCacheTags: {
121
121
  collectionKey: string;
122
122
  itemId: string;
123
123
  }) => string[];
124
- /** 批次:項目標籤放得下才逐一列;放不下就改清該集合所有單筆(列表標籤一定在) */
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
125
  readonly itemsBulkChanged: (input: {
126
126
  collectionKey: string;
127
127
  itemIds: readonly string[];
128
128
  }) => string[];
129
- /** 欄位結構變了:集合清單、列表與該集合所有單筆(投影的欄位變了) */
129
+ /** The field structure changed: the collection list, the item list and every single-item response of the collection (projected fields changed) */
130
130
  readonly schemaChanged: (input: {
131
131
  collectionKey: string;
132
132
  }) => string[];
133
- /** 語系集合變了(上線、下線、移除、改前綴、順序、換主語系):語言切換與 hreflang 在每一頁都有 */
133
+ /** A form's definition changed, it was paused or resumed, or it moved to or from the trash: the form's own response in every locale */
134
+ readonly formChanged: (formId: string) => string[];
135
+ /** The locale set changed (enabled, disabled, removed, prefix, order, primary): the language switcher and hreflang are on every page */
134
136
  readonly localeChanged: (siteId: string) => string[];
135
- /** 整站翻譯完成:該語系所有回應 */
137
+ /** A full-site translation finished: every response in that locale */
136
138
  readonly translationJobCompleted: (locale: string) => string[];
137
139
  /**
138
- * 一筆紀錄在一個語系的譯文上線或刪除:只送帶語系的標籤,其他語系與主語系的快取不動。
139
- * 網站設定與站上公告是整個語系的外框 → `locale:{code}`;商品的規格、分類、課程大綱沒有單一商品 id → `products@{code}`。
140
+ * 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.
141
+ * 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
142
  */
141
143
  readonly translationChanged: (input: TranslationEventInput) => string[];
142
144
  };