UNPKG

browser-extension-url-match

Version:

Browser extension URL pattern matching

66 lines (65 loc) 1.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.matchPattern = matchPattern; var _config = require("./config"); var _getExampleUrls = require("./getExampleUrls"); var _toMatcherOrError = require("./toMatcherOrError"); function assertValid() { if (!this.valid) { throw new TypeError(this.error.message); } return this; } function _matchPattern(options) { return pattern => { const combinedOptions = Object.assign(Object.assign({}, _config.defaultOptions), options); const val = (0, _toMatcherOrError.toMatchFnOrError)(pattern, combinedOptions); return val instanceof Error ? { valid: false, error: val, assertValid } : { valid: true, match: val, get examples() { return (0, _getExampleUrls.getExampleUrls)(pattern, combinedOptions) // sanity check - examples should all match .filter(url => val(url)) // prevent example list from getting too long .slice(0, 100); }, patterns: [pattern], config: combinedOptions, assertValid }; }; } function allValid(matchers) { return matchers.every(m => m.valid); } function matchPattern(pattern, options = {}) { const patterns = typeof pattern === 'string' ? [pattern] : [...new Set(pattern)]; if (patterns.length === 1) return _matchPattern(options)(patterns[0]); const matchers = patterns.map(_matchPattern(options)); if (allValid(matchers)) { return { valid: true, get examples() { return [...new Set(matchers.flatMap(m => m.examples))]; }, match: url => matchers.some(m => m.match(url)), patterns, config: options, assertValid }; } else { const invalid = matchers.find(m => !m.valid); return { valid: false, error: invalid.error, assertValid }; } }