nodeApiClient.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import { ApiError } from "@zcode/shared";
  3. import { createNodeApiClient } from "../src/providers/api/nodeApiClient.js";
  4. describe("nodeApiClient", () => {
  5. it.each(["bigmodel", "zai"])("%s 空业务响应经身份核验确认失效,保留原响应", async (family) => {
  6. const original = new Response("");
  7. const notified = vi.fn();
  8. const fetchImpl = vi.fn(async (url: string | URL) =>
  9. String(url).endsWith("/userinfo")
  10. ? family === "bigmodel"
  11. ? new Response("")
  12. : Response.json({ code: 401 })
  13. : original,
  14. );
  15. const options = {
  16. fetchImpl,
  17. isZcodeJwtRequest: () => true,
  18. isBusinessUnauthorizedRequest: () => true,
  19. resolveBusinessCredentialValidationRequest: async () => ({
  20. url: "https://identity.example/userinfo",
  21. authorization: "business-token",
  22. emptyBodyMeansInvalid: family === "bigmodel",
  23. }),
  24. onZcodeJwtInvalid: notified,
  25. };
  26. const client = createNodeApiClient(options);
  27. const response = await client.request("https://business.example/pricing");
  28. expect(response).toBe(original);
  29. expect(await response.text()).toBe("");
  30. expect(fetchImpl).toHaveBeenCalledTimes(2);
  31. expect(notified).toHaveBeenCalledOnce();
  32. });
  33. it.each([200, 403])("业务 HTTP %i 异常但身份正常时不登出", async (status) => {
  34. const notified = vi.fn();
  35. const client = createNodeApiClient({
  36. fetchImpl: async (url) =>
  37. String(url).endsWith("/userinfo")
  38. ? Response.json({ code: 200, data: { customerNumber: "synthetic" } })
  39. : new Response("", { status }),
  40. isZcodeJwtRequest: () => true,
  41. isBusinessUnauthorizedRequest: () => true,
  42. resolveBusinessCredentialValidationRequest: async () => ({
  43. url: "https://identity.example/userinfo",
  44. authorization: "business-token",
  45. emptyBodyMeansInvalid: true,
  46. }),
  47. onZcodeJwtInvalid: notified,
  48. });
  49. await client.request("https://business.example/pricing");
  50. expect(notified).not.toHaveBeenCalled();
  51. });
  52. it.each(["", "<html>blocked</html>", "{", '{"code":500}'])(
  53. "未确认的 ZAI 身份响应不登出:%s",
  54. async (body) => {
  55. const notified = vi.fn();
  56. const client = createNodeApiClient({
  57. fetchImpl: async (url) => new Response(String(url).endsWith("/userinfo") ? body : ""),
  58. isZcodeJwtRequest: () => true,
  59. isBusinessUnauthorizedRequest: () => true,
  60. resolveBusinessCredentialValidationRequest: async () => ({
  61. url: "https://identity.example/userinfo",
  62. authorization: "business-token",
  63. emptyBodyMeansInvalid: false,
  64. }),
  65. onZcodeJwtInvalid: notified,
  66. });
  67. await client.request("https://business.example/pricing");
  68. expect(notified).not.toHaveBeenCalled();
  69. },
  70. );
  71. it.each(["network", "server"])("BigModel 身份核验 %s 失败时保留登录", async (failure) => {
  72. const notified = vi.fn();
  73. const client = createNodeApiClient({
  74. fetchImpl: async (url) => {
  75. if (!String(url).endsWith("/userinfo")) return new Response("");
  76. if (failure === "network") throw new TypeError("offline");
  77. return Response.json({ code: 401 }, { status: 500 });
  78. },
  79. isZcodeJwtRequest: () => true,
  80. isBusinessUnauthorizedRequest: () => true,
  81. resolveBusinessCredentialValidationRequest: async () => ({
  82. url: "https://identity.example/userinfo",
  83. authorization: "business-token",
  84. emptyBodyMeansInvalid: true,
  85. }),
  86. onZcodeJwtInvalid: notified,
  87. });
  88. await client.request("https://business.example/pricing");
  89. expect(notified).not.toHaveBeenCalled();
  90. });
  91. it("当前 BigModel 身份接口空200直接确认,不递归核验", async () => {
  92. const notified = vi.fn();
  93. const fetchImpl = vi.fn(async () => new Response(""));
  94. const client = createNodeApiClient({
  95. fetchImpl,
  96. isZcodeJwtRequest: () => true,
  97. isBusinessUnauthorizedRequest: () => true,
  98. resolveBusinessCredentialValidationRequest: async () => ({
  99. url: "https://identity.example/userinfo",
  100. authorization: "business-token",
  101. emptyBodyMeansInvalid: true,
  102. }),
  103. onZcodeJwtInvalid: notified,
  104. });
  105. await client.request("https://identity.example/userinfo");
  106. expect(fetchImpl).toHaveBeenCalledOnce();
  107. expect(notified).toHaveBeenCalledOnce();
  108. });
  109. it("并发空业务响应共享一个在途身份核验", async () => {
  110. let release!: (response: Response) => void;
  111. const identity = new Promise<Response>((resolve) => {
  112. release = resolve;
  113. });
  114. const fetchImpl = vi.fn(async (url) =>
  115. String(url).endsWith("/userinfo") ? identity : new Response(""),
  116. );
  117. const client = createNodeApiClient({
  118. fetchImpl,
  119. isZcodeJwtRequest: () => true,
  120. isBusinessUnauthorizedRequest: () => true,
  121. resolveBusinessCredentialValidationRequest: async () => ({
  122. url: "https://identity.example/userinfo",
  123. authorization: "business-token",
  124. emptyBodyMeansInvalid: true,
  125. }),
  126. onZcodeJwtInvalid: vi.fn(),
  127. });
  128. const requests = [
  129. client.request("https://business.example/a"),
  130. client.request("https://business.example/b"),
  131. ];
  132. await vi.waitFor(() =>
  133. expect(
  134. fetchImpl.mock.calls.filter(([url]) => String(url).endsWith("/userinfo")),
  135. ).toHaveLength(1),
  136. );
  137. release(new Response(""));
  138. await Promise.all(requests);
  139. expect(fetchImpl.mock.calls.filter(([url]) => String(url).endsWith("/userinfo"))).toHaveLength(
  140. 1,
  141. );
  142. });
  143. it.each(["abort", "timeout"] as const)(
  144. "身份核验 fetch 期间 %s 立即收口且不提交迟到失效",
  145. async (cancellation) => {
  146. vi.useFakeTimers();
  147. const controller = new AbortController();
  148. let identitySignal: AbortSignal | undefined;
  149. let release!: (response: Response) => void;
  150. let started!: () => void;
  151. const identityStarted = new Promise<void>((resolve) => {
  152. started = resolve;
  153. });
  154. const notified = vi.fn();
  155. const finalized = vi.fn();
  156. const client = createNodeApiClient({
  157. fetchImpl: async (url, init) => {
  158. if (!String(url).endsWith("/userinfo")) return new Response("", { status: 403 });
  159. identitySignal = init?.signal ?? undefined;
  160. started();
  161. return new Promise<Response>((resolve) => {
  162. release = resolve;
  163. });
  164. },
  165. isZcodeJwtRequest: () => true,
  166. isBusinessUnauthorizedRequest: () => true,
  167. resolveBusinessCredentialValidationRequest: async () => ({
  168. url: "https://identity.example/userinfo",
  169. authorization: "business-token",
  170. emptyBodyMeansInvalid: true,
  171. }),
  172. onZcodeJwtInvalid: notified,
  173. });
  174. const result = client
  175. .request("https://business.example/pricing", {
  176. signal: controller.signal,
  177. timeoutMs: 50,
  178. })
  179. .finally(finalized)
  180. .catch((error: unknown) => error);
  181. await identityStarted;
  182. if (cancellation === "abort") controller.abort();
  183. else await vi.advanceTimersByTimeAsync(50);
  184. // 受控 transport 故意忽略 abort:主请求不能等待迟到响应才能执行 finally。
  185. const error = await result;
  186. expect(finalized).toHaveBeenCalledOnce();
  187. expect(error).toBeInstanceOf(ApiError);
  188. if (!(error instanceof ApiError)) throw error;
  189. expect(error.message).toBe(
  190. cancellation === "timeout" ? "Request timed out after 50ms" : "The operation was aborted.",
  191. );
  192. expect(identitySignal?.aborted).toBe(true);
  193. release(new Response("", { status: 401 }));
  194. await vi.advanceTimersByTimeAsync(0);
  195. expect(notified).not.toHaveBeenCalled();
  196. expect(vi.getTimerCount()).toBe(0);
  197. },
  198. );
  199. it.each(["business", "identity"] as const)(
  200. "%s 响应副本读取期间取消会立即收口并取消观察副本",
  201. async (phase) => {
  202. const controller = new AbortController();
  203. let reading!: () => void;
  204. const readStarted = new Promise<void>((resolve) => {
  205. reading = resolve;
  206. });
  207. const cancel = vi.fn();
  208. const body = new ReadableStream<Uint8Array>(
  209. {
  210. pull() {
  211. reading();
  212. },
  213. cancel,
  214. },
  215. { highWaterMark: 0 },
  216. );
  217. const response = new Response("", { status: phase === "identity" ? 403 : 200 });
  218. vi.spyOn(response, "clone").mockReturnValue(new Response(body));
  219. const notified = vi.fn();
  220. const client = createNodeApiClient({
  221. fetchImpl: async (url) =>
  222. phase === "business" || String(url).endsWith("/userinfo")
  223. ? response
  224. : new Response("", { status: 403 }),
  225. isZcodeJwtRequest: () => true,
  226. isBusinessUnauthorizedRequest: () => true,
  227. resolveBusinessCredentialValidationRequest: async () => ({
  228. url: "https://identity.example/userinfo",
  229. authorization: "business-token",
  230. emptyBodyMeansInvalid: true,
  231. }),
  232. onZcodeJwtInvalid: notified,
  233. });
  234. const result = client
  235. .request("https://business.example/pricing", { signal: controller.signal })
  236. .catch((error: unknown) => error);
  237. await readStarted;
  238. controller.abort();
  239. const error = await result;
  240. expect(error).toBeInstanceOf(ApiError);
  241. await vi.waitFor(() => expect(cancel).toHaveBeenCalledOnce());
  242. expect(notified).not.toHaveBeenCalled();
  243. },
  244. );
  245. it("并发核验中一个请求取消不会取消另一请求的核验", async () => {
  246. const controller = new AbortController();
  247. let release!: (response: Response) => void;
  248. let signal: AbortSignal | undefined;
  249. const identity = new Promise<Response>((resolve) => {
  250. release = resolve;
  251. });
  252. const fetchImpl = vi.fn(async (url, init) => {
  253. if (!String(url).endsWith("/userinfo")) return new Response("", { status: 403 });
  254. signal = init?.signal ?? undefined;
  255. return identity;
  256. });
  257. const notified = vi.fn();
  258. const client = createNodeApiClient({
  259. fetchImpl,
  260. isZcodeJwtRequest: () => true,
  261. isBusinessUnauthorizedRequest: () => true,
  262. resolveBusinessCredentialValidationRequest: async () => ({
  263. url: "https://identity.example/userinfo",
  264. authorization: "business-token",
  265. emptyBodyMeansInvalid: true,
  266. }),
  267. onZcodeJwtInvalid: notified,
  268. });
  269. const cancelled = client
  270. .request("https://business.example/a", { signal: controller.signal })
  271. .catch((error: unknown) => error);
  272. const retained = client.request("https://business.example/b");
  273. await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledTimes(3));
  274. await new Promise<void>((resolve) => setImmediate(resolve));
  275. controller.abort();
  276. expect(await cancelled).toBeInstanceOf(ApiError);
  277. expect(signal?.aborted).toBe(false);
  278. release(new Response("", { status: 401 }));
  279. await expect(retained).resolves.toMatchObject({ status: 403 });
  280. expect(notified).toHaveBeenCalledOnce();
  281. });
  282. it("身份 transport 忽略取消时仍按观察预算结束核验且不登出", async () => {
  283. const notified = vi.fn();
  284. let identitySignal: AbortSignal | undefined;
  285. const original = new Response("", { status: 403 });
  286. const client = createNodeApiClient({
  287. fetchImpl: async (url, init) => {
  288. if (!String(url).endsWith("/userinfo")) return original;
  289. identitySignal = init?.signal ?? undefined;
  290. return new Promise<Response>(() => {});
  291. },
  292. businessUnauthorizedObservationTimeoutMs: 20,
  293. isZcodeJwtRequest: () => true,
  294. isBusinessUnauthorizedRequest: () => true,
  295. resolveBusinessCredentialValidationRequest: async () => ({
  296. url: "https://identity.example/userinfo",
  297. authorization: "business-token",
  298. emptyBodyMeansInvalid: true,
  299. }),
  300. onZcodeJwtInvalid: notified,
  301. });
  302. await expect(client.request("https://business.example/pricing")).resolves.toBe(original);
  303. expect(identitySignal?.aborted).toBe(true);
  304. expect(notified).not.toHaveBeenCalled();
  305. });
  306. it("响应观察自身超时取消副本并保留原响应和会话", async () => {
  307. const cancel = vi.fn();
  308. const response = new Response("original");
  309. vi.spyOn(response, "clone").mockReturnValue(new Response(new ReadableStream({ cancel })));
  310. const notified = vi.fn();
  311. const client = createNodeApiClient({
  312. fetchImpl: async () => response,
  313. businessUnauthorizedObservationTimeoutMs: 20,
  314. isZcodeJwtRequest: () => true,
  315. isBusinessUnauthorizedRequest: () => true,
  316. onZcodeJwtInvalid: notified,
  317. });
  318. await expect(client.request("https://business.example/pricing")).resolves.toBe(response);
  319. expect(await response.text()).toBe("original");
  320. expect(cancel).toHaveBeenCalledOnce();
  321. expect(notified).not.toHaveBeenCalled();
  322. });
  323. it("取消后迟到的凭据分类结果不启动核验或通知失效", async () => {
  324. const controller = new AbortController();
  325. let release!: (current: boolean) => void;
  326. let started!: () => void;
  327. const classified = new Promise<void>((resolve) => {
  328. started = resolve;
  329. });
  330. const notified = vi.fn();
  331. const fetchImpl = vi.fn(async () => new Response("", { status: 403 }));
  332. const resolveValidation = vi.fn(async () => ({
  333. url: "https://identity.example/userinfo",
  334. authorization: "business-token",
  335. emptyBodyMeansInvalid: true,
  336. }));
  337. const client = createNodeApiClient({
  338. fetchImpl,
  339. isZcodeJwtRequest: async () => {
  340. started();
  341. return new Promise<boolean>((resolve) => {
  342. release = resolve;
  343. });
  344. },
  345. isBusinessUnauthorizedRequest: () => true,
  346. resolveBusinessCredentialValidationRequest: resolveValidation,
  347. onZcodeJwtInvalid: notified,
  348. });
  349. const result = client
  350. .request("https://business.example/pricing", { signal: controller.signal })
  351. .catch((error: unknown) => error);
  352. await classified;
  353. controller.abort();
  354. expect(await result).toBeInstanceOf(ApiError);
  355. release(true);
  356. await new Promise<void>((resolve) => setImmediate(resolve));
  357. expect(fetchImpl).toHaveBeenCalledOnce();
  358. expect(resolveValidation).not.toHaveBeenCalled();
  359. expect(notified).not.toHaveBeenCalled();
  360. });
  361. afterEach(() => {
  362. vi.useRealTimers();
  363. });
  364. it("会给请求自动补 x-request-id", async () => {
  365. const fetchImpl = vi.fn(async () => new Response("{}", { status: 200 }));
  366. const client = createNodeApiClient({ fetchImpl });
  367. await client.request("https://example.com/oauth/token", {
  368. method: "POST",
  369. });
  370. const headers = new Headers(fetchImpl.mock.calls[0]?.[1]?.headers);
  371. expect(headers.get("x-request-id")).toMatch(
  372. /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
  373. );
  374. });
  375. it("保留调用方显式传入的 x-request-id", async () => {
  376. const fetchImpl = vi.fn(async () => new Response("{}", { status: 200 }));
  377. const client = createNodeApiClient({ fetchImpl });
  378. await client.request("https://example.com/oauth/token", {
  379. method: "POST",
  380. headers: {
  381. "X-Request-Id": "caller-request-id",
  382. },
  383. });
  384. const headers = new Headers(fetchImpl.mock.calls[0]?.[1]?.headers);
  385. expect(headers.get("x-request-id")).toBe("caller-request-id");
  386. });
  387. it("401 且请求携带当前 ZCode JWT 时通知回调", async () => {
  388. const onZcodeJwtInvalid = vi.fn();
  389. const fetchImpl = vi.fn(
  390. async () =>
  391. new Response("", {
  392. status: 401,
  393. }),
  394. );
  395. const client = createNodeApiClient({
  396. fetchImpl,
  397. onZcodeJwtInvalid,
  398. isZcodeJwtRequest: (_input, headers) => headers.get("authorization") === "Bearer jwt",
  399. });
  400. await client.request("https://example.com/model", { headers: { Authorization: "Bearer jwt" } });
  401. expect(onZcodeJwtInvalid).toHaveBeenCalledTimes(1);
  402. });
  403. it("普通 401 不通知 ZCode JWT 失效", async () => {
  404. const onZcodeJwtInvalid = vi.fn();
  405. const fetchImpl = vi.fn(async () => new Response("", { status: 401 }));
  406. const client = createNodeApiClient({ fetchImpl, onZcodeJwtInvalid });
  407. await client.request("https://example.com/model");
  408. expect(onZcodeJwtInvalid).not.toHaveBeenCalled();
  409. });
  410. it("HTTP 200 业务 401 复用失效通知,保留原响应正文", async () => {
  411. const payload = { code: 401, msg: "登录状态已过期", success: false };
  412. const response = Response.json(payload);
  413. const onZcodeJwtInvalid = vi.fn();
  414. const client = createNodeApiClient({
  415. fetchImpl: async () => response,
  416. isZcodeJwtRequest: () => true,
  417. isBusinessUnauthorizedRequest: () => true,
  418. onZcodeJwtInvalid,
  419. });
  420. const result = await client.request("https://example.com/userinfo");
  421. expect(onZcodeJwtInvalid).toHaveBeenCalledOnce();
  422. expect(result).toBe(response);
  423. expect(result.status).toBe(200);
  424. expect(result.bodyUsed).toBe(false);
  425. expect(await result.json()).toEqual(payload);
  426. });
  427. it("不匹配当前凭据的 HTTP 200 不读取响应副本", async () => {
  428. const response = Response.json({ code: 401 });
  429. const clone = vi.spyOn(response, "clone");
  430. const onZcodeJwtInvalid = vi.fn();
  431. const client = createNodeApiClient({
  432. fetchImpl: async () => response,
  433. isZcodeJwtRequest: () => false,
  434. onZcodeJwtInvalid,
  435. });
  436. expect(await client.request("https://example.com/model")).toBe(response);
  437. expect(clone).not.toHaveBeenCalled();
  438. expect(onZcodeJwtInvalid).not.toHaveBeenCalled();
  439. });
  440. it("当前 JWT 的 SSE 不读取正文,不等待 continuous 流结束", async () => {
  441. const response = new Response(new ReadableStream(), {
  442. headers: { "Content-Type": "text/event-stream; charset=utf-8" },
  443. });
  444. const clone = vi.spyOn(response, "clone");
  445. const onZcodeJwtInvalid = vi.fn();
  446. const client = createNodeApiClient({
  447. fetchImpl: async () => response,
  448. isZcodeJwtRequest: () => true,
  449. onZcodeJwtInvalid,
  450. });
  451. expect(await client.request("https://example.com/stream")).toBe(response);
  452. expect(clone).not.toHaveBeenCalled();
  453. expect(onZcodeJwtInvalid).not.toHaveBeenCalled();
  454. await response.body?.cancel();
  455. });
  456. it("业务 401 观察达到时间预算后放行原响应", async () => {
  457. const response = new Response(new ReadableStream(), {
  458. headers: { "Content-Type": "application/json" },
  459. });
  460. const onZcodeJwtInvalid = vi.fn();
  461. const client = createNodeApiClient({
  462. fetchImpl: async () => response,
  463. isZcodeJwtRequest: () => true,
  464. isBusinessUnauthorizedRequest: () => true,
  465. onZcodeJwtInvalid,
  466. businessUnauthorizedObservationTimeoutMs: 10,
  467. });
  468. const request = client.request("https://bigmodel.cn/api/biz/customer/getCustomerInfo", {
  469. headers: { Authorization: "Bearer jwt" },
  470. });
  471. await expect(request).resolves.toBe(response);
  472. expect(onZcodeJwtInvalid).not.toHaveBeenCalled();
  473. await response.body?.cancel();
  474. });
  475. it("普通当前 JWT 请求不会读取 HTTP 200 响应副本", async () => {
  476. const response = Response.json({ code: 401 });
  477. const clone = vi.spyOn(response, "clone");
  478. const onZcodeJwtInvalid = vi.fn();
  479. const client = createNodeApiClient({
  480. fetchImpl: async () => response,
  481. isZcodeJwtRequest: () => true,
  482. onZcodeJwtInvalid,
  483. });
  484. await expect(client.request("https://example.com/model")).resolves.toBe(response);
  485. expect(clone).not.toHaveBeenCalled();
  486. expect(onZcodeJwtInvalid).not.toHaveBeenCalled();
  487. });
  488. it("业务 401 观察超过正文预算后放行原响应", async () => {
  489. const body = "x".repeat(64 * 1024 + 1);
  490. const response = new Response(body, { headers: { "Content-Type": "application/json" } });
  491. const onZcodeJwtInvalid = vi.fn();
  492. const client = createNodeApiClient({
  493. fetchImpl: async () => response,
  494. isZcodeJwtRequest: () => true,
  495. isBusinessUnauthorizedRequest: () => true,
  496. onZcodeJwtInvalid,
  497. });
  498. await expect(
  499. client.request("https://bigmodel.cn/api/biz/customer/getCustomerInfo"),
  500. ).resolves.toBe(response);
  501. expect(onZcodeJwtInvalid).not.toHaveBeenCalled();
  502. expect((await response.text()).length).toBe(body.length);
  503. });
  504. it("会把 timeoutMs 转成统一的 ApiError", async () => {
  505. vi.useFakeTimers();
  506. const fetchImpl = vi.fn((input: RequestInfo | URL, init?: RequestInit) => {
  507. return new Promise<Response>((_resolve, reject) => {
  508. const signal = init?.signal;
  509. signal?.addEventListener(
  510. "abort",
  511. () => {
  512. reject(new DOMException("The operation was aborted.", "AbortError"));
  513. },
  514. { once: true },
  515. );
  516. });
  517. });
  518. const client = createNodeApiClient({ fetchImpl });
  519. const requestPromise = client.request("https://example.com/oauth/token", {
  520. method: "POST",
  521. timeoutMs: 10,
  522. });
  523. const expectation = expect(requestPromise).rejects.toEqual(
  524. expect.objectContaining<ApiError>({
  525. name: "ApiError",
  526. method: "POST",
  527. status: undefined,
  528. url: "https://example.com/oauth/token",
  529. }),
  530. );
  531. await vi.advanceTimersByTimeAsync(10);
  532. await expectation;
  533. });
  534. it("外部主动 abort 时不会误报成 timeout", async () => {
  535. const fetchImpl = vi.fn((input: RequestInfo | URL, init?: RequestInit) => {
  536. return new Promise<Response>((_resolve, reject) => {
  537. init?.signal?.addEventListener(
  538. "abort",
  539. () => {
  540. reject(new DOMException("The operation was aborted.", "AbortError"));
  541. },
  542. { once: true },
  543. );
  544. });
  545. });
  546. const client = createNodeApiClient({ fetchImpl });
  547. const controller = new AbortController();
  548. const requestPromise = client.request("https://example.com/oauth/token", {
  549. method: "POST",
  550. timeoutMs: 100,
  551. signal: controller.signal,
  552. });
  553. controller.abort();
  554. await expect(requestPromise).rejects.toMatchObject<ApiError>({
  555. name: "ApiError",
  556. method: "POST",
  557. status: undefined,
  558. url: "https://example.com/oauth/token",
  559. message: "The operation was aborted.",
  560. });
  561. });
  562. });