2023-01-03 19:55:46 +00:00
|
|
|
// Copyright 2018 Signal Messenger, LLC
|
2020-10-30 20:34:04 +00:00
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2018-05-05 01:19:54 +00:00
|
|
|
import libphonenumber from 'google-libphonenumber';
|
2022-04-05 00:38:22 +00:00
|
|
|
import type { PhoneNumber } from 'google-libphonenumber';
|
2018-05-05 01:19:54 +00:00
|
|
|
|
|
|
|
const instance = libphonenumber.PhoneNumberUtil.getInstance();
|
2020-09-14 21:56:35 +00:00
|
|
|
const { PhoneNumberFormat } = libphonenumber;
|
2018-05-05 01:19:54 +00:00
|
|
|
|
|
|
|
export { instance, PhoneNumberFormat };
|
2022-04-05 00:38:22 +00:00
|
|
|
|
|
|
|
export type ParsedE164Type = Readonly<{
|
|
|
|
isValid: boolean;
|
|
|
|
userInput: string;
|
|
|
|
e164: string;
|
|
|
|
}>;
|
|
|
|
|
|
|
|
export function parseAndFormatPhoneNumber(
|
|
|
|
str: string,
|
|
|
|
regionCode: string | undefined,
|
|
|
|
format = PhoneNumberFormat.E164
|
|
|
|
): ParsedE164Type | undefined {
|
|
|
|
let result: PhoneNumber;
|
|
|
|
try {
|
|
|
|
result = instance.parse(str, regionCode);
|
|
|
|
} catch (err) {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
isValid: instance.isValidNumber(result),
|
|
|
|
userInput: str,
|
|
|
|
e164: instance.format(result, format),
|
|
|
|
};
|
|
|
|
}
|