@mdgascar/phone 0.8.0 → 0.10.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/README.md +14 -13
- package/dist/index.cjs +62 -27
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +69 -38
- package/dist/index.d.ts +69 -38
- package/dist/index.js +58 -23
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
# @mdgascar/phone
|
|
2
2
|
|
|
3
|
-
Parse, validate and format Madagascar (+261) mobile
|
|
3
|
+
Parse, validate and format Madagascar (+261) phone numbers, mobile and fixed. Zero dependencies,
|
|
4
4
|
ESM + CommonJS + types.
|
|
5
5
|
|
|
6
|
-
Implements spec 0.
|
|
6
|
+
Implements spec 0.9.0.
|
|
7
7
|
|
|
8
8
|
```sh
|
|
9
9
|
npm install @mdgascar/phone
|
|
@@ -12,21 +12,22 @@ npm install @mdgascar/phone
|
|
|
12
12
|
```ts
|
|
13
13
|
import {
|
|
14
14
|
OPERATOR_NAMES,
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
15
|
+
formatPhone,
|
|
16
|
+
isValidPhone,
|
|
17
|
+
parsePhone,
|
|
18
|
+
safeParsePhone,
|
|
19
|
+
tryParsePhone,
|
|
20
20
|
} from '@mdgascar/phone';
|
|
21
21
|
|
|
22
|
-
|
|
23
|
-
// { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }
|
|
22
|
+
parsePhone('034 12 345 67');
|
|
23
|
+
// { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas', type: 'mobile', area: null }
|
|
24
|
+
parsePhone('020 22 421 19').area; // { name: 'Antananarivo', province: 'Antananarivo' }
|
|
24
25
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
formatPhone('+261341234567', 'national'); // '034 12 345 67'
|
|
27
|
+
isValidPhone('031 12 345 67'); // false
|
|
28
|
+
tryParsePhone('031 12 345 67'); // undefined (never throws)
|
|
28
29
|
|
|
29
|
-
const result =
|
|
30
|
+
const result = safeParsePhone(userInput);
|
|
30
31
|
if (!result.success) console.log(result.error.code); // 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR' | …
|
|
31
32
|
|
|
32
33
|
OPERATOR_NAMES.yas; // 'Yas Madagascar'
|
package/dist/index.cjs
CHANGED
|
@@ -10,21 +10,47 @@ var OPERATOR_NAMES = {
|
|
|
10
10
|
orange: "Orange Madagascar",
|
|
11
11
|
airtel: "Airtel Madagascar",
|
|
12
12
|
yas: "Yas Madagascar",
|
|
13
|
-
blueline: "Blueline"
|
|
13
|
+
blueline: "Blueline",
|
|
14
|
+
gulfsat: "Gulfsat Madagascar"
|
|
14
15
|
};
|
|
15
16
|
var OPERATOR_BY_PREFIX = /* @__PURE__ */ new Map([
|
|
16
|
-
["
|
|
17
|
-
["
|
|
18
|
-
["
|
|
19
|
-
["
|
|
20
|
-
["
|
|
21
|
-
["
|
|
22
|
-
["
|
|
17
|
+
["20", { operator: "yas", type: "fixed" }],
|
|
18
|
+
["22", { operator: "gulfsat", type: "fixed" }],
|
|
19
|
+
["32", { operator: "orange", type: "mobile" }],
|
|
20
|
+
["33", { operator: "airtel", type: "mobile" }],
|
|
21
|
+
["34", { operator: "yas", type: "mobile" }],
|
|
22
|
+
["35", { operator: "airtel", type: "mobile" }],
|
|
23
|
+
["36", { operator: "yas", type: "mobile" }],
|
|
24
|
+
["37", { operator: "orange", type: "mobile" }],
|
|
25
|
+
["38", { operator: "yas", type: "mobile" }],
|
|
26
|
+
["39", { operator: "blueline", type: "mobile" }]
|
|
23
27
|
]);
|
|
24
28
|
var OPERATOR_PREFIX_LENGTH = 2;
|
|
29
|
+
var FIXED_ZONE_PREFIX = "20";
|
|
30
|
+
var FIXED_ZONE_DIGITS = ["2", "4", "5", "6", "7", "8", "9"];
|
|
31
|
+
var AREAS = [
|
|
32
|
+
{ prefix: "20722", name: "Manakara", province: "Fianarantsoa" },
|
|
33
|
+
{ prefix: "20729", name: "Mananjary", province: "Fianarantsoa" },
|
|
34
|
+
{ prefix: "2053", name: "Toamasina", province: "Toamasina" },
|
|
35
|
+
{ prefix: "2054", name: "Ambatondrazaka", province: "Toamasina" },
|
|
36
|
+
{ prefix: "2056", name: "Moramanga", province: "Toamasina" },
|
|
37
|
+
{ prefix: "2057", name: "Sainte-Marie", province: "Toamasina" },
|
|
38
|
+
{ prefix: "2062", name: "Mahajanga", province: "Mahajanga" },
|
|
39
|
+
{ prefix: "2067", name: "Antsohihy", province: "Mahajanga" },
|
|
40
|
+
{ prefix: "2069", name: "Maintirano", province: "Mahajanga" },
|
|
41
|
+
{ prefix: "2073", name: "Farafangana", province: "Fianarantsoa" },
|
|
42
|
+
{ prefix: "2075", name: "Fianarantsoa", province: "Fianarantsoa" },
|
|
43
|
+
{ prefix: "2082", name: "Antsiranana", province: "Antsiranana" },
|
|
44
|
+
{ prefix: "2086", name: "Nosy Be", province: "Antsiranana" },
|
|
45
|
+
{ prefix: "2088", name: "Sambava", province: "Antsiranana" },
|
|
46
|
+
{ prefix: "2092", name: "Tolagnaro", province: "Toliary" },
|
|
47
|
+
{ prefix: "2094", name: "Toliary", province: "Toliary" },
|
|
48
|
+
{ prefix: "2095", name: "Morondava", province: "Toliary" },
|
|
49
|
+
{ prefix: "202", name: "Antananarivo", province: "Antananarivo" }
|
|
50
|
+
];
|
|
25
51
|
|
|
26
52
|
// src/generated/errors.ts
|
|
27
|
-
var SPEC_VERSION = "0.
|
|
53
|
+
var SPEC_VERSION = "0.9.0";
|
|
28
54
|
var MdgError = class extends Error {
|
|
29
55
|
/** Always `'MdgError'`. */
|
|
30
56
|
name = "MdgError";
|
|
@@ -91,32 +117,41 @@ function readNationalNumber(input) {
|
|
|
91
117
|
}
|
|
92
118
|
|
|
93
119
|
// src/phone-number.ts
|
|
94
|
-
|
|
120
|
+
var FIXED_ZONES = new Set(FIXED_ZONE_DIGITS);
|
|
121
|
+
function areaOf(nationalNumber) {
|
|
122
|
+
const area = AREAS.find((entry) => nationalNumber.startsWith(entry.prefix));
|
|
123
|
+
return area === void 0 ? null : { name: area.name, province: area.province };
|
|
124
|
+
}
|
|
125
|
+
function safeParsePhone(input) {
|
|
95
126
|
if (typeof input !== "string") return failure("INVALID_TYPE", "Expected the number as a string.");
|
|
96
127
|
const national = readNationalNumber(input);
|
|
97
128
|
if (!national.success) return national;
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
|
|
129
|
+
const prefix = national.data.slice(0, OPERATOR_PREFIX_LENGTH);
|
|
130
|
+
const holder = OPERATOR_BY_PREFIX.get(prefix);
|
|
131
|
+
const zone = national.data.charAt(OPERATOR_PREFIX_LENGTH);
|
|
132
|
+
if (holder === void 0 || prefix === FIXED_ZONE_PREFIX && !FIXED_ZONES.has(zone)) {
|
|
133
|
+
return failure("UNKNOWN_OPERATOR", "The prefix is not assigned to a Malagasy operator.");
|
|
101
134
|
}
|
|
102
135
|
const phone = {
|
|
103
136
|
e164: `+${COUNTRY_CODE}${national.data}`,
|
|
104
137
|
nationalNumber: national.data,
|
|
105
|
-
operator
|
|
138
|
+
operator: holder.operator,
|
|
139
|
+
type: holder.type,
|
|
140
|
+
area: areaOf(national.data)
|
|
106
141
|
};
|
|
107
142
|
return { success: true, data: phone };
|
|
108
143
|
}
|
|
109
|
-
function
|
|
110
|
-
const result =
|
|
144
|
+
function parsePhone(input) {
|
|
145
|
+
const result = safeParsePhone(input);
|
|
111
146
|
if (!result.success) throw result.error;
|
|
112
147
|
return result.data;
|
|
113
148
|
}
|
|
114
|
-
function
|
|
115
|
-
const result =
|
|
149
|
+
function tryParsePhone(input) {
|
|
150
|
+
const result = safeParsePhone(input);
|
|
116
151
|
return result.success ? result.data : void 0;
|
|
117
152
|
}
|
|
118
|
-
function
|
|
119
|
-
return
|
|
153
|
+
function isValidPhone(input) {
|
|
154
|
+
return safeParsePhone(input).success;
|
|
120
155
|
}
|
|
121
156
|
|
|
122
157
|
// src/format.ts
|
|
@@ -136,23 +171,23 @@ var FORMATTERS = {
|
|
|
136
171
|
function isPhoneNumberFormat(value) {
|
|
137
172
|
return PHONE_NUMBER_FORMATS.some((format) => format === value);
|
|
138
173
|
}
|
|
139
|
-
function
|
|
174
|
+
function formatPhone(input, format) {
|
|
140
175
|
if (!isPhoneNumberFormat(format)) {
|
|
141
176
|
throw new MdgError(
|
|
142
177
|
"INVALID_TYPE",
|
|
143
178
|
`Format must be one of: ${PHONE_NUMBER_FORMATS.join(", ")}.`
|
|
144
179
|
);
|
|
145
180
|
}
|
|
146
|
-
return FORMATTERS[format](
|
|
181
|
+
return FORMATTERS[format](parsePhone(input).nationalNumber);
|
|
147
182
|
}
|
|
148
183
|
|
|
149
184
|
exports.MdgError = MdgError;
|
|
150
185
|
exports.OPERATOR_NAMES = OPERATOR_NAMES;
|
|
151
186
|
exports.SPEC_VERSION = SPEC_VERSION;
|
|
152
|
-
exports.
|
|
153
|
-
exports.
|
|
154
|
-
exports.
|
|
155
|
-
exports.
|
|
156
|
-
exports.
|
|
187
|
+
exports.formatPhone = formatPhone;
|
|
188
|
+
exports.isValidPhone = isValidPhone;
|
|
189
|
+
exports.parsePhone = parsePhone;
|
|
190
|
+
exports.safeParsePhone = safeParsePhone;
|
|
191
|
+
exports.tryParsePhone = tryParsePhone;
|
|
157
192
|
//# sourceMappingURL=index.cjs.map
|
|
158
193
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/generated/data.ts","../src/generated/errors.ts","../src/result.ts","../src/read-national-number.ts","../src/phone-number.ts","../src/format.ts"],"names":[],"mappings":";;;AAKO,IAAM,YAAA,GAAe,KAAA;AAGrB,IAAM,oBAAA,GAAuB,IAAA;AAG7B,IAAM,YAAA,GAAe,GAAA;AAGrB,IAAM,sBAAA,GAAyB,CAAA;AAG/B,IAAM,QAAA,GAAW,CAA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GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n// From spec/modules/phone/data.yaml, spec 0.7.0.\n\n/** @internal */\nexport const COUNTRY_CODE = '261' as const;\n\n/** @internal */\nexport const INTERNATIONAL_PREFIX = '00' as const;\n\n/** @internal */\nexport const TRUNK_PREFIX = '0' as const;\n\n/** @internal */\nexport const NATIONAL_NUMBER_LENGTH = 9 as const;\n\n/** @internal Digit group sizes of the national number. */\nexport const GROUPING = [2, 2, 3, 2] as const;\n\n/** Identifier of a Malagasy mobile operator. */\nexport type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline';\n\n/**\n * Display name of each mobile operator, by {@link OperatorId}.\n *\n * @example\n * ```ts\n * OPERATOR_NAMES[parsePhoneNumber('034 12 345 67').operator]; // 'Yas Madagascar'\n * ```\n */\nexport const OPERATOR_NAMES = {\n orange: 'Orange Madagascar',\n airtel: 'Airtel Madagascar',\n yas: 'Yas Madagascar',\n blueline: 'Blueline',\n} as const;\n\n/** @internal Two-digit operator code → operator. */\nexport const OPERATOR_BY_PREFIX: ReadonlyMap<string, OperatorId> = new Map<string, OperatorId>([\n ['32', 'orange'],\n ['33', 'airtel'],\n ['34', 'yas'],\n ['35', 'airtel'],\n ['37', 'orange'],\n ['38', 'yas'],\n ['39', 'blueline'],\n]);\n\n/** @internal */\nexport const OPERATOR_PREFIX_LENGTH = 2 as const;\n","// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n/** Version of the shared spec this code was generated from. */\nexport const SPEC_VERSION = '0.7.0';\n\n/**\n * Error code shared by every mdg-utils language port.\n *\n * - `INVALID_TYPE`: The input is not of the accepted type (for example a string or a non-integer where an integer is expected).\n * - `OUT_OF_RANGE`: The input has the right type but lies outside the supported range.\n * - `INVALID_FORMAT`: The input text cannot be read as a value of this module (wrong characters or wrong length).\n * - `UNKNOWN_OPERATOR`: The phone number is well formed but its operator code is not assigned to a mobile operator.\n */\nexport type ErrorCode = 'INVALID_TYPE' | 'OUT_OF_RANGE' | 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR';\n\n/**\n * Outcome of a `safeParse…` function: the value, or the error that would have been thrown.\n *\n * @example\n * ```ts\n * const result = safeParsePhoneNumber(input);\n * if (result.success) console.log(result.data);\n * else console.log(result.error.code);\n * ```\n */\nexport type SafeParseResult<T> =\n | { readonly success: true; readonly data: T }\n | { readonly success: false; readonly error: MdgError };\n\n/**\n * Error thrown by mdg-utils functions. Check `code`, which is the same in every language.\n *\n * @example\n * ```ts\n * try {\n * numberToWords(-1);\n * } catch (error) {\n * if (error instanceof MdgError && error.code === 'OUT_OF_RANGE') {\n * // handle it\n * }\n * }\n * ```\n */\nexport class MdgError extends Error {\n /** Always `'MdgError'`. */\n override readonly name = 'MdgError';\n /** Why the call failed; the same code in every language. */\n readonly code: ErrorCode;\n\n /**\n * Creates an error with a shared spec code.\n *\n * @param code - Shared spec error code.\n * @param message - Human-readable explanation, in English.\n */\n constructor(code: ErrorCode, message: string) {\n super(message);\n this.code = code;\n }\n\n /**\n * Makes `instanceof MdgError` true for errors from any mdg-utils package or build.\n *\n * @remarks Each package, and its ESM and CommonJS builds, has its own copy of this class,\n * so the check looks at the error's shape instead of its prototype chain.\n *\n * @param value - Any value, usually a caught error.\n * @returns `true` when `value` is an mdg-utils error.\n */\n static override [Symbol.hasInstance](value: unknown): boolean {\n return value instanceof Error && value.name === 'MdgError' && 'code' in value;\n }\n}\n","import { MdgError, type ErrorCode, type SafeParseResult } from './generated/errors.ts';\n\n/**\n * A rejected parse carrying its spec error code.\n *\n * @param code - The spec error code.\n * @param message - What was wrong with the input.\n * @returns `{ success: false, error }`.\n *\n * @example\n * ```ts\n * failure('INVALID_FORMAT', 'Expected a number.'); // { success: false, error: MdgError }\n * ```\n */\nexport function failure(code: ErrorCode, message: string): SafeParseResult<never> {\n return { success: false, error: new MdgError(code, message) };\n}\n","// Reads a number typed in any common way into its 9-digit national significant number.\nimport {\n COUNTRY_CODE,\n INTERNATIONAL_PREFIX,\n NATIONAL_NUMBER_LENGTH,\n TRUNK_PREFIX,\n} from './generated/data.ts';\nimport type { SafeParseResult } from './generated/errors.ts';\nimport { failure } from './result.ts';\n\n// Bounded so a parser that reads user input never scans unbounded text.\nconst MAX_INPUT_LENGTH = 32;\nconst SEPARATORS = /[\\s().-]/g;\n// A national significant number never starts with the trunk prefix 0 (ITU-T E.164).\nconst NATIONAL_NUMBER_DIGITS = /^[1-9]\\d*$/;\nconst NATIONAL_PREFIXES = [\n `+${COUNTRY_CODE}`,\n `${INTERNATIONAL_PREFIX}${COUNTRY_CODE}`,\n COUNTRY_CODE,\n TRUNK_PREFIX,\n '',\n] as const;\n\nfunction stripNationalPrefix(compact: string): string | undefined {\n const prefix = NATIONAL_PREFIXES.find(\n (candidate) =>\n compact.startsWith(candidate) && compact.length === candidate.length + NATIONAL_NUMBER_LENGTH,\n );\n return prefix === undefined ? undefined : compact.slice(prefix.length);\n}\n\n/**\n * Strips separators and the `+261`, `00261`, `261` or `0` prefix, keeping the 9 digits.\n *\n * @param input - The number as typed by a user.\n * @returns The national significant number, or `INVALID_FORMAT`.\n *\n * @example\n * ```ts\n * readNationalNumber('+261 34 12 345 67'); // { success: true, data: '341234567' }\n * ```\n */\nexport function readNationalNumber(input: string): SafeParseResult<string> {\n if (input.length > MAX_INPUT_LENGTH) {\n return failure(\n 'INVALID_FORMAT',\n `Phone numbers are at most ${String(MAX_INPUT_LENGTH)} characters.`,\n );\n }\n const nationalNumber = stripNationalPrefix(input.replace(SEPARATORS, ''));\n if (nationalNumber === undefined || !NATIONAL_NUMBER_DIGITS.test(nationalNumber)) {\n return failure('INVALID_FORMAT', 'Expected a Malagasy number such as 034 12 345 67.');\n }\n return { success: true, data: nationalNumber };\n}\n","import {\n COUNTRY_CODE,\n OPERATOR_BY_PREFIX,\n OPERATOR_PREFIX_LENGTH,\n type OperatorId,\n} from './generated/data.ts';\nimport type { SafeParseResult } from './generated/errors.ts';\nimport { readNationalNumber } from './read-national-number.ts';\nimport { failure } from './result.ts';\n\ndeclare const phoneNumberBrand: unique symbol;\n\n/**\n * A Malagasy mobile number that passed validation. Create it with {@link parsePhoneNumber}.\n *\n * @example\n * ```ts\n * const phone: PhoneNumber = parsePhoneNumber('034 12 345 67');\n * phone.e164; // '+261341234567'\n * ```\n */\nexport interface PhoneNumber {\n /** The number in E.164 form, for storage and APIs: `+261341234567`. */\n readonly e164: string;\n /** The 9 digits after the country code: `341234567`. */\n readonly nationalNumber: string;\n /** The operator that holds the number's prefix. */\n readonly operator: OperatorId;\n /** Marks values that went through validation; it does not exist at runtime. */\n readonly [phoneNumberBrand]: true;\n}\n\n/**\n * Reads a Malagasy mobile number without throwing.\n *\n * @param input - The number as typed by a user, in any accepted spelling.\n * @returns `{ success: true, data }` with the {@link PhoneNumber}, or `{ success: false, error }`.\n *\n * @example\n * ```ts\n * const result = safeParsePhoneNumber('+261 34 12 345 67');\n * if (result.success) result.data.operator; // 'yas'\n * ```\n */\nexport function safeParsePhoneNumber(input: unknown): SafeParseResult<PhoneNumber> {\n if (typeof input !== 'string') return failure('INVALID_TYPE', 'Expected the number as a string.');\n const national = readNationalNumber(input);\n if (!national.success) return national;\n const operator = OPERATOR_BY_PREFIX.get(national.data.slice(0, OPERATOR_PREFIX_LENGTH));\n if (operator === undefined) {\n return failure('UNKNOWN_OPERATOR', 'The prefix is not assigned to a Malagasy mobile operator.');\n }\n const phone = {\n e164: `+${COUNTRY_CODE}${national.data}`,\n nationalNumber: national.data,\n operator,\n };\n return { success: true, data: phone as PhoneNumber };\n}\n\n/**\n * Reads a Malagasy mobile number written in any common way.\n *\n * Accepts `034 12 345 67`, `+261 34 12 345 67`, `00261…`, `261…` and `34 12 345 67`;\n * spaces, dashes, dots and parentheses are ignored.\n *\n * @param input - The number as typed by a user.\n * @returns The validated {@link PhoneNumber}.\n * @throws {@link MdgError} `INVALID_TYPE` for non-strings, `INVALID_FORMAT` for text that is\n * not a Malagasy number, `UNKNOWN_OPERATOR` for an unassigned mobile prefix.\n *\n * @example\n * ```ts\n * parsePhoneNumber('034 12 345 67');\n * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }\n * ```\n */\nexport function parsePhoneNumber(input: string): PhoneNumber {\n const result = safeParsePhoneNumber(input);\n if (!result.success) throw result.error;\n return result.data;\n}\n\n/**\n * Reads a Malagasy mobile number, or gives `undefined` instead of throwing.\n *\n * Use {@link safeParsePhoneNumber} when you need to know why the input was rejected.\n *\n * @param input - The number as typed by a user, in any accepted spelling.\n * @returns The {@link PhoneNumber}, or `undefined` when {@link parsePhoneNumber} would throw.\n *\n * @example\n * ```ts\n * tryParsePhoneNumber('034 12 345 67')?.operator; // 'yas'\n * tryParsePhoneNumber('031 12 345 67'); // undefined\n * ```\n */\nexport function tryParsePhoneNumber(input: unknown): PhoneNumber | undefined {\n const result = safeParsePhoneNumber(input);\n return result.success ? result.data : undefined;\n}\n\n/**\n * Tells whether the input is a valid Malagasy mobile number. Never throws.\n *\n * @param input - Any value.\n * @returns `true` when {@link parsePhoneNumber} would succeed.\n *\n * @example\n * ```ts\n * isValidPhoneNumber('034 12 345 67'); // true\n * isValidPhoneNumber('031 12 345 67'); // false\n * ```\n */\nexport function isValidPhoneNumber(input: unknown): boolean {\n return safeParsePhoneNumber(input).success;\n}\n","import { COUNTRY_CODE, GROUPING, TRUNK_PREFIX } from './generated/data.ts';\nimport { MdgError } from './generated/errors.ts';\nimport { parsePhoneNumber } from './phone-number.ts';\n\n/**\n * How {@link formatPhoneNumber} writes a number.\n *\n * - `e164`: `+261341234567`\n * - `international`: `+261 34 12 345 67`\n * - `national`: `034 12 345 67`\n *\n * @example\n * ```ts\n * const format: PhoneNumberFormat = 'national';\n * ```\n */\nexport type PhoneNumberFormat = 'e164' | 'international' | 'national';\n\nconst PHONE_NUMBER_FORMATS: readonly PhoneNumberFormat[] = ['e164', 'international', 'national'];\n\nconst GROUP_BOUNDS = GROUPING.reduce<readonly (readonly [number, number])[]>((bounds, size) => {\n const start = bounds.at(-1)?.[1] ?? 0;\n return [...bounds, [start, start + size]];\n}, []);\n\nfunction groupDigits(nationalNumber: string): string {\n return GROUP_BOUNDS.map(([start, end]) => nationalNumber.slice(start, end)).join(' ');\n}\n\nconst FORMATTERS: Readonly<Record<PhoneNumberFormat, (nationalNumber: string) => string>> = {\n e164: (nationalNumber) => `+${COUNTRY_CODE}${nationalNumber}`,\n international: (nationalNumber) => `+${COUNTRY_CODE} ${groupDigits(nationalNumber)}`,\n national: (nationalNumber) => `${TRUNK_PREFIX}${groupDigits(nationalNumber)}`,\n};\n\nfunction isPhoneNumberFormat(value: unknown): value is PhoneNumberFormat {\n return PHONE_NUMBER_FORMATS.some((format) => format === value);\n}\n\n/**\n * Writes a Malagasy mobile number in a standard form.\n *\n * @param input - The number in any spelling accepted by {@link parsePhoneNumber}.\n * @param format - `'e164'`, `'international'` or `'national'`.\n * @returns The formatted number.\n * @throws {@link MdgError} `INVALID_TYPE` for an unknown format, plus every error of\n * {@link parsePhoneNumber}.\n *\n * @example\n * ```ts\n * formatPhoneNumber('+261341234567', 'national'); // '034 12 345 67'\n * formatPhoneNumber('034 12 345 67', 'international'); // '+261 34 12 345 67'\n * ```\n */\nexport function formatPhoneNumber(input: string, format: PhoneNumberFormat): string {\n if (!isPhoneNumberFormat(format)) {\n throw new MdgError(\n 'INVALID_TYPE',\n `Format must be one of: ${PHONE_NUMBER_FORMATS.join(', ')}.`,\n );\n }\n return FORMATTERS[format](parsePhoneNumber(input).nationalNumber);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/generated/data.ts","../src/generated/errors.ts","../src/result.ts","../src/read-national-number.ts","../src/phone-number.ts","../src/format.ts"],"names":[],"mappings":";;;AAKO,IAAM,YAAA,GAAe,KAAA;AAGrB,IAAM,oBAAA,GAAuB,IAAA;AAG7B,IAAM,YAAA,GAAe,GAAA;AAGrB,IAAM,sBAAA,GAAyB,CAAA;AAG/B,IAAM,QAAA,GAAW,CAAC,CAAA,EAAG,CAAA,EAAG,GAAG,CAAC,CAAA;AAa5B,IAAM,cA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A,CAAK,CAAC,MAAA,KAAW,WAAW,KAAK,CAAA;AAC/D;AAiBO,SAAS,WAAA,CAAY,OAAe,MAAA,EAAmC;AAC5E,EAAA,IAAI,CAAC,mBAAA,CAAoB,MAAM,CAAA,EAAG;AAChC,IAAA,MAAM,IAAI,QAAA;AAAA,MACR,cAAA;AAAA,MACA,CAAA,uBAAA,EAA0B,oBAAA,CAAqB,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AAAA,KAC3D;AAAA,EACF;AACA,EAAA,OAAO,WAAW,MAAM,CAAA,CAAE,UAAA,CAAW,KAAK,EAAE,cAAc,CAAA;AAC5D","file":"index.cjs","sourcesContent":["// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n// From spec/modules/phone/data.yaml, spec 0.9.0.\n\n/** @internal */\nexport const COUNTRY_CODE = '261' as const;\n\n/** @internal */\nexport const INTERNATIONAL_PREFIX = '00' as const;\n\n/** @internal */\nexport const TRUNK_PREFIX = '0' as const;\n\n/** @internal */\nexport const NATIONAL_NUMBER_LENGTH = 9 as const;\n\n/** @internal Digit group sizes of the national number. */\nexport const GROUPING = [2, 2, 3, 2] as const;\n\n/** Identifier of a Malagasy telephone operator. */\nexport type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline' | 'gulfsat';\n\n/**\n * Display name of each operator, by {@link OperatorId}.\n *\n * @example\n * ```ts\n * OPERATOR_NAMES[parsePhone('034 12 345 67').operator]; // 'Yas Madagascar'\n * ```\n */\nexport const OPERATOR_NAMES = {\n orange: 'Orange Madagascar',\n airtel: 'Airtel Madagascar',\n yas: 'Yas Madagascar',\n blueline: 'Blueline',\n gulfsat: 'Gulfsat Madagascar',\n} as const;\n\n/** @internal Two-digit operator code → operator and line type. */\nexport const OPERATOR_BY_PREFIX: ReadonlyMap<\n string,\n { readonly operator: OperatorId; readonly type: 'mobile' | 'fixed' }\n> = new Map<string, { readonly operator: OperatorId; readonly type: 'mobile' | 'fixed' }>([\n ['20', { operator: 'yas', type: 'fixed' }],\n ['22', { operator: 'gulfsat', type: 'fixed' }],\n ['32', { operator: 'orange', type: 'mobile' }],\n ['33', { operator: 'airtel', type: 'mobile' }],\n ['34', { operator: 'yas', type: 'mobile' }],\n ['35', { operator: 'airtel', type: 'mobile' }],\n ['36', { operator: 'yas', type: 'mobile' }],\n ['37', { operator: 'orange', type: 'mobile' }],\n ['38', { operator: 'yas', type: 'mobile' }],\n ['39', { operator: 'blueline', type: 'mobile' }],\n]);\n\n/** @internal */\nexport const OPERATOR_PREFIX_LENGTH = 2 as const;\n\n/** @internal Operator code whose next digit is a zone. */\nexport const FIXED_ZONE_PREFIX = '20' as const;\n\n/** @internal Assigned zone digits after it. */\nexport const FIXED_ZONE_DIGITS = ['2', '4', '5', '6', '7', '8', '9'] as const;\n\n/** @internal Geographic numbers, longest prefix first. */\nexport const AREAS = [\n { prefix: '20722', name: 'Manakara', province: 'Fianarantsoa' },\n { prefix: '20729', name: 'Mananjary', province: 'Fianarantsoa' },\n { prefix: '2053', name: 'Toamasina', province: 'Toamasina' },\n { prefix: '2054', name: 'Ambatondrazaka', province: 'Toamasina' },\n { prefix: '2056', name: 'Moramanga', province: 'Toamasina' },\n { prefix: '2057', name: 'Sainte-Marie', province: 'Toamasina' },\n { prefix: '2062', name: 'Mahajanga', province: 'Mahajanga' },\n { prefix: '2067', name: 'Antsohihy', province: 'Mahajanga' },\n { prefix: '2069', name: 'Maintirano', province: 'Mahajanga' },\n { prefix: '2073', name: 'Farafangana', province: 'Fianarantsoa' },\n { prefix: '2075', name: 'Fianarantsoa', province: 'Fianarantsoa' },\n { prefix: '2082', name: 'Antsiranana', province: 'Antsiranana' },\n { prefix: '2086', name: 'Nosy Be', province: 'Antsiranana' },\n { prefix: '2088', name: 'Sambava', province: 'Antsiranana' },\n { prefix: '2092', name: 'Tolagnaro', province: 'Toliary' },\n { prefix: '2094', name: 'Toliary', province: 'Toliary' },\n { prefix: '2095', name: 'Morondava', province: 'Toliary' },\n { prefix: '202', name: 'Antananarivo', province: 'Antananarivo' },\n] as const;\n","// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n/** Version of the shared spec this code was generated from. */\nexport const SPEC_VERSION = '0.9.0';\n\n/**\n * Error code shared by every mdg-utils language port.\n *\n * - `INVALID_TYPE`: The input is not of the accepted type (for example a string or a non-integer where an integer is expected).\n * - `OUT_OF_RANGE`: The input has the right type but lies outside the supported range.\n * - `INVALID_FORMAT`: The input text cannot be read as a value of this module (wrong characters or wrong length).\n * - `UNKNOWN_OPERATOR`: The phone number is well formed but its operator code is not assigned to an operator.\n * - `PRECISION_LOSS`: The value is exact in the text but the port's number type cannot hold it exactly; ask for the exact text instead.\n * - `AMBIGUOUS`: The text reads as more than one value, so none is chosen.\n */\nexport type ErrorCode =\n | 'INVALID_TYPE'\n | 'OUT_OF_RANGE'\n | 'INVALID_FORMAT'\n | 'UNKNOWN_OPERATOR'\n | 'PRECISION_LOSS'\n | 'AMBIGUOUS';\n\n/**\n * Outcome of a `safeParse…` function: the value, or the error that would have been thrown.\n *\n * @example\n * ```ts\n * const result = safeParsePhone(input);\n * if (result.success) console.log(result.data);\n * else console.log(result.error.code);\n * ```\n */\nexport type SafeParseResult<T> =\n | { readonly success: true; readonly data: T }\n | { readonly success: false; readonly error: MdgError };\n\n/**\n * Error thrown by mdg-utils functions. Check `code`, which is the same in every language.\n *\n * @example\n * ```ts\n * try {\n * spell(-1);\n * } catch (error) {\n * if (error instanceof MdgError && error.code === 'OUT_OF_RANGE') {\n * // handle it\n * }\n * }\n * ```\n */\nexport class MdgError extends Error {\n /** Always `'MdgError'`. */\n override readonly name = 'MdgError';\n /** Why the call failed; the same code in every language. */\n readonly code: ErrorCode;\n\n /**\n * Creates an error with a shared spec code.\n *\n * @param code - Shared spec error code.\n * @param message - Human-readable explanation, in English.\n */\n constructor(code: ErrorCode, message: string) {\n super(message);\n this.code = code;\n }\n\n /**\n * Makes `instanceof MdgError` true for errors from any mdg-utils package or build.\n *\n * @remarks Each package, and its ESM and CommonJS builds, has its own copy of this class,\n * so the check looks at the error's shape instead of its prototype chain.\n *\n * @param value - Any value, usually a caught error.\n * @returns `true` when `value` is an mdg-utils error.\n */\n static override [Symbol.hasInstance](value: unknown): boolean {\n return value instanceof Error && value.name === 'MdgError' && 'code' in value;\n }\n}\n","import { MdgError, type ErrorCode, type SafeParseResult } from './generated/errors.ts';\n\n/**\n * A rejected parse carrying its spec error code.\n *\n * @param code - The spec error code.\n * @param message - What was wrong with the input.\n * @returns `{ success: false, error }`.\n *\n * @example\n * ```ts\n * failure('INVALID_FORMAT', 'Expected a number.'); // { success: false, error: MdgError }\n * ```\n */\nexport function failure(code: ErrorCode, message: string): SafeParseResult<never> {\n return { success: false, error: new MdgError(code, message) };\n}\n","// Reads a number typed in any common way into its 9-digit national significant number.\nimport {\n COUNTRY_CODE,\n INTERNATIONAL_PREFIX,\n NATIONAL_NUMBER_LENGTH,\n TRUNK_PREFIX,\n} from './generated/data.ts';\nimport type { SafeParseResult } from './generated/errors.ts';\nimport { failure } from './result.ts';\n\n// Bounded so a parser that reads user input never scans unbounded text.\nconst MAX_INPUT_LENGTH = 32;\nconst SEPARATORS = /[\\s().-]/g;\n// A national significant number never starts with the trunk prefix 0 (ITU-T E.164).\nconst NATIONAL_NUMBER_DIGITS = /^[1-9]\\d*$/;\nconst NATIONAL_PREFIXES = [\n `+${COUNTRY_CODE}`,\n `${INTERNATIONAL_PREFIX}${COUNTRY_CODE}`,\n COUNTRY_CODE,\n TRUNK_PREFIX,\n '',\n] as const;\n\nfunction stripNationalPrefix(compact: string): string | undefined {\n const prefix = NATIONAL_PREFIXES.find(\n (candidate) =>\n compact.startsWith(candidate) && compact.length === candidate.length + NATIONAL_NUMBER_LENGTH,\n );\n return prefix === undefined ? undefined : compact.slice(prefix.length);\n}\n\n/**\n * Strips separators and the `+261`, `00261`, `261` or `0` prefix, keeping the 9 digits.\n *\n * @param input - The number as typed by a user.\n * @returns The national significant number, or `INVALID_FORMAT`.\n *\n * @example\n * ```ts\n * readNationalNumber('+261 34 12 345 67'); // { success: true, data: '341234567' }\n * ```\n */\nexport function readNationalNumber(input: string): SafeParseResult<string> {\n if (input.length > MAX_INPUT_LENGTH) {\n return failure(\n 'INVALID_FORMAT',\n `Phone numbers are at most ${String(MAX_INPUT_LENGTH)} characters.`,\n );\n }\n const nationalNumber = stripNationalPrefix(input.replace(SEPARATORS, ''));\n if (nationalNumber === undefined || !NATIONAL_NUMBER_DIGITS.test(nationalNumber)) {\n return failure('INVALID_FORMAT', 'Expected a Malagasy number such as 034 12 345 67.');\n }\n return { success: true, data: nationalNumber };\n}\n","import {\n AREAS,\n COUNTRY_CODE,\n FIXED_ZONE_DIGITS,\n FIXED_ZONE_PREFIX,\n OPERATOR_BY_PREFIX,\n OPERATOR_PREFIX_LENGTH,\n type OperatorId,\n} from './generated/data.ts';\nimport type { SafeParseResult } from './generated/errors.ts';\nimport { readNationalNumber } from './read-national-number.ts';\nimport { failure } from './result.ts';\n\ndeclare const phoneNumberBrand: unique symbol;\n\n/**\n * What kind of line a number reaches: `mobile` (codes 3x) or `fixed` (codes 2x).\n *\n * @example\n * ```ts\n * const type: PhoneLineType = 'fixed';\n * ```\n */\nexport type PhoneLineType = 'mobile' | 'fixed';\n\n/**\n * The town of a geographic fixed number, as the national numbering plan lists it.\n *\n * @example\n * ```ts\n * const area: PhoneArea = { name: 'Toamasina', province: 'Toamasina' };\n * ```\n */\nexport interface PhoneArea {\n /** Town, e.g. `Toamasina`. */\n readonly name: string;\n /** Former province, e.g. `Toamasina`. */\n readonly province: string;\n}\n\nconst FIXED_ZONES: ReadonlySet<string> = new Set(FIXED_ZONE_DIGITS);\n\n/**\n * A Malagasy phone number, mobile or fixed, that passed validation. Create it with {@link parsePhone}.\n *\n * @example\n * ```ts\n * const phone: PhoneNumber = parsePhone('034 12 345 67');\n * phone.e164; // '+261341234567'\n * ```\n */\nexport interface PhoneNumber {\n /** The number in E.164 form, for storage and APIs: `+261341234567`. */\n readonly e164: string;\n /** The 9 digits after the country code: `341234567`. */\n readonly nationalNumber: string;\n /** The operator that holds the number's prefix. */\n readonly operator: OperatorId;\n /** `mobile` or `fixed`. */\n readonly type: PhoneLineType;\n /** The town of a geographic fixed number, or `null` (mobile, VSAT, or an unlisted town). */\n readonly area: PhoneArea | null;\n /** Marks values that went through validation; it does not exist at runtime. */\n readonly [phoneNumberBrand]: true;\n}\n\nfunction areaOf(nationalNumber: string): PhoneArea | null {\n const area = AREAS.find((entry) => nationalNumber.startsWith(entry.prefix));\n return area === undefined ? null : { name: area.name, province: area.province };\n}\n\n/**\n * Reads a Malagasy phone number, mobile or fixed, without throwing.\n *\n * @param input - The number as typed by a user, in any accepted spelling.\n * @returns `{ success: true, data }` with the {@link PhoneNumber}, or `{ success: false, error }`.\n *\n * @example\n * ```ts\n * const result = safeParsePhone('+261 34 12 345 67');\n * if (result.success) result.data.operator; // 'yas'\n * ```\n */\nexport function safeParsePhone(input: unknown): SafeParseResult<PhoneNumber> {\n if (typeof input !== 'string') return failure('INVALID_TYPE', 'Expected the number as a string.');\n const national = readNationalNumber(input);\n if (!national.success) return national;\n const prefix = national.data.slice(0, OPERATOR_PREFIX_LENGTH);\n const holder = OPERATOR_BY_PREFIX.get(prefix);\n const zone = national.data.charAt(OPERATOR_PREFIX_LENGTH);\n if (holder === undefined || (prefix === FIXED_ZONE_PREFIX && !FIXED_ZONES.has(zone))) {\n return failure('UNKNOWN_OPERATOR', 'The prefix is not assigned to a Malagasy operator.');\n }\n const phone = {\n e164: `+${COUNTRY_CODE}${national.data}`,\n nationalNumber: national.data,\n operator: holder.operator,\n type: holder.type,\n area: areaOf(national.data),\n };\n return { success: true, data: phone as PhoneNumber };\n}\n\n/**\n * Reads a Malagasy phone number, mobile or fixed, written in any common way.\n *\n * Accepts `034 12 345 67`, `+261 34 12 345 67`, `00261…`, `261…` and `34 12 345 67`;\n * spaces, dashes, dots and parentheses are ignored.\n *\n * @param input - The number as typed by a user.\n * @returns The validated {@link PhoneNumber}.\n * @throws {@link MdgError} `INVALID_TYPE` for non-strings, `INVALID_FORMAT` for text that is\n * not a Malagasy number, `UNKNOWN_OPERATOR` for an unassigned prefix.\n *\n * @example\n * ```ts\n * parsePhone('034 12 345 67');\n * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas', type: 'mobile', area: null }\n * parsePhone('020 53 123 45').area; // { name: 'Toamasina', province: 'Toamasina' }\n * ```\n */\nexport function parsePhone(input: string): PhoneNumber {\n const result = safeParsePhone(input);\n if (!result.success) throw result.error;\n return result.data;\n}\n\n/**\n * Reads a Malagasy phone number, or gives `undefined` instead of throwing.\n *\n * Use {@link safeParsePhone} when you need to know why the input was rejected.\n *\n * @param input - The number as typed by a user, in any accepted spelling.\n * @returns The {@link PhoneNumber}, or `undefined` when {@link parsePhone} would throw.\n *\n * @example\n * ```ts\n * tryParsePhone('034 12 345 67')?.operator; // 'yas'\n * tryParsePhone('031 12 345 67'); // undefined\n * ```\n */\nexport function tryParsePhone(input: unknown): PhoneNumber | undefined {\n const result = safeParsePhone(input);\n return result.success ? result.data : undefined;\n}\n\n/**\n * Tells whether the input is a valid Malagasy phone number, mobile or fixed. Never throws.\n *\n * @param input - Any value.\n * @returns `true` when {@link parsePhone} would succeed.\n *\n * @example\n * ```ts\n * isValidPhone('034 12 345 67'); // true\n * isValidPhone('031 12 345 67'); // false\n * ```\n */\nexport function isValidPhone(input: unknown): boolean {\n return safeParsePhone(input).success;\n}\n","import { COUNTRY_CODE, GROUPING, TRUNK_PREFIX } from './generated/data.ts';\nimport { MdgError } from './generated/errors.ts';\nimport { parsePhone } from './phone-number.ts';\n\n/**\n * How {@link formatPhone} writes a number.\n *\n * - `e164`: `+261341234567`\n * - `international`: `+261 34 12 345 67`\n * - `national`: `034 12 345 67`\n *\n * @example\n * ```ts\n * const format: PhoneNumberFormat = 'national';\n * ```\n */\nexport type PhoneNumberFormat = 'e164' | 'international' | 'national';\n\nconst PHONE_NUMBER_FORMATS: readonly PhoneNumberFormat[] = ['e164', 'international', 'national'];\n\nconst GROUP_BOUNDS = GROUPING.reduce<readonly (readonly [number, number])[]>((bounds, size) => {\n const start = bounds.at(-1)?.[1] ?? 0;\n return [...bounds, [start, start + size]];\n}, []);\n\nfunction groupDigits(nationalNumber: string): string {\n return GROUP_BOUNDS.map(([start, end]) => nationalNumber.slice(start, end)).join(' ');\n}\n\nconst FORMATTERS: Readonly<Record<PhoneNumberFormat, (nationalNumber: string) => string>> = {\n e164: (nationalNumber) => `+${COUNTRY_CODE}${nationalNumber}`,\n international: (nationalNumber) => `+${COUNTRY_CODE} ${groupDigits(nationalNumber)}`,\n national: (nationalNumber) => `${TRUNK_PREFIX}${groupDigits(nationalNumber)}`,\n};\n\nfunction isPhoneNumberFormat(value: unknown): value is PhoneNumberFormat {\n return PHONE_NUMBER_FORMATS.some((format) => format === value);\n}\n\n/**\n * Writes a Malagasy mobile number in a standard form.\n *\n * @param input - The number in any spelling accepted by {@link parsePhone}.\n * @param format - `'e164'`, `'international'` or `'national'`.\n * @returns The formatted number.\n * @throws {@link MdgError} `INVALID_TYPE` for an unknown format, plus every error of\n * {@link parsePhone}.\n *\n * @example\n * ```ts\n * formatPhone('+261341234567', 'national'); // '034 12 345 67'\n * formatPhone('034 12 345 67', 'international'); // '+261 34 12 345 67'\n * ```\n */\nexport function formatPhone(input: string, format: PhoneNumberFormat): string {\n if (!isPhoneNumberFormat(format)) {\n throw new MdgError(\n 'INVALID_TYPE',\n `Format must be one of: ${PHONE_NUMBER_FORMATS.join(', ')}.`,\n );\n }\n return FORMATTERS[format](parsePhone(input).nationalNumber);\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* How {@link
|
|
2
|
+
* How {@link formatPhone} writes a number.
|
|
3
3
|
*
|
|
4
4
|
* - `e164`: `+261341234567`
|
|
5
5
|
* - `international`: `+261 34 12 345 67`
|
|
@@ -14,28 +14,28 @@ type PhoneNumberFormat = 'e164' | 'international' | 'national';
|
|
|
14
14
|
/**
|
|
15
15
|
* Writes a Malagasy mobile number in a standard form.
|
|
16
16
|
*
|
|
17
|
-
* @param input - The number in any spelling accepted by {@link
|
|
17
|
+
* @param input - The number in any spelling accepted by {@link parsePhone}.
|
|
18
18
|
* @param format - `'e164'`, `'international'` or `'national'`.
|
|
19
19
|
* @returns The formatted number.
|
|
20
20
|
* @throws {@link MdgError} `INVALID_TYPE` for an unknown format, plus every error of
|
|
21
|
-
* {@link
|
|
21
|
+
* {@link parsePhone}.
|
|
22
22
|
*
|
|
23
23
|
* @example
|
|
24
24
|
* ```ts
|
|
25
|
-
*
|
|
26
|
-
*
|
|
25
|
+
* formatPhone('+261341234567', 'national'); // '034 12 345 67'
|
|
26
|
+
* formatPhone('034 12 345 67', 'international'); // '+261 34 12 345 67'
|
|
27
27
|
* ```
|
|
28
28
|
*/
|
|
29
|
-
declare function
|
|
29
|
+
declare function formatPhone(input: string, format: PhoneNumberFormat): string;
|
|
30
30
|
|
|
31
|
-
/** Identifier of a Malagasy
|
|
32
|
-
type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline';
|
|
31
|
+
/** Identifier of a Malagasy telephone operator. */
|
|
32
|
+
type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline' | 'gulfsat';
|
|
33
33
|
/**
|
|
34
|
-
* Display name of each
|
|
34
|
+
* Display name of each operator, by {@link OperatorId}.
|
|
35
35
|
*
|
|
36
36
|
* @example
|
|
37
37
|
* ```ts
|
|
38
|
-
* OPERATOR_NAMES[
|
|
38
|
+
* OPERATOR_NAMES[parsePhone('034 12 345 67').operator]; // 'Yas Madagascar'
|
|
39
39
|
* ```
|
|
40
40
|
*/
|
|
41
41
|
declare const OPERATOR_NAMES: {
|
|
@@ -43,25 +43,28 @@ declare const OPERATOR_NAMES: {
|
|
|
43
43
|
readonly airtel: "Airtel Madagascar";
|
|
44
44
|
readonly yas: "Yas Madagascar";
|
|
45
45
|
readonly blueline: "Blueline";
|
|
46
|
+
readonly gulfsat: "Gulfsat Madagascar";
|
|
46
47
|
};
|
|
47
48
|
|
|
48
49
|
/** Version of the shared spec this code was generated from. */
|
|
49
|
-
declare const SPEC_VERSION = "0.
|
|
50
|
+
declare const SPEC_VERSION = "0.9.0";
|
|
50
51
|
/**
|
|
51
52
|
* Error code shared by every mdg-utils language port.
|
|
52
53
|
*
|
|
53
54
|
* - `INVALID_TYPE`: The input is not of the accepted type (for example a string or a non-integer where an integer is expected).
|
|
54
55
|
* - `OUT_OF_RANGE`: The input has the right type but lies outside the supported range.
|
|
55
56
|
* - `INVALID_FORMAT`: The input text cannot be read as a value of this module (wrong characters or wrong length).
|
|
56
|
-
* - `UNKNOWN_OPERATOR`: The phone number is well formed but its operator code is not assigned to
|
|
57
|
+
* - `UNKNOWN_OPERATOR`: The phone number is well formed but its operator code is not assigned to an operator.
|
|
58
|
+
* - `PRECISION_LOSS`: The value is exact in the text but the port's number type cannot hold it exactly; ask for the exact text instead.
|
|
59
|
+
* - `AMBIGUOUS`: The text reads as more than one value, so none is chosen.
|
|
57
60
|
*/
|
|
58
|
-
type ErrorCode = 'INVALID_TYPE' | 'OUT_OF_RANGE' | 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR';
|
|
61
|
+
type ErrorCode = 'INVALID_TYPE' | 'OUT_OF_RANGE' | 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR' | 'PRECISION_LOSS' | 'AMBIGUOUS';
|
|
59
62
|
/**
|
|
60
63
|
* Outcome of a `safeParse…` function: the value, or the error that would have been thrown.
|
|
61
64
|
*
|
|
62
65
|
* @example
|
|
63
66
|
* ```ts
|
|
64
|
-
* const result =
|
|
67
|
+
* const result = safeParsePhone(input);
|
|
65
68
|
* if (result.success) console.log(result.data);
|
|
66
69
|
* else console.log(result.error.code);
|
|
67
70
|
* ```
|
|
@@ -79,7 +82,7 @@ type SafeParseResult<T> = {
|
|
|
79
82
|
* @example
|
|
80
83
|
* ```ts
|
|
81
84
|
* try {
|
|
82
|
-
*
|
|
85
|
+
* spell(-1);
|
|
83
86
|
* } catch (error) {
|
|
84
87
|
* if (error instanceof MdgError && error.code === 'OUT_OF_RANGE') {
|
|
85
88
|
* // handle it
|
|
@@ -113,11 +116,34 @@ declare class MdgError extends Error {
|
|
|
113
116
|
|
|
114
117
|
declare const phoneNumberBrand: unique symbol;
|
|
115
118
|
/**
|
|
116
|
-
*
|
|
119
|
+
* What kind of line a number reaches: `mobile` (codes 3x) or `fixed` (codes 2x).
|
|
117
120
|
*
|
|
118
121
|
* @example
|
|
119
122
|
* ```ts
|
|
120
|
-
* const
|
|
123
|
+
* const type: PhoneLineType = 'fixed';
|
|
124
|
+
* ```
|
|
125
|
+
*/
|
|
126
|
+
type PhoneLineType = 'mobile' | 'fixed';
|
|
127
|
+
/**
|
|
128
|
+
* The town of a geographic fixed number, as the national numbering plan lists it.
|
|
129
|
+
*
|
|
130
|
+
* @example
|
|
131
|
+
* ```ts
|
|
132
|
+
* const area: PhoneArea = { name: 'Toamasina', province: 'Toamasina' };
|
|
133
|
+
* ```
|
|
134
|
+
*/
|
|
135
|
+
interface PhoneArea {
|
|
136
|
+
/** Town, e.g. `Toamasina`. */
|
|
137
|
+
readonly name: string;
|
|
138
|
+
/** Former province, e.g. `Toamasina`. */
|
|
139
|
+
readonly province: string;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* A Malagasy phone number, mobile or fixed, that passed validation. Create it with {@link parsePhone}.
|
|
143
|
+
*
|
|
144
|
+
* @example
|
|
145
|
+
* ```ts
|
|
146
|
+
* const phone: PhoneNumber = parsePhone('034 12 345 67');
|
|
121
147
|
* phone.e164; // '+261341234567'
|
|
122
148
|
* ```
|
|
123
149
|
*/
|
|
@@ -128,24 +154,28 @@ interface PhoneNumber {
|
|
|
128
154
|
readonly nationalNumber: string;
|
|
129
155
|
/** The operator that holds the number's prefix. */
|
|
130
156
|
readonly operator: OperatorId;
|
|
157
|
+
/** `mobile` or `fixed`. */
|
|
158
|
+
readonly type: PhoneLineType;
|
|
159
|
+
/** The town of a geographic fixed number, or `null` (mobile, VSAT, or an unlisted town). */
|
|
160
|
+
readonly area: PhoneArea | null;
|
|
131
161
|
/** Marks values that went through validation; it does not exist at runtime. */
|
|
132
162
|
readonly [phoneNumberBrand]: true;
|
|
133
163
|
}
|
|
134
164
|
/**
|
|
135
|
-
* Reads a Malagasy
|
|
165
|
+
* Reads a Malagasy phone number, mobile or fixed, without throwing.
|
|
136
166
|
*
|
|
137
167
|
* @param input - The number as typed by a user, in any accepted spelling.
|
|
138
168
|
* @returns `{ success: true, data }` with the {@link PhoneNumber}, or `{ success: false, error }`.
|
|
139
169
|
*
|
|
140
170
|
* @example
|
|
141
171
|
* ```ts
|
|
142
|
-
* const result =
|
|
172
|
+
* const result = safeParsePhone('+261 34 12 345 67');
|
|
143
173
|
* if (result.success) result.data.operator; // 'yas'
|
|
144
174
|
* ```
|
|
145
175
|
*/
|
|
146
|
-
declare function
|
|
176
|
+
declare function safeParsePhone(input: unknown): SafeParseResult<PhoneNumber>;
|
|
147
177
|
/**
|
|
148
|
-
* Reads a Malagasy
|
|
178
|
+
* Reads a Malagasy phone number, mobile or fixed, written in any common way.
|
|
149
179
|
*
|
|
150
180
|
* Accepts `034 12 345 67`, `+261 34 12 345 67`, `00261…`, `261…` and `34 12 345 67`;
|
|
151
181
|
* spaces, dashes, dots and parentheses are ignored.
|
|
@@ -153,43 +183,44 @@ declare function safeParsePhoneNumber(input: unknown): SafeParseResult<PhoneNumb
|
|
|
153
183
|
* @param input - The number as typed by a user.
|
|
154
184
|
* @returns The validated {@link PhoneNumber}.
|
|
155
185
|
* @throws {@link MdgError} `INVALID_TYPE` for non-strings, `INVALID_FORMAT` for text that is
|
|
156
|
-
* not a Malagasy number, `UNKNOWN_OPERATOR` for an unassigned
|
|
186
|
+
* not a Malagasy number, `UNKNOWN_OPERATOR` for an unassigned prefix.
|
|
157
187
|
*
|
|
158
188
|
* @example
|
|
159
189
|
* ```ts
|
|
160
|
-
*
|
|
161
|
-
* // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }
|
|
190
|
+
* parsePhone('034 12 345 67');
|
|
191
|
+
* // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas', type: 'mobile', area: null }
|
|
192
|
+
* parsePhone('020 53 123 45').area; // { name: 'Toamasina', province: 'Toamasina' }
|
|
162
193
|
* ```
|
|
163
194
|
*/
|
|
164
|
-
declare function
|
|
195
|
+
declare function parsePhone(input: string): PhoneNumber;
|
|
165
196
|
/**
|
|
166
|
-
* Reads a Malagasy
|
|
197
|
+
* Reads a Malagasy phone number, or gives `undefined` instead of throwing.
|
|
167
198
|
*
|
|
168
|
-
* Use {@link
|
|
199
|
+
* Use {@link safeParsePhone} when you need to know why the input was rejected.
|
|
169
200
|
*
|
|
170
201
|
* @param input - The number as typed by a user, in any accepted spelling.
|
|
171
|
-
* @returns The {@link PhoneNumber}, or `undefined` when {@link
|
|
202
|
+
* @returns The {@link PhoneNumber}, or `undefined` when {@link parsePhone} would throw.
|
|
172
203
|
*
|
|
173
204
|
* @example
|
|
174
205
|
* ```ts
|
|
175
|
-
*
|
|
176
|
-
*
|
|
206
|
+
* tryParsePhone('034 12 345 67')?.operator; // 'yas'
|
|
207
|
+
* tryParsePhone('031 12 345 67'); // undefined
|
|
177
208
|
* ```
|
|
178
209
|
*/
|
|
179
|
-
declare function
|
|
210
|
+
declare function tryParsePhone(input: unknown): PhoneNumber | undefined;
|
|
180
211
|
/**
|
|
181
|
-
* Tells whether the input is a valid Malagasy mobile
|
|
212
|
+
* Tells whether the input is a valid Malagasy phone number, mobile or fixed. Never throws.
|
|
182
213
|
*
|
|
183
214
|
* @param input - Any value.
|
|
184
|
-
* @returns `true` when {@link
|
|
215
|
+
* @returns `true` when {@link parsePhone} would succeed.
|
|
185
216
|
*
|
|
186
217
|
* @example
|
|
187
218
|
* ```ts
|
|
188
|
-
*
|
|
189
|
-
*
|
|
219
|
+
* isValidPhone('034 12 345 67'); // true
|
|
220
|
+
* isValidPhone('031 12 345 67'); // false
|
|
190
221
|
* ```
|
|
191
222
|
*/
|
|
192
|
-
declare function
|
|
223
|
+
declare function isValidPhone(input: unknown): boolean;
|
|
193
224
|
|
|
194
|
-
export { MdgError, OPERATOR_NAMES, SPEC_VERSION,
|
|
195
|
-
export type { ErrorCode, OperatorId, PhoneNumber, PhoneNumberFormat, SafeParseResult };
|
|
225
|
+
export { MdgError, OPERATOR_NAMES, SPEC_VERSION, formatPhone, isValidPhone, parsePhone, safeParsePhone, tryParsePhone };
|
|
226
|
+
export type { ErrorCode, OperatorId, PhoneArea, PhoneLineType, PhoneNumber, PhoneNumberFormat, SafeParseResult };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* How {@link
|
|
2
|
+
* How {@link formatPhone} writes a number.
|
|
3
3
|
*
|
|
4
4
|
* - `e164`: `+261341234567`
|
|
5
5
|
* - `international`: `+261 34 12 345 67`
|
|
@@ -14,28 +14,28 @@ type PhoneNumberFormat = 'e164' | 'international' | 'national';
|
|
|
14
14
|
/**
|
|
15
15
|
* Writes a Malagasy mobile number in a standard form.
|
|
16
16
|
*
|
|
17
|
-
* @param input - The number in any spelling accepted by {@link
|
|
17
|
+
* @param input - The number in any spelling accepted by {@link parsePhone}.
|
|
18
18
|
* @param format - `'e164'`, `'international'` or `'national'`.
|
|
19
19
|
* @returns The formatted number.
|
|
20
20
|
* @throws {@link MdgError} `INVALID_TYPE` for an unknown format, plus every error of
|
|
21
|
-
* {@link
|
|
21
|
+
* {@link parsePhone}.
|
|
22
22
|
*
|
|
23
23
|
* @example
|
|
24
24
|
* ```ts
|
|
25
|
-
*
|
|
26
|
-
*
|
|
25
|
+
* formatPhone('+261341234567', 'national'); // '034 12 345 67'
|
|
26
|
+
* formatPhone('034 12 345 67', 'international'); // '+261 34 12 345 67'
|
|
27
27
|
* ```
|
|
28
28
|
*/
|
|
29
|
-
declare function
|
|
29
|
+
declare function formatPhone(input: string, format: PhoneNumberFormat): string;
|
|
30
30
|
|
|
31
|
-
/** Identifier of a Malagasy
|
|
32
|
-
type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline';
|
|
31
|
+
/** Identifier of a Malagasy telephone operator. */
|
|
32
|
+
type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline' | 'gulfsat';
|
|
33
33
|
/**
|
|
34
|
-
* Display name of each
|
|
34
|
+
* Display name of each operator, by {@link OperatorId}.
|
|
35
35
|
*
|
|
36
36
|
* @example
|
|
37
37
|
* ```ts
|
|
38
|
-
* OPERATOR_NAMES[
|
|
38
|
+
* OPERATOR_NAMES[parsePhone('034 12 345 67').operator]; // 'Yas Madagascar'
|
|
39
39
|
* ```
|
|
40
40
|
*/
|
|
41
41
|
declare const OPERATOR_NAMES: {
|
|
@@ -43,25 +43,28 @@ declare const OPERATOR_NAMES: {
|
|
|
43
43
|
readonly airtel: "Airtel Madagascar";
|
|
44
44
|
readonly yas: "Yas Madagascar";
|
|
45
45
|
readonly blueline: "Blueline";
|
|
46
|
+
readonly gulfsat: "Gulfsat Madagascar";
|
|
46
47
|
};
|
|
47
48
|
|
|
48
49
|
/** Version of the shared spec this code was generated from. */
|
|
49
|
-
declare const SPEC_VERSION = "0.
|
|
50
|
+
declare const SPEC_VERSION = "0.9.0";
|
|
50
51
|
/**
|
|
51
52
|
* Error code shared by every mdg-utils language port.
|
|
52
53
|
*
|
|
53
54
|
* - `INVALID_TYPE`: The input is not of the accepted type (for example a string or a non-integer where an integer is expected).
|
|
54
55
|
* - `OUT_OF_RANGE`: The input has the right type but lies outside the supported range.
|
|
55
56
|
* - `INVALID_FORMAT`: The input text cannot be read as a value of this module (wrong characters or wrong length).
|
|
56
|
-
* - `UNKNOWN_OPERATOR`: The phone number is well formed but its operator code is not assigned to
|
|
57
|
+
* - `UNKNOWN_OPERATOR`: The phone number is well formed but its operator code is not assigned to an operator.
|
|
58
|
+
* - `PRECISION_LOSS`: The value is exact in the text but the port's number type cannot hold it exactly; ask for the exact text instead.
|
|
59
|
+
* - `AMBIGUOUS`: The text reads as more than one value, so none is chosen.
|
|
57
60
|
*/
|
|
58
|
-
type ErrorCode = 'INVALID_TYPE' | 'OUT_OF_RANGE' | 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR';
|
|
61
|
+
type ErrorCode = 'INVALID_TYPE' | 'OUT_OF_RANGE' | 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR' | 'PRECISION_LOSS' | 'AMBIGUOUS';
|
|
59
62
|
/**
|
|
60
63
|
* Outcome of a `safeParse…` function: the value, or the error that would have been thrown.
|
|
61
64
|
*
|
|
62
65
|
* @example
|
|
63
66
|
* ```ts
|
|
64
|
-
* const result =
|
|
67
|
+
* const result = safeParsePhone(input);
|
|
65
68
|
* if (result.success) console.log(result.data);
|
|
66
69
|
* else console.log(result.error.code);
|
|
67
70
|
* ```
|
|
@@ -79,7 +82,7 @@ type SafeParseResult<T> = {
|
|
|
79
82
|
* @example
|
|
80
83
|
* ```ts
|
|
81
84
|
* try {
|
|
82
|
-
*
|
|
85
|
+
* spell(-1);
|
|
83
86
|
* } catch (error) {
|
|
84
87
|
* if (error instanceof MdgError && error.code === 'OUT_OF_RANGE') {
|
|
85
88
|
* // handle it
|
|
@@ -113,11 +116,34 @@ declare class MdgError extends Error {
|
|
|
113
116
|
|
|
114
117
|
declare const phoneNumberBrand: unique symbol;
|
|
115
118
|
/**
|
|
116
|
-
*
|
|
119
|
+
* What kind of line a number reaches: `mobile` (codes 3x) or `fixed` (codes 2x).
|
|
117
120
|
*
|
|
118
121
|
* @example
|
|
119
122
|
* ```ts
|
|
120
|
-
* const
|
|
123
|
+
* const type: PhoneLineType = 'fixed';
|
|
124
|
+
* ```
|
|
125
|
+
*/
|
|
126
|
+
type PhoneLineType = 'mobile' | 'fixed';
|
|
127
|
+
/**
|
|
128
|
+
* The town of a geographic fixed number, as the national numbering plan lists it.
|
|
129
|
+
*
|
|
130
|
+
* @example
|
|
131
|
+
* ```ts
|
|
132
|
+
* const area: PhoneArea = { name: 'Toamasina', province: 'Toamasina' };
|
|
133
|
+
* ```
|
|
134
|
+
*/
|
|
135
|
+
interface PhoneArea {
|
|
136
|
+
/** Town, e.g. `Toamasina`. */
|
|
137
|
+
readonly name: string;
|
|
138
|
+
/** Former province, e.g. `Toamasina`. */
|
|
139
|
+
readonly province: string;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* A Malagasy phone number, mobile or fixed, that passed validation. Create it with {@link parsePhone}.
|
|
143
|
+
*
|
|
144
|
+
* @example
|
|
145
|
+
* ```ts
|
|
146
|
+
* const phone: PhoneNumber = parsePhone('034 12 345 67');
|
|
121
147
|
* phone.e164; // '+261341234567'
|
|
122
148
|
* ```
|
|
123
149
|
*/
|
|
@@ -128,24 +154,28 @@ interface PhoneNumber {
|
|
|
128
154
|
readonly nationalNumber: string;
|
|
129
155
|
/** The operator that holds the number's prefix. */
|
|
130
156
|
readonly operator: OperatorId;
|
|
157
|
+
/** `mobile` or `fixed`. */
|
|
158
|
+
readonly type: PhoneLineType;
|
|
159
|
+
/** The town of a geographic fixed number, or `null` (mobile, VSAT, or an unlisted town). */
|
|
160
|
+
readonly area: PhoneArea | null;
|
|
131
161
|
/** Marks values that went through validation; it does not exist at runtime. */
|
|
132
162
|
readonly [phoneNumberBrand]: true;
|
|
133
163
|
}
|
|
134
164
|
/**
|
|
135
|
-
* Reads a Malagasy
|
|
165
|
+
* Reads a Malagasy phone number, mobile or fixed, without throwing.
|
|
136
166
|
*
|
|
137
167
|
* @param input - The number as typed by a user, in any accepted spelling.
|
|
138
168
|
* @returns `{ success: true, data }` with the {@link PhoneNumber}, or `{ success: false, error }`.
|
|
139
169
|
*
|
|
140
170
|
* @example
|
|
141
171
|
* ```ts
|
|
142
|
-
* const result =
|
|
172
|
+
* const result = safeParsePhone('+261 34 12 345 67');
|
|
143
173
|
* if (result.success) result.data.operator; // 'yas'
|
|
144
174
|
* ```
|
|
145
175
|
*/
|
|
146
|
-
declare function
|
|
176
|
+
declare function safeParsePhone(input: unknown): SafeParseResult<PhoneNumber>;
|
|
147
177
|
/**
|
|
148
|
-
* Reads a Malagasy
|
|
178
|
+
* Reads a Malagasy phone number, mobile or fixed, written in any common way.
|
|
149
179
|
*
|
|
150
180
|
* Accepts `034 12 345 67`, `+261 34 12 345 67`, `00261…`, `261…` and `34 12 345 67`;
|
|
151
181
|
* spaces, dashes, dots and parentheses are ignored.
|
|
@@ -153,43 +183,44 @@ declare function safeParsePhoneNumber(input: unknown): SafeParseResult<PhoneNumb
|
|
|
153
183
|
* @param input - The number as typed by a user.
|
|
154
184
|
* @returns The validated {@link PhoneNumber}.
|
|
155
185
|
* @throws {@link MdgError} `INVALID_TYPE` for non-strings, `INVALID_FORMAT` for text that is
|
|
156
|
-
* not a Malagasy number, `UNKNOWN_OPERATOR` for an unassigned
|
|
186
|
+
* not a Malagasy number, `UNKNOWN_OPERATOR` for an unassigned prefix.
|
|
157
187
|
*
|
|
158
188
|
* @example
|
|
159
189
|
* ```ts
|
|
160
|
-
*
|
|
161
|
-
* // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }
|
|
190
|
+
* parsePhone('034 12 345 67');
|
|
191
|
+
* // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas', type: 'mobile', area: null }
|
|
192
|
+
* parsePhone('020 53 123 45').area; // { name: 'Toamasina', province: 'Toamasina' }
|
|
162
193
|
* ```
|
|
163
194
|
*/
|
|
164
|
-
declare function
|
|
195
|
+
declare function parsePhone(input: string): PhoneNumber;
|
|
165
196
|
/**
|
|
166
|
-
* Reads a Malagasy
|
|
197
|
+
* Reads a Malagasy phone number, or gives `undefined` instead of throwing.
|
|
167
198
|
*
|
|
168
|
-
* Use {@link
|
|
199
|
+
* Use {@link safeParsePhone} when you need to know why the input was rejected.
|
|
169
200
|
*
|
|
170
201
|
* @param input - The number as typed by a user, in any accepted spelling.
|
|
171
|
-
* @returns The {@link PhoneNumber}, or `undefined` when {@link
|
|
202
|
+
* @returns The {@link PhoneNumber}, or `undefined` when {@link parsePhone} would throw.
|
|
172
203
|
*
|
|
173
204
|
* @example
|
|
174
205
|
* ```ts
|
|
175
|
-
*
|
|
176
|
-
*
|
|
206
|
+
* tryParsePhone('034 12 345 67')?.operator; // 'yas'
|
|
207
|
+
* tryParsePhone('031 12 345 67'); // undefined
|
|
177
208
|
* ```
|
|
178
209
|
*/
|
|
179
|
-
declare function
|
|
210
|
+
declare function tryParsePhone(input: unknown): PhoneNumber | undefined;
|
|
180
211
|
/**
|
|
181
|
-
* Tells whether the input is a valid Malagasy mobile
|
|
212
|
+
* Tells whether the input is a valid Malagasy phone number, mobile or fixed. Never throws.
|
|
182
213
|
*
|
|
183
214
|
* @param input - Any value.
|
|
184
|
-
* @returns `true` when {@link
|
|
215
|
+
* @returns `true` when {@link parsePhone} would succeed.
|
|
185
216
|
*
|
|
186
217
|
* @example
|
|
187
218
|
* ```ts
|
|
188
|
-
*
|
|
189
|
-
*
|
|
219
|
+
* isValidPhone('034 12 345 67'); // true
|
|
220
|
+
* isValidPhone('031 12 345 67'); // false
|
|
190
221
|
* ```
|
|
191
222
|
*/
|
|
192
|
-
declare function
|
|
223
|
+
declare function isValidPhone(input: unknown): boolean;
|
|
193
224
|
|
|
194
|
-
export { MdgError, OPERATOR_NAMES, SPEC_VERSION,
|
|
195
|
-
export type { ErrorCode, OperatorId, PhoneNumber, PhoneNumberFormat, SafeParseResult };
|
|
225
|
+
export { MdgError, OPERATOR_NAMES, SPEC_VERSION, formatPhone, isValidPhone, parsePhone, safeParsePhone, tryParsePhone };
|
|
226
|
+
export type { ErrorCode, OperatorId, PhoneArea, PhoneLineType, PhoneNumber, PhoneNumberFormat, SafeParseResult };
|
package/dist/index.js
CHANGED
|
@@ -8,21 +8,47 @@ var OPERATOR_NAMES = {
|
|
|
8
8
|
orange: "Orange Madagascar",
|
|
9
9
|
airtel: "Airtel Madagascar",
|
|
10
10
|
yas: "Yas Madagascar",
|
|
11
|
-
blueline: "Blueline"
|
|
11
|
+
blueline: "Blueline",
|
|
12
|
+
gulfsat: "Gulfsat Madagascar"
|
|
12
13
|
};
|
|
13
14
|
var OPERATOR_BY_PREFIX = /* @__PURE__ */ new Map([
|
|
14
|
-
["
|
|
15
|
-
["
|
|
16
|
-
["
|
|
17
|
-
["
|
|
18
|
-
["
|
|
19
|
-
["
|
|
20
|
-
["
|
|
15
|
+
["20", { operator: "yas", type: "fixed" }],
|
|
16
|
+
["22", { operator: "gulfsat", type: "fixed" }],
|
|
17
|
+
["32", { operator: "orange", type: "mobile" }],
|
|
18
|
+
["33", { operator: "airtel", type: "mobile" }],
|
|
19
|
+
["34", { operator: "yas", type: "mobile" }],
|
|
20
|
+
["35", { operator: "airtel", type: "mobile" }],
|
|
21
|
+
["36", { operator: "yas", type: "mobile" }],
|
|
22
|
+
["37", { operator: "orange", type: "mobile" }],
|
|
23
|
+
["38", { operator: "yas", type: "mobile" }],
|
|
24
|
+
["39", { operator: "blueline", type: "mobile" }]
|
|
21
25
|
]);
|
|
22
26
|
var OPERATOR_PREFIX_LENGTH = 2;
|
|
27
|
+
var FIXED_ZONE_PREFIX = "20";
|
|
28
|
+
var FIXED_ZONE_DIGITS = ["2", "4", "5", "6", "7", "8", "9"];
|
|
29
|
+
var AREAS = [
|
|
30
|
+
{ prefix: "20722", name: "Manakara", province: "Fianarantsoa" },
|
|
31
|
+
{ prefix: "20729", name: "Mananjary", province: "Fianarantsoa" },
|
|
32
|
+
{ prefix: "2053", name: "Toamasina", province: "Toamasina" },
|
|
33
|
+
{ prefix: "2054", name: "Ambatondrazaka", province: "Toamasina" },
|
|
34
|
+
{ prefix: "2056", name: "Moramanga", province: "Toamasina" },
|
|
35
|
+
{ prefix: "2057", name: "Sainte-Marie", province: "Toamasina" },
|
|
36
|
+
{ prefix: "2062", name: "Mahajanga", province: "Mahajanga" },
|
|
37
|
+
{ prefix: "2067", name: "Antsohihy", province: "Mahajanga" },
|
|
38
|
+
{ prefix: "2069", name: "Maintirano", province: "Mahajanga" },
|
|
39
|
+
{ prefix: "2073", name: "Farafangana", province: "Fianarantsoa" },
|
|
40
|
+
{ prefix: "2075", name: "Fianarantsoa", province: "Fianarantsoa" },
|
|
41
|
+
{ prefix: "2082", name: "Antsiranana", province: "Antsiranana" },
|
|
42
|
+
{ prefix: "2086", name: "Nosy Be", province: "Antsiranana" },
|
|
43
|
+
{ prefix: "2088", name: "Sambava", province: "Antsiranana" },
|
|
44
|
+
{ prefix: "2092", name: "Tolagnaro", province: "Toliary" },
|
|
45
|
+
{ prefix: "2094", name: "Toliary", province: "Toliary" },
|
|
46
|
+
{ prefix: "2095", name: "Morondava", province: "Toliary" },
|
|
47
|
+
{ prefix: "202", name: "Antananarivo", province: "Antananarivo" }
|
|
48
|
+
];
|
|
23
49
|
|
|
24
50
|
// src/generated/errors.ts
|
|
25
|
-
var SPEC_VERSION = "0.
|
|
51
|
+
var SPEC_VERSION = "0.9.0";
|
|
26
52
|
var MdgError = class extends Error {
|
|
27
53
|
/** Always `'MdgError'`. */
|
|
28
54
|
name = "MdgError";
|
|
@@ -89,32 +115,41 @@ function readNationalNumber(input) {
|
|
|
89
115
|
}
|
|
90
116
|
|
|
91
117
|
// src/phone-number.ts
|
|
92
|
-
|
|
118
|
+
var FIXED_ZONES = new Set(FIXED_ZONE_DIGITS);
|
|
119
|
+
function areaOf(nationalNumber) {
|
|
120
|
+
const area = AREAS.find((entry) => nationalNumber.startsWith(entry.prefix));
|
|
121
|
+
return area === void 0 ? null : { name: area.name, province: area.province };
|
|
122
|
+
}
|
|
123
|
+
function safeParsePhone(input) {
|
|
93
124
|
if (typeof input !== "string") return failure("INVALID_TYPE", "Expected the number as a string.");
|
|
94
125
|
const national = readNationalNumber(input);
|
|
95
126
|
if (!national.success) return national;
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
127
|
+
const prefix = national.data.slice(0, OPERATOR_PREFIX_LENGTH);
|
|
128
|
+
const holder = OPERATOR_BY_PREFIX.get(prefix);
|
|
129
|
+
const zone = national.data.charAt(OPERATOR_PREFIX_LENGTH);
|
|
130
|
+
if (holder === void 0 || prefix === FIXED_ZONE_PREFIX && !FIXED_ZONES.has(zone)) {
|
|
131
|
+
return failure("UNKNOWN_OPERATOR", "The prefix is not assigned to a Malagasy operator.");
|
|
99
132
|
}
|
|
100
133
|
const phone = {
|
|
101
134
|
e164: `+${COUNTRY_CODE}${national.data}`,
|
|
102
135
|
nationalNumber: national.data,
|
|
103
|
-
operator
|
|
136
|
+
operator: holder.operator,
|
|
137
|
+
type: holder.type,
|
|
138
|
+
area: areaOf(national.data)
|
|
104
139
|
};
|
|
105
140
|
return { success: true, data: phone };
|
|
106
141
|
}
|
|
107
|
-
function
|
|
108
|
-
const result =
|
|
142
|
+
function parsePhone(input) {
|
|
143
|
+
const result = safeParsePhone(input);
|
|
109
144
|
if (!result.success) throw result.error;
|
|
110
145
|
return result.data;
|
|
111
146
|
}
|
|
112
|
-
function
|
|
113
|
-
const result =
|
|
147
|
+
function tryParsePhone(input) {
|
|
148
|
+
const result = safeParsePhone(input);
|
|
114
149
|
return result.success ? result.data : void 0;
|
|
115
150
|
}
|
|
116
|
-
function
|
|
117
|
-
return
|
|
151
|
+
function isValidPhone(input) {
|
|
152
|
+
return safeParsePhone(input).success;
|
|
118
153
|
}
|
|
119
154
|
|
|
120
155
|
// src/format.ts
|
|
@@ -134,16 +169,16 @@ var FORMATTERS = {
|
|
|
134
169
|
function isPhoneNumberFormat(value) {
|
|
135
170
|
return PHONE_NUMBER_FORMATS.some((format) => format === value);
|
|
136
171
|
}
|
|
137
|
-
function
|
|
172
|
+
function formatPhone(input, format) {
|
|
138
173
|
if (!isPhoneNumberFormat(format)) {
|
|
139
174
|
throw new MdgError(
|
|
140
175
|
"INVALID_TYPE",
|
|
141
176
|
`Format must be one of: ${PHONE_NUMBER_FORMATS.join(", ")}.`
|
|
142
177
|
);
|
|
143
178
|
}
|
|
144
|
-
return FORMATTERS[format](
|
|
179
|
+
return FORMATTERS[format](parsePhone(input).nationalNumber);
|
|
145
180
|
}
|
|
146
181
|
|
|
147
|
-
export { MdgError, OPERATOR_NAMES, SPEC_VERSION,
|
|
182
|
+
export { MdgError, OPERATOR_NAMES, SPEC_VERSION, formatPhone, isValidPhone, parsePhone, safeParsePhone, tryParsePhone };
|
|
148
183
|
//# sourceMappingURL=index.js.map
|
|
149
184
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/generated/data.ts","../src/generated/errors.ts","../src/result.ts","../src/read-national-number.ts","../src/phone-number.ts","../src/format.ts"],"names":[],"mappings":";AAKO,IAAM,YAAA,GAAe,KAAA;AAGrB,IAAM,oBAAA,GAAuB,IAAA;AAG7B,IAAM,YAAA,GAAe,GAAA;AAGrB,IAAM,sBAAA,GAAyB,CAAA;AAG/B,IAAM,QAAA,GAAW,CAAC,CAAA,EAAG,CAAA,EAAG,GAAG,CAAC,CAAA;AAa5B,IAAM,cAAA,GAAiB;AAAA,EAC5B,MAAA,EAAQ,mBAAA;AAAA,EACR,MAAA,EAAQ,mBAAA;AAAA,EACR,GAAA,EAAK,gBAAA;AAAA,EACL,QAAA,EAAU;AACZ;AAGO,IAAM,kBAAA,uBAA0D,GAAA,CAAwB;AAAA,EAC7F,CAAC,MAAM,QAAQ,CAAA;AAAA,EACf,CAAC,MAAM,QAAQ,CAAA;AAAA,EACf,CAAC,MAAM,KAAK,CAAA;AAAA,EACZ,CAAC,MAAM,QAAQ,CAAA;AAAA,EACf,CAAC,MAAM,QAAQ,CAAA;AAAA,EACf,CAAC,MAAM,KAAK,CAAA;AAAA,EACZ,CAAC,MAAM,UAAU;AACnB,CAAC,CAAA;AAGM,IAAM,sBAAA,GAAyB,CAAA;;;AC9C/B,IAAM,YAAA,GAAe;AAwCrB,IAAM,QAAA,GAAN,cAAuB,KAAA,CAAM;AAAA;AAAA,EAEhB,IAAA,GAAO,UAAA;AAAA;AAAA,EAEhB,IAAA;AAAA;AAAA;AA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YAAY,CAAA,EAAG,WAAA,CAAY,cAAc,CAAC,CAAA;AAC7E,CAAA;AAEA,SAAS,oBAAoB,KAAA,EAA4C;AACvE,EAAA,OAAO,oBAAA,CAAqB,IAAA,CAAK,CAAC,MAAA,KAAW,WAAW,KAAK,CAAA;AAC/D;AAiBO,SAAS,iBAAA,CAAkB,OAAe,MAAA,EAAmC;AAClF,EAAA,IAAI,CAAC,mBAAA,CAAoB,MAAM,CAAA,EAAG;AAChC,IAAA,MAAM,IAAI,QAAA;AAAA,MACR,cAAA;AAAA,MACA,CAAA,uBAAA,EAA0B,oBAAA,CAAqB,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AAAA,KAC3D;AAAA,EACF;AACA,EAAA,OAAO,WAAW,MAAM,CAAA,CAAE,gBAAA,CAAiB,KAAK,EAAE,cAAc,CAAA;AAClE","file":"index.js","sourcesContent":["// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n// From spec/modules/phone/data.yaml, spec 0.7.0.\n\n/** @internal */\nexport const COUNTRY_CODE = '261' as const;\n\n/** @internal */\nexport const INTERNATIONAL_PREFIX = '00' as const;\n\n/** @internal */\nexport const TRUNK_PREFIX = '0' as const;\n\n/** @internal */\nexport const NATIONAL_NUMBER_LENGTH = 9 as const;\n\n/** @internal Digit group sizes of the national number. */\nexport const GROUPING = [2, 2, 3, 2] as const;\n\n/** Identifier of a Malagasy mobile operator. */\nexport type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline';\n\n/**\n * Display name of each mobile operator, by {@link OperatorId}.\n *\n * @example\n * ```ts\n * OPERATOR_NAMES[parsePhoneNumber('034 12 345 67').operator]; // 'Yas Madagascar'\n * ```\n */\nexport const OPERATOR_NAMES = {\n orange: 'Orange Madagascar',\n airtel: 'Airtel Madagascar',\n yas: 'Yas Madagascar',\n blueline: 'Blueline',\n} as const;\n\n/** @internal Two-digit operator code → operator. */\nexport const OPERATOR_BY_PREFIX: ReadonlyMap<string, OperatorId> = new Map<string, OperatorId>([\n ['32', 'orange'],\n ['33', 'airtel'],\n ['34', 'yas'],\n ['35', 'airtel'],\n ['37', 'orange'],\n ['38', 'yas'],\n ['39', 'blueline'],\n]);\n\n/** @internal */\nexport const OPERATOR_PREFIX_LENGTH = 2 as const;\n","// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n/** Version of the shared spec this code was generated from. */\nexport const SPEC_VERSION = '0.7.0';\n\n/**\n * Error code shared by every mdg-utils language port.\n *\n * - `INVALID_TYPE`: The input is not of the accepted type (for example a string or a non-integer where an integer is expected).\n * - `OUT_OF_RANGE`: The input has the right type but lies outside the supported range.\n * - `INVALID_FORMAT`: The input text cannot be read as a value of this module (wrong characters or wrong length).\n * - `UNKNOWN_OPERATOR`: The phone number is well formed but its operator code is not assigned to a mobile operator.\n */\nexport type ErrorCode = 'INVALID_TYPE' | 'OUT_OF_RANGE' | 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR';\n\n/**\n * Outcome of a `safeParse…` function: the value, or the error that would have been thrown.\n *\n * @example\n * ```ts\n * const result = safeParsePhoneNumber(input);\n * if (result.success) console.log(result.data);\n * else console.log(result.error.code);\n * ```\n */\nexport type SafeParseResult<T> =\n | { readonly success: true; readonly data: T }\n | { readonly success: false; readonly error: MdgError };\n\n/**\n * Error thrown by mdg-utils functions. Check `code`, which is the same in every language.\n *\n * @example\n * ```ts\n * try {\n * numberToWords(-1);\n * } catch (error) {\n * if (error instanceof MdgError && error.code === 'OUT_OF_RANGE') {\n * // handle it\n * }\n * }\n * ```\n */\nexport class MdgError extends Error {\n /** Always `'MdgError'`. */\n override readonly name = 'MdgError';\n /** Why the call failed; the same code in every language. */\n readonly code: ErrorCode;\n\n /**\n * Creates an error with a shared spec code.\n *\n * @param code - Shared spec error code.\n * @param message - Human-readable explanation, in English.\n */\n constructor(code: ErrorCode, message: string) {\n super(message);\n this.code = code;\n }\n\n /**\n * Makes `instanceof MdgError` true for errors from any mdg-utils package or build.\n *\n * @remarks Each package, and its ESM and CommonJS builds, has its own copy of this class,\n * so the check looks at the error's shape instead of its prototype chain.\n *\n * @param value - Any value, usually a caught error.\n * @returns `true` when `value` is an mdg-utils error.\n */\n static override [Symbol.hasInstance](value: unknown): boolean {\n return value instanceof Error && value.name === 'MdgError' && 'code' in value;\n }\n}\n","import { MdgError, type ErrorCode, type SafeParseResult } from './generated/errors.ts';\n\n/**\n * A rejected parse carrying its spec error code.\n *\n * @param code - The spec error code.\n * @param message - What was wrong with the input.\n * @returns `{ success: false, error }`.\n *\n * @example\n * ```ts\n * failure('INVALID_FORMAT', 'Expected a number.'); // { success: false, error: MdgError }\n * ```\n */\nexport function failure(code: ErrorCode, message: string): SafeParseResult<never> {\n return { success: false, error: new MdgError(code, message) };\n}\n","// Reads a number typed in any common way into its 9-digit national significant number.\nimport {\n COUNTRY_CODE,\n INTERNATIONAL_PREFIX,\n NATIONAL_NUMBER_LENGTH,\n TRUNK_PREFIX,\n} from './generated/data.ts';\nimport type { SafeParseResult } from './generated/errors.ts';\nimport { failure } from './result.ts';\n\n// Bounded so a parser that reads user input never scans unbounded text.\nconst MAX_INPUT_LENGTH = 32;\nconst SEPARATORS = /[\\s().-]/g;\n// A national significant number never starts with the trunk prefix 0 (ITU-T E.164).\nconst NATIONAL_NUMBER_DIGITS = /^[1-9]\\d*$/;\nconst NATIONAL_PREFIXES = [\n `+${COUNTRY_CODE}`,\n `${INTERNATIONAL_PREFIX}${COUNTRY_CODE}`,\n COUNTRY_CODE,\n TRUNK_PREFIX,\n '',\n] as const;\n\nfunction stripNationalPrefix(compact: string): string | undefined {\n const prefix = NATIONAL_PREFIXES.find(\n (candidate) =>\n compact.startsWith(candidate) && compact.length === candidate.length + NATIONAL_NUMBER_LENGTH,\n );\n return prefix === undefined ? undefined : compact.slice(prefix.length);\n}\n\n/**\n * Strips separators and the `+261`, `00261`, `261` or `0` prefix, keeping the 9 digits.\n *\n * @param input - The number as typed by a user.\n * @returns The national significant number, or `INVALID_FORMAT`.\n *\n * @example\n * ```ts\n * readNationalNumber('+261 34 12 345 67'); // { success: true, data: '341234567' }\n * ```\n */\nexport function readNationalNumber(input: string): SafeParseResult<string> {\n if (input.length > MAX_INPUT_LENGTH) {\n return failure(\n 'INVALID_FORMAT',\n `Phone numbers are at most ${String(MAX_INPUT_LENGTH)} characters.`,\n );\n }\n const nationalNumber = stripNationalPrefix(input.replace(SEPARATORS, ''));\n if (nationalNumber === undefined || !NATIONAL_NUMBER_DIGITS.test(nationalNumber)) {\n return failure('INVALID_FORMAT', 'Expected a Malagasy number such as 034 12 345 67.');\n }\n return { success: true, data: nationalNumber };\n}\n","import {\n COUNTRY_CODE,\n OPERATOR_BY_PREFIX,\n OPERATOR_PREFIX_LENGTH,\n type OperatorId,\n} from './generated/data.ts';\nimport type { SafeParseResult } from './generated/errors.ts';\nimport { readNationalNumber } from './read-national-number.ts';\nimport { failure } from './result.ts';\n\ndeclare const phoneNumberBrand: unique symbol;\n\n/**\n * A Malagasy mobile number that passed validation. Create it with {@link parsePhoneNumber}.\n *\n * @example\n * ```ts\n * const phone: PhoneNumber = parsePhoneNumber('034 12 345 67');\n * phone.e164; // '+261341234567'\n * ```\n */\nexport interface PhoneNumber {\n /** The number in E.164 form, for storage and APIs: `+261341234567`. */\n readonly e164: string;\n /** The 9 digits after the country code: `341234567`. */\n readonly nationalNumber: string;\n /** The operator that holds the number's prefix. */\n readonly operator: OperatorId;\n /** Marks values that went through validation; it does not exist at runtime. */\n readonly [phoneNumberBrand]: true;\n}\n\n/**\n * Reads a Malagasy mobile number without throwing.\n *\n * @param input - The number as typed by a user, in any accepted spelling.\n * @returns `{ success: true, data }` with the {@link PhoneNumber}, or `{ success: false, error }`.\n *\n * @example\n * ```ts\n * const result = safeParsePhoneNumber('+261 34 12 345 67');\n * if (result.success) result.data.operator; // 'yas'\n * ```\n */\nexport function safeParsePhoneNumber(input: unknown): SafeParseResult<PhoneNumber> {\n if (typeof input !== 'string') return failure('INVALID_TYPE', 'Expected the number as a string.');\n const national = readNationalNumber(input);\n if (!national.success) return national;\n const operator = OPERATOR_BY_PREFIX.get(national.data.slice(0, OPERATOR_PREFIX_LENGTH));\n if (operator === undefined) {\n return failure('UNKNOWN_OPERATOR', 'The prefix is not assigned to a Malagasy mobile operator.');\n }\n const phone = {\n e164: `+${COUNTRY_CODE}${national.data}`,\n nationalNumber: national.data,\n operator,\n };\n return { success: true, data: phone as PhoneNumber };\n}\n\n/**\n * Reads a Malagasy mobile number written in any common way.\n *\n * Accepts `034 12 345 67`, `+261 34 12 345 67`, `00261…`, `261…` and `34 12 345 67`;\n * spaces, dashes, dots and parentheses are ignored.\n *\n * @param input - The number as typed by a user.\n * @returns The validated {@link PhoneNumber}.\n * @throws {@link MdgError} `INVALID_TYPE` for non-strings, `INVALID_FORMAT` for text that is\n * not a Malagasy number, `UNKNOWN_OPERATOR` for an unassigned mobile prefix.\n *\n * @example\n * ```ts\n * parsePhoneNumber('034 12 345 67');\n * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }\n * ```\n */\nexport function parsePhoneNumber(input: string): PhoneNumber {\n const result = safeParsePhoneNumber(input);\n if (!result.success) throw result.error;\n return result.data;\n}\n\n/**\n * Reads a Malagasy mobile number, or gives `undefined` instead of throwing.\n *\n * Use {@link safeParsePhoneNumber} when you need to know why the input was rejected.\n *\n * @param input - The number as typed by a user, in any accepted spelling.\n * @returns The {@link PhoneNumber}, or `undefined` when {@link parsePhoneNumber} would throw.\n *\n * @example\n * ```ts\n * tryParsePhoneNumber('034 12 345 67')?.operator; // 'yas'\n * tryParsePhoneNumber('031 12 345 67'); // undefined\n * ```\n */\nexport function tryParsePhoneNumber(input: unknown): PhoneNumber | undefined {\n const result = safeParsePhoneNumber(input);\n return result.success ? result.data : undefined;\n}\n\n/**\n * Tells whether the input is a valid Malagasy mobile number. Never throws.\n *\n * @param input - Any value.\n * @returns `true` when {@link parsePhoneNumber} would succeed.\n *\n * @example\n * ```ts\n * isValidPhoneNumber('034 12 345 67'); // true\n * isValidPhoneNumber('031 12 345 67'); // false\n * ```\n */\nexport function isValidPhoneNumber(input: unknown): boolean {\n return safeParsePhoneNumber(input).success;\n}\n","import { COUNTRY_CODE, GROUPING, TRUNK_PREFIX } from './generated/data.ts';\nimport { MdgError } from './generated/errors.ts';\nimport { parsePhoneNumber } from './phone-number.ts';\n\n/**\n * How {@link formatPhoneNumber} writes a number.\n *\n * - `e164`: `+261341234567`\n * - `international`: `+261 34 12 345 67`\n * - `national`: `034 12 345 67`\n *\n * @example\n * ```ts\n * const format: PhoneNumberFormat = 'national';\n * ```\n */\nexport type PhoneNumberFormat = 'e164' | 'international' | 'national';\n\nconst PHONE_NUMBER_FORMATS: readonly PhoneNumberFormat[] = ['e164', 'international', 'national'];\n\nconst GROUP_BOUNDS = GROUPING.reduce<readonly (readonly [number, number])[]>((bounds, size) => {\n const start = bounds.at(-1)?.[1] ?? 0;\n return [...bounds, [start, start + size]];\n}, []);\n\nfunction groupDigits(nationalNumber: string): string {\n return GROUP_BOUNDS.map(([start, end]) => nationalNumber.slice(start, end)).join(' ');\n}\n\nconst FORMATTERS: Readonly<Record<PhoneNumberFormat, (nationalNumber: string) => string>> = {\n e164: (nationalNumber) => `+${COUNTRY_CODE}${nationalNumber}`,\n international: (nationalNumber) => `+${COUNTRY_CODE} ${groupDigits(nationalNumber)}`,\n national: (nationalNumber) => `${TRUNK_PREFIX}${groupDigits(nationalNumber)}`,\n};\n\nfunction isPhoneNumberFormat(value: unknown): value is PhoneNumberFormat {\n return PHONE_NUMBER_FORMATS.some((format) => format === value);\n}\n\n/**\n * Writes a Malagasy mobile number in a standard form.\n *\n * @param input - The number in any spelling accepted by {@link parsePhoneNumber}.\n * @param format - `'e164'`, `'international'` or `'national'`.\n * @returns The formatted number.\n * @throws {@link MdgError} `INVALID_TYPE` for an unknown format, plus every error of\n * {@link parsePhoneNumber}.\n *\n * @example\n * ```ts\n * formatPhoneNumber('+261341234567', 'national'); // '034 12 345 67'\n * formatPhoneNumber('034 12 345 67', 'international'); // '+261 34 12 345 67'\n * ```\n */\nexport function formatPhoneNumber(input: string, format: PhoneNumberFormat): string {\n if (!isPhoneNumberFormat(format)) {\n throw new MdgError(\n 'INVALID_TYPE',\n `Format must be one of: ${PHONE_NUMBER_FORMATS.join(', ')}.`,\n );\n }\n return FORMATTERS[format](parsePhoneNumber(input).nationalNumber);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/generated/data.ts","../src/generated/errors.ts","../src/result.ts","../src/read-national-number.ts","../src/phone-number.ts","../src/format.ts"],"names":[],"mappings":";AAKO,IAAM,YAAA,GAAe,KAAA;AAGrB,IAAM,oBAAA,GAAuB,IAAA;AAG7B,IAAM,YAAA,GAAe,GAAA;AAGrB,IAAM,sBAAA,GAAyB,CAAA;AAG/B,IAAM,QAAA,GAAW,CAAC,CAAA,EAAG,CAAA,EAAG,GAAG,CAAC,CAAA;AAa5B,IAAM,cAAA,GAAiB;AAAA,EAC5B,MAAA,EAAQ,mBAAA;AAAA,EACR,MAAA,EAAQ,mBAAA;AAAA,EACR,GAAA,EAAK,gBAAA;AAAA,EACL,QAAA,EAAU,UAAA;AAAA,EACV,OAAA,EAAS;AACX;AAGO,IAAM,kBAAA,uBAGL,GAAA,CAAkF;AAAA,EACxF,CAAC,IAAA,EAAM,EAAE,UAAU,KAAA,EAAO,IAAA,EAAM,SAAS,CAAA;AAAA,EACzC,CAAC,IAAA,EAAM,EAAE,UAAU,SAAA,EAAW,IAAA,EAAM,SAAS,CAAA;AAAA,EAC7C,CAAC,IAAA,EAAM,EAAE,UAAU,QAAA,EAAU,IAAA,EAAM,UAAU,CAAA;AAAA,EAC7C,CAAC,IAAA,EAAM,EAAE,UAAU,QAAA,EAAU,IAAA,EAAM,UAAU,CAAA;AAAA,EAC7C,CAAC,IAAA,EAAM,EAAE,UAAU,KAAA,EAAO,IAAA,EAAM,UAAU,CAAA;AAAA,EAC1C,CAAC,IAAA,EAAM,EAAE,UAAU,QAAA,EAAU,IAAA,EAAM,UAAU,CAAA;AAAA,EAC7C,C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CAAC,CAAC,OAAO,GAAG,CAAA,KAAM,cAAA,CAAe,KAAA,CAAM,KAAA,EAAO,GAAG,CAAC,CAAA,CAAE,KAAK,GAAG,CAAA;AACtF;AAEA,IAAM,UAAA,GAAsF;AAAA,EAC1F,MAAM,CAAC,cAAA,KAAmB,CAAA,CAAA,EAAI,YAAY,GAAG,cAAc,CAAA,CAAA;AAAA,EAC3D,aAAA,EAAe,CAAC,cAAA,KAAmB,CAAA,CAAA,EAAI,YAAY,CAAA,CAAA,EAAI,WAAA,CAAY,cAAc,CAAC,CAAA,CAAA;AAAA,EAClF,QAAA,EAAU,CAAC,cAAA,KAAmB,CAAA,EAAG,YAAY,CAAA,EAAG,WAAA,CAAY,cAAc,CAAC,CAAA;AAC7E,CAAA;AAEA,SAAS,oBAAoB,KAAA,EAA4C;AACvE,EAAA,OAAO,oBAAA,CAAqB,IAAA,CAAK,CAAC,MAAA,KAAW,WAAW,KAAK,CAAA;AAC/D;AAiBO,SAAS,WAAA,CAAY,OAAe,MAAA,EAAmC;AAC5E,EAAA,IAAI,CAAC,mBAAA,CAAoB,MAAM,CAAA,EAAG;AAChC,IAAA,MAAM,IAAI,QAAA;AAAA,MACR,cAAA;AAAA,MACA,CAAA,uBAAA,EAA0B,oBAAA,CAAqB,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AAAA,KAC3D;AAAA,EACF;AACA,EAAA,OAAO,WAAW,MAAM,CAAA,CAAE,UAAA,CAAW,KAAK,EAAE,cAAc,CAAA;AAC5D","file":"index.js","sourcesContent":["// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n// From spec/modules/phone/data.yaml, spec 0.9.0.\n\n/** @internal */\nexport const COUNTRY_CODE = '261' as const;\n\n/** @internal */\nexport const INTERNATIONAL_PREFIX = '00' as const;\n\n/** @internal */\nexport const TRUNK_PREFIX = '0' as const;\n\n/** @internal */\nexport const NATIONAL_NUMBER_LENGTH = 9 as const;\n\n/** @internal Digit group sizes of the national number. */\nexport const GROUPING = [2, 2, 3, 2] as const;\n\n/** Identifier of a Malagasy telephone operator. */\nexport type OperatorId = 'orange' | 'airtel' | 'yas' | 'blueline' | 'gulfsat';\n\n/**\n * Display name of each operator, by {@link OperatorId}.\n *\n * @example\n * ```ts\n * OPERATOR_NAMES[parsePhone('034 12 345 67').operator]; // 'Yas Madagascar'\n * ```\n */\nexport const OPERATOR_NAMES = {\n orange: 'Orange Madagascar',\n airtel: 'Airtel Madagascar',\n yas: 'Yas Madagascar',\n blueline: 'Blueline',\n gulfsat: 'Gulfsat Madagascar',\n} as const;\n\n/** @internal Two-digit operator code → operator and line type. */\nexport const OPERATOR_BY_PREFIX: ReadonlyMap<\n string,\n { readonly operator: OperatorId; readonly type: 'mobile' | 'fixed' }\n> = new Map<string, { readonly operator: OperatorId; readonly type: 'mobile' | 'fixed' }>([\n ['20', { operator: 'yas', type: 'fixed' }],\n ['22', { operator: 'gulfsat', type: 'fixed' }],\n ['32', { operator: 'orange', type: 'mobile' }],\n ['33', { operator: 'airtel', type: 'mobile' }],\n ['34', { operator: 'yas', type: 'mobile' }],\n ['35', { operator: 'airtel', type: 'mobile' }],\n ['36', { operator: 'yas', type: 'mobile' }],\n ['37', { operator: 'orange', type: 'mobile' }],\n ['38', { operator: 'yas', type: 'mobile' }],\n ['39', { operator: 'blueline', type: 'mobile' }],\n]);\n\n/** @internal */\nexport const OPERATOR_PREFIX_LENGTH = 2 as const;\n\n/** @internal Operator code whose next digit is a zone. */\nexport const FIXED_ZONE_PREFIX = '20' as const;\n\n/** @internal Assigned zone digits after it. */\nexport const FIXED_ZONE_DIGITS = ['2', '4', '5', '6', '7', '8', '9'] as const;\n\n/** @internal Geographic numbers, longest prefix first. */\nexport const AREAS = [\n { prefix: '20722', name: 'Manakara', province: 'Fianarantsoa' },\n { prefix: '20729', name: 'Mananjary', province: 'Fianarantsoa' },\n { prefix: '2053', name: 'Toamasina', province: 'Toamasina' },\n { prefix: '2054', name: 'Ambatondrazaka', province: 'Toamasina' },\n { prefix: '2056', name: 'Moramanga', province: 'Toamasina' },\n { prefix: '2057', name: 'Sainte-Marie', province: 'Toamasina' },\n { prefix: '2062', name: 'Mahajanga', province: 'Mahajanga' },\n { prefix: '2067', name: 'Antsohihy', province: 'Mahajanga' },\n { prefix: '2069', name: 'Maintirano', province: 'Mahajanga' },\n { prefix: '2073', name: 'Farafangana', province: 'Fianarantsoa' },\n { prefix: '2075', name: 'Fianarantsoa', province: 'Fianarantsoa' },\n { prefix: '2082', name: 'Antsiranana', province: 'Antsiranana' },\n { prefix: '2086', name: 'Nosy Be', province: 'Antsiranana' },\n { prefix: '2088', name: 'Sambava', province: 'Antsiranana' },\n { prefix: '2092', name: 'Tolagnaro', province: 'Toliary' },\n { prefix: '2094', name: 'Toliary', province: 'Toliary' },\n { prefix: '2095', name: 'Morondava', province: 'Toliary' },\n { prefix: '202', name: 'Antananarivo', province: 'Antananarivo' },\n] as const;\n","// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n/** Version of the shared spec this code was generated from. */\nexport const SPEC_VERSION = '0.9.0';\n\n/**\n * Error code shared by every mdg-utils language port.\n *\n * - `INVALID_TYPE`: The input is not of the accepted type (for example a string or a non-integer where an integer is expected).\n * - `OUT_OF_RANGE`: The input has the right type but lies outside the supported range.\n * - `INVALID_FORMAT`: The input text cannot be read as a value of this module (wrong characters or wrong length).\n * - `UNKNOWN_OPERATOR`: The phone number is well formed but its operator code is not assigned to an operator.\n * - `PRECISION_LOSS`: The value is exact in the text but the port's number type cannot hold it exactly; ask for the exact text instead.\n * - `AMBIGUOUS`: The text reads as more than one value, so none is chosen.\n */\nexport type ErrorCode =\n | 'INVALID_TYPE'\n | 'OUT_OF_RANGE'\n | 'INVALID_FORMAT'\n | 'UNKNOWN_OPERATOR'\n | 'PRECISION_LOSS'\n | 'AMBIGUOUS';\n\n/**\n * Outcome of a `safeParse…` function: the value, or the error that would have been thrown.\n *\n * @example\n * ```ts\n * const result = safeParsePhone(input);\n * if (result.success) console.log(result.data);\n * else console.log(result.error.code);\n * ```\n */\nexport type SafeParseResult<T> =\n | { readonly success: true; readonly data: T }\n | { readonly success: false; readonly error: MdgError };\n\n/**\n * Error thrown by mdg-utils functions. Check `code`, which is the same in every language.\n *\n * @example\n * ```ts\n * try {\n * spell(-1);\n * } catch (error) {\n * if (error instanceof MdgError && error.code === 'OUT_OF_RANGE') {\n * // handle it\n * }\n * }\n * ```\n */\nexport class MdgError extends Error {\n /** Always `'MdgError'`. */\n override readonly name = 'MdgError';\n /** Why the call failed; the same code in every language. */\n readonly code: ErrorCode;\n\n /**\n * Creates an error with a shared spec code.\n *\n * @param code - Shared spec error code.\n * @param message - Human-readable explanation, in English.\n */\n constructor(code: ErrorCode, message: string) {\n super(message);\n this.code = code;\n }\n\n /**\n * Makes `instanceof MdgError` true for errors from any mdg-utils package or build.\n *\n * @remarks Each package, and its ESM and CommonJS builds, has its own copy of this class,\n * so the check looks at the error's shape instead of its prototype chain.\n *\n * @param value - Any value, usually a caught error.\n * @returns `true` when `value` is an mdg-utils error.\n */\n static override [Symbol.hasInstance](value: unknown): boolean {\n return value instanceof Error && value.name === 'MdgError' && 'code' in value;\n }\n}\n","import { MdgError, type ErrorCode, type SafeParseResult } from './generated/errors.ts';\n\n/**\n * A rejected parse carrying its spec error code.\n *\n * @param code - The spec error code.\n * @param message - What was wrong with the input.\n * @returns `{ success: false, error }`.\n *\n * @example\n * ```ts\n * failure('INVALID_FORMAT', 'Expected a number.'); // { success: false, error: MdgError }\n * ```\n */\nexport function failure(code: ErrorCode, message: string): SafeParseResult<never> {\n return { success: false, error: new MdgError(code, message) };\n}\n","// Reads a number typed in any common way into its 9-digit national significant number.\nimport {\n COUNTRY_CODE,\n INTERNATIONAL_PREFIX,\n NATIONAL_NUMBER_LENGTH,\n TRUNK_PREFIX,\n} from './generated/data.ts';\nimport type { SafeParseResult } from './generated/errors.ts';\nimport { failure } from './result.ts';\n\n// Bounded so a parser that reads user input never scans unbounded text.\nconst MAX_INPUT_LENGTH = 32;\nconst SEPARATORS = /[\\s().-]/g;\n// A national significant number never starts with the trunk prefix 0 (ITU-T E.164).\nconst NATIONAL_NUMBER_DIGITS = /^[1-9]\\d*$/;\nconst NATIONAL_PREFIXES = [\n `+${COUNTRY_CODE}`,\n `${INTERNATIONAL_PREFIX}${COUNTRY_CODE}`,\n COUNTRY_CODE,\n TRUNK_PREFIX,\n '',\n] as const;\n\nfunction stripNationalPrefix(compact: string): string | undefined {\n const prefix = NATIONAL_PREFIXES.find(\n (candidate) =>\n compact.startsWith(candidate) && compact.length === candidate.length + NATIONAL_NUMBER_LENGTH,\n );\n return prefix === undefined ? undefined : compact.slice(prefix.length);\n}\n\n/**\n * Strips separators and the `+261`, `00261`, `261` or `0` prefix, keeping the 9 digits.\n *\n * @param input - The number as typed by a user.\n * @returns The national significant number, or `INVALID_FORMAT`.\n *\n * @example\n * ```ts\n * readNationalNumber('+261 34 12 345 67'); // { success: true, data: '341234567' }\n * ```\n */\nexport function readNationalNumber(input: string): SafeParseResult<string> {\n if (input.length > MAX_INPUT_LENGTH) {\n return failure(\n 'INVALID_FORMAT',\n `Phone numbers are at most ${String(MAX_INPUT_LENGTH)} characters.`,\n );\n }\n const nationalNumber = stripNationalPrefix(input.replace(SEPARATORS, ''));\n if (nationalNumber === undefined || !NATIONAL_NUMBER_DIGITS.test(nationalNumber)) {\n return failure('INVALID_FORMAT', 'Expected a Malagasy number such as 034 12 345 67.');\n }\n return { success: true, data: nationalNumber };\n}\n","import {\n AREAS,\n COUNTRY_CODE,\n FIXED_ZONE_DIGITS,\n FIXED_ZONE_PREFIX,\n OPERATOR_BY_PREFIX,\n OPERATOR_PREFIX_LENGTH,\n type OperatorId,\n} from './generated/data.ts';\nimport type { SafeParseResult } from './generated/errors.ts';\nimport { readNationalNumber } from './read-national-number.ts';\nimport { failure } from './result.ts';\n\ndeclare const phoneNumberBrand: unique symbol;\n\n/**\n * What kind of line a number reaches: `mobile` (codes 3x) or `fixed` (codes 2x).\n *\n * @example\n * ```ts\n * const type: PhoneLineType = 'fixed';\n * ```\n */\nexport type PhoneLineType = 'mobile' | 'fixed';\n\n/**\n * The town of a geographic fixed number, as the national numbering plan lists it.\n *\n * @example\n * ```ts\n * const area: PhoneArea = { name: 'Toamasina', province: 'Toamasina' };\n * ```\n */\nexport interface PhoneArea {\n /** Town, e.g. `Toamasina`. */\n readonly name: string;\n /** Former province, e.g. `Toamasina`. */\n readonly province: string;\n}\n\nconst FIXED_ZONES: ReadonlySet<string> = new Set(FIXED_ZONE_DIGITS);\n\n/**\n * A Malagasy phone number, mobile or fixed, that passed validation. Create it with {@link parsePhone}.\n *\n * @example\n * ```ts\n * const phone: PhoneNumber = parsePhone('034 12 345 67');\n * phone.e164; // '+261341234567'\n * ```\n */\nexport interface PhoneNumber {\n /** The number in E.164 form, for storage and APIs: `+261341234567`. */\n readonly e164: string;\n /** The 9 digits after the country code: `341234567`. */\n readonly nationalNumber: string;\n /** The operator that holds the number's prefix. */\n readonly operator: OperatorId;\n /** `mobile` or `fixed`. */\n readonly type: PhoneLineType;\n /** The town of a geographic fixed number, or `null` (mobile, VSAT, or an unlisted town). */\n readonly area: PhoneArea | null;\n /** Marks values that went through validation; it does not exist at runtime. */\n readonly [phoneNumberBrand]: true;\n}\n\nfunction areaOf(nationalNumber: string): PhoneArea | null {\n const area = AREAS.find((entry) => nationalNumber.startsWith(entry.prefix));\n return area === undefined ? null : { name: area.name, province: area.province };\n}\n\n/**\n * Reads a Malagasy phone number, mobile or fixed, without throwing.\n *\n * @param input - The number as typed by a user, in any accepted spelling.\n * @returns `{ success: true, data }` with the {@link PhoneNumber}, or `{ success: false, error }`.\n *\n * @example\n * ```ts\n * const result = safeParsePhone('+261 34 12 345 67');\n * if (result.success) result.data.operator; // 'yas'\n * ```\n */\nexport function safeParsePhone(input: unknown): SafeParseResult<PhoneNumber> {\n if (typeof input !== 'string') return failure('INVALID_TYPE', 'Expected the number as a string.');\n const national = readNationalNumber(input);\n if (!national.success) return national;\n const prefix = national.data.slice(0, OPERATOR_PREFIX_LENGTH);\n const holder = OPERATOR_BY_PREFIX.get(prefix);\n const zone = national.data.charAt(OPERATOR_PREFIX_LENGTH);\n if (holder === undefined || (prefix === FIXED_ZONE_PREFIX && !FIXED_ZONES.has(zone))) {\n return failure('UNKNOWN_OPERATOR', 'The prefix is not assigned to a Malagasy operator.');\n }\n const phone = {\n e164: `+${COUNTRY_CODE}${national.data}`,\n nationalNumber: national.data,\n operator: holder.operator,\n type: holder.type,\n area: areaOf(national.data),\n };\n return { success: true, data: phone as PhoneNumber };\n}\n\n/**\n * Reads a Malagasy phone number, mobile or fixed, written in any common way.\n *\n * Accepts `034 12 345 67`, `+261 34 12 345 67`, `00261…`, `261…` and `34 12 345 67`;\n * spaces, dashes, dots and parentheses are ignored.\n *\n * @param input - The number as typed by a user.\n * @returns The validated {@link PhoneNumber}.\n * @throws {@link MdgError} `INVALID_TYPE` for non-strings, `INVALID_FORMAT` for text that is\n * not a Malagasy number, `UNKNOWN_OPERATOR` for an unassigned prefix.\n *\n * @example\n * ```ts\n * parsePhone('034 12 345 67');\n * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas', type: 'mobile', area: null }\n * parsePhone('020 53 123 45').area; // { name: 'Toamasina', province: 'Toamasina' }\n * ```\n */\nexport function parsePhone(input: string): PhoneNumber {\n const result = safeParsePhone(input);\n if (!result.success) throw result.error;\n return result.data;\n}\n\n/**\n * Reads a Malagasy phone number, or gives `undefined` instead of throwing.\n *\n * Use {@link safeParsePhone} when you need to know why the input was rejected.\n *\n * @param input - The number as typed by a user, in any accepted spelling.\n * @returns The {@link PhoneNumber}, or `undefined` when {@link parsePhone} would throw.\n *\n * @example\n * ```ts\n * tryParsePhone('034 12 345 67')?.operator; // 'yas'\n * tryParsePhone('031 12 345 67'); // undefined\n * ```\n */\nexport function tryParsePhone(input: unknown): PhoneNumber | undefined {\n const result = safeParsePhone(input);\n return result.success ? result.data : undefined;\n}\n\n/**\n * Tells whether the input is a valid Malagasy phone number, mobile or fixed. Never throws.\n *\n * @param input - Any value.\n * @returns `true` when {@link parsePhone} would succeed.\n *\n * @example\n * ```ts\n * isValidPhone('034 12 345 67'); // true\n * isValidPhone('031 12 345 67'); // false\n * ```\n */\nexport function isValidPhone(input: unknown): boolean {\n return safeParsePhone(input).success;\n}\n","import { COUNTRY_CODE, GROUPING, TRUNK_PREFIX } from './generated/data.ts';\nimport { MdgError } from './generated/errors.ts';\nimport { parsePhone } from './phone-number.ts';\n\n/**\n * How {@link formatPhone} writes a number.\n *\n * - `e164`: `+261341234567`\n * - `international`: `+261 34 12 345 67`\n * - `national`: `034 12 345 67`\n *\n * @example\n * ```ts\n * const format: PhoneNumberFormat = 'national';\n * ```\n */\nexport type PhoneNumberFormat = 'e164' | 'international' | 'national';\n\nconst PHONE_NUMBER_FORMATS: readonly PhoneNumberFormat[] = ['e164', 'international', 'national'];\n\nconst GROUP_BOUNDS = GROUPING.reduce<readonly (readonly [number, number])[]>((bounds, size) => {\n const start = bounds.at(-1)?.[1] ?? 0;\n return [...bounds, [start, start + size]];\n}, []);\n\nfunction groupDigits(nationalNumber: string): string {\n return GROUP_BOUNDS.map(([start, end]) => nationalNumber.slice(start, end)).join(' ');\n}\n\nconst FORMATTERS: Readonly<Record<PhoneNumberFormat, (nationalNumber: string) => string>> = {\n e164: (nationalNumber) => `+${COUNTRY_CODE}${nationalNumber}`,\n international: (nationalNumber) => `+${COUNTRY_CODE} ${groupDigits(nationalNumber)}`,\n national: (nationalNumber) => `${TRUNK_PREFIX}${groupDigits(nationalNumber)}`,\n};\n\nfunction isPhoneNumberFormat(value: unknown): value is PhoneNumberFormat {\n return PHONE_NUMBER_FORMATS.some((format) => format === value);\n}\n\n/**\n * Writes a Malagasy mobile number in a standard form.\n *\n * @param input - The number in any spelling accepted by {@link parsePhone}.\n * @param format - `'e164'`, `'international'` or `'national'`.\n * @returns The formatted number.\n * @throws {@link MdgError} `INVALID_TYPE` for an unknown format, plus every error of\n * {@link parsePhone}.\n *\n * @example\n * ```ts\n * formatPhone('+261341234567', 'national'); // '034 12 345 67'\n * formatPhone('034 12 345 67', 'international'); // '+261 34 12 345 67'\n * ```\n */\nexport function formatPhone(input: string, format: PhoneNumberFormat): string {\n if (!isPhoneNumberFormat(format)) {\n throw new MdgError(\n 'INVALID_TYPE',\n `Format must be one of: ${PHONE_NUMBER_FORMATS.join(', ')}.`,\n );\n }\n return FORMATTERS[format](parsePhone(input).nationalNumber);\n}\n"]}
|