@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.
- package/LICENSE +21 -0
- package/README.md +66 -2
- package/dist/customer-oauth.d.ts +86 -0
- package/dist/customer-oauth.js +112 -0
- package/dist/customer.d.ts +176 -0
- package/dist/customer.js +116 -0
- package/dist/delivery.d.ts +35 -0
- package/dist/delivery.js +49 -0
- package/dist/edge.d.ts +104 -0
- package/dist/edge.js +287 -0
- package/dist/forms.d.ts +123 -0
- package/dist/forms.js +130 -0
- package/dist/generated/customer.d.ts +3157 -0
- package/dist/generated/delivery.d.ts +2380 -0
- package/dist/generated/management.d.ts +38248 -0
- package/dist/http.d.ts +73 -0
- package/dist/http.js +162 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +17 -0
- package/dist/locales.d.ts +80 -0
- package/dist/locales.js +81 -0
- package/dist/management.d.ts +19 -0
- package/dist/management.js +22 -0
- package/dist/paginate.d.ts +18 -0
- package/dist/paginate.js +27 -0
- package/dist/preview.d.ts +40 -0
- package/dist/preview.js +131 -0
- package/dist/protection.d.ts +74 -0
- package/dist/protection.js +68 -0
- package/dist/revalidate.d.ts +84 -0
- package/dist/revalidate.js +143 -0
- package/dist/seo.d.ts +120 -0
- package/dist/seo.js +125 -0
- package/dist/server-key.d.ts +71 -0
- package/dist/server-key.js +103 -0
- package/dist/shared/api/delivery/cache-tags.d.ts +142 -0
- package/dist/shared/api/delivery/cache-tags.js +212 -0
- package/dist/shared/api/server-key.d.ts +86 -0
- package/dist/shared/api/server-key.js +252 -0
- package/dist/shared/business-registry/attribution.d.ts +14 -0
- package/dist/shared/business-registry/attribution.js +28 -0
- package/dist/shared/business-registry/define.d.ts +3 -0
- package/dist/shared/business-registry/define.js +4 -0
- package/dist/shared/business-registry/formats/eu-vat.d.ts +2 -0
- package/dist/shared/business-registry/formats/eu-vat.js +54 -0
- package/dist/shared/business-registry/formats/hk-br.d.ts +5 -0
- package/dist/shared/business-registry/formats/hk-br.js +23 -0
- package/dist/shared/business-registry/formats/jp-trn.d.ts +6 -0
- package/dist/shared/business-registry/formats/jp-trn.js +23 -0
- package/dist/shared/business-registry/formats/kr-brn.d.ts +6 -0
- package/dist/shared/business-registry/formats/kr-brn.js +30 -0
- package/dist/shared/business-registry/formats/my.d.ts +7 -0
- package/dist/shared/business-registry/formats/my.js +32 -0
- package/dist/shared/business-registry/formats/sg-uen.d.ts +1 -0
- package/dist/shared/business-registry/formats/sg-uen.js +21 -0
- package/dist/shared/business-registry/formats/tw-vat.d.ts +10 -0
- package/dist/shared/business-registry/formats/tw-vat.js +32 -0
- package/dist/shared/business-registry/index.d.ts +9 -0
- package/dist/shared/business-registry/index.js +10 -0
- package/dist/shared/business-registry/lookup-wire.d.ts +33 -0
- package/dist/shared/business-registry/lookup-wire.js +8 -0
- package/dist/shared/business-registry/normalize.d.ts +7 -0
- package/dist/shared/business-registry/normalize.js +12 -0
- package/dist/shared/business-registry/registry.d.ts +26 -0
- package/dist/shared/business-registry/registry.js +67 -0
- package/dist/shared/business-registry/types.d.ts +60 -0
- package/dist/shared/business-registry/types.js +10 -0
- package/dist/shared/localization/locale-path.d.ts +38 -0
- package/dist/shared/localization/locale-path.js +76 -0
- package/dist/shared/localization/request-locale.d.ts +42 -0
- package/dist/shared/localization/request-locale.js +61 -0
- package/dist/shared/seo/alternates.d.ts +61 -0
- package/dist/shared/seo/alternates.js +71 -0
- package/dist/shared/types/forms-logic.d.ts +96 -0
- package/dist/shared/types/forms-logic.js +209 -0
- package/dist/shared/types/number-input.d.ts +5 -0
- package/dist/shared/types/number-input.js +16 -0
- package/dist/shared/utils/redirect-matching.d.ts +67 -0
- package/dist/shared/utils/redirect-matching.js +148 -0
- package/dist/tax-id.d.ts +7 -0
- package/dist/tax-id.js +6 -0
- package/dist/typed.d.ts +85 -0
- package/dist/typed.js +28 -0
- package/package.json +86 -3
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 三個客戶端共用的 fetch 核心:組 URL、帶標頭、解 JSON、把錯誤封包轉成 `KanorioApiError`、
|
|
3
|
+
* 讀 Deprecation/Sunset 標頭(RFC 9745/8594)。不含任何業務邏輯。
|
|
4
|
+
*/
|
|
5
|
+
import { type ServerKeyOptions } from "./server-key.js";
|
|
6
|
+
export declare const KANORIO_SDK_VERSION = "1.0.0";
|
|
7
|
+
export declare const SDK_VERSION_HEADER = "x-kanorio-sdk-version";
|
|
8
|
+
export interface ErrorEnvelope {
|
|
9
|
+
error: {
|
|
10
|
+
code: string;
|
|
11
|
+
message: string;
|
|
12
|
+
details?: unknown;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export declare function isErrorEnvelope(value: unknown): value is ErrorEnvelope;
|
|
16
|
+
export declare class KanorioApiError extends Error {
|
|
17
|
+
readonly code: string;
|
|
18
|
+
readonly status: number;
|
|
19
|
+
readonly details?: unknown | undefined;
|
|
20
|
+
/** 429/503 時建議等待的秒數(`Retry-After` 標頭或 `details.retryAfter`) */
|
|
21
|
+
readonly retryAfter?: number | undefined;
|
|
22
|
+
/** 存取判定附帶的開放時間(`NOT_RELEASED` 的 `details.availableAt`) */
|
|
23
|
+
readonly availableAt?: string | undefined;
|
|
24
|
+
constructor(code: string, status: number, message: string, details?: unknown | undefined,
|
|
25
|
+
/** 429/503 時建議等待的秒數(`Retry-After` 標頭或 `details.retryAfter`) */
|
|
26
|
+
retryAfter?: number | undefined,
|
|
27
|
+
/** 存取判定附帶的開放時間(`NOT_RELEASED` 的 `details.availableAt`) */
|
|
28
|
+
availableAt?: string | undefined);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The request never reached the API: Kanorio's edge answered with a challenge page (HTTP 403, HTML).
|
|
32
|
+
* On a server this means the write needs a server key; `message` says exactly what to do.
|
|
33
|
+
*/
|
|
34
|
+
export declare class KanorioEdgeChallengeError extends KanorioApiError {
|
|
35
|
+
constructor(message: string);
|
|
36
|
+
}
|
|
37
|
+
export declare function toApiError(status: number, body: unknown, headers: Headers): KanorioApiError;
|
|
38
|
+
export interface DeprecationNotice {
|
|
39
|
+
method: string;
|
|
40
|
+
path: string;
|
|
41
|
+
sunset: string | null;
|
|
42
|
+
successor: string | null;
|
|
43
|
+
policy: string | null;
|
|
44
|
+
}
|
|
45
|
+
export declare function parseDeprecation(headers: Headers, method: string, path: string): DeprecationNotice | null;
|
|
46
|
+
export type QueryValue = string | number | boolean | null | undefined;
|
|
47
|
+
export type Query = Record<string, QueryValue | QueryValue[]>;
|
|
48
|
+
export declare function buildUrl(baseUrl: string, path: string, query?: Query): string;
|
|
49
|
+
export interface HttpClientOptions extends ServerKeyOptions {
|
|
50
|
+
baseUrl: string;
|
|
51
|
+
/** 省略時用全域 `fetch` */
|
|
52
|
+
fetch?: typeof fetch;
|
|
53
|
+
/** 每次請求都附上的標頭(可為函式,供動態 token) */
|
|
54
|
+
headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
|
|
55
|
+
/** 逾時毫秒;省略不設 */
|
|
56
|
+
timeoutMs?: number;
|
|
57
|
+
/** 伺服端宣告淘汰時呼叫(預設 `console.warn` 一次) */
|
|
58
|
+
onDeprecation?: (notice: DeprecationNotice) => void;
|
|
59
|
+
/** 使用者代理字串(Node 端);瀏覽器忽略 */
|
|
60
|
+
userAgent?: string;
|
|
61
|
+
}
|
|
62
|
+
export interface RequestOptions {
|
|
63
|
+
query?: Query;
|
|
64
|
+
body?: unknown;
|
|
65
|
+
headers?: HeadersInit;
|
|
66
|
+
signal?: AbortSignal;
|
|
67
|
+
}
|
|
68
|
+
export interface HttpClient {
|
|
69
|
+
request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
|
|
70
|
+
/** 完整回應(含標頭與狀態),不丟錯 */
|
|
71
|
+
raw(method: string, path: string, options?: RequestOptions): Promise<Response>;
|
|
72
|
+
}
|
|
73
|
+
export declare function createHttpClient(options: HttpClientOptions): HttpClient;
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 三個客戶端共用的 fetch 核心:組 URL、帶標頭、解 JSON、把錯誤封包轉成 `KanorioApiError`、
|
|
3
|
+
* 讀 Deprecation/Sunset 標頭(RFC 9745/8594)。不含任何業務邏輯。
|
|
4
|
+
*/
|
|
5
|
+
import { EDGE_CHALLENGE_CODE, edgeChallengeMessage, isEdgeChallenge, serverKeyRequest } from "./server-key.js";
|
|
6
|
+
export const KANORIO_SDK_VERSION = "1.0.0";
|
|
7
|
+
export const SDK_VERSION_HEADER = "x-kanorio-sdk-version";
|
|
8
|
+
export function isErrorEnvelope(value) {
|
|
9
|
+
if (typeof value !== "object" || value === null)
|
|
10
|
+
return false;
|
|
11
|
+
const error = value.error;
|
|
12
|
+
if (typeof error !== "object" || error === null)
|
|
13
|
+
return false;
|
|
14
|
+
const { code, message } = error;
|
|
15
|
+
return typeof code === "string" && typeof message === "string";
|
|
16
|
+
}
|
|
17
|
+
export class KanorioApiError extends Error {
|
|
18
|
+
code;
|
|
19
|
+
status;
|
|
20
|
+
details;
|
|
21
|
+
retryAfter;
|
|
22
|
+
availableAt;
|
|
23
|
+
constructor(code, status, message, details,
|
|
24
|
+
/** 429/503 時建議等待的秒數(`Retry-After` 標頭或 `details.retryAfter`) */
|
|
25
|
+
retryAfter,
|
|
26
|
+
/** 存取判定附帶的開放時間(`NOT_RELEASED` 的 `details.availableAt`) */
|
|
27
|
+
availableAt) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.code = code;
|
|
30
|
+
this.status = status;
|
|
31
|
+
this.details = details;
|
|
32
|
+
this.retryAfter = retryAfter;
|
|
33
|
+
this.availableAt = availableAt;
|
|
34
|
+
this.name = "KanorioApiError";
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The request never reached the API: Kanorio's edge answered with a challenge page (HTTP 403, HTML).
|
|
39
|
+
* On a server this means the write needs a server key; `message` says exactly what to do.
|
|
40
|
+
*/
|
|
41
|
+
export class KanorioEdgeChallengeError extends KanorioApiError {
|
|
42
|
+
constructor(message) {
|
|
43
|
+
super(EDGE_CHALLENGE_CODE, 403, message);
|
|
44
|
+
this.name = "KanorioEdgeChallengeError";
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export function toApiError(status, body, headers) {
|
|
48
|
+
const retryHeader = headers.get("retry-after");
|
|
49
|
+
const retryAfter = retryHeader ? Number.parseInt(retryHeader, 10) : undefined;
|
|
50
|
+
if (isErrorEnvelope(body)) {
|
|
51
|
+
// 三套 API 同一個錯誤信封(ADR-0006 決定 2-1):補充欄位在 details
|
|
52
|
+
const details = body.error.details;
|
|
53
|
+
const detailRetry = typeof details?.retryAfter === "number" ? details.retryAfter : undefined;
|
|
54
|
+
const availableAt = typeof details?.availableAt === "string" ? details.availableAt : undefined;
|
|
55
|
+
return new KanorioApiError(body.error.code, status, body.error.message, body.error.details, retryAfter ?? detailRetry, availableAt);
|
|
56
|
+
}
|
|
57
|
+
const code = status === 401 ? "UNAUTHENTICATED" : status === 404 ? "NOT_FOUND" : status === 429 ? "RATE_LIMITED" : status >= 500 ? "UPSTREAM_ERROR" : "HTTP_ERROR";
|
|
58
|
+
const text = typeof body === "string" ? body.slice(0, 200) : "";
|
|
59
|
+
return new KanorioApiError(code, status, text || `Request failed with HTTP ${status}.`, undefined, retryAfter);
|
|
60
|
+
}
|
|
61
|
+
export function parseDeprecation(headers, method, path) {
|
|
62
|
+
if (!headers.has("deprecation"))
|
|
63
|
+
return null;
|
|
64
|
+
const link = headers.get("link") ?? "";
|
|
65
|
+
const rel = (name) => {
|
|
66
|
+
const match = link.match(new RegExp(`<([^>]+)>;\\s*rel="${name}"`));
|
|
67
|
+
return match?.[1] ?? null;
|
|
68
|
+
};
|
|
69
|
+
return { method, path, sunset: headers.get("sunset"), successor: rel("successor-version"), policy: rel("deprecation") };
|
|
70
|
+
}
|
|
71
|
+
export function buildUrl(baseUrl, path, query) {
|
|
72
|
+
const url = new URL(path.replace(/^\//, ""), baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`);
|
|
73
|
+
if (query) {
|
|
74
|
+
for (const [key, raw] of Object.entries(query)) {
|
|
75
|
+
const values = Array.isArray(raw) ? raw : [raw];
|
|
76
|
+
for (const v of values) {
|
|
77
|
+
if (v === undefined || v === null)
|
|
78
|
+
continue;
|
|
79
|
+
url.searchParams.append(key, String(v));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return url.toString();
|
|
84
|
+
}
|
|
85
|
+
export function createHttpClient(options) {
|
|
86
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
87
|
+
if (!fetchImpl)
|
|
88
|
+
throw new Error("@kanorio/sdk: global fetch is not available; pass `fetch` in options.");
|
|
89
|
+
const warned = new Set();
|
|
90
|
+
const onDeprecation = options.onDeprecation ??
|
|
91
|
+
((notice) => {
|
|
92
|
+
const key = `${notice.method} ${notice.path}`;
|
|
93
|
+
if (warned.has(key))
|
|
94
|
+
return;
|
|
95
|
+
warned.add(key);
|
|
96
|
+
console.warn(`[kanorio] ${key} is deprecated${notice.sunset ? ` (sunset ${notice.sunset})` : ""}${notice.successor ? `; use ${notice.successor}` : ""}.`);
|
|
97
|
+
});
|
|
98
|
+
async function raw(method, path, req = {}) {
|
|
99
|
+
const headers = new Headers(typeof options.headers === "function" ? await options.headers() : options.headers);
|
|
100
|
+
new Headers(req.headers).forEach((v, k) => headers.set(k, v));
|
|
101
|
+
headers.set("accept", "application/json");
|
|
102
|
+
if (typeof document === "undefined") {
|
|
103
|
+
headers.set(SDK_VERSION_HEADER, KANORIO_SDK_VERSION);
|
|
104
|
+
if (options.userAgent)
|
|
105
|
+
headers.set("user-agent", options.userAgent);
|
|
106
|
+
}
|
|
107
|
+
let body;
|
|
108
|
+
if (req.body !== undefined) {
|
|
109
|
+
headers.set("content-type", "application/json");
|
|
110
|
+
body = JSON.stringify(req.body);
|
|
111
|
+
}
|
|
112
|
+
const url = buildUrl(options.baseUrl, path, req.query);
|
|
113
|
+
// 網站主機金鑰:只在伺服器端、只走 https、不跟轉址(自訂標頭在跨來源轉址時不會被剝掉)
|
|
114
|
+
const viaServerKey = await serverKeyRequest(options, url);
|
|
115
|
+
if (viaServerKey)
|
|
116
|
+
for (const [name, value] of Object.entries(viaServerKey.headers))
|
|
117
|
+
headers.set(name, value);
|
|
118
|
+
const controller = options.timeoutMs ? new AbortController() : null;
|
|
119
|
+
const timer = controller ? setTimeout(() => controller.abort(), options.timeoutMs) : null;
|
|
120
|
+
if (controller && req.signal)
|
|
121
|
+
req.signal.addEventListener("abort", () => controller.abort(), { once: true });
|
|
122
|
+
try {
|
|
123
|
+
return await fetchImpl(url, {
|
|
124
|
+
method,
|
|
125
|
+
headers,
|
|
126
|
+
body,
|
|
127
|
+
signal: controller?.signal ?? req.signal,
|
|
128
|
+
...(viaServerKey ? { redirect: viaServerKey.redirect } : {}),
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
finally {
|
|
132
|
+
if (timer)
|
|
133
|
+
clearTimeout(timer);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
async function request(method, path, req = {}) {
|
|
137
|
+
const res = await raw(method, path, req);
|
|
138
|
+
// 邊緣的 challenge 頁不是 API 回應:給一個說得出下一步的錯誤,而不是「HTTP 403」加一段 HTML
|
|
139
|
+
if (isEdgeChallenge(res))
|
|
140
|
+
throw new KanorioEdgeChallengeError(edgeChallengeMessage(Boolean(options.serverKey)));
|
|
141
|
+
const notice = parseDeprecation(res.headers, method, path);
|
|
142
|
+
if (notice)
|
|
143
|
+
onDeprecation(notice);
|
|
144
|
+
const text = await res.text();
|
|
145
|
+
let parsed = text;
|
|
146
|
+
if (text) {
|
|
147
|
+
try {
|
|
148
|
+
parsed = JSON.parse(text);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
parsed = text;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
parsed = undefined;
|
|
156
|
+
}
|
|
157
|
+
if (!res.ok)
|
|
158
|
+
throw toApiError(res.status, parsed, res.headers);
|
|
159
|
+
return parsed;
|
|
160
|
+
}
|
|
161
|
+
return { request, raw };
|
|
162
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export { KanorioApiError, KanorioEdgeChallengeError, KANORIO_SDK_VERSION, SDK_VERSION_HEADER, type DeprecationNotice, type HttpClientOptions, type HttpClient, } from "./http.js";
|
|
2
|
+
export { visitorIpFromRequest, SERVER_KEY_HEADER, SERVER_KEY_VISITOR_IP_HEADER, EDGE_CHALLENGE_CODE, type ServerKeyOptions, type VisitorIpSource, type VisitorIpOptions, } from "./server-key.js";
|
|
3
|
+
export type { TypedClient, TypedRequest, SuccessResponseOf } from "./typed.js";
|
|
4
|
+
export { paginate, listAll, type ListPage } from "./paginate.js";
|
|
5
|
+
export { createManagementClient, DEFAULT_MANAGEMENT_BASE_URL, type ManagementClient, type ManagementClientOptions, type ManagementPaths, } from "./management.js";
|
|
6
|
+
export { createDeliveryClient, deliveryBaseUrl, parseDeliveryCacheTags, frameworkCacheTags, DELIVERY_CACHE_TAGS_HEADER, DELIVERY_PREVIEW_HEADER, type DeliveryClient, type DeliveryClientOptions, type DeliveryPaths, } from "./delivery.js";
|
|
7
|
+
export { createCustomerClient, createCustomerContentClient, customerBaseUrl, readStoredCustomerToken, writeStoredCustomerToken, CUSTOMER_TOKEN_STORAGE_KEY, type CustomerClient, type CustomerClientOptions, type CustomerContentClientLike, type CustomerPaths, type CustomerTokenSource, } from "./customer.js";
|
|
8
|
+
export { buildHostedLoginUrl, completeHostedCustomerLogin, createPkcePair, exchangeHostedLoginCode, refreshCustomerToken, revokeCustomerToken, startHostedCustomerLogin, type CompleteHostedLoginOptions, type HostedLoginGrant, type HostedLoginUrlParams, type StartHostedLoginOptions, } from "./customer-oauth.js";
|
|
9
|
+
export { seo, seoRewrites, fetchDeliveryJsonLd, fetchSitemapEntries, createSeoHelpers, listingRobots, type ListingKey, type ListingState, type SeoRewriteFramework, type NextSeoRewriteRule, type SeoRewritesOptions, type DeliveryJsonLdResult, type SitemapEntry, type SitemapEntriesResult, type SeoHelpers, } from "./seo.js";
|
|
10
|
+
export { cacheTag, localizeCacheTag, localizeCacheTags, prefixCacheTags, responseCacheTags, eventCacheTags, DEFAULT_CACHE_TAG_PREFIX, CACHE_TAG_LOCALE_SEPARATOR, DELIVERY_CACHE_TAG_LIMIT, type TranslationCacheScope, } from "./shared/api/delivery/cache-tags.js";
|
|
11
|
+
export { locales, buildAlternates, requestLocaleOf, localizedPath, languageSwitcher, resolveRequestLocale, withLocalePrefix, localeRootPath, localePrefixMap, localePrefixOf, localeOfPrefix, hreflangOf, buildSiteAlternates, sitemapAlternates, type BuildAlternatesOptions, type PageAlternates, type HreflangLink, type SiteLocaleMeta, type LocaleRoute, type RequestLocaleResult, type SiteAlternates, } from "./locales.js";
|
|
12
|
+
export { revalidate, createRevalidateHandler, verifyWebhookSignature, computeWebhookSignature, buildWebhookSignatureHeader, parseWebhookSignatureHeader, extractWebhookCacheTags, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_DELIVERY_HEADER, WEBHOOK_EVENT_HEADER, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, type VerifyWebhookSignatureOptions, type ParsedWebhookSignature, type WebhookEnvelope, type RevalidateHandlerOptions, } from "./revalidate.js";
|
|
13
|
+
export { forms, createFormsHelpers, protectionFromChallenge, uploadProtectionFromChallenge, type FormApiError, type FormProtectionFields, type FormChallengeResponse, type FormUploadTicketRequest, type FormUploadTicketResponse, type FormSubmitInput, type FormSubmitResult, type FormsHelpers, } from "./forms.js";
|
|
14
|
+
export { edge, createKanorioMiddleware, classifyEdgeUserAgent, isEdgeBotBlocked, EDGE_BOT_LIST, CRAWLER_LIST_VERSION, type EdgeBotInfo, type RedirectRule, type KanorioMiddlewareOptions, type MiddlewareDecision, type KanorioMiddleware, } from "./edge.js";
|
|
15
|
+
export { preview, previewHeaders, tokenFromCookieHeader, isValidPreviewTokenFormat, sanitizePreviewRedirectPath, createPreviewRouteHandler, PREVIEW_TOKEN_PREFIX, PREVIEW_COOKIE_NAME, type PreviewRouteHandlerOptions, } from "./preview.js";
|
|
16
|
+
export { protectionFromChallenge as solveProtectionChallenge, solveAltchaChallenge, type AltchaChallenge, type ProtectionChallenge, type ProtectionFields, type ProtectionProvider, } from "./protection.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export { KanorioApiError, KanorioEdgeChallengeError, KANORIO_SDK_VERSION, SDK_VERSION_HEADER, } from "./http.js";
|
|
2
|
+
export { visitorIpFromRequest, SERVER_KEY_HEADER, SERVER_KEY_VISITOR_IP_HEADER, EDGE_CHALLENGE_CODE, } from "./server-key.js";
|
|
3
|
+
export { paginate, listAll } from "./paginate.js";
|
|
4
|
+
export { createManagementClient, DEFAULT_MANAGEMENT_BASE_URL, } from "./management.js";
|
|
5
|
+
export { createDeliveryClient, deliveryBaseUrl, parseDeliveryCacheTags, frameworkCacheTags, DELIVERY_CACHE_TAGS_HEADER, DELIVERY_PREVIEW_HEADER, } from "./delivery.js";
|
|
6
|
+
export { createCustomerClient, createCustomerContentClient, customerBaseUrl, readStoredCustomerToken, writeStoredCustomerToken, CUSTOMER_TOKEN_STORAGE_KEY, } from "./customer.js";
|
|
7
|
+
export { buildHostedLoginUrl, completeHostedCustomerLogin, createPkcePair, exchangeHostedLoginCode, refreshCustomerToken, revokeCustomerToken, startHostedCustomerLogin, } from "./customer-oauth.js";
|
|
8
|
+
export { seo, seoRewrites, fetchDeliveryJsonLd, fetchSitemapEntries, createSeoHelpers, listingRobots, } from "./seo.js";
|
|
9
|
+
export { cacheTag, localizeCacheTag, localizeCacheTags, prefixCacheTags, responseCacheTags, eventCacheTags, DEFAULT_CACHE_TAG_PREFIX, CACHE_TAG_LOCALE_SEPARATOR, DELIVERY_CACHE_TAG_LIMIT, } from "./shared/api/delivery/cache-tags.js";
|
|
10
|
+
export { locales, buildAlternates, requestLocaleOf, localizedPath, languageSwitcher, resolveRequestLocale, withLocalePrefix, localeRootPath, localePrefixMap, localePrefixOf, localeOfPrefix, hreflangOf, buildSiteAlternates, sitemapAlternates, } from "./locales.js";
|
|
11
|
+
export { revalidate, createRevalidateHandler, verifyWebhookSignature, computeWebhookSignature, buildWebhookSignatureHeader, parseWebhookSignatureHeader, extractWebhookCacheTags, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_DELIVERY_HEADER, WEBHOOK_EVENT_HEADER, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, } from "./revalidate.js";
|
|
12
|
+
export { forms, createFormsHelpers, protectionFromChallenge, uploadProtectionFromChallenge, } from "./forms.js";
|
|
13
|
+
export { edge, createKanorioMiddleware, classifyEdgeUserAgent, isEdgeBotBlocked, EDGE_BOT_LIST, CRAWLER_LIST_VERSION, } from "./edge.js";
|
|
14
|
+
export { preview, previewHeaders, tokenFromCookieHeader, isValidPreviewTokenFormat, sanitizePreviewRedirectPath, createPreviewRouteHandler, PREVIEW_TOKEN_PREFIX, PREVIEW_COOKIE_NAME, } from "./preview.js";
|
|
15
|
+
// 人機驗證(表單與顧客登入共用):表單的 `protectionFromChallenge(formId, challenge, renderedAt)` 在上面;
|
|
16
|
+
// 登入(`GET /customer/auth/protection`)用 `solveProtectionChallenge(challenge, { context, renderedAt })`
|
|
17
|
+
export { protectionFromChallenge as solveProtectionChallenge, solveAltchaChallenge, } from "./protection.js";
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 多語網站的語系路由與 hreflang(ADR-0010 決策 4、10、13;Headless 同權)。
|
|
3
|
+
*
|
|
4
|
+
* 與 Kanorio 代管站同一套純函式(`src/shared/**` 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製):
|
|
5
|
+
* - 主語系無前綴(`/about`),次語系子目錄(`/en/about`);前綴是站主存下來的 `pathPrefix`(`GET /api/v1/site` 的 `locales[]`)
|
|
6
|
+
* - `resolveRequestLocale` 認路徑第一段;主語系碼當前綴(`/zh-hant/about`)要 301 回無前綴
|
|
7
|
+
* - `buildAlternates` 算 canonical 與 hreflang:每個語系版本 self-canonical、只列這一頁有翻譯的語系、x-default 指主語系;
|
|
8
|
+
* 未翻譯的 fallback 頁 canonical 指主語系網址、不出 hreflang
|
|
9
|
+
*/
|
|
10
|
+
import { type LocaleRoute } from "./shared/localization/locale-path.js";
|
|
11
|
+
import { type RequestLocaleResult } from "./shared/localization/request-locale.js";
|
|
12
|
+
import { hreflangEntries, type SiteAlternates } from "./shared/seo/alternates.js";
|
|
13
|
+
export { localeOfPrefix, localePrefixMap, localePrefixOf, languageOfLocale, type LocaleRoute } from "./shared/localization/locale-path.js";
|
|
14
|
+
export { resolveRequestLocale, withLocalePrefix, localeRootPath, type RequestLocaleInput, type RequestLocaleResult } from "./shared/localization/request-locale.js";
|
|
15
|
+
export { buildSiteAlternates, hreflangEntries, hreflangOf, localizedSiteUrl, sitemapAlternates, type SiteAlternates, type SiteAlternatesInput, type LocalePrefixes } from "./shared/seo/alternates.js";
|
|
16
|
+
/** `GET /api/v1/site` 回應裡與語系有關的欄位 */
|
|
17
|
+
export interface SiteLocaleMeta {
|
|
18
|
+
primaryLocale?: string | null;
|
|
19
|
+
locales?: readonly LocaleRoute[] | null;
|
|
20
|
+
}
|
|
21
|
+
export interface BuildAlternatesOptions {
|
|
22
|
+
/** 外部前端的對外網址,不含尾斜線(`https://www.example.com`) */
|
|
23
|
+
siteUrl: string;
|
|
24
|
+
/** `GET /api/v1/site` 的回應(`primaryLocale`、`locales[]`) */
|
|
25
|
+
site: SiteLocaleMeta;
|
|
26
|
+
/** 主語系空間的路徑(無前綴):`/about`、`/blog/hello`、首頁 `/` */
|
|
27
|
+
path: string;
|
|
28
|
+
/** 網址上的語系(`resolveRequestLocale` 的 `locale`);省略=主語系 */
|
|
29
|
+
requestLocale?: string | null;
|
|
30
|
+
/** 內容實際交付的語系(Delivery 回應的 `resolvedLocale`);省略=`requestLocale` */
|
|
31
|
+
resolvedLocale?: string | null;
|
|
32
|
+
/** 這一頁有已發布翻譯的次語系(Delivery 回應的 `availableLocales`);`"all"`=每個已上線語系都有(列表頁) */
|
|
33
|
+
availableLocales?: readonly string[] | "all" | null;
|
|
34
|
+
/**
|
|
35
|
+
* 這一頁在每個已上線語系的路徑(無前綴;Delivery 回應的 `localePaths`)。各語系可有自己的翻譯網址代稱,
|
|
36
|
+
* 有給就用它組每個語系的網址;沒給時每個語系用 `path`
|
|
37
|
+
*/
|
|
38
|
+
localePaths?: Readonly<Record<string, string>> | null;
|
|
39
|
+
}
|
|
40
|
+
export interface HreflangLink {
|
|
41
|
+
rel: "alternate";
|
|
42
|
+
hreflang: string;
|
|
43
|
+
href: string;
|
|
44
|
+
}
|
|
45
|
+
export interface PageAlternates extends SiteAlternates {
|
|
46
|
+
/** `<link rel="alternate" hreflang="…" href="…">`,fallback 頁與單語網站為空 */
|
|
47
|
+
links: HreflangLink[];
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* 一頁的 canonical 與 hreflang(Next.js `metadata.alternates` 可直接用 `canonical`/`languages`)。
|
|
51
|
+
* 單語網站只回 canonical;fallback 頁(請求次語系但這一頁沒翻譯)canonical 指主語系網址、不出 hreflang。
|
|
52
|
+
*/
|
|
53
|
+
export declare function buildAlternates(options: BuildAlternatesOptions): PageAlternates;
|
|
54
|
+
/** 外部前端的請求語系:從路徑第一段認前綴;`site` 缺語系資料(單語網站)時一律主語系 */
|
|
55
|
+
export declare function requestLocaleOf(pathname: string, site: SiteLocaleMeta): RequestLocaleResult;
|
|
56
|
+
/** 某語系的這一頁路徑(主語系無前綴);語言切換用 */
|
|
57
|
+
export declare function localizedPath(pathname: string, locale: string, site: SiteLocaleMeta): string;
|
|
58
|
+
/**
|
|
59
|
+
* 語言切換選單:每個已上線語系的這一頁網址(主語系在前,其餘依 `locales[]` 順序)。
|
|
60
|
+
* 給了 `localePaths`(Delivery 回應)就用每個語系自己的路徑(翻譯網址代稱);沒給時把 `path` 換到各語系前綴底下。
|
|
61
|
+
*/
|
|
62
|
+
export declare function languageSwitcher(options: {
|
|
63
|
+
siteUrl: string;
|
|
64
|
+
site: SiteLocaleMeta;
|
|
65
|
+
path: string;
|
|
66
|
+
localePaths?: Readonly<Record<string, string>> | null;
|
|
67
|
+
}): Array<{
|
|
68
|
+
locale: string;
|
|
69
|
+
hreflang: string;
|
|
70
|
+
href: string;
|
|
71
|
+
isPrimary: boolean;
|
|
72
|
+
pathPrefix: string | null;
|
|
73
|
+
}>;
|
|
74
|
+
export { hreflangEntries as hreflangEntriesOf };
|
|
75
|
+
export declare const locales: {
|
|
76
|
+
readonly resolve: typeof requestLocaleOf;
|
|
77
|
+
readonly path: typeof localizedPath;
|
|
78
|
+
readonly alternates: typeof buildAlternates;
|
|
79
|
+
readonly switcher: typeof languageSwitcher;
|
|
80
|
+
};
|
package/dist/locales.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 多語網站的語系路由與 hreflang(ADR-0010 決策 4、10、13;Headless 同權)。
|
|
3
|
+
*
|
|
4
|
+
* 與 Kanorio 代管站同一套純函式(`src/shared/**` 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製):
|
|
5
|
+
* - 主語系無前綴(`/about`),次語系子目錄(`/en/about`);前綴是站主存下來的 `pathPrefix`(`GET /api/v1/site` 的 `locales[]`)
|
|
6
|
+
* - `resolveRequestLocale` 認路徑第一段;主語系碼當前綴(`/zh-hant/about`)要 301 回無前綴
|
|
7
|
+
* - `buildAlternates` 算 canonical 與 hreflang:每個語系版本 self-canonical、只列這一頁有翻譯的語系、x-default 指主語系;
|
|
8
|
+
* 未翻譯的 fallback 頁 canonical 指主語系網址、不出 hreflang
|
|
9
|
+
*/
|
|
10
|
+
import { localePrefixMap, localePrefixOf } from "./shared/localization/locale-path.js";
|
|
11
|
+
import { resolveRequestLocale, withLocalePrefix } from "./shared/localization/request-locale.js";
|
|
12
|
+
import { buildSiteAlternates, hreflangEntries, hreflangOf } from "./shared/seo/alternates.js";
|
|
13
|
+
export { localeOfPrefix, localePrefixMap, localePrefixOf, languageOfLocale } from "./shared/localization/locale-path.js";
|
|
14
|
+
export { resolveRequestLocale, withLocalePrefix, localeRootPath } from "./shared/localization/request-locale.js";
|
|
15
|
+
export { buildSiteAlternates, hreflangEntries, hreflangOf, localizedSiteUrl, sitemapAlternates } from "./shared/seo/alternates.js";
|
|
16
|
+
/**
|
|
17
|
+
* 一頁的 canonical 與 hreflang(Next.js `metadata.alternates` 可直接用 `canonical`/`languages`)。
|
|
18
|
+
* 單語網站只回 canonical;fallback 頁(請求次語系但這一頁沒翻譯)canonical 指主語系網址、不出 hreflang。
|
|
19
|
+
*/
|
|
20
|
+
export function buildAlternates(options) {
|
|
21
|
+
const primaryLocale = options.site.primaryLocale ?? null;
|
|
22
|
+
const routes = options.site.locales ?? [];
|
|
23
|
+
const siteUrl = options.siteUrl.replace(/\/+$/, "");
|
|
24
|
+
const path = options.path.startsWith("/") ? options.path : `/${options.path}`;
|
|
25
|
+
if (!primaryLocale || routes.length < 2) {
|
|
26
|
+
return { canonical: `${siteUrl}${path === "/" ? "" : path}`, languages: {}, links: [] };
|
|
27
|
+
}
|
|
28
|
+
const requestLocale = options.requestLocale ?? primaryLocale;
|
|
29
|
+
const resolvedLocale = options.resolvedLocale ?? requestLocale;
|
|
30
|
+
const secondary = routes.filter((r) => !r.isPrimary && r.locale !== primaryLocale).map((r) => r.locale);
|
|
31
|
+
const availableLocales = options.availableLocales === "all" ? secondary : (options.availableLocales ?? []);
|
|
32
|
+
const alternates = buildSiteAlternates({
|
|
33
|
+
siteUrl,
|
|
34
|
+
path,
|
|
35
|
+
primaryLocale,
|
|
36
|
+
requestLocale,
|
|
37
|
+
resolvedLocale,
|
|
38
|
+
availableLocales,
|
|
39
|
+
localePrefixes: localePrefixMap(routes, primaryLocale),
|
|
40
|
+
localizedPaths: options.localePaths ?? null,
|
|
41
|
+
});
|
|
42
|
+
const links = Object.entries(alternates.languages).map(([hreflang, href]) => ({ rel: "alternate", hreflang, href }));
|
|
43
|
+
return { ...alternates, links };
|
|
44
|
+
}
|
|
45
|
+
/** 外部前端的請求語系:從路徑第一段認前綴;`site` 缺語系資料(單語網站)時一律主語系 */
|
|
46
|
+
export function requestLocaleOf(pathname, site) {
|
|
47
|
+
const primaryLocale = site.primaryLocale ?? "";
|
|
48
|
+
const routes = site.locales ?? [];
|
|
49
|
+
if (!primaryLocale || routes.length === 0)
|
|
50
|
+
return { locale: primaryLocale, pathname: pathname || "/", prefixed: false, redirectTo: null };
|
|
51
|
+
return resolveRequestLocale({ pathname, primaryLocale, locales: routes });
|
|
52
|
+
}
|
|
53
|
+
/** 某語系的這一頁路徑(主語系無前綴);語言切換用 */
|
|
54
|
+
export function localizedPath(pathname, locale, site) {
|
|
55
|
+
const primaryLocale = site.primaryLocale ?? locale;
|
|
56
|
+
return withLocalePrefix(pathname, locale, primaryLocale, site.locales ?? []);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* 語言切換選單:每個已上線語系的這一頁網址(主語系在前,其餘依 `locales[]` 順序)。
|
|
60
|
+
* 給了 `localePaths`(Delivery 回應)就用每個語系自己的路徑(翻譯網址代稱);沒給時把 `path` 換到各語系前綴底下。
|
|
61
|
+
*/
|
|
62
|
+
export function languageSwitcher(options) {
|
|
63
|
+
const primaryLocale = options.site.primaryLocale ?? null;
|
|
64
|
+
const routes = options.site.locales ?? [];
|
|
65
|
+
if (!primaryLocale)
|
|
66
|
+
return [];
|
|
67
|
+
const siteUrl = options.siteUrl.replace(/\/+$/, "");
|
|
68
|
+
const ordered = [...routes].sort((a, b) => Number(Boolean(b.isPrimary)) - Number(Boolean(a.isPrimary)));
|
|
69
|
+
return ordered.map((route) => {
|
|
70
|
+
const prefix = localePrefixOf(route.locale, routes, primaryLocale);
|
|
71
|
+
const path = withLocalePrefix(options.localePaths?.[route.locale] ?? options.path, route.locale, primaryLocale, routes);
|
|
72
|
+
return { locale: route.locale, hreflang: hreflangOf(route.locale), href: `${siteUrl}${path === "/" ? "" : path}`, isPrimary: route.locale === primaryLocale, pathPrefix: prefix };
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
export { hreflangEntries as hreflangEntriesOf };
|
|
76
|
+
export const locales = {
|
|
77
|
+
resolve: requestLocaleOf,
|
|
78
|
+
path: localizedPath,
|
|
79
|
+
alternates: buildAlternates,
|
|
80
|
+
switcher: languageSwitcher,
|
|
81
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Management API(`https://app.kanorio.com/api/v1`,Bearer = personal access token `knr_pat_` 或 service account token `knr_sa_`;OAuth access token `knr_at_` 只對 MCP 有效)。
|
|
3
|
+
* MCP(`https://app.kanorio.com/api/mcp`)是同一套 API 的另一種接法,共用同一份 capability registry。
|
|
4
|
+
* 型別由 `packages/shared/openapi/management.json`(`GET /api/v1/openapi.json` 的快照)經 openapi-typescript 產生。
|
|
5
|
+
*/
|
|
6
|
+
import type { paths as ManagementPaths } from "./generated/management.js";
|
|
7
|
+
import { type HttpClientOptions } from "./http.js";
|
|
8
|
+
import { type TypedClient } from "./typed.js";
|
|
9
|
+
export type { ManagementPaths };
|
|
10
|
+
export type ManagementClient = TypedClient<ManagementPaths>;
|
|
11
|
+
export interface ManagementClientOptions extends Omit<HttpClientOptions, "baseUrl" | "headers"> {
|
|
12
|
+
/** `knr_pat_…` 或 `knr_sa_…`(OAuth 的 `knr_at_…` 只能用在 MCP);可為函式供輪替 */
|
|
13
|
+
token: string | (() => string | Promise<string>);
|
|
14
|
+
/** 預設 {@link DEFAULT_MANAGEMENT_BASE_URL} */
|
|
15
|
+
baseUrl?: string;
|
|
16
|
+
headers?: HeadersInit;
|
|
17
|
+
}
|
|
18
|
+
export declare const DEFAULT_MANAGEMENT_BASE_URL = "https://app.kanorio.com/api/v1";
|
|
19
|
+
export declare function createManagementClient(options: ManagementClientOptions): ManagementClient;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Management API(`https://app.kanorio.com/api/v1`,Bearer = personal access token `knr_pat_` 或 service account token `knr_sa_`;OAuth access token `knr_at_` 只對 MCP 有效)。
|
|
3
|
+
* MCP(`https://app.kanorio.com/api/mcp`)是同一套 API 的另一種接法,共用同一份 capability registry。
|
|
4
|
+
* 型別由 `packages/shared/openapi/management.json`(`GET /api/v1/openapi.json` 的快照)經 openapi-typescript 產生。
|
|
5
|
+
*/
|
|
6
|
+
import { createHttpClient } from "./http.js";
|
|
7
|
+
import { createTypedClient } from "./typed.js";
|
|
8
|
+
export const DEFAULT_MANAGEMENT_BASE_URL = "https://app.kanorio.com/api/v1";
|
|
9
|
+
export function createManagementClient(options) {
|
|
10
|
+
const { token, baseUrl, headers, ...rest } = options;
|
|
11
|
+
const http = createHttpClient({
|
|
12
|
+
...rest,
|
|
13
|
+
baseUrl: baseUrl ?? DEFAULT_MANAGEMENT_BASE_URL,
|
|
14
|
+
headers: async () => {
|
|
15
|
+
const h = new Headers(headers);
|
|
16
|
+
const value = typeof token === "function" ? await token() : token;
|
|
17
|
+
h.set("authorization", `Bearer ${value}`);
|
|
18
|
+
return h;
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
return createTypedClient(http);
|
|
22
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 三套 API 的列表都回同一個信封 `{ data, hasMore, nextCursor }`(ADR-0006 決定 2-2)。
|
|
3
|
+
* `paginate` 依 `nextCursor` 一頁一頁取,逐筆 yield;呼叫端只要把 cursor 放進自己的查詢。
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* for await (const post of paginate((cursor) => client.get("/collections/{key}/items", { params: { key: "blog" }, query: { cursor } }))) {
|
|
7
|
+
* console.log(post.slug);
|
|
8
|
+
* }
|
|
9
|
+
* ```
|
|
10
|
+
*/
|
|
11
|
+
export interface ListPage<T> {
|
|
12
|
+
data: T[];
|
|
13
|
+
hasMore: boolean;
|
|
14
|
+
nextCursor: string | null;
|
|
15
|
+
}
|
|
16
|
+
export declare function paginate<T>(fetchPage: (cursor: string | undefined) => Promise<ListPage<T>>): AsyncGenerator<T, void, undefined>;
|
|
17
|
+
/** 取完所有頁並回傳陣列(小清單用;大清單請用 {@link paginate} 逐筆處理) */
|
|
18
|
+
export declare function listAll<T>(fetchPage: (cursor: string | undefined) => Promise<ListPage<T>>): Promise<T[]>;
|
package/dist/paginate.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 三套 API 的列表都回同一個信封 `{ data, hasMore, nextCursor }`(ADR-0006 決定 2-2)。
|
|
3
|
+
* `paginate` 依 `nextCursor` 一頁一頁取,逐筆 yield;呼叫端只要把 cursor 放進自己的查詢。
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* for await (const post of paginate((cursor) => client.get("/collections/{key}/items", { params: { key: "blog" }, query: { cursor } }))) {
|
|
7
|
+
* console.log(post.slug);
|
|
8
|
+
* }
|
|
9
|
+
* ```
|
|
10
|
+
*/
|
|
11
|
+
export async function* paginate(fetchPage) {
|
|
12
|
+
let cursor;
|
|
13
|
+
for (;;) {
|
|
14
|
+
const page = await fetchPage(cursor);
|
|
15
|
+
yield* page.data;
|
|
16
|
+
if (!page.hasMore || !page.nextCursor)
|
|
17
|
+
return;
|
|
18
|
+
cursor = page.nextCursor;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** 取完所有頁並回傳陣列(小清單用;大清單請用 {@link paginate} 逐筆處理) */
|
|
22
|
+
export async function listAll(fetchPage) {
|
|
23
|
+
const out = [];
|
|
24
|
+
for await (const item of paginate(fetchPage))
|
|
25
|
+
out.push(item);
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@kanorio/sdk/preview`:Next.js Draft Mode 與 Astro 預覽權杖(`knr_pv_`)輔助(Stage F3)。
|
|
3
|
+
*
|
|
4
|
+
* - `previewHeaders(token)`:組裝 `X-Kanorio-Preview: knr_pv_...` 標頭,配合 `?preview=1` 讀取未發布草稿。
|
|
5
|
+
* - `tokenFromCookieHeader(cookieHeader)`:從 `Request` 的 `Cookie` 標頭安全取出 `kanorio_preview` 權杖。
|
|
6
|
+
* - `createPreviewRouteHandler({ siteUrl, enableDraftMode })`:一行掛在 Next.js `app/api/preview/route.ts` 或 Astro endpoint,
|
|
7
|
+
* 驗證 `knr_pv_` 格式、(當提供 `siteUrl` 時)向 Kanorio Delivery API 驗證簽章與時效、阻擋 open redirect,
|
|
8
|
+
* 寫入 `kanorio_preview` HttpOnly cookie 並 307 導向目標頁。
|
|
9
|
+
*/
|
|
10
|
+
export declare const PREVIEW_TOKEN_PREFIX = "knr_pv_";
|
|
11
|
+
export declare const PREVIEW_COOKIE_NAME = "kanorio_preview";
|
|
12
|
+
export declare function isValidPreviewTokenFormat(token: string | null | undefined): token is string;
|
|
13
|
+
/** 僅允許以單一 `/` 開頭的站內路徑,阻擋 `//evil.com` 或 `https://evil.com` open redirect */
|
|
14
|
+
export declare function sanitizePreviewRedirectPath(raw: string | null | undefined): string;
|
|
15
|
+
export declare function previewHeaders(token: string): Record<string, string>;
|
|
16
|
+
/** 從 HTTP `Cookie` 標頭提取並驗證 `kanorio_preview` 權杖;不存在或格式不符時回傳 `null` */
|
|
17
|
+
export declare function tokenFromCookieHeader(cookieHeader: string | null | undefined): string | null;
|
|
18
|
+
export interface PreviewRouteHandlerOptions {
|
|
19
|
+
/**
|
|
20
|
+
* 選填:傳入 Kanorio 系統或服務網址(如 `https://s-xxx.kanorio.com`)時,
|
|
21
|
+
* 會在啟用 Draft Mode 前先向 `GET {siteUrl}/api/v1/site?preview=1` 驗證權杖簽章與有效期限,
|
|
22
|
+
* 防止偽造或過期的權杖讓瀏覽器進入失敗的預覽狀態。
|
|
23
|
+
*/
|
|
24
|
+
siteUrl?: string;
|
|
25
|
+
/** Next.js App Router 傳入 `async () => (await draftMode()).enable()` */
|
|
26
|
+
enableDraftMode?: (token: string) => void | Promise<void>;
|
|
27
|
+
/** Cookie 存活秒數(預設 3600 秒) */
|
|
28
|
+
cookieMaxAgeSeconds?: number;
|
|
29
|
+
fetch?: typeof globalThis.fetch;
|
|
30
|
+
}
|
|
31
|
+
export declare function createPreviewRouteHandler(options?: PreviewRouteHandlerOptions): (request: Request) => Promise<Response>;
|
|
32
|
+
export declare const preview: {
|
|
33
|
+
headers: typeof previewHeaders;
|
|
34
|
+
tokenFromCookieHeader: typeof tokenFromCookieHeader;
|
|
35
|
+
isValidTokenFormat: typeof isValidPreviewTokenFormat;
|
|
36
|
+
sanitizeRedirectPath: typeof sanitizePreviewRedirectPath;
|
|
37
|
+
createRouteHandler: typeof createPreviewRouteHandler;
|
|
38
|
+
COOKIE_NAME: string;
|
|
39
|
+
TOKEN_PREFIX: string;
|
|
40
|
+
};
|