@celestoai/sdk 0.1.2 → 0.1.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/README.md +242 -52
- package/dist/{chunk-4KVRJSVJ.js → chunk-5VVB6N33.js} +2 -2
- package/dist/{chunk-N3HU6ONW.js → chunk-JS6BTDP5.js} +31 -4
- package/dist/chunk-JS6BTDP5.js.map +1 -0
- package/dist/chunk-XNTZDOKY.js +747 -0
- package/dist/chunk-XNTZDOKY.js.map +1 -0
- package/dist/computers/index.cjs +638 -65
- package/dist/computers/index.cjs.map +1 -1
- package/dist/computers/index.d.cts +159 -61
- package/dist/computers/index.d.ts +159 -61
- package/dist/computers/index.js +10 -4
- package/dist/gatekeeper/index.cjs +5 -2
- package/dist/gatekeeper/index.cjs.map +1 -1
- package/dist/gatekeeper/index.js +2 -2
- package/dist/index.cjs +783 -222
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -13
- package/dist/index.d.ts +4 -13
- package/dist/index.js +12 -15
- package/dist/index.js.map +1 -1
- package/package.json +6 -3
- package/dist/chunk-7OJDEZ7J.js +0 -212
- package/dist/chunk-7OJDEZ7J.js.map +0 -1
- package/dist/chunk-N3HU6ONW.js.map +0 -1
- /package/dist/{chunk-4KVRJSVJ.js.map → chunk-5VVB6N33.js.map} +0 -0
package/README.md
CHANGED
|
@@ -1,12 +1,26 @@
|
|
|
1
1
|
# @celestoai/sdk
|
|
2
2
|
|
|
3
|
-
Use this package to
|
|
4
|
-
|
|
3
|
+
Use this package to run work in Celesto from a Node.js app. Your code can create
|
|
4
|
+
a cloud computer, run commands in it, and delete it when the work is done.
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
An AI agent is software that can plan and run tasks. A harness is the code that
|
|
7
|
+
starts, tests, or supervises an agent.
|
|
7
8
|
|
|
8
|
-
|
|
9
|
-
|
|
9
|
+
Use this package when you want to:
|
|
10
|
+
|
|
11
|
+
- Run an AI agent or harness in a clean computer.
|
|
12
|
+
- Run shell commands from JavaScript or TypeScript.
|
|
13
|
+
- Keep agent work separate from your laptop, server, or production system.
|
|
14
|
+
- Ask a user to approve access to Google Drive through Gatekeeper.
|
|
15
|
+
|
|
16
|
+
Gatekeeper is Celesto's access helper. It lets a user approve which external
|
|
17
|
+
files or folders your app can use.
|
|
18
|
+
|
|
19
|
+
## Requirements
|
|
20
|
+
|
|
21
|
+
- Node.js 18 or newer.
|
|
22
|
+
- A Celesto API key from [Celesto Settings](https://celesto.ai) under
|
|
23
|
+
**Settings > Security**.
|
|
10
24
|
|
|
11
25
|
## Install
|
|
12
26
|
|
|
@@ -14,80 +28,219 @@ It includes:
|
|
|
14
28
|
npm install @celestoai/sdk
|
|
15
29
|
```
|
|
16
30
|
|
|
31
|
+
Sign in once with the Celesto CLI:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install celesto
|
|
35
|
+
celesto auth login
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The `Computer` API checks an explicitly passed `token` or `apiKey` first, then `CELESTO_API_KEY` in the shell, the current project's `.env`, and credentials saved by `celesto auth login`. You can use a local `.env` instead of the CLI:
|
|
39
|
+
|
|
40
|
+
```bash .env
|
|
41
|
+
CELESTO_API_KEY="your-api-key"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Add `.env` to `.gitignore`.
|
|
45
|
+
|
|
17
46
|
## Quickstart
|
|
18
47
|
|
|
19
|
-
|
|
20
|
-
import { Celesto } from "@celestoai/sdk";
|
|
48
|
+
Create a file named `quickstart.mjs`:
|
|
21
49
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
// organizationId: "org_123", // optional, for JWTs with multiple orgs
|
|
25
|
-
});
|
|
50
|
+
```js
|
|
51
|
+
import { Computer } from "@celestoai/sdk";
|
|
26
52
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
await
|
|
53
|
+
const computer = await Computer.create();
|
|
54
|
+
try {
|
|
55
|
+
console.log(`Computer ready: ${computer.name}`);
|
|
56
|
+
|
|
57
|
+
const result = await computer.run("uname -a");
|
|
58
|
+
console.log(result.stdout);
|
|
59
|
+
} finally {
|
|
60
|
+
await computer.delete();
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Run it:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
node quickstart.mjs
|
|
32
68
|
```
|
|
33
69
|
|
|
34
70
|
## Computers
|
|
35
71
|
|
|
36
|
-
|
|
37
|
-
|
|
72
|
+
A computer is a disposable cloud machine for your app or agent. By default,
|
|
73
|
+
Celesto creates a `scratch` computer, which is a minimal Ubuntu computer.
|
|
38
74
|
|
|
39
|
-
###
|
|
75
|
+
### Create with Custom Resources
|
|
40
76
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
77
|
+
Create a file named `create-computer.mjs`:
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
import { Computer } from "@celestoai/sdk";
|
|
81
|
+
|
|
82
|
+
const computer = await Computer.create({
|
|
44
83
|
cpus: 2,
|
|
45
84
|
memory: 2048,
|
|
46
|
-
|
|
85
|
+
disk: "15gb",
|
|
47
86
|
});
|
|
48
87
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
88
|
+
try {
|
|
89
|
+
console.log(computer.name, computer["name"]);
|
|
90
|
+
} finally {
|
|
91
|
+
await computer.delete();
|
|
92
|
+
}
|
|
54
93
|
```
|
|
55
94
|
|
|
56
|
-
Omit CPU, memory, or disk fields to use the
|
|
95
|
+
Omit CPU, memory, or disk fields to use the default size. `disk` accepts MB as
|
|
96
|
+
an integer or strings such as `"2gb"`.
|
|
97
|
+
|
|
98
|
+
### Templates
|
|
57
99
|
|
|
58
|
-
|
|
59
|
-
|
|
100
|
+
Use a template when you want a computer that already has extra tools installed.
|
|
101
|
+
For example, `coding-agent` includes common tools for coding tasks.
|
|
102
|
+
|
|
103
|
+
List available templates:
|
|
104
|
+
|
|
105
|
+
Create a file named `list-templates.mjs`:
|
|
106
|
+
|
|
107
|
+
```js
|
|
108
|
+
import { Computer } from "@celestoai/sdk";
|
|
109
|
+
|
|
110
|
+
const templates = await Computer.listTemplates();
|
|
60
111
|
for (const template of templates) {
|
|
61
112
|
console.log(template.id, template.defaultRamMb);
|
|
62
113
|
}
|
|
63
114
|
```
|
|
64
115
|
|
|
65
|
-
|
|
116
|
+
Create a computer from a template:
|
|
117
|
+
|
|
118
|
+
```js
|
|
119
|
+
import { Computer } from "@celestoai/sdk";
|
|
120
|
+
|
|
121
|
+
const computer = await Computer.create({ templateId: "coding-agent" });
|
|
122
|
+
try {
|
|
123
|
+
console.log(computer.name);
|
|
124
|
+
} finally {
|
|
125
|
+
await computer.delete();
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Run a Command
|
|
130
|
+
|
|
131
|
+
Create a file named `run-command.mjs`:
|
|
132
|
+
|
|
133
|
+
```js
|
|
134
|
+
import { Computer } from "@celestoai/sdk";
|
|
135
|
+
|
|
136
|
+
const computer = await Computer.create();
|
|
137
|
+
try {
|
|
138
|
+
const result = await computer.run("ls -la", {
|
|
139
|
+
timeout: 60,
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
console.log(result.exitCode);
|
|
143
|
+
console.log(result.stdout);
|
|
144
|
+
console.error(result.stderr);
|
|
145
|
+
} finally {
|
|
146
|
+
await computer.delete();
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Stream output while the command is running:
|
|
151
|
+
|
|
152
|
+
```js
|
|
153
|
+
import { Computer } from "@celestoai/sdk";
|
|
66
154
|
|
|
67
|
-
|
|
68
|
-
const
|
|
69
|
-
|
|
155
|
+
const computer = await Computer.get("curie");
|
|
156
|
+
const controller = new AbortController();
|
|
157
|
+
|
|
158
|
+
for await (const event of computer.runStream("npm test", {
|
|
159
|
+
timeout: 300,
|
|
160
|
+
signal: controller.signal,
|
|
161
|
+
})) {
|
|
162
|
+
if (event.type === "stdout") process.stdout.write(event.data);
|
|
163
|
+
if (event.type === "stderr") process.stderr.write(event.data);
|
|
164
|
+
if (event.type === "exit") console.log(`Exit code: ${event.exitCode}`);
|
|
165
|
+
}
|
|
70
166
|
```
|
|
71
167
|
|
|
72
|
-
|
|
168
|
+
Call `controller.abort()` to stop the stream and the remote command.
|
|
169
|
+
|
|
170
|
+
### Manage Computers
|
|
171
|
+
|
|
172
|
+
`computerId` can be `computer.id` from `Computer.create()` or a computer name
|
|
173
|
+
shown by the Celesto command-line tool: `celesto computer list`.
|
|
174
|
+
|
|
175
|
+
| Method | What it does |
|
|
176
|
+
| --- | --- |
|
|
177
|
+
| `Computer.list()` | List computers in your account |
|
|
178
|
+
| `Computer.get(computerId)` | Get one computer by name or ID |
|
|
179
|
+
| `computer.listCommandHistory()` | List recent commands and their status |
|
|
180
|
+
| `computer.stop()` | Stop a running computer |
|
|
181
|
+
| `computer.start()` | Start a stopped computer |
|
|
182
|
+
| `computer.delete()` | Delete a computer |
|
|
183
|
+
|
|
184
|
+
### Publish Ports
|
|
185
|
+
|
|
186
|
+
Publish a port when a service inside the computer needs a public URL:
|
|
187
|
+
|
|
188
|
+
```js
|
|
189
|
+
import { Computer } from "@celestoai/sdk";
|
|
190
|
+
|
|
191
|
+
const computer = await Computer.get("curie");
|
|
192
|
+
const url = await computer.publishPort(8000);
|
|
193
|
+
console.log(url);
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
List and remove published ports:
|
|
197
|
+
|
|
198
|
+
```js
|
|
199
|
+
import { Computer } from "@celestoai/sdk";
|
|
200
|
+
|
|
201
|
+
const computer = await Computer.get("curie");
|
|
202
|
+
console.log(await computer.listPublishedPorts());
|
|
203
|
+
await computer.unpublishPort(8000);
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
### Terminal Connections
|
|
207
|
+
|
|
208
|
+
Use `createTerminalSession()` when you are building an interactive terminal.
|
|
209
|
+
Celesto returns a short-lived URL that connects directly to the fast terminal
|
|
210
|
+
gateway instead of sending terminal traffic through the control plane. Creating
|
|
211
|
+
a terminal session requires write access to the computer.
|
|
73
212
|
|
|
74
|
-
|
|
75
|
-
to open a WebSocket terminal with any library of your choice. No built-in WebSocket
|
|
76
|
-
dependency — bring your own.
|
|
213
|
+
For Node.js, first install a WebSocket client:
|
|
77
214
|
|
|
78
|
-
```
|
|
79
|
-
|
|
215
|
+
```bash
|
|
216
|
+
npm install ws
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Then connect with the authenticated URL:
|
|
80
220
|
|
|
81
|
-
|
|
221
|
+
```js
|
|
222
|
+
import { Computer } from "@celestoai/sdk";
|
|
82
223
|
import WebSocket from "ws";
|
|
83
|
-
|
|
84
|
-
|
|
224
|
+
|
|
225
|
+
const computer = await Computer.get("curie");
|
|
226
|
+
const connection = await computer.createTerminalSession();
|
|
227
|
+
const ws = new WebSocket(connection.url);
|
|
228
|
+
|
|
85
229
|
ws.on("message", (data) => process.stdout.write(data));
|
|
230
|
+
ws.on("open", () => ws.send("pwd\n"));
|
|
86
231
|
```
|
|
87
232
|
|
|
233
|
+
`connection.url` contains a short-lived terminal token. Treat it as a secret and
|
|
234
|
+
create a new terminal session after `connection.expiresAt`.
|
|
235
|
+
|
|
88
236
|
## Gatekeeper
|
|
89
237
|
|
|
90
|
-
|
|
238
|
+
Use Gatekeeper when your app needs user-approved access to an external resource,
|
|
239
|
+
such as Google Drive.
|
|
240
|
+
|
|
241
|
+
Create a file named `gatekeeper-connect.mjs`:
|
|
242
|
+
|
|
243
|
+
```js
|
|
91
244
|
import { GatekeeperClient } from "@celestoai/sdk/gatekeeper";
|
|
92
245
|
|
|
93
246
|
const client = new GatekeeperClient({ token: process.env.CELESTO_API_KEY });
|
|
@@ -99,18 +252,55 @@ const connect = await client.connect({
|
|
|
99
252
|
});
|
|
100
253
|
|
|
101
254
|
if (connect.status === "redirect") {
|
|
102
|
-
console.log(
|
|
255
|
+
console.log(connect.oauthUrl);
|
|
256
|
+
} else {
|
|
257
|
+
console.log(connect.status);
|
|
103
258
|
}
|
|
104
259
|
```
|
|
105
260
|
|
|
106
|
-
|
|
261
|
+
If the response prints a URL, open it so the user can approve access.
|
|
262
|
+
|
|
263
|
+
Full Gatekeeper docs: https://docs.celesto.ai/celesto-sdk/gatekeeper
|
|
264
|
+
|
|
265
|
+
## Configuration
|
|
107
266
|
|
|
108
|
-
|
|
267
|
+
| Option | What it does |
|
|
268
|
+
| --- | --- |
|
|
269
|
+
| `token` | Celesto API key or JWT |
|
|
270
|
+
| `apiKey` | Alias for `token` |
|
|
271
|
+
| `baseUrl` | Custom Celesto API URL |
|
|
272
|
+
| `organizationId` | Sends the `X-Current-Organization` header |
|
|
273
|
+
| `timeoutMs` | Request timeout in milliseconds |
|
|
274
|
+
| `headers` | Extra headers to send with every request |
|
|
109
275
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
276
|
+
Pass these options as the second argument to `Computer.create()` or
|
|
277
|
+
`Computer.get()`. An explicit `token` or `apiKey` takes precedence over local credential discovery. Gatekeeper clients accept the same options in their constructor and require an explicit token.
|
|
278
|
+
|
|
279
|
+
JWT is a signed login token. Most users should use a Celesto API key.
|
|
280
|
+
|
|
281
|
+
## Errors
|
|
282
|
+
|
|
283
|
+
The SDK exports these error classes:
|
|
284
|
+
|
|
285
|
+
| Error | When it is used |
|
|
286
|
+
| --- | --- |
|
|
287
|
+
| `CelestoApiError` | The API returns an error status |
|
|
288
|
+
| `CelestoNetworkError` | The network request fails |
|
|
289
|
+
| `CelestoError` | Base class for all SDK errors |
|
|
290
|
+
|
|
291
|
+
## Develop Locally
|
|
292
|
+
|
|
293
|
+
If you are contributing and have `npm` installed, run these commands from the
|
|
294
|
+
repository's `ts` directory:
|
|
295
|
+
|
|
296
|
+
```bash
|
|
297
|
+
npm install
|
|
298
|
+
npm test
|
|
299
|
+
npm run lint
|
|
300
|
+
npm run build
|
|
301
|
+
```
|
|
113
302
|
|
|
114
303
|
## License
|
|
115
304
|
|
|
116
|
-
Apache-2.0. The SDK is open source
|
|
305
|
+
Apache-2.0. The SDK is open source. Use of the Celesto platform is governed by
|
|
306
|
+
the Celesto Terms of Service: https://celesto.ai/legal/terms
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
buildRequestContext,
|
|
3
3
|
request
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-JS6BTDP5.js";
|
|
5
5
|
|
|
6
6
|
// src/gatekeeper/client.ts
|
|
7
7
|
var toConnectRequest = (payload) => ({
|
|
@@ -174,4 +174,4 @@ var GatekeeperClient = class {
|
|
|
174
174
|
export {
|
|
175
175
|
GatekeeperClient
|
|
176
176
|
};
|
|
177
|
-
//# sourceMappingURL=chunk-
|
|
177
|
+
//# sourceMappingURL=chunk-5VVB6N33.js.map
|
|
@@ -85,7 +85,7 @@ var extractErrorMessage = (data, status) => {
|
|
|
85
85
|
}
|
|
86
86
|
return `Request failed with status ${status}`;
|
|
87
87
|
};
|
|
88
|
-
var
|
|
88
|
+
var buildRequestInit = (ctx, options) => {
|
|
89
89
|
const url = `${joinUrl(ctx.baseUrl, options.path)}${buildQuery(options.query)}`;
|
|
90
90
|
const headers = {
|
|
91
91
|
...ctx.headers ?? {},
|
|
@@ -103,13 +103,16 @@ var request = async (ctx, options) => {
|
|
|
103
103
|
const init = {
|
|
104
104
|
method: options.method,
|
|
105
105
|
headers,
|
|
106
|
-
body: void 0,
|
|
107
106
|
signal: options.signal
|
|
108
107
|
};
|
|
109
108
|
if (options.body !== void 0) {
|
|
110
109
|
headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
|
|
111
110
|
init.body = headers["Content-Type"].includes("application/json") ? JSON.stringify(options.body) : options.body;
|
|
112
111
|
}
|
|
112
|
+
return { url, init };
|
|
113
|
+
};
|
|
114
|
+
var request = async (ctx, options) => {
|
|
115
|
+
const { url, init } = buildRequestInit(ctx, options);
|
|
113
116
|
let timeoutId;
|
|
114
117
|
let controller;
|
|
115
118
|
if (!options.signal && ctx.timeoutMs && ctx.timeoutMs > 0) {
|
|
@@ -137,12 +140,36 @@ var request = async (ctx, options) => {
|
|
|
137
140
|
}
|
|
138
141
|
}
|
|
139
142
|
};
|
|
143
|
+
var requestStream = async (ctx, options) => {
|
|
144
|
+
const { url, init } = buildRequestInit(ctx, options);
|
|
145
|
+
try {
|
|
146
|
+
const response = await ctx.fetch(url, init);
|
|
147
|
+
if (!response.ok) {
|
|
148
|
+
const data = await parseResponseBody(response);
|
|
149
|
+
const message = extractErrorMessage(data, response.status);
|
|
150
|
+
throw new CelestoApiError(
|
|
151
|
+
message,
|
|
152
|
+
response.status,
|
|
153
|
+
data,
|
|
154
|
+
response.headers.get("x-request-id") ?? void 0
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
return response;
|
|
158
|
+
} catch (err) {
|
|
159
|
+
if (err instanceof CelestoApiError) {
|
|
160
|
+
throw err;
|
|
161
|
+
}
|
|
162
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
163
|
+
throw new CelestoNetworkError(error.message, error);
|
|
164
|
+
}
|
|
165
|
+
};
|
|
140
166
|
|
|
141
167
|
export {
|
|
142
168
|
buildRequestContext,
|
|
143
169
|
CelestoError,
|
|
144
170
|
CelestoApiError,
|
|
145
171
|
CelestoNetworkError,
|
|
146
|
-
request
|
|
172
|
+
request,
|
|
173
|
+
requestStream
|
|
147
174
|
};
|
|
148
|
-
//# sourceMappingURL=chunk-
|
|
175
|
+
//# sourceMappingURL=chunk-JS6BTDP5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/errors.ts","../src/core/config.ts","../src/core/http.ts"],"sourcesContent":["/** Base error for all Celesto SDK errors. */\nexport class CelestoError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CelestoError\";\n }\n}\n\n/** Thrown when an API request returns a non-2xx HTTP status. */\nexport class CelestoApiError extends CelestoError {\n readonly status: number;\n readonly data: unknown;\n readonly requestId?: string;\n\n constructor(message: string, status: number, data: unknown, requestId?: string) {\n super(message);\n this.name = \"CelestoApiError\";\n this.status = status;\n this.data = data;\n this.requestId = requestId;\n }\n}\n\n/** Thrown when fetch() itself fails — DNS, network, timeout, abort. */\nexport class CelestoNetworkError extends CelestoError {\n readonly cause?: Error;\n\n constructor(message: string, cause?: Error) {\n super(message);\n this.name = \"CelestoNetworkError\";\n this.cause = cause;\n }\n}\n","export type FetchLike = typeof fetch;\n\nexport interface ClientConfig {\n /** Base API URL, e.g. https://api.celesto.ai */\n baseUrl?: string;\n /** Bearer token (API key or JWT). */\n token?: string;\n /** Alias for token. */\n apiKey?: string;\n /** Organization ID to send as X-Current-Organization. */\n organizationId?: string;\n /** Optional user agent for server-side requests. */\n userAgent?: string;\n /** Default request timeout in milliseconds. */\n timeoutMs?: number;\n /** Override fetch implementation (useful for testing). */\n fetch?: FetchLike;\n /** Default headers to include in every request. */\n headers?: Record<string, string>;\n}\n\nexport interface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined | null | (string | number | boolean)[]>;\n body?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\nexport interface RequestOverrides {\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\nexport interface RequestContext {\n fetch: FetchLike;\n baseUrl: string;\n token?: string;\n organizationId?: string;\n userAgent?: string;\n timeoutMs?: number;\n headers?: Record<string, string>;\n}\n\nexport const DEFAULT_BASE_URL = \"https://api.celesto.ai\";\n\nexport const buildRequestContext = (config: ClientConfig): RequestContext => ({\n fetch: config.fetch ?? fetch,\n baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,\n token: config.token ?? config.apiKey,\n organizationId: config.organizationId,\n userAgent: config.userAgent,\n timeoutMs: config.timeoutMs,\n headers: config.headers,\n});\n","import { CelestoApiError, CelestoNetworkError } from \"./errors\";\nimport { RequestContext, RequestOptions } from \"./config\";\n\nconst joinUrl = (baseUrl: string, path: string): string => {\n const trimmedBase = baseUrl.endsWith(\"/\") ? baseUrl.slice(0, -1) : baseUrl;\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n return `${trimmedBase}${normalizedPath}`;\n};\n\nconst buildQuery = (\n query?: RequestOptions[\"query\"],\n): string => {\n if (!query) {\n return \"\";\n }\n\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) {\n continue;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n params.append(key, String(item));\n }\n continue;\n }\n params.set(key, String(value));\n }\n\n const serialized = params.toString();\n return serialized ? `?${serialized}` : \"\";\n};\n\nconst parseResponseBody = async (response: Response): Promise<unknown> => {\n if (response.status === 204) {\n return undefined;\n }\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\")) {\n return response.json();\n }\n\n return response.text();\n};\n\nconst extractErrorMessage = (data: unknown, status: number): string => {\n if (data && typeof data === \"object\") {\n const record = data as Record<string, unknown>;\n if (typeof record.detail === \"string\") {\n return record.detail;\n }\n if (typeof record.message === \"string\") {\n return record.message;\n }\n if (typeof record.error === \"string\") {\n return record.error;\n }\n }\n return `Request failed with status ${status}`;\n};\n\nconst buildRequestInit = (\n ctx: RequestContext,\n options: RequestOptions,\n): { url: string; init: RequestInit } => {\n const url = `${joinUrl(ctx.baseUrl, options.path)}${buildQuery(options.query)}`;\n const headers: Record<string, string> = {\n ...(ctx.headers ?? {}),\n ...(options.headers ?? {}),\n };\n\n if (ctx.token) {\n headers.Authorization = `Bearer ${ctx.token}`;\n }\n if (ctx.organizationId) {\n headers[\"X-Current-Organization\"] = ctx.organizationId;\n }\n if (ctx.userAgent && !headers[\"User-Agent\"]) {\n headers[\"User-Agent\"] = ctx.userAgent;\n }\n\n const init: RequestInit = {\n method: options.method,\n headers,\n signal: options.signal,\n };\n if (options.body !== undefined) {\n headers[\"Content-Type\"] = headers[\"Content-Type\"] ?? \"application/json\";\n init.body = headers[\"Content-Type\"].includes(\"application/json\")\n ? JSON.stringify(options.body)\n : (options.body as BodyInit);\n }\n return { url, init };\n};\n\nexport const request = async <T>(ctx: RequestContext, options: RequestOptions): Promise<T> => {\n const { url, init } = buildRequestInit(ctx, options);\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let controller: AbortController | undefined;\n\n if (!options.signal && ctx.timeoutMs && ctx.timeoutMs > 0) {\n controller = new AbortController();\n timeoutId = setTimeout(() => controller?.abort(), ctx.timeoutMs);\n init.signal = controller.signal;\n }\n\n try {\n const response = await ctx.fetch(url, init);\n const data = await parseResponseBody(response);\n\n if (!response.ok) {\n const message = extractErrorMessage(data, response.status);\n throw new CelestoApiError(message, response.status, data, response.headers.get(\"x-request-id\") ?? undefined);\n }\n\n return data as T;\n } catch (err) {\n if (err instanceof CelestoApiError) {\n throw err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n throw new CelestoNetworkError(error.message, error);\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n};\n\n/** Make an authenticated request without consuming its response body. */\nexport const requestStream = async (\n ctx: RequestContext,\n options: RequestOptions,\n): Promise<Response> => {\n const { url, init } = buildRequestInit(ctx, options);\n try {\n const response = await ctx.fetch(url, init);\n if (!response.ok) {\n const data = await parseResponseBody(response);\n const message = extractErrorMessage(data, response.status);\n throw new CelestoApiError(\n message,\n response.status,\n data,\n response.headers.get(\"x-request-id\") ?? undefined,\n );\n }\n return response;\n } catch (err) {\n if (err instanceof CelestoApiError) {\n throw err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n throw new CelestoNetworkError(error.message, error);\n }\n};\n"],"mappings":";AACO,IAAM,eAAN,cAA2B,MAAM;AAAA,EACtC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,kBAAN,cAA8B,aAAa;AAAA,EAKhD,YAAY,SAAiB,QAAgB,MAAe,WAAoB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