@mdgascar/phone 0.9.0 → 0.11.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 CHANGED
@@ -1,9 +1,9 @@
1
1
  # @mdgascar/phone
2
2
 
3
- Parse, validate and format Madagascar (+261) mobile phone numbers. Zero dependencies,
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.8.0.
6
+ Implements spec 0.10.0.
7
7
 
8
8
  ```sh
9
9
  npm install @mdgascar/phone
@@ -20,7 +20,8 @@ import {
20
20
  } from '@mdgascar/phone';
21
21
 
22
22
  parsePhone('034 12 345 67');
23
- // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }
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
  formatPhone('+261341234567', 'national'); // '034 12 345 67'
26
27
  isValidPhone('031 12 345 67'); // false
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
- ["32", "orange"],
17
- ["33", "airtel"],
18
- ["34", "yas"],
19
- ["35", "airtel"],
20
- ["37", "orange"],
21
- ["38", "yas"],
22
- ["39", "blueline"]
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.8.0";
53
+ var SPEC_VERSION = "0.10.0";
28
54
  var MdgError = class extends Error {
29
55
  /** Always `'MdgError'`. */
30
56
  name = "MdgError";
@@ -91,18 +117,27 @@ function readNationalNumber(input) {
91
117
  }
92
118
 
93
119
  // src/phone-number.ts
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
+ }
94
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 operator = OPERATOR_BY_PREFIX.get(national.data.slice(0, OPERATOR_PREFIX_LENGTH));
99
- if (operator === void 0) {
100
- return failure("UNKNOWN_OPERATOR", "The prefix is not assigned to a Malagasy mobile operator.");
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
  }
@@ -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;AA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C,KAAA,EAAO,KAAA,GAAQ,IAAI,CAAC,CAAA;AAC1C,CAAA,EAAG,EAAE,CAAA;AAEL,SAAS,YAAY,cAAA,EAAgC;AACnD,EAAA,OAAO,YAAA,CAAa,GAAA,CAAI,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.cjs","sourcesContent":["// GENERATED — edit spec/ instead. Run `just codegen` to refresh.\n\n// From spec/modules/phone/data.yaml, spec 0.8.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[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} 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.8.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 = 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 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 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 /** 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 = 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 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 * parsePhone('034 12 345 67');\n * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }\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 mobile 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 mobile number. 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"]}
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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AA,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.10.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.10.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
@@ -28,10 +28,10 @@ type PhoneNumberFormat = 'e164' | 'international' | 'national';
28
28
  */
29
29
  declare function formatPhone(input: string, format: PhoneNumberFormat): string;
30
30
 
31
- /** Identifier of a Malagasy mobile operator. */
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 mobile operator, by {@link OperatorId}.
34
+ * Display name of each operator, by {@link OperatorId}.
35
35
  *
36
36
  * @example
37
37
  * ```ts
@@ -43,19 +43,22 @@ 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.8.0";
50
+ declare const SPEC_VERSION = "0.10.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 a mobile operator.
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
  *
@@ -113,7 +116,30 @@ declare class MdgError extends Error {
113
116
 
114
117
  declare const phoneNumberBrand: unique symbol;
115
118
  /**
116
- * A Malagasy mobile number that passed validation. Create it with {@link parsePhone}.
119
+ * What kind of line a number reaches: `mobile` (codes 3x) or `fixed` (codes 2x).
120
+ *
121
+ * @example
122
+ * ```ts
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}.
117
143
  *
118
144
  * @example
119
145
  * ```ts
@@ -128,11 +154,15 @@ 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 mobile number without throwing.
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 }`.
@@ -145,7 +175,7 @@ interface PhoneNumber {
145
175
  */
146
176
  declare function safeParsePhone(input: unknown): SafeParseResult<PhoneNumber>;
147
177
  /**
148
- * Reads a Malagasy mobile number written in any common way.
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,17 +183,18 @@ declare function safeParsePhone(input: unknown): SafeParseResult<PhoneNumber>;
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 mobile prefix.
186
+ * not a Malagasy number, `UNKNOWN_OPERATOR` for an unassigned prefix.
157
187
  *
158
188
  * @example
159
189
  * ```ts
160
190
  * parsePhone('034 12 345 67');
161
- * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }
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
195
  declare function parsePhone(input: string): PhoneNumber;
165
196
  /**
166
- * Reads a Malagasy mobile number, or gives `undefined` instead of throwing.
197
+ * Reads a Malagasy phone number, or gives `undefined` instead of throwing.
167
198
  *
168
199
  * Use {@link safeParsePhone} when you need to know why the input was rejected.
169
200
  *
@@ -178,7 +209,7 @@ declare function parsePhone(input: string): PhoneNumber;
178
209
  */
179
210
  declare function tryParsePhone(input: unknown): PhoneNumber | undefined;
180
211
  /**
181
- * Tells whether the input is a valid Malagasy mobile number. Never throws.
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
215
  * @returns `true` when {@link parsePhone} would succeed.
@@ -192,4 +223,4 @@ declare function tryParsePhone(input: unknown): PhoneNumber | undefined;
192
223
  declare function isValidPhone(input: unknown): boolean;
193
224
 
194
225
  export { MdgError, OPERATOR_NAMES, SPEC_VERSION, formatPhone, isValidPhone, parsePhone, safeParsePhone, tryParsePhone };
195
- export type { ErrorCode, OperatorId, PhoneNumber, PhoneNumberFormat, SafeParseResult };
226
+ export type { ErrorCode, OperatorId, PhoneArea, PhoneLineType, PhoneNumber, PhoneNumberFormat, SafeParseResult };
package/dist/index.d.ts CHANGED
@@ -28,10 +28,10 @@ type PhoneNumberFormat = 'e164' | 'international' | 'national';
28
28
  */
29
29
  declare function formatPhone(input: string, format: PhoneNumberFormat): string;
30
30
 
31
- /** Identifier of a Malagasy mobile operator. */
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 mobile operator, by {@link OperatorId}.
34
+ * Display name of each operator, by {@link OperatorId}.
35
35
  *
36
36
  * @example
37
37
  * ```ts
@@ -43,19 +43,22 @@ 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.8.0";
50
+ declare const SPEC_VERSION = "0.10.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 a mobile operator.
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
  *
@@ -113,7 +116,30 @@ declare class MdgError extends Error {
113
116
 
114
117
  declare const phoneNumberBrand: unique symbol;
115
118
  /**
116
- * A Malagasy mobile number that passed validation. Create it with {@link parsePhone}.
119
+ * What kind of line a number reaches: `mobile` (codes 3x) or `fixed` (codes 2x).
120
+ *
121
+ * @example
122
+ * ```ts
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}.
117
143
  *
118
144
  * @example
119
145
  * ```ts
@@ -128,11 +154,15 @@ 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 mobile number without throwing.
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 }`.
@@ -145,7 +175,7 @@ interface PhoneNumber {
145
175
  */
146
176
  declare function safeParsePhone(input: unknown): SafeParseResult<PhoneNumber>;
147
177
  /**
148
- * Reads a Malagasy mobile number written in any common way.
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,17 +183,18 @@ declare function safeParsePhone(input: unknown): SafeParseResult<PhoneNumber>;
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 mobile prefix.
186
+ * not a Malagasy number, `UNKNOWN_OPERATOR` for an unassigned prefix.
157
187
  *
158
188
  * @example
159
189
  * ```ts
160
190
  * parsePhone('034 12 345 67');
161
- * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }
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
195
  declare function parsePhone(input: string): PhoneNumber;
165
196
  /**
166
- * Reads a Malagasy mobile number, or gives `undefined` instead of throwing.
197
+ * Reads a Malagasy phone number, or gives `undefined` instead of throwing.
167
198
  *
168
199
  * Use {@link safeParsePhone} when you need to know why the input was rejected.
169
200
  *
@@ -178,7 +209,7 @@ declare function parsePhone(input: string): PhoneNumber;
178
209
  */
179
210
  declare function tryParsePhone(input: unknown): PhoneNumber | undefined;
180
211
  /**
181
- * Tells whether the input is a valid Malagasy mobile number. Never throws.
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
215
  * @returns `true` when {@link parsePhone} would succeed.
@@ -192,4 +223,4 @@ declare function tryParsePhone(input: unknown): PhoneNumber | undefined;
192
223
  declare function isValidPhone(input: unknown): boolean;
193
224
 
194
225
  export { MdgError, OPERATOR_NAMES, SPEC_VERSION, formatPhone, isValidPhone, parsePhone, safeParsePhone, tryParsePhone };
195
- export type { ErrorCode, OperatorId, PhoneNumber, PhoneNumberFormat, SafeParseResult };
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
- ["32", "orange"],
15
- ["33", "airtel"],
16
- ["34", "yas"],
17
- ["35", "airtel"],
18
- ["37", "orange"],
19
- ["38", "yas"],
20
- ["39", "blueline"]
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.8.0";
51
+ var SPEC_VERSION = "0.10.0";
26
52
  var MdgError = class extends Error {
27
53
  /** Always `'MdgError'`. */
28
54
  name = "MdgError";
@@ -89,18 +115,27 @@ function readNationalNumber(input) {
89
115
  }
90
116
 
91
117
  // src/phone-number.ts
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
+ }
92
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 operator = OPERATOR_BY_PREFIX.get(national.data.slice(0, OPERATOR_PREFIX_LENGTH));
97
- if (operator === void 0) {
98
- return failure("UNKNOWN_OPERATOR", "The prefix is not assigned to a Malagasy mobile operator.");
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
  }
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;AAAA;AAAA;AAAA;AAAA;AAAA,EAQT,WAAA,CAAY,MAAiB,OAAA,EAAiB;AAC5C,IAAA,KAAA,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AA,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.8.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[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} 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.8.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 = 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 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 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 /** 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 = 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 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 * parsePhone('034 12 345 67');\n * // { e164: '+261341234567', nationalNumber: '341234567', operator: 'yas' }\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 mobile 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 mobile number. 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"]}
1
+ {"version":3,"sources":["../src/generated/data.ts","../src/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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.10.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.10.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mdgascar/phone",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "Parse, validate and format Madagascar (+261) mobile phone numbers.",
5
5
  "license": "MIT",
6
6
  "author": "Mdgascar contributors",