conversationShareBundleBoundary.test.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import { readFileSync } from "node:fs";
  2. import { dirname, relative, resolve } from "node:path";
  3. import { fileURLToPath } from "node:url";
  4. import { describe, expect, it } from "vitest";
  5. // SG-01 静态守卫:公开匿名分享页(packages/web/src/share)直接引用的只读时间线必须物理
  6. // 排除 open-with 子树(OpenSplitButton → platform hooks、tab store、workspace-file-tree、
  7. // editorPreference 等 Desktop 专属依赖)。此前该边界只靠源码注释与 spec 约束:重新加回
  8. // 静态值 import 不会有任何测试失败,公开页 bundle 会被无声撑大并引入无 Desktop 宿主的
  9. // 运行时依赖。这里读取源码做机械断言(照搬 markdownTableStickyScrollbar.test.ts 的
  10. // readFileSync 先例),denylist 模块只允许 `import type`(构建期擦除)。
  11. //
  12. // 盲区修复记录:首版守卫只匹配「行首 + 带 from 子句」的 import,且 denylist 键是 `@/`
  13. // 别名字面量,副作用导入 `import "@/x"`、动态 `import("@/x")`、相对路径
  14. // `from "../../x"`(IDE 自动补全常见产物)三种写法可无声绕过。因此这里把 specifier
  15. // 解析统一归一化后再比对,并覆盖副作用 / 动态 / re-export 三种额外形态。
  16. const UI_SRC_ROOT = fileURLToPath(new URL("../src", import.meta.url));
  17. const SHARE_BOUNDARY_SOURCES = ["v4/ConversationShareReadonlyTimeline.tsx"] as const;
  18. // denylist:会把 Desktop 专属子树拖进公开页 bundle 的模块根。@/OpenSplitButton.js 是
  19. // open-with 子树的入口;其余条目是其 Desktop 专属依赖,防止绕过入口直接静态引入。
  20. // specifier 会先归一化成 @/ 形态,因此 denylist 统一只存别名字面量。
  21. // 新增边界文件或 denylist 条目时在此追加。
  22. const VALUE_IMPORT_DENYLIST: ReadonlySet<string> = new Set([
  23. "@/OpenSplitButton.js",
  24. "@/hooks/usePlatform.js",
  25. "@/hooks/useFileContextActions.js",
  26. "@/hooks/useWorkspaceOpenInEditorTarget.js",
  27. "@/lib/editorPreference.js",
  28. "@/lib/workspaceEditorSelection.js",
  29. "@/workspace-file-tree/model.js",
  30. ]);
  31. type DeniedValueImportKind = "from-clause" | "side-effect" | "dynamic-import";
  32. interface DeniedValueImport {
  33. specifier: string;
  34. kind: DeniedValueImportKind;
  35. }
  36. /**
  37. * 把边界文件里的 import specifier 归一化成 `@/` 别名形态。
  38. *
  39. * 修复原因:denylist 只存别名字面量时,`from "../../OpenSplitButton.js"` 这种 IDE
  40. * 自动补全产物解析到同一模块却比对失败,等于换一种写法就绕过守卫。这里以 ui 包
  41. * src 根为锚点 resolve 相对路径,折算回别名形态;解析后落在 src 外的(正常不该出现)
  42. * 保留原样交给字面量比对兜底。分隔符统一成 `/`,保证 Windows 上与 denylist 可比。
  43. */
  44. function normalizeSpecifier(sourceDir: string, specifier: string): string {
  45. if (!specifier.startsWith(".")) return specifier;
  46. const fromSrcRoot = relative(UI_SRC_ROOT, resolve(sourceDir, specifier)).replaceAll("\\", "/");
  47. return fromSrcRoot.startsWith("..") ? specifier : `@/${fromSrcRoot}`;
  48. }
  49. /**
  50. * 提取边界源码中所有命中 denylist 的「值引入」。
  51. *
  52. * 覆盖四种形态:
  53. * 1. `import <clause> from "..."` —— 仅 `import type` 构建期擦除,其余计入;
  54. * 2. `export <clause> from "..."` —— re-export 同样会把值拖进 bundle,同 1 判定;
  55. * 3. `import "..."` 副作用导入 —— 不存在 type 擦除变体,命中即计入;
  56. * 4. `import("...")` 动态导入 —— 会为公开页生成异步 chunk,命中即计入。
  57. * from 子句正则的 `[^"']*?` 含换行,因此多行 import 也能匹配;`^import` 限定行首,
  58. * 避免命中行尾注释。
  59. */
  60. function findDeniedValueImports(source: string, sourceDir: string): DeniedValueImport[] {
  61. const violations: DeniedValueImport[] = [];
  62. const fromClausePatterns: ReadonlyArray<readonly [RegExp, DeniedValueImportKind]> = [
  63. [/^import\s+([^"']*?)\s+from\s*["']([^"']+)["']/gm, "from-clause"],
  64. [/^export\s+([^"']*?)\s+from\s*["']([^"']+)["']/gm, "from-clause"],
  65. ];
  66. for (const [pattern, kind] of fromClausePatterns) {
  67. for (const match of source.matchAll(pattern)) {
  68. const clause = match[1] ?? "";
  69. const specifier = normalizeSpecifier(sourceDir, match[2] ?? "");
  70. // 只认整句 `import type` / `export type`。`import { type X }` 内联形式虽也会被
  71. // 擦除,但边界文件统一用 `import type` 写法,收紧成单一形态让 denylist 审查
  72. // 不因两种写法变松。
  73. if (VALUE_IMPORT_DENYLIST.has(specifier) && !/^type\b/u.test(clause)) {
  74. violations.push({ specifier, kind });
  75. }
  76. }
  77. }
  78. const bareSpecifierPatterns: ReadonlyArray<readonly [RegExp, DeniedValueImportKind]> = [
  79. [/^import\s+["']([^"']+)["']/gm, "side-effect"],
  80. [/\bimport\s*\(\s*["']([^"']+)["']/g, "dynamic-import"],
  81. ];
  82. for (const [pattern, kind] of bareSpecifierPatterns) {
  83. for (const match of source.matchAll(pattern)) {
  84. const specifier = normalizeSpecifier(sourceDir, match[1] ?? "");
  85. if (VALUE_IMPORT_DENYLIST.has(specifier)) violations.push({ specifier, kind });
  86. }
  87. }
  88. return violations;
  89. }
  90. describe("conversation share public-page bundle boundary", () => {
  91. it("分享只读时间线对 open-with 子树只允许 import type 引用", () => {
  92. for (const sourceRelPath of SHARE_BOUNDARY_SOURCES) {
  93. const sourcePath = resolve(UI_SRC_ROOT, sourceRelPath);
  94. const violations = findDeniedValueImports(
  95. readFileSync(sourcePath, "utf8"),
  96. dirname(sourcePath),
  97. );
  98. expect(
  99. violations,
  100. `${sourceRelPath} 对 open-with 子树存在静态值 import(公开页 bundle 边界回归):` +
  101. JSON.stringify(violations) +
  102. "。Desktop 侧能力请改由消费方经组件注入(见 artifactOpenAction 注入契约)。",
  103. ).toEqual([]);
  104. }
  105. });
  106. // 守卫自身的回归测试:首版正则漏掉的三类写法必须都能被抓到,防止未来改提取器时
  107. // 重新引入盲区(机器守卫的价值取决于最难被绕过的形态)。
  108. describe("denylist 提取器形态覆盖(盲区自测)", () => {
  109. // 用比边界文件更深的虚拟目录模拟 IDE 补全的多层相对路径;relative 只做路径
  110. // 计算,不要求目录真实存在。
  111. const sourceDir = resolve(UI_SRC_ROOT, "v4/share/nested");
  112. it("多层相对路径 from 子句按别名根归一化后命中 denylist", () => {
  113. const violations = findDeniedValueImports(
  114. 'import { OpenSplitButton } from "../../../OpenSplitButton.js";\n',
  115. sourceDir,
  116. );
  117. expect(violations).toEqual([{ specifier: "@/OpenSplitButton.js", kind: "from-clause" }]);
  118. });
  119. it("副作用导入(无 from 子句)命中 denylist", () => {
  120. const violations = findDeniedValueImports(
  121. 'import "@/OpenSplitButton.js";\n',
  122. sourceDir,
  123. );
  124. expect(violations).toEqual([{ specifier: "@/OpenSplitButton.js", kind: "side-effect" }]);
  125. });
  126. it("动态 import() 命中 denylist(公开页会生成异步 chunk)", () => {
  127. const violations = findDeniedValueImports(
  128. 'const mod = await import("@/OpenSplitButton.js");\n',
  129. sourceDir,
  130. );
  131. expect(violations).toEqual([{ specifier: "@/OpenSplitButton.js", kind: "dynamic-import" }]);
  132. });
  133. it("re-export 值形态命中 denylist", () => {
  134. const violations = findDeniedValueImports(
  135. 'export { OpenSplitButton } from "@/OpenSplitButton.js";\n',
  136. sourceDir,
  137. );
  138. expect(violations).toEqual([{ specifier: "@/OpenSplitButton.js", kind: "from-clause" }]);
  139. });
  140. it("import type / export type / 非 denylist 模块不产生违规", () => {
  141. const violations = findDeniedValueImports(
  142. [
  143. 'import type { OpenSplitButtonTarget } from "@/OpenSplitButton.js";',
  144. 'export type { OpenSplitButtonTarget } from "@/OpenSplitButton.js";',
  145. 'import { TooltipProvider } from "@/components/ui/tooltip.js";',
  146. 'const x = await import("@zcode/shared");',
  147. ].join("\n"),
  148. sourceDir,
  149. );
  150. expect(violations).toEqual([]);
  151. });
  152. });
  153. });