// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
import type { SemVer } from "./types.ts";
import { parse } from "./parse.ts";

/**
 * Returns the parsed version, or undefined if it's not valid.
 *
 * @example Usage
 * ```ts
 * import { tryParse } from "@std/semver/try-parse";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * assertEquals(tryParse("1.2.3"), { major: 1, minor: 2, patch: 3, prerelease: [], build: [] });
 * assertEquals(tryParse("1.2.3-alpha"), { major: 1, minor: 2, patch: 3, prerelease: ["alpha"], build: [] });
 * assertEquals(tryParse("1.2.3+build"), { major: 1, minor: 2, patch: 3, prerelease: [], build: ["build"] });
 * assertEquals(tryParse("1.2.3-alpha.1+build.1"), { major: 1, minor: 2, patch: 3, prerelease: ["alpha", 1], build: ["build", "1"] });
 * assertEquals(tryParse(" invalid "), undefined);
 * ```
 *
 * @param version The version string to parse
 * @returns A valid SemVer or `undefined`
 */
export function tryParse(version?: string): SemVer | undefined {
  if (version === undefined) {
    return undefined;
  }
  try {
    return parse(version);
  } catch {
    return undefined;
  }
}

// denoCacheMetadata={"headers":{"x-content-type-options":"nosniff","cf-ray":"a223e657ca927db6-LAX","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=E8qebZPbKuKV3NmyJ8mBCS9IgqDgRvkeo8Qc%2FDsia8qYio%2F7h%2BG8qekb%2F1croK2%2Fy8lhYGuQqkNh26uZJRskhx7EAPLC3n7lBEFOje%2B6BquX8JimgnUO924%3D\"}]}","access-control-allow-origin":"*","age":"3635422","content-type":"text/typescript","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';","set-cookie":"__cf_bm=16IgyzUtZlAXuZsTeD24CujraW7h8yaZRV044l0XfpI-1785241875.171943-1.0.1.1-.XY_7BsOPFbXVFSUXlHKkLSZryMw1qEgVmx5x.3iG7cuQPIr2RbsXYKiwXNDniyckM24WTFWH8CF1N_i9M4mFzl4ks3G0qeYz6d3yJg1evb5bWhNyXrMTjjU7_HtXffe; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","x-robots-tag":"noindex","cf-cache-status":"HIT","vary":"Origin","content-length":"1208","access-control-expose-headers":"*","alt-svc":"h3=\":443\"; ma=86400","server":"cloudflare","accept-ranges":"bytes","cache-control":"public, max-age=31536000, immutable","x-jsr-backend":"modules","etag":"\"29cb4caa0e454f77ef0d10dcb9eb93bd\"","cross-origin-resource-policy":"cross-origin","date":"Tue, 28 Jul 2026 12:31:15 GMT"},"url":"https://jsr.io/@std/semver/0.224.3/try_parse.ts","time":1785241875}