-
Notifications
You must be signed in to change notification settings - Fork 29.6k
/
url.js
1505 lines (1318 loc) Β· 41.6 KB
/
url.js
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const {
Array,
ArrayIsArray,
ArrayPrototypeJoin,
ArrayPrototypeMap,
ArrayPrototypePush,
ArrayPrototypeReduce,
ArrayPrototypeSlice,
Boolean,
Int8Array,
IteratorPrototype,
Number,
ObjectDefineProperties,
ObjectSetPrototypeOf,
ReflectGetOwnPropertyDescriptor,
ReflectOwnKeys,
RegExpPrototypeSymbolReplace,
SafeMap,
SafeSet,
StringPrototypeCharAt,
StringPrototypeCharCodeAt,
StringPrototypeCodePointAt,
StringPrototypeIncludes,
StringPrototypeIndexOf,
StringPrototypeSlice,
StringPrototypeStartsWith,
Symbol,
SymbolIterator,
SymbolToStringTag,
decodeURIComponent,
} = primordials;
const { inspect } = require('internal/util/inspect');
const {
encodeStr,
hexTable,
isHexTable,
} = require('internal/querystring');
const {
getConstructorOf,
removeColors,
toUSVString,
kEnumerableProperty,
SideEffectFreeRegExpPrototypeSymbolReplace,
} = require('internal/util');
const {
codes: {
ERR_ARG_NOT_ITERABLE,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE,
ERR_INVALID_FILE_URL_HOST,
ERR_INVALID_FILE_URL_PATH,
ERR_INVALID_THIS,
ERR_INVALID_TUPLE,
ERR_INVALID_URL,
ERR_INVALID_URL_SCHEME,
ERR_MISSING_ARGS,
ERR_NO_CRYPTO,
},
} = require('internal/errors');
const {
CHAR_AMPERSAND,
CHAR_BACKWARD_SLASH,
CHAR_EQUAL,
CHAR_FORWARD_SLASH,
CHAR_LOWERCASE_A,
CHAR_LOWERCASE_Z,
CHAR_PERCENT,
CHAR_PLUS,
} = require('internal/constants');
const path = require('path');
const {
validateFunction,
} = require('internal/validators');
const querystring = require('querystring');
const { platform } = process;
const isWindows = platform === 'win32';
const bindingUrl = internalBinding('url');
const FORWARD_SLASH = /\//g;
const contextForInspect = Symbol('context');
// `unsafeProtocol`, `hostlessProtocol` and `slashedProtocol` is
// deliberately moved to `internal/url` rather than `url`.
// Workers does not bootstrap URL module. Therefore, `SafeSet`
// is not initialized on bootstrap. This case breaks the
// test-require-delete-array-iterator test.
// Protocols that can allow "unsafe" and "unwise" chars.
const unsafeProtocol = new SafeSet([
'javascript',
'javascript:',
]);
// Protocols that never have a hostname.
const hostlessProtocol = new SafeSet([
'javascript',
'javascript:',
]);
// Protocols that always contain a // bit.
const slashedProtocol = new SafeSet([
'http',
'http:',
'https',
'https:',
'ftp',
'ftp:',
'gopher',
'gopher:',
'file',
'file:',
'ws',
'ws:',
'wss',
'wss:',
]);
const updateActions = {
kProtocol: 0,
kHost: 1,
kHostname: 2,
kPort: 3,
kUsername: 4,
kPassword: 5,
kPathname: 6,
kSearch: 7,
kHash: 8,
kHref: 9,
};
let blob;
let cryptoRandom;
function lazyBlob() {
blob ??= require('internal/blob');
return blob;
}
function lazyCryptoRandom() {
try {
cryptoRandom ??= require('internal/crypto/random');
} catch {
// If Node.js built without crypto support, we'll fall
// through here and handle it later.
}
return cryptoRandom;
}
// This class provides the internal state of a URL object. An instance of this
// class is stored in every URL object and is accessed internally by setters
// and getters. It roughly corresponds to the concept of a URL record in the
// URL Standard, with a few differences. It is also the object transported to
// the C++ binding.
// Refs: https://url.spec.whatwg.org/#concept-url
class URLContext {
// This is the maximum value uint32_t can get.
// Ada uses uint32_t(-1) for declaring omitted values.
static #omitted = 4294967295;
href = '';
protocol_end = 0;
username_end = 0;
host_start = 0;
host_end = 0;
pathname_start = 0;
search_start = 0;
hash_start = 0;
port = 0;
/**
* Refers to `ada::scheme::type`
*
* enum type : uint8_t {
* HTTP = 0,
* NOT_SPECIAL = 1,
* HTTPS = 2,
* WS = 3,
* FTP = 4,
* WSS = 5,
* FILE = 6
* };
* @type {number}
*/
scheme_type = 1;
get hasPort() {
return this.port !== URLContext.#omitted;
}
get hasSearch() {
return this.search_start !== URLContext.#omitted;
}
get hasHash() {
return this.hash_start !== URLContext.#omitted;
}
}
let setURLSearchParamsContext;
let getURLSearchParamsList;
let setURLSearchParams;
class URLSearchParamsIterator {
#target;
#kind;
#index;
// https://heycam.github.io/webidl/#dfn-default-iterator-object
constructor(target, kind) {
this.#target = target;
this.#kind = kind;
this.#index = 0;
}
next() {
if (typeof this !== 'object' || this === null || !(#target in this))
throw new ERR_INVALID_THIS('URLSearchParamsIterator');
const index = this.#index;
const values = getURLSearchParamsList(this.#target);
const len = values.length;
if (index >= len) {
return {
value: undefined,
done: true,
};
}
const name = values[index];
const value = values[index + 1];
this.#index = index + 2;
let result;
if (this.#kind === 'key') {
result = name;
} else if (this.#kind === 'value') {
result = value;
} else {
result = [name, value];
}
return {
value: result,
done: false,
};
}
[inspect.custom](recurseTimes, ctx) {
if (!this || typeof this !== 'object' || !(#target in this))
throw new ERR_INVALID_THIS('URLSearchParamsIterator');
if (typeof recurseTimes === 'number' && recurseTimes < 0)
return ctx.stylize('[Object]', 'special');
const innerOpts = { ...ctx };
if (recurseTimes !== null) {
innerOpts.depth = recurseTimes - 1;
}
const index = this.#index;
const values = getURLSearchParamsList(this.#target);
const output = ArrayPrototypeReduce(
ArrayPrototypeSlice(values, index),
(prev, cur, i) => {
const key = i % 2 === 0;
if (this.#kind === 'key' && key) {
ArrayPrototypePush(prev, cur);
} else if (this.#kind === 'value' && !key) {
ArrayPrototypePush(prev, cur);
} else if (this.#kind === 'key+value' && !key) {
ArrayPrototypePush(prev, [values[index + i - 1], cur]);
}
return prev;
},
[],
);
const breakLn = StringPrototypeIncludes(inspect(output, innerOpts), '\n');
const outputStrs = ArrayPrototypeMap(output, (p) => inspect(p, innerOpts));
let outputStr;
if (breakLn) {
outputStr = `\n ${ArrayPrototypeJoin(outputStrs, ',\n ')}`;
} else {
outputStr = ` ${ArrayPrototypeJoin(outputStrs, ', ')}`;
}
return `${this[SymbolToStringTag]} {${outputStr} }`;
}
}
// https://heycam.github.io/webidl/#dfn-iterator-prototype-object
delete URLSearchParamsIterator.prototype.constructor;
ObjectSetPrototypeOf(URLSearchParamsIterator.prototype, IteratorPrototype);
ObjectDefineProperties(URLSearchParamsIterator.prototype, {
[SymbolToStringTag]: { __proto__: null, configurable: true, value: 'URLSearchParams Iterator' },
next: kEnumerableProperty,
});
class URLSearchParams {
#searchParams = [];
// "associated url object"
#context;
static {
setURLSearchParamsContext = (obj, ctx) => {
obj.#context = ctx;
};
getURLSearchParamsList = (obj) => obj.#searchParams;
setURLSearchParams = (obj, query) => {
if (query === undefined) {
obj.#searchParams = [];
} else {
obj.#searchParams = parseParams(query);
}
};
}
// URL Standard says the default value is '', but as undefined and '' have
// the same result, undefined is used to prevent unnecessary parsing.
// Default parameter is necessary to keep URLSearchParams.length === 0 in
// accordance with Web IDL spec.
constructor(init = undefined) {
if (init == null) {
// Do nothing
} else if (typeof init === 'object' || typeof init === 'function') {
const method = init[SymbolIterator];
if (method === this[SymbolIterator] && #searchParams in init) {
// While the spec does not have this branch, we can use it as a
// shortcut to avoid having to go through the costly generic iterator.
const childParams = init.#searchParams;
this.#searchParams = childParams.slice();
} else if (method != null) {
// Sequence<sequence<USVString>>
if (typeof method !== 'function') {
throw new ERR_ARG_NOT_ITERABLE('Query pairs');
}
// The following implementationd differs from the URL specification:
// Sequences must first be converted from ECMAScript objects before
// and operations are done on them, and the operation of converting
// the sequences would first exhaust the iterators. If the iterator
// returns something invalid in the middle, whether it would be called
// after that would be an observable change to the users.
// Exhausting the iterator and later converting them to USVString comes
// with a significant cost (~40-80%). In order optimize URLSearchParams
// creation duration, Node.js merges the iteration and converting
// iterations into a single iteration.
for (const pair of init) {
if (pair == null) {
throw new ERR_INVALID_TUPLE('Each query pair', '[name, value]');
} else if (ArrayIsArray(pair)) {
// If innerSequence's size is not 2, then throw a TypeError.
if (pair.length !== 2) {
throw new ERR_INVALID_TUPLE('Each query pair', '[name, value]');
}
// Append (innerSequence[0], innerSequence[1]) to querys list.
ArrayPrototypePush(this.#searchParams, toUSVString(pair[0]), toUSVString(pair[1]));
} else {
if (((typeof pair !== 'object' && typeof pair !== 'function') ||
typeof pair[SymbolIterator] !== 'function')) {
throw new ERR_INVALID_TUPLE('Each query pair', '[name, value]');
}
let length = 0;
for (const element of pair) {
length++;
ArrayPrototypePush(this.#searchParams, toUSVString(element));
}
// If innerSequence's size is not 2, then throw a TypeError.
if (length !== 2) {
throw new ERR_INVALID_TUPLE('Each query pair', '[name, value]');
}
}
}
} else {
// Record<USVString, USVString>
// Need to use reflection APIs for full spec compliance.
const visited = new SafeMap();
const keys = ReflectOwnKeys(init);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const desc = ReflectGetOwnPropertyDescriptor(init, key);
if (desc !== undefined && desc.enumerable) {
const typedKey = toUSVString(key);
const typedValue = toUSVString(init[key]);
// Two different keys may become the same USVString after normalization.
// In that case, we retain the later one. Refer to WPT.
const keyIdx = visited.get(typedKey);
if (keyIdx !== undefined) {
this.#searchParams[keyIdx] = typedValue;
} else {
visited.set(typedKey, ArrayPrototypePush(this.#searchParams,
typedKey,
typedValue) - 1);
}
}
}
}
} else {
// https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
init = toUSVString(init);
this.#searchParams = init ? parseParams(init) : [];
}
}
[inspect.custom](recurseTimes, ctx) {
if (typeof this !== 'object' || this === null || !(#searchParams in this))
throw new ERR_INVALID_THIS('URLSearchParams');
if (typeof recurseTimes === 'number' && recurseTimes < 0)
return ctx.stylize('[Object]', 'special');
const separator = ', ';
const innerOpts = { ...ctx };
if (recurseTimes !== null) {
innerOpts.depth = recurseTimes - 1;
}
const innerInspect = (v) => inspect(v, innerOpts);
const list = this.#searchParams;
const output = [];
for (let i = 0; i < list.length; i += 2)
ArrayPrototypePush(
output,
`${innerInspect(list[i])} => ${innerInspect(list[i + 1])}`);
const length = ArrayPrototypeReduce(
output,
(prev, cur) => prev + removeColors(cur).length + separator.length,
-separator.length,
);
if (length > ctx.breakLength) {
return `${this.constructor.name} {\n` +
` ${ArrayPrototypeJoin(output, ',\n ')} }`;
} else if (output.length) {
return `${this.constructor.name} { ` +
`${ArrayPrototypeJoin(output, separator)} }`;
}
return `${this.constructor.name} {}`;
}
get size() {
if (typeof this !== 'object' || this === null || !(#searchParams in this))
throw new ERR_INVALID_THIS('URLSearchParams');
return this.#searchParams.length / 2;
}
append(name, value) {
if (typeof this !== 'object' || this === null || !(#searchParams in this))
throw new ERR_INVALID_THIS('URLSearchParams');
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('name', 'value');
}
name = toUSVString(name);
value = toUSVString(value);
ArrayPrototypePush(this.#searchParams, name, value);
if (this.#context) {
this.#context.search = this.toString();
}
}
delete(name, value = undefined) {
if (typeof this !== 'object' || this === null || !(#searchParams in this))
throw new ERR_INVALID_THIS('URLSearchParams');
if (arguments.length < 1) {
throw new ERR_MISSING_ARGS('name');
}
const list = this.#searchParams;
name = toUSVString(name);
if (value !== undefined) {
value = toUSVString(value);
for (let i = 0; i < list.length;) {
if (list[i] === name && list[i + 1] === value) {
list.splice(i, 2);
} else {
i += 2;
}
}
} else {
for (let i = 0; i < list.length;) {
if (list[i] === name) {
list.splice(i, 2);
} else {
i += 2;
}
}
}
if (this.#context) {
this.#context.search = this.toString();
}
}
get(name) {
if (typeof this !== 'object' || this === null || !(#searchParams in this))
throw new ERR_INVALID_THIS('URLSearchParams');
if (arguments.length < 1) {
throw new ERR_MISSING_ARGS('name');
}
const list = this.#searchParams;
name = toUSVString(name);
for (let i = 0; i < list.length; i += 2) {
if (list[i] === name) {
return list[i + 1];
}
}
return null;
}
getAll(name) {
if (typeof this !== 'object' || this === null || !(#searchParams in this))
throw new ERR_INVALID_THIS('URLSearchParams');
if (arguments.length < 1) {
throw new ERR_MISSING_ARGS('name');
}
const list = this.#searchParams;
const values = [];
name = toUSVString(name);
for (let i = 0; i < list.length; i += 2) {
if (list[i] === name) {
values.push(list[i + 1]);
}
}
return values;
}
has(name, value = undefined) {
if (typeof this !== 'object' || this === null || !(#searchParams in this))
throw new ERR_INVALID_THIS('URLSearchParams');
if (arguments.length < 1) {
throw new ERR_MISSING_ARGS('name');
}
const list = this.#searchParams;
name = toUSVString(name);
if (value !== undefined) {
value = toUSVString(value);
}
for (let i = 0; i < list.length; i += 2) {
if (list[i] === name) {
if (value === undefined || list[i + 1] === value) {
return true;
}
}
}
return false;
}
set(name, value) {
if (typeof this !== 'object' || this === null || !(#searchParams in this))
throw new ERR_INVALID_THIS('URLSearchParams');
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('name', 'value');
}
const list = this.#searchParams;
name = toUSVString(name);
value = toUSVString(value);
// If there are any name-value pairs whose name is `name`, in `list`, set
// the value of the first such name-value pair to `value` and remove the
// others.
let found = false;
for (let i = 0; i < list.length;) {
const cur = list[i];
if (cur === name) {
if (!found) {
list[i + 1] = value;
found = true;
i += 2;
} else {
list.splice(i, 2);
}
} else {
i += 2;
}
}
// Otherwise, append a new name-value pair whose name is `name` and value
// is `value`, to `list`.
if (!found) {
ArrayPrototypePush(list, name, value);
}
if (this.#context) {
this.#context.search = this.toString();
}
}
sort() {
if (typeof this !== 'object' || this === null || !(#searchParams in this))
throw new ERR_INVALID_THIS('URLSearchParams');
const a = this.#searchParams;
const len = a.length;
if (len <= 2) {
// Nothing needs to be done.
} else if (len < 100) {
// 100 is found through testing.
// Simple stable in-place insertion sort
// Derived from v8/src/js/array.js
for (let i = 2; i < len; i += 2) {
const curKey = a[i];
const curVal = a[i + 1];
let j;
for (j = i - 2; j >= 0; j -= 2) {
if (a[j] > curKey) {
a[j + 2] = a[j];
a[j + 3] = a[j + 1];
} else {
break;
}
}
a[j + 2] = curKey;
a[j + 3] = curVal;
}
} else {
// Bottom-up iterative stable merge sort
const lBuffer = new Array(len);
const rBuffer = new Array(len);
for (let step = 2; step < len; step *= 2) {
for (let start = 0; start < len - 2; start += 2 * step) {
const mid = start + step;
let end = mid + step;
end = end < len ? end : len;
if (mid > end)
continue;
merge(a, start, mid, end, lBuffer, rBuffer);
}
}
}
if (this.#context) {
this.#context.search = this.toString();
}
}
// https://heycam.github.io/webidl/#es-iterators
// Define entries here rather than [Symbol.iterator] as the function name
// must be set to `entries`.
entries() {
if (typeof this !== 'object' || this === null || !(#searchParams in this))
throw new ERR_INVALID_THIS('URLSearchParams');
return new URLSearchParamsIterator(this, 'key+value');
}
forEach(callback, thisArg = undefined) {
if (typeof this !== 'object' || this === null || !(#searchParams in this))
throw new ERR_INVALID_THIS('URLSearchParams');
validateFunction(callback, 'callback');
let list = this.#searchParams;
let i = 0;
while (i < list.length) {
const key = list[i];
const value = list[i + 1];
callback.call(thisArg, value, key, this);
// In case the URL object's `search` is updated
list = this.#searchParams;
i += 2;
}
}
// https://heycam.github.io/webidl/#es-iterable
keys() {
if (typeof this !== 'object' || this === null || !(#searchParams in this))
throw new ERR_INVALID_THIS('URLSearchParams');
return new URLSearchParamsIterator(this, 'key');
}
values() {
if (typeof this !== 'object' || this === null || !(#searchParams in this))
throw new ERR_INVALID_THIS('URLSearchParams');
return new URLSearchParamsIterator(this, 'value');
}
// https://heycam.github.io/webidl/#es-stringifier
// https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior
toString() {
if (typeof this !== 'object' || this === null || !(#searchParams in this))
throw new ERR_INVALID_THIS('URLSearchParams');
return serializeParams(this.#searchParams);
}
}
ObjectDefineProperties(URLSearchParams.prototype, {
append: kEnumerableProperty,
delete: kEnumerableProperty,
get: kEnumerableProperty,
getAll: kEnumerableProperty,
has: kEnumerableProperty,
set: kEnumerableProperty,
size: kEnumerableProperty,
sort: kEnumerableProperty,
entries: kEnumerableProperty,
forEach: kEnumerableProperty,
keys: kEnumerableProperty,
values: kEnumerableProperty,
toString: kEnumerableProperty,
[SymbolToStringTag]: { __proto__: null, configurable: true, value: 'URLSearchParams' },
// https://heycam.github.io/webidl/#es-iterable-entries
[SymbolIterator]: {
__proto__: null,
configurable: true,
writable: true,
value: URLSearchParams.prototype.entries,
},
});
/**
* Checks if a value has the shape of a WHATWG URL object.
*
* Using a symbol or instanceof would not be able to recognize URL objects
* coming from other implementations (e.g. in Electron), so instead we are
* checking some well known properties for a lack of a better test.
*
* We use `href` and `protocol` as they are the only properties that are
* easy to retrieve and calculate due to the lazy nature of the getters.
*
* We check for auth attribute to distinguish legacy url instance with
* WHATWG URL instance.
* @param {*} self
* @returns {self is URL}
*/
function isURL(self) {
return Boolean(self?.href && self.protocol && self.auth === undefined);
}
class URL {
#context = new URLContext();
#searchParams;
constructor(input, base = undefined) {
if (arguments.length === 0) {
throw new ERR_MISSING_ARGS('url');
}
// toUSVString is not needed.
input = `${input}`;
if (base !== undefined) {
base = `${base}`;
}
const href = bindingUrl.parse(input, base);
if (!href) {
throw new ERR_INVALID_URL(input);
}
this.#updateContext(href);
}
[inspect.custom](depth, opts) {
if (typeof depth === 'number' && depth < 0)
return this;
const constructor = getConstructorOf(this) || URL;
const obj = { __proto__: { constructor } };
obj.href = this.href;
obj.origin = this.origin;
obj.protocol = this.protocol;
obj.username = this.username;
obj.password = this.password;
obj.host = this.host;
obj.hostname = this.hostname;
obj.port = this.port;
obj.pathname = this.pathname;
obj.search = this.search;
obj.searchParams = this.searchParams;
obj.hash = this.hash;
if (opts.showHidden) {
obj[contextForInspect] = this.#context;
}
return `${constructor.name} ${inspect(obj, opts)}`;
}
#updateContext(href) {
this.#context.href = href;
const {
0: protocol_end,
1: username_end,
2: host_start,
3: host_end,
4: port,
5: pathname_start,
6: search_start,
7: hash_start,
8: scheme_type,
} = bindingUrl.urlComponents;
this.#context.protocol_end = protocol_end;
this.#context.username_end = username_end;
this.#context.host_start = host_start;
this.#context.host_end = host_end;
this.#context.port = port;
this.#context.pathname_start = pathname_start;
this.#context.search_start = search_start;
this.#context.hash_start = hash_start;
this.#context.scheme_type = scheme_type;
if (this.#searchParams) {
if (this.#context.hasSearch) {
setURLSearchParams(this.#searchParams, this.search);
} else {
setURLSearchParams(this.#searchParams, undefined);
}
}
}
toString() {
return this.#context.href;
}
get href() {
return this.#context.href;
}
set href(value) {
value = `${value}`;
const href = bindingUrl.update(this.#context.href, updateActions.kHref, value);
if (!href) { throw ERR_INVALID_URL(value); }
this.#updateContext(href);
}
// readonly
get origin() {
const protocol = StringPrototypeSlice(this.#context.href, 0, this.#context.protocol_end);
// Check if scheme_type is not `NOT_SPECIAL`
if (this.#context.scheme_type !== 1) {
// Check if scheme_type is `FILE`
if (this.#context.scheme_type === 6) {
return 'null';
}
return `${protocol}//${this.host}`;
}
if (protocol === 'blob:') {
const path = this.pathname;
if (path.length > 0) {
try {
const out = new URL(path);
// Only return origin of scheme is `http` or `https`
// Otherwise return a new opaque origin (null).
if (out.#context.scheme_type === 0 || out.#context.scheme_type === 2) {
return `${out.protocol}//${out.host}`;
}
} catch {
// Do nothing.
}
}
}
return 'null';
}
get protocol() {
return StringPrototypeSlice(this.#context.href, 0, this.#context.protocol_end);
}
set protocol(value) {
const href = bindingUrl.update(this.#context.href, updateActions.kProtocol, `${value}`);
if (href) {
this.#updateContext(href);
}
}
get username() {
if (this.#context.protocol_end + 2 < this.#context.username_end) {
return StringPrototypeSlice(this.#context.href, this.#context.protocol_end + 2, this.#context.username_end);
}
return '';
}
set username(value) {
const href = bindingUrl.update(this.#context.href, updateActions.kUsername, `${value}`);
if (href) {
this.#updateContext(href);
}
}
get password() {
if (this.#context.host_start - this.#context.username_end > 0) {
return StringPrototypeSlice(this.#context.href, this.#context.username_end + 1, this.#context.host_start);
}
return '';
}
set password(value) {
const href = bindingUrl.update(this.#context.href, updateActions.kPassword, `${value}`);
if (href) {
this.#updateContext(href);
}
}
get host() {
let startsAt = this.#context.host_start;
if (this.#context.href[startsAt] === '@') {
startsAt++;
}
// If we have an empty host, then the space between components.host_end and
// components.pathname_start may be occupied by /.
if (startsAt === this.#context.host_end) {
return '';
}
return StringPrototypeSlice(this.#context.href, startsAt, this.#context.pathname_start);
}
set host(value) {
const href = bindingUrl.update(this.#context.href, updateActions.kHost, `${value}`);
if (href) {
this.#updateContext(href);
}
}
get hostname() {
let startsAt = this.#context.host_start;
// host_start might be "@" if the URL has credentials
if (this.#context.href[startsAt] === '@') {
startsAt++;
}
return StringPrototypeSlice(this.#context.href, startsAt, this.#context.host_end);
}
set hostname(value) {
const href = bindingUrl.update(this.#context.href, updateActions.kHostname, `${value}`);
if (href) {
this.#updateContext(href);
}
}
get port() {
if (this.#context.hasPort) {
return `${this.#context.port}`;
}
return '';
}
set port(value) {
const href = bindingUrl.update(this.#context.href, updateActions.kPort, `${value}`);
if (href) {
this.#updateContext(href);
}
}
get pathname() {
let endsAt;
if (this.#context.hasSearch) {
endsAt = this.#context.search_start;
} else if (this.#context.hasHash) {
endsAt = this.#context.hash_start;
}
return StringPrototypeSlice(this.#context.href, this.#context.pathname_start, endsAt);
}
set pathname(value) {
const href = bindingUrl.update(this.#context.href, updateActions.kPathname, `${value}`);
if (href) {
this.#updateContext(href);
}
}
get search() {
if (!this.#context.hasSearch) { return ''; }
let endsAt = this.#context.href.length;