@xata.io/client 0.0.0-alpha.vfd68d20 → 0.0.0-alpha.vfd68f4d

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
@@ -1,5 +1,6 @@
1
- const defaultTrace = async (_name, fn, _options) => {
1
+ const defaultTrace = async (name, fn, _options) => {
2
2
  return await fn({
3
+ name,
3
4
  setAttributes: () => {
4
5
  return;
5
6
  }
@@ -41,6 +42,18 @@ function isStringArray(value) {
41
42
  function isNumber(value) {
42
43
  return isDefined(value) && typeof value === "number";
43
44
  }
45
+ function parseNumber(value) {
46
+ if (isNumber(value)) {
47
+ return value;
48
+ }
49
+ if (isString(value)) {
50
+ const parsed = Number(value);
51
+ if (!Number.isNaN(parsed)) {
52
+ return parsed;
53
+ }
54
+ }
55
+ return void 0;
56
+ }
44
57
  function toBase64(value) {
45
58
  try {
46
59
  return btoa(value);
@@ -60,10 +73,20 @@ function deepMerge(a, b) {
60
73
  }
61
74
  return result;
62
75
  }
76
+ function chunk(array, chunkSize) {
77
+ const result = [];
78
+ for (let i = 0; i < array.length; i += chunkSize) {
79
+ result.push(array.slice(i, i + chunkSize));
80
+ }
81
+ return result;
82
+ }
83
+ async function timeout(ms) {
84
+ return new Promise((resolve) => setTimeout(resolve, ms));
85
+ }
63
86
 
64
87
  function getEnvironment() {
65
88
  try {
66
- if (isObject(process) && isObject(process.env)) {
89
+ if (isDefined(process) && isDefined(process.env)) {
67
90
  return {
68
91
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
69
92
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
@@ -147,9 +170,6 @@ async function getGitBranch() {
147
170
  const nodeModule = ["child", "process"].join("_");
148
171
  const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
149
172
  try {
150
- if (typeof require === "function") {
151
- return require(nodeModule).execSync(fullCmd, execOptions).trim();
152
- }
153
173
  const { execSync } = await import(nodeModule);
154
174
  return execSync(fullCmd, execOptions).toString().trim();
155
175
  } catch (err) {
@@ -172,6 +192,29 @@ function getAPIKey() {
172
192
  }
173
193
  }
174
194
 
195
+ var __accessCheck$8 = (obj, member, msg) => {
196
+ if (!member.has(obj))
197
+ throw TypeError("Cannot " + msg);
198
+ };
199
+ var __privateGet$8 = (obj, member, getter) => {
200
+ __accessCheck$8(obj, member, "read from private field");
201
+ return getter ? getter.call(obj) : member.get(obj);
202
+ };
203
+ var __privateAdd$8 = (obj, member, value) => {
204
+ if (member.has(obj))
205
+ throw TypeError("Cannot add the same private member more than once");
206
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
207
+ };
208
+ var __privateSet$8 = (obj, member, value, setter) => {
209
+ __accessCheck$8(obj, member, "write to private field");
210
+ setter ? setter.call(obj, value) : member.set(obj, value);
211
+ return value;
212
+ };
213
+ var __privateMethod$4 = (obj, member, method) => {
214
+ __accessCheck$8(obj, member, "access private method");
215
+ return method;
216
+ };
217
+ var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
175
218
  function getFetchImplementation(userFetch) {
176
219
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
177
220
  const fetchImpl = userFetch ?? globalFetch;
@@ -182,8 +225,81 @@ function getFetchImplementation(userFetch) {
182
225
  }
183
226
  return fetchImpl;
184
227
  }
228
+ class ApiRequestPool {
229
+ constructor(concurrency = 10) {
230
+ __privateAdd$8(this, _enqueue);
231
+ __privateAdd$8(this, _fetch, void 0);
232
+ __privateAdd$8(this, _queue, void 0);
233
+ __privateAdd$8(this, _concurrency, void 0);
234
+ __privateSet$8(this, _queue, []);
235
+ __privateSet$8(this, _concurrency, concurrency);
236
+ this.running = 0;
237
+ this.started = 0;
238
+ }
239
+ setFetch(fetch2) {
240
+ __privateSet$8(this, _fetch, fetch2);
241
+ }
242
+ getFetch() {
243
+ if (!__privateGet$8(this, _fetch)) {
244
+ throw new Error("Fetch not set");
245
+ }
246
+ return __privateGet$8(this, _fetch);
247
+ }
248
+ request(url, options) {
249
+ const start = new Date();
250
+ const fetch2 = this.getFetch();
251
+ const runRequest = async (stalled = false) => {
252
+ const response = await fetch2(url, options);
253
+ if (response.status === 429) {
254
+ const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
255
+ await timeout(rateLimitReset * 1e3);
256
+ return await runRequest(true);
257
+ }
258
+ if (stalled) {
259
+ const stalledTime = new Date().getTime() - start.getTime();
260
+ console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
261
+ }
262
+ return response;
263
+ };
264
+ return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
265
+ return await runRequest();
266
+ });
267
+ }
268
+ }
269
+ _fetch = new WeakMap();
270
+ _queue = new WeakMap();
271
+ _concurrency = new WeakMap();
272
+ _enqueue = new WeakSet();
273
+ enqueue_fn = function(task) {
274
+ const promise = new Promise((resolve) => __privateGet$8(this, _queue).push(resolve)).finally(() => {
275
+ this.started--;
276
+ this.running++;
277
+ }).then(() => task()).finally(() => {
278
+ this.running--;
279
+ const next = __privateGet$8(this, _queue).shift();
280
+ if (next !== void 0) {
281
+ this.started++;
282
+ next();
283
+ }
284
+ });
285
+ if (this.running + this.started < __privateGet$8(this, _concurrency)) {
286
+ const next = __privateGet$8(this, _queue).shift();
287
+ if (next !== void 0) {
288
+ this.started++;
289
+ next();
290
+ }
291
+ }
292
+ return promise;
293
+ };
294
+
295
+ function generateUUID() {
296
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
297
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
298
+ return v.toString(16);
299
+ });
300
+ }
185
301
 
186
- const VERSION = "0.0.0-alpha.vfd68d20";
302
+ const VERSION = "0.22.0";
187
303
 
188
304
  class ErrorWithCause extends Error {
189
305
  constructor(message, options) {
@@ -194,7 +310,7 @@ class FetcherError extends ErrorWithCause {
194
310
  constructor(status, data, requestId) {
195
311
  super(getMessage(data));
196
312
  this.status = status;
197
- this.errors = isBulkError(data) ? data.errors : void 0;
313
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
198
314
  this.requestId = requestId;
199
315
  if (data instanceof Error) {
200
316
  this.stack = data.stack;
@@ -226,6 +342,7 @@ function getMessage(data) {
226
342
  }
227
343
  }
228
344
 
345
+ const pool = new ApiRequestPool();
229
346
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
230
347
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
231
348
  if (value === void 0 || value === null)
@@ -258,11 +375,12 @@ function hostHeader(url) {
258
375
  const { groups } = pattern.exec(url) ?? {};
259
376
  return groups?.host ? { Host: groups.host } : {};
260
377
  }
378
+ const defaultClientID = generateUUID();
261
379
  async function fetch$1({
262
380
  url: path,
263
381
  method,
264
382
  body,
265
- headers,
383
+ headers: customHeaders,
266
384
  pathParams,
267
385
  queryParams,
268
386
  fetchImpl,
@@ -274,9 +392,12 @@ async function fetch$1({
274
392
  signal,
275
393
  clientID,
276
394
  sessionID,
395
+ clientName,
396
+ xataAgentExtra,
277
397
  fetchOptions = {}
278
398
  }) {
279
- return trace(
399
+ pool.setFetch(fetchImpl);
400
+ return await trace(
280
401
  `${method.toUpperCase()} ${path}`,
281
402
  async ({ setAttributes }) => {
282
403
  const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
@@ -286,24 +407,29 @@ async function fetch$1({
286
407
  [TraceAttributes.HTTP_URL]: url,
287
408
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
288
409
  });
289
- const response = await fetchImpl(url, {
410
+ const xataAgent = compact([
411
+ ["client", "TS_SDK"],
412
+ ["version", VERSION],
413
+ isDefined(clientName) ? ["service", clientName] : void 0,
414
+ ...Object.entries(xataAgentExtra ?? {})
415
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
416
+ const headers = {
417
+ "Accept-Encoding": "identity",
418
+ "Content-Type": "application/json",
419
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
420
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
421
+ "X-Xata-Agent": xataAgent,
422
+ ...customHeaders,
423
+ ...hostHeader(fullUrl),
424
+ Authorization: `Bearer ${apiKey}`
425
+ };
426
+ const response = await pool.request(url, {
290
427
  ...fetchOptions,
291
428
  method: method.toUpperCase(),
292
429
  body: body ? JSON.stringify(body) : void 0,
293
- headers: {
294
- "Content-Type": "application/json",
295
- "User-Agent": `Xata client-ts/${VERSION}`,
296
- "X-Xata-Client-ID": clientID ?? "",
297
- "X-Xata-Session-ID": sessionID ?? "",
298
- ...headers,
299
- ...hostHeader(fullUrl),
300
- Authorization: `Bearer ${apiKey}`
301
- },
430
+ headers,
302
431
  signal
303
432
  });
304
- if (response.status === 204) {
305
- return {};
306
- }
307
433
  const { host, protocol } = parseUrl(response.url);
308
434
  const requestId = response.headers?.get("x-request-id") ?? void 0;
309
435
  setAttributes({
@@ -313,6 +439,12 @@ async function fetch$1({
313
439
  [TraceAttributes.HTTP_HOST]: host,
314
440
  [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
315
441
  });
442
+ if (response.status === 204) {
443
+ return {};
444
+ }
445
+ if (response.status === 429) {
446
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
447
+ }
316
448
  try {
317
449
  const jsonResponse = await response.json();
318
450
  if (response.ok) {
@@ -337,17 +469,12 @@ function parseUrl(url) {
337
469
 
338
470
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
339
471
 
340
- const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
341
472
  const getBranchList = (variables, signal) => dataPlaneFetch({
342
473
  url: "/dbs/{dbName}",
343
474
  method: "get",
344
475
  ...variables,
345
476
  signal
346
477
  });
347
- const dEPRECATEDcreateDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
348
- const dEPRECATEDdeleteDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "delete", ...variables, signal });
349
- const dEPRECATEDgetDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "get", ...variables, signal });
350
- const dEPRECATEDupdateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
351
478
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
352
479
  url: "/db/{dbBranchName}",
353
480
  method: "get",
@@ -386,7 +513,6 @@ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName
386
513
  const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
387
514
  const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
388
515
  const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
389
- const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
390
516
  const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
391
517
  const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
392
518
  const getMigrationRequest = (variables, signal) => dataPlaneFetch({
@@ -453,6 +579,7 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
453
579
  ...variables,
454
580
  signal
455
581
  });
582
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
456
583
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
457
584
  const getRecord = (variables, signal) => dataPlaneFetch({
458
585
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
@@ -486,13 +613,6 @@ const searchTable = (variables, signal) => dataPlaneFetch({
486
613
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
487
614
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
488
615
  const operationsByTag$2 = {
489
- database: {
490
- dEPRECATEDgetDatabaseList,
491
- dEPRECATEDcreateDatabase,
492
- dEPRECATEDdeleteDatabase,
493
- dEPRECATEDgetDatabaseMetadata,
494
- dEPRECATEDupdateDatabaseMetadata
495
- },
496
616
  branch: {
497
617
  getBranchList,
498
618
  getBranchDetails,
@@ -517,16 +637,6 @@ const operationsByTag$2 = {
517
637
  previewBranchSchemaEdit,
518
638
  applyBranchSchemaEdit
519
639
  },
520
- records: {
521
- branchTransaction,
522
- insertRecord,
523
- getRecord,
524
- insertRecordWithID,
525
- updateRecordWithID,
526
- upsertRecordWithID,
527
- deleteRecord,
528
- bulkInsertTableRecords
529
- },
530
640
  migrationRequests: {
531
641
  queryMigrationRequests,
532
642
  createMigrationRequest,
@@ -549,6 +659,16 @@ const operationsByTag$2 = {
549
659
  updateColumn,
550
660
  deleteColumn
551
661
  },
662
+ records: {
663
+ branchTransaction,
664
+ insertRecord,
665
+ getRecord,
666
+ insertRecordWithID,
667
+ updateRecordWithID,
668
+ upsertRecordWithID,
669
+ deleteRecord,
670
+ bulkInsertTableRecords
671
+ },
552
672
  searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
553
673
  };
554
674
 
@@ -648,6 +768,9 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
648
768
  });
649
769
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
650
770
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
771
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
772
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
773
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
651
774
  const listRegions = (variables, signal) => controlPlaneFetch({
652
775
  url: "/workspaces/{workspaceId}/regions",
653
776
  method: "get",
@@ -680,6 +803,9 @@ const operationsByTag$1 = {
680
803
  deleteDatabase,
681
804
  getDatabaseMetadata,
682
805
  updateDatabaseMetadata,
806
+ getDatabaseGithubSettings,
807
+ updateDatabaseGithubSettings,
808
+ deleteDatabaseGithubSettings,
683
809
  listRegions
684
810
  }
685
811
  };
@@ -722,12 +848,13 @@ function parseProviderString(provider = "production") {
722
848
  function parseWorkspacesUrlParts(url) {
723
849
  if (!isString(url))
724
850
  return null;
725
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
726
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
727
- const match = url.match(regex) || url.match(regexStaging);
851
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
852
+ const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
853
+ const regexDev = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xata\.tech.*/;
854
+ const match = url.match(regex) || url.match(regexStaging) || url.match(regexDev);
728
855
  if (!match)
729
856
  return null;
730
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
857
+ return { workspace: match[1], region: match[2] };
731
858
  }
732
859
 
733
860
  var __accessCheck$7 = (obj, member, msg) => {
@@ -756,6 +883,7 @@ class XataApiClient {
756
883
  const provider = options.host ?? "production";
757
884
  const apiKey = options.apiKey ?? getAPIKey();
758
885
  const trace = options.trace ?? defaultTrace;
886
+ const clientID = generateUUID();
759
887
  if (!apiKey) {
760
888
  throw new Error("Could not resolve a valid apiKey");
761
889
  }
@@ -764,7 +892,10 @@ class XataApiClient {
764
892
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
765
893
  fetchImpl: getFetchImplementation(options.fetch),
766
894
  apiKey,
767
- trace
895
+ trace,
896
+ clientName: options.clientName,
897
+ xataAgentExtra: options.xataAgentExtra,
898
+ clientID
768
899
  });
769
900
  }
770
901
  get user() {
@@ -1366,6 +1497,19 @@ class RecordsApi {
1366
1497
  ...this.extraProps
1367
1498
  });
1368
1499
  }
1500
+ branchTransaction({
1501
+ workspace,
1502
+ region,
1503
+ database,
1504
+ branch,
1505
+ operations
1506
+ }) {
1507
+ return operationsByTag.records.branchTransaction({
1508
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1509
+ body: { operations },
1510
+ ...this.extraProps
1511
+ });
1512
+ }
1369
1513
  }
1370
1514
  class SearchAndFilterApi {
1371
1515
  constructor(extraProps) {
@@ -1626,11 +1770,13 @@ class MigrationsApi {
1626
1770
  region,
1627
1771
  database,
1628
1772
  branch,
1629
- schema
1773
+ schema,
1774
+ schemaOperations,
1775
+ branchOperations
1630
1776
  }) {
1631
1777
  return operationsByTag.migrations.compareBranchWithUserSchema({
1632
1778
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1633
- body: { schema },
1779
+ body: { schema, schemaOperations, branchOperations },
1634
1780
  ...this.extraProps
1635
1781
  });
1636
1782
  }
@@ -1640,11 +1786,12 @@ class MigrationsApi {
1640
1786
  database,
1641
1787
  branch,
1642
1788
  compare,
1643
- schema
1789
+ sourceBranchOperations,
1790
+ targetBranchOperations
1644
1791
  }) {
1645
1792
  return operationsByTag.migrations.compareBranchSchemas({
1646
1793
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1647
- body: { schema },
1794
+ body: { sourceBranchOperations, targetBranchOperations },
1648
1795
  ...this.extraProps
1649
1796
  });
1650
1797
  }
@@ -1738,6 +1885,35 @@ class DatabaseApi {
1738
1885
  ...this.extraProps
1739
1886
  });
1740
1887
  }
1888
+ getDatabaseGithubSettings({
1889
+ workspace,
1890
+ database
1891
+ }) {
1892
+ return operationsByTag.databases.getDatabaseGithubSettings({
1893
+ pathParams: { workspaceId: workspace, dbName: database },
1894
+ ...this.extraProps
1895
+ });
1896
+ }
1897
+ updateDatabaseGithubSettings({
1898
+ workspace,
1899
+ database,
1900
+ settings
1901
+ }) {
1902
+ return operationsByTag.databases.updateDatabaseGithubSettings({
1903
+ pathParams: { workspaceId: workspace, dbName: database },
1904
+ body: settings,
1905
+ ...this.extraProps
1906
+ });
1907
+ }
1908
+ deleteDatabaseGithubSettings({
1909
+ workspace,
1910
+ database
1911
+ }) {
1912
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
1913
+ pathParams: { workspaceId: workspace, dbName: database },
1914
+ ...this.extraProps
1915
+ });
1916
+ }
1741
1917
  listRegions({ workspace }) {
1742
1918
  return operationsByTag.databases.listRegions({
1743
1919
  pathParams: { workspaceId: workspace },
@@ -1756,13 +1932,6 @@ class XataApiPlugin {
1756
1932
  class XataPlugin {
1757
1933
  }
1758
1934
 
1759
- function generateUUID() {
1760
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1761
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1762
- return v.toString(16);
1763
- });
1764
- }
1765
-
1766
1935
  function cleanFilter(filter) {
1767
1936
  if (!filter)
1768
1937
  return void 0;
@@ -1839,6 +2008,12 @@ const _RecordArray = class extends Array {
1839
2008
  toArray() {
1840
2009
  return new Array(...this);
1841
2010
  }
2011
+ toSerializable() {
2012
+ return JSON.parse(this.toString());
2013
+ }
2014
+ toString() {
2015
+ return JSON.stringify(this.toArray());
2016
+ }
1842
2017
  map(callbackfn, thisArg) {
1843
2018
  return this.toArray().map(callbackfn, thisArg);
1844
2019
  }
@@ -1910,6 +2085,7 @@ const _Query = class {
1910
2085
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1911
2086
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1912
2087
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
2088
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
1913
2089
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1914
2090
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
1915
2091
  __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
@@ -2131,7 +2307,8 @@ var __privateMethod$2 = (obj, member, method) => {
2131
2307
  __accessCheck$4(obj, member, "access private method");
2132
2308
  return method;
2133
2309
  };
2134
- var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
2310
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
2311
+ const BULK_OPERATION_MAX_SIZE = 1e3;
2135
2312
  class Repository extends Query {
2136
2313
  }
2137
2314
  class RestRepository extends Query {
@@ -2143,10 +2320,12 @@ class RestRepository extends Query {
2143
2320
  );
2144
2321
  __privateAdd$4(this, _insertRecordWithoutId);
2145
2322
  __privateAdd$4(this, _insertRecordWithId);
2146
- __privateAdd$4(this, _bulkInsertTableRecords);
2323
+ __privateAdd$4(this, _insertRecords);
2147
2324
  __privateAdd$4(this, _updateRecordWithID);
2325
+ __privateAdd$4(this, _updateRecords);
2148
2326
  __privateAdd$4(this, _upsertRecordWithID);
2149
2327
  __privateAdd$4(this, _deleteRecord);
2328
+ __privateAdd$4(this, _deleteRecords);
2150
2329
  __privateAdd$4(this, _setCacheQuery);
2151
2330
  __privateAdd$4(this, _getCacheQuery);
2152
2331
  __privateAdd$4(this, _getSchemaTables$1);
@@ -2180,20 +2359,22 @@ class RestRepository extends Query {
2180
2359
  if (Array.isArray(a)) {
2181
2360
  if (a.length === 0)
2182
2361
  return [];
2183
- const columns = isStringArray(b) ? b : void 0;
2184
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2362
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2363
+ const columns = isStringArray(b) ? b : ["*"];
2364
+ const result = await this.read(ids, columns);
2365
+ return result;
2185
2366
  }
2186
2367
  if (isString(a) && isObject(b)) {
2187
2368
  if (a === "")
2188
2369
  throw new Error("The id can't be empty");
2189
2370
  const columns = isStringArray(c) ? c : void 0;
2190
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2371
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2191
2372
  }
2192
2373
  if (isObject(a) && isString(a.id)) {
2193
2374
  if (a.id === "")
2194
2375
  throw new Error("The id can't be empty");
2195
2376
  const columns = isStringArray(b) ? b : void 0;
2196
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2377
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2197
2378
  }
2198
2379
  if (isObject(a)) {
2199
2380
  const columns = isStringArray(b) ? b : void 0;
@@ -2268,19 +2449,29 @@ class RestRepository extends Query {
2268
2449
  if (Array.isArray(a)) {
2269
2450
  if (a.length === 0)
2270
2451
  return [];
2271
- if (a.length > 100) {
2272
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2273
- }
2452
+ const existing = await this.read(a, ["id"]);
2453
+ const updates = a.filter((_item, index) => existing[index] !== null);
2454
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
2455
+ ifVersion,
2456
+ upsert: false
2457
+ });
2274
2458
  const columns = isStringArray(b) ? b : ["*"];
2275
- return Promise.all(a.map((object) => this.update(object, columns)));
2276
- }
2277
- if (isString(a) && isObject(b)) {
2278
- const columns = isStringArray(c) ? c : void 0;
2279
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2459
+ const result = await this.read(a, columns);
2460
+ return result;
2280
2461
  }
2281
- if (isObject(a) && isString(a.id)) {
2282
- const columns = isStringArray(b) ? b : void 0;
2283
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2462
+ try {
2463
+ if (isString(a) && isObject(b)) {
2464
+ const columns = isStringArray(c) ? c : void 0;
2465
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2466
+ }
2467
+ if (isObject(a) && isString(a.id)) {
2468
+ const columns = isStringArray(b) ? b : void 0;
2469
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2470
+ }
2471
+ } catch (error) {
2472
+ if (error.status === 422)
2473
+ return null;
2474
+ throw error;
2284
2475
  }
2285
2476
  throw new Error("Invalid arguments for update method");
2286
2477
  });
@@ -2310,11 +2501,13 @@ class RestRepository extends Query {
2310
2501
  if (Array.isArray(a)) {
2311
2502
  if (a.length === 0)
2312
2503
  return [];
2313
- if (a.length > 100) {
2314
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2315
- }
2504
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
2505
+ ifVersion,
2506
+ upsert: true
2507
+ });
2316
2508
  const columns = isStringArray(b) ? b : ["*"];
2317
- return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
2509
+ const result = await this.read(a, columns);
2510
+ return result;
2318
2511
  }
2319
2512
  if (isString(a) && isObject(b)) {
2320
2513
  const columns = isStringArray(c) ? c : void 0;
@@ -2333,8 +2526,10 @@ class RestRepository extends Query {
2333
2526
  if (Array.isArray(a)) {
2334
2527
  if (a.length === 0)
2335
2528
  return [];
2529
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2336
2530
  const columns = isStringArray(b) ? b : ["*"];
2337
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2531
+ const result = await this.read(ids, columns);
2532
+ return result;
2338
2533
  }
2339
2534
  if (isString(a) && isObject(b)) {
2340
2535
  const columns = isStringArray(c) ? c : void 0;
@@ -2352,10 +2547,17 @@ class RestRepository extends Query {
2352
2547
  if (Array.isArray(a)) {
2353
2548
  if (a.length === 0)
2354
2549
  return [];
2355
- if (a.length > 100) {
2356
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
2357
- }
2358
- return Promise.all(a.map((id) => this.delete(id, b)));
2550
+ const ids = a.map((o) => {
2551
+ if (isString(o))
2552
+ return o;
2553
+ if (isString(o.id))
2554
+ return o.id;
2555
+ throw new Error("Invalid arguments for delete method");
2556
+ });
2557
+ const columns = isStringArray(b) ? b : ["*"];
2558
+ const result = await this.read(a, columns);
2559
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2560
+ return result;
2359
2561
  }
2360
2562
  if (isString(a)) {
2361
2563
  return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
@@ -2400,7 +2602,9 @@ class RestRepository extends Query {
2400
2602
  prefix: options.prefix,
2401
2603
  highlight: options.highlight,
2402
2604
  filter: options.filter,
2403
- boosters: options.boosters
2605
+ boosters: options.boosters,
2606
+ page: options.page,
2607
+ target: options.target
2404
2608
  },
2405
2609
  ...fetchProps
2406
2610
  });
@@ -2442,7 +2646,8 @@ class RestRepository extends Query {
2442
2646
  filter: cleanFilter(data.filter),
2443
2647
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2444
2648
  page: data.pagination,
2445
- columns: data.columns ?? ["*"]
2649
+ columns: data.columns ?? ["*"],
2650
+ consistency: data.consistency
2446
2651
  },
2447
2652
  fetchOptions: data.fetchOptions,
2448
2653
  ...fetchProps
@@ -2470,6 +2675,7 @@ class RestRepository extends Query {
2470
2675
  filter: cleanFilter(data.filter),
2471
2676
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2472
2677
  columns: data.columns,
2678
+ consistency: data.consistency,
2473
2679
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2474
2680
  summaries,
2475
2681
  summariesFilter
@@ -2523,31 +2729,40 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2523
2729
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2524
2730
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2525
2731
  };
2526
- _bulkInsertTableRecords = new WeakSet();
2527
- bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
2732
+ _insertRecords = new WeakSet();
2733
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2528
2734
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2529
- const records = objects.map((object) => transformObjectLinks(object));
2530
- const response = await bulkInsertTableRecords({
2531
- pathParams: {
2532
- workspace: "{workspaceId}",
2533
- dbBranchName: "{dbBranch}",
2534
- region: "{region}",
2535
- tableName: __privateGet$4(this, _table)
2536
- },
2537
- queryParams: { columns },
2538
- body: { records },
2539
- ...fetchProps
2540
- });
2541
- if (!isResponseWithRecords(response)) {
2542
- throw new Error("Request included columns but server didn't include them");
2735
+ const chunkedOperations = chunk(
2736
+ objects.map((object) => ({
2737
+ insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2738
+ })),
2739
+ BULK_OPERATION_MAX_SIZE
2740
+ );
2741
+ const ids = [];
2742
+ for (const operations of chunkedOperations) {
2743
+ const { results } = await branchTransaction({
2744
+ pathParams: {
2745
+ workspace: "{workspaceId}",
2746
+ dbBranchName: "{dbBranch}",
2747
+ region: "{region}"
2748
+ },
2749
+ body: { operations },
2750
+ ...fetchProps
2751
+ });
2752
+ for (const result of results) {
2753
+ if (result.operation === "insert") {
2754
+ ids.push(result.id);
2755
+ } else {
2756
+ ids.push(null);
2757
+ }
2758
+ }
2543
2759
  }
2544
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2545
- return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
2760
+ return ids;
2546
2761
  };
2547
2762
  _updateRecordWithID = new WeakSet();
2548
2763
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2549
2764
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2550
- const record = transformObjectLinks(object);
2765
+ const { id: _id, ...record } = transformObjectLinks(object);
2551
2766
  try {
2552
2767
  const response = await updateRecordWithID({
2553
2768
  pathParams: {
@@ -2570,6 +2785,36 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2570
2785
  throw e;
2571
2786
  }
2572
2787
  };
2788
+ _updateRecords = new WeakSet();
2789
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2790
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2791
+ const chunkedOperations = chunk(
2792
+ objects.map(({ id, ...object }) => ({
2793
+ update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2794
+ })),
2795
+ BULK_OPERATION_MAX_SIZE
2796
+ );
2797
+ const ids = [];
2798
+ for (const operations of chunkedOperations) {
2799
+ const { results } = await branchTransaction({
2800
+ pathParams: {
2801
+ workspace: "{workspaceId}",
2802
+ dbBranchName: "{dbBranch}",
2803
+ region: "{region}"
2804
+ },
2805
+ body: { operations },
2806
+ ...fetchProps
2807
+ });
2808
+ for (const result of results) {
2809
+ if (result.operation === "update") {
2810
+ ids.push(result.id);
2811
+ } else {
2812
+ ids.push(null);
2813
+ }
2814
+ }
2815
+ }
2816
+ return ids;
2817
+ };
2573
2818
  _upsertRecordWithID = new WeakSet();
2574
2819
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2575
2820
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
@@ -2612,6 +2857,25 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2612
2857
  throw e;
2613
2858
  }
2614
2859
  };
2860
+ _deleteRecords = new WeakSet();
2861
+ deleteRecords_fn = async function(recordIds) {
2862
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2863
+ const chunkedOperations = chunk(
2864
+ recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2865
+ BULK_OPERATION_MAX_SIZE
2866
+ );
2867
+ for (const operations of chunkedOperations) {
2868
+ await branchTransaction({
2869
+ pathParams: {
2870
+ workspace: "{workspaceId}",
2871
+ dbBranchName: "{dbBranch}",
2872
+ region: "{region}"
2873
+ },
2874
+ body: { operations },
2875
+ ...fetchProps
2876
+ });
2877
+ }
2878
+ };
2615
2879
  _setCacheQuery = new WeakSet();
2616
2880
  setCacheQuery_fn = async function(query, meta, records) {
2617
2881
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -2648,23 +2912,23 @@ const transformObjectLinks = (object) => {
2648
2912
  }, {});
2649
2913
  };
2650
2914
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2651
- const result = {};
2915
+ const data = {};
2652
2916
  const { xata, ...rest } = object ?? {};
2653
- Object.assign(result, rest);
2917
+ Object.assign(data, rest);
2654
2918
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2655
2919
  if (!columns)
2656
2920
  console.error(`Table ${table} not found in schema`);
2657
2921
  for (const column of columns ?? []) {
2658
2922
  if (!isValidColumn(selectedColumns, column))
2659
2923
  continue;
2660
- const value = result[column.name];
2924
+ const value = data[column.name];
2661
2925
  switch (column.type) {
2662
2926
  case "datetime": {
2663
- const date = value !== void 0 ? new Date(value) : void 0;
2664
- if (date && isNaN(date.getTime())) {
2927
+ const date = value !== void 0 ? new Date(value) : null;
2928
+ if (date !== null && isNaN(date.getTime())) {
2665
2929
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2666
- } else if (date) {
2667
- result[column.name] = date;
2930
+ } else {
2931
+ data[column.name] = date;
2668
2932
  }
2669
2933
  break;
2670
2934
  }
@@ -2683,48 +2947,52 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2683
2947
  }
2684
2948
  return acc;
2685
2949
  }, []);
2686
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2950
+ data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2687
2951
  } else {
2688
- result[column.name] = null;
2952
+ data[column.name] = null;
2689
2953
  }
2690
2954
  break;
2691
2955
  }
2692
2956
  default:
2693
- result[column.name] = value ?? null;
2957
+ data[column.name] = value ?? null;
2694
2958
  if (column.notNull === true && value === null) {
2695
2959
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2696
2960
  }
2697
2961
  break;
2698
2962
  }
2699
2963
  }
2700
- result.read = function(columns2) {
2701
- return db[table].read(result["id"], columns2);
2964
+ const record = { ...data };
2965
+ record.read = function(columns2) {
2966
+ return db[table].read(record["id"], columns2);
2702
2967
  };
2703
- result.update = function(data, b, c) {
2968
+ record.update = function(data2, b, c) {
2704
2969
  const columns2 = isStringArray(b) ? b : ["*"];
2705
2970
  const ifVersion = parseIfVersion(b, c);
2706
- return db[table].update(result["id"], data, columns2, { ifVersion });
2971
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2707
2972
  };
2708
- result.replace = function(data, b, c) {
2973
+ record.replace = function(data2, b, c) {
2709
2974
  const columns2 = isStringArray(b) ? b : ["*"];
2710
2975
  const ifVersion = parseIfVersion(b, c);
2711
- return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
2976
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2712
2977
  };
2713
- result.delete = function() {
2714
- return db[table].delete(result["id"]);
2978
+ record.delete = function() {
2979
+ return db[table].delete(record["id"]);
2715
2980
  };
2716
- result.getMetadata = function() {
2981
+ record.getMetadata = function() {
2717
2982
  return xata;
2718
2983
  };
2719
- for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
2720
- Object.defineProperty(result, prop, { enumerable: false });
2984
+ record.toSerializable = function() {
2985
+ return JSON.parse(JSON.stringify(transformObjectLinks(data)));
2986
+ };
2987
+ record.toString = function() {
2988
+ return JSON.stringify(transformObjectLinks(data));
2989
+ };
2990
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
2991
+ Object.defineProperty(record, prop, { enumerable: false });
2721
2992
  }
2722
- Object.freeze(result);
2723
- return result;
2993
+ Object.freeze(record);
2994
+ return record;
2724
2995
  };
2725
- function isResponseWithRecords(value) {
2726
- return isObject(value) && Array.isArray(value.records);
2727
- }
2728
2996
  function extractId(value) {
2729
2997
  if (isString(value))
2730
2998
  return value;
@@ -2934,10 +3202,10 @@ _schemaTables = new WeakMap();
2934
3202
  _search = new WeakSet();
2935
3203
  search_fn = async function(query, options, getFetchProps) {
2936
3204
  const fetchProps = await getFetchProps();
2937
- const { tables, fuzziness, highlight, prefix } = options ?? {};
3205
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
2938
3206
  const { records } = await searchBranch({
2939
3207
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2940
- body: { tables, query, fuzziness, prefix, highlight },
3208
+ body: { tables, query, fuzziness, prefix, highlight, page },
2941
3209
  ...fetchProps
2942
3210
  });
2943
3211
  return records;
@@ -2955,18 +3223,30 @@ getSchemaTables_fn = async function(getFetchProps) {
2955
3223
  return schema.tables;
2956
3224
  };
2957
3225
 
3226
+ class TransactionPlugin extends XataPlugin {
3227
+ build({ getFetchProps }) {
3228
+ return {
3229
+ run: async (operations) => {
3230
+ const fetchProps = await getFetchProps();
3231
+ const response = await branchTransaction({
3232
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3233
+ body: { operations },
3234
+ ...fetchProps
3235
+ });
3236
+ return response;
3237
+ }
3238
+ };
3239
+ }
3240
+ }
3241
+
2958
3242
  const isBranchStrategyBuilder = (strategy) => {
2959
3243
  return typeof strategy === "function";
2960
3244
  };
2961
3245
 
2962
3246
  async function getCurrentBranchName(options) {
2963
3247
  const { branch, envBranch } = getEnvironment();
2964
- if (branch) {
2965
- const details = await getDatabaseBranch(branch, options);
2966
- if (details)
2967
- return branch;
2968
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2969
- }
3248
+ if (branch)
3249
+ return branch;
2970
3250
  const gitBranch = envBranch || await getGitBranch();
2971
3251
  return resolveXataBranch(gitBranch, options);
2972
3252
  }
@@ -2998,7 +3278,9 @@ async function resolveXataBranch(gitBranch, options) {
2998
3278
  workspacesApiUrl: `${protocol}//${host}`,
2999
3279
  pathParams: { dbName, workspace, region },
3000
3280
  queryParams: { gitBranch, fallbackBranch },
3001
- trace: defaultTrace
3281
+ trace: defaultTrace,
3282
+ clientName: options?.clientName,
3283
+ xataAgentExtra: options?.xataAgentExtra
3002
3284
  });
3003
3285
  return branch;
3004
3286
  }
@@ -3082,8 +3364,10 @@ const buildClient = (plugins) => {
3082
3364
  };
3083
3365
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3084
3366
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3367
+ const transactions = new TransactionPlugin().build(pluginOptions);
3085
3368
  this.db = db;
3086
3369
  this.search = search;
3370
+ this.transactions = transactions;
3087
3371
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3088
3372
  if (namespace === void 0)
3089
3373
  continue;
@@ -3104,7 +3388,7 @@ const buildClient = (plugins) => {
3104
3388
  }
3105
3389
  }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3106
3390
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3107
- const isBrowser = typeof window !== "undefined";
3391
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3108
3392
  if (isBrowser && !enableBrowser) {
3109
3393
  throw new Error(
3110
3394
  "You are trying to use Xata from the browser, which is potentially a non-secure environment. If you understand the security concerns, such as leaking your credentials, pass `enableBrowser: true` to the client options to remove this error."
@@ -3115,15 +3399,43 @@ const buildClient = (plugins) => {
3115
3399
  const apiKey = options?.apiKey || getAPIKey();
3116
3400
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3117
3401
  const trace = options?.trace ?? defaultTrace;
3118
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
3402
+ const clientName = options?.clientName;
3403
+ const xataAgentExtra = options?.xataAgentExtra;
3404
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({
3405
+ apiKey,
3406
+ databaseURL,
3407
+ fetchImpl: options?.fetch,
3408
+ clientName,
3409
+ xataAgentExtra
3410
+ });
3119
3411
  if (!apiKey) {
3120
3412
  throw new Error("Option apiKey is required");
3121
3413
  }
3122
3414
  if (!databaseURL) {
3123
3415
  throw new Error("Option databaseURL is required");
3124
3416
  }
3125
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser };
3126
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3417
+ return {
3418
+ fetch,
3419
+ databaseURL,
3420
+ apiKey,
3421
+ branch,
3422
+ cache,
3423
+ trace,
3424
+ clientID: generateUUID(),
3425
+ enableBrowser,
3426
+ clientName,
3427
+ xataAgentExtra
3428
+ };
3429
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
3430
+ fetch,
3431
+ apiKey,
3432
+ databaseURL,
3433
+ branch,
3434
+ trace,
3435
+ clientID,
3436
+ clientName,
3437
+ xataAgentExtra
3438
+ }) {
3127
3439
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3128
3440
  if (!branchValue)
3129
3441
  throw new Error("Unable to resolve branch value");
@@ -3137,7 +3449,9 @@ const buildClient = (plugins) => {
3137
3449
  return databaseURL + newPath;
3138
3450
  },
3139
3451
  trace,
3140
- clientID
3452
+ clientID,
3453
+ clientName,
3454
+ xataAgentExtra
3141
3455
  };
3142
3456
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3143
3457
  if (__privateGet(this, _branch))
@@ -3228,7 +3542,7 @@ const deserialize = (json) => {
3228
3542
  };
3229
3543
 
3230
3544
  function buildWorkerRunner(config) {
3231
- return function xataWorker(name, _worker) {
3545
+ return function xataWorker(name, worker) {
3232
3546
  return async (...args) => {
3233
3547
  const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3234
3548
  const result = await fetch(url, {
@@ -3249,5 +3563,5 @@ class XataError extends Error {
3249
3563
  }
3250
3564
  }
3251
3565
 
3252
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, branchTransaction, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, dEPRECATEDcreateDatabase, dEPRECATEDdeleteDatabase, dEPRECATEDgetDatabaseList, dEPRECATEDgetDatabaseMetadata, dEPRECATEDupdateDatabaseMetadata, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
3566
+ export { BaseClient, FetcherError, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, branchTransaction, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
3253
3567
  //# sourceMappingURL=index.mjs.map