| 295 | * Converts and escape the file URL to a regular expression. |
| 296 | */ |
| 297 | export function urlToRegex(aPath: string, escapeRegex = true) { |
| 298 | const patterns: string[] = []; |
| 299 | |
| 300 | // aPath will often (always?) be provided as a file URI, or URL. Decode it |
| 301 | // --we'll reencode it as we go--and also create a match for its absolute |
| 302 | // path. |
| 303 | // |
| 304 | // This de- and re-encoding is important for special characters, since: |
| 305 | // - It comes in like "file:///c:/foo/%F0%9F%92%A9.js" |
| 306 | // - We decode it to file:///c:/foo/💩.js |
| 307 | // - For case insensitive systems, we generate a regex like [fF][oO][oO]/(?:💩|%F0%9F%92%A9).[jJ][sS] |
| 308 | // - If we didn't de-encode it, the percent would be case-insensitized as |
| 309 | // well and we would not include the original character in the regex |
| 310 | for (const str of [decodeURI(aPath), fileUrlToAbsolutePath(aPath)]) { |
| 311 | if (!str) { |
| 312 | continue; |
| 313 | } |
| 314 | |
| 315 | // Loop through each character of the string. Convert the char to a regex, |
| 316 | // creating a group, and then appent that to the match. |
| 317 | const chars = new Set<string>(); |
| 318 | let re = ''; |
| 319 | for (const char of str) { |
| 320 | if (isCaseSensitive) { |
| 321 | urlToRegexChar(char, chars, escapeRegex); |
| 322 | } else { |
| 323 | urlToRegexChar(char.toLowerCase(), chars, escapeRegex); |
| 324 | urlToRegexChar(char.toUpperCase(), chars, escapeRegex); |
| 325 | } |
| 326 | |
| 327 | re += createReGroup(chars); |
| 328 | chars.clear(); |
| 329 | } |
| 330 | |
| 331 | // If we're on windows but not case sensitive (i.e. we didn't expand a |
| 332 | // fancy regex above), replace `file:///c:/` or simple `c:/` patterns with |
| 333 | // an insensitive drive letter. |
| 334 | patterns.push( |
| 335 | re.replace( |
| 336 | /^(file:\\\/\\\/\\\/)?([a-z]):/i, |
| 337 | (_, file = '', letter) => `${file}[${letter.toUpperCase()}${letter.toLowerCase()}]:`, |
| 338 | ), |
| 339 | ); |
| 340 | } |
| 341 | |
| 342 | return patterns.join('|'); |
| 343 | } |
| 344 | |
| 345 | /** |
| 346 | * Opaque typed used to indicate strings that are file URLs. |