zcode-site.test.mjs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. // zcode-site CLI 测试:用内存里的 Sites API 替身(按 api/openapi.yaml 的状态机)代替 zcode-server 和后面的控制面。
  2. import assert from "node:assert/strict";
  3. import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { test } from "node:test";
  7. import { createServer } from "node:http";
  8. import {
  9. createEndpointFetch,
  10. main,
  11. normalizePrefix,
  12. } from "../skills/site-deploy/scripts/zcode-site.mjs";
  13. import { packStage } from "../skills/site-deploy/scripts/stage.mjs";
  14. // CLI 只认 agent 注入的官方命令端点(技术方案 5.8);身份头和版本头由端点补,CLI 不带。
  15. const ENV = {
  16. ZCODE_OFFICIAL_ENDPOINT: "/tmp/zcode-official-test.sock",
  17. ZCODE_OFFICIAL_ENDPOINT_TOKEN: "session-token",
  18. };
  19. class FakeSites {
  20. constructor() {
  21. this.sites = [];
  22. this.deployments = [];
  23. this.nextId = 1000;
  24. // 发布结果:上传完成之后第几次轮询进入终态、终态是什么
  25. this.publishPolls = 1;
  26. this.publishOutcome = { status: "success" };
  27. this.uploads = 0;
  28. // 第一次上传:truncate 时服务端只收到一部分(3604);dropResponse 时服务端收完了但响应丢了(网络错误)
  29. this.firstUpload = undefined;
  30. this.unauthenticated = false;
  31. this.planExpired = false;
  32. this.endpointNetworkError = false;
  33. this.badgeRemovable = false;
  34. // 服务端机审:rejectNames 里的名称返回 3611,rejectPrefixes 里的(规范化后的)前缀换成 site。
  35. this.rejectNames = new Set();
  36. this.rejectPrefixes = new Set();
  37. // 统计:前几次读返回 computing(服务端后台计算中)。
  38. this.analyticsComputing = 0;
  39. this.analyticsCalls = [];
  40. }
  41. site({ prefix = "app", ...overrides } = {}) {
  42. const id = String(this.nextId++);
  43. const s = {
  44. id,
  45. name: overrides.name ?? "app",
  46. domainLabel: `${prefix}-${id}`,
  47. url: `https://${prefix}-${id}.zcode-cn.site`,
  48. status: "pending",
  49. region: "cn",
  50. badgeHidden: false,
  51. badgeVisible: true,
  52. multiInstance: false,
  53. currentDeployment: null,
  54. latestDeployment: null,
  55. ...overrides,
  56. };
  57. this.sites.push(s);
  58. return s;
  59. }
  60. deployment(siteId, overrides = {}) {
  61. const d = {
  62. id: String(this.nextId++),
  63. siteId,
  64. status: "preparing",
  65. artifactSize: 0,
  66. failure: null,
  67. logs: [],
  68. polls: 0,
  69. ...overrides,
  70. };
  71. this.deployments.push(d);
  72. return d;
  73. }
  74. view(d) {
  75. const { logs, polls, ...rest } = d;
  76. return rest;
  77. }
  78. fetch = async (url, init = {}) => {
  79. const method = init.method ?? "GET";
  80. if (this.unauthenticated) return new Response(null, { status: 401 });
  81. if (this.planExpired)
  82. return Response.json(
  83. { code: 3101, msg: "coding plan is required", logid: "l" },
  84. { status: 403 },
  85. );
  86. if (this.endpointNetworkError) {
  87. return Response.json(
  88. { code: 2007, msg: "x", data: null, logid: "" },
  89. { status: 502, headers: { "X-ZCode-Official-Endpoint-Error": "network" } },
  90. );
  91. }
  92. assert.equal(init.headers.Authorization, "Bearer session-token");
  93. assert.equal(init.headers["X-ZCode-App-Version"], undefined);
  94. assert.equal(init.headers["X-Bigmodel-Authorization"], undefined);
  95. const { pathname } = new URL(url);
  96. const body = typeof init.body === "string" ? JSON.parse(init.body) : init.body;
  97. const ok = (data) => Response.json({ code: 0, msg: "success", data, logid: "l" });
  98. const err = (status, code, data) =>
  99. Response.json({ code, msg: "x", data, logid: "l" }, { status });
  100. const parts = pathname.split("/").slice(4); // /api/v1/sites/...
  101. if (pathname === "/api/v1/sites/usage") return ok({ plan: "free", canDeploy: true });
  102. if (parts.length === 0 && method === "GET")
  103. return ok({ items: [...this.sites].reverse(), nextCursor: null });
  104. if (parts.length === 0 && method === "POST") {
  105. this.createBodies = [...(this.createBodies ?? []), body];
  106. if (this.rejectNames.has(body.name)) return err(400, 3611);
  107. const prefix = normalizePrefix(body.domainPrefix ?? body.name);
  108. return ok(
  109. this.site({ name: body.name, prefix: this.rejectPrefixes.has(prefix) ? "site" : prefix }),
  110. );
  111. }
  112. const site = this.sites.find((s) => s.id === parts[0]);
  113. if (!site) return err(404, 3601);
  114. if (parts.length === 1 && method === "GET") return ok(site);
  115. if (parts.length === 1 && method === "DELETE") {
  116. const busy = this.deployments.some(
  117. (d) =>
  118. d.siteId === site.id &&
  119. ["preparing", "uploading", "publishing", "verifying"].includes(d.status),
  120. );
  121. if (busy) return err(409, 3610);
  122. this.sites = this.sites.filter((s) => s !== site);
  123. return ok(undefined);
  124. }
  125. if (parts.length === 2 && parts[1] === "analytics" && method === "GET") {
  126. const range = new URL(url).searchParams.get("range");
  127. this.analyticsCalls.push(range);
  128. if (this.analyticsComputing-- > 0) return ok({ status: "computing", range });
  129. return ok({ status: "ready", range, generatedAt: "t", partial: false, summary: null });
  130. }
  131. if (parts.length === 1 && method === "PATCH" && "domainPrefix" in body) {
  132. // 服务端规则(契约 updateSite):改前缀不兜底,不足 4 位 3001,机审不过 3614,后缀重新生成。
  133. const prefix = normalizePrefix(body.domainPrefix);
  134. if (prefix === "site" && body.domainPrefix.toLowerCase() !== "site") return err(400, 3001);
  135. if (this.rejectPrefixes.has(prefix)) return err(400, 3614);
  136. const label = `${prefix}-${this.nextId++}`;
  137. Object.assign(site, { domainLabel: label, url: `https://${label}.zcode-cn.site` });
  138. return ok(site);
  139. }
  140. if (parts.length === 1 && method === "PATCH") {
  141. if (body.badgeHidden && !this.badgeRemovable) return err(403, 3608);
  142. if ("multiInstance" in body && typeof body.multiInstance !== "boolean") return err(400, 3001);
  143. if (this.rejectNames.has(body.name)) return err(400, 3611);
  144. // 服务端规则:当前线上版本被人审驳回时不能改回上线。
  145. if (body.status === "online" && site.offlineReason === "review_rejected")
  146. return err(403, 3612);
  147. if ("badgeHidden" in body) site.badgeVisible = !body.badgeHidden;
  148. Object.assign(site, body);
  149. // 服务端规则:没有线上版本的站点上线后还是 pending。
  150. if (site.status === "online" && !site.currentDeployment) site.status = "pending";
  151. return ok(site);
  152. }
  153. if (parts.length === 2 && method === "POST") {
  154. const busy = this.deployments.find((d) =>
  155. ["preparing", "uploading", "publishing", "verifying"].includes(d.status),
  156. );
  157. if (busy)
  158. return err(409, 3610, {
  159. inProgress: { siteId: busy.siteId, deploymentId: busy.id, status: busy.status },
  160. });
  161. const d = this.deployment(site.id, {
  162. artifactSize: body.artifactSize,
  163. logs: [{ stage: "preparing", level: "info", message: "created" }],
  164. });
  165. site.latestDeployment = this.view(d);
  166. return ok(this.view(d));
  167. }
  168. const d = this.deployments.find((x) => x.id === parts[2] && x.siteId === site.id);
  169. if (!d) return err(404, 3602);
  170. const action = parts[3];
  171. if (!action && method === "GET") {
  172. if (d.status === "publishing" && ++d.polls >= this.publishPolls) {
  173. Object.assign(d, this.publishOutcome);
  174. d.logs.push({
  175. stage: "verifying",
  176. level: d.status === "success" ? "info" : "error",
  177. message: d.status,
  178. });
  179. if (d.status === "success") {
  180. site.currentDeployment = this.view(d);
  181. site.status = "online";
  182. delete site.offlineReason;
  183. }
  184. }
  185. return ok(this.view(d));
  186. }
  187. if (action === "package" && method === "PUT") {
  188. this.uploads++;
  189. assert.equal(init.headers["Content-Type"], "application/gzip");
  190. if (!["preparing", "uploading"].includes(d.status)) return err(409, 3603);
  191. d.status = "uploading";
  192. const first = this.uploads === 1 ? this.firstUpload : undefined;
  193. if (first === "truncate" || body.length !== d.artifactSize) return err(409, 3604);
  194. d.status = "publishing";
  195. d.logs.push({ stage: "publishing", level: "info", message: "publishing" });
  196. if (first === "dropResponse") throw new TypeError("fetch failed");
  197. return ok(this.view(d));
  198. }
  199. if (action === "logs") {
  200. const offset = Number(new URL(url).searchParams.get("offset"));
  201. const entries = d.logs.slice(offset).map((e, i) => ({ ...e, offset: offset + i, ts: "t" }));
  202. return ok({
  203. entries,
  204. nextOffset: d.logs.length,
  205. done: !["preparing", "uploading", "publishing", "verifying"].includes(d.status),
  206. });
  207. }
  208. return err(404, 3601);
  209. };
  210. }
  211. async function project() {
  212. const dir = await mkdtemp(join(tmpdir(), "zcode-site-cli-"));
  213. await mkdir(join(dir, "stage"));
  214. await writeFile(join(dir, "stage", "start.sh"), "exec node static-server.mjs .\n");
  215. await writeFile(join(dir, "stage", "index.html"), "<h1>hi</h1>");
  216. return dir;
  217. }
  218. async function run(fake, cwd, ...argv) {
  219. let stdout = "";
  220. let stderr = "";
  221. const code = await main(argv, {
  222. env: ENV,
  223. cwd,
  224. fetchImpl: fake.fetch,
  225. stdout: { write: (s) => (stdout += s) },
  226. stderr: { write: (s) => (stderr += s) },
  227. sleep: async () => {},
  228. now: () => 0,
  229. });
  230. const lines = stdout
  231. .trim()
  232. .split("\n")
  233. .filter(Boolean)
  234. .map((l) => JSON.parse(l));
  235. return {
  236. code,
  237. lines,
  238. result: lines.at(-1),
  239. error: stderr ? JSON.parse(stderr).error : undefined,
  240. };
  241. }
  242. test("first deploy creates and binds a site, then later deploys reuse it", async () => {
  243. const fake = new FakeSites();
  244. const cwd = await project();
  245. const r = await run(fake, cwd, "deploy", "stage", "--name", "My App");
  246. assert.equal(r.code, 0, JSON.stringify(r.error));
  247. assert.equal(fake.sites.length, 1);
  248. assert.equal(fake.sites[0].name, "My App");
  249. assert.deepEqual(r.result, {
  250. siteId: fake.sites[0].id,
  251. deploymentId: fake.deployments[0].id,
  252. status: "success",
  253. url: fake.sites[0].url,
  254. failure: null,
  255. });
  256. assert.ok(r.lines.some((l) => l.event === "site_created"));
  257. assert.deepEqual(r.lines[0], {
  258. event: "packed",
  259. packageBytes: fake.deployments[0].artifactSize,
  260. unpackedBytes: 41,
  261. files: 2,
  262. linuxBinaries: 0,
  263. });
  264. assert.ok(r.lines.some((l) => l.event === "log" && l.message === "publishing"));
  265. const binding = JSON.parse(await readFile(join(cwd, ".zcode-site.json"), "utf8"));
  266. assert.deepEqual(binding, { siteId: fake.sites[0].id, domainLabel: fake.sites[0].domainLabel });
  267. const again = await run(fake, cwd, "deploy", "stage", "--quiet");
  268. assert.equal(again.code, 0);
  269. assert.equal(again.lines.length, 1, "--quiet prints only the result");
  270. assert.equal(fake.sites.length, 1);
  271. assert.equal(fake.deployments.length, 2);
  272. // skill 让首次部署统一带 --new;已绑定的项目误带时只提醒,仍部署到已绑定的站点。
  273. const withNew = await run(fake, cwd, "deploy", "stage", "--new");
  274. assert.equal(withNew.code, 0);
  275. assert.equal(fake.sites.length, 1);
  276. assert.ok(withNew.lines.some((l) => l.event === "warning" && /--new is ignored/.test(l.message)));
  277. });
  278. test("an unbound project does not guess among existing sites", async () => {
  279. const fake = new FakeSites();
  280. fake.site({ name: "a" });
  281. fake.site({ name: "b" });
  282. const r = await run(fake, await project(), "deploy", "stage");
  283. assert.equal(r.code, 1);
  284. assert.equal(r.error.code, "SITE_NOT_SELECTED");
  285. assert.deepEqual(
  286. r.error.data.candidates.map((c) => c.name),
  287. ["b", "a"],
  288. );
  289. assert.equal(fake.deployments.length, 0);
  290. const created = await run(fake, await project(), "deploy", "stage", "--new");
  291. assert.equal(created.code, 0);
  292. assert.equal(fake.sites.length, 3);
  293. });
  294. test("a 3610 for the same site that has not started publishing is resumed", async () => {
  295. const fake = new FakeSites();
  296. const site = fake.site();
  297. const cwd = await project();
  298. // 续传按包大小认同一次部署;同一个 stage 每次打出的包字节一致(tar 头用文件 mtime,gzip 头不写时间)。
  299. const { body } = await packStage(join(cwd, "stage"));
  300. const stuck = fake.deployment(site.id, { status: "uploading", artifactSize: body.length });
  301. const r = await run(fake, cwd, "deploy", "stage", "--site", site.id);
  302. assert.equal(r.code, 0, JSON.stringify(r.error));
  303. assert.equal(r.result.deploymentId, stuck.id);
  304. assert.ok(r.lines.some((l) => l.event === "deployment_started" && l.resumed === true));
  305. });
  306. test("a deployment in progress elsewhere is reported with exit code 3", async () => {
  307. const fake = new FakeSites();
  308. const other = fake.site();
  309. const mine = fake.site();
  310. fake.deployment(other.id, { status: "publishing" });
  311. const r = await run(fake, await project(), "deploy", "stage", "--site", mine.id);
  312. assert.equal(r.code, 3);
  313. assert.equal(r.error.code, 3610);
  314. assert.match(r.error.hint, new RegExp(other.id));
  315. });
  316. test("an upload the server rejects as incomplete is uploaded again", async () => {
  317. const fake = new FakeSites();
  318. fake.firstUpload = "truncate";
  319. const r = await run(fake, await project(), "deploy", "stage");
  320. assert.equal(r.code, 0, JSON.stringify(r.error));
  321. assert.equal(fake.uploads, 2);
  322. assert.equal(r.lines.filter((l) => l.event === "uploading").length, 2);
  323. });
  324. test("a lost upload response continues with the deployment the server already accepted", async () => {
  325. const fake = new FakeSites();
  326. fake.firstUpload = "dropResponse";
  327. const r = await run(fake, await project(), "deploy", "stage");
  328. assert.equal(r.code, 0, JSON.stringify(r.error));
  329. assert.equal(fake.uploads, 2); // 第二次收到 3603,CLI 查到部署已在发布,直接轮询
  330. assert.equal(r.result.status, "success");
  331. });
  332. test("a failed deployment exits 4 with the failure", async () => {
  333. const fake = new FakeSites();
  334. fake.publishPolls = 2;
  335. fake.publishOutcome = {
  336. status: "failed",
  337. failure: { stage: "verifying", code: "WARMUP_FAILED", message: "no 200 within 90s" },
  338. };
  339. const r = await run(fake, await project(), "deploy", "stage");
  340. assert.equal(r.code, 4);
  341. assert.equal(r.error.code, "WARMUP_FAILED");
  342. assert.match(r.error.hint, /start\.sh/);
  343. assert.equal(r.error.data.status, "failed");
  344. });
  345. test("a stage that fails the package contract creates nothing", async () => {
  346. const fake = new FakeSites();
  347. const cwd = await project();
  348. await writeFile(join(cwd, "stage", "start.sh"), "exec node server.js\r\n");
  349. await writeFile(join(cwd, "stage", ".env"), "SECRET=1");
  350. const r = await run(fake, cwd, "deploy", "stage", "--new");
  351. assert.equal(r.code, 1);
  352. assert.equal(r.error.code, "PACKAGE_CHECK_FAILED");
  353. assert.equal(r.error.data.problems.length, 2);
  354. assert.equal(fake.sites.length, 0);
  355. assert.equal(fake.deployments.length, 0);
  356. });
  357. test("local and auth errors", async () => {
  358. const fake = new FakeSites();
  359. const cwd = await project();
  360. assert.equal((await run(fake, cwd, "deploy", "missing")).error.code, "STAGE_NOT_FOUND");
  361. assert.equal((await run(fake, cwd, "deploy", "stage", "--site", "1", "--new")).code, 1);
  362. assert.equal((await run(fake, cwd, "nope")).error.code, "UNKNOWN_COMMAND");
  363. fake.unauthenticated = true;
  364. const r = await run(fake, cwd, "usage");
  365. assert.equal(r.code, 2);
  366. assert.equal(r.error.code, "UNAUTHENTICATED");
  367. fake.unauthenticated = false;
  368. fake.planExpired = true;
  369. const expired = await run(fake, cwd, "usage");
  370. assert.equal(expired.code, 2);
  371. assert.equal(expired.error.code, 3101);
  372. assert.match(expired.error.hint, /sign in again/);
  373. const noEnv = await main(["usage"], {
  374. env: {},
  375. cwd,
  376. stdout: { write() {} },
  377. stderr: { write() {} },
  378. });
  379. assert.equal(noEnv, 2);
  380. fake.planExpired = false;
  381. fake.endpointNetworkError = true;
  382. const offline = await run(fake, cwd, "usage");
  383. assert.equal(offline.code, 4);
  384. assert.equal(offline.error.code, "NETWORK_ERROR");
  385. });
  386. test("createEndpointFetch talks HTTP over the endpoint socket", async () => {
  387. const dir = await mkdtemp(join(tmpdir(), "zcode-site-ep-"));
  388. const socketPath = join(dir, "endpoint.sock");
  389. const seen = [];
  390. const server = createServer((req, res) => {
  391. const chunks = [];
  392. req.on("data", (c) => chunks.push(c));
  393. req.on("end", () => {
  394. seen.push({
  395. method: req.method,
  396. url: req.url,
  397. headers: req.headers,
  398. body: Buffer.concat(chunks),
  399. });
  400. if (req.url === "/empty") return res.writeHead(204).end();
  401. res
  402. .writeHead(200, { "content-type": "application/json" })
  403. .end(JSON.stringify({ code: 0, data: { ok: true } }));
  404. });
  405. });
  406. await new Promise((resolve) => server.listen(socketPath, resolve));
  407. try {
  408. const fetchImpl = createEndpointFetch(socketPath);
  409. const res = await fetchImpl(
  410. "http://zcode-official-endpoint/api/v1/sites/1/deployments/2/package?x=1",
  411. {
  412. method: "PUT",
  413. headers: { Authorization: "Bearer t", "Content-Type": "application/gzip" },
  414. body: Buffer.from("tarball"),
  415. },
  416. );
  417. assert.equal(res.status, 200);
  418. assert.deepEqual(await res.json(), { code: 0, data: { ok: true } });
  419. assert.equal(seen[0].url, "/api/v1/sites/1/deployments/2/package?x=1");
  420. assert.equal(seen[0].headers["content-length"], "7");
  421. assert.equal(seen[0].headers["transfer-encoding"], undefined);
  422. assert.equal(seen[0].body.toString(), "tarball");
  423. assert.equal((await fetchImpl("http://zcode-official-endpoint/empty")).status, 204);
  424. } finally {
  425. await new Promise((resolve) => server.close(resolve));
  426. }
  427. });
  428. // Z.ai 沙箱把官方命令端点提供成 http(s) 地址:起一个真实的 HTTP 服务挂在 /sandbox 前缀下,把请求转给 FakeSites,
  429. // 不注入 fetchImpl,走 main() 默认的 createEndpointFetch 和全局 fetch。
  430. async function startHttpEndpoint(fake) {
  431. const seen = [];
  432. const server = createServer((req, res) => {
  433. const chunks = [];
  434. req.on("data", (c) => chunks.push(c));
  435. req.on("end", async () => {
  436. const raw = Buffer.concat(chunks);
  437. seen.push({ method: req.method, url: req.url, headers: req.headers, bodyLength: raw.length });
  438. const headers = {};
  439. if (req.headers.authorization) headers.Authorization = req.headers.authorization;
  440. const type = req.headers["content-type"];
  441. if (type) headers["Content-Type"] = type;
  442. const body =
  443. raw.length === 0 ? undefined : type === "application/json" ? raw.toString("utf8") : raw;
  444. try {
  445. const out = await fake.fetch(`http://fake${req.url.replace(/^\/sandbox/, "")}`, {
  446. method: req.method,
  447. headers,
  448. body,
  449. });
  450. res.writeHead(out.status, Object.fromEntries(out.headers));
  451. res.end(Buffer.from(await out.arrayBuffer()));
  452. } catch (err) {
  453. res.writeHead(500).end(String(err));
  454. }
  455. });
  456. });
  457. await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
  458. const { port } = server.address();
  459. return {
  460. seen,
  461. url: `http://127.0.0.1:${port}/sandbox/`,
  462. close: () => new Promise((resolve) => server.close(resolve)),
  463. };
  464. }
  465. async function runWithEndpoint(endpoint, cwd, ...argv) {
  466. let stdout = "";
  467. let stderr = "";
  468. const code = await main(argv, {
  469. env: { ZCODE_OFFICIAL_ENDPOINT: endpoint, ZCODE_OFFICIAL_ENDPOINT_TOKEN: "session-token" },
  470. cwd,
  471. stdout: { write: (s) => (stdout += s) },
  472. stderr: { write: (s) => (stderr += s) },
  473. sleep: async () => {},
  474. now: () => 0,
  475. });
  476. const lines = stdout
  477. .trim()
  478. .split("\n")
  479. .filter(Boolean)
  480. .map((l) => JSON.parse(l));
  481. return { code, result: lines.at(-1), error: stderr ? JSON.parse(stderr).error : undefined };
  482. }
  483. test("an http(s) endpoint is requested with fetch under its base path", async () => {
  484. const fake = new FakeSites();
  485. const endpoint = await startHttpEndpoint(fake);
  486. try {
  487. const cwd = await project();
  488. const r = await runWithEndpoint(endpoint.url, cwd, "deploy", "stage", "--name", "My App");
  489. assert.equal(r.code, 0, JSON.stringify(r.error));
  490. assert.equal(r.result.status, "success");
  491. assert.equal(r.result.url, fake.sites[0].url);
  492. assert.ok(endpoint.seen.length > 0);
  493. for (const req of endpoint.seen) {
  494. assert.match(req.url, /^\/sandbox\/api\/v1\/sites(\/|\?|$)/);
  495. assert.equal(req.headers.authorization, "Bearer session-token");
  496. }
  497. const upload = endpoint.seen.find(
  498. (req) => req.method === "PUT" && req.url.endsWith("/package"),
  499. );
  500. assert.ok(upload, "the package is uploaded through the http endpoint");
  501. assert.equal(upload.headers["content-type"], "application/gzip");
  502. assert.equal(upload.headers["content-length"], String(fake.deployments[0].artifactSize));
  503. assert.equal(upload.bodyLength, fake.deployments[0].artifactSize);
  504. assert.equal(upload.headers["transfer-encoding"], undefined);
  505. assert.ok(
  506. endpoint.seen.some((req) => req.url.includes("?offset=")),
  507. "query is kept",
  508. );
  509. // 端点自己连不上 zcode-server 时用响应头报 network,http 端点也照样映射成 NETWORK_ERROR。
  510. fake.endpointNetworkError = true;
  511. const offline = await runWithEndpoint(endpoint.url, cwd, "usage");
  512. assert.equal(offline.code, 4);
  513. assert.equal(offline.error.code, "NETWORK_ERROR");
  514. } finally {
  515. await endpoint.close();
  516. }
  517. });
  518. test("an unreachable http endpoint exits with NETWORK_ERROR", async () => {
  519. const endpoint = await startHttpEndpoint(new FakeSites());
  520. await endpoint.close();
  521. const r = await runWithEndpoint(endpoint.url, await project(), "usage");
  522. assert.equal(r.code, 4);
  523. assert.equal(r.error.code, "NETWORK_ERROR");
  524. });
  525. test("status, rename, offline and online use the bound site", async () => {
  526. const fake = new FakeSites();
  527. const site = fake.site();
  528. const cwd = await project();
  529. await writeFile(
  530. join(cwd, ".zcode-site.json"),
  531. JSON.stringify({ siteId: site.id, domainLabel: site.domainLabel }),
  532. );
  533. assert.equal((await run(fake, cwd, "status")).result.id, site.id);
  534. assert.equal((await run(fake, cwd, "rename", "New", "Name")).result.name, "New Name");
  535. assert.equal((await run(fake, cwd, "offline")).result.status, "offline");
  536. assert.equal((await run(fake, cwd, "online")).result.status, "pending");
  537. fake.sites[0].currentDeployment = { id: "1", status: "success" };
  538. assert.equal((await run(fake, cwd, "online")).result.status, "online");
  539. assert.equal((await run(fake, cwd, "list")).result.sites.length, 1);
  540. assert.equal((await run(fake, cwd, "status", "--site", "999")).code, 1);
  541. });
  542. test("analytics waits while the server computes them, then gives up after a minute", async () => {
  543. const fake = new FakeSites();
  544. const site = fake.site();
  545. const cwd = await project();
  546. fake.analyticsComputing = 2;
  547. const ok = await run(fake, cwd, "analytics", "--site", site.id, "--range", "30d");
  548. assert.equal(ok.code, 0);
  549. assert.deepEqual(fake.analyticsCalls, ["30d", "30d", "30d"]);
  550. assert.deepEqual(
  551. { siteId: ok.result.siteId, status: ok.result.status, range: ok.result.range },
  552. { siteId: site.id, status: "ready", range: "30d" },
  553. );
  554. assert.equal((await run(fake, cwd, "analytics", "--site", site.id)).result.range, "7d");
  555. fake.analyticsComputing = 100;
  556. const pending = await run(fake, cwd, "analytics", "--site", site.id);
  557. assert.equal(pending.code, 4);
  558. assert.equal(pending.error.code, "ANALYTICS_PENDING");
  559. assert.equal((await run(fake, cwd, "analytics", "--site", site.id, "--range", "1y")).code, 1);
  560. });
  561. test("prefix changes the domain, updates the binding and reports the old address", async () => {
  562. const fake = new FakeSites();
  563. const site = fake.site({ prefix: "old-name" });
  564. const cwd = await project();
  565. await writeFile(
  566. join(cwd, ".zcode-site.json"),
  567. JSON.stringify({ siteId: site.id, domainLabel: site.domainLabel }),
  568. );
  569. const oldUrl = site.url;
  570. const changed = await run(fake, cwd, "prefix", "Tokyo Trip");
  571. assert.equal(changed.code, 0);
  572. assert.match(changed.result.url, /^https:\/\/tokyo-trip-\d+\.zcode-cn\.site$/);
  573. assert.equal(changed.result.previousUrl, oldUrl);
  574. const binding = JSON.parse(await readFile(join(cwd, ".zcode-site.json"), "utf8"));
  575. assert.equal(binding.domainLabel, fake.sites[0].domainLabel);
  576. // 规范化后不足 4 位在本地就拦下,不发请求;机审不过是 3614,退出码 1。
  577. const short = await run(fake, cwd, "prefix", "生日");
  578. assert.equal(short.code, 1);
  579. assert.equal(short.error.code, "INVALID_ARGS");
  580. fake.rejectPrefixes.add("bad-word");
  581. const rejected = await run(fake, cwd, "prefix", "bad word");
  582. assert.equal(rejected.code, 1);
  583. assert.equal(rejected.error.code, 3614);
  584. assert.equal((await run(fake, cwd, "prefix")).code, 1);
  585. });
  586. test("delete needs an explicit --site and unlinks the project", async () => {
  587. const fake = new FakeSites();
  588. const site = fake.site();
  589. const other = fake.site();
  590. const cwd = await project();
  591. await writeFile(
  592. join(cwd, ".zcode-site.json"),
  593. JSON.stringify({ siteId: site.id, domainLabel: site.domainLabel }),
  594. );
  595. const missing = await run(fake, cwd, "delete");
  596. assert.equal(missing.code, 1);
  597. assert.equal(missing.error.code, "MISSING_SITE");
  598. assert.equal(fake.sites.length, 2);
  599. const kept = await run(fake, cwd, "delete", "--site", other.id);
  600. assert.deepEqual(kept.result, { siteId: other.id, deleted: true, unlinked: false });
  601. await readFile(join(cwd, ".zcode-site.json"), "utf8");
  602. fake.deployment(site.id, { status: "publishing" });
  603. const busy = await run(fake, cwd, "delete", "--site", site.id);
  604. assert.equal(busy.code, 3);
  605. assert.equal(busy.error.code, 3610);
  606. fake.deployments = [];
  607. const removed = await run(fake, cwd, "delete", "--site", site.id);
  608. assert.deepEqual(removed.result, { siteId: site.id, deleted: true, unlinked: true });
  609. await assert.rejects(readFile(join(cwd, ".zcode-site.json"), "utf8"), { code: "ENOENT" });
  610. assert.equal(fake.sites.length, 0);
  611. assert.equal((await run(fake, cwd, "delete", "--site", site.id)).error.code, 3601);
  612. });
  613. test("badge hide needs a plan that can remove the badge", async () => {
  614. const fake = new FakeSites();
  615. const site = fake.site();
  616. const cwd = await project();
  617. await writeFile(
  618. join(cwd, ".zcode-site.json"),
  619. JSON.stringify({ siteId: site.id, domainLabel: site.domainLabel }),
  620. );
  621. const denied = await run(fake, cwd, "badge", "hide");
  622. assert.equal(denied.code, 3);
  623. assert.equal(denied.error.code, 3608);
  624. assert.match(denied.error.hint, /paid/);
  625. fake.badgeRemovable = true;
  626. const hidden = (await run(fake, cwd, "badge", "hide")).result;
  627. assert.equal(hidden.badgeHidden, true);
  628. assert.equal(hidden.badgeVisible, false);
  629. assert.equal((await run(fake, cwd, "badge", "show")).result.badgeVisible, true);
  630. assert.equal((await run(fake, cwd, "badge")).code, 1);
  631. });
  632. test("instance switches between single and multi instance", async () => {
  633. const fake = new FakeSites();
  634. const site = fake.site();
  635. const cwd = await project();
  636. await writeFile(
  637. join(cwd, ".zcode-site.json"),
  638. JSON.stringify({ siteId: site.id, domainLabel: site.domainLabel }),
  639. );
  640. assert.equal((await run(fake, cwd, "status")).result.multiInstance, false);
  641. assert.equal((await run(fake, cwd, "instance", "multi")).result.multiInstance, true);
  642. assert.equal(fake.sites[0].multiInstance, true);
  643. assert.equal((await run(fake, cwd, "instance", "single")).result.multiInstance, false);
  644. const bad = await run(fake, cwd, "instance", "many");
  645. assert.equal(bad.code, 1);
  646. assert.equal(bad.error.code, "INVALID_ARGS");
  647. assert.equal((await run(fake, cwd, "instance")).code, 1);
  648. });
  649. test("--prefix is sent as domainPrefix only when the site is created", async () => {
  650. const fake = new FakeSites();
  651. const cwd = await project();
  652. const r = await run(
  653. fake,
  654. cwd,
  655. "deploy",
  656. "stage",
  657. "--name",
  658. "生日网站",
  659. "--prefix",
  660. "happy-birthday",
  661. );
  662. assert.equal(r.code, 0, JSON.stringify(r.error));
  663. assert.deepEqual(fake.createBodies, [{ name: "生日网站", domainPrefix: "happy-birthday" }]);
  664. assert.ok(!r.lines.some((l) => l.event === "warning"));
  665. // 已绑定站点:--prefix 不生效,也不再创建,只提示一次。
  666. const again = await run(fake, cwd, "deploy", "stage", "--prefix", "other-name");
  667. assert.equal(again.code, 0);
  668. assert.equal(fake.createBodies.length, 1);
  669. assert.match(again.lines.find((l) => l.event === "warning").message, /ignored/);
  670. });
  671. test("without --prefix the server derives the prefix from the name", async () => {
  672. const fake = new FakeSites();
  673. const r = await run(fake, await project(), "deploy", "stage", "--name", "My App");
  674. assert.equal(r.code, 0);
  675. assert.deepEqual(fake.createBodies, [{ name: "My App" }]);
  676. });
  677. test("a non-conforming --prefix is still sent, with a warning about the normalized result", async () => {
  678. const fake = new FakeSites();
  679. const r = await run(fake, await project(), "deploy", "stage", "--prefix", "Happy Birthday!");
  680. assert.equal(r.code, 0);
  681. assert.equal(fake.createBodies[0].domainPrefix, "Happy Birthday!");
  682. assert.match(r.lines.find((l) => l.event === "warning").message, /"happy-birthday"/);
  683. const short = await run(fake, await project(), "deploy", "stage", "--new", "--prefix", "ab");
  684. assert.equal(short.code, 0);
  685. assert.match(short.lines.find((l) => l.event === "warning").message, /"site"/);
  686. });
  687. test("a name that fails content review gets 3611 and nothing is linked", async () => {
  688. const fake = new FakeSites();
  689. fake.rejectNames.add("bad name");
  690. const cwd = await project();
  691. const r = await run(
  692. fake,
  693. cwd,
  694. "deploy",
  695. "stage",
  696. "--name",
  697. "bad name",
  698. "--prefix",
  699. "fine-prefix",
  700. );
  701. assert.equal(r.code, 1);
  702. assert.equal(r.error.code, 3611);
  703. assert.match(r.error.hint, /--name/);
  704. assert.equal(fake.deployments.length, 0);
  705. await assert.rejects(readFile(join(cwd, ".zcode-site.json")));
  706. // 改名不通过时名称不变。
  707. assert.equal((await run(fake, cwd, "deploy", "stage", "--name", "good")).code, 0);
  708. const renamed = await run(fake, cwd, "rename", "bad", "name");
  709. assert.equal(renamed.code, 1);
  710. assert.equal(renamed.error.code, 3611);
  711. assert.equal(fake.sites[0].name, "good");
  712. });
  713. test("a site whose live version was rejected by content review gets 3612 until redeployed", async () => {
  714. const fake = new FakeSites();
  715. const cwd = await project();
  716. assert.equal((await run(fake, cwd, "deploy", "stage")).code, 0);
  717. const site = fake.sites[0];
  718. assert.equal((await run(fake, cwd, "status")).result.offlineReason, undefined);
  719. // 人审驳回:服务端把站点下线并带上 offlineReason。
  720. Object.assign(site, { status: "offline", offlineReason: "review_rejected" });
  721. const status = (await run(fake, cwd, "status")).result;
  722. assert.equal(status.status, "offline");
  723. assert.equal(status.offlineReason, "review_rejected");
  724. const denied = await run(fake, cwd, "online");
  725. assert.equal(denied.code, 3);
  726. assert.equal(denied.error.code, 3612);
  727. assert.match(denied.error.hint, /deploy again/);
  728. assert.equal(site.status, "offline");
  729. // 重新部署成功后站点恢复上线。
  730. assert.equal((await run(fake, cwd, "deploy", "stage")).code, 0);
  731. const redeployed = (await run(fake, cwd, "status")).result;
  732. assert.equal(redeployed.status, "online");
  733. assert.equal(redeployed.offlineReason, undefined);
  734. });
  735. test("a prefix replaced by site after content review gets a warning", async () => {
  736. const fake = new FakeSites();
  737. fake.rejectPrefixes.add("bad-prefix").add("bad-name");
  738. const r = await run(fake, await project(), "deploy", "stage", "--prefix", "Bad Prefix");
  739. assert.equal(r.code, 0);
  740. const warnings = r.lines.filter((l) => l.event === "warning").map((l) => l.message);
  741. assert.ok(
  742. warnings.some(
  743. (m) => /"bad-prefix" did not pass content review/.test(m) && m.includes(r.result.url),
  744. ),
  745. warnings,
  746. );
  747. assert.match(r.result.url, /^https:\/\/site-/);
  748. // 没有 --prefix 时前缀来自名称,同样提示。
  749. const byName = await run(fake, await project(), "deploy", "stage", "--new", "--name", "Bad Name");
  750. assert.ok(byName.lines.some((l) => l.event === "warning" && /"bad-name"/.test(l.message)));
  751. // 规范化后本来就是 site 的不算机审替换,只有规范化提示。
  752. const short = await run(fake, await project(), "deploy", "stage", "--new", "--prefix", "ab");
  753. assert.equal(short.code, 0);
  754. assert.ok(!short.lines.some((l) => /content review/.test(l.message ?? "")));
  755. });
  756. test("normalizePrefix matches the server rule", () => {
  757. const cases = [
  758. ["happy-birthday", "happy-birthday"],
  759. ["Happy Birthday!", "happy-birthday"],
  760. ["-a..b--cd-", "a-b-cd"],
  761. ["生日快乐", "site"],
  762. ["ab", "site"],
  763. ["abcd", "abcd"],
  764. ["", "site"],
  765. ["a".repeat(40), "a".repeat(30)],
  766. ["a".repeat(29) + "-b", "a".repeat(29)],
  767. ];
  768. for (const [input, want] of cases) assert.equal(normalizePrefix(input), want, input);
  769. });
  770. test("help documents every command and option, and needs no endpoint", async () => {
  771. let stdout = "";
  772. const code = await main(["help"], {
  773. env: {},
  774. cwd: tmpdir(),
  775. stdout: { write: (s) => (stdout += s) },
  776. stderr: { write() {} },
  777. });
  778. assert.equal(code, 0);
  779. const commands = [
  780. "check",
  781. "deploy",
  782. "status",
  783. "logs",
  784. "offline",
  785. "online",
  786. "rename",
  787. "badge",
  788. "instance",
  789. "list",
  790. "usage",
  791. "analytics",
  792. "prefix",
  793. "delete",
  794. "help",
  795. ];
  796. const options = [
  797. "--new",
  798. "--site",
  799. "--name",
  800. "--prefix",
  801. "--offset",
  802. "--range",
  803. "--quiet",
  804. "--port",
  805. "--allow-foreign-binaries",
  806. ];
  807. for (const word of commands) assert.match(stdout, new RegExp(`^ ${word}\\b`, "m"), word);
  808. for (const word of options) assert.ok(stdout.includes(word), word);
  809. for (const exit of ["0", "1", "2", "3", "4"])
  810. assert.match(stdout, new RegExp(`^ ${exit} `, "m"));
  811. });