@kanorio/sdk 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +66 -2
  3. package/dist/customer-oauth.d.ts +86 -0
  4. package/dist/customer-oauth.js +112 -0
  5. package/dist/customer.d.ts +176 -0
  6. package/dist/customer.js +116 -0
  7. package/dist/delivery.d.ts +35 -0
  8. package/dist/delivery.js +49 -0
  9. package/dist/edge.d.ts +104 -0
  10. package/dist/edge.js +287 -0
  11. package/dist/forms.d.ts +123 -0
  12. package/dist/forms.js +130 -0
  13. package/dist/generated/customer.d.ts +3157 -0
  14. package/dist/generated/delivery.d.ts +2380 -0
  15. package/dist/generated/management.d.ts +38248 -0
  16. package/dist/http.d.ts +73 -0
  17. package/dist/http.js +162 -0
  18. package/dist/index.d.ts +16 -0
  19. package/dist/index.js +17 -0
  20. package/dist/locales.d.ts +80 -0
  21. package/dist/locales.js +81 -0
  22. package/dist/management.d.ts +19 -0
  23. package/dist/management.js +22 -0
  24. package/dist/paginate.d.ts +18 -0
  25. package/dist/paginate.js +27 -0
  26. package/dist/preview.d.ts +40 -0
  27. package/dist/preview.js +131 -0
  28. package/dist/protection.d.ts +74 -0
  29. package/dist/protection.js +68 -0
  30. package/dist/revalidate.d.ts +84 -0
  31. package/dist/revalidate.js +143 -0
  32. package/dist/seo.d.ts +120 -0
  33. package/dist/seo.js +125 -0
  34. package/dist/server-key.d.ts +71 -0
  35. package/dist/server-key.js +103 -0
  36. package/dist/shared/api/delivery/cache-tags.d.ts +142 -0
  37. package/dist/shared/api/delivery/cache-tags.js +212 -0
  38. package/dist/shared/api/server-key.d.ts +86 -0
  39. package/dist/shared/api/server-key.js +252 -0
  40. package/dist/shared/business-registry/attribution.d.ts +14 -0
  41. package/dist/shared/business-registry/attribution.js +28 -0
  42. package/dist/shared/business-registry/define.d.ts +3 -0
  43. package/dist/shared/business-registry/define.js +4 -0
  44. package/dist/shared/business-registry/formats/eu-vat.d.ts +2 -0
  45. package/dist/shared/business-registry/formats/eu-vat.js +54 -0
  46. package/dist/shared/business-registry/formats/hk-br.d.ts +5 -0
  47. package/dist/shared/business-registry/formats/hk-br.js +23 -0
  48. package/dist/shared/business-registry/formats/jp-trn.d.ts +6 -0
  49. package/dist/shared/business-registry/formats/jp-trn.js +23 -0
  50. package/dist/shared/business-registry/formats/kr-brn.d.ts +6 -0
  51. package/dist/shared/business-registry/formats/kr-brn.js +30 -0
  52. package/dist/shared/business-registry/formats/my.d.ts +7 -0
  53. package/dist/shared/business-registry/formats/my.js +32 -0
  54. package/dist/shared/business-registry/formats/sg-uen.d.ts +1 -0
  55. package/dist/shared/business-registry/formats/sg-uen.js +21 -0
  56. package/dist/shared/business-registry/formats/tw-vat.d.ts +10 -0
  57. package/dist/shared/business-registry/formats/tw-vat.js +32 -0
  58. package/dist/shared/business-registry/index.d.ts +9 -0
  59. package/dist/shared/business-registry/index.js +10 -0
  60. package/dist/shared/business-registry/lookup-wire.d.ts +33 -0
  61. package/dist/shared/business-registry/lookup-wire.js +8 -0
  62. package/dist/shared/business-registry/normalize.d.ts +7 -0
  63. package/dist/shared/business-registry/normalize.js +12 -0
  64. package/dist/shared/business-registry/registry.d.ts +26 -0
  65. package/dist/shared/business-registry/registry.js +67 -0
  66. package/dist/shared/business-registry/types.d.ts +60 -0
  67. package/dist/shared/business-registry/types.js +10 -0
  68. package/dist/shared/localization/locale-path.d.ts +38 -0
  69. package/dist/shared/localization/locale-path.js +76 -0
  70. package/dist/shared/localization/request-locale.d.ts +42 -0
  71. package/dist/shared/localization/request-locale.js +61 -0
  72. package/dist/shared/seo/alternates.d.ts +61 -0
  73. package/dist/shared/seo/alternates.js +71 -0
  74. package/dist/shared/types/forms-logic.d.ts +96 -0
  75. package/dist/shared/types/forms-logic.js +209 -0
  76. package/dist/shared/types/number-input.d.ts +5 -0
  77. package/dist/shared/types/number-input.js +16 -0
  78. package/dist/shared/utils/redirect-matching.d.ts +67 -0
  79. package/dist/shared/utils/redirect-matching.js +148 -0
  80. package/dist/tax-id.d.ts +7 -0
  81. package/dist/tax-id.js +6 -0
  82. package/dist/typed.d.ts +85 -0
  83. package/dist/typed.js +28 -0
  84. package/package.json +86 -3
package/dist/edge.d.ts ADDED
@@ -0,0 +1,104 @@
1
+ /**
2
+ * `@kanorio/sdk/edge`:AI 爬蟲管理與追蹤+301/302 轉址規則邊緣中介層(Stage F2)。
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`(語系、無前綴路徑)供前端路由
12
+ */
13
+ import { type RequestLocaleResult } from "./shared/localization/request-locale.js";
14
+ export declare const CRAWLER_LIST_VERSION = "2026-10-22";
15
+ export interface EdgeBotInfo {
16
+ uaToken: string;
17
+ operator: string;
18
+ intent: "training" | "retrieval" | "search";
19
+ blockable: boolean;
20
+ }
21
+ export declare const EDGE_BOT_LIST: readonly EdgeBotInfo[];
22
+ export declare function classifyEdgeUserAgent(ua: string): EdgeBotInfo | null;
23
+ export declare function isEdgeBotBlocked(bot: EdgeBotInfo, blockedTokens: readonly string[] | null | undefined): boolean;
24
+ export interface RedirectRule {
25
+ sourcePath: string;
26
+ targetUrl: string;
27
+ statusCode: number;
28
+ /** null=各語系共用(以無前綴路徑比對);語系碼=只屬於那個語系(以含前綴的完整路徑比對、目標原樣) */
29
+ locale?: string | null;
30
+ }
31
+ export interface KanorioMiddlewareOptions {
32
+ /** Kanorio 系統或服務網址(如 `https://s-xxx.kanorio.com`) */
33
+ siteUrl: string;
34
+ /** 規則快取秒數(預設 60 秒) */
35
+ cacheTtlSeconds?: number;
36
+ /** 功能開關(預設 crawlers、redirects、indexNow、locales 皆啟用) */
37
+ features?: {
38
+ crawlers?: boolean;
39
+ redirects?: boolean;
40
+ /**
41
+ * 自動回應 IndexNow 金鑰驗證檔(`/<32hex>.txt`),讓 IndexNow(Bing/Naver/Seznam/Yandex)
42
+ * 能向這個外部網域驗證金鑰所有權,站主不需要自己接金鑰端點。
43
+ */
44
+ indexNow?: boolean;
45
+ /**
46
+ * 多語網站的語系路由:主語系碼當前綴時 301 回無前綴、每語系的 llms/RSS 檔由邊緣回應、
47
+ * 轉址規則以無前綴路徑比對;放行時決策帶 `locale`。單語網站沒有影響。
48
+ */
49
+ locales?: boolean;
50
+ };
51
+ fetch?: typeof globalThis.fetch;
52
+ /**
53
+ * Server key (`knr_sa_…`, from an environment variable). Required for crawler hit reporting: the report is a
54
+ * server-to-server write, and without a key Kanorio's edge challenges it and the hit is lost. The visitor's
55
+ * (crawler's) IP is read from the incoming request with `visitorIpFromRequest`.
56
+ */
57
+ serverKey?: string;
58
+ }
59
+ /** 放行時的請求語系(多語網站才有;`pathname` 是去掉前綴的主語系空間路徑,前端路由與 Delivery 讀取都用它) */
60
+ export type MiddlewareLocale = RequestLocaleResult & {
61
+ primaryLocale: string;
62
+ };
63
+ export type MiddlewareDecision = {
64
+ action: "pass";
65
+ botHit?: {
66
+ bot: EdgeBotInfo;
67
+ blocked: false;
68
+ };
69
+ locale?: MiddlewareLocale;
70
+ } | {
71
+ action: "block";
72
+ status: 403;
73
+ botHit: {
74
+ bot: EdgeBotInfo;
75
+ blocked: true;
76
+ };
77
+ } | {
78
+ action: "redirect";
79
+ status: 301 | 302;
80
+ location: string;
81
+ } | {
82
+ action: "respond";
83
+ status: 200;
84
+ body: string;
85
+ contentType: string;
86
+ };
87
+ export interface KanorioMiddleware {
88
+ /** 評估單一 Request,回傳決策(不直接產生框架專屬 Response) */
89
+ evaluate(request: Request, event?: {
90
+ waitUntil?: (promise: Promise<unknown>) => void;
91
+ }): Promise<MiddlewareDecision>;
92
+ /** Next.js `proxy.ts`(Next.js 15 以前為 `middleware.ts`)直接處理器:回傳 `Response`(403 或 301/302)或 `null`(放行) */
93
+ handleRequest(request: Request, event?: {
94
+ waitUntil?: (promise: Promise<unknown>) => void;
95
+ }): Promise<Response | null>;
96
+ }
97
+ export declare function createKanorioMiddleware(options: KanorioMiddlewareOptions): KanorioMiddleware;
98
+ export declare const edge: {
99
+ middleware: typeof createKanorioMiddleware;
100
+ classifyUserAgent: typeof classifyEdgeUserAgent;
101
+ isBotBlocked: typeof isEdgeBotBlocked;
102
+ };
103
+ export { resolveRequestLocale } from "./shared/localization/request-locale.js";
104
+ export { matchRedirect, matchLocalizedRedirect } from "./shared/utils/redirect-matching.js";
package/dist/edge.js ADDED
@@ -0,0 +1,287 @@
1
+ /**
2
+ * `@kanorio/sdk/edge`:AI 爬蟲管理與追蹤+301/302 轉址規則邊緣中介層(Stage F2)。
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`(語系、無前綴路徑)供前端路由
12
+ */
13
+ import { deliveryBaseUrl } from "./delivery.js";
14
+ import { serverKeyRequest, visitorIpFromRequest } from "./server-key.js";
15
+ import { localeRootPath, resolveRequestLocale } from "./shared/localization/request-locale.js";
16
+ import { matchLocalizedRedirect } from "./shared/utils/redirect-matching.js";
17
+ export const CRAWLER_LIST_VERSION = "2026-10-22";
18
+ export const EDGE_BOT_LIST = [
19
+ { uaToken: "OAI-SearchBot", operator: "openai", intent: "retrieval", blockable: true },
20
+ { uaToken: "ChatGPT-User", operator: "openai", intent: "retrieval", blockable: true },
21
+ { uaToken: "GPTBot", operator: "openai", intent: "training", blockable: true },
22
+ { uaToken: "Claude-SearchBot", operator: "anthropic", intent: "retrieval", blockable: true },
23
+ { uaToken: "Claude-User", operator: "anthropic", intent: "retrieval", blockable: true },
24
+ { uaToken: "Claude-Web", operator: "anthropic", intent: "retrieval", blockable: true },
25
+ { uaToken: "ClaudeBot", operator: "anthropic", intent: "training", blockable: true },
26
+ { uaToken: "anthropic-ai", operator: "anthropic", intent: "training", blockable: true },
27
+ { uaToken: "Google-Extended", operator: "google", intent: "training", blockable: true },
28
+ { uaToken: "Google-Agent", operator: "google", intent: "retrieval", blockable: true },
29
+ { uaToken: "Googlebot", operator: "google", intent: "search", blockable: false },
30
+ { uaToken: "PerplexityBot", operator: "perplexity", intent: "retrieval", blockable: true },
31
+ { uaToken: "Perplexity-User", operator: "perplexity", intent: "retrieval", blockable: true },
32
+ { uaToken: "CCBot", operator: "commoncrawl", intent: "training", blockable: true },
33
+ { uaToken: "Bytespider", operator: "bytedance", intent: "training", blockable: true },
34
+ { uaToken: "Applebot-Extended", operator: "apple", intent: "training", blockable: true },
35
+ { uaToken: "Applebot", operator: "apple", intent: "search", blockable: false },
36
+ { uaToken: "Meta-ExternalAgent", operator: "meta", intent: "training", blockable: true },
37
+ { uaToken: "meta-webindexer", operator: "meta", intent: "retrieval", blockable: true },
38
+ { uaToken: "meta-externalfetcher", operator: "meta", intent: "retrieval", blockable: true },
39
+ { uaToken: "FacebookBot", operator: "meta", intent: "training", blockable: true },
40
+ { uaToken: "Amazonbot", operator: "amazon", intent: "training", blockable: true },
41
+ { uaToken: "Amzn-SearchBot", operator: "amazon", intent: "retrieval", blockable: true },
42
+ { uaToken: "Amzn-User", operator: "amazon", intent: "retrieval", blockable: true },
43
+ { uaToken: "MistralAI-User", operator: "mistral", intent: "retrieval", blockable: true },
44
+ { uaToken: "DuckAssistBot", operator: "duckduckgo", intent: "retrieval", blockable: true },
45
+ { uaToken: "YouBot", operator: "you", intent: "retrieval", blockable: true },
46
+ { uaToken: "cohere-ai", operator: "cohere", intent: "training", blockable: true },
47
+ { uaToken: "Grok-DeepSearch", operator: "xai", intent: "retrieval", blockable: true },
48
+ { uaToken: "xAI-Grok", operator: "xai", intent: "retrieval", blockable: true },
49
+ { uaToken: "GrokBot", operator: "xai", intent: "training", blockable: true },
50
+ { uaToken: "Diffbot", operator: "diffbot", intent: "training", blockable: true },
51
+ { uaToken: "AI2Bot", operator: "ai2", intent: "training", blockable: true },
52
+ { uaToken: "iaskspider", operator: "iask", intent: "retrieval", blockable: true },
53
+ { uaToken: "bingbot", operator: "microsoft", intent: "search", blockable: false },
54
+ ];
55
+ const _lowerList = EDGE_BOT_LIST.map((b) => ({
56
+ bot: b,
57
+ lower: b.uaToken.toLowerCase(),
58
+ }));
59
+ export function classifyEdgeUserAgent(ua) {
60
+ if (!ua)
61
+ return null;
62
+ const lowerUa = ua.toLowerCase();
63
+ for (const { bot, lower } of _lowerList) {
64
+ if (lowerUa.includes(lower))
65
+ return bot;
66
+ }
67
+ return null;
68
+ }
69
+ export function isEdgeBotBlocked(bot, blockedTokens) {
70
+ if (!bot.blockable)
71
+ return false;
72
+ if (!blockedTokens?.length)
73
+ return false;
74
+ const botToken = bot.uaToken.toLowerCase();
75
+ return blockedTokens.some((token) => token.toLowerCase() === botToken);
76
+ }
77
+ const INDEXNOW_KEY_PATH_RE = /^\/([a-f0-9]{32})\.txt$/i;
78
+ /** `/{前綴}/llms.txt` 這類每語系的 SEO 衍生檔 → Delivery 端點(與代管站 `localized-seo-files.ts` 同一組檔名) */
79
+ const LOCALIZED_SEO_FILES = {
80
+ "llms.txt": "/seo/llms.txt",
81
+ "llms-full.txt": "/seo/llms-full.txt",
82
+ "rss.xml": "/feed",
83
+ "feed.xml": "/feed",
84
+ "feed.atom": "/feed.atom",
85
+ };
86
+ export function createKanorioMiddleware(options) {
87
+ const apiBase = deliveryBaseUrl(options.siteUrl);
88
+ const ttlMs = Math.max(5, options.cacheTtlSeconds ?? 60) * 1000;
89
+ const enableCrawlers = options.features?.crawlers !== false;
90
+ const enableRedirects = options.features?.redirects !== false;
91
+ const enableIndexNow = options.features?.indexNow !== false;
92
+ const enableLocales = options.features?.locales !== false;
93
+ const f = options.fetch ?? globalThis.fetch;
94
+ let cached = null;
95
+ let inflight = null;
96
+ async function loadState() {
97
+ const now = Date.now();
98
+ if (cached && cached.expiresAt > now)
99
+ return cached;
100
+ if (inflight)
101
+ return inflight;
102
+ inflight = (async () => {
103
+ let blockedTokens = cached?.blockedTokens ?? [];
104
+ let indexNowKey = cached?.indexNowKey ?? null;
105
+ let redirects = cached?.redirects ?? [];
106
+ let primaryLocale = cached?.primaryLocale ?? null;
107
+ let locales = cached?.locales ?? [];
108
+ try {
109
+ const tasks = [];
110
+ if (enableCrawlers || enableIndexNow || enableLocales) {
111
+ // 爬蟲封鎖規則、IndexNow 金鑰與語系集合同一支 /site 回應,合併一次請求避免重複打 Delivery API
112
+ tasks.push(f(`${apiBase}/site`, { headers: { Accept: "application/json" } })
113
+ .then((r) => (r.ok ? r.json() : null))
114
+ .then((data) => {
115
+ if (enableCrawlers && Array.isArray(data?.crawlerRules?.blockedTokens)) {
116
+ blockedTokens = data.crawlerRules.blockedTokens;
117
+ }
118
+ if (enableIndexNow && typeof data?.indexNowKey === "string") {
119
+ indexNowKey = data.indexNowKey;
120
+ }
121
+ if (enableLocales && typeof data?.primaryLocale === "string" && Array.isArray(data.locales)) {
122
+ primaryLocale = data.primaryLocale;
123
+ locales = data.locales.filter((l) => typeof l?.locale === "string").map((l) => ({ locale: l.locale, isPrimary: Boolean(l.isPrimary), pathPrefix: l.pathPrefix ?? null }));
124
+ }
125
+ })
126
+ .catch(() => undefined));
127
+ }
128
+ if (enableRedirects) {
129
+ tasks.push(f(`${apiBase}/redirects`, { headers: { Accept: "application/json" } })
130
+ .then((r) => (r.ok ? r.json() : null))
131
+ .then((page) => {
132
+ if (Array.isArray(page?.data)) {
133
+ redirects = page.data
134
+ .filter((rule) => rule?.sourcePath && rule?.targetUrl)
135
+ .map((rule) => ({ sourcePath: rule.sourcePath, targetUrl: rule.targetUrl, statusCode: rule.statusCode === 302 ? 302 : 301 }));
136
+ }
137
+ })
138
+ .catch(() => undefined));
139
+ }
140
+ await Promise.all(tasks);
141
+ }
142
+ finally {
143
+ inflight = null;
144
+ }
145
+ cached = {
146
+ expiresAt: Date.now() + ttlMs,
147
+ blockedTokens,
148
+ redirects,
149
+ indexNowKey,
150
+ primaryLocale,
151
+ locales,
152
+ };
153
+ return cached;
154
+ })();
155
+ return inflight;
156
+ }
157
+ function reportBotHit(request, pathname, bot, blocked, event) {
158
+ const userAgent = request.headers.get("user-agent") ?? bot.uaToken;
159
+ const url = `${apiBase}/analytics/bot-hit`;
160
+ // 帶主機金鑰與來源 IP(只讀平台保證的標頭);沒設金鑰時照舊送,邊緣會擋下,回報遺失但不影響請求
161
+ const promise = serverKeyRequest({ serverKey: options.serverKey, visitorIp: visitorIpFromRequest(request) }, url)
162
+ .then((viaServerKey) => f(url, {
163
+ method: "POST",
164
+ headers: { "Content-Type": "application/json", ...(viaServerKey?.headers ?? {}) },
165
+ body: JSON.stringify({
166
+ botToken: bot.uaToken,
167
+ path: pathname,
168
+ blocked,
169
+ userAgent,
170
+ }),
171
+ ...(viaServerKey ? { redirect: viaServerKey.redirect } : {}),
172
+ }))
173
+ .catch(() => undefined);
174
+ if (event?.waitUntil) {
175
+ event.waitUntil(promise);
176
+ }
177
+ }
178
+ return {
179
+ async evaluate(request, event) {
180
+ const url = new URL(request.url);
181
+ const pathname = url.pathname || "/";
182
+ const state = await loadState();
183
+ if (enableIndexNow && state.indexNowKey) {
184
+ const match = INDEXNOW_KEY_PATH_RE.exec(pathname);
185
+ if (match && match[1].toLowerCase() === state.indexNowKey.toLowerCase()) {
186
+ return {
187
+ action: "respond",
188
+ status: 200,
189
+ body: state.indexNowKey,
190
+ contentType: "text/plain; charset=utf-8",
191
+ };
192
+ }
193
+ }
194
+ // 語系(多語網站):主語系碼當前綴 301 回無前綴;每語系的 SEO 衍生檔由邊緣回應
195
+ let locale;
196
+ if (enableLocales && state.primaryLocale && state.locales.length > 1) {
197
+ const resolved = resolveRequestLocale({ pathname, primaryLocale: state.primaryLocale, locales: state.locales });
198
+ if (resolved.redirectTo !== null) {
199
+ return { action: "redirect", status: 301, location: new URL(`${resolved.redirectTo}${url.search}`, url.origin).toString() };
200
+ }
201
+ locale = { ...resolved, primaryLocale: state.primaryLocale };
202
+ if (resolved.prefixed) {
203
+ const file = /^\/([^/]+)$/.exec(resolved.pathname)?.[1];
204
+ const apiPath = file ? LOCALIZED_SEO_FILES[file] : undefined;
205
+ if (apiPath) {
206
+ const target = new URL(`${apiBase}${apiPath}`);
207
+ target.searchParams.set("locale", resolved.locale);
208
+ for (const [key, value] of url.searchParams)
209
+ if (key !== "locale")
210
+ target.searchParams.append(key, value);
211
+ try {
212
+ const res = await f(target.toString(), { headers: { Accept: "*/*" } });
213
+ if (res.ok) {
214
+ return { action: "respond", status: 200, body: await res.text(), contentType: res.headers.get("content-type") ?? "text/plain; charset=utf-8" };
215
+ }
216
+ }
217
+ catch {
218
+ // 回源失敗:放行讓前端自己處理(通常是 404)
219
+ }
220
+ }
221
+ }
222
+ }
223
+ // 轉址規則:精確優先、再最長 wildcard 前綴(與代管站同一份比對);多語網站的共用規則以無前綴的路徑比對、站內目標接回同一個前綴,
224
+ // 帶語系的規則(翻譯代稱改名、語系停用、改前綴)以完整路徑比對、目標原樣(ADR-0010 決策 18)
225
+ if (enableRedirects && state.redirects.length > 0) {
226
+ const matchPath = locale ? locale.pathname : pathname;
227
+ const hit = matchLocalizedRedirect(pathname, matchPath, state.redirects);
228
+ if (hit) {
229
+ const statusCode = hit.statusCode === 302 ? 302 : 301;
230
+ if (hit.target.startsWith("/")) {
231
+ const root = !hit.scoped && locale?.prefixed ? localeRootPath(locale.locale, locale.primaryLocale, state.locales) : "";
232
+ const localized = root ? `${root}${hit.target === "/" ? "" : hit.target}` : hit.target;
233
+ // 迴圈保險:目標就是目前這一頁(例如 wildcard "/*" → "/")就不轉
234
+ if (localized !== pathname) {
235
+ return { action: "redirect", status: statusCode, location: new URL(`${localized}${url.search}`, url.origin).toString() };
236
+ }
237
+ }
238
+ else {
239
+ return { action: "redirect", status: statusCode, location: hit.target };
240
+ }
241
+ }
242
+ }
243
+ if (enableCrawlers) {
244
+ const ua = request.headers.get("user-agent") ?? "";
245
+ const bot = classifyEdgeUserAgent(ua);
246
+ if (bot) {
247
+ const blocked = isEdgeBotBlocked(bot, state.blockedTokens);
248
+ reportBotHit(request, pathname, bot, blocked, event);
249
+ if (blocked) {
250
+ return { action: "block", status: 403, botHit: { bot, blocked: true } };
251
+ }
252
+ return { action: "pass", botHit: { bot, blocked: false }, ...(locale ? { locale } : {}) };
253
+ }
254
+ }
255
+ return { action: "pass", ...(locale ? { locale } : {}) };
256
+ },
257
+ async handleRequest(request, event) {
258
+ const decision = await this.evaluate(request, event);
259
+ if (decision.action === "block") {
260
+ return new Response("Forbidden", {
261
+ status: 403,
262
+ headers: { "Content-Type": "text/plain; charset=utf-8" },
263
+ });
264
+ }
265
+ if (decision.action === "redirect") {
266
+ return new Response(null, {
267
+ status: decision.status,
268
+ headers: { Location: decision.location },
269
+ });
270
+ }
271
+ if (decision.action === "respond") {
272
+ return new Response(decision.body, {
273
+ status: decision.status,
274
+ headers: { "Content-Type": decision.contentType },
275
+ });
276
+ }
277
+ return null;
278
+ },
279
+ };
280
+ }
281
+ export const edge = {
282
+ middleware: createKanorioMiddleware,
283
+ classifyUserAgent: classifyEdgeUserAgent,
284
+ isBotBlocked: isEdgeBotBlocked,
285
+ };
286
+ export { resolveRequestLocale } from "./shared/localization/request-locale.js";
287
+ export { matchRedirect, matchLocalizedRedirect } from "./shared/utils/redirect-matching.js";
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Headless 表單 SDK 輔助:讀取表單定義 → 取得人機驗證題目 → 申請檔案上傳票 → 送出表單回覆。
3
+ * 給自刻表單 UI 的開發者搭配 `useKanorioBotProtection` 或伺服器端流程使用。
4
+ *
5
+ * 回應依三套 API 共用的契約(ADR-0006 決定 2-1):成功是原物件、失敗是 `{ error: { code, message, details? } }`。
6
+ * 這裡把兩者收斂成 `{ ok: true, … }`/`{ ok: false, error }`,表單 UI 不必自己分辨 HTTP 狀態。
7
+ */
8
+ import { type ServerKeyOptions } from "./server-key.js";
9
+ import type { TaxIdLookupResponse } from "./shared/business-registry/lookup-wire.js";
10
+ import { resolveVisibleFieldIds } from "./shared/types/forms-logic.js";
11
+ import { type ProtectionChallenge, type ProtectionFields } from "./protection.js";
12
+ /** `GET /forms/{id}/challenge`:內建 ALTCHA 題目,或網站選的第三方 widget 參數(form-protection.md「人機驗證提供者」) */
13
+ export type FormChallengeResponse = ProtectionChallenge;
14
+ /** 送出與上傳都要帶的防護欄位(`_hp`、`_wp`、`_co` 為蜜罐,一律空字串) */
15
+ export type FormProtectionFields = ProtectionFields;
16
+ export interface FormUploadTicketRequest {
17
+ fieldId: string;
18
+ fileName: string;
19
+ mimeType: string;
20
+ fileSize: number;
21
+ protection?: FormProtectionFields | Record<string, unknown>;
22
+ }
23
+ export interface FormApiError {
24
+ code: string;
25
+ message: string;
26
+ /** INVALID_ANSWERS 時為各題的錯誤(`details.issues`) */
27
+ issues?: unknown;
28
+ details?: unknown;
29
+ }
30
+ export type FormUploadTicketResponse = {
31
+ ok: true;
32
+ uploadId: string;
33
+ uploadUrl: string;
34
+ headers?: Record<string, string>;
35
+ expiresIn: number;
36
+ } | {
37
+ ok: false;
38
+ error: FormApiError;
39
+ };
40
+ export interface FormSubmitInput {
41
+ answers: Record<string, unknown>;
42
+ protection?: FormProtectionFields | Record<string, unknown>;
43
+ consent?: "checked" | "submit_statement";
44
+ consentTextId?: string;
45
+ locale?: string;
46
+ pagePath?: string;
47
+ /** Where this visit came from (kept on the submission record): UTM and ad-click parameters, external referrer host, landing path. */
48
+ attribution?: {
49
+ utm?: Record<string, string>;
50
+ referrerHost?: string;
51
+ landingPath?: string;
52
+ };
53
+ }
54
+ export type FormSubmitResult = {
55
+ ok: true;
56
+ state?: "closed" | "not_open" | "full";
57
+ } | {
58
+ ok: false;
59
+ error: FormApiError;
60
+ };
61
+ export interface FormsHelpers {
62
+ get(formId: string): Promise<unknown>;
63
+ challenge(formId: string): Promise<FormChallengeResponse>;
64
+ requestUpload(formId: string, input: FormUploadTicketRequest): Promise<FormUploadTicketResponse>;
65
+ /**
66
+ * Look up the public business registry for a `tax_id` question, to prefill the business name.
67
+ * Only works for a tax ID question on a form that is currently open. The result is advisory:
68
+ * `{ ok: false }` and `NOT_FOUND` are normal outcomes and must not block the submission.
69
+ */
70
+ lookupTaxId(formId: string, input: FormTaxIdLookupRequest): Promise<TaxIdLookupResponse>;
71
+ submit(formId: string, input: FormSubmitInput): Promise<FormSubmitResult>;
72
+ }
73
+ export interface FormTaxIdLookupRequest {
74
+ /** Id of the tax_id question. */
75
+ fieldId: string;
76
+ /** ISO 3166-1 alpha-2 country of the tax ID. */
77
+ country: string;
78
+ /** Tax ID type; defaults to the country's first type. */
79
+ type?: string;
80
+ value: string;
81
+ /** Same protection fields as an upload request (from `uploadProtectionFromChallenge`). */
82
+ protection?: FormProtectionFields | Record<string, unknown>;
83
+ }
84
+ /**
85
+ * 由 challenge 組出防護欄位:表單顯示時呼叫 `challenge()`,送出時把結果交給這裡。
86
+ * 內建題目在這裡解(工作量證明,約 0.5~1 秒);網站改用 Turnstile、reCAPTCHA、hCaptcha 時,先用 challenge 的
87
+ * `siteKey`、`action`(Turnstile 另有 `cData`)畫該家 widget,再把 token 以 `captchaToken` 傳進來。
88
+ * `renderedAt` 是表單顯示的時間(毫秒)。題目與 token 都是一次性的:每次送出前重新取。
89
+ */
90
+ export declare function protectionFromChallenge(formId: string, challenge: FormChallengeResponse, renderedAt: number, options?: {
91
+ captchaToken?: string;
92
+ signal?: AbortSignal;
93
+ }): Promise<FormProtectionFields>;
94
+ /**
95
+ * 附件上傳票的防護欄位:內建時傳入送出用的那份(`solved`,同一個解可重複用於上傳);
96
+ * 網站改用第三方時用 challenge 的 `uploadToken`(widget token 是一次性的,留給送出)。
97
+ */
98
+ export declare function uploadProtectionFromChallenge(formId: string, challenge: FormChallengeResponse, renderedAt: number, solved?: FormProtectionFields): FormProtectionFields | null;
99
+ export interface FormsHelpersOptions extends ServerKeyOptions {
100
+ siteUrl: string;
101
+ fetch?: typeof globalThis.fetch;
102
+ }
103
+ /**
104
+ * Pass `serverKey` (and `visitorIp`) when your **server** submits on behalf of a visitor. The key proves the
105
+ * request comes from your server; it does not replace form protection, so the submission still needs the
106
+ * `protection` fields the visitor's browser obtained.
107
+ */
108
+ export declare function createFormsHelpers(options: FormsHelpersOptions): FormsHelpers;
109
+ /**
110
+ * Which questions to show for the current answers. A question can carry `visibleWhen` (conditions on earlier questions
111
+ * or hidden fields); the server applies the same function on submit, so a question hidden here is never required and
112
+ * its answer is not saved. Pass the raw values the visitor has entered so far, keyed by question id, together with
113
+ * any hidden field values.
114
+ */
115
+ export { resolveVisibleFieldIds as visibleFieldIds, hasVisibilityRules } from "./shared/types/forms-logic.js";
116
+ export type { FormCondition, FormConditionOp, FormVisibleWhen, LogicField as FormLogicField } from "./shared/types/forms-logic.js";
117
+ export declare const forms: {
118
+ client: typeof createFormsHelpers;
119
+ protectionFromChallenge: typeof protectionFromChallenge;
120
+ uploadProtectionFromChallenge: typeof uploadProtectionFromChallenge;
121
+ visibleFieldIds: typeof resolveVisibleFieldIds;
122
+ };
123
+ export type { TaxIdLookupResponse, TaxIdLookupWire, TaxIdLookupUnavailableWire } from "./shared/business-registry/lookup-wire.js";
package/dist/forms.js ADDED
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Headless 表單 SDK 輔助:讀取表單定義 → 取得人機驗證題目 → 申請檔案上傳票 → 送出表單回覆。
3
+ * 給自刻表單 UI 的開發者搭配 `useKanorioBotProtection` 或伺服器端流程使用。
4
+ *
5
+ * 回應依三套 API 共用的契約(ADR-0006 決定 2-1):成功是原物件、失敗是 `{ error: { code, message, details? } }`。
6
+ * 這裡把兩者收斂成 `{ ok: true, … }`/`{ ok: false, error }`,表單 UI 不必自己分辨 HTTP 狀態。
7
+ */
8
+ import { EDGE_CHALLENGE_CODE, edgeChallengeMessage, isEdgeChallenge, serverKeyRequest } from "./server-key.js";
9
+ import { deliveryBaseUrl } from "./delivery.js";
10
+ import { resolveVisibleFieldIds } from "./shared/types/forms-logic.js";
11
+ import { protectionFromChallenge as protectionFieldsFromChallenge, uploadProtectionFromChallenge as uploadFieldsFromChallenge } from "./protection.js";
12
+ /**
13
+ * 由 challenge 組出防護欄位:表單顯示時呼叫 `challenge()`,送出時把結果交給這裡。
14
+ * 內建題目在這裡解(工作量證明,約 0.5~1 秒);網站改用 Turnstile、reCAPTCHA、hCaptcha 時,先用 challenge 的
15
+ * `siteKey`、`action`(Turnstile 另有 `cData`)畫該家 widget,再把 token 以 `captchaToken` 傳進來。
16
+ * `renderedAt` 是表單顯示的時間(毫秒)。題目與 token 都是一次性的:每次送出前重新取。
17
+ */
18
+ export function protectionFromChallenge(formId, challenge, renderedAt, options = {}) {
19
+ return protectionFieldsFromChallenge(challenge, { context: formId, renderedAt, captchaToken: options.captchaToken, signal: options.signal });
20
+ }
21
+ /**
22
+ * 附件上傳票的防護欄位:內建時傳入送出用的那份(`solved`,同一個解可重複用於上傳);
23
+ * 網站改用第三方時用 challenge 的 `uploadToken`(widget token 是一次性的,留給送出)。
24
+ */
25
+ export function uploadProtectionFromChallenge(formId, challenge, renderedAt, solved) {
26
+ return uploadFieldsFromChallenge(challenge, { context: formId, renderedAt, solved });
27
+ }
28
+ async function readFormError(res, hasServerKey) {
29
+ // 邊緣的 challenge 頁(伺服器端沒帶主機金鑰):回一個說得出下一步的錯誤
30
+ if (isEdgeChallenge(res))
31
+ return { code: EDGE_CHALLENGE_CODE, message: edgeChallengeMessage(hasServerKey) };
32
+ const body = (await res.json().catch(() => null));
33
+ const error = body?.error;
34
+ if (error && typeof error.code === "string") {
35
+ const details = error.details;
36
+ return {
37
+ code: error.code,
38
+ message: typeof error.message === "string" ? error.message : error.code,
39
+ ...(details?.issues !== undefined ? { issues: details.issues } : {}),
40
+ ...(error.details !== undefined ? { details: error.details } : {}),
41
+ };
42
+ }
43
+ return { code: res.status === 429 ? "RATE_LIMITED" : "UPSTREAM_UNAVAILABLE", message: `HTTP ${res.status}` };
44
+ }
45
+ /**
46
+ * Pass `serverKey` (and `visitorIp`) when your **server** submits on behalf of a visitor. The key proves the
47
+ * request comes from your server; it does not replace form protection, so the submission still needs the
48
+ * `protection` fields the visitor's browser obtained.
49
+ */
50
+ export function createFormsHelpers(options) {
51
+ const apiBase = deliveryBaseUrl(options.siteUrl);
52
+ const f = options.fetch ?? globalThis.fetch;
53
+ const post = async (path, body) => {
54
+ const url = `${apiBase}${path}`;
55
+ const viaServerKey = await serverKeyRequest(options, url);
56
+ return f(url, {
57
+ method: "POST",
58
+ headers: { "Content-Type": "application/json", Accept: "application/json", ...(viaServerKey?.headers ?? {}) },
59
+ body: JSON.stringify(body),
60
+ ...(viaServerKey ? { redirect: viaServerKey.redirect } : {}),
61
+ });
62
+ };
63
+ const readError = (res) => readFormError(res, Boolean(options.serverKey));
64
+ return {
65
+ async get(formId) {
66
+ const res = await f(`${apiBase}/forms/${encodeURIComponent(formId)}`, { headers: { Accept: "application/json" } });
67
+ if (!res.ok)
68
+ throw new Error(`Failed to fetch form ${formId}: HTTP ${res.status}`);
69
+ return res.json();
70
+ },
71
+ async challenge(formId) {
72
+ const res = await f(`${apiBase}/forms/${encodeURIComponent(formId)}/challenge`, {
73
+ headers: { Accept: "application/json" },
74
+ cache: "no-store",
75
+ });
76
+ if (!res.ok)
77
+ throw new Error(`Failed to fetch form challenge: HTTP ${res.status}`);
78
+ return (await res.json());
79
+ },
80
+ async requestUpload(formId, input) {
81
+ const { protection, ...rest } = input;
82
+ const res = await post(`/forms/${encodeURIComponent(formId)}/upload-request`, { ...rest, ...(protection ?? {}) }).catch(() => null);
83
+ if (!res)
84
+ return { ok: false, error: { code: "UPSTREAM_UNAVAILABLE", message: "Network error" } };
85
+ if (!res.ok)
86
+ return { ok: false, error: await readError(res) };
87
+ const data = (await res.json());
88
+ return { ok: true, ...data };
89
+ },
90
+ async lookupTaxId(formId, input) {
91
+ const { protection, ...rest } = input;
92
+ const res = await post(`/forms/${encodeURIComponent(formId)}/tax-id-lookup`, { ...rest, ...(protection ?? {}) }).catch(() => null);
93
+ // 查不了不是錯誤:一律當成「沒有可帶入的資料」
94
+ if (!res || !res.ok)
95
+ return { ok: false, reason: res?.status === 429 ? "rate_limited" : "unavailable" };
96
+ // Delivery 的回應不帶 ok:`{ status, ... }`,沒查時是 `{ status: "UNAVAILABLE", reason }`
97
+ const data = (await res.json().catch(() => null));
98
+ if (!data || typeof data.status !== "string")
99
+ return { ok: false, reason: "unavailable" };
100
+ if (data.status === "UNAVAILABLE")
101
+ return { ok: false, reason: data.reason ?? "unavailable" };
102
+ const { reason: _reason, ...wire } = data;
103
+ void _reason;
104
+ return { ok: true, ...wire };
105
+ },
106
+ async submit(formId, input) {
107
+ const { protection, ...rest } = input;
108
+ const res = await post(`/forms/${encodeURIComponent(formId)}/submit`, { ...rest, ...(protection ?? {}) }).catch(() => null);
109
+ if (!res)
110
+ return { ok: false, error: { code: "UPSTREAM_UNAVAILABLE", message: "Network error" } };
111
+ if (!res.ok)
112
+ return { ok: false, error: await readError(res) };
113
+ const data = (await res.json().catch(() => ({})));
114
+ return data.state ? { ok: true, state: data.state } : { ok: true };
115
+ },
116
+ };
117
+ }
118
+ /**
119
+ * Which questions to show for the current answers. A question can carry `visibleWhen` (conditions on earlier questions
120
+ * or hidden fields); the server applies the same function on submit, so a question hidden here is never required and
121
+ * its answer is not saved. Pass the raw values the visitor has entered so far, keyed by question id, together with
122
+ * any hidden field values.
123
+ */
124
+ export { resolveVisibleFieldIds as visibleFieldIds, hasVisibilityRules } from "./shared/types/forms-logic.js";
125
+ export const forms = {
126
+ client: createFormsHelpers,
127
+ protectionFromChallenge,
128
+ uploadProtectionFromChallenge,
129
+ visibleFieldIds: resolveVisibleFieldIds,
130
+ };