MCPcopy Create free account
hub / github.com/sindresorhus/query-string / decodeSequence

Function decodeSequence

base.js:328–366  ·  view source on GitHub ↗
(value, position)

Source from the content-addressed store, hash-verified

326
327// Decode the UTF-8 sequence that starts with the percent escape at `position`. The decoded text and the position just past the sequence are returned.
328function decodeSequence(value, position) {
329 const leadByte = readPercentByte(value, position);
330
331 // A `%` that is not followed by two hexadecimal digits is not an escape, so it is kept as it is.
332 if (leadByte === -1) {
333 return ['%', position + 1];
334 }
335
336 const length = utf8SequenceLength(leadByte);
337
338 // A continuation byte with no lead byte in front of it, or a lead byte that can only ever start an invalid sequence.
339 if (length === 0) {
340 return [replacementCharacter, position + 3];
341 }
342
343 // An ASCII byte is its own character.
344 if (length === 1) {
345 return [String.fromCodePoint(leadByte), position + 3];
346 }
347
348 // The lead byte holds the top bits of the code point, and each continuation byte holds six more. The sequence stops when a byte is missing, because the value ends, or is not valid where it sits.
349 // eslint-disable-next-line no-bitwise -- Unpacking a UTF-8 sequence is bit arithmetic by definition.
350 let codePoint = leadByte & (0x7F >> length);
351 let offset = 1;
352
353 while (offset < length) {
354 const byte = readPercentByte(value, position + (offset * 3));
355 if (!(offset === 1 ? isValidSecondByte(leadByte, byte) : (byte >= 0x80 && byte <= 0xBF))) {
356 // What was read before the sequence stopped is consumed together with it, so `%E4%80%41` is one replacement character and then `A` rather than a replacement character for every byte.
357 return [replacementCharacter, position + (offset * 3)];
358 }
359
360 // eslint-disable-next-line no-bitwise -- Unpacking a UTF-8 sequence is bit arithmetic by definition.
361 codePoint = (codePoint << 6) | (byte & 0x3F);
362 offset++;
363 }
364
365 return [String.fromCodePoint(codePoint), position + (length * 3)];
366}
367
368// Decode the percent escapes in `value`, like `URLSearchParams` does.
369//

Callers 1

decodeComponentFunction · 0.85

Calls 3

readPercentByteFunction · 0.85
utf8SequenceLengthFunction · 0.85
isValidSecondByteFunction · 0.85

Tested by

no test coverage detected