zcode-site.test.mjs 29 KB

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