exa-js 2.28.0 → 2.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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.28.0",
7
+ version: "2.29.0",
8
8
  description: "Exa SDK for Node.js and the browser",
9
9
  publishConfig: {
10
10
  access: "public"
@@ -42,7 +42,6 @@ var package_default = {
42
42
  "generate:types:websets": "openapi-typescript https://raw.githubusercontent.com/exa-labs/openapi-spec/refs/heads/master/exa-websets-spec.yaml --enum --root-types --alphabetize --root-types-no-schema-prefix --output ./src/websets/openapi.ts && npm run format:websets",
43
43
  format: 'prettier --write "src/**/*.ts"',
44
44
  "format:websets": "prettier --write src/websets/openapi.ts",
45
- "generate-docs": "npx tsx scripts/generate-docs.ts",
46
45
  "build:beta": "cross-env NPM_CONFIG_TAG=beta npm run build",
47
46
  "version:beta": "npm version prerelease --preid=beta",
48
47
  "version:stable": "npm version patch",
@@ -58,10 +57,7 @@ var package_default = {
58
57
  openai: "^6.49.0",
59
58
  "openapi-typescript": "~7.6.1",
60
59
  prettier: "~3.5.3",
61
- "ts-morph": "^27.0.2",
62
- "ts-node": "~10.9.2",
63
60
  tsup: "~8.4.0",
64
- tsx: "^4.23.15",
65
61
  typescript: "~5.8.3",
66
62
  vitest: "~4.1.12"
67
63
  },
@@ -127,6 +123,7 @@ var ExaError = class extends Error {
127
123
  this.code = envelope.code;
128
124
  this.detail = envelope.detail;
129
125
  this.requestId = envelope.requestId;
126
+ this.tag = envelope.tag;
130
127
  }
131
128
  }
132
129
  };
@@ -226,6 +223,7 @@ async function exaErrorFromResponse(response, path) {
226
223
  message += (message.length > 0 ? ". " : "") + errorData.message;
227
224
  }
228
225
  }
226
+ const tag = typeof errorData.tag === "string" ? errorData.tag : void 0;
229
227
  return new ExaError(
230
228
  message,
231
229
  response.status,
@@ -235,8 +233,9 @@ async function exaErrorFromResponse(response, path) {
235
233
  type: envelope.type,
236
234
  code: envelope.code,
237
235
  detail: envelope.detail,
238
- requestId: errorData.requestId ?? envelope.requestId
239
- } : errorData.requestId ? { requestId: errorData.requestId } : void 0
236
+ requestId: errorData.requestId ?? envelope.requestId,
237
+ tag
238
+ } : errorData.requestId || tag ? { requestId: errorData.requestId, tag } : void 0
240
239
  );
241
240
  }
242
241
 
@@ -358,6 +357,12 @@ function mergeRequestHeaders(headers, extraHeaders) {
358
357
  }
359
358
  return merged;
360
359
  }
360
+ function setsHeader(headers, name) {
361
+ const lowerCaseName = name.toLowerCase();
362
+ return Object.entries(headers ?? {}).some(
363
+ ([key, value]) => key.toLowerCase() === lowerCaseName && value !== void 0
364
+ );
365
+ }
361
366
  var CLIENT_DEFAULTS = /* @__PURE__ */ new WeakMap();
362
367
  function setClientDefaults(client, defaults) {
363
368
  if (defaults === void 0) {
@@ -612,6 +617,26 @@ function sleep(ms, signal) {
612
617
  }, ms);
613
618
  });
614
619
  }
620
+ function untilAborted(promise, signal) {
621
+ return new Promise((resolve, reject) => {
622
+ const onAbort = () => reject(signal.reason);
623
+ if (signal.aborted) {
624
+ onAbort();
625
+ } else {
626
+ signal.addEventListener("abort", onAbort, { once: true });
627
+ }
628
+ promise.then(
629
+ (value) => {
630
+ signal.removeEventListener("abort", onAbort);
631
+ resolve(value);
632
+ },
633
+ (error) => {
634
+ signal.removeEventListener("abort", onAbort);
635
+ reject(error);
636
+ }
637
+ );
638
+ });
639
+ }
615
640
  var RequestScopedClient = class {
616
641
  /**
617
642
  * Returns a view of this client that sends `requestOptions` with every
@@ -645,7 +670,35 @@ var RequestScopedClient = class {
645
670
  view.requestOptions = { ...this.requestOptions, query: remaining };
646
671
  return view;
647
672
  }
673
+ /**
674
+ * Yields every item of a cursor-paginated listing. `fetchPage` fetches the
675
+ * page at `cursor` with the view it is given: this one for the first page,
676
+ * `forNextPage()` for the rest. Stops after a page without `hasMore` or
677
+ * without a `nextCursor`.
678
+ */
679
+ async *paginate(firstCursor, fetchPage) {
680
+ let view = this;
681
+ let cursor = firstCursor;
682
+ while (true) {
683
+ const page = await fetchPage(view, cursor);
684
+ for (const item of page.data) {
685
+ yield item;
686
+ }
687
+ if (!page.hasMore || !page.nextCursor) {
688
+ return;
689
+ }
690
+ cursor = page.nextCursor;
691
+ view = view.forNextPage();
692
+ }
693
+ }
648
694
  };
695
+ async function collectAll(items) {
696
+ const all = [];
697
+ for await (const item of items) {
698
+ all.push(item);
699
+ }
700
+ return all;
701
+ }
649
702
 
650
703
  // src/agent/base.ts
651
704
  var AgentBaseClient = class extends RequestScopedClient {
@@ -808,33 +861,19 @@ var AgentMonitorEntitiesClient = class extends AgentMonitorsBaseClient {
808
861
  * automatically.
809
862
  */
810
863
  async *listAll(monitorId, options, requestOptions) {
811
- let scoped = this.withRequestOptions(requestOptions);
812
- let cursor = options.cursor;
813
864
  const { betas, ...pagination } = options;
814
- const pageOptions = { ...pagination };
815
- while (true) {
816
- pageOptions.cursor = cursor;
817
- const response = await scoped.list(monitorId, { ...pageOptions, betas });
818
- for (const entityView of response.data) {
819
- yield entityView;
820
- }
821
- if (!response.hasMore || !response.nextCursor) {
822
- break;
823
- }
824
- cursor = response.nextCursor;
825
- scoped = scoped.forNextPage();
826
- }
865
+ yield* this.withRequestOptions(requestOptions).paginate(
866
+ options.cursor,
867
+ (view, cursor) => view.list(monitorId, { ...pagination, cursor, betas })
868
+ );
827
869
  }
828
870
  /**
829
871
  * Collect all of a monitor's entities into an array.
830
872
  */
831
873
  async getAll(monitorId, options, requestOptions) {
832
- const scoped = this.withRequestOptions(requestOptions);
833
- const entities = [];
834
- for await (const entityView of scoped.listAll(monitorId, options)) {
835
- entities.push(entityView);
836
- }
837
- return entities;
874
+ return collectAll(
875
+ this.withRequestOptions(requestOptions).listAll(monitorId, options)
876
+ );
838
877
  }
839
878
  };
840
879
  var AgentMonitorChangesClient = class extends AgentMonitorsBaseClient {
@@ -858,33 +897,19 @@ var AgentMonitorChangesClient = class extends AgentMonitorsBaseClient {
858
897
  * automatically.
859
898
  */
860
899
  async *listAll(monitorId, options, requestOptions) {
861
- let scoped = this.withRequestOptions(requestOptions);
862
- let cursor = options.cursor;
863
900
  const { betas, ...pagination } = options;
864
- const pageOptions = { ...pagination };
865
- while (true) {
866
- pageOptions.cursor = cursor;
867
- const response = await scoped.list(monitorId, { ...pageOptions, betas });
868
- for (const change of response.data) {
869
- yield change;
870
- }
871
- if (!response.hasMore || !response.nextCursor) {
872
- break;
873
- }
874
- cursor = response.nextCursor;
875
- scoped = scoped.forNextPage();
876
- }
901
+ yield* this.withRequestOptions(requestOptions).paginate(
902
+ options.cursor,
903
+ (view, cursor) => view.list(monitorId, { ...pagination, cursor, betas })
904
+ );
877
905
  }
878
906
  /**
879
907
  * Collect a monitor's change feed into an array.
880
908
  */
881
909
  async getAll(monitorId, options, requestOptions) {
882
- const scoped = this.withRequestOptions(requestOptions);
883
- const changes = [];
884
- for await (const change of scoped.listAll(monitorId, options)) {
885
- changes.push(change);
886
- }
887
- return changes;
910
+ return collectAll(
911
+ this.withRequestOptions(requestOptions).listAll(monitorId, options)
912
+ );
888
913
  }
889
914
  };
890
915
  var AgentMonitorBacktestsClient = class extends AgentMonitorsBaseClient {
@@ -1004,33 +1029,19 @@ var AgentMonitorsClient = class extends AgentMonitorsBaseClient {
1004
1029
  * Iterate through all Agent Monitors, handling pagination automatically.
1005
1030
  */
1006
1031
  async *listAll(options, requestOptions) {
1007
- let scoped = this.withRequestOptions(requestOptions);
1008
- let cursor = options.cursor;
1009
1032
  const { betas, ...pagination } = options;
1010
- const pageOptions = { ...pagination };
1011
- while (true) {
1012
- pageOptions.cursor = cursor;
1013
- const response = await scoped.list({ ...pageOptions, betas });
1014
- for (const monitor of response.data) {
1015
- yield monitor;
1016
- }
1017
- if (!response.hasMore || !response.nextCursor) {
1018
- break;
1019
- }
1020
- cursor = response.nextCursor;
1021
- scoped = scoped.forNextPage();
1022
- }
1033
+ yield* this.withRequestOptions(requestOptions).paginate(
1034
+ options.cursor,
1035
+ (view, cursor) => view.list({ ...pagination, cursor, betas })
1036
+ );
1023
1037
  }
1024
1038
  /**
1025
1039
  * Collect all Agent Monitors into an array.
1026
1040
  */
1027
1041
  async getAll(options, requestOptions) {
1028
- const scoped = this.withRequestOptions(requestOptions);
1029
- const monitors = [];
1030
- for await (const monitor of scoped.listAll(options)) {
1031
- monitors.push(monitor);
1032
- }
1033
- return monitors;
1042
+ return collectAll(
1043
+ this.withRequestOptions(requestOptions).listAll(options)
1044
+ );
1034
1045
  }
1035
1046
  /**
1036
1047
  * Delete an Agent Monitor and stop its refreshes.
@@ -1208,32 +1219,18 @@ var AgentRunsClient = class extends AgentBaseClient {
1208
1219
  * Iterate through all Agent runs, handling pagination automatically.
1209
1220
  */
1210
1221
  async *listAll(options, requestOptions) {
1211
- let scoped = this.withRequestOptions(requestOptions);
1212
- let cursor = void 0;
1213
- const pageOptions = options ? { ...options } : {};
1214
- while (true) {
1215
- pageOptions.cursor = cursor;
1216
- const response = await scoped.list(pageOptions);
1217
- for (const run of response.data) {
1218
- yield run;
1219
- }
1220
- if (!response.hasMore || !response.nextCursor) {
1221
- break;
1222
- }
1223
- cursor = response.nextCursor;
1224
- scoped = scoped.forNextPage();
1225
- }
1222
+ yield* this.withRequestOptions(requestOptions).paginate(
1223
+ options?.cursor,
1224
+ (view, cursor) => view.list({ ...options, cursor })
1225
+ );
1226
1226
  }
1227
1227
  /**
1228
1228
  * Collect all Agent runs into an array.
1229
1229
  */
1230
1230
  async getAll(options, requestOptions) {
1231
- const scoped = this.withRequestOptions(requestOptions);
1232
- const runs = [];
1233
- for await (const run of scoped.listAll(options)) {
1234
- runs.push(run);
1235
- }
1236
- return runs;
1231
+ return collectAll(
1232
+ this.withRequestOptions(requestOptions).listAll(options)
1233
+ );
1237
1234
  }
1238
1235
  /**
1239
1236
  * Cancel a queued or running Agent run.
@@ -1370,30 +1367,16 @@ var AgentBetaRunsClient = class extends AgentRunsClient {
1370
1367
  );
1371
1368
  }
1372
1369
  async *listAll(options, requestOptions) {
1373
- let scoped = this.withRequestOptions(requestOptions);
1374
- let cursor = void 0;
1375
1370
  const { betas, ...pagination } = options ?? {};
1376
- const pageOptions = { ...pagination };
1377
- while (true) {
1378
- pageOptions.cursor = cursor;
1379
- const response = await scoped.list({ ...pageOptions, betas });
1380
- for (const run of response.data) {
1381
- yield run;
1382
- }
1383
- if (!response.hasMore || !response.nextCursor) {
1384
- break;
1385
- }
1386
- cursor = response.nextCursor;
1387
- scoped = scoped.forNextPage();
1388
- }
1371
+ yield* this.withRequestOptions(requestOptions).paginate(
1372
+ pagination?.cursor,
1373
+ (view, cursor) => view.list({ ...pagination, cursor, betas })
1374
+ );
1389
1375
  }
1390
1376
  async getAll(options, requestOptions) {
1391
- const scoped = this.withRequestOptions(requestOptions);
1392
- const runs = [];
1393
- for await (const run of scoped.listAll(options)) {
1394
- runs.push(run);
1395
- }
1396
- return runs;
1377
+ return collectAll(
1378
+ this.withRequestOptions(requestOptions).listAll(options)
1379
+ );
1397
1380
  }
1398
1381
  async cancel(runId, options) {
1399
1382
  const scoped = this.withRequestOptions(options);
@@ -1558,21 +1541,10 @@ var SearchMonitorRunsClient = class extends SearchMonitorsBaseClient {
1558
1541
  * @returns Async generator of Search Monitor runs
1559
1542
  */
1560
1543
  async *listAll(monitorId, options, requestOptions) {
1561
- let scoped = this.withRequestOptions(requestOptions);
1562
- let cursor = void 0;
1563
- const pageOptions = options ? { ...options } : {};
1564
- while (true) {
1565
- pageOptions.cursor = cursor;
1566
- const response = await scoped.list(monitorId, pageOptions);
1567
- for (const run of response.data) {
1568
- yield run;
1569
- }
1570
- if (!response.hasMore || !response.nextCursor) {
1571
- break;
1572
- }
1573
- cursor = response.nextCursor;
1574
- scoped = scoped.forNextPage();
1575
- }
1544
+ yield* this.withRequestOptions(requestOptions).paginate(
1545
+ options?.cursor,
1546
+ (view, cursor) => view.list(monitorId, { ...options, cursor })
1547
+ );
1576
1548
  }
1577
1549
  /**
1578
1550
  * Collect all runs for a Search Monitor into an array
@@ -1582,12 +1554,9 @@ var SearchMonitorRunsClient = class extends SearchMonitorsBaseClient {
1582
1554
  * @returns Promise resolving to an array of all Search Monitor runs
1583
1555
  */
1584
1556
  async getAll(monitorId, options, requestOptions) {
1585
- const scoped = this.withRequestOptions(requestOptions);
1586
- const runs = [];
1587
- for await (const run of scoped.listAll(monitorId, options)) {
1588
- runs.push(run);
1589
- }
1590
- return runs;
1557
+ return collectAll(
1558
+ this.withRequestOptions(requestOptions).listAll(monitorId, options)
1559
+ );
1591
1560
  }
1592
1561
  };
1593
1562
  var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
@@ -1672,21 +1641,10 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
1672
1641
  * @returns Async generator of Search Monitors
1673
1642
  */
1674
1643
  async *listAll(options, requestOptions) {
1675
- let scoped = this.withRequestOptions(requestOptions);
1676
- let cursor = void 0;
1677
- const pageOptions = options ? { ...options } : {};
1678
- while (true) {
1679
- pageOptions.cursor = cursor;
1680
- const response = await scoped.list(pageOptions);
1681
- for (const monitor of response.data) {
1682
- yield monitor;
1683
- }
1684
- if (!response.hasMore || !response.nextCursor) {
1685
- break;
1686
- }
1687
- cursor = response.nextCursor;
1688
- scoped = scoped.forNextPage();
1689
- }
1644
+ yield* this.withRequestOptions(requestOptions).paginate(
1645
+ options?.cursor,
1646
+ (view, cursor) => view.list({ ...options, cursor })
1647
+ );
1690
1648
  }
1691
1649
  /**
1692
1650
  * Collect all Search Monitors into an array
@@ -1695,12 +1653,9 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
1695
1653
  * @returns Promise resolving to an array of all Search Monitors
1696
1654
  */
1697
1655
  async getAll(options, requestOptions) {
1698
- const scoped = this.withRequestOptions(requestOptions);
1699
- const monitors = [];
1700
- for await (const monitor of scoped.listAll(options)) {
1701
- monitors.push(monitor);
1702
- }
1703
- return monitors;
1656
+ return collectAll(
1657
+ this.withRequestOptions(requestOptions).listAll(options)
1658
+ );
1704
1659
  }
1705
1660
  };
1706
1661
 
@@ -1714,21 +1669,6 @@ var ResearchBaseClient = class extends RequestScopedClient {
1714
1669
  super();
1715
1670
  this.client = client;
1716
1671
  }
1717
- /** Rejects with `researchRetiredError()`: the Research API has been retired. */
1718
- async request(_endpoint, _method = "POST", _data, _params) {
1719
- throw researchRetiredError();
1720
- }
1721
- /** Rejects with `researchRetiredError()`: the Research API has been retired. */
1722
- async rawRequest(_endpoint, _method = "POST", _data, _params) {
1723
- throw researchRetiredError();
1724
- }
1725
- buildPaginationParams(pagination) {
1726
- const params = {};
1727
- if (!pagination) return params;
1728
- if (pagination.cursor) params.cursor = pagination.cursor;
1729
- if (pagination.limit) params.limit = pagination.limit;
1730
- return params;
1731
- }
1732
1672
  };
1733
1673
 
1734
1674
  // src/research/client.ts
@@ -1736,105 +1676,14 @@ var ResearchClient = class extends ResearchBaseClient {
1736
1676
  constructor(client) {
1737
1677
  super(client);
1738
1678
  }
1739
- async create(params, requestOptions) {
1740
- const scoped = this.withRequestOptions(requestOptions);
1741
- const { instructions, model, outputSchema } = params;
1742
- let schema = outputSchema;
1743
- if (schema && isZodSchema(schema)) {
1744
- schema = zodToJsonSchema(schema);
1745
- }
1746
- const payload = {
1747
- instructions,
1748
- model: model ?? "exa-research-fast"
1749
- };
1750
- if (schema) {
1751
- payload.outputSchema = schema;
1752
- }
1753
- return scoped.request("", "POST", payload);
1679
+ async create(_params, _requestOptions) {
1680
+ throw researchRetiredError();
1754
1681
  }
1755
- get(researchId, options, requestOptions) {
1756
- const scoped = this.withRequestOptions(requestOptions);
1757
- if (options?.stream) {
1758
- const promise = async () => {
1759
- const params = { stream: "true" };
1760
- if (options.events !== void 0) {
1761
- params.events = options.events.toString();
1762
- }
1763
- const resp = await scoped.rawRequest(
1764
- `/${researchId}`,
1765
- "GET",
1766
- void 0,
1767
- params
1768
- );
1769
- if (!resp.ok) {
1770
- throw await exaErrorFromResponse(resp, `/research/v1/${researchId}`);
1771
- }
1772
- if (!resp.body) {
1773
- throw new Error("No response body for SSE stream");
1774
- }
1775
- const reader = resp.body.getReader();
1776
- const decoder = new TextDecoder();
1777
- let buffer = "";
1778
- function processPart(part) {
1779
- const lines = part.split("\n");
1780
- let data = lines.slice(1).join("\n");
1781
- if (data.startsWith("data:")) {
1782
- data = data.slice(5).trimStart();
1783
- }
1784
- try {
1785
- return JSON.parse(data);
1786
- } catch (e) {
1787
- return null;
1788
- }
1789
- }
1790
- async function* streamEvents() {
1791
- try {
1792
- while (true) {
1793
- const { done, value } = await reader.read();
1794
- if (done) break;
1795
- buffer += decoder.decode(value, { stream: true });
1796
- let parts = buffer.split("\n\n");
1797
- buffer = parts.pop() ?? "";
1798
- for (const part of parts) {
1799
- const processed = processPart(part);
1800
- if (processed) {
1801
- yield processed;
1802
- }
1803
- }
1804
- }
1805
- if (buffer.trim()) {
1806
- const processed = processPart(buffer.trim());
1807
- if (processed) {
1808
- yield processed;
1809
- }
1810
- }
1811
- } finally {
1812
- try {
1813
- await reader.cancel();
1814
- } catch {
1815
- }
1816
- }
1817
- }
1818
- return streamEvents();
1819
- };
1820
- return promise();
1821
- } else {
1822
- const params = { stream: "false" };
1823
- if (options?.events !== void 0) {
1824
- params.events = options.events.toString();
1825
- }
1826
- return scoped.request(
1827
- `/${researchId}`,
1828
- "GET",
1829
- void 0,
1830
- params
1831
- );
1832
- }
1682
+ get(_researchId, _options, _requestOptions) {
1683
+ return Promise.reject(researchRetiredError());
1833
1684
  }
1834
- async list(options, requestOptions) {
1835
- const scoped = this.withRequestOptions(requestOptions);
1836
- const params = this.buildPaginationParams(options);
1837
- return scoped.request("", "GET", void 0, params);
1685
+ async list(_options, _requestOptions) {
1686
+ throw researchRetiredError();
1838
1687
  }
1839
1688
  async pollUntilFinished(_researchId, _options, _requestOptions) {
1840
1689
  throw researchRetiredError();
@@ -2016,21 +1865,10 @@ var EventsClient = class extends WebsetsBaseClient {
2016
1865
  * @returns Async generator of Events
2017
1866
  */
2018
1867
  async *listAll(options, requestOptions) {
2019
- let scoped = this.withRequestOptions(requestOptions);
2020
- let cursor = void 0;
2021
- const pageOptions = options ? { ...options } : {};
2022
- while (true) {
2023
- pageOptions.cursor = cursor;
2024
- const response = await scoped.list(pageOptions);
2025
- for (const event of response.data) {
2026
- yield event;
2027
- }
2028
- if (!response.hasMore || !response.nextCursor) {
2029
- break;
2030
- }
2031
- cursor = response.nextCursor;
2032
- scoped = scoped.forNextPage();
2033
- }
1868
+ yield* this.withRequestOptions(requestOptions).paginate(
1869
+ options?.cursor,
1870
+ (view, cursor) => view.list({ ...options, cursor })
1871
+ );
2034
1872
  }
2035
1873
  /**
2036
1874
  * Collect all Events into an array
@@ -2039,12 +1877,9 @@ var EventsClient = class extends WebsetsBaseClient {
2039
1877
  * @returns Promise resolving to an array of all Events
2040
1878
  */
2041
1879
  async getAll(options, requestOptions) {
2042
- const scoped = this.withRequestOptions(requestOptions);
2043
- const events = [];
2044
- for await (const event of scoped.listAll(options)) {
2045
- events.push(event);
2046
- }
2047
- return events;
1880
+ return collectAll(
1881
+ this.withRequestOptions(requestOptions).listAll(options)
1882
+ );
2048
1883
  }
2049
1884
  };
2050
1885
 
@@ -2389,21 +2224,10 @@ var ImportsClient = class extends WebsetsBaseClient {
2389
2224
  * @returns Async generator of Imports
2390
2225
  */
2391
2226
  async *listAll(options, requestOptions) {
2392
- let scoped = this.withRequestOptions(requestOptions);
2393
- let cursor = void 0;
2394
- const pageOptions = options ? { ...options } : {};
2395
- while (true) {
2396
- pageOptions.cursor = cursor;
2397
- const response = await scoped.list(pageOptions);
2398
- for (const importItem of response.data) {
2399
- yield importItem;
2400
- }
2401
- if (!response.hasMore || !response.nextCursor) {
2402
- break;
2403
- }
2404
- cursor = response.nextCursor;
2405
- scoped = scoped.forNextPage();
2406
- }
2227
+ yield* this.withRequestOptions(requestOptions).paginate(
2228
+ options?.cursor,
2229
+ (view, cursor) => view.list({ ...options, cursor })
2230
+ );
2407
2231
  }
2408
2232
  /**
2409
2233
  * Collect all Imports into an array
@@ -2412,12 +2236,9 @@ var ImportsClient = class extends WebsetsBaseClient {
2412
2236
  * @returns Promise resolving to an array of all Imports
2413
2237
  */
2414
2238
  async getAll(options, requestOptions) {
2415
- const scoped = this.withRequestOptions(requestOptions);
2416
- const imports = [];
2417
- for await (const importItem of scoped.listAll(options)) {
2418
- imports.push(importItem);
2419
- }
2420
- return imports;
2239
+ return collectAll(
2240
+ this.withRequestOptions(requestOptions).listAll(options)
2241
+ );
2421
2242
  }
2422
2243
  };
2423
2244
 
@@ -2451,21 +2272,10 @@ var WebsetItemsClient = class extends WebsetsBaseClient {
2451
2272
  * @returns Async generator of Webset Items
2452
2273
  */
2453
2274
  async *listAll(websetId, options, requestOptions) {
2454
- let scoped = this.withRequestOptions(requestOptions);
2455
- let cursor = void 0;
2456
- const pageOptions = options ? { ...options } : {};
2457
- while (true) {
2458
- pageOptions.cursor = cursor;
2459
- const response = await scoped.list(websetId, pageOptions);
2460
- for (const item of response.data) {
2461
- yield item;
2462
- }
2463
- if (!response.hasMore || !response.nextCursor) {
2464
- break;
2465
- }
2466
- cursor = response.nextCursor;
2467
- scoped = scoped.forNextPage();
2468
- }
2275
+ yield* this.withRequestOptions(requestOptions).paginate(
2276
+ options?.cursor,
2277
+ (view, cursor) => view.list(websetId, { ...options, cursor })
2278
+ );
2469
2279
  }
2470
2280
  /**
2471
2281
  * Collect all items from a Webset into an array
@@ -2475,12 +2285,9 @@ var WebsetItemsClient = class extends WebsetsBaseClient {
2475
2285
  * @returns Promise resolving to an array of all Webset Items
2476
2286
  */
2477
2287
  async getAll(websetId, options, requestOptions) {
2478
- const scoped = this.withRequestOptions(requestOptions);
2479
- const items = [];
2480
- for await (const item of scoped.listAll(websetId, options)) {
2481
- items.push(item);
2482
- }
2483
- return items;
2288
+ return collectAll(
2289
+ this.withRequestOptions(requestOptions).listAll(websetId, options)
2290
+ );
2484
2291
  }
2485
2292
  /**
2486
2293
  * Get an Item by ID
@@ -2619,21 +2426,10 @@ var WebsetMonitorsClient = class extends WebsetsBaseClient {
2619
2426
  * @returns Async generator of Monitors
2620
2427
  */
2621
2428
  async *listAll(options, requestOptions) {
2622
- let scoped = this.withRequestOptions(requestOptions);
2623
- let cursor = void 0;
2624
- const pageOptions = options ? { ...options } : {};
2625
- while (true) {
2626
- pageOptions.cursor = cursor;
2627
- const response = await scoped.list(pageOptions);
2628
- for (const monitor of response.data) {
2629
- yield monitor;
2630
- }
2631
- if (!response.hasMore || !response.nextCursor) {
2632
- break;
2633
- }
2634
- cursor = response.nextCursor;
2635
- scoped = scoped.forNextPage();
2636
- }
2429
+ yield* this.withRequestOptions(requestOptions).paginate(
2430
+ options?.cursor,
2431
+ (view, cursor) => view.list({ ...options, cursor })
2432
+ );
2637
2433
  }
2638
2434
  /**
2639
2435
  * Collect all Monitors into an array
@@ -2642,12 +2438,9 @@ var WebsetMonitorsClient = class extends WebsetsBaseClient {
2642
2438
  * @returns Promise resolving to an array of all Monitors
2643
2439
  */
2644
2440
  async getAll(options, requestOptions) {
2645
- const scoped = this.withRequestOptions(requestOptions);
2646
- const monitors = [];
2647
- for await (const monitor of scoped.listAll(options)) {
2648
- monitors.push(monitor);
2649
- }
2650
- return monitors;
2441
+ return collectAll(
2442
+ this.withRequestOptions(requestOptions).listAll(options)
2443
+ );
2651
2444
  }
2652
2445
  };
2653
2446
 
@@ -2745,21 +2538,10 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2745
2538
  * @returns Async generator of Webhooks
2746
2539
  */
2747
2540
  async *listAll(options, requestOptions) {
2748
- let scoped = this.withRequestOptions(requestOptions);
2749
- let cursor = void 0;
2750
- const pageOptions = options ? { ...options } : {};
2751
- while (true) {
2752
- pageOptions.cursor = cursor;
2753
- const response = await scoped.list(pageOptions);
2754
- for (const webhook of response.data) {
2755
- yield webhook;
2756
- }
2757
- if (!response.hasMore || !response.nextCursor) {
2758
- break;
2759
- }
2760
- cursor = response.nextCursor;
2761
- scoped = scoped.forNextPage();
2762
- }
2541
+ yield* this.withRequestOptions(requestOptions).paginate(
2542
+ options?.cursor,
2543
+ (view, cursor) => view.list({ ...options, cursor })
2544
+ );
2763
2545
  }
2764
2546
  /**
2765
2547
  * Collect all Webhooks into an array
@@ -2768,12 +2550,9 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2768
2550
  * @returns Promise resolving to an array of all Webhooks
2769
2551
  */
2770
2552
  async getAll(options, requestOptions) {
2771
- const scoped = this.withRequestOptions(requestOptions);
2772
- const webhooks = [];
2773
- for await (const webhook of scoped.listAll(options)) {
2774
- webhooks.push(webhook);
2775
- }
2776
- return webhooks;
2553
+ return collectAll(
2554
+ this.withRequestOptions(requestOptions).listAll(options)
2555
+ );
2777
2556
  }
2778
2557
  /**
2779
2558
  * Update a Webhook
@@ -2826,21 +2605,10 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2826
2605
  * @returns Async generator of Webhook attempts
2827
2606
  */
2828
2607
  async *listAllAttempts(id, options, requestOptions) {
2829
- let scoped = this.withRequestOptions(requestOptions);
2830
- let cursor = void 0;
2831
- const pageOptions = options ? { ...options } : {};
2832
- while (true) {
2833
- pageOptions.cursor = cursor;
2834
- const response = await scoped.listAttempts(id, pageOptions);
2835
- for (const attempt of response.data) {
2836
- yield attempt;
2837
- }
2838
- if (!response.hasMore || !response.nextCursor) {
2839
- break;
2840
- }
2841
- cursor = response.nextCursor;
2842
- scoped = scoped.forNextPage();
2843
- }
2608
+ yield* this.withRequestOptions(requestOptions).paginate(
2609
+ options?.cursor,
2610
+ (view, cursor) => view.listAttempts(id, { ...options, cursor })
2611
+ );
2844
2612
  }
2845
2613
  /**
2846
2614
  * Collect all attempts for a Webhook into an array
@@ -2850,12 +2618,9 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2850
2618
  * @returns Promise resolving to an array of all Webhook attempts
2851
2619
  */
2852
2620
  async getAllAttempts(id, options, requestOptions) {
2853
- const scoped = this.withRequestOptions(requestOptions);
2854
- const attempts = [];
2855
- for await (const attempt of scoped.listAllAttempts(id, options)) {
2856
- attempts.push(attempt);
2857
- }
2858
- return attempts;
2621
+ return collectAll(
2622
+ this.withRequestOptions(requestOptions).listAllAttempts(id, options)
2623
+ );
2859
2624
  }
2860
2625
  };
2861
2626
 
@@ -2954,21 +2719,10 @@ var WebsetsClient = class extends WebsetsBaseClient {
2954
2719
  * @returns Async generator of Websets
2955
2720
  */
2956
2721
  async *listAll(options, requestOptions) {
2957
- let scoped = this.withRequestOptions(requestOptions);
2958
- let cursor = void 0;
2959
- const pageOptions = options ? { ...options } : {};
2960
- while (true) {
2961
- pageOptions.cursor = cursor;
2962
- const response = await scoped.list(pageOptions);
2963
- for (const webset of response.data) {
2964
- yield webset;
2965
- }
2966
- if (!response.hasMore || !response.nextCursor) {
2967
- break;
2968
- }
2969
- cursor = response.nextCursor;
2970
- scoped = scoped.forNextPage();
2971
- }
2722
+ yield* this.withRequestOptions(requestOptions).paginate(
2723
+ options?.cursor,
2724
+ (view, cursor) => view.list({ ...options, cursor })
2725
+ );
2972
2726
  }
2973
2727
  /**
2974
2728
  * Collect all Websets into an array
@@ -2977,12 +2731,9 @@ var WebsetsClient = class extends WebsetsBaseClient {
2977
2731
  * @returns Promise resolving to an array of all Websets
2978
2732
  */
2979
2733
  async getAll(options, requestOptions) {
2980
- const scoped = this.withRequestOptions(requestOptions);
2981
- const websets = [];
2982
- for await (const webset of scoped.listAll(options)) {
2983
- websets.push(webset);
2984
- }
2985
- return websets;
2734
+ return collectAll(
2735
+ this.withRequestOptions(requestOptions).listAll(options)
2736
+ );
2986
2737
  }
2987
2738
  /**
2988
2739
  * Update a Webset
@@ -3489,7 +3240,47 @@ function isResponsesInput(value) {
3489
3240
  var fetchImpl = typeof global !== "undefined" && global.fetch ? global.fetch : fetch2;
3490
3241
  var HeadersImpl = typeof global !== "undefined" && global.Headers ? global.Headers : Headers;
3491
3242
  var DEFAULT_MAX_CHARACTERS = 1e4;
3243
+ var DEFAULT_BASE_URL = "https://api.exa.ai";
3244
+ function resolveBaseURL(baseURL) {
3245
+ if (baseURL === void 0) {
3246
+ const fromEnvironment = typeof process === "undefined" ? void 0 : process.env?.EXA_BASE_URL?.trim();
3247
+ baseURL = fromEnvironment || DEFAULT_BASE_URL;
3248
+ }
3249
+ return baseURL.replace(/\/+$/, "");
3250
+ }
3251
+ function clientArguments(second, third) {
3252
+ if (typeof URL !== "undefined" && second instanceof URL) {
3253
+ second = String(second);
3254
+ }
3255
+ if (typeof second === "object" && second !== null) {
3256
+ if (third !== void 0) {
3257
+ throw new TypeError(
3258
+ "Pass the client options once, as the second argument or as the third after a base URL"
3259
+ );
3260
+ }
3261
+ return { baseURL: second.baseURL, options: second };
3262
+ }
3263
+ if (second != null && third?.baseURL !== void 0) {
3264
+ throw new TypeError(
3265
+ "Pass the base URL once, as the second argument or as options.baseURL"
3266
+ );
3267
+ }
3268
+ return { baseURL: second ?? third?.baseURL, options: third };
3269
+ }
3492
3270
  var DYNAMIC_HIGHLIGHTS_BETA = "dynamic-highlights-2026-08-28";
3271
+ async function resolveApiKey(apiKey, signal) {
3272
+ if (signal?.aborted) {
3273
+ throw signal.reason;
3274
+ }
3275
+ const pending = Promise.resolve(apiKey({ signal }));
3276
+ const key = await (signal ? untilAborted(pending, signal) : pending);
3277
+ if (typeof key !== "string" || !/^[\x21-\x7E]+$/.test(key)) {
3278
+ throw new TypeError(
3279
+ "apiKey must return a non-empty string of visible ASCII characters"
3280
+ );
3281
+ }
3282
+ return key;
3283
+ }
3493
3284
  var loggedWarnings = /* @__PURE__ */ new Set();
3494
3285
  function logWarningOnce(warning, context) {
3495
3286
  const request = `${context.method} ${context.endpoint}`;
@@ -3541,6 +3332,24 @@ function costDollarsOf(payload) {
3541
3332
  }
3542
3333
  return costDollars;
3543
3334
  }
3335
+ function streamErrorOf(payload, path, requestIdHeader) {
3336
+ const event = payload?.type === "error" ? payload : payload?.tag === "ERROR" ? payload.payload : void 0;
3337
+ if (typeof event !== "object" || event === null) {
3338
+ return void 0;
3339
+ }
3340
+ const { code, message, tag } = event.error ?? {};
3341
+ const requestId = typeof event.requestId === "string" ? event.requestId : requestIdHeader;
3342
+ return new ExaError(
3343
+ typeof message === "string" && message ? message : "Unknown error",
3344
+ typeof code === "number" ? code : 500 /* InternalServerError */,
3345
+ void 0,
3346
+ path,
3347
+ {
3348
+ requestId: requestId ?? void 0,
3349
+ tag: typeof tag === "string" ? tag : void 0
3350
+ }
3351
+ );
3352
+ }
3544
3353
  function citationsFromResults(results) {
3545
3354
  if (!Array.isArray(results)) {
3546
3355
  return void 0;
@@ -3567,36 +3376,47 @@ function withJsonSummarySchema(contents) {
3567
3376
  };
3568
3377
  }
3569
3378
  var Exa2 = class {
3570
- /**
3571
- * Constructs the Exa API client.
3572
- * @param {string} apiKey - The API key for authentication.
3573
- * @param {string} [baseURL] - The base URL of the Exa API.
3574
- * @param {ExaClientOptions} [options] - Client-wide settings (`timeout`, `warnings`).
3575
- * @throws {RangeError} When `options.timeout` is not an integer from 1 to 2147483647.
3576
- * @throws {TypeError} When `options.warnings` is not `"log"`, `"silent"` or a function.
3577
- */
3578
- constructor(apiKey, baseURL = "https://api.exa.ai", options) {
3379
+ constructor(apiKey, baseURLOrOptions, maybeOptions) {
3579
3380
  this.toolRegistry = new ToolRegistry();
3580
- this.baseURL = baseURL;
3381
+ const { baseURL, options } = clientArguments(
3382
+ baseURLOrOptions,
3383
+ maybeOptions
3384
+ );
3385
+ this.baseURL = resolveBaseURL(baseURL);
3581
3386
  this.warningHandler = warningHandlerFor(options?.warnings);
3582
3387
  setClientDefaults(
3583
3388
  this,
3584
3389
  options?.timeout === void 0 ? void 0 : { timeout: validateTimeout(options.timeout) }
3585
3390
  );
3586
- if (!apiKey) {
3587
- apiKey = process.env.EXA_API_KEY;
3391
+ const customFetch = options?.fetch;
3392
+ if (customFetch !== void 0 && typeof customFetch !== "function") {
3393
+ throw new TypeError("options.fetch must be a function");
3394
+ }
3395
+ const send = customFetch ?? fetchImpl;
3396
+ this.fetcher = (input, init) => send(input, init);
3397
+ if (typeof apiKey === "function") {
3398
+ this.apiKeySource = apiKey;
3399
+ this.headers = new HeadersImpl({
3400
+ "Content-Type": "application/json",
3401
+ "User-Agent": `exa-node ${package_default.version}`
3402
+ });
3403
+ } else {
3404
+ this.apiKeySource = void 0;
3588
3405
  if (!apiKey) {
3589
- throw new ExaError(
3590
- "API key must be provided as an argument or as an environment variable (EXA_API_KEY)",
3591
- 401 /* Unauthorized */
3592
- );
3406
+ apiKey = process.env.EXA_API_KEY;
3407
+ if (!apiKey) {
3408
+ throw new ExaError(
3409
+ "API key must be provided as an argument or as an environment variable (EXA_API_KEY)",
3410
+ 401 /* Unauthorized */
3411
+ );
3412
+ }
3593
3413
  }
3414
+ this.headers = new HeadersImpl({
3415
+ "x-api-key": apiKey,
3416
+ "Content-Type": "application/json",
3417
+ "User-Agent": `exa-node ${package_default.version}`
3418
+ });
3594
3419
  }
3595
- this.headers = new HeadersImpl({
3596
- "x-api-key": apiKey,
3597
- "Content-Type": "application/json",
3598
- "User-Agent": `exa-node ${package_default.version}`
3599
- });
3600
3420
  this.websets = new WebsetsClient(this);
3601
3421
  this.research = new ResearchClient(this);
3602
3422
  this.monitors = new SearchMonitorsClient(this);
@@ -3691,6 +3511,22 @@ var Exa2 = class {
3691
3511
  }
3692
3512
  return { query, ...body };
3693
3513
  }
3514
+ /**
3515
+ * Returns the headers a request sends, which are `headers` with the call's
3516
+ * `extraHeaders` on top and, when `apiKey` is a function, the key it returns
3517
+ * as `x-api-key` beneath them. The function is called only when neither
3518
+ * sets `x-api-key` nor removes it with `null`, whatever its case. Called
3519
+ * inside each request's lifecycle, so the request's `signal` and `timeout`
3520
+ * also bound the wait for the key.
3521
+ */
3522
+ async requestHeaders(headers, extraHeaders, signal) {
3523
+ const merged = mergeRequestHeaders(headers, extraHeaders);
3524
+ if (!this.apiKeySource || setsHeader(headers, "x-api-key") || setsHeader(extraHeaders, "x-api-key")) {
3525
+ return merged;
3526
+ }
3527
+ const apiKey = await resolveApiKey(this.apiKeySource, signal);
3528
+ return mergeRequestHeaders({ "x-api-key": apiKey }, merged);
3529
+ }
3694
3530
  /**
3695
3531
  * Makes a request to the Exa API.
3696
3532
  * @param {string} endpoint - The API endpoint to call.
@@ -3732,17 +3568,17 @@ var Exa2 = class {
3732
3568
  if (headers) {
3733
3569
  combinedHeaders = { ...combinedHeaders, ...headers };
3734
3570
  }
3735
- combinedHeaders = mergeRequestHeaders(
3736
- combinedHeaders,
3737
- requestOptions?.headers
3738
- );
3739
3571
  const { signal, dispose, toRequestError } = resolveRequestSignal(
3740
3572
  withClientDefaults(this, requestOptions)
3741
3573
  );
3742
3574
  try {
3743
- const response = await fetchImpl(url, {
3575
+ const response = await this.fetcher(url, {
3744
3576
  method,
3745
- headers: combinedHeaders,
3577
+ headers: await this.requestHeaders(
3578
+ combinedHeaders,
3579
+ requestOptions?.headers,
3580
+ signal
3581
+ ),
3746
3582
  body: body ? JSON.stringify(body) : void 0,
3747
3583
  signal
3748
3584
  });
@@ -3807,15 +3643,15 @@ var Exa2 = class {
3807
3643
  if (headers) {
3808
3644
  combinedHeaders = { ...combinedHeaders, ...headers };
3809
3645
  }
3810
- combinedHeaders = mergeRequestHeaders(
3811
- combinedHeaders,
3812
- requestOptions?.headers
3813
- );
3814
3646
  const { signal, dispose, needsDispose, stopTimeout, toRequestError } = resolveRequestSignal(withClientDefaults(this, requestOptions));
3815
3647
  try {
3816
- const response = await fetchImpl(url, {
3648
+ const response = await this.fetcher(url, {
3817
3649
  method,
3818
- headers: combinedHeaders,
3650
+ headers: await this.requestHeaders(
3651
+ combinedHeaders,
3652
+ requestOptions?.headers,
3653
+ signal
3654
+ ),
3819
3655
  body: body ? JSON.stringify(body) : void 0,
3820
3656
  signal
3821
3657
  });
@@ -3906,6 +3742,9 @@ var Exa2 = class {
3906
3742
  * A search without `outputSchema` has no text to stream. Its stream yields
3907
3743
  * one chunk with the results as `citations`, then the warnings chunk when
3908
3744
  * the API returns warnings. Call `search()` for every field of the results.
3745
+ *
3746
+ * If the API reports an error partway through, the stream yields the chunks
3747
+ * before it and then rejects with an `ExaError`.
3909
3748
  * @param {RequestOptions} [requestOptions] - Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`).
3910
3749
  */
3911
3750
  streamSearch(query, options, requestOptions) {
@@ -4159,18 +3998,29 @@ var Exa2 = class {
4159
3998
  continue;
4160
3999
  }
4161
4000
  this.reportWarnings(endpoint, "POST", chunkData, requestIdHeader);
4001
+ const error = streamErrorOf(chunkData, endpoint, requestIdHeader);
4002
+ if (error) {
4003
+ throw error;
4004
+ }
4162
4005
  yield* this.payloadChunks(chunkData);
4163
4006
  }
4164
4007
  }
4165
4008
  if (buffer.startsWith("data: ")) {
4166
4009
  const leftover = buffer.replace(/^data:\s*/, "").trim();
4167
4010
  if (leftover && leftover !== "[DONE]") {
4011
+ let error;
4168
4012
  try {
4169
4013
  const chunkData = JSON.parse(leftover);
4170
4014
  this.reportWarnings(endpoint, "POST", chunkData, requestIdHeader);
4171
- yield* this.payloadChunks(chunkData);
4015
+ error = streamErrorOf(chunkData, endpoint, requestIdHeader);
4016
+ if (!error) {
4017
+ yield* this.payloadChunks(chunkData);
4018
+ }
4172
4019
  } catch (e) {
4173
4020
  }
4021
+ if (error) {
4022
+ throw error;
4023
+ }
4174
4024
  }
4175
4025
  }
4176
4026
  } finally {