@xata.io/client 0.0.0-alpha.vff4bc47 → 0.0.0-alpha.vff9649a

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
+ };
185
294
 
186
- const VERSION = "0.0.0-alpha.vff4bc47";
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
+ }
301
+
302
+ const VERSION = "0.21.6";
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,11 @@ async function fetch$1({
274
392
  signal,
275
393
  clientID,
276
394
  sessionID,
395
+ clientName,
277
396
  fetchOptions = {}
278
397
  }) {
279
- return trace(
398
+ pool.setFetch(fetchImpl);
399
+ return await trace(
280
400
  `${method.toUpperCase()} ${path}`,
281
401
  async ({ setAttributes }) => {
282
402
  const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
@@ -286,24 +406,28 @@ async function fetch$1({
286
406
  [TraceAttributes.HTTP_URL]: url,
287
407
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
288
408
  });
289
- const response = await fetchImpl(url, {
409
+ const xataAgent = compact([
410
+ ["client", "TS_SDK"],
411
+ ["version", VERSION],
412
+ isDefined(clientName) ? ["service", clientName] : void 0
413
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
414
+ const headers = {
415
+ "Accept-Encoding": "identity",
416
+ "Content-Type": "application/json",
417
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
418
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
419
+ "X-Xata-Agent": xataAgent,
420
+ ...customHeaders,
421
+ ...hostHeader(fullUrl),
422
+ Authorization: `Bearer ${apiKey}`
423
+ };
424
+ const response = await pool.request(url, {
290
425
  ...fetchOptions,
291
426
  method: method.toUpperCase(),
292
427
  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
- },
428
+ headers,
302
429
  signal
303
430
  });
304
- if (response.status === 204) {
305
- return {};
306
- }
307
431
  const { host, protocol } = parseUrl(response.url);
308
432
  const requestId = response.headers?.get("x-request-id") ?? void 0;
309
433
  setAttributes({
@@ -313,6 +437,12 @@ async function fetch$1({
313
437
  [TraceAttributes.HTTP_HOST]: host,
314
438
  [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
315
439
  });
440
+ if (response.status === 204) {
441
+ return {};
442
+ }
443
+ if (response.status === 429) {
444
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
445
+ }
316
446
  try {
317
447
  const jsonResponse = await response.json();
318
448
  if (response.ok) {
@@ -337,17 +467,12 @@ function parseUrl(url) {
337
467
 
338
468
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
339
469
 
340
- const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
341
470
  const getBranchList = (variables, signal) => dataPlaneFetch({
342
471
  url: "/dbs/{dbName}",
343
472
  method: "get",
344
473
  ...variables,
345
474
  signal
346
475
  });
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
476
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
352
477
  url: "/db/{dbBranchName}",
353
478
  method: "get",
@@ -486,13 +611,6 @@ const searchTable = (variables, signal) => dataPlaneFetch({
486
611
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
487
612
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
488
613
  const operationsByTag$2 = {
489
- database: {
490
- dEPRECATEDgetDatabaseList,
491
- dEPRECATEDcreateDatabase,
492
- dEPRECATEDdeleteDatabase,
493
- dEPRECATEDgetDatabaseMetadata,
494
- dEPRECATEDupdateDatabaseMetadata
495
- },
496
614
  branch: {
497
615
  getBranchList,
498
616
  getBranchDetails,
@@ -722,12 +840,12 @@ function parseProviderString(provider = "production") {
722
840
  function parseWorkspacesUrlParts(url) {
723
841
  if (!isString(url))
724
842
  return null;
725
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
726
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
843
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
844
+ const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
727
845
  const match = url.match(regex) || url.match(regexStaging);
728
846
  if (!match)
729
847
  return null;
730
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
848
+ return { workspace: match[1], region: match[2] };
731
849
  }
732
850
 
733
851
  var __accessCheck$7 = (obj, member, msg) => {
@@ -756,6 +874,7 @@ class XataApiClient {
756
874
  const provider = options.host ?? "production";
757
875
  const apiKey = options.apiKey ?? getAPIKey();
758
876
  const trace = options.trace ?? defaultTrace;
877
+ const clientID = generateUUID();
759
878
  if (!apiKey) {
760
879
  throw new Error("Could not resolve a valid apiKey");
761
880
  }
@@ -764,7 +883,9 @@ class XataApiClient {
764
883
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
765
884
  fetchImpl: getFetchImplementation(options.fetch),
766
885
  apiKey,
767
- trace
886
+ trace,
887
+ clientName: options.clientName,
888
+ clientID
768
889
  });
769
890
  }
770
891
  get user() {
@@ -1769,13 +1890,6 @@ class XataApiPlugin {
1769
1890
  class XataPlugin {
1770
1891
  }
1771
1892
 
1772
- function generateUUID() {
1773
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1774
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1775
- return v.toString(16);
1776
- });
1777
- }
1778
-
1779
1893
  function cleanFilter(filter) {
1780
1894
  if (!filter)
1781
1895
  return void 0;
@@ -1923,6 +2037,7 @@ const _Query = class {
1923
2037
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1924
2038
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1925
2039
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
2040
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
1926
2041
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1927
2042
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
1928
2043
  __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
@@ -2144,7 +2259,8 @@ var __privateMethod$2 = (obj, member, method) => {
2144
2259
  __accessCheck$4(obj, member, "access private method");
2145
2260
  return method;
2146
2261
  };
2147
- var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_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;
2262
+ 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;
2263
+ const BULK_OPERATION_MAX_SIZE = 1e3;
2148
2264
  class Repository extends Query {
2149
2265
  }
2150
2266
  class RestRepository extends Query {
@@ -2156,7 +2272,7 @@ class RestRepository extends Query {
2156
2272
  );
2157
2273
  __privateAdd$4(this, _insertRecordWithoutId);
2158
2274
  __privateAdd$4(this, _insertRecordWithId);
2159
- __privateAdd$4(this, _bulkInsertTableRecords);
2275
+ __privateAdd$4(this, _insertRecords);
2160
2276
  __privateAdd$4(this, _updateRecordWithID);
2161
2277
  __privateAdd$4(this, _updateRecords);
2162
2278
  __privateAdd$4(this, _upsertRecordWithID);
@@ -2195,20 +2311,22 @@ class RestRepository extends Query {
2195
2311
  if (Array.isArray(a)) {
2196
2312
  if (a.length === 0)
2197
2313
  return [];
2198
- const columns = isStringArray(b) ? b : void 0;
2199
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2314
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2315
+ const columns = isStringArray(b) ? b : ["*"];
2316
+ const result = await this.read(ids, columns);
2317
+ return result;
2200
2318
  }
2201
2319
  if (isString(a) && isObject(b)) {
2202
2320
  if (a === "")
2203
2321
  throw new Error("The id can't be empty");
2204
2322
  const columns = isStringArray(c) ? c : void 0;
2205
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2323
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2206
2324
  }
2207
2325
  if (isObject(a) && isString(a.id)) {
2208
2326
  if (a.id === "")
2209
2327
  throw new Error("The id can't be empty");
2210
2328
  const columns = isStringArray(b) ? b : void 0;
2211
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2329
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2212
2330
  }
2213
2331
  if (isObject(a)) {
2214
2332
  const columns = isStringArray(b) ? b : void 0;
@@ -2293,13 +2411,19 @@ class RestRepository extends Query {
2293
2411
  const result = await this.read(a, columns);
2294
2412
  return result;
2295
2413
  }
2296
- if (isString(a) && isObject(b)) {
2297
- const columns = isStringArray(c) ? c : void 0;
2298
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2299
- }
2300
- if (isObject(a) && isString(a.id)) {
2301
- const columns = isStringArray(b) ? b : void 0;
2302
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2414
+ try {
2415
+ if (isString(a) && isObject(b)) {
2416
+ const columns = isStringArray(c) ? c : void 0;
2417
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2418
+ }
2419
+ if (isObject(a) && isString(a.id)) {
2420
+ const columns = isStringArray(b) ? b : void 0;
2421
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2422
+ }
2423
+ } catch (error) {
2424
+ if (error.status === 422)
2425
+ return null;
2426
+ throw error;
2303
2427
  }
2304
2428
  throw new Error("Invalid arguments for update method");
2305
2429
  });
@@ -2354,8 +2478,10 @@ class RestRepository extends Query {
2354
2478
  if (Array.isArray(a)) {
2355
2479
  if (a.length === 0)
2356
2480
  return [];
2481
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2357
2482
  const columns = isStringArray(b) ? b : ["*"];
2358
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2483
+ const result = await this.read(ids, columns);
2484
+ return result;
2359
2485
  }
2360
2486
  if (isString(a) && isObject(b)) {
2361
2487
  const columns = isStringArray(c) ? c : void 0;
@@ -2428,7 +2554,9 @@ class RestRepository extends Query {
2428
2554
  prefix: options.prefix,
2429
2555
  highlight: options.highlight,
2430
2556
  filter: options.filter,
2431
- boosters: options.boosters
2557
+ boosters: options.boosters,
2558
+ page: options.page,
2559
+ target: options.target
2432
2560
  },
2433
2561
  ...fetchProps
2434
2562
  });
@@ -2470,7 +2598,8 @@ class RestRepository extends Query {
2470
2598
  filter: cleanFilter(data.filter),
2471
2599
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2472
2600
  page: data.pagination,
2473
- columns: data.columns ?? ["*"]
2601
+ columns: data.columns ?? ["*"],
2602
+ consistency: data.consistency
2474
2603
  },
2475
2604
  fetchOptions: data.fetchOptions,
2476
2605
  ...fetchProps
@@ -2498,6 +2627,7 @@ class RestRepository extends Query {
2498
2627
  filter: cleanFilter(data.filter),
2499
2628
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2500
2629
  columns: data.columns,
2630
+ consistency: data.consistency,
2501
2631
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2502
2632
  summaries,
2503
2633
  summariesFilter
@@ -2551,31 +2681,40 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2551
2681
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2552
2682
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2553
2683
  };
2554
- _bulkInsertTableRecords = new WeakSet();
2555
- bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
2684
+ _insertRecords = new WeakSet();
2685
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2556
2686
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2557
- const records = objects.map((object) => transformObjectLinks(object));
2558
- const response = await bulkInsertTableRecords({
2559
- pathParams: {
2560
- workspace: "{workspaceId}",
2561
- dbBranchName: "{dbBranch}",
2562
- region: "{region}",
2563
- tableName: __privateGet$4(this, _table)
2564
- },
2565
- queryParams: { columns },
2566
- body: { records },
2567
- ...fetchProps
2568
- });
2569
- if (!isResponseWithRecords(response)) {
2570
- throw new Error("Request included columns but server didn't include them");
2687
+ const chunkedOperations = chunk(
2688
+ objects.map((object) => ({
2689
+ insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2690
+ })),
2691
+ BULK_OPERATION_MAX_SIZE
2692
+ );
2693
+ const ids = [];
2694
+ for (const operations of chunkedOperations) {
2695
+ const { results } = await branchTransaction({
2696
+ pathParams: {
2697
+ workspace: "{workspaceId}",
2698
+ dbBranchName: "{dbBranch}",
2699
+ region: "{region}"
2700
+ },
2701
+ body: { operations },
2702
+ ...fetchProps
2703
+ });
2704
+ for (const result of results) {
2705
+ if (result.operation === "insert") {
2706
+ ids.push(result.id);
2707
+ } else {
2708
+ ids.push(null);
2709
+ }
2710
+ }
2571
2711
  }
2572
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2573
- return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
2712
+ return ids;
2574
2713
  };
2575
2714
  _updateRecordWithID = new WeakSet();
2576
2715
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2577
2716
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2578
- const record = transformObjectLinks(object);
2717
+ const { id: _id, ...record } = transformObjectLinks(object);
2579
2718
  try {
2580
2719
  const response = await updateRecordWithID({
2581
2720
  pathParams: {
@@ -2595,24 +2734,38 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2595
2734
  if (isObject(e) && e.status === 404) {
2596
2735
  return null;
2597
2736
  }
2737
+ throw e;
2598
2738
  }
2599
2739
  };
2600
2740
  _updateRecords = new WeakSet();
2601
2741
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2602
2742
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2603
- const operations = objects.map(({ id, ...fields }) => ({
2604
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields }
2605
- }));
2606
- const { results } = await branchTransaction({
2607
- pathParams: {
2608
- workspace: "{workspaceId}",
2609
- dbBranchName: "{dbBranch}",
2610
- region: "{region}"
2611
- },
2612
- body: { operations },
2613
- ...fetchProps
2614
- });
2615
- return results;
2743
+ const chunkedOperations = chunk(
2744
+ objects.map(({ id, ...object }) => ({
2745
+ update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2746
+ })),
2747
+ BULK_OPERATION_MAX_SIZE
2748
+ );
2749
+ const ids = [];
2750
+ for (const operations of chunkedOperations) {
2751
+ const { results } = await branchTransaction({
2752
+ pathParams: {
2753
+ workspace: "{workspaceId}",
2754
+ dbBranchName: "{dbBranch}",
2755
+ region: "{region}"
2756
+ },
2757
+ body: { operations },
2758
+ ...fetchProps
2759
+ });
2760
+ for (const result of results) {
2761
+ if (result.operation === "update") {
2762
+ ids.push(result.id);
2763
+ } else {
2764
+ ids.push(null);
2765
+ }
2766
+ }
2767
+ }
2768
+ return ids;
2616
2769
  };
2617
2770
  _upsertRecordWithID = new WeakSet();
2618
2771
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
@@ -2659,17 +2812,21 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2659
2812
  _deleteRecords = new WeakSet();
2660
2813
  deleteRecords_fn = async function(recordIds) {
2661
2814
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2662
- const operations = recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } }));
2663
- const { results } = await branchTransaction({
2664
- pathParams: {
2665
- workspace: "{workspaceId}",
2666
- dbBranchName: "{dbBranch}",
2667
- region: "{region}"
2668
- },
2669
- body: { operations },
2670
- ...fetchProps
2671
- });
2672
- return results;
2815
+ const chunkedOperations = chunk(
2816
+ recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2817
+ BULK_OPERATION_MAX_SIZE
2818
+ );
2819
+ for (const operations of chunkedOperations) {
2820
+ await branchTransaction({
2821
+ pathParams: {
2822
+ workspace: "{workspaceId}",
2823
+ dbBranchName: "{dbBranch}",
2824
+ region: "{region}"
2825
+ },
2826
+ body: { operations },
2827
+ ...fetchProps
2828
+ });
2829
+ }
2673
2830
  };
2674
2831
  _setCacheQuery = new WeakSet();
2675
2832
  setCacheQuery_fn = async function(query, meta, records) {
@@ -2707,23 +2864,23 @@ const transformObjectLinks = (object) => {
2707
2864
  }, {});
2708
2865
  };
2709
2866
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2710
- const result = {};
2867
+ const data = {};
2711
2868
  const { xata, ...rest } = object ?? {};
2712
- Object.assign(result, rest);
2869
+ Object.assign(data, rest);
2713
2870
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2714
2871
  if (!columns)
2715
2872
  console.error(`Table ${table} not found in schema`);
2716
2873
  for (const column of columns ?? []) {
2717
2874
  if (!isValidColumn(selectedColumns, column))
2718
2875
  continue;
2719
- const value = result[column.name];
2876
+ const value = data[column.name];
2720
2877
  switch (column.type) {
2721
2878
  case "datetime": {
2722
- const date = value !== void 0 ? new Date(value) : void 0;
2723
- if (date && isNaN(date.getTime())) {
2879
+ const date = value !== void 0 ? new Date(value) : null;
2880
+ if (date !== null && isNaN(date.getTime())) {
2724
2881
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2725
- } else if (date) {
2726
- result[column.name] = date;
2882
+ } else {
2883
+ data[column.name] = date;
2727
2884
  }
2728
2885
  break;
2729
2886
  }
@@ -2742,48 +2899,46 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2742
2899
  }
2743
2900
  return acc;
2744
2901
  }, []);
2745
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2902
+ data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2746
2903
  } else {
2747
- result[column.name] = null;
2904
+ data[column.name] = null;
2748
2905
  }
2749
2906
  break;
2750
2907
  }
2751
2908
  default:
2752
- result[column.name] = value ?? null;
2909
+ data[column.name] = value ?? null;
2753
2910
  if (column.notNull === true && value === null) {
2754
2911
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2755
2912
  }
2756
2913
  break;
2757
2914
  }
2758
2915
  }
2759
- result.read = function(columns2) {
2760
- return db[table].read(result["id"], columns2);
2916
+ const record = { ...data };
2917
+ record.read = function(columns2) {
2918
+ return db[table].read(record["id"], columns2);
2761
2919
  };
2762
- result.update = function(data, b, c) {
2920
+ record.update = function(data2, b, c) {
2763
2921
  const columns2 = isStringArray(b) ? b : ["*"];
2764
2922
  const ifVersion = parseIfVersion(b, c);
2765
- return db[table].update(result["id"], data, columns2, { ifVersion });
2923
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2766
2924
  };
2767
- result.replace = function(data, b, c) {
2925
+ record.replace = function(data2, b, c) {
2768
2926
  const columns2 = isStringArray(b) ? b : ["*"];
2769
2927
  const ifVersion = parseIfVersion(b, c);
2770
- return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
2928
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2771
2929
  };
2772
- result.delete = function() {
2773
- return db[table].delete(result["id"]);
2930
+ record.delete = function() {
2931
+ return db[table].delete(record["id"]);
2774
2932
  };
2775
- result.getMetadata = function() {
2933
+ record.getMetadata = function() {
2776
2934
  return xata;
2777
2935
  };
2778
2936
  for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
2779
- Object.defineProperty(result, prop, { enumerable: false });
2937
+ Object.defineProperty(record, prop, { enumerable: false });
2780
2938
  }
2781
- Object.freeze(result);
2782
- return result;
2939
+ Object.freeze(record);
2940
+ return record;
2783
2941
  };
2784
- function isResponseWithRecords(value) {
2785
- return isObject(value) && Array.isArray(value.records);
2786
- }
2787
2942
  function extractId(value) {
2788
2943
  if (isString(value))
2789
2944
  return value;
@@ -2993,10 +3148,10 @@ _schemaTables = new WeakMap();
2993
3148
  _search = new WeakSet();
2994
3149
  search_fn = async function(query, options, getFetchProps) {
2995
3150
  const fetchProps = await getFetchProps();
2996
- const { tables, fuzziness, highlight, prefix } = options ?? {};
3151
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
2997
3152
  const { records } = await searchBranch({
2998
3153
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2999
- body: { tables, query, fuzziness, prefix, highlight },
3154
+ body: { tables, query, fuzziness, prefix, highlight, page },
3000
3155
  ...fetchProps
3001
3156
  });
3002
3157
  return records;
@@ -3014,18 +3169,30 @@ getSchemaTables_fn = async function(getFetchProps) {
3014
3169
  return schema.tables;
3015
3170
  };
3016
3171
 
3172
+ class TransactionPlugin extends XataPlugin {
3173
+ build({ getFetchProps }) {
3174
+ return {
3175
+ run: async (operations) => {
3176
+ const fetchProps = await getFetchProps();
3177
+ const response = await branchTransaction({
3178
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3179
+ body: { operations },
3180
+ ...fetchProps
3181
+ });
3182
+ return response;
3183
+ }
3184
+ };
3185
+ }
3186
+ }
3187
+
3017
3188
  const isBranchStrategyBuilder = (strategy) => {
3018
3189
  return typeof strategy === "function";
3019
3190
  };
3020
3191
 
3021
3192
  async function getCurrentBranchName(options) {
3022
3193
  const { branch, envBranch } = getEnvironment();
3023
- if (branch) {
3024
- const details = await getDatabaseBranch(branch, options);
3025
- if (details)
3026
- return branch;
3027
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
3028
- }
3194
+ if (branch)
3195
+ return branch;
3029
3196
  const gitBranch = envBranch || await getGitBranch();
3030
3197
  return resolveXataBranch(gitBranch, options);
3031
3198
  }
@@ -3057,7 +3224,8 @@ async function resolveXataBranch(gitBranch, options) {
3057
3224
  workspacesApiUrl: `${protocol}//${host}`,
3058
3225
  pathParams: { dbName, workspace, region },
3059
3226
  queryParams: { gitBranch, fallbackBranch },
3060
- trace: defaultTrace
3227
+ trace: defaultTrace,
3228
+ clientName: options?.clientName
3061
3229
  });
3062
3230
  return branch;
3063
3231
  }
@@ -3141,8 +3309,10 @@ const buildClient = (plugins) => {
3141
3309
  };
3142
3310
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3143
3311
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3312
+ const transactions = new TransactionPlugin().build(pluginOptions);
3144
3313
  this.db = db;
3145
3314
  this.search = search;
3315
+ this.transactions = transactions;
3146
3316
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3147
3317
  if (namespace === void 0)
3148
3318
  continue;
@@ -3163,7 +3333,7 @@ const buildClient = (plugins) => {
3163
3333
  }
3164
3334
  }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3165
3335
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3166
- const isBrowser = typeof window !== "undefined";
3336
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3167
3337
  if (isBrowser && !enableBrowser) {
3168
3338
  throw new Error(
3169
3339
  "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."
@@ -3174,15 +3344,29 @@ const buildClient = (plugins) => {
3174
3344
  const apiKey = options?.apiKey || getAPIKey();
3175
3345
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3176
3346
  const trace = options?.trace ?? defaultTrace;
3177
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
3347
+ const clientName = options?.clientName;
3348
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({
3349
+ apiKey,
3350
+ databaseURL,
3351
+ fetchImpl: options?.fetch,
3352
+ clientName: options?.clientName
3353
+ });
3178
3354
  if (!apiKey) {
3179
3355
  throw new Error("Option apiKey is required");
3180
3356
  }
3181
3357
  if (!databaseURL) {
3182
3358
  throw new Error("Option databaseURL is required");
3183
3359
  }
3184
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser };
3185
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3360
+ return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser, clientName };
3361
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
3362
+ fetch,
3363
+ apiKey,
3364
+ databaseURL,
3365
+ branch,
3366
+ trace,
3367
+ clientID,
3368
+ clientName
3369
+ }) {
3186
3370
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3187
3371
  if (!branchValue)
3188
3372
  throw new Error("Unable to resolve branch value");
@@ -3196,7 +3380,8 @@ const buildClient = (plugins) => {
3196
3380
  return databaseURL + newPath;
3197
3381
  },
3198
3382
  trace,
3199
- clientID
3383
+ clientID,
3384
+ clientName
3200
3385
  };
3201
3386
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3202
3387
  if (__privateGet(this, _branch))
@@ -3287,7 +3472,7 @@ const deserialize = (json) => {
3287
3472
  };
3288
3473
 
3289
3474
  function buildWorkerRunner(config) {
3290
- return function xataWorker(name, _worker) {
3475
+ return function xataWorker(name, worker) {
3291
3476
  return async (...args) => {
3292
3477
  const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3293
3478
  const result = await fetch(url, {
@@ -3308,5 +3493,5 @@ class XataError extends Error {
3308
3493
  }
3309
3494
  }
3310
3495
 
3311
- 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 };
3496
+ 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, 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 };
3312
3497
  //# sourceMappingURL=index.mjs.map