// 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/posix/to-file-url";
 *
 * toFileUrl("/home/foo"); // new URL("file:///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 url = new URL("file:///");
  url.pathname = encodeWhitespace(
    path.replace(/%/g, "%25").replace(/\\/g, "%5C"),
  );
  return url;
}

// denoCacheMetadata={"headers":{"x-content-type-options":"nosniff","set-cookie":"__cf_bm=cHJCN.VgBNLk.7pz49OhwJ_sQ8PkUXtzpoYTHcsOyJs-1785241875.2589011-1.0.1.1-TtFAjKeI5OrlpMhlaTYY1YYhJwqkXlcTsY5_sphenw7DcAjrPNFVpQLmzYmZUSDSIG78BKP.jcgI2I0Hrs.yr0xhK.p_ZMWFB0yK6ydEMN_rvY3hhknp83l4EXPx5FZj; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","cross-origin-resource-policy":"cross-origin","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","cf-cache-status":"HIT","access-control-allow-origin":"*","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';","accept-ranges":"bytes","server":"cloudflare","age":"44352","cache-control":"public, max-age=31536000, immutable","cf-ray":"a223e6585c1b7db6-LAX","vary":"Origin","x-jsr-backend":"modules","access-control-expose-headers":"*","x-robots-tag":"noindex","content-type":"text/typescript","alt-svc":"h3=\":443\"; ma=86400","date":"Tue, 28 Jul 2026 12:31:15 GMT","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=v1SKc9RWxvgEevmG7ziY0lz%2BAV7jwIVwIuM8xfHdi1Xe26EnLg8OfIieb%2BmaThVbIjxl9LvYZRgJ4kqojVVLPsgNzNga%2BLs8ufGrTEFSIbaz2wY7hVJB3V0%3D\"}]}","etag":"\"a261c5c68d0a3d7b7c81825fb4fcd6fc\"","content-length":"728"},"url":"https://jsr.io/@std/path/0.224.0/posix/to_file_url.ts","time":1785241875}