@dangao/bun-server 1.1.4 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,29 @@
1
1
  /**
2
2
  * 获取测试专用端口
3
- * 使用随机高位端口,降低并行测试的端口冲突概率
3
+ * 使用随机高位端口,并主动探测端口可用性,降低并行测试/系统占用导致的端口冲突概率
4
4
  * @returns 不同测试之间不冲突的端口号
5
5
  */
6
6
  export function getTestPort(): number {
7
7
  // 选择 30000-59999 之间的随机端口,避免常用端口冲突
8
- return 30000 + Math.floor(Math.random() * 30000);
8
+ // 并通过 Bun.serve 探测端口是否可用(可用则立刻 stop),避免 EADDRINUSE 造成测试雪崩失败
9
+ let lastError: unknown;
10
+ for (let i = 0; i < 50; i++) {
11
+ const port = 30000 + Math.floor(Math.random() * 30000);
12
+ try {
13
+ const probe = Bun.serve({
14
+ port,
15
+ fetch: () => new Response('ok'),
16
+ });
17
+ probe.stop();
18
+ return port;
19
+ } catch (error) {
20
+ lastError = error;
21
+ // 端口占用,继续尝试
22
+ }
23
+ }
24
+
25
+ throw new Error(
26
+ `Unable to find an available test port. Last error: ${String(lastError)}`,
27
+ );
9
28
  }
10
29
 
File without changes