Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
709 lines (639 loc) · 25.2 KB
/
Copy pathindex.js
File metadata and controls
709 lines (639 loc) · 25.2 KB
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
'use strict'
const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, encodeHost, isIPv4, nonSimpleDomain } = require('./lib/utils')
const { SCHEMES, getSchemeHandler } = require('./lib/schemes')
const VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u
const MALFORMED_SCHEME_ERROR = 'URI scheme is malformed.'
/**
* @param {string} scheme
* @returns {string}
*/
function decodeValidScheme (scheme) {
const decodedScheme = unescape(String(scheme))
if (!VALID_SCHEME.test(decodedScheme)) {
throw new TypeError(MALFORMED_SCHEME_ERROR)
}
return decodedScheme
}
/**
* @template {import('./types/index').URIComponent|string} T
* @param {T} uri
* @param {import('./types/index').Options} [options]
* @returns {T}
*/
function normalize (uri, options) {
if (typeof uri === 'string') {
uri = /** @type {T} */ (normalizeString(uri, options))
} else if (typeof uri === 'object') {
uri = /** @type {T} */ (parse(serialize(uri, options), options))
}
return uri
}
/**
* @param {string} baseURI
* @param {string} relativeURI
* @param {import('./types/index').Options} [options]
* @returns {string}
*/
function resolve (baseURI, relativeURI, options) {
const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' }
const {
parsed: baseParsed,
malformedAuthorityOrPort: baseMalformed,
malformedReferenceEdge: baseMalformedReferenceEdge,
malformedPercentEncoding: baseMalformedPercentEncoding,
malformedSchemeSpecific: baseMalformedSchemeSpecific,
malformedHost: baseMalformedHost,
malformedScheme: baseMalformedScheme
} = parseWithStatus(baseURI, schemelessOptions)
const {
parsed: relativeParsed,
malformedAuthorityOrPort: relativeMalformed,
malformedReferenceEdge: relativeMalformedReferenceEdge,
malformedPercentEncoding: relativeMalformedPercentEncoding,
malformedSchemeSpecific: relativeMalformedSchemeSpecific,
malformedHost: relativeMalformedHost,
malformedScheme: relativeMalformedScheme
} = parseWithStatus(relativeURI, schemelessOptions)
if (
baseMalformed ||
relativeMalformed ||
baseMalformedReferenceEdge ||
relativeMalformedReferenceEdge ||
baseMalformedPercentEncoding ||
relativeMalformedPercentEncoding ||
baseMalformedSchemeSpecific ||
relativeMalformedSchemeSpecific ||
baseMalformedHost ||
relativeMalformedHost ||
baseMalformedScheme ||
relativeMalformedScheme
) {
throw new Error(baseParsed.error || relativeParsed.error || 'URI is malformed.')
}
const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true)
const resolvedSchemeHandler = getSchemeHandler((options && options.scheme) || resolved.scheme)
const resolvedHost = resolved.host
// Inputs are parsed scheme-neutrally during resolution, so enforce the final
// HTTP scheme's required host before serializing an invalid HTTP URI.
if (
(resolved.scheme === 'http' || resolved.scheme === 'https') &&
!resolvedHost
) {
throw new Error('HTTP URIs must have a host.')
}
const resolvedHostIsIP = resolvedHost !== undefined && resolvedHost !== '' &&
(isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6)
canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP)
// Percent escapes in an ASCII reg-name are encoded data. The WHATWG hostname
// parser can reject them even though fast-uri preserves them safely as RFC
// 3986 data. A raw non-ASCII host must still fail closed if conversion fails.
const encodedASCIIHost = resolvedHost && resolvedHost.indexOf('%') !== -1 &&
!/\P{ASCII}/u.test(resolvedHost)
if (resolved.error && !encodedASCIIHost) {
throw new Error(resolved.error)
}
schemelessOptions.skipEscape = true
if (resolvedSchemeHandler && resolvedSchemeHandler.absolutePath) {
schemelessOptions.absolutePath = true
}
return serialize(resolved, schemelessOptions)
}
/**
* Copies a host component together with its parse-time zone identifier (if
* any), so downstream recomposition does not re-derive an IPv6 zone from the
* ambiguous single-"%" component form. The zone is validated on use by
* `recomposeAuthority` rather than blindly trusted.
*
* @param {import('./types/index').URIComponent} target
* @param {import('./types/index').URIComponent} source
*/
function copyHost (target, source) {
target.host = source.host
if (source.ipv6Zone !== undefined) {
target.ipv6Zone = source.ipv6Zone
}
}
/**
* @param {import ('./types/index').URIComponent} base
* @param {import ('./types/index').URIComponent} relative
* @param {import('./types/index').Options} [options]
* @param {boolean} [skipNormalization=false]
* @returns {import ('./types/index').URIComponent}
*/
function resolveComponent (base, relative, options, skipNormalization) {
/** @type {import('./types/index').URIComponent} */
const target = {}
if (!skipNormalization) {
base = parse(serialize(base, options), options) // normalize base component
relative = parse(serialize(relative, options), options) // normalize relative component
}
options = options || {}
if (!options.tolerant && relative.scheme) {
target.scheme = relative.scheme
// target.authority = relative.authority;
target.userinfo = relative.userinfo
copyHost(target, relative)
target.port = relative.port
const relativeSchemeHandler = getSchemeHandler(relative.scheme)
target.path = relativeSchemeHandler && relativeSchemeHandler.absolutePath
? relative.path || ''
: removeDotSegments(relative.path || '')
target.query = relative.query
} else {
if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
// target.authority = relative.authority;
target.userinfo = relative.userinfo
copyHost(target, relative)
target.port = relative.port
target.path = removeDotSegments(relative.path || '')
target.query = relative.query
} else {
if (!relative.path) {
target.path = base.path
if (relative.query !== undefined) {
target.query = relative.query
} else {
target.query = base.query
}
} else {
if (relative.path[0] === '/') {
target.path = removeDotSegments(relative.path)
} else {
if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {
target.path = '/' + relative.path
} else if (!base.path) {
target.path = relative.path
} else {
target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path
}
target.path = removeDotSegments(target.path)
}
target.query = relative.query
}
// target.authority = base.authority;
target.userinfo = base.userinfo
copyHost(target, base)
target.port = base.port
}
target.scheme = base.scheme
}
target.fragment = relative.fragment
return target
}
/**
* @param {import ('./types/index').URIComponent|string} uriA
* @param {import ('./types/index').URIComponent|string} uriB
* @param {import ('./types/index').Options} options
* @returns {boolean}
*/
function equal (uriA, uriB, options) {
const normalizedA = normalizeComparableURI(uriA, options)
const normalizedB = normalizeComparableURI(uriB, options)
return normalizedA !== undefined && normalizedB !== undefined && normalizedA === normalizedB
}
/**
* @param {Readonly<import('./types/index').URIComponent>} cmpts
* @param {import('./types/index').Options} [opts]
* @returns {string}
*/
function serialize (cmpts, opts) {
const component = {
host: cmpts.host,
ipv6Zone: cmpts.ipv6Zone,
scheme: cmpts.scheme,
userinfo: cmpts.userinfo,
port: cmpts.port,
path: cmpts.path,
query: cmpts.query,
nid: cmpts.nid,
nss: cmpts.nss,
uuid: cmpts.uuid,
fragment: cmpts.fragment,
reference: cmpts.reference,
resourceName: cmpts.resourceName,
secure: cmpts.secure,
to: cmpts.to,
subject: cmpts.subject,
body: cmpts.body,
headers: cmpts.headers,
error: ''
}
const options = Object.assign({}, opts)
const uriTokens = []
if (component.scheme) {
component.scheme = decodeValidScheme(component.scheme)
}
// find scheme handler
const schemeHandler = getSchemeHandler(options.scheme || component.scheme)
// perform scheme specific serialization
if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options)
const hasAuthority = component.userinfo !== undefined || component.host !== undefined || component.port !== undefined
const pathNoScheme = !options.skipEscape && component.scheme === undefined && !hasAuthority
if (component.path !== undefined) {
if (!options.skipEscape) {
component.path = serializePathEncoding(component.path, pathNoScheme)
} else {
component.path = normalizePercentEncoding(component.path)
}
}
if (options.reference !== 'suffix' && component.scheme) {
// Scheme handlers may replace the scheme during serialization.
component.scheme = decodeValidScheme(component.scheme)
uriTokens.push(component.scheme, ':')
}
const allowNonAsciiHost = options.unicodeSupport === true || Boolean(schemeHandler && schemeHandler.unicodeSupport)
const authority = recomposeAuthority(component, allowNonAsciiHost)
if (authority !== undefined) {
if (options.reference !== 'suffix') {
uriTokens.push('//')
}
uriTokens.push(authority)
if (component.path && component.path[0] !== '/') {
uriTokens.push('/')
}
}
if (component.path !== undefined) {
let s = component.path
if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
s = removeDotSegments(s)
}
// Dot-segment removal can expose a colon that was not originally in the
// first segment (for example, "./a:b"). Reapply path-noscheme encoding so
// the serialized relative reference cannot be reparsed as a URI scheme.
if (pathNoScheme) {
s = serializePathEncoding(s, true)
}
if (
authority === undefined &&
s[0] === '/' &&
s[1] === '/'
) {
// don't allow the path to start with "//"
s = '/%2F' + s.slice(2)
}
uriTokens.push(s)
}
if (component.query !== undefined) {
uriTokens.push('?', encodeQuery(component.query))
}
if (component.fragment !== undefined) {
uriTokens.push('#', encodeFragment(component.fragment))
}
return uriTokens.join('')
}
const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u
// Captures the authority component (between "//" and the next "/", "?" or "#"),
// with or without a scheme prefix, for the literal-backslash rejection below.
const AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/
// Captures the leading authority-introducer region after an optional scheme: a
// run of forward slashes, backslashes, and the characters the WHATWG URL parser
// removes before parsing (TAB U+0009, LF U+000A, CR U+000D). A valid introducer
// is exactly "//". Node treats "\" as "/" on special schemes and strips those
// characters first, so forms like "\\", "/\", "\/", "/<TAB>/", or a leading
// "<TAB>//" reach an authority in Node while fast-uri's URI_PARSE folds them into
// the path group (host confusion / SSRF / redirect bypass).
const AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/
/**
* @param {import('./types/index').URIComponent} parsed
* @param {RegExpMatchArray} matches
* @returns {string|undefined}
*/
function getParseError (parsed, matches) {
if (matches[2] !== undefined && parsed.path && parsed.path[0] !== '/') {
return 'URI path must start with "/" when authority is present.'
}
if (typeof parsed.port === 'number' && (parsed.port < 0 || parsed.port > 65535)) {
return 'URI port is malformed.'
}
return undefined
}
/**
* Checks percent syntax without decoding the represented octets. RFC 3986
* percent-encoding is byte-oriented, so sequences such as `%FF` are valid even
* though they are not independently valid UTF-8.
*
* @param {string|undefined} component
* @returns {boolean}
*/
function hasMalformedPercentEncoding (component) {
if (component === undefined) return false
let percent = component.indexOf('%')
while (percent !== -1) {
if (percent + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) {
return true
}
percent = component.indexOf('%', percent + 3)
}
return false
}
/**
* Whether the host is a bracketed IP literal (RFC 3986 `IP-literal`).
* An unterminated `[` is not a literal, so it must still be validated as a
* reg-name instead of being waved through as an IP.
*
* @param {string} host
* @returns {boolean}
*/
function isIPLiteral (host) {
return host[0] === '[' && host[host.length - 1] === ']'
}
/**
* @param {RegExpMatchArray} matches
* @returns {boolean}
*/
function hasMalformedComponentPercentEncoding (matches) {
// Bracketed IP literals use a raw "%" as the zone separator for historical
// compatibility. Their parsing is intentionally left to normalizeIPv6.
const host = matches[4]
return hasMalformedPercentEncoding(matches[3]) ||
(host !== undefined && !isIPLiteral(host) && hasMalformedPercentEncoding(host)) ||
hasMalformedPercentEncoding(matches[6]) ||
hasMalformedPercentEncoding(matches[7]) ||
hasMalformedPercentEncoding(matches[8])
}
/**
* @param {import('./types/index').URIComponent} parsed
* @param {import('./types/index').Options} options
* @param {{ domainHost?: boolean, unicodeSupport?: boolean }|undefined} schemeHandler
* @param {boolean} isIP
* @returns {boolean} whether host conversion failed
*/
function canonicalizeHost (parsed, options, schemeHandler, isIP) {
const bracketedIPLiteral =
parsed.host &&
parsed.host[0] === '[' &&
parsed.host[parsed.host.length - 1] === ']'
if (
!options.unicodeSupport &&
(!schemeHandler || !schemeHandler.unicodeSupport) &&
parsed.host &&
!isIPLiteral(parsed.host) &&
(options.domainHost || (schemeHandler && schemeHandler.domainHost)) &&
isIP === false &&
!bracketedIPLiteral &&
nonSimpleDomain(parsed.host)
) {
try {
parsed.host = new URL('http://' + parsed.host).hostname
} catch (e) {
parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e
return true
}
}
return false
}
/**
* @param {string} uri
* @param {import('./types/index').Options} [opts]
* @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean, malformedReferenceEdge: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}
*/
function parseWithStatus (uri, opts) {
const options = Object.assign({}, opts)
/** @type {import('./types/index').URIComponent} */
const parsed = {
scheme: undefined,
userinfo: undefined,
host: '',
port: undefined,
path: '',
query: undefined,
fragment: undefined
}
let malformedAuthorityOrPort = false
// Check the caller's original reference before suffix mode prepends a scheme
// or authority marker and turns its leading edge into interior data.
const malformedReferenceEdge = uri.length !== 0 && (
uri.charCodeAt(0) <= 0x20 ||
uri.charCodeAt(uri.length - 1) <= 0x20
)
let malformedPercentEncoding = false
let malformedSchemeSpecific = false
let malformedHost = false
let malformedIPLiteral = false
let malformedScheme = false
let isIP = false
if (options.reference === 'suffix') {
if (options.scheme) {
uri = options.scheme + ':' + uri
} else {
uri = '//' + uri
}
}
// A literal backslash (U+005C) is not a valid RFC 3986 URI character and is
// not an authority delimiter. Reject it in the authority rather than
// rewriting it: normalizing "\" -> "/" (WHATWG error recovery) could silently
// change the resource identified by an otherwise-invalid input, and lets "\"
// act as a host delimiter here while Node's native URL parses a different
// host (SSRF / redirect / origin-allowlist bypass). Percent-encoded %5C is
// untouched and remains valid encoded data.
const authorityMatch = uri.match(AUTHORITY_PREFIX)
if (authorityMatch !== null && authorityMatch[1].indexOf('\\') !== -1) {
parsed.error = 'URI authority must not contain a literal backslash.'
malformedAuthorityOrPort = true
}
// Reject a malformed or whitespace-smuggled authority introducer. fast-uri
// only recognizes a literal "//"; anything else in the leading separator run
// (a backslash, or a "//" that appears only after removing the TAB/LF/CR that
// Node strips) means the authority fast-uri parses differs from the one Node's
// URL resolves. Reject rather than rewrite, mirroring the literal-backslash
// guard above. Percent-encoded forms (%5C, %09) are untouched, valid data.
const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION)
if (introducerMatch !== null) {
const region = introducerMatch[1]
const normalizedRegion = region.replace(/[\t\n\r]/g, '')
// Two or more leading separators introduce an authority.
if (normalizedRegion.length >= 2) {
if (normalizedRegion.slice(0, 2) !== '//') {
parsed.error = parsed.error || 'URI authority must not contain a literal backslash.'
malformedAuthorityOrPort = true
} else if (region.length !== normalizedRegion.length) {
parsed.error = parsed.error || 'URI authority introducer must not contain whitespace.'
malformedAuthorityOrPort = true
}
}
}
if (malformedReferenceEdge) {
parsed.error = parsed.error || 'URI must not contain leading or trailing C0 controls or spaces.'
}
const matches = uri.match(URI_PARSE)
if (matches) {
// store each component
parsed.scheme = matches[1]
parsed.userinfo = matches[3]
parsed.host = matches[4]
parsed.port = parseInt(matches[5], 10)
parsed.path = matches[6] || ''
parsed.query = matches[7]
parsed.fragment = matches[8]
if (parsed.scheme !== undefined) {
const decodedScheme = unescape(parsed.scheme)
if (VALID_SCHEME.test(decodedScheme)) {
parsed.scheme = decodedScheme.toLowerCase()
} else {
parsed.error = parsed.error || MALFORMED_SCHEME_ERROR
malformedScheme = true
}
}
malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches)
if (malformedPercentEncoding) {
parsed.error = parsed.error || 'URI contains malformed percent-encoding.'
}
// fix port number
if (isNaN(parsed.port)) {
parsed.port = matches[5]
}
const parseError = getParseError(parsed, matches)
if (parseError !== undefined) {
parsed.error = parsed.error || parseError
malformedAuthorityOrPort = true
}
if (parsed.host) {
const ipv4result = isIPv4(parsed.host)
if (ipv4result === false) {
const bracketedIPLiteral = isIPLiteral(parsed.host)
const hasIPLiteralBracket = parsed.host.indexOf('[') !== -1 || parsed.host.indexOf(']') !== -1
const ipv6result = normalizeIPv6(parsed.host)
isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true
malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true)
parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase()
if (isIP && ipv6result.isIPV6 === true && parsed.host.indexOf('%') !== -1) {
// Persist the zone identifier so recomposition never has to re-derive
// it from the ambiguous single-"%" component form, which misreads a
// zone that begins with "25" as a %25 separator. It is validated on
// use during recomposition, so a host reassigned after parse or an
// input zone that does not describe the host is ignored. Only zoned
// literals are ambiguous; plain IPv6 addresses round-trip without it.
parsed.ipv6Zone = parsed.host.slice(parsed.host.indexOf('%') + 1)
}
if (malformedIPLiteral) {
parsed.error = parsed.error || 'URI host is malformed.'
malformedAuthorityOrPort = true
}
} else {
isIP = true
}
}
if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {
parsed.reference = 'same-document'
} else if (parsed.scheme === undefined) {
parsed.reference = 'relative'
} else if (parsed.fragment === undefined) {
parsed.reference = 'absolute'
} else {
parsed.reference = 'uri'
}
// check for reference errors
if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {
parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'
}
// find scheme handler
const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme)
// convert Unicode IDN -> ASCII IDN when the effective scheme uses domain hosts
if (!malformedIPLiteral) {
malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP)
}
if (parsed.host !== undefined && !malformedIPLiteral) {
let host = parsed.host
if (uri.indexOf('%') !== -1 && !isIP) {
host = normalizePercentEncoding(host, true)
// Fold reg-name case after decoding unreserved octets. The second
// pass only restores uppercase hex in escapes that remain encoded.
host = normalizePercentEncoding(host.toLowerCase())
}
// Resolution parses both inputs with the internal `null` scheme before
// the effective scheme is known. Preserve raw host characters for that
// intermediate step so the final scheme can apply domain canonicalization;
// the resolved authority is encoded when it is serialized.
if (options.scheme !== 'null') {
const allowNonAsciiHost = options.unicodeSupport === true || Boolean(schemeHandler && schemeHandler.unicodeSupport)
parsed.host = encodeHost(host, isIP, allowNonAsciiHost)
} else {
parsed.host = host
}
}
if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {
if (parsed.path) {
parsed.path = normalizePathEncoding(parsed.path)
}
if (parsed.query) {
parsed.query = normalizeQueryFragmentEncoding(parsed.query)
}
if (parsed.fragment) {
parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment)
}
}
// perform scheme specific parsing
if (schemeHandler && schemeHandler.parse) {
schemeHandler.parse(parsed, options)
if (schemeHandler === SCHEMES.urn && parsed.nid === undefined) {
malformedSchemeSpecific = true
}
}
} else {
parsed.error = parsed.error || 'URI can not be parsed.'
}
return { parsed, malformedAuthorityOrPort, malformedReferenceEdge, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme }
}
/**
* @param {string} uri
* @param {import('./types/index').Options} [opts]
* @returns
*/
function parse (uri, opts) {
return parseWithStatus(uri, opts).parsed
}
/**
* @param {string} uri
* @param {import('./types/index').Options} [opts]
* @returns {string}
*/
function normalizeString (uri, opts) {
return normalizeStringWithStatus(uri, opts).normalized
}
/**
* @param {string} uri
* @param {import('./types/index').Options} [opts]
* @returns {{ normalized: string, malformedAuthorityOrPort: boolean, malformedReferenceEdge: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}
*/
function normalizeStringWithStatus (uri, opts) {
const { parsed, malformedAuthorityOrPort, malformedReferenceEdge, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts)
return {
normalized: malformedAuthorityOrPort || malformedReferenceEdge || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts),
malformedAuthorityOrPort,
malformedReferenceEdge,
malformedPercentEncoding,
malformedSchemeSpecific,
malformedHost,
malformedScheme
}
}
/**
* @param {import ('./types/index').URIComponent|string} uri
* @param {import('./types/index').Options} [opts]
* @returns {string|undefined}
*/
function normalizeComparableURI (uri, opts) {
if (typeof uri !== 'string' && typeof uri !== 'object') {
return undefined
}
let value
try {
value = typeof uri === 'string' ? uri : serialize(uri, opts)
} catch {
return undefined
}
const { normalized, malformedAuthorityOrPort, malformedReferenceEdge, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts)
return malformedAuthorityOrPort || malformedReferenceEdge || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? undefined : normalized
}
const fastUri = {
SCHEMES,
normalize,
resolve,
resolveComponent,
equal,
serialize,
parse
}
module.exports = fastUri
module.exports.default = fastUri
module.exports.fastUri = fastUri