exa-js 2.5.1-beta.2 → 2.5.1-beta.3

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.mjs CHANGED
@@ -4,7 +4,7 @@ import fetch2, { Headers } from "cross-fetch";
4
4
  // package.json
5
5
  var package_default = {
6
6
  name: "exa-js",
7
- version: "2.5.1-beta.2",
7
+ version: "2.5.1-beta.3",
8
8
  description: "Exa SDK for Node.js and the browser",
9
9
  publishConfig: {
10
10
  access: "public"
@@ -176,6 +176,29 @@ var EventsClient = class extends WebsetsBaseClient {
176
176
  async get(id) {
177
177
  return this.request(`/v0/events/${id}`, "GET");
178
178
  }
179
+ /** Iterate through all events, handling pagination automatically. */
180
+ async *listAll(options) {
181
+ let cursor = void 0;
182
+ const pageOptions = options ? { ...options } : {};
183
+ while (true) {
184
+ const response = await this.list({ ...pageOptions, cursor });
185
+ for (const event of response.data) {
186
+ yield event;
187
+ }
188
+ if (!response.hasMore || !response.nextCursor) {
189
+ break;
190
+ }
191
+ cursor = response.nextCursor;
192
+ }
193
+ }
194
+ /** Collect all events into an array. */
195
+ async getAll(options) {
196
+ const events = [];
197
+ for await (const event of this.listAll(options)) {
198
+ events.push(event);
199
+ }
200
+ return events;
201
+ }
179
202
  };
180
203
  var WebsetMonitorRunsClient = class extends WebsetsBaseClient {
181
204
  async list(monitorId) {
@@ -251,6 +274,52 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
251
274
  const queryParams = { ...this.buildPaginationParams(options), eventType: options?.eventType, successful: options?.successful };
252
275
  return this.request(`/v0/webhooks/${id}/attempts`, "GET", void 0, queryParams);
253
276
  }
277
+ /** Iterate through all webhooks, handling pagination automatically. */
278
+ async *listAll(options) {
279
+ let cursor = void 0;
280
+ const pageOptions = options ? { ...options } : {};
281
+ while (true) {
282
+ const response = await this.list({ ...pageOptions, cursor });
283
+ for (const webhook of response.data) {
284
+ yield webhook;
285
+ }
286
+ if (!response.hasMore || !response.nextCursor) {
287
+ break;
288
+ }
289
+ cursor = response.nextCursor;
290
+ }
291
+ }
292
+ /** Collect all webhooks into an array. */
293
+ async getAll(options) {
294
+ const webhooks = [];
295
+ for await (const webhook of this.listAll(options)) {
296
+ webhooks.push(webhook);
297
+ }
298
+ return webhooks;
299
+ }
300
+ /** Iterate through all webhook attempts, handling pagination automatically. */
301
+ async *listAllAttempts(id, options) {
302
+ let cursor = void 0;
303
+ const pageOptions = options ? { ...options } : {};
304
+ while (true) {
305
+ const response = await this.listAttempts(id, { ...pageOptions, cursor });
306
+ for (const attempt of response.data) {
307
+ yield attempt;
308
+ }
309
+ if (!response.hasMore || !response.nextCursor) {
310
+ break;
311
+ }
312
+ cursor = response.nextCursor;
313
+ }
314
+ }
315
+ /** Collect all webhook attempts into an array. */
316
+ async getAllAttempts(id, options) {
317
+ const attempts = [];
318
+ for await (const attempt of this.listAllAttempts(id, options)) {
319
+ attempts.push(attempt);
320
+ }
321
+ return attempts;
322
+ }
254
323
  };
255
324
  var ImportsClient = class extends WebsetsBaseClient {
256
325
  async create(params) {
@@ -269,6 +338,51 @@ var ImportsClient = class extends WebsetsBaseClient {
269
338
  async delete(id) {
270
339
  return this.request(`/v0/imports/${id}`, "DELETE");
271
340
  }
341
+ /** Wait for an import to reach a terminal status. */
342
+ async waitUntilCompleted(id, options) {
343
+ const timeout = options?.timeout ?? 30 * 60 * 1e3;
344
+ const pollInterval = options?.pollInterval ?? 2e3;
345
+ const startTime = Date.now();
346
+ while (true) {
347
+ const importItem = await this.get(id);
348
+ if (options?.onPoll) {
349
+ options.onPoll(importItem.status);
350
+ }
351
+ if (importItem.status === "completed") {
352
+ return importItem;
353
+ }
354
+ if (importItem.status === "failed") {
355
+ throw new Error(`Import ${id} failed: ${importItem.failedMessage ?? "Unknown error"}`);
356
+ }
357
+ if (Date.now() - startTime > timeout) {
358
+ throw new Error(`Import ${id} did not complete within ${timeout}ms. Current status: ${importItem.status}`);
359
+ }
360
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
361
+ }
362
+ }
363
+ /** Iterate through all imports, handling pagination automatically. */
364
+ async *listAll(options) {
365
+ let cursor = void 0;
366
+ const pageOptions = options ? { ...options } : {};
367
+ while (true) {
368
+ const response = await this.list({ ...pageOptions, cursor });
369
+ for (const importItem of response.data) {
370
+ yield importItem;
371
+ }
372
+ if (!response.hasMore || !response.nextCursor) {
373
+ break;
374
+ }
375
+ cursor = response.nextCursor;
376
+ }
377
+ }
378
+ /** Collect all imports into an array. */
379
+ async getAll(options) {
380
+ const imports = [];
381
+ for await (const importItem of this.listAll(options)) {
382
+ imports.push(importItem);
383
+ }
384
+ return imports;
385
+ }
272
386
  };
273
387
  var WebsetsClient = class extends WebsetsBaseClient {
274
388
  constructor(client) {
@@ -396,10 +510,75 @@ var ResearchClient = class extends ResearchBaseClient {
396
510
  }
397
511
  return this.client.request("/research/v1", "POST", payload, void 0);
398
512
  }
399
- /** Get a research request by ID. */
400
513
  async get(researchId, options) {
401
514
  const params = {};
402
515
  if (options?.events !== void 0) params.events = options.events.toString();
516
+ if (options?.stream) {
517
+ params.stream = "true";
518
+ const response = await this.client.rawRequest(`/research/v1/${researchId}`, "GET", void 0, params);
519
+ if (!response.ok) {
520
+ const message = await response.text();
521
+ throw new Error(`Research stream request failed (${response.status}): ${message}`);
522
+ }
523
+ const reader = response.body?.getReader();
524
+ if (!reader) {
525
+ throw new Error("No response body for SSE stream");
526
+ }
527
+ const streamReader = reader;
528
+ const decoder = new TextDecoder();
529
+ let buffer = "";
530
+ const parseSseChunk = (chunk) => {
531
+ const lines = chunk.split("\n");
532
+ const dataLines = [];
533
+ for (const line of lines) {
534
+ if (line.startsWith("data:")) {
535
+ dataLines.push(line.replace(/^data:\s*/, ""));
536
+ }
537
+ }
538
+ const payload = dataLines.join("\n").trim();
539
+ if (payload.length === 0 || payload === "[DONE]") {
540
+ return null;
541
+ }
542
+ try {
543
+ const parsed = JSON.parse(payload);
544
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
545
+ return null;
546
+ }
547
+ const event = {};
548
+ for (const [key, value] of Object.entries(parsed)) {
549
+ event[key] = value;
550
+ }
551
+ return event;
552
+ } catch {
553
+ return null;
554
+ }
555
+ };
556
+ async function* streamEvents() {
557
+ while (true) {
558
+ const { done, value } = await streamReader.read();
559
+ if (done) break;
560
+ buffer += decoder.decode(value, { stream: true });
561
+ const parts = buffer.split("\n\n");
562
+ buffer = parts.pop() ?? "";
563
+ for (const part of parts) {
564
+ const event = parseSseChunk(part);
565
+ if (event != null) {
566
+ yield event;
567
+ }
568
+ }
569
+ }
570
+ if (buffer.trim().length > 0) {
571
+ const event = parseSseChunk(buffer.trim());
572
+ if (event != null) {
573
+ yield event;
574
+ }
575
+ }
576
+ }
577
+ return streamEvents();
578
+ }
579
+ if (options?.stream === false) {
580
+ params.stream = "false";
581
+ }
403
582
  return this.client.request(`/research/v1/${researchId}`, "GET", void 0, params);
404
583
  }
405
584
  /** Poll a research request until it reaches a terminal state (completed, failed, or canceled). */
@@ -431,9 +610,21 @@ var ResearchClient = class extends ResearchBaseClient {
431
610
  };
432
611
 
433
612
  // src/nova/client.ts
613
+ import { ZodType as ZodType2 } from "zod";
614
+ import { zodToJsonSchema as zodToJsonSchemaLib2 } from "zod-to-json-schema";
434
615
  function isRecord(value) {
435
616
  return value != null && typeof value === "object" && !Array.isArray(value);
436
617
  }
618
+ function isZodSchema(value) {
619
+ return value instanceof ZodType2;
620
+ }
621
+ function zodToJsonSchema2(schema) {
622
+ const converted = zodToJsonSchemaLib2(schema, { $refStrategy: "none" });
623
+ if (!isRecord(converted)) {
624
+ throw new Error("Failed to convert Zod schema to JSON Schema.");
625
+ }
626
+ return converted;
627
+ }
437
628
  var ExaError = class extends Error {
438
629
  constructor(message, statusCode, timestamp, path, details) {
439
630
  super(message);
@@ -602,10 +793,7 @@ var Exa = class {
602
793
  if (content == null && (citations == null || citations.length === 0)) {
603
794
  return null;
604
795
  }
605
- return {
606
- ...content != null ? { content } : {},
607
- ...citations != null ? { citations } : {}
608
- };
796
+ return { content, citations };
609
797
  }
610
798
  /** Separate content-specific options from search/filter options. */
611
799
  extractContentsOptions(options) {
@@ -650,16 +838,49 @@ var Exa = class {
650
838
  return this.request("/findSimilar", "POST", body);
651
839
  }
652
840
  getContents(urls, options) {
653
- return this.request("/contents", "POST", { urls, ...options });
841
+ let requestUrls;
842
+ if (typeof urls === "string") {
843
+ requestUrls = [urls];
844
+ } else if (urls.length === 0) {
845
+ throw new ExaError("Must provide at least one URL", 400);
846
+ } else if (typeof urls[0] === "string") {
847
+ requestUrls = [];
848
+ for (const url of urls) {
849
+ if (typeof url !== "string") {
850
+ throw new ExaError("Expected all URLs to be strings or SearchResult objects with a url field", 400);
851
+ }
852
+ requestUrls.push(url);
853
+ }
854
+ } else {
855
+ requestUrls = [];
856
+ for (const result of urls) {
857
+ if (!isRecord(result) || typeof result.url !== "string") {
858
+ throw new ExaError("Expected all entries to have a string url field", 400);
859
+ }
860
+ requestUrls.push(result.url);
861
+ }
862
+ }
863
+ if (requestUrls.length === 0) {
864
+ throw new ExaError("Must provide at least one URL", 400);
865
+ }
866
+ return this.request("/contents", "POST", { urls: requestUrls, ...options });
654
867
  }
655
- answer(query, options) {
868
+ async answer(query, options) {
656
869
  if (options?.stream) {
657
870
  throw new ExaError("For streaming responses, please use streamAnswer() instead:\n\nfor await (const chunk of exa.streamAnswer(query)) {\n // Handle chunks\n}", 400);
658
871
  }
659
- return this.request("/answer", "POST", { query, model: "exa", stream: false, text: false, ...options });
872
+ let outputSchema = options?.outputSchema;
873
+ if (outputSchema != null && isZodSchema(outputSchema)) {
874
+ outputSchema = zodToJsonSchema2(outputSchema);
875
+ }
876
+ return this.request("/answer", "POST", { query, model: "exa", stream: false, text: false, ...options, outputSchema });
660
877
  }
661
878
  async *streamAnswer(query, options) {
662
- const response = await this.rawRequest("/answer", "POST", { query, model: "exa", text: false, ...options, stream: true });
879
+ let outputSchema = options?.outputSchema;
880
+ if (outputSchema != null && isZodSchema(outputSchema)) {
881
+ outputSchema = zodToJsonSchema2(outputSchema);
882
+ }
883
+ const response = await this.rawRequest("/answer", "POST", { query, model: "exa", text: false, ...options, outputSchema, stream: true });
663
884
  if (!response.ok) {
664
885
  throw await this.toExaError(response, "/answer");
665
886
  }
@@ -735,12 +956,12 @@ var HttpStatusCode = /* @__PURE__ */ ((HttpStatusCode2) => {
735
956
  })(HttpStatusCode || {});
736
957
 
737
958
  // src/zod-utils.ts
738
- import { ZodType as ZodType2 } from "zod";
959
+ import { ZodType as ZodType3 } from "zod";
739
960
  import { zodToJsonSchema as convertZodToJsonSchema } from "zod-to-json-schema";
740
- function isZodSchema(obj) {
741
- return obj instanceof ZodType2;
961
+ function isZodSchema2(obj) {
962
+ return obj instanceof ZodType3;
742
963
  }
743
- function zodToJsonSchema2(schema) {
964
+ function zodToJsonSchema3(schema) {
744
965
  return convertZodToJsonSchema(schema, {
745
966
  $refStrategy: "none"
746
967
  });
@@ -784,8 +1005,8 @@ var ResearchClient2 = class extends ResearchBaseClient2 {
784
1005
  async create(params) {
785
1006
  const { instructions, model, outputSchema } = params;
786
1007
  let schema = outputSchema;
787
- if (schema && isZodSchema(schema)) {
788
- schema = zodToJsonSchema2(schema);
1008
+ if (schema && isZodSchema2(schema)) {
1009
+ schema = zodToJsonSchema3(schema);
789
1010
  }
790
1011
  const payload = {
791
1012
  instructions,
@@ -2008,10 +2229,10 @@ var Exa3 = class {
2008
2229
  if (text !== void 0) contentsOptions.text = text;
2009
2230
  if (highlights !== void 0) contentsOptions.highlights = highlights;
2010
2231
  if (summary !== void 0) {
2011
- if (typeof summary === "object" && summary !== null && "schema" in summary && summary.schema && isZodSchema(summary.schema)) {
2232
+ if (typeof summary === "object" && summary !== null && "schema" in summary && summary.schema && isZodSchema2(summary.schema)) {
2012
2233
  contentsOptions.summary = {
2013
2234
  ...summary,
2014
- schema: zodToJsonSchema2(summary.schema)
2235
+ schema: zodToJsonSchema3(summary.schema)
2015
2236
  };
2016
2237
  } else {
2017
2238
  contentsOptions.summary = summary;
@@ -2264,8 +2485,8 @@ var Exa3 = class {
2264
2485
  );
2265
2486
  }
2266
2487
  let outputSchema = options?.outputSchema;
2267
- if (outputSchema && isZodSchema(outputSchema)) {
2268
- outputSchema = zodToJsonSchema2(outputSchema);
2488
+ if (outputSchema && isZodSchema2(outputSchema)) {
2489
+ outputSchema = zodToJsonSchema3(outputSchema);
2269
2490
  }
2270
2491
  const requestBody = {
2271
2492
  query,
@@ -2280,8 +2501,8 @@ var Exa3 = class {
2280
2501
  }
2281
2502
  async *streamAnswer(query, options) {
2282
2503
  let outputSchema = options?.outputSchema;
2283
- if (outputSchema && isZodSchema(outputSchema)) {
2284
- outputSchema = zodToJsonSchema2(outputSchema);
2504
+ if (outputSchema && isZodSchema2(outputSchema)) {
2505
+ outputSchema = zodToJsonSchema3(outputSchema);
2285
2506
  }
2286
2507
  const body = {
2287
2508
  query,