@20baht/formats 0.0.0-stage → 0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nattapong Promthong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,83 @@
1
- # Temporary Holding Version
1
+ # @20baht/formats
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Named value formats. Each is three plain functions: a **check**, a **normaliser** (the one spelling to
4
+ store) and a **formatter** (the spelling people read). No dependencies, no DOM; the same code runs in the
5
+ browser and on the server.
6
+
7
+ ```bash
8
+ bun add @20baht/formats
9
+ ```
10
+
11
+ | Export | Valid when | `normalize` | `format` |
12
+ | --- | --- | --- | --- |
13
+ | `thaiId` | 13 digits, first digit 1–8, check digit fits | `1101700230708` | `1-1017-00230-70-8` |
14
+ | `thaiTaxId` | 13 digits (a juristic person's begin with 0, or a person's own ID), check digit fits | `0101000000001` | `0-1010-00000-00-1` |
15
+ | `thaiPhone` | Thai mobile (06/08/09 + 8 digits) or landline (9 digits), national or `+66` | `+66812345678` | `081-234-5678` |
16
+ | `e164` | `+` and 8–15 digits, the first not 0 (shape only) | `+14155552671` | `+14155552671` |
17
+ | `cardNumber` | 12–19 digits passing the Luhn check | `4111111111111111` | `4111 1111 1111 1111` |
18
+ | `iban` | ISO 13616 shape and the mod-97 check | `GB82WEST12345698765432` | `GB82 WEST 1234 5698 7654 32` |
19
+
20
+ Also `luhn(digits)`, the bare check.
21
+
22
+ ```ts
23
+ import { thaiId, thaiPhone } from '@20baht/formats';
24
+
25
+ thaiId.check('1-1017-00230-70-8'); // true: spaces and dashes are read through
26
+ thaiId.normalize('1-1017-00230-70-8'); // '1101700230708', or null when not valid
27
+ thaiPhone.normalize('081-234-5678'); // '+66812345678'
28
+ thaiPhone.format('+66812345678'); // '081-234-5678'; a value that is not valid comes back as it was
29
+ ```
30
+
31
+ Nothing throws: a value that is not text (or a whole number, for the all-digit formats) is not valid.
32
+
33
+ ## In a bahtui form
34
+
35
+ `formatRegistry()` wraps every format as registry entries, so a schema refers to one by name and the
36
+ browser and the server give the same answer from one import:
37
+
38
+ ```jsonc
39
+ { "type": "text", "key": "citizen_id", "label": "ID card",
40
+ "formatter": "thaiId",
41
+ "validators": [{ "type": "custom", "fn": "thaiId" }] }
42
+ ```
43
+
44
+ ```ts
45
+ import { formatRegistry } from '@20baht/formats';
46
+
47
+ // browser
48
+ form.registry = { ...formatRegistry({ locale: 'th' }) };
49
+
50
+ // server
51
+ const result = validateSubmission(schema, body, formatRegistry({ locale: 'th' }));
52
+ ```
53
+
54
+ Merge it with a registry of your own by spreading both levels:
55
+
56
+ ```ts
57
+ const formats = formatRegistry();
58
+ form.registry = {
59
+ ...mine,
60
+ validators: { ...formats.validators, ...mine.validators },
61
+ formatters: { ...formats.formatters, ...mine.formatters },
62
+ };
63
+ ```
64
+
65
+ - A **validator** answers `null` for a valid value and for an empty one (`required` owns emptiness), else
66
+ a message: English or Thai (`locale`), or your own per format (`messages: { iban: '…' }`). A schema's own
67
+ `message` on the validator still wins.
68
+ - A **formatter** runs while the user types: it rewrites a complete, valid value to its display spelling and
69
+ leaves anything else untouched. The value the form submits is therefore the display spelling
70
+ (`1-1017-00230-70-8`); the validator reads it through, and the server stores `thaiId.normalize(value)`.
71
+
72
+ The names are `FORMAT_NAMES`: `thaiId`, `thaiTaxId`, `thaiPhone`, `e164`, `cardNumber`, `iban`.
73
+
74
+ ## What is not here, and why
75
+
76
+ - **Email.** bahtui's built-in `email` validator is loose on purpose: a strict one refuses real addresses.
77
+ - **Phone numbers of every country.** That is libphonenumber. `e164` checks the shape; `thaiPhone` knows Thailand.
78
+ - **A plain shape** (a postcode, an employee code). A schema already states those as `pattern`.
79
+ - **Thai bank account numbers.** There is no check digit common to the banks; the length is a `pattern`.
80
+ - **IBAN length per country.** That table changes when a country joins; this package ships no data that
81
+ changes on someone else's schedule.
82
+
83
+ A new format is a release of this package and of nothing else: it versions on its own.
@@ -0,0 +1,21 @@
1
+ /**
2
+ * One kind of value, three questions. None of them throws: a value that is not text (or a whole
3
+ * number, for the all-digit formats) is simply not valid.
4
+ */
5
+ export interface Format {
6
+ /** Is this a valid value of the format, however it is spaced or dashed? */
7
+ check(value: unknown): boolean;
8
+ /** The one spelling to store and compare: no separators. `null` when the value is not valid. */
9
+ normalize(value: unknown): string | null;
10
+ /** The spelling people read. A value that is not valid comes back as the text it was. */
11
+ format(value: unknown): string;
12
+ }
13
+ /**
14
+ * A format from its two halves: `parse` (text to the canonical spelling, or null) and `show`
15
+ * (canonical to display).
16
+ */
17
+ export declare function defineFormat(parse: (text: string) => string | null, show: (canonical: string) => string): Format;
18
+ /** Spaces and dashes out; null when anything but digits is left. */
19
+ export declare function digitsOf(text: string): string | null;
20
+ /** `abcdefgh` in groups of 4: `abcd efgh`. */
21
+ export declare function inFours(text: string): string;
package/dist/format.js ADDED
@@ -0,0 +1,26 @@
1
+ function textOf(value) {
2
+ if (typeof value === 'string')
3
+ return value;
4
+ return typeof value === 'number' && Number.isSafeInteger(value) ? String(value) : null;
5
+ }
6
+ export function defineFormat(parse, show) {
7
+ const normalize = (value) => {
8
+ const text = textOf(value);
9
+ return text === null ? null : parse(text);
10
+ };
11
+ return {
12
+ check: (value) => normalize(value) !== null,
13
+ normalize,
14
+ format: (value) => {
15
+ const canonical = normalize(value);
16
+ return canonical === null ? (textOf(value) ?? '') : show(canonical);
17
+ },
18
+ };
19
+ }
20
+ export function digitsOf(text) {
21
+ const digits = text.replace(/[\s-]/g, '');
22
+ return /^\d+$/.test(digits) ? digits : null;
23
+ }
24
+ export function inFours(text) {
25
+ return text.replace(/(.{4})(?=.)/g, '$1 ');
26
+ }
@@ -0,0 +1,4 @@
1
+ export type { Format } from './format.js';
2
+ export { thaiId, thaiPhone, thaiTaxId } from './thai.js';
3
+ export { cardNumber, e164, iban, luhn } from './international.js';
4
+ export { FORMAT_NAMES, formatRegistry, type FormatLocale, type FormatName, type FormatRegistry, type FormatRegistryOptions, } from './registry.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { thaiId, thaiPhone, thaiTaxId } from './thai.js';
2
+ export { cardNumber, e164, iban, luhn } from './international.js';
3
+ export { FORMAT_NAMES, formatRegistry, } from './registry.js';
@@ -0,0 +1,19 @@
1
+ import { type Format } from './format.js';
2
+ /**
3
+ * A phone number in E.164: `+`, then 8 to 15 digits, the first not 0. This is the shape only:
4
+ * whether a country has such a number is libphonenumber's question, not this package's.
5
+ */
6
+ export declare const e164: Format;
7
+ /**
8
+ * The Luhn check (ISO/IEC 7812) on a string of digits: from the right, every second digit is
9
+ * doubled (and 9 taken off when that passes 9); the total must end in 0.
10
+ */
11
+ export declare function luhn(digits: string): boolean;
12
+ /** A payment card number: 12 to 19 digits that pass the Luhn check. */
13
+ export declare const cardNumber: Format;
14
+ /**
15
+ * An IBAN (ISO 13616): two letters, two check digits, then 11 to 30 letters or digits; with the
16
+ * first four characters moved to the end, the number is 1 modulo 97. The length each country
17
+ * uses is not checked: that table changes when a country joins, and belongs to the host.
18
+ */
19
+ export declare const iban: Format;
@@ -0,0 +1,37 @@
1
+ import { defineFormat, digitsOf, inFours } from './format.js';
2
+ export const e164 = defineFormat((text) => {
3
+ const compact = text.replace(/[\s().-]/g, '');
4
+ return /^\+[1-9]\d{7,14}$/.test(compact) ? compact : null;
5
+ }, (canonical) => canonical);
6
+ export function luhn(digits) {
7
+ if (!/^\d+$/.test(digits))
8
+ return false;
9
+ let sum = 0;
10
+ for (let i = 0; i < digits.length; i++) {
11
+ const digit = Number(digits[digits.length - 1 - i]);
12
+ const doubled = digit * 2;
13
+ if (i % 2 === 0)
14
+ sum += digit;
15
+ else
16
+ sum += doubled > 9 ? doubled - 9 : doubled;
17
+ }
18
+ return sum % 10 === 0;
19
+ }
20
+ export const cardNumber = defineFormat((text) => {
21
+ const digits = digitsOf(text);
22
+ return digits && digits.length >= 12 && digits.length <= 19 && luhn(digits) ? digits : null;
23
+ }, inFours);
24
+ function mod97(text) {
25
+ let remainder = 0;
26
+ for (const char of text) {
27
+ const value = char >= 'A' ? String(char.charCodeAt(0) - 55) : char;
28
+ remainder = Number(`${remainder}${value}`) % 97;
29
+ }
30
+ return remainder;
31
+ }
32
+ export const iban = defineFormat((text) => {
33
+ const compact = text.replace(/\s/g, '').toUpperCase();
34
+ if (!/^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/.test(compact))
35
+ return null;
36
+ return mod97(compact.slice(4) + compact.slice(0, 4)) === 1 ? compact : null;
37
+ }, inFours);
@@ -0,0 +1,40 @@
1
+ import type { Format } from './format.js';
2
+ declare const FORMATS: {
3
+ thaiId: Format;
4
+ thaiTaxId: Format;
5
+ thaiPhone: Format;
6
+ e164: Format;
7
+ cardNumber: Format;
8
+ iban: Format;
9
+ };
10
+ export type FormatName = keyof typeof FORMATS;
11
+ /** The names a schema refers to: `{ "type": "custom", "fn": "thaiId" }`, `"formatter": "thaiId"`. */
12
+ export declare const FORMAT_NAMES: FormatName[];
13
+ export type FormatLocale = 'en' | 'th';
14
+ export interface FormatRegistryOptions {
15
+ /** Language of the built-in messages. Default `en`. */
16
+ locale?: FormatLocale;
17
+ /** A message of your own per format; the rest keep the built-in one. */
18
+ messages?: Partial<Record<FormatName, string>>;
19
+ }
20
+ /**
21
+ * The part of a bahtui `Registry` these formats fill. Structural on purpose: this package does
22
+ * not import the engine, and the two shapes fit (a validator may ignore the `data` and `field`
23
+ * it is also handed).
24
+ */
25
+ export interface FormatRegistry {
26
+ validators: Record<FormatName, (value: unknown) => string | null>;
27
+ formatters: Record<FormatName, (value: unknown) => unknown>;
28
+ }
29
+ /**
30
+ * Every format as registry entries, for the browser and the server alike:
31
+ *
32
+ * element.registry = { ...formatRegistry({ locale: 'th' }) };
33
+ * validateSubmission(schema, body, formatRegistry());
34
+ *
35
+ * A validator answers null for a valid or an empty value (`required` owns emptiness), else the
36
+ * message. A formatter rewrites a complete, valid value to its display spelling and returns
37
+ * anything else untouched: it runs while the user types.
38
+ */
39
+ export declare function formatRegistry(options?: FormatRegistryOptions): FormatRegistry;
40
+ export {};
@@ -0,0 +1,34 @@
1
+ import { cardNumber, e164, iban } from './international.js';
2
+ import { thaiId, thaiPhone, thaiTaxId } from './thai.js';
3
+ const FORMATS = { thaiId, thaiTaxId, thaiPhone, e164, cardNumber, iban };
4
+ export const FORMAT_NAMES = Object.keys(FORMATS);
5
+ const MESSAGES = {
6
+ en: {
7
+ thaiId: 'Enter a valid Thai national ID number',
8
+ thaiTaxId: 'Enter a valid Thai tax ID number',
9
+ thaiPhone: 'Enter a valid Thai phone number',
10
+ e164: 'Enter a phone number in international format, like +66812345678',
11
+ cardNumber: 'Enter a valid card number',
12
+ iban: 'Enter a valid IBAN',
13
+ },
14
+ th: {
15
+ thaiId: 'เลขประจำตัวประชาชนไม่ถูกต้อง',
16
+ thaiTaxId: 'เลขประจำตัวผู้เสียภาษีไม่ถูกต้อง',
17
+ thaiPhone: 'หมายเลขโทรศัพท์ไม่ถูกต้อง',
18
+ e164: 'กรอกหมายเลขโทรศัพท์รูปแบบสากล เช่น +66812345678',
19
+ cardNumber: 'หมายเลขบัตรไม่ถูกต้อง',
20
+ iban: 'IBAN ไม่ถูกต้อง',
21
+ },
22
+ };
23
+ const isEmpty = (value) => value === null || value === undefined || value === '';
24
+ export function formatRegistry(options = {}) {
25
+ const messages = { ...MESSAGES[options.locale ?? 'en'], ...options.messages };
26
+ const validators = {};
27
+ const formatters = {};
28
+ for (const name of FORMAT_NAMES) {
29
+ const format = FORMATS[name];
30
+ validators[name] = (value) => (isEmpty(value) || format.check(value) ? null : messages[name]);
31
+ formatters[name] = (value) => (format.check(value) ? format.format(value) : value);
32
+ }
33
+ return { validators, formatters };
34
+ }
package/dist/thai.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { type Format } from './format.js';
2
+ /**
3
+ * A Thai national ID number: 13 digits, a first digit of 1 to 8 (the kinds of person the
4
+ * register knows) and a check digit that fits.
5
+ */
6
+ export declare const thaiId: Format;
7
+ /**
8
+ * A Thai taxpayer identification number: the 13 digits of a juristic person (they begin with 0)
9
+ * or a person's own national ID. Same check digit.
10
+ */
11
+ export declare const thaiTaxId: Format;
12
+ /**
13
+ * A Thai phone number, mobile or landline, written nationally (`081-234-5678`) or with the
14
+ * country code (`+66 81 234 5678`). Normalises to E.164 (`+66812345678`).
15
+ */
16
+ export declare const thaiPhone: Format;
package/dist/thai.js ADDED
@@ -0,0 +1,37 @@
1
+ import { defineFormat, digitsOf } from './format.js';
2
+ function checkDigitFits(digits) {
3
+ let sum = 0;
4
+ for (let i = 0; i < 12; i++)
5
+ sum += Number(digits[i]) * (13 - i);
6
+ return (11 - (sum % 11)) % 10 === Number(digits[12]);
7
+ }
8
+ function thirteen(text) {
9
+ const digits = digitsOf(text);
10
+ return digits?.length === 13 && checkDigitFits(digits) ? digits : null;
11
+ }
12
+ const dashed = (d) => `${d.slice(0, 1)}-${d.slice(1, 5)}-${d.slice(5, 10)}-${d.slice(10, 12)}-${d.slice(12)}`;
13
+ export const thaiId = defineFormat((text) => {
14
+ const digits = thirteen(text);
15
+ return digits && /^[1-8]/.test(digits) ? digits : null;
16
+ }, dashed);
17
+ export const thaiTaxId = defineFormat(thirteen, dashed);
18
+ function thaiNational(text) {
19
+ const compact = text.replace(/[\s().-]/g, '');
20
+ const match = /^(?:\+?66|0)0?(\d+)$/.exec(compact);
21
+ const national = match?.[1];
22
+ if (national === undefined)
23
+ return null;
24
+ return /^(?:[689]\d{8}|[23457]\d{7})$/.test(national) ? national : null;
25
+ }
26
+ function nationalDisplay(e164Number) {
27
+ const n = e164Number.slice(3);
28
+ if (n.length === 9)
29
+ return `0${n.slice(0, 2)}-${n.slice(2, 5)}-${n.slice(5)}`;
30
+ return n.startsWith('2')
31
+ ? `02-${n.slice(1, 4)}-${n.slice(4)}`
32
+ : `0${n.slice(0, 2)}-${n.slice(2, 5)}-${n.slice(5)}`;
33
+ }
34
+ export const thaiPhone = defineFormat((text) => {
35
+ const national = thaiNational(text);
36
+ return national === null ? null : `+66${national}`;
37
+ }, nationalDisplay);
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@20baht/formats",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "engines": {
6
+ "node": ">=20.19.0"
7
+ },
8
+ "description": "Named value formats with a check, a normaliser and a display formatter each: Thai national ID and tax ID, Thai phone numbers, E.164, card numbers (Luhn) and IBAN. No dependencies; plugs into a bahtui registry.",
9
+ "license": "MIT",
10
+ "author": "Nattapong Promthong",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/bank20baht/20baht.git",
14
+ "directory": "packages/core/formats"
15
+ },
16
+ "homepage": "https://github.com/bank20baht/20baht/tree/main/packages/core/formats#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/bank20baht/20baht/issues"
19
+ },
20
+ "keywords": [
21
+ "validation",
22
+ "thai-id",
23
+ "tax-id",
24
+ "phone",
25
+ "luhn",
26
+ "iban",
27
+ "forms"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "exports": {
36
+ ".": {
37
+ "types": "./dist/index.d.ts",
38
+ "import": "./dist/index.js",
39
+ "default": "./dist/index.js"
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
43
+ "scripts": {
44
+ "build": "rm -rf dist && tsc -p tsconfig.json --removeComments && tsc -p tsconfig.json --emitDeclarationOnly",
45
+ "test": "vitest run",
46
+ "test:watch": "vitest",
47
+ "test:coverage": "vitest run --coverage"
48
+ },
49
+ "devDependencies": {
50
+ "typescript": "^5.8.3",
51
+ "vitest": "^3.2.4"
52
+ },
53
+ "main": "./dist/index.js",
54
+ "types": "./dist/index.d.ts",
55
+ "sideEffects": false
56
+ }