@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.cjs CHANGED
@@ -1,27 +1,8 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopNamespace(e) {
6
- if (e && e.__esModule) return e;
7
- var n = Object.create(null);
8
- if (e) {
9
- Object.keys(e).forEach(function (k) {
10
- if (k !== 'default') {
11
- var d = Object.getOwnPropertyDescriptor(e, k);
12
- Object.defineProperty(n, k, d.get ? d : {
13
- enumerable: true,
14
- get: function () { return e[k]; }
15
- });
16
- }
17
- });
18
- }
19
- n["default"] = e;
20
- return Object.freeze(n);
21
- }
22
-
23
- const defaultTrace = async (_name, fn, _options) => {
3
+ const defaultTrace = async (name, fn, _options) => {
24
4
  return await fn({
5
+ name,
25
6
  setAttributes: () => {
26
7
  return;
27
8
  }
@@ -63,6 +44,18 @@ function isStringArray(value) {
63
44
  function isNumber(value) {
64
45
  return isDefined(value) && typeof value === "number";
65
46
  }
47
+ function parseNumber(value) {
48
+ if (isNumber(value)) {
49
+ return value;
50
+ }
51
+ if (isString(value)) {
52
+ const parsed = Number(value);
53
+ if (!Number.isNaN(parsed)) {
54
+ return parsed;
55
+ }
56
+ }
57
+ return void 0;
58
+ }
66
59
  function toBase64(value) {
67
60
  try {
68
61
  return btoa(value);
@@ -82,10 +75,20 @@ function deepMerge(a, b) {
82
75
  }
83
76
  return result;
84
77
  }
78
+ function chunk(array, chunkSize) {
79
+ const result = [];
80
+ for (let i = 0; i < array.length; i += chunkSize) {
81
+ result.push(array.slice(i, i + chunkSize));
82
+ }
83
+ return result;
84
+ }
85
+ async function timeout(ms) {
86
+ return new Promise((resolve) => setTimeout(resolve, ms));
87
+ }
85
88
 
86
89
  function getEnvironment() {
87
90
  try {
88
- if (isObject(process) && isObject(process.env)) {
91
+ if (isDefined(process) && isDefined(process.env)) {
89
92
  return {
90
93
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
91
94
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
@@ -172,8 +175,6 @@ async function getGitBranch() {
172
175
  if (typeof require === "function") {
173
176
  return require(nodeModule).execSync(fullCmd, execOptions).trim();
174
177
  }
175
- const { execSync } = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(nodeModule);
176
- return execSync(fullCmd, execOptions).toString().trim();
177
178
  } catch (err) {
178
179
  }
179
180
  try {
@@ -194,6 +195,29 @@ function getAPIKey() {
194
195
  }
195
196
  }
196
197
 
198
+ var __accessCheck$8 = (obj, member, msg) => {
199
+ if (!member.has(obj))
200
+ throw TypeError("Cannot " + msg);
201
+ };
202
+ var __privateGet$8 = (obj, member, getter) => {
203
+ __accessCheck$8(obj, member, "read from private field");
204
+ return getter ? getter.call(obj) : member.get(obj);
205
+ };
206
+ var __privateAdd$8 = (obj, member, value) => {
207
+ if (member.has(obj))
208
+ throw TypeError("Cannot add the same private member more than once");
209
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
210
+ };
211
+ var __privateSet$8 = (obj, member, value, setter) => {
212
+ __accessCheck$8(obj, member, "write to private field");
213
+ setter ? setter.call(obj, value) : member.set(obj, value);
214
+ return value;
215
+ };
216
+ var __privateMethod$4 = (obj, member, method) => {
217
+ __accessCheck$8(obj, member, "access private method");
218
+ return method;
219
+ };
220
+ var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
197
221
  function getFetchImplementation(userFetch) {
198
222
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
199
223
  const fetchImpl = userFetch ?? globalFetch;
@@ -204,8 +228,81 @@ function getFetchImplementation(userFetch) {
204
228
  }
205
229
  return fetchImpl;
206
230
  }
231
+ class ApiRequestPool {
232
+ constructor(concurrency = 10) {
233
+ __privateAdd$8(this, _enqueue);
234
+ __privateAdd$8(this, _fetch, void 0);
235
+ __privateAdd$8(this, _queue, void 0);
236
+ __privateAdd$8(this, _concurrency, void 0);
237
+ __privateSet$8(this, _queue, []);
238
+ __privateSet$8(this, _concurrency, concurrency);
239
+ this.running = 0;
240
+ this.started = 0;
241
+ }
242
+ setFetch(fetch2) {
243
+ __privateSet$8(this, _fetch, fetch2);
244
+ }
245
+ getFetch() {
246
+ if (!__privateGet$8(this, _fetch)) {
247
+ throw new Error("Fetch not set");
248
+ }
249
+ return __privateGet$8(this, _fetch);
250
+ }
251
+ request(url, options) {
252
+ const start = new Date();
253
+ const fetch2 = this.getFetch();
254
+ const runRequest = async (stalled = false) => {
255
+ const response = await fetch2(url, options);
256
+ if (response.status === 429) {
257
+ const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
258
+ await timeout(rateLimitReset * 1e3);
259
+ return await runRequest(true);
260
+ }
261
+ if (stalled) {
262
+ const stalledTime = new Date().getTime() - start.getTime();
263
+ console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
264
+ }
265
+ return response;
266
+ };
267
+ return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
268
+ return await runRequest();
269
+ });
270
+ }
271
+ }
272
+ _fetch = new WeakMap();
273
+ _queue = new WeakMap();
274
+ _concurrency = new WeakMap();
275
+ _enqueue = new WeakSet();
276
+ enqueue_fn = function(task) {
277
+ const promise = new Promise((resolve) => __privateGet$8(this, _queue).push(resolve)).finally(() => {
278
+ this.started--;
279
+ this.running++;
280
+ }).then(() => task()).finally(() => {
281
+ this.running--;
282
+ const next = __privateGet$8(this, _queue).shift();
283
+ if (next !== void 0) {
284
+ this.started++;
285
+ next();
286
+ }
287
+ });
288
+ if (this.running + this.started < __privateGet$8(this, _concurrency)) {
289
+ const next = __privateGet$8(this, _queue).shift();
290
+ if (next !== void 0) {
291
+ this.started++;
292
+ next();
293
+ }
294
+ }
295
+ return promise;
296
+ };
297
+
298
+ function generateUUID() {
299
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
300
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
301
+ return v.toString(16);
302
+ });
303
+ }
207
304
 
208
- const VERSION = "0.0.0-alpha.vfd68d20";
305
+ const VERSION = "0.22.0";
209
306
 
210
307
  class ErrorWithCause extends Error {
211
308
  constructor(message, options) {
@@ -216,7 +313,7 @@ class FetcherError extends ErrorWithCause {
216
313
  constructor(status, data, requestId) {
217
314
  super(getMessage(data));
218
315
  this.status = status;
219
- this.errors = isBulkError(data) ? data.errors : void 0;
316
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
220
317
  this.requestId = requestId;
221
318
  if (data instanceof Error) {
222
319
  this.stack = data.stack;
@@ -248,6 +345,7 @@ function getMessage(data) {
248
345
  }
249
346
  }
250
347
 
348
+ const pool = new ApiRequestPool();
251
349
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
252
350
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
253
351
  if (value === void 0 || value === null)
@@ -280,11 +378,12 @@ function hostHeader(url) {
280
378
  const { groups } = pattern.exec(url) ?? {};
281
379
  return groups?.host ? { Host: groups.host } : {};
282
380
  }
381
+ const defaultClientID = generateUUID();
283
382
  async function fetch$1({
284
383
  url: path,
285
384
  method,
286
385
  body,
287
- headers,
386
+ headers: customHeaders,
288
387
  pathParams,
289
388
  queryParams,
290
389
  fetchImpl,
@@ -296,9 +395,12 @@ async function fetch$1({
296
395
  signal,
297
396
  clientID,
298
397
  sessionID,
398
+ clientName,
399
+ xataAgentExtra,
299
400
  fetchOptions = {}
300
401
  }) {
301
- return trace(
402
+ pool.setFetch(fetchImpl);
403
+ return await trace(
302
404
  `${method.toUpperCase()} ${path}`,
303
405
  async ({ setAttributes }) => {
304
406
  const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
@@ -308,24 +410,29 @@ async function fetch$1({
308
410
  [TraceAttributes.HTTP_URL]: url,
309
411
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
310
412
  });
311
- const response = await fetchImpl(url, {
413
+ const xataAgent = compact([
414
+ ["client", "TS_SDK"],
415
+ ["version", VERSION],
416
+ isDefined(clientName) ? ["service", clientName] : void 0,
417
+ ...Object.entries(xataAgentExtra ?? {})
418
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
419
+ const headers = {
420
+ "Accept-Encoding": "identity",
421
+ "Content-Type": "application/json",
422
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
423
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
424
+ "X-Xata-Agent": xataAgent,
425
+ ...customHeaders,
426
+ ...hostHeader(fullUrl),
427
+ Authorization: `Bearer ${apiKey}`
428
+ };
429
+ const response = await pool.request(url, {
312
430
  ...fetchOptions,
313
431
  method: method.toUpperCase(),
314
432
  body: body ? JSON.stringify(body) : void 0,
315
- headers: {
316
- "Content-Type": "application/json",
317
- "User-Agent": `Xata client-ts/${VERSION}`,
318
- "X-Xata-Client-ID": clientID ?? "",
319
- "X-Xata-Session-ID": sessionID ?? "",
320
- ...headers,
321
- ...hostHeader(fullUrl),
322
- Authorization: `Bearer ${apiKey}`
323
- },
433
+ headers,
324
434
  signal
325
435
  });
326
- if (response.status === 204) {
327
- return {};
328
- }
329
436
  const { host, protocol } = parseUrl(response.url);
330
437
  const requestId = response.headers?.get("x-request-id") ?? void 0;
331
438
  setAttributes({
@@ -335,6 +442,12 @@ async function fetch$1({
335
442
  [TraceAttributes.HTTP_HOST]: host,
336
443
  [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
337
444
  });
445
+ if (response.status === 204) {
446
+ return {};
447
+ }
448
+ if (response.status === 429) {
449
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
450
+ }
338
451
  try {
339
452
  const jsonResponse = await response.json();
340
453
  if (response.ok) {
@@ -359,17 +472,12 @@ function parseUrl(url) {
359
472
 
360
473
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
361
474
 
362
- const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
363
475
  const getBranchList = (variables, signal) => dataPlaneFetch({
364
476
  url: "/dbs/{dbName}",
365
477
  method: "get",
366
478
  ...variables,
367
479
  signal
368
480
  });
369
- const dEPRECATEDcreateDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
370
- const dEPRECATEDdeleteDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "delete", ...variables, signal });
371
- const dEPRECATEDgetDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "get", ...variables, signal });
372
- const dEPRECATEDupdateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
373
481
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
374
482
  url: "/db/{dbBranchName}",
375
483
  method: "get",
@@ -408,7 +516,6 @@ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName
408
516
  const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
409
517
  const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
410
518
  const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
411
- const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
412
519
  const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
413
520
  const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
414
521
  const getMigrationRequest = (variables, signal) => dataPlaneFetch({
@@ -475,6 +582,7 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
475
582
  ...variables,
476
583
  signal
477
584
  });
585
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
478
586
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
479
587
  const getRecord = (variables, signal) => dataPlaneFetch({
480
588
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
@@ -508,13 +616,6 @@ const searchTable = (variables, signal) => dataPlaneFetch({
508
616
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
509
617
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
510
618
  const operationsByTag$2 = {
511
- database: {
512
- dEPRECATEDgetDatabaseList,
513
- dEPRECATEDcreateDatabase,
514
- dEPRECATEDdeleteDatabase,
515
- dEPRECATEDgetDatabaseMetadata,
516
- dEPRECATEDupdateDatabaseMetadata
517
- },
518
619
  branch: {
519
620
  getBranchList,
520
621
  getBranchDetails,
@@ -539,16 +640,6 @@ const operationsByTag$2 = {
539
640
  previewBranchSchemaEdit,
540
641
  applyBranchSchemaEdit
541
642
  },
542
- records: {
543
- branchTransaction,
544
- insertRecord,
545
- getRecord,
546
- insertRecordWithID,
547
- updateRecordWithID,
548
- upsertRecordWithID,
549
- deleteRecord,
550
- bulkInsertTableRecords
551
- },
552
643
  migrationRequests: {
553
644
  queryMigrationRequests,
554
645
  createMigrationRequest,
@@ -571,6 +662,16 @@ const operationsByTag$2 = {
571
662
  updateColumn,
572
663
  deleteColumn
573
664
  },
665
+ records: {
666
+ branchTransaction,
667
+ insertRecord,
668
+ getRecord,
669
+ insertRecordWithID,
670
+ updateRecordWithID,
671
+ upsertRecordWithID,
672
+ deleteRecord,
673
+ bulkInsertTableRecords
674
+ },
574
675
  searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
575
676
  };
576
677
 
@@ -670,6 +771,9 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
670
771
  });
671
772
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
672
773
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
774
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
775
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
776
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
673
777
  const listRegions = (variables, signal) => controlPlaneFetch({
674
778
  url: "/workspaces/{workspaceId}/regions",
675
779
  method: "get",
@@ -702,6 +806,9 @@ const operationsByTag$1 = {
702
806
  deleteDatabase,
703
807
  getDatabaseMetadata,
704
808
  updateDatabaseMetadata,
809
+ getDatabaseGithubSettings,
810
+ updateDatabaseGithubSettings,
811
+ deleteDatabaseGithubSettings,
705
812
  listRegions
706
813
  }
707
814
  };
@@ -744,12 +851,13 @@ function parseProviderString(provider = "production") {
744
851
  function parseWorkspacesUrlParts(url) {
745
852
  if (!isString(url))
746
853
  return null;
747
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
748
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
749
- const match = url.match(regex) || url.match(regexStaging);
854
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
855
+ const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
856
+ const regexDev = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xata\.tech.*/;
857
+ const match = url.match(regex) || url.match(regexStaging) || url.match(regexDev);
750
858
  if (!match)
751
859
  return null;
752
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
860
+ return { workspace: match[1], region: match[2] };
753
861
  }
754
862
 
755
863
  var __accessCheck$7 = (obj, member, msg) => {
@@ -778,6 +886,7 @@ class XataApiClient {
778
886
  const provider = options.host ?? "production";
779
887
  const apiKey = options.apiKey ?? getAPIKey();
780
888
  const trace = options.trace ?? defaultTrace;
889
+ const clientID = generateUUID();
781
890
  if (!apiKey) {
782
891
  throw new Error("Could not resolve a valid apiKey");
783
892
  }
@@ -786,7 +895,10 @@ class XataApiClient {
786
895
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
787
896
  fetchImpl: getFetchImplementation(options.fetch),
788
897
  apiKey,
789
- trace
898
+ trace,
899
+ clientName: options.clientName,
900
+ xataAgentExtra: options.xataAgentExtra,
901
+ clientID
790
902
  });
791
903
  }
792
904
  get user() {
@@ -1388,6 +1500,19 @@ class RecordsApi {
1388
1500
  ...this.extraProps
1389
1501
  });
1390
1502
  }
1503
+ branchTransaction({
1504
+ workspace,
1505
+ region,
1506
+ database,
1507
+ branch,
1508
+ operations
1509
+ }) {
1510
+ return operationsByTag.records.branchTransaction({
1511
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1512
+ body: { operations },
1513
+ ...this.extraProps
1514
+ });
1515
+ }
1391
1516
  }
1392
1517
  class SearchAndFilterApi {
1393
1518
  constructor(extraProps) {
@@ -1648,11 +1773,13 @@ class MigrationsApi {
1648
1773
  region,
1649
1774
  database,
1650
1775
  branch,
1651
- schema
1776
+ schema,
1777
+ schemaOperations,
1778
+ branchOperations
1652
1779
  }) {
1653
1780
  return operationsByTag.migrations.compareBranchWithUserSchema({
1654
1781
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1655
- body: { schema },
1782
+ body: { schema, schemaOperations, branchOperations },
1656
1783
  ...this.extraProps
1657
1784
  });
1658
1785
  }
@@ -1662,11 +1789,12 @@ class MigrationsApi {
1662
1789
  database,
1663
1790
  branch,
1664
1791
  compare,
1665
- schema
1792
+ sourceBranchOperations,
1793
+ targetBranchOperations
1666
1794
  }) {
1667
1795
  return operationsByTag.migrations.compareBranchSchemas({
1668
1796
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1669
- body: { schema },
1797
+ body: { sourceBranchOperations, targetBranchOperations },
1670
1798
  ...this.extraProps
1671
1799
  });
1672
1800
  }
@@ -1760,6 +1888,35 @@ class DatabaseApi {
1760
1888
  ...this.extraProps
1761
1889
  });
1762
1890
  }
1891
+ getDatabaseGithubSettings({
1892
+ workspace,
1893
+ database
1894
+ }) {
1895
+ return operationsByTag.databases.getDatabaseGithubSettings({
1896
+ pathParams: { workspaceId: workspace, dbName: database },
1897
+ ...this.extraProps
1898
+ });
1899
+ }
1900
+ updateDatabaseGithubSettings({
1901
+ workspace,
1902
+ database,
1903
+ settings
1904
+ }) {
1905
+ return operationsByTag.databases.updateDatabaseGithubSettings({
1906
+ pathParams: { workspaceId: workspace, dbName: database },
1907
+ body: settings,
1908
+ ...this.extraProps
1909
+ });
1910
+ }
1911
+ deleteDatabaseGithubSettings({
1912
+ workspace,
1913
+ database
1914
+ }) {
1915
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
1916
+ pathParams: { workspaceId: workspace, dbName: database },
1917
+ ...this.extraProps
1918
+ });
1919
+ }
1763
1920
  listRegions({ workspace }) {
1764
1921
  return operationsByTag.databases.listRegions({
1765
1922
  pathParams: { workspaceId: workspace },
@@ -1778,13 +1935,6 @@ class XataApiPlugin {
1778
1935
  class XataPlugin {
1779
1936
  }
1780
1937
 
1781
- function generateUUID() {
1782
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1783
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1784
- return v.toString(16);
1785
- });
1786
- }
1787
-
1788
1938
  function cleanFilter(filter) {
1789
1939
  if (!filter)
1790
1940
  return void 0;
@@ -1861,6 +2011,12 @@ const _RecordArray = class extends Array {
1861
2011
  toArray() {
1862
2012
  return new Array(...this);
1863
2013
  }
2014
+ toSerializable() {
2015
+ return JSON.parse(this.toString());
2016
+ }
2017
+ toString() {
2018
+ return JSON.stringify(this.toArray());
2019
+ }
1864
2020
  map(callbackfn, thisArg) {
1865
2021
  return this.toArray().map(callbackfn, thisArg);
1866
2022
  }
@@ -1932,6 +2088,7 @@ const _Query = class {
1932
2088
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1933
2089
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1934
2090
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
2091
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
1935
2092
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1936
2093
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
1937
2094
  __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
@@ -2153,7 +2310,8 @@ var __privateMethod$2 = (obj, member, method) => {
2153
2310
  __accessCheck$4(obj, member, "access private method");
2154
2311
  return method;
2155
2312
  };
2156
- 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;
2313
+ 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;
2314
+ const BULK_OPERATION_MAX_SIZE = 1e3;
2157
2315
  class Repository extends Query {
2158
2316
  }
2159
2317
  class RestRepository extends Query {
@@ -2165,10 +2323,12 @@ class RestRepository extends Query {
2165
2323
  );
2166
2324
  __privateAdd$4(this, _insertRecordWithoutId);
2167
2325
  __privateAdd$4(this, _insertRecordWithId);
2168
- __privateAdd$4(this, _bulkInsertTableRecords);
2326
+ __privateAdd$4(this, _insertRecords);
2169
2327
  __privateAdd$4(this, _updateRecordWithID);
2328
+ __privateAdd$4(this, _updateRecords);
2170
2329
  __privateAdd$4(this, _upsertRecordWithID);
2171
2330
  __privateAdd$4(this, _deleteRecord);
2331
+ __privateAdd$4(this, _deleteRecords);
2172
2332
  __privateAdd$4(this, _setCacheQuery);
2173
2333
  __privateAdd$4(this, _getCacheQuery);
2174
2334
  __privateAdd$4(this, _getSchemaTables$1);
@@ -2202,20 +2362,22 @@ class RestRepository extends Query {
2202
2362
  if (Array.isArray(a)) {
2203
2363
  if (a.length === 0)
2204
2364
  return [];
2205
- const columns = isStringArray(b) ? b : void 0;
2206
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2365
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2366
+ const columns = isStringArray(b) ? b : ["*"];
2367
+ const result = await this.read(ids, columns);
2368
+ return result;
2207
2369
  }
2208
2370
  if (isString(a) && isObject(b)) {
2209
2371
  if (a === "")
2210
2372
  throw new Error("The id can't be empty");
2211
2373
  const columns = isStringArray(c) ? c : void 0;
2212
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2374
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2213
2375
  }
2214
2376
  if (isObject(a) && isString(a.id)) {
2215
2377
  if (a.id === "")
2216
2378
  throw new Error("The id can't be empty");
2217
2379
  const columns = isStringArray(b) ? b : void 0;
2218
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2380
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2219
2381
  }
2220
2382
  if (isObject(a)) {
2221
2383
  const columns = isStringArray(b) ? b : void 0;
@@ -2290,19 +2452,29 @@ class RestRepository extends Query {
2290
2452
  if (Array.isArray(a)) {
2291
2453
  if (a.length === 0)
2292
2454
  return [];
2293
- if (a.length > 100) {
2294
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2295
- }
2455
+ const existing = await this.read(a, ["id"]);
2456
+ const updates = a.filter((_item, index) => existing[index] !== null);
2457
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
2458
+ ifVersion,
2459
+ upsert: false
2460
+ });
2296
2461
  const columns = isStringArray(b) ? b : ["*"];
2297
- return Promise.all(a.map((object) => this.update(object, columns)));
2298
- }
2299
- if (isString(a) && isObject(b)) {
2300
- const columns = isStringArray(c) ? c : void 0;
2301
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2462
+ const result = await this.read(a, columns);
2463
+ return result;
2302
2464
  }
2303
- if (isObject(a) && isString(a.id)) {
2304
- const columns = isStringArray(b) ? b : void 0;
2305
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2465
+ try {
2466
+ if (isString(a) && isObject(b)) {
2467
+ const columns = isStringArray(c) ? c : void 0;
2468
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2469
+ }
2470
+ if (isObject(a) && isString(a.id)) {
2471
+ const columns = isStringArray(b) ? b : void 0;
2472
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2473
+ }
2474
+ } catch (error) {
2475
+ if (error.status === 422)
2476
+ return null;
2477
+ throw error;
2306
2478
  }
2307
2479
  throw new Error("Invalid arguments for update method");
2308
2480
  });
@@ -2332,11 +2504,13 @@ class RestRepository extends Query {
2332
2504
  if (Array.isArray(a)) {
2333
2505
  if (a.length === 0)
2334
2506
  return [];
2335
- if (a.length > 100) {
2336
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2337
- }
2507
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
2508
+ ifVersion,
2509
+ upsert: true
2510
+ });
2338
2511
  const columns = isStringArray(b) ? b : ["*"];
2339
- return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
2512
+ const result = await this.read(a, columns);
2513
+ return result;
2340
2514
  }
2341
2515
  if (isString(a) && isObject(b)) {
2342
2516
  const columns = isStringArray(c) ? c : void 0;
@@ -2355,8 +2529,10 @@ class RestRepository extends Query {
2355
2529
  if (Array.isArray(a)) {
2356
2530
  if (a.length === 0)
2357
2531
  return [];
2532
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2358
2533
  const columns = isStringArray(b) ? b : ["*"];
2359
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2534
+ const result = await this.read(ids, columns);
2535
+ return result;
2360
2536
  }
2361
2537
  if (isString(a) && isObject(b)) {
2362
2538
  const columns = isStringArray(c) ? c : void 0;
@@ -2374,10 +2550,17 @@ class RestRepository extends Query {
2374
2550
  if (Array.isArray(a)) {
2375
2551
  if (a.length === 0)
2376
2552
  return [];
2377
- if (a.length > 100) {
2378
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
2379
- }
2380
- return Promise.all(a.map((id) => this.delete(id, b)));
2553
+ const ids = a.map((o) => {
2554
+ if (isString(o))
2555
+ return o;
2556
+ if (isString(o.id))
2557
+ return o.id;
2558
+ throw new Error("Invalid arguments for delete method");
2559
+ });
2560
+ const columns = isStringArray(b) ? b : ["*"];
2561
+ const result = await this.read(a, columns);
2562
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2563
+ return result;
2381
2564
  }
2382
2565
  if (isString(a)) {
2383
2566
  return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
@@ -2422,7 +2605,9 @@ class RestRepository extends Query {
2422
2605
  prefix: options.prefix,
2423
2606
  highlight: options.highlight,
2424
2607
  filter: options.filter,
2425
- boosters: options.boosters
2608
+ boosters: options.boosters,
2609
+ page: options.page,
2610
+ target: options.target
2426
2611
  },
2427
2612
  ...fetchProps
2428
2613
  });
@@ -2464,7 +2649,8 @@ class RestRepository extends Query {
2464
2649
  filter: cleanFilter(data.filter),
2465
2650
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2466
2651
  page: data.pagination,
2467
- columns: data.columns ?? ["*"]
2652
+ columns: data.columns ?? ["*"],
2653
+ consistency: data.consistency
2468
2654
  },
2469
2655
  fetchOptions: data.fetchOptions,
2470
2656
  ...fetchProps
@@ -2492,6 +2678,7 @@ class RestRepository extends Query {
2492
2678
  filter: cleanFilter(data.filter),
2493
2679
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2494
2680
  columns: data.columns,
2681
+ consistency: data.consistency,
2495
2682
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2496
2683
  summaries,
2497
2684
  summariesFilter
@@ -2545,31 +2732,40 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2545
2732
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2546
2733
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2547
2734
  };
2548
- _bulkInsertTableRecords = new WeakSet();
2549
- bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
2735
+ _insertRecords = new WeakSet();
2736
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2550
2737
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2551
- const records = objects.map((object) => transformObjectLinks(object));
2552
- const response = await bulkInsertTableRecords({
2553
- pathParams: {
2554
- workspace: "{workspaceId}",
2555
- dbBranchName: "{dbBranch}",
2556
- region: "{region}",
2557
- tableName: __privateGet$4(this, _table)
2558
- },
2559
- queryParams: { columns },
2560
- body: { records },
2561
- ...fetchProps
2562
- });
2563
- if (!isResponseWithRecords(response)) {
2564
- throw new Error("Request included columns but server didn't include them");
2738
+ const chunkedOperations = chunk(
2739
+ objects.map((object) => ({
2740
+ insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2741
+ })),
2742
+ BULK_OPERATION_MAX_SIZE
2743
+ );
2744
+ const ids = [];
2745
+ for (const operations of chunkedOperations) {
2746
+ const { results } = await branchTransaction({
2747
+ pathParams: {
2748
+ workspace: "{workspaceId}",
2749
+ dbBranchName: "{dbBranch}",
2750
+ region: "{region}"
2751
+ },
2752
+ body: { operations },
2753
+ ...fetchProps
2754
+ });
2755
+ for (const result of results) {
2756
+ if (result.operation === "insert") {
2757
+ ids.push(result.id);
2758
+ } else {
2759
+ ids.push(null);
2760
+ }
2761
+ }
2565
2762
  }
2566
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2567
- return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
2763
+ return ids;
2568
2764
  };
2569
2765
  _updateRecordWithID = new WeakSet();
2570
2766
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2571
2767
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2572
- const record = transformObjectLinks(object);
2768
+ const { id: _id, ...record } = transformObjectLinks(object);
2573
2769
  try {
2574
2770
  const response = await updateRecordWithID({
2575
2771
  pathParams: {
@@ -2592,6 +2788,36 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2592
2788
  throw e;
2593
2789
  }
2594
2790
  };
2791
+ _updateRecords = new WeakSet();
2792
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2793
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2794
+ const chunkedOperations = chunk(
2795
+ objects.map(({ id, ...object }) => ({
2796
+ update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2797
+ })),
2798
+ BULK_OPERATION_MAX_SIZE
2799
+ );
2800
+ const ids = [];
2801
+ for (const operations of chunkedOperations) {
2802
+ const { results } = await branchTransaction({
2803
+ pathParams: {
2804
+ workspace: "{workspaceId}",
2805
+ dbBranchName: "{dbBranch}",
2806
+ region: "{region}"
2807
+ },
2808
+ body: { operations },
2809
+ ...fetchProps
2810
+ });
2811
+ for (const result of results) {
2812
+ if (result.operation === "update") {
2813
+ ids.push(result.id);
2814
+ } else {
2815
+ ids.push(null);
2816
+ }
2817
+ }
2818
+ }
2819
+ return ids;
2820
+ };
2595
2821
  _upsertRecordWithID = new WeakSet();
2596
2822
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2597
2823
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
@@ -2634,6 +2860,25 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2634
2860
  throw e;
2635
2861
  }
2636
2862
  };
2863
+ _deleteRecords = new WeakSet();
2864
+ deleteRecords_fn = async function(recordIds) {
2865
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2866
+ const chunkedOperations = chunk(
2867
+ recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2868
+ BULK_OPERATION_MAX_SIZE
2869
+ );
2870
+ for (const operations of chunkedOperations) {
2871
+ await branchTransaction({
2872
+ pathParams: {
2873
+ workspace: "{workspaceId}",
2874
+ dbBranchName: "{dbBranch}",
2875
+ region: "{region}"
2876
+ },
2877
+ body: { operations },
2878
+ ...fetchProps
2879
+ });
2880
+ }
2881
+ };
2637
2882
  _setCacheQuery = new WeakSet();
2638
2883
  setCacheQuery_fn = async function(query, meta, records) {
2639
2884
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -2670,23 +2915,23 @@ const transformObjectLinks = (object) => {
2670
2915
  }, {});
2671
2916
  };
2672
2917
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2673
- const result = {};
2918
+ const data = {};
2674
2919
  const { xata, ...rest } = object ?? {};
2675
- Object.assign(result, rest);
2920
+ Object.assign(data, rest);
2676
2921
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2677
2922
  if (!columns)
2678
2923
  console.error(`Table ${table} not found in schema`);
2679
2924
  for (const column of columns ?? []) {
2680
2925
  if (!isValidColumn(selectedColumns, column))
2681
2926
  continue;
2682
- const value = result[column.name];
2927
+ const value = data[column.name];
2683
2928
  switch (column.type) {
2684
2929
  case "datetime": {
2685
- const date = value !== void 0 ? new Date(value) : void 0;
2686
- if (date && isNaN(date.getTime())) {
2930
+ const date = value !== void 0 ? new Date(value) : null;
2931
+ if (date !== null && isNaN(date.getTime())) {
2687
2932
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2688
- } else if (date) {
2689
- result[column.name] = date;
2933
+ } else {
2934
+ data[column.name] = date;
2690
2935
  }
2691
2936
  break;
2692
2937
  }
@@ -2705,48 +2950,52 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2705
2950
  }
2706
2951
  return acc;
2707
2952
  }, []);
2708
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2953
+ data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2709
2954
  } else {
2710
- result[column.name] = null;
2955
+ data[column.name] = null;
2711
2956
  }
2712
2957
  break;
2713
2958
  }
2714
2959
  default:
2715
- result[column.name] = value ?? null;
2960
+ data[column.name] = value ?? null;
2716
2961
  if (column.notNull === true && value === null) {
2717
2962
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2718
2963
  }
2719
2964
  break;
2720
2965
  }
2721
2966
  }
2722
- result.read = function(columns2) {
2723
- return db[table].read(result["id"], columns2);
2967
+ const record = { ...data };
2968
+ record.read = function(columns2) {
2969
+ return db[table].read(record["id"], columns2);
2724
2970
  };
2725
- result.update = function(data, b, c) {
2971
+ record.update = function(data2, b, c) {
2726
2972
  const columns2 = isStringArray(b) ? b : ["*"];
2727
2973
  const ifVersion = parseIfVersion(b, c);
2728
- return db[table].update(result["id"], data, columns2, { ifVersion });
2974
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2729
2975
  };
2730
- result.replace = function(data, b, c) {
2976
+ record.replace = function(data2, b, c) {
2731
2977
  const columns2 = isStringArray(b) ? b : ["*"];
2732
2978
  const ifVersion = parseIfVersion(b, c);
2733
- return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
2979
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2734
2980
  };
2735
- result.delete = function() {
2736
- return db[table].delete(result["id"]);
2981
+ record.delete = function() {
2982
+ return db[table].delete(record["id"]);
2737
2983
  };
2738
- result.getMetadata = function() {
2984
+ record.getMetadata = function() {
2739
2985
  return xata;
2740
2986
  };
2741
- for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
2742
- Object.defineProperty(result, prop, { enumerable: false });
2987
+ record.toSerializable = function() {
2988
+ return JSON.parse(JSON.stringify(transformObjectLinks(data)));
2989
+ };
2990
+ record.toString = function() {
2991
+ return JSON.stringify(transformObjectLinks(data));
2992
+ };
2993
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
2994
+ Object.defineProperty(record, prop, { enumerable: false });
2743
2995
  }
2744
- Object.freeze(result);
2745
- return result;
2996
+ Object.freeze(record);
2997
+ return record;
2746
2998
  };
2747
- function isResponseWithRecords(value) {
2748
- return isObject(value) && Array.isArray(value.records);
2749
- }
2750
2999
  function extractId(value) {
2751
3000
  if (isString(value))
2752
3001
  return value;
@@ -2956,10 +3205,10 @@ _schemaTables = new WeakMap();
2956
3205
  _search = new WeakSet();
2957
3206
  search_fn = async function(query, options, getFetchProps) {
2958
3207
  const fetchProps = await getFetchProps();
2959
- const { tables, fuzziness, highlight, prefix } = options ?? {};
3208
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
2960
3209
  const { records } = await searchBranch({
2961
3210
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2962
- body: { tables, query, fuzziness, prefix, highlight },
3211
+ body: { tables, query, fuzziness, prefix, highlight, page },
2963
3212
  ...fetchProps
2964
3213
  });
2965
3214
  return records;
@@ -2977,18 +3226,30 @@ getSchemaTables_fn = async function(getFetchProps) {
2977
3226
  return schema.tables;
2978
3227
  };
2979
3228
 
3229
+ class TransactionPlugin extends XataPlugin {
3230
+ build({ getFetchProps }) {
3231
+ return {
3232
+ run: async (operations) => {
3233
+ const fetchProps = await getFetchProps();
3234
+ const response = await branchTransaction({
3235
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3236
+ body: { operations },
3237
+ ...fetchProps
3238
+ });
3239
+ return response;
3240
+ }
3241
+ };
3242
+ }
3243
+ }
3244
+
2980
3245
  const isBranchStrategyBuilder = (strategy) => {
2981
3246
  return typeof strategy === "function";
2982
3247
  };
2983
3248
 
2984
3249
  async function getCurrentBranchName(options) {
2985
3250
  const { branch, envBranch } = getEnvironment();
2986
- if (branch) {
2987
- const details = await getDatabaseBranch(branch, options);
2988
- if (details)
2989
- return branch;
2990
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2991
- }
3251
+ if (branch)
3252
+ return branch;
2992
3253
  const gitBranch = envBranch || await getGitBranch();
2993
3254
  return resolveXataBranch(gitBranch, options);
2994
3255
  }
@@ -3020,7 +3281,9 @@ async function resolveXataBranch(gitBranch, options) {
3020
3281
  workspacesApiUrl: `${protocol}//${host}`,
3021
3282
  pathParams: { dbName, workspace, region },
3022
3283
  queryParams: { gitBranch, fallbackBranch },
3023
- trace: defaultTrace
3284
+ trace: defaultTrace,
3285
+ clientName: options?.clientName,
3286
+ xataAgentExtra: options?.xataAgentExtra
3024
3287
  });
3025
3288
  return branch;
3026
3289
  }
@@ -3104,8 +3367,10 @@ const buildClient = (plugins) => {
3104
3367
  };
3105
3368
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3106
3369
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3370
+ const transactions = new TransactionPlugin().build(pluginOptions);
3107
3371
  this.db = db;
3108
3372
  this.search = search;
3373
+ this.transactions = transactions;
3109
3374
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3110
3375
  if (namespace === void 0)
3111
3376
  continue;
@@ -3126,7 +3391,7 @@ const buildClient = (plugins) => {
3126
3391
  }
3127
3392
  }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3128
3393
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3129
- const isBrowser = typeof window !== "undefined";
3394
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3130
3395
  if (isBrowser && !enableBrowser) {
3131
3396
  throw new Error(
3132
3397
  "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."
@@ -3137,15 +3402,43 @@ const buildClient = (plugins) => {
3137
3402
  const apiKey = options?.apiKey || getAPIKey();
3138
3403
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3139
3404
  const trace = options?.trace ?? defaultTrace;
3140
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
3405
+ const clientName = options?.clientName;
3406
+ const xataAgentExtra = options?.xataAgentExtra;
3407
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({
3408
+ apiKey,
3409
+ databaseURL,
3410
+ fetchImpl: options?.fetch,
3411
+ clientName,
3412
+ xataAgentExtra
3413
+ });
3141
3414
  if (!apiKey) {
3142
3415
  throw new Error("Option apiKey is required");
3143
3416
  }
3144
3417
  if (!databaseURL) {
3145
3418
  throw new Error("Option databaseURL is required");
3146
3419
  }
3147
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser };
3148
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3420
+ return {
3421
+ fetch,
3422
+ databaseURL,
3423
+ apiKey,
3424
+ branch,
3425
+ cache,
3426
+ trace,
3427
+ clientID: generateUUID(),
3428
+ enableBrowser,
3429
+ clientName,
3430
+ xataAgentExtra
3431
+ };
3432
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
3433
+ fetch,
3434
+ apiKey,
3435
+ databaseURL,
3436
+ branch,
3437
+ trace,
3438
+ clientID,
3439
+ clientName,
3440
+ xataAgentExtra
3441
+ }) {
3149
3442
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3150
3443
  if (!branchValue)
3151
3444
  throw new Error("Unable to resolve branch value");
@@ -3159,7 +3452,9 @@ const buildClient = (plugins) => {
3159
3452
  return databaseURL + newPath;
3160
3453
  },
3161
3454
  trace,
3162
- clientID
3455
+ clientID,
3456
+ clientName,
3457
+ xataAgentExtra
3163
3458
  };
3164
3459
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3165
3460
  if (__privateGet(this, _branch))
@@ -3250,7 +3545,7 @@ const deserialize = (json) => {
3250
3545
  };
3251
3546
 
3252
3547
  function buildWorkerRunner(config) {
3253
- return function xataWorker(name, _worker) {
3548
+ return function xataWorker(name, worker) {
3254
3549
  return async (...args) => {
3255
3550
  const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3256
3551
  const result = await fetch(url, {
@@ -3272,6 +3567,7 @@ class XataError extends Error {
3272
3567
  }
3273
3568
 
3274
3569
  exports.BaseClient = BaseClient;
3570
+ exports.FetcherError = FetcherError;
3275
3571
  exports.Operations = operationsByTag;
3276
3572
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
3277
3573
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -3310,14 +3606,10 @@ exports.createMigrationRequest = createMigrationRequest;
3310
3606
  exports.createTable = createTable;
3311
3607
  exports.createUserAPIKey = createUserAPIKey;
3312
3608
  exports.createWorkspace = createWorkspace;
3313
- exports.dEPRECATEDcreateDatabase = dEPRECATEDcreateDatabase;
3314
- exports.dEPRECATEDdeleteDatabase = dEPRECATEDdeleteDatabase;
3315
- exports.dEPRECATEDgetDatabaseList = dEPRECATEDgetDatabaseList;
3316
- exports.dEPRECATEDgetDatabaseMetadata = dEPRECATEDgetDatabaseMetadata;
3317
- exports.dEPRECATEDupdateDatabaseMetadata = dEPRECATEDupdateDatabaseMetadata;
3318
3609
  exports.deleteBranch = deleteBranch;
3319
3610
  exports.deleteColumn = deleteColumn;
3320
3611
  exports.deleteDatabase = deleteDatabase;
3612
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
3321
3613
  exports.deleteRecord = deleteRecord;
3322
3614
  exports.deleteTable = deleteTable;
3323
3615
  exports.deleteUser = deleteUser;
@@ -3340,6 +3632,7 @@ exports.getBranchStats = getBranchStats;
3340
3632
  exports.getColumn = getColumn;
3341
3633
  exports.getCurrentBranchDetails = getCurrentBranchDetails;
3342
3634
  exports.getCurrentBranchName = getCurrentBranchName;
3635
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
3343
3636
  exports.getDatabaseList = getDatabaseList;
3344
3637
  exports.getDatabaseMetadata = getDatabaseMetadata;
3345
3638
  exports.getDatabaseURL = getDatabaseURL;
@@ -3404,6 +3697,7 @@ exports.summarizeTable = summarizeTable;
3404
3697
  exports.updateBranchMetadata = updateBranchMetadata;
3405
3698
  exports.updateBranchSchema = updateBranchSchema;
3406
3699
  exports.updateColumn = updateColumn;
3700
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
3407
3701
  exports.updateDatabaseMetadata = updateDatabaseMetadata;
3408
3702
  exports.updateMigrationRequest = updateMigrationRequest;
3409
3703
  exports.updateRecordWithID = updateRecordWithID;