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

/**
 * Utilities for
 * {@link https://www.rfc-editor.org/rfc/rfc4648.html#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://www.rfc-editor.org/rfc/rfc4648.html#section-5}
 *
 * @param data The data to encode.
 * @returns The base64url-encoded string.
 *
 * @example Usage
 * ```ts
 * import { encodeBase64Url } from "@std/encoding/base64url";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * assertEquals(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://www.rfc-editor.org/rfc/rfc4648.html#section-5}
 *
 * @param b64url The base64url-encoded string to decode.
 * @returns The decoded data.
 *
 * @example Usage
 * ```ts
 * import { decodeBase64Url } from "@std/encoding/base64url";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * assertEquals(
 *   decodeBase64Url("Zm9vYmFy"),
 *   new TextEncoder().encode("foobar")
 * );
 * ```
 */
export function decodeBase64Url(b64url: string): Uint8Array {
  return base64.decodeBase64(convertBase64urlToBase64(b64url));
}

// denoCacheMetadata={"headers":{"cross-origin-resource-policy":"cross-origin","cf-ray":"a223e658ad1e7db6-LAX","etag":"\"baf8a725895af235af1510be88f66ecc\"","vary":"Origin","access-control-expose-headers":"*","x-content-type-options":"nosniff","accept-ranges":"bytes","date":"Tue, 28 Jul 2026 12:31:15 GMT","access-control-allow-origin":"*","age":"4145","cf-cache-status":"HIT","cache-control":"public, max-age=31536000, immutable","set-cookie":"__cf_bm=K3fXUTbZOEC5We_y_ipfP2RKNM3TezuCObeIYS6ESk0-1785241875.306342-1.0.1.1-rjLVvv2w1Y5iSpiquSoghhItGFnA.ATXPk5dj16l7my6KmW6Rihs.l8Pm7.NRYzA.AIz3_weP2Ujme8JBLIdLo7Gug7p0rj6pbCxhgCZlJe6XxHl_0CZWdu2yKrzFOZS; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=1J5RoWY3GvEvaDykDwdKOv9oDBI7Au2cIUijnKBIqKDOp1fCKOL%2BNrwjwaJLaAO5yazz4vz43mNYClMgCKZh2b9Q8IOFOrfNAcXzOquFB4NjPd55zQUAt4w%3D\"}]}","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","x-robots-tag":"noindex","content-type":"text/typescript","server":"cloudflare","alt-svc":"h3=\":443\"; ma=86400","x-jsr-backend":"modules","content-length":"2583","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}"},"url":"https://jsr.io/@std/encoding/0.224.3/base64url.ts","time":1785241875}