Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Encoding.ts

889 lines20.8 KB

1/**
2 * Encoding and decoding helpers for Base64, Base64Url, and hexadecimal text.
3 * The functions convert between strings, UTF-8 text, and `Uint8Array` bytes.
4 * Encode functions return strings directly, while decode functions return
5 * `Result.Result` so invalid input is reported as an `EncodingError` instead of
6 * being thrown.
7 *
8 * @since 4.0.0
9 */
10import * as Data from "./Data.ts"
11import { hasProperty } from "./Predicate.ts"
12import * as Result from "./Result.ts"
13​
14// -------------------------------------------------------------------------------------
15// EncodingError
16// -------------------------------------------------------------------------------------
17​
18/**
19 * Type identifier stored on `EncodingError` values and used by
20 * `isEncodingError`.
21 *
22 * **When to use**
23 *
24 * Use when implementing low-level `EncodingError`-compatible values that need
25 * to carry the runtime marker.
26 *
27 * **Details**
28 *
29 * This marker is part of the runtime representation of `EncodingError`. Prefer
30 * `isEncodingError` when narrowing unknown values.
31 *
32 * @see {@link isEncodingError} for the public guard that checks this marker
33 *
34 * @category type IDs
35 * @since 4.0.0
36 */
37export const EncodingErrorTypeId = "~effect/Encoding/EncodingError" as const
38​
39/**
40 * Literal type of the `EncodingErrorTypeId` marker.
41 *
42 * **When to use**
43 *
44 * Use to type the marker carried by `EncodingError` values.
45 *
46 * @category type IDs
47 * @since 4.0.0
48 */
49export type EncodingErrorTypeId = typeof EncodingErrorTypeId
50​
51/**
52 * Error returned when an encoding or decoding operation cannot process its
53 * input.
54 *
55 * **When to use**
56 *
57 * Use when you need to handle or inspect failures from encoding or decoding
58 * operations.
59 *
60 * **Details**
61 *
62 * The error records whether the failure happened during encoding or decoding,
63 * which encoding module reported it, the original input, and a human-readable
64 * message.
65 *
66 * @see {@link isEncodingError} for checking whether a value is an EncodingError
67 * @category errors
68 * @since 4.0.0
69 */
70export class EncodingError extends Data.TaggedError("EncodingError")<{
71 kind: "Decode" | "Encode"
72 module: string
73 input: unknown
74 message: string
75}> {
76 /**
77 * Marks this value as an encoding or decoding error for runtime guards.
78 *
79 * **When to use**
80 *
81 * Use to identify `EncodingError` instances through `isEncodingError`.
82 *
83 * @since 4.0.0
84 */
85 readonly [EncodingErrorTypeId]: EncodingErrorTypeId = EncodingErrorTypeId
87​
88/**
89 * Checks whether a value is an `EncodingError`.
90 *
91 * **When to use**
92 *
93 * Use to narrow an unknown value before handling it as an `EncodingError` from
94 * encoding or decoding code.
95 *
96 * **Details**
97 *
98 * Returns `true` when the value carries the `EncodingErrorTypeId` marker and
99 * narrows the value to `EncodingError`.
100 *
101 * @see {@link EncodingError} for the structured error produced by failed
102 * encoding and decoding operations
103 *
104 * @category guards
105 * @since 4.0.0
106 */
107export const isEncodingError = (u: unknown): u is EncodingError => hasProperty(u, EncodingErrorTypeId)
108​
109// -------------------------------------------------------------------------------------
110// Base64
111// -------------------------------------------------------------------------------------
112​
113/**
114 * Encodes the given value into a base64 (RFC4648) `string`.
115 *
116 * **When to use**
117 *
118 * Use to encode text or bytes as a standard padded Base64 string for storage or
119 * transport.
120 *
121 * **Details**
122 *
123 * String inputs are encoded as UTF-8 bytes before Base64 encoding.
124 * `Uint8Array` inputs are encoded directly. The output uses the standard
125 * RFC4648 alphabet with `=` padding.
126 *
127 * **Example** (Encoding Base64 strings and bytes)
128 *
129 * ```ts import.meta.vitest
130 * import { Encoding } from "effect"
131 *
132 * // Encode a string
133 * Encoding.encodeBase64("hello") // => "aGVsbG8="
134 *
135 * // Encode binary data
136 * const bytes = new Uint8Array([72, 101, 108, 108, 111])
137 * Encoding.encodeBase64(bytes) // => "SGVsbG8="
138 * ```
139 *
140 * @see {@link decodeBase64} for decoding standard Base64 to bytes
141 * @see {@link decodeBase64String} for decoding standard Base64 to UTF-8 text
142 * @see {@link encodeBase64Url} for URL-safe unpadded Base64 output
143 *
144 * @category encoding
145 * @since 2.0.0
146 */
147export const encodeBase64: (input: Uint8Array | string) => string = (input) =>
148 typeof input === "string" ? base64EncodeUint8Array(encoder.encode(input)) : base64EncodeUint8Array(input)
149​
150/**
151 * Decodes a base64 (RFC4648) string into bytes safely.
152 *
153 * **When to use**
154 *
155 * Use to decode a standard padded Base64 string into bytes without throwing on
156 * invalid input.
157 *
158 * **Details**
159 *
160 * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or
161 * `Result.fail` with an `EncodingError` when the input is not valid base64.
162 *
163 * **Example** (Decoding Base64 bytes)
164 *
165 * ```ts import.meta.vitest
166 * import { Encoding, Result } from "effect"
167 *
168 * Encoding.decodeBase64("SGVsbG8=") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111]))
169 * ```
170 *
171 * @category decoding
172 * @since 2.0.0
173 */
174export const decodeBase64 = (str: string): Result.Result<Uint8Array, EncodingError> => {
175 const stripped = stripCrlf(str)
176 const length = stripped.length
177 if (length % 4 !== 0) {
178 return Result.fail(
179 new EncodingError({
180 kind: "Decode",
181 module: "Base64",
182 input: stripped,
183 message: `Length must be a multiple of 4, but is ${length}`
184 })
185 )
186 }
187​
188 const index = stripped.indexOf("=")
189 if (index !== -1 && ((index < length - 2) || (index === length - 2 && stripped[length - 1] !== "="))) {
190 return Result.fail(
191 new EncodingError({
192 kind: "Decode",
193 module: "Base64",
194 input: stripped,
195 message: `Found a '=' character, but it is not at the end`
196 })
197 )
198 }
199​
200 try {
201 const missingOctets = stripped.endsWith("==") ? 2 : stripped.endsWith("=") ? 1 : 0
202 const result = new Uint8Array(3 * (length / 4) - missingOctets)
203 for (let i = 0, j = 0; i < length; i += 4, j += 3) {
204 const buffer = getBase64Code(stripped.charCodeAt(i)) << 18 |
205 getBase64Code(stripped.charCodeAt(i + 1)) << 12 |
206 getBase64Code(stripped.charCodeAt(i + 2)) << 6 |
207 getBase64Code(stripped.charCodeAt(i + 3))
208​
209 result[j] = buffer >> 16
210 result[j + 1] = (buffer >> 8) & 0xff
211 result[j + 2] = buffer & 0xff
212 }
213​
214 return Result.succeed(result)
215 } catch (e) {
216 return Result.fail(
217 new EncodingError({
218 kind: "Decode",
219 module: "Base64",
220 input: stripped,
221 message: e instanceof Error ? e.message : "Invalid input"
222 })
223 )
224 }
226​
227/**
228 * Decodes a base64 (RFC4648) string into a UTF-8 string safely.
229 *
230 * **When to use**
231 *
232 * Use to decode a standard padded Base64 string into UTF-8 text without
233 * throwing on invalid input.
234 *
235 * **Details**
236 *
237 * Returns `Result.succeed` with the decoded text when decoding succeeds, or
238 * `Result.fail` with an `EncodingError` when the input is not valid base64.
239 *
240 * **Example** (Decoding Base64 strings)
241 *
242 * ```ts import.meta.vitest
243 * import { Encoding, Result } from "effect"
244 *
245 * Encoding.decodeBase64String("aGVsbG8=") // => Result.succeed("hello")
246 * ```
247 *
248 * @category decoding
249 * @since 2.0.0
250 */
251export const decodeBase64String = (str: string) => Result.map(decodeBase64(str), (_) => decoder.decode(_))
252​
253// -------------------------------------------------------------------------------------
254// Base64Url
255// -------------------------------------------------------------------------------------
256​
257/**
258 * Encodes the given value into a base64 (URL) `string`.
259 *
260 * **When to use**
261 *
262 * Use to encode text or bytes as an unpadded Base64Url string for contexts that
263 * require the URL-safe alphabet.
264 *
265 * **Details**
266 *
267 * String inputs are encoded as UTF-8 bytes before Base64Url encoding.
268 * `Uint8Array` inputs are encoded directly. The output removes `=` padding and
269 * replaces `+` with `-` and `/` with `_`.
270 *
271 * **Example** (Encoding URL-safe Base64)
272 *
273 * ```ts import.meta.vitest
274 * import { Encoding } from "effect"
275 *
276 * // URL-safe base64 encoding (uses - and _ instead of + and /)
277 * Encoding.encodeBase64Url("hello?") // => "aGVsbG8_"
278 *
279 * const bytes = new Uint8Array([72, 101, 108, 108, 111, 63])
280 * Encoding.encodeBase64Url(bytes) // => "SGVsbG8_"
281 * ```
282 *
283 * @see {@link decodeBase64Url} for decoding URL-safe Base64 to bytes
284 * @see {@link decodeBase64UrlString} for decoding URL-safe Base64 to UTF-8 text
285 * @see {@link encodeBase64} for standard padded Base64 output
286 *
287 * @category encoding
288 * @since 2.0.0
289 */
290export const encodeBase64Url: (input: Uint8Array | string) => string = (input) =>
291 typeof input === "string" ? base64UrlEncodeUint8Array(encoder.encode(input)) : base64UrlEncodeUint8Array(input)
292​
293/**
294 * Decodes a URL-safe base64 string into bytes safely.
295 *
296 * **When to use**
297 *
298 * Use to decode padded or unpadded Base64Url text into bytes without throwing
299 * on invalid input.
300 *
301 * **Details**
302 *
303 * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or
304 * `Result.fail` with an `EncodingError` when the input is not valid URL-safe
305 * base64. Both padded and unpadded URL-safe base64 forms are accepted when
306 * otherwise valid.
307 *
308 * **Example** (Decoding URL-safe Base64 bytes)
309 *
310 * ```ts import.meta.vitest
311 * import { Encoding, Result } from "effect"
312 *
313 * Encoding.decodeBase64Url("SGVsbG8_") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111, 63]))
314 * ```
315 *
316 * @category decoding
317 * @since 2.0.0
318 */
319export const decodeBase64Url = (str: string): Result.Result<Uint8Array, EncodingError> => {
320 const stripped = stripCrlf(str)
321 const length = stripped.length
322 if (length % 4 === 1) {
323 return Result.fail(
324 new EncodingError({
325 module: "Base64Url",
326 kind: "Decode",
327 input: stripped,
328 message: `Length should be a multiple of 4, but is ${length}`
329 })
330 )
331 }
332​
333 if (!/^[-_A-Z0-9]*?={0,2}$/i.test(stripped)) {
334 return Result.fail(
335 new EncodingError({
336 module: "Base64Url",
337 kind: "Decode",
338 input: stripped,
339 message: "Invalid input"
340 })
341 )
342 }
343​
344 // Some variants allow or require omitting the padding '=' signs
345 let sanitized = length % 4 === 2 ? `${stripped}==` : length % 4 === 3 ? `${stripped}=` : stripped
346 sanitized = sanitized.replace(/-/g, "+").replace(/_/g, "/")
347​
348 return decodeBase64(sanitized)
350​
351/**
352 * Decodes a URL-safe base64 string into a UTF-8 string safely.
353 *
354 * **When to use**
355 *
356 * Use to decode padded or unpadded Base64Url text into UTF-8 text without
357 * throwing on invalid input.
358 *
359 * **Details**
360 *
361 * Returns `Result.succeed` with the decoded text when decoding succeeds, or
362 * `Result.fail` with an `EncodingError` when the input is not valid URL-safe
363 * base64.
364 *
365 * **Example** (Decoding URL-safe Base64 strings)
366 *
367 * ```ts import.meta.vitest
368 * import { Encoding, Result } from "effect"
369 *
370 * Encoding.decodeBase64UrlString("aGVsbG8_") // => Result.succeed("hello?")
371 * ```
372 *
373 * @category decoding
374 * @since 2.0.0
375 */
376export const decodeBase64UrlString = (str: string) => Result.map(decodeBase64Url(str), (_) => decoder.decode(_))
377​
378// -------------------------------------------------------------------------------------
379// Hex
380// -------------------------------------------------------------------------------------
381​
382/**
383 * Encodes the given value into a hex `string`.
384 *
385 * **When to use**
386 *
387 * Use to encode text or bytes as lowercase hexadecimal text.
388 *
389 * **Example** (Encoding hex strings and bytes)
390 *
391 * ```ts import.meta.vitest
392 * import { Encoding } from "effect"
393 *
394 * // Encode a string to hex
395 * Encoding.encodeHex("hello") // => "68656c6c6f"
396 *
397 * // Encode binary data to hex
398 * const bytes = new Uint8Array([72, 101, 108, 108, 111])
399 * Encoding.encodeHex(bytes) // => "48656c6c6f"
400 * ```
401 *
402 * @category encoding
403 * @since 2.0.0
404 */
405export const encodeHex: (input: Uint8Array | string) => string = (input) =>
406 typeof input === "string" ? hexEncodeUint8Array(encoder.encode(input)) : hexEncodeUint8Array(input)
407​
408/**
409 * Generates a random lowercase hexadecimal string, optimized for lengths that
410 * are multiples of 8.
411 *
412 * **Details**
413 *
414 * `length` is not validated. The function generates `length >>> 3` random
415 * 8-character words, so non-negative lengths below `2 ** 32` are rounded down
416 * to a multiple of 8 and other values follow JavaScript's unsigned 32-bit
417 * coercion rules.
418 *
419 * This function uses `Math.random()` and is not cryptographically secure. For
420 * security-sensitive values, use the `Crypto.Crypto` service's `randomBytes`
421 * method and encode the result with {@link encodeHex}.
422 *
423 * @category encoding
424 * @since 4.0.0
425 */
426export const randomHex = (length: number): string => {
427 switch (length) {
428 case 16:
429 return randomHex16()
430 case 32:
431 return randomHex32()
432 default: {
433 let result = ""
434 for (let i = length >>> 3; i > 0; i--) {
435 result += randomHex8()
436 }
437 return result
438 }
439 }
441​
442const hexCharCodes = Uint8Array.from("0123456789abcdef", (c) => c.charCodeAt(0))
443​
444const randomWord = (): number => (Math.random() * 0x100000000) >>> 0
445​
446// Trace and span identifiers are the common lengths. A single
447// String.fromCharCode call produces a flat string, which avoids rope
448// flattening when the identifier is later serialized.
449const randomHex8 = (): string => {
450 const a = randomWord()
451 return String.fromCharCode(
452 hexCharCodes[a >>> 28],
453 hexCharCodes[(a >>> 24) & 15],
454 hexCharCodes[(a >>> 20) & 15],
455 hexCharCodes[(a >>> 16) & 15],
456 hexCharCodes[(a >>> 12) & 15],
457 hexCharCodes[(a >>> 8) & 15],
458 hexCharCodes[(a >>> 4) & 15],
459 hexCharCodes[a & 15]
460 )
462​
463const randomHex16 = (): string => {
464 const a = randomWord()
465 const b = randomWord()
466 return String.fromCharCode(
467 hexCharCodes[a >>> 28],
468 hexCharCodes[(a >>> 24) & 15],
469 hexCharCodes[(a >>> 20) & 15],
470 hexCharCodes[(a >>> 16) & 15],
471 hexCharCodes[(a >>> 12) & 15],
472 hexCharCodes[(a >>> 8) & 15],
473 hexCharCodes[(a >>> 4) & 15],
474 hexCharCodes[a & 15],
475 hexCharCodes[b >>> 28],
476 hexCharCodes[(b >>> 24) & 15],
477 hexCharCodes[(b >>> 20) & 15],
478 hexCharCodes[(b >>> 16) & 15],
479 hexCharCodes[(b >>> 12) & 15],
480 hexCharCodes[(b >>> 8) & 15],
481 hexCharCodes[(b >>> 4) & 15],
482 hexCharCodes[b & 15]
483 )
485​
486const randomHex32 = (): string => {
487 const a = randomWord()
488 const b = randomWord()
489 const c = randomWord()
490 const d = randomWord()
491 return String.fromCharCode(
492 hexCharCodes[a >>> 28],
493 hexCharCodes[(a >>> 24) & 15],
494 hexCharCodes[(a >>> 20) & 15],
495 hexCharCodes[(a >>> 16) & 15],
496 hexCharCodes[(a >>> 12) & 15],
497 hexCharCodes[(a >>> 8) & 15],
498 hexCharCodes[(a >>> 4) & 15],
499 hexCharCodes[a & 15],
500 hexCharCodes[b >>> 28],
501 hexCharCodes[(b >>> 24) & 15],
502 hexCharCodes[(b >>> 20) & 15],
503 hexCharCodes[(b >>> 16) & 15],
504 hexCharCodes[(b >>> 12) & 15],
505 hexCharCodes[(b >>> 8) & 15],
506 hexCharCodes[(b >>> 4) & 15],
507 hexCharCodes[b & 15],
508 hexCharCodes[c >>> 28],
509 hexCharCodes[(c >>> 24) & 15],
510 hexCharCodes[(c >>> 20) & 15],
511 hexCharCodes[(c >>> 16) & 15],
512 hexCharCodes[(c >>> 12) & 15],
513 hexCharCodes[(c >>> 8) & 15],
514 hexCharCodes[(c >>> 4) & 15],
515 hexCharCodes[c & 15],
516 hexCharCodes[d >>> 28],
517 hexCharCodes[(d >>> 24) & 15],
518 hexCharCodes[(d >>> 20) & 15],
519 hexCharCodes[(d >>> 16) & 15],
520 hexCharCodes[(d >>> 12) & 15],
521 hexCharCodes[(d >>> 8) & 15],
522 hexCharCodes[(d >>> 4) & 15],
523 hexCharCodes[d & 15]
524 )
526​
527/**
528 * Decodes a hexadecimal string into bytes safely.
529 *
530 * **When to use**
531 *
532 * Use to decode hexadecimal text into bytes without throwing on invalid input.
533 *
534 * **Details**
535 *
536 * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or
537 * `Result.fail` with an `EncodingError` when the input has an odd length or
538 * contains invalid hex characters.
539 *
540 * **Example** (Decoding hex bytes)
541 *
542 * ```ts import.meta.vitest
543 * import { Encoding, Result } from "effect"
544 *
545 * Encoding.decodeHex("48656c6c6f") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111]))
546 * ```
547 *
548 * @category decoding
549 * @since 2.0.0
550 */
551export const decodeHex = (str: string): Result.Result<Uint8Array, EncodingError> => {
552 const bytes = new TextEncoder().encode(str)
553 if (bytes.length % 2 !== 0) {
554 return Result.fail(
555 new EncodingError({
556 module: "Hex",
557 kind: "Decode",
558 input: str,
559 message: `Length must be a multiple of 2, but is ${bytes.length}`
560 })
561 )
562 }
563​
564 try {
565 const length = bytes.length / 2
566 const result = new Uint8Array(length)
567 for (let i = 0; i < length; i++) {
568 const a = fromHexChar(bytes[i * 2])
569 const b = fromHexChar(bytes[i * 2 + 1])
570 result[i] = (a << 4) | b
571 }
572​
573 return Result.succeed(result)
574 } catch (e) {
575 return Result.fail(
576 new EncodingError({
577 module: "Hex",
578 kind: "Decode",
579 input: str,
580 message: e instanceof Error ? e.message : "Invalid input"
581 })
582 )
583 }
585​
586/**
587 * Decodes a hexadecimal string into a UTF-8 string safely.
588 *
589 * **When to use**
590 *
591 * Use to decode hexadecimal text into UTF-8 text without throwing on invalid
592 * input.
593 *
594 * **Details**
595 *
596 * Returns `Result.succeed` with the decoded text when decoding succeeds, or
597 * `Result.fail` with an `EncodingError` when the input is not valid hex.
598 *
599 * **Example** (Decoding hex strings)
600 *
601 * ```ts import.meta.vitest
602 * import { Encoding, Result } from "effect"
603 *
604 * Encoding.decodeHexString("68656c6c6f") // => Result.succeed("hello")
605 * ```
606 *
607 * @category decoding
608 * @since 2.0.0
609 */
610export const decodeHexString = (str: string) => Result.map(decodeHex(str), (_) => decoder.decode(_))
611​
612// -------------------------------------------------------------------------------------
613// internals
614// -------------------------------------------------------------------------------------
615​
616const encoder = new TextEncoder()
617const decoder = new TextDecoder()
618​
619const stripCrlf = (str: string) => str.replace(/[\n\r]/g, "")
620​
621// Base64 internals
622​
623const base64EncodeUint8Array = (bytes: Uint8Array) => {
624 const length = bytes.length
625​
626 let result = ""
627 let i: number
628​
629 for (i = 2; i < length; i += 3) {
630 result += base64abc[bytes[i - 2] >> 2]
631 result += base64abc[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]
632 result += base64abc[((bytes[i - 1] & 0x0f) << 2) | (bytes[i] >> 6)]
633 result += base64abc[bytes[i] & 0x3f]
634 }
635​
636 if (i === length + 1) {
637 result += base64abc[bytes[i - 2] >> 2]
638 result += base64abc[(bytes[i - 2] & 0x03) << 4]
639 result += "=="
640 }
641​
642 if (i === length) {
643 result += base64abc[bytes[i - 2] >> 2]
644 result += base64abc[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]
645 result += base64abc[(bytes[i - 1] & 0x0f) << 2]
646 result += "="
647 }
648​
649 return result
651​
652function getBase64Code(charCode: number) {
653 if (charCode >= base64codes.length) {
654 throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`)
655 }
656​
657 const code = base64codes[charCode]
658 if (code === 255) {
659 throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`)
660 }
661​
662 return code
664​
665const base64abc = [
666 "A",
667 "B",
668 "C",
669 "D",
670 "E",
671 "F",
672 "G",
673 "H",
674 "I",
675 "J",
676 "K",
677 "L",
678 "M",
679 "N",
680 "O",
681 "P",
682 "Q",
683 "R",
684 "S",
685 "T",
686 "U",
687 "V",
688 "W",
689 "X",
690 "Y",
691 "Z",
692 "a",
693 "b",
694 "c",
695 "d",
696 "e",
697 "f",
698 "g",
699 "h",
700 "i",
701 "j",
702 "k",
703 "l",
704 "m",
705 "n",
706 "o",
707 "p",
708 "q",
709 "r",
710 "s",
711 "t",
712 "u",
713 "v",
714 "w",
715 "x",
716 "y",
717 "z",
718 "0",
719 "1",
720 "2",
721 "3",
722 "4",
723 "5",
724 "6",
725 "7",
726 "8",
727 "9",
728 "+",
729 "/"
731​
732const base64codes = [
733 255,
734 255,
735 255,
736 255,
737 255,
738 255,
739 255,
740 255,
741 255,
742 255,
743 255,
744 255,
745 255,
746 255,
747 255,
748 255,
749 255,
750 255,
751 255,
752 255,
753 255,
754 255,
755 255,
756 255,
757 255,
758 255,
759 255,
760 255,
761 255,
762 255,
763 255,
764 255,
765 255,
766 255,
767 255,
768 255,
769 255,
770 255,
771 255,
772 255,
773 255,
774 255,
775 255,
776 62,
777 255,
778 255,
779 255,
780 63,
781 52,
782 53,
783 54,
784 55,
785 56,
786 57,
787 58,
788 59,
789 60,
790 61,
791 255,
792 255,
793 255,
794 0,
795 255,
796 255,
797 255,
798 0,
799 1,
800 2,
801 3,
802 4,
803 5,
804 6,
805 7,
806 8,
807 9,
808 10,
809 11,
810 12,
811 13,
812 14,
813 15,
814 16,
815 17,
816 18,
817 19,
818 20,
819 21,
820 22,
821 23,
822 24,
823 25,
824 255,
825 255,
826 255,
827 255,
828 255,
829 255,
830 26,
831 27,
832 28,
833 29,
834 30,
835 31,
836 32,
837 33,
838 34,
839 35,
840 36,
841 37,
842 38,
843 39,
844 40,
845 41,
846 42,
847 43,
848 44,
849 45,
850 46,
851 47,
852 48,
853 49,
854 50,
855 51
857​
858// Base64Url internals
859​
860const base64UrlEncodeUint8Array = (data: Uint8Array) =>
861 base64EncodeUint8Array(data).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_")
862​
863// Hex internals
864​
865const byteToHex: Array<string> = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"))
866​
867const hexEncodeUint8Array = (bytes: Uint8Array): string => {
868 let result = ""
869 for (let i = 0; i < bytes.length; i++) {
870 result += byteToHex[bytes[i]]
871 }
872 return result
874​
875const fromHexChar = (byte: number) => {
876 if (48 <= byte && byte <= 57) {
877 return byte - 48
878 }
879​
880 if (97 <= byte && byte <= 102) {
881 return byte - 97 + 10
882 }
883​
884 if (65 <= byte && byte <= 70) {
885 return byte - 65 + 10
886 }
887​
888 throw new TypeError("Invalid input")