@xata.io/client 0.0.0-alpha.vfef462e → 0.0.0-alpha.vff43566

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,24 +1,27 @@
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
- }
3
+ const defaultTrace = async (name, fn, _options) => {
4
+ return await fn({
5
+ name,
6
+ setAttributes: () => {
7
+ return;
8
+ }
9
+ });
10
+ };
11
+ const TraceAttributes = {
12
+ KIND: "xata.trace.kind",
13
+ VERSION: "xata.sdk.version",
14
+ TABLE: "xata.table",
15
+ HTTP_REQUEST_ID: "http.request_id",
16
+ HTTP_STATUS_CODE: "http.status_code",
17
+ HTTP_HOST: "http.host",
18
+ HTTP_SCHEME: "http.scheme",
19
+ HTTP_USER_AGENT: "http.user_agent",
20
+ HTTP_METHOD: "http.method",
21
+ HTTP_URL: "http.url",
22
+ HTTP_ROUTE: "http.route",
23
+ HTTP_TARGET: "http.target"
24
+ };
22
25
 
23
26
  function notEmpty(value) {
24
27
  return value !== null && value !== void 0;
@@ -38,6 +41,21 @@ function isString(value) {
38
41
  function isStringArray(value) {
39
42
  return isDefined(value) && Array.isArray(value) && value.every(isString);
40
43
  }
44
+ function isNumber(value) {
45
+ return isDefined(value) && typeof value === "number";
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
+ }
41
59
  function toBase64(value) {
42
60
  try {
43
61
  return btoa(value);
@@ -46,10 +64,31 @@ function toBase64(value) {
46
64
  return buf.from(value).toString("base64");
47
65
  }
48
66
  }
67
+ function deepMerge(a, b) {
68
+ const result = { ...a };
69
+ for (const [key, value] of Object.entries(b)) {
70
+ if (isObject(value) && isObject(result[key])) {
71
+ result[key] = deepMerge(result[key], value);
72
+ } else {
73
+ result[key] = value;
74
+ }
75
+ }
76
+ return result;
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
+ }
49
88
 
50
89
  function getEnvironment() {
51
90
  try {
52
- if (isObject(process) && isObject(process.env)) {
91
+ if (isDefined(process) && isDefined(process.env)) {
53
92
  return {
54
93
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
55
94
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
@@ -80,6 +119,25 @@ function getEnvironment() {
80
119
  fallbackBranch: getGlobalFallbackBranch()
81
120
  };
82
121
  }
122
+ function getEnableBrowserVariable() {
123
+ try {
124
+ if (isObject(process) && isObject(process.env) && process.env.XATA_ENABLE_BROWSER !== void 0) {
125
+ return process.env.XATA_ENABLE_BROWSER === "true";
126
+ }
127
+ } catch (err) {
128
+ }
129
+ try {
130
+ if (isObject(Deno) && isObject(Deno.env) && Deno.env.get("XATA_ENABLE_BROWSER") !== void 0) {
131
+ return Deno.env.get("XATA_ENABLE_BROWSER") === "true";
132
+ }
133
+ } catch (err) {
134
+ }
135
+ try {
136
+ return XATA_ENABLE_BROWSER === true || XATA_ENABLE_BROWSER === "true";
137
+ } catch (err) {
138
+ return void 0;
139
+ }
140
+ }
83
141
  function getGlobalApiKey() {
84
142
  try {
85
143
  return XATA_API_KEY;
@@ -108,25 +166,20 @@ function getGlobalFallbackBranch() {
108
166
  return void 0;
109
167
  }
110
168
  }
111
- async function getGitBranch() {
112
- const cmd = ["git", "branch", "--show-current"];
113
- const fullCmd = cmd.join(" ");
114
- const nodeModule = ["child", "process"].join("_");
115
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
169
+ function getDatabaseURL() {
116
170
  try {
117
- if (typeof require === "function") {
118
- return require(nodeModule).execSync(fullCmd, execOptions).trim();
119
- }
120
- const { execSync } = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(nodeModule);
121
- return execSync(fullCmd, execOptions).toString().trim();
171
+ const { databaseURL } = getEnvironment();
172
+ return databaseURL;
122
173
  } catch (err) {
174
+ return void 0;
123
175
  }
176
+ }
177
+ function getBranch() {
124
178
  try {
125
- if (isObject(Deno)) {
126
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
127
- return new TextDecoder().decode(await process2.output()).trim();
128
- }
179
+ const { branch, envBranch } = getEnvironment();
180
+ return branch ?? envBranch;
129
181
  } catch (err) {
182
+ return void 0;
130
183
  }
131
184
  }
132
185
 
@@ -139,18 +192,287 @@ function getAPIKey() {
139
192
  }
140
193
  }
141
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;
142
218
  function getFetchImplementation(userFetch) {
143
219
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
144
220
  const fetchImpl = userFetch ?? globalFetch;
145
221
  if (!fetchImpl) {
146
222
  throw new Error(
147
- `The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`
223
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
148
224
  );
149
225
  }
150
226
  return fetchImpl;
151
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
+ }
301
+
302
+ async function getBytes(stream, onChunk) {
303
+ const reader = stream.getReader();
304
+ let result;
305
+ while (!(result = await reader.read()).done) {
306
+ onChunk(result.value);
307
+ }
308
+ }
309
+ function getLines(onLine) {
310
+ let buffer;
311
+ let position;
312
+ let fieldLength;
313
+ let discardTrailingNewline = false;
314
+ return function onChunk(arr) {
315
+ if (buffer === void 0) {
316
+ buffer = arr;
317
+ position = 0;
318
+ fieldLength = -1;
319
+ } else {
320
+ buffer = concat(buffer, arr);
321
+ }
322
+ const bufLength = buffer.length;
323
+ let lineStart = 0;
324
+ while (position < bufLength) {
325
+ if (discardTrailingNewline) {
326
+ if (buffer[position] === 10 /* NewLine */) {
327
+ lineStart = ++position;
328
+ }
329
+ discardTrailingNewline = false;
330
+ }
331
+ let lineEnd = -1;
332
+ for (; position < bufLength && lineEnd === -1; ++position) {
333
+ switch (buffer[position]) {
334
+ case 58 /* Colon */:
335
+ if (fieldLength === -1) {
336
+ fieldLength = position - lineStart;
337
+ }
338
+ break;
339
+ case 13 /* CarriageReturn */:
340
+ discardTrailingNewline = true;
341
+ case 10 /* NewLine */:
342
+ lineEnd = position;
343
+ break;
344
+ }
345
+ }
346
+ if (lineEnd === -1) {
347
+ break;
348
+ }
349
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
350
+ lineStart = position;
351
+ fieldLength = -1;
352
+ }
353
+ if (lineStart === bufLength) {
354
+ buffer = void 0;
355
+ } else if (lineStart !== 0) {
356
+ buffer = buffer.subarray(lineStart);
357
+ position -= lineStart;
358
+ }
359
+ };
360
+ }
361
+ function getMessages(onId, onRetry, onMessage) {
362
+ let message = newMessage();
363
+ const decoder = new TextDecoder();
364
+ return function onLine(line, fieldLength) {
365
+ if (line.length === 0) {
366
+ onMessage?.(message);
367
+ message = newMessage();
368
+ } else if (fieldLength > 0) {
369
+ const field = decoder.decode(line.subarray(0, fieldLength));
370
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
371
+ const value = decoder.decode(line.subarray(valueOffset));
372
+ switch (field) {
373
+ case "data":
374
+ message.data = message.data ? message.data + "\n" + value : value;
375
+ break;
376
+ case "event":
377
+ message.event = value;
378
+ break;
379
+ case "id":
380
+ onId(message.id = value);
381
+ break;
382
+ case "retry":
383
+ const retry = parseInt(value, 10);
384
+ if (!isNaN(retry)) {
385
+ onRetry(message.retry = retry);
386
+ }
387
+ break;
388
+ }
389
+ }
390
+ };
391
+ }
392
+ function concat(a, b) {
393
+ const res = new Uint8Array(a.length + b.length);
394
+ res.set(a);
395
+ res.set(b, a.length);
396
+ return res;
397
+ }
398
+ function newMessage() {
399
+ return {
400
+ data: "",
401
+ event: "",
402
+ id: "",
403
+ retry: void 0
404
+ };
405
+ }
406
+ const EventStreamContentType = "text/event-stream";
407
+ const LastEventId = "last-event-id";
408
+ function fetchEventSource(input, {
409
+ signal: inputSignal,
410
+ headers: inputHeaders,
411
+ onopen: inputOnOpen,
412
+ onmessage,
413
+ onclose,
414
+ onerror,
415
+ fetch: inputFetch,
416
+ ...rest
417
+ }) {
418
+ return new Promise((resolve, reject) => {
419
+ const headers = { ...inputHeaders };
420
+ if (!headers.accept) {
421
+ headers.accept = EventStreamContentType;
422
+ }
423
+ let curRequestController;
424
+ function dispose() {
425
+ curRequestController.abort();
426
+ }
427
+ inputSignal?.addEventListener("abort", () => {
428
+ dispose();
429
+ resolve();
430
+ });
431
+ const fetchImpl = inputFetch ?? fetch;
432
+ const onopen = inputOnOpen ?? defaultOnOpen;
433
+ async function create() {
434
+ curRequestController = new AbortController();
435
+ try {
436
+ const response = await fetchImpl(input, {
437
+ ...rest,
438
+ headers,
439
+ signal: curRequestController.signal
440
+ });
441
+ await onopen(response);
442
+ await getBytes(
443
+ response.body,
444
+ getLines(
445
+ getMessages(
446
+ (id) => {
447
+ if (id) {
448
+ headers[LastEventId] = id;
449
+ } else {
450
+ delete headers[LastEventId];
451
+ }
452
+ },
453
+ (_retry) => {
454
+ },
455
+ onmessage
456
+ )
457
+ )
458
+ );
459
+ onclose?.();
460
+ dispose();
461
+ resolve();
462
+ } catch (err) {
463
+ }
464
+ }
465
+ create();
466
+ });
467
+ }
468
+ function defaultOnOpen(response) {
469
+ const contentType = response.headers?.get("content-type");
470
+ if (!contentType?.startsWith(EventStreamContentType)) {
471
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
472
+ }
473
+ }
152
474
 
153
- const VERSION = "0.0.0-alpha.vfef462e";
475
+ const VERSION = "0.22.4";
154
476
 
155
477
  class ErrorWithCause extends Error {
156
478
  constructor(message, options) {
@@ -161,7 +483,7 @@ class FetcherError extends ErrorWithCause {
161
483
  constructor(status, data, requestId) {
162
484
  super(getMessage(data));
163
485
  this.status = status;
164
- this.errors = isBulkError(data) ? data.errors : void 0;
486
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
165
487
  this.requestId = requestId;
166
488
  if (data instanceof Error) {
167
489
  this.stack = data.stack;
@@ -193,6 +515,7 @@ function getMessage(data) {
193
515
  }
194
516
  }
195
517
 
518
+ const pool = new ApiRequestPool();
196
519
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
197
520
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
198
521
  if (value === void 0 || value === null)
@@ -201,310 +524,368 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
201
524
  }, {});
202
525
  const query = new URLSearchParams(cleanQueryParams).toString();
203
526
  const queryString = query.length > 0 ? `?${query}` : "";
204
- return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
527
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
528
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
529
+ }, {});
530
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
205
531
  };
206
532
  function buildBaseUrl({
533
+ endpoint,
207
534
  path,
208
535
  workspacesApiUrl,
209
536
  apiUrl,
210
- pathParams
537
+ pathParams = {}
211
538
  }) {
212
- if (!pathParams?.workspace)
213
- return `${apiUrl}${path}`;
214
- const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
215
- return url.replace("{workspaceId}", pathParams.workspace);
539
+ if (endpoint === "dataPlane") {
540
+ const url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
541
+ const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
542
+ return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
543
+ }
544
+ return `${apiUrl}${path}`;
216
545
  }
217
546
  function hostHeader(url) {
218
547
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
219
548
  const { groups } = pattern.exec(url) ?? {};
220
549
  return groups?.host ? { Host: groups.host } : {};
221
550
  }
551
+ const defaultClientID = generateUUID();
222
552
  async function fetch$1({
223
553
  url: path,
224
554
  method,
225
555
  body,
226
- headers,
556
+ headers: customHeaders,
557
+ pathParams,
558
+ queryParams,
559
+ fetch: fetch2,
560
+ apiKey,
561
+ endpoint,
562
+ apiUrl,
563
+ workspacesApiUrl,
564
+ trace,
565
+ signal,
566
+ clientID,
567
+ sessionID,
568
+ clientName,
569
+ xataAgentExtra,
570
+ fetchOptions = {}
571
+ }) {
572
+ pool.setFetch(fetch2);
573
+ return await trace(
574
+ `${method.toUpperCase()} ${path}`,
575
+ async ({ setAttributes }) => {
576
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
577
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
578
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
579
+ setAttributes({
580
+ [TraceAttributes.HTTP_URL]: url,
581
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
582
+ });
583
+ const xataAgent = compact([
584
+ ["client", "TS_SDK"],
585
+ ["version", VERSION],
586
+ isDefined(clientName) ? ["service", clientName] : void 0,
587
+ ...Object.entries(xataAgentExtra ?? {})
588
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
589
+ const headers = {
590
+ "Accept-Encoding": "identity",
591
+ "Content-Type": "application/json",
592
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
593
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
594
+ "X-Xata-Agent": xataAgent,
595
+ ...customHeaders,
596
+ ...hostHeader(fullUrl),
597
+ Authorization: `Bearer ${apiKey}`
598
+ };
599
+ const response = await pool.request(url, {
600
+ ...fetchOptions,
601
+ method: method.toUpperCase(),
602
+ body: body ? JSON.stringify(body) : void 0,
603
+ headers,
604
+ signal
605
+ });
606
+ const { host, protocol } = parseUrl(response.url);
607
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
608
+ setAttributes({
609
+ [TraceAttributes.KIND]: "http",
610
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
611
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
612
+ [TraceAttributes.HTTP_HOST]: host,
613
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
614
+ });
615
+ if (response.status === 204) {
616
+ return {};
617
+ }
618
+ if (response.status === 429) {
619
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
620
+ }
621
+ try {
622
+ const jsonResponse = await response.json();
623
+ if (response.ok) {
624
+ return jsonResponse;
625
+ }
626
+ throw new FetcherError(response.status, jsonResponse, requestId);
627
+ } catch (error) {
628
+ throw new FetcherError(response.status, error, requestId);
629
+ }
630
+ },
631
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
632
+ );
633
+ }
634
+ function fetchSSERequest({
635
+ url: path,
636
+ method,
637
+ body,
638
+ headers: customHeaders,
227
639
  pathParams,
228
640
  queryParams,
229
- fetchImpl,
641
+ fetch: fetch2,
230
642
  apiKey,
643
+ endpoint,
231
644
  apiUrl,
232
- workspacesApiUrl
645
+ workspacesApiUrl,
646
+ onMessage,
647
+ onError,
648
+ onClose,
649
+ signal,
650
+ clientID,
651
+ sessionID,
652
+ clientName,
653
+ xataAgentExtra
233
654
  }) {
234
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
655
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
235
656
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
236
657
  const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
237
- const response = await fetchImpl(url, {
238
- method: method.toUpperCase(),
239
- body: body ? JSON.stringify(body) : void 0,
658
+ void fetchEventSource(url, {
659
+ method,
660
+ body: JSON.stringify(body),
661
+ fetch: fetch2,
662
+ signal,
240
663
  headers: {
241
- "Content-Type": "application/json",
242
- "User-Agent": `Xata client-ts/${VERSION}`,
243
- ...headers,
244
- ...hostHeader(fullUrl),
245
- Authorization: `Bearer ${apiKey}`
664
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
665
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
666
+ "X-Xata-Agent": compact([
667
+ ["client", "TS_SDK"],
668
+ ["version", VERSION],
669
+ isDefined(clientName) ? ["service", clientName] : void 0,
670
+ ...Object.entries(xataAgentExtra ?? {})
671
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
672
+ ...customHeaders,
673
+ Authorization: `Bearer ${apiKey}`,
674
+ "Content-Type": "application/json"
675
+ },
676
+ onmessage(ev) {
677
+ onMessage?.(JSON.parse(ev.data));
678
+ },
679
+ onerror(ev) {
680
+ onError?.(JSON.parse(ev.data));
681
+ },
682
+ onclose() {
683
+ onClose?.();
246
684
  }
247
685
  });
248
- if (response.status === 204) {
249
- return {};
250
- }
251
- const requestId = response.headers?.get("x-request-id") ?? void 0;
686
+ }
687
+ function parseUrl(url) {
252
688
  try {
253
- const jsonResponse = await response.json();
254
- if (response.ok) {
255
- return jsonResponse;
256
- }
257
- throw new FetcherError(response.status, jsonResponse, requestId);
689
+ const { host, protocol } = new URL(url);
690
+ return { host, protocol };
258
691
  } catch (error) {
259
- throw new FetcherError(response.status, error, requestId);
692
+ return {};
260
693
  }
261
694
  }
262
695
 
263
- const getUser = (variables) => fetch$1({ url: "/user", method: "get", ...variables });
264
- const updateUser = (variables) => fetch$1({ url: "/user", method: "put", ...variables });
265
- const deleteUser = (variables) => fetch$1({ url: "/user", method: "delete", ...variables });
266
- const getUserAPIKeys = (variables) => fetch$1({
267
- url: "/user/keys",
268
- method: "get",
269
- ...variables
270
- });
271
- const createUserAPIKey = (variables) => fetch$1({
272
- url: "/user/keys/{keyName}",
273
- method: "post",
274
- ...variables
275
- });
276
- const deleteUserAPIKey = (variables) => fetch$1({
277
- url: "/user/keys/{keyName}",
278
- method: "delete",
279
- ...variables
280
- });
281
- const createWorkspace = (variables) => fetch$1({
282
- url: "/workspaces",
283
- method: "post",
284
- ...variables
285
- });
286
- const getWorkspacesList = (variables) => fetch$1({
287
- url: "/workspaces",
288
- method: "get",
289
- ...variables
290
- });
291
- const getWorkspace = (variables) => fetch$1({
292
- url: "/workspaces/{workspaceId}",
293
- method: "get",
294
- ...variables
295
- });
296
- const updateWorkspace = (variables) => fetch$1({
297
- url: "/workspaces/{workspaceId}",
298
- method: "put",
299
- ...variables
300
- });
301
- const deleteWorkspace = (variables) => fetch$1({
302
- url: "/workspaces/{workspaceId}",
303
- method: "delete",
304
- ...variables
305
- });
306
- const getWorkspaceMembersList = (variables) => fetch$1({
307
- url: "/workspaces/{workspaceId}/members",
308
- method: "get",
309
- ...variables
310
- });
311
- const updateWorkspaceMemberRole = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables });
312
- const removeWorkspaceMember = (variables) => fetch$1({
313
- url: "/workspaces/{workspaceId}/members/{userId}",
314
- method: "delete",
315
- ...variables
316
- });
317
- const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
318
- const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
319
- const cancelWorkspaceMemberInvite = (variables) => fetch$1({
320
- url: "/workspaces/{workspaceId}/invites/{inviteId}",
321
- method: "delete",
322
- ...variables
323
- });
324
- const resendWorkspaceMemberInvite = (variables) => fetch$1({
325
- url: "/workspaces/{workspaceId}/invites/{inviteId}/resend",
326
- method: "post",
327
- ...variables
328
- });
329
- const acceptWorkspaceMemberInvite = (variables) => fetch$1({
330
- url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept",
331
- method: "post",
332
- ...variables
333
- });
334
- const getDatabaseList = (variables) => fetch$1({
335
- url: "/dbs",
336
- method: "get",
337
- ...variables
338
- });
339
- const getBranchList = (variables) => fetch$1({
696
+ const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
697
+
698
+ const getBranchList = (variables, signal) => dataPlaneFetch({
340
699
  url: "/dbs/{dbName}",
341
700
  method: "get",
342
- ...variables
343
- });
344
- const createDatabase = (variables) => fetch$1({
345
- url: "/dbs/{dbName}",
346
- method: "put",
347
- ...variables
348
- });
349
- const deleteDatabase = (variables) => fetch$1({
350
- url: "/dbs/{dbName}",
351
- method: "delete",
352
- ...variables
701
+ ...variables,
702
+ signal
353
703
  });
354
- const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
355
- const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
356
- const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
357
- const resolveBranch = (variables) => fetch$1({
358
- url: "/dbs/{dbName}/resolveBranch",
359
- method: "get",
360
- ...variables
361
- });
362
- const getBranchDetails = (variables) => fetch$1({
704
+ const getBranchDetails = (variables, signal) => dataPlaneFetch({
363
705
  url: "/db/{dbBranchName}",
364
706
  method: "get",
365
- ...variables
707
+ ...variables,
708
+ signal
366
709
  });
367
- const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
368
- const deleteBranch = (variables) => fetch$1({
710
+ const createBranch = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
711
+ const deleteBranch = (variables, signal) => dataPlaneFetch({
369
712
  url: "/db/{dbBranchName}",
370
713
  method: "delete",
371
- ...variables
714
+ ...variables,
715
+ signal
716
+ });
717
+ const copyBranch = (variables, signal) => dataPlaneFetch({
718
+ url: "/db/{dbBranchName}/copy",
719
+ method: "post",
720
+ ...variables,
721
+ signal
372
722
  });
373
- const updateBranchMetadata = (variables) => fetch$1({
723
+ const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
374
724
  url: "/db/{dbBranchName}/metadata",
375
725
  method: "put",
376
- ...variables
726
+ ...variables,
727
+ signal
377
728
  });
378
- const getBranchMetadata = (variables) => fetch$1({
729
+ const getBranchMetadata = (variables, signal) => dataPlaneFetch({
379
730
  url: "/db/{dbBranchName}/metadata",
380
731
  method: "get",
381
- ...variables
732
+ ...variables,
733
+ signal
382
734
  });
383
- const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
384
- const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
385
- const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
386
- const getBranchStats = (variables) => fetch$1({
735
+ const getBranchStats = (variables, signal) => dataPlaneFetch({
387
736
  url: "/db/{dbBranchName}/stats",
388
737
  method: "get",
389
- ...variables
738
+ ...variables,
739
+ signal
390
740
  });
391
- const createTable = (variables) => fetch$1({
741
+ const getGitBranchesMapping = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables, signal });
742
+ const addGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables, signal });
743
+ const removeGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables, signal });
744
+ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/resolveBranch", method: "get", ...variables, signal });
745
+ const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
746
+ const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
747
+ const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
748
+ const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
749
+ const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
750
+ const getMigrationRequest = (variables, signal) => dataPlaneFetch({
751
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
752
+ method: "get",
753
+ ...variables,
754
+ signal
755
+ });
756
+ const updateMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables, signal });
757
+ const listMigrationRequestsCommits = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables, signal });
758
+ const compareMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables, signal });
759
+ const getMigrationRequestIsMerged = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables, signal });
760
+ const mergeMigrationRequest = (variables, signal) => dataPlaneFetch({
761
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
762
+ method: "post",
763
+ ...variables,
764
+ signal
765
+ });
766
+ const getBranchSchemaHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables, signal });
767
+ const compareBranchWithUserSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables, signal });
768
+ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables, signal });
769
+ const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
770
+ const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
771
+ const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
772
+ const createTable = (variables, signal) => dataPlaneFetch({
392
773
  url: "/db/{dbBranchName}/tables/{tableName}",
393
774
  method: "put",
394
- ...variables
775
+ ...variables,
776
+ signal
395
777
  });
396
- const deleteTable = (variables) => fetch$1({
778
+ const deleteTable = (variables, signal) => dataPlaneFetch({
397
779
  url: "/db/{dbBranchName}/tables/{tableName}",
398
780
  method: "delete",
399
- ...variables
400
- });
401
- const updateTable = (variables) => fetch$1({
402
- url: "/db/{dbBranchName}/tables/{tableName}",
403
- method: "patch",
404
- ...variables
781
+ ...variables,
782
+ signal
405
783
  });
406
- const getTableSchema = (variables) => fetch$1({
784
+ const updateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}", method: "patch", ...variables, signal });
785
+ const getTableSchema = (variables, signal) => dataPlaneFetch({
407
786
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
408
787
  method: "get",
409
- ...variables
788
+ ...variables,
789
+ signal
410
790
  });
411
- const setTableSchema = (variables) => fetch$1({
412
- url: "/db/{dbBranchName}/tables/{tableName}/schema",
413
- method: "put",
414
- ...variables
415
- });
416
- const getTableColumns = (variables) => fetch$1({
791
+ const setTableSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/schema", method: "put", ...variables, signal });
792
+ const getTableColumns = (variables, signal) => dataPlaneFetch({
417
793
  url: "/db/{dbBranchName}/tables/{tableName}/columns",
418
794
  method: "get",
419
- ...variables
420
- });
421
- const addTableColumn = (variables) => fetch$1({
422
- url: "/db/{dbBranchName}/tables/{tableName}/columns",
423
- method: "post",
424
- ...variables
795
+ ...variables,
796
+ signal
425
797
  });
426
- const getColumn = (variables) => fetch$1({
798
+ const addTableColumn = (variables, signal) => dataPlaneFetch(
799
+ { url: "/db/{dbBranchName}/tables/{tableName}/columns", method: "post", ...variables, signal }
800
+ );
801
+ const getColumn = (variables, signal) => dataPlaneFetch({
427
802
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
428
803
  method: "get",
429
- ...variables
804
+ ...variables,
805
+ signal
430
806
  });
431
- const deleteColumn = (variables) => fetch$1({
807
+ const updateColumn = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}", method: "patch", ...variables, signal });
808
+ const deleteColumn = (variables, signal) => dataPlaneFetch({
432
809
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
433
810
  method: "delete",
434
- ...variables
435
- });
436
- const updateColumn = (variables) => fetch$1({
437
- url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
438
- method: "patch",
439
- ...variables
440
- });
441
- const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
442
- const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
443
- const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
444
- const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
445
- const deleteRecord = (variables) => fetch$1({
446
- url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
447
- method: "delete",
448
- ...variables
811
+ ...variables,
812
+ signal
449
813
  });
450
- const getRecord = (variables) => fetch$1({
814
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
815
+ const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
816
+ const getRecord = (variables, signal) => dataPlaneFetch({
451
817
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
452
818
  method: "get",
453
- ...variables
819
+ ...variables,
820
+ signal
454
821
  });
455
- const bulkInsertTableRecords = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables });
456
- const queryTable = (variables) => fetch$1({
822
+ const insertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables, signal });
823
+ const updateRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables, signal });
824
+ const upsertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables, signal });
825
+ const deleteRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "delete", ...variables, signal });
826
+ const bulkInsertTableRecords = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables, signal });
827
+ const queryTable = (variables, signal) => dataPlaneFetch({
457
828
  url: "/db/{dbBranchName}/tables/{tableName}/query",
458
829
  method: "post",
459
- ...variables
830
+ ...variables,
831
+ signal
460
832
  });
461
- const searchTable = (variables) => fetch$1({
833
+ const searchBranch = (variables, signal) => dataPlaneFetch({
834
+ url: "/db/{dbBranchName}/search",
835
+ method: "post",
836
+ ...variables,
837
+ signal
838
+ });
839
+ const searchTable = (variables, signal) => dataPlaneFetch({
462
840
  url: "/db/{dbBranchName}/tables/{tableName}/search",
463
841
  method: "post",
464
- ...variables
842
+ ...variables,
843
+ signal
465
844
  });
466
- const searchBranch = (variables) => fetch$1({
467
- url: "/db/{dbBranchName}/search",
845
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
846
+ const askTable = (variables, signal) => dataPlaneFetch({
847
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
468
848
  method: "post",
469
- ...variables
849
+ ...variables,
850
+ signal
470
851
  });
471
- const operationsByTag = {
472
- users: { getUser, updateUser, deleteUser, getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
473
- workspaces: {
474
- createWorkspace,
475
- getWorkspacesList,
476
- getWorkspace,
477
- updateWorkspace,
478
- deleteWorkspace,
479
- getWorkspaceMembersList,
480
- updateWorkspaceMemberRole,
481
- removeWorkspaceMember,
482
- inviteWorkspaceMember,
483
- updateWorkspaceMemberInvite,
484
- cancelWorkspaceMemberInvite,
485
- resendWorkspaceMemberInvite,
486
- acceptWorkspaceMemberInvite
487
- },
488
- database: {
489
- getDatabaseList,
490
- createDatabase,
491
- deleteDatabase,
492
- getGitBranchesMapping,
493
- addGitBranchesEntry,
494
- removeGitBranchesEntry,
495
- resolveBranch
496
- },
852
+ const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
853
+ const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
854
+ const operationsByTag$2 = {
497
855
  branch: {
498
856
  getBranchList,
499
857
  getBranchDetails,
500
858
  createBranch,
501
859
  deleteBranch,
860
+ copyBranch,
502
861
  updateBranchMetadata,
503
862
  getBranchMetadata,
863
+ getBranchStats,
864
+ getGitBranchesMapping,
865
+ addGitBranchesEntry,
866
+ removeGitBranchesEntry,
867
+ resolveBranch
868
+ },
869
+ migrations: {
504
870
  getBranchMigrationHistory,
505
- executeBranchMigrationPlan,
506
871
  getBranchMigrationPlan,
507
- getBranchStats
872
+ executeBranchMigrationPlan,
873
+ getBranchSchemaHistory,
874
+ compareBranchWithUserSchema,
875
+ compareBranchSchemas,
876
+ updateBranchSchema,
877
+ previewBranchSchemaEdit,
878
+ applyBranchSchemaEdit
879
+ },
880
+ migrationRequests: {
881
+ queryMigrationRequests,
882
+ createMigrationRequest,
883
+ getMigrationRequest,
884
+ updateMigrationRequest,
885
+ listMigrationRequestsCommits,
886
+ compareMigrationRequest,
887
+ getMigrationRequestIsMerged,
888
+ mergeMigrationRequest
508
889
  },
509
890
  table: {
510
891
  createTable,
@@ -515,27 +896,174 @@ const operationsByTag = {
515
896
  getTableColumns,
516
897
  addTableColumn,
517
898
  getColumn,
518
- deleteColumn,
519
- updateColumn
899
+ updateColumn,
900
+ deleteColumn
520
901
  },
521
902
  records: {
903
+ branchTransaction,
522
904
  insertRecord,
905
+ getRecord,
523
906
  insertRecordWithID,
524
907
  updateRecordWithID,
525
908
  upsertRecordWithID,
526
909
  deleteRecord,
527
- getRecord,
528
- bulkInsertTableRecords,
910
+ bulkInsertTableRecords
911
+ },
912
+ searchAndFilter: {
529
913
  queryTable,
914
+ searchBranch,
530
915
  searchTable,
531
- searchBranch
916
+ vectorSearchTable,
917
+ askTable,
918
+ summarizeTable,
919
+ aggregateTable
920
+ }
921
+ };
922
+
923
+ const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
924
+
925
+ const getUser = (variables, signal) => controlPlaneFetch({
926
+ url: "/user",
927
+ method: "get",
928
+ ...variables,
929
+ signal
930
+ });
931
+ const updateUser = (variables, signal) => controlPlaneFetch({
932
+ url: "/user",
933
+ method: "put",
934
+ ...variables,
935
+ signal
936
+ });
937
+ const deleteUser = (variables, signal) => controlPlaneFetch({
938
+ url: "/user",
939
+ method: "delete",
940
+ ...variables,
941
+ signal
942
+ });
943
+ const getUserAPIKeys = (variables, signal) => controlPlaneFetch({
944
+ url: "/user/keys",
945
+ method: "get",
946
+ ...variables,
947
+ signal
948
+ });
949
+ const createUserAPIKey = (variables, signal) => controlPlaneFetch({
950
+ url: "/user/keys/{keyName}",
951
+ method: "post",
952
+ ...variables,
953
+ signal
954
+ });
955
+ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
956
+ url: "/user/keys/{keyName}",
957
+ method: "delete",
958
+ ...variables,
959
+ signal
960
+ });
961
+ const getWorkspacesList = (variables, signal) => controlPlaneFetch({
962
+ url: "/workspaces",
963
+ method: "get",
964
+ ...variables,
965
+ signal
966
+ });
967
+ const createWorkspace = (variables, signal) => controlPlaneFetch({
968
+ url: "/workspaces",
969
+ method: "post",
970
+ ...variables,
971
+ signal
972
+ });
973
+ const getWorkspace = (variables, signal) => controlPlaneFetch({
974
+ url: "/workspaces/{workspaceId}",
975
+ method: "get",
976
+ ...variables,
977
+ signal
978
+ });
979
+ const updateWorkspace = (variables, signal) => controlPlaneFetch({
980
+ url: "/workspaces/{workspaceId}",
981
+ method: "put",
982
+ ...variables,
983
+ signal
984
+ });
985
+ const deleteWorkspace = (variables, signal) => controlPlaneFetch({
986
+ url: "/workspaces/{workspaceId}",
987
+ method: "delete",
988
+ ...variables,
989
+ signal
990
+ });
991
+ const getWorkspaceMembersList = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/members", method: "get", ...variables, signal });
992
+ const updateWorkspaceMemberRole = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables, signal });
993
+ const removeWorkspaceMember = (variables, signal) => controlPlaneFetch({
994
+ url: "/workspaces/{workspaceId}/members/{userId}",
995
+ method: "delete",
996
+ ...variables,
997
+ signal
998
+ });
999
+ const inviteWorkspaceMember = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables, signal });
1000
+ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables, signal });
1001
+ const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
1002
+ const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
1003
+ const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1004
+ const getDatabaseList = (variables, signal) => controlPlaneFetch({
1005
+ url: "/workspaces/{workspaceId}/dbs",
1006
+ method: "get",
1007
+ ...variables,
1008
+ signal
1009
+ });
1010
+ const createDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables, signal });
1011
+ const deleteDatabase = (variables, signal) => controlPlaneFetch({
1012
+ url: "/workspaces/{workspaceId}/dbs/{dbName}",
1013
+ method: "delete",
1014
+ ...variables,
1015
+ signal
1016
+ });
1017
+ const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
1018
+ const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1019
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1020
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1021
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
1022
+ const listRegions = (variables, signal) => controlPlaneFetch({
1023
+ url: "/workspaces/{workspaceId}/regions",
1024
+ method: "get",
1025
+ ...variables,
1026
+ signal
1027
+ });
1028
+ const operationsByTag$1 = {
1029
+ users: { getUser, updateUser, deleteUser },
1030
+ authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
1031
+ workspaces: {
1032
+ getWorkspacesList,
1033
+ createWorkspace,
1034
+ getWorkspace,
1035
+ updateWorkspace,
1036
+ deleteWorkspace,
1037
+ getWorkspaceMembersList,
1038
+ updateWorkspaceMemberRole,
1039
+ removeWorkspaceMember
1040
+ },
1041
+ invites: {
1042
+ inviteWorkspaceMember,
1043
+ updateWorkspaceMemberInvite,
1044
+ cancelWorkspaceMemberInvite,
1045
+ acceptWorkspaceMemberInvite,
1046
+ resendWorkspaceMemberInvite
1047
+ },
1048
+ databases: {
1049
+ getDatabaseList,
1050
+ createDatabase,
1051
+ deleteDatabase,
1052
+ getDatabaseMetadata,
1053
+ updateDatabaseMetadata,
1054
+ getDatabaseGithubSettings,
1055
+ updateDatabaseGithubSettings,
1056
+ deleteDatabaseGithubSettings,
1057
+ listRegions
532
1058
  }
533
1059
  };
534
1060
 
1061
+ const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);
1062
+
535
1063
  function getHostUrl(provider, type) {
536
- if (isValidAlias(provider)) {
1064
+ if (isHostProviderAlias(provider)) {
537
1065
  return providers[provider][type];
538
- } else if (isValidBuilder(provider)) {
1066
+ } else if (isHostProviderBuilder(provider)) {
539
1067
  return provider[type];
540
1068
  }
541
1069
  throw new Error("Invalid API provider");
@@ -543,19 +1071,40 @@ function getHostUrl(provider, type) {
543
1071
  const providers = {
544
1072
  production: {
545
1073
  main: "https://api.xata.io",
546
- workspaces: "https://{workspaceId}.xata.sh"
1074
+ workspaces: "https://{workspaceId}.{region}.xata.sh"
547
1075
  },
548
1076
  staging: {
549
- main: "https://staging.xatabase.co",
550
- workspaces: "https://{workspaceId}.staging.xatabase.co"
1077
+ main: "https://api.staging-xata.dev",
1078
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
551
1079
  }
552
1080
  };
553
- function isValidAlias(alias) {
1081
+ function isHostProviderAlias(alias) {
554
1082
  return isString(alias) && Object.keys(providers).includes(alias);
555
1083
  }
556
- function isValidBuilder(builder) {
1084
+ function isHostProviderBuilder(builder) {
557
1085
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
558
1086
  }
1087
+ function parseProviderString(provider = "production") {
1088
+ if (isHostProviderAlias(provider)) {
1089
+ return provider;
1090
+ }
1091
+ const [main, workspaces] = provider.split(",");
1092
+ if (!main || !workspaces)
1093
+ return null;
1094
+ return { main, workspaces };
1095
+ }
1096
+ function parseWorkspacesUrlParts(url) {
1097
+ if (!isString(url))
1098
+ return null;
1099
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
1100
+ const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1101
+ const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1102
+ const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1103
+ const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
1104
+ if (!match)
1105
+ return null;
1106
+ return { workspace: match[1], region: match[2] };
1107
+ }
559
1108
 
560
1109
  var __accessCheck$7 = (obj, member, msg) => {
561
1110
  if (!member.has(obj))
@@ -581,15 +1130,21 @@ class XataApiClient {
581
1130
  __privateAdd$7(this, _extraProps, void 0);
582
1131
  __privateAdd$7(this, _namespaces, {});
583
1132
  const provider = options.host ?? "production";
584
- const apiKey = options?.apiKey ?? getAPIKey();
1133
+ const apiKey = options.apiKey ?? getAPIKey();
1134
+ const trace = options.trace ?? defaultTrace;
1135
+ const clientID = generateUUID();
585
1136
  if (!apiKey) {
586
1137
  throw new Error("Could not resolve a valid apiKey");
587
1138
  }
588
1139
  __privateSet$7(this, _extraProps, {
589
1140
  apiUrl: getHostUrl(provider, "main"),
590
1141
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
591
- fetchImpl: getFetchImplementation(options.fetch),
592
- apiKey
1142
+ fetch: getFetchImplementation(options.fetch),
1143
+ apiKey,
1144
+ trace,
1145
+ clientName: options.clientName,
1146
+ xataAgentExtra: options.xataAgentExtra,
1147
+ clientID
593
1148
  });
594
1149
  }
595
1150
  get user() {
@@ -597,21 +1152,41 @@ class XataApiClient {
597
1152
  __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
598
1153
  return __privateGet$7(this, _namespaces).user;
599
1154
  }
1155
+ get authentication() {
1156
+ if (!__privateGet$7(this, _namespaces).authentication)
1157
+ __privateGet$7(this, _namespaces).authentication = new AuthenticationApi(__privateGet$7(this, _extraProps));
1158
+ return __privateGet$7(this, _namespaces).authentication;
1159
+ }
600
1160
  get workspaces() {
601
1161
  if (!__privateGet$7(this, _namespaces).workspaces)
602
1162
  __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
603
1163
  return __privateGet$7(this, _namespaces).workspaces;
604
1164
  }
605
- get databases() {
606
- if (!__privateGet$7(this, _namespaces).databases)
607
- __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
608
- return __privateGet$7(this, _namespaces).databases;
1165
+ get invites() {
1166
+ if (!__privateGet$7(this, _namespaces).invites)
1167
+ __privateGet$7(this, _namespaces).invites = new InvitesApi(__privateGet$7(this, _extraProps));
1168
+ return __privateGet$7(this, _namespaces).invites;
1169
+ }
1170
+ get database() {
1171
+ if (!__privateGet$7(this, _namespaces).database)
1172
+ __privateGet$7(this, _namespaces).database = new DatabaseApi(__privateGet$7(this, _extraProps));
1173
+ return __privateGet$7(this, _namespaces).database;
609
1174
  }
610
1175
  get branches() {
611
1176
  if (!__privateGet$7(this, _namespaces).branches)
612
1177
  __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
613
1178
  return __privateGet$7(this, _namespaces).branches;
614
1179
  }
1180
+ get migrations() {
1181
+ if (!__privateGet$7(this, _namespaces).migrations)
1182
+ __privateGet$7(this, _namespaces).migrations = new MigrationsApi(__privateGet$7(this, _extraProps));
1183
+ return __privateGet$7(this, _namespaces).migrations;
1184
+ }
1185
+ get migrationRequests() {
1186
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
1187
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
1188
+ return __privateGet$7(this, _namespaces).migrationRequests;
1189
+ }
615
1190
  get tables() {
616
1191
  if (!__privateGet$7(this, _namespaces).tables)
617
1192
  __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
@@ -622,6 +1197,11 @@ class XataApiClient {
622
1197
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
623
1198
  return __privateGet$7(this, _namespaces).records;
624
1199
  }
1200
+ get searchAndFilter() {
1201
+ if (!__privateGet$7(this, _namespaces).searchAndFilter)
1202
+ __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
1203
+ return __privateGet$7(this, _namespaces).searchAndFilter;
1204
+ }
625
1205
  }
626
1206
  _extraProps = new WeakMap();
627
1207
  _namespaces = new WeakMap();
@@ -632,24 +1212,29 @@ class UserApi {
632
1212
  getUser() {
633
1213
  return operationsByTag.users.getUser({ ...this.extraProps });
634
1214
  }
635
- updateUser(user) {
1215
+ updateUser({ user }) {
636
1216
  return operationsByTag.users.updateUser({ body: user, ...this.extraProps });
637
1217
  }
638
1218
  deleteUser() {
639
1219
  return operationsByTag.users.deleteUser({ ...this.extraProps });
640
1220
  }
1221
+ }
1222
+ class AuthenticationApi {
1223
+ constructor(extraProps) {
1224
+ this.extraProps = extraProps;
1225
+ }
641
1226
  getUserAPIKeys() {
642
- return operationsByTag.users.getUserAPIKeys({ ...this.extraProps });
1227
+ return operationsByTag.authentication.getUserAPIKeys({ ...this.extraProps });
643
1228
  }
644
- createUserAPIKey(keyName) {
645
- return operationsByTag.users.createUserAPIKey({
646
- pathParams: { keyName },
1229
+ createUserAPIKey({ name }) {
1230
+ return operationsByTag.authentication.createUserAPIKey({
1231
+ pathParams: { keyName: name },
647
1232
  ...this.extraProps
648
1233
  });
649
1234
  }
650
- deleteUserAPIKey(keyName) {
651
- return operationsByTag.users.deleteUserAPIKey({
652
- pathParams: { keyName },
1235
+ deleteUserAPIKey({ name }) {
1236
+ return operationsByTag.authentication.deleteUserAPIKey({
1237
+ pathParams: { keyName: name },
653
1238
  ...this.extraProps
654
1239
  });
655
1240
  }
@@ -658,368 +1243,996 @@ class WorkspaceApi {
658
1243
  constructor(extraProps) {
659
1244
  this.extraProps = extraProps;
660
1245
  }
661
- createWorkspace(workspaceMeta) {
1246
+ getWorkspacesList() {
1247
+ return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
1248
+ }
1249
+ createWorkspace({ data }) {
662
1250
  return operationsByTag.workspaces.createWorkspace({
663
- body: workspaceMeta,
1251
+ body: data,
664
1252
  ...this.extraProps
665
1253
  });
666
1254
  }
667
- getWorkspacesList() {
668
- return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
669
- }
670
- getWorkspace(workspaceId) {
1255
+ getWorkspace({ workspace }) {
671
1256
  return operationsByTag.workspaces.getWorkspace({
672
- pathParams: { workspaceId },
1257
+ pathParams: { workspaceId: workspace },
673
1258
  ...this.extraProps
674
1259
  });
675
1260
  }
676
- updateWorkspace(workspaceId, workspaceMeta) {
1261
+ updateWorkspace({
1262
+ workspace,
1263
+ update
1264
+ }) {
677
1265
  return operationsByTag.workspaces.updateWorkspace({
678
- pathParams: { workspaceId },
679
- body: workspaceMeta,
1266
+ pathParams: { workspaceId: workspace },
1267
+ body: update,
680
1268
  ...this.extraProps
681
1269
  });
682
1270
  }
683
- deleteWorkspace(workspaceId) {
1271
+ deleteWorkspace({ workspace }) {
684
1272
  return operationsByTag.workspaces.deleteWorkspace({
685
- pathParams: { workspaceId },
1273
+ pathParams: { workspaceId: workspace },
686
1274
  ...this.extraProps
687
1275
  });
688
1276
  }
689
- getWorkspaceMembersList(workspaceId) {
1277
+ getWorkspaceMembersList({ workspace }) {
690
1278
  return operationsByTag.workspaces.getWorkspaceMembersList({
691
- pathParams: { workspaceId },
1279
+ pathParams: { workspaceId: workspace },
692
1280
  ...this.extraProps
693
1281
  });
694
1282
  }
695
- updateWorkspaceMemberRole(workspaceId, userId, role) {
1283
+ updateWorkspaceMemberRole({
1284
+ workspace,
1285
+ user,
1286
+ role
1287
+ }) {
696
1288
  return operationsByTag.workspaces.updateWorkspaceMemberRole({
697
- pathParams: { workspaceId, userId },
1289
+ pathParams: { workspaceId: workspace, userId: user },
698
1290
  body: { role },
699
1291
  ...this.extraProps
700
1292
  });
701
1293
  }
702
- removeWorkspaceMember(workspaceId, userId) {
1294
+ removeWorkspaceMember({
1295
+ workspace,
1296
+ user
1297
+ }) {
703
1298
  return operationsByTag.workspaces.removeWorkspaceMember({
704
- pathParams: { workspaceId, userId },
1299
+ pathParams: { workspaceId: workspace, userId: user },
705
1300
  ...this.extraProps
706
1301
  });
707
1302
  }
708
- inviteWorkspaceMember(workspaceId, email, role) {
709
- return operationsByTag.workspaces.inviteWorkspaceMember({
710
- pathParams: { workspaceId },
1303
+ }
1304
+ class InvitesApi {
1305
+ constructor(extraProps) {
1306
+ this.extraProps = extraProps;
1307
+ }
1308
+ inviteWorkspaceMember({
1309
+ workspace,
1310
+ email,
1311
+ role
1312
+ }) {
1313
+ return operationsByTag.invites.inviteWorkspaceMember({
1314
+ pathParams: { workspaceId: workspace },
711
1315
  body: { email, role },
712
1316
  ...this.extraProps
713
1317
  });
714
1318
  }
715
- updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
716
- return operationsByTag.workspaces.updateWorkspaceMemberInvite({
717
- pathParams: { workspaceId, inviteId },
1319
+ updateWorkspaceMemberInvite({
1320
+ workspace,
1321
+ invite,
1322
+ role
1323
+ }) {
1324
+ return operationsByTag.invites.updateWorkspaceMemberInvite({
1325
+ pathParams: { workspaceId: workspace, inviteId: invite },
718
1326
  body: { role },
719
1327
  ...this.extraProps
720
1328
  });
721
1329
  }
722
- cancelWorkspaceMemberInvite(workspaceId, inviteId) {
723
- return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
724
- pathParams: { workspaceId, inviteId },
1330
+ cancelWorkspaceMemberInvite({
1331
+ workspace,
1332
+ invite
1333
+ }) {
1334
+ return operationsByTag.invites.cancelWorkspaceMemberInvite({
1335
+ pathParams: { workspaceId: workspace, inviteId: invite },
725
1336
  ...this.extraProps
726
1337
  });
727
1338
  }
728
- resendWorkspaceMemberInvite(workspaceId, inviteId) {
729
- return operationsByTag.workspaces.resendWorkspaceMemberInvite({
730
- pathParams: { workspaceId, inviteId },
1339
+ acceptWorkspaceMemberInvite({
1340
+ workspace,
1341
+ key
1342
+ }) {
1343
+ return operationsByTag.invites.acceptWorkspaceMemberInvite({
1344
+ pathParams: { workspaceId: workspace, inviteKey: key },
731
1345
  ...this.extraProps
732
1346
  });
733
1347
  }
734
- acceptWorkspaceMemberInvite(workspaceId, inviteKey) {
735
- return operationsByTag.workspaces.acceptWorkspaceMemberInvite({
736
- pathParams: { workspaceId, inviteKey },
1348
+ resendWorkspaceMemberInvite({
1349
+ workspace,
1350
+ invite
1351
+ }) {
1352
+ return operationsByTag.invites.resendWorkspaceMemberInvite({
1353
+ pathParams: { workspaceId: workspace, inviteId: invite },
737
1354
  ...this.extraProps
738
1355
  });
739
1356
  }
740
1357
  }
741
- class DatabaseApi {
1358
+ class BranchApi {
742
1359
  constructor(extraProps) {
743
1360
  this.extraProps = extraProps;
744
1361
  }
745
- getDatabaseList(workspace) {
746
- return operationsByTag.database.getDatabaseList({
747
- pathParams: { workspace },
1362
+ getBranchList({
1363
+ workspace,
1364
+ region,
1365
+ database
1366
+ }) {
1367
+ return operationsByTag.branch.getBranchList({
1368
+ pathParams: { workspace, region, dbName: database },
748
1369
  ...this.extraProps
749
1370
  });
750
1371
  }
751
- createDatabase(workspace, dbName, options = {}) {
752
- return operationsByTag.database.createDatabase({
753
- pathParams: { workspace, dbName },
754
- body: options,
1372
+ getBranchDetails({
1373
+ workspace,
1374
+ region,
1375
+ database,
1376
+ branch
1377
+ }) {
1378
+ return operationsByTag.branch.getBranchDetails({
1379
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1380
+ ...this.extraProps
1381
+ });
1382
+ }
1383
+ createBranch({
1384
+ workspace,
1385
+ region,
1386
+ database,
1387
+ branch,
1388
+ from,
1389
+ metadata
1390
+ }) {
1391
+ return operationsByTag.branch.createBranch({
1392
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1393
+ body: { from, metadata },
1394
+ ...this.extraProps
1395
+ });
1396
+ }
1397
+ deleteBranch({
1398
+ workspace,
1399
+ region,
1400
+ database,
1401
+ branch
1402
+ }) {
1403
+ return operationsByTag.branch.deleteBranch({
1404
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1405
+ ...this.extraProps
1406
+ });
1407
+ }
1408
+ copyBranch({
1409
+ workspace,
1410
+ region,
1411
+ database,
1412
+ branch,
1413
+ destinationBranch,
1414
+ limit
1415
+ }) {
1416
+ return operationsByTag.branch.copyBranch({
1417
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1418
+ body: { destinationBranch, limit },
1419
+ ...this.extraProps
1420
+ });
1421
+ }
1422
+ updateBranchMetadata({
1423
+ workspace,
1424
+ region,
1425
+ database,
1426
+ branch,
1427
+ metadata
1428
+ }) {
1429
+ return operationsByTag.branch.updateBranchMetadata({
1430
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1431
+ body: metadata,
1432
+ ...this.extraProps
1433
+ });
1434
+ }
1435
+ getBranchMetadata({
1436
+ workspace,
1437
+ region,
1438
+ database,
1439
+ branch
1440
+ }) {
1441
+ return operationsByTag.branch.getBranchMetadata({
1442
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
755
1443
  ...this.extraProps
756
1444
  });
757
1445
  }
758
- deleteDatabase(workspace, dbName) {
759
- return operationsByTag.database.deleteDatabase({
760
- pathParams: { workspace, dbName },
1446
+ getBranchStats({
1447
+ workspace,
1448
+ region,
1449
+ database,
1450
+ branch
1451
+ }) {
1452
+ return operationsByTag.branch.getBranchStats({
1453
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
761
1454
  ...this.extraProps
762
1455
  });
763
1456
  }
764
- getGitBranchesMapping(workspace, dbName) {
765
- return operationsByTag.database.getGitBranchesMapping({
766
- pathParams: { workspace, dbName },
1457
+ getGitBranchesMapping({
1458
+ workspace,
1459
+ region,
1460
+ database
1461
+ }) {
1462
+ return operationsByTag.branch.getGitBranchesMapping({
1463
+ pathParams: { workspace, region, dbName: database },
767
1464
  ...this.extraProps
768
1465
  });
769
1466
  }
770
- addGitBranchesEntry(workspace, dbName, body) {
771
- return operationsByTag.database.addGitBranchesEntry({
772
- pathParams: { workspace, dbName },
773
- body,
1467
+ addGitBranchesEntry({
1468
+ workspace,
1469
+ region,
1470
+ database,
1471
+ gitBranch,
1472
+ xataBranch
1473
+ }) {
1474
+ return operationsByTag.branch.addGitBranchesEntry({
1475
+ pathParams: { workspace, region, dbName: database },
1476
+ body: { gitBranch, xataBranch },
774
1477
  ...this.extraProps
775
1478
  });
776
1479
  }
777
- removeGitBranchesEntry(workspace, dbName, gitBranch) {
778
- return operationsByTag.database.removeGitBranchesEntry({
779
- pathParams: { workspace, dbName },
1480
+ removeGitBranchesEntry({
1481
+ workspace,
1482
+ region,
1483
+ database,
1484
+ gitBranch
1485
+ }) {
1486
+ return operationsByTag.branch.removeGitBranchesEntry({
1487
+ pathParams: { workspace, region, dbName: database },
780
1488
  queryParams: { gitBranch },
781
1489
  ...this.extraProps
782
1490
  });
783
1491
  }
784
- resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
785
- return operationsByTag.database.resolveBranch({
786
- pathParams: { workspace, dbName },
1492
+ resolveBranch({
1493
+ workspace,
1494
+ region,
1495
+ database,
1496
+ gitBranch,
1497
+ fallbackBranch
1498
+ }) {
1499
+ return operationsByTag.branch.resolveBranch({
1500
+ pathParams: { workspace, region, dbName: database },
787
1501
  queryParams: { gitBranch, fallbackBranch },
788
1502
  ...this.extraProps
789
1503
  });
790
1504
  }
791
1505
  }
792
- class BranchApi {
1506
+ class TableApi {
793
1507
  constructor(extraProps) {
794
1508
  this.extraProps = extraProps;
795
1509
  }
796
- getBranchList(workspace, dbName) {
797
- return operationsByTag.branch.getBranchList({
798
- pathParams: { workspace, dbName },
1510
+ createTable({
1511
+ workspace,
1512
+ region,
1513
+ database,
1514
+ branch,
1515
+ table
1516
+ }) {
1517
+ return operationsByTag.table.createTable({
1518
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
799
1519
  ...this.extraProps
800
1520
  });
801
1521
  }
802
- getBranchDetails(workspace, database, branch) {
803
- return operationsByTag.branch.getBranchDetails({
804
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1522
+ deleteTable({
1523
+ workspace,
1524
+ region,
1525
+ database,
1526
+ branch,
1527
+ table
1528
+ }) {
1529
+ return operationsByTag.table.deleteTable({
1530
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
805
1531
  ...this.extraProps
806
1532
  });
807
1533
  }
808
- createBranch(workspace, database, branch, from, options = {}) {
809
- return operationsByTag.branch.createBranch({
810
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
811
- queryParams: isString(from) ? { from } : void 0,
812
- body: options,
1534
+ updateTable({
1535
+ workspace,
1536
+ region,
1537
+ database,
1538
+ branch,
1539
+ table,
1540
+ update
1541
+ }) {
1542
+ return operationsByTag.table.updateTable({
1543
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1544
+ body: update,
813
1545
  ...this.extraProps
814
1546
  });
815
1547
  }
816
- deleteBranch(workspace, database, branch) {
817
- return operationsByTag.branch.deleteBranch({
818
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1548
+ getTableSchema({
1549
+ workspace,
1550
+ region,
1551
+ database,
1552
+ branch,
1553
+ table
1554
+ }) {
1555
+ return operationsByTag.table.getTableSchema({
1556
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
819
1557
  ...this.extraProps
820
1558
  });
821
1559
  }
822
- updateBranchMetadata(workspace, database, branch, metadata = {}) {
823
- return operationsByTag.branch.updateBranchMetadata({
824
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
825
- body: metadata,
1560
+ setTableSchema({
1561
+ workspace,
1562
+ region,
1563
+ database,
1564
+ branch,
1565
+ table,
1566
+ schema
1567
+ }) {
1568
+ return operationsByTag.table.setTableSchema({
1569
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1570
+ body: schema,
826
1571
  ...this.extraProps
827
1572
  });
828
1573
  }
829
- getBranchMetadata(workspace, database, branch) {
830
- return operationsByTag.branch.getBranchMetadata({
831
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1574
+ getTableColumns({
1575
+ workspace,
1576
+ region,
1577
+ database,
1578
+ branch,
1579
+ table
1580
+ }) {
1581
+ return operationsByTag.table.getTableColumns({
1582
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
832
1583
  ...this.extraProps
833
1584
  });
834
1585
  }
835
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
836
- return operationsByTag.branch.getBranchMigrationHistory({
837
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
838
- body: options,
1586
+ addTableColumn({
1587
+ workspace,
1588
+ region,
1589
+ database,
1590
+ branch,
1591
+ table,
1592
+ column
1593
+ }) {
1594
+ return operationsByTag.table.addTableColumn({
1595
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1596
+ body: column,
839
1597
  ...this.extraProps
840
1598
  });
841
1599
  }
842
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
843
- return operationsByTag.branch.executeBranchMigrationPlan({
844
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
845
- body: migrationPlan,
1600
+ getColumn({
1601
+ workspace,
1602
+ region,
1603
+ database,
1604
+ branch,
1605
+ table,
1606
+ column
1607
+ }) {
1608
+ return operationsByTag.table.getColumn({
1609
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
846
1610
  ...this.extraProps
847
1611
  });
848
1612
  }
849
- getBranchMigrationPlan(workspace, database, branch, schema) {
850
- return operationsByTag.branch.getBranchMigrationPlan({
851
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
852
- body: schema,
1613
+ updateColumn({
1614
+ workspace,
1615
+ region,
1616
+ database,
1617
+ branch,
1618
+ table,
1619
+ column,
1620
+ update
1621
+ }) {
1622
+ return operationsByTag.table.updateColumn({
1623
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
1624
+ body: update,
853
1625
  ...this.extraProps
854
1626
  });
855
1627
  }
856
- getBranchStats(workspace, database, branch) {
857
- return operationsByTag.branch.getBranchStats({
858
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1628
+ deleteColumn({
1629
+ workspace,
1630
+ region,
1631
+ database,
1632
+ branch,
1633
+ table,
1634
+ column
1635
+ }) {
1636
+ return operationsByTag.table.deleteColumn({
1637
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
859
1638
  ...this.extraProps
860
1639
  });
861
1640
  }
862
1641
  }
863
- class TableApi {
1642
+ class RecordsApi {
864
1643
  constructor(extraProps) {
865
1644
  this.extraProps = extraProps;
866
1645
  }
867
- createTable(workspace, database, branch, tableName) {
868
- return operationsByTag.table.createTable({
869
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1646
+ insertRecord({
1647
+ workspace,
1648
+ region,
1649
+ database,
1650
+ branch,
1651
+ table,
1652
+ record,
1653
+ columns
1654
+ }) {
1655
+ return operationsByTag.records.insertRecord({
1656
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1657
+ queryParams: { columns },
1658
+ body: record,
1659
+ ...this.extraProps
1660
+ });
1661
+ }
1662
+ getRecord({
1663
+ workspace,
1664
+ region,
1665
+ database,
1666
+ branch,
1667
+ table,
1668
+ id,
1669
+ columns
1670
+ }) {
1671
+ return operationsByTag.records.getRecord({
1672
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1673
+ queryParams: { columns },
1674
+ ...this.extraProps
1675
+ });
1676
+ }
1677
+ insertRecordWithID({
1678
+ workspace,
1679
+ region,
1680
+ database,
1681
+ branch,
1682
+ table,
1683
+ id,
1684
+ record,
1685
+ columns,
1686
+ createOnly,
1687
+ ifVersion
1688
+ }) {
1689
+ return operationsByTag.records.insertRecordWithID({
1690
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1691
+ queryParams: { columns, createOnly, ifVersion },
1692
+ body: record,
1693
+ ...this.extraProps
1694
+ });
1695
+ }
1696
+ updateRecordWithID({
1697
+ workspace,
1698
+ region,
1699
+ database,
1700
+ branch,
1701
+ table,
1702
+ id,
1703
+ record,
1704
+ columns,
1705
+ ifVersion
1706
+ }) {
1707
+ return operationsByTag.records.updateRecordWithID({
1708
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1709
+ queryParams: { columns, ifVersion },
1710
+ body: record,
1711
+ ...this.extraProps
1712
+ });
1713
+ }
1714
+ upsertRecordWithID({
1715
+ workspace,
1716
+ region,
1717
+ database,
1718
+ branch,
1719
+ table,
1720
+ id,
1721
+ record,
1722
+ columns,
1723
+ ifVersion
1724
+ }) {
1725
+ return operationsByTag.records.upsertRecordWithID({
1726
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1727
+ queryParams: { columns, ifVersion },
1728
+ body: record,
1729
+ ...this.extraProps
1730
+ });
1731
+ }
1732
+ deleteRecord({
1733
+ workspace,
1734
+ region,
1735
+ database,
1736
+ branch,
1737
+ table,
1738
+ id,
1739
+ columns
1740
+ }) {
1741
+ return operationsByTag.records.deleteRecord({
1742
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1743
+ queryParams: { columns },
1744
+ ...this.extraProps
1745
+ });
1746
+ }
1747
+ bulkInsertTableRecords({
1748
+ workspace,
1749
+ region,
1750
+ database,
1751
+ branch,
1752
+ table,
1753
+ records,
1754
+ columns
1755
+ }) {
1756
+ return operationsByTag.records.bulkInsertTableRecords({
1757
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1758
+ queryParams: { columns },
1759
+ body: { records },
1760
+ ...this.extraProps
1761
+ });
1762
+ }
1763
+ branchTransaction({
1764
+ workspace,
1765
+ region,
1766
+ database,
1767
+ branch,
1768
+ operations
1769
+ }) {
1770
+ return operationsByTag.records.branchTransaction({
1771
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1772
+ body: { operations },
1773
+ ...this.extraProps
1774
+ });
1775
+ }
1776
+ }
1777
+ class SearchAndFilterApi {
1778
+ constructor(extraProps) {
1779
+ this.extraProps = extraProps;
1780
+ }
1781
+ queryTable({
1782
+ workspace,
1783
+ region,
1784
+ database,
1785
+ branch,
1786
+ table,
1787
+ filter,
1788
+ sort,
1789
+ page,
1790
+ columns,
1791
+ consistency
1792
+ }) {
1793
+ return operationsByTag.searchAndFilter.queryTable({
1794
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1795
+ body: { filter, sort, page, columns, consistency },
1796
+ ...this.extraProps
1797
+ });
1798
+ }
1799
+ searchTable({
1800
+ workspace,
1801
+ region,
1802
+ database,
1803
+ branch,
1804
+ table,
1805
+ query,
1806
+ fuzziness,
1807
+ target,
1808
+ prefix,
1809
+ filter,
1810
+ highlight,
1811
+ boosters
1812
+ }) {
1813
+ return operationsByTag.searchAndFilter.searchTable({
1814
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1815
+ body: { query, fuzziness, target, prefix, filter, highlight, boosters },
1816
+ ...this.extraProps
1817
+ });
1818
+ }
1819
+ searchBranch({
1820
+ workspace,
1821
+ region,
1822
+ database,
1823
+ branch,
1824
+ tables,
1825
+ query,
1826
+ fuzziness,
1827
+ prefix,
1828
+ highlight
1829
+ }) {
1830
+ return operationsByTag.searchAndFilter.searchBranch({
1831
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1832
+ body: { tables, query, fuzziness, prefix, highlight },
1833
+ ...this.extraProps
1834
+ });
1835
+ }
1836
+ vectorSearchTable({
1837
+ workspace,
1838
+ region,
1839
+ database,
1840
+ branch,
1841
+ table,
1842
+ queryVector,
1843
+ column,
1844
+ similarityFunction,
1845
+ size,
1846
+ filter
1847
+ }) {
1848
+ return operationsByTag.searchAndFilter.vectorSearchTable({
1849
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1850
+ body: { queryVector, column, similarityFunction, size, filter },
1851
+ ...this.extraProps
1852
+ });
1853
+ }
1854
+ askTable({
1855
+ workspace,
1856
+ region,
1857
+ database,
1858
+ branch,
1859
+ table,
1860
+ options
1861
+ }) {
1862
+ return operationsByTag.searchAndFilter.askTable({
1863
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1864
+ body: { ...options },
1865
+ ...this.extraProps
1866
+ });
1867
+ }
1868
+ summarizeTable({
1869
+ workspace,
1870
+ region,
1871
+ database,
1872
+ branch,
1873
+ table,
1874
+ filter,
1875
+ columns,
1876
+ summaries,
1877
+ sort,
1878
+ summariesFilter,
1879
+ page,
1880
+ consistency
1881
+ }) {
1882
+ return operationsByTag.searchAndFilter.summarizeTable({
1883
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1884
+ body: { filter, columns, summaries, sort, summariesFilter, page, consistency },
1885
+ ...this.extraProps
1886
+ });
1887
+ }
1888
+ aggregateTable({
1889
+ workspace,
1890
+ region,
1891
+ database,
1892
+ branch,
1893
+ table,
1894
+ filter,
1895
+ aggs
1896
+ }) {
1897
+ return operationsByTag.searchAndFilter.aggregateTable({
1898
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1899
+ body: { filter, aggs },
1900
+ ...this.extraProps
1901
+ });
1902
+ }
1903
+ }
1904
+ class MigrationRequestsApi {
1905
+ constructor(extraProps) {
1906
+ this.extraProps = extraProps;
1907
+ }
1908
+ queryMigrationRequests({
1909
+ workspace,
1910
+ region,
1911
+ database,
1912
+ filter,
1913
+ sort,
1914
+ page,
1915
+ columns
1916
+ }) {
1917
+ return operationsByTag.migrationRequests.queryMigrationRequests({
1918
+ pathParams: { workspace, region, dbName: database },
1919
+ body: { filter, sort, page, columns },
1920
+ ...this.extraProps
1921
+ });
1922
+ }
1923
+ createMigrationRequest({
1924
+ workspace,
1925
+ region,
1926
+ database,
1927
+ migration
1928
+ }) {
1929
+ return operationsByTag.migrationRequests.createMigrationRequest({
1930
+ pathParams: { workspace, region, dbName: database },
1931
+ body: migration,
870
1932
  ...this.extraProps
871
1933
  });
872
1934
  }
873
- deleteTable(workspace, database, branch, tableName) {
874
- return operationsByTag.table.deleteTable({
875
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1935
+ getMigrationRequest({
1936
+ workspace,
1937
+ region,
1938
+ database,
1939
+ migrationRequest
1940
+ }) {
1941
+ return operationsByTag.migrationRequests.getMigrationRequest({
1942
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
1943
+ ...this.extraProps
1944
+ });
1945
+ }
1946
+ updateMigrationRequest({
1947
+ workspace,
1948
+ region,
1949
+ database,
1950
+ migrationRequest,
1951
+ update
1952
+ }) {
1953
+ return operationsByTag.migrationRequests.updateMigrationRequest({
1954
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
1955
+ body: update,
1956
+ ...this.extraProps
1957
+ });
1958
+ }
1959
+ listMigrationRequestsCommits({
1960
+ workspace,
1961
+ region,
1962
+ database,
1963
+ migrationRequest,
1964
+ page
1965
+ }) {
1966
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1967
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
1968
+ body: { page },
1969
+ ...this.extraProps
1970
+ });
1971
+ }
1972
+ compareMigrationRequest({
1973
+ workspace,
1974
+ region,
1975
+ database,
1976
+ migrationRequest
1977
+ }) {
1978
+ return operationsByTag.migrationRequests.compareMigrationRequest({
1979
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
1980
+ ...this.extraProps
1981
+ });
1982
+ }
1983
+ getMigrationRequestIsMerged({
1984
+ workspace,
1985
+ region,
1986
+ database,
1987
+ migrationRequest
1988
+ }) {
1989
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1990
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
1991
+ ...this.extraProps
1992
+ });
1993
+ }
1994
+ mergeMigrationRequest({
1995
+ workspace,
1996
+ region,
1997
+ database,
1998
+ migrationRequest
1999
+ }) {
2000
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
2001
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2002
+ ...this.extraProps
2003
+ });
2004
+ }
2005
+ }
2006
+ class MigrationsApi {
2007
+ constructor(extraProps) {
2008
+ this.extraProps = extraProps;
2009
+ }
2010
+ getBranchMigrationHistory({
2011
+ workspace,
2012
+ region,
2013
+ database,
2014
+ branch,
2015
+ limit,
2016
+ startFrom
2017
+ }) {
2018
+ return operationsByTag.migrations.getBranchMigrationHistory({
2019
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2020
+ body: { limit, startFrom },
876
2021
  ...this.extraProps
877
2022
  });
878
2023
  }
879
- updateTable(workspace, database, branch, tableName, options) {
880
- return operationsByTag.table.updateTable({
881
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
882
- body: options,
2024
+ getBranchMigrationPlan({
2025
+ workspace,
2026
+ region,
2027
+ database,
2028
+ branch,
2029
+ schema
2030
+ }) {
2031
+ return operationsByTag.migrations.getBranchMigrationPlan({
2032
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2033
+ body: schema,
883
2034
  ...this.extraProps
884
2035
  });
885
2036
  }
886
- getTableSchema(workspace, database, branch, tableName) {
887
- return operationsByTag.table.getTableSchema({
888
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
2037
+ executeBranchMigrationPlan({
2038
+ workspace,
2039
+ region,
2040
+ database,
2041
+ branch,
2042
+ plan
2043
+ }) {
2044
+ return operationsByTag.migrations.executeBranchMigrationPlan({
2045
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2046
+ body: plan,
889
2047
  ...this.extraProps
890
2048
  });
891
2049
  }
892
- setTableSchema(workspace, database, branch, tableName, options) {
893
- return operationsByTag.table.setTableSchema({
894
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
895
- body: options,
2050
+ getBranchSchemaHistory({
2051
+ workspace,
2052
+ region,
2053
+ database,
2054
+ branch,
2055
+ page
2056
+ }) {
2057
+ return operationsByTag.migrations.getBranchSchemaHistory({
2058
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2059
+ body: { page },
896
2060
  ...this.extraProps
897
2061
  });
898
2062
  }
899
- getTableColumns(workspace, database, branch, tableName) {
900
- return operationsByTag.table.getTableColumns({
901
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
2063
+ compareBranchWithUserSchema({
2064
+ workspace,
2065
+ region,
2066
+ database,
2067
+ branch,
2068
+ schema,
2069
+ schemaOperations,
2070
+ branchOperations
2071
+ }) {
2072
+ return operationsByTag.migrations.compareBranchWithUserSchema({
2073
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2074
+ body: { schema, schemaOperations, branchOperations },
902
2075
  ...this.extraProps
903
2076
  });
904
2077
  }
905
- addTableColumn(workspace, database, branch, tableName, column) {
906
- return operationsByTag.table.addTableColumn({
907
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
908
- body: column,
2078
+ compareBranchSchemas({
2079
+ workspace,
2080
+ region,
2081
+ database,
2082
+ branch,
2083
+ compare,
2084
+ sourceBranchOperations,
2085
+ targetBranchOperations
2086
+ }) {
2087
+ return operationsByTag.migrations.compareBranchSchemas({
2088
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
2089
+ body: { sourceBranchOperations, targetBranchOperations },
909
2090
  ...this.extraProps
910
2091
  });
911
2092
  }
912
- getColumn(workspace, database, branch, tableName, columnName) {
913
- return operationsByTag.table.getColumn({
914
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
2093
+ updateBranchSchema({
2094
+ workspace,
2095
+ region,
2096
+ database,
2097
+ branch,
2098
+ migration
2099
+ }) {
2100
+ return operationsByTag.migrations.updateBranchSchema({
2101
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2102
+ body: migration,
915
2103
  ...this.extraProps
916
2104
  });
917
2105
  }
918
- deleteColumn(workspace, database, branch, tableName, columnName) {
919
- return operationsByTag.table.deleteColumn({
920
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
2106
+ previewBranchSchemaEdit({
2107
+ workspace,
2108
+ region,
2109
+ database,
2110
+ branch,
2111
+ data
2112
+ }) {
2113
+ return operationsByTag.migrations.previewBranchSchemaEdit({
2114
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2115
+ body: data,
921
2116
  ...this.extraProps
922
2117
  });
923
2118
  }
924
- updateColumn(workspace, database, branch, tableName, columnName, options) {
925
- return operationsByTag.table.updateColumn({
926
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
927
- body: options,
2119
+ applyBranchSchemaEdit({
2120
+ workspace,
2121
+ region,
2122
+ database,
2123
+ branch,
2124
+ edits
2125
+ }) {
2126
+ return operationsByTag.migrations.applyBranchSchemaEdit({
2127
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2128
+ body: { edits },
928
2129
  ...this.extraProps
929
2130
  });
930
2131
  }
931
2132
  }
932
- class RecordsApi {
2133
+ class DatabaseApi {
933
2134
  constructor(extraProps) {
934
2135
  this.extraProps = extraProps;
935
2136
  }
936
- insertRecord(workspace, database, branch, tableName, record, options = {}) {
937
- return operationsByTag.records.insertRecord({
938
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
939
- queryParams: options,
940
- body: record,
941
- ...this.extraProps
942
- });
943
- }
944
- insertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
945
- return operationsByTag.records.insertRecordWithID({
946
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
947
- queryParams: options,
948
- body: record,
2137
+ getDatabaseList({ workspace }) {
2138
+ return operationsByTag.databases.getDatabaseList({
2139
+ pathParams: { workspaceId: workspace },
949
2140
  ...this.extraProps
950
2141
  });
951
2142
  }
952
- updateRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
953
- return operationsByTag.records.updateRecordWithID({
954
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
955
- queryParams: options,
956
- body: record,
2143
+ createDatabase({
2144
+ workspace,
2145
+ database,
2146
+ data
2147
+ }) {
2148
+ return operationsByTag.databases.createDatabase({
2149
+ pathParams: { workspaceId: workspace, dbName: database },
2150
+ body: data,
957
2151
  ...this.extraProps
958
2152
  });
959
2153
  }
960
- upsertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
961
- return operationsByTag.records.upsertRecordWithID({
962
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
963
- queryParams: options,
964
- body: record,
2154
+ deleteDatabase({
2155
+ workspace,
2156
+ database
2157
+ }) {
2158
+ return operationsByTag.databases.deleteDatabase({
2159
+ pathParams: { workspaceId: workspace, dbName: database },
965
2160
  ...this.extraProps
966
2161
  });
967
2162
  }
968
- deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
969
- return operationsByTag.records.deleteRecord({
970
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
971
- queryParams: options,
2163
+ getDatabaseMetadata({
2164
+ workspace,
2165
+ database
2166
+ }) {
2167
+ return operationsByTag.databases.getDatabaseMetadata({
2168
+ pathParams: { workspaceId: workspace, dbName: database },
972
2169
  ...this.extraProps
973
2170
  });
974
2171
  }
975
- getRecord(workspace, database, branch, tableName, recordId, options = {}) {
976
- return operationsByTag.records.getRecord({
977
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
978
- queryParams: options,
2172
+ updateDatabaseMetadata({
2173
+ workspace,
2174
+ database,
2175
+ metadata
2176
+ }) {
2177
+ return operationsByTag.databases.updateDatabaseMetadata({
2178
+ pathParams: { workspaceId: workspace, dbName: database },
2179
+ body: metadata,
979
2180
  ...this.extraProps
980
2181
  });
981
2182
  }
982
- bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
983
- return operationsByTag.records.bulkInsertTableRecords({
984
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
985
- queryParams: options,
986
- body: { records },
2183
+ getDatabaseGithubSettings({
2184
+ workspace,
2185
+ database
2186
+ }) {
2187
+ return operationsByTag.databases.getDatabaseGithubSettings({
2188
+ pathParams: { workspaceId: workspace, dbName: database },
987
2189
  ...this.extraProps
988
2190
  });
989
2191
  }
990
- queryTable(workspace, database, branch, tableName, query) {
991
- return operationsByTag.records.queryTable({
992
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
993
- body: query,
2192
+ updateDatabaseGithubSettings({
2193
+ workspace,
2194
+ database,
2195
+ settings
2196
+ }) {
2197
+ return operationsByTag.databases.updateDatabaseGithubSettings({
2198
+ pathParams: { workspaceId: workspace, dbName: database },
2199
+ body: settings,
994
2200
  ...this.extraProps
995
2201
  });
996
2202
  }
997
- searchTable(workspace, database, branch, tableName, query) {
998
- return operationsByTag.records.searchTable({
999
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1000
- body: query,
2203
+ deleteDatabaseGithubSettings({
2204
+ workspace,
2205
+ database
2206
+ }) {
2207
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
2208
+ pathParams: { workspaceId: workspace, dbName: database },
1001
2209
  ...this.extraProps
1002
2210
  });
1003
2211
  }
1004
- searchBranch(workspace, database, branch, query) {
1005
- return operationsByTag.records.searchBranch({
1006
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1007
- body: query,
2212
+ listRegions({ workspace }) {
2213
+ return operationsByTag.databases.listRegions({
2214
+ pathParams: { workspaceId: workspace },
1008
2215
  ...this.extraProps
1009
2216
  });
1010
2217
  }
1011
2218
  }
1012
2219
 
1013
2220
  class XataApiPlugin {
1014
- async build(options) {
1015
- const { fetchImpl, apiKey } = await options.getFetchProps();
1016
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2221
+ build(options) {
2222
+ return new XataApiClient(options);
1017
2223
  }
1018
2224
  }
1019
2225
 
1020
2226
  class XataPlugin {
1021
2227
  }
1022
2228
 
2229
+ function cleanFilter(filter) {
2230
+ if (!filter)
2231
+ return void 0;
2232
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
2233
+ return values.length > 0 ? filter : void 0;
2234
+ }
2235
+
1023
2236
  var __accessCheck$6 = (obj, member, msg) => {
1024
2237
  if (!member.has(obj))
1025
2238
  throw TypeError("Cannot " + msg);
@@ -1052,11 +2265,11 @@ class Page {
1052
2265
  async previousPage(size, offset) {
1053
2266
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1054
2267
  }
1055
- async firstPage(size, offset) {
1056
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
2268
+ async startPage(size, offset) {
2269
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1057
2270
  }
1058
- async lastPage(size, offset) {
1059
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
2271
+ async endPage(size, offset) {
2272
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1060
2273
  }
1061
2274
  hasNextPage() {
1062
2275
  return this.meta.page.more;
@@ -1068,7 +2281,7 @@ const PAGINATION_DEFAULT_SIZE = 20;
1068
2281
  const PAGINATION_MAX_OFFSET = 800;
1069
2282
  const PAGINATION_DEFAULT_OFFSET = 0;
1070
2283
  function isCursorPaginationOptions(options) {
1071
- return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
2284
+ return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1072
2285
  }
1073
2286
  const _RecordArray = class extends Array {
1074
2287
  constructor(...args) {
@@ -1089,6 +2302,12 @@ const _RecordArray = class extends Array {
1089
2302
  toArray() {
1090
2303
  return new Array(...this);
1091
2304
  }
2305
+ toSerializable() {
2306
+ return JSON.parse(this.toString());
2307
+ }
2308
+ toString() {
2309
+ return JSON.stringify(this.toArray());
2310
+ }
1092
2311
  map(callbackfn, thisArg) {
1093
2312
  return this.toArray().map(callbackfn, thisArg);
1094
2313
  }
@@ -1100,12 +2319,12 @@ const _RecordArray = class extends Array {
1100
2319
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1101
2320
  return new _RecordArray(newPage);
1102
2321
  }
1103
- async firstPage(size, offset) {
1104
- const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
2322
+ async startPage(size, offset) {
2323
+ const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1105
2324
  return new _RecordArray(newPage);
1106
2325
  }
1107
- async lastPage(size, offset) {
1108
- const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
2326
+ async endPage(size, offset) {
2327
+ const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1109
2328
  return new _RecordArray(newPage);
1110
2329
  }
1111
2330
  hasNextPage() {
@@ -1133,9 +2352,14 @@ var __privateSet$5 = (obj, member, value, setter) => {
1133
2352
  setter ? setter.call(obj, value) : member.set(obj, value);
1134
2353
  return value;
1135
2354
  };
1136
- var _table$1, _repository, _data;
2355
+ var __privateMethod$3 = (obj, member, method) => {
2356
+ __accessCheck$5(obj, member, "access private method");
2357
+ return method;
2358
+ };
2359
+ var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
1137
2360
  const _Query = class {
1138
2361
  constructor(repository, table, data, rawParent) {
2362
+ __privateAdd$5(this, _cleanFilterConstraint);
1139
2363
  __privateAdd$5(this, _table$1, void 0);
1140
2364
  __privateAdd$5(this, _repository, void 0);
1141
2365
  __privateAdd$5(this, _data, { filter: {} });
@@ -1154,9 +2378,11 @@ const _Query = class {
1154
2378
  __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1155
2379
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1156
2380
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1157
- __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
2381
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
2382
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
1158
2383
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1159
2384
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
2385
+ __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
1160
2386
  this.any = this.any.bind(this);
1161
2387
  this.all = this.all.bind(this);
1162
2388
  this.not = this.not.bind(this);
@@ -1192,15 +2418,18 @@ const _Query = class {
1192
2418
  }
1193
2419
  filter(a, b) {
1194
2420
  if (arguments.length === 1) {
1195
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
2421
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
2422
+ [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
2423
+ }));
1196
2424
  const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1197
2425
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1198
2426
  } else {
1199
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
2427
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
2428
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1200
2429
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1201
2430
  }
1202
2431
  }
1203
- sort(column, direction) {
2432
+ sort(column, direction = "asc") {
1204
2433
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1205
2434
  const sort = [...originalSort, { column, direction }];
1206
2435
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
@@ -1234,11 +2463,20 @@ const _Query = class {
1234
2463
  }
1235
2464
  }
1236
2465
  async getMany(options = {}) {
1237
- const page = await this.getPaginated(options);
2466
+ const { pagination = {}, ...rest } = options;
2467
+ const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
2468
+ const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
2469
+ let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
2470
+ const results = [...page.records];
2471
+ while (page.hasNextPage() && results.length < size) {
2472
+ page = await page.nextPage();
2473
+ results.push(...page.records);
2474
+ }
1238
2475
  if (page.hasNextPage() && options.pagination?.size === void 0) {
1239
2476
  console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1240
2477
  }
1241
- return page.records;
2478
+ const array = new RecordArray(page, results.slice(0, size));
2479
+ return array;
1242
2480
  }
1243
2481
  async getAll(options = {}) {
1244
2482
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1252,19 +2490,35 @@ const _Query = class {
1252
2490
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1253
2491
  return records[0] ?? null;
1254
2492
  }
2493
+ async getFirstOrThrow(options = {}) {
2494
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
2495
+ if (records[0] === void 0)
2496
+ throw new Error("No results found.");
2497
+ return records[0];
2498
+ }
2499
+ async summarize(params = {}) {
2500
+ const { summaries, summariesFilter, ...options } = params;
2501
+ const query = new _Query(
2502
+ __privateGet$5(this, _repository),
2503
+ __privateGet$5(this, _table$1),
2504
+ options,
2505
+ __privateGet$5(this, _data)
2506
+ );
2507
+ return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2508
+ }
1255
2509
  cache(ttl) {
1256
2510
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1257
2511
  }
1258
2512
  nextPage(size, offset) {
1259
- return this.firstPage(size, offset);
2513
+ return this.startPage(size, offset);
1260
2514
  }
1261
2515
  previousPage(size, offset) {
1262
- return this.firstPage(size, offset);
2516
+ return this.startPage(size, offset);
1263
2517
  }
1264
- firstPage(size, offset) {
2518
+ startPage(size, offset) {
1265
2519
  return this.getPaginated({ pagination: { size, offset } });
1266
2520
  }
1267
- lastPage(size, offset) {
2521
+ endPage(size, offset) {
1268
2522
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
1269
2523
  }
1270
2524
  hasNextPage() {
@@ -1275,9 +2529,20 @@ let Query = _Query;
1275
2529
  _table$1 = new WeakMap();
1276
2530
  _repository = new WeakMap();
1277
2531
  _data = new WeakMap();
2532
+ _cleanFilterConstraint = new WeakSet();
2533
+ cleanFilterConstraint_fn = function(column, value) {
2534
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
2535
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
2536
+ return { $includes: value };
2537
+ }
2538
+ if (columnType === "link" && isObject(value) && isString(value.id)) {
2539
+ return value.id;
2540
+ }
2541
+ return value;
2542
+ };
1278
2543
  function cleanParent(data, parent) {
1279
2544
  if (isCursorPaginationOptions(data.pagination)) {
1280
- return { ...parent, sorting: void 0, filter: void 0 };
2545
+ return { ...parent, sort: void 0, filter: void 0 };
1281
2546
  }
1282
2547
  return parent;
1283
2548
  }
@@ -1336,18 +2601,25 @@ var __privateMethod$2 = (obj, member, method) => {
1336
2601
  __accessCheck$4(obj, member, "access private method");
1337
2602
  return method;
1338
2603
  };
1339
- var _table, _getFetchProps, _db, _cache, _schemaTables$2, _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;
2604
+ 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;
2605
+ const BULK_OPERATION_MAX_SIZE = 1e3;
1340
2606
  class Repository extends Query {
1341
2607
  }
1342
2608
  class RestRepository extends Query {
1343
2609
  constructor(options) {
1344
- super(null, options.table, {});
2610
+ super(
2611
+ null,
2612
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
2613
+ {}
2614
+ );
1345
2615
  __privateAdd$4(this, _insertRecordWithoutId);
1346
2616
  __privateAdd$4(this, _insertRecordWithId);
1347
- __privateAdd$4(this, _bulkInsertTableRecords);
2617
+ __privateAdd$4(this, _insertRecords);
1348
2618
  __privateAdd$4(this, _updateRecordWithID);
2619
+ __privateAdd$4(this, _updateRecords);
1349
2620
  __privateAdd$4(this, _upsertRecordWithID);
1350
2621
  __privateAdd$4(this, _deleteRecord);
2622
+ __privateAdd$4(this, _deleteRecords);
1351
2623
  __privateAdd$4(this, _setCacheQuery);
1352
2624
  __privateAdd$4(this, _getCacheQuery);
1353
2625
  __privateAdd$4(this, _getSchemaTables$1);
@@ -1356,168 +2628,398 @@ class RestRepository extends Query {
1356
2628
  __privateAdd$4(this, _db, void 0);
1357
2629
  __privateAdd$4(this, _cache, void 0);
1358
2630
  __privateAdd$4(this, _schemaTables$2, void 0);
2631
+ __privateAdd$4(this, _trace, void 0);
1359
2632
  __privateSet$4(this, _table, options.table);
1360
- __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1361
2633
  __privateSet$4(this, _db, options.db);
1362
2634
  __privateSet$4(this, _cache, options.pluginOptions.cache);
1363
2635
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2636
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2637
+ const trace = options.pluginOptions.trace ?? defaultTrace;
2638
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2639
+ return trace(name, fn, {
2640
+ ...options2,
2641
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
2642
+ [TraceAttributes.KIND]: "sdk-operation",
2643
+ [TraceAttributes.VERSION]: VERSION
2644
+ });
2645
+ });
1364
2646
  }
1365
- async create(a, b, c) {
1366
- if (Array.isArray(a)) {
1367
- if (a.length === 0)
1368
- return [];
1369
- const columns = isStringArray(b) ? b : void 0;
1370
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1371
- }
1372
- if (isString(a) && isObject(b)) {
1373
- if (a === "")
1374
- throw new Error("The id can't be empty");
1375
- const columns = isStringArray(c) ? c : void 0;
1376
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1377
- }
1378
- if (isObject(a) && isString(a.id)) {
1379
- if (a.id === "")
1380
- throw new Error("The id can't be empty");
1381
- const columns = isStringArray(b) ? b : void 0;
1382
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1383
- }
1384
- if (isObject(a)) {
1385
- const columns = isStringArray(b) ? b : void 0;
1386
- return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1387
- }
1388
- throw new Error("Invalid arguments for create method");
2647
+ async create(a, b, c, d) {
2648
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
2649
+ const ifVersion = parseIfVersion(b, c, d);
2650
+ if (Array.isArray(a)) {
2651
+ if (a.length === 0)
2652
+ return [];
2653
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2654
+ const columns = isStringArray(b) ? b : ["*"];
2655
+ const result = await this.read(ids, columns);
2656
+ return result;
2657
+ }
2658
+ if (isString(a) && isObject(b)) {
2659
+ if (a === "")
2660
+ throw new Error("The id can't be empty");
2661
+ const columns = isStringArray(c) ? c : void 0;
2662
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2663
+ }
2664
+ if (isObject(a) && isString(a.id)) {
2665
+ if (a.id === "")
2666
+ throw new Error("The id can't be empty");
2667
+ const columns = isStringArray(b) ? b : void 0;
2668
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2669
+ }
2670
+ if (isObject(a)) {
2671
+ const columns = isStringArray(b) ? b : void 0;
2672
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2673
+ }
2674
+ throw new Error("Invalid arguments for create method");
2675
+ });
1389
2676
  }
1390
2677
  async read(a, b) {
1391
- const columns = isStringArray(b) ? b : ["*"];
1392
- if (Array.isArray(a)) {
1393
- if (a.length === 0)
1394
- return [];
1395
- const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1396
- const finalObjects = await this.getAll({ filter: { id: { $any: ids } }, columns });
1397
- const dictionary = finalObjects.reduce((acc, object) => {
1398
- acc[object.id] = object;
1399
- return acc;
1400
- }, {});
1401
- return ids.map((id2) => dictionary[id2] ?? null);
1402
- }
1403
- const id = isString(a) ? a : a.id;
1404
- if (isString(id)) {
1405
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1406
- try {
1407
- const response = await getRecord({
1408
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1409
- queryParams: { columns },
1410
- ...fetchProps
2678
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
2679
+ const columns = isStringArray(b) ? b : ["*"];
2680
+ if (Array.isArray(a)) {
2681
+ if (a.length === 0)
2682
+ return [];
2683
+ const ids = a.map((item) => extractId(item));
2684
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
2685
+ const dictionary = finalObjects.reduce((acc, object) => {
2686
+ acc[object.id] = object;
2687
+ return acc;
2688
+ }, {});
2689
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
2690
+ }
2691
+ const id = extractId(a);
2692
+ if (id) {
2693
+ try {
2694
+ const response = await getRecord({
2695
+ pathParams: {
2696
+ workspace: "{workspaceId}",
2697
+ dbBranchName: "{dbBranch}",
2698
+ region: "{region}",
2699
+ tableName: __privateGet$4(this, _table),
2700
+ recordId: id
2701
+ },
2702
+ queryParams: { columns },
2703
+ ...__privateGet$4(this, _getFetchProps).call(this)
2704
+ });
2705
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2706
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2707
+ } catch (e) {
2708
+ if (isObject(e) && e.status === 404) {
2709
+ return null;
2710
+ }
2711
+ throw e;
2712
+ }
2713
+ }
2714
+ return null;
2715
+ });
2716
+ }
2717
+ async readOrThrow(a, b) {
2718
+ return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
2719
+ const result = await this.read(a, b);
2720
+ if (Array.isArray(result)) {
2721
+ const missingIds = compact(
2722
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
2723
+ );
2724
+ if (missingIds.length > 0) {
2725
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
2726
+ }
2727
+ return result;
2728
+ }
2729
+ if (result === null) {
2730
+ const id = extractId(a) ?? "unknown";
2731
+ throw new Error(`Record with id ${id} not found`);
2732
+ }
2733
+ return result;
2734
+ });
2735
+ }
2736
+ async update(a, b, c, d) {
2737
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
2738
+ const ifVersion = parseIfVersion(b, c, d);
2739
+ if (Array.isArray(a)) {
2740
+ if (a.length === 0)
2741
+ return [];
2742
+ const existing = await this.read(a, ["id"]);
2743
+ const updates = a.filter((_item, index) => existing[index] !== null);
2744
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
2745
+ ifVersion,
2746
+ upsert: false
1411
2747
  });
1412
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1413
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1414
- } catch (e) {
1415
- if (isObject(e) && e.status === 404) {
2748
+ const columns = isStringArray(b) ? b : ["*"];
2749
+ const result = await this.read(a, columns);
2750
+ return result;
2751
+ }
2752
+ try {
2753
+ if (isString(a) && isObject(b)) {
2754
+ const columns = isStringArray(c) ? c : void 0;
2755
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2756
+ }
2757
+ if (isObject(a) && isString(a.id)) {
2758
+ const columns = isStringArray(b) ? b : void 0;
2759
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2760
+ }
2761
+ } catch (error) {
2762
+ if (error.status === 422)
1416
2763
  return null;
2764
+ throw error;
2765
+ }
2766
+ throw new Error("Invalid arguments for update method");
2767
+ });
2768
+ }
2769
+ async updateOrThrow(a, b, c, d) {
2770
+ return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
2771
+ const result = await this.update(a, b, c, d);
2772
+ if (Array.isArray(result)) {
2773
+ const missingIds = compact(
2774
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
2775
+ );
2776
+ if (missingIds.length > 0) {
2777
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1417
2778
  }
1418
- throw e;
2779
+ return result;
1419
2780
  }
1420
- }
1421
- return null;
2781
+ if (result === null) {
2782
+ const id = extractId(a) ?? "unknown";
2783
+ throw new Error(`Record with id ${id} not found`);
2784
+ }
2785
+ return result;
2786
+ });
1422
2787
  }
1423
- async update(a, b, c) {
1424
- if (Array.isArray(a)) {
1425
- if (a.length === 0)
1426
- return [];
1427
- if (a.length > 100) {
1428
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2788
+ async createOrUpdate(a, b, c, d) {
2789
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
2790
+ const ifVersion = parseIfVersion(b, c, d);
2791
+ if (Array.isArray(a)) {
2792
+ if (a.length === 0)
2793
+ return [];
2794
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
2795
+ ifVersion,
2796
+ upsert: true
2797
+ });
2798
+ const columns = isStringArray(b) ? b : ["*"];
2799
+ const result = await this.read(a, columns);
2800
+ return result;
1429
2801
  }
1430
- const columns = isStringArray(b) ? b : ["*"];
1431
- return Promise.all(a.map((object) => this.update(object, columns)));
1432
- }
1433
- if (isString(a) && isObject(b)) {
1434
- const columns = isStringArray(c) ? c : void 0;
1435
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1436
- }
1437
- if (isObject(a) && isString(a.id)) {
1438
- const columns = isStringArray(b) ? b : void 0;
1439
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1440
- }
1441
- throw new Error("Invalid arguments for update method");
1442
- }
1443
- async createOrUpdate(a, b, c) {
1444
- if (Array.isArray(a)) {
1445
- if (a.length === 0)
1446
- return [];
1447
- if (a.length > 100) {
1448
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2802
+ if (isString(a) && isObject(b)) {
2803
+ const columns = isStringArray(c) ? c : void 0;
2804
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
1449
2805
  }
1450
- const columns = isStringArray(b) ? b : ["*"];
1451
- return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1452
- }
1453
- if (isString(a) && isObject(b)) {
1454
- const columns = isStringArray(c) ? c : void 0;
1455
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1456
- }
1457
- if (isObject(a) && isString(a.id)) {
1458
- const columns = isStringArray(c) ? c : void 0;
1459
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1460
- }
1461
- throw new Error("Invalid arguments for createOrUpdate method");
1462
- }
1463
- async delete(a) {
1464
- if (Array.isArray(a)) {
1465
- if (a.length === 0)
1466
- return;
1467
- if (a.length > 100) {
1468
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
2806
+ if (isObject(a) && isString(a.id)) {
2807
+ const columns = isStringArray(c) ? c : void 0;
2808
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
1469
2809
  }
1470
- await Promise.all(a.map((id) => this.delete(id)));
1471
- return;
1472
- }
1473
- if (isString(a)) {
1474
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1475
- return;
1476
- }
1477
- if (isObject(a) && isString(a.id)) {
1478
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1479
- return;
1480
- }
1481
- throw new Error("Invalid arguments for delete method");
2810
+ throw new Error("Invalid arguments for createOrUpdate method");
2811
+ });
2812
+ }
2813
+ async createOrReplace(a, b, c, d) {
2814
+ return __privateGet$4(this, _trace).call(this, "createOrReplace", async () => {
2815
+ const ifVersion = parseIfVersion(b, c, d);
2816
+ if (Array.isArray(a)) {
2817
+ if (a.length === 0)
2818
+ return [];
2819
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2820
+ const columns = isStringArray(b) ? b : ["*"];
2821
+ const result = await this.read(ids, columns);
2822
+ return result;
2823
+ }
2824
+ if (isString(a) && isObject(b)) {
2825
+ const columns = isStringArray(c) ? c : void 0;
2826
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2827
+ }
2828
+ if (isObject(a) && isString(a.id)) {
2829
+ const columns = isStringArray(c) ? c : void 0;
2830
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
2831
+ }
2832
+ throw new Error("Invalid arguments for createOrReplace method");
2833
+ });
2834
+ }
2835
+ async delete(a, b) {
2836
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
2837
+ if (Array.isArray(a)) {
2838
+ if (a.length === 0)
2839
+ return [];
2840
+ const ids = a.map((o) => {
2841
+ if (isString(o))
2842
+ return o;
2843
+ if (isString(o.id))
2844
+ return o.id;
2845
+ throw new Error("Invalid arguments for delete method");
2846
+ });
2847
+ const columns = isStringArray(b) ? b : ["*"];
2848
+ const result = await this.read(a, columns);
2849
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2850
+ return result;
2851
+ }
2852
+ if (isString(a)) {
2853
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
2854
+ }
2855
+ if (isObject(a) && isString(a.id)) {
2856
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
2857
+ }
2858
+ throw new Error("Invalid arguments for delete method");
2859
+ });
2860
+ }
2861
+ async deleteOrThrow(a, b) {
2862
+ return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
2863
+ const result = await this.delete(a, b);
2864
+ if (Array.isArray(result)) {
2865
+ const missingIds = compact(
2866
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
2867
+ );
2868
+ if (missingIds.length > 0) {
2869
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
2870
+ }
2871
+ return result;
2872
+ } else if (result === null) {
2873
+ const id = extractId(a) ?? "unknown";
2874
+ throw new Error(`Record with id ${id} not found`);
2875
+ }
2876
+ return result;
2877
+ });
1482
2878
  }
1483
2879
  async search(query, options = {}) {
1484
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1485
- const { records } = await searchTable({
1486
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1487
- body: {
1488
- query,
1489
- fuzziness: options.fuzziness,
1490
- prefix: options.prefix,
1491
- highlight: options.highlight,
1492
- filter: options.filter,
1493
- boosters: options.boosters
1494
- },
1495
- ...fetchProps
2880
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
2881
+ const { records } = await searchTable({
2882
+ pathParams: {
2883
+ workspace: "{workspaceId}",
2884
+ dbBranchName: "{dbBranch}",
2885
+ region: "{region}",
2886
+ tableName: __privateGet$4(this, _table)
2887
+ },
2888
+ body: {
2889
+ query,
2890
+ fuzziness: options.fuzziness,
2891
+ prefix: options.prefix,
2892
+ highlight: options.highlight,
2893
+ filter: options.filter,
2894
+ boosters: options.boosters,
2895
+ page: options.page,
2896
+ target: options.target
2897
+ },
2898
+ ...__privateGet$4(this, _getFetchProps).call(this)
2899
+ });
2900
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2901
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
2902
+ });
2903
+ }
2904
+ async vectorSearch(column, query, options) {
2905
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
2906
+ const { records } = await vectorSearchTable({
2907
+ pathParams: {
2908
+ workspace: "{workspaceId}",
2909
+ dbBranchName: "{dbBranch}",
2910
+ region: "{region}",
2911
+ tableName: __privateGet$4(this, _table)
2912
+ },
2913
+ body: {
2914
+ column,
2915
+ queryVector: query,
2916
+ similarityFunction: options?.similarityFunction,
2917
+ size: options?.size,
2918
+ filter: options?.filter
2919
+ },
2920
+ ...__privateGet$4(this, _getFetchProps).call(this)
2921
+ });
2922
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2923
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
2924
+ });
2925
+ }
2926
+ async aggregate(aggs, filter) {
2927
+ return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2928
+ const result = await aggregateTable({
2929
+ pathParams: {
2930
+ workspace: "{workspaceId}",
2931
+ dbBranchName: "{dbBranch}",
2932
+ region: "{region}",
2933
+ tableName: __privateGet$4(this, _table)
2934
+ },
2935
+ body: { aggs, filter },
2936
+ ...__privateGet$4(this, _getFetchProps).call(this)
2937
+ });
2938
+ return result;
1496
2939
  });
1497
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1498
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1499
2940
  }
1500
2941
  async query(query) {
1501
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1502
- if (cacheQuery)
1503
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1504
- const data = query.getQueryOptions();
1505
- const body = {
1506
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1507
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1508
- page: data.pagination,
1509
- columns: data.columns
1510
- };
1511
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1512
- const { meta, records: objects } = await queryTable({
1513
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1514
- body,
1515
- ...fetchProps
2942
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
2943
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
2944
+ if (cacheQuery)
2945
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
2946
+ const data = query.getQueryOptions();
2947
+ const { meta, records: objects } = await queryTable({
2948
+ pathParams: {
2949
+ workspace: "{workspaceId}",
2950
+ dbBranchName: "{dbBranch}",
2951
+ region: "{region}",
2952
+ tableName: __privateGet$4(this, _table)
2953
+ },
2954
+ body: {
2955
+ filter: cleanFilter(data.filter),
2956
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2957
+ page: data.pagination,
2958
+ columns: data.columns ?? ["*"],
2959
+ consistency: data.consistency
2960
+ },
2961
+ fetchOptions: data.fetchOptions,
2962
+ ...__privateGet$4(this, _getFetchProps).call(this)
2963
+ });
2964
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2965
+ const records = objects.map(
2966
+ (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
2967
+ );
2968
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
2969
+ return new Page(query, meta, records);
1516
2970
  });
1517
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1518
- const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1519
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1520
- return new Page(query, meta, records);
2971
+ }
2972
+ async summarizeTable(query, summaries, summariesFilter) {
2973
+ return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2974
+ const data = query.getQueryOptions();
2975
+ const result = await summarizeTable({
2976
+ pathParams: {
2977
+ workspace: "{workspaceId}",
2978
+ dbBranchName: "{dbBranch}",
2979
+ region: "{region}",
2980
+ tableName: __privateGet$4(this, _table)
2981
+ },
2982
+ body: {
2983
+ filter: cleanFilter(data.filter),
2984
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2985
+ columns: data.columns,
2986
+ consistency: data.consistency,
2987
+ page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2988
+ summaries,
2989
+ summariesFilter
2990
+ },
2991
+ ...__privateGet$4(this, _getFetchProps).call(this)
2992
+ });
2993
+ return result;
2994
+ });
2995
+ }
2996
+ ask(question, options) {
2997
+ const params = {
2998
+ pathParams: {
2999
+ workspace: "{workspaceId}",
3000
+ dbBranchName: "{dbBranch}",
3001
+ region: "{region}",
3002
+ tableName: __privateGet$4(this, _table)
3003
+ },
3004
+ body: {
3005
+ question,
3006
+ ...options
3007
+ },
3008
+ ...__privateGet$4(this, _getFetchProps).call(this)
3009
+ };
3010
+ if (options?.onMessage) {
3011
+ fetchSSERequest({
3012
+ endpoint: "dataPlane",
3013
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
3014
+ method: "POST",
3015
+ onMessage: (message) => {
3016
+ options.onMessage?.({ answer: message.text });
3017
+ },
3018
+ ...params
3019
+ });
3020
+ } else {
3021
+ return askTable(params);
3022
+ }
1521
3023
  }
1522
3024
  }
1523
3025
  _table = new WeakMap();
@@ -1525,89 +3027,182 @@ _getFetchProps = new WeakMap();
1525
3027
  _db = new WeakMap();
1526
3028
  _cache = new WeakMap();
1527
3029
  _schemaTables$2 = new WeakMap();
3030
+ _trace = new WeakMap();
1528
3031
  _insertRecordWithoutId = new WeakSet();
1529
3032
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1530
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1531
3033
  const record = transformObjectLinks(object);
1532
3034
  const response = await insertRecord({
1533
3035
  pathParams: {
1534
3036
  workspace: "{workspaceId}",
1535
3037
  dbBranchName: "{dbBranch}",
3038
+ region: "{region}",
1536
3039
  tableName: __privateGet$4(this, _table)
1537
3040
  },
1538
3041
  queryParams: { columns },
1539
3042
  body: record,
1540
- ...fetchProps
3043
+ ...__privateGet$4(this, _getFetchProps).call(this)
1541
3044
  });
1542
3045
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1543
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
3046
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1544
3047
  };
1545
3048
  _insertRecordWithId = new WeakSet();
1546
- insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1547
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3049
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
1548
3050
  const record = transformObjectLinks(object);
1549
3051
  const response = await insertRecordWithID({
1550
3052
  pathParams: {
1551
3053
  workspace: "{workspaceId}",
1552
3054
  dbBranchName: "{dbBranch}",
3055
+ region: "{region}",
1553
3056
  tableName: __privateGet$4(this, _table),
1554
3057
  recordId
1555
3058
  },
1556
3059
  body: record,
1557
- queryParams: { createOnly: true, columns },
1558
- ...fetchProps
3060
+ queryParams: { createOnly, columns, ifVersion },
3061
+ ...__privateGet$4(this, _getFetchProps).call(this)
1559
3062
  });
1560
3063
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1561
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1562
- };
1563
- _bulkInsertTableRecords = new WeakSet();
1564
- bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1565
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1566
- const records = objects.map((object) => transformObjectLinks(object));
1567
- const response = await bulkInsertTableRecords({
1568
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1569
- queryParams: { columns },
1570
- body: { records },
1571
- ...fetchProps
1572
- });
1573
- if (!isResponseWithRecords(response)) {
1574
- throw new Error("Request included columns but server didn't include them");
3064
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3065
+ };
3066
+ _insertRecords = new WeakSet();
3067
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
3068
+ const chunkedOperations = chunk(
3069
+ objects.map((object) => ({
3070
+ insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
3071
+ })),
3072
+ BULK_OPERATION_MAX_SIZE
3073
+ );
3074
+ const ids = [];
3075
+ for (const operations of chunkedOperations) {
3076
+ const { results } = await branchTransaction({
3077
+ pathParams: {
3078
+ workspace: "{workspaceId}",
3079
+ dbBranchName: "{dbBranch}",
3080
+ region: "{region}"
3081
+ },
3082
+ body: { operations },
3083
+ ...__privateGet$4(this, _getFetchProps).call(this)
3084
+ });
3085
+ for (const result of results) {
3086
+ if (result.operation === "insert") {
3087
+ ids.push(result.id);
3088
+ } else {
3089
+ ids.push(null);
3090
+ }
3091
+ }
1575
3092
  }
1576
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1577
- return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
3093
+ return ids;
1578
3094
  };
1579
3095
  _updateRecordWithID = new WeakSet();
1580
- updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1581
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1582
- const record = transformObjectLinks(object);
1583
- const response = await updateRecordWithID({
1584
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1585
- queryParams: { columns },
1586
- body: record,
1587
- ...fetchProps
1588
- });
1589
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1590
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
3096
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
3097
+ const { id: _id, ...record } = transformObjectLinks(object);
3098
+ try {
3099
+ const response = await updateRecordWithID({
3100
+ pathParams: {
3101
+ workspace: "{workspaceId}",
3102
+ dbBranchName: "{dbBranch}",
3103
+ region: "{region}",
3104
+ tableName: __privateGet$4(this, _table),
3105
+ recordId
3106
+ },
3107
+ queryParams: { columns, ifVersion },
3108
+ body: record,
3109
+ ...__privateGet$4(this, _getFetchProps).call(this)
3110
+ });
3111
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3112
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3113
+ } catch (e) {
3114
+ if (isObject(e) && e.status === 404) {
3115
+ return null;
3116
+ }
3117
+ throw e;
3118
+ }
3119
+ };
3120
+ _updateRecords = new WeakSet();
3121
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
3122
+ const chunkedOperations = chunk(
3123
+ objects.map(({ id, ...object }) => ({
3124
+ update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
3125
+ })),
3126
+ BULK_OPERATION_MAX_SIZE
3127
+ );
3128
+ const ids = [];
3129
+ for (const operations of chunkedOperations) {
3130
+ const { results } = await branchTransaction({
3131
+ pathParams: {
3132
+ workspace: "{workspaceId}",
3133
+ dbBranchName: "{dbBranch}",
3134
+ region: "{region}"
3135
+ },
3136
+ body: { operations },
3137
+ ...__privateGet$4(this, _getFetchProps).call(this)
3138
+ });
3139
+ for (const result of results) {
3140
+ if (result.operation === "update") {
3141
+ ids.push(result.id);
3142
+ } else {
3143
+ ids.push(null);
3144
+ }
3145
+ }
3146
+ }
3147
+ return ids;
1591
3148
  };
1592
3149
  _upsertRecordWithID = new WeakSet();
1593
- upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1594
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3150
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
1595
3151
  const response = await upsertRecordWithID({
1596
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1597
- queryParams: { columns },
3152
+ pathParams: {
3153
+ workspace: "{workspaceId}",
3154
+ dbBranchName: "{dbBranch}",
3155
+ region: "{region}",
3156
+ tableName: __privateGet$4(this, _table),
3157
+ recordId
3158
+ },
3159
+ queryParams: { columns, ifVersion },
1598
3160
  body: object,
1599
- ...fetchProps
3161
+ ...__privateGet$4(this, _getFetchProps).call(this)
1600
3162
  });
1601
3163
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1602
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
3164
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1603
3165
  };
1604
3166
  _deleteRecord = new WeakSet();
1605
- deleteRecord_fn = async function(recordId) {
1606
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1607
- await deleteRecord({
1608
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1609
- ...fetchProps
1610
- });
3167
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
3168
+ try {
3169
+ const response = await deleteRecord({
3170
+ pathParams: {
3171
+ workspace: "{workspaceId}",
3172
+ dbBranchName: "{dbBranch}",
3173
+ region: "{region}",
3174
+ tableName: __privateGet$4(this, _table),
3175
+ recordId
3176
+ },
3177
+ queryParams: { columns },
3178
+ ...__privateGet$4(this, _getFetchProps).call(this)
3179
+ });
3180
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3181
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3182
+ } catch (e) {
3183
+ if (isObject(e) && e.status === 404) {
3184
+ return null;
3185
+ }
3186
+ throw e;
3187
+ }
3188
+ };
3189
+ _deleteRecords = new WeakSet();
3190
+ deleteRecords_fn = async function(recordIds) {
3191
+ const chunkedOperations = chunk(
3192
+ recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
3193
+ BULK_OPERATION_MAX_SIZE
3194
+ );
3195
+ for (const operations of chunkedOperations) {
3196
+ await branchTransaction({
3197
+ pathParams: {
3198
+ workspace: "{workspaceId}",
3199
+ dbBranchName: "{dbBranch}",
3200
+ region: "{region}"
3201
+ },
3202
+ body: { operations },
3203
+ ...__privateGet$4(this, _getFetchProps).call(this)
3204
+ });
3205
+ }
1611
3206
  };
1612
3207
  _setCacheQuery = new WeakSet();
1613
3208
  setCacheQuery_fn = async function(query, meta, records) {
@@ -1629,10 +3224,9 @@ _getSchemaTables$1 = new WeakSet();
1629
3224
  getSchemaTables_fn$1 = async function() {
1630
3225
  if (__privateGet$4(this, _schemaTables$2))
1631
3226
  return __privateGet$4(this, _schemaTables$2);
1632
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1633
3227
  const { schema } = await getBranchDetails({
1634
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1635
- ...fetchProps
3228
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3229
+ ...__privateGet$4(this, _getFetchProps).call(this)
1636
3230
  });
1637
3231
  __privateSet$4(this, _schemaTables$2, schema.tables);
1638
3232
  return schema.tables;
@@ -1644,22 +3238,24 @@ const transformObjectLinks = (object) => {
1644
3238
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1645
3239
  }, {});
1646
3240
  };
1647
- const initObject = (db, schemaTables, table, object) => {
1648
- const result = {};
3241
+ const initObject = (db, schemaTables, table, object, selectedColumns) => {
3242
+ const data = {};
1649
3243
  const { xata, ...rest } = object ?? {};
1650
- Object.assign(result, rest);
3244
+ Object.assign(data, rest);
1651
3245
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1652
3246
  if (!columns)
1653
3247
  console.error(`Table ${table} not found in schema`);
1654
3248
  for (const column of columns ?? []) {
1655
- const value = result[column.name];
3249
+ if (!isValidColumn(selectedColumns, column))
3250
+ continue;
3251
+ const value = data[column.name];
1656
3252
  switch (column.type) {
1657
3253
  case "datetime": {
1658
- const date = value !== void 0 ? new Date(value) : void 0;
1659
- if (date && isNaN(date.getTime())) {
3254
+ const date = value !== void 0 ? new Date(value) : null;
3255
+ if (date !== null && isNaN(date.getTime())) {
1660
3256
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1661
- } else if (date) {
1662
- result[column.name] = date;
3257
+ } else {
3258
+ data[column.name] = date;
1663
3259
  }
1664
3260
  break;
1665
3261
  }
@@ -1668,32 +3264,85 @@ const initObject = (db, schemaTables, table, object) => {
1668
3264
  if (!linkTable) {
1669
3265
  console.error(`Failed to parse link for field ${column.name}`);
1670
3266
  } else if (isObject(value)) {
1671
- result[column.name] = initObject(db, schemaTables, linkTable, value);
3267
+ const selectedLinkColumns = selectedColumns.reduce((acc, item) => {
3268
+ if (item === column.name) {
3269
+ return [...acc, "*"];
3270
+ }
3271
+ if (item.startsWith(`${column.name}.`)) {
3272
+ const [, ...path] = item.split(".");
3273
+ return [...acc, path.join(".")];
3274
+ }
3275
+ return acc;
3276
+ }, []);
3277
+ data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
3278
+ } else {
3279
+ data[column.name] = null;
1672
3280
  }
1673
3281
  break;
1674
3282
  }
3283
+ default:
3284
+ data[column.name] = value ?? null;
3285
+ if (column.notNull === true && value === null) {
3286
+ console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
3287
+ }
3288
+ break;
1675
3289
  }
1676
3290
  }
1677
- result.read = function(columns2) {
1678
- return db[table].read(result["id"], columns2);
3291
+ const record = { ...data };
3292
+ record.read = function(columns2) {
3293
+ return db[table].read(record["id"], columns2);
1679
3294
  };
1680
- result.update = function(data, columns2) {
1681
- return db[table].update(result["id"], data, columns2);
3295
+ record.update = function(data2, b, c) {
3296
+ const columns2 = isStringArray(b) ? b : ["*"];
3297
+ const ifVersion = parseIfVersion(b, c);
3298
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
1682
3299
  };
1683
- result.delete = function() {
1684
- return db[table].delete(result["id"]);
3300
+ record.replace = function(data2, b, c) {
3301
+ const columns2 = isStringArray(b) ? b : ["*"];
3302
+ const ifVersion = parseIfVersion(b, c);
3303
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
1685
3304
  };
1686
- result.getMetadata = function() {
3305
+ record.delete = function() {
3306
+ return db[table].delete(record["id"]);
3307
+ };
3308
+ record.getMetadata = function() {
1687
3309
  return xata;
1688
3310
  };
1689
- for (const prop of ["read", "update", "delete", "getMetadata"]) {
1690
- Object.defineProperty(result, prop, { enumerable: false });
3311
+ record.toSerializable = function() {
3312
+ return JSON.parse(JSON.stringify(transformObjectLinks(data)));
3313
+ };
3314
+ record.toString = function() {
3315
+ return JSON.stringify(transformObjectLinks(data));
3316
+ };
3317
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
3318
+ Object.defineProperty(record, prop, { enumerable: false });
1691
3319
  }
1692
- Object.freeze(result);
1693
- return result;
3320
+ Object.freeze(record);
3321
+ return record;
1694
3322
  };
1695
- function isResponseWithRecords(value) {
1696
- return isObject(value) && Array.isArray(value.records);
3323
+ function extractId(value) {
3324
+ if (isString(value))
3325
+ return value;
3326
+ if (isObject(value) && isString(value.id))
3327
+ return value.id;
3328
+ return void 0;
3329
+ }
3330
+ function isValidColumn(columns, column) {
3331
+ if (columns.includes("*"))
3332
+ return true;
3333
+ if (column.type === "link") {
3334
+ const linkColumns = columns.filter((item) => item.startsWith(column.name));
3335
+ return linkColumns.length > 0;
3336
+ }
3337
+ return columns.includes(column.name);
3338
+ }
3339
+ function parseIfVersion(...args) {
3340
+ for (const arg of args) {
3341
+ if (isObject(arg) && isNumber(arg.ifVersion)) {
3342
+ return arg.ifVersion;
3343
+ }
3344
+ }
3345
+ return void 0;
1697
3346
  }
1698
3347
 
1699
3348
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1745,18 +3394,25 @@ class SimpleCache {
1745
3394
  }
1746
3395
  _map = new WeakMap();
1747
3396
 
1748
- const gt = (value) => ({ $gt: value });
1749
- const ge = (value) => ({ $ge: value });
1750
- const gte = (value) => ({ $ge: value });
1751
- const lt = (value) => ({ $lt: value });
1752
- const lte = (value) => ({ $le: value });
1753
- const le = (value) => ({ $le: value });
3397
+ const greaterThan = (value) => ({ $gt: value });
3398
+ const gt = greaterThan;
3399
+ const greaterThanEquals = (value) => ({ $ge: value });
3400
+ const greaterEquals = greaterThanEquals;
3401
+ const gte = greaterThanEquals;
3402
+ const ge = greaterThanEquals;
3403
+ const lessThan = (value) => ({ $lt: value });
3404
+ const lt = lessThan;
3405
+ const lessThanEquals = (value) => ({ $le: value });
3406
+ const lessEquals = lessThanEquals;
3407
+ const lte = lessThanEquals;
3408
+ const le = lessThanEquals;
1754
3409
  const exists = (column) => ({ $exists: column });
1755
3410
  const notExists = (column) => ({ $notExists: column });
1756
3411
  const startsWith = (value) => ({ $startsWith: value });
1757
3412
  const endsWith = (value) => ({ $endsWith: value });
1758
3413
  const pattern = (value) => ({ $pattern: value });
1759
3414
  const is = (value) => ({ $is: value });
3415
+ const equals = is;
1760
3416
  const isNot = (value) => ({ $isNot: value });
1761
3417
  const contains = (value) => ({ $contains: value });
1762
3418
  const includes = (value) => ({ $includes: value });
@@ -1846,23 +3502,23 @@ class SearchPlugin extends XataPlugin {
1846
3502
  __privateAdd$1(this, _schemaTables, void 0);
1847
3503
  __privateSet$1(this, _schemaTables, schemaTables);
1848
3504
  }
1849
- build({ getFetchProps }) {
3505
+ build(pluginOptions) {
1850
3506
  return {
1851
3507
  all: async (query, options = {}) => {
1852
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1853
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3508
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3509
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
1854
3510
  return records.map((record) => {
1855
3511
  const { table = "orphan" } = record.xata;
1856
- return { table, record: initObject(this.db, schemaTables, table, record) };
3512
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
1857
3513
  });
1858
3514
  },
1859
3515
  byTable: async (query, options = {}) => {
1860
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1861
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3516
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3517
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
1862
3518
  return records.reduce((acc, record) => {
1863
3519
  const { table = "orphan" } = record.xata;
1864
3520
  const items = acc[table] ?? [];
1865
- const item = initObject(this.db, schemaTables, table, record);
3521
+ const item = initObject(this.db, schemaTables, table, record, ["*"]);
1866
3522
  return { ...acc, [table]: [...items, item] };
1867
3523
  }, {});
1868
3524
  }
@@ -1871,106 +3527,39 @@ class SearchPlugin extends XataPlugin {
1871
3527
  }
1872
3528
  _schemaTables = new WeakMap();
1873
3529
  _search = new WeakSet();
1874
- search_fn = async function(query, options, getFetchProps) {
1875
- const fetchProps = await getFetchProps();
1876
- const { tables, fuzziness, highlight, prefix } = options ?? {};
3530
+ search_fn = async function(query, options, pluginOptions) {
3531
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
1877
3532
  const { records } = await searchBranch({
1878
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1879
- body: { tables, query, fuzziness, prefix, highlight },
1880
- ...fetchProps
3533
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3534
+ body: { tables, query, fuzziness, prefix, highlight, page },
3535
+ ...pluginOptions
1881
3536
  });
1882
3537
  return records;
1883
3538
  };
1884
3539
  _getSchemaTables = new WeakSet();
1885
- getSchemaTables_fn = async function(getFetchProps) {
3540
+ getSchemaTables_fn = async function(pluginOptions) {
1886
3541
  if (__privateGet$1(this, _schemaTables))
1887
3542
  return __privateGet$1(this, _schemaTables);
1888
- const fetchProps = await getFetchProps();
1889
3543
  const { schema } = await getBranchDetails({
1890
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1891
- ...fetchProps
3544
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3545
+ ...pluginOptions
1892
3546
  });
1893
3547
  __privateSet$1(this, _schemaTables, schema.tables);
1894
3548
  return schema.tables;
1895
3549
  };
1896
3550
 
1897
- const isBranchStrategyBuilder = (strategy) => {
1898
- return typeof strategy === "function";
1899
- };
1900
-
1901
- async function getCurrentBranchName(options) {
1902
- const { branch, envBranch } = getEnvironment();
1903
- if (branch) {
1904
- const details = await getDatabaseBranch(branch, options);
1905
- if (details)
1906
- return branch;
1907
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1908
- }
1909
- const gitBranch = envBranch || await getGitBranch();
1910
- return resolveXataBranch(gitBranch, options);
1911
- }
1912
- async function getCurrentBranchDetails(options) {
1913
- const branch = await getCurrentBranchName(options);
1914
- return getDatabaseBranch(branch, options);
1915
- }
1916
- async function resolveXataBranch(gitBranch, options) {
1917
- const databaseURL = options?.databaseURL || getDatabaseURL();
1918
- const apiKey = options?.apiKey || getAPIKey();
1919
- if (!databaseURL)
1920
- throw new Error(
1921
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
1922
- );
1923
- if (!apiKey)
1924
- throw new Error(
1925
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
1926
- );
1927
- const [protocol, , host, , dbName] = databaseURL.split("/");
1928
- const [workspace] = host.split(".");
1929
- const { fallbackBranch } = getEnvironment();
1930
- const { branch } = await resolveBranch({
1931
- apiKey,
1932
- apiUrl: databaseURL,
1933
- fetchImpl: getFetchImplementation(options?.fetchImpl),
1934
- workspacesApiUrl: `${protocol}//${host}`,
1935
- pathParams: { dbName, workspace },
1936
- queryParams: { gitBranch, fallbackBranch }
1937
- });
1938
- return branch;
1939
- }
1940
- async function getDatabaseBranch(branch, options) {
1941
- const databaseURL = options?.databaseURL || getDatabaseURL();
1942
- const apiKey = options?.apiKey || getAPIKey();
1943
- if (!databaseURL)
1944
- throw new Error(
1945
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
1946
- );
1947
- if (!apiKey)
1948
- throw new Error(
1949
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
1950
- );
1951
- const [protocol, , host, , database] = databaseURL.split("/");
1952
- const [workspace] = host.split(".");
1953
- const dbBranchName = `${database}:${branch}`;
1954
- try {
1955
- return await getBranchDetails({
1956
- apiKey,
1957
- apiUrl: databaseURL,
1958
- fetchImpl: getFetchImplementation(options?.fetchImpl),
1959
- workspacesApiUrl: `${protocol}//${host}`,
1960
- pathParams: { dbBranchName, workspace }
1961
- });
1962
- } catch (err) {
1963
- if (isObject(err) && err.status === 404)
1964
- return null;
1965
- throw err;
1966
- }
1967
- }
1968
- function getDatabaseURL() {
1969
- try {
1970
- const { databaseURL } = getEnvironment();
1971
- return databaseURL;
1972
- } catch (err) {
1973
- return void 0;
3551
+ class TransactionPlugin extends XataPlugin {
3552
+ build(pluginOptions) {
3553
+ return {
3554
+ run: async (operations) => {
3555
+ const response = await branchTransaction({
3556
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3557
+ body: { operations },
3558
+ ...pluginOptions
3559
+ });
3560
+ return response;
3561
+ }
3562
+ };
1974
3563
  }
1975
3564
  }
1976
3565
 
@@ -1997,24 +3586,24 @@ var __privateMethod = (obj, member, method) => {
1997
3586
  return method;
1998
3587
  };
1999
3588
  const buildClient = (plugins) => {
2000
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
3589
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
2001
3590
  return _a = class {
2002
3591
  constructor(options = {}, schemaTables) {
2003
3592
  __privateAdd(this, _parseOptions);
2004
3593
  __privateAdd(this, _getFetchProps);
2005
- __privateAdd(this, _evaluateBranch);
2006
- __privateAdd(this, _branch, void 0);
2007
3594
  __privateAdd(this, _options, void 0);
2008
3595
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2009
3596
  __privateSet(this, _options, safeOptions);
2010
3597
  const pluginOptions = {
2011
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3598
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
2012
3599
  cache: safeOptions.cache
2013
3600
  };
2014
3601
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2015
3602
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3603
+ const transactions = new TransactionPlugin().build(pluginOptions);
2016
3604
  this.db = db;
2017
3605
  this.search = search;
3606
+ this.transactions = transactions;
2018
3607
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
2019
3608
  if (namespace === void 0)
2020
3609
  continue;
@@ -2030,54 +3619,156 @@ const buildClient = (plugins) => {
2030
3619
  }
2031
3620
  async getConfig() {
2032
3621
  const databaseURL = __privateGet(this, _options).databaseURL;
2033
- const branch = await __privateGet(this, _options).branch();
3622
+ const branch = __privateGet(this, _options).branch;
2034
3623
  return { databaseURL, branch };
2035
3624
  }
2036
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3625
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3626
+ const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3627
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3628
+ if (isBrowser && !enableBrowser) {
3629
+ throw new Error(
3630
+ "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."
3631
+ );
3632
+ }
2037
3633
  const fetch = getFetchImplementation(options?.fetch);
2038
3634
  const databaseURL = options?.databaseURL || getDatabaseURL();
3635
+ const branch = options?.branch || getBranch() || "main";
2039
3636
  const apiKey = options?.apiKey || getAPIKey();
2040
3637
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2041
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2042
- if (!databaseURL || !apiKey) {
2043
- throw new Error("Options databaseURL and apiKey are required");
3638
+ const trace = options?.trace ?? defaultTrace;
3639
+ const clientName = options?.clientName;
3640
+ const host = options?.host ?? "production";
3641
+ const xataAgentExtra = options?.xataAgentExtra;
3642
+ if (!apiKey) {
3643
+ throw new Error("Option apiKey is required");
2044
3644
  }
2045
- return { fetch, databaseURL, apiKey, branch, cache };
2046
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch }) {
2047
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
2048
- if (!branchValue)
2049
- throw new Error("Unable to resolve branch value");
3645
+ if (!databaseURL) {
3646
+ throw new Error("Option databaseURL is required");
3647
+ }
3648
+ return {
3649
+ fetch,
3650
+ databaseURL,
3651
+ apiKey,
3652
+ branch,
3653
+ cache,
3654
+ trace,
3655
+ host,
3656
+ clientID: generateUUID(),
3657
+ enableBrowser,
3658
+ clientName,
3659
+ xataAgentExtra
3660
+ };
3661
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
3662
+ fetch,
3663
+ apiKey,
3664
+ databaseURL,
3665
+ branch,
3666
+ trace,
3667
+ clientID,
3668
+ clientName,
3669
+ xataAgentExtra
3670
+ }) {
2050
3671
  return {
2051
- fetchImpl: fetch,
3672
+ fetch,
2052
3673
  apiKey,
2053
3674
  apiUrl: "",
2054
3675
  workspacesApiUrl: (path, params) => {
2055
3676
  const hasBranch = params.dbBranchName ?? params.branch;
2056
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
3677
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
2057
3678
  return databaseURL + newPath;
2058
- }
2059
- };
2060
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
2061
- if (__privateGet(this, _branch))
2062
- return __privateGet(this, _branch);
2063
- if (param === void 0)
2064
- return void 0;
2065
- const strategies = Array.isArray(param) ? [...param] : [param];
2066
- const evaluateBranch = async (strategy) => {
2067
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
3679
+ },
3680
+ trace,
3681
+ clientID,
3682
+ clientName,
3683
+ xataAgentExtra
2068
3684
  };
2069
- for await (const strategy of strategies) {
2070
- const branch = await evaluateBranch(strategy);
2071
- if (branch) {
2072
- __privateSet(this, _branch, branch);
2073
- return branch;
2074
- }
2075
- }
2076
3685
  }, _a;
2077
3686
  };
2078
3687
  class BaseClient extends buildClient() {
2079
3688
  }
2080
3689
 
3690
+ const META = "__";
3691
+ const VALUE = "___";
3692
+ class Serializer {
3693
+ constructor() {
3694
+ this.classes = {};
3695
+ }
3696
+ add(clazz) {
3697
+ this.classes[clazz.name] = clazz;
3698
+ }
3699
+ toJSON(data) {
3700
+ function visit(obj) {
3701
+ if (Array.isArray(obj))
3702
+ return obj.map(visit);
3703
+ const type = typeof obj;
3704
+ if (type === "undefined")
3705
+ return { [META]: "undefined" };
3706
+ if (type === "bigint")
3707
+ return { [META]: "bigint", [VALUE]: obj.toString() };
3708
+ if (obj === null || type !== "object")
3709
+ return obj;
3710
+ const constructor = obj.constructor;
3711
+ const o = { [META]: constructor.name };
3712
+ for (const [key, value] of Object.entries(obj)) {
3713
+ o[key] = visit(value);
3714
+ }
3715
+ if (constructor === Date)
3716
+ o[VALUE] = obj.toISOString();
3717
+ if (constructor === Map)
3718
+ o[VALUE] = Object.fromEntries(obj);
3719
+ if (constructor === Set)
3720
+ o[VALUE] = [...obj];
3721
+ return o;
3722
+ }
3723
+ return JSON.stringify(visit(data));
3724
+ }
3725
+ fromJSON(json) {
3726
+ return JSON.parse(json, (key, value) => {
3727
+ if (value && typeof value === "object" && !Array.isArray(value)) {
3728
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
3729
+ const constructor = this.classes[clazz];
3730
+ if (constructor) {
3731
+ return Object.assign(Object.create(constructor.prototype), rest);
3732
+ }
3733
+ if (clazz === "Date")
3734
+ return new Date(val);
3735
+ if (clazz === "Set")
3736
+ return new Set(val);
3737
+ if (clazz === "Map")
3738
+ return new Map(Object.entries(val));
3739
+ if (clazz === "bigint")
3740
+ return BigInt(val);
3741
+ if (clazz === "undefined")
3742
+ return void 0;
3743
+ return rest;
3744
+ }
3745
+ return value;
3746
+ });
3747
+ }
3748
+ }
3749
+ const defaultSerializer = new Serializer();
3750
+ const serialize = (data) => {
3751
+ return defaultSerializer.toJSON(data);
3752
+ };
3753
+ const deserialize = (json) => {
3754
+ return defaultSerializer.fromJSON(json);
3755
+ };
3756
+
3757
+ function buildWorkerRunner(config) {
3758
+ return function xataWorker(name, worker) {
3759
+ return async (...args) => {
3760
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3761
+ const result = await fetch(url, {
3762
+ method: "POST",
3763
+ headers: { "Content-Type": "application/json" },
3764
+ body: serialize({ args })
3765
+ });
3766
+ const text = await result.text();
3767
+ return deserialize(text);
3768
+ };
3769
+ };
3770
+ }
3771
+
2081
3772
  class XataError extends Error {
2082
3773
  constructor(message, status) {
2083
3774
  super(message);
@@ -2086,6 +3777,7 @@ class XataError extends Error {
2086
3777
  }
2087
3778
 
2088
3779
  exports.BaseClient = BaseClient;
3780
+ exports.FetcherError = FetcherError;
2089
3781
  exports.Operations = operationsByTag;
2090
3782
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
2091
3783
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -2098,6 +3790,7 @@ exports.Repository = Repository;
2098
3790
  exports.RestRepository = RestRepository;
2099
3791
  exports.SchemaPlugin = SchemaPlugin;
2100
3792
  exports.SearchPlugin = SearchPlugin;
3793
+ exports.Serializer = Serializer;
2101
3794
  exports.SimpleCache = SimpleCache;
2102
3795
  exports.XataApiClient = XataApiClient;
2103
3796
  exports.XataApiPlugin = XataApiPlugin;
@@ -2106,40 +3799,58 @@ exports.XataPlugin = XataPlugin;
2106
3799
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
2107
3800
  exports.addGitBranchesEntry = addGitBranchesEntry;
2108
3801
  exports.addTableColumn = addTableColumn;
3802
+ exports.aggregateTable = aggregateTable;
3803
+ exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
3804
+ exports.askTable = askTable;
3805
+ exports.branchTransaction = branchTransaction;
2109
3806
  exports.buildClient = buildClient;
3807
+ exports.buildWorkerRunner = buildWorkerRunner;
2110
3808
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
2111
3809
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
3810
+ exports.compareBranchSchemas = compareBranchSchemas;
3811
+ exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
3812
+ exports.compareMigrationRequest = compareMigrationRequest;
2112
3813
  exports.contains = contains;
3814
+ exports.copyBranch = copyBranch;
2113
3815
  exports.createBranch = createBranch;
2114
3816
  exports.createDatabase = createDatabase;
3817
+ exports.createMigrationRequest = createMigrationRequest;
2115
3818
  exports.createTable = createTable;
2116
3819
  exports.createUserAPIKey = createUserAPIKey;
2117
3820
  exports.createWorkspace = createWorkspace;
2118
3821
  exports.deleteBranch = deleteBranch;
2119
3822
  exports.deleteColumn = deleteColumn;
2120
3823
  exports.deleteDatabase = deleteDatabase;
3824
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
2121
3825
  exports.deleteRecord = deleteRecord;
2122
3826
  exports.deleteTable = deleteTable;
2123
3827
  exports.deleteUser = deleteUser;
2124
3828
  exports.deleteUserAPIKey = deleteUserAPIKey;
2125
3829
  exports.deleteWorkspace = deleteWorkspace;
3830
+ exports.deserialize = deserialize;
2126
3831
  exports.endsWith = endsWith;
3832
+ exports.equals = equals;
2127
3833
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
2128
3834
  exports.exists = exists;
2129
3835
  exports.ge = ge;
2130
3836
  exports.getAPIKey = getAPIKey;
3837
+ exports.getBranch = getBranch;
2131
3838
  exports.getBranchDetails = getBranchDetails;
2132
3839
  exports.getBranchList = getBranchList;
2133
3840
  exports.getBranchMetadata = getBranchMetadata;
2134
3841
  exports.getBranchMigrationHistory = getBranchMigrationHistory;
2135
3842
  exports.getBranchMigrationPlan = getBranchMigrationPlan;
3843
+ exports.getBranchSchemaHistory = getBranchSchemaHistory;
2136
3844
  exports.getBranchStats = getBranchStats;
2137
3845
  exports.getColumn = getColumn;
2138
- exports.getCurrentBranchDetails = getCurrentBranchDetails;
2139
- exports.getCurrentBranchName = getCurrentBranchName;
3846
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
2140
3847
  exports.getDatabaseList = getDatabaseList;
3848
+ exports.getDatabaseMetadata = getDatabaseMetadata;
2141
3849
  exports.getDatabaseURL = getDatabaseURL;
2142
3850
  exports.getGitBranchesMapping = getGitBranchesMapping;
3851
+ exports.getHostUrl = getHostUrl;
3852
+ exports.getMigrationRequest = getMigrationRequest;
3853
+ exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
2143
3854
  exports.getRecord = getRecord;
2144
3855
  exports.getTableColumns = getTableColumns;
2145
3856
  exports.getTableSchema = getTableSchema;
@@ -2148,6 +3859,9 @@ exports.getUserAPIKeys = getUserAPIKeys;
2148
3859
  exports.getWorkspace = getWorkspace;
2149
3860
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
2150
3861
  exports.getWorkspacesList = getWorkspacesList;
3862
+ exports.greaterEquals = greaterEquals;
3863
+ exports.greaterThan = greaterThan;
3864
+ exports.greaterThanEquals = greaterThanEquals;
2151
3865
  exports.gt = gt;
2152
3866
  exports.gte = gte;
2153
3867
  exports.includes = includes;
@@ -2159,15 +3873,27 @@ exports.insertRecordWithID = insertRecordWithID;
2159
3873
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
2160
3874
  exports.is = is;
2161
3875
  exports.isCursorPaginationOptions = isCursorPaginationOptions;
3876
+ exports.isHostProviderAlias = isHostProviderAlias;
3877
+ exports.isHostProviderBuilder = isHostProviderBuilder;
2162
3878
  exports.isIdentifiable = isIdentifiable;
2163
3879
  exports.isNot = isNot;
2164
3880
  exports.isXataRecord = isXataRecord;
2165
3881
  exports.le = le;
3882
+ exports.lessEquals = lessEquals;
3883
+ exports.lessThan = lessThan;
3884
+ exports.lessThanEquals = lessThanEquals;
3885
+ exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
3886
+ exports.listRegions = listRegions;
2166
3887
  exports.lt = lt;
2167
3888
  exports.lte = lte;
3889
+ exports.mergeMigrationRequest = mergeMigrationRequest;
2168
3890
  exports.notExists = notExists;
2169
3891
  exports.operationsByTag = operationsByTag;
3892
+ exports.parseProviderString = parseProviderString;
3893
+ exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
2170
3894
  exports.pattern = pattern;
3895
+ exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
3896
+ exports.queryMigrationRequests = queryMigrationRequests;
2171
3897
  exports.queryTable = queryTable;
2172
3898
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
2173
3899
  exports.removeWorkspaceMember = removeWorkspaceMember;
@@ -2175,10 +3901,16 @@ exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
2175
3901
  exports.resolveBranch = resolveBranch;
2176
3902
  exports.searchBranch = searchBranch;
2177
3903
  exports.searchTable = searchTable;
3904
+ exports.serialize = serialize;
2178
3905
  exports.setTableSchema = setTableSchema;
2179
3906
  exports.startsWith = startsWith;
3907
+ exports.summarizeTable = summarizeTable;
2180
3908
  exports.updateBranchMetadata = updateBranchMetadata;
3909
+ exports.updateBranchSchema = updateBranchSchema;
2181
3910
  exports.updateColumn = updateColumn;
3911
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
3912
+ exports.updateDatabaseMetadata = updateDatabaseMetadata;
3913
+ exports.updateMigrationRequest = updateMigrationRequest;
2182
3914
  exports.updateRecordWithID = updateRecordWithID;
2183
3915
  exports.updateTable = updateTable;
2184
3916
  exports.updateUser = updateUser;
@@ -2186,4 +3918,5 @@ exports.updateWorkspace = updateWorkspace;
2186
3918
  exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
2187
3919
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
2188
3920
  exports.upsertRecordWithID = upsertRecordWithID;
3921
+ exports.vectorSearchTable = vectorSearchTable;
2189
3922
  //# sourceMappingURL=index.cjs.map