// 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 `'.'`.
 *
 * @example Usage
 * ```ts
 * import { normalize } from "@std/path/posix/normalize";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const path = normalize("/foo/bar//baz/asdf/quux/..");
 * assertEquals(path, "/foo/bar/baz/asdf");
 * ```
 *
 * @param path The path to normalize.
 * @returns The normalized path.
 */
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":{"date":"Tue, 28 Jul 2026 12:31:15 GMT","cf-ray":"a223e658bd3f7db6-LAX","x-robots-tag":"noindex","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=nMgTem00e7AtVJGuWG%2FgyISjuJaKNbpyY6uuhYSJLuDwZRhj7vXe0jNXJG%2FAisRt3uMFU7g03FG4kfhi%2BeXIgmPRaluAlCdSRZp5IWcb6i3eBDZeRLtPK%2BU%3D\"}]}","alt-svc":"h3=\":443\"; ma=86400","access-control-allow-origin":"*","vary":"Origin","server":"cloudflare","age":"126790","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","access-control-expose-headers":"*","cf-cache-status":"HIT","set-cookie":"__cf_bm=C13oiDgTlqagR97TtyREAv3qetWIybnEkFZBOexo6S4-1785241875.3136618-1.0.1.1-JhYqVdDbxx5zl9n_.IISq9NZI3LGW_56Q5aBgjh7ND5QRj40UBAjPSiLZ_IlKQnwJlEZ0Jl_g4i3zjHFj6tCnLtc6J21yHIVKb3gyjfdfklI81Z4lp0rZMoSGASdyflB; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","accept-ranges":"bytes","content-type":"text/typescript","cross-origin-resource-policy":"cross-origin","content-length":"1358","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","etag":"\"8ff07ec3ce08a9f18df246267fe90f6a\"","cache-control":"public, max-age=31536000, immutable","x-jsr-backend":"modules"},"url":"https://jsr.io/@std/path/1.0.0-rc.2/posix/normalize.ts","time":1785241875}