UNPKG

8.68 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports["default"] = formatNumber;
7
8var _matchesEntirely = _interopRequireDefault(require("./helpers/matchesEntirely"));
9
10var _formatNationalNumberUsingFormat = _interopRequireDefault(require("./helpers/formatNationalNumberUsingFormat"));
11
12var _metadata = _interopRequireWildcard(require("./metadata"));
13
14var _getIddPrefix = _interopRequireDefault(require("./helpers/getIddPrefix"));
15
16var _RFC = require("./helpers/RFC3966");
17
18function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
19
20function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
21
22function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
23
24function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
25
26var DEFAULT_OPTIONS = {
27 formatExtension: function formatExtension(formattedNumber, extension, metadata) {
28 return "".concat(formattedNumber).concat(metadata.ext()).concat(extension);
29 } // Formats a phone number
30 //
31 // Example use cases:
32 //
33 // ```js
34 // formatNumber('8005553535', 'RU', 'INTERNATIONAL')
35 // formatNumber('8005553535', 'RU', 'INTERNATIONAL', metadata)
36 // formatNumber({ phone: '8005553535', country: 'RU' }, 'INTERNATIONAL')
37 // formatNumber({ phone: '8005553535', country: 'RU' }, 'INTERNATIONAL', metadata)
38 // formatNumber('+78005553535', 'NATIONAL')
39 // formatNumber('+78005553535', 'NATIONAL', metadata)
40 // ```
41 //
42
43};
44
45function formatNumber(input, format, options, metadata) {
46 // Apply default options.
47 if (options) {
48 options = _objectSpread({}, DEFAULT_OPTIONS, options);
49 } else {
50 options = DEFAULT_OPTIONS;
51 }
52
53 metadata = new _metadata["default"](metadata);
54
55 if (input.country && input.country !== '001') {
56 // Validate `input.country`.
57 if (!metadata.hasCountry(input.country)) {
58 throw new Error("Unknown country: ".concat(input.country));
59 }
60
61 metadata.country(input.country);
62 } else if (input.countryCallingCode) {
63 metadata.selectNumberingPlan(input.countryCallingCode);
64 } else return input.phone || '';
65
66 var countryCallingCode = metadata.countryCallingCode();
67 var nationalNumber = options.v2 ? input.nationalNumber : input.phone; // This variable should have been declared inside `case`s
68 // but Babel has a bug and it says "duplicate variable declaration".
69
70 var number;
71
72 switch (format) {
73 case 'NATIONAL':
74 // Legacy argument support.
75 // (`{ country: ..., phone: '' }`)
76 if (!nationalNumber) {
77 return '';
78 }
79
80 number = formatNationalNumber(nationalNumber, input.carrierCode, 'NATIONAL', metadata, options);
81 return addExtension(number, input.ext, metadata, options.formatExtension);
82
83 case 'INTERNATIONAL':
84 // Legacy argument support.
85 // (`{ country: ..., phone: '' }`)
86 if (!nationalNumber) {
87 return "+".concat(countryCallingCode);
88 }
89
90 number = formatNationalNumber(nationalNumber, null, 'INTERNATIONAL', metadata, options);
91 number = "+".concat(countryCallingCode, " ").concat(number);
92 return addExtension(number, input.ext, metadata, options.formatExtension);
93
94 case 'E.164':
95 // `E.164` doesn't define "phone number extensions".
96 return "+".concat(countryCallingCode).concat(nationalNumber);
97
98 case 'RFC3966':
99 return (0, _RFC.formatRFC3966)({
100 number: "+".concat(countryCallingCode).concat(nationalNumber),
101 ext: input.ext
102 });
103 // For reference, here's Google's IDD formatter:
104 // https://github.com/google/libphonenumber/blob/32719cf74e68796788d1ca45abc85dcdc63ba5b9/java/libphonenumber/src/com/google/i18n/phonenumbers/PhoneNumberUtil.java#L1546
105 // Not saying that this IDD formatter replicates it 1:1, but it seems to work.
106 // Who would even need to format phone numbers in IDD format anyway?
107
108 case 'IDD':
109 if (!options.fromCountry) {
110 return; // throw new Error('`fromCountry` option not passed for IDD-prefixed formatting.')
111 }
112
113 var formattedNumber = formatIDD(nationalNumber, input.carrierCode, countryCallingCode, options.fromCountry, metadata);
114 return addExtension(formattedNumber, input.ext, metadata, options.formatExtension);
115
116 default:
117 throw new Error("Unknown \"format\" argument passed to \"formatNumber()\": \"".concat(format, "\""));
118 }
119}
120
121function formatNationalNumber(number, carrierCode, formatAs, metadata, options) {
122 var format = chooseFormatForNumber(metadata.formats(), number);
123
124 if (!format) {
125 return number;
126 }
127
128 return (0, _formatNationalNumberUsingFormat["default"])(number, format, {
129 useInternationalFormat: formatAs === 'INTERNATIONAL',
130 withNationalPrefix: format.nationalPrefixIsOptionalWhenFormattingInNationalFormat() && options && options.nationalPrefix === false ? false : true,
131 carrierCode: carrierCode,
132 metadata: metadata
133 });
134}
135
136function chooseFormatForNumber(availableFormats, nationalNnumber) {
137 for (var _iterator = availableFormats, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
138 var _ref;
139
140 if (_isArray) {
141 if (_i >= _iterator.length) break;
142 _ref = _iterator[_i++];
143 } else {
144 _i = _iterator.next();
145 if (_i.done) break;
146 _ref = _i.value;
147 }
148
149 var format = _ref;
150
151 // Validate leading digits
152 if (format.leadingDigitsPatterns().length > 0) {
153 // The last leading_digits_pattern is used here, as it is the most detailed
154 var lastLeadingDigitsPattern = format.leadingDigitsPatterns()[format.leadingDigitsPatterns().length - 1]; // If leading digits don't match then move on to the next phone number format
155
156 if (nationalNnumber.search(lastLeadingDigitsPattern) !== 0) {
157 continue;
158 }
159 } // Check that the national number matches the phone number format regular expression
160
161
162 if ((0, _matchesEntirely["default"])(nationalNnumber, format.pattern())) {
163 return format;
164 }
165 }
166}
167
168function addExtension(formattedNumber, ext, metadata, formatExtension) {
169 return ext ? formatExtension(formattedNumber, ext, metadata) : formattedNumber;
170}
171
172function formatIDD(nationalNumber, carrierCode, countryCallingCode, fromCountry, metadata) {
173 var fromCountryCallingCode = (0, _metadata.getCountryCallingCode)(fromCountry, metadata.metadata); // When calling within the same country calling code.
174
175 if (fromCountryCallingCode === countryCallingCode) {
176 var formattedNumber = formatNationalNumber(nationalNumber, carrierCode, 'NATIONAL', metadata); // For NANPA regions, return the national format for these regions
177 // but prefix it with the country calling code.
178
179 if (countryCallingCode === '1') {
180 return countryCallingCode + ' ' + formattedNumber;
181 } // If regions share a country calling code, the country calling code need
182 // not be dialled. This also applies when dialling within a region, so this
183 // if clause covers both these cases. Technically this is the case for
184 // dialling from La Reunion to other overseas departments of France (French
185 // Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover
186 // this edge case for now and for those cases return the version including
187 // country calling code. Details here:
188 // http://www.petitfute.com/voyage/225-info-pratiques-reunion
189 //
190
191
192 return formattedNumber;
193 }
194
195 var iddPrefix = (0, _getIddPrefix["default"])(fromCountry, undefined, metadata.metadata);
196
197 if (iddPrefix) {
198 return "".concat(iddPrefix, " ").concat(countryCallingCode, " ").concat(formatNationalNumber(nationalNumber, null, 'INTERNATIONAL', metadata));
199 }
200}
201//# sourceMappingURL=format_.js.map
\No newline at end of file