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

import { assertArg } from "../_common/from_file_url.ts";

/**
 * Converts a file URL to a path string.
 *
 * ```ts
 * import { fromFileUrl } from "@std/path/windows/from-file-url";
 *
 * fromFileUrl("file:///home/foo"); // "\\home\\foo"
 * fromFileUrl("file:///C:/Users/foo"); // "C:\\Users\\foo"
 * fromFileUrl("file://localhost/home/foo"); // "\\\\localhost\\home\\foo"
 * ```
 * @param url of a file URL
 */
export function fromFileUrl(url: URL | string): string {
  url = assertArg(url);
  let path = decodeURIComponent(
    url.pathname.replace(/\//g, "\\").replace(/%(?![0-9A-Fa-f]{2})/g, "%25"),
  ).replace(/^\\*([A-Za-z]:)(\\|$)/, "$1\\");
  if (url.hostname !== "") {
    // Note: The `URL` implementation guarantees that the drive letter and
    // hostname are mutually exclusive. Otherwise it would not have been valid
    // to append the hostname and path like this.
    path = `\\\\${url.hostname}${path}`;
  }
  return path;
}

// denoCacheMetadata={"headers":{"content-length":"1058","content-type":"text/typescript","etag":"\"12fa7b29b90f5ba1c828b6a9affe0625\"","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';","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","x-robots-tag":"noindex","server":"cloudflare","date":"Tue, 28 Jul 2026 12:31:15 GMT","cross-origin-resource-policy":"cross-origin","x-jsr-backend":"modules","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=%2F1eiZYaH2cwOxkncsT2%2FecbEOygUqpDSJr46%2F27Mw14q3rdXHfHD62Oj3hq4JWxnsmSNjOZzh23Jwo%2FyFjaZkzDc4Wud%2F9WHm5N13o1ygFEKddqqa0iicig%3D\"}]}","vary":"Origin","alt-svc":"h3=\":443\"; ma=86400","access-control-expose-headers":"*","cf-ray":"a223e6582baa7db6-LAX","cf-cache-status":"HIT","age":"3333550","cache-control":"public, max-age=31536000, immutable","x-content-type-options":"nosniff","accept-ranges":"bytes","access-control-allow-origin":"*","set-cookie":"__cf_bm=EzUOi_l32mZn5FXJBrBWCIX8r3QBrhxdBy2RkHKengQ-1785241875.2329597-1.0.1.1-vojGheBxn0Ne5dunCRj1ySCH3Vz4lD6NaGrCsR9bX.uL7iSmfOXIXfcEjXq2l_5.zz6KBQGeB71SNW9UapIaYDDrpC9cMSGmKWQjuzeAjARy7Ve9qZta3pHrUmiPuOd8; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT"},"url":"https://jsr.io/@std/path/0.224.0/windows/from_file_url.ts","time":1785241875}