asma-core-helpers 0.35.0 → 0.37.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asma-core-helpers",
3
- "version": "0.35.0",
3
+ "version": "0.37.0",
4
4
  "description": "Core helper utilities for ASMA applications",
5
5
  "files": [
6
6
  "lib/**/*",
@@ -30,6 +30,10 @@
30
30
  "./validation": {
31
31
  "types": "./lib/validation/index.d.ts",
32
32
  "default": "./lib/validation/index.js"
33
+ },
34
+ "./phone": {
35
+ "types": "./lib/phone/index.d.ts",
36
+ "default": "./lib/phone/index.js"
33
37
  }
34
38
  },
35
39
  "scripts": {
@@ -62,6 +66,7 @@
62
66
  "asma-event-bus": "^0.7.27",
63
67
  "buffer": "^6.0.3",
64
68
  "idb-keyval": "^6.2.1",
69
+ "libphonenumber-js": "^1.13.12",
65
70
  "mobx": "^6.12.3",
66
71
  "mobx-state-tree": "^7.0.2",
67
72
  "wonka": "^6.3.4"
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Country-aware phone primitives for ASMA forms (ASMA-7485).
3
+ *
4
+ * Published as `asma-core-helpers/phone` and deliberately **not** re-exported from
5
+ * the root barrel: the root entry is what the ESM kernel bundles and serves to all
6
+ * 17 fleet apps, and `libphonenumber-js` has no business in that shared unit. As a
7
+ * subpath it is absent from `KERNEL_EXTERNAL_SPECIFIERS`, so it bundles into the two
8
+ * apps that actually render a phone field instead.
9
+ *
10
+ * @see asma-modules/_docs/adr/adr-g-0017-frontend-form-state-and-validation-ownership.md:49 — DEC-001, why the rules live here and not in asma-ui-core
11
+ */
12
+
13
+ export {
14
+ DEFAULT_PHONE_COUNTRY,
15
+ findCountryByDialCode,
16
+ getPhoneDialCode,
17
+ listPhoneCountries,
18
+ matchesPhoneCountry,
19
+ type PhoneCountry,
20
+ type PhoneCountryOption,
21
+ } from './phoneCountries.js'
22
+
23
+ export {
24
+ formatNationalAsYouType,
25
+ formatPhoneForDisplay,
26
+ isValidPhone,
27
+ isValidPhoneValue,
28
+ parsePhoneNr,
29
+ parsePhoneValue,
30
+ phoneTelHref,
31
+ PHONE_MAX_DIGITS,
32
+ PHONE_MIN_DIGITS,
33
+ toE164,
34
+ type ParsedPhone,
35
+ type PhoneNrParse,
36
+ } from './phoneNumber.js'
37
+
38
+ export { phoneExample } from './phoneExample.js'
@@ -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
+ }