// Ported and adapted from js-yaml-js-types v1.0.0:
// https://github.com/nodeca/js-yaml-js-types/tree/ac537e7bbdd3c2cbbd9882ca3919c520c2dc022b
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

import { Type } from "../type.ts";
import type { Any } from "../_utils.ts";

const REGEXP = /^\/(?<regexp>[\s\S]+)\/(?<modifiers>[gismuy]*)$/;

export const regexp = new Type("tag:yaml.org,2002:js/regexp", {
  kind: "scalar",
  resolve(data: Any) {
    if ((data === null) || (!data.length)) {
      return false;
    }

    const regexp = `${data}`;
    if (regexp.charAt(0) === "/") {
      // Ensure regex is properly terminated
      if (!REGEXP.test(data)) {
        return false;
      }
      // Check no duplicate modifiers
      const modifiers = [...(regexp.match(REGEXP)?.groups?.modifiers ?? "")];
      if (new Set(modifiers).size < modifiers.length) {
        return false;
      }
    }

    return true;
  },
  construct(data: string) {
    const { regexp = `${data}`, modifiers = "" } =
      `${data}`.match(REGEXP)?.groups ?? {};
    return new RegExp(regexp, modifiers);
  },
  predicate(object: unknown) {
    return object instanceof RegExp;
  },
  represent(object: RegExp) {
    return object.toString();
  },
});

// denoCacheMetadata={"headers":{"content-type":"text/typescript","age":"1643671","etag":"\"d0fe9177b8bb475f3ce1d595f06274e4\"","content-length":"1333","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=vhtfZip9BoTz91GKPQw700JRPR4fNWa71sIGn%2BrpTvv5WsGR5WzHyWmnPbB8GvbFJg3CLJjBlWrfwuCJUhiReJ%2FkCGPGLULeKS3mejHg31eXsk3qBX2O9WI%3D\"}]}","cache-control":"public, max-age=31536000, immutable","accept-ranges":"bytes","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","set-cookie":"__cf_bm=USJT2z_83P_VzETSJrNs5blriD0bmXzmXBzLZe2fM2A-1785241875.300575-1.0.1.1-e4NNX2cPle9qfGYS2YkXy5ZeJMUo07EMQ4XljXrQe6ebLMgmzMbQYYROTy0nxR3iJxvvYInAs4HS9EpuVWgl11vJveMOnbFK04ige5Jt9uQAFhokL95AA7Ew41HJoqoe; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","date":"Tue, 28 Jul 2026 12:31:15 GMT","cross-origin-resource-policy":"cross-origin","vary":"Origin","cf-ray":"a223e6589cf57db6-LAX","access-control-expose-headers":"*","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';","cf-cache-status":"HIT","x-robots-tag":"noindex","x-content-type-options":"nosniff","alt-svc":"h3=\":443\"; ma=86400","access-control-allow-origin":"*","x-jsr-backend":"modules","server":"cloudflare"},"url":"https://jsr.io/@std/yaml/0.224.3/_type/regexp.ts","time":1785241875}