@kanorio/sdk 1.0.0 → 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 (76) hide show
  1. package/README.md +2 -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 +19 -19
  10. package/dist/forms.d.ts +13 -13
  11. package/dist/forms.js +13 -13
  12. package/dist/generated/delivery.d.ts +35 -7
  13. package/dist/generated/management.d.ts +111 -26
  14. package/dist/http.d.ts +13 -13
  15. package/dist/http.js +8 -8
  16. package/dist/index.js +2 -2
  17. package/dist/locales.d.ts +22 -22
  18. package/dist/locales.js +12 -12
  19. package/dist/management.d.ts +5 -5
  20. package/dist/management.js +3 -3
  21. package/dist/paginate.d.ts +3 -3
  22. package/dist/paginate.js +3 -3
  23. package/dist/preview.d.ts +13 -13
  24. package/dist/preview.js +11 -11
  25. package/dist/protection.d.ts +18 -18
  26. package/dist/protection.js +11 -11
  27. package/dist/revalidate.d.ts +22 -22
  28. package/dist/revalidate.js +14 -14
  29. package/dist/seo.d.ts +20 -20
  30. package/dist/seo.js +20 -20
  31. package/dist/server-key.d.ts +2 -2
  32. package/dist/server-key.js +2 -2
  33. package/dist/shared/api/delivery/cache-tags.d.ts +39 -39
  34. package/dist/shared/api/delivery/cache-tags.js +34 -34
  35. package/dist/shared/api/server-key.d.ts +32 -28
  36. package/dist/shared/api/server-key.js +41 -33
  37. package/dist/shared/business-registry/attribution.d.ts +5 -5
  38. package/dist/shared/business-registry/attribution.js +4 -4
  39. package/dist/shared/business-registry/define.d.ts +1 -1
  40. package/dist/shared/business-registry/define.js +1 -1
  41. package/dist/shared/business-registry/formats/eu-vat.js +4 -4
  42. package/dist/shared/business-registry/formats/hk-br.d.ts +2 -2
  43. package/dist/shared/business-registry/formats/hk-br.js +4 -4
  44. package/dist/shared/business-registry/formats/jp-trn.d.ts +3 -3
  45. package/dist/shared/business-registry/formats/jp-trn.js +4 -4
  46. package/dist/shared/business-registry/formats/kr-brn.d.ts +2 -2
  47. package/dist/shared/business-registry/formats/kr-brn.js +3 -3
  48. package/dist/shared/business-registry/formats/my.d.ts +3 -3
  49. package/dist/shared/business-registry/formats/my.js +4 -4
  50. package/dist/shared/business-registry/formats/sg-uen.js +4 -4
  51. package/dist/shared/business-registry/formats/tw-vat.d.ts +5 -5
  52. package/dist/shared/business-registry/formats/tw-vat.js +6 -6
  53. package/dist/shared/business-registry/index.js +1 -1
  54. package/dist/shared/business-registry/lookup-wire.d.ts +9 -9
  55. package/dist/shared/business-registry/lookup-wire.js +4 -4
  56. package/dist/shared/business-registry/normalize.d.ts +3 -3
  57. package/dist/shared/business-registry/normalize.js +4 -4
  58. package/dist/shared/business-registry/registry.d.ts +9 -9
  59. package/dist/shared/business-registry/registry.js +13 -13
  60. package/dist/shared/business-registry/types.d.ts +20 -20
  61. package/dist/shared/business-registry/types.js +6 -6
  62. package/dist/shared/localization/locale-path.d.ts +18 -18
  63. package/dist/shared/localization/locale-path.js +18 -18
  64. package/dist/shared/localization/request-locale.d.ts +16 -16
  65. package/dist/shared/localization/request-locale.js +13 -13
  66. package/dist/shared/seo/alternates.d.ts +26 -26
  67. package/dist/shared/seo/alternates.js +18 -18
  68. package/dist/shared/types/forms-logic.d.ts +28 -28
  69. package/dist/shared/types/forms-logic.js +27 -27
  70. package/dist/shared/types/number-input.d.ts +2 -2
  71. package/dist/shared/types/number-input.js +3 -3
  72. package/dist/shared/utils/redirect-matching.d.ts +33 -24
  73. package/dist/shared/utils/redirect-matching.js +73 -40
  74. package/dist/typed.d.ts +5 -5
  75. package/dist/typed.js +3 -3
  76. package/package.json +10 -10
package/README.md CHANGED
@@ -30,7 +30,7 @@ import { createFormsHelpers, visitorIpFromRequest } from "@kanorio/sdk";
30
30
 
31
31
  const forms = createFormsHelpers({
32
32
  siteUrl: "https://example.com",
33
- serverKey: process.env.KANORIO_SERVER_KEY, // knr_sa_…, a service account of type "Website server"
33
+ serverKey: process.env.KANORIO_SERVER_KEY, // knr_sk_…, a service account of type "Website server"
34
34
  visitorIp: visitorIpFromRequest(request),
35
35
  });
36
36
  ```
@@ -56,7 +56,7 @@ Type names follow Stripe (`tw_vat`, `hk_br`, `jp_trn`, `kr_brn`, `eu_vat`, `sg_u
56
56
 
57
57
  ## Compatibility
58
58
 
59
- - ESM only. Use `import`; from CommonJS code, use `await import("@kanorio/sdk")`. `require()` is not supported.
59
+ - ES modules only. Use `import`. CommonJS code can `require("@kanorio/sdk")` on Node.js 20.19 / 22.12 or later (this is how `next.config.ts` loads it); on older versions use `await import("@kanorio/sdk")`.
60
60
  - Node.js 20 or later for server-side use.
61
61
  - Within `1.x`, methods, options and response fields are only added. Removing or changing one is a new major version.
62
62
 
@@ -1,10 +1,10 @@
1
1
  /**
2
- * 託管登入頁的 OAuth 2.1 授權碼+PKCE(customers ADR-0001 修訂三第 9 條):自建前端不畫登入畫面,
3
- * 把顧客送到 Kanorio 託管的 `/account/login`,回來後用授權碼換 `knr_cat_` Bearer(與 `<kanorio-account>` 直打同一種 token)。
2
+ * OAuth 2.1 authorization code + PKCE for the hosted sign-in page: your own front end does not draw a sign-in screen.
3
+ * It sends the customer to Kanorio's hosted `/account/login`, and on return exchanges the authorization code for a `knr_cat_` bearer token (the same token `<kanorio-account>` uses).
4
4
  *
5
- * 瀏覽器端:`startHostedCustomerLogin()` 產 PKCE 與 state 存 sessionStorage、整頁導去登入頁;
6
- * 回到 `redirectUri` 後 `completeHostedCustomerLogin()` 讀 `?code&state`、對 state、換 token、清掉 query。
7
- * 伺服器端(或要自己管 token 時):`exchangeHostedLoginCode()`/`refreshCustomerToken()`/`revokeCustomerToken()`。
5
+ * In the browser: `startHostedCustomerLogin()` creates the PKCE pair and state, stores them in sessionStorage and navigates to the sign-in page;
6
+ * back on `redirectUri`, `completeHostedCustomerLogin()` reads `?code&state`, checks the state, exchanges the token and clears the query.
7
+ * On a server (or when you manage tokens yourself): `exchangeHostedLoginCode()`, `refreshCustomerToken()` and `revokeCustomerToken()`.
8
8
  */
9
9
  import type { ServerKeyOptions } from "./server-key.js";
10
10
  export interface HostedLoginGrant {
@@ -16,54 +16,54 @@ export interface HostedLoginGrant {
16
16
  refreshTokenExpiresIn: number;
17
17
  contactId: string;
18
18
  }
19
- /** PKCE:verifier 隨機 43–128 字元、challenge=BASE64URL(SHA-256(verifier))(RFC 7636;OAuth 2.1 只允許 S256) */
19
+ /** PKCE: a random verifier of 43 to 128 characters; challenge = BASE64URL(SHA-256(verifier)) (RFC 7636; OAuth 2.1 allows S256 only) */
20
20
  export declare function createPkcePair(): Promise<{
21
21
  verifier: string;
22
22
  challenge: string;
23
23
  method: "S256";
24
24
  }>;
25
25
  export interface HostedLoginUrlParams {
26
- /** 例如 `https://demo.kanorio.com`:託管登入頁所在的站台網址 */
26
+ /** For example `https://demo.kanorio.com`: the site URL that serves the hosted sign-in page */
27
27
  siteUrl: string;
28
- /** 網站 id(`GET /site` 的 `id`);OAuth 的 client_id */
28
+ /** Site id (`id` from `GET /site`); the OAuth client_id */
29
29
  clientId: string;
30
- /** 登入後回來的網址:https、origin 要在網站設定「允許的來源」裡 */
30
+ /** Where to return after sign-in: https, and its origin must be in the site's allowed origins */
31
31
  redirectUri: string;
32
32
  codeChallenge: string;
33
33
  state: string;
34
- /** 登入頁的語系路徑根(多語網站,例如 `/en`);省略為主語系 */
34
+ /** Locale path root of the sign-in page (multilingual sites, for example `/en`); omit for the primary locale */
35
35
  localeRoot?: string;
36
36
  }
37
37
  export declare function buildHostedLoginUrl(params: HostedLoginUrlParams): string;
38
38
  export interface StartHostedLoginOptions {
39
39
  siteUrl: string;
40
40
  clientId: string;
41
- /** 省略時是目前這頁(去掉 code/state) */
41
+ /** Defaults to the current page (without code and state) */
42
42
  redirectUri?: string;
43
43
  localeRoot?: string;
44
- /** 存 PKCE verifier 與 state 的地方;預設 sessionStorage(同一分頁回來才讀得到) */
44
+ /** Where the PKCE verifier and state are kept; sessionStorage by default (readable only when returning in the same tab) */
45
45
  storage?: Storage;
46
- /** 自行導頁(例如用 router);預設 `window.location.assign` */
46
+ /** Navigate yourself (with a router, for example); `window.location.assign` by default */
47
47
  navigate?: (url: string) => void;
48
48
  }
49
- /** 第一步:產 PKCE 與 state、記下來、把顧客送去託管登入頁 */
49
+ /** Step one: create the PKCE pair and state, remember them, and send the customer to the hosted sign-in page */
50
50
  export declare function startHostedCustomerLogin(options: StartHostedLoginOptions): Promise<void>;
51
51
  export interface CompleteHostedLoginOptions {
52
52
  siteUrl: string;
53
53
  clientId: string;
54
54
  storage?: Storage;
55
- /** 換到 token 後存進 `localStorage["kanorio.customer.token"]`(其他 Elements 讀得到);預設 true */
55
+ /** Store the token in `localStorage["kanorio.customer.token"]` after the exchange (other Elements read it); true by default */
56
56
  storeToken?: boolean;
57
- /** 從網址拿掉 code/state(不留在歷史與 Referer);預設 true */
57
+ /** Remove code and state from the URL (so they stay out of history and Referer); true by default */
58
58
  cleanUrl?: boolean;
59
59
  }
60
60
  /**
61
- * 第二步:回到 redirectUri 後呼叫。網址沒有 `code` 回 null;state 對不上或換 token 失敗丟錯。
61
+ * Step two: call this back on redirectUri. Returns null when the URL has no `code`; throws when the state does not match or the token exchange fails.
62
62
  */
63
63
  export declare function completeHostedCustomerLogin(options: CompleteHostedLoginOptions): Promise<HostedLoginGrant | null>;
64
64
  /**
65
- * 授權碼換 token(任何環境)。在**伺服器**上呼叫時要帶 `serverKey`(與 `visitorIp`):
66
- * 伺服器對伺服器的寫入沒有主機金鑰會被邊緣擋下。瀏覽器端不要帶。
65
+ * Exchanges an authorization code for tokens (any environment). When called on a **server**, pass `serverKey` (and `visitorIp`):
66
+ * a server-to-server write without a server key is blocked at the edge. Do not pass it in the browser.
67
67
  */
68
68
  export declare function exchangeHostedLoginCode(params: {
69
69
  siteUrl: string;
@@ -72,13 +72,13 @@ export declare function exchangeHostedLoginCode(params: {
72
72
  codeVerifier: string;
73
73
  redirectUri: string;
74
74
  } & ServerKeyOptions): Promise<HostedLoginGrant>;
75
- /** 輪替:拿新的 access/refresh token;舊的 refresh token 立即作廢,請把回傳的兩把都存起來 */
75
+ /** Rotation: get a new access and refresh token; the old refresh token is revoked immediately, so store both returned tokens */
76
76
  export declare function refreshCustomerToken(params: {
77
77
  siteUrl: string;
78
78
  clientId: string;
79
79
  refreshToken: string;
80
80
  } & ServerKeyOptions): Promise<HostedLoginGrant>;
81
- /** 撤銷 access 或 refresh token(整個 session 結束) */
81
+ /** Revokes an access or refresh token (ends the whole session) */
82
82
  export declare function revokeCustomerToken(params: {
83
83
  siteUrl: string;
84
84
  token: string;
@@ -1,10 +1,10 @@
1
1
  /**
2
- * 託管登入頁的 OAuth 2.1 授權碼+PKCE(customers ADR-0001 修訂三第 9 條):自建前端不畫登入畫面,
3
- * 把顧客送到 Kanorio 託管的 `/account/login`,回來後用授權碼換 `knr_cat_` Bearer(與 `<kanorio-account>` 直打同一種 token)。
2
+ * OAuth 2.1 authorization code + PKCE for the hosted sign-in page: your own front end does not draw a sign-in screen.
3
+ * It sends the customer to Kanorio's hosted `/account/login`, and on return exchanges the authorization code for a `knr_cat_` bearer token (the same token `<kanorio-account>` uses).
4
4
  *
5
- * 瀏覽器端:`startHostedCustomerLogin()` 產 PKCE 與 state 存 sessionStorage、整頁導去登入頁;
6
- * 回到 `redirectUri` 後 `completeHostedCustomerLogin()` 讀 `?code&state`、對 state、換 token、清掉 query。
7
- * 伺服器端(或要自己管 token 時):`exchangeHostedLoginCode()`/`refreshCustomerToken()`/`revokeCustomerToken()`。
5
+ * In the browser: `startHostedCustomerLogin()` creates the PKCE pair and state, stores them in sessionStorage and navigates to the sign-in page;
6
+ * back on `redirectUri`, `completeHostedCustomerLogin()` reads `?code&state`, checks the state, exchanges the token and clears the query.
7
+ * On a server (or when you manage tokens yourself): `exchangeHostedLoginCode()`, `refreshCustomerToken()` and `revokeCustomerToken()`.
8
8
  */
9
9
  import { createCustomerClient, writeStoredCustomerToken } from "./customer.js";
10
10
  const PKCE_STORAGE_KEY = "kanorio.customer.pkce";
@@ -30,7 +30,7 @@ function randomString(bytes = 32) {
30
30
  crypto.getRandomValues(buffer);
31
31
  return base64url(buffer);
32
32
  }
33
- /** PKCE:verifier 隨機 43–128 字元、challenge=BASE64URL(SHA-256(verifier))(RFC 7636;OAuth 2.1 只允許 S256) */
33
+ /** PKCE: a random verifier of 43 to 128 characters; challenge = BASE64URL(SHA-256(verifier)) (RFC 7636; OAuth 2.1 allows S256 only) */
34
34
  export async function createPkcePair() {
35
35
  const verifier = randomString(32);
36
36
  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
@@ -53,7 +53,7 @@ function currentRedirectUri() {
53
53
  url.hash = "";
54
54
  return url.toString();
55
55
  }
56
- /** 第一步:產 PKCE 與 state、記下來、把顧客送去託管登入頁 */
56
+ /** Step one: create the PKCE pair and state, remember them, and send the customer to the hosted sign-in page */
57
57
  export async function startHostedCustomerLogin(options) {
58
58
  const storage = options.storage ?? sessionStorage;
59
59
  const redirectUri = options.redirectUri ?? currentRedirectUri();
@@ -64,7 +64,7 @@ export async function startHostedCustomerLogin(options) {
64
64
  (options.navigate ?? ((target) => window.location.assign(target)))(url);
65
65
  }
66
66
  /**
67
- * 第二步:回到 redirectUri 後呼叫。網址沒有 `code` 回 null;state 對不上或換 token 失敗丟錯。
67
+ * Step two: call this back on redirectUri. Returns null when the URL has no `code`; throws when the state does not match or the token exchange fails.
68
68
  */
69
69
  export async function completeHostedCustomerLogin(options) {
70
70
  const url = new URL(window.location.href);
@@ -89,8 +89,8 @@ export async function completeHostedCustomerLogin(options) {
89
89
  return grant;
90
90
  }
91
91
  /**
92
- * 授權碼換 token(任何環境)。在**伺服器**上呼叫時要帶 `serverKey`(與 `visitorIp`):
93
- * 伺服器對伺服器的寫入沒有主機金鑰會被邊緣擋下。瀏覽器端不要帶。
92
+ * Exchanges an authorization code for tokens (any environment). When called on a **server**, pass `serverKey` (and `visitorIp`):
93
+ * a server-to-server write without a server key is blocked at the edge. Do not pass it in the browser.
94
94
  */
95
95
  export async function exchangeHostedLoginCode(params) {
96
96
  const client = createCustomerClient({ siteUrl: params.siteUrl, serverKey: params.serverKey, visitorIp: params.visitorIp });
@@ -99,13 +99,13 @@ export async function exchangeHostedLoginCode(params) {
99
99
  }));
100
100
  return toGrant(wire);
101
101
  }
102
- /** 輪替:拿新的 access/refresh token;舊的 refresh token 立即作廢,請把回傳的兩把都存起來 */
102
+ /** Rotation: get a new access and refresh token; the old refresh token is revoked immediately, so store both returned tokens */
103
103
  export async function refreshCustomerToken(params) {
104
104
  const client = createCustomerClient({ siteUrl: params.siteUrl, serverKey: params.serverKey, visitorIp: params.visitorIp });
105
105
  const wire = (await client.post("/auth/oauth2/token", { body: { grant_type: "refresh_token", refresh_token: params.refreshToken, client_id: params.clientId } }));
106
106
  return toGrant(wire);
107
107
  }
108
- /** 撤銷 access 或 refresh token(整個 session 結束) */
108
+ /** Revokes an access or refresh token (ends the whole session) */
109
109
  export async function revokeCustomerToken(params) {
110
110
  const client = createCustomerClient({ siteUrl: params.siteUrl, serverKey: params.serverKey, visitorIp: params.visitorIp });
111
111
  await client.post("/auth/oauth2/revoke", { body: { token: params.token, ...(params.tokenTypeHint ? { token_type_hint: params.tokenTypeHint } : {}) } });
@@ -1,9 +1,9 @@
1
1
  /**
2
- * Customer API(`https://{site}/api/v1/customer`,Bearer = 顧客 session token;ADR-0003)。
3
- * 瀏覽器可直打(CORS 依站台 allowedOrigins)。型別由 `packages/shared/openapi/customer.json` 產生;成功回應不含 ok、錯誤是統一信封。
2
+ * Customer API (`https://{site}/api/v1/customer`, Bearer = the customer's session token).
3
+ * Browsers can call it directly (CORS follows the site's allowed origins). Types are generated from the Customer API's OpenAPI document; successful responses carry no `ok`, and errors use the shared envelope.
4
4
  *
5
- * `createCustomerClient` 之外另提供 `createCustomerContentClient`:符合 `@kanorio/shared` 的
6
- * `CustomerContentClient` 介面(`openUnit`/`reportProgress`/`submitQuiz`/`getCertificate`),給 `@kanorio/elements` 的 `<kanorio-unit>` 注入。
5
+ * Besides `createCustomerClient` there is `createCustomerContentClient`, which implements the
6
+ * content client interface (`openUnit`, `reportProgress`, `submitQuiz`, `getCertificate`) that `@kanorio/elements` injects into `<kanorio-unit>`.
7
7
  */
8
8
  import type { paths as CustomerPaths } from "./generated/customer.js";
9
9
  import { type HttpClientOptions } from "./http.js";
@@ -12,24 +12,24 @@ export type { CustomerPaths };
12
12
  export type CustomerClient = TypedClient<CustomerPaths>;
13
13
  export type CustomerTokenSource = string | null | undefined | (() => string | null | undefined | Promise<string | null | undefined>);
14
14
  export interface CustomerClientOptions extends Omit<HttpClientOptions, "baseUrl" | "headers"> {
15
- /** 例如 `https://demo.kanorio.com` */
15
+ /** For example `https://demo.kanorio.com` */
16
16
  siteUrl: string;
17
- /** 顧客 Bearer;匿名端點(challenge/verify)可為 null */
17
+ /** The customer's bearer token; may be null for anonymous endpoints (challenge, verify) */
18
18
  token?: CustomerTokenSource;
19
19
  headers?: HeadersInit;
20
20
  /**
21
- * 內容語系(多語網站;ADR-0010 決策 13):開啟單元時帶 `locale`,標題依它。省略=顧客自己的語系(Contact.locale)或主語系。
22
- * 只影響 `createCustomerContentClient`;典型用法是 Elements 的 Provider 把頁面語系傳進來。
21
+ * Content locale (multilingual sites): sent as `locale` when opening a unit, and titles follow it. Omit to use the customer's own locale or the primary locale.
22
+ * Only affects `createCustomerContentClient`; typically the Elements provider passes the page locale in.
23
23
  */
24
24
  locale?: string | null;
25
25
  }
26
26
  export declare function customerBaseUrl(siteUrl: string): string;
27
27
  export declare function createCustomerClient(options: CustomerClientOptions): CustomerClient;
28
- /** 瀏覽器端保存 Bearer 的預設位置(`<kanorio-login>` 寫入、其他元件讀取) */
28
+ /** Default place the browser keeps the bearer token (`<kanorio-login>` writes it, other components read it) */
29
29
  export declare const CUSTOMER_TOKEN_STORAGE_KEY = "kanorio.customer.token";
30
30
  export declare function readStoredCustomerToken(storage?: Storage | undefined): string | null;
31
31
  export declare function writeStoredCustomerToken(token: string | null, storage?: Storage | undefined): void;
32
- /** `captions` 筆(媒體 ADR 0011):字幕軌,一語系一筆;`source` 是 AI 產生或站主上傳、`edited` 代表站主改過字。預設不顯示,學員按 CC 才開 */
32
+ /** One `captions` entry: a caption track, one per locale; `source` says AI-generated or uploaded by the owner, and `edited` means the owner changed the text. Hidden by default until the learner turns captions on */
33
33
  type OpenUnitRendition = {
34
34
  kind: "original" | "mp4" | "hls" | "poster" | "thumbnails" | "captions" | "chapters";
35
35
  url: string;
@@ -41,7 +41,7 @@ type OpenUnitRendition = {
41
41
  source?: "ai" | "upload" | "translation";
42
42
  edited?: boolean;
43
43
  };
44
- /** `renditions`/`poster`/`thumbnails`/`streaming`:影片的串流來源(有 `hls` 就播它、`url` 是原檔);`expiresIn` 依影片長度 */
44
+ /** `renditions`, `poster`, `thumbnails`, `streaming`: the video's streaming sources (play `hls` when present; `url` is the original file); `expiresIn` depends on the video's length */
45
45
  type OpenUnitOk = {
46
46
  ok: true;
47
47
  mode: "read" | "download";
@@ -61,7 +61,7 @@ type OpenUnitFail = {
61
61
  code: string;
62
62
  availableAt?: string;
63
63
  };
64
- /** 一筆回報:位置與片長之外,帶 sessionId+segments 伺服器才記觀看紀錄(播放次數、時數、留存);見 Customer API 文件 */
64
+ /** One report: besides position and duration, the server only records watch history (plays, hours, retention) when sessionId and segments are sent; see the Customer API docs */
65
65
  type ProgressReportItem = {
66
66
  positionSeconds?: number;
67
67
  durationSeconds?: number;
@@ -79,9 +79,9 @@ type ProgressReportItem = {
79
79
  type ProgressOk = {
80
80
  ok: true;
81
81
  unit: "not_started" | "in-progress" | "completed";
82
- /** 影音單元看過的比例 0–100;沒片長或沒段落資料為 null;舊版 server 沒有 */
82
+ /** Share of an audio or video unit that was watched, 0 to 100; null without a duration or segment data; absent on older servers */
83
83
  unitCoveredPercent?: number | null;
84
- /** `lite` 心跳且單元沒有剛完成時為 null */
84
+ /** null for a `lite` heartbeat when the unit was not just completed */
85
85
  deliverable: {
86
86
  id: string;
87
87
  percent: number;
@@ -96,7 +96,7 @@ type ProgressFail = {
96
96
  };
97
97
  type QuizSubmitOk = {
98
98
  ok: true;
99
- /** graded:及格才完成;practice:交卷即完成、不計及格。舊版 server 沒有這個欄位 */
99
+ /** graded: passing completes the unit; practice: submitting completes it and no pass mark applies. Absent on older servers */
100
100
  mode?: "graded" | "practice";
101
101
  score: number;
102
102
  correct: number;
@@ -109,7 +109,7 @@ type QuizSubmitOk = {
109
109
  reveal: {
110
110
  questions: Array<{
111
111
  id: string;
112
- correctOptionIds: string[]; /** 簡答/數字題的接受答案;舊版 server 沒有 */
112
+ correctOptionIds: string[]; /** Accepted answers for short-answer and number questions; absent on older servers */
113
113
  acceptedAnswers?: string[];
114
114
  explanation: string | null;
115
115
  }>;
@@ -156,21 +156,21 @@ export interface CustomerContentClientLike {
156
156
  }): Promise<OpenUnitOk | OpenUnitFail>;
157
157
  reportProgress(input: {
158
158
  unitId: string;
159
- reports: ProgressReportItem[]; /** 心跳:單元沒因這次回報完成時不算交付物層 */
159
+ reports: ProgressReportItem[]; /** Heartbeat: skips the deliverable-level result unless this report completed the unit */
160
160
  lite?: boolean;
161
161
  }): Promise<ProgressOk | ProgressFail>;
162
- /** 交測驗,server 評分;計分測驗及格、練習測驗交卷就把單元標成完成。選擇題的值是選項 id,簡答與數字題是一個字串 */
162
+ /** Submits a quiz, graded by the server; passing a graded quiz, or submitting a practice quiz, marks the unit complete. Multiple-choice values are option ids; short-answer and number questions take one string */
163
163
  submitQuiz(input: {
164
164
  unitId: string;
165
165
  answers: Record<string, string[]>;
166
166
  }): Promise<QuizSubmitOk | ProgressFail>;
167
- /** 結業證書的短效下載網址(完課且課程有開證書) */
167
+ /** Short-lived download URL of the completion certificate (course completed and certificates enabled) */
168
168
  getCertificate(deliverableId: string): Promise<CertificateOk | ProgressFail>;
169
- /** 單元逐字稿(與字幕軌同一集合;`locale` 省略=顧客自己的語系,沒有對應的軌就回原文) */
169
+ /** The unit's transcript (same set as the caption tracks; omit `locale` for the customer's own locale, and the original is returned when no track matches) */
170
170
  getTranscript(unitId: string, locale?: string | null): Promise<TranscriptOk | ProgressFail>;
171
171
  }
172
172
  /**
173
- * 給 Elements 的內容客戶端:錯誤不丟、改回 `{ ok: false, code }`(結果型別,與 HTTP 形狀無關),元件依 code 顯示鎖定/未開放/到期。
174
- * 匿名(無 token)時 `openUnit` 走 Delivery 的 `POST /api/v1/units/:id/open`(只放行試看單元)。
173
+ * Content client for Elements: errors are returned as `{ ok: false, code }` instead of thrown (a result type, unrelated to the HTTP shape), and components show locked, not released or expired by code.
174
+ * When anonymous (no token), `openUnit` goes through the Delivery API's `POST /api/v1/units/:id/open` (free preview units only).
175
175
  */
176
176
  export declare function createCustomerContentClient(options: CustomerClientOptions): CustomerContentClientLike;
package/dist/customer.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * Customer API(`https://{site}/api/v1/customer`,Bearer = 顧客 session token;ADR-0003)。
3
- * 瀏覽器可直打(CORS 依站台 allowedOrigins)。型別由 `packages/shared/openapi/customer.json` 產生;成功回應不含 ok、錯誤是統一信封。
2
+ * Customer API (`https://{site}/api/v1/customer`, Bearer = the customer's session token).
3
+ * Browsers can call it directly (CORS follows the site's allowed origins). Types are generated from the Customer API's OpenAPI document; successful responses carry no `ok`, and errors use the shared envelope.
4
4
  *
5
- * `createCustomerClient` 之外另提供 `createCustomerContentClient`:符合 `@kanorio/shared` 的
6
- * `CustomerContentClient` 介面(`openUnit`/`reportProgress`/`submitQuiz`/`getCertificate`),給 `@kanorio/elements` 的 `<kanorio-unit>` 注入。
5
+ * Besides `createCustomerClient` there is `createCustomerContentClient`, which implements the
6
+ * content client interface (`openUnit`, `reportProgress`, `submitQuiz`, `getCertificate`) that `@kanorio/elements` injects into `<kanorio-unit>`.
7
7
  */
8
8
  import { createHttpClient, KanorioApiError } from "./http.js";
9
9
  import { createTypedClient } from "./typed.js";
@@ -29,9 +29,18 @@ export function createCustomerClient(options) {
29
29
  });
30
30
  return createTypedClient(http);
31
31
  }
32
- /** 瀏覽器端保存 Bearer 的預設位置(`<kanorio-login>` 寫入、其他元件讀取) */
32
+ /** Default place the browser keeps the bearer token (`<kanorio-login>` writes it, other components read it) */
33
33
  export const CUSTOMER_TOKEN_STORAGE_KEY = "kanorio.customer.token";
34
- export function readStoredCustomerToken(storage = typeof localStorage === "undefined" ? undefined : localStorage) {
34
+ /** `localStorage`, or undefined where there is none or reading it throws (a sandboxed frame without `allow-same-origin`, storage blocked) */
35
+ function defaultStorage() {
36
+ try {
37
+ return typeof localStorage === "undefined" ? undefined : localStorage;
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ }
43
+ export function readStoredCustomerToken(storage = defaultStorage()) {
35
44
  try {
36
45
  return storage?.getItem(CUSTOMER_TOKEN_STORAGE_KEY) ?? null;
37
46
  }
@@ -39,7 +48,7 @@ export function readStoredCustomerToken(storage = typeof localStorage === "undef
39
48
  return null;
40
49
  }
41
50
  }
42
- export function writeStoredCustomerToken(token, storage = typeof localStorage === "undefined" ? undefined : localStorage) {
51
+ export function writeStoredCustomerToken(token, storage = defaultStorage()) {
43
52
  try {
44
53
  if (token)
45
54
  storage?.setItem(CUSTOMER_TOKEN_STORAGE_KEY, token);
@@ -47,16 +56,16 @@ export function writeStoredCustomerToken(token, storage = typeof localStorage ==
47
56
  storage?.removeItem(CUSTOMER_TOKEN_STORAGE_KEY);
48
57
  }
49
58
  catch {
50
- // 隱私模式或禁用儲存:忽略
59
+ // Private mode or storage disabled: ignore
51
60
  }
52
61
  }
53
- /** HTTP 成功回應不含 ok;元件共用的結果型別用 ok 區分成功與失敗 */
62
+ /** Successful HTTP responses carry no `ok`; the result types shared by components use `ok` to tell success from failure */
54
63
  function succeed(body) {
55
64
  return { ...body, ok: true };
56
65
  }
57
66
  /**
58
- * 給 Elements 的內容客戶端:錯誤不丟、改回 `{ ok: false, code }`(結果型別,與 HTTP 形狀無關),元件依 code 顯示鎖定/未開放/到期。
59
- * 匿名(無 token)時 `openUnit` 走 Delivery 的 `POST /api/v1/units/:id/open`(只放行試看單元)。
67
+ * Content client for Elements: errors are returned as `{ ok: false, code }` instead of thrown (a result type, unrelated to the HTTP shape), and components show locked, not released or expired by code.
68
+ * When anonymous (no token), `openUnit` goes through the Delivery API's `POST /api/v1/units/:id/open` (free preview units only).
60
69
  */
61
70
  export function createCustomerContentClient(options) {
62
71
  const client = createCustomerClient(options);
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Content Delivery API(`https://{site}/api/v1`,匿名、可快取)。
3
- * 型別由 `packages/shared/openapi/delivery.json` 產生。`siteUrl` 是站台網址(託管子網域或自訂網域)。
2
+ * Content Delivery API (`https://{site}/api/v1`, anonymous and cacheable).
3
+ * Types are generated from the Delivery API's OpenAPI document. `siteUrl` is the site's URL (hosted subdomain or custom domain).
4
4
  */
5
5
  import type { paths as DeliveryPaths } from "./generated/delivery.js";
6
6
  import { type HttpClientOptions } from "./http.js";
@@ -11,11 +11,11 @@ export type DeliveryClient = TypedClient<DeliveryPaths> & {
11
11
  readonly seo: SeoHelpers;
12
12
  };
13
13
  export interface DeliveryClientOptions extends Omit<HttpClientOptions, "baseUrl"> {
14
- /** 例如 `https://demo.kanorio.com` */
14
+ /** For example `https://demo.kanorio.com` */
15
15
  siteUrl: string;
16
16
  /**
17
- * 唯讀預覽權杖(`knr_pv_…`,由後台「網站設定 › 開發者」或 Agent `site.create_preview_token` 簽發)。
18
- * 設定後每個請求帶 `X-Kanorio-Preview`,回未發布草稿且不經快取;可傳函式供 Draft Mode 動態決定。
17
+ * Read-only preview token (`knr_pv_...`, issued under Site settings > Developer or by the `site.create_preview_token` operation).
18
+ * When set, every request sends `X-Kanorio-Preview` and gets unpublished drafts without caching; pass a function to decide per request in Draft Mode.
19
19
  */
20
20
  previewToken?: string | (() => string | null | undefined | Promise<string | null | undefined>);
21
21
  }
@@ -24,12 +24,12 @@ export declare function deliveryBaseUrl(siteUrl: string): string;
24
24
  export declare function createDeliveryClient(options: DeliveryClientOptions): DeliveryClient;
25
25
  export declare const DELIVERY_CACHE_TAGS_HEADER = "x-kanorio-cache-tags";
26
26
  /**
27
- * 從 Delivery API 回應標頭(`X-Kanorio-Cache-Tags`)解析快取標籤陣列(原始字串,與 Webhook `data.cacheTags` 同一套字彙)。
28
- * 要打在框架快取上請用 `frameworkCacheTags`(加命名空間)。
27
+ * Parses the cache tags from a Delivery API response's `X-Kanorio-Cache-Tags` header (raw strings, the same vocabulary as a webhook's `data.cacheTags`).
28
+ * To tag a framework cache, use `frameworkCacheTags` (which adds the namespace).
29
29
  */
30
30
  export declare function parseDeliveryCacheTags(headers: Headers | Record<string, string | undefined> | null | undefined): string[];
31
31
  /**
32
- * 回應的快取標籤加上命名空間(預設 `kanorio:`),直接交給 Next.js `fetch(..., { next: { tags } })` 或 `cacheTag()`;
33
- * `createRevalidateHandler` 收到事件時用同一個前綴呼叫 `revalidateTag`,兩邊才對得上。收標頭或已解析的陣列都可以。
32
+ * Response cache tags with the namespace added (`kanorio:` by default), ready for Next.js `fetch(..., { next: { tags } })` or `cacheTag()`.
33
+ * `createRevalidateHandler` calls `revalidateTag` with the same prefix when an event arrives, so the two sides match. Accepts headers or an already parsed array.
34
34
  */
35
35
  export declare function frameworkCacheTags(source: Headers | Record<string, string | undefined> | readonly string[] | null | undefined, prefix?: string): string[];
package/dist/delivery.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Content Delivery API(`https://{site}/api/v1`,匿名、可快取)。
3
- * 型別由 `packages/shared/openapi/delivery.json` 產生。`siteUrl` 是站台網址(託管子網域或自訂網域)。
2
+ * Content Delivery API (`https://{site}/api/v1`, anonymous and cacheable).
3
+ * Types are generated from the Delivery API's OpenAPI document. `siteUrl` is the site's URL (hosted subdomain or custom domain).
4
4
  */
5
5
  import { createHttpClient } from "./http.js";
6
6
  import { createSeoHelpers } from "./seo.js";
@@ -27,8 +27,8 @@ export function createDeliveryClient(options) {
27
27
  }
28
28
  export const DELIVERY_CACHE_TAGS_HEADER = SHARED_CACHE_TAGS_HEADER;
29
29
  /**
30
- * 從 Delivery API 回應標頭(`X-Kanorio-Cache-Tags`)解析快取標籤陣列(原始字串,與 Webhook `data.cacheTags` 同一套字彙)。
31
- * 要打在框架快取上請用 `frameworkCacheTags`(加命名空間)。
30
+ * Parses the cache tags from a Delivery API response's `X-Kanorio-Cache-Tags` header (raw strings, the same vocabulary as a webhook's `data.cacheTags`).
31
+ * To tag a framework cache, use `frameworkCacheTags` (which adds the namespace).
32
32
  */
33
33
  export function parseDeliveryCacheTags(headers) {
34
34
  if (!headers)
@@ -40,8 +40,8 @@ export function parseDeliveryCacheTags(headers) {
40
40
  return parseCacheTagsHeader(raw);
41
41
  }
42
42
  /**
43
- * 回應的快取標籤加上命名空間(預設 `kanorio:`),直接交給 Next.js `fetch(..., { next: { tags } })` 或 `cacheTag()`;
44
- * `createRevalidateHandler` 收到事件時用同一個前綴呼叫 `revalidateTag`,兩邊才對得上。收標頭或已解析的陣列都可以。
43
+ * Response cache tags with the namespace added (`kanorio:` by default), ready for Next.js `fetch(..., { next: { tags } })` or `cacheTag()`.
44
+ * `createRevalidateHandler` calls `revalidateTag` with the same prefix when an event arrives, so the two sides match. Accepts headers or an already parsed array.
45
45
  */
46
46
  export function frameworkCacheTags(source, prefix = DEFAULT_CACHE_TAG_PREFIX) {
47
47
  const raw = Array.isArray(source) ? source : parseDeliveryCacheTags(source);
package/dist/edge.d.ts CHANGED
@@ -1,14 +1,14 @@
1
1
  /**
2
- * `@kanorio/sdk/edge`:AI 爬蟲管理與追蹤+301/302 轉址規則邊緣中介層(Stage F2)。
2
+ * `@kanorio/sdk/edge`: edge middleware for AI crawler management and tracking, plus 301/302 redirect rules.
3
3
  *
4
- * 設計原則(智慧放伺服器,SDK 越薄越好):
5
- * - 封鎖清單(`crawlerRules.blockedTokens`)與轉址規則(`/api/v1/redirects`)皆由 Kanorio Content Delivery API
6
- * 動態拉取並以記憶體短快取(預設 60 秒)保存,站主在後台更新規則後無須重部署前端即生效。
7
- * - 命中已知 AI 爬蟲時,自動非阻塞回報至 `POST {siteUrl}/api/v1/analytics/bot-hit`,
8
- * 讓後台 `/analytics/bots` 與 `/console`「AI 與安全防護」卡在自架前端(Headless)模式下同樣有完整數據。
9
- * - 多語網站(ADR-0010 決策 13;`features.locales`):與代管站同一套規則——主語系碼當前綴(`/zh-hant/about`)301 回無前綴;
10
- * `/{前綴}/llms.txt`、`llms-full.txt`、`rss.xml`、`feed.xml`、`feed.atom` 由邊緣回該語系的檔案;轉址規則以無前綴的路徑比對、
11
- * 站內目標接回同一個前綴;放行的決策帶 `locale`(語系、無前綴路徑)供前端路由
4
+ * Design (the logic lives on the server; the SDK stays thin):
5
+ * - The block list (`crawlerRules.blockedTokens`) and the redirect rules (`/api/v1/redirects`) are fetched from the Kanorio Content Delivery API
6
+ * and kept in a short in-memory cache (60 seconds by default), so rule changes in the dashboard apply without redeploying the front end.
7
+ * - A hit from a known AI crawler is reported, without blocking, to `POST {siteUrl}/api/v1/analytics/bot-hit`,
8
+ * so the dashboard's crawler analytics have full data for a self-hosted front end too.
9
+ * - Multilingual sites (`features.locales`) follow the same rules as hosted sites: the primary locale code used as a prefix (`/zh-hant/about`) redirects 301 to the unprefixed path;
10
+ * `/{prefix}/llms.txt`, `llms-full.txt`, `rss.xml`, `feed.xml` and `feed.atom` are answered at the edge with that locale's file; redirect rules match the unprefixed path
11
+ * and in-site targets get the same prefix back; an allowed decision carries `locale` (locale and unprefixed path) for the front end's routing
12
12
  */
13
13
  import { type RequestLocaleResult } from "./shared/localization/request-locale.js";
14
14
  export declare const CRAWLER_LIST_VERSION = "2026-10-22";
@@ -25,38 +25,38 @@ export interface RedirectRule {
25
25
  sourcePath: string;
26
26
  targetUrl: string;
27
27
  statusCode: number;
28
- /** null=各語系共用(以無前綴路徑比對);語系碼=只屬於那個語系(以含前綴的完整路徑比對、目標原樣) */
28
+ /** null: shared by every locale (matched on the unprefixed path); a locale code: belongs to that locale only (matched on the full prefixed path, target used as is) */
29
29
  locale?: string | null;
30
30
  }
31
31
  export interface KanorioMiddlewareOptions {
32
- /** Kanorio 系統或服務網址(如 `https://s-xxx.kanorio.com`) */
32
+ /** Kanorio system or service URL (for example `https://s-xxx.kanorio.com`) */
33
33
  siteUrl: string;
34
- /** 規則快取秒數(預設 60 秒) */
34
+ /** Rule cache lifetime in seconds (60 by default) */
35
35
  cacheTtlSeconds?: number;
36
- /** 功能開關(預設 crawlers、redirects、indexNow、locales 皆啟用) */
36
+ /** Feature switches (crawlers, redirects, indexNow and locales are all on by default) */
37
37
  features?: {
38
38
  crawlers?: boolean;
39
39
  redirects?: boolean;
40
40
  /**
41
- * 自動回應 IndexNow 金鑰驗證檔(`/<32hex>.txt`),讓 IndexNow(Bing/Naver/Seznam/Yandex)
42
- * 能向這個外部網域驗證金鑰所有權,站主不需要自己接金鑰端點。
41
+ * Answers the IndexNow key verification file (`/<32hex>.txt`) automatically, so IndexNow (Bing, Naver, Seznam, Yandex)
42
+ * can verify key ownership on this external domain without the owner wiring a key endpoint.
43
43
  */
44
44
  indexNow?: boolean;
45
45
  /**
46
- * 多語網站的語系路由:主語系碼當前綴時 301 回無前綴、每語系的 llms/RSS 檔由邊緣回應、
47
- * 轉址規則以無前綴路徑比對;放行時決策帶 `locale`。單語網站沒有影響。
46
+ * Locale routing for multilingual sites: the primary locale code as a prefix redirects 301 to the unprefixed path, per-locale llms and RSS files are answered at the edge,
47
+ * and redirect rules match the unprefixed path; an allowed decision carries `locale`. No effect on single-language sites.
48
48
  */
49
49
  locales?: boolean;
50
50
  };
51
51
  fetch?: typeof globalThis.fetch;
52
52
  /**
53
- * Server key (`knr_sa_…`, from an environment variable). Required for crawler hit reporting: the report is a
53
+ * Server key (`knr_sk_…`, from an environment variable). Required for crawler hit reporting: the report is a
54
54
  * server-to-server write, and without a key Kanorio's edge challenges it and the hit is lost. The visitor's
55
55
  * (crawler's) IP is read from the incoming request with `visitorIpFromRequest`.
56
56
  */
57
57
  serverKey?: string;
58
58
  }
59
- /** 放行時的請求語系(多語網站才有;`pathname` 是去掉前綴的主語系空間路徑,前端路由與 Delivery 讀取都用它) */
59
+ /** The request's locale on an allowed decision (multilingual sites only; `pathname` is the primary-locale path without the prefix, used for front-end routing and Delivery reads) */
60
60
  export type MiddlewareLocale = RequestLocaleResult & {
61
61
  primaryLocale: string;
62
62
  };
@@ -85,11 +85,15 @@ export type MiddlewareDecision = {
85
85
  contentType: string;
86
86
  };
87
87
  export interface KanorioMiddleware {
88
- /** 評估單一 Request,回傳決策(不直接產生框架專屬 Response) */
88
+ /** Evaluates one Request and returns a decision (no framework-specific Response) */
89
89
  evaluate(request: Request, event?: {
90
90
  waitUntil?: (promise: Promise<unknown>) => void;
91
91
  }): Promise<MiddlewareDecision>;
92
- /** Next.js `proxy.ts`(Next.js 15 以前為 `middleware.ts`)直接處理器:回傳 `Response`(403 或 301/302)或 `null`(放行) */
92
+ /**
93
+ * Next.js handler (the file is `proxy.ts` from Next.js 16, `middleware.ts` in 15 and earlier): returns a `Response` (403, 301/302 or the IndexNow key file) or `null` (allow).
94
+ * On `null`, continue with your own logic; it can go at the top of an existing middleware. Rules are cached in memory (`cacheTtlSeconds`, 60 seconds by default);
95
+ * when Kanorio is unreachable the last rules are kept, and before the first load everything is allowed, so visitors are never blocked.
96
+ */
93
97
  handleRequest(request: Request, event?: {
94
98
  waitUntil?: (promise: Promise<unknown>) => void;
95
99
  }): Promise<Response | null>;