npm.test.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import fs from "fs/promises"
  2. import path from "path"
  3. import { describe, expect, test } from "bun:test"
  4. import { Effect, Option } from "effect"
  5. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  6. import { Global } from "@opencode-ai/util/global"
  7. import { Npm } from "@opencode-ai/util/npm"
  8. import { tmpdir } from "./fixture/tmpdir"
  9. const win = process.platform === "win32"
  10. const writePackage = (dir: string, pkg: Record<string, unknown>) =>
  11. Bun.write(
  12. path.join(dir, "package.json"),
  13. JSON.stringify({
  14. version: "1.0.0",
  15. ...pkg,
  16. }),
  17. )
  18. const npmLayer = (cache: string) =>
  19. AppNodeBuilder.build(Npm.node, [[Global.node, Global.layerWith({ cache, state: path.join(cache, "state") })]])
  20. describe("Npm.sanitize", () => {
  21. test("keeps normal scoped package specs unchanged", () => {
  22. expect(Npm.sanitize("@opencode/acme")).toBe("@opencode/acme")
  23. expect(Npm.sanitize("@opencode/acme@1.0.0")).toBe("@opencode/acme@1.0.0")
  24. expect(Npm.sanitize("prettier")).toBe("prettier")
  25. })
  26. test("handles git https specs", () => {
  27. const spec = "acme@git+https://github.com/opencode/acme.git"
  28. const expected = win ? "acme@git+https_//github.com/opencode/acme.git" : spec
  29. expect(Npm.sanitize(spec)).toBe(expected)
  30. })
  31. })
  32. describe("Npm.add", () => {
  33. test("reifies when package cache directory exists without the package installed", async () => {
  34. await using tmp = await tmpdir()
  35. await fs.mkdir(path.join(tmp.path, "fixture-provider"))
  36. await writePackage(path.join(tmp.path, "fixture-provider"), {
  37. name: "fixture-provider",
  38. exports: {
  39. ".": "./index.js",
  40. "./tui": "./tui.js",
  41. },
  42. })
  43. await Bun.write(path.join(tmp.path, "fixture-provider", "index.js"), "export const fixture = true\n")
  44. await Bun.write(path.join(tmp.path, "fixture-provider", "tui.js"), "export const tui = true\n")
  45. const spec = `fixture-provider@file:${path.join(tmp.path, "fixture-provider")}`
  46. await fs.mkdir(path.join(tmp.path, "cache", "packages", Npm.sanitize(spec)), { recursive: true })
  47. const entries = await Effect.gen(function* () {
  48. const npm = yield* Npm.Service
  49. return {
  50. tui: yield* npm.add(spec, { subpaths: ["tui", ""] }),
  51. fallback: yield* npm.add(spec, { subpaths: ["missing", ""] }),
  52. }
  53. }).pipe(Effect.scoped, Effect.provide(npmLayer(path.join(tmp.path, "cache"))), Effect.runPromise)
  54. expect(entries.tui.entrypoint).toEndWith("/tui.js")
  55. expect(entries.fallback.entrypoint).toEndWith("/index.js")
  56. })
  57. })