PhoneNumberMatcher.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. 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."); }
  2. 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); }
  3. 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; }
  4. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  6. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  7. /**
  8. * A port of Google's `PhoneNumberMatcher.java`.
  9. * https://github.com/googlei18n/libphonenumber/blob/master/java/libphonenumber/src/com/google/i18n/phonenumbers/PhoneNumberMatcher.java
  10. * Date: 08.03.2018.
  11. */
  12. import PhoneNumber from './PhoneNumber.js';
  13. import { MAX_LENGTH_FOR_NSN, MAX_LENGTH_COUNTRY_CODE, VALID_PUNCTUATION } from './constants.js';
  14. import createExtensionPattern from './helpers/extension/createExtensionPattern.js';
  15. import RegExpCache from './findNumbers/RegExpCache.js';
  16. import { limit, trimAfterFirstMatch } from './findNumbers/util.js';
  17. import { _pL, _pN, pZ, PZ, pNd } from './findNumbers/utf-8.js';
  18. import Leniency from './findNumbers/Leniency.js';
  19. import parsePreCandidate from './findNumbers/parsePreCandidate.js';
  20. import isValidPreCandidate from './findNumbers/isValidPreCandidate.js';
  21. import isValidCandidate, { LEAD_CLASS } from './findNumbers/isValidCandidate.js';
  22. import { isSupportedCountry } from './metadata.js';
  23. import parsePhoneNumber from './parsePhoneNumber.js';
  24. var USE_NON_GEOGRAPHIC_COUNTRY_CODE = false;
  25. var EXTN_PATTERNS_FOR_MATCHING = createExtensionPattern('matching');
  26. /**
  27. * Patterns used to extract phone numbers from a larger phone-number-like pattern. These are
  28. * ordered according to specificity. For example, white-space is last since that is frequently
  29. * used in numbers, not just to separate two numbers. We have separate patterns since we don't
  30. * want to break up the phone-number-like text on more than one different kind of symbol at one
  31. * time, although symbols of the same type (e.g. space) can be safely grouped together.
  32. *
  33. * Note that if there is a match, we will always check any text found up to the first match as
  34. * well.
  35. */
  36. var INNER_MATCHES = [// Breaks on the slash - e.g. "651-234-2345/332-445-1234"
  37. '\\/+(.*)/', // Note that the bracket here is inside the capturing group, since we consider it part of the
  38. // phone number. Will match a pattern like "(650) 223 3345 (754) 223 3321".
  39. '(\\([^(]*)', // Breaks on a hyphen - e.g. "12345 - 332-445-1234 is my number."
  40. // We require a space on either side of the hyphen for it to be considered a separator.
  41. "(?:".concat(pZ, "-|-").concat(pZ, ")").concat(pZ, "*(.+)"), // Various types of wide hyphens. Note we have decided not to enforce a space here, since it's
  42. // possible that it's supposed to be used to break two numbers without spaces, and we haven't
  43. // seen many instances of it used within a number.
  44. "[\u2012-\u2015\uFF0D]".concat(pZ, "*(.+)"), // Breaks on a full stop - e.g. "12345. 332-445-1234 is my number."
  45. "\\.+".concat(pZ, "*([^.]+)"), // Breaks on space - e.g. "3324451234 8002341234"
  46. "".concat(pZ, "+(").concat(PZ, "+)")]; // Limit on the number of leading (plus) characters.
  47. var leadLimit = limit(0, 2); // Limit on the number of consecutive punctuation characters.
  48. var punctuationLimit = limit(0, 4);
  49. /* The maximum number of digits allowed in a digit-separated block. As we allow all digits in a
  50. * single block, set high enough to accommodate the entire national number and the international
  51. * country code. */
  52. var digitBlockLimit = MAX_LENGTH_FOR_NSN + MAX_LENGTH_COUNTRY_CODE; // Limit on the number of blocks separated by punctuation.
  53. // Uses digitBlockLimit since some formats use spaces to separate each digit.
  54. var blockLimit = limit(0, digitBlockLimit);
  55. /* A punctuation sequence allowing white space. */
  56. var punctuation = "[".concat(VALID_PUNCTUATION, "]") + punctuationLimit; // A digits block without punctuation.
  57. var digitSequence = pNd + limit(1, digitBlockLimit);
  58. /**
  59. * Phone number pattern allowing optional punctuation.
  60. * The phone number pattern used by `find()`, similar to
  61. * VALID_PHONE_NUMBER, but with the following differences:
  62. * <ul>
  63. * <li>All captures are limited in order to place an upper bound to the text matched by the
  64. * pattern.
  65. * <ul>
  66. * <li>Leading punctuation / plus signs are limited.
  67. * <li>Consecutive occurrences of punctuation are limited.
  68. * <li>Number of digits is limited.
  69. * </ul>
  70. * <li>No whitespace is allowed at the start or end.
  71. * <li>No alpha digits (vanity numbers such as 1-800-SIX-FLAGS) are currently supported.
  72. * </ul>
  73. */
  74. var PATTERN = '(?:' + LEAD_CLASS + punctuation + ')' + leadLimit + digitSequence + '(?:' + punctuation + digitSequence + ')' + blockLimit + '(?:' + EXTN_PATTERNS_FOR_MATCHING + ')?'; // Regular expression of trailing characters that we want to remove.
  75. // We remove all characters that are not alpha or numerical characters.
  76. // The hash character is retained here, as it may signify
  77. // the previous block was an extension.
  78. //
  79. // // Don't know what does '&&' mean here.
  80. // const UNWANTED_END_CHAR_PATTERN = new RegExp(`[[\\P{N}&&\\P{L}]&&[^#]]+$`)
  81. //
  82. var UNWANTED_END_CHAR_PATTERN = new RegExp("[^".concat(_pN).concat(_pL, "#]+$"));
  83. var NON_DIGITS_PATTERN = /(\D+)/;
  84. var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;
  85. /**
  86. * A stateful class that finds and extracts telephone numbers from {@linkplain CharSequence text}.
  87. * Instances can be created using the {@linkplain PhoneNumberUtil#findNumbers factory methods} in
  88. * {@link PhoneNumberUtil}.
  89. *
  90. * <p>Vanity numbers (phone numbers using alphabetic digits such as <tt>1-800-SIX-FLAGS</tt> are
  91. * not found.
  92. *
  93. * <p>This class is not thread-safe.
  94. */
  95. var PhoneNumberMatcher = /*#__PURE__*/function () {
  96. /**
  97. * @param {string} text — the character sequence that we will search, null for no text.
  98. * @param {'POSSIBLE'|'VALID'|'STRICT_GROUPING'|'EXACT_GROUPING'} [options.leniency] — The leniency to use when evaluating candidate phone numbers. See `source/findNumbers/Leniency.js` for more details.
  99. * @param {number} [options.maxTries] — The maximum number of invalid numbers to try before giving up on the text. This is to cover degenerate cases where the text has a lot of false positives in it. Must be >= 0.
  100. */
  101. function PhoneNumberMatcher() {
  102. var text = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  103. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  104. var metadata = arguments.length > 2 ? arguments[2] : undefined;
  105. _classCallCheck(this, PhoneNumberMatcher);
  106. options = {
  107. v2: options.v2,
  108. defaultCallingCode: options.defaultCallingCode,
  109. defaultCountry: options.defaultCountry && isSupportedCountry(options.defaultCountry, metadata) ? options.defaultCountry : undefined,
  110. leniency: options.leniency || (options.extended ? 'POSSIBLE' : 'VALID'),
  111. maxTries: options.maxTries || MAX_SAFE_INTEGER
  112. }; // Validate `leniency`.
  113. if (!options.leniency) {
  114. throw new TypeError('`leniency` is required');
  115. }
  116. if (options.leniency !== 'POSSIBLE' && options.leniency !== 'VALID') {
  117. throw new TypeError("Invalid `leniency`: \"".concat(options.leniency, "\". Supported values: \"POSSIBLE\", \"VALID\"."));
  118. } // Validate `maxTries`.
  119. if (options.maxTries < 0) {
  120. throw new TypeError('`maxTries` must be `>= 0`');
  121. }
  122. this.text = text;
  123. this.options = options;
  124. this.metadata = metadata; // The degree of phone number validation.
  125. this.leniency = Leniency[options.leniency];
  126. if (!this.leniency) {
  127. throw new TypeError("Unknown leniency: \"".concat(options.leniency, "\""));
  128. }
  129. /** The maximum number of retries after matching an invalid number. */
  130. this.maxTries = options.maxTries;
  131. this.PATTERN = new RegExp(PATTERN, 'ig');
  132. /** The iteration tristate. */
  133. this.state = 'NOT_READY';
  134. /** The next index to start searching at. Undefined in {@link State#DONE}. */
  135. this.searchIndex = 0; // A cache for frequently used country-specific regular expressions. Set to 32 to cover ~2-3
  136. // countries being used for the same doc with ~10 patterns for each country. Some pages will have
  137. // a lot more countries in use, but typically fewer numbers for each so expanding the cache for
  138. // that use-case won't have a lot of benefit.
  139. this.regExpCache = new RegExpCache(32);
  140. }
  141. /**
  142. * Attempts to find the next subsequence in the searched sequence on or after {@code searchIndex}
  143. * that represents a phone number. Returns the next match, null if none was found.
  144. *
  145. * @param index the search index to start searching at
  146. * @return the phone number match found, null if none can be found
  147. */
  148. _createClass(PhoneNumberMatcher, [{
  149. key: "find",
  150. value: function find() {
  151. // // Reset the regular expression.
  152. // this.PATTERN.lastIndex = index
  153. var matches;
  154. while (this.maxTries > 0 && (matches = this.PATTERN.exec(this.text)) !== null) {
  155. var candidate = matches[0];
  156. var offset = matches.index;
  157. candidate = parsePreCandidate(candidate);
  158. if (isValidPreCandidate(candidate, offset, this.text)) {
  159. var match = // Try to come up with a valid match given the entire candidate.
  160. this.parseAndVerify(candidate, offset, this.text) // If that failed, try to find an "inner match" -
  161. // there might be a phone number within this candidate.
  162. || this.extractInnerMatch(candidate, offset, this.text);
  163. if (match) {
  164. if (this.options.v2) {
  165. return {
  166. startsAt: match.startsAt,
  167. endsAt: match.endsAt,
  168. number: match.phoneNumber
  169. };
  170. } else {
  171. var phoneNumber = match.phoneNumber;
  172. var result = {
  173. startsAt: match.startsAt,
  174. endsAt: match.endsAt,
  175. phone: phoneNumber.nationalNumber
  176. };
  177. if (phoneNumber.country) {
  178. /* istanbul ignore if */
  179. if (USE_NON_GEOGRAPHIC_COUNTRY_CODE && country === '001') {
  180. result.countryCallingCode = phoneNumber.countryCallingCode;
  181. } else {
  182. result.country = phoneNumber.country;
  183. }
  184. } else {
  185. result.countryCallingCode = phoneNumber.countryCallingCode;
  186. }
  187. if (phoneNumber.ext) {
  188. result.ext = phoneNumber.ext;
  189. }
  190. return result;
  191. }
  192. }
  193. }
  194. this.maxTries--;
  195. }
  196. }
  197. /**
  198. * Attempts to extract a match from `substring`
  199. * if the substring itself does not qualify as a match.
  200. */
  201. }, {
  202. key: "extractInnerMatch",
  203. value: function extractInnerMatch(substring, offset, text) {
  204. for (var _iterator = _createForOfIteratorHelperLoose(INNER_MATCHES), _step; !(_step = _iterator()).done;) {
  205. var innerMatchPattern = _step.value;
  206. var isFirstMatch = true;
  207. var candidateMatch = void 0;
  208. var innerMatchRegExp = new RegExp(innerMatchPattern, 'g');
  209. while (this.maxTries > 0 && (candidateMatch = innerMatchRegExp.exec(substring)) !== null) {
  210. if (isFirstMatch) {
  211. // We should handle any group before this one too.
  212. var _candidate = trimAfterFirstMatch(UNWANTED_END_CHAR_PATTERN, substring.slice(0, candidateMatch.index));
  213. var _match = this.parseAndVerify(_candidate, offset, text);
  214. if (_match) {
  215. return _match;
  216. }
  217. this.maxTries--;
  218. isFirstMatch = false;
  219. }
  220. var candidate = trimAfterFirstMatch(UNWANTED_END_CHAR_PATTERN, candidateMatch[1]); // Java code does `groupMatcher.start(1)` here,
  221. // but there's no way in javascript to get a `candidate` start index,
  222. // therefore resort to using this kind of an approximation.
  223. // (`groupMatcher` is called `candidateInSubstringMatch` in this javascript port)
  224. // https://stackoverflow.com/questions/15934353/get-index-of-each-capture-in-a-javascript-regex
  225. var candidateIndexGuess = substring.indexOf(candidate, candidateMatch.index);
  226. var match = this.parseAndVerify(candidate, offset + candidateIndexGuess, text);
  227. if (match) {
  228. return match;
  229. }
  230. this.maxTries--;
  231. }
  232. }
  233. }
  234. /**
  235. * Parses a phone number from the `candidate` using `parse` and
  236. * verifies it matches the requested `leniency`. If parsing and verification succeed,
  237. * a corresponding `PhoneNumberMatch` is returned, otherwise this method returns `null`.
  238. *
  239. * @param candidate the candidate match
  240. * @param offset the offset of {@code candidate} within {@link #text}
  241. * @return the parsed and validated phone number match, or null
  242. */
  243. }, {
  244. key: "parseAndVerify",
  245. value: function parseAndVerify(candidate, offset, text) {
  246. if (!isValidCandidate(candidate, offset, text, this.options.leniency)) {
  247. return;
  248. }
  249. var phoneNumber = parsePhoneNumber(candidate, {
  250. extended: true,
  251. defaultCountry: this.options.defaultCountry,
  252. defaultCallingCode: this.options.defaultCallingCode
  253. }, this.metadata);
  254. if (!phoneNumber) {
  255. return;
  256. }
  257. if (!phoneNumber.isPossible()) {
  258. return;
  259. }
  260. if (this.leniency(phoneNumber, {
  261. candidate: candidate,
  262. defaultCountry: this.options.defaultCountry,
  263. metadata: this.metadata,
  264. regExpCache: this.regExpCache
  265. })) {
  266. return {
  267. startsAt: offset,
  268. endsAt: offset + candidate.length,
  269. phoneNumber: phoneNumber
  270. };
  271. }
  272. }
  273. }, {
  274. key: "hasNext",
  275. value: function hasNext() {
  276. if (this.state === 'NOT_READY') {
  277. this.lastMatch = this.find(); // (this.searchIndex)
  278. if (this.lastMatch) {
  279. // this.searchIndex = this.lastMatch.endsAt
  280. this.state = 'READY';
  281. } else {
  282. this.state = 'DONE';
  283. }
  284. }
  285. return this.state === 'READY';
  286. }
  287. }, {
  288. key: "next",
  289. value: function next() {
  290. // Check the state and find the next match as a side-effect if necessary.
  291. if (!this.hasNext()) {
  292. throw new Error('No next element');
  293. } // Don't retain that memory any longer than necessary.
  294. var result = this.lastMatch;
  295. this.lastMatch = null;
  296. this.state = 'NOT_READY';
  297. return result;
  298. }
  299. }]);
  300. return PhoneNumberMatcher;
  301. }();
  302. export { PhoneNumberMatcher as default };
  303. //# sourceMappingURL=PhoneNumberMatcher.js.map