@ai-sdk/provider-utils 5.0.47 → 5.0.49

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 CHANGED
@@ -26,9 +26,9 @@ async function delay(delayInMs, options) {
26
26
  if (delayInMs == null) {
27
27
  return;
28
28
  }
29
- const signal = options == null ? void 0 : options.abortSignal;
29
+ const signal = options?.abortSignal;
30
30
  return new Promise((resolve2, reject) => {
31
- if (signal == null ? void 0 : signal.aborted) {
31
+ if (signal?.aborted) {
32
32
  reject(createAbortError());
33
33
  return;
34
34
  }
@@ -38,13 +38,13 @@ async function delay(delayInMs, options) {
38
38
  }, delayInMs);
39
39
  const cleanup = () => {
40
40
  clearTimeout(timeoutId);
41
- signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
41
+ signal?.removeEventListener("abort", onAbort);
42
42
  };
43
43
  const onAbort = () => {
44
44
  cleanup();
45
45
  reject(createAbortError());
46
46
  };
47
- signal == null ? void 0 : signal.addEventListener("abort", onAbort);
47
+ signal?.addEventListener("abort", onAbort);
48
48
  });
49
49
  }
50
50
  function createAbortError() {
@@ -53,7 +53,7 @@ function createAbortError() {
53
53
 
54
54
  // src/websocket.ts
55
55
  function getWebSocketConstructor(webSocket) {
56
- const WebSocketConstructor = webSocket != null ? webSocket : globalThis.WebSocket;
56
+ const WebSocketConstructor = webSocket ?? globalThis.WebSocket;
57
57
  if (WebSocketConstructor == null) {
58
58
  throw new Error("No WebSocket implementation available.");
59
59
  }
@@ -86,9 +86,8 @@ async function waitForWebSocketBufferDrain(socket, {
86
86
  pollIntervalMs = 20,
87
87
  abortSignal
88
88
  } = {}) {
89
- var _a3;
90
- while (socket.readyState === WEBSOCKET_OPEN_STATE && ((_a3 = socket.bufferedAmount) != null ? _a3 : 0) > highWaterMark) {
91
- if ((abortSignal == null ? void 0 : abortSignal.aborted) === true) {
89
+ while (socket.readyState === WEBSOCKET_OPEN_STATE && (socket.bufferedAmount ?? 0) > highWaterMark) {
90
+ if (abortSignal?.aborted === true) {
92
91
  return;
93
92
  }
94
93
  await delay(pollIntervalMs);
@@ -109,43 +108,39 @@ function connectToWebSocket({
109
108
  onClose,
110
109
  onAbort
111
110
  }) {
112
- var _a3;
113
111
  let socket;
114
112
  let abortListener;
115
113
  const close = (code) => {
116
114
  if (abortListener != null) {
117
- abortSignal == null ? void 0 : abortSignal.removeEventListener("abort", abortListener);
115
+ abortSignal?.removeEventListener("abort", abortListener);
118
116
  abortListener = void 0;
119
117
  }
120
118
  try {
121
- socket == null ? void 0 : socket.close(code);
122
- } catch (e) {
119
+ socket?.close(code);
120
+ } catch {
123
121
  }
124
122
  };
125
- if (abortSignal == null ? void 0 : abortSignal.aborted) {
126
- onAbort == null ? void 0 : onAbort((_a3 = abortSignal.reason) != null ? _a3 : new Error("Aborted"));
123
+ if (abortSignal?.aborted) {
124
+ onAbort?.(abortSignal.reason ?? new Error("Aborted"));
127
125
  return { socket: void 0, close };
128
126
  }
129
127
  try {
130
128
  const WebSocketConstructor = getWebSocketConstructor(webSocket);
131
129
  socket = new WebSocketConstructor(url, protocols, {
132
- headers: removeUndefinedEntries(headers != null ? headers : {})
130
+ headers: removeUndefinedEntries(headers ?? {})
133
131
  });
134
132
  } catch (error) {
135
133
  onProcessingError(error);
136
134
  return { socket: void 0, close };
137
135
  }
138
136
  if (abortSignal != null && onAbort != null) {
139
- abortListener = () => {
140
- var _a4;
141
- return onAbort((_a4 = abortSignal.reason) != null ? _a4 : new Error("Aborted"));
142
- };
137
+ abortListener = () => onAbort(abortSignal.reason ?? new Error("Aborted"));
143
138
  abortSignal.addEventListener("abort", abortListener, { once: true });
144
139
  }
145
140
  const openedSocket = socket;
146
141
  socket.onopen = () => {
147
142
  try {
148
- onOpen == null ? void 0 : onOpen(openedSocket);
143
+ onOpen?.(openedSocket);
149
144
  } catch (error) {
150
145
  onProcessingError(error);
151
146
  }
@@ -155,13 +150,13 @@ function connectToWebSocket({
155
150
  tail = tail.then(() => readWebSocketMessageText(event.data)).then((text) => onMessageText(text)).catch(onProcessingError);
156
151
  };
157
152
  socket.onerror = () => {
158
- tail = tail.then(() => onSocketError == null ? void 0 : onSocketError()).catch(onProcessingError);
153
+ tail = tail.then(() => onSocketError?.()).catch(onProcessingError);
159
154
  };
160
155
  socket.onclose = (event) => {
161
156
  const closeEvent = event;
162
- const code = typeof (closeEvent == null ? void 0 : closeEvent.code) === "number" ? closeEvent.code : void 0;
163
- const reason = typeof (closeEvent == null ? void 0 : closeEvent.reason) === "string" ? closeEvent.reason : void 0;
164
- tail = tail.then(() => onClose == null ? void 0 : onClose({ code, reason })).catch(onProcessingError);
157
+ const code = typeof closeEvent?.code === "number" ? closeEvent.code : void 0;
158
+ const reason = typeof closeEvent?.reason === "string" ? closeEvent.reason : void 0;
159
+ tail = tail.then(() => onClose?.({ code, reason })).catch(onProcessingError);
165
160
  };
166
161
  return { socket, close };
167
162
  }
@@ -197,7 +192,7 @@ function convertAsyncIteratorToReadableStream(iterator) {
197
192
  if (iterator.return) {
198
193
  try {
199
194
  await iterator.return(reason);
200
- } catch (e) {
195
+ } catch {
201
196
  }
202
197
  }
203
198
  }
@@ -285,8 +280,8 @@ function createLanguageModelResponseMetadata({
285
280
  created
286
281
  }) {
287
282
  return {
288
- id: id != null ? id : void 0,
289
- modelId: model != null ? model : void 0,
283
+ id: id ?? void 0,
284
+ modelId: model ?? void 0,
290
285
  timestamp: created != null ? new Date(created * 1e3) : void 0
291
286
  };
292
287
  }
@@ -324,14 +319,8 @@ function createToolNameMapping({
324
319
  }
325
320
  }
326
321
  return {
327
- toProviderToolName: (customToolName) => {
328
- var _a3;
329
- return (_a3 = customToolNameToProviderToolName[customToolName]) != null ? _a3 : customToolName;
330
- },
331
- toCustomToolName: (providerToolName) => {
332
- var _a3;
333
- return (_a3 = providerToolNameToCustomToolName[providerToolName]) != null ? _a3 : providerToolName;
334
- }
322
+ toProviderToolName: (customToolName) => customToolNameToProviderToolName[customToolName] ?? customToolName,
323
+ toCustomToolName: (providerToolName) => providerToolNameToCustomToolName[providerToolName] ?? providerToolName
335
324
  };
336
325
  }
337
326
 
@@ -383,17 +372,15 @@ var DelayedPromise = class {
383
372
  return this._promise;
384
373
  }
385
374
  resolve(value) {
386
- var _a3;
387
375
  this.status = { type: "resolved", value };
388
376
  if (this._promise) {
389
- (_a3 = this._resolve) == null ? void 0 : _a3.call(this, value);
377
+ this._resolve?.(value);
390
378
  }
391
379
  }
392
380
  reject(error) {
393
- var _a3;
394
381
  this.status = { type: "rejected", error };
395
382
  if (this._promise) {
396
- (_a3 = this._reject) == null ? void 0 : _a3.call(this, error);
383
+ this._reject?.(error);
397
384
  }
398
385
  }
399
386
  isResolved() {
@@ -417,14 +404,13 @@ function extractResponseHeaders(response) {
417
404
 
418
405
  // src/get-runtime-environment-user-agent.ts
419
406
  function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
420
- var _a3, _b3, _c;
421
407
  if (globalThisAny.window) {
422
408
  return `runtime/browser`;
423
409
  }
424
- if ((_a3 = globalThisAny.navigator) == null ? void 0 : _a3.userAgent) {
410
+ if (globalThisAny.navigator?.userAgent) {
425
411
  return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
426
412
  }
427
- if ((_c = (_b3 = globalThisAny.process) == null ? void 0 : _b3.versions) == null ? void 0 : _c.node) {
413
+ if (globalThisAny.process?.versions?.node) {
428
414
  return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
429
415
  }
430
416
  if (globalThisAny.EdgeRuntime) {
@@ -517,7 +503,7 @@ function handleFetchError({
517
503
  }
518
504
 
519
505
  // src/version.ts
520
- var VERSION = true ? "5.0.47" : "0.0.0-test";
506
+ var VERSION = true ? "5.0.49" : "0.0.0-test";
521
507
 
522
508
  // src/normalize-headers.ts
523
509
  function normalizeHeaders(headers) {
@@ -950,10 +936,9 @@ function isFullMediaType(mediaType) {
950
936
 
951
937
  // src/cancel-response-body.ts
952
938
  async function cancelResponseBody(response) {
953
- var _a3;
954
939
  try {
955
- await ((_a3 = response.body) == null ? void 0 : _a3.cancel());
956
- } catch (e) {
940
+ await response.body?.cancel();
941
+ } catch {
957
942
  }
958
943
  }
959
944
 
@@ -991,7 +976,7 @@ function isBrowserRuntime(globalThisAny = globalThis) {
991
976
  function isSameOrigin(url, baseUrl) {
992
977
  try {
993
978
  return new URL(url).origin === new URL(baseUrl).origin;
994
- } catch (e) {
979
+ } catch {
995
980
  return false;
996
981
  }
997
982
  }
@@ -1001,7 +986,7 @@ function validateDownloadUrl(url) {
1001
986
  let parsed;
1002
987
  try {
1003
988
  parsed = new URL(url);
1004
- } catch (e) {
989
+ } catch {
1005
990
  throw new DownloadError({
1006
991
  url,
1007
992
  message: `Invalid URL: ${url}`
@@ -1187,15 +1172,14 @@ function createSafeLookup(lookup) {
1187
1172
  }
1188
1173
  var safeNodeFetchPromise;
1189
1174
  function isNodeRuntime() {
1190
- var _a3, _b3, _c;
1191
1175
  const runtimeProcess = globalThis.process;
1192
- return ((_a3 = runtimeProcess == null ? void 0 : runtimeProcess.release) == null ? void 0 : _a3.name) === "node" && ((_b3 = runtimeProcess.versions) == null ? void 0 : _b3.bun) == null && ((_c = runtimeProcess.versions) == null ? void 0 : _c.deno) == null && runtimeProcess.title !== "workerd" && globalThis.EdgeRuntime == null;
1176
+ return runtimeProcess?.release?.name === "node" && runtimeProcess.versions?.bun == null && runtimeProcess.versions?.deno == null && runtimeProcess.title !== "workerd" && globalThis.EdgeRuntime == null;
1193
1177
  }
1194
1178
  async function getDefaultDownloadFetch() {
1195
1179
  if (!isNodeRuntime()) {
1196
1180
  return globalThis.fetch;
1197
1181
  }
1198
- return safeNodeFetchPromise != null ? safeNodeFetchPromise : safeNodeFetchPromise = Promise.resolve().then(createSafeNodeFetch);
1182
+ return safeNodeFetchPromise ??= Promise.resolve().then(createSafeNodeFetch);
1199
1183
  }
1200
1184
  function createSafeNodeFetch() {
1201
1185
  const module = loadBuiltinModule("node:module");
@@ -1216,9 +1200,8 @@ function createSafeNodeFetch() {
1216
1200
  ));
1217
1201
  }
1218
1202
  function loadBuiltinModule(id) {
1219
- var _a3;
1220
1203
  const processWithBuiltins = globalThis.process;
1221
- const builtinModule = (_a3 = processWithBuiltins == null ? void 0 : processWithBuiltins.getBuiltinModule) == null ? void 0 : _a3.call(processWithBuiltins, id);
1204
+ const builtinModule = processWithBuiltins?.getBuiltinModule?.(id);
1222
1205
  if (builtinModule == null) {
1223
1206
  throw new Error(`Node.js built-in module ${id} is unavailable`);
1224
1207
  }
@@ -1231,7 +1214,7 @@ function getCurrentModulePath() {
1231
1214
  const error = new Error("Capture current module path");
1232
1215
  Error.captureStackTrace(error, getCurrentModulePath);
1233
1216
  const [caller] = error.stack;
1234
- const fileName = caller == null ? void 0 : caller.getFileName();
1217
+ const fileName = caller?.getFileName();
1235
1218
  if (fileName == null) {
1236
1219
  throw new Error("Unable to determine the current module path");
1237
1220
  }
@@ -1309,7 +1292,6 @@ async function fetchWithValidatedRedirects({
1309
1292
  fetch: customFetch,
1310
1293
  trustedOrigin
1311
1294
  }) {
1312
- var _a3;
1313
1295
  let currentHeaders = headers === void 0 ? void 0 : sanitizeRequestHeaders(headers);
1314
1296
  const perHopInit = (redirect) => {
1315
1297
  const init = { signal: abortSignal, redirect };
@@ -1335,7 +1317,7 @@ async function fetchWithValidatedRedirects({
1335
1317
  }
1336
1318
  return await fetch(currentUrl, perHopInit("follow"));
1337
1319
  }
1338
- const location = (_a3 = response.headers) == null ? void 0 : _a3.get("location");
1320
+ const location = response.headers?.get("location");
1339
1321
  if (REDIRECT_STATUS_CODES.has(response.status) && location) {
1340
1322
  void cancelResponseBody(response);
1341
1323
  const nextUrl = new URL(location, currentUrl).toString();
@@ -1356,6 +1338,52 @@ async function fetchWithValidatedRedirects({
1356
1338
  });
1357
1339
  }
1358
1340
 
1341
+ // src/fetch-untrusted-url.ts
1342
+ var SAFE_UNTRUSTED_FIRST_HOP_HEADERS = /* @__PURE__ */ new Set([
1343
+ "accept",
1344
+ "accept-language",
1345
+ "baggage",
1346
+ "cache-control",
1347
+ "idempotency-key",
1348
+ "if-match",
1349
+ "if-modified-since",
1350
+ "if-none-match",
1351
+ "if-range",
1352
+ "if-unmodified-since",
1353
+ "pragma",
1354
+ "range",
1355
+ "traceparent",
1356
+ "tracestate",
1357
+ "user-agent",
1358
+ "x-correlation-id",
1359
+ "x-request-id"
1360
+ ]);
1361
+ async function fetchUntrustedUrl({
1362
+ headers,
1363
+ credentialedOrigin,
1364
+ untrustedFirstHopHeaders,
1365
+ ...options
1366
+ }) {
1367
+ let firstHopHeaders;
1368
+ if (headers !== void 0) {
1369
+ firstHopHeaders = sanitizeRequestHeaders(headers);
1370
+ const origin = credentialedOrigin ?? options.trustedOrigin;
1371
+ if (origin === void 0 || !isSameOrigin(options.url, origin)) {
1372
+ const allowedHeaders = /* @__PURE__ */ new Set([
1373
+ ...SAFE_UNTRUSTED_FIRST_HOP_HEADERS,
1374
+ ...(untrustedFirstHopHeaders ?? []).map((name3) => name3.toLowerCase())
1375
+ ]);
1376
+ firstHopHeaders = new Headers(
1377
+ [...firstHopHeaders].filter(([name3]) => allowedHeaders.has(name3))
1378
+ );
1379
+ }
1380
+ }
1381
+ return fetchWithValidatedRedirects({
1382
+ ...options,
1383
+ headers: firstHopHeaders
1384
+ });
1385
+ }
1386
+
1359
1387
  // src/read-response-with-size-limit.ts
1360
1388
  var DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
1361
1389
  async function readResponseWithSizeLimit({
@@ -1399,7 +1427,7 @@ async function readResponseWithSizeLimit({
1399
1427
  } finally {
1400
1428
  try {
1401
1429
  await reader.cancel();
1402
- } catch (e) {
1430
+ } catch {
1403
1431
  } finally {
1404
1432
  reader.releaseLock();
1405
1433
  }
@@ -1415,11 +1443,10 @@ async function readResponseWithSizeLimit({
1415
1443
 
1416
1444
  // src/download-blob.ts
1417
1445
  async function downloadBlob(url, options) {
1418
- var _a3, _b3;
1419
1446
  try {
1420
- const response = await fetchWithValidatedRedirects({
1447
+ const response = await fetchUntrustedUrl({
1421
1448
  url,
1422
- abortSignal: options == null ? void 0 : options.abortSignal
1449
+ abortSignal: options?.abortSignal
1423
1450
  });
1424
1451
  if (!response.ok) {
1425
1452
  await cancelResponseBody(response);
@@ -1432,9 +1459,9 @@ async function downloadBlob(url, options) {
1432
1459
  const data = await readResponseWithSizeLimit({
1433
1460
  response,
1434
1461
  url,
1435
- maxBytes: (_a3 = options == null ? void 0 : options.maxBytes) != null ? _a3 : DEFAULT_MAX_DOWNLOAD_SIZE
1462
+ maxBytes: options?.maxBytes ?? DEFAULT_MAX_DOWNLOAD_SIZE
1436
1463
  });
1437
- const contentType = (_b3 = response.headers.get("content-type")) != null ? _b3 : void 0;
1464
+ const contentType = response.headers.get("content-type") ?? void 0;
1438
1465
  return new Blob([data], contentType ? { type: contentType } : void 0);
1439
1466
  } catch (error) {
1440
1467
  if (DownloadError.isInstance(error)) {
@@ -1461,8 +1488,8 @@ function extractLines({
1461
1488
  if (startLine == null && endLine == null) return text;
1462
1489
  const lineEnding = text.includes("\r\n") ? "\r\n" : text.includes("\n") ? "\n" : text.includes("\r") ? "\r" : "\n";
1463
1490
  const lines = text.split(lineEnding);
1464
- const start = Math.max(1, startLine != null ? startLine : 1) - 1;
1465
- const end = Math.min(lines.length, endLine != null ? endLine : lines.length);
1491
+ const start = Math.max(1, startLine ?? 1) - 1;
1492
+ const end = Math.min(lines.length, endLine ?? lines.length);
1466
1493
  return lines.slice(start, end).join(lineEnding);
1467
1494
  }
1468
1495
 
@@ -1518,7 +1545,7 @@ var getFromApi = async ({
1518
1545
  trustedOrigin
1519
1546
  }) => {
1520
1547
  try {
1521
- const requestFetch = fetch != null ? fetch : getOriginalFetch2();
1548
+ const requestFetch = fetch ?? getOriginalFetch2();
1522
1549
  const outgoingHeaders = credentialedOrigin !== void 0 && !isSameOrigin(url, credentialedOrigin) ? {} : headers;
1523
1550
  const requestHeaders = withUserAgentSuffix(
1524
1551
  outgoingHeaders,
@@ -1611,8 +1638,7 @@ function injectJsonInstructionIntoMessages({
1611
1638
  schemaPrefix,
1612
1639
  schemaSuffix
1613
1640
  }) {
1614
- var _a3, _b3;
1615
- const systemMessage = ((_a3 = messages[0]) == null ? void 0 : _a3.role) === "system" ? { ...messages[0] } : { role: "system", content: "" };
1641
+ const systemMessage = messages[0]?.role === "system" ? { ...messages[0] } : { role: "system", content: "" };
1616
1642
  systemMessage.content = injectJsonInstruction({
1617
1643
  prompt: systemMessage.content,
1618
1644
  schema,
@@ -1621,14 +1647,13 @@ function injectJsonInstructionIntoMessages({
1621
1647
  });
1622
1648
  return [
1623
1649
  systemMessage,
1624
- ...((_b3 = messages[0]) == null ? void 0 : _b3.role) === "system" ? messages.slice(1) : messages
1650
+ ...messages[0]?.role === "system" ? messages.slice(1) : messages
1625
1651
  ];
1626
1652
  }
1627
1653
 
1628
1654
  // src/is-buffer.ts
1629
1655
  function isBuffer(value) {
1630
- var _a3, _b3;
1631
- return (_b3 = (_a3 = globalThis.Buffer) == null ? void 0 : _a3.isBuffer(value)) != null ? _b3 : false;
1656
+ return globalThis.Buffer?.isBuffer(value) ?? false;
1632
1657
  }
1633
1658
 
1634
1659
  // src/is-non-nullable.ts
@@ -1665,7 +1690,7 @@ function isUrlSupported({
1665
1690
  if (isTopLevelOnly) {
1666
1691
  return `${mediaType}/` === mediaTypePrefix;
1667
1692
  }
1668
- return mediaType.startsWith(mediaTypePrefix);
1693
+ return mediaTypePrefix.endsWith("/") ? mediaType.startsWith(mediaTypePrefix) : mediaType === mediaTypePrefix;
1669
1694
  }).flatMap(({ regexes }) => regexes).some((pattern) => testRegExpFromStart(pattern, url));
1670
1695
  }
1671
1696
  function testRegExpFromStart(pattern, value) {
@@ -1828,15 +1853,14 @@ function mapReasoningToProviderBudget({
1828
1853
 
1829
1854
  // src/media-type-to-extension.ts
1830
1855
  function mediaTypeToExtension(mediaType) {
1831
- var _a3;
1832
1856
  const [_type, subtype = ""] = mediaType.toLowerCase().split("/");
1833
- return (_a3 = {
1857
+ return {
1834
1858
  mpeg: "mp3",
1835
1859
  "x-wav": "wav",
1836
1860
  opus: "ogg",
1837
1861
  mp4: "m4a",
1838
1862
  "x-m4a": "m4a"
1839
- }[subtype]) != null ? _a3 : subtype;
1863
+ }[subtype] ?? subtype;
1840
1864
  }
1841
1865
 
1842
1866
  // src/normalize-batch-request-counts.ts
@@ -1904,7 +1928,7 @@ function secureJsonParse(text) {
1904
1928
  const { stackTraceLimit } = Error;
1905
1929
  try {
1906
1930
  Error.stackTraceLimit = 0;
1907
- } catch (e) {
1931
+ } catch {
1908
1932
  return _parse(text);
1909
1933
  }
1910
1934
  try {
@@ -2001,11 +2025,10 @@ function parseAnyDef() {
2001
2025
 
2002
2026
  // src/to-json-schema/zod3-to-json-schema/parsers/array.ts
2003
2027
  function parseArrayDef(def, refs) {
2004
- var _a3, _b3, _c;
2005
2028
  const res = {
2006
2029
  type: "array"
2007
2030
  };
2008
- if (((_a3 = def.type) == null ? void 0 : _a3._def) && ((_c = (_b3 = def.type) == null ? void 0 : _b3._def) == null ? void 0 : _c.typeName) !== "ZodAny") {
2031
+ if (def.type?._def && def.type?._def?.typeName !== "ZodAny") {
2009
2032
  res.items = parseDef(def.type._def, {
2010
2033
  ...refs,
2011
2034
  currentPath: [...refs.currentPath, "items"]
@@ -2072,7 +2095,7 @@ var parseCatchDef = (def, refs) => {
2072
2095
 
2073
2096
  // src/to-json-schema/zod3-to-json-schema/parsers/date.ts
2074
2097
  function parseDateDef(def, refs, overrideDateStrategy) {
2075
- const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
2098
+ const strategy = overrideDateStrategy ?? refs.dateStrategy;
2076
2099
  if (Array.isArray(strategy)) {
2077
2100
  return {
2078
2101
  anyOf: strategy.map((item) => parseDateDef(def, refs, item))
@@ -2393,8 +2416,7 @@ function escapeNonAlphaNumeric(source) {
2393
2416
  return result;
2394
2417
  }
2395
2418
  function addFormat(schema, value, message, refs) {
2396
- var _a3;
2397
- if (schema.format || ((_a3 = schema.anyOf) == null ? void 0 : _a3.some((x) => x.format))) {
2419
+ if (schema.format || schema.anyOf?.some((x) => x.format)) {
2398
2420
  if (!schema.anyOf) {
2399
2421
  schema.anyOf = [];
2400
2422
  }
@@ -2413,8 +2435,7 @@ function addFormat(schema, value, message, refs) {
2413
2435
  }
2414
2436
  }
2415
2437
  function addPattern(schema, regex, message, refs) {
2416
- var _a3;
2417
- if (schema.pattern || ((_a3 = schema.allOf) == null ? void 0 : _a3.some((x) => x.pattern))) {
2438
+ if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
2418
2439
  if (!schema.allOf) {
2419
2440
  schema.allOf = [];
2420
2441
  }
@@ -2433,7 +2454,6 @@ function addPattern(schema, regex, message, refs) {
2433
2454
  }
2434
2455
  }
2435
2456
  function stringifyRegExpWithFlags(regex, refs) {
2436
- var _a3;
2437
2457
  if (!refs.applyRegexFlags || !regex.flags) {
2438
2458
  return regex.source;
2439
2459
  }
@@ -2463,7 +2483,7 @@ function stringifyRegExpWithFlags(regex, refs) {
2463
2483
  pattern += source[i];
2464
2484
  pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
2465
2485
  inCharRange = false;
2466
- } else if (source[i + 1] === "-" && ((_a3 = source[i + 2]) == null ? void 0 : _a3.match(/[a-z]/))) {
2486
+ } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
2467
2487
  pattern += source[i];
2468
2488
  inCharRange = true;
2469
2489
  } else {
@@ -2504,7 +2524,7 @@ function stringifyRegExpWithFlags(regex, refs) {
2504
2524
  }
2505
2525
  try {
2506
2526
  new RegExp(pattern);
2507
- } catch (e) {
2527
+ } catch {
2508
2528
  console.warn(
2509
2529
  `Could not convert regex pattern at ${refs.currentPath.join(
2510
2530
  "/"
@@ -2517,28 +2537,27 @@ function stringifyRegExpWithFlags(regex, refs) {
2517
2537
 
2518
2538
  // src/to-json-schema/zod3-to-json-schema/parsers/record.ts
2519
2539
  function parseRecordDef(def, refs) {
2520
- var _a3, _b3, _c, _d, _e, _f;
2521
2540
  const schema = {
2522
2541
  type: "object",
2523
- additionalProperties: (_a3 = parseDef(def.valueType._def, {
2542
+ additionalProperties: parseDef(def.valueType._def, {
2524
2543
  ...refs,
2525
2544
  currentPath: [...refs.currentPath, "additionalProperties"]
2526
- })) != null ? _a3 : refs.allowedAdditionalProperties
2545
+ }) ?? refs.allowedAdditionalProperties
2527
2546
  };
2528
- if (((_b3 = def.keyType) == null ? void 0 : _b3._def.typeName) === "ZodString" && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
2547
+ if (def.keyType?._def.typeName === "ZodString" && def.keyType._def.checks?.length) {
2529
2548
  const { type: _type, ...keyType } = parseStringDef(def.keyType._def, refs);
2530
2549
  return {
2531
2550
  ...schema,
2532
2551
  propertyNames: keyType
2533
2552
  };
2534
- } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === "ZodEnum") {
2553
+ } else if (def.keyType?._def.typeName === "ZodEnum") {
2535
2554
  return {
2536
2555
  ...schema,
2537
2556
  propertyNames: {
2538
2557
  enum: def.keyType._def.values
2539
2558
  }
2540
2559
  };
2541
- } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === "ZodBranded" && def.keyType._def.type._def.typeName === "ZodString" && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
2560
+ } else if (def.keyType?._def.typeName === "ZodBranded" && def.keyType._def.type._def.typeName === "ZodString" && def.keyType._def.type._def.checks?.length) {
2542
2561
  const { type: _type, ...keyType } = parseBrandedDef(
2543
2562
  def.keyType._def,
2544
2563
  refs
@@ -2791,15 +2810,14 @@ function decideAdditionalProperties(def, refs) {
2791
2810
  function safeIsOptional(schema) {
2792
2811
  try {
2793
2812
  return schema.isOptional();
2794
- } catch (e) {
2813
+ } catch {
2795
2814
  return true;
2796
2815
  }
2797
2816
  }
2798
2817
 
2799
2818
  // src/to-json-schema/zod3-to-json-schema/parsers/optional.ts
2800
2819
  var parseOptionalDef = (def, refs) => {
2801
- var _a3;
2802
- if (refs.currentPath.toString() === ((_a3 = refs.propertyPath) == null ? void 0 : _a3.toString())) {
2820
+ if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
2803
2821
  return parseDef(def.innerType._def, refs);
2804
2822
  }
2805
2823
  const innerSchema = parseDef(def.innerType._def, {
@@ -2998,11 +3016,9 @@ var getRelativePath = (pathA, pathB) => {
2998
3016
 
2999
3017
  // src/to-json-schema/zod3-to-json-schema/parse-def.ts
3000
3018
  function parseDef(def, refs, forceResolution = false) {
3001
- var _a3;
3002
3019
  const seenItem = refs.seen.get(def);
3003
3020
  if (refs.override) {
3004
- const overrideResult = (_a3 = refs.override) == null ? void 0 : _a3.call(
3005
- refs,
3021
+ const overrideResult = refs.override?.(
3006
3022
  def,
3007
3023
  refs,
3008
3024
  seenItem,
@@ -3084,34 +3100,30 @@ var getRefs = (options) => {
3084
3100
 
3085
3101
  // src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts
3086
3102
  var zod3ToJsonSchema = (schema, options) => {
3087
- var _a3;
3088
3103
  const refs = getRefs(options);
3089
3104
  let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
3090
- (acc, [name4, schema2]) => {
3091
- var _a4;
3092
- return {
3093
- ...acc,
3094
- [name4]: (_a4 = parseDef(
3095
- schema2._def,
3096
- {
3097
- ...refs,
3098
- currentPath: [...refs.basePath, refs.definitionPath, name4]
3099
- },
3100
- true
3101
- )) != null ? _a4 : parseAnyDef()
3102
- };
3103
- },
3105
+ (acc, [name4, schema2]) => ({
3106
+ ...acc,
3107
+ [name4]: parseDef(
3108
+ schema2._def,
3109
+ {
3110
+ ...refs,
3111
+ currentPath: [...refs.basePath, refs.definitionPath, name4]
3112
+ },
3113
+ true
3114
+ ) ?? parseAnyDef()
3115
+ }),
3104
3116
  {}
3105
3117
  ) : void 0;
3106
- const name3 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
3107
- const main = (_a3 = parseDef(
3118
+ const name3 = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
3119
+ const main = parseDef(
3108
3120
  schema._def,
3109
3121
  name3 === void 0 ? refs : {
3110
3122
  ...refs,
3111
3123
  currentPath: [...refs.basePath, refs.definitionPath, name3]
3112
3124
  },
3113
3125
  false
3114
- )) != null ? _a3 : parseAnyDef();
3126
+ ) ?? parseAnyDef();
3115
3127
  const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
3116
3128
  if (title !== void 0) {
3117
3129
  main.title = title;
@@ -3203,8 +3215,7 @@ function hasStandardJsonSchema(schema) {
3203
3215
  return schema["~standard"].jsonSchema != null;
3204
3216
  }
3205
3217
  function zod3Schema(zodSchema2, options) {
3206
- var _a3;
3207
- const useReferences = (_a3 = options == null ? void 0 : options.useReferences) != null ? _a3 : false;
3218
+ const useReferences = options?.useReferences ?? false;
3208
3219
  return jsonSchema(
3209
3220
  // defer json schema creation to avoid unnecessary computation when only validation is needed
3210
3221
  () => zod3ToJsonSchema(zodSchema2, {
@@ -3219,8 +3230,7 @@ function zod3Schema(zodSchema2, options) {
3219
3230
  );
3220
3231
  }
3221
3232
  function zod4Schema(zodSchema2, options) {
3222
- var _a3;
3223
- const useReferences = (_a3 = options == null ? void 0 : options.useReferences) != null ? _a3 : false;
3233
+ const useReferences = options?.useReferences ?? false;
3224
3234
  return jsonSchema(
3225
3235
  // defer json schema creation to avoid unnecessary computation when only validation is needed
3226
3236
  () => addAdditionalPropertiesToJsonSchema(
@@ -3329,7 +3339,7 @@ function isParsableJson(input) {
3329
3339
  try {
3330
3340
  secureJsonParse(input);
3331
3341
  return true;
3332
- } catch (e) {
3342
+ } catch {
3333
3343
  return false;
3334
3344
  }
3335
3345
  }
@@ -3361,7 +3371,7 @@ async function parseProviderOptions({
3361
3371
  providerOptions,
3362
3372
  schema
3363
3373
  }) {
3364
- if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
3374
+ if (providerOptions?.[provider] == null) {
3365
3375
  return void 0;
3366
3376
  }
3367
3377
  const parsedProviderOptions = await safeValidateTypes({
@@ -3390,7 +3400,6 @@ function createMultipartBody(parts, boundary) {
3390
3400
  let activeReader;
3391
3401
  const enteredStreams = /* @__PURE__ */ new Set();
3392
3402
  async function* emitParts() {
3393
- var _a3, _b3;
3394
3403
  for (const part of parts) {
3395
3404
  if (disposed) return;
3396
3405
  const disposition = `--${boundary}\r
@@ -3403,9 +3412,9 @@ ${part.value}\r
3403
3412
  continue;
3404
3413
  }
3405
3414
  const filenameParameter = `; filename="${escapeMultipartHeaderValue(
3406
- (_a3 = part.filename) != null ? _a3 : "blob"
3415
+ part.filename ?? "blob"
3407
3416
  )}"`;
3408
- const mediaType = ((_b3 = part.mediaType) != null ? _b3 : "application/octet-stream").replace(
3417
+ const mediaType = (part.mediaType ?? "application/octet-stream").replace(
3409
3418
  /[\r\n]/g,
3410
3419
  ""
3411
3420
  );
@@ -3476,13 +3485,10 @@ var postMultipartStreamToApi = async ({
3476
3485
  }) => {
3477
3486
  const boundary = `ai-sdk-multipart-${generateId()}`;
3478
3487
  const requestBodyValues = Object.fromEntries(
3479
- parts.map((part) => {
3480
- var _a3;
3481
- return [
3482
- part.name,
3483
- part.type === "field" ? part.value : `<file:${(_a3 = part.filename) != null ? _a3 : part.name}>`
3484
- ];
3485
- })
3488
+ parts.map((part) => [
3489
+ part.name,
3490
+ part.type === "field" ? part.value : `<file:${part.filename ?? part.name}>`
3491
+ ])
3486
3492
  );
3487
3493
  const body = createMultipartBody(parts, boundary);
3488
3494
  try {
@@ -3979,7 +3985,7 @@ var createJsonErrorResponseHandler = ({
3979
3985
  statusCode: response.status,
3980
3986
  responseHeaders,
3981
3987
  responseBody,
3982
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
3988
+ isRetryable: isRetryable?.(response)
3983
3989
  })
3984
3990
  };
3985
3991
  }
@@ -3998,10 +4004,10 @@ var createJsonErrorResponseHandler = ({
3998
4004
  responseHeaders,
3999
4005
  responseBody,
4000
4006
  data: parsedError,
4001
- isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
4007
+ isRetryable: isRetryable?.(response, parsedError)
4002
4008
  })
4003
4009
  };
4004
- } catch (e) {
4010
+ } catch {
4005
4011
  return {
4006
4012
  responseHeaders,
4007
4013
  value: new APICallError6({
@@ -4011,7 +4017,7 @@ var createJsonErrorResponseHandler = ({
4011
4017
  statusCode: response.status,
4012
4018
  responseHeaders,
4013
4019
  responseBody,
4014
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
4020
+ isRetryable: isRetryable?.(response)
4015
4021
  })
4016
4022
  };
4017
4023
  }
@@ -4248,10 +4254,9 @@ var StreamingToolCallTracker = class {
4248
4254
  this.toolCalls = /* @__PURE__ */ new Set();
4249
4255
  this.toolCallsById = /* @__PURE__ */ new Map();
4250
4256
  this.toolCallsByIndex = /* @__PURE__ */ new Map();
4251
- var _a3, _b3;
4252
4257
  this.controller = controller;
4253
- this._generateId = (_a3 = options.generateId) != null ? _a3 : generateId;
4254
- this.typeValidation = (_b3 = options.typeValidation) != null ? _b3 : "none";
4258
+ this._generateId = options.generateId ?? generateId;
4259
+ this.typeValidation = options.typeValidation ?? "none";
4255
4260
  this.extractMetadata = options.extractMetadata;
4256
4261
  this.buildToolCallProviderMetadata = options.buildToolCallProviderMetadata;
4257
4262
  }
@@ -4285,7 +4290,6 @@ var StreamingToolCallTracker = class {
4285
4290
  }
4286
4291
  }
4287
4292
  processNewToolCall(toolCallDelta) {
4288
- var _a3, _b3, _c;
4289
4293
  if (this.typeValidation === "required") {
4290
4294
  if (toolCallDelta.type !== "function") {
4291
4295
  throw new InvalidResponseDataError({
@@ -4307,7 +4311,7 @@ var StreamingToolCallTracker = class {
4307
4311
  message: `Expected 'id' to be a string.`
4308
4312
  });
4309
4313
  }
4310
- if (((_a3 = toolCallDelta.function) == null ? void 0 : _a3.name) == null) {
4314
+ if (toolCallDelta.function?.name == null) {
4311
4315
  throw new InvalidResponseDataError({
4312
4316
  data: toolCallDelta,
4313
4317
  message: `Expected 'function.name' to be a string.`
@@ -4318,13 +4322,13 @@ var StreamingToolCallTracker = class {
4318
4322
  id: toolCallDelta.id,
4319
4323
  toolName: toolCallDelta.function.name
4320
4324
  });
4321
- const metadata = (_b3 = this.extractMetadata) == null ? void 0 : _b3.call(this, toolCallDelta);
4325
+ const metadata = this.extractMetadata?.(toolCallDelta);
4322
4326
  const toolCall = {
4323
4327
  id: toolCallDelta.id,
4324
4328
  type: "function",
4325
4329
  function: {
4326
4330
  name: toolCallDelta.function.name,
4327
- arguments: (_c = toolCallDelta.function.arguments) != null ? _c : ""
4331
+ arguments: toolCallDelta.function.arguments ?? ""
4328
4332
  },
4329
4333
  hasFinished: false,
4330
4334
  metadata
@@ -4343,11 +4347,10 @@ var StreamingToolCallTracker = class {
4343
4347
  return toolCall;
4344
4348
  }
4345
4349
  processExistingToolCall(toolCall, toolCallDelta) {
4346
- var _a3;
4347
4350
  if (toolCall.hasFinished) {
4348
4351
  return;
4349
4352
  }
4350
- if (((_a3 = toolCallDelta.function) == null ? void 0 : _a3.arguments) != null) {
4353
+ if (toolCallDelta.function?.arguments != null) {
4351
4354
  toolCall.function.arguments += toolCallDelta.function.arguments;
4352
4355
  this.controller.enqueue({
4353
4356
  type: "tool-input-delta",
@@ -4357,18 +4360,16 @@ var StreamingToolCallTracker = class {
4357
4360
  }
4358
4361
  }
4359
4362
  finishToolCall(toolCall) {
4360
- var _a3, _b3;
4361
4363
  this.controller.enqueue({
4362
4364
  type: "tool-input-end",
4363
4365
  id: toolCall.id
4364
4366
  });
4365
- const providerMetadata = (_a3 = this.buildToolCallProviderMetadata) == null ? void 0 : _a3.call(
4366
- this,
4367
+ const providerMetadata = this.buildToolCallProviderMetadata?.(
4367
4368
  toolCall.metadata
4368
4369
  );
4369
4370
  this.controller.enqueue({
4370
4371
  type: "tool-call",
4371
- toolCallId: (_b3 = toolCall.id) != null ? _b3 : this._generateId(),
4372
+ toolCallId: toolCall.id ?? this._generateId(),
4372
4373
  toolName: toolCall.function.name,
4373
4374
  input: toolCall.function.arguments,
4374
4375
  ...providerMetadata ? { providerMetadata } : {}
@@ -4390,7 +4391,7 @@ function parseTranscriptionStreamClientFrame(text) {
4390
4391
  let value;
4391
4392
  try {
4392
4393
  value = secureJsonParse(text);
4393
- } catch (e) {
4394
+ } catch {
4394
4395
  return { type: "invalid", message: "malformed JSON" };
4395
4396
  }
4396
4397
  if (value == null || typeof value !== "object" || Array.isArray(value)) {
@@ -4447,7 +4448,7 @@ function serializeTranscriptionStreamPart(part) {
4447
4448
  });
4448
4449
  }
4449
4450
  return JSON.stringify(part);
4450
- } catch (e) {
4451
+ } catch {
4451
4452
  return void 0;
4452
4453
  }
4453
4454
  }
@@ -4458,7 +4459,7 @@ function parseTranscriptionStreamPart(text) {
4458
4459
  let value;
4459
4460
  try {
4460
4461
  value = secureJsonParse(text);
4461
- } catch (e) {
4462
+ } catch {
4462
4463
  return void 0;
4463
4464
  }
4464
4465
  if (value == null || typeof value !== "object" || Array.isArray(value)) {
@@ -4517,7 +4518,7 @@ function isSegment(value) {
4517
4518
  // src/validate-base-url.ts
4518
4519
  import { InvalidArgumentError as InvalidArgumentError3 } from "@ai-sdk/provider";
4519
4520
  function validateBaseURL(baseURL) {
4520
- if ((baseURL == null ? void 0 : baseURL.trim()) === "") {
4521
+ if (baseURL?.trim() === "") {
4521
4522
  throw new InvalidArgumentError3({
4522
4523
  argument: "baseURL",
4523
4524
  message: "baseURL must be a non-empty string."
@@ -4528,7 +4529,7 @@ function validateBaseURL(baseURL) {
4528
4529
 
4529
4530
  // src/without-trailing-slash.ts
4530
4531
  function withoutTrailingSlash(url) {
4531
- return url == null ? void 0 : url.replace(/\/$/, "");
4532
+ return url?.replace(/\/$/, "");
4532
4533
  }
4533
4534
 
4534
4535
  // src/types/executable-tool.ts
@@ -4567,7 +4568,7 @@ function toolCaller(tool2, definition) {
4567
4568
  });
4568
4569
  }
4569
4570
  function getToolCaller(tool2) {
4570
- return tool2 == null ? void 0 : tool2.experimental_toolCaller;
4571
+ return tool2?.experimental_toolCaller;
4571
4572
  }
4572
4573
 
4573
4574
  // src/index.ts
@@ -4629,6 +4630,7 @@ export {
4629
4630
  toolCaller as experimental_toolCaller,
4630
4631
  extractLines,
4631
4632
  extractResponseHeaders,
4633
+ fetchUntrustedUrl,
4632
4634
  fetchWithValidatedEndpoint,
4633
4635
  fetchWithValidatedRedirects,
4634
4636
  filterNullable,