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

import { assertArg } from "../_common/normalize.ts";
import { normalizeString } from "../_common/normalize_string.ts";
import { isPosixPathSeparator } from "./_util.ts";

/**
 * Normalize the `path`, resolving `'..'` and `'.'` segments.
 * Note that resolving these segments does not necessarily mean that all will be eliminated.
 * A `'..'` at the top-level will be preserved, and an empty path is canonically `'.'`.
 * @param path to be normalized
 */
export function normalize(path: string): string {
  assertArg(path);

  const isAbsolute = isPosixPathSeparator(path.charCodeAt(0));
  const trailingSeparator = isPosixPathSeparator(
    path.charCodeAt(path.length - 1),
  );

  // Normalize the path
  path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator);

  if (path.length === 0 && !isAbsolute) path = ".";
  if (path.length > 0 && trailingSeparator) path += "/";

  if (isAbsolute) return `/${path}`;
  return path;
}

// denoCacheMetadata={"headers":{"report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=9waEFr5G7uW%2BRwuLb%2FT0sQ%2BhzNBpikhsLIQOL7xxq8eHb4JfzYrz8tpOOSluTKMrLIj2nwDjM0YscwxaMMFFbMd5VikDzox99mdKRc%2BVTAA7piEQA2%2BvpCA%3D\"}]}","server":"cloudflare","content-type":"text/typescript","cf-cache-status":"HIT","date":"Tue, 28 Jul 2026 12:31:15 GMT","x-robots-tag":"noindex","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}","alt-svc":"h3=\":443\"; ma=86400","x-content-type-options":"nosniff","cache-control":"public, max-age=31536000, immutable","vary":"Origin","etag":"\"db20394d76da2207867289705b9390d7\"","content-length":"1056","age":"1647613","x-jsr-backend":"modules","access-control-expose-headers":"*","cross-origin-resource-policy":"cross-origin","set-cookie":"__cf_bm=jgTzG6EKqvOUUCKr0QuTDFh_FoRwTh8fhcyW8bcCKGs-1785241875.256839-1.0.1.1-iTx45H9yy8SyuBUu8eb2dfGLAZ8XxcYqnRTQv5XAM9jYDr8suT5wy3bJoYI19ReM1t11KYpPF73dHpAX.ugAuCosZfE6V0DhA6NoqOLtec_lXRSR4daiT79nKdE3va6s; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","accept-ranges":"bytes","cf-ray":"a223e6585c127db6-LAX","access-control-allow-origin":"*"},"url":"https://jsr.io/@std/path/0.224.0/posix/normalize.ts","time":1785241875}