@bitbybit-dev/cad-cloud-sdk 1.1.1 → 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 +54 -46
- 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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// ---------------------------------------------------------------------------
|
|
2
2
|
// AUTO-GENERATED by generate-pipeline-types.ts — do not edit manually.
|
|
3
|
-
// Generated from operation-catalog.json v1.
|
|
3
|
+
// Generated from operation-catalog.json v1.2.0-rc.0
|
|
4
4
|
// ---------------------------------------------------------------------------
|
|
5
5
|
/**
|
|
6
6
|
* Create a type-safe pipeline step with autocomplete for operation paths and params.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipeline-operations.js","sourceRoot":"","sources":["../../src/types/pipeline-operations.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,uEAAuE;AACvE,
|
|
1
|
+
{"version":3,"file":"pipeline-operations.js","sourceRoot":"","sources":["../../src/types/pipeline-operations.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,uEAAuE;AACvE,oDAAoD;AACpD,8EAA8E;AA6xR9E;;;;;;GAMG;AACH,MAAM,UAAU,IAAI,CAChB,SAAY,EACZ,MAA0B,EAC1B,IAA2B;IAE3B,MAAM,CAAC,GAA4B,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC;IACzD,IAAI,IAAI,EAAE,MAAM;QAAE,CAAC,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC;IACrC,OAAO,CAAiB,CAAC;AAC7B,CAAC"}
|
package/dist/unwrap.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unwrap.d.ts","sourceRoot":"","sources":["../src/unwrap.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"unwrap.d.ts","sourceRoot":"","sources":["../src/unwrap.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,wBAAsB,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,CAAC,CAAC,CAYzD"}
|
package/dist/unwrap.js
CHANGED
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
// ---------------------------------------------------------------------------
|
|
2
|
-
// Shared response unwrapper — extracts data from API envelope or throws
|
|
3
|
-
// ---------------------------------------------------------------------------
|
|
4
1
|
import { BitbybitApiError } from "./errors.js";
|
|
5
2
|
/**
|
|
6
3
|
* Unwrap a standard `{ ok, data } | { ok, error }` API response envelope.
|
package/dist/unwrap.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unwrap.js","sourceRoot":"","sources":["../src/unwrap.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"unwrap.js","sourceRoot":"","sources":["../src/unwrap.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,MAAM,CAAI,GAAa;IACzC,MAAM,IAAI,GAAmB,MAAM,GAAG,CAAC,IAAI,EAAoB,CAAC;IAChE,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC;QACX,MAAM,IAAI,gBAAgB,CAAC;YACvB,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI;YACrB,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO;YAC3B,UAAU,EAAE,GAAG,CAAC,MAAM;YACtB,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO;YAC3B,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS;SAClC,CAAC,CAAC;IACP,CAAC;IACD,OAAO,IAAI,CAAC,IAAI,CAAC;AACrB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.d.ts","sourceRoot":"","sources":["../../src/validation/validator.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"validator.d.ts","sourceRoot":"","sources":["../../src/validation/validator.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAU,MAAM,uBAAuB,CAAC;AAGhE,mEAAmE;AACnE,qBAAa,uBAAwB,SAAQ,KAAK;IAC9C,QAAQ,CAAC,MAAM,EAAE,UAAU,EAAE,CAAC;gBAElB,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE;CAQvD;AAsBD;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,CAS3E;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAEzE"}
|
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
// ---------------------------------------------------------------------------
|
|
2
|
-
// Client-side request validation using JSON Schema (derived from OpenAPI spec).
|
|
3
|
-
// Uses @cfworker/json-schema
|
|
4
|
-
// ---------------------------------------------------------------------------
|
|
5
1
|
import { Validator } from "@cfworker/json-schema";
|
|
6
2
|
import { schemaBundle } from "./request-schemas.js";
|
|
7
3
|
/** Structured validation error thrown before a request is sent. */
|
|
@@ -16,7 +12,6 @@ export class BitbybitValidationError extends Error {
|
|
|
16
12
|
this.errors = errors;
|
|
17
13
|
}
|
|
18
14
|
}
|
|
19
|
-
// Cache validators per schema name (lazy, created on first use)
|
|
20
15
|
const validators = new Map();
|
|
21
16
|
function getValidator(schemaName) {
|
|
22
17
|
const cached = validators.get(schemaName);
|
|
@@ -25,7 +20,6 @@ function getValidator(schemaName) {
|
|
|
25
20
|
const def = schemaBundle.$defs[schemaName];
|
|
26
21
|
if (!def)
|
|
27
22
|
return undefined;
|
|
28
|
-
// Build a root schema that references the target $def and carries all $defs
|
|
29
23
|
const rootSchema = {
|
|
30
24
|
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
31
25
|
$ref: `#/$defs/${schemaName}`,
|
|
@@ -42,8 +36,6 @@ function getValidator(schemaName) {
|
|
|
42
36
|
export function validateRequestBody(schemaName, data) {
|
|
43
37
|
const validator = getValidator(schemaName);
|
|
44
38
|
if (!validator) {
|
|
45
|
-
// Unknown schema — skip validation silently (e.g. new model added
|
|
46
|
-
// before SDK is regenerated). Server will still validate.
|
|
47
39
|
return;
|
|
48
40
|
}
|
|
49
41
|
const result = validator.validate(data);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.js","sourceRoot":"","sources":["../../src/validation/validator.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"validator.js","sourceRoot":"","sources":["../../src/validation/validator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAElD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAEpD,mEAAmE;AACnE,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IACrC,MAAM,CAAe;IAE9B,YAAY,UAAkB,EAAE,MAAoB;QAChD,MAAM,OAAO,GAAG,MAAM;aACjB,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,gBAAgB,IAAI,CAAC,CAAC,KAAK,EAAE,CAAC;aAC9C,IAAI,CAAC,IAAI,CAAC,CAAC;QAChB,KAAK,CAAC,yBAAyB,UAAU,KAAK,OAAO,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;QACtC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AAED,MAAM,UAAU,GAAG,IAAI,GAAG,EAAqB,CAAC;AAEhD,SAAS,YAAY,CAAC,UAAkB;IACpC,MAAM,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC1C,IAAI,MAAM;QAAE,OAAO,MAAM,CAAC;IAE1B,MAAM,GAAG,GAAI,YAAY,CAAC,KAA2C,CAAC,UAAU,CAAC,CAAC;IAClF,IAAI,CAAC,GAAG;QAAE,OAAO,SAAS,CAAC;IAE3B,MAAM,UAAU,GAAW;QACvB,OAAO,EAAE,8CAA8C;QACvD,IAAI,EAAE,WAAW,UAAU,EAAE;QAC7B,KAAK,EAAE,YAAY,CAAC,KAAK;KAC5B,CAAC;IAEF,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,UAAU,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;IAC9D,UAAU,CAAC,GAAG,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;IACtC,OAAO,SAAS,CAAC;AACrB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,UAAkB,EAAE,IAAa;IACjE,MAAM,SAAS,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC;IAC3C,IAAI,CAAC,SAAS,EAAE,CAAC;QACb,OAAO;IACX,CAAC;IACD,MAAM,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACxC,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,uBAAuB,CAAC,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACjE,CAAC;AACL,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,WAAmB;IACjD,OAAQ,YAAY,CAAC,SAAoC,CAAC,WAAW,CAAC,CAAC;AAC3E,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bitbybit-dev/cad-cloud-sdk",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Type-safe SDK for the Bitbybit CAD Cloud API
|
|
3
|
+
"version": "1.2.0-rc.0",
|
|
4
|
+
"description": "Type-safe SDK for the Bitbybit CAD Cloud API \u2014 parametric models, CAD operations, file conversion, and task management",
|
|
5
5
|
"author": "Bit By Bit Developers",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"type": "module",
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
},
|
|
24
24
|
"files": [
|
|
25
25
|
"dist",
|
|
26
|
+
"src",
|
|
26
27
|
"LICENSE",
|
|
27
28
|
"README.md"
|
|
28
29
|
],
|
|
@@ -31,9 +32,11 @@
|
|
|
31
32
|
"clean": "rm -rf dist",
|
|
32
33
|
"typecheck": "tsc --noEmit",
|
|
33
34
|
"test": "vitest run",
|
|
35
|
+
"test:coverage": "vitest run --coverage",
|
|
34
36
|
"test:watch": "vitest",
|
|
35
37
|
"coverage": "vitest run --coverage",
|
|
36
|
-
"prepublishOnly": "npm run clean && npm run build"
|
|
38
|
+
"prepublishOnly": "npm run clean && npm run build",
|
|
39
|
+
"typecheck:tests": "tsc -p tsconfig.json --noEmit --pretty false"
|
|
37
40
|
},
|
|
38
41
|
"engines": {
|
|
39
42
|
"node": ">=18.0.0"
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Creates a mock Response with a JSON body matching the API envelope.
|
|
3
|
+
*/
|
|
4
|
+
export function okResponse<T>(data: T, status = 200): Response {
|
|
5
|
+
return new Response(JSON.stringify({ ok: true, data }), {
|
|
6
|
+
status,
|
|
7
|
+
headers: { "Content-Type": "application/json" },
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function errorResponse(
|
|
12
|
+
code: string,
|
|
13
|
+
message: string,
|
|
14
|
+
status = 400,
|
|
15
|
+
details?: unknown,
|
|
16
|
+
requestId?: string,
|
|
17
|
+
): Response {
|
|
18
|
+
return new Response(
|
|
19
|
+
JSON.stringify({
|
|
20
|
+
ok: false,
|
|
21
|
+
error: { code, message, details, requestId },
|
|
22
|
+
}),
|
|
23
|
+
{ status, headers: { "Content-Type": "application/json" } },
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Creates a fetcher function stub that returns the given responses in order.
|
|
29
|
+
*/
|
|
30
|
+
export function mockFetcher(
|
|
31
|
+
...responses: Response[]
|
|
32
|
+
): (method: string, path: string, body?: unknown) => Promise<Response> {
|
|
33
|
+
const queue = [...responses];
|
|
34
|
+
return async (_method: string, _path: string, _body?: unknown) => {
|
|
35
|
+
const res = queue.shift();
|
|
36
|
+
if (!res) throw new Error("mockFetcher: no more responses");
|
|
37
|
+
return res;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Creates a fetcher that tracks calls and returns responses in order.
|
|
43
|
+
*/
|
|
44
|
+
export function spyFetcher(...responses: Response[]) {
|
|
45
|
+
const calls: { method: string; path: string; body?: unknown }[] = [];
|
|
46
|
+
const queue = [...responses];
|
|
47
|
+
const fn = async (method: string, path: string, body?: unknown) => {
|
|
48
|
+
calls.push({ method, path, body });
|
|
49
|
+
const res = queue.shift();
|
|
50
|
+
if (!res) throw new Error("spyFetcher: no more responses");
|
|
51
|
+
return res;
|
|
52
|
+
};
|
|
53
|
+
return { fn, calls };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* A task status response, as GET /api/v1/tasks/:id answers it.
|
|
58
|
+
*/
|
|
59
|
+
export function taskResponse(taskId: string, status: string, extra: Record<string, unknown> = {}): Response {
|
|
60
|
+
return okResponse({ taskId, status, ...extra });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The downloads response, as GET /api/v1/tasks/:id/results answers it.
|
|
65
|
+
*/
|
|
66
|
+
export function downloadsResponse(...downloads: { format: string; url: string }[]): Response {
|
|
67
|
+
return okResponse({ downloads });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Poll options that do not wait between attempts, so a suite runs at full speed. */
|
|
71
|
+
export const NO_WAIT = { intervalMs: 0 };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { okResponse, errorResponse, mockFetcher, spyFetcher } from "./helpers.js";
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
2
|
+
import { BitbybitClient } from "./client.js";
|
|
3
|
+
|
|
4
|
+
const fetchMock = vi.fn();
|
|
5
|
+
|
|
6
|
+
describe("BitbybitClient", () => {
|
|
7
|
+
beforeEach(() => {
|
|
8
|
+
fetchMock.mockReset();
|
|
9
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
afterEach(() => {
|
|
13
|
+
vi.restoreAllMocks();
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
describe("constructor", () => {
|
|
17
|
+
it("throws when apiKey is empty", () => {
|
|
18
|
+
// Act
|
|
19
|
+
const act = () => new BitbybitClient({ apiKey: "" });
|
|
20
|
+
|
|
21
|
+
// Assert
|
|
22
|
+
expect(act).toThrow("BitbybitClient requires an apiKey");
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it("creates endpoint instances", () => {
|
|
26
|
+
// Act
|
|
27
|
+
const client = new BitbybitClient({ apiKey: "bbk_test" });
|
|
28
|
+
|
|
29
|
+
// Assert
|
|
30
|
+
expect(client.models).not.toBe(undefined);
|
|
31
|
+
expect(client.tasks).not.toBe(undefined);
|
|
32
|
+
expect(client.cad).not.toBe(undefined);
|
|
33
|
+
expect(client.convert).not.toBe(undefined);
|
|
34
|
+
expect(client.files).not.toBe(undefined);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("strips trailing slashes from baseUrl", async () => {
|
|
38
|
+
// Arrange
|
|
39
|
+
const client = new BitbybitClient({ apiKey: "bbk_test", baseUrl: "https://api.example.com//" });
|
|
40
|
+
fetchMock.mockResolvedValueOnce(
|
|
41
|
+
new Response(JSON.stringify({ ok: true, data: [] }), { status: 200 }),
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
// Act
|
|
45
|
+
await client.request("GET", "/api/v1/models");
|
|
46
|
+
|
|
47
|
+
// Assert
|
|
48
|
+
expect(fetchMock).toHaveBeenCalledWith(
|
|
49
|
+
"https://api.example.com/api/v1/models",
|
|
50
|
+
expect.objectContaining({ method: "GET" }),
|
|
51
|
+
);
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
describe("request", () => {
|
|
56
|
+
it("sends x-api-key on every request and Content-Type only with a body", async () => {
|
|
57
|
+
// Arrange
|
|
58
|
+
const client = new BitbybitClient({ apiKey: "bbk_mykey" });
|
|
59
|
+
fetchMock.mockResolvedValue(new Response("{}", { status: 200 }));
|
|
60
|
+
|
|
61
|
+
// Act
|
|
62
|
+
await client.request("GET", "/api/v1/tasks");
|
|
63
|
+
await client.request("POST", "/api/v1/tasks", { kind: "probe" });
|
|
64
|
+
|
|
65
|
+
// Assert
|
|
66
|
+
const [getArgs, postArgs] = fetchMock.mock.calls;
|
|
67
|
+
expect(getArgs![1].headers["x-api-key"]).toBe("bbk_mykey");
|
|
68
|
+
expect(getArgs![1].headers["Content-Type"]).toBeUndefined();
|
|
69
|
+
expect(getArgs![1].body).toBeUndefined();
|
|
70
|
+
expect(postArgs![1].headers["x-api-key"]).toBe("bbk_mykey");
|
|
71
|
+
expect(postArgs![1].headers["Content-Type"]).toBe("application/json");
|
|
72
|
+
expect(postArgs![1].body).toBe(JSON.stringify({ kind: "probe" }));
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it("sends JSON body for POST requests", async () => {
|
|
76
|
+
// Arrange
|
|
77
|
+
const client = new BitbybitClient({ apiKey: "bbk_test", validate: false });
|
|
78
|
+
fetchMock.mockResolvedValueOnce(new Response("{}", { status: 200 }));
|
|
79
|
+
const body = { operation: "test", params: {} };
|
|
80
|
+
|
|
81
|
+
// Act
|
|
82
|
+
await client.request("POST", "/api/v1/cad/execute", body);
|
|
83
|
+
|
|
84
|
+
// Assert
|
|
85
|
+
expect(fetchMock.mock.calls[0]![1].body).toBe(JSON.stringify(body));
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("does not send body for GET requests", async () => {
|
|
89
|
+
// Arrange
|
|
90
|
+
const client = new BitbybitClient({ apiKey: "bbk_test" });
|
|
91
|
+
fetchMock.mockResolvedValueOnce(new Response("{}", { status: 200 }));
|
|
92
|
+
|
|
93
|
+
// Act
|
|
94
|
+
await client.request("GET", "/api/v1/tasks");
|
|
95
|
+
|
|
96
|
+
// Assert
|
|
97
|
+
expect(fetchMock.mock.calls[0]![1].body).toBe(undefined);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("uses default base URL when none provided", async () => {
|
|
101
|
+
// Arrange
|
|
102
|
+
const client = new BitbybitClient({ apiKey: "bbk_test" });
|
|
103
|
+
fetchMock.mockResolvedValueOnce(new Response("{}", { status: 200 }));
|
|
104
|
+
|
|
105
|
+
// Act
|
|
106
|
+
await client.request("GET", "/api/v1/tasks");
|
|
107
|
+
|
|
108
|
+
// Assert
|
|
109
|
+
expect(fetchMock.mock.calls[0]![0]).toBe("https://api.bitbybit.dev/api/v1/tasks");
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("skips validation when validate is false", async () => {
|
|
113
|
+
// Arrange
|
|
114
|
+
const client = new BitbybitClient({ apiKey: "bbk_test", validate: false });
|
|
115
|
+
fetchMock.mockResolvedValueOnce(new Response("{}", { status: 200 }));
|
|
116
|
+
const invalidBody = {};
|
|
117
|
+
|
|
118
|
+
await expect(client.request("POST", "/api/v1/cad/execute", invalidBody)).resolves.toBeInstanceOf(Response);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it("skips validation for GET requests even when validate is true", async () => {
|
|
122
|
+
// Arrange
|
|
123
|
+
const client = new BitbybitClient({ apiKey: "bbk_test", validate: true });
|
|
124
|
+
fetchMock.mockResolvedValueOnce(new Response("{}", { status: 200 }));
|
|
125
|
+
|
|
126
|
+
await expect(client.request("GET", "/api/v1/tasks", {})).resolves.toBeInstanceOf(Response);
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
describe("health", () => {
|
|
131
|
+
it("fetches from /health endpoint", async () => {
|
|
132
|
+
// Arrange
|
|
133
|
+
const healthData = { ok: true, instance: "worker-1", timestamp: "2024-01-01T00:00:00Z" };
|
|
134
|
+
const client = new BitbybitClient({ apiKey: "bbk_test" });
|
|
135
|
+
fetchMock.mockResolvedValueOnce(
|
|
136
|
+
new Response(JSON.stringify(healthData), { status: 200 }),
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
// Act
|
|
140
|
+
const result = await client.health();
|
|
141
|
+
|
|
142
|
+
// Assert
|
|
143
|
+
expect(fetchMock.mock.calls[0]![0]).toBe("https://api.bitbybit.dev/health");
|
|
144
|
+
expect(result).toStrictEqual(healthData);
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
describe("request validation by path", () => {
|
|
149
|
+
it("refuses a body the endpoint's schema rejects", async () => {
|
|
150
|
+
// Arrange
|
|
151
|
+
const client = new BitbybitClient({ apiKey: "bbk_test" });
|
|
152
|
+
fetchMock.mockResolvedValue(new Response("{}", { status: 200 }));
|
|
153
|
+
|
|
154
|
+
// Act & Assert
|
|
155
|
+
await expect(client.request("POST", "/api/v1/cad/execute", {})).rejects.toThrow();
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it("checks a model with a schema of its own against that schema", async () => {
|
|
159
|
+
// Arrange
|
|
160
|
+
const client = new BitbybitClient({ apiKey: "bbk_test" });
|
|
161
|
+
fetchMock.mockResolvedValue(new Response("{}", { status: 200 }));
|
|
162
|
+
|
|
163
|
+
// Act & Assert
|
|
164
|
+
await expect(client.request("POST", "/api/v1/models/dragon-cup", { params: { height: "tall" } })).rejects.toThrow();
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
it("checks a model with no schema of its own against the generic one", async () => {
|
|
168
|
+
// Arrange
|
|
169
|
+
const client = new BitbybitClient({ apiKey: "bbk_test" });
|
|
170
|
+
fetchMock.mockResolvedValue(new Response("{}", { status: 200 }));
|
|
171
|
+
|
|
172
|
+
// Act & Assert
|
|
173
|
+
await expect(client.request("POST", "/api/v1/models/no-such-model", { outputs: 7 })).rejects.toThrow();
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it("checks a batch submission against the batch schema", async () => {
|
|
177
|
+
// Arrange
|
|
178
|
+
const client = new BitbybitClient({ apiKey: "bbk_test" });
|
|
179
|
+
fetchMock.mockResolvedValue(new Response("{}", { status: 200 }));
|
|
180
|
+
|
|
181
|
+
// Act & Assert
|
|
182
|
+
await expect(client.request("POST", "/api/v1/models/dragon-cup/batch", { variations: "many" })).rejects.toThrow();
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it("sends a body on a path no schema covers without checking it", async () => {
|
|
186
|
+
// Arrange
|
|
187
|
+
const client = new BitbybitClient({ apiKey: "bbk_test" });
|
|
188
|
+
fetchMock.mockResolvedValue(new Response("{}", { status: 200 }));
|
|
189
|
+
|
|
190
|
+
// Act & Assert
|
|
191
|
+
await expect(client.request("POST", "/api/v1/something/new", { anything: true })).resolves.toBeInstanceOf(Response);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it("trims a trailing slash from the base url it was given", async () => {
|
|
195
|
+
// Arrange
|
|
196
|
+
const client = new BitbybitClient({ apiKey: "bbk_test", baseUrl: "https://staging.example.test/" });
|
|
197
|
+
fetchMock.mockResolvedValueOnce(new Response("{}", { status: 200 }));
|
|
198
|
+
|
|
199
|
+
// Act
|
|
200
|
+
await client.request("GET", "/api/v1/tasks");
|
|
201
|
+
|
|
202
|
+
// Assert
|
|
203
|
+
expect(fetchMock.mock.calls[0]![0]).toBe("https://staging.example.test/api/v1/tasks");
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
});
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { ModelsEndpoint } from "./endpoints/models.js";
|
|
2
|
+
import { TasksEndpoint } from "./endpoints/tasks.js";
|
|
3
|
+
import { CadEndpoint } from "./endpoints/cad.js";
|
|
4
|
+
import { ConvertEndpoint } from "./endpoints/convert.js";
|
|
5
|
+
import { FilesEndpoint } from "./endpoints/files.js";
|
|
6
|
+
import { validateRequestBody, getEndpointSchema } from "./validation/index.js";
|
|
7
|
+
|
|
8
|
+
const DEFAULT_BASE_URL = "https://api.bitbybit.dev";
|
|
9
|
+
|
|
10
|
+
export interface BitbybitClientOptions {
|
|
11
|
+
/** Your Bitbybit API key (starts with `bbk_`). */
|
|
12
|
+
apiKey: string;
|
|
13
|
+
/**
|
|
14
|
+
* Base URL of the Bitbybit API.
|
|
15
|
+
* @default "https://api.bitbybit.dev"
|
|
16
|
+
*/
|
|
17
|
+
baseUrl?: string;
|
|
18
|
+
/**
|
|
19
|
+
* Validate request bodies against JSON Schema before sending.
|
|
20
|
+
* Catches parameter errors early with clear messages.
|
|
21
|
+
* @default true
|
|
22
|
+
*/
|
|
23
|
+
validate?: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Type-safe client for the Bitbybit CAD Cloud API.
|
|
28
|
+
*
|
|
29
|
+
* **Server-side only** — never expose your API key in frontend code.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* import { BitbybitClient } from "@bitbybit-dev/cad-cloud-sdk";
|
|
34
|
+
*
|
|
35
|
+
* const client = new BitbybitClient({ apiKey: process.env.BITBYBIT_API_KEY! });
|
|
36
|
+
*
|
|
37
|
+
* // Generate a dragon cup and get a GLB download URL
|
|
38
|
+
* const { downloadUrl } = await client.models.run("dragon-cup", {
|
|
39
|
+
* params: { height: 10, radiusBottom: 5 },
|
|
40
|
+
* outputs: { formats: ["gltf"] },
|
|
41
|
+
* });
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export class BitbybitClient {
|
|
45
|
+
/** Parametric model generation. */
|
|
46
|
+
readonly models: ModelsEndpoint;
|
|
47
|
+
|
|
48
|
+
/** Task status, polling, and result retrieval. */
|
|
49
|
+
readonly tasks: TasksEndpoint;
|
|
50
|
+
|
|
51
|
+
/** Raw CAD operations (execute, pipeline, compound). */
|
|
52
|
+
readonly cad: CadEndpoint;
|
|
53
|
+
|
|
54
|
+
/** STEP → glTF conversion. */
|
|
55
|
+
readonly convert: ConvertEndpoint;
|
|
56
|
+
|
|
57
|
+
/** File upload and management. */
|
|
58
|
+
readonly files: FilesEndpoint;
|
|
59
|
+
|
|
60
|
+
private readonly baseUrl: string;
|
|
61
|
+
private readonly apiKey: string;
|
|
62
|
+
private readonly validate: boolean;
|
|
63
|
+
|
|
64
|
+
constructor(opts: BitbybitClientOptions) {
|
|
65
|
+
if (!opts.apiKey) {
|
|
66
|
+
throw new Error("BitbybitClient requires an apiKey");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
this.apiKey = opts.apiKey;
|
|
70
|
+
this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
71
|
+
this.validate = opts.validate !== false;
|
|
72
|
+
|
|
73
|
+
const fetcher = this.request.bind(this);
|
|
74
|
+
this.models = new ModelsEndpoint(fetcher);
|
|
75
|
+
this.tasks = new TasksEndpoint(fetcher);
|
|
76
|
+
this.cad = new CadEndpoint(fetcher);
|
|
77
|
+
this.convert = new ConvertEndpoint(fetcher);
|
|
78
|
+
this.files = new FilesEndpoint(fetcher);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Check API health. */
|
|
82
|
+
async health(): Promise<{ ok: boolean; instance: string; timestamp: string }> {
|
|
83
|
+
const res = await fetch(`${this.baseUrl}/health`);
|
|
84
|
+
return res.json() as Promise<{ ok: boolean; instance: string; timestamp: string }>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Low-level request method used by all endpoints.
|
|
89
|
+
* Can also be used directly for custom / future endpoints.
|
|
90
|
+
*/
|
|
91
|
+
async request(method: string, path: string, body?: unknown): Promise<Response> {
|
|
92
|
+
if (this.validate && body != null && method !== "GET") {
|
|
93
|
+
const endpointKey = pathToEndpointKey(path);
|
|
94
|
+
if (endpointKey) {
|
|
95
|
+
const schemaName = getEndpointSchema(endpointKey);
|
|
96
|
+
if (schemaName) {
|
|
97
|
+
validateRequestBody(schemaName, body);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const url = `${this.baseUrl}${path}`;
|
|
103
|
+
const headers: Record<string, string> = {
|
|
104
|
+
"x-api-key": this.apiKey,
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
let serializedBody: string | undefined;
|
|
108
|
+
if (body != null) {
|
|
109
|
+
headers["Content-Type"] = "application/json";
|
|
110
|
+
serializedBody = JSON.stringify(body);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const init: RequestInit = { method, headers };
|
|
114
|
+
if (serializedBody !== undefined) {
|
|
115
|
+
init.body = serializedBody;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const res = await fetch(url, init);
|
|
119
|
+
|
|
120
|
+
return res;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const STATIC_PATH_MAP: Record<string, string> = {
|
|
125
|
+
"/api/v1/cad/execute": "cad.execute",
|
|
126
|
+
"/api/v1/cad/pipeline": "cad.pipeline",
|
|
127
|
+
"/api/v1/cad/compound": "cad.compound",
|
|
128
|
+
"/api/v1/models/definitions": "models.definitions",
|
|
129
|
+
"/api/v1/convert/step-to-gltf": "convert.stepToGltf",
|
|
130
|
+
"/api/v1/convert/step-to-gltf-advanced": "convert.stepToGltfAdvanced",
|
|
131
|
+
"/api/v1/files/upload": "files.upload",
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const MODEL_PATH_RE = /^\/api\/v1\/models\/([a-z][a-z0-9-]*)$/;
|
|
135
|
+
const MODEL_BATCH_PATH_RE = /^\/api\/v1\/models\/([a-z][a-z0-9-]*)\/batch$/;
|
|
136
|
+
|
|
137
|
+
function pathToEndpointKey(path: string): string | undefined {
|
|
138
|
+
const staticKey = STATIC_PATH_MAP[path];
|
|
139
|
+
if (staticKey) return staticKey;
|
|
140
|
+
|
|
141
|
+
const batchMatch = MODEL_BATCH_PATH_RE.exec(path);
|
|
142
|
+
if (batchMatch) return "models.batchSubmit";
|
|
143
|
+
|
|
144
|
+
const modelMatch = MODEL_PATH_RE.exec(path);
|
|
145
|
+
if (modelMatch) {
|
|
146
|
+
const slug = modelMatch[1];
|
|
147
|
+
const perModel = `models.submit.${slug}`;
|
|
148
|
+
if (getEndpointSchema(perModel)) return perModel;
|
|
149
|
+
return "models.submit";
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return undefined;
|
|
153
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { CadEndpoint } from "./cad.js";
|
|
3
|
+
import { NO_WAIT, downloadsResponse, okResponse, spyFetcher, taskResponse } from "../__test__/helpers.js";
|
|
4
|
+
|
|
5
|
+
describe("CadEndpoint", () => {
|
|
6
|
+
describe("execute", () => {
|
|
7
|
+
it("sends POST to /api/v1/cad/execute and returns data", async () => {
|
|
8
|
+
// Arrange
|
|
9
|
+
const taskResult = { taskId: "t-1", status: "queued" };
|
|
10
|
+
const { fn, calls } = spyFetcher(okResponse(taskResult));
|
|
11
|
+
const cad = new CadEndpoint(fn);
|
|
12
|
+
const body = { operation: "occt.shapes.solid.createBox", params: { width: 10 } };
|
|
13
|
+
|
|
14
|
+
// Act
|
|
15
|
+
const result = await cad.execute(body);
|
|
16
|
+
|
|
17
|
+
// Assert
|
|
18
|
+
expect(calls[0]!.method).toBe("POST");
|
|
19
|
+
expect(calls[0]!.path).toBe("/api/v1/cad/execute");
|
|
20
|
+
expect(calls[0]!.body).toStrictEqual(body);
|
|
21
|
+
expect(result).toStrictEqual(taskResult);
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
describe("pipeline", () => {
|
|
26
|
+
it("sends POST to /api/v1/cad/pipeline and returns data", async () => {
|
|
27
|
+
// Arrange
|
|
28
|
+
const taskResult = { taskId: "t-2", status: "queued" };
|
|
29
|
+
const { fn, calls } = spyFetcher(okResponse(taskResult));
|
|
30
|
+
const cad = new CadEndpoint(fn);
|
|
31
|
+
const body = { steps: [{ operation: "test", params: {} }] };
|
|
32
|
+
|
|
33
|
+
// Act
|
|
34
|
+
const result = await cad.pipeline(body);
|
|
35
|
+
|
|
36
|
+
// Assert
|
|
37
|
+
expect(calls[0]!.method).toBe("POST");
|
|
38
|
+
expect(calls[0]!.path).toBe("/api/v1/cad/pipeline");
|
|
39
|
+
expect(result).toStrictEqual(taskResult);
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe("compound", () => {
|
|
44
|
+
it("sends POST to /api/v1/cad/compound and returns data", async () => {
|
|
45
|
+
// Arrange
|
|
46
|
+
const compoundResult = { taskId: "c-1", subTasks: [{ taskId: "s-1", index: 0 }] };
|
|
47
|
+
const { fn, calls } = spyFetcher(okResponse(compoundResult));
|
|
48
|
+
const cad = new CadEndpoint(fn);
|
|
49
|
+
|
|
50
|
+
// Act
|
|
51
|
+
const result = await cad.compound({ operations: [] } as never);
|
|
52
|
+
|
|
53
|
+
// Assert
|
|
54
|
+
expect(calls[0]!.method).toBe("POST");
|
|
55
|
+
expect(calls[0]!.path).toBe("/api/v1/cad/compound");
|
|
56
|
+
expect(result).toStrictEqual(compoundResult);
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
describe("executeAndPoll", () => {
|
|
61
|
+
it("submits, polls until the task completes, and returns its downloads", async () => {
|
|
62
|
+
// Arrange
|
|
63
|
+
const { fn, calls } = spyFetcher(
|
|
64
|
+
okResponse({ taskId: "t-1", status: "queued" }),
|
|
65
|
+
taskResponse("t-1", "completed"),
|
|
66
|
+
downloadsResponse({ format: "step", url: "https://example.test/part.step" }),
|
|
67
|
+
);
|
|
68
|
+
const cad = new CadEndpoint(fn);
|
|
69
|
+
|
|
70
|
+
// Act
|
|
71
|
+
const result = await cad.executeAndPoll({ operation: "box" }, NO_WAIT);
|
|
72
|
+
|
|
73
|
+
// Assert
|
|
74
|
+
expect(calls.map((call) => call.path)).toStrictEqual([
|
|
75
|
+
"/api/v1/cad/execute",
|
|
76
|
+
"/api/v1/tasks/t-1",
|
|
77
|
+
"/api/v1/tasks/t-1/results",
|
|
78
|
+
]);
|
|
79
|
+
expect(result).toStrictEqual({ taskId: "t-1", downloads: [{ format: "step", url: "https://example.test/part.step" }] });
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
describe("pipelineAndPoll", () => {
|
|
84
|
+
it("submits, polls until the task completes, and returns its downloads", async () => {
|
|
85
|
+
// Arrange
|
|
86
|
+
const { fn, calls } = spyFetcher(
|
|
87
|
+
okResponse({ taskId: "t-2", status: "queued" }),
|
|
88
|
+
taskResponse("t-2", "completed"),
|
|
89
|
+
downloadsResponse({ format: "glb", url: "https://example.test/part.glb" }),
|
|
90
|
+
);
|
|
91
|
+
const cad = new CadEndpoint(fn);
|
|
92
|
+
|
|
93
|
+
// Act
|
|
94
|
+
const result = await cad.pipelineAndPoll({ steps: [] }, NO_WAIT);
|
|
95
|
+
|
|
96
|
+
// Assert
|
|
97
|
+
expect(calls[0]!.path).toBe("/api/v1/cad/pipeline");
|
|
98
|
+
expect(result.taskId).toBe("t-2");
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
});
|