buildx-sdk 1.0.4
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/LICENSE +21 -0
- package/README.md +514 -0
- package/dist/Buildx.d.ts +97 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.esm.js +2 -0
- package/dist/index.esm.js.map +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/services/ApiKeys.d.ts +36 -0
- package/dist/services/Auth.d.ts +141 -0
- package/dist/services/BaseService.d.ts +85 -0
- package/dist/services/BuildxObjects.d.ts +48 -0
- package/dist/services/Collections.d.ts +126 -0
- package/dist/services/Flows.d.ts +41 -0
- package/dist/services/Functions.d.ts +40 -0
- package/dist/services/Projects.d.ts +55 -0
- package/dist/services/Storage.d.ts +44 -0
- package/dist/services/Templates.d.ts +36 -0
- package/dist/types/index.d.ts +256 -0
- package/package.json +92 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Buildx Team
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
# Buildx SDK
|
|
2
|
+
|
|
3
|
+
Official JavaScript/TypeScript SDK for Buildx APIs.
|
|
4
|
+
|
|
5
|
+
`buildx-sdk` gives you typed services for auth, collections, storage, flows, templates, functions, and Buildx system objects.
|
|
6
|
+
|
|
7
|
+
## Contents
|
|
8
|
+
- [Install](#install)
|
|
9
|
+
- [Quick Start](#quick-start)
|
|
10
|
+
- [SDK Boundary](#sdk-boundary)
|
|
11
|
+
- [How Scoping Works](#how-scoping-works)
|
|
12
|
+
- [Configuration](#configuration)
|
|
13
|
+
- [Error Handling](#error-handling)
|
|
14
|
+
- [Authentication](#authentication)
|
|
15
|
+
- [Auth Flows](#auth-flows)
|
|
16
|
+
- [Collections](#collections)
|
|
17
|
+
- [Storage](#storage)
|
|
18
|
+
- [Projects](#projects)
|
|
19
|
+
- [Flows](#flows)
|
|
20
|
+
- [Templates](#templates)
|
|
21
|
+
- [Functions](#functions)
|
|
22
|
+
- [Buildx Objects](#buildx-objects)
|
|
23
|
+
- [API Keys](#api-keys)
|
|
24
|
+
- [Production Notes](#production-notes)
|
|
25
|
+
- [Generate Docs](#generate-docs)
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
yarn add buildx-sdk
|
|
31
|
+
# or
|
|
32
|
+
npm install buildx-sdk
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Quick Start
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { Buildx } from "buildx-sdk";
|
|
39
|
+
|
|
40
|
+
const buildx = new Buildx({
|
|
41
|
+
apiEndpoint: "https://api.buildx.app",
|
|
42
|
+
apiKey: process.env.BUILDX_API_KEY!,
|
|
43
|
+
projectId: process.env.BUILDX_PROJECT_ID!, // required for most project data operations
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
const auth = buildx.auth();
|
|
47
|
+
const collections = buildx.collections();
|
|
48
|
+
|
|
49
|
+
// 1) login
|
|
50
|
+
const user = await auth.login({
|
|
51
|
+
username: "demo@example.com",
|
|
52
|
+
password: "secret",
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// 2) query collection data
|
|
56
|
+
const orders = await collections.query("orders", {
|
|
57
|
+
filter: { status: "paid" },
|
|
58
|
+
limit: 20,
|
|
59
|
+
sort: { createdAt: -1 },
|
|
60
|
+
});
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## SDK Boundary
|
|
64
|
+
|
|
65
|
+
`buildx-sdk` is the **public/client SDK** for Buildx APIs.
|
|
66
|
+
|
|
67
|
+
Use this SDK when:
|
|
68
|
+
- building frontend or backend application logic against Buildx APIs
|
|
69
|
+
- you need typed access to auth, collections, storage, flows, templates, functions
|
|
70
|
+
|
|
71
|
+
Do not treat this package as an admin-only runtime layer.
|
|
72
|
+
Admin/machine concerns are handled by `buildx-admin-sdk` together with private datastore routes used by `buildx-edge-function`.
|
|
73
|
+
|
|
74
|
+
## How Scoping Works
|
|
75
|
+
|
|
76
|
+
Buildx API has three practical scopes:
|
|
77
|
+
|
|
78
|
+
- `project-scoped`: routes like `/project/:project_id/...`
|
|
79
|
+
- `organization-scoped`: routes like `/:organization_id/...` for org resources
|
|
80
|
+
- `root`: routes like `/auth/...` and `/projects`
|
|
81
|
+
|
|
82
|
+
This SDK maps scope automatically from your config and selected method:
|
|
83
|
+
|
|
84
|
+
- services like `collections`, `storage`, `flows`, `templates`, `functions`, `buildxObjects` are **project-scoped**
|
|
85
|
+
- `apiKeys.list/get/getSecret` can be **root** or **organization-scoped**
|
|
86
|
+
- `auth.requestPasswordReset` and `auth.resetPassword` support:
|
|
87
|
+
- project scope when `projectId` is configured
|
|
88
|
+
- root scope when `projectId` is omitted or `"default"`
|
|
89
|
+
- OTP login is **project-scoped only** in this SDK/API
|
|
90
|
+
|
|
91
|
+
## Configuration
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
const buildx = new Buildx({
|
|
95
|
+
apiEndpoint: "https://api.buildx.app",
|
|
96
|
+
apiKey: "YOUR_API_KEY",
|
|
97
|
+
projectId: "YOUR_PROJECT_ID", // optional at init, but required for project-scoped services
|
|
98
|
+
organizationId: "YOUR_ORG_ID", // optional; used by org helpers (for example api keys/users)
|
|
99
|
+
});
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Update runtime config:
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
buildx.updateConfig({
|
|
106
|
+
apiKey: "NEW_API_KEY",
|
|
107
|
+
projectId: "ANOTHER_PROJECT_ID",
|
|
108
|
+
});
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Error Handling
|
|
112
|
+
|
|
113
|
+
All methods return either success data or:
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
type ErrorResponse = {
|
|
117
|
+
error: string;
|
|
118
|
+
message: string;
|
|
119
|
+
statusCode: number;
|
|
120
|
+
success: false;
|
|
121
|
+
};
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Recommended type guard:
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
import type { ErrorResponse } from "buildx-sdk";
|
|
128
|
+
|
|
129
|
+
function isError<T>(value: T | ErrorResponse): value is ErrorResponse {
|
|
130
|
+
return !!value && typeof value === "object" && "success" in value && value.success === false;
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## Authentication
|
|
135
|
+
|
|
136
|
+
### Login / Signup / Current User
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
const auth = buildx.auth();
|
|
140
|
+
|
|
141
|
+
await auth.login({ username: "user", password: "pass" });
|
|
142
|
+
await auth.loginWithGoogle({ credential: "google-id-token" });
|
|
143
|
+
await auth.signup({ username: "new-user", password: "pass" });
|
|
144
|
+
|
|
145
|
+
const me = await auth.getCurrentUser();
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### Token Management
|
|
149
|
+
|
|
150
|
+
`login`, `signup`, and OTP verify auto-store tokens if response contains them.
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
auth.setAccessToken("token");
|
|
154
|
+
auth.setRefreshToken("refresh");
|
|
155
|
+
auth.getAccessToken();
|
|
156
|
+
auth.getRefreshToken();
|
|
157
|
+
auth.isAuthenticated();
|
|
158
|
+
auth.clearTokens();
|
|
159
|
+
|
|
160
|
+
await auth.refreshToken();
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
### OTP Login (Project-Scoped Only)
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
// request OTP
|
|
167
|
+
await auth.requestEotp({ email: "user@example.com" });
|
|
168
|
+
// alias: requestEotpAuth / requestOtpLogin
|
|
169
|
+
|
|
170
|
+
// verify OTP and receive auth tokens
|
|
171
|
+
await auth.verifyEotp({ email: "user@example.com", otp: "123456" });
|
|
172
|
+
// alias: verifyEotpAuth / verifyOtpLogin
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Notes:
|
|
176
|
+
- requires valid `projectId`
|
|
177
|
+
- root OTP login is intentionally not supported
|
|
178
|
+
|
|
179
|
+
### Auth Flows
|
|
180
|
+
|
|
181
|
+
#### EOTP Login Flow
|
|
182
|
+
|
|
183
|
+
```mermaid
|
|
184
|
+
sequenceDiagram
|
|
185
|
+
participant C as Client App
|
|
186
|
+
participant B as buildx-sdk
|
|
187
|
+
participant A as Buildx API
|
|
188
|
+
C->>B: auth.requestEotp({ email })
|
|
189
|
+
B->>A: POST /project/:projectId/auth/eotp/auth/request
|
|
190
|
+
A-->>C: OTP sent (email)
|
|
191
|
+
C->>B: auth.verifyEotp({ email, otp })
|
|
192
|
+
B->>A: POST /project/:projectId/auth/eotp/auth/verify
|
|
193
|
+
A-->>B: user + access_token (+ refresh_token)
|
|
194
|
+
B-->>C: stores tokens in Auth service
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
Failure points to handle:
|
|
198
|
+
- invalid/expired OTP
|
|
199
|
+
- suspended/deleted user
|
|
200
|
+
- missing `projectId` (OTP route is not available at root scope)
|
|
201
|
+
|
|
202
|
+
### Change Password (Authenticated User)
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
// simple
|
|
206
|
+
await auth.updatePassword("new-password");
|
|
207
|
+
|
|
208
|
+
// richer payload
|
|
209
|
+
await auth.changePassword({
|
|
210
|
+
currentPassword: "old-password",
|
|
211
|
+
newPassword: "new-password",
|
|
212
|
+
});
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
### Admin Password Update
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
await auth.adminUpdatePassword("USER_ID", "new-password");
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
### Password Reset (Token-Based)
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
// request reset link
|
|
225
|
+
await auth.requestPasswordReset({
|
|
226
|
+
email: "user@example.com",
|
|
227
|
+
reset_url: "https://your-app.com/reset-password",
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
// reset with token
|
|
231
|
+
await auth.resetPassword({
|
|
232
|
+
token: "reset-token-from-email",
|
|
233
|
+
new_password: "new-secret",
|
|
234
|
+
email: "user@example.com", // optional; token-only also supported
|
|
235
|
+
});
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
Scope behavior:
|
|
239
|
+
- with `projectId`: `POST /project/:id/auth/password/reset/...`
|
|
240
|
+
- without `projectId` or with `"default"`: `POST /auth/password/reset/...`
|
|
241
|
+
|
|
242
|
+
#### Password Reset Flow
|
|
243
|
+
|
|
244
|
+
```mermaid
|
|
245
|
+
sequenceDiagram
|
|
246
|
+
participant C as Client App
|
|
247
|
+
participant B as buildx-sdk
|
|
248
|
+
participant A as Buildx API
|
|
249
|
+
participant M as User Mailbox
|
|
250
|
+
C->>B: auth.requestPasswordReset({ email, reset_url? })
|
|
251
|
+
B->>A: POST /project/:projectId/auth/password/reset/request OR /auth/password/reset/request
|
|
252
|
+
A-->>M: reset link with token
|
|
253
|
+
C->>B: auth.resetPassword({ token, new_password, email? })
|
|
254
|
+
B->>A: POST /project/:projectId/auth/password/reset OR /auth/password/reset
|
|
255
|
+
A-->>C: reset success
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
### User Management
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
await auth.listUsers(); // root
|
|
262
|
+
await auth.listUsers("org-id"); // organization scope
|
|
263
|
+
|
|
264
|
+
await auth.lookupUsers();
|
|
265
|
+
await auth.getUser("user-id");
|
|
266
|
+
await auth.deleteUser("user-id");
|
|
267
|
+
|
|
268
|
+
await auth.updatePushToken("expo-or-fcm-token");
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
## Collections
|
|
272
|
+
|
|
273
|
+
### List / Schema / Upsert / Delete Collection
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
const collections = buildx.collections();
|
|
277
|
+
|
|
278
|
+
await collections.list(); // filters out buildx_* by default
|
|
279
|
+
await collections.list(true, true); // withStats + include buildx_*
|
|
280
|
+
await collections.getSchema("orders", 1); // depth default 1
|
|
281
|
+
await collections.set({ collection_id: "orders", name: "Orders" });
|
|
282
|
+
await collections.deleteCollection("orders");
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
### Query Data
|
|
286
|
+
|
|
287
|
+
```ts
|
|
288
|
+
await collections.query("orders", {
|
|
289
|
+
filter: { status: "paid" },
|
|
290
|
+
select: ["_id", "customer", "total", "createdAt"],
|
|
291
|
+
sort: { createdAt: -1 },
|
|
292
|
+
limit: 50,
|
|
293
|
+
skip: 0,
|
|
294
|
+
});
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
Query options:
|
|
298
|
+
- `q` or `searchQuery`
|
|
299
|
+
- `filter`, `jsonFilter`
|
|
300
|
+
- `select`, `projection`
|
|
301
|
+
- `options`, `sort`
|
|
302
|
+
- `limit`, `skip`
|
|
303
|
+
- `quick_filter_fields`
|
|
304
|
+
|
|
305
|
+
### Raw Query (No Populate)
|
|
306
|
+
|
|
307
|
+
```ts
|
|
308
|
+
await collections.queryRaw("orders", {
|
|
309
|
+
filter: { status: "paid" },
|
|
310
|
+
select: ["_id", "customer", "total"],
|
|
311
|
+
});
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
### Pagination Metadata
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
const page = await collections.queryWithPagination("orders", {
|
|
318
|
+
limit: 100,
|
|
319
|
+
skip: 0,
|
|
320
|
+
sort: { _id: -1 },
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
// page = { data: [...], meta: { count, limit, skip, transport, ... } }
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
### Pagination Transport (HTTP / WS / Auto)
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
await collections.queryWithPagination("orders", {
|
|
330
|
+
limit: 100,
|
|
331
|
+
paginationTransport: "auto", // "auto" | "http" | "ws"
|
|
332
|
+
});
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
`auto` tries WebSocket first then falls back to HTTP.
|
|
336
|
+
|
|
337
|
+
### Relation Hydration
|
|
338
|
+
|
|
339
|
+
```ts
|
|
340
|
+
await collections.query("orders", {
|
|
341
|
+
select: ["_id", "customer", "items"],
|
|
342
|
+
relations: [
|
|
343
|
+
{ field: "customer", collectionId: "customers" },
|
|
344
|
+
{ field: "items", collectionId: "products", many: true },
|
|
345
|
+
],
|
|
346
|
+
relationSelect: "_id,_display,name,price",
|
|
347
|
+
});
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
### Realtime (SSE)
|
|
351
|
+
|
|
352
|
+
```ts
|
|
353
|
+
const sub = collections.subscribeRealtime("orders", {
|
|
354
|
+
onConnected: () => console.log("connected"),
|
|
355
|
+
onEvent: (event) => console.log(event),
|
|
356
|
+
onError: (error) => console.error(error),
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
// later
|
|
360
|
+
sub.close();
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
### Document CRUD
|
|
364
|
+
|
|
365
|
+
```ts
|
|
366
|
+
await collections.getDocument("orders", "doc-id");
|
|
367
|
+
await collections.getDocument("orders", "doc-id", ["customer"]);
|
|
368
|
+
|
|
369
|
+
await collections.createDocument("orders", { status: "new" });
|
|
370
|
+
await collections.updateDocument("orders", "doc-id", { status: "paid" });
|
|
371
|
+
|
|
372
|
+
// update with query mode=updateOnly
|
|
373
|
+
await collections.updateDocumentWithOptions(
|
|
374
|
+
"orders",
|
|
375
|
+
"doc-id",
|
|
376
|
+
{ total: 1200 },
|
|
377
|
+
{ updateOnly: true }
|
|
378
|
+
);
|
|
379
|
+
|
|
380
|
+
await collections.getDocumentRevisions("orders", "doc-id");
|
|
381
|
+
await collections.deleteDocument("orders", "doc-id");
|
|
382
|
+
await collections.deleteByFilter("orders", { status: "archived" });
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
### Utility Methods
|
|
386
|
+
|
|
387
|
+
```ts
|
|
388
|
+
await collections.lookup("users", { limit: 20 });
|
|
389
|
+
await collections.getDataTypes();
|
|
390
|
+
await collections.validate("orders");
|
|
391
|
+
await collections.migrate("orders");
|
|
392
|
+
|
|
393
|
+
await collections.import("orders", file, {
|
|
394
|
+
ext_ref: "external_ref",
|
|
395
|
+
amount: "total",
|
|
396
|
+
});
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
## Storage
|
|
400
|
+
|
|
401
|
+
```ts
|
|
402
|
+
const storage = buildx.storage();
|
|
403
|
+
|
|
404
|
+
await storage.upload(file, "invoices/2026");
|
|
405
|
+
await storage.uploadToCollection(file, "orders", "attachments");
|
|
406
|
+
|
|
407
|
+
await storage.list("invoices/");
|
|
408
|
+
await storage.getSize("invoices/");
|
|
409
|
+
|
|
410
|
+
await storage.delete("invoices/2026/a.pdf");
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
## Projects
|
|
414
|
+
|
|
415
|
+
```ts
|
|
416
|
+
const projects = buildx.projects();
|
|
417
|
+
|
|
418
|
+
await projects.list();
|
|
419
|
+
await projects.get("project-id");
|
|
420
|
+
await projects.create({ name: "My Project" });
|
|
421
|
+
await projects.update("project-id", { description: "Updated" });
|
|
422
|
+
await projects.deleteById("project-id");
|
|
423
|
+
|
|
424
|
+
await projects.backup("project-id");
|
|
425
|
+
await projects.restore("project-id", backupFile);
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
## Flows
|
|
429
|
+
|
|
430
|
+
```ts
|
|
431
|
+
const flows = buildx.flows();
|
|
432
|
+
|
|
433
|
+
await flows.getTypes();
|
|
434
|
+
await flows.run("flow-id", null, "root", { orderId: "123" });
|
|
435
|
+
|
|
436
|
+
await flows.getGptFlowSuggestions("Create approval flow");
|
|
437
|
+
await flows.getGptCollectionSuggestions("Design invoice schema");
|
|
438
|
+
await flows.getGptLifecycleSuggestions("Draft to approved states");
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
## Templates
|
|
442
|
+
|
|
443
|
+
```ts
|
|
444
|
+
const templates = buildx.templates();
|
|
445
|
+
|
|
446
|
+
await templates.preview(templateJson, { customerName: "Alice" });
|
|
447
|
+
await templates.render("template-id", { customerName: "Alice" });
|
|
448
|
+
await templates.renderPDF("template-id", { customerName: "Alice" });
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
## Functions
|
|
452
|
+
|
|
453
|
+
```ts
|
|
454
|
+
const functions = buildx.functions();
|
|
455
|
+
|
|
456
|
+
await functions.list();
|
|
457
|
+
await functions.getByName("sendInvoice");
|
|
458
|
+
await functions.update("sendInvoice", { code: "exports.handler = async () => {};" });
|
|
459
|
+
await functions.getLogs("sendInvoice");
|
|
460
|
+
```
|
|
461
|
+
|
|
462
|
+
## Buildx Objects
|
|
463
|
+
|
|
464
|
+
```ts
|
|
465
|
+
const bo = buildx.buildxObjects();
|
|
466
|
+
|
|
467
|
+
await bo.getCollection("roles");
|
|
468
|
+
await bo.getDocument("roles", "role-id");
|
|
469
|
+
await bo.query("roles", { limit: 50, sort: { createdAt: -1 } });
|
|
470
|
+
await bo.create("roles", { role_id: "auditor", name: "Auditor" });
|
|
471
|
+
await bo.update("roles", "role-id", { name: "Senior Auditor" });
|
|
472
|
+
await bo.deleteObject("roles", "role-id");
|
|
473
|
+
```
|
|
474
|
+
|
|
475
|
+
## API Keys
|
|
476
|
+
|
|
477
|
+
```ts
|
|
478
|
+
const keys = buildx.apiKeys();
|
|
479
|
+
|
|
480
|
+
await keys.list(); // root scope
|
|
481
|
+
await keys.list("org-id"); // org scope
|
|
482
|
+
|
|
483
|
+
await keys.get("api-key-id");
|
|
484
|
+
await keys.getSecret("api-key-id");
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
## Production Notes
|
|
488
|
+
|
|
489
|
+
- Keep `apiKey` server-side when possible.
|
|
490
|
+
- If using browser apps, treat API keys as public identifiers and rely on JWT + backend authorization rules.
|
|
491
|
+
- Rotate API keys and refresh tokens on schedule.
|
|
492
|
+
- For uploads in Node.js, ensure `File`/`FormData` compatibility (Node 18+ or polyfills).
|
|
493
|
+
- Handle `ErrorResponse` centrally and map `statusCode` to UX states.
|
|
494
|
+
- Prefer `queryWithPagination` for large datasets.
|
|
495
|
+
- Use `paginationTransport: "auto"` for large list views when WS is available.
|
|
496
|
+
|
|
497
|
+
## Generate Docs
|
|
498
|
+
|
|
499
|
+
This package uses TypeDoc and includes `README.md` in generated docs.
|
|
500
|
+
|
|
501
|
+
```bash
|
|
502
|
+
yarn docs
|
|
503
|
+
```
|
|
504
|
+
|
|
505
|
+
Output locations:
|
|
506
|
+
- `docs/api/html`
|
|
507
|
+
- `docs/api/html/docs.json`
|
|
508
|
+
- `docs/api/markdown`
|
|
509
|
+
|
|
510
|
+
---
|
|
511
|
+
|
|
512
|
+
For generated API reference, see:
|
|
513
|
+
- `docs/api/markdown`
|
|
514
|
+
- `docs/api/html`
|
package/dist/Buildx.d.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { BuildxConfig } from "./types";
|
|
2
|
+
import { Auth } from "./services/Auth";
|
|
3
|
+
import { Projects } from "./services/Projects";
|
|
4
|
+
import { Collections } from "./services/Collections";
|
|
5
|
+
import { Storage } from "./services/Storage";
|
|
6
|
+
import { Flows } from "./services/Flows";
|
|
7
|
+
import { Templates } from "./services/Templates";
|
|
8
|
+
import { Functions } from "./services/Functions";
|
|
9
|
+
import { BuildxObjects } from "./services/BuildxObjects";
|
|
10
|
+
import { ApiKeys } from "./services/ApiKeys";
|
|
11
|
+
/**
|
|
12
|
+
* Main Buildx SDK class
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```typescript
|
|
16
|
+
* import { Buildx } from 'buildx-sdk';
|
|
17
|
+
*
|
|
18
|
+
* const buildx = new Buildx({
|
|
19
|
+
* apiEndpoint: 'https://api.buildx.com',
|
|
20
|
+
* apiKey: 'your-api-key',
|
|
21
|
+
* projectId: 'your-project-id'
|
|
22
|
+
* });
|
|
23
|
+
*
|
|
24
|
+
* // Use different services
|
|
25
|
+
* const auth = buildx.auth();
|
|
26
|
+
* const projects = buildx.projects();
|
|
27
|
+
* const collections = buildx.collections();
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export declare class Buildx {
|
|
31
|
+
private config;
|
|
32
|
+
private _auth;
|
|
33
|
+
private _projects;
|
|
34
|
+
private _collections;
|
|
35
|
+
private _storage;
|
|
36
|
+
private _flows;
|
|
37
|
+
private _templates;
|
|
38
|
+
private _functions;
|
|
39
|
+
private _buildxObjects;
|
|
40
|
+
private _apiKeys;
|
|
41
|
+
private _baseService;
|
|
42
|
+
constructor(config: BuildxConfig);
|
|
43
|
+
/**
|
|
44
|
+
* Get the current configuration
|
|
45
|
+
*/
|
|
46
|
+
getConfig(): BuildxConfig;
|
|
47
|
+
/**
|
|
48
|
+
* Update the configuration
|
|
49
|
+
*/
|
|
50
|
+
updateConfig(config: Partial<BuildxConfig>): void;
|
|
51
|
+
/**
|
|
52
|
+
* Authentication service
|
|
53
|
+
* Handles user authentication, login, signup, and user management
|
|
54
|
+
*/
|
|
55
|
+
auth(): Auth;
|
|
56
|
+
/**
|
|
57
|
+
* Projects service
|
|
58
|
+
* Manages projects, including CRUD operations
|
|
59
|
+
*/
|
|
60
|
+
projects(): Projects;
|
|
61
|
+
/**
|
|
62
|
+
* Collections service
|
|
63
|
+
* Manages data collections, documents, and queries
|
|
64
|
+
*/
|
|
65
|
+
collections(): Collections;
|
|
66
|
+
/**
|
|
67
|
+
* Storage service
|
|
68
|
+
* Handles file upload, download, and management
|
|
69
|
+
*/
|
|
70
|
+
storage(): Storage;
|
|
71
|
+
/**
|
|
72
|
+
* Flows service
|
|
73
|
+
* Manages workflow execution and flow types
|
|
74
|
+
*/
|
|
75
|
+
flows(): Flows;
|
|
76
|
+
/**
|
|
77
|
+
* Templates service
|
|
78
|
+
* Handles template rendering and preview
|
|
79
|
+
*/
|
|
80
|
+
templates(): Templates;
|
|
81
|
+
/**
|
|
82
|
+
* Functions service
|
|
83
|
+
* Manages serverless functions
|
|
84
|
+
*/
|
|
85
|
+
functions(): Functions;
|
|
86
|
+
/**
|
|
87
|
+
* Buildx Objects service
|
|
88
|
+
* Manages Buildx-specific objects (users, roles, etc.)
|
|
89
|
+
*/
|
|
90
|
+
buildxObjects(): BuildxObjects;
|
|
91
|
+
/**
|
|
92
|
+
* API Keys service
|
|
93
|
+
* Manages API key operations
|
|
94
|
+
*/
|
|
95
|
+
apiKeys(): ApiKeys;
|
|
96
|
+
}
|
|
97
|
+
export default Buildx;
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("axios");class t{constructor(e){this.baseService=e}setAccessToken(e){this.baseService.setAccessToken(e)}getAccessToken(){return this.baseService.getAccessToken()}setRefreshToken(e){this.baseService.setRefreshToken(e)}getRefreshToken(){return this.baseService.getRefreshToken()}clearTokens(){this.baseService.clearTokens()}isAuthenticated(){return this.baseService.isAuthenticated()}storeTokens(e){"access_token"in e&&e.access_token&&this.baseService.setAccessToken(e.access_token),"refresh_token"in e&&e.refresh_token&&this.baseService.setRefreshToken(e.refresh_token)}isErrorResponse(e){return e&&"object"==typeof e&&"success"in e&&!1===e.success}hasProjectScope(){const e=this.baseService.config.projectId;return!!e&&"default"!==e}async login(e){const t=this.baseService.buildProjectUrl("/auth/login"),s=await this.baseService.post(t,e);return this.isErrorResponse(s)||this.storeTokens(s),s}async loginWithGoogle(e){const t=this.baseService.buildProjectUrl("/auth/google"),s=await this.baseService.post(t,e);return this.isErrorResponse(s)||this.storeTokens(s),s}async signup(e){const t=this.baseService.buildProjectUrl("/auth/signup"),s=await this.baseService.post(t,e);return this.isErrorResponse(s)||this.storeTokens(s),s}async requestEotp(e){const t=this.baseService.buildProjectUrl("/auth/eotp/auth/request");return await this.baseService.post(t,e)}async requestEotpAuth(e){return this.requestEotp(e)}async requestOtpLogin(e){return this.requestEotp(e)}async verifyEotp(e){const t=this.baseService.buildProjectUrl("/auth/eotp/auth/verify"),s=await this.baseService.post(t,e);return this.isErrorResponse(s)||this.storeTokens(s),s}async verifyEotpAuth(e){return this.verifyEotp(e)}async verifyOtpLogin(e){return this.verifyEotp(e)}async getCurrentUser(){const e=this.baseService.buildProjectUrl("/auth/me");return await this.baseService.get(e)}async refreshToken(){const e=this.baseService.buildProjectUrl("/auth/token"),t=await this.baseService.post(e,{});return this.isErrorResponse(t)||"access_token"in t&&t.access_token&&this.storeTokens(t),t}async updatePassword(e){const t=this.baseService.buildProjectUrl("/auth/password/update");return await this.baseService.post(t,{password:e})}async changePassword(e){const t=this.baseService.buildProjectUrl("/auth/password/update");if("string"==typeof e)return await this.baseService.post(t,{password:e});const s=e.password??e.newPassword??e.new_password,i={...e};return s&&(i.password=s),e.currentPassword&&!i.current_password&&(i.current_password=e.currentPassword),e.newPassword&&!i.new_password&&(i.new_password=e.newPassword),await this.baseService.post(t,i)}async adminUpdatePassword(e,t){const s=this.baseService.buildProjectUrl("/auth/password/update");return await this.baseService.post(s,{user_id:e,password:t})}async requestPasswordReset(e){const t=this.hasProjectScope()?this.baseService.buildProjectUrl("/auth/password/reset/request"):"/auth/password/reset/request";return await this.baseService.post(t,e)}async resetPassword(e){const t=this.hasProjectScope()?this.baseService.buildProjectUrl("/auth/password/reset"):"/auth/password/reset";return await this.baseService.post(t,e)}async updatePushToken(e){const t=this.baseService.buildProjectUrl("/users/push-tokens");return await this.baseService.post(t,{token:e})}async listUsers(e){const t=e?this.baseService.buildOrgUrl("/auth/users"):"/auth/users";return await this.baseService.get(t)}async lookupUsers(e){const t=e?this.baseService.buildOrgUrl("/auth/users/lookup"):"/auth/users/lookup";return await this.baseService.get(t)}async getUser(e,t){const s=t?this.baseService.buildOrgUrl(`/auth/user/${e}`):`/auth/user/${e}`;return await this.baseService.get(s)}async deleteUser(e){const t=this.baseService.buildProjectUrl(`/auth/user/${e}/delete`);return await this.baseService.post(t,{})}}class s{constructor(e){this.baseService=e}async list(){return await this.baseService.get("/projects")}async get(e){return await this.baseService.get(`/project/${e}`)}async create(e){return await this.baseService.post("/projects",e)}async update(e,t){return await this.baseService.patch(`/project/${e}`,t)}async deleteById(e){return await this.baseService.delete(`/project/${e}`)}async backup(e){const t=await this.baseService.axiosInstance.get(`/project/${e}/backup`,{responseType:"blob",headers:await this.baseService.getHeaders()});if("undefined"!=typeof window){const s=window.URL.createObjectURL(t.data),i=document.createElement("a");i.href=s,i.setAttribute("download",`backup_${e}.buildx`),document.body.appendChild(i),i.click(),document.body.removeChild(i),window.URL.revokeObjectURL(s)}return{success:!0,message:"Backup downloaded successfully"}}async restore(e,t){const s=new FormData;s.append("new_project_id",e),s.append("backup_file",t);const i={...await this.baseService.getHeaders(),"Content-Type":"multipart/form-data"};return await this.baseService.post("/project/import",s,{headers:i})}}class i{constructor(e,t,s){this.baseService=e,this.collectionId=t,this.wsFactory=s,this.socket=null,this.connectPromise=null,this.requestCounter=0,this.pending=new Map}async query(e,t,s=3e4){if(await this.ensureConnected(),!this.socket)throw new Error("WebSocket connection is unavailable");const i=`${Date.now()}_${++this.requestCounter}`,r=new Promise((e,t)=>{const r=setTimeout(()=>{this.pending.delete(i),t(new Error("WebSocket pagination timeout"))},s);this.pending.set(i,{resolve:e,reject:t,timeout:r})});return this.socket.send(JSON.stringify({id:i,action:e,payload:t})),r}close(){if(this.socket){try{this.socket.close()}catch(e){}this.socket=null,this.connectPromise=null;for(const[,e]of this.pending.entries())clearTimeout(e.timeout),e.reject(new Error("WebSocket closed"));this.pending.clear()}}async ensureConnected(){if(!this.socket||!this.isSocketOpen(this.socket))return this.connectPromise||(this.connectPromise=new Promise((e,t)=>{const s=globalThis.WebSocket;if(!this.wsFactory&&!s)return void t(new Error("WebSocket is not available in this runtime"));const i=this.wsFactory?this.wsFactory(this.buildSocketUrl()):new s(this.buildSocketUrl());this.socket=i;let r=!1;const a=()=>{r||(r=!0,e())},o=e=>{r||(r=!0,t(e)),this.close()},n=()=>{r||(r=!0,t(new Error("WebSocket closed before connection is ready"))),this.close()},c=e=>{let t;try{t=JSON.parse(e?.data||"{}")}catch(e){return}const s=t?.id;if(!s)return;const i=this.pending.get(s);i&&(clearTimeout(i.timeout),this.pending.delete(s),t.ok&&t.result?i.resolve(t.result):i.reject(new Error(t.error||"WebSocket pagination query failed")))};i.addEventListener?(i.addEventListener("open",a),i.addEventListener("error",o),i.addEventListener("close",n),i.addEventListener("message",c)):(i.onopen=a,i.onerror=o,i.onclose=n,i.onmessage=c)}).finally(()=>{this.connectPromise=null})),this.connectPromise}isSocketOpen(e){const t=globalThis.WebSocket?.OPEN??1;return e.readyState===t}buildSocketUrl(){const e=this.baseService.config.apiEndpoint.replace(/\/$/,"").replace(/^http:/i,"ws:").replace(/^https:/i,"wss:"),t=this.baseService.buildProjectUrl(`/${this.collectionId}/data/pagination/ws`),s=new URLSearchParams,i=this.baseService.config.apiKey;i&&s.set("api_key",i);const r=this.baseService.getAccessToken();r&&s.set("token",r);const a=s.toString();return`${e}${t}${a?`?${a}`:""}`}}class r{constructor(e){this.collectionWsClient=null,this.collectionWsCollectionId=null,this.collectionWsDisabledUntil=0,this.baseService=e}async list(e=!1,t=!1){const s=this.baseService.buildProjectUrl("/collections"),i={};e&&(i.with_stats=!0);const r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s,o=await this.baseService.get(a);return Array.isArray(o)&&!t?o.filter(e=>e.collection_id&&!e.collection_id.startsWith("buildx_")):o}async getSchema(e,t=1){const s=this.baseService.buildProjectUrl(`/collection/${e}`),i={};t>1&&(i.depth=t);const r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s;return await this.baseService.get(a)}async set(e){const t=this.baseService.buildProjectUrl("/collections");return await this.baseService.post(t,e)}async deleteCollection(e){const t=this.baseService.buildProjectUrl(`/collections/${e}`);return await this.baseService.delete(t)}async query(e,t){const s=this.baseService.buildProjectUrl(`/${e}`),i=t?.noPopulate??(!!t?.relations&&t.relations.length>0),r=this.buildQueryParams({...t,options:i?{...t?.options||{},noPopulate:!0}:t?.options}),a=this.baseService.buildQueryString(r),o=a?`${s}${a}`:s,n=await this.baseService.get(o);if(!Array.isArray(n))return n;if(!t?.relations||0===t.relations.length)return n;const c="http"!==(t?.paginationTransport||"auto");return await this.hydrateRelations(n,t.relations,t.relationSelect,{preferWs:c,wsFactory:t.wsFactory})}async queryRaw(e,t){const s={...t,options:{...t?.options||{},noPopulate:!0}};if("http"!==(s.paginationTransport||"http")&&Date.now()>=this.collectionWsDisabledUntil)try{return await this.queryRawViaWs(e,s)}catch(e){console.warn("[buildx-sdk] WS raw query failed, fallback to HTTP",e?.message||e),this.collectionWsDisabledUntil=Date.now()+3e4,this.resetCollectionWsClient()}const i=this.baseService.buildProjectUrl(`/${e}/raw`),r=this.buildQueryParams(s),a=this.baseService.buildQueryString(r),o=a?`${i}${a}`:i;return await this.baseService.get(o)}async queryWithPagination(e,t){const s=t?.noPopulate??(!!t?.relations&&t.relations.length>0),i={...t,options:s?{...t?.options||{},noPopulate:!0}:t?.options},r=i.paginationTransport||"auto";let a;if("http"!==r&&Date.now()>=this.collectionWsDisabledUntil)try{a=await this.queryWithPaginationViaWs(e,i)}catch(t){console.warn("[buildx-sdk] WS pagination failed, fallback to HTTP",t?.message||t),this.collectionWsDisabledUntil=Date.now()+3e4,this.resetCollectionWsClient(),a=await this.queryWithPaginationViaHttp(e,i)}else a=await this.queryWithPaginationViaHttp(e,i);if(!a||!1===a.success)return a;if(!i?.relations||0===i.relations.length)return a;const o="http"!==r,n=await this.hydrateRelations(a.data||[],i.relations,i.relationSelect,{preferWs:o,wsFactory:i.wsFactory});return Array.isArray(n)?{...a,data:n}:n}async queryWithPaginationViaHttp(e,t){const s=this.baseService.buildProjectUrl(`/${e}/data/pagination`),i=this.buildQueryParams(t),r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s,o=await this.baseService.get(a);return o&&!1!==o.success?{...o,meta:{...o.meta||{},transport:"http"}}:o}async queryWithPaginationViaWs(e,t){const s=this.buildQueryParams(t),i=this.getOrCreateCollectionWsClient(e,t?.wsFactory),r=await i.query("queryWithPagination",s);return r&&!1!==r.success?{...r,meta:{...r.meta||{},transport:"ws"}}:r}async queryRawViaWs(e,t){const s=this.buildQueryParams(t),i=this.getOrCreateCollectionWsClient(e,t?.wsFactory),r=await i.query("queryRaw",s);return r&&!1!==r.success?Array.isArray(r)?r:[]:r}getOrCreateCollectionWsClient(e,t){return this.collectionWsClient&&this.collectionWsCollectionId===e||(this.resetCollectionWsClient(),this.collectionWsClient=new i(this.baseService,e,t),this.collectionWsCollectionId=e),this.collectionWsClient}resetCollectionWsClient(){this.collectionWsClient&&this.collectionWsClient.close(),this.collectionWsClient=null,this.collectionWsCollectionId=null}subscribeRealtime(e,t,s){const i=this.baseService.config.apiEndpoint.replace(/\/$/,""),r=this.baseService.buildProjectUrl(`/${e}/realtime/stream`),a=new URLSearchParams,o=s?.apiKey||this.baseService.config.apiKey;o&&a.set("api_key",o);const n=s?.token||this.baseService.getAccessToken();n&&a.set("token",n),s?.lastEventId&&a.set("lastEventId",s.lastEventId);const c=a.toString(),l=`${i}${r}${c?`?${c}`:""}`,u=s?.eventSourceFactory||globalThis.EventSource;if(!u)throw new Error("EventSource is not available in this runtime. Provide eventSourceFactory in options.");const h=u(l);let d=!1;const p=()=>{d||(d=!0,t.onConnected?.())},b=e=>{try{const s=JSON.parse(e.data);t.onEvent?.(s)}catch(e){t.onError?.(e)}};return h.onopen=()=>{p()},h.onmessage=e=>b(e),h.onerror=e=>{t.onError?.(e)},h.addEventListener?.("connected",()=>{p()}),h.addEventListener?.("collection:data",e=>{b(e)}),{close:()=>h.close()}}async lookup(e,t){const s=this.baseService.buildProjectUrl(`/${e}`),i={};t&&(t.filter&&(i.filter=t.filter),t.jsonFilter&&(i.jsonFilter=t.jsonFilter),t.projection&&(i.projection=t.projection),t.options&&(i.options=t.options));const r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s,o=await this.baseService.get(a);return Array.isArray(o)?o.map(e=>({value:e._id,label:e._display||e.label||e.title||e.name||e.username||e.description||""})):o}buildQueryParams(e){const t={};if(!e)return t;const s=e.q||e.searchQuery;return s&&(t.q=s),e.quick_filter_fields&&(t.quick_filter_fields=e.quick_filter_fields),e.filter&&(t.filter=e.filter),e.jsonFilter&&(t.jsonFilter=e.jsonFilter),e.select&&(t.select=Array.isArray(e.select)?e.select.join(","):e.select),e.projection&&(t.projection=e.projection),e.options&&(t.options=e.options),e.sort&&(t.sort=e.sort),"number"==typeof e.limit&&(t.limit=e.limit),"number"==typeof e.skip&&e.skip>0&&(t.skip=e.skip),t}async hydrateRelations(e,t,s,i){const a=e.map(e=>({...e})),o=s||"_id,_display,name,title,username",n=t.reduce((e,t)=>(e[t.collectionId]||(e[t.collectionId]=[]),e[t.collectionId].push(t),e),{}),c=new Map;for(const[e,t]of Object.entries(n)){const s=new Set;for(const e of a)for(const i of t){const t=e[i.field];if(t)if(Array.isArray(t))for(const e of t)"string"==typeof e?s.add(e):e&&"object"==typeof e&&e._id&&s.add(e._id);else"string"==typeof t?s.add(t):t&&"object"==typeof t&&t._id&&s.add(t._id)}const n=Array.from(s).filter(t=>!c.has(`${e}:${t}`));if(n.length>0){const t=r.RELATION_QUERY_CHUNK_SIZE;for(let s=0;s<n.length;s+=t){const r=n.slice(s,s+t),a=await this.queryRaw(e,{filter:{_id:{$in:r}},select:o,paginationTransport:i?.preferWs?"auto":"http",wsFactory:i?.wsFactory});if(!Array.isArray(a))return a;for(const t of a)t?._id&&c.set(`${e}:${t._id}`,t)}}for(const s of a)for(const i of t){const t=s[i.field];if(t)if(Array.isArray(t))s[i.field]=t.map(t=>{const s="string"==typeof t?t:t?._id;return s&&c.get(`${e}:${s}`)||t});else{const r="string"==typeof t?t:t?._id;if(!r)continue;s[i.field]=c.get(`${e}:${r}`)||t}}}return a}async getDocument(e,t,s){const i=this.baseService.buildProjectUrl(`/${e}/${t}`),r={};s&&s.length>0&&(r.populate=s.join(","));const a=this.baseService.buildQueryString(r),o=a?`${i}${a}`:i;return await this.baseService.get(o)}async createDocument(e,t){const s=this.baseService.buildProjectUrl(`/${e}`);return await this.baseService.post(s,t)}async updateDocument(e,t,s){const i=this.baseService.buildProjectUrl(`/${e}/${t}`);return await this.baseService.patch(i,s)}async updateDocumentWithOptions(e,t,s,i){const r=this.baseService.buildProjectUrl(`/${e}/${t}`),a=i?.updateOnly?`${r}?mode=updateOnly`:r;return await this.baseService.patch(a,s)}async getDocumentRevisions(e,t){const s=this.baseService.buildProjectUrl(`/${e}/${t}/revisions`);return await this.baseService.get(s)}async deleteDocument(e,t){const s=this.baseService.buildProjectUrl(`/${e}/${t}`);return await this.baseService.delete(s)}async deleteByFilter(e,t){const s=this.baseService.buildProjectUrl(`/${e}/delete`);return await this.baseService.post(s,{filter:t})}async import(e,t,s){const i=new FormData;i.append("mapping",JSON.stringify(s)),i.append("file",t);const r=this.baseService.buildProjectUrl(`/${e}/import`),a={...await this.baseService.getHeaders(),"Content-Type":"multipart/form-data"};return await this.baseService.post(r,i,{headers:a})}async getDataTypes(){const e=this.baseService.buildProjectUrl("/collections/types");return await this.baseService.get(e)}async validate(e){const t=this.baseService.buildProjectUrl(`/${e}/validate`);return await this.baseService.post(t,null)}async migrate(e){const t=this.baseService.buildProjectUrl(`/${e}/migrate`);return await this.baseService.post(t,null)}}r.RELATION_QUERY_CHUNK_SIZE=200;class a{constructor(e){this.baseService=e}async upload(e,t){const s=new FormData;t&&""!==t&&s.append("prefix",t),s.append("file",e),s.append("filename",e.name||"file");const i=this.baseService.buildProjectUrl("/storage/upload"),r={...await this.baseService.getHeaders(),"Content-Type":"multipart/form-data; charset=utf-8"};return await this.baseService.post(i,s,{headers:r})}async uploadToCollection(e,t,s){const i=new FormData;s&&""!==s&&i.append("prefix",s),i.append("file",e),i.append("filename",e.name||"file"),i.append("collection_id",t);const r=this.baseService.buildProjectUrl("/storage/upload"),a={...await this.baseService.getHeaders(),"Content-Type":"multipart/form-data; charset=utf-8"};return await this.baseService.post(r,i,{headers:a})}async list(e){const t=this.baseService.buildProjectUrl(`/storage?path=${encodeURIComponent(e)}`);return await this.baseService.get(t)}async getSize(e){const t=this.baseService.buildProjectUrl(`/storage/size?path=${encodeURIComponent(e)}`);return await this.baseService.get(t)}async delete(e){const t=this.baseService.buildProjectUrl(`/storage?path=${encodeURIComponent(e)}`);return await this.baseService.delete(t)}}class o{constructor(e){this.baseService=e}async getTypes(){return await this.baseService.get("/flows/types")}async run(e,t=null,s="root",i={}){const r=this.baseService.buildProjectUrl(`/flows/${e}/run`);return await this.baseService.post(r,{session_id:t,state:s,args:i})}async getGptFlowSuggestions(e){const t=this.baseService.buildProjectUrl("/ai/gpt/flow/node");return await this.baseService.post(t,{instruction:e})}async getGptCollectionSuggestions(e){const t=this.baseService.buildProjectUrl("/ai/gpt/collections");return await this.baseService.post(t,{instruction:e})}async getGptLifecycleSuggestions(e){const t=this.baseService.buildProjectUrl("/ai/gpt/lifecycle");return await this.baseService.post(t,{instruction:e})}}class n{constructor(e){this.baseService=e}async preview(e,t){const s=this.baseService.buildProjectUrl("/templates/preview");return await this.baseService.post(s,{template:e,data:t})}async render(e,t){const s=this.baseService.buildProjectUrl(`/templates/${e}/render`);return await this.baseService.post(s,t)}async renderPDF(e,t){const s=this.baseService.buildProjectUrl(`/templates/${e}/pdf`),i={...await this.baseService.getHeaders(),responseType:"blob"},r=await this.baseService.axiosInstance.post(s,t,{headers:i});if("undefined"!=typeof window){const e=window.URL.createObjectURL(r.data),t=document.createElement("a");t.href=e,t.setAttribute("download","document.pdf"),document.body.appendChild(t),t.click(),document.body.removeChild(t),window.URL.revokeObjectURL(e)}return{success:!0,message:"PDF downloaded successfully"}}}class c{constructor(e){this.baseService=e}async list(){const e=this.baseService.buildProjectUrl("/functions");return await this.baseService.get(e)}async getByName(e){const t=this.baseService.buildProjectUrl(`/functions/${e}`);return await this.baseService.get(t)}async update(e,t){const s=this.baseService.buildProjectUrl(`/functions/${e}`);return await this.baseService.post(s,t)}async getLogs(e){const t=this.baseService.buildProjectUrl(`/functions/${e}/logs`);return await this.baseService.get(t)}}class l{constructor(e){this.baseService=e}async getCollection(e){const t=this.baseService.buildProjectUrl(`/buildx/collection/${e}`);return await this.baseService.get(t)}async getDocument(e,t){const s=this.baseService.buildProjectUrl(`/buildx/${e}/${t}`),i=await this.baseService.get(s);return"object"==typeof i&&null!==i&&(i._display=i._display||i.label||i.title||i.name||i.username||i.description||""),i}async query(e,t){const s=this.baseService.buildProjectUrl(`/buildx/${e}`),i={};t&&(t.filter&&(i.filter=t.filter),t.jsonFilter&&(i.jsonFilter=t.jsonFilter),t.select&&(i.select=Array.isArray(t.select)?t.select.join(","):t.select),t.projection&&(i.projection=t.projection),t.options&&(i.options=t.options),t.sort&&(i.sort=t.sort),t.limit&&(i.limit=t.limit));const r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s,o=await this.baseService.get(a);return Array.isArray(o)&&o.forEach(e=>{e._display=e._display||e.label||e.title||e.name||e.username||e.description||""}),o}async create(e,t){const s=this.baseService.buildProjectUrl(`/buildx/${e}`);return await this.baseService.post(s,t)}async update(e,t,s){const i=this.baseService.buildProjectUrl(`/buildx/${e}/${t}`);return await this.baseService.patch(i,s)}async deleteObject(e,t){const s=this.baseService.buildProjectUrl(`/buildx/${e}/${t}`);return await this.baseService.delete(s)}}class u{constructor(e){this.baseService=e}async list(e){const t=e?this.baseService.buildOrgUrl("/auth/api-keys"):"/auth/api-keys";return await this.baseService.get(t)}async get(e,t){const s=t?this.baseService.buildOrgUrl(`/auth/api-key/${e}`):`/auth/api-key/${e}`;return await this.baseService.get(s)}async getSecret(e,t){const s=t?this.baseService.buildOrgUrl(`/auth/api-key/${e}/secret`):`/auth/api-key/${e}/secret`;return await this.baseService.get(s)}}let h={};class d{static getInstance(e,t,s){t||(t="default");const i=(s||"https://api.buildx.ai").replace(/\/$/,"");if(h[t]){const s=h[t];s.config.apiEndpoint===i&&s.config.apiKey===e||s.updateConfig({...s.config,apiEndpoint:i,apiKey:e})}else h[t]=new d({apiEndpoint:i,projectId:t,apiKey:e});return h[t]}constructor(t){this._accessToken=null,this._refreshToken=null,this.config=t,this.axiosInstance=e.create({baseURL:t.apiEndpoint,timeout:3e4}),this.axiosInstance.interceptors.request.use(e=>(e.headers["X-API-Key"]=this.config.apiKey,e),e=>Promise.reject(e)),this.axiosInstance.interceptors.response.use(e=>e,e=>this.handleError(e))}updateConfig(e){this.config=e,this.axiosInstance.defaults.baseURL=e.apiEndpoint}setAccessToken(e){this._accessToken=e}getAccessToken(){return this._accessToken}setRefreshToken(e){this._refreshToken=e}getRefreshToken(){return this._refreshToken}clearTokens(){this._accessToken=null,this._refreshToken=null}isAuthenticated(){return null!==this._accessToken}async getHeaders(e=!1){const t=e?this._refreshToken:this._accessToken,s={"Content-Type":"application/json","X-API-Key":this.config.apiKey};return t&&(s.Authorization=`Bearer ${t}`),s}getPublicHeaders(){return{"Content-Type":"application/json","X-API-Key":this.config.apiKey}}async get(e,t){const s=await this.getHeaders();return(await this.axiosInstance.get(e,{...t,headers:{...s,...t?.headers}})).data}async post(e,t,s){const i=await this.getHeaders();return(await this.axiosInstance.post(e,t,{...s,headers:{...i,...s?.headers}})).data}async put(e,t,s){const i=await this.getHeaders();return(await this.axiosInstance.put(e,t,{...s,headers:{...i,...s?.headers}})).data}async patch(e,t,s){const i=await this.getHeaders();return(await this.axiosInstance.patch(e,t,{...s,headers:{...i,...s?.headers}})).data}async delete(e,t){const s=await this.getHeaders();return(await this.axiosInstance.delete(e,{...t,headers:{...s,...t?.headers}})).data}handleError(e){if(e.response){const{status:t,data:s}=e.response;return s&&"object"==typeof s?{error:s.error||"RequestError",message:s.message||s.description||"Something went wrong",statusCode:t,success:!1}:{error:"RequestError",message:`Request failed with status ${t}`,statusCode:t,success:!1}}return"Network Error"===e.message?{error:"NetworkError",message:"Network connection failed",statusCode:500,success:!1}:{error:"RequestError",message:e.message||"Unknown error occurred",statusCode:500,success:!1}}buildProjectUrl(e=""){const t=this.config.projectId;if(!t||"default"===t)throw new Error("Project ID is required");return`/project/${t}${e}`}buildOrgUrl(e=""){const t=this.config.organizationId||this.config.projectId;if(!t)throw new Error("Organization ID is required");return`/${t}${e}`}buildQueryString(e){const t=new URLSearchParams;Object.entries(e).forEach(([e,s])=>{null!=s&&("object"==typeof s?t.append(e,JSON.stringify(s)):t.append(e,String(s)))});const s=t.toString();return s?`?${s}`:""}}class p{constructor(e){this.config={apiEndpoint:e.apiEndpoint.replace(/\/$/,""),apiKey:e.apiKey,projectId:e.projectId,organizationId:e.organizationId},this._baseService=d.getInstance(this.config.apiKey,this.config.projectId,this.config.apiEndpoint),this._auth=new t(this._baseService),this._projects=new s(this._baseService),this._collections=new r(this._baseService),this._storage=new a(this._baseService),this._flows=new o(this._baseService),this._templates=new n(this._baseService),this._functions=new c(this._baseService),this._buildxObjects=new l(this._baseService),this._apiKeys=new u(this._baseService)}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},this._baseService.updateConfig(this.config)}auth(){return this._auth}projects(){return this._projects}collections(){return this._collections}storage(){return this._storage}flows(){return this._flows}templates(){return this._templates}functions(){return this._functions}buildxObjects(){return this._buildxObjects}apiKeys(){return this._apiKeys}}exports.ApiKeys=u,exports.Auth=t,exports.Buildx=p,exports.BuildxObjects=l,exports.Collections=r,exports.Flows=o,exports.Functions=c,exports.Projects=s,exports.Storage=a,exports.Templates=n,exports.default=p;
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|