zcode-site.mjs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  1. #!/usr/bin/env node
  2. // zcode-site:ZCode Sites 的命令行客户端(技术方案 4.2、4.3、5.3)。
  3. // deploy 的输入是 Agent 准备好的 stage 目录,打包与契约检查、以及本地命令 check 在 stage.mjs;其余只和云端交互,不探测项目。
  4. // 命令、参数、输出和错误码的完整说明只写在 HELP 里(`zcode-site help`),site-deploy skill 引用它,不再重复。
  5. //
  6. // 输出契约:成功时 stdout 输出 JSON,退出码 0;deploy 过程中每个阶段和每条日志各输出一行 JSON(--quiet 只输出终态)。
  7. // 失败时 stderr 输出一行 {"error":{code,message,hint}},退出码 1=参数或本地文件错误、2=未登录、3=超出额度或限额、4=部署失败或服务端错误。
  8. //
  9. // 鉴权(技术方案 5.8):CLI 不持有任何登录凭证。请求发给 ZCode agent 侧的官方命令端点,端点按
  10. // session token 认出会话,补上 ZCode 身份头和 X-ZCode-App-Version 后转发给 zcode-server。
  11. // 端点地址和 token 由 ZCode 注入当前会话的 Bash,在普通终端里运行会按未登录退出:
  12. // ZCODE_OFFICIAL_ENDPOINT 端点地址(macOS / Linux 是 UDS 路径,Windows 是命名管道)
  13. // ZCODE_OFFICIAL_ENDPOINT_TOKEN 本会话的 token
  14. import { realpathSync } from "node:fs";
  15. import { request as httpRequest } from "node:http";
  16. import { readFile, rm, writeFile } from "node:fs/promises";
  17. import { basename, join } from "node:path";
  18. import { pathToFileURL } from "node:url";
  19. import { parseArgs } from "node:util";
  20. import { apiError, CliError, localError } from "./errors.mjs";
  21. import { checkStage, packStage } from "./stage.mjs";
  22. const BINDING_FILE = ".zcode-site.json";
  23. const POLL_INTERVAL_MS = 2000;
  24. // 服务端兜底清理会把 publishing / verifying 超 10 分钟的部署置为 failed,这里多等一点再放弃。
  25. const POLL_TIMEOUT_MS = 15 * 60 * 1000;
  26. const UPLOAD_ATTEMPTS = 3;
  27. const IN_FLIGHT = new Set(["preparing", "uploading", "publishing", "verifying"]);
  28. const RESUMABLE = new Set(["preparing", "uploading"]);
  29. // 统计在服务端 5 秒内没算完时返回 computing,后台继续算;按契约每 3 秒再读,最多约 1 分钟。
  30. const ANALYTICS_RANGES = ["24h", "7d", "30d"];
  31. const ANALYTICS_RETRY_MS = 3000;
  32. const ANALYTICS_ATTEMPTS = 20;
  33. // ---------- 鉴权与 API ----------
  34. const ENDPOINT_ORIGIN = "http://zcode-official-endpoint";
  35. // 端点自己产生的错误经这个响应头说明类型;network 表示端点连不上 zcode-server。
  36. const ENDPOINT_ERROR_HEADER = "x-zcode-official-endpoint-error";
  37. function loadEndpoint(env) {
  38. const address = env.ZCODE_OFFICIAL_ENDPOINT?.trim();
  39. const token = env.ZCODE_OFFICIAL_ENDPOINT_TOKEN?.trim();
  40. if (!address || !token) {
  41. throw new CliError(
  42. "UNAUTHENTICATED",
  43. "ZCode credentials are not available",
  44. "Run zcode-site from a ZCode session (the Sites plugin must be enabled), then retry.",
  45. 2,
  46. );
  47. }
  48. return { address, token };
  49. }
  50. // 经 UDS / 命名管道发 HTTP 请求,返回标准 Response,和 fetch 同形状(测试注入 fetchImpl 替换它)。
  51. export function createEndpointFetch(address) {
  52. return (url, init = {}) =>
  53. new Promise((resolve, reject) => {
  54. const { pathname, search } = new URL(url);
  55. const headers = { ...init.headers };
  56. if (init.body !== undefined) headers["Content-Length"] = String(Buffer.byteLength(init.body));
  57. const req = httpRequest(
  58. { socketPath: address, path: pathname + search, method: init.method ?? "GET", headers },
  59. (res) => {
  60. const chunks = [];
  61. res.on("data", (chunk) => chunks.push(chunk));
  62. res.on("error", reject);
  63. res.on("aborted", () =>
  64. reject(new Error("the connection was closed before the response ended")),
  65. );
  66. res.on("end", () => {
  67. if (!res.complete)
  68. return reject(new Error("the connection was closed before the response ended"));
  69. const responseHeaders = new Headers();
  70. for (const [name, value] of Object.entries(res.headers)) {
  71. if (value !== undefined)
  72. responseHeaders.set(name, Array.isArray(value) ? value.join(", ") : value);
  73. }
  74. const status = res.statusCode ?? 502;
  75. const nullBody = status === 204 || status === 205 || status === 304;
  76. resolve(
  77. new Response(nullBody ? null : Buffer.concat(chunks), {
  78. status,
  79. headers: responseHeaders,
  80. }),
  81. );
  82. });
  83. },
  84. );
  85. req.on("error", reject);
  86. req.end(init.body);
  87. });
  88. }
  89. function createClient(endpoint, fetchImpl) {
  90. // body 是 JSON 对象;Buffer 原样作为请求体发送(产物包),按长度带上 Content-Length。
  91. async function call(method, path, body) {
  92. const headers = { Authorization: `Bearer ${endpoint.token}` };
  93. const raw = Buffer.isBuffer(body);
  94. if (body !== undefined) headers["Content-Type"] = raw ? "application/gzip" : "application/json";
  95. let res;
  96. try {
  97. res = await fetchImpl(ENDPOINT_ORIGIN + path, {
  98. method,
  99. headers,
  100. body: body === undefined || raw ? body : JSON.stringify(body),
  101. });
  102. } catch (err) {
  103. throw new CliError(
  104. "NETWORK_ERROR",
  105. `Cannot reach the Sites API: ${err.message}`,
  106. "Check the network connection to ZCode and retry.",
  107. 4,
  108. );
  109. }
  110. if (res.headers.get(ENDPOINT_ERROR_HEADER) === "network") {
  111. throw new CliError(
  112. "NETWORK_ERROR",
  113. "ZCode cannot reach the Sites API",
  114. "Check the network connection and retry.",
  115. 4,
  116. );
  117. }
  118. const text = await res.text();
  119. let parsed;
  120. try {
  121. parsed = text ? JSON.parse(text) : undefined;
  122. } catch {
  123. parsed = undefined;
  124. }
  125. if (!res.ok || parsed?.code !== 0) throw apiError(res.status, parsed);
  126. return parsed.data;
  127. }
  128. return {
  129. listSites: (cursor) =>
  130. call(
  131. "GET",
  132. `/api/v1/sites?limit=100${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`,
  133. ),
  134. // domainPrefix 不传时服务端按 name 规范化(openapi createSite)。
  135. createSite: (name, domainPrefix) =>
  136. call("POST", "/api/v1/sites", domainPrefix === undefined ? { name } : { name, domainPrefix }),
  137. getSite: (id) => call("GET", `/api/v1/sites/${id}`),
  138. updateSite: (id, patch) => call("PATCH", `/api/v1/sites/${id}`, patch),
  139. createDeployment: (siteId, artifactSize) =>
  140. call("POST", `/api/v1/sites/${siteId}/deployments`, { artifactSize }),
  141. getDeployment: (siteId, id) => call("GET", `/api/v1/sites/${siteId}/deployments/${id}`),
  142. uploadPackage: (siteId, id, body) =>
  143. call("PUT", `/api/v1/sites/${siteId}/deployments/${id}/package`, body),
  144. logs: (siteId, id, offset) =>
  145. call("GET", `/api/v1/sites/${siteId}/deployments/${id}/logs?offset=${offset}`),
  146. usage: () => call("GET", "/api/v1/sites/usage"),
  147. analytics: (siteId, range) =>
  148. call("GET", `/api/v1/sites/${siteId}/analytics?range=${encodeURIComponent(range)}`),
  149. deleteSite: (id) => call("DELETE", `/api/v1/sites/${id}`),
  150. };
  151. }
  152. // ---------- 站点绑定(技术方案 4.3) ----------
  153. async function readBinding(cwd) {
  154. let text;
  155. try {
  156. text = await readFile(join(cwd, BINDING_FILE), "utf8");
  157. } catch (err) {
  158. if (err.code === "ENOENT") return undefined;
  159. throw err;
  160. }
  161. try {
  162. const b = JSON.parse(text);
  163. if (typeof b.siteId === "string" && b.siteId) return b;
  164. } catch {
  165. // 落到下面统一报错
  166. }
  167. throw localError(
  168. "INVALID_BINDING",
  169. `${BINDING_FILE} is not valid`,
  170. `Fix or delete ${BINDING_FILE}, or pass --site <id>.`,
  171. );
  172. }
  173. async function writeBinding(cwd, site) {
  174. await writeFile(
  175. join(cwd, BINDING_FILE),
  176. `${JSON.stringify({ siteId: site.id, domainLabel: site.domainLabel }, null, 2)}\n`,
  177. );
  178. }
  179. async function allSites(client) {
  180. const items = [];
  181. let cursor;
  182. do {
  183. const page = await client.listSites(cursor);
  184. items.push(...page.items);
  185. cursor = page.nextCursor;
  186. } while (cursor);
  187. return items;
  188. }
  189. function candidates(sites) {
  190. return sites.map((s) => ({ id: s.id, name: s.name, url: s.url, status: s.status }));
  191. }
  192. // resolveSite 的规则:--site > 绑定文件 > 账户下没有站点时(只限 deploy)新建;已有站点时报错并给出候选,不按名字匹配,也不自动新建。
  193. async function resolveSite(ctx, { allowCreate }) {
  194. const { client, cwd, opts } = ctx;
  195. if (opts.site) return { site: await client.getSite(opts.site), bound: false };
  196. const binding = await readBinding(cwd);
  197. if (binding) return { site: await client.getSite(binding.siteId), bound: true };
  198. if (allowCreate && opts.new)
  199. return {
  200. site: await client.createSite(siteName(ctx), opts.prefix),
  201. bound: false,
  202. created: true,
  203. };
  204. const sites = await allSites(client);
  205. if (allowCreate && sites.length === 0)
  206. return {
  207. site: await client.createSite(siteName(ctx), opts.prefix),
  208. bound: false,
  209. created: true,
  210. };
  211. throw new CliError(
  212. "SITE_NOT_SELECTED",
  213. sites.length ? "This project is not linked to a site" : "You have no sites yet",
  214. allowCreate
  215. ? "Ask the user which site to update, then retry with --site <id>, or with --new to create a new site."
  216. : "Pass --site <id>, or deploy first.",
  217. 1,
  218. { candidates: candidates(sites) },
  219. );
  220. }
  221. function siteName(ctx) {
  222. return (ctx.opts.name ?? basename(ctx.cwd)).trim() || "site";
  223. }
  224. // normalizePrefix 与服务端 site.NormalizePrefix 同一规则(技术方案 5.4),只用来提前告诉 Agent 实际会得到的前缀;
  225. // 发给服务端的仍是原值,以服务端规范化的结果为准。
  226. export function normalizePrefix(prefix) {
  227. let s = prefix
  228. .toLowerCase()
  229. .replace(/[^a-z0-9]+/g, "-")
  230. .replace(/^-+|-+$/g, "");
  231. if (s.length > 30) s = s.slice(0, 30).replace(/-+$/, "");
  232. return s.length < 4 ? "site" : s;
  233. }
  234. // --prefix 只在本次新建站点时生效;不合规时提示规范化结果,但不拦截,交给服务端兜底。
  235. // 前缀(没有 --prefix 时是名称)没有通过服务端机审时,服务端换成 site,按返回的 domainLabel 提示(契约 0.15.0)。
  236. function prefixNotice(opts, created, site) {
  237. if (!created)
  238. return opts.prefix === undefined
  239. ? undefined
  240. : "--prefix is ignored: the site already exists. Change its domain with `zcode-site prefix <prefix>`.";
  241. const expected = normalizePrefix(opts.prefix ?? site.name);
  242. if (expected !== "site" && !site.domainLabel.startsWith(`${expected}-`))
  243. return `The domain prefix ${JSON.stringify(expected)} did not pass content review, so the server used "site": the domain is ${site.url}. Change it with \`zcode-site prefix <prefix>\`.`;
  244. if (opts.prefix === undefined) return undefined;
  245. const normalized = expected;
  246. if (normalized === opts.prefix) return undefined;
  247. return normalized === "site"
  248. ? `--prefix ${JSON.stringify(opts.prefix)} has fewer than 4 usable [a-z0-9-] characters; the server falls back to "site".`
  249. : `--prefix ${JSON.stringify(opts.prefix)} is normalized to ${JSON.stringify(normalized)}.`;
  250. }
  251. // ---------- deploy ----------
  252. async function deploy(ctx, stageDir) {
  253. const { client, out, opts } = ctx;
  254. if (!stageDir)
  255. throw localError(
  256. "MISSING_STAGE",
  257. "Missing stage directory",
  258. "Usage: zcode-site deploy <stage-dir> [--new | --site <id>]",
  259. );
  260. if (opts.site && opts.new)
  261. throw localError(
  262. "INVALID_ARGS",
  263. "--site and --new cannot be used together",
  264. "Pass only one of them.",
  265. );
  266. // 先打包再选站点:契约检查不过时不建站、不建部署。
  267. const packed = await packStage(stageDir, {
  268. cwd: ctx.cwd,
  269. allowForeignBinaries: opts["allow-foreign-binaries"],
  270. });
  271. if (packed.error)
  272. throw localError(packed.error, packed.message, "Pass the stage directory that holds start.sh.");
  273. if (packed.problems)
  274. throw new CliError(
  275. "PACKAGE_CHECK_FAILED",
  276. `The stage does not meet the package contract:\n${packed.problems.map((p) => ` - ${p}`).join("\n")}`,
  277. "Fix every listed problem in the stage (see the site-deploy skill references), then deploy again.",
  278. 1,
  279. { problems: packed.problems },
  280. );
  281. out.event({ event: "packed", ...packed.result });
  282. for (const message of packed.warnings) out.event({ event: "warning", message });
  283. const { site, bound, created } = await resolveSite(ctx, { allowCreate: true });
  284. if (!bound) await writeBinding(ctx.cwd, site);
  285. if (created) out.event({ event: "site_created", siteId: site.id, url: site.url });
  286. // 已绑定时 --new 不生效:首次部署统一带 --new,后续部署即使误带也只会更新已绑定的站点,不会重复建站。
  287. if (bound && opts.new)
  288. out.event({
  289. event: "warning",
  290. message: `--new is ignored: this project is linked to site ${site.id} (${BINDING_FILE}).`,
  291. });
  292. const notice = prefixNotice(opts, created, site);
  293. if (notice) out.event({ event: "warning", message: notice });
  294. const deployment = await startDeployment(client, site.id, packed.body.length);
  295. out.event({
  296. event: "deployment_started",
  297. siteId: site.id,
  298. deploymentId: deployment.id,
  299. resumed: deployment.resumed,
  300. });
  301. await uploadPackage(ctx, site.id, deployment.id, packed.body);
  302. const final = await watch(ctx, site.id, deployment.id);
  303. const result = {
  304. siteId: site.id,
  305. deploymentId: final.id,
  306. status: final.status,
  307. url: site.url,
  308. failure: final.failure,
  309. };
  310. if (final.status !== "success") {
  311. throw new CliError(
  312. final.failure?.code ?? "DEPLOYMENT_FAILED",
  313. `Deployment failed at ${final.failure?.stage ?? "unknown"}: ${final.failure?.message ?? final.status}`,
  314. deployHint(final.failure?.code),
  315. 4,
  316. result,
  317. );
  318. }
  319. return result;
  320. }
  321. // 同一用户同时只能有一个进行中的部署。3610 指向本站点、且还没开始发布时,多半是上一次请求成功了但响应丢了,直接续传(技术方案 5.3)。
  322. async function startDeployment(client, siteId, size) {
  323. try {
  324. return { ...(await client.createDeployment(siteId, size)), resumed: false };
  325. } catch (err) {
  326. const p = err.data?.inProgress;
  327. if (err.code === 3610 && p && p.siteId === siteId && RESUMABLE.has(p.status)) {
  328. const d = await client.getDeployment(siteId, p.deploymentId);
  329. if (d.artifactSize === size) return { ...d, resumed: true };
  330. }
  331. if (err.code === 3610 && p)
  332. err.hint = `Deployment ${p.deploymentId} of site ${p.siteId} is ${p.status}. Wait for it to finish, then retry.`;
  333. throw err;
  334. }
  335. }
  336. // 包经 zcode-server 转发给控制面,由控制面写 OSS 并进入 publishing(openapi uploadPackage),CLI 不直接访问 OSS。
  337. // 断网或 3604(传输中断、长度不符)时用同一个请求整包重传;3603 说明上一次其实已经传完、只是响应丢了,直接进入轮询。
  338. async function uploadPackage(ctx, siteId, deploymentId, body) {
  339. const { client, out } = ctx;
  340. for (let attempt = 1; ; attempt++) {
  341. out.event({ event: "uploading", attempt, bytes: body.length });
  342. try {
  343. return await client.uploadPackage(siteId, deploymentId, body);
  344. } catch (err) {
  345. if (err.code === 3603) {
  346. const d = await client.getDeployment(siteId, deploymentId);
  347. if (!RESUMABLE.has(d.status)) return d;
  348. throw err;
  349. }
  350. const retryable = err.code === 3604 || err.code === "NETWORK_ERROR";
  351. if (!retryable || attempt >= UPLOAD_ATTEMPTS) throw err;
  352. }
  353. }
  354. }
  355. async function watch(ctx, siteId, deploymentId) {
  356. const { client, out, sleep, now } = ctx;
  357. const deadline = now() + POLL_TIMEOUT_MS;
  358. let offset = 0;
  359. let lastStatus;
  360. const drainLogs = async () => {
  361. const logs = await client.logs(siteId, deploymentId, offset);
  362. for (const e of logs.entries)
  363. out.event({ event: "log", stage: e.stage, level: e.level, message: e.message, ts: e.ts });
  364. offset = logs.nextOffset;
  365. };
  366. for (;;) {
  367. const d = await client.getDeployment(siteId, deploymentId);
  368. // 先读状态再读日志:状态已到终态时,这一轮读到的日志一定是全部。
  369. await drainLogs();
  370. if (d.status !== lastStatus) {
  371. out.event({ event: "status", status: d.status });
  372. lastStatus = d.status;
  373. }
  374. if (!IN_FLIGHT.has(d.status)) return d;
  375. if (now() > deadline) {
  376. throw new CliError(
  377. "WATCH_TIMEOUT",
  378. "Timed out waiting for the deployment to finish",
  379. `It is still ${d.status}; check later with \`zcode-site status --site ${siteId}\`.`,
  380. 4,
  381. { siteId, deploymentId },
  382. );
  383. }
  384. await sleep(POLL_INTERVAL_MS);
  385. }
  386. }
  387. function deployHint(code) {
  388. switch (code) {
  389. case "PACKAGE_INVALID":
  390. return "Fix the stage as described in the message (see the site-deploy skill's packaging reference) and deploy again.";
  391. case "WARMUP_FAILED":
  392. return "start.sh did not answer GET / on 0.0.0.0:3000 with a status below 500 in time. Read `zcode-site logs <deploymentId>`, run `zcode-site check <stage-dir>`, fix it and deploy again.";
  393. case "UPLOAD_TIMEOUT":
  394. return "The upload did not finish in time. Run `zcode-site deploy` again.";
  395. default:
  396. return "Run `zcode-site logs <deploymentId>` for details, then retry. The previous live version keeps serving.";
  397. }
  398. }
  399. // ---------- 其他命令 ----------
  400. function summarize(site) {
  401. return {
  402. id: site.id,
  403. name: site.name,
  404. url: site.url,
  405. status: site.status,
  406. ...(site.offlineReason && { offlineReason: site.offlineReason }),
  407. region: site.region,
  408. badgeHidden: site.badgeHidden,
  409. badgeVisible: site.badgeVisible,
  410. multiInstance: site.multiInstance,
  411. currentDeployment: site.currentDeployment && pickDeployment(site.currentDeployment),
  412. latestDeployment: site.latestDeployment && pickDeployment(site.latestDeployment),
  413. };
  414. }
  415. function pickDeployment(d) {
  416. return {
  417. id: d.id,
  418. status: d.status,
  419. createdAt: d.createdAt,
  420. finishedAt: d.finishedAt,
  421. failure: d.failure,
  422. };
  423. }
  424. async function logsCommand(ctx, deploymentId) {
  425. if (!deploymentId)
  426. throw localError(
  427. "MISSING_DEPLOYMENT",
  428. "Missing deployment id",
  429. "Usage: zcode-site logs <deploymentId> [--site <id>] [--offset <n>]",
  430. );
  431. const { site } = await resolveSite(ctx, { allowCreate: false });
  432. const offset = ctx.opts.offset === undefined ? 0 : Number(ctx.opts.offset);
  433. if (!Number.isInteger(offset) || offset < 0)
  434. throw localError(
  435. "INVALID_ARGS",
  436. "--offset must be a non-negative integer",
  437. "Pass the nextOffset from the previous call.",
  438. );
  439. return ctx.client.logs(site.id, deploymentId, offset);
  440. }
  441. async function setStatus(ctx, status) {
  442. const { site } = await resolveSite(ctx, { allowCreate: false });
  443. return summarize(await ctx.client.updateSite(site.id, { status }));
  444. }
  445. async function setBadge(ctx, action) {
  446. if (action !== "hide" && action !== "show")
  447. throw localError(
  448. "INVALID_ARGS",
  449. "Expected hide or show",
  450. "Usage: zcode-site badge hide|show [--site <id>]",
  451. );
  452. const { site } = await resolveSite(ctx, { allowCreate: false });
  453. return summarize(await ctx.client.updateSite(site.id, { badgeHidden: action === "hide" }));
  454. }
  455. // 实例模式(契约 Site.multiInstance):single 是默认,所有请求进同一个实例;multi 让请求分到多个实例。
  456. async function setInstance(ctx, mode) {
  457. if (mode !== "single" && mode !== "multi")
  458. throw localError(
  459. "INVALID_ARGS",
  460. "Expected single or multi",
  461. "Usage: zcode-site instance single|multi [--site <id>]",
  462. );
  463. const { site } = await resolveSite(ctx, { allowCreate: false });
  464. return summarize(await ctx.client.updateSite(site.id, { multiInstance: mode === "multi" }));
  465. }
  466. async function rename(ctx, name) {
  467. if (!name?.trim())
  468. throw localError(
  469. "MISSING_NAME",
  470. "Missing site name",
  471. "Usage: zcode-site rename [--site <id>] <name>",
  472. );
  473. const { site } = await resolveSite(ctx, { allowCreate: false });
  474. return summarize(await ctx.client.updateSite(site.id, { name: name.trim() }));
  475. }
  476. async function analyticsCommand(ctx) {
  477. const range = ctx.opts.range ?? "7d";
  478. if (!ANALYTICS_RANGES.includes(range))
  479. throw localError(
  480. "INVALID_ARGS",
  481. "--range must be 24h, 7d or 30d",
  482. "Usage: zcode-site analytics [--site <id>] [--range 24h|7d|30d]",
  483. );
  484. const { site } = await resolveSite(ctx, { allowCreate: false });
  485. for (let attempt = 1; ; attempt++) {
  486. const result = await ctx.client.analytics(site.id, range);
  487. if (result.status !== "computing") return { siteId: site.id, url: site.url, ...result };
  488. if (attempt >= ANALYTICS_ATTEMPTS)
  489. throw new CliError(
  490. "ANALYTICS_PENDING",
  491. "The analytics are still being computed",
  492. "Run the same command again in a minute.",
  493. 4,
  494. { siteId: site.id, range },
  495. );
  496. await ctx.sleep(ANALYTICS_RETRY_MS);
  497. }
  498. }
  499. // 改域名前缀:服务端规范化后生成新的 {前缀}-{4 位随机},旧地址立即失效,统计从零开始(契约 updateSite)。
  500. // 改前缀时服务端不兜底:规范化后不足 4 位直接报错,这里提前拦截,省一次请求。
  501. async function changePrefix(ctx, prefix) {
  502. if (!prefix?.trim())
  503. throw localError(
  504. "MISSING_PREFIX",
  505. "Missing domain prefix",
  506. "Usage: zcode-site prefix <prefix> [--site <id>]",
  507. );
  508. const normalized = normalizePrefix(prefix);
  509. if (normalized === "site" && !/^site$/i.test(prefix.trim()))
  510. throw localError(
  511. "INVALID_ARGS",
  512. "The prefix has fewer than 4 usable characters",
  513. "Use 4-30 lowercase letters, digits and -.",
  514. );
  515. const { site, bound } = await resolveSite(ctx, { allowCreate: false });
  516. const updated = await ctx.client.updateSite(site.id, { domainPrefix: prefix.trim() });
  517. if (bound) await writeBinding(ctx.cwd, updated);
  518. return { ...summarize(updated), previousUrl: site.url };
  519. }
  520. // 删除不可恢复,只接受显式的 --site,不按绑定文件猜目标;删掉的是本项目绑定的站点时一并删除绑定文件。
  521. async function deleteCommand(ctx) {
  522. const id = ctx.opts.site;
  523. if (!id)
  524. throw localError(
  525. "MISSING_SITE",
  526. "delete needs --site <id>",
  527. "Confirm with the user which site to delete, then pass --site <id>.",
  528. );
  529. await ctx.client.deleteSite(id);
  530. let unlinked = false;
  531. const binding = await readBinding(ctx.cwd).catch(() => undefined);
  532. if (binding?.siteId === id) {
  533. await rm(join(ctx.cwd, BINDING_FILE), { force: true });
  534. unlinked = true;
  535. }
  536. return { siteId: id, deleted: true, unlinked };
  537. }
  538. const HELP = `zcode-site: deploy and manage ZCode Sites. Run it from the project root.
  539. Output
  540. stdout: JSON, one object per line. deploy prints progress events first; the last line is the result.
  541. stderr on failure: one line {"error":{"code","message","hint","data"?}}. Follow hint.
  542. Exit codes
  543. 0 success
  544. 1 bad arguments, a local file or stage problem, or SITE_NOT_SELECTED
  545. 2 not signed in to ZCode, sign-in expired, or not run inside a ZCode session
  546. 3 quota, rate or size limit, or another deployment in progress
  547. 4 the deployment failed, or a server error
  548. Local command (no sign-in, nothing is uploaded)
  549. check <stage-dir> [--port <n>]
  550. Run "bash start.sh" in the stage with PORT (default 13000) and a temporary DATA_DIR, wait
  551. up to 90 s for GET / below 500, then stop it.
  552. Result: {status: "live", httpStatus, log} - the site should answer 200.
  553. {status: "skipped", reason} - the stage can't run on this machine (Linux binaries on
  554. macOS/Windows, or no bash); run the app from its normal local environment instead.
  555. START_FAILED: data {reason, httpStatus?, log}.
  556. Site commands
  557. deploy <stage-dir> [--new | --site <id>] [--name <name>] [--prefix <prefix>]
  558. [--allow-foreign-binaries] [--quiet]
  559. Pack the stage directory (its root becomes /app) and publish it. Packing runs first and
  560. checks the package contract: root start.sh with LF line endings, size, file count, path
  561. depth, reserved /.__zcode/, broken symlinks, .env files, dependencies present, and every
  562. native binary linux x86-64. It skips .git, .DS_Store, __pycache__ and .zcode-site.json.
  563. PACKAGE_CHECK_FAILED (exit 1): data.problems lists everything to fix; nothing was created
  564. or uploaded. Fix all of them, then deploy again.
  565. --allow-foreign-binaries: accept non-linux binaries; only after confirming each listed file
  566. is never loaded at runtime (e.g. prebuilt binaries for other platforms next to
  567. the linux-x64 one).
  568. Target site: --site <id>, else the site in .zcode-site.json, else with --new a new site.
  569. A new site is linked by writing .zcode-site.json; keep it and don't put it in the stage.
  570. --new is ignored (with a warning) when the project is already linked.
  571. Without --new or --site on an unlinked project: SITE_NOT_SELECTED if the account has sites,
  572. data.candidates [{id, name, url, status}]; ask the user, never pick one yourself.
  573. --name display name of a new site, any language (default: directory name). A name that
  574. fails the server's content review gets 3611 and nothing is created.
  575. --prefix domain prefix of a new site: 4-30 chars, lowercase a-z 0-9 and -. The domain is
  576. {prefix}-{4 random chars}. The server lowercases it, turns other characters into
  577. -, cuts it to 30 and falls back to "site" below 4 or when the prefix fails content
  578. review; a warning event says so.
  579. Ignored for an existing site; change its domain with \`prefix\`.
  580. --quiet print only the result.
  581. Events: {event: "packed", packageBytes, unpackedBytes, files, linuxBinaries}, then
  582. {event: "site_created" | "warning" | "deployment_started" | "uploading" | "log" | "status", ...}
  583. Result: {siteId, deploymentId, status: "success", url}
  584. Failure (exit 4): code is the failed stage reason, data has {siteId, deploymentId, failure}.
  585. PACKAGE_INVALID server preflight rejected the package; message names the file.
  586. WARMUP_FAILED GET / got no answer below 500 within 90 s; read logs, run check.
  587. UPLOAD_TIMEOUT deploy again.
  588. PUBLISH_FAILED, PUBLISH_TIMEOUT, INTERNAL platform side; retry later.
  589. The previous live version keeps serving after a failed deployment.
  590. status [--site <id>]
  591. Result: {id, name, url, status, offlineReason?, region, badgeHidden, badgeVisible, multiInstance,
  592. currentDeployment, latestDeployment} (deployments: {id, status, createdAt, finishedAt, failure}).
  593. status: pending = never deployed successfully, the URL shows nothing yet; online = the URL
  594. serves currentDeployment; offline = taken offline. offlineReason review_rejected means
  595. content review rejected the live version and took the site offline: online gets 3612,
  596. change the content and deploy again. A redeploy keeps the site online
  597. on the old version. Deployment progress is latestDeployment.status: preparing,
  598. uploading, publishing or verifying means still running (it ends within about 10
  599. minutes) - wait and check again, don't redeploy.
  600. logs <deploymentId> [--site <id>] [--offset <n>]
  601. Result: {entries: [{stage, level, message, ts}], nextOffset}; pass nextOffset to read on.
  602. offline [--site <id>] take the site offline; domain and records are kept. Result: as status.
  603. online [--site <id>] bring it back; a site never deployed successfully stays pending, and one whose
  604. live version was rejected by content review gets 3612. Result: as status.
  605. rename [--site <id>] <name> change the display name only; 3611 if it fails content review.
  606. Result: as status.
  607. badge hide|show [--site <id>] hide or show the "ZCode" badge on the site. Only paid plans can
  608. hide it (usage.badgeRemovable); free plans get 3608. badgeHidden is the user's choice,
  609. badgeVisible whether the badge actually shows. Result: as status.
  610. instance single|multi [--site <id>] single (default): all requests go to one instance, so
  611. memory and $DATA_DIR are shared by every request; at most 200 in flight, more get 429.
  612. multi: requests spread over several instances, nothing in memory or $DATA_DIR is shared;
  613. for stateless sites with heavy traffic. Takes effect without a redeploy (another region
  614. within 30 s). Result: as status (multiInstance).
  615. prefix <prefix> [--site <id>] change the domain to {prefix}-{4 new random chars}. The prefix is
  616. normalized like --prefix but never falls back: fewer than 4 usable characters is an error,
  617. and a prefix that fails content review gets 3614. The old address stops working at once
  618. (no redirect) and may go to another site; visit analytics start over. Confirm with the
  619. user first. Updates .zcode-site.json. Result: as status, plus previousUrl.
  620. delete --site <id> permanently delete the site: its address returns 404 at once and it can't
  621. be restored; this month's traffic and requests are not refunded. Needs an explicit
  622. --site; confirm with the user first. 3610 while a deployment is in progress. Removes
  623. .zcode-site.json when it points to this site.
  624. Result: {siteId, deleted: true, unlinked}.
  625. analytics [--site <id>] [--range 24h|7d|30d] visit analytics (default 7d), from browsers that
  626. ran the page; bots excluded, a few minutes of delay. Waits up to about a minute while
  627. the server computes them (ANALYTICS_PENDING after that, retry later); 3613 = retry later.
  628. Result: {siteId, url, status: "ready", range, generatedAt, partial, summary: {pv, uv,
  629. avgDurationSeconds, bounceRate}, series: [{start, pv, uv}], pages, referrers, devices,
  630. regions: [{key, pv, share}]}. summary and the lists are null when there were no visits;
  631. a referrer key "" is direct or unknown. Counting restarts when the prefix changes.
  632. list Result: {sites: [{id, name, url, status}]}
  633. usage Account traffic, requests and storage against the plan; canDeploy and exceededReasons.
  634. help this text.
  635. Commands without --site use the site in .zcode-site.json. Numeric error codes come from the Sites
  636. API (e.g. 3605 quota exceeded, 3610 another deployment in progress); their hint says what to do.`;
  637. // ---------- 入口 ----------
  638. export async function main(
  639. argv,
  640. {
  641. env = process.env,
  642. cwd = process.cwd(),
  643. fetchImpl,
  644. stdout = process.stdout,
  645. stderr = process.stderr,
  646. sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
  647. now = Date.now,
  648. } = {},
  649. ) {
  650. let parsed;
  651. try {
  652. parsed = parseArgs({
  653. args: argv,
  654. allowPositionals: true,
  655. options: {
  656. site: { type: "string" },
  657. new: { type: "boolean" },
  658. name: { type: "string" },
  659. prefix: { type: "string" },
  660. offset: { type: "string" },
  661. range: { type: "string" },
  662. port: { type: "string" },
  663. "allow-foreign-binaries": { type: "boolean" },
  664. quiet: { type: "boolean" },
  665. help: { type: "boolean", short: "h" },
  666. },
  667. });
  668. } catch (err) {
  669. return fail(stderr, localError("INVALID_ARGS", err.message, "Run `zcode-site help`."));
  670. }
  671. const [command, ...args] = parsed.positionals;
  672. if (!command || command === "help" || parsed.values.help) {
  673. stdout.write(`${HELP}\n`);
  674. return command || parsed.values.help ? 0 : 1;
  675. }
  676. if (command === "check") {
  677. try {
  678. const result = await check(cwd, args, parsed.values);
  679. stdout.write(`${JSON.stringify(result)}\n`);
  680. return 0;
  681. } catch (err) {
  682. return fail(stderr, err instanceof CliError ? err : internalError(err));
  683. }
  684. }
  685. const quiet = parsed.values.quiet;
  686. const out = { event: (e) => quiet || stdout.write(`${JSON.stringify(e)}\n`) };
  687. try {
  688. const endpoint = loadEndpoint(env);
  689. const client = createClient(endpoint, fetchImpl ?? createEndpointFetch(endpoint.address));
  690. const ctx = { client, cwd, opts: parsed.values, out, sleep, now };
  691. let result;
  692. switch (command) {
  693. case "deploy":
  694. result = await deploy(ctx, args[0]);
  695. break;
  696. case "status":
  697. result = summarize((await resolveSite(ctx, { allowCreate: false })).site);
  698. break;
  699. case "logs":
  700. result = await logsCommand(ctx, args[0]);
  701. break;
  702. case "offline":
  703. result = await setStatus(ctx, "offline");
  704. break;
  705. case "online":
  706. result = await setStatus(ctx, "online");
  707. break;
  708. case "usage":
  709. result = await client.usage();
  710. break;
  711. case "list":
  712. result = { sites: candidates(await allSites(client)) };
  713. break;
  714. case "rename":
  715. result = await rename(ctx, args.join(" "));
  716. break;
  717. case "badge":
  718. result = await setBadge(ctx, args[0]);
  719. break;
  720. case "instance":
  721. result = await setInstance(ctx, args[0]);
  722. break;
  723. case "analytics":
  724. result = await analyticsCommand(ctx);
  725. break;
  726. case "prefix":
  727. result = await changePrefix(ctx, args.join(" "));
  728. break;
  729. case "delete":
  730. result = await deleteCommand(ctx);
  731. break;
  732. default:
  733. throw localError(
  734. "UNKNOWN_COMMAND",
  735. `Unknown command: ${command}`,
  736. "Run `zcode-site help`.",
  737. );
  738. }
  739. stdout.write(`${JSON.stringify(result)}\n`);
  740. return 0;
  741. } catch (err) {
  742. return fail(stderr, err instanceof CliError ? err : internalError(err));
  743. }
  744. }
  745. function internalError(err) {
  746. return new CliError(
  747. "INTERNAL",
  748. err.message,
  749. "This is a bug in zcode-site; report it with the command you ran.",
  750. 4,
  751. );
  752. }
  753. async function check(cwd, [stageDir], opts) {
  754. if (!stageDir)
  755. throw localError(
  756. "INVALID_ARGS",
  757. "Missing stage directory",
  758. "Usage: zcode-site check <stage-dir> [--port <n>]",
  759. );
  760. const port = opts.port === undefined ? undefined : Number(opts.port);
  761. if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535))
  762. throw localError("INVALID_ARGS", "--port must be a port number", "Pass e.g. --port 13000.");
  763. const checked = await checkStage(stageDir, { cwd, ...(port ? { port } : {}) });
  764. if (checked.error)
  765. throw localError(
  766. checked.error,
  767. checked.message,
  768. "Pass the stage directory that holds start.sh.",
  769. );
  770. if (checked.failed)
  771. throw new CliError(
  772. "START_FAILED",
  773. checked.failed.reason,
  774. "Read data.log and the site-deploy skill's troubleshooting reference, fix the stage, then check again.",
  775. 1,
  776. checked.failed,
  777. );
  778. return checked.result;
  779. }
  780. function fail(stderr, err) {
  781. const error = { code: err.code, message: err.message, hint: err.hint };
  782. if (err.data !== undefined) error.data = err.data;
  783. stderr.write(`${JSON.stringify({ error })}\n`);
  784. return err.exitCode;
  785. }
  786. if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
  787. process.exitCode = await main(process.argv.slice(2));
  788. }