@kanorio/sdk 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +125 -0
  7. package/dist/delivery.d.ts +35 -0
  8. package/dist/delivery.js +49 -0
  9. package/dist/edge.d.ts +108 -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 +2408 -0
  15. package/dist/generated/management.d.ts +38333 -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 +90 -0
  39. package/dist/shared/api/server-key.js +260 -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 +76 -0
  79. package/dist/shared/utils/redirect-matching.js +181 -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
+ // Copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`. Do not edit by hand; a contract test keeps the two copies identical.
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
+ * Taiwan's Unified Business Number: 8 digits including a check digit (the Ministry of Finance's rule revised in April 2023).
8
+ *
9
+ * Each digit is multiplied by the weights [1,2,1,2,1,2,4,1]; a two-digit product contributes its tens digit plus its ones digit, and the number is valid when the sum is divisible by 5
10
+ * (the old rule required divisibility by 10; the ministry relaxed it to enlarge the number space, and 04595252, 10458570 and 62176616, issued under the new rule, would be misjudged by the old one).
11
+ * Exception: when the 7th digit is 7 (the product 28 can count as 10 or 1), the number is also valid when the sum plus 1 is divisible by 5.
12
+ * Source: the Fiscal Information Agency (Ministry of Finance, Taiwan), notice on the revised check digit logic for the Unified Business Number.
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
+ // Copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`. Do not edit by hand; a contract test keeps the two copies identical.
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
+ * Response shape of a tax ID registry lookup (from the context-bound lookup endpoint to the storefront's tax ID input). No dependencies; only relative imports inside this folder.
3
+ *
4
+ * The lookup is only for prefilling the name and labeling; no result may ever block a submit:
5
+ * `NOT_FOUND` only means the public data has no match, not that the tax ID is invalid.
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
+ /** The normalized tax ID */
15
+ normalized: string;
16
+ /** Present only when `VERIFIED` */
17
+ registry?: {
18
+ name: string;
19
+ address?: string;
20
+ /** ACTIVE, SUSPENDED, CLOSED or UNKNOWN (UNKNOWN when the source does not say; do not treat it as active) */
21
+ registryStatus: string;
22
+ /** The name contains custom characters most fonts show as boxes: do not prefill it, let the person type it */
23
+ nameHasPrivateUse?: boolean;
24
+ };
25
+ /** The attribution that must be shown whenever government open data is used */
26
+ attribution?: RegistryAttributionWire;
27
+ }
28
+ /** The lookup could not run (wrong context, rate limited, bad format); the storefront always treats it as nothing to prefill and shows no error */
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
+ // Copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`. Do not edit by hand; a contract test keeps the two copies identical.
2
+ /**
3
+ * Response shape of a tax ID registry lookup (from the context-bound lookup endpoint to the storefront's tax ID input). No dependencies; only relative imports inside this folder.
4
+ *
5
+ * The lookup is only for prefilling the name and labeling; no result may ever block a submit:
6
+ * `NOT_FOUND` only means the public data has no match, not that the tax ID is invalid.
7
+ */
8
+ export {};
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Shared cleanup of tax ID input: full-width to half-width (NFKC), whitespace removed, uppercased.
3
+ * Each type's normalize then handles its own separators and prefix.
4
+ */
5
+ export declare function cleanTaxIdInput(raw: string): string;
6
+ /** Removes common separators (hyphens, dots, slashes) */
7
+ export declare function stripSeparators(value: string): string;
@@ -0,0 +1,12 @@
1
+ // Copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`. Do not edit by hand; a contract test keeps the two copies identical.
2
+ /**
3
+ * Shared cleanup of tax ID input: full-width to half-width (NFKC), whitespace removed, uppercased.
4
+ * Each type's normalize then handles its own separators and prefix.
5
+ */
6
+ export function cleanTaxIdInput(raw) {
7
+ return raw.normalize("NFKC").replace(/\s+/g, "").toUpperCase();
8
+ }
9
+ /** Removes common separators (hyphens, dots, slashes) */
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
+ /** The tax ID types available for a country; the first is the default. An unregistered country returns an empty array (the caller treats the value as free text) */
6
+ export declare function listTaxIdTypes(country: string): readonly TaxIdType[];
7
+ /** Countries with a registered tax ID format (for the country menu of a tax ID question) */
8
+ export declare function listTaxIdCountries(): readonly string[];
9
+ /**
10
+ * Validates and normalizes a tax ID.
11
+ * - Without a type, the country's default type is used
12
+ * - A country with no registered type, or a type that does not belong to the country: `UNSUPPORTED` (enforcement is warn: the caller accepts it as free text)
13
+ * - A format or check digit mismatch: whether it blocks depends on the type's enforcement, see `isBlockingTaxIdIssue`
14
+ */
15
+ export declare function validateTaxIdFormat(input: {
16
+ country: string;
17
+ type?: TaxIdType | null;
18
+ value: string;
19
+ }): TaxIdFormatResult;
20
+ /**
21
+ * Checks a value that is already in normalized form, with no cleanup. For schemas whose value is stored or sent to a third party as is
22
+ * (a payment onboarding form, for example: accepting a value with separators and sending it unchanged gets it rejected). Returns null when valid.
23
+ */
24
+ export declare function checkNormalizedTaxId(type: TaxIdType, country: string, value: string): null | "FORMAT" | "CHECKSUM";
25
+ /** Whether this result should block (the format is wrong and the type's rules are verified). `warn` and `UNSUPPORTED` do not block */
26
+ export declare function isBlockingTaxIdIssue(result: TaxIdFormatResult): boolean;
@@ -0,0 +1,67 @@
1
+ // Copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`. Do not edit by hand; a contract test keeps the two copies identical.
2
+ /**
3
+ * The registry of tax ID formats and the single entry point `validateTaxIdFormat`.
4
+ * To add a country: write formats/<type>.ts and add an entry to TAX_ID_FORMATS; the UI and the contract need no change (there are no per-country branches).
5
+ * When a country has several types, the first in the array is the default.
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
+ /** The tax ID types available for a country; the first is the default. An unregistered country returns an empty array (the caller treats the value as free text) */
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
+ /** Countries with a registered tax ID format (for the country menu of a tax ID question) */
29
+ export function listTaxIdCountries() {
30
+ return [...new Set(TAX_ID_FORMATS.flatMap((format) => format.countries))];
31
+ }
32
+ /**
33
+ * Validates and normalizes a tax ID.
34
+ * - Without a type, the country's default type is used
35
+ * - A country with no registered type, or a type that does not belong to the country: `UNSUPPORTED` (enforcement is warn: the caller accepts it as free text)
36
+ * - A format or check digit mismatch: whether it blocks depends on the type's enforcement, see `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
+ * Checks a value that is already in normalized form, with no cleanup. For schemas whose value is stored or sent to a third party as is
56
+ * (a payment onboarding form, for example: accepting a value with separators and sending it unchanged gets it rejected). Returns null when valid.
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
+ /** Whether this result should block (the format is wrong and the type's rules are verified). `warn` and `UNSUPPORTED` do not block */
65
+ export function isBlockingTaxIdIssue(result) {
66
+ return !result.ok && result.enforcement === "block";
67
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Shared types for tax ID and business data validation.
3
+ *
4
+ * This folder is the only implementation of formats and check digits: pure functions with no dependencies (no zod, no DOM or Node APIs),
5
+ * used by Kanorio's storefront (hosted checkout, forms, Elements), its dashboard and `@kanorio/sdk` (which carries a copy).
6
+ * Registry lookups run on Kanorio's server only.
7
+ * Only relative imports inside this folder.
8
+ */
9
+ /** Tax ID types; the names follow Stripe's 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
+ * Whether a format mismatch blocks:
13
+ * - `block`: the rules are verified against official documentation, so a wrong format is wrong
14
+ * - `warn`: the rules are not verified line by line yet (or the authority has not published full rules), so it only warns and never blocks a submit, to avoid being stricter than the authority
15
+ */
16
+ export type TaxIdEnforcement = "block" | "warn";
17
+ export type TaxIdFormatIssue = "EMPTY" | "FORMAT" | "CHECKSUM" | "UNSUPPORTED";
18
+ export interface TaxIdFormatDefinition {
19
+ type: TaxIdType;
20
+ /** The country it applies to (ISO 3166-1 alpha-2) */
21
+ countries: readonly string[];
22
+ /** The matching Stripe tax id type (used when platform billing passes the tax ID to Stripe) */
23
+ stripeType: string;
24
+ /** Input to the normalized value used for storage and comparison (already full-width to half-width, whitespace removed, uppercased) */
25
+ normalize(cleaned: string, country: string): string;
26
+ /** Whether the normalized value is valid; null when valid */
27
+ validate(normalized: string, country: string): null | "FORMAT" | "CHECKSUM";
28
+ enforcement: TaxIdEnforcement;
29
+ /** Whether it has a check digit (when it does, a single mistyped digit is usually caught) */
30
+ hasChecksum: boolean;
31
+ /** An example for the input's placeholder (a valid value) */
32
+ example(country: string): string;
33
+ /** Maximum input length (including separators the user may type) */
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
+ /** With `warn`, the caller only warns and does not block */
48
+ enforcement: TaxIdEnforcement;
49
+ normalized: string;
50
+ };
51
+ /** Attribution for government open data (license condition: the providing agency must be named on use) */
52
+ export interface RegistryAttributionWire {
53
+ /** The providing agency (original name) */
54
+ provider: string;
55
+ providerEn: string;
56
+ license: "OGDL-TW-1.0";
57
+ licenseUrl: "https://data.gov.tw/license";
58
+ /** Data date (the snapshot's version date, YYYY-MM-DD); absent for live lookups */
59
+ dataDate?: string;
60
+ }
@@ -0,0 +1,10 @@
1
+ // Copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`. Do not edit by hand; a contract test keeps the two copies identical.
2
+ /**
3
+ * Shared types for tax ID and business data validation.
4
+ *
5
+ * This folder is the only implementation of formats and check digits: pure functions with no dependencies (no zod, no DOM or Node APIs),
6
+ * used by Kanorio's storefront (hosted checkout, forms, Elements), its dashboard and `@kanorio/sdk` (which carries a copy).
7
+ * Registry lookups run on Kanorio's server only.
8
+ * Only relative imports inside this folder.
9
+ */
10
+ export {};
@@ -0,0 +1,38 @@
1
+ /**
2
+ * URL prefixes of secondary locales.
3
+ *
4
+ * The locale code (`en-US`, BCP 47) and the URL prefix (`en`) are two values, as in Webflow, Framer, Shopify Hydrogen, next-intl, Nuxt, Astro and Docusaurus:
5
+ * - The prefix is **decided and saved when the locale is added**, so adding other locales later never moves existing URLs.
6
+ * - Default: when the site has only this version of a language, the bare language (`/en`); when another version of the same language already exists, language plus region (`/en-gb`).
7
+ * Traditional, Simplified and Hong Kong Chinese are different writing systems and always keep the full code (`/zh-hant`, `/zh-cn`, `/zh-hk`).
8
+ * - The owner can change it to a custom word (Settings > Languages; see `isValidLocalePathPrefix` for the format), and the old prefix then redirects 301 to the new one as a whole.
9
+ * - The primary locale never has a prefix.
10
+ *
11
+ * Pure functions that run at the edge: shared by Kanorio's hosted-site middleware, its server and the Delivery API.
12
+ */
13
+ /** Locale data with its prefix (the shape used by site lookup, site info and the editor) */
14
+ export interface LocaleRoute {
15
+ locale: string;
16
+ isPrimary?: boolean;
17
+ /** URL prefix of a secondary locale (no slashes, lowercase); null for the primary locale. Older data without one falls back to the lowercase locale code */
18
+ pathPrefix?: string | null;
19
+ }
20
+ export declare const LOCALE_PATH_PREFIX_MIN = 2;
21
+ export declare const LOCALE_PATH_PREFIX_MAX = 30;
22
+ /** The language subtag of a locale code (`en-US` to `en`, `zh-Hant` to `zh`) */
23
+ export declare function languageOfLocale(locale: string): string;
24
+ /**
25
+ * The default prefix when a locale is added. `siteLocales` are the locales the site already has (including the primary, excluding this one).
26
+ * `takenPrefixes` are the prefixes other locales on the site already use: on a clash the default falls back to the full code.
27
+ */
28
+ export declare function defaultLocalePathPrefix(locale: string, siteLocales: readonly string[], takenPrefixes?: readonly string[]): string;
29
+ /** Format of a custom prefix: lowercase letters and digits with single hyphens, not at either end, 2 to 30 characters (`en`, `english`, `en-us`) */
30
+ export declare function isValidLocalePathPrefix(prefix: string): boolean;
31
+ /** User input to prefix: trims whitespace and slashes and lowercases; null when the format is wrong */
32
+ export declare function normalizeLocalePathPrefix(input: string): string | null;
33
+ /** This locale's prefix segment in URLs (no slashes); null for the primary locale */
34
+ export declare function localePrefixOf(locale: string, routes: readonly LocaleRoute[], primaryLocale: string): string | null;
35
+ /** Locale to prefix map (secondary locales only); for places that build many URLs at once (sitemap, alternates) */
36
+ export declare function localePrefixMap(routes: readonly LocaleRoute[], primaryLocale: string): Record<string, string>;
37
+ /** First URL segment to locale (only secondary-locale prefixes, case-insensitive); null when it is not a prefix */
38
+ export declare function localeOfPrefix(segment: string, routes: readonly LocaleRoute[], primaryLocale: string): string | null;
@@ -0,0 +1,76 @@
1
+ // Copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`. Do not edit by hand; a contract test keeps the two copies identical.
2
+ /**
3
+ * URL prefixes of secondary locales.
4
+ *
5
+ * The locale code (`en-US`, BCP 47) and the URL prefix (`en`) are two values, as in Webflow, Framer, Shopify Hydrogen, next-intl, Nuxt, Astro and Docusaurus:
6
+ * - The prefix is **decided and saved when the locale is added**, so adding other locales later never moves existing URLs.
7
+ * - Default: when the site has only this version of a language, the bare language (`/en`); when another version of the same language already exists, language plus region (`/en-gb`).
8
+ * Traditional, Simplified and Hong Kong Chinese are different writing systems and always keep the full code (`/zh-hant`, `/zh-cn`, `/zh-hk`).
9
+ * - The owner can change it to a custom word (Settings > Languages; see `isValidLocalePathPrefix` for the format), and the old prefix then redirects 301 to the new one as a whole.
10
+ * - The primary locale never has a prefix.
11
+ *
12
+ * Pure functions that run at the edge: shared by Kanorio's hosted-site middleware, its server and the Delivery API.
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
+ /** The language subtag of a locale code (`en-US` to `en`, `zh-Hant` to `zh`) */
18
+ export function languageOfLocale(locale) {
19
+ return (locale.split("-")[0] ?? locale).toLowerCase();
20
+ }
21
+ /** Chinese variants are different writing systems; neither prefixes nor hreflang collapse them to the bare language */
22
+ function keepsFullCode(locale) {
23
+ return languageOfLocale(locale) === "zh";
24
+ }
25
+ /**
26
+ * The default prefix when a locale is added. `siteLocales` are the locales the site already has (including the primary, excluding this one).
27
+ * `takenPrefixes` are the prefixes other locales on the site already use: on a clash the default falls back to the full code.
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
+ /** Format of a custom prefix: lowercase letters and digits with single hyphens, not at either end, 2 to 30 characters (`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
+ /** User input to prefix: trims whitespace and slashes and lowercases; null when the format is wrong */
44
+ export function normalizeLocalePathPrefix(input) {
45
+ const value = input.trim().replace(/^\/+|\/+$/g, "").toLowerCase();
46
+ return isValidLocalePathPrefix(value) ? value : null;
47
+ }
48
+ /** This locale's prefix segment in URLs (no slashes); null for the primary locale */
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
+ /** Locale to prefix map (secondary locales only); for places that build many URLs at once (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
+ /** First URL segment to locale (only secondary-locale prefixes, case-insensitive); null when it is not a prefix */
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
+ * Request locale resolution: recognizes the locale prefix in the first path segment.
3
+ * Shared by Kanorio's hosted-site middleware and the SDK's middleware; runs at the edge (pure functions, no Node dependency).
4
+ *
5
+ * - Secondary locales are served under a `/{prefix}/` subdirectory; the prefix is the locale's saved `pathPrefix` (default `/en`, see `locale-path.ts`), case-insensitive.
6
+ * - The primary locale never has a prefix: `/zh-hant/about` (the primary locale code used as a prefix) must redirect 301 to `/about` (`redirectTo`).
7
+ * - Anything that is not a live locale's prefix is an ordinary path.
8
+ */
9
+ import { type LocaleRoute } from "./locale-path.js";
10
+ export interface RequestLocaleInput {
11
+ pathname: string;
12
+ primaryLocale: string;
13
+ /** Live locales (including the primary), each with its prefix */
14
+ locales: readonly LocaleRoute[];
15
+ }
16
+ export interface RequestLocaleResult {
17
+ /** The locale in effect */
18
+ locale: string;
19
+ /** The path without the prefix (a path in the primary locale's space), at least `/` */
20
+ pathname: string;
21
+ /** Whether the URL carried a secondary-locale prefix */
22
+ prefixed: boolean;
23
+ /** The path to redirect 301 to when the primary locale was used as a prefix; otherwise null */
24
+ redirectTo: string | null;
25
+ }
26
+ export declare function resolveRequestLocale(input: RequestLocaleInput): RequestLocaleResult;
27
+ /** Turns a path in the primary locale's space into a locale's URL path (no prefix for the primary; the saved prefix for a secondary locale) */
28
+ export declare function withLocalePrefix(pathname: string, locale: string, primaryLocale: string, routes: readonly LocaleRoute[]): string;
29
+ /**
30
+ * Route parameter of hosted sites: visitor pages are statically regenerated, so the request locale cannot come from a header and the middleware
31
+ * encodes it into the `[siteId]` segment: `/en-us/about` becomes `/public/{siteId}__en-us/about`. The primary locale is not encoded (the parameter is just the siteId).
32
+ * The separator is `__`: site ids contain only lowercase letters and digits, and locale codes only letters, digits and hyphens, so they cannot clash.
33
+ */
34
+ export declare const SITE_PARAM_LOCALE_SEPARATOR = "__";
35
+ export declare function composeSiteParam(siteId: string, locale: string | null | undefined, primaryLocale?: string): string;
36
+ /** Splits the route parameter back into siteId and request locale (lowercase code; null without a prefix, meaning the primary locale) */
37
+ export declare function parseSiteParam(param: string): {
38
+ siteId: string;
39
+ locale: string | null;
40
+ };
41
+ /** A locale's root path in URLs: empty for the primary locale, `/{prefix}` for a secondary one; path builders put it first */
42
+ export declare function localeRootPath(locale: string | null | undefined, primaryLocale: string, routes: readonly LocaleRoute[]): string;
@@ -0,0 +1,61 @@
1
+ // Copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`. Do not edit by hand; a contract test keeps the two copies identical.
2
+ /**
3
+ * Request locale resolution: recognizes the locale prefix in the first path segment.
4
+ * Shared by Kanorio's hosted-site middleware and the SDK's middleware; runs at the edge (pure functions, no Node dependency).
5
+ *
6
+ * - Secondary locales are served under a `/{prefix}/` subdirectory; the prefix is the locale's saved `pathPrefix` (default `/en`, see `locale-path.ts`), case-insensitive.
7
+ * - The primary locale never has a prefix: `/zh-hant/about` (the primary locale code used as a prefix) must redirect 301 to `/about` (`redirectTo`).
8
+ * - Anything that is not a live locale's prefix is an ordinary path.
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
+ // The primary locale code as a prefix (`/zh-hant/about`): the primary locale has no prefix, so redirect 301 to the unprefixed URL
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
+ /** Turns a path in the primary locale's space into a locale's URL path (no prefix for the primary; the saved prefix for a secondary locale) */
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
+ * Route parameter of hosted sites: visitor pages are statically regenerated, so the request locale cannot come from a header and the middleware
36
+ * encodes it into the `[siteId]` segment: `/en-us/about` becomes `/public/{siteId}__en-us/about`. The primary locale is not encoded (the parameter is just the siteId).
37
+ * The separator is `__`: site ids contain only lowercase letters and digits, and locale codes only letters, digits and hyphens, so they cannot clash.
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
+ /** Splits the route parameter back into siteId and request locale (lowercase code; null without a prefix, meaning the primary locale) */
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
+ /** A locale's root path in URLs: empty for the primary locale, `/{prefix}` for a secondary one; path builders put it first */
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 and hreflang for a customer site. `<head>` and the sitemap both call this one function, so they always agree.
3
+ *
4
+ * Rules:
5
+ * - The primary locale has no prefix (`/about`) and secondary locales use a subdirectory (`/en/about`); the prefix is the locale's saved `pathPrefix` (`locale-path.ts`).
6
+ * - Each locale version is self-canonical; only locales that are live and have a translation of this page are listed, plus the primary locale; x-default points to the primary locale.
7
+ * - A fallback page (a secondary locale was requested but this page has no translation, so primary-locale content is served): canonical points to the primary locale URL and no hreflang is emitted.
8
+ * - hreflang codes: `zh-Hant` becomes `zh-TW`, everything else is the locale code; Google accepts BCP 47 such as `en-US` and `pt-BR`.
9
+ * - Language catch-all (as Nuxt i18n does): when a language has a single regional version in this set (`en-US`),
10
+ * a bare-language hreflang (`en`) is added for the same URL so users of that language elsewhere match it too; it is not added when the language has two or more versions
11
+ * (there is no basis for choosing one, so it is left to Google) and never for Chinese (Traditional, Simplified and Hong Kong are different writing systems).
12
+ * - Never redirects by Accept-Language or IP (this only produces markup).
13
+ */
14
+ /** Site locale code to hreflang */
15
+ export declare function hreflangOf(locale: string): string;
16
+ /** Locale to URL prefix (secondary locales only; built by `localePrefixMap`). A locale not listed falls back to its lowercase code */
17
+ export type LocalePrefixes = Readonly<Record<string, string>>;
18
+ export interface SiteAlternatesInput {
19
+ /** The site's public URL, without a trailing slash (`https://www.example.com`) */
20
+ siteUrl: string;
21
+ /** The unprefixed primary-locale path (home page `/`, otherwise `/about`, `/blog/x`) */
22
+ path: string;
23
+ primaryLocale: string;
24
+ /** The requested locale (the one in the URL) */
25
+ requestLocale: string;
26
+ /** The locale actually served: the primary locale when there is no translation */
27
+ resolvedLocale: string;
28
+ /** Secondary locales that are live and have a translation of this page (excluding the primary); independent of `requestLocale` */
29
+ availableLocales: readonly string[];
30
+ /** URL prefixes of the secondary locales */
31
+ localePrefixes: LocalePrefixes;
32
+ /**
33
+ * This page's path in each locale (no prefix; translated slugs give each locale its own path). `localePaths` of the Delivery response;
34
+ * `path` is used when it is not given or a locale is missing
35
+ */
36
+ localizedPaths?: LocalizedPaths | null;
37
+ }
38
+ /** Locale to this page's path in that locale (no prefix) */
39
+ export type LocalizedPaths = Readonly<Record<string, string>>;
40
+ export interface SiteAlternates {
41
+ canonical: string;
42
+ /** hreflang to full URL; empty for a fallback page */
43
+ languages: Record<string, string>;
44
+ }
45
+ /** This page's URL in a locale */
46
+ export declare function localizedSiteUrl(siteUrl: string, primaryLocale: string, locale: string, path: string, localePrefixes: LocalePrefixes): string;
47
+ /**
48
+ * hreflang to URL for a set of locale versions (primary first, secondary locales sorted by code, language catch-alls, and x-default last pointing to the primary).
49
+ * Both the alternates in `<head>` and the sitemap's `<xhtml:link>` are produced here.
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
+ /** For the sitemap's `<xhtml:link rel="alternate">`: every version of the same page (primary, language catch-alls and 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
+ }[];