path.test.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { describe, expect, it } from "vitest";
  2. import { getContainingDirectoryPath, toFileUrl } from "@/lib/path.js";
  3. import { getModelTrajectorySourceDirectory } from "@/ModelTrajectoryPane.js";
  4. describe("path helpers", () => {
  5. it("解析 POSIX 和 Windows 文件的所在目录", () => {
  6. expect(getContainingDirectoryPath("/Users/dev/.zcode/cli/debug/model-io.jsonl")).toBe(
  7. "/Users/dev/.zcode/cli/debug",
  8. );
  9. expect(getContainingDirectoryPath("C:\\Users\\dev\\.zcode\\cli\\debug\\model-io.jsonl")).toBe(
  10. "C:\\Users\\dev\\.zcode\\cli\\debug",
  11. );
  12. expect(getContainingDirectoryPath("C:\\model-io.jsonl")).toBe("C:\\");
  13. expect(getContainingDirectoryPath("/model-io.jsonl")).toBe("/");
  14. });
  15. it("调用轨迹源文件目录会跳过空路径并回退到首个有效源文件", () => {
  16. expect(
  17. getModelTrajectorySourceDirectory([" ", "/Users/dev/.zcode/cli/rollout/model-io.jsonl"]),
  18. ).toBe("/Users/dev/.zcode/cli/rollout");
  19. expect(getModelTrajectorySourceDirectory(["model-io.jsonl"])).toBeNull();
  20. expect(getModelTrajectorySourceDirectory(undefined)).toBeNull();
  21. });
  22. // ZCT-2096502552646832128:encodeURI 不转义 # / ?,文件名含 # 时下游 URL 解析
  23. // 会把其后内容当 fragment,pathname 截断、shell 打开必然失败。回归以
  24. // new URL().pathname 的完整性为准——它才是真实消费路径(白名单与 fileURLToPath)。
  25. describe("toFileUrl", () => {
  26. it("Windows 盘符 + 中文 + 空格路径完整编码且可被 URL 解析还原", () => {
  27. const url = toFileUrl("E:\\web\\报告 v2.html");
  28. expect(url).toBe("file:///E:/web/%E6%8A%A5%E5%91%8A%20v2.html");
  29. expect(new URL(url).pathname).toBe("/E:/web/%E6%8A%A5%E5%91%8A%20v2.html");
  30. });
  31. it("文件名含 # 时转义为 %23,pathname 不被 fragment 截断", () => {
  32. const url = toFileUrl("E:\\web\\index#anchor.html");
  33. expect(url).toBe("file:///E:/web/index%23anchor.html");
  34. expect(new URL(url).hash).toBe("");
  35. expect(new URL(url).pathname).toBe("/E:/web/index%23anchor.html");
  36. });
  37. it("POSIX 路径含 # / ? / 空格 时同样完整转义", () => {
  38. const url = toFileUrl("/tmp/what? q#1.html");
  39. expect(url).toBe("file:///tmp/what%3F%20q%231.html");
  40. expect(new URL(url).pathname).toBe("/tmp/what%3F%20q%231.html");
  41. expect(new URL(url).search).toBe("");
  42. expect(new URL(url).hash).toBe("");
  43. });
  44. it("字面 % 字符被编码,不产生畸形 percent-encoding", () => {
  45. const url = toFileUrl("E:\\web\\50%.html");
  46. expect(url).toBe("file:///E:/web/50%25.html");
  47. expect(new URL(url).pathname).toBe("/E:/web/50%25.html");
  48. });
  49. it("纯 ASCII POSIX 路径保持既有输出不变", () => {
  50. expect(toFileUrl("/tmp/plain.html")).toBe("file:///tmp/plain.html");
  51. });
  52. });
  53. });