Hyperlinkv0.8.0-beta.28

Encoding

Encoding.decodeBase64Urlconsteffect/Encoding.ts:328
(str: string): Result.Result<Uint8Array, EncodingError>

Decodes a URL-safe base64 string into bytes safely.

When to use

Use to decode padded or unpadded Base64Url text into bytes without throwing on invalid input.

Details

Returns Result.succeed with a Uint8Array when decoding succeeds, or Result.fail with an EncodingError when the input is not valid URL-safe base64. Both padded and unpadded URL-safe base64 forms are accepted when otherwise valid.

Example (Decoding URL-safe Base64 bytes)

import { Encoding, Result } from "effect"

const result = Encoding.decodeBase64Url("SGVsbG8_")
if (Result.isSuccess(result)) {
  console.log(Array.from(result.success)) // [72, 101, 108, 108, 111, 63]
}
decoding
Source effect/Encoding.ts:32831 lines
export const decodeBase64Url = (str: string): Result.Result<Uint8Array, EncodingError> => {
  const stripped = stripCrlf(str)
  const length = stripped.length
  if (length % 4 === 1) {
    return Result.fail(
      new EncodingError({
        module: "Base64Url",
        kind: "Decode",
        input: stripped,
        message: `Length should be a multiple of 4, but is ${length}`
      })
    )
  }

  if (!/^[-_A-Z0-9]*?={0,2}$/i.test(stripped)) {
    return Result.fail(
      new EncodingError({
        module: "Base64Url",
        kind: "Decode",
        input: stripped,
        message: "Invalid input"
      })
    )
  }

  // Some variants allow or require omitting the padding '=' signs
  let sanitized = length % 4 === 2 ? `${stripped}==` : length % 4 === 3 ? `${stripped}=` : stripped
  sanitized = sanitized.replace(/-/g, "+").replace(/_/g, "/")

  return decodeBase64(sanitized)
}
Referenced by 2 symbols