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

import { encodeWhitespace } from "../_common/to_file_url.ts";
import { isAbsolute } from "./is_absolute.ts";

/**
 * Converts a path string to a file URL.
 *
 * ```ts
 * import { toFileUrl } from "@std/path/windows/to-file-url";
 *
 * toFileUrl("\\home\\foo"); // new URL("file:///home/foo")
 * toFileUrl("C:\\Users\\foo"); // new URL("file:///C:/Users/foo")
 * toFileUrl("\\\\127.0.0.1\\home\\foo"); // new URL("file://127.0.0.1/home/foo")
 * ```
 * @param path to convert to file URL
 */
export function toFileUrl(path: string): URL {
  if (!isAbsolute(path)) {
    throw new TypeError("Must be an absolute path.");
  }
  const [, hostname, pathname] = path.match(
    /^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/,
  )!;
  const url = new URL("file:///");
  url.pathname = encodeWhitespace(pathname!.replace(/%/g, "%25"));
  if (hostname !== undefined && hostname !== "localhost") {
    url.hostname = hostname;
    if (!url.hostname) {
      throw new TypeError("Invalid hostname.");
    }
  }
  return url;
}

// denoCacheMetadata={"headers":{"date":"Tue, 28 Jul 2026 12:31:15 GMT","cf-ray":"a223e6583bc77db6-LAX","content-type":"text/typescript","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=UPpwQgQIO3cpIy9urhgCPHZ2wiGD6Tf1Yhz0lyjTN8PrB7tl6O9yHQ7heRg%2BmwwTcY7JeLLdPS6BSLUqPJ4GL5btIda%2FIUzKGvFYYMwTr4HTzWYGxBIIxUY%3D\"}]}","x-jsr-backend":"modules","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-content-type-options":"nosniff","vary":"Origin","access-control-allow-origin":"*","server":"cloudflare","cf-cache-status":"HIT","content-length":"1133","accept-ranges":"bytes","access-control-expose-headers":"*","age":"4275755","cross-origin-resource-policy":"cross-origin","set-cookie":"__cf_bm=1hGidxnGAvouQ3g2DA.SR1jUsIVbXogiAppIc_K_dPs-1785241875.2408113-1.0.1.1-4ZDdVJgOE3TKo6YT8zYPAljQRg9oq2P4gkXpbxnPznaBHgy3ncwLI3dEQzhMNiOlr1JtVNrr5Jt5bxnh5Y1mtbnlH8FOGFWMu4s56RzMMx9NRYt.FzxGrPbeRVR0Qyty; 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}","alt-svc":"h3=\":443\"; ma=86400","x-robots-tag":"noindex","cache-control":"public, max-age=31536000, immutable","etag":"\"e705ad3fa0649ed02ca810f15352097b\""},"url":"https://jsr.io/@std/path/0.224.0/windows/to_file_url.ts","time":1785241875}