UNPKG

14.7 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.containsMoreThanOneSlashInNationalNumber = containsMoreThanOneSlashInNationalNumber;
7exports["default"] = void 0;
8
9var _validate_ = _interopRequireDefault(require("../validate_"));
10
11var _parseDigits = _interopRequireDefault(require("../helpers/parseDigits"));
12
13var _util = require("./util");
14
15function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
16
17/**
18 * Leniency when finding potential phone numbers in text segments
19 * The levels here are ordered in increasing strictness.
20 */
21var _default = {
22 /**
23 * Phone numbers accepted are "possible", but not necessarily "valid".
24 */
25 POSSIBLE: function POSSIBLE(number, candidate, metadata) {
26 return true;
27 },
28
29 /**
30 * Phone numbers accepted are "possible" and "valid".
31 * Numbers written in national format must have their national-prefix
32 * present if it is usually written for a number of this type.
33 */
34 VALID: function VALID(number, candidate, metadata) {
35 if (!(0, _validate_["default"])(number, undefined, metadata) || !containsOnlyValidXChars(number, candidate.toString(), metadata)) {
36 return false;
37 } // Skipped for simplicity.
38 // return isNationalPrefixPresentIfRequired(number, metadata)
39
40
41 return true;
42 },
43
44 /**
45 * Phone numbers accepted are "valid" and
46 * are grouped in a possible way for this locale. For example, a US number written as
47 * "65 02 53 00 00" and "650253 0000" are not accepted at this leniency level, whereas
48 * "650 253 0000", "650 2530000" or "6502530000" are.
49 * Numbers with more than one '/' symbol in the national significant number
50 * are also dropped at this level.
51 *
52 * Warning: This level might result in lower coverage especially for regions outside of
53 * country code "+1". If you are not sure about which level to use,
54 * email the discussion group libphonenumber-discuss@googlegroups.com.
55 */
56 STRICT_GROUPING: function STRICT_GROUPING(number, candidate, metadata, regExpCache) {
57 var candidateString = candidate.toString();
58
59 if (!(0, _validate_["default"])(number, undefined, metadata) || !containsOnlyValidXChars(number, candidateString, metadata) || containsMoreThanOneSlashInNationalNumber(number, candidateString) || !isNationalPrefixPresentIfRequired(number, metadata)) {
60 return false;
61 }
62
63 return checkNumberGroupingIsValid(number, candidate, metadata, allNumberGroupsRemainGrouped, regExpCache);
64 },
65
66 /**
67 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and
68 * are grouped in the same way that we would have formatted it, or as a single block. For
69 * example, a US number written as "650 2530000" is not accepted at this leniency level, whereas
70 * "650 253 0000" or "6502530000" are.
71 * Numbers with more than one '/' symbol are also dropped at this level.
72 * <p>
73 * Warning: This level might result in lower coverage especially for regions outside of country
74 * code "+1". If you are not sure about which level to use, email the discussion group
75 * libphonenumber-discuss@googlegroups.com.
76 */
77 EXACT_GROUPING: function EXACT_GROUPING(number, candidate, metadata, regExpCache) {
78 var candidateString = candidate.toString();
79
80 if (!(0, _validate_["default"])(number, undefined, metadata) || !containsOnlyValidXChars(number, candidateString, metadata) || containsMoreThanOneSlashInNationalNumber(number, candidateString) || !isNationalPrefixPresentIfRequired(number, metadata)) {
81 return false;
82 }
83
84 return checkNumberGroupingIsValid(number, candidate, metadata, allNumberGroupsAreExactlyPresent, regExpCache);
85 }
86};
87exports["default"] = _default;
88
89function containsOnlyValidXChars(number, candidate, metadata) {
90 // The characters 'x' and 'X' can be (1) a carrier code, in which case they always precede the
91 // national significant number or (2) an extension sign, in which case they always precede the
92 // extension number. We assume a carrier code is more than 1 digit, so the first case has to
93 // have more than 1 consecutive 'x' or 'X', whereas the second case can only have exactly 1 'x'
94 // or 'X'. We ignore the character if it appears as the last character of the string.
95 for (var index = 0; index < candidate.length - 1; index++) {
96 var charAtIndex = candidate.charAt(index);
97
98 if (charAtIndex === 'x' || charAtIndex === 'X') {
99 var charAtNextIndex = candidate.charAt(index + 1);
100
101 if (charAtNextIndex === 'x' || charAtNextIndex === 'X') {
102 // This is the carrier code case, in which the 'X's always precede the national
103 // significant number.
104 index++;
105
106 if (util.isNumberMatch(number, candidate.substring(index)) != MatchType.NSN_MATCH) {
107 return false;
108 } // This is the extension sign case, in which the 'x' or 'X' should always precede the
109 // extension number.
110
111 } else if ((0, _parseDigits["default"])(candidate.substring(index)) !== number.ext) {
112 return false;
113 }
114 }
115 }
116
117 return true;
118}
119
120function isNationalPrefixPresentIfRequired(number, _metadata) {
121 // First, check how we deduced the country code. If it was written in international format, then
122 // the national prefix is not required.
123 if (number.getCountryCodeSource() != 'FROM_DEFAULT_COUNTRY') {
124 return true;
125 }
126
127 var phoneNumberRegion = util.getRegionCodeForCountryCode(number.getCountryCode());
128 var metadata = util.getMetadataForRegion(phoneNumberRegion);
129
130 if (metadata == null) {
131 return true;
132 } // Check if a national prefix should be present when formatting this number.
133
134
135 var nationalNumber = util.getNationalSignificantNumber(number);
136 var formatRule = util.chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber); // To do this, we check that a national prefix formatting rule was present
137 // and that it wasn't just the first-group symbol ($1) with punctuation.
138
139 if (formatRule && formatRule.getNationalPrefixFormattingRule().length > 0) {
140 if (formatRule.getNationalPrefixOptionalWhenFormatting()) {
141 // The national-prefix is optional in these cases, so we don't need to check if it was
142 // present.
143 return true;
144 }
145
146 if (PhoneNumberUtil.formattingRuleHasFirstGroupOnly(formatRule.getNationalPrefixFormattingRule())) {
147 // National Prefix not needed for this number.
148 return true;
149 } // Normalize the remainder.
150
151
152 var rawInputCopy = PhoneNumberUtil.normalizeDigitsOnly(number.getRawInput()); // Check if we found a national prefix and/or carrier code at the start of the raw input, and
153 // return the result.
154
155 return util.maybeStripNationalPrefixAndCarrierCode(rawInputCopy, metadata, null);
156 }
157
158 return true;
159}
160
161function containsMoreThanOneSlashInNationalNumber(number, candidate) {
162 var firstSlashInBodyIndex = candidate.indexOf('/');
163
164 if (firstSlashInBodyIndex < 0) {
165 // No slashes, this is okay.
166 return false;
167 } // Now look for a second one.
168
169
170 var secondSlashInBodyIndex = candidate.indexOf('/', firstSlashInBodyIndex + 1);
171
172 if (secondSlashInBodyIndex < 0) {
173 // Only one slash, this is okay.
174 return false;
175 } // If the first slash is after the country calling code, this is permitted.
176
177
178 var candidateHasCountryCode = number.getCountryCodeSource() === CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN || number.getCountryCodeSource() === CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN;
179
180 if (candidateHasCountryCode && PhoneNumberUtil.normalizeDigitsOnly(candidate.substring(0, firstSlashInBodyIndex)) === String(number.getCountryCode())) {
181 // Any more slashes and this is illegal.
182 return candidate.slice(secondSlashInBodyIndex + 1).indexOf('/') >= 0;
183 }
184
185 return true;
186}
187
188function checkNumberGroupingIsValid(number, candidate, metadata, checkGroups, regExpCache) {
189 var normalizedCandidate = normalizeDigits(candidate, true
190 /* keep non-digits */
191 );
192 var formattedNumberGroups = getNationalNumberGroups(metadata, number, null);
193
194 if (checkGroups(metadata, number, normalizedCandidate, formattedNumberGroups)) {
195 return true;
196 } // If this didn't pass, see if there are any alternate formats that match, and try them instead.
197
198
199 var alternateFormats = MetadataManager.getAlternateFormatsForCountry(number.getCountryCode());
200 var nationalSignificantNumber = util.getNationalSignificantNumber(number);
201
202 if (alternateFormats) {
203 for (var _iterator = alternateFormats.numberFormats(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
204 var _ref;
205
206 if (_isArray) {
207 if (_i >= _iterator.length) break;
208 _ref = _iterator[_i++];
209 } else {
210 _i = _iterator.next();
211 if (_i.done) break;
212 _ref = _i.value;
213 }
214
215 var alternateFormat = _ref;
216
217 if (alternateFormat.leadingDigitsPatterns().length > 0) {
218 // There is only one leading digits pattern for alternate formats.
219 var leadingDigitsRegExp = regExpCache.getPatternForRegExp('^' + alternateFormat.leadingDigitsPatterns()[0]);
220
221 if (!leadingDigitsRegExp.test(nationalSignificantNumber)) {
222 // Leading digits don't match; try another one.
223 continue;
224 }
225 }
226
227 formattedNumberGroups = getNationalNumberGroups(metadata, number, alternateFormat);
228
229 if (checkGroups(metadata, number, normalizedCandidate, formattedNumberGroups)) {
230 return true;
231 }
232 }
233 }
234
235 return false;
236}
237/**
238 * Helper method to get the national-number part of a number, formatted without any national
239 * prefix, and return it as a set of digit blocks that would be formatted together following
240 * standard formatting rules.
241 */
242
243
244function getNationalNumberGroups(metadata, number, formattingPattern) {
245 if (formattingPattern) {
246 // We format the NSN only, and split that according to the separator.
247 var nationalSignificantNumber = util.getNationalSignificantNumber(number);
248 return util.formatNsnUsingPattern(nationalSignificantNumber, formattingPattern, 'RFC3966', metadata).split('-');
249 } // This will be in the format +CC-DG1-DG2-DGX;ext=EXT where DG1..DGX represents groups of digits.
250
251
252 var rfc3966Format = formatNumber(number, 'RFC3966', metadata); // We remove the extension part from the formatted string before splitting it into different
253 // groups.
254
255 var endIndex = rfc3966Format.indexOf(';');
256
257 if (endIndex < 0) {
258 endIndex = rfc3966Format.length;
259 } // The country-code will have a '-' following it.
260
261
262 var startIndex = rfc3966Format.indexOf('-') + 1;
263 return rfc3966Format.slice(startIndex, endIndex).split('-');
264}
265
266function allNumberGroupsAreExactlyPresent(metadata, number, normalizedCandidate, formattedNumberGroups) {
267 var candidateGroups = normalizedCandidate.split(NON_DIGITS_PATTERN); // Set this to the last group, skipping it if the number has an extension.
268
269 var candidateNumberGroupIndex = number.hasExtension() ? candidateGroups.length - 2 : candidateGroups.length - 1; // First we check if the national significant number is formatted as a block.
270 // We use contains and not equals, since the national significant number may be present with
271 // a prefix such as a national number prefix, or the country code itself.
272
273 if (candidateGroups.length == 1 || candidateGroups[candidateNumberGroupIndex].contains(util.getNationalSignificantNumber(number))) {
274 return true;
275 } // Starting from the end, go through in reverse, excluding the first group, and check the
276 // candidate and number groups are the same.
277
278
279 var formattedNumberGroupIndex = formattedNumberGroups.length - 1;
280
281 while (formattedNumberGroupIndex > 0 && candidateNumberGroupIndex >= 0) {
282 if (candidateGroups[candidateNumberGroupIndex] !== formattedNumberGroups[formattedNumberGroupIndex]) {
283 return false;
284 }
285
286 formattedNumberGroupIndex--;
287 candidateNumberGroupIndex--;
288 } // Now check the first group. There may be a national prefix at the start, so we only check
289 // that the candidate group ends with the formatted number group.
290
291
292 return candidateNumberGroupIndex >= 0 && (0, _util.endsWith)(candidateGroups[candidateNumberGroupIndex], formattedNumberGroups[0]);
293}
294
295function allNumberGroupsRemainGrouped(metadata, number, normalizedCandidate, formattedNumberGroups) {
296 var fromIndex = 0;
297
298 if (number.getCountryCodeSource() !== CountryCodeSource.FROM_DEFAULT_COUNTRY) {
299 // First skip the country code if the normalized candidate contained it.
300 var countryCode = String(number.getCountryCode());
301 fromIndex = normalizedCandidate.indexOf(countryCode) + countryCode.length();
302 } // Check each group of consecutive digits are not broken into separate groupings in the
303 // {@code normalizedCandidate} string.
304
305
306 for (var i = 0; i < formattedNumberGroups.length; i++) {
307 // Fails if the substring of {@code normalizedCandidate} starting from {@code fromIndex}
308 // doesn't contain the consecutive digits in formattedNumberGroups[i].
309 fromIndex = normalizedCandidate.indexOf(formattedNumberGroups[i], fromIndex);
310
311 if (fromIndex < 0) {
312 return false;
313 } // Moves {@code fromIndex} forward.
314
315
316 fromIndex += formattedNumberGroups[i].length();
317
318 if (i == 0 && fromIndex < normalizedCandidate.length()) {
319 // We are at the position right after the NDC. We get the region used for formatting
320 // information based on the country code in the phone number, rather than the number itself,
321 // as we do not need to distinguish between different countries with the same country
322 // calling code and this is faster.
323 var region = util.getRegionCodeForCountryCode(number.getCountryCode());
324
325 if (util.getNddPrefixForRegion(region, true) != null && Character.isDigit(normalizedCandidate.charAt(fromIndex))) {
326 // This means there is no formatting symbol after the NDC. In this case, we only
327 // accept the number if there is no formatting symbol at all in the number, except
328 // for extensions. This is only important for countries with national prefixes.
329 var nationalSignificantNumber = util.getNationalSignificantNumber(number);
330 return (0, _util.startsWith)(normalizedCandidate.slice(fromIndex - formattedNumberGroups[i].length), nationalSignificantNumber);
331 }
332 }
333 } // The check here makes sure that we haven't mistakenly already used the extension to
334 // match the last group of the subscriber number. Note the extension cannot have
335 // formatting in-between digits.
336
337
338 return normalizedCandidate.slice(fromIndex).contains(number.getExtension());
339}
340//# sourceMappingURL=Leniency.js.map
\No newline at end of file