@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kanorio, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # @kanorio/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Typed `fetch` clients for the three Kanorio HTTP APIs, plus helpers for headless frontends (SEO rewrites, JSON-LD, webhook-driven cache revalidation). Types are generated from the OpenAPI documents with openapi-typescript, so each path, its parameters, request body and success response are checked at compile time.
4
+
5
+ | Client | API | Base URL | Credential |
6
+ |---|---|---|---|
7
+ | `createManagementClient` | Management API | `https://app.kanorio.com/api/v1` | Personal access token, OAuth access token or service account token. Server-side only. |
8
+ | `createDeliveryClient` | Content Delivery API | `https://{site}/api/v1` | None for reads (anonymous and edge-cached). A server key for writes sent from your own server. |
9
+ | `createCustomerClient` | Customer API | `https://{site}/api/v1/customer` | Customer access token from passwordless sign-in, plus a server key when your own server makes the call. |
10
+
11
+ ```ts
12
+ import { createCustomerClient, createDeliveryClient, createManagementClient } from "@kanorio/sdk";
13
+
14
+ const management = createManagementClient({ token: process.env.KANORIO_TOKEN! });
15
+ const sites = await management.get("/sites");
16
+
17
+ const delivery = createDeliveryClient({ siteUrl: "https://example.com" });
18
+ const { product } = await delivery.get("/products/{slug}", { params: { slug: "react-course" } });
19
+
20
+ const customer = createCustomerClient({
21
+ siteUrl: "https://example.com",
22
+ token: () => localStorage.getItem("kanorio.customer.token"),
23
+ });
24
+ ```
25
+
26
+ When your own server writes on a visitor's behalf (submitting a form, exchanging a customer sign-in code, reporting crawler hits from middleware), pass a server key and the visitor's IP. Without the key, server-to-server writes are stopped by an edge challenge and the SDK throws `KanorioEdgeChallengeError`.
27
+
28
+ ```ts
29
+ import { createFormsHelpers, visitorIpFromRequest } from "@kanorio/sdk";
30
+
31
+ const forms = createFormsHelpers({
32
+ siteUrl: "https://example.com",
33
+ serverKey: process.env.KANORIO_SERVER_KEY, // knr_sa_…, a service account of type "Website server"
34
+ visitorIp: visitorIpFromRequest(request),
35
+ });
36
+ ```
37
+
38
+ A server key is refused in browser code, requires HTTPS, and cannot call the Management API. `visitorIpFromRequest` reads the IP on Cloudflare, Vercel, Netlify and Fly.io; on other hosts pass the IP your platform gives you, or name a header your own reverse proxy overwrites with `{ trustedHeader }`.
39
+
40
+ Errors throw `KanorioApiError` with `code`, `status` and `details`. Deprecated operations surface through the `onDeprecation` callback (the `Deprecation`, `Sunset` and `Link` response headers).
41
+
42
+ ## Tax id validation
43
+
44
+ `@kanorio/sdk/tax-id` validates tax ids the way the hosted checkout and forms do, without a network call:
45
+
46
+ ```ts
47
+ import { isBlockingTaxIdIssue, listTaxIdTypes, validateTaxIdFormat } from "@kanorio/sdk/tax-id";
48
+
49
+ listTaxIdTypes("TW"); // ["tw_vat"]
50
+ const result = validateTaxIdFormat({ country: "TW", value: "0459-5252" });
51
+ if (result.ok) save(result.normalized); // "04595252"
52
+ else if (isBlockingTaxIdIssue(result)) showError(result.issue); // "FORMAT" | "CHECKSUM" | "EMPTY"
53
+ ```
54
+
55
+ Type names follow Stripe (`tw_vat`, `hk_br`, `jp_trn`, `kr_brn`, `eu_vat`, `sg_uen`, `my_itn`, `my_sst`). A country with no registered type returns `UNSUPPORTED`; accept the value as free text. Types whose rules are not yet verified against the authority's own documents report `enforcement: "warn"`: show a hint, do not block.
56
+
57
+ ## Compatibility
58
+
59
+ - ESM only. Use `import`; from CommonJS code, use `await import("@kanorio/sdk")`. `require()` is not supported.
60
+ - Node.js 20 or later for server-side use.
61
+ - Within `1.x`, methods, options and response fields are only added. Removing or changing one is a new major version.
62
+
63
+ ## Documentation and support
64
+
65
+ - Documentation: <https://kanorio.com/en/developers/sdk>
66
+ - Changes: [CHANGELOG.md](./CHANGELOG.md). Released together with `@kanorio/elements` and `@kanorio/cli` under one version number.
67
+ - Questions and bug reports: <support@kanorio.com>. To report a security issue, write to <security@kanorio.com> instead of opening a public report.
@@ -0,0 +1,86 @@
1
+ /**
2
+ * 託管登入頁的 OAuth 2.1 授權碼+PKCE(customers ADR-0001 修訂三第 9 條):自建前端不畫登入畫面,
3
+ * 把顧客送到 Kanorio 託管的 `/account/login`,回來後用授權碼換 `knr_cat_` Bearer(與 `<kanorio-account>` 直打同一種 token)。
4
+ *
5
+ * 瀏覽器端:`startHostedCustomerLogin()` 產 PKCE 與 state 存 sessionStorage、整頁導去登入頁;
6
+ * 回到 `redirectUri` 後 `completeHostedCustomerLogin()` 讀 `?code&state`、對 state、換 token、清掉 query。
7
+ * 伺服器端(或要自己管 token 時):`exchangeHostedLoginCode()`/`refreshCustomerToken()`/`revokeCustomerToken()`。
8
+ */
9
+ import type { ServerKeyOptions } from "./server-key.js";
10
+ export interface HostedLoginGrant {
11
+ accessToken: string;
12
+ tokenType: "Bearer";
13
+ expiresIn: number;
14
+ expiresAt: string;
15
+ refreshToken: string;
16
+ refreshTokenExpiresIn: number;
17
+ contactId: string;
18
+ }
19
+ /** PKCE:verifier 隨機 43–128 字元、challenge=BASE64URL(SHA-256(verifier))(RFC 7636;OAuth 2.1 只允許 S256) */
20
+ export declare function createPkcePair(): Promise<{
21
+ verifier: string;
22
+ challenge: string;
23
+ method: "S256";
24
+ }>;
25
+ export interface HostedLoginUrlParams {
26
+ /** 例如 `https://demo.kanorio.com`:託管登入頁所在的站台網址 */
27
+ siteUrl: string;
28
+ /** 網站 id(`GET /site` 的 `id`);OAuth 的 client_id */
29
+ clientId: string;
30
+ /** 登入後回來的網址:https、origin 要在網站設定「允許的來源」裡 */
31
+ redirectUri: string;
32
+ codeChallenge: string;
33
+ state: string;
34
+ /** 登入頁的語系路徑根(多語網站,例如 `/en`);省略為主語系 */
35
+ localeRoot?: string;
36
+ }
37
+ export declare function buildHostedLoginUrl(params: HostedLoginUrlParams): string;
38
+ export interface StartHostedLoginOptions {
39
+ siteUrl: string;
40
+ clientId: string;
41
+ /** 省略時是目前這頁(去掉 code/state) */
42
+ redirectUri?: string;
43
+ localeRoot?: string;
44
+ /** 存 PKCE verifier 與 state 的地方;預設 sessionStorage(同一分頁回來才讀得到) */
45
+ storage?: Storage;
46
+ /** 自行導頁(例如用 router);預設 `window.location.assign` */
47
+ navigate?: (url: string) => void;
48
+ }
49
+ /** 第一步:產 PKCE 與 state、記下來、把顧客送去託管登入頁 */
50
+ export declare function startHostedCustomerLogin(options: StartHostedLoginOptions): Promise<void>;
51
+ export interface CompleteHostedLoginOptions {
52
+ siteUrl: string;
53
+ clientId: string;
54
+ storage?: Storage;
55
+ /** 換到 token 後存進 `localStorage["kanorio.customer.token"]`(其他 Elements 讀得到);預設 true */
56
+ storeToken?: boolean;
57
+ /** 從網址拿掉 code/state(不留在歷史與 Referer);預設 true */
58
+ cleanUrl?: boolean;
59
+ }
60
+ /**
61
+ * 第二步:回到 redirectUri 後呼叫。網址沒有 `code` 回 null;state 對不上或換 token 失敗丟錯。
62
+ */
63
+ export declare function completeHostedCustomerLogin(options: CompleteHostedLoginOptions): Promise<HostedLoginGrant | null>;
64
+ /**
65
+ * 授權碼換 token(任何環境)。在**伺服器**上呼叫時要帶 `serverKey`(與 `visitorIp`):
66
+ * 伺服器對伺服器的寫入沒有主機金鑰會被邊緣擋下。瀏覽器端不要帶。
67
+ */
68
+ export declare function exchangeHostedLoginCode(params: {
69
+ siteUrl: string;
70
+ clientId: string;
71
+ code: string;
72
+ codeVerifier: string;
73
+ redirectUri: string;
74
+ } & ServerKeyOptions): Promise<HostedLoginGrant>;
75
+ /** 輪替:拿新的 access/refresh token;舊的 refresh token 立即作廢,請把回傳的兩把都存起來 */
76
+ export declare function refreshCustomerToken(params: {
77
+ siteUrl: string;
78
+ clientId: string;
79
+ refreshToken: string;
80
+ } & ServerKeyOptions): Promise<HostedLoginGrant>;
81
+ /** 撤銷 access 或 refresh token(整個 session 結束) */
82
+ export declare function revokeCustomerToken(params: {
83
+ siteUrl: string;
84
+ token: string;
85
+ tokenTypeHint?: "access_token" | "refresh_token";
86
+ } & ServerKeyOptions): Promise<void>;
@@ -0,0 +1,112 @@
1
+ /**
2
+ * 託管登入頁的 OAuth 2.1 授權碼+PKCE(customers ADR-0001 修訂三第 9 條):自建前端不畫登入畫面,
3
+ * 把顧客送到 Kanorio 託管的 `/account/login`,回來後用授權碼換 `knr_cat_` Bearer(與 `<kanorio-account>` 直打同一種 token)。
4
+ *
5
+ * 瀏覽器端:`startHostedCustomerLogin()` 產 PKCE 與 state 存 sessionStorage、整頁導去登入頁;
6
+ * 回到 `redirectUri` 後 `completeHostedCustomerLogin()` 讀 `?code&state`、對 state、換 token、清掉 query。
7
+ * 伺服器端(或要自己管 token 時):`exchangeHostedLoginCode()`/`refreshCustomerToken()`/`revokeCustomerToken()`。
8
+ */
9
+ import { createCustomerClient, writeStoredCustomerToken } from "./customer.js";
10
+ const PKCE_STORAGE_KEY = "kanorio.customer.pkce";
11
+ function toGrant(wire) {
12
+ return {
13
+ accessToken: wire.access_token,
14
+ tokenType: wire.token_type,
15
+ expiresIn: wire.expires_in,
16
+ expiresAt: wire.expires_at,
17
+ refreshToken: wire.refresh_token,
18
+ refreshTokenExpiresIn: wire.refresh_token_expires_in,
19
+ contactId: wire.contactId,
20
+ };
21
+ }
22
+ function base64url(bytes) {
23
+ let binary = "";
24
+ for (const byte of bytes)
25
+ binary += String.fromCharCode(byte);
26
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
27
+ }
28
+ function randomString(bytes = 32) {
29
+ const buffer = new Uint8Array(bytes);
30
+ crypto.getRandomValues(buffer);
31
+ return base64url(buffer);
32
+ }
33
+ /** PKCE:verifier 隨機 43–128 字元、challenge=BASE64URL(SHA-256(verifier))(RFC 7636;OAuth 2.1 只允許 S256) */
34
+ export async function createPkcePair() {
35
+ const verifier = randomString(32);
36
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
37
+ return { verifier, challenge: base64url(new Uint8Array(digest)), method: "S256" };
38
+ }
39
+ export function buildHostedLoginUrl(params) {
40
+ const base = params.siteUrl.replace(/\/+$/, "");
41
+ const url = new URL(`${base}${params.localeRoot ?? ""}/account/login`);
42
+ url.searchParams.set("client_id", params.clientId);
43
+ url.searchParams.set("redirect_uri", params.redirectUri);
44
+ url.searchParams.set("code_challenge", params.codeChallenge);
45
+ url.searchParams.set("code_challenge_method", "S256");
46
+ url.searchParams.set("state", params.state);
47
+ return url.toString();
48
+ }
49
+ function currentRedirectUri() {
50
+ const url = new URL(window.location.href);
51
+ url.searchParams.delete("code");
52
+ url.searchParams.delete("state");
53
+ url.hash = "";
54
+ return url.toString();
55
+ }
56
+ /** 第一步:產 PKCE 與 state、記下來、把顧客送去託管登入頁 */
57
+ export async function startHostedCustomerLogin(options) {
58
+ const storage = options.storage ?? sessionStorage;
59
+ const redirectUri = options.redirectUri ?? currentRedirectUri();
60
+ const pkce = await createPkcePair();
61
+ const state = randomString(16);
62
+ storage.setItem(PKCE_STORAGE_KEY, JSON.stringify({ verifier: pkce.verifier, state, redirectUri }));
63
+ const url = buildHostedLoginUrl({ siteUrl: options.siteUrl, clientId: options.clientId, redirectUri, codeChallenge: pkce.challenge, state, localeRoot: options.localeRoot });
64
+ (options.navigate ?? ((target) => window.location.assign(target)))(url);
65
+ }
66
+ /**
67
+ * 第二步:回到 redirectUri 後呼叫。網址沒有 `code` 回 null;state 對不上或換 token 失敗丟錯。
68
+ */
69
+ export async function completeHostedCustomerLogin(options) {
70
+ const url = new URL(window.location.href);
71
+ const code = url.searchParams.get("code");
72
+ const state = url.searchParams.get("state");
73
+ if (!code)
74
+ return null;
75
+ const storage = options.storage ?? sessionStorage;
76
+ const raw = storage.getItem(PKCE_STORAGE_KEY);
77
+ storage.removeItem(PKCE_STORAGE_KEY);
78
+ const saved = raw ? JSON.parse(raw) : null;
79
+ if (!saved || saved.state !== state)
80
+ throw new Error("Hosted sign-in state mismatch; start the sign-in again.");
81
+ if (options.cleanUrl !== false) {
82
+ url.searchParams.delete("code");
83
+ url.searchParams.delete("state");
84
+ window.history.replaceState(window.history.state, "", url.toString());
85
+ }
86
+ const grant = await exchangeHostedLoginCode({ siteUrl: options.siteUrl, clientId: options.clientId, code, codeVerifier: saved.verifier, redirectUri: saved.redirectUri });
87
+ if (options.storeToken !== false)
88
+ writeStoredCustomerToken(grant.accessToken);
89
+ return grant;
90
+ }
91
+ /**
92
+ * 授權碼換 token(任何環境)。在**伺服器**上呼叫時要帶 `serverKey`(與 `visitorIp`):
93
+ * 伺服器對伺服器的寫入沒有主機金鑰會被邊緣擋下。瀏覽器端不要帶。
94
+ */
95
+ export async function exchangeHostedLoginCode(params) {
96
+ const client = createCustomerClient({ siteUrl: params.siteUrl, serverKey: params.serverKey, visitorIp: params.visitorIp });
97
+ const wire = (await client.post("/auth/oauth2/token", {
98
+ body: { grant_type: "authorization_code", code: params.code, code_verifier: params.codeVerifier, redirect_uri: params.redirectUri, client_id: params.clientId },
99
+ }));
100
+ return toGrant(wire);
101
+ }
102
+ /** 輪替:拿新的 access/refresh token;舊的 refresh token 立即作廢,請把回傳的兩把都存起來 */
103
+ export async function refreshCustomerToken(params) {
104
+ const client = createCustomerClient({ siteUrl: params.siteUrl, serverKey: params.serverKey, visitorIp: params.visitorIp });
105
+ const wire = (await client.post("/auth/oauth2/token", { body: { grant_type: "refresh_token", refresh_token: params.refreshToken, client_id: params.clientId } }));
106
+ return toGrant(wire);
107
+ }
108
+ /** 撤銷 access 或 refresh token(整個 session 結束) */
109
+ export async function revokeCustomerToken(params) {
110
+ const client = createCustomerClient({ siteUrl: params.siteUrl, serverKey: params.serverKey, visitorIp: params.visitorIp });
111
+ await client.post("/auth/oauth2/revoke", { body: { token: params.token, ...(params.tokenTypeHint ? { token_type_hint: params.tokenTypeHint } : {}) } });
112
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Customer API(`https://{site}/api/v1/customer`,Bearer = 顧客 session token;ADR-0003)。
3
+ * 瀏覽器可直打(CORS 依站台 allowedOrigins)。型別由 `packages/shared/openapi/customer.json` 產生;成功回應不含 ok、錯誤是統一信封。
4
+ *
5
+ * `createCustomerClient` 之外另提供 `createCustomerContentClient`:符合 `@kanorio/shared` 的
6
+ * `CustomerContentClient` 介面(`openUnit`/`reportProgress`/`submitQuiz`/`getCertificate`),給 `@kanorio/elements` 的 `<kanorio-unit>` 注入。
7
+ */
8
+ import type { paths as CustomerPaths } from "./generated/customer.js";
9
+ import { type HttpClientOptions } from "./http.js";
10
+ import { type TypedClient } from "./typed.js";
11
+ export type { CustomerPaths };
12
+ export type CustomerClient = TypedClient<CustomerPaths>;
13
+ export type CustomerTokenSource = string | null | undefined | (() => string | null | undefined | Promise<string | null | undefined>);
14
+ export interface CustomerClientOptions extends Omit<HttpClientOptions, "baseUrl" | "headers"> {
15
+ /** 例如 `https://demo.kanorio.com` */
16
+ siteUrl: string;
17
+ /** 顧客 Bearer;匿名端點(challenge/verify)可為 null */
18
+ token?: CustomerTokenSource;
19
+ headers?: HeadersInit;
20
+ /**
21
+ * 內容語系(多語網站;ADR-0010 決策 13):開啟單元時帶 `locale`,標題依它。省略=顧客自己的語系(Contact.locale)或主語系。
22
+ * 只影響 `createCustomerContentClient`;典型用法是 Elements 的 Provider 把頁面語系傳進來。
23
+ */
24
+ locale?: string | null;
25
+ }
26
+ export declare function customerBaseUrl(siteUrl: string): string;
27
+ export declare function createCustomerClient(options: CustomerClientOptions): CustomerClient;
28
+ /** 瀏覽器端保存 Bearer 的預設位置(`<kanorio-login>` 寫入、其他元件讀取) */
29
+ export declare const CUSTOMER_TOKEN_STORAGE_KEY = "kanorio.customer.token";
30
+ export declare function readStoredCustomerToken(storage?: Storage | undefined): string | null;
31
+ export declare function writeStoredCustomerToken(token: string | null, storage?: Storage | undefined): void;
32
+ /** `captions` 筆(媒體 ADR 0011):字幕軌,一語系一筆;`source` 是 AI 產生或站主上傳、`edited` 代表站主改過字。預設不顯示,學員按 CC 才開 */
33
+ type OpenUnitRendition = {
34
+ kind: "original" | "mp4" | "hls" | "poster" | "thumbnails" | "captions" | "chapters";
35
+ url: string;
36
+ mimeType: string;
37
+ width?: number;
38
+ height?: number;
39
+ bytes?: number;
40
+ locale?: string;
41
+ source?: "ai" | "upload" | "translation";
42
+ edited?: boolean;
43
+ };
44
+ /** `renditions`/`poster`/`thumbnails`/`streaming`:影片的串流來源(有 `hls` 就播它、`url` 是原檔);`expiresIn` 依影片長度 */
45
+ type OpenUnitOk = {
46
+ ok: true;
47
+ mode: "read" | "download";
48
+ url: string;
49
+ expiresIn: number;
50
+ title: string | null;
51
+ fileName: string;
52
+ mimeType: string | null;
53
+ allowDownload: boolean;
54
+ renditions?: OpenUnitRendition[];
55
+ poster?: string | null;
56
+ thumbnails?: string | null;
57
+ streaming?: "none" | "partial" | "ready";
58
+ };
59
+ type OpenUnitFail = {
60
+ ok: false;
61
+ code: string;
62
+ availableAt?: string;
63
+ };
64
+ /** 一筆回報:位置與片長之外,帶 sessionId+segments 伺服器才記觀看紀錄(播放次數、時數、留存);見 Customer API 文件 */
65
+ type ProgressReportItem = {
66
+ positionSeconds?: number;
67
+ durationSeconds?: number;
68
+ completed?: boolean;
69
+ opened?: boolean;
70
+ sessionId?: string;
71
+ segments?: Array<[number, number] | [number, number, number]>;
72
+ startupMs?: number;
73
+ stallCount?: number;
74
+ stallMs?: number;
75
+ rendition?: number;
76
+ seekTargets?: number[];
77
+ device?: "desktop" | "mobile" | "tablet";
78
+ };
79
+ type ProgressOk = {
80
+ ok: true;
81
+ unit: "not_started" | "in-progress" | "completed";
82
+ /** 影音單元看過的比例 0–100;沒片長或沒段落資料為 null;舊版 server 沒有 */
83
+ unitCoveredPercent?: number | null;
84
+ /** `lite` 心跳且單元沒有剛完成時為 null */
85
+ deliverable: {
86
+ id: string;
87
+ percent: number;
88
+ completed: boolean;
89
+ completedAt?: string | null;
90
+ } | null;
91
+ deliverableJustCompleted: boolean;
92
+ };
93
+ type ProgressFail = {
94
+ ok: false;
95
+ code: string;
96
+ };
97
+ type QuizSubmitOk = {
98
+ ok: true;
99
+ /** graded:及格才完成;practice:交卷即完成、不計及格。舊版 server 沒有這個欄位 */
100
+ mode?: "graded" | "practice";
101
+ score: number;
102
+ correct: number;
103
+ total: number;
104
+ passed: boolean;
105
+ perQuestion: Record<string, boolean>;
106
+ attemptsUsed: number;
107
+ maxAttempts: number | null;
108
+ canRetry: boolean;
109
+ reveal: {
110
+ questions: Array<{
111
+ id: string;
112
+ correctOptionIds: string[]; /** 簡答/數字題的接受答案;舊版 server 沒有 */
113
+ acceptedAnswers?: string[];
114
+ explanation: string | null;
115
+ }>;
116
+ } | null;
117
+ unit: "not_started" | "in-progress" | "completed";
118
+ deliverable: {
119
+ id: string;
120
+ percent: number;
121
+ completed: boolean;
122
+ completedAt?: string | null;
123
+ };
124
+ deliverableJustCompleted: boolean;
125
+ };
126
+ type CertificateOk = {
127
+ ok: true;
128
+ certificate: {
129
+ serial: string;
130
+ issuedAt: string;
131
+ url: string;
132
+ expiresIn: number;
133
+ };
134
+ };
135
+ type TranscriptOk = {
136
+ ok: true;
137
+ unitId: string;
138
+ locale: string;
139
+ source: "ai" | "upload" | "translation";
140
+ edited: boolean;
141
+ segments: Array<{
142
+ s: number;
143
+ e: number;
144
+ t: string;
145
+ }>;
146
+ tracks: Array<{
147
+ locale: string;
148
+ source: "ai" | "upload" | "translation";
149
+ edited: boolean;
150
+ }>;
151
+ };
152
+ export interface CustomerContentClientLike {
153
+ /** `options.attachmentId`: download URL for one of the unit's attachments (`mode` is ignored) */
154
+ openUnit(unitId: string, mode: "read" | "download", options?: {
155
+ attachmentId?: string;
156
+ }): Promise<OpenUnitOk | OpenUnitFail>;
157
+ reportProgress(input: {
158
+ unitId: string;
159
+ reports: ProgressReportItem[]; /** 心跳:單元沒因這次回報完成時不算交付物層 */
160
+ lite?: boolean;
161
+ }): Promise<ProgressOk | ProgressFail>;
162
+ /** 交測驗,server 評分;計分測驗及格、練習測驗交卷就把單元標成完成。選擇題的值是選項 id,簡答與數字題是一個字串 */
163
+ submitQuiz(input: {
164
+ unitId: string;
165
+ answers: Record<string, string[]>;
166
+ }): Promise<QuizSubmitOk | ProgressFail>;
167
+ /** 結業證書的短效下載網址(完課且課程有開證書) */
168
+ getCertificate(deliverableId: string): Promise<CertificateOk | ProgressFail>;
169
+ /** 單元逐字稿(與字幕軌同一集合;`locale` 省略=顧客自己的語系,沒有對應的軌就回原文) */
170
+ getTranscript(unitId: string, locale?: string | null): Promise<TranscriptOk | ProgressFail>;
171
+ }
172
+ /**
173
+ * 給 Elements 的內容客戶端:錯誤不丟、改回 `{ ok: false, code }`(結果型別,與 HTTP 形狀無關),元件依 code 顯示鎖定/未開放/到期。
174
+ * 匿名(無 token)時 `openUnit` 走 Delivery 的 `POST /api/v1/units/:id/open`(只放行試看單元)。
175
+ */
176
+ export declare function createCustomerContentClient(options: CustomerClientOptions): CustomerContentClientLike;
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Customer API(`https://{site}/api/v1/customer`,Bearer = 顧客 session token;ADR-0003)。
3
+ * 瀏覽器可直打(CORS 依站台 allowedOrigins)。型別由 `packages/shared/openapi/customer.json` 產生;成功回應不含 ok、錯誤是統一信封。
4
+ *
5
+ * `createCustomerClient` 之外另提供 `createCustomerContentClient`:符合 `@kanorio/shared` 的
6
+ * `CustomerContentClient` 介面(`openUnit`/`reportProgress`/`submitQuiz`/`getCertificate`),給 `@kanorio/elements` 的 `<kanorio-unit>` 注入。
7
+ */
8
+ import { createHttpClient, KanorioApiError } from "./http.js";
9
+ import { createTypedClient } from "./typed.js";
10
+ export function customerBaseUrl(siteUrl) {
11
+ return `${siteUrl.replace(/\/+$/, "")}/api/v1/customer`;
12
+ }
13
+ async function resolveToken(source) {
14
+ const value = typeof source === "function" ? await source() : source;
15
+ return value ? value : null;
16
+ }
17
+ export function createCustomerClient(options) {
18
+ const { siteUrl, token, headers, ...rest } = options;
19
+ const http = createHttpClient({
20
+ ...rest,
21
+ baseUrl: customerBaseUrl(siteUrl),
22
+ headers: async () => {
23
+ const h = new Headers(headers);
24
+ const value = await resolveToken(token);
25
+ if (value)
26
+ h.set("authorization", `Bearer ${value}`);
27
+ return h;
28
+ },
29
+ });
30
+ return createTypedClient(http);
31
+ }
32
+ /** 瀏覽器端保存 Bearer 的預設位置(`<kanorio-login>` 寫入、其他元件讀取) */
33
+ export const CUSTOMER_TOKEN_STORAGE_KEY = "kanorio.customer.token";
34
+ export function readStoredCustomerToken(storage = typeof localStorage === "undefined" ? undefined : localStorage) {
35
+ try {
36
+ return storage?.getItem(CUSTOMER_TOKEN_STORAGE_KEY) ?? null;
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ export function writeStoredCustomerToken(token, storage = typeof localStorage === "undefined" ? undefined : localStorage) {
43
+ try {
44
+ if (token)
45
+ storage?.setItem(CUSTOMER_TOKEN_STORAGE_KEY, token);
46
+ else
47
+ storage?.removeItem(CUSTOMER_TOKEN_STORAGE_KEY);
48
+ }
49
+ catch {
50
+ // 隱私模式或禁用儲存:忽略
51
+ }
52
+ }
53
+ /** HTTP 成功回應不含 ok;元件共用的結果型別用 ok 區分成功與失敗 */
54
+ function succeed(body) {
55
+ return { ...body, ok: true };
56
+ }
57
+ /**
58
+ * 給 Elements 的內容客戶端:錯誤不丟、改回 `{ ok: false, code }`(結果型別,與 HTTP 形狀無關),元件依 code 顯示鎖定/未開放/到期。
59
+ * 匿名(無 token)時 `openUnit` 走 Delivery 的 `POST /api/v1/units/:id/open`(只放行試看單元)。
60
+ */
61
+ export function createCustomerContentClient(options) {
62
+ const client = createCustomerClient(options);
63
+ const anonymous = createHttpClient({ ...options, baseUrl: `${options.siteUrl.replace(/\/+$/, "")}/api/v1` });
64
+ const toFail = (error) => {
65
+ if (error instanceof KanorioApiError)
66
+ return { ok: false, code: error.code, ...(error.availableAt ? { availableAt: error.availableAt } : {}) };
67
+ return { ok: false, code: "NETWORK_ERROR" };
68
+ };
69
+ return {
70
+ async openUnit(unitId, mode, openOptions) {
71
+ try {
72
+ const token = await resolveToken(options.token);
73
+ if (!token)
74
+ return succeed(await anonymous.request("POST", `units/${encodeURIComponent(unitId)}/open`, { body: { mode } }));
75
+ const body = openOptions?.attachmentId ? { mode, attachmentId: openOptions.attachmentId } : { mode };
76
+ return succeed((await client.post("/units/{id}/open", { params: { id: unitId }, query: options.locale ? { locale: options.locale } : {}, body })));
77
+ }
78
+ catch (error) {
79
+ return toFail(error);
80
+ }
81
+ },
82
+ async reportProgress(input) {
83
+ try {
84
+ return succeed((await client.post("/progress", { body: input })));
85
+ }
86
+ catch (error) {
87
+ return toFail(error);
88
+ }
89
+ },
90
+ async submitQuiz(input) {
91
+ try {
92
+ return succeed((await client.post("/units/{id}/quiz", { params: { id: input.unitId }, body: { answers: input.answers } })));
93
+ }
94
+ catch (error) {
95
+ return toFail(error);
96
+ }
97
+ },
98
+ async getCertificate(deliverableId) {
99
+ try {
100
+ return succeed((await client.get("/deliverables/{deliverableId}/certificate", { params: { deliverableId } })));
101
+ }
102
+ catch (error) {
103
+ return toFail(error);
104
+ }
105
+ },
106
+ async getTranscript(unitId, locale) {
107
+ try {
108
+ const wanted = locale ?? options.locale;
109
+ return succeed((await client.get("/units/{id}/transcript", { params: { id: unitId }, query: wanted ? { locale: wanted } : {} })));
110
+ }
111
+ catch (error) {
112
+ return toFail(error);
113
+ }
114
+ },
115
+ };
116
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Content Delivery API(`https://{site}/api/v1`,匿名、可快取)。
3
+ * 型別由 `packages/shared/openapi/delivery.json` 產生。`siteUrl` 是站台網址(託管子網域或自訂網域)。
4
+ */
5
+ import type { paths as DeliveryPaths } from "./generated/delivery.js";
6
+ import { type HttpClientOptions } from "./http.js";
7
+ import { type SeoHelpers } from "./seo.js";
8
+ import { type TypedClient } from "./typed.js";
9
+ export type { DeliveryPaths };
10
+ export type DeliveryClient = TypedClient<DeliveryPaths> & {
11
+ readonly seo: SeoHelpers;
12
+ };
13
+ export interface DeliveryClientOptions extends Omit<HttpClientOptions, "baseUrl"> {
14
+ /** 例如 `https://demo.kanorio.com` */
15
+ siteUrl: string;
16
+ /**
17
+ * 唯讀預覽權杖(`knr_pv_…`,由後台「網站設定 › 開發者」或 Agent `site.create_preview_token` 簽發)。
18
+ * 設定後每個請求帶 `X-Kanorio-Preview`,回未發布草稿且不經快取;可傳函式供 Draft Mode 動態決定。
19
+ */
20
+ previewToken?: string | (() => string | null | undefined | Promise<string | null | undefined>);
21
+ }
22
+ export declare const DELIVERY_PREVIEW_HEADER = "x-kanorio-preview";
23
+ export declare function deliveryBaseUrl(siteUrl: string): string;
24
+ export declare function createDeliveryClient(options: DeliveryClientOptions): DeliveryClient;
25
+ export declare const DELIVERY_CACHE_TAGS_HEADER = "x-kanorio-cache-tags";
26
+ /**
27
+ * 從 Delivery API 回應標頭(`X-Kanorio-Cache-Tags`)解析快取標籤陣列(原始字串,與 Webhook `data.cacheTags` 同一套字彙)。
28
+ * 要打在框架快取上請用 `frameworkCacheTags`(加命名空間)。
29
+ */
30
+ export declare function parseDeliveryCacheTags(headers: Headers | Record<string, string | undefined> | null | undefined): string[];
31
+ /**
32
+ * 回應的快取標籤加上命名空間(預設 `kanorio:`),直接交給 Next.js `fetch(..., { next: { tags } })` 或 `cacheTag()`;
33
+ * `createRevalidateHandler` 收到事件時用同一個前綴呼叫 `revalidateTag`,兩邊才對得上。收標頭或已解析的陣列都可以。
34
+ */
35
+ export declare function frameworkCacheTags(source: Headers | Record<string, string | undefined> | readonly string[] | null | undefined, prefix?: string): string[];
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Content Delivery API(`https://{site}/api/v1`,匿名、可快取)。
3
+ * 型別由 `packages/shared/openapi/delivery.json` 產生。`siteUrl` 是站台網址(託管子網域或自訂網域)。
4
+ */
5
+ import { createHttpClient } from "./http.js";
6
+ import { createSeoHelpers } from "./seo.js";
7
+ import { createTypedClient } from "./typed.js";
8
+ import { DEFAULT_CACHE_TAG_PREFIX, DELIVERY_CACHE_TAGS_HEADER as SHARED_CACHE_TAGS_HEADER, parseCacheTagsHeader, prefixCacheTags } from "./shared/api/delivery/cache-tags.js";
9
+ export const DELIVERY_PREVIEW_HEADER = "x-kanorio-preview";
10
+ export function deliveryBaseUrl(siteUrl) {
11
+ return `${siteUrl.replace(/\/+$/, "")}/api/v1`;
12
+ }
13
+ export function createDeliveryClient(options) {
14
+ const { siteUrl, previewToken, headers: baseHeaders, ...rest } = options;
15
+ const headers = previewToken === undefined
16
+ ? baseHeaders
17
+ : async () => {
18
+ const merged = new Headers(typeof baseHeaders === "function" ? await baseHeaders() : baseHeaders);
19
+ const token = typeof previewToken === "function" ? await previewToken() : previewToken;
20
+ if (token)
21
+ merged.set(DELIVERY_PREVIEW_HEADER, token);
22
+ return merged;
23
+ };
24
+ const baseClient = createTypedClient(createHttpClient({ ...rest, headers, baseUrl: deliveryBaseUrl(siteUrl) }));
25
+ const seoHelpers = createSeoHelpers({ siteUrl, fetch: rest.fetch });
26
+ return Object.assign(baseClient, { seo: seoHelpers });
27
+ }
28
+ export const DELIVERY_CACHE_TAGS_HEADER = SHARED_CACHE_TAGS_HEADER;
29
+ /**
30
+ * 從 Delivery API 回應標頭(`X-Kanorio-Cache-Tags`)解析快取標籤陣列(原始字串,與 Webhook `data.cacheTags` 同一套字彙)。
31
+ * 要打在框架快取上請用 `frameworkCacheTags`(加命名空間)。
32
+ */
33
+ export function parseDeliveryCacheTags(headers) {
34
+ if (!headers)
35
+ return [];
36
+ const raw = typeof headers.get === "function"
37
+ ? headers.get(DELIVERY_CACHE_TAGS_HEADER)
38
+ : headers[DELIVERY_CACHE_TAGS_HEADER] ??
39
+ headers["X-Kanorio-Cache-Tags"];
40
+ return parseCacheTagsHeader(raw);
41
+ }
42
+ /**
43
+ * 回應的快取標籤加上命名空間(預設 `kanorio:`),直接交給 Next.js `fetch(..., { next: { tags } })` 或 `cacheTag()`;
44
+ * `createRevalidateHandler` 收到事件時用同一個前綴呼叫 `revalidateTag`,兩邊才對得上。收標頭或已解析的陣列都可以。
45
+ */
46
+ export function frameworkCacheTags(source, prefix = DEFAULT_CACHE_TAG_PREFIX) {
47
+ const raw = Array.isArray(source) ? source : parseDeliveryCacheTags(source);
48
+ return prefixCacheTags(raw, prefix);
49
+ }