third-party-npm.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. import { execFile } from "node:child_process";
  2. import { createHash } from "node:crypto";
  3. import { readFile, readdir, realpath } from "node:fs/promises";
  4. import { join, relative } from "node:path";
  5. import { promisify } from "node:util";
  6. import { resolveSpawnRuntimeOptions } from "./spawn-command.mjs";
  7. const exec = promisify(execFile);
  8. export const hashBytes = (bytes) => createHash("sha256").update(bytes).digest("hex");
  9. const noticeName =
  10. /(?:^|[._-])(?:licen[sc]es?|copying|notice|copyright|unlicense|third.party|ofl)(?:[._-]|$)/iu;
  11. export async function readPackageNotices(directory) {
  12. const files = [];
  13. async function visit(path) {
  14. for (const entry of await readdir(path, { withFileTypes: true })) {
  15. if (["node_modules", ".git", "test", "tests", "fixtures"].includes(entry.name)) continue;
  16. // Chromium 聚合许可由打包流程经 resources/licenses/electron 单独分发,不进 npm 通知。
  17. if (entry.isFile() && entry.name === "LICENSES.chromium.html") continue;
  18. const full = join(path, entry.name);
  19. if (entry.isDirectory()) await visit(full);
  20. else if (entry.isFile() && noticeName.test(entry.name)) {
  21. const bytes = await readFile(full);
  22. if (bytes.includes(0) || bytes.length === 0) continue;
  23. files.push({ member: relative(directory, full).replaceAll("\\", "/"), bytes });
  24. } else if (entry.isFile() && /^readme(?:\.[^/]*)?$/iu.test(entry.name)) {
  25. const text = await readFile(full, "utf8");
  26. const match = /^(?:#{1,6}\s+licen[sc]e[^\n]*\n|licen[sc]e\s*\n[=-]+\n)/imu.exec(text);
  27. if (match) {
  28. const section = text.slice(match.index).split(/\n(?=#{1,6}\s)/u)[0];
  29. files.push({
  30. member: `${relative(directory, full).replaceAll("\\", "/")} (license section)`,
  31. bytes: Buffer.from(section),
  32. });
  33. }
  34. }
  35. }
  36. }
  37. await visit(directory);
  38. return files.sort((a, b) => a.member.localeCompare(b.member, "en"));
  39. }
  40. // 解析锁文件(v9)packages 段的平台约束:` 'name@version':` 下的 ` os/cpu/libc: [..]` 行。
  41. export function readLockfilePlatformConstraints(lockfileText) {
  42. const constraints = new Map();
  43. let inPackages = false;
  44. let key = null;
  45. for (const line of lockfileText.split(/\r?\n/u)) {
  46. if (/^\S/u.test(line)) {
  47. inPackages = line === "packages:";
  48. key = null;
  49. continue;
  50. }
  51. if (!inPackages) continue;
  52. const header = /^ {2}(?:'([^']+)'|([^\s'][^:]*)):$/u.exec(line);
  53. if (header) {
  54. key = header[1] ?? header[2];
  55. continue;
  56. }
  57. const field = key && /^ {4}(os|cpu|libc): \[(.*)\]$/u.exec(line);
  58. if (field) {
  59. const values = field[2]
  60. .split(",")
  61. .map((value) => value.trim().replace(/^'(.*)'$/u, "$1"))
  62. .filter(Boolean);
  63. constraints.set(key, { ...constraints.get(key), [field[1]]: values });
  64. }
  65. }
  66. return constraints;
  67. }
  68. // 照搬 pnpm package-is-installable 的 checkList,保证与实际安装结果一致(含否定项语义)。
  69. function pnpmCheckList(values, list) {
  70. if (list.length === 1 && list[0] === "any") return true;
  71. let match = false;
  72. let blc = 0;
  73. for (const value of values) {
  74. for (const item of list) {
  75. if (item[0] === "!") {
  76. if (item.slice(1) === value) return false;
  77. ++blc;
  78. } else {
  79. match = match || item === value;
  80. }
  81. }
  82. }
  83. return match || blc === list.length;
  84. }
  85. // targets.libc 为 null 表示宿主 libc 未知(非 Linux),pnpm 此时不检查 libc。
  86. export function createInstallablePackageFilter(constraints, targets) {
  87. return (name, version) => {
  88. const wanted = constraints.get(`${name}@${version.split("(")[0]}`);
  89. if (!wanted) return true;
  90. if (wanted.os && !pnpmCheckList(targets.os, wanted.os)) return false;
  91. if (wanted.cpu && !pnpmCheckList(targets.cpu, wanted.cpu)) return false;
  92. if (wanted.libc && targets.libc && !pnpmCheckList(targets.libc, wanted.libc)) return false;
  93. return true;
  94. };
  95. }
  96. function hostLibc() {
  97. if (process.platform !== "linux") return null;
  98. return process.report?.getReport?.()?.header?.glibcVersionRuntime ? "glibc" : "musl";
  99. }
  100. // 与 pnpm checkPlatform 相同:supportedArchitectures 未配置时只取宿主,`current` 替换为宿主值。
  101. export async function readInstallTargets(root) {
  102. const { parse } = await import("yaml");
  103. const workspace = parse(await readFile(join(root, "pnpm-workspace.yaml"), "utf8")) ?? {};
  104. const supported = workspace.supportedArchitectures ?? {};
  105. const resolveCurrent = (list, current) =>
  106. (list ?? ["current"]).map((value) => (value === "current" ? current : value));
  107. const libc = hostLibc();
  108. return {
  109. os: resolveCurrent(supported.os, process.platform),
  110. cpu: resolveCurrent(supported.cpu, process.arch),
  111. libc: libc ? resolveCurrent(supported.libc, libc) : null,
  112. };
  113. }
  114. // 修复:pnpm 按 supportedArchitectures 跳过的平台包(如 sharp 的 s390x/wasm32 构建)从不安装、不分发,
  115. // 此前靠按包名的例外名单放行,新依赖一引入就会误报缺失;现在按锁文件平台约束整棵子树跳过。
  116. export function productionPackages(projects, isInstallable = () => true) {
  117. const own = new Set(projects.map((project) => project.name));
  118. const required = new Map();
  119. function dependencies(deps) {
  120. for (const [alias, info] of Object.entries(deps ?? {})) {
  121. const name = info.name ?? alias;
  122. if (!isInstallable(name, info.version)) continue;
  123. if (!own.has(name) && !name.startsWith("@zcode/") && !info.version.startsWith("link:")) {
  124. required.set(`${name}@${info.version}`, { name, version: info.version });
  125. }
  126. dependencies(info.dependencies);
  127. dependencies(info.optionalDependencies);
  128. }
  129. }
  130. for (const project of projects) {
  131. dependencies(project.dependencies);
  132. dependencies(project.optionalDependencies);
  133. }
  134. return required;
  135. }
  136. export function assertProductionGraphs(lockedProjects, installedProjects, isInstallable) {
  137. const locked = productionPackages(lockedProjects, isInstallable);
  138. const installed = productionPackages(installedProjects, isInstallable);
  139. const missing = [...locked].filter(([key]) => !installed.has(key));
  140. const stale = [...installed.keys()].filter((key) => !locked.has(key));
  141. if (missing.length || stale.length) {
  142. throw new Error(
  143. `Installed production graph differs from pnpm-lock.yaml. Run pnpm install --frozen-lockfile.\nMissing: ${missing.map(([key]) => key).join(", ")}\nStale: ${stale.join(", ")}`,
  144. );
  145. }
  146. return locked;
  147. }
  148. export async function readWorkspaceProductionGraph(root) {
  149. root = await realpath(root);
  150. // 修复:pnpm ls 默认读取安装快照,不能把旧图与当前锁文件哈希拼成有效声明。
  151. const [locked, actual] = await Promise.all(
  152. [true, false].map(async (lockfileOnly) => {
  153. const { stdout } = await exec(
  154. "pnpm",
  155. [
  156. "-r",
  157. "ls",
  158. "--prod",
  159. "--json",
  160. "--depth",
  161. "Infinity",
  162. ...(lockfileOnly ? ["--lockfile-only"] : []),
  163. ],
  164. {
  165. cwd: root,
  166. maxBuffer: 256 * 1024 * 1024,
  167. ...resolveSpawnRuntimeOptions("pnpm"),
  168. },
  169. );
  170. return JSON.parse(stdout);
  171. }),
  172. );
  173. const isInstallable = createInstallablePackageFilter(
  174. readLockfilePlatformConstraints(await readFile(join(root, "pnpm-lock.yaml"), "utf8")),
  175. await readInstallTargets(root),
  176. );
  177. const required = assertProductionGraphs(locked, actual, isInstallable);
  178. return { required, projects: actual };
  179. }
  180. export async function scanInstalledPackages(root, projects) {
  181. // pnpm hoisted 布局的 ls.path 仍可能指向不存在的 .pnpm 路径;按真实安装目录和精确版本匹配。
  182. const installed = new Map();
  183. const visited = new Set();
  184. async function scanNodeModules(directory) {
  185. let actual;
  186. try {
  187. actual = await realpath(directory);
  188. } catch (error) {
  189. if (error.code === "ENOENT") return;
  190. throw error;
  191. }
  192. if (visited.has(actual)) return;
  193. visited.add(actual);
  194. const entries = await readdir(directory, { withFileTypes: true });
  195. for (const entry of entries) {
  196. if (entry.name.startsWith(".")) continue;
  197. const path = join(directory, entry.name);
  198. if (entry.name.startsWith("@")) {
  199. for (const scoped of await readdir(path)) await scanPackage(join(path, scoped));
  200. } else await scanPackage(path);
  201. }
  202. }
  203. async function scanPackage(directory) {
  204. let pkg;
  205. try {
  206. pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8"));
  207. } catch (error) {
  208. if (["ENOENT", "ENOTDIR"].includes(error.code)) return;
  209. throw error;
  210. }
  211. if (pkg.name && pkg.version) installed.set(`${pkg.name}@${pkg.version}`, { pkg, directory });
  212. await scanNodeModules(join(directory, "node_modules"));
  213. }
  214. for (const project of projects) await scanNodeModules(join(project.path, "node_modules"));
  215. await scanNodeModules(join(root, "node_modules"));
  216. await scanNodeModules(join(root, "apps/zcode-cli/node_modules"));
  217. return installed;
  218. }
  219. export function missingProductionPackages(required, installed) {
  220. const missing = [...required].filter(([key]) => !installed.has(key)).map(([, item]) => item);
  221. for (const item of missing) {
  222. throw new Error(`Missing installed dependency: ${item.name}@${item.version}`);
  223. }
  224. return missing;
  225. }
  226. export async function collectNpmNotices(root, overrides) {
  227. root = await realpath(root);
  228. const { required, projects } = await readWorkspaceProductionGraph(root);
  229. // 修复:标识门禁和声明生成必须扫描同一安装集合,避免嵌套版本只进声明、不进门禁。
  230. const installed = await scanInstalledPackages(root, projects);
  231. const packages = [];
  232. const missing = [];
  233. const notInstalled = missingProductionPackages(required, installed);
  234. for (const [key, item] of [...required].sort(([a], [b]) => a.localeCompare(b, "en"))) {
  235. const installedPackage = installed.get(key);
  236. if (!installedPackage) {
  237. continue;
  238. }
  239. const { pkg, directory } = installedPackage;
  240. const notices = await readPackageNotices(directory);
  241. const override = overrides.find((record) => record.package === key);
  242. if (override?.file) {
  243. const bytes = await readFile(join(root, override.file));
  244. if (hashBytes(bytes) !== override.sha256) throw new Error(`Changed upstream notice: ${key}`);
  245. notices.push({ member: override.source, bytes });
  246. }
  247. // README 中仅有 MIT 等标签不能冒充完整许可文件;这种包仍需要版本固定的补充材料。
  248. if (
  249. !notices.some(({ member }) => !member.endsWith(" (license section)")) &&
  250. !override?.acceptedMissingNotice
  251. )
  252. missing.push(key);
  253. packages.push({
  254. ...item,
  255. license:
  256. pkg.license ??
  257. pkg.licenses?.map((item) => (typeof item === "string" ? item : item.type)).join(" OR ") ??
  258. override?.license ??
  259. "(not declared)",
  260. repository: typeof pkg.repository === "string" ? pkg.repository : pkg.repository?.url,
  261. ...(override?.acceptedMissingNotice
  262. ? { acceptedMissingNotice: override.acceptedMissingNotice }
  263. : {}),
  264. notices,
  265. });
  266. }
  267. if (missing.length) throw new Error(`Missing complete upstream notices:\n${missing.join("\n")}`);
  268. return {
  269. packages,
  270. notInstalled,
  271. workspaceManifests: projects.map((project) =>
  272. relative(root, join(project.path, "package.json")).replaceAll("\\", "/"),
  273. ),
  274. };
  275. }