@bitbybit-dev/cad-cloud-sdk 1.1.0 → 1.2.0-rc.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.
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +5 -15
- package/dist/client.js.map +1 -1
- package/dist/endpoints/cad.d.ts.map +1 -1
- package/dist/endpoints/cad.js +0 -3
- package/dist/endpoints/cad.js.map +1 -1
- package/dist/endpoints/convert.d.ts.map +1 -1
- package/dist/endpoints/convert.js +0 -3
- package/dist/endpoints/convert.js.map +1 -1
- package/dist/endpoints/files.d.ts.map +1 -1
- package/dist/endpoints/files.js +0 -3
- package/dist/endpoints/files.js.map +1 -1
- package/dist/endpoints/models.d.ts.map +1 -1
- package/dist/endpoints/models.js +0 -3
- package/dist/endpoints/models.js.map +1 -1
- package/dist/endpoints/tasks.d.ts.map +1 -1
- package/dist/endpoints/tasks.js +0 -3
- package/dist/endpoints/tasks.js.map +1 -1
- package/dist/errors.d.ts +4 -4
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +0 -3
- package/dist/errors.js.map +1 -1
- package/dist/fetch-downloads.d.ts.map +1 -1
- package/dist/fetch-downloads.js +0 -3
- package/dist/fetch-downloads.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -8
- package/dist/index.js.map +1 -1
- package/dist/polling.d.ts.map +1 -1
- package/dist/polling.js +0 -3
- package/dist/polling.js.map +1 -1
- package/dist/types/custom.d.ts.map +1 -1
- package/dist/types/custom.js +0 -5
- package/dist/types/custom.js.map +1 -1
- package/dist/types/generated.d.ts +19 -6
- package/dist/types/generated.d.ts.map +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +0 -7
- package/dist/types/index.js.map +1 -1
- package/dist/types/pipeline-operations.d.ts +253 -47
- package/dist/types/pipeline-operations.d.ts.map +1 -1
- package/dist/types/pipeline-operations.js +1 -1
- package/dist/types/pipeline-operations.js.map +1 -1
- package/dist/unwrap.d.ts.map +1 -1
- package/dist/unwrap.js +0 -3
- package/dist/unwrap.js.map +1 -1
- package/dist/validation/validator.d.ts.map +1 -1
- package/dist/validation/validator.js +0 -8
- package/dist/validation/validator.js.map +1 -1
- package/package.json +6 -3
- package/src/__test__/helpers.ts +71 -0
- package/src/__test__/index.ts +1 -0
- package/src/client.test.ts +206 -0
- package/src/client.ts +153 -0
- package/src/endpoints/cad.test.ts +101 -0
- package/src/endpoints/cad.ts +53 -0
- package/src/endpoints/convert.test.ts +154 -0
- package/src/endpoints/convert.ts +83 -0
- package/src/endpoints/files.test.ts +170 -0
- package/src/endpoints/files.ts +89 -0
- package/src/endpoints/index.ts +5 -0
- package/src/endpoints/models.test.ts +228 -0
- package/src/endpoints/models.ts +131 -0
- package/src/endpoints/tasks.test.ts +193 -0
- package/src/endpoints/tasks.ts +93 -0
- package/src/errors.test.ts +57 -0
- package/src/errors.ts +21 -0
- package/src/fetch-downloads.test.ts +67 -0
- package/src/fetch-downloads.ts +18 -0
- package/src/index.ts +19 -0
- package/src/polling.test.ts +194 -0
- package/src/polling.ts +81 -0
- package/src/types/custom.ts +45 -0
- package/src/types/generated.ts +3136 -0
- package/src/types/index.ts +3 -0
- package/src/types/pipeline-operations.ts +9008 -0
- package/src/types/schema-exports.ts +228 -0
- package/src/unwrap.test.ts +75 -0
- package/src/unwrap.ts +20 -0
- package/src/validation/index.ts +1 -0
- package/src/validation/request-schemas.ts +1001 -0
- package/src/validation/validator.test.ts +218 -0
- package/src/validation/validator.ts +60 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { BitbybitApiError } from "./errors.js";
|
|
3
|
+
|
|
4
|
+
describe("BitbybitApiError", () => {
|
|
5
|
+
it("sets all properties from constructor options", () => {
|
|
6
|
+
// Arrange
|
|
7
|
+
const opts = {
|
|
8
|
+
code: "VALIDATION_ERROR",
|
|
9
|
+
message: "Invalid input",
|
|
10
|
+
statusCode: 400,
|
|
11
|
+
details: { field: "name" },
|
|
12
|
+
requestId: "req-123",
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
// Act
|
|
16
|
+
const error = new BitbybitApiError(opts);
|
|
17
|
+
|
|
18
|
+
// Assert
|
|
19
|
+
expect(error.code).toBe("VALIDATION_ERROR");
|
|
20
|
+
expect(error.message).toBe("Invalid input");
|
|
21
|
+
expect(error.statusCode).toBe(400);
|
|
22
|
+
expect(error.details).toStrictEqual({ field: "name" });
|
|
23
|
+
expect(error.requestId).toBe("req-123");
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it("extends Error", () => {
|
|
27
|
+
// Act
|
|
28
|
+
const error = new BitbybitApiError({ code: "TEST", message: "test", statusCode: 500 });
|
|
29
|
+
|
|
30
|
+
// Assert
|
|
31
|
+
expect(error).toBeInstanceOf(Error);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it("has name set to BitbybitApiError", () => {
|
|
35
|
+
// Act
|
|
36
|
+
const error = new BitbybitApiError({ code: "TEST", message: "test", statusCode: 500 });
|
|
37
|
+
|
|
38
|
+
// Assert
|
|
39
|
+
expect(error.name).toBe("BitbybitApiError");
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("leaves details undefined when not provided", () => {
|
|
43
|
+
// Act
|
|
44
|
+
const error = new BitbybitApiError({ code: "TEST", message: "test", statusCode: 500 });
|
|
45
|
+
|
|
46
|
+
// Assert
|
|
47
|
+
expect(error.details).toBe(undefined);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("leaves requestId undefined when not provided", () => {
|
|
51
|
+
// Act
|
|
52
|
+
const error = new BitbybitApiError({ code: "TEST", message: "test", statusCode: 500 });
|
|
53
|
+
|
|
54
|
+
// Assert
|
|
55
|
+
expect(error.requestId).toBe(undefined);
|
|
56
|
+
});
|
|
57
|
+
});
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export class BitbybitApiError extends Error {
|
|
2
|
+
readonly code: string;
|
|
3
|
+
readonly statusCode: number;
|
|
4
|
+
readonly details?: unknown | undefined;
|
|
5
|
+
readonly requestId?: string | undefined;
|
|
6
|
+
|
|
7
|
+
constructor(opts: {
|
|
8
|
+
code: string;
|
|
9
|
+
message: string;
|
|
10
|
+
statusCode: number;
|
|
11
|
+
details?: unknown | undefined;
|
|
12
|
+
requestId?: string | undefined;
|
|
13
|
+
}) {
|
|
14
|
+
super(opts.message);
|
|
15
|
+
this.name = "BitbybitApiError";
|
|
16
|
+
this.code = opts.code;
|
|
17
|
+
this.statusCode = opts.statusCode;
|
|
18
|
+
this.details = opts.details;
|
|
19
|
+
this.requestId = opts.requestId;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { fetchDownloads } from "./fetch-downloads.js";
|
|
3
|
+
import { BitbybitApiError } from "./errors.js";
|
|
4
|
+
|
|
5
|
+
function jsonResponse(data: unknown, status = 200): Response {
|
|
6
|
+
return new Response(JSON.stringify(data), {
|
|
7
|
+
status,
|
|
8
|
+
headers: { "Content-Type": "application/json" },
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
describe("fetchDownloads", () => {
|
|
13
|
+
it("returns downloads array from successful response", async () => {
|
|
14
|
+
// Arrange
|
|
15
|
+
const downloads = [
|
|
16
|
+
{ format: "glb", downloadUrl: "https://r2.example.com/result.glb", filename: "result.glb" },
|
|
17
|
+
{ format: "step", downloadUrl: "https://r2.example.com/result.step", filename: "result.step" },
|
|
18
|
+
];
|
|
19
|
+
const fetcher = async (_m: string, _p: string) =>
|
|
20
|
+
jsonResponse({ ok: true, data: { downloads } });
|
|
21
|
+
|
|
22
|
+
// Act
|
|
23
|
+
const result = await fetchDownloads(fetcher, "task-123");
|
|
24
|
+
|
|
25
|
+
// Assert
|
|
26
|
+
expect(result).toStrictEqual(downloads);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it("calls the correct API path with encoded taskId", async () => {
|
|
30
|
+
// Arrange
|
|
31
|
+
let calledPath = "";
|
|
32
|
+
const fetcher = async (_m: string, path: string) => {
|
|
33
|
+
calledPath = path;
|
|
34
|
+
return jsonResponse({ ok: true, data: { downloads: [] } });
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// Act
|
|
38
|
+
await fetchDownloads(fetcher, "task/with special");
|
|
39
|
+
|
|
40
|
+
// Assert
|
|
41
|
+
expect(calledPath).toBe("/api/v1/tasks/task%2Fwith%20special/results");
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it("uses GET method", async () => {
|
|
45
|
+
// Arrange
|
|
46
|
+
let calledMethod = "";
|
|
47
|
+
const fetcher = async (method: string, _p: string) => {
|
|
48
|
+
calledMethod = method;
|
|
49
|
+
return jsonResponse({ ok: true, data: { downloads: [] } });
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// Act
|
|
53
|
+
await fetchDownloads(fetcher, "t-1");
|
|
54
|
+
|
|
55
|
+
// Assert
|
|
56
|
+
expect(calledMethod).toBe("GET");
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("throws BitbybitApiError when API returns error", async () => {
|
|
60
|
+
// Arrange
|
|
61
|
+
const fetcher = async () =>
|
|
62
|
+
jsonResponse({ ok: false, error: { code: "NOT_FOUND", message: "no task" } }, 404);
|
|
63
|
+
|
|
64
|
+
// Act & Assert
|
|
65
|
+
await expect(fetchDownloads(fetcher, "t-bad")).rejects.toThrow(BitbybitApiError);
|
|
66
|
+
});
|
|
67
|
+
});
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { TaskDownload, TaskResultsDownload } from "./types/index.js";
|
|
2
|
+
import { unwrap } from "./unwrap.js";
|
|
3
|
+
|
|
4
|
+
type Fetcher = (method: string, path: string, body?: unknown) => Promise<Response>;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Fetch all download URLs for a completed task in a single API call.
|
|
8
|
+
* Uses `GET /api/v1/tasks/{taskId}/results` (returns all formats at once).
|
|
9
|
+
*/
|
|
10
|
+
export async function fetchDownloads(
|
|
11
|
+
fetcher: Fetcher,
|
|
12
|
+
taskId: string,
|
|
13
|
+
): Promise<TaskDownload[]> {
|
|
14
|
+
const path = `/api/v1/tasks/${encodeURIComponent(taskId)}/results`;
|
|
15
|
+
const res = await fetcher("GET", path);
|
|
16
|
+
const data = await unwrap<TaskResultsDownload>(res);
|
|
17
|
+
return data.downloads;
|
|
18
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export { BitbybitClient } from "./client.js";
|
|
2
|
+
export type { BitbybitClientOptions } from "./client.js";
|
|
3
|
+
|
|
4
|
+
export { BitbybitApiError } from "./errors.js";
|
|
5
|
+
export { BitbybitValidationError } from "./validation/index.js";
|
|
6
|
+
|
|
7
|
+
export { unwrap } from "./unwrap.js";
|
|
8
|
+
|
|
9
|
+
export type { PollOptions } from "./polling.js";
|
|
10
|
+
|
|
11
|
+
export { ModelsEndpoint } from "./endpoints/models.js";
|
|
12
|
+
export { TasksEndpoint } from "./endpoints/tasks.js";
|
|
13
|
+
export { CadEndpoint } from "./endpoints/cad.js";
|
|
14
|
+
export { ConvertEndpoint } from "./endpoints/convert.js";
|
|
15
|
+
export { FilesEndpoint } from "./endpoints/files.js";
|
|
16
|
+
|
|
17
|
+
export { step } from "./types/pipeline-operations.js";
|
|
18
|
+
|
|
19
|
+
export type * from "./types/index.js";
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from "vitest";
|
|
2
|
+
import { pollTask } from "./polling.js";
|
|
3
|
+
import { BitbybitApiError } from "./errors.js";
|
|
4
|
+
|
|
5
|
+
function jsonResponse(data: unknown, status = 200): Response {
|
|
6
|
+
return new Response(JSON.stringify(data), {
|
|
7
|
+
status,
|
|
8
|
+
headers: { "Content-Type": "application/json" },
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
describe("pollTask", () => {
|
|
13
|
+
it("returns completed task after polling", async () => {
|
|
14
|
+
// Arrange
|
|
15
|
+
const completedTask = { taskId: "t-1", status: "completed", kind: "model" };
|
|
16
|
+
const fetcher = vi.fn()
|
|
17
|
+
.mockResolvedValueOnce(jsonResponse({ ok: true, data: { taskId: "t-1", status: "processing", kind: "model" } }))
|
|
18
|
+
.mockResolvedValueOnce(jsonResponse({ ok: true, data: completedTask }));
|
|
19
|
+
|
|
20
|
+
// Act
|
|
21
|
+
const result = await pollTask(fetcher, "t-1", { intervalMs: 1, maxAttempts: 5 });
|
|
22
|
+
|
|
23
|
+
// Assert
|
|
24
|
+
expect(result).toStrictEqual(completedTask);
|
|
25
|
+
expect(fetcher).toHaveBeenCalledTimes(2);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it("calls the correct endpoint path", async () => {
|
|
29
|
+
// Arrange
|
|
30
|
+
const fetcher = vi.fn()
|
|
31
|
+
.mockResolvedValueOnce(jsonResponse({ ok: true, data: { taskId: "t-99", status: "completed" } }));
|
|
32
|
+
|
|
33
|
+
// Act
|
|
34
|
+
await pollTask(fetcher, "t-99", { intervalMs: 1 });
|
|
35
|
+
|
|
36
|
+
// Assert
|
|
37
|
+
expect(fetcher).toHaveBeenCalledWith("GET", "/api/v1/tasks/t-99");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it("throws TASK_FAILED for failed tasks", async () => {
|
|
41
|
+
// Arrange
|
|
42
|
+
const fetcher = vi.fn()
|
|
43
|
+
.mockImplementation(async () => jsonResponse({
|
|
44
|
+
ok: true,
|
|
45
|
+
data: { taskId: "t-1", status: "failed", error: "out of memory" },
|
|
46
|
+
}));
|
|
47
|
+
|
|
48
|
+
// Act
|
|
49
|
+
let error: BitbybitApiError | undefined;
|
|
50
|
+
try {
|
|
51
|
+
await pollTask(fetcher, "t-1", { intervalMs: 1 });
|
|
52
|
+
} catch (e) {
|
|
53
|
+
error = e as BitbybitApiError;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Assert
|
|
57
|
+
expect(error!.code).toBe("TASK_FAILED");
|
|
58
|
+
expect(error!.message).toContain("out of memory");
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it("throws TASK_CANCELLED for cancelled tasks", async () => {
|
|
62
|
+
// Arrange
|
|
63
|
+
const fetcher = vi.fn()
|
|
64
|
+
.mockImplementation(async () => jsonResponse({
|
|
65
|
+
ok: true,
|
|
66
|
+
data: { taskId: "t-1", status: "cancelled" },
|
|
67
|
+
}));
|
|
68
|
+
|
|
69
|
+
// Act
|
|
70
|
+
let error: BitbybitApiError | undefined;
|
|
71
|
+
try {
|
|
72
|
+
await pollTask(fetcher, "t-1", { intervalMs: 1 });
|
|
73
|
+
} catch (e) {
|
|
74
|
+
error = e as BitbybitApiError;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Assert
|
|
78
|
+
expect(error!.code).toBe("TASK_CANCELLED");
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it("throws TASK_EXPIRED for expired tasks", async () => {
|
|
82
|
+
// Arrange
|
|
83
|
+
const fetcher = vi.fn()
|
|
84
|
+
.mockImplementation(async () => jsonResponse({
|
|
85
|
+
ok: true,
|
|
86
|
+
data: { taskId: "t-1", status: "expired" },
|
|
87
|
+
}));
|
|
88
|
+
|
|
89
|
+
// Act
|
|
90
|
+
let error: BitbybitApiError | undefined;
|
|
91
|
+
try {
|
|
92
|
+
await pollTask(fetcher, "t-1", { intervalMs: 1 });
|
|
93
|
+
} catch (e) {
|
|
94
|
+
error = e as BitbybitApiError;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Assert
|
|
98
|
+
expect(error!.code).toBe("TASK_EXPIRED");
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it("throws POLL_TIMEOUT when maxAttempts exceeded", async () => {
|
|
102
|
+
// Arrange
|
|
103
|
+
const fetcher = vi.fn()
|
|
104
|
+
.mockImplementation(async () => jsonResponse({
|
|
105
|
+
ok: true,
|
|
106
|
+
data: { taskId: "t-1", status: "processing" },
|
|
107
|
+
}));
|
|
108
|
+
|
|
109
|
+
// Act
|
|
110
|
+
let error: BitbybitApiError | undefined;
|
|
111
|
+
try {
|
|
112
|
+
await pollTask(fetcher, "t-1", { intervalMs: 1, maxAttempts: 2 });
|
|
113
|
+
} catch (e) {
|
|
114
|
+
error = e as BitbybitApiError;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Assert
|
|
118
|
+
expect(error!.code).toBe("POLL_TIMEOUT");
|
|
119
|
+
expect(error!.message).toContain("t-1");
|
|
120
|
+
expect(fetcher).toHaveBeenCalledTimes(2);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it("throws BitbybitApiError when API returns error envelope", async () => {
|
|
124
|
+
// Arrange
|
|
125
|
+
const fetcher = vi.fn()
|
|
126
|
+
.mockImplementation(async () => jsonResponse(
|
|
127
|
+
{ ok: false, error: { code: "UNAUTHORIZED", message: "bad key" } },
|
|
128
|
+
401,
|
|
129
|
+
));
|
|
130
|
+
|
|
131
|
+
// Act
|
|
132
|
+
let error: BitbybitApiError | undefined;
|
|
133
|
+
try {
|
|
134
|
+
await pollTask(fetcher, "t-1", { intervalMs: 1 });
|
|
135
|
+
} catch (e) {
|
|
136
|
+
error = e as BitbybitApiError;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Assert
|
|
140
|
+
expect(error!.code).toBe("UNAUTHORIZED");
|
|
141
|
+
expect(error!.statusCode).toBe(401);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("calls onProgress callback after each poll", async () => {
|
|
145
|
+
// Arrange
|
|
146
|
+
const onProgress = vi.fn();
|
|
147
|
+
const fetcher = vi.fn()
|
|
148
|
+
.mockResolvedValueOnce(jsonResponse({ ok: true, data: { taskId: "t-1", status: "queued" } }))
|
|
149
|
+
.mockResolvedValueOnce(jsonResponse({ ok: true, data: { taskId: "t-1", status: "processing" } }))
|
|
150
|
+
.mockResolvedValueOnce(jsonResponse({ ok: true, data: { taskId: "t-1", status: "completed" } }));
|
|
151
|
+
|
|
152
|
+
// Act
|
|
153
|
+
await pollTask(fetcher, "t-1", { intervalMs: 1, onProgress });
|
|
154
|
+
|
|
155
|
+
// Assert
|
|
156
|
+
expect(onProgress).toHaveBeenCalledTimes(3);
|
|
157
|
+
expect(onProgress).toHaveBeenNthCalledWith(1, { taskId: "t-1", status: "queued" });
|
|
158
|
+
expect(onProgress).toHaveBeenNthCalledWith(2, { taskId: "t-1", status: "processing" });
|
|
159
|
+
expect(onProgress).toHaveBeenNthCalledWith(3, { taskId: "t-1", status: "completed" });
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it("throws POLL_ABORTED when AbortSignal is aborted", async () => {
|
|
163
|
+
// Arrange
|
|
164
|
+
const controller = new AbortController();
|
|
165
|
+
controller.abort();
|
|
166
|
+
const fetcher = vi.fn();
|
|
167
|
+
|
|
168
|
+
// Act
|
|
169
|
+
let error: BitbybitApiError | undefined;
|
|
170
|
+
try {
|
|
171
|
+
await pollTask(fetcher, "t-1", { intervalMs: 1, signal: controller.signal });
|
|
172
|
+
} catch (e) {
|
|
173
|
+
error = e as BitbybitApiError;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Assert
|
|
177
|
+
expect(error!.code).toBe("POLL_ABORTED");
|
|
178
|
+
expect(fetcher).not.toHaveBeenCalled();
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
describe("defaults", () => {
|
|
182
|
+
it("gives up before the first check when no attempts are allowed", async () => {
|
|
183
|
+
const calls: string[] = [];
|
|
184
|
+
const fetcher = (_method: string, path: string): Promise<Response> => {
|
|
185
|
+
calls.push(path);
|
|
186
|
+
return Promise.resolve(new Response("{}"));
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
// Act & Assert
|
|
190
|
+
await expect(pollTask(fetcher, "t-1", { maxAttempts: 0 })).rejects.toThrow("did not complete within 0 polls");
|
|
191
|
+
expect(calls).toHaveLength(0);
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
});
|
package/src/polling.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { TaskDetail, ApiResponse } from "./types/index.js";
|
|
2
|
+
import { BitbybitApiError } from "./errors.js";
|
|
3
|
+
|
|
4
|
+
export interface PollOptions {
|
|
5
|
+
/** Milliseconds between status checks. Default: 2 000. */
|
|
6
|
+
intervalMs?: number;
|
|
7
|
+
/** Maximum number of poll attempts before giving up. Default: 120 (≈ 4 min at 2 s). */
|
|
8
|
+
maxAttempts?: number;
|
|
9
|
+
/** Called after every status check so callers can report progress. */
|
|
10
|
+
onProgress?: (task: TaskDetail) => void;
|
|
11
|
+
/** AbortSignal to cancel polling early. */
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const DEFAULT_INTERVAL_MS = 2_000;
|
|
16
|
+
const DEFAULT_MAX_ATTEMPTS = 120;
|
|
17
|
+
|
|
18
|
+
const TERMINAL_STATUSES = new Set(["completed", "failed", "cancelled", "expired"]);
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Polls `GET /api/v1/tasks/:id` until the task reaches a terminal status.
|
|
22
|
+
*
|
|
23
|
+
* @returns The final `TaskDetail` once completed (or throws on failure / timeout).
|
|
24
|
+
*/
|
|
25
|
+
export async function pollTask(
|
|
26
|
+
fetcher: (method: string, path: string) => Promise<Response>,
|
|
27
|
+
taskId: string,
|
|
28
|
+
opts: PollOptions = {},
|
|
29
|
+
): Promise<TaskDetail> {
|
|
30
|
+
const interval = opts.intervalMs ?? DEFAULT_INTERVAL_MS;
|
|
31
|
+
const maxAttempts = opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
32
|
+
|
|
33
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
34
|
+
if (opts.signal?.aborted) {
|
|
35
|
+
throw new BitbybitApiError({
|
|
36
|
+
code: "POLL_ABORTED",
|
|
37
|
+
message: "Task polling was aborted",
|
|
38
|
+
statusCode: 0,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
await sleep(interval);
|
|
43
|
+
|
|
44
|
+
const res = await fetcher("GET", `/api/v1/tasks/${taskId}`);
|
|
45
|
+
const body: ApiResponse<TaskDetail> = await res.json() as ApiResponse<TaskDetail>;
|
|
46
|
+
|
|
47
|
+
if (!body.ok) {
|
|
48
|
+
throw new BitbybitApiError({
|
|
49
|
+
code: body.error.code,
|
|
50
|
+
message: body.error.message,
|
|
51
|
+
statusCode: res.status,
|
|
52
|
+
details: body.error.details,
|
|
53
|
+
requestId: body.error.requestId,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const task = body.data;
|
|
58
|
+
opts.onProgress?.(task);
|
|
59
|
+
|
|
60
|
+
if (TERMINAL_STATUSES.has(task.status)) {
|
|
61
|
+
if (task.status === "completed") {
|
|
62
|
+
return task;
|
|
63
|
+
}
|
|
64
|
+
throw new BitbybitApiError({
|
|
65
|
+
code: `TASK_${task.status.toUpperCase()}`,
|
|
66
|
+
message: `Task ${task.status}: ${task.error ?? "no details"}`,
|
|
67
|
+
statusCode: 200,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
throw new BitbybitApiError({
|
|
73
|
+
code: "POLL_TIMEOUT",
|
|
74
|
+
message: `Task ${taskId} did not complete within ${maxAttempts} polls`,
|
|
75
|
+
statusCode: 0,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function sleep(ms: number): Promise<void> {
|
|
80
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
81
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
OutputOptions,
|
|
3
|
+
TaskDetail,
|
|
4
|
+
SubTaskSummary,
|
|
5
|
+
} from "./schema-exports.js";
|
|
6
|
+
|
|
7
|
+
/** Generic success envelope with typed data. */
|
|
8
|
+
export interface ApiSuccess<T = unknown> {
|
|
9
|
+
readonly ok: true;
|
|
10
|
+
readonly data: T;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Generic error envelope. */
|
|
14
|
+
export interface ApiError {
|
|
15
|
+
readonly ok: false;
|
|
16
|
+
readonly error: {
|
|
17
|
+
readonly code: string;
|
|
18
|
+
readonly message: string;
|
|
19
|
+
readonly details?: unknown;
|
|
20
|
+
readonly requestId?: string;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Discriminated union of success / error. */
|
|
25
|
+
export type ApiResponse<T = unknown> = ApiSuccess<T> | ApiError;
|
|
26
|
+
|
|
27
|
+
/** Model submission with typed params. */
|
|
28
|
+
export interface ModelSubmission<TParams = Record<string, unknown>> {
|
|
29
|
+
readonly params?: TParams;
|
|
30
|
+
readonly outputs: OutputOptions;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Batch model submission (multiple param sets, one output config). */
|
|
34
|
+
export interface BatchModelSubmission<TParams = Record<string, unknown>> {
|
|
35
|
+
readonly items: readonly { readonly params?: TParams }[];
|
|
36
|
+
readonly outputs: OutputOptions;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Compound task detail (extends TaskDetail with sub-tasks). */
|
|
40
|
+
export interface CompoundTaskDetail extends TaskDetail {
|
|
41
|
+
readonly subTasks: readonly SubTaskSummary[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Available download result formats (not an enum in the spec). */
|
|
45
|
+
export type ResultFormat = "glb" | "step" | "stpz" | "metadata" | "decomposed-mesh";
|