asma-core-helpers 0.35.0 → 0.36.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.
@@ -0,0 +1,96 @@
1
+ import assert from 'node:assert/strict'
2
+ import { describe, it } from 'node:test'
3
+
4
+ import {
5
+ DEFAULT_PHONE_COUNTRY,
6
+ findCountryByDialCode,
7
+ getPhoneDialCode,
8
+ listPhoneCountries,
9
+ matchesPhoneCountry,
10
+ } from './phoneCountries.js'
11
+ import type { PhoneCountryOption } from './phoneCountries.js'
12
+
13
+ const norway = (locale: string): PhoneCountryOption | undefined =>
14
+ listPhoneCountries(locale).find((option) => option.iso2 === 'NO')
15
+
16
+ describe('DEFAULT_PHONE_COUNTRY', () => {
17
+ it('pre-selects Norway (ASMA-7485)', () => {
18
+ assert.equal(DEFAULT_PHONE_COUNTRY, 'NO')
19
+ })
20
+ })
21
+
22
+ describe('listPhoneCountries', () => {
23
+ it('covers every supported country with its calling code', () => {
24
+ const options = listPhoneCountries('en')
25
+ assert.equal(options.length, 245)
26
+ assert.deepEqual(norway('en'), { iso2: 'NO', dialCode: '47', name: 'Norway' })
27
+ })
28
+
29
+ it('localizes names per locale instead of shipping a translation table', () => {
30
+ assert.equal(norway('nb')?.name, 'Norge')
31
+ assert.equal(norway('en')?.name, 'Norway')
32
+ })
33
+
34
+ it('sorts by localized name, so the order differs between locales', () => {
35
+ const nb = listPhoneCountries('nb').map((option) => option.name)
36
+ const en = listPhoneCountries('en').map((option) => option.name)
37
+
38
+ assert.deepEqual(nb, [...nb].sort(new Intl.Collator('nb').compare))
39
+ assert.deepEqual(en, [...en].sort(new Intl.Collator('en').compare))
40
+ // Østerrike sorts last in nb, Austria near the front in en.
41
+ assert.notEqual(nb.indexOf('Østerrike'), en.indexOf('Austria'))
42
+ })
43
+
44
+ it('memoizes per locale — the Intl lookup runs once per country', () => {
45
+ assert.equal(listPhoneCountries('en'), listPhoneCountries('en'))
46
+ assert.notEqual(listPhoneCountries('en'), listPhoneCountries('nb'))
47
+ })
48
+ })
49
+
50
+ describe('getPhoneDialCode', () => {
51
+ it('returns the calling code without a plus', () => {
52
+ assert.equal(getPhoneDialCode('NO'), '47')
53
+ assert.equal(getPhoneDialCode('US'), '1')
54
+ })
55
+ })
56
+
57
+ describe('matchesPhoneCountry', () => {
58
+ const option: PhoneCountryOption = { iso2: 'NO', dialCode: '47', name: 'Norway' }
59
+
60
+ it('matches by country name, case-insensitively', () => {
61
+ assert.equal(matchesPhoneCountry(option, 'nor'), true)
62
+ assert.equal(matchesPhoneCountry(option, 'NORWAY'), true)
63
+ assert.equal(matchesPhoneCountry(option, 'sweden'), false)
64
+ })
65
+
66
+ it('matches by calling code, with or without the plus', () => {
67
+ assert.equal(matchesPhoneCountry(option, '47'), true)
68
+ assert.equal(matchesPhoneCountry(option, '+47'), true)
69
+ assert.equal(matchesPhoneCountry(option, '4'), true)
70
+ assert.equal(matchesPhoneCountry(option, '61'), false)
71
+ })
72
+
73
+ it('keeps every row for an empty or whitespace query', () => {
74
+ assert.equal(matchesPhoneCountry(option, ''), true)
75
+ assert.equal(matchesPhoneCountry(option, ' '), true)
76
+ })
77
+ })
78
+
79
+ describe('findCountryByDialCode', () => {
80
+ it('resolves the main country of a shared calling code', () => {
81
+ // 25 countries share +1; a first-match scan would answer Antigua.
82
+ assert.equal(findCountryByDialCode('12015550123'), 'US')
83
+ assert.equal(findCountryByDialCode('79161234567'), 'RU')
84
+ assert.equal(findCountryByDialCode('447400123456'), 'GB')
85
+ })
86
+
87
+ it('prefers the longest matching calling code', () => {
88
+ assert.equal(findCountryByDialCode('4748012345'), 'NO')
89
+ assert.equal(findCountryByDialCode('46701234567'), 'SE')
90
+ })
91
+
92
+ it('returns undefined when no calling code matches', () => {
93
+ assert.equal(findCountryByDialCode('9991234'), undefined)
94
+ assert.equal(findCountryByDialCode(''), undefined)
95
+ })
96
+ })
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Country dial-code catalogue for the ASMA phone field (ASMA-7485).
3
+ *
4
+ * Country names come from the platform's own `Intl.DisplayNames` rather than a
5
+ * checked-in translation table, so every locale the browser knows is covered
6
+ * without shipping (or maintaining) 245 names per language.
7
+ */
8
+
9
+ import { getCountries, getCountryCallingCode, isSupportedCountry, Metadata } from 'libphonenumber-js'
10
+ import type { CountryCode } from 'libphonenumber-js'
11
+
12
+ /** ISO 3166-1 alpha-2 code, narrowed to what the phone metadata actually supports. */
13
+ export type PhoneCountry = CountryCode
14
+
15
+ /** Pre-selected country for every ASMA phone field — see ASMA-7485. */
16
+ export const DEFAULT_PHONE_COUNTRY: PhoneCountry = 'NO'
17
+
18
+ export interface PhoneCountryOption {
19
+ iso2: PhoneCountry
20
+ /** Calling code without the leading `+`, e.g. `'47'`. */
21
+ dialCode: string
22
+ /** Country name in the requested locale, e.g. `'Norge'` / `'Norway'`. */
23
+ name: string
24
+ }
25
+
26
+ const optionsByLocale = new Map<string, readonly PhoneCountryOption[]>()
27
+
28
+ function countryName(iso2: PhoneCountry, displayNames: Intl.DisplayNames): string {
29
+ // `of` returns undefined for codes the ICU data does not know; the code itself
30
+ // is a better fallback than an empty row.
31
+ return displayNames.of(iso2) ?? iso2
32
+ }
33
+
34
+ /**
35
+ * Every supported country, sorted by localized name.
36
+ *
37
+ * Ordering of the *rendered* list (pinning the selected country first) belongs to
38
+ * the UI; this returns the stable alphabetical catalogue. Memoized per locale
39
+ * because the underlying `Intl.DisplayNames` lookup runs once per country.
40
+ */
41
+ export function listPhoneCountries(locale: string): readonly PhoneCountryOption[] {
42
+ const cached = optionsByLocale.get(locale)
43
+ if (cached !== undefined) return cached
44
+
45
+ const displayNames = new Intl.DisplayNames([locale], { type: 'region' })
46
+ const collator = new Intl.Collator(locale)
47
+
48
+ const options = getCountries()
49
+ .map((iso2) => ({
50
+ iso2,
51
+ dialCode: getCountryCallingCode(iso2),
52
+ name: countryName(iso2, displayNames),
53
+ }))
54
+ .sort((left, right) => collator.compare(left.name, right.name))
55
+
56
+ optionsByLocale.set(locale, options)
57
+ return options
58
+ }
59
+
60
+ export function getPhoneDialCode(iso2: PhoneCountry): string {
61
+ return getCountryCallingCode(iso2)
62
+ }
63
+
64
+ /**
65
+ * Search predicate for the country picker: matches on localized name **or** on the
66
+ * calling code, so both `"Norway"` and `"47"` narrow the list to +47 (ASMA-7485).
67
+ *
68
+ * A leading `+` in the query is ignored so pasting `+47` works.
69
+ */
70
+ export function matchesPhoneCountry(option: PhoneCountryOption, query: string): boolean {
71
+ const trimmed = query.trim()
72
+ if (trimmed.length === 0) return true
73
+
74
+ if (option.name.toLocaleLowerCase().includes(trimmed.toLocaleLowerCase())) return true
75
+
76
+ const digits = trimmed.replace(/^\+/, '').replace(/\D/g, '')
77
+ return digits.length > 0 && option.dialCode.startsWith(digits)
78
+ }
79
+
80
+ /** Calling codes are at most three digits in the E.164 plan. */
81
+ const MAX_CALLING_CODE_LENGTH = 3
82
+
83
+ /**
84
+ * `Metadata` exposes the calling-code → countries index at runtime, but the shipped
85
+ * typings declare only `selectNumberingPlan`/`numberingPlan`. Narrowed here against
86
+ * the inspected runtime shape and guarded at the call site, so a future release that
87
+ * drops the method degrades to "country not found" instead of throwing.
88
+ */
89
+ interface CallingCodeIndex {
90
+ getCountryCodesForCallingCode?: (callingCode: string) => readonly string[] | undefined
91
+ }
92
+
93
+ /**
94
+ * The primary country for a calling code — `'1'` → `US`, not whichever NANP
95
+ * territory happens to sort first. The metadata index lists the main country first.
96
+ */
97
+ function mainCountryForCallingCode(callingCode: string): PhoneCountry | undefined {
98
+ const index = new Metadata() as unknown as CallingCodeIndex
99
+ const candidate = index.getCountryCodesForCallingCode?.(callingCode)?.[0]
100
+
101
+ return candidate !== undefined && isSupportedCountry(candidate) ? candidate : undefined
102
+ }
103
+
104
+ /**
105
+ * The country owning the longest calling-code prefix of `digits`.
106
+ *
107
+ * Longest-prefix rather than first-match because calling codes are not prefix-free
108
+ * (`+1` vs `+7`, `+47` vs `+473`), and main-country-wins because 25 countries share
109
+ * `+1` — a plain scan resolves every North-American number to Antigua.
110
+ */
111
+ export function findCountryByDialCode(digits: string): PhoneCountry | undefined {
112
+ for (let length = Math.min(MAX_CALLING_CODE_LENGTH, digits.length); length >= 1; length -= 1) {
113
+ const country = mainCountryForCallingCode(digits.slice(0, length))
114
+ if (country !== undefined) return country
115
+ }
116
+
117
+ return undefined
118
+ }
@@ -0,0 +1,17 @@
1
+ import assert from 'node:assert/strict'
2
+ import { describe, it } from 'node:test'
3
+
4
+ import { phoneExample } from './phoneExample.js'
5
+
6
+ describe('phoneExample', () => {
7
+ it('supplies the actionable half of a validation message (REQ-003)', () => {
8
+ assert.equal(phoneExample('NO'), '+47 40 61 23 45')
9
+ assert.equal(phoneExample('US'), '+1 201 555 0123')
10
+ })
11
+
12
+ it('always yields something to show, even without example metadata', () => {
13
+ for (const iso2 of ['NO', 'US', 'GB', 'SE', 'AX', 'SJ'] as const) {
14
+ assert.match(phoneExample(iso2), /^\+\d/)
15
+ }
16
+ })
17
+ })
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Example numbers for the actionable half of a validation message (ADR-0017 REQ-003:
3
+ * "what's wrong — how to fix"), e.g. `errorWithHint(msgs.invalid_phone, phoneExample('NO'))`
4
+ * → `'Invalid phone — Ex: +47 40 61 23 45'`.
5
+ *
6
+ * Kept in its own module so consumers that only format or validate do not pull the
7
+ * example metadata (~1.4 kB gz) into their bundle.
8
+ */
9
+
10
+ import { getExampleNumber } from 'libphonenumber-js'
11
+ import examples from 'libphonenumber-js/examples.mobile.json'
12
+
13
+ import { getPhoneDialCode } from './phoneCountries.js'
14
+ import type { PhoneCountry } from './phoneCountries.js'
15
+
16
+ /**
17
+ * A representative mobile number for the country, in international form.
18
+ *
19
+ * Falls back to the bare dial code for the handful of territories that have no
20
+ * example in the metadata, so the hint is never an empty string.
21
+ */
22
+ export function phoneExample(iso2: PhoneCountry): string {
23
+ return getExampleNumber(iso2, examples)?.formatInternational() ?? `+${getPhoneDialCode(iso2)}`
24
+ }
@@ -0,0 +1,242 @@
1
+ import assert from 'node:assert/strict'
2
+ import { describe, it } from 'node:test'
3
+
4
+ import {
5
+ formatNationalAsYouType,
6
+ formatPhoneForDisplay,
7
+ isValidPhone,
8
+ isValidPhoneValue,
9
+ parsePhoneNr,
10
+ parsePhoneValue,
11
+ phoneTelHref,
12
+ toE164,
13
+ } from './phoneNumber.js'
14
+ import type { PhoneCountry } from './phoneCountries.js'
15
+
16
+ describe('parsePhoneNr', () => {
17
+ // The canonicalisation contract every writer and the backfill share. Each row is a
18
+ // shape found in, or reachable into, `customer_user.phone_nr` today.
19
+ const contract: readonly [string, PhoneCountry, string | 'INVALID'][] = [
20
+ ['45456565', 'NO', '+4745456565'],
21
+ ['4745456565', 'NO', '+4745456565'],
22
+ ['004745456565', 'NO', '+4745456565'],
23
+ ['+47 454 56 565', 'NO', '+4745456565'],
24
+ ['47123456', 'NO', '+4747123456'],
25
+ ['+37379094538', 'NO', '+37379094538'],
26
+ ['0701234567', 'NO', 'INVALID'],
27
+ ['0701234567', 'SE', '+46701234567'],
28
+ ['12345', 'NO', 'INVALID'],
29
+ ]
30
+
31
+ for (const [input, region, expected] of contract) {
32
+ it(`canonicalises ${input} under ${region} to ${expected}`, () => {
33
+ const result = parsePhoneNr(input, region)
34
+
35
+ if (expected === 'INVALID') {
36
+ assert.deepEqual(result, { ok: false, reason: 'INVALID', input: input.trim() })
37
+ return
38
+ }
39
+
40
+ assert.equal(result.ok, true)
41
+ assert.equal(result.ok && result.e164, expected)
42
+ })
43
+ }
44
+
45
+ it('reports the country and calling code the value resolved to', () => {
46
+ const result = parsePhoneNr('45456565', 'NO')
47
+
48
+ assert.deepEqual(result, { ok: true, e164: '+4745456565', country: 'NO', callingCode: '47' })
49
+ })
50
+
51
+ it('separates an empty value from an invalid one so a report can tell them apart', () => {
52
+ for (const value of ['', ' ', null, undefined]) {
53
+ assert.deepEqual(parsePhoneNr(value, 'NO'), { ok: false, reason: 'EMPTY', input: '' })
54
+ }
55
+ })
56
+
57
+ it('reports rather than rewrites a number that is not real for the region', () => {
58
+ // `12345678` and `00000000` passed the pre-ticket digit-count rules and are in the
59
+ // data; no algorithm can recover an intended number from them.
60
+ for (const junk of ['12345678', '00000000', '11111111']) {
61
+ assert.deepEqual(parsePhoneNr(junk, 'NO'), { ok: false, reason: 'INVALID', input: junk })
62
+ }
63
+ })
64
+ })
65
+
66
+ describe('parsePhoneValue', () => {
67
+ it('splits a stored E.164 value into country and national number', () => {
68
+ assert.deepEqual(parsePhoneValue('+4748012345'), { iso2: 'NO', national: '48012345' })
69
+ assert.deepEqual(parsePhoneValue('+12015550123', 'NO'), { iso2: 'US', national: '2015550123' })
70
+ })
71
+
72
+ it('reads a pre-ASMA-7485 bare national number as the fallback country', () => {
73
+ // Every record written before this ticket is 8 bare digits with no country.
74
+ assert.deepEqual(parsePhoneValue('48012345', 'NO'), { iso2: 'NO', national: '48012345' })
75
+ assert.deepEqual(parsePhoneValue('48012345', 'SE'), { iso2: 'SE', national: '48012345' })
76
+ })
77
+
78
+ it('keeps the caller country while a matching number is still being typed', () => {
79
+ assert.deepEqual(parsePhoneValue('+47', 'NO'), { iso2: 'NO', national: '' })
80
+ assert.deepEqual(parsePhoneValue('+4748', 'NO'), { iso2: 'NO', national: '48' })
81
+ })
82
+
83
+ it('switches country when the typed prefix belongs to another one', () => {
84
+ assert.deepEqual(parsePhoneValue('+46701', 'NO'), { iso2: 'SE', national: '701' })
85
+ })
86
+
87
+ it('treats empty, whitespace and nullish values as an empty number', () => {
88
+ for (const value of ['', ' ', null, undefined]) {
89
+ assert.deepEqual(parsePhoneValue(value, 'NO'), { iso2: 'NO', national: '' })
90
+ }
91
+ })
92
+
93
+ it('falls back to the given country for an unknown calling code', () => {
94
+ assert.deepEqual(parsePhoneValue('+9991234', 'NO'), { iso2: 'NO', national: '9991234' })
95
+ })
96
+ })
97
+
98
+ describe('toE164', () => {
99
+ it('composes the stored value from the country and the typed digits', () => {
100
+ assert.equal(toE164('48012345', 'NO'), '+4748012345')
101
+ assert.equal(toE164('2015550123', 'US'), '+12015550123')
102
+ })
103
+
104
+ it('drops mask separators so the stored value is digits and a plus only', () => {
105
+ assert.equal(toE164('48 01 23 45', 'NO'), '+4748012345')
106
+ assert.equal(toE164('(201) 555-0123', 'US'), '+12015550123')
107
+ })
108
+
109
+ it('stores nothing rather than a bare dial code for an empty number', () => {
110
+ assert.equal(toE164('', 'NO'), '')
111
+ assert.equal(toE164(' ', 'NO'), '')
112
+ })
113
+
114
+ it('does not validate — an in-progress number must still round-trip', () => {
115
+ assert.equal(toE164('4', 'NO'), '+474')
116
+ })
117
+
118
+ it('does not double a country code the input already carries', () => {
119
+ // Concatenation stored `+474748012345` and `+47004748012345`, both unusable.
120
+ assert.equal(toE164('4748012345', 'NO'), '+4748012345')
121
+ assert.equal(toE164('004748012345', 'NO'), '+4748012345')
122
+ assert.equal(toE164('4781234567', 'NO'), '+4781234567')
123
+ })
124
+
125
+ it('drops the trunk prefix countries write their national numbers with', () => {
126
+ // SE/GB/DE national form carries a leading 0 that is not part of the E.164 number,
127
+ // so concatenation stored `+460701234567` for a number people write as 070-123 45 67.
128
+ assert.equal(toE164('0701234567', 'SE'), '+46701234567')
129
+ assert.equal(toE164('07911123456', 'GB'), '+447911123456')
130
+ assert.equal(toE164('015112345678', 'DE'), '+4915112345678')
131
+ })
132
+
133
+ it('keeps a genuine national number that merely starts with the dial code', () => {
134
+ assert.equal(toE164('47123456', 'NO'), '+4747123456')
135
+ })
136
+
137
+ it('round-trips through parsePhoneValue', () => {
138
+ const parsed = parsePhoneValue(toE164('48012345', 'NO'))
139
+ assert.deepEqual(parsed, { iso2: 'NO', national: '48012345' })
140
+ })
141
+ })
142
+
143
+ describe('formatNationalAsYouType', () => {
144
+ it('groups by the country format, progressively', () => {
145
+ assert.equal(formatNationalAsYouType('4', 'NO'), '4')
146
+ assert.equal(formatNationalAsYouType('480', 'NO'), '48 0')
147
+ assert.equal(formatNationalAsYouType('48012345', 'NO'), '48 01 23 45')
148
+ })
149
+
150
+ it('uses each country own grouping, not a Norwegian one', () => {
151
+ assert.equal(formatNationalAsYouType('2133734253', 'US'), '213 373 4253')
152
+ assert.equal(formatNationalAsYouType('512345678', 'PL'), '512 345 678')
153
+ })
154
+
155
+ it('groups countries that carry a trunk prefix, which the national format cannot', () => {
156
+ // AsYouType('SE') returns '701234567' unformatted: Swedish national formats are
157
+ // defined with the leading 0, which a national significant number does not carry.
158
+ assert.equal(formatNationalAsYouType('701234567', 'SE'), '70 123 45 67')
159
+ assert.equal(formatNationalAsYouType('7400123456', 'GB'), '7400 123456')
160
+ assert.equal(formatNationalAsYouType('612345678', 'FR'), '6 12 34 56 78')
161
+ })
162
+
163
+ it('returns an empty string when there is nothing to format', () => {
164
+ assert.equal(formatNationalAsYouType('', 'NO'), '')
165
+ assert.equal(formatNationalAsYouType('abc', 'NO'), '')
166
+ })
167
+ })
168
+
169
+ describe('isValidPhone', () => {
170
+ it('accepts a real number for the country', () => {
171
+ assert.equal(isValidPhone('48012345', 'NO'), true)
172
+ assert.equal(isValidPhone('2015550123', 'US'), true)
173
+ })
174
+
175
+ it('rejects by country pattern, not merely by digit count', () => {
176
+ // Both are eight digits — the length the field used to accept unconditionally.
177
+ assert.equal(isValidPhone('12345678', 'NO'), false)
178
+ assert.equal(isValidPhone('00000000', 'NO'), false)
179
+ })
180
+
181
+ it('rejects numbers outside the E.164 length bounds', () => {
182
+ assert.equal(isValidPhone('123', 'NO'), false)
183
+ assert.equal(isValidPhone('1234567890123456', 'NO'), false)
184
+ })
185
+
186
+ it('accepts a number that is valid elsewhere but not for the selected country', () => {
187
+ assert.equal(isValidPhone('2015550123', 'NO'), false)
188
+ })
189
+
190
+ it('ignores mask separators', () => {
191
+ assert.equal(isValidPhone('48 01 23 45', 'NO'), true)
192
+ })
193
+ })
194
+
195
+ describe('isValidPhoneValue', () => {
196
+ it('resolves the country from the stored value', () => {
197
+ assert.equal(isValidPhoneValue('+12015550123'), true)
198
+ assert.equal(isValidPhoneValue('+4712345678'), false)
199
+ })
200
+
201
+ it('validates a legacy bare number against the fallback country', () => {
202
+ assert.equal(isValidPhoneValue('48012345', 'NO'), true)
203
+ assert.equal(isValidPhoneValue('12345678', 'NO'), false)
204
+ })
205
+
206
+ it('treats an empty value as invalid — emptiness is the required rule job', () => {
207
+ assert.equal(isValidPhoneValue(''), false)
208
+ assert.equal(isValidPhoneValue(null), false)
209
+ })
210
+ })
211
+
212
+ describe('formatPhoneForDisplay', () => {
213
+ it('renders the international form for read-only views', () => {
214
+ assert.equal(formatPhoneForDisplay('+4748012345'), '+47 48 01 23 45')
215
+ assert.equal(formatPhoneForDisplay('+12015550123'), '+1 201 555 0123')
216
+ })
217
+
218
+ it('upgrades a legacy bare number to the international form', () => {
219
+ assert.equal(formatPhoneForDisplay('48012345', 'NO'), '+47 48 01 23 45')
220
+ })
221
+
222
+ it('returns an empty string for an empty value', () => {
223
+ assert.equal(formatPhoneForDisplay(''), '')
224
+ assert.equal(formatPhoneForDisplay(null), '')
225
+ })
226
+ })
227
+
228
+ describe('phoneTelHref', () => {
229
+ it('is the only place the tel: scheme is added (ASMA-7485)', () => {
230
+ assert.equal(phoneTelHref('+4748012345'), 'tel:+4748012345')
231
+ assert.equal(phoneTelHref('48012345', 'NO'), 'tel:+4748012345')
232
+ })
233
+
234
+ it('carries no spaces or dashes', () => {
235
+ assert.equal(phoneTelHref('48 01 23 45', 'NO'), 'tel:+4748012345')
236
+ })
237
+
238
+ it('returns an empty string when there is nothing to dial', () => {
239
+ assert.equal(phoneTelHref(''), '')
240
+ assert.equal(phoneTelHref(null), '')
241
+ })
242
+ })