conversationShareBundleBoundary.test.ts 8.5 KB

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