// Two workspace members each directly depend on a different version of the same
// package. In the hoisted linker this is a version conflict: the higher version
// (2.0.0) is hoisted to the workspace root, and the lower version (1.0.0) is not
// placed anywhere in the hoisted layout. A member that declares the lower
// version therefore does NOT get it linked into its own `node_modules`.
//
// This is a known limitation, deferred to a follow-up. The test pins the
// current behavior so that when the fix lands, the marked assertion below flips
// from "package1's link is missing" to "package1 resolves 1.0.0 locally".
// See https://github.com/denoland/deno/pull/34970.

const dep = "@denotest/breaking-change-between-versions";

function version(path: string): string {
  return JSON.parse(Deno.readTextFileSync(path)).version;
}

function assertMissing(path: string) {
  try {
    Deno.lstatSync(path);
  } catch (err) {
    if (err instanceof Deno.errors.NotFound) return;
    throw err;
  }
  throw new Error(`expected ${path} to be missing`);
}

// The higher version wins the workspace root (the hoisted top level).
if (version(`node_modules/${dep}/package.json`) !== "2.0.0") {
  throw new Error("expected 2.0.0 to be hoisted to the workspace root");
}

// package2 declares the winning version, so it is linked into package2.
if (version(`package2/node_modules/${dep}/package.json`) !== "2.0.0") {
  throw new Error("expected package2 to resolve its declared 2.0.0");
}

// KNOWN LIMITATION: package1 declares 1.0.0, which is not placed in the hoisted
// layout, so no link is created for it in package1's `node_modules`. When the
// follow-up lands, package1 should resolve 1.0.0 locally and this should become
// a version check against "1.0.0" instead.
assertMissing(`package1/node_modules/${dep}`);

console.log("ok");
