@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
@@ -0,0 +1,32 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ import { defineTaxIdFormat } from "../define.js";
3
+ import { stripSeparators } from "../normalize.js";
4
+ const WEIGHTS = [1, 2, 1, 2, 1, 2, 4, 1];
5
+ const sumOfDigits = (n) => (n < 10 ? n : Math.floor(n / 10) + (n % 10));
6
+ /**
7
+ * 台灣統一編號:8 碼數字+檢查碼(財政部 112 年 4 月新制)。
8
+ *
9
+ * 各位數乘上權重 [1,2,1,2,1,2,4,1],乘積為兩位數時取十位+個位,加總後能被 5 整除即有效
10
+ * (舊制是被 10 整除;財政部為擴增號碼空間放寬,新制配發的 04595252、10458570、62176616 在舊制會被誤判)。
11
+ * 例外:第 7 碼是 7 時(乘積 28 可視為 10 或 1),總和加 1 能被 5 整除也有效。
12
+ * 來源:財政部財政資訊中心「營利事業統一編號檢查碼邏輯修正說明」。
13
+ */
14
+ export function isValidTwVat(normalized) {
15
+ if (!/^\d{8}$/.test(normalized))
16
+ return false;
17
+ const digits = normalized.split("").map(Number);
18
+ const total = digits.reduce((acc, d, i) => acc + sumOfDigits(d * WEIGHTS[i]), 0);
19
+ return total % 5 === 0 || (digits[6] === 7 && (total + 1) % 5 === 0);
20
+ }
21
+ export const twVat = defineTaxIdFormat({
22
+ type: "tw_vat",
23
+ countries: ["TW"],
24
+ stripeType: "tw_vat",
25
+ normalize: (cleaned) => stripSeparators(cleaned),
26
+ validate: (normalized) => (!/^\d{8}$/.test(normalized) ? "FORMAT" : isValidTwVat(normalized) ? null : "CHECKSUM"),
27
+ enforcement: "block",
28
+ hasChecksum: true,
29
+ example: () => "04595252",
30
+ maxLength: 10,
31
+ inputMode: "numeric",
32
+ });
@@ -0,0 +1,9 @@
1
+ export * from "./types.js";
2
+ export * from "./define.js";
3
+ export * from "./normalize.js";
4
+ export * from "./registry.js";
5
+ export * from "./attribution.js";
6
+ export * from "./lookup-wire.js";
7
+ export { isValidTwVat } from "./formats/tw-vat.js";
8
+ export { isValidKrBrn } from "./formats/kr-brn.js";
9
+ export { EU_VAT_COUNTRIES } from "./formats/eu-vat.js";
@@ -0,0 +1,10 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ export * from "./types.js";
3
+ export * from "./define.js";
4
+ export * from "./normalize.js";
5
+ export * from "./registry.js";
6
+ export * from "./attribution.js";
7
+ export * from "./lookup-wire.js";
8
+ export { isValidTwVat } from "./formats/tw-vat.js";
9
+ export { isValidKrBrn } from "./formats/kr-brn.js";
10
+ export { EU_VAT_COUNTRIES } from "./formats/eu-vat.js";
@@ -0,0 +1,33 @@
1
+ /**
2
+ * 稅號登記查詢的回應形狀(綁定情境的查詢端點 → 前台的稅號輸入元件)。零依賴,資料夾內只用相對 import。
3
+ *
4
+ * 這個查詢只用來「自動帶入名稱」與「標示」,任何結果都不能拿來擋送出:
5
+ * `NOT_FOUND` 只代表公開資料裡沒查到,不代表稅號無效。
6
+ */
7
+ import type { RegistryAttributionWire, TaxIdType } from "./types.js";
8
+ export type TaxIdLookupStatus = "VERIFIED" | "NOT_FOUND" | "VALID_FORMAT" | "UNAVAILABLE";
9
+ export interface TaxIdLookupWire {
10
+ ok: true;
11
+ status: TaxIdLookupStatus;
12
+ country: string;
13
+ type: TaxIdType;
14
+ /** 正規化後的稅號 */
15
+ normalized: string;
16
+ /** `VERIFIED` 時才有 */
17
+ registry?: {
18
+ name: string;
19
+ address?: string;
20
+ /** ACTIVE/SUSPENDED/CLOSED/UNKNOWN(來源沒給就是 UNKNOWN,不要當成營業中) */
21
+ registryStatus: string;
22
+ /** 名稱含造字、多數字型顯示成方框:不要自動帶入,讓對方自己填 */
23
+ nameHasPrivateUse?: boolean;
24
+ };
25
+ /** 用到政府開放資料時必須一併顯示的來源標示 */
26
+ attribution?: RegistryAttributionWire;
27
+ }
28
+ /** 查不了(情境不符、被限流、格式不對);前台一律當成「沒有可帶入的資料」,不顯示錯誤 */
29
+ export interface TaxIdLookupUnavailableWire {
30
+ ok: false;
31
+ reason: "invalid_tax_id" | "unavailable" | "rate_limited";
32
+ }
33
+ export type TaxIdLookupResponse = TaxIdLookupWire | TaxIdLookupUnavailableWire;
@@ -0,0 +1,8 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ /**
3
+ * 稅號登記查詢的回應形狀(綁定情境的查詢端點 → 前台的稅號輸入元件)。零依賴,資料夾內只用相對 import。
4
+ *
5
+ * 這個查詢只用來「自動帶入名稱」與「標示」,任何結果都不能拿來擋送出:
6
+ * `NOT_FOUND` 只代表公開資料裡沒查到,不代表稅號無效。
7
+ */
8
+ export {};
@@ -0,0 +1,7 @@
1
+ /**
2
+ * 稅號輸入的共通清理:全形轉半形(NFKC)、去掉空白、轉大寫。
3
+ * 各類型的 normalize 再處理自己的分隔符號與前綴。
4
+ */
5
+ export declare function cleanTaxIdInput(raw: string): string;
6
+ /** 去掉常見分隔符號(橫線、點、斜線) */
7
+ export declare function stripSeparators(value: string): string;
@@ -0,0 +1,12 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ /**
3
+ * 稅號輸入的共通清理:全形轉半形(NFKC)、去掉空白、轉大寫。
4
+ * 各類型的 normalize 再處理自己的分隔符號與前綴。
5
+ */
6
+ export function cleanTaxIdInput(raw) {
7
+ return raw.normalize("NFKC").replace(/\s+/g, "").toUpperCase();
8
+ }
9
+ /** 去掉常見分隔符號(橫線、點、斜線) */
10
+ export function stripSeparators(value) {
11
+ return value.replace(/[-./]/g, "");
12
+ }
@@ -0,0 +1,26 @@
1
+ import type { TaxIdFormatDefinition, TaxIdFormatResult, TaxIdType } from "./types.js";
2
+ export declare const TAX_ID_FORMATS: readonly TaxIdFormatDefinition[];
3
+ export declare function isTaxIdType(value: unknown): value is TaxIdType;
4
+ export declare function getTaxIdFormat(type: TaxIdType): TaxIdFormatDefinition;
5
+ /** 這個國家可用的稅號類型;第一個是預設。沒有登錄的國家回空陣列(呼叫端當成自由文字) */
6
+ export declare function listTaxIdTypes(country: string): readonly TaxIdType[];
7
+ /** 有登錄稅號格式的國家(稅號題的國家選單用) */
8
+ export declare function listTaxIdCountries(): readonly string[];
9
+ /**
10
+ * 驗證並正規化一個稅號。
11
+ * - 沒指定 type 時用該國的預設類型
12
+ * - 國家沒有登錄任何類型、或指定的類型不屬於該國 → `UNSUPPORTED`(enforcement 為 warn:呼叫端當成自由文字收下)
13
+ * - 格式或檢查碼不符 → 依該類型的 enforcement 決定要不要擋,見 `isBlockingTaxIdIssue`
14
+ */
15
+ export declare function validateTaxIdFormat(input: {
16
+ country: string;
17
+ type?: TaxIdType | null;
18
+ value: string;
19
+ }): TaxIdFormatResult;
20
+ /**
21
+ * 檢查一個「已經是正規化形式」的值,不做任何清理。給值要原樣存檔或送給第三方的 schema 用
22
+ * (例如金流開通表單:放行帶分隔符號的寫法卻原樣送出,對方會退件)。合法回 null。
23
+ */
24
+ export declare function checkNormalizedTaxId(type: TaxIdType, country: string, value: string): null | "FORMAT" | "CHECKSUM";
25
+ /** 這個結果要不要擋下(格式錯且該類型的規則已核實)。`warn` 與 `UNSUPPORTED` 不擋 */
26
+ export declare function isBlockingTaxIdIssue(result: TaxIdFormatResult): boolean;
@@ -0,0 +1,67 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ /**
3
+ * 稅號格式的登錄表與唯一入口 `validateTaxIdFormat`。
4
+ * 新增國家:寫一個 formats/<類型>.ts、在 TAX_ID_FORMATS 加一筆;UI 與契約不需要改(沒有國別分支)。
5
+ * 同一國有多種類型時,陣列裡排前面的是預設。
6
+ */
7
+ import { euVat } from "./formats/eu-vat.js";
8
+ import { hkBr } from "./formats/hk-br.js";
9
+ import { jpTrn } from "./formats/jp-trn.js";
10
+ import { krBrn } from "./formats/kr-brn.js";
11
+ import { myItn, mySst } from "./formats/my.js";
12
+ import { sgUen } from "./formats/sg-uen.js";
13
+ import { twVat } from "./formats/tw-vat.js";
14
+ import { cleanTaxIdInput } from "./normalize.js";
15
+ export const TAX_ID_FORMATS = [twVat, hkBr, jpTrn, krBrn, sgUen, myItn, mySst, euVat];
16
+ const BY_TYPE = new Map(TAX_ID_FORMATS.map((format) => [format.type, format]));
17
+ export function isTaxIdType(value) {
18
+ return typeof value === "string" && BY_TYPE.has(value);
19
+ }
20
+ export function getTaxIdFormat(type) {
21
+ return BY_TYPE.get(type);
22
+ }
23
+ /** 這個國家可用的稅號類型;第一個是預設。沒有登錄的國家回空陣列(呼叫端當成自由文字) */
24
+ export function listTaxIdTypes(country) {
25
+ const code = country.toUpperCase();
26
+ return TAX_ID_FORMATS.filter((format) => format.countries.includes(code)).map((format) => format.type);
27
+ }
28
+ /** 有登錄稅號格式的國家(稅號題的國家選單用) */
29
+ export function listTaxIdCountries() {
30
+ return [...new Set(TAX_ID_FORMATS.flatMap((format) => format.countries))];
31
+ }
32
+ /**
33
+ * 驗證並正規化一個稅號。
34
+ * - 沒指定 type 時用該國的預設類型
35
+ * - 國家沒有登錄任何類型、或指定的類型不屬於該國 → `UNSUPPORTED`(enforcement 為 warn:呼叫端當成自由文字收下)
36
+ * - 格式或檢查碼不符 → 依該類型的 enforcement 決定要不要擋,見 `isBlockingTaxIdIssue`
37
+ */
38
+ export function validateTaxIdFormat(input) {
39
+ const country = input.country.toUpperCase();
40
+ const cleaned = cleanTaxIdInput(input.value);
41
+ const type = input.type ?? listTaxIdTypes(country)[0] ?? null;
42
+ const format = type ? BY_TYPE.get(type) : undefined;
43
+ if (!format || !format.countries.includes(country)) {
44
+ return { ok: false, country, type: null, issue: "UNSUPPORTED", enforcement: "warn", normalized: cleaned };
45
+ }
46
+ if (!cleaned)
47
+ return { ok: false, country, type: format.type, issue: "EMPTY", enforcement: "block", normalized: "" };
48
+ const normalized = format.normalize(cleaned, country);
49
+ const issue = format.validate(normalized, country);
50
+ if (issue)
51
+ return { ok: false, country, type: format.type, issue, enforcement: format.enforcement, normalized };
52
+ return { ok: true, country, type: format.type, normalized };
53
+ }
54
+ /**
55
+ * 檢查一個「已經是正規化形式」的值,不做任何清理。給值要原樣存檔或送給第三方的 schema 用
56
+ * (例如金流開通表單:放行帶分隔符號的寫法卻原樣送出,對方會退件)。合法回 null。
57
+ */
58
+ export function checkNormalizedTaxId(type, country, value) {
59
+ const format = BY_TYPE.get(type);
60
+ if (!format || !format.countries.includes(country.toUpperCase()))
61
+ return "FORMAT";
62
+ return format.validate(value, country.toUpperCase());
63
+ }
64
+ /** 這個結果要不要擋下(格式錯且該類型的規則已核實)。`warn` 與 `UNSUPPORTED` 不擋 */
65
+ export function isBlockingTaxIdIssue(result) {
66
+ return !result.ok && result.enforcement === "block";
67
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * 稅號與企業資料驗證的共用型別(ADR-0005 修訂一)。
3
+ *
4
+ * 這個資料夾是「格式與檢查碼」的唯一實作:純函式、零依賴(不用 zod、不碰 DOM/Node),
5
+ * 前台(託管結帳、表單、Elements)、後台與 `@kanorio/sdk`(以複製的方式帶走,見 packages/sdk/scripts/copy-shared.mjs)用同一份。
6
+ * 登記機關查詢在 apps/main/lib/business-registry(只在伺服器)。
7
+ * 資料夾內只用相對 import。
8
+ */
9
+ /** 稅號類型;名稱沿用 Stripe Customer Tax IDs 的命名 */
10
+ export type TaxIdType = "tw_vat" | "hk_br" | "jp_trn" | "kr_brn" | "eu_vat" | "sg_uen" | "my_itn" | "my_sst";
11
+ /**
12
+ * 格式不符時要不要擋:
13
+ * - `block`:規則已對照官方文件核實,格式錯就是錯
14
+ * - `warn`:規則還沒逐條核實(或官方沒有公開完整規則),只提醒、不擋送出,避免我們比官方嚴
15
+ */
16
+ export type TaxIdEnforcement = "block" | "warn";
17
+ export type TaxIdFormatIssue = "EMPTY" | "FORMAT" | "CHECKSUM" | "UNSUPPORTED";
18
+ export interface TaxIdFormatDefinition {
19
+ type: TaxIdType;
20
+ /** 適用的國家(ISO 3166-1 alpha-2) */
21
+ countries: readonly string[];
22
+ /** 對應的 Stripe tax id type(平台收費把稅號交給 Stripe 時用) */
23
+ stripeType: string;
24
+ /** 輸入 → 存檔與比對用的正規化值(已先做過全形轉半形、去空白、轉大寫) */
25
+ normalize(cleaned: string, country: string): string;
26
+ /** 正規化值是否合法;合法回 null */
27
+ validate(normalized: string, country: string): null | "FORMAT" | "CHECKSUM";
28
+ enforcement: TaxIdEnforcement;
29
+ /** 有沒有檢查碼(有的話打錯一碼多半擋得住) */
30
+ hasChecksum: boolean;
31
+ /** 給輸入框 placeholder 的範例(合法值) */
32
+ example(country: string): string;
33
+ /** 輸入框的長度上限(含使用者可能打的分隔符號) */
34
+ maxLength: number;
35
+ inputMode: "numeric" | "text";
36
+ }
37
+ export type TaxIdFormatResult = {
38
+ ok: true;
39
+ country: string;
40
+ type: TaxIdType;
41
+ normalized: string;
42
+ } | {
43
+ ok: false;
44
+ country: string;
45
+ type: TaxIdType | null;
46
+ issue: TaxIdFormatIssue;
47
+ /** `warn` 時呼叫端只提醒、不擋 */
48
+ enforcement: TaxIdEnforcement;
49
+ normalized: string;
50
+ };
51
+ /** 政府開放資料的來源標示(授權條件:使用時必須標示提供機關) */
52
+ export interface RegistryAttributionWire {
53
+ /** 提供機關(原文) */
54
+ provider: string;
55
+ providerEn: string;
56
+ license: "OGDL-TW-1.0";
57
+ licenseUrl: "https://data.gov.tw/license";
58
+ /** 資料日期(快照的版本日,YYYY-MM-DD);即時查詢沒有 */
59
+ dataDate?: string;
60
+ }
@@ -0,0 +1,10 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ /**
3
+ * 稅號與企業資料驗證的共用型別(ADR-0005 修訂一)。
4
+ *
5
+ * 這個資料夾是「格式與檢查碼」的唯一實作:純函式、零依賴(不用 zod、不碰 DOM/Node),
6
+ * 前台(託管結帳、表單、Elements)、後台與 `@kanorio/sdk`(以複製的方式帶走,見 packages/sdk/scripts/copy-shared.mjs)用同一份。
7
+ * 登記機關查詢在 apps/main/lib/business-registry(只在伺服器)。
8
+ * 資料夾內只用相對 import。
9
+ */
10
+ export {};
@@ -0,0 +1,38 @@
1
+ /**
2
+ * 次語系的網址前綴(ADR-0010 決策 4 修訂,2026-11-02 Wilson 定案 A;benchmark §C3b)。
3
+ *
4
+ * 語系碼(`en-US`,BCP 47)與網址前綴(`en`)是兩個值——Webflow、Framer、Shopify Hydrogen、next-intl、Nuxt、Astro、Docusaurus 同做法:
5
+ * - 前綴在**加入語系時決定並存下來**(`WebsiteLocale.pathPrefix`),之後加別的語系不會搬動既有網址(決策 4「既有網址永不搬動」)。
6
+ * - 預設:同一種語言站上只有這一個版本 → 純語言(`/en`);已經有同語言的其他版本 → 語言+地區(`/en-gb`)。
7
+ * 中文的繁、簡、港是不同書寫系統,一律保留完整碼(`/zh-hant`、`/zh-cn`、`/zh-hk`)。
8
+ * - 站主可以改成自訂字(設定 › 語言;格式見 `isValidLocalePathPrefix`),改了舊前綴整批 301 到新前綴。
9
+ * - 主語系永遠沒有前綴。
10
+ *
11
+ * 純函式、邊緣可跑:public-sites middleware、main 的 service、Delivery 共用。
12
+ */
13
+ /** 帶前綴的語系資料(lookup、站資訊、編輯器都用這個形狀) */
14
+ export interface LocaleRoute {
15
+ locale: string;
16
+ isPrimary?: boolean;
17
+ /** 次語系的網址前綴(不含斜線、小寫);主語系 null。舊資料沒有時以語系碼小寫代替 */
18
+ pathPrefix?: string | null;
19
+ }
20
+ export declare const LOCALE_PATH_PREFIX_MIN = 2;
21
+ export declare const LOCALE_PATH_PREFIX_MAX = 30;
22
+ /** 語系碼的語言子標籤(`en-US` → `en`、`zh-Hant` → `zh`) */
23
+ export declare function languageOfLocale(locale: string): string;
24
+ /**
25
+ * 加入語系時的預設前綴。`siteLocales` 是站上已經有的語系(含主語系,不含這個)。
26
+ * `takenPrefixes` 是站上其他語系已經用掉的前綴:預設撞到時退回完整碼。
27
+ */
28
+ export declare function defaultLocalePathPrefix(locale: string, siteLocales: readonly string[], takenPrefixes?: readonly string[]): string;
29
+ /** 自訂前綴的格式:小寫英數與單一連字號、不在頭尾,2–30 字(`en`、`english`、`en-us`) */
30
+ export declare function isValidLocalePathPrefix(prefix: string): boolean;
31
+ /** 使用者輸入 → 前綴:去頭尾空白與斜線、轉小寫;格式不對回 null */
32
+ export declare function normalizeLocalePathPrefix(input: string): string | null;
33
+ /** 這個語系在網址上的前綴段(不含斜線);主語系 null */
34
+ export declare function localePrefixOf(locale: string, routes: readonly LocaleRoute[], primaryLocale: string): string | null;
35
+ /** 語系 → 前綴的對照(只有次語系);給一次要算很多網址的地方(sitemap、alternates) */
36
+ export declare function localePrefixMap(routes: readonly LocaleRoute[], primaryLocale: string): Record<string, string>;
37
+ /** 網址第一段 → 語系(只認次語系的前綴,不分大小寫);不是前綴回 null */
38
+ export declare function localeOfPrefix(segment: string, routes: readonly LocaleRoute[], primaryLocale: string): string | null;
@@ -0,0 +1,76 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ /**
3
+ * 次語系的網址前綴(ADR-0010 決策 4 修訂,2026-11-02 Wilson 定案 A;benchmark §C3b)。
4
+ *
5
+ * 語系碼(`en-US`,BCP 47)與網址前綴(`en`)是兩個值——Webflow、Framer、Shopify Hydrogen、next-intl、Nuxt、Astro、Docusaurus 同做法:
6
+ * - 前綴在**加入語系時決定並存下來**(`WebsiteLocale.pathPrefix`),之後加別的語系不會搬動既有網址(決策 4「既有網址永不搬動」)。
7
+ * - 預設:同一種語言站上只有這一個版本 → 純語言(`/en`);已經有同語言的其他版本 → 語言+地區(`/en-gb`)。
8
+ * 中文的繁、簡、港是不同書寫系統,一律保留完整碼(`/zh-hant`、`/zh-cn`、`/zh-hk`)。
9
+ * - 站主可以改成自訂字(設定 › 語言;格式見 `isValidLocalePathPrefix`),改了舊前綴整批 301 到新前綴。
10
+ * - 主語系永遠沒有前綴。
11
+ *
12
+ * 純函式、邊緣可跑:public-sites middleware、main 的 service、Delivery 共用。
13
+ */
14
+ export const LOCALE_PATH_PREFIX_MIN = 2;
15
+ export const LOCALE_PATH_PREFIX_MAX = 30;
16
+ const PREFIX_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
17
+ /** 語系碼的語言子標籤(`en-US` → `en`、`zh-Hant` → `zh`) */
18
+ export function languageOfLocale(locale) {
19
+ return (locale.split("-")[0] ?? locale).toLowerCase();
20
+ }
21
+ /** 中文的變體是不同書寫系統,前綴與 hreflang 都不收成純語言 */
22
+ function keepsFullCode(locale) {
23
+ return languageOfLocale(locale) === "zh";
24
+ }
25
+ /**
26
+ * 加入語系時的預設前綴。`siteLocales` 是站上已經有的語系(含主語系,不含這個)。
27
+ * `takenPrefixes` 是站上其他語系已經用掉的前綴:預設撞到時退回完整碼。
28
+ */
29
+ export function defaultLocalePathPrefix(locale, siteLocales, takenPrefixes = []) {
30
+ const full = locale.toLowerCase();
31
+ if (keepsFullCode(locale) || !locale.includes("-"))
32
+ return full;
33
+ const language = languageOfLocale(locale);
34
+ const sameLanguage = siteLocales.some((other) => other !== locale && languageOfLocale(other) === language);
35
+ if (sameLanguage || takenPrefixes.includes(language))
36
+ return full;
37
+ return language;
38
+ }
39
+ /** 自訂前綴的格式:小寫英數與單一連字號、不在頭尾,2–30 字(`en`、`english`、`en-us`) */
40
+ export function isValidLocalePathPrefix(prefix) {
41
+ return prefix.length >= LOCALE_PATH_PREFIX_MIN && prefix.length <= LOCALE_PATH_PREFIX_MAX && PREFIX_RE.test(prefix);
42
+ }
43
+ /** 使用者輸入 → 前綴:去頭尾空白與斜線、轉小寫;格式不對回 null */
44
+ export function normalizeLocalePathPrefix(input) {
45
+ const value = input.trim().replace(/^\/+|\/+$/g, "").toLowerCase();
46
+ return isValidLocalePathPrefix(value) ? value : null;
47
+ }
48
+ /** 這個語系在網址上的前綴段(不含斜線);主語系 null */
49
+ export function localePrefixOf(locale, routes, primaryLocale) {
50
+ if (locale === primaryLocale)
51
+ return null;
52
+ const route = routes.find((r) => r.locale === locale);
53
+ if (route?.isPrimary)
54
+ return null;
55
+ return route?.pathPrefix || locale.toLowerCase();
56
+ }
57
+ /** 語系 → 前綴的對照(只有次語系);給一次要算很多網址的地方(sitemap、alternates) */
58
+ export function localePrefixMap(routes, primaryLocale) {
59
+ const out = {};
60
+ for (const route of routes) {
61
+ const prefix = localePrefixOf(route.locale, routes, primaryLocale);
62
+ if (prefix)
63
+ out[route.locale] = prefix;
64
+ }
65
+ return out;
66
+ }
67
+ /** 網址第一段 → 語系(只認次語系的前綴,不分大小寫);不是前綴回 null */
68
+ export function localeOfPrefix(segment, routes, primaryLocale) {
69
+ const wanted = segment.toLowerCase();
70
+ for (const route of routes) {
71
+ const prefix = localePrefixOf(route.locale, routes, primaryLocale);
72
+ if (prefix && prefix === wanted)
73
+ return route.locale;
74
+ }
75
+ return null;
76
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * 請求語系解析(ADR-0010 決策 4、5;P3):從路徑第一層段落辨認語系前綴。
3
+ * public-sites middleware 與 Delivery SDK 的 middleware 共用;邊緣可跑(純函式、無 Node 依賴)。
4
+ *
5
+ * - 次語系以 `/{前綴}/` 子目錄交付;前綴是語系存下來的 `pathPrefix`(預設 `/en`,見 `locale-path.ts`),不分大小寫。
6
+ * - 主語系永遠無前綴:`/zh-hant/about`(主語系碼當前綴)要 301 到 `/about`(`redirectTo`)。
7
+ * - 不是任何已上線語系的前綴,當一般路徑。
8
+ */
9
+ import { type LocaleRoute } from "./locale-path.js";
10
+ export interface RequestLocaleInput {
11
+ pathname: string;
12
+ primaryLocale: string;
13
+ /** 已上線的語系(含主語系),帶各自的前綴 */
14
+ locales: readonly LocaleRoute[];
15
+ }
16
+ export interface RequestLocaleResult {
17
+ /** 採用的語系 */
18
+ locale: string;
19
+ /** 剝掉前綴後的路徑(主語系空間的路徑),至少 `/` */
20
+ pathname: string;
21
+ /** 網址是否帶了次語系前綴 */
22
+ prefixed: boolean;
23
+ /** 主語系帶前綴時要 301 到的路徑;其餘 null */
24
+ redirectTo: string | null;
25
+ }
26
+ export declare function resolveRequestLocale(input: RequestLocaleInput): RequestLocaleResult;
27
+ /** 把主語系空間的路徑換成某語系的網址路徑(主語系無前綴;次語系用存下來的前綴) */
28
+ export declare function withLocalePrefix(pathname: string, locale: string, primaryLocale: string, routes: readonly LocaleRoute[]): string;
29
+ /**
30
+ * 託管站的路由參數(ADR-0010 P3):訪客端頁面是 ISR,請求語系不能靠 header,所以 middleware 把語系
31
+ * 編進 `[siteId]` 段:`/en-us/about` → `/public/{siteId}__en-us/about`。主語系不編(參數就是 siteId)。
32
+ * 分隔用 `__`:cuid 只有小寫英數,語系碼只有字母、數字與連字號,不會撞到。
33
+ */
34
+ export declare const SITE_PARAM_LOCALE_SEPARATOR = "__";
35
+ export declare function composeSiteParam(siteId: string, locale: string | null | undefined, primaryLocale?: string): string;
36
+ /** 把路由參數拆回 siteId 與請求語系(小寫碼;沒有前綴就是 null=主語系) */
37
+ export declare function parseSiteParam(param: string): {
38
+ siteId: string;
39
+ locale: string | null;
40
+ };
41
+ /** 語系在網址上的根路徑:主語系空字串,次語系 `/{前綴}`;路徑建構器把它接在最前面 */
42
+ export declare function localeRootPath(locale: string | null | undefined, primaryLocale: string, routes: readonly LocaleRoute[]): string;
@@ -0,0 +1,61 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ /**
3
+ * 請求語系解析(ADR-0010 決策 4、5;P3):從路徑第一層段落辨認語系前綴。
4
+ * public-sites middleware 與 Delivery SDK 的 middleware 共用;邊緣可跑(純函式、無 Node 依賴)。
5
+ *
6
+ * - 次語系以 `/{前綴}/` 子目錄交付;前綴是語系存下來的 `pathPrefix`(預設 `/en`,見 `locale-path.ts`),不分大小寫。
7
+ * - 主語系永遠無前綴:`/zh-hant/about`(主語系碼當前綴)要 301 到 `/about`(`redirectTo`)。
8
+ * - 不是任何已上線語系的前綴,當一般路徑。
9
+ */
10
+ import { localeOfPrefix, localePrefixOf } from "./locale-path.js";
11
+ export function resolveRequestLocale(input) {
12
+ const { pathname, primaryLocale } = input;
13
+ const match = /^\/([^/]+)(\/.*)?$/.exec(pathname);
14
+ if (!match)
15
+ return { locale: primaryLocale, pathname: pathname || "/", prefixed: false, redirectTo: null };
16
+ const first = match[1].toLowerCase();
17
+ const rest = match[2] && match[2] !== "" ? match[2] : "/";
18
+ const locale = localeOfPrefix(first, input.locales, primaryLocale);
19
+ if (locale)
20
+ return { locale, pathname: rest, prefixed: true, redirectTo: null };
21
+ // 主語系碼當前綴(`/zh-hant/about`):主語系沒有前綴,301 回無前綴網址
22
+ if (first === primaryLocale.toLowerCase())
23
+ return { locale: primaryLocale, pathname: rest, prefixed: false, redirectTo: rest };
24
+ return { locale: primaryLocale, pathname, prefixed: false, redirectTo: null };
25
+ }
26
+ /** 把主語系空間的路徑換成某語系的網址路徑(主語系無前綴;次語系用存下來的前綴) */
27
+ export function withLocalePrefix(pathname, locale, primaryLocale, routes) {
28
+ const clean = pathname.startsWith("/") ? pathname : `/${pathname}`;
29
+ const prefix = localePrefixOf(locale, routes, primaryLocale);
30
+ if (!prefix)
31
+ return clean;
32
+ return `/${prefix}${clean === "/" ? "" : clean}`;
33
+ }
34
+ /**
35
+ * 託管站的路由參數(ADR-0010 P3):訪客端頁面是 ISR,請求語系不能靠 header,所以 middleware 把語系
36
+ * 編進 `[siteId]` 段:`/en-us/about` → `/public/{siteId}__en-us/about`。主語系不編(參數就是 siteId)。
37
+ * 分隔用 `__`:cuid 只有小寫英數,語系碼只有字母、數字與連字號,不會撞到。
38
+ */
39
+ export const SITE_PARAM_LOCALE_SEPARATOR = "__";
40
+ export function composeSiteParam(siteId, locale, primaryLocale) {
41
+ if (!locale || (primaryLocale && locale === primaryLocale))
42
+ return siteId;
43
+ return `${siteId}${SITE_PARAM_LOCALE_SEPARATOR}${locale.toLowerCase()}`;
44
+ }
45
+ /** 把路由參數拆回 siteId 與請求語系(小寫碼;沒有前綴就是 null=主語系) */
46
+ export function parseSiteParam(param) {
47
+ const index = param.indexOf(SITE_PARAM_LOCALE_SEPARATOR);
48
+ if (index <= 0)
49
+ return { siteId: param, locale: null };
50
+ const locale = param.slice(index + SITE_PARAM_LOCALE_SEPARATOR.length);
51
+ if (!/^[a-z0-9-]+$/i.test(locale))
52
+ return { siteId: param, locale: null };
53
+ return { siteId: param.slice(0, index), locale: locale.toLowerCase() };
54
+ }
55
+ /** 語系在網址上的根路徑:主語系空字串,次語系 `/{前綴}`;路徑建構器把它接在最前面 */
56
+ export function localeRootPath(locale, primaryLocale, routes) {
57
+ if (!locale)
58
+ return "";
59
+ const prefix = localePrefixOf(locale, routes, primaryLocale);
60
+ return prefix ? `/${prefix}` : "";
61
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * 用戶網站的 canonical 與 hreflang(ADR-0010 決策 4、10;benchmark §H)。`<head>` 與 sitemap 都呼叫這一個函式,確保同源。
3
+ *
4
+ * 規則:
5
+ * - 主語系無前綴(`/about`),次語系子目錄(`/en/about`);前綴是語系存下來的 `pathPrefix`(`locale-path.ts`)。
6
+ * - 每個語系版本 self-canonical;只列「已上線且這一頁有翻譯」的語系,加主語系;x-default 指主語系。
7
+ * - fallback 頁(請求次語系但這一頁沒翻譯,服務的是主語系內容):canonical 指主語系網址、不出 hreflang。
8
+ * - hreflang 代碼:`zh-Hant → zh-TW`,其餘照語系碼;Google 接受 `en-US`、`pt-BR` 這類 BCP 47。
9
+ * - 語言 catchall(Nuxt i18n 做法,benchmark §C3b):某語言在這組版本裡只有一個地區版本(`en-US`)時,
10
+ * 多列一個純語言 hreflang(`en`)指同一個網址,其他地區的同語言使用者也對得到;同語言有兩個以上版本時不列
11
+ * (指哪一個沒有依據,交給 Google);中文不列(繁、簡、港是不同書寫系統)。
12
+ * - 永不依 Accept-Language 或 IP 轉址(這裡只產生標記)。
13
+ */
14
+ /** 網站語系碼 → hreflang(行銷站 LOCALE_TO_HREFLANG 的泛化) */
15
+ export declare function hreflangOf(locale: string): string;
16
+ /** 語系 → 網址前綴(只有次語系;`localePrefixMap` 產生)。沒列的語系退回語系碼小寫 */
17
+ export type LocalePrefixes = Readonly<Record<string, string>>;
18
+ export interface SiteAlternatesInput {
19
+ /** 站的對外網址,不含尾斜線(`https://isla-vita.com`) */
20
+ siteUrl: string;
21
+ /** 主語系無前綴的路徑(首頁 `/`,其他 `/about`、`/blog/x`) */
22
+ path: string;
23
+ primaryLocale: string;
24
+ /** 請求的語系(網址上的) */
25
+ requestLocale: string;
26
+ /** 實際交付的語系:沒有翻譯時是主語系 */
27
+ resolvedLocale: string;
28
+ /** 已上線且這一頁有翻譯的次語系(不含主語系);與 `requestLocale` 無關 */
29
+ availableLocales: readonly string[];
30
+ /** 次語系的網址前綴 */
31
+ localePrefixes: LocalePrefixes;
32
+ /**
33
+ * 每個語系的這一頁路徑(無前綴;ADR-0010 決策 18:翻譯網址代稱讓各語系路徑不同)。Delivery 回應的 `localePaths`;
34
+ * 沒給或缺某語系時用 `path`
35
+ */
36
+ localizedPaths?: LocalizedPaths | null;
37
+ }
38
+ /** 語系 → 這一頁在該語系的路徑(無前綴) */
39
+ export type LocalizedPaths = Readonly<Record<string, string>>;
40
+ export interface SiteAlternates {
41
+ canonical: string;
42
+ /** hreflang → 完整網址;fallback 頁為空 */
43
+ languages: Record<string, string>;
44
+ }
45
+ /** 某語系的這一頁網址 */
46
+ export declare function localizedSiteUrl(siteUrl: string, primaryLocale: string, locale: string, path: string, localePrefixes: LocalePrefixes): string;
47
+ /**
48
+ * 一組語系版本的 hreflang → 網址(主語系在前、次語系依碼排序、語言 catchall、最後 x-default 指主語系)。
49
+ * `<head>` 的 alternates 與 sitemap 的 `<xhtml:link>` 都由這裡產生。
50
+ */
51
+ export declare function hreflangEntries(siteUrl: string, path: string, primaryLocale: string, secondaryLocales: readonly string[], localePrefixes: LocalePrefixes, localizedPaths?: LocalizedPaths | null): Array<{
52
+ hreflang: string;
53
+ href: string;
54
+ locale: string | null;
55
+ }>;
56
+ export declare function buildSiteAlternates(input: SiteAlternatesInput): SiteAlternates;
57
+ /** sitemap `<xhtml:link rel="alternate">` 用:同一頁所有版本(含主語系、語言 catchall 與 x-default) */
58
+ export declare function sitemapAlternates(siteUrl: string, path: string, primaryLocale: string, availableLocales: readonly string[], localePrefixes: LocalePrefixes, localizedPaths?: LocalizedPaths | null): {
59
+ hreflang: string;
60
+ href: string;
61
+ }[];
@@ -0,0 +1,71 @@
1
+ // 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製,請勿手改(契約測試鎖兩份相同)。
2
+ /**
3
+ * 用戶網站的 canonical 與 hreflang(ADR-0010 決策 4、10;benchmark §H)。`<head>` 與 sitemap 都呼叫這一個函式,確保同源。
4
+ *
5
+ * 規則:
6
+ * - 主語系無前綴(`/about`),次語系子目錄(`/en/about`);前綴是語系存下來的 `pathPrefix`(`locale-path.ts`)。
7
+ * - 每個語系版本 self-canonical;只列「已上線且這一頁有翻譯」的語系,加主語系;x-default 指主語系。
8
+ * - fallback 頁(請求次語系但這一頁沒翻譯,服務的是主語系內容):canonical 指主語系網址、不出 hreflang。
9
+ * - hreflang 代碼:`zh-Hant → zh-TW`,其餘照語系碼;Google 接受 `en-US`、`pt-BR` 這類 BCP 47。
10
+ * - 語言 catchall(Nuxt i18n 做法,benchmark §C3b):某語言在這組版本裡只有一個地區版本(`en-US`)時,
11
+ * 多列一個純語言 hreflang(`en`)指同一個網址,其他地區的同語言使用者也對得到;同語言有兩個以上版本時不列
12
+ * (指哪一個沒有依據,交給 Google);中文不列(繁、簡、港是不同書寫系統)。
13
+ * - 永不依 Accept-Language 或 IP 轉址(這裡只產生標記)。
14
+ */
15
+ import { languageOfLocale } from "../localization/locale-path.js";
16
+ /** 網站語系碼 → hreflang(行銷站 LOCALE_TO_HREFLANG 的泛化) */
17
+ export function hreflangOf(locale) {
18
+ if (locale === "zh-Hant")
19
+ return "zh-TW";
20
+ return locale;
21
+ }
22
+ function pathIn(locale, path, localizedPaths) {
23
+ return localizedPaths?.[locale] ?? path;
24
+ }
25
+ /** 某語系的這一頁網址 */
26
+ export function localizedSiteUrl(siteUrl, primaryLocale, locale, path, localePrefixes) {
27
+ const base = siteUrl.replace(/\/+$/, "");
28
+ const cleanPath = path === "/" || path === "" ? "" : path.startsWith("/") ? path : `/${path}`;
29
+ // 首頁沿用站內既有慣例:主語系首頁是 `https://host`(不帶尾斜線),次語系 `https://host/en`
30
+ if (locale === primaryLocale)
31
+ return `${base}${cleanPath}`;
32
+ return `${base}/${localePrefixes[locale] ?? locale.toLowerCase()}${cleanPath}`;
33
+ }
34
+ /**
35
+ * 一組語系版本的 hreflang → 網址(主語系在前、次語系依碼排序、語言 catchall、最後 x-default 指主語系)。
36
+ * `<head>` 的 alternates 與 sitemap 的 `<xhtml:link>` 都由這裡產生。
37
+ */
38
+ export function hreflangEntries(siteUrl, path, primaryLocale, secondaryLocales, localePrefixes, localizedPaths) {
39
+ const versions = [primaryLocale, ...[...new Set(secondaryLocales.filter((l) => l !== primaryLocale))].sort()];
40
+ const entries = versions.map((locale) => ({
41
+ hreflang: hreflangOf(locale),
42
+ href: localizedSiteUrl(siteUrl, primaryLocale, locale, pathIn(locale, path, localizedPaths), localePrefixes),
43
+ locale,
44
+ }));
45
+ const byLanguage = new Map();
46
+ for (const locale of versions)
47
+ byLanguage.set(languageOfLocale(locale), [...(byLanguage.get(languageOfLocale(locale)) ?? []), locale]);
48
+ for (const [language, group] of byLanguage) {
49
+ const only = group.length === 1 ? group[0] : null;
50
+ if (!only || language === "zh" || !only.includes("-") || hreflangOf(only) === language)
51
+ continue;
52
+ entries.push({ hreflang: language, href: localizedSiteUrl(siteUrl, primaryLocale, only, pathIn(only, path, localizedPaths), localePrefixes), locale: null });
53
+ }
54
+ entries.push({ hreflang: "x-default", href: entries[0].href, locale: null });
55
+ return entries;
56
+ }
57
+ export function buildSiteAlternates(input) {
58
+ const { siteUrl, path, primaryLocale, requestLocale, resolvedLocale, localePrefixes, localizedPaths } = input;
59
+ const canonical = localizedSiteUrl(siteUrl, primaryLocale, resolvedLocale, pathIn(resolvedLocale, path, localizedPaths), localePrefixes);
60
+ // fallback:請求次語系但服務的是主語系內容 → canonical 指主語系、不出 hreflang
61
+ if (resolvedLocale !== requestLocale)
62
+ return { canonical, languages: {} };
63
+ const languages = {};
64
+ for (const entry of hreflangEntries(siteUrl, path, primaryLocale, input.availableLocales, localePrefixes, localizedPaths))
65
+ languages[entry.hreflang] = entry.href;
66
+ return { canonical, languages };
67
+ }
68
+ /** sitemap `<xhtml:link rel="alternate">` 用:同一頁所有版本(含主語系、語言 catchall 與 x-default) */
69
+ export function sitemapAlternates(siteUrl, path, primaryLocale, availableLocales, localePrefixes, localizedPaths) {
70
+ return hreflangEntries(siteUrl, path, primaryLocale, availableLocales, localePrefixes, localizedPaths).map(({ hreflang, href }) => ({ hreflang, href }));
71
+ }