-
Notifications
You must be signed in to change notification settings - Fork 43
/
utils.ts
663 lines (613 loc) Β· 15.2 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
import { parseURL, stringifyParsedURL } from "./parse";
import { QueryObject, parseQuery, stringifyQuery, ParsedQuery } from "./query";
import {
decode,
decodePath,
encodeHash,
encodeHost,
encodePath,
} from "./encoding";
const PROTOCOL_STRICT_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{1,2})/;
const PROTOCOL_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{2})?/;
const PROTOCOL_RELATIVE_REGEX = /^([/\\]\s*){2,}[^/\\]/;
const PROTOCOL_SCRIPT_RE = /^[\s\0]*(blob|data|javascript|vbscript):$/i;
const TRAILING_SLASH_RE = /\/$|\/\?|\/#/;
const JOIN_LEADING_SLASH_RE = /^\.?\//;
/**
* Check if a path starts with `./` or `../`.
*
* @example
* ```js
* isRelative("./foo"); // true
* ```
*
* @group utils
*/
export function isRelative(inputString: string) {
return ["./", "../"].some((string_) => inputString.startsWith(string_));
}
export interface HasProtocolOptions {
acceptRelative?: boolean;
strict?: boolean;
}
/**
* Checks if the input has a protocol.
*
* You can use `{ acceptRelative: true }` to accept relative URLs as valid protocol.
*
* @group utils
*/
export function hasProtocol(
inputString: string,
opts?: HasProtocolOptions
): boolean;
/** @deprecated Same as { hasProtocol(inputString, { acceptRelative: true }) */
export function hasProtocol(
inputString: string,
acceptRelative: boolean
): boolean;
export function hasProtocol(
inputString: string,
opts: boolean | HasProtocolOptions = {}
): boolean {
if (typeof opts === "boolean") {
opts = { acceptRelative: opts };
}
if (opts.strict) {
return PROTOCOL_STRICT_REGEX.test(inputString);
}
return (
PROTOCOL_REGEX.test(inputString) ||
(opts.acceptRelative ? PROTOCOL_RELATIVE_REGEX.test(inputString) : false)
);
}
/**
* Checks if the input protocol is any of the dangerous `blob:`, `data:`, `javascript`: or `vbscript:` protocols.
*
* @group utils
*/
export function isScriptProtocol(protocol?: string) {
return !!protocol && PROTOCOL_SCRIPT_RE.test(protocol);
}
/**
* Checks if the input has a trailing slash.
*
* @group utils
*/
export function hasTrailingSlash(
input = "",
respectQueryAndFragment?: boolean
): boolean {
if (!respectQueryAndFragment) {
return input.endsWith("/");
}
return TRAILING_SLASH_RE.test(input);
}
/**
* Removes trailing slash from the URL or pathname.
*
* If second argument is true, it will only remove the trailing slash if it's not part of the query or fragment with cost of more expensive operations.
*
* @example
*
* ```js
* withoutTrailingSlash("/foo/"); // "/foo"
*
* withoutTrailingSlash("/path/?query=true", true); // "/path?query=true"
* ```
*
* @group utils
*/
export function withoutTrailingSlash(
input = "",
respectQueryAndFragment?: boolean
): string {
if (!respectQueryAndFragment) {
return (hasTrailingSlash(input) ? input.slice(0, -1) : input) || "/";
}
if (!hasTrailingSlash(input, true)) {
return input || "/";
}
let path = input;
let fragment = "";
const fragmentIndex = input.indexOf("#");
if (fragmentIndex >= 0) {
path = input.slice(0, fragmentIndex);
fragment = input.slice(fragmentIndex);
}
const [s0, ...s] = path.split("?");
const cleanPath = s0.endsWith("/") ? s0.slice(0, -1) : s0;
return (
(cleanPath || "/") + (s.length > 0 ? `?${s.join("?")}` : "") + fragment
);
}
/**
* Ensures url ends with a trailing slash.
*
* If seccond argument is `true`, it will only add the trailing slash if it's not part of the query or fragment with cost of more expensive operation.
*
* @example
*
* ```js
* withTrailingSlash("/foo"); // "/foo/"
*
* withTrailingSlash("/path?query=true", true); // "/path/?query=true"
* ```
*
* @group utils
*/
export function withTrailingSlash(
input = "",
respectQueryAndFragment?: boolean
): string {
if (!respectQueryAndFragment) {
return input.endsWith("/") ? input : input + "/";
}
if (hasTrailingSlash(input, true)) {
return input || "/";
}
let path = input;
let fragment = "";
const fragmentIndex = input.indexOf("#");
if (fragmentIndex >= 0) {
path = input.slice(0, fragmentIndex);
fragment = input.slice(fragmentIndex);
if (!path) {
return fragment;
}
}
const [s0, ...s] = path.split("?");
return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
}
/**
* Checks if the input has a leading slash. (e.g. `/foo`)
*
* @group utils
*/
export function hasLeadingSlash(input = ""): boolean {
return input.startsWith("/");
}
/**
* Removes leading slash from the URL or pathname.
*
* @group utils
*/
export function withoutLeadingSlash(input = ""): string {
return (hasLeadingSlash(input) ? input.slice(1) : input) || "/";
}
/**
* Ensures the URL or pathname has a leading slash.
*
* @group utils
*/
export function withLeadingSlash(input = ""): string {
return hasLeadingSlash(input) ? input : "/" + input;
}
/**
* Removes double slashes from the URL.
*
* @example
*
* ```js
* cleanDoubleSlashes("//foo//bar//"); // "/foo/bar/"
*
* cleanDoubleSlashes("http://example.com/analyze//http://localhost:3000//");
* // Returns "http://example.com/analyze/http://localhost:3000/"
* ```
*
* @group utils
*/
export function cleanDoubleSlashes(input = ""): string {
return input
.split("://")
.map((string_) => string_.replace(/\/{2,}/g, "/"))
.join("://");
}
/**
* Ensures the URL or pathname has a trailing slash.
*
* If input aleady start with base, it will not be added again.
*
* @group utils
*/
export function withBase(input: string, base: string) {
if (isEmptyURL(base) || hasProtocol(input)) {
return input;
}
const _base = withoutTrailingSlash(base);
if (input.startsWith(_base)) {
return input;
}
return joinURL(_base, input);
}
/**
* Removes the base from the URL or pathname.
*
* If input does not start with base, it will not be removed.
*
* @group utils
*/
export function withoutBase(input: string, base: string) {
if (isEmptyURL(base)) {
return input;
}
const _base = withoutTrailingSlash(base);
if (!input.startsWith(_base)) {
return input;
}
const trimmed = input.slice(_base.length);
return trimmed[0] === "/" ? trimmed : "/" + trimmed;
}
/**
* Add/Replace the query section of the URL.
*
* @example
*
* ```js
* withQuery("/foo?page=a", { token: "secret" }); // "/foo?page=a&token=secret"
* ```
*
* @group utils
*/
export function withQuery(input: string, query: QueryObject): string {
const parsed = parseURL(input);
const mergedQuery = { ...parseQuery(parsed.search), ...query };
parsed.search = stringifyQuery(mergedQuery);
return stringifyParsedURL(parsed);
}
/**
* Parses and decods the query object of an input URL into an object.
*
* @example
*
* ```js
* getQuery("http://foo.com/foo?test=123&unicode=%E5%A5%BD");
* // { test: "123", unicode: "ε₯½" }
* ```
* @group utils
*/
export function getQuery<T extends ParsedQuery = ParsedQuery>(
input: string
): T {
return parseQuery<T>(parseURL(input).search);
}
/**
* Checks if the input url is empty or `/`.
*
* @group utils
*/
export function isEmptyURL(url: string) {
return !url || url === "/";
}
/**
* Checks if the input url is not empty nor `/`.
*
* @group utils
*/
export function isNonEmptyURL(url: string) {
return url && url !== "/";
}
/**
* Joins multiple URL segments into a single URL.
*
* @example
*
* ```js
* joinURL("a", "/b", "/c"); // "a/b/c"
* ```
*
* @group utils
*/
export function joinURL(base: string, ...input: string[]): string {
let url = base || "";
for (const segment of input.filter((url) => isNonEmptyURL(url))) {
if (url) {
// TODO: Handle .. when joining
const _segment = segment.replace(JOIN_LEADING_SLASH_RE, "");
url = withTrailingSlash(url) + _segment;
} else {
url = segment;
}
}
return url;
}
/**
* Joins multiple URL segments into a single URL and also handles relative paths with `./` and `../`.
*
* @example
*
* ```js
* joinRelativeURL("/a", "../b", "./c"); // "/b/c"
* ```
*
* @group utils
*/
export function joinRelativeURL(..._input: string[]): string {
// Inlined regex to increase browser compatibiltiy
const JOIN_SEGMENT_SPLIT_RE = /\/(?!\/)/;
const input = _input.filter(Boolean);
const segments: string[] = [];
let segmentsDepth = 0;
for (const i of input) {
if (!i || i === "/") {
continue;
}
for (const [sindex, s] of i.split(JOIN_SEGMENT_SPLIT_RE).entries()) {
if (!s || s === ".") {
continue;
}
if (s === "..") {
if (segments.length === 1 && hasProtocol(segments[0])) {
continue;
}
segments.pop();
segmentsDepth--;
continue;
}
// eslint-disable-next-line unicorn/prefer-at
if (sindex === 1 && segments[segments.length - 1]?.endsWith(":/")) {
segments[segments.length - 1] += "/" + s;
continue;
}
segments.push(s);
segmentsDepth++;
}
}
let url = segments.join("/");
if (segmentsDepth >= 0) {
// Preserve leading slash
if (input[0]?.startsWith("/") && !url.startsWith("/")) {
url = "/" + url;
} else if (input[0]?.startsWith("./") && !url.startsWith("./")) {
url = "./" + url;
}
} else {
// Add relative prefix
url = "../".repeat(-1 * segmentsDepth) + url;
}
// Preserve trailing slash
// eslint-disable-next-line unicorn/prefer-at
if (input[input.length - 1]?.endsWith("/") && !url.endsWith("/")) {
url += "/";
}
return url;
}
/**
* Adds or replaces url protocol to `http://`.
*
* @example
*
* ```js
* withHttp("https://example.com"); // http://example.com
* ```
*
* @group utils
*/
export function withHttp(input: string): string {
return withProtocol(input, "http://");
}
/**
* Adds or replaces url protocol to `https://`.
*
* @example
*
* ```js
* withHttps("http://example.com"); // https://example.com
* ```
*
* @group utils
*/
export function withHttps(input: string): string {
return withProtocol(input, "https://");
}
/**
* Removes the protocol from the input.
*
* @example
* ```js
* withoutProtocol("http://example.com"); // "example.com"
* ```
*/
export function withoutProtocol(input: string): string {
return withProtocol(input, "");
}
/**
* Adds or Replaces protocol of the input URL.
*
* @example
* ```js
* withProtocol("http://example.com", "ftp://"); // "ftp://example.com"
* ```
*
* @group utils
*/
export function withProtocol(input: string, protocol: string): string {
const match = input.match(PROTOCOL_REGEX);
if (!match) {
return protocol + input;
}
return protocol + input.slice(match[0].length);
}
/**
* Normlizes inputed url:
*
* - Ensures url is properly encoded
* - Ensures pathname starts with slash
* - Preserves protocol/host if provided
*
* @example
*
* ```js
* normalizeURL("test?query=123 123#hash, test");
* // Returns "test?query=123%20123#hash,%20test"
*
* normalizeURL("http://localhost:3000");
* // Returns "http://localhost:3000"
* ```
*
* @group utils
*/
export function normalizeURL(input: string): string {
const parsed = parseURL(input);
parsed.pathname = encodePath(decodePath(parsed.pathname));
parsed.hash = encodeHash(decode(parsed.hash));
parsed.host = encodeHost(decode(parsed.host));
parsed.search = stringifyQuery(parseQuery(parsed.search));
return stringifyParsedURL(parsed);
}
/**
* Resolves multiple URL segments into a single URL.
*
* @example
*
* ```js
* resolveURL("http://foo.com/foo?test=123#token", "bar", "baz");
* // Returns "http://foo.com/foo/bar/baz?test=123#token"
* ```
*
* @group utils
*/
export function resolveURL(base = "", ...inputs: string[]): string {
if (typeof base !== "string") {
throw new TypeError(
`URL input should be string received ${typeof base} (${base})`
);
}
const filteredInputs = inputs.filter((input) => isNonEmptyURL(input));
if (filteredInputs.length === 0) {
return base;
}
const url = parseURL(base);
for (const inputSegment of filteredInputs) {
const urlSegment = parseURL(inputSegment);
// Append path
if (urlSegment.pathname) {
url.pathname =
withTrailingSlash(url.pathname) +
withoutLeadingSlash(urlSegment.pathname);
}
// Override hash
if (urlSegment.hash && urlSegment.hash !== "#") {
url.hash = urlSegment.hash;
}
// Append search
if (urlSegment.search && urlSegment.search !== "?") {
if (url.search && url.search !== "?") {
const queryString = stringifyQuery({
...parseQuery(url.search),
...parseQuery(urlSegment.search),
});
url.search = queryString.length > 0 ? "?" + queryString : "";
} else {
url.search = urlSegment.search;
}
}
}
return stringifyParsedURL(url);
}
/**
* Check two paths are equal or not. Trailing slash and encoding are normalized before comparison.
*
* @example
* ```js
* isSamePath("/foo", "/foo/"); // true
* ```
*
* @group utils
*/
export function isSamePath(p1: string, p2: string) {
return decode(withoutTrailingSlash(p1)) === decode(withoutTrailingSlash(p2));
}
interface CompareURLOptions {
trailingSlash?: boolean;
leadingSlash?: boolean;
encoding?: boolean;
}
/**
* Checks if two paths are equal regardless of encoding, trailing slash, and leading slash differences.
*
* You can make slash check strict by setting `{ trailingSlash: true, leadingSlash: true }` as options.
*
* You can make encoding check strict by setting `{ encoding: true }` as options.
*
* @example
*
* ```js
* isEqual("/foo", "foo"); // true
* isEqual("foo/", "foo"); // true
* isEqual("/foo bar", "/foo%20bar"); // true
*
* // Strict compare
* isEqual("/foo", "foo", { leadingSlash: true }); // false
* isEqual("foo/", "foo", { trailingSlash: true }); // false
* isEqual("/foo bar", "/foo%20bar", { encoding: true }); // false
* ```
*
* @group utils
*/
export function isEqual(a: string, b: string, options: CompareURLOptions = {}) {
if (!options.trailingSlash) {
a = withTrailingSlash(a);
b = withTrailingSlash(b);
}
if (!options.leadingSlash) {
a = withLeadingSlash(a);
b = withLeadingSlash(b);
}
if (!options.encoding) {
a = decode(a);
b = decode(b);
}
return a === b;
}
/**
* Add/Replace the fragment section of the URL.
*
* @example
*
* ```js
* withFragment("/foo", "bar"); // "/foo#bar"
* withFragment("/foo#bar", "baz"); // "/foo#baz"
* withFragment("/foo#bar", ""); // "/foo"
* ```
*
* @group utils
*/
export function withFragment(input: string, hash: string): string {
if (!hash || hash === "#") {
return input;
}
const parsed = parseURL(input);
parsed.hash = hash === "" ? "" : "#" + encodeHash(hash);
return stringifyParsedURL(parsed);
}
/**
* Removes the fragment section from the URL.
*
* @example
*
* ```js
* withoutFragment("http://example.com/foo?q=123#bar")
* // Returns "http://example.com/foo?q=123"
* ```
*
* @group utils
*/
export function withoutFragment(input: string): string {
return stringifyParsedURL({ ...parseURL(input), hash: "" });
}
/**
* Removes the host from the URL preserving everything else.
*
* @example
* ```js
* withoutHost("http://example.com/foo?q=123#bar")
* // Returns "/foo?q=123#bar"
* ```
*
* @group utils
*/
export function withoutHost(input: string) {
const parsed = parseURL(input);
return (parsed.pathname || "/") + parsed.search + parsed.hash;
}