// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

/**
 * Utilities for
 * {@link https://datatracker.ietf.org/doc/html/rfc4648#section-5 | base64url}
 * encoding and decoding.
 *
 * This module is browser compatible.
 *
 * @module
 */

import * as base64 from "./base64.ts";

/**
 * Some variants allow or require omitting the padding '=' signs:
 * https://en.wikipedia.org/wiki/Base64#The_URL_applications
 *
 * @param base64url
 */
function addPaddingToBase64url(base64url: string): string {
  if (base64url.length % 4 === 2) return base64url + "==";
  if (base64url.length % 4 === 3) return base64url + "=";
  if (base64url.length % 4 === 1) {
    throw new TypeError("Illegal base64url string!");
  }
  return base64url;
}

function convertBase64urlToBase64(b64url: string): string {
  if (!/^[-_A-Z0-9]*?={0,2}$/i.test(b64url)) {
    // Contains characters not part of base64url spec.
    throw new TypeError("Failed to decode base64url: invalid character");
  }
  return addPaddingToBase64url(b64url).replace(/\-/g, "+").replace(/_/g, "/");
}

function convertBase64ToBase64url(b64: string) {
  return b64.endsWith("=")
    ? b64.endsWith("==")
      ? b64.replace(/\+/g, "-").replace(/\//g, "_").slice(0, -2)
      : b64.replace(/\+/g, "-").replace(/\//g, "_").slice(0, -1)
    : b64.replace(/\+/g, "-").replace(/\//g, "_");
}

/**
 * Convert data into a base64url-encoded string.
 *
 * @see {@link https://datatracker.ietf.org/doc/html/rfc4648#section-5}
 *
 * @param data The data to encode.
 * @returns The base64url-encoded string.
 *
 * @example
 * ```ts
 * import { encodeBase64Url } from "https://deno.land/std@$STD_VERSION/encoding/base64url.ts";
 *
 * encodeBase64Url("foobar"); // "Zm9vYmFy"
 * ```
 */
export function encodeBase64Url(
  data: ArrayBuffer | Uint8Array | string,
): string {
  return convertBase64ToBase64url(base64.encodeBase64(data));
}

/**
 * Decodes a given base64url-encoded string.
 *
 * @see {@link https://datatracker.ietf.org/doc/html/rfc4648#section-5}
 *
 * @param b64url The base64url-encoded string to decode.
 * @returns The decoded data.
 *
 * @example
 * ```ts
 * import { decodeBase64Url } from "https://deno.land/std@$STD_VERSION/encoding/base64url.ts";
 *
 * decodeBase64Url("Zm9vYmFy"); // Uint8Array(6) [ 102, 111, 111, 98, 97, 114 ]
 * ```
 */
export function decodeBase64Url(b64url: string): Uint8Array {
  return base64.decodeBase64(convertBase64urlToBase64(b64url));
}

// denoCacheMetadata={"headers":{"x-content-type-options":"nosniff","vary":"Origin","age":"1114871","x-amz-replication-status":"COMPLETED","x-cache":"Hit from cloudfront","content-length":"2492","referrer-policy":"strict-origin-when-cross-origin","accept-ranges":"bytes","x-amz-version-id":"W62dfC.rm9Q09lJDBbSenRx1qWqjURGK","x-amz-server-side-encryption":"AES256","server":"AmazonS3,deployd","cross-origin-resource-policy":"same-origin","x-amz-cf-id":"e-EOzi8vTf1C0Tn2isnTLA5KdAkfPazem4SPT4vcaBAYGVBjMC4t3A==","last-modified":"Thu, 25 Apr 2024 03:01:09 GMT","cache-control":"public, max-age=31536000, immutable","cross-origin-opener-policy":"same-origin","cross-origin-embedder-policy":"same-origin","x-deno-trace-id":"37393d6856ba489f32c30ae4dd98db74","alt-svc":"h3=\":443\"; ma=86400","date":"Wed, 15 Jul 2026 14:50:02 GMT","server-timing":"fetchSource;dur=8","access-control-allow-origin":"*","cache-status":"deno; hit","x-frame-options":"DENY","strict-transport-security":"max-age=63072000; includeSubDomains; preload","content-security-policy":"default-src 'none'; style-src 'unsafe-inline'; sandbox","x-amz-cf-pop":"ORD56-P16","via":"1.1 8267ddda05eecda7c23d647573952fee.cloudfront.net (CloudFront),HTTP/2 ord.vultr.prod.deno-cluster.net","etag":"\"04d1fff675696396c1b39b8c427f0525\"","content-type":"application/typescript; charset=utf-8"},"url":"https://deno.land/std@0.224.0/encoding/base64url.ts","time":1785241873}