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

import { assertArg } from "../_common/dirname.ts";
import { stripTrailingSeparators } from "../_common/strip_trailing_separators.ts";
import { isPosixPathSeparator } from "./_util.ts";

/**
 * Return the directory path of a `path`.
 *
 * @example
 * ```ts
 * import { dirname } from "@std/path/dirname";
 *
 * console.log(dirname("/home/user/Documents/")); // "/home/user"
 * console.log(dirname("/home/user/Documents/image.png")); // "/home/user/Documents"
 * ```
 *
 * @param path - path to extract the directory from.
 */
export function dirname(path: string): string {
  assertArg(path);

  let end = -1;
  let matchedNonSeparator = false;

  for (let i = path.length - 1; i >= 1; --i) {
    if (isPosixPathSeparator(path.charCodeAt(i))) {
      if (matchedNonSeparator) {
        end = i;
        break;
      }
    } else {
      matchedNonSeparator = true;
    }
  }

  // No matches. Fallback based on provided path:
  //
  // - leading slashes paths
  //     "/foo" => "/"
  //     "///foo" => "/"
  // - no slash path
  //     "foo" => "."
  if (end === -1) {
    return isPosixPathSeparator(path.charCodeAt(0)) ? "/" : ".";
  }

  return stripTrailingSeparators(
    path.slice(0, end),
    isPosixPathSeparator,
  );
}

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