// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/
// This module is browser compatible.

import { CHAR_DOT, CHAR_FORWARD_SLASH } from "./constants.ts";

// Resolves . and .. elements in a path with directory names
export function normalizeString(
  path: string,
  allowAboveRoot: boolean,
  separator: string,
  isPathSeparator: (code: number) => boolean,
): string {
  let res = "";
  let lastSegmentLength = 0;
  let lastSlash = -1;
  let dots = 0;
  let code: number | undefined;
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) code = path.charCodeAt(i);
    else if (isPathSeparator(code!)) break;
    else code = CHAR_FORWARD_SLASH;

    if (isPathSeparator(code!)) {
      if (lastSlash === i - 1 || dots === 1) {
        // NOOP
      } else if (lastSlash !== i - 1 && dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator);
            if (lastSlashIndex === -1) {
              res = "";
              lastSegmentLength = 0;
            } else {
              res = res.slice(0, lastSlashIndex);
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
            }
            lastSlash = i;
            dots = 0;
            continue;
          } else if (res.length === 2 || res.length === 1) {
            res = "";
            lastSegmentLength = 0;
            lastSlash = i;
            dots = 0;
            continue;
          }
        }
        if (allowAboveRoot) {
          if (res.length > 0) res += `${separator}..`;
          else res = "..";
          lastSegmentLength = 2;
        }
      } else {
        if (res.length > 0) res += separator + path.slice(lastSlash + 1, i);
        else res = path.slice(lastSlash + 1, i);
        lastSegmentLength = i - lastSlash - 1;
      }
      lastSlash = i;
      dots = 0;
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots;
    } else {
      dots = -1;
    }
  }
  return res;
}

// denoCacheMetadata={"headers":{"set-cookie":"__cf_bm=k9NqT5FQyypO0iVz5rtXvq4P8aJKeS4gx2ynDIfpbF4-1785241875.3405452-1.0.1.1-MKEwc.KZ_9mxmwRgZIJql1Lawtu2LCHYvz6eXhlEAr1OG3jHh86CnstsNrIVwA_IgW6jAgLXvn9LLjPCg8qekk..6H6OcICEWJNyLti84WN0t5UXCb7EYxeN1txT0c55; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","cache-control":"public, max-age=31536000, immutable","etag":"\"206425ad9bc3d231ba388158f147d90d\"","age":"38659","date":"Tue, 28 Jul 2026 12:31:15 GMT","cf-cache-status":"HIT","vary":"Origin","accept-ranges":"bytes","access-control-expose-headers":"*","cross-origin-resource-policy":"cross-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';","access-control-allow-origin":"*","x-robots-tag":"noindex","content-length":"2301","x-content-type-options":"nosniff","x-jsr-backend":"modules","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","content-type":"text/typescript","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=ogVgVtscmM9xgDwuri1PwckXgco%2FF83CozZdpyJ%2FReIOCYe6Yu%2B5506Dq9031idUh%2BcCcfB8%2FGK3JgoiiSBJ4Ua1E2Kn8HIYH65OTxkZrEAtuoZEzopOjRI%3D\"}]}","alt-svc":"h3=\":443\"; ma=86400","cf-ray":"a223e658cda97db6-LAX","server":"cloudflare"},"url":"https://jsr.io/@std/path/1.0.0-rc.2/_common/normalize_string.ts","time":1785241875}