upload-sea-smb.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import { mkdir, readFile, rename, rm, stat } from "node:fs/promises";
  2. import { basename, isAbsolute, relative, resolve } from "node:path";
  3. import { createInterface } from "node:readline/promises";
  4. import { pathToFileURL } from "node:url";
  5. import { outputBinaryName, supportedTargets } from "./sea-targets.mjs";
  6. import { copyReleaseFiles, createConsoleProgressReporter, fileMode } from "./upload-progress.mjs";
  7. import { resolveIntranetMachineHost } from "../../../../../scripts/intranetDefaults.mjs";
  8. import { readVerifiedNotices } from "../../../../../scripts/third-party-notices.mjs";
  9. export const resolveDefaultSmbUrl = (env = process.env) =>
  10. `smb://${resolveIntranetMachineHost(env)}/shared`;
  11. export const DEFAULT_SMB_URL = resolveDefaultSmbUrl();
  12. export const DEFAULT_MOUNT_ROOT = "/Volumes/shared";
  13. export const DEFAULT_DESTINATION_ROOT = resolve(DEFAULT_MOUNT_ROOT, "zcode", "deps");
  14. export const RELEASE_DIRECTORY_PREFIX = "zcode-cli-";
  15. const root = resolve(import.meta.dirname, "../../..");
  16. const cliRoot = resolve(import.meta.dirname, "..");
  17. const defaultDist = resolve(cliRoot, "dist");
  18. const usage = `Usage:
  19. node packages/cli/scripts/upload-sea-smb.mjs
  20. node packages/cli/scripts/upload-sea-smb.mjs --force
  21. node packages/cli/scripts/upload-sea-smb.mjs --dest-root /Volumes/shared/zcode/deps
  22. node packages/cli/scripts/upload-sea-smb.mjs --dist packages/cli/dist
  23. node packages/cli/scripts/upload-sea-smb.mjs --version 0.12.3
  24. Options:
  25. --dist <path> SEA binary dist directory. Defaults to packages/cli/dist.
  26. --dest-root <path> Mounted SMB release root. Defaults to /Volumes/shared/zcode/deps.
  27. --version <text> Release version. Defaults to the root package.json version.
  28. --smb-url <url> SMB label for messages. Defaults to ${DEFAULT_SMB_URL}.
  29. --force, -f Replace an existing version directory.
  30. --help, -h Show this help.
  31. `;
  32. export const seaUploadBinaryNames = () =>
  33. supportedTargets.map((target) => outputBinaryName(target));
  34. const resolvePath = (value, cwd) => (isAbsolute(value) ? value : resolve(cwd, value));
  35. const readArgValue = (argv, arg, index) => {
  36. if (arg.includes("=")) {
  37. return {
  38. nextIndex: index,
  39. value: arg.slice(arg.indexOf("=") + 1),
  40. };
  41. }
  42. const value = argv[index + 1];
  43. if (!value || value.startsWith("--")) {
  44. throw new Error(`Missing value for ${arg}`);
  45. }
  46. return {
  47. nextIndex: index + 1,
  48. value,
  49. };
  50. };
  51. export const parseUploadSeaSmbArgs = (argv, { cwd = process.cwd(), env = process.env } = {}) => {
  52. const options = {
  53. destinationRoot: DEFAULT_DESTINATION_ROOT,
  54. distDir: defaultDist,
  55. force: false,
  56. help: false,
  57. smbUrl: resolveDefaultSmbUrl(env),
  58. version: undefined,
  59. };
  60. for (let index = 0; index < argv.length; index += 1) {
  61. const arg = argv[index];
  62. if (arg === "--") continue;
  63. if (arg === "--help" || arg === "-h") {
  64. options.help = true;
  65. continue;
  66. }
  67. if (arg === "--force" || arg === "-f") {
  68. options.force = true;
  69. continue;
  70. }
  71. if (arg === "--dist" || arg.startsWith("--dist=")) {
  72. const { nextIndex, value } = readArgValue(argv, arg, index);
  73. options.distDir = resolvePath(value, cwd);
  74. index = nextIndex;
  75. continue;
  76. }
  77. if (arg === "--dest-root" || arg.startsWith("--dest-root=")) {
  78. const { nextIndex, value } = readArgValue(argv, arg, index);
  79. options.destinationRoot = resolvePath(value, cwd);
  80. index = nextIndex;
  81. continue;
  82. }
  83. if (arg === "--version" || arg.startsWith("--version=")) {
  84. const { nextIndex, value } = readArgValue(argv, arg, index);
  85. options.version = value;
  86. index = nextIndex;
  87. continue;
  88. }
  89. if (arg === "--smb-url" || arg.startsWith("--smb-url=")) {
  90. const { nextIndex, value } = readArgValue(argv, arg, index);
  91. options.smbUrl = value;
  92. index = nextIndex;
  93. continue;
  94. }
  95. throw new Error(`Unknown option "${arg}". Run with --help for usage.`);
  96. }
  97. return options;
  98. };
  99. const missingFileErrorCode = "ENOENT";
  100. const maybeStat = async (path) => {
  101. try {
  102. return await stat(path);
  103. } catch (error) {
  104. if (error?.code === missingFileErrorCode) return null;
  105. throw error;
  106. }
  107. };
  108. export const readRootPackageVersion = async ({ rootDirectory = root } = {}) => {
  109. const packagePath = resolve(rootDirectory, "package.json");
  110. const parsed = JSON.parse(await readFile(packagePath, "utf8"));
  111. if (typeof parsed.version !== "string" || parsed.version.trim() === "") {
  112. throw new Error(`Invalid root package version in ${packagePath}`);
  113. }
  114. return parsed.version;
  115. };
  116. export const releaseDirectoryName = (version) => {
  117. const normalized = version.trim();
  118. if (!normalized || normalized === "." || normalized === ".." || /[\\/]/.test(normalized)) {
  119. throw new Error(`Invalid release version "${version}"`);
  120. }
  121. return `${RELEASE_DIRECTORY_PREFIX}${normalized}`;
  122. };
  123. const assertInsideDirectory = ({ child, parent }) => {
  124. const childRelativePath = relative(parent, child);
  125. if (!childRelativePath || childRelativePath.startsWith("..") || isAbsolute(childRelativePath)) {
  126. throw new Error(`Refusing to write outside destination root: ${child}`);
  127. }
  128. };
  129. export const collectSeaUploadFiles = async ({ distDir }) => {
  130. const missing = [];
  131. const files = [];
  132. for (const fileName of seaUploadBinaryNames()) {
  133. const source = resolve(distDir, fileName);
  134. const fileStat = await maybeStat(source);
  135. if (!fileStat?.isFile()) {
  136. missing.push(fileName);
  137. continue;
  138. }
  139. files.push({
  140. fileName,
  141. mode: fileMode(fileStat),
  142. size: fileStat.size,
  143. source,
  144. });
  145. }
  146. if (missing.length > 0) {
  147. throw new Error(
  148. `Missing SEA binaries in ${distDir}: ${missing.join(", ")}. ` +
  149. "Run `pnpm --filter @zcode/cli build:sea` first.",
  150. );
  151. }
  152. return files;
  153. };
  154. const ensureDirectory = async (path, label) => {
  155. const pathStat = await maybeStat(path);
  156. if (!pathStat) {
  157. throw new Error(`${label} does not exist: ${path}`);
  158. }
  159. if (!pathStat.isDirectory()) {
  160. throw new Error(`${label} is not a directory: ${path}`);
  161. }
  162. };
  163. export const ensureDestinationRoot = async ({ destinationRoot, smbUrl }) => {
  164. if (destinationRoot === DEFAULT_DESTINATION_ROOT) {
  165. await ensureDirectory(
  166. DEFAULT_MOUNT_ROOT,
  167. `Default SMB mount root for ${smbUrl}. Mount ${smbUrl} before uploading`,
  168. );
  169. }
  170. await mkdir(destinationRoot, {
  171. recursive: true,
  172. });
  173. await ensureDirectory(destinationRoot, "Destination root");
  174. };
  175. export const promptExistingVersionAction = async ({
  176. destination,
  177. stdin = process.stdin,
  178. stdout = process.stdout,
  179. } = {}) => {
  180. if (!stdin.isTTY) {
  181. throw new Error(
  182. `Release directory already exists: ${destination}. ` +
  183. "Re-run with --force to replace it, or remove it manually.",
  184. );
  185. }
  186. const rl = createInterface({
  187. input: stdin,
  188. output: stdout,
  189. });
  190. try {
  191. for (;;) {
  192. const answer = (
  193. await rl.question(
  194. `Release directory already exists: ${destination}\nChoose [a]bandon or [f]orce update: `,
  195. )
  196. )
  197. .trim()
  198. .toLowerCase();
  199. if (!answer || answer === "a" || answer === "abandon") return "abandon";
  200. if (answer === "f" || answer === "force") return "force";
  201. stdout.write("Please enter `a` to abandon or `f` to force update.\n");
  202. }
  203. } finally {
  204. rl.close();
  205. }
  206. };
  207. export const uploadSeaBinaries = async ({
  208. confirmExistingVersion = promptExistingVersionAction,
  209. destinationRoot,
  210. distDir,
  211. force,
  212. onProgress = () => {},
  213. rootDirectory = root,
  214. smbUrl,
  215. version,
  216. }) => {
  217. // 修复:上传入口也执行严格材料检查,--force 只控制覆盖,不能豁免许可证缺口。
  218. await readVerifiedNotices(resolve(rootDirectory, "../.."), { requireComplete: true });
  219. const releaseVersion = version ?? (await readRootPackageVersion({ rootDirectory }));
  220. const releaseName = releaseDirectoryName(releaseVersion);
  221. const targetDirectory = resolve(destinationRoot, releaseName);
  222. const stagingDirectory = resolve(
  223. destinationRoot,
  224. `.${releaseName}.uploading-${process.pid}-${Date.now()}`,
  225. );
  226. assertInsideDirectory({
  227. child: targetDirectory,
  228. parent: destinationRoot,
  229. });
  230. assertInsideDirectory({
  231. child: stagingDirectory,
  232. parent: destinationRoot,
  233. });
  234. const files = await collectSeaUploadFiles({
  235. distDir,
  236. });
  237. const totalBytes = files.reduce((sum, file) => sum + file.size, 0);
  238. await ensureDestinationRoot({
  239. destinationRoot,
  240. smbUrl,
  241. });
  242. const existing = await maybeStat(targetDirectory);
  243. if (existing && !existing.isDirectory()) {
  244. throw new Error(`Release destination exists but is not a directory: ${targetDirectory}`);
  245. }
  246. let shouldReplace = force;
  247. if (existing && !force) {
  248. const action = await confirmExistingVersion({
  249. destination: targetDirectory,
  250. });
  251. if (action === "abandon") {
  252. return {
  253. bytes: totalBytes,
  254. destination: targetDirectory,
  255. files,
  256. status: "abandoned",
  257. version: releaseVersion,
  258. };
  259. }
  260. shouldReplace = true;
  261. }
  262. await rm(stagingDirectory, {
  263. force: true,
  264. recursive: true,
  265. });
  266. await mkdir(stagingDirectory, {
  267. recursive: true,
  268. });
  269. try {
  270. await copyReleaseFiles({
  271. files,
  272. onProgress,
  273. stagingDirectory,
  274. });
  275. if (shouldReplace) {
  276. await rm(targetDirectory, {
  277. force: true,
  278. recursive: true,
  279. });
  280. }
  281. await rename(stagingDirectory, targetDirectory);
  282. } catch (error) {
  283. await rm(stagingDirectory, {
  284. force: true,
  285. recursive: true,
  286. }).catch(() => undefined);
  287. throw error;
  288. }
  289. return {
  290. bytes: totalBytes,
  291. destination: targetDirectory,
  292. files,
  293. status: "uploaded",
  294. version: releaseVersion,
  295. };
  296. };
  297. export const main = async (argv = process.argv.slice(2)) => {
  298. const options = parseUploadSeaSmbArgs(argv);
  299. if (options.help) {
  300. process.stdout.write(usage);
  301. return;
  302. }
  303. const result = await uploadSeaBinaries({
  304. ...options,
  305. onProgress: createConsoleProgressReporter(),
  306. });
  307. if (result.status === "abandoned") {
  308. process.stdout.write(`[upload] abandoned existing release ${basename(result.destination)}\n`);
  309. return;
  310. }
  311. process.stdout.write(`[upload] uploaded ${result.files.length} files to ${result.destination}\n`);
  312. };
  313. const entryPath = process.argv[1];
  314. if (entryPath && import.meta.url === pathToFileURL(entryPath).href) {
  315. try {
  316. await main();
  317. } catch (error) {
  318. console.error(error instanceof Error ? error.message : String(error));
  319. process.exitCode = 1;
  320. }
  321. }