antarya 0.0.0-stage → 0.1.2

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/index.js ADDED
@@ -0,0 +1,511 @@
1
+ // src/errors.ts
2
+ var APIError = class extends Error {
3
+ status;
4
+ type;
5
+ requestId;
6
+ retryAfter;
7
+ constructor(message, init = {}) {
8
+ super(message);
9
+ this.name = new.target.name;
10
+ this.status = init.status;
11
+ this.type = init.type ?? "api_error";
12
+ this.requestId = init.requestId;
13
+ this.retryAfter = init.retryAfter;
14
+ }
15
+ };
16
+ var BadRequestError = class extends APIError {
17
+ };
18
+ var AuthenticationError = class extends APIError {
19
+ };
20
+ var PermissionDeniedError = class extends APIError {
21
+ };
22
+ var NotFoundError = class extends APIError {
23
+ };
24
+ var RequestTooLargeError = class extends APIError {
25
+ };
26
+ var RateLimitError = class extends APIError {
27
+ };
28
+ var InternalServerError = class extends APIError {
29
+ };
30
+ var OverloadedError = class extends APIError {
31
+ };
32
+ var APIConnectionError = class extends APIError {
33
+ constructor(message = "Could not reach the API.", init = {}) {
34
+ super(message, { type: "connection_error" });
35
+ if (init.cause !== void 0) this.cause = init.cause;
36
+ }
37
+ };
38
+ var APITimeoutError = class extends APIConnectionError {
39
+ constructor(message = "The request timed out.") {
40
+ super(message);
41
+ }
42
+ };
43
+ var BY_TYPE = {
44
+ invalid_request: BadRequestError,
45
+ authentication_error: AuthenticationError,
46
+ permission_error: PermissionDeniedError,
47
+ not_found: NotFoundError,
48
+ request_too_large: RequestTooLargeError,
49
+ rate_limit_error: RateLimitError,
50
+ api_error: InternalServerError,
51
+ overloaded: OverloadedError
52
+ };
53
+ var BY_STATUS = {
54
+ 400: "invalid_request",
55
+ 401: "authentication_error",
56
+ 403: "permission_error",
57
+ 404: "not_found",
58
+ 413: "request_too_large",
59
+ 429: "rate_limit_error",
60
+ 503: "overloaded"
61
+ };
62
+ function errorFrom(status, body, headers) {
63
+ const err = body && typeof body === "object" ? body.error : void 0;
64
+ const bodyId = body && typeof body === "object" ? body.request_id : void 0;
65
+ const type = typeof err?.type === "string" && err.type in BY_TYPE ? err.type : BY_STATUS[status] ?? "api_error";
66
+ const message = typeof err?.message === "string" && err.message ? err.message : `The API returned an error (${status}).`;
67
+ const requestId = typeof bodyId === "string" ? bodyId : headers.get("request-id") ?? void 0;
68
+ const ra = Number(headers.get("retry-after"));
69
+ const retryAfter = headers.get("retry-after") !== null && Number.isFinite(ra) && ra >= 0 ? ra : void 0;
70
+ return new BY_TYPE[type](message, { status, type, requestId, retryAfter });
71
+ }
72
+
73
+ // src/streaming.ts
74
+ async function* readLines(res, onReader) {
75
+ if (!res.body) return;
76
+ const reader = res.body.getReader();
77
+ onReader?.(reader);
78
+ const dec = new TextDecoder();
79
+ let buf = "";
80
+ try {
81
+ for (; ; ) {
82
+ const { done, value } = await reader.read();
83
+ if (done) break;
84
+ buf += dec.decode(value, { stream: true });
85
+ let m;
86
+ while (m = /\r\n|\n|\r/.exec(buf)) {
87
+ if (m[0] === "\r" && m.index === buf.length - 1) break;
88
+ yield buf.slice(0, m.index);
89
+ buf = buf.slice(m.index + m[0].length);
90
+ }
91
+ }
92
+ buf += dec.decode();
93
+ if (buf) yield buf;
94
+ } finally {
95
+ await reader.cancel().catch(() => {
96
+ });
97
+ }
98
+ }
99
+ var ChatStream = class {
100
+ /** onClose runs once, when the stream ends, fails, is left early or is stopped. */
101
+ constructor(res, controller, onClose) {
102
+ this.res = res;
103
+ this.controller = controller;
104
+ this.onClose = onClose;
105
+ this.requestId = res.headers.get("request-id") ?? void 0;
106
+ this.events = this.run();
107
+ }
108
+ res;
109
+ controller;
110
+ onClose;
111
+ requestId;
112
+ aborted = false;
113
+ reader;
114
+ events;
115
+ id = "";
116
+ model = "";
117
+ parts = [];
118
+ done;
119
+ [Symbol.asyncIterator]() {
120
+ return this.events;
121
+ }
122
+ /** Stops the stream. Iteration ends without an error. */
123
+ abort() {
124
+ this.aborted = true;
125
+ this.controller?.abort();
126
+ void this.reader?.cancel().catch(() => {
127
+ });
128
+ this.close();
129
+ }
130
+ close() {
131
+ const f = this.onClose;
132
+ this.onClose = void 0;
133
+ f?.();
134
+ }
135
+ /** Reads the rest of the stream and returns the assembled reply. */
136
+ async finalReply() {
137
+ for await (const _ of this.events) {
138
+ }
139
+ if (!this.done) throw new APIConnectionError(this.aborted ? "The stream was stopped." : "The stream ended before the reply was complete.");
140
+ return { id: this.id, model: this.model, content: this.parts.filter(Boolean), ...this.done };
141
+ }
142
+ async *run() {
143
+ let name = "";
144
+ let data = [];
145
+ try {
146
+ for await (const line of readLines(this.res, (r) => {
147
+ this.reader = r;
148
+ if (this.aborted) void r.cancel().catch(() => {
149
+ });
150
+ })) {
151
+ if (line === "") {
152
+ if (data.length) {
153
+ const ev = this.shape(name || "message", data.join("\n"));
154
+ name = "";
155
+ data = [];
156
+ if (ev) {
157
+ yield ev;
158
+ if (ev.type === "reply.done") return;
159
+ }
160
+ } else name = "";
161
+ continue;
162
+ }
163
+ if (line.startsWith(":")) continue;
164
+ const i = line.indexOf(":");
165
+ const field = i < 0 ? line : line.slice(0, i);
166
+ let val = i < 0 ? "" : line.slice(i + 1);
167
+ if (val.startsWith(" ")) val = val.slice(1);
168
+ if (field === "event") name = val;
169
+ else if (field === "data") data.push(val);
170
+ }
171
+ } catch (e) {
172
+ if (this.aborted) return;
173
+ if (e instanceof APIError) throw e;
174
+ throw new APIConnectionError("The stream was cut off.", { cause: e });
175
+ } finally {
176
+ this.close();
177
+ }
178
+ if (this.aborted) return;
179
+ if (!this.done) throw new APIConnectionError("The stream ended before the reply was complete.");
180
+ }
181
+ shape(name, raw) {
182
+ let d;
183
+ try {
184
+ d = JSON.parse(raw);
185
+ } catch {
186
+ return void 0;
187
+ }
188
+ if (!d || typeof d !== "object") return void 0;
189
+ switch (name) {
190
+ case "reply.start":
191
+ this.id = String(d.id ?? "");
192
+ this.model = String(d.model ?? "");
193
+ return { ...d, type: "reply.start" };
194
+ case "content.delta": {
195
+ const { index, ...part } = d;
196
+ const ev = { type: "content.delta", index, part };
197
+ if (part.type === "text" && typeof part.text === "string") {
198
+ ev.text = part.text;
199
+ const cur = this.parts[index];
200
+ if (cur && cur.type === "text") cur.text += part.text;
201
+ else this.parts[index] = { type: "text", text: part.text };
202
+ } else this.parts[index] = part;
203
+ return ev;
204
+ }
205
+ case "reply.done":
206
+ this.done = { stop_reason: d.stop_reason, usage: d.usage };
207
+ return { ...d, type: "reply.done" };
208
+ case "error": {
209
+ const err = errorFrom(this.res.status, "error" in d ? d : { error: d }, this.res.headers);
210
+ err.status = void 0;
211
+ throw err;
212
+ }
213
+ default:
214
+ return { ...d, type: name };
215
+ }
216
+ }
217
+ };
218
+
219
+ // src/resources/batches.ts
220
+ var Batches = class {
221
+ constructor(client) {
222
+ this.client = client;
223
+ }
224
+ client;
225
+ async create(p, opts = {}) {
226
+ return await this.client.request("POST", "/batches", { body: p, signal: opts.signal });
227
+ }
228
+ async get(id, opts = {}) {
229
+ return await this.client.request("GET", `/batches/${encodeURIComponent(id)}`, { signal: opts.signal });
230
+ }
231
+ async cancel(id, opts = {}) {
232
+ return await this.client.request("POST", `/batches/${encodeURIComponent(id)}/cancel`, { signal: opts.signal });
233
+ }
234
+ /** The finished results, one parsed line at a time. */
235
+ async *results(id, opts = {}) {
236
+ const res = await this.client.request("GET", `/batches/${encodeURIComponent(id)}/results`, { stream: true, signal: opts.signal });
237
+ for await (const line of readLines(res)) {
238
+ if (line.trim()) yield JSON.parse(line);
239
+ }
240
+ }
241
+ };
242
+
243
+ // src/resources/chat.ts
244
+ var Chat = class {
245
+ constructor(client) {
246
+ this.client = client;
247
+ }
248
+ client;
249
+ async create(p, opts = {}) {
250
+ if (p.stream) return this.stream(p, opts);
251
+ return await this.client.request("POST", "/chat", { body: p, signal: opts.signal });
252
+ }
253
+ /** Starts a streamed reply. Call `abort()` on the result to stop it. */
254
+ async stream(p, opts = {}) {
255
+ const ctl = new AbortController();
256
+ const link = () => ctl.abort();
257
+ const unlink = () => opts.signal?.removeEventListener("abort", link);
258
+ if (opts.signal?.aborted) ctl.abort();
259
+ else opts.signal?.addEventListener("abort", link, { once: true });
260
+ try {
261
+ const res = await this.client.request("POST", "/chat", { body: { ...p, stream: true }, stream: true, signal: ctl.signal });
262
+ return new ChatStream(res, ctl, unlink);
263
+ } catch (e) {
264
+ unlink();
265
+ ctl.abort();
266
+ throw e;
267
+ }
268
+ }
269
+ async countTokens(p, opts = {}) {
270
+ return await this.client.request("POST", "/count-tokens", { body: p, signal: opts.signal });
271
+ }
272
+ };
273
+
274
+ // src/resources/paging.ts
275
+ function pageQuery(p) {
276
+ const q = new URLSearchParams();
277
+ if (p.limit !== void 0) q.set("limit", String(p.limit));
278
+ if (p.after !== void 0 && p.after !== "") q.set("after", p.after);
279
+ const s = q.toString();
280
+ return s ? `?${s}` : "";
281
+ }
282
+
283
+ // src/resources/files.ts
284
+ var isPathStream = (f) => !!f && typeof f === "object" && typeof f.path === "string" && Symbol.asyncIterator in f;
285
+ var baseName = (p) => p.split(/[\\/]/).filter(Boolean).pop() ?? "file";
286
+ var Files = class {
287
+ constructor(client) {
288
+ this.client = client;
289
+ }
290
+ client;
291
+ async create(p, opts = {}) {
292
+ const f = p.file;
293
+ let blob;
294
+ let name = p.filename;
295
+ if (f instanceof Blob) {
296
+ blob = f;
297
+ name ??= f.name;
298
+ } else if (f instanceof ArrayBuffer) blob = new Blob([f]);
299
+ else if (f instanceof Uint8Array) blob = new Blob([f]);
300
+ else if (isPathStream(f)) {
301
+ const chunks = [];
302
+ for await (const c of f) chunks.push(typeof c === "string" ? c : c);
303
+ blob = new Blob(chunks);
304
+ name ??= baseName(f.path);
305
+ } else throw new TypeError("file must be a Blob, File, Uint8Array, ArrayBuffer or ReadStream.");
306
+ if (p.media_type) blob = new Blob([blob], { type: p.media_type });
307
+ const form = new FormData();
308
+ form.append("file", blob, name ?? "file");
309
+ return await this.client.request("POST", "/files", { form, signal: opts.signal });
310
+ }
311
+ async list(params = {}, opts = {}) {
312
+ return await this.client.request("GET", `/files${pageQuery(params)}`, { signal: opts.signal });
313
+ }
314
+ async get(id, opts = {}) {
315
+ return await this.client.request("GET", `/files/${encodeURIComponent(id)}`, { signal: opts.signal });
316
+ }
317
+ async delete(id, opts = {}) {
318
+ return await this.client.request("DELETE", `/files/${encodeURIComponent(id)}`, { signal: opts.signal });
319
+ }
320
+ };
321
+
322
+ // src/resources/models.ts
323
+ var Models = class {
324
+ constructor(client) {
325
+ this.client = client;
326
+ }
327
+ client;
328
+ async list(opts = {}) {
329
+ return await this.client.request("GET", "/models", { signal: opts.signal });
330
+ }
331
+ async get(id, opts = {}) {
332
+ return await this.client.request("GET", `/models/${encodeURIComponent(id)}`, { signal: opts.signal });
333
+ }
334
+ };
335
+
336
+ // src/resources/sessions.ts
337
+ var Sessions = class {
338
+ constructor(client) {
339
+ this.client = client;
340
+ }
341
+ client;
342
+ async create(p = {}, opts = {}) {
343
+ return await this.client.request("POST", "/sessions", { body: p, signal: opts.signal });
344
+ }
345
+ async list(params = {}, opts = {}) {
346
+ return await this.client.request("GET", `/sessions${pageQuery(params)}`, { signal: opts.signal });
347
+ }
348
+ async get(id, opts = {}) {
349
+ return await this.client.request("GET", `/sessions/${encodeURIComponent(id)}`, { signal: opts.signal });
350
+ }
351
+ async delete(id, opts = {}) {
352
+ return await this.client.request("DELETE", `/sessions/${encodeURIComponent(id)}`, { signal: opts.signal });
353
+ }
354
+ };
355
+
356
+ // src/client.ts
357
+ var DEFAULT_BASE_URL = "https://antarya.ai/v1";
358
+ var RETRY_STATUS = /* @__PURE__ */ new Set([429, 500, 503]);
359
+ var MAX_RETRY_AFTER_S = 60;
360
+ var realSleep = (ms, signal) => new Promise((resolve) => {
361
+ if (signal?.aborted) return resolve();
362
+ const done = () => {
363
+ clearTimeout(t);
364
+ signal?.removeEventListener("abort", done);
365
+ resolve();
366
+ };
367
+ const t = setTimeout(done, ms);
368
+ signal?.addEventListener("abort", done, { once: true });
369
+ });
370
+ var Antarya = class {
371
+ static APIError = APIError;
372
+ static BadRequestError = BadRequestError;
373
+ static AuthenticationError = AuthenticationError;
374
+ static PermissionDeniedError = PermissionDeniedError;
375
+ static NotFoundError = NotFoundError;
376
+ static RequestTooLargeError = RequestTooLargeError;
377
+ static RateLimitError = RateLimitError;
378
+ static InternalServerError = InternalServerError;
379
+ static OverloadedError = OverloadedError;
380
+ static APIConnectionError = APIConnectionError;
381
+ static APITimeoutError = APITimeoutError;
382
+ #apiKey;
383
+ baseURL;
384
+ maxRetries;
385
+ timeout;
386
+ chat = new Chat(this);
387
+ models = new Models(this);
388
+ files = new Files(this);
389
+ batches = new Batches(this);
390
+ sessions = new Sessions(this);
391
+ fetchFn;
392
+ sleep;
393
+ constructor(opts = {}) {
394
+ const env = globalThis.process?.env;
395
+ this.#apiKey = opts.apiKey ?? env?.ANTARYA_API_KEY;
396
+ this.baseURL = (opts.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
397
+ this.maxRetries = opts.maxRetries ?? 2;
398
+ this.timeout = opts.timeout ?? 6e5;
399
+ this.sleep = opts.sleep ?? realSleep;
400
+ this.fetchFn = opts.fetch ?? ((...a) => globalThis.fetch(...a));
401
+ }
402
+ /** The key in use. A getter, so it is not listed by JSON.stringify or console.log. */
403
+ get apiKey() {
404
+ return this.#apiKey;
405
+ }
406
+ /** Keeps the key and the circular resource links out of JSON.stringify. */
407
+ toJSON() {
408
+ return { baseURL: this.baseURL };
409
+ }
410
+ async request(method, path, opts = {}) {
411
+ const useAuth = opts.auth !== false;
412
+ if (useAuth && !this.#apiKey) throw new AuthenticationError("No API key. Set ANTARYA_API_KEY or pass apiKey.", { type: "authentication_error" });
413
+ const headers = {};
414
+ if (useAuth) headers.authorization = `Bearer ${this.#apiKey}`;
415
+ let body;
416
+ if (opts.form) body = opts.form;
417
+ else if (opts.body !== void 0) {
418
+ headers["content-type"] = "application/json";
419
+ body = JSON.stringify(opts.body);
420
+ }
421
+ const url = this.baseURL + (path.startsWith("/") ? path : `/${path}`);
422
+ for (let attempt = 0; ; attempt++) {
423
+ let wait;
424
+ let failure;
425
+ const ctl = new AbortController();
426
+ let timedOut = false;
427
+ const timer = setTimeout(() => {
428
+ timedOut = true;
429
+ ctl.abort();
430
+ }, this.timeout);
431
+ let keepLink = false;
432
+ const onAbort = () => ctl.abort();
433
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
434
+ try {
435
+ if (opts.signal?.aborted) ctl.abort();
436
+ const res = await this.fetchFn(url, { method, headers, body, signal: ctl.signal });
437
+ clearTimeout(timer);
438
+ if (res.ok) {
439
+ if (!opts.stream) return await res.json();
440
+ if (!opts.signal) return res;
441
+ keepLink = true;
442
+ return releaseOnEnd(res, () => opts.signal.removeEventListener("abort", onAbort));
443
+ }
444
+ const parsed = await res.json().catch(() => void 0);
445
+ failure = errorFrom(res.status, parsed, res.headers);
446
+ if (!RETRY_STATUS.has(res.status)) throw failure;
447
+ if (failure.retryAfter !== void 0) wait = Math.min(failure.retryAfter, MAX_RETRY_AFTER_S) * 1e3;
448
+ } catch (e) {
449
+ clearTimeout(timer);
450
+ if (e instanceof APIError && !(e instanceof APIConnectionError)) throw e;
451
+ if (opts.signal?.aborted) throw e;
452
+ failure = timedOut ? new APITimeoutError() : new APIConnectionError("Could not reach the API.", { cause: e });
453
+ } finally {
454
+ if (!keepLink) opts.signal?.removeEventListener("abort", onAbort);
455
+ }
456
+ if (attempt >= this.maxRetries) throw failure;
457
+ await this.sleep(wait ?? Math.min(8e3, 500 * 2 ** attempt) * (0.75 + Math.random() * 0.5), opts.signal);
458
+ if (opts.signal?.aborted) throw failure;
459
+ }
460
+ }
461
+ };
462
+ function releaseOnEnd(res, release) {
463
+ const reader = res.body?.getReader();
464
+ if (!reader) {
465
+ release();
466
+ return res;
467
+ }
468
+ const body = new ReadableStream({
469
+ async pull(c) {
470
+ try {
471
+ const { done, value } = await reader.read();
472
+ if (done) {
473
+ release();
474
+ c.close();
475
+ } else c.enqueue(value);
476
+ } catch (e) {
477
+ release();
478
+ c.error(e);
479
+ }
480
+ },
481
+ cancel(reason) {
482
+ release();
483
+ return reader.cancel(reason);
484
+ }
485
+ });
486
+ return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers });
487
+ }
488
+
489
+ // src/types.ts
490
+ var ARTIFACT_KINDS = ["workbook", "table", "chart", "report"];
491
+
492
+ // src/index.ts
493
+ var index_default = Antarya;
494
+ export {
495
+ APIConnectionError,
496
+ APIError,
497
+ APITimeoutError,
498
+ ARTIFACT_KINDS,
499
+ Antarya,
500
+ AuthenticationError,
501
+ BadRequestError,
502
+ ChatStream,
503
+ InternalServerError,
504
+ NotFoundError,
505
+ OverloadedError,
506
+ PermissionDeniedError,
507
+ RateLimitError,
508
+ RequestTooLargeError,
509
+ index_default as default,
510
+ errorFrom
511
+ };
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "antarya",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "license": "MIT",
5
+ "description": "TypeScript SDK for the Antarya API",
6
+ "type": "module",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "import": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "require": {
17
+ "types": "./dist/index.d.cts",
18
+ "default": "./dist/index.cjs"
19
+ }
20
+ }
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "engines": {
26
+ "node": ">=18"
27
+ },
28
+ "scripts": {
29
+ "build": "tsup",
30
+ "test": "vitest run",
31
+ "typecheck": "tsc --noEmit"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^26.6.11",
35
+ "tsup": "^9.0.0",
36
+ "typescript": "^5.9.3",
37
+ "vitest": "^5.1.2"
38
+ }
39
+ }