Leniency.js 16 KB

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