@xata.io/client 0.0.0-alpha.vfe4ae98 → 0.0.0-alpha.vfe4b459

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,6 +1,27 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
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
+ };
4
25
 
5
26
  function notEmpty(value) {
6
27
  return value !== null && value !== void 0;
@@ -17,6 +38,24 @@ function isDefined(value) {
17
38
  function isString(value) {
18
39
  return isDefined(value) && typeof value === "string";
19
40
  }
41
+ function isStringArray(value) {
42
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
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
+ }
20
59
  function toBase64(value) {
21
60
  try {
22
61
  return btoa(value);
@@ -25,60 +64,435 @@ function toBase64(value) {
25
64
  return buf.from(value).toString("base64");
26
65
  }
27
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
+ }
28
88
 
29
- function getEnvVariable(name) {
89
+ function getEnvironment() {
30
90
  try {
31
- if (isObject(process) && isString(process?.env?.[name])) {
32
- return process.env[name];
91
+ if (isDefined(process) && isDefined(process.env)) {
92
+ return {
93
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
94
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
95
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
96
+ deployPreview: process.env.XATA_PREVIEW,
97
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
98
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
99
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
100
+ };
33
101
  }
34
102
  } catch (err) {
35
103
  }
36
104
  try {
37
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
38
- return Deno.env.get(name);
105
+ if (isObject(Deno) && isObject(Deno.env)) {
106
+ return {
107
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
108
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
109
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
110
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
111
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
112
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
113
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
114
+ };
39
115
  }
40
116
  } catch (err) {
41
117
  }
118
+ return {
119
+ apiKey: getGlobalApiKey(),
120
+ databaseURL: getGlobalDatabaseURL(),
121
+ branch: getGlobalBranch(),
122
+ deployPreview: void 0,
123
+ deployPreviewBranch: void 0,
124
+ vercelGitCommitRef: void 0,
125
+ vercelGitRepoOwner: void 0
126
+ };
42
127
  }
43
- async function getGitBranch() {
128
+ function getEnableBrowserVariable() {
44
129
  try {
45
- if (typeof require === "function") {
46
- const req = require;
47
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
130
+ if (isObject(process) && isObject(process.env) && process.env.XATA_ENABLE_BROWSER !== void 0) {
131
+ return process.env.XATA_ENABLE_BROWSER === "true";
48
132
  }
49
133
  } catch (err) {
50
134
  }
51
135
  try {
52
- if (isObject(Deno)) {
53
- const process2 = Deno.run({
54
- cmd: ["git", "branch", "--show-current"],
55
- stdout: "piped",
56
- stderr: "piped"
57
- });
58
- return new TextDecoder().decode(await process2.output()).trim();
136
+ if (isObject(Deno) && isObject(Deno.env) && Deno.env.get("XATA_ENABLE_BROWSER") !== void 0) {
137
+ return Deno.env.get("XATA_ENABLE_BROWSER") === "true";
59
138
  }
60
139
  } catch (err) {
61
140
  }
141
+ try {
142
+ return XATA_ENABLE_BROWSER === true || XATA_ENABLE_BROWSER === "true";
143
+ } catch (err) {
144
+ return void 0;
145
+ }
146
+ }
147
+ function getGlobalApiKey() {
148
+ try {
149
+ return XATA_API_KEY;
150
+ } catch (err) {
151
+ return void 0;
152
+ }
153
+ }
154
+ function getGlobalDatabaseURL() {
155
+ try {
156
+ return XATA_DATABASE_URL;
157
+ } catch (err) {
158
+ return void 0;
159
+ }
160
+ }
161
+ function getGlobalBranch() {
162
+ try {
163
+ return XATA_BRANCH;
164
+ } catch (err) {
165
+ return void 0;
166
+ }
167
+ }
168
+ function getDatabaseURL() {
169
+ try {
170
+ const { databaseURL } = getEnvironment();
171
+ return databaseURL;
172
+ } catch (err) {
173
+ return void 0;
174
+ }
62
175
  }
63
-
64
176
  function getAPIKey() {
65
177
  try {
66
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
178
+ const { apiKey } = getEnvironment();
179
+ return apiKey;
180
+ } catch (err) {
181
+ return void 0;
182
+ }
183
+ }
184
+ function getBranch() {
185
+ try {
186
+ const { branch } = getEnvironment();
187
+ return branch ?? "main";
188
+ } catch (err) {
189
+ return void 0;
190
+ }
191
+ }
192
+ function buildPreviewBranchName({ org, branch }) {
193
+ return `preview-${org}-${branch}`;
194
+ }
195
+ function getPreviewBranch() {
196
+ try {
197
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
198
+ if (deployPreviewBranch)
199
+ return deployPreviewBranch;
200
+ switch (deployPreview) {
201
+ case "vercel": {
202
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
203
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
204
+ return void 0;
205
+ }
206
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
207
+ }
208
+ }
209
+ return void 0;
67
210
  } catch (err) {
68
211
  return void 0;
69
212
  }
70
213
  }
71
214
 
215
+ var __accessCheck$8 = (obj, member, msg) => {
216
+ if (!member.has(obj))
217
+ throw TypeError("Cannot " + msg);
218
+ };
219
+ var __privateGet$8 = (obj, member, getter) => {
220
+ __accessCheck$8(obj, member, "read from private field");
221
+ return getter ? getter.call(obj) : member.get(obj);
222
+ };
223
+ var __privateAdd$8 = (obj, member, value) => {
224
+ if (member.has(obj))
225
+ throw TypeError("Cannot add the same private member more than once");
226
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
227
+ };
228
+ var __privateSet$8 = (obj, member, value, setter) => {
229
+ __accessCheck$8(obj, member, "write to private field");
230
+ setter ? setter.call(obj, value) : member.set(obj, value);
231
+ return value;
232
+ };
233
+ var __privateMethod$4 = (obj, member, method) => {
234
+ __accessCheck$8(obj, member, "access private method");
235
+ return method;
236
+ };
237
+ var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
72
238
  function getFetchImplementation(userFetch) {
73
239
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
74
240
  const fetchImpl = userFetch ?? globalFetch;
75
241
  if (!fetchImpl) {
76
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
242
+ throw new Error(
243
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
244
+ );
77
245
  }
78
246
  return fetchImpl;
79
247
  }
248
+ class ApiRequestPool {
249
+ constructor(concurrency = 10) {
250
+ __privateAdd$8(this, _enqueue);
251
+ __privateAdd$8(this, _fetch, void 0);
252
+ __privateAdd$8(this, _queue, void 0);
253
+ __privateAdd$8(this, _concurrency, void 0);
254
+ __privateSet$8(this, _queue, []);
255
+ __privateSet$8(this, _concurrency, concurrency);
256
+ this.running = 0;
257
+ this.started = 0;
258
+ }
259
+ setFetch(fetch2) {
260
+ __privateSet$8(this, _fetch, fetch2);
261
+ }
262
+ getFetch() {
263
+ if (!__privateGet$8(this, _fetch)) {
264
+ throw new Error("Fetch not set");
265
+ }
266
+ return __privateGet$8(this, _fetch);
267
+ }
268
+ request(url, options) {
269
+ const start = /* @__PURE__ */ new Date();
270
+ const fetch2 = this.getFetch();
271
+ const runRequest = async (stalled = false) => {
272
+ const response = await fetch2(url, options);
273
+ if (response.status === 429) {
274
+ const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
275
+ await timeout(rateLimitReset * 1e3);
276
+ return await runRequest(true);
277
+ }
278
+ if (stalled) {
279
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
280
+ console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
281
+ }
282
+ return response;
283
+ };
284
+ return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
285
+ return await runRequest();
286
+ });
287
+ }
288
+ }
289
+ _fetch = new WeakMap();
290
+ _queue = new WeakMap();
291
+ _concurrency = new WeakMap();
292
+ _enqueue = new WeakSet();
293
+ enqueue_fn = function(task) {
294
+ const promise = new Promise((resolve) => __privateGet$8(this, _queue).push(resolve)).finally(() => {
295
+ this.started--;
296
+ this.running++;
297
+ }).then(() => task()).finally(() => {
298
+ this.running--;
299
+ const next = __privateGet$8(this, _queue).shift();
300
+ if (next !== void 0) {
301
+ this.started++;
302
+ next();
303
+ }
304
+ });
305
+ if (this.running + this.started < __privateGet$8(this, _concurrency)) {
306
+ const next = __privateGet$8(this, _queue).shift();
307
+ if (next !== void 0) {
308
+ this.started++;
309
+ next();
310
+ }
311
+ }
312
+ return promise;
313
+ };
314
+
315
+ function generateUUID() {
316
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
317
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
318
+ return v.toString(16);
319
+ });
320
+ }
321
+
322
+ async function getBytes(stream, onChunk) {
323
+ const reader = stream.getReader();
324
+ let result;
325
+ while (!(result = await reader.read()).done) {
326
+ onChunk(result.value);
327
+ }
328
+ }
329
+ function getLines(onLine) {
330
+ let buffer;
331
+ let position;
332
+ let fieldLength;
333
+ let discardTrailingNewline = false;
334
+ return function onChunk(arr) {
335
+ if (buffer === void 0) {
336
+ buffer = arr;
337
+ position = 0;
338
+ fieldLength = -1;
339
+ } else {
340
+ buffer = concat(buffer, arr);
341
+ }
342
+ const bufLength = buffer.length;
343
+ let lineStart = 0;
344
+ while (position < bufLength) {
345
+ if (discardTrailingNewline) {
346
+ if (buffer[position] === 10 /* NewLine */) {
347
+ lineStart = ++position;
348
+ }
349
+ discardTrailingNewline = false;
350
+ }
351
+ let lineEnd = -1;
352
+ for (; position < bufLength && lineEnd === -1; ++position) {
353
+ switch (buffer[position]) {
354
+ case 58 /* Colon */:
355
+ if (fieldLength === -1) {
356
+ fieldLength = position - lineStart;
357
+ }
358
+ break;
359
+ case 13 /* CarriageReturn */:
360
+ discardTrailingNewline = true;
361
+ case 10 /* NewLine */:
362
+ lineEnd = position;
363
+ break;
364
+ }
365
+ }
366
+ if (lineEnd === -1) {
367
+ break;
368
+ }
369
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
370
+ lineStart = position;
371
+ fieldLength = -1;
372
+ }
373
+ if (lineStart === bufLength) {
374
+ buffer = void 0;
375
+ } else if (lineStart !== 0) {
376
+ buffer = buffer.subarray(lineStart);
377
+ position -= lineStart;
378
+ }
379
+ };
380
+ }
381
+ function getMessages(onId, onRetry, onMessage) {
382
+ let message = newMessage();
383
+ const decoder = new TextDecoder();
384
+ return function onLine(line, fieldLength) {
385
+ if (line.length === 0) {
386
+ onMessage?.(message);
387
+ message = newMessage();
388
+ } else if (fieldLength > 0) {
389
+ const field = decoder.decode(line.subarray(0, fieldLength));
390
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
391
+ const value = decoder.decode(line.subarray(valueOffset));
392
+ switch (field) {
393
+ case "data":
394
+ message.data = message.data ? message.data + "\n" + value : value;
395
+ break;
396
+ case "event":
397
+ message.event = value;
398
+ break;
399
+ case "id":
400
+ onId(message.id = value);
401
+ break;
402
+ case "retry":
403
+ const retry = parseInt(value, 10);
404
+ if (!isNaN(retry)) {
405
+ onRetry(message.retry = retry);
406
+ }
407
+ break;
408
+ }
409
+ }
410
+ };
411
+ }
412
+ function concat(a, b) {
413
+ const res = new Uint8Array(a.length + b.length);
414
+ res.set(a);
415
+ res.set(b, a.length);
416
+ return res;
417
+ }
418
+ function newMessage() {
419
+ return {
420
+ data: "",
421
+ event: "",
422
+ id: "",
423
+ retry: void 0
424
+ };
425
+ }
426
+ const EventStreamContentType = "text/event-stream";
427
+ const LastEventId = "last-event-id";
428
+ function fetchEventSource(input, {
429
+ signal: inputSignal,
430
+ headers: inputHeaders,
431
+ onopen: inputOnOpen,
432
+ onmessage,
433
+ onclose,
434
+ onerror,
435
+ fetch: inputFetch,
436
+ ...rest
437
+ }) {
438
+ return new Promise((resolve, reject) => {
439
+ const headers = { ...inputHeaders };
440
+ if (!headers.accept) {
441
+ headers.accept = EventStreamContentType;
442
+ }
443
+ let curRequestController;
444
+ function dispose() {
445
+ curRequestController.abort();
446
+ }
447
+ inputSignal?.addEventListener("abort", () => {
448
+ dispose();
449
+ resolve();
450
+ });
451
+ const fetchImpl = inputFetch ?? fetch;
452
+ const onopen = inputOnOpen ?? defaultOnOpen;
453
+ async function create() {
454
+ curRequestController = new AbortController();
455
+ try {
456
+ const response = await fetchImpl(input, {
457
+ ...rest,
458
+ headers,
459
+ signal: curRequestController.signal
460
+ });
461
+ await onopen(response);
462
+ await getBytes(
463
+ response.body,
464
+ getLines(
465
+ getMessages(
466
+ (id) => {
467
+ if (id) {
468
+ headers[LastEventId] = id;
469
+ } else {
470
+ delete headers[LastEventId];
471
+ }
472
+ },
473
+ (_retry) => {
474
+ },
475
+ onmessage
476
+ )
477
+ )
478
+ );
479
+ onclose?.();
480
+ dispose();
481
+ resolve();
482
+ } catch (err) {
483
+ }
484
+ }
485
+ create();
486
+ });
487
+ }
488
+ function defaultOnOpen(response) {
489
+ const contentType = response.headers?.get("content-type");
490
+ if (!contentType?.startsWith(EventStreamContentType)) {
491
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
492
+ }
493
+ }
80
494
 
81
- const VERSION = "0.0.0-alpha.vfe4ae98";
495
+ const VERSION = "0.24.3";
82
496
 
83
497
  class ErrorWithCause extends Error {
84
498
  constructor(message, options) {
@@ -89,7 +503,7 @@ class FetcherError extends ErrorWithCause {
89
503
  constructor(status, data, requestId) {
90
504
  super(getMessage(data));
91
505
  this.status = status;
92
- this.errors = isBulkError(data) ? data.errors : void 0;
506
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
93
507
  this.requestId = requestId;
94
508
  if (data instanceof Error) {
95
509
  this.stack = data.stack;
@@ -121,6 +535,7 @@ function getMessage(data) {
121
535
  }
122
536
  }
123
537
 
538
+ const pool = new ApiRequestPool();
124
539
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
125
540
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
126
541
  if (value === void 0 || value === null)
@@ -129,316 +544,418 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
129
544
  }, {});
130
545
  const query = new URLSearchParams(cleanQueryParams).toString();
131
546
  const queryString = query.length > 0 ? `?${query}` : "";
132
- return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
547
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
548
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
549
+ }, {});
550
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
133
551
  };
134
552
  function buildBaseUrl({
553
+ endpoint,
135
554
  path,
136
555
  workspacesApiUrl,
137
556
  apiUrl,
138
- pathParams
557
+ pathParams = {}
139
558
  }) {
140
- if (!pathParams?.workspace)
141
- return `${apiUrl}${path}`;
142
- const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
143
- return url.replace("{workspaceId}", pathParams.workspace);
559
+ if (endpoint === "dataPlane") {
560
+ const url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
561
+ const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
562
+ return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
563
+ }
564
+ return `${apiUrl}${path}`;
144
565
  }
145
566
  function hostHeader(url) {
146
567
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
147
568
  const { groups } = pattern.exec(url) ?? {};
148
569
  return groups?.host ? { Host: groups.host } : {};
149
570
  }
571
+ const defaultClientID = generateUUID();
150
572
  async function fetch$1({
151
573
  url: path,
152
574
  method,
153
575
  body,
154
- headers,
576
+ headers: customHeaders,
577
+ pathParams,
578
+ queryParams,
579
+ fetch: fetch2,
580
+ apiKey,
581
+ endpoint,
582
+ apiUrl,
583
+ workspacesApiUrl,
584
+ trace,
585
+ signal,
586
+ clientID,
587
+ sessionID,
588
+ clientName,
589
+ xataAgentExtra,
590
+ fetchOptions = {}
591
+ }) {
592
+ pool.setFetch(fetch2);
593
+ return await trace(
594
+ `${method.toUpperCase()} ${path}`,
595
+ async ({ setAttributes }) => {
596
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
597
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
598
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
599
+ setAttributes({
600
+ [TraceAttributes.HTTP_URL]: url,
601
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
602
+ });
603
+ const xataAgent = compact([
604
+ ["client", "TS_SDK"],
605
+ ["version", VERSION],
606
+ isDefined(clientName) ? ["service", clientName] : void 0,
607
+ ...Object.entries(xataAgentExtra ?? {})
608
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
609
+ const headers = {
610
+ "Accept-Encoding": "identity",
611
+ "Content-Type": "application/json",
612
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
613
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
614
+ "X-Xata-Agent": xataAgent,
615
+ ...customHeaders,
616
+ ...hostHeader(fullUrl),
617
+ Authorization: `Bearer ${apiKey}`
618
+ };
619
+ const response = await pool.request(url, {
620
+ ...fetchOptions,
621
+ method: method.toUpperCase(),
622
+ body: body ? JSON.stringify(body) : void 0,
623
+ headers,
624
+ signal
625
+ });
626
+ const { host, protocol } = parseUrl(response.url);
627
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
628
+ setAttributes({
629
+ [TraceAttributes.KIND]: "http",
630
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
631
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
632
+ [TraceAttributes.HTTP_HOST]: host,
633
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
634
+ });
635
+ if (response.status === 204) {
636
+ return {};
637
+ }
638
+ if (response.status === 429) {
639
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
640
+ }
641
+ try {
642
+ const jsonResponse = await response.json();
643
+ if (response.ok) {
644
+ return jsonResponse;
645
+ }
646
+ throw new FetcherError(response.status, jsonResponse, requestId);
647
+ } catch (error) {
648
+ throw new FetcherError(response.status, error, requestId);
649
+ }
650
+ },
651
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
652
+ );
653
+ }
654
+ function fetchSSERequest({
655
+ url: path,
656
+ method,
657
+ body,
658
+ headers: customHeaders,
155
659
  pathParams,
156
660
  queryParams,
157
- fetchImpl,
661
+ fetch: fetch2,
158
662
  apiKey,
663
+ endpoint,
159
664
  apiUrl,
160
- workspacesApiUrl
665
+ workspacesApiUrl,
666
+ onMessage,
667
+ onError,
668
+ onClose,
669
+ signal,
670
+ clientID,
671
+ sessionID,
672
+ clientName,
673
+ xataAgentExtra
161
674
  }) {
162
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
675
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
163
676
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
164
677
  const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
165
- const response = await fetchImpl(url, {
166
- method: method.toUpperCase(),
167
- body: body ? JSON.stringify(body) : void 0,
678
+ void fetchEventSource(url, {
679
+ method,
680
+ body: JSON.stringify(body),
681
+ fetch: fetch2,
682
+ signal,
168
683
  headers: {
169
- "Content-Type": "application/json",
170
- "User-Agent": `Xata client-ts/${VERSION}`,
171
- ...headers,
172
- ...hostHeader(fullUrl),
173
- Authorization: `Bearer ${apiKey}`
684
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
685
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
686
+ "X-Xata-Agent": compact([
687
+ ["client", "TS_SDK"],
688
+ ["version", VERSION],
689
+ isDefined(clientName) ? ["service", clientName] : void 0,
690
+ ...Object.entries(xataAgentExtra ?? {})
691
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
692
+ ...customHeaders,
693
+ Authorization: `Bearer ${apiKey}`,
694
+ "Content-Type": "application/json"
695
+ },
696
+ onmessage(ev) {
697
+ onMessage?.(JSON.parse(ev.data));
698
+ },
699
+ onerror(ev) {
700
+ onError?.(JSON.parse(ev.data));
701
+ },
702
+ onclose() {
703
+ onClose?.();
174
704
  }
175
705
  });
176
- if (response.status === 204) {
177
- return {};
178
- }
179
- const requestId = response.headers?.get("x-request-id") ?? void 0;
706
+ }
707
+ function parseUrl(url) {
180
708
  try {
181
- const jsonResponse = await response.json();
182
- if (response.ok) {
183
- return jsonResponse;
184
- }
185
- throw new FetcherError(response.status, jsonResponse, requestId);
709
+ const { host, protocol } = new URL(url);
710
+ return { host, protocol };
186
711
  } catch (error) {
187
- throw new FetcherError(response.status, error, requestId);
712
+ return {};
188
713
  }
189
714
  }
190
715
 
191
- const getUser = (variables) => fetch$1({ url: "/user", method: "get", ...variables });
192
- const updateUser = (variables) => fetch$1({ url: "/user", method: "put", ...variables });
193
- const deleteUser = (variables) => fetch$1({ url: "/user", method: "delete", ...variables });
194
- const getUserAPIKeys = (variables) => fetch$1({
195
- url: "/user/keys",
196
- method: "get",
197
- ...variables
198
- });
199
- const createUserAPIKey = (variables) => fetch$1({
200
- url: "/user/keys/{keyName}",
201
- method: "post",
202
- ...variables
203
- });
204
- const deleteUserAPIKey = (variables) => fetch$1({
205
- url: "/user/keys/{keyName}",
206
- method: "delete",
207
- ...variables
208
- });
209
- const createWorkspace = (variables) => fetch$1({
210
- url: "/workspaces",
211
- method: "post",
212
- ...variables
213
- });
214
- const getWorkspacesList = (variables) => fetch$1({
215
- url: "/workspaces",
216
- method: "get",
217
- ...variables
218
- });
219
- const getWorkspace = (variables) => fetch$1({
220
- url: "/workspaces/{workspaceId}",
221
- method: "get",
222
- ...variables
223
- });
224
- const updateWorkspace = (variables) => fetch$1({
225
- url: "/workspaces/{workspaceId}",
226
- method: "put",
227
- ...variables
228
- });
229
- const deleteWorkspace = (variables) => fetch$1({
230
- url: "/workspaces/{workspaceId}",
231
- method: "delete",
232
- ...variables
233
- });
234
- const getWorkspaceMembersList = (variables) => fetch$1({
235
- url: "/workspaces/{workspaceId}/members",
236
- method: "get",
237
- ...variables
238
- });
239
- const updateWorkspaceMemberRole = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables });
240
- const removeWorkspaceMember = (variables) => fetch$1({
241
- url: "/workspaces/{workspaceId}/members/{userId}",
242
- method: "delete",
243
- ...variables
244
- });
245
- const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
246
- const cancelWorkspaceMemberInvite = (variables) => fetch$1({
247
- url: "/workspaces/{workspaceId}/invites/{inviteId}",
248
- method: "delete",
249
- ...variables
250
- });
251
- const resendWorkspaceMemberInvite = (variables) => fetch$1({
252
- url: "/workspaces/{workspaceId}/invites/{inviteId}/resend",
253
- method: "post",
254
- ...variables
255
- });
256
- const acceptWorkspaceMemberInvite = (variables) => fetch$1({
257
- url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept",
258
- method: "post",
259
- ...variables
260
- });
261
- const getDatabaseList = (variables) => fetch$1({
262
- url: "/dbs",
263
- method: "get",
264
- ...variables
265
- });
266
- const getBranchList = (variables) => fetch$1({
267
- url: "/dbs/{dbName}",
268
- method: "get",
269
- ...variables
270
- });
271
- const createDatabase = (variables) => fetch$1({
272
- url: "/dbs/{dbName}",
273
- method: "put",
274
- ...variables
275
- });
276
- const deleteDatabase = (variables) => fetch$1({
716
+ const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
717
+
718
+ const getBranchList = (variables, signal) => dataPlaneFetch({
277
719
  url: "/dbs/{dbName}",
278
- method: "delete",
279
- ...variables
280
- });
281
- const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
282
- const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
283
- const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
284
- const resolveBranch = (variables) => fetch$1({
285
- url: "/dbs/{dbName}/resolveBranch",
286
720
  method: "get",
287
- ...variables
721
+ ...variables,
722
+ signal
288
723
  });
289
- const getBranchDetails = (variables) => fetch$1({
724
+ const getBranchDetails = (variables, signal) => dataPlaneFetch({
290
725
  url: "/db/{dbBranchName}",
291
726
  method: "get",
292
- ...variables
293
- });
294
- const createBranch = (variables) => fetch$1({
295
- url: "/db/{dbBranchName}",
296
- method: "put",
297
- ...variables
727
+ ...variables,
728
+ signal
298
729
  });
299
- const deleteBranch = (variables) => fetch$1({
730
+ const createBranch = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
731
+ const deleteBranch = (variables, signal) => dataPlaneFetch({
300
732
  url: "/db/{dbBranchName}",
301
733
  method: "delete",
302
- ...variables
734
+ ...variables,
735
+ signal
303
736
  });
304
- const updateBranchMetadata = (variables) => fetch$1({
737
+ const copyBranch = (variables, signal) => dataPlaneFetch({
738
+ url: "/db/{dbBranchName}/copy",
739
+ method: "post",
740
+ ...variables,
741
+ signal
742
+ });
743
+ const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
305
744
  url: "/db/{dbBranchName}/metadata",
306
745
  method: "put",
307
- ...variables
746
+ ...variables,
747
+ signal
308
748
  });
309
- const getBranchMetadata = (variables) => fetch$1({
749
+ const getBranchMetadata = (variables, signal) => dataPlaneFetch({
310
750
  url: "/db/{dbBranchName}/metadata",
311
751
  method: "get",
312
- ...variables
752
+ ...variables,
753
+ signal
313
754
  });
314
- const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
315
- const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
316
- const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
317
- const getBranchStats = (variables) => fetch$1({
755
+ const getBranchStats = (variables, signal) => dataPlaneFetch({
318
756
  url: "/db/{dbBranchName}/stats",
319
757
  method: "get",
320
- ...variables
758
+ ...variables,
759
+ signal
760
+ });
761
+ const getGitBranchesMapping = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables, signal });
762
+ const addGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables, signal });
763
+ const removeGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables, signal });
764
+ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/resolveBranch", method: "get", ...variables, signal });
765
+ const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
766
+ const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
767
+ const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
768
+ const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
769
+ const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
770
+ const getMigrationRequest = (variables, signal) => dataPlaneFetch({
771
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
772
+ method: "get",
773
+ ...variables,
774
+ signal
321
775
  });
322
- const createTable = (variables) => fetch$1({
776
+ const updateMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables, signal });
777
+ const listMigrationRequestsCommits = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables, signal });
778
+ const compareMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables, signal });
779
+ const getMigrationRequestIsMerged = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables, signal });
780
+ const mergeMigrationRequest = (variables, signal) => dataPlaneFetch({
781
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
782
+ method: "post",
783
+ ...variables,
784
+ signal
785
+ });
786
+ const getBranchSchemaHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables, signal });
787
+ const compareBranchWithUserSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables, signal });
788
+ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables, signal });
789
+ const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
790
+ const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
791
+ const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
792
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
793
+ const createTable = (variables, signal) => dataPlaneFetch({
323
794
  url: "/db/{dbBranchName}/tables/{tableName}",
324
795
  method: "put",
325
- ...variables
796
+ ...variables,
797
+ signal
326
798
  });
327
- const deleteTable = (variables) => fetch$1({
799
+ const deleteTable = (variables, signal) => dataPlaneFetch({
328
800
  url: "/db/{dbBranchName}/tables/{tableName}",
329
801
  method: "delete",
330
- ...variables
331
- });
332
- const updateTable = (variables) => fetch$1({
333
- url: "/db/{dbBranchName}/tables/{tableName}",
334
- method: "patch",
335
- ...variables
802
+ ...variables,
803
+ signal
336
804
  });
337
- const getTableSchema = (variables) => fetch$1({
805
+ const updateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}", method: "patch", ...variables, signal });
806
+ const getTableSchema = (variables, signal) => dataPlaneFetch({
338
807
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
339
808
  method: "get",
340
- ...variables
809
+ ...variables,
810
+ signal
341
811
  });
342
- const setTableSchema = (variables) => fetch$1({
343
- url: "/db/{dbBranchName}/tables/{tableName}/schema",
344
- method: "put",
345
- ...variables
346
- });
347
- const getTableColumns = (variables) => fetch$1({
812
+ const setTableSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/schema", method: "put", ...variables, signal });
813
+ const getTableColumns = (variables, signal) => dataPlaneFetch({
348
814
  url: "/db/{dbBranchName}/tables/{tableName}/columns",
349
815
  method: "get",
350
- ...variables
351
- });
352
- const addTableColumn = (variables) => fetch$1({
353
- url: "/db/{dbBranchName}/tables/{tableName}/columns",
354
- method: "post",
355
- ...variables
816
+ ...variables,
817
+ signal
356
818
  });
357
- const getColumn = (variables) => fetch$1({
819
+ const addTableColumn = (variables, signal) => dataPlaneFetch(
820
+ { url: "/db/{dbBranchName}/tables/{tableName}/columns", method: "post", ...variables, signal }
821
+ );
822
+ const getColumn = (variables, signal) => dataPlaneFetch({
358
823
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
359
824
  method: "get",
360
- ...variables
825
+ ...variables,
826
+ signal
361
827
  });
362
- const deleteColumn = (variables) => fetch$1({
828
+ const updateColumn = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}", method: "patch", ...variables, signal });
829
+ const deleteColumn = (variables, signal) => dataPlaneFetch({
363
830
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
364
831
  method: "delete",
365
- ...variables
832
+ ...variables,
833
+ signal
366
834
  });
367
- const updateColumn = (variables) => fetch$1({
368
- url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
369
- method: "patch",
370
- ...variables
835
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
836
+ const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
837
+ const getFileItem = (variables, signal) => dataPlaneFetch({
838
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
839
+ method: "get",
840
+ ...variables,
841
+ signal
371
842
  });
372
- const insertRecord = (variables) => fetch$1({
373
- url: "/db/{dbBranchName}/tables/{tableName}/data",
374
- method: "post",
375
- ...variables
843
+ const putFileItem = (variables, signal) => dataPlaneFetch({
844
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
845
+ method: "put",
846
+ ...variables,
847
+ signal
376
848
  });
377
- const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
378
- const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
379
- const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
380
- const deleteRecord = (variables) => fetch$1({
381
- url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
849
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
850
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
851
+ method: "delete",
852
+ ...variables,
853
+ signal
854
+ });
855
+ const getFile = (variables, signal) => dataPlaneFetch({
856
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
857
+ method: "get",
858
+ ...variables,
859
+ signal
860
+ });
861
+ const putFile = (variables, signal) => dataPlaneFetch({
862
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
863
+ method: "put",
864
+ ...variables,
865
+ signal
866
+ });
867
+ const deleteFile = (variables, signal) => dataPlaneFetch({
868
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
382
869
  method: "delete",
383
- ...variables
870
+ ...variables,
871
+ signal
384
872
  });
385
- const getRecord = (variables) => fetch$1({
873
+ const getRecord = (variables, signal) => dataPlaneFetch({
386
874
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
387
875
  method: "get",
388
- ...variables
876
+ ...variables,
877
+ signal
389
878
  });
390
- const bulkInsertTableRecords = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables });
391
- const queryTable = (variables) => fetch$1({
879
+ const insertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables, signal });
880
+ const updateRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables, signal });
881
+ const upsertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables, signal });
882
+ const deleteRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "delete", ...variables, signal });
883
+ const bulkInsertTableRecords = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables, signal });
884
+ const queryTable = (variables, signal) => dataPlaneFetch({
392
885
  url: "/db/{dbBranchName}/tables/{tableName}/query",
393
886
  method: "post",
394
- ...variables
887
+ ...variables,
888
+ signal
889
+ });
890
+ const searchBranch = (variables, signal) => dataPlaneFetch({
891
+ url: "/db/{dbBranchName}/search",
892
+ method: "post",
893
+ ...variables,
894
+ signal
395
895
  });
396
- const searchTable = (variables) => fetch$1({
896
+ const searchTable = (variables, signal) => dataPlaneFetch({
397
897
  url: "/db/{dbBranchName}/tables/{tableName}/search",
398
898
  method: "post",
399
- ...variables
899
+ ...variables,
900
+ signal
400
901
  });
401
- const searchBranch = (variables) => fetch$1({
402
- url: "/db/{dbBranchName}/search",
902
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
903
+ url: "/db/{dbBranchName}/sql",
403
904
  method: "post",
404
- ...variables
905
+ ...variables,
906
+ signal
405
907
  });
406
- const operationsByTag = {
407
- users: { getUser, updateUser, deleteUser, getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
408
- workspaces: {
409
- createWorkspace,
410
- getWorkspacesList,
411
- getWorkspace,
412
- updateWorkspace,
413
- deleteWorkspace,
414
- getWorkspaceMembersList,
415
- updateWorkspaceMemberRole,
416
- removeWorkspaceMember,
417
- inviteWorkspaceMember,
418
- cancelWorkspaceMemberInvite,
419
- resendWorkspaceMemberInvite,
420
- acceptWorkspaceMemberInvite
421
- },
422
- database: {
423
- getDatabaseList,
424
- createDatabase,
425
- deleteDatabase,
426
- getGitBranchesMapping,
427
- addGitBranchesEntry,
428
- removeGitBranchesEntry,
429
- resolveBranch
430
- },
908
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
909
+ const askTable = (variables, signal) => dataPlaneFetch({
910
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
911
+ method: "post",
912
+ ...variables,
913
+ signal
914
+ });
915
+ const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
916
+ const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
917
+ const fileAccess = (variables, signal) => dataPlaneFetch({
918
+ url: "/file/{fileId}",
919
+ method: "get",
920
+ ...variables,
921
+ signal
922
+ });
923
+ const operationsByTag$2 = {
431
924
  branch: {
432
925
  getBranchList,
433
926
  getBranchDetails,
434
927
  createBranch,
435
928
  deleteBranch,
929
+ copyBranch,
436
930
  updateBranchMetadata,
437
931
  getBranchMetadata,
932
+ getBranchStats,
933
+ getGitBranchesMapping,
934
+ addGitBranchesEntry,
935
+ removeGitBranchesEntry,
936
+ resolveBranch
937
+ },
938
+ migrations: {
438
939
  getBranchMigrationHistory,
439
- executeBranchMigrationPlan,
440
940
  getBranchMigrationPlan,
441
- getBranchStats
941
+ executeBranchMigrationPlan,
942
+ getBranchSchemaHistory,
943
+ compareBranchWithUserSchema,
944
+ compareBranchSchemas,
945
+ updateBranchSchema,
946
+ previewBranchSchemaEdit,
947
+ applyBranchSchemaEdit,
948
+ pushBranchMigrations
949
+ },
950
+ migrationRequests: {
951
+ queryMigrationRequests,
952
+ createMigrationRequest,
953
+ getMigrationRequest,
954
+ updateMigrationRequest,
955
+ listMigrationRequestsCommits,
956
+ compareMigrationRequest,
957
+ getMigrationRequestIsMerged,
958
+ mergeMigrationRequest
442
959
  },
443
960
  table: {
444
961
  createTable,
@@ -449,27 +966,178 @@ const operationsByTag = {
449
966
  getTableColumns,
450
967
  addTableColumn,
451
968
  getColumn,
452
- deleteColumn,
453
- updateColumn
969
+ updateColumn,
970
+ deleteColumn
454
971
  },
455
972
  records: {
973
+ branchTransaction,
456
974
  insertRecord,
975
+ getRecord,
457
976
  insertRecordWithID,
458
977
  updateRecordWithID,
459
978
  upsertRecordWithID,
460
979
  deleteRecord,
461
- getRecord,
462
- bulkInsertTableRecords,
980
+ bulkInsertTableRecords
981
+ },
982
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess },
983
+ searchAndFilter: {
463
984
  queryTable,
985
+ searchBranch,
464
986
  searchTable,
465
- searchBranch
987
+ sqlQuery,
988
+ vectorSearchTable,
989
+ askTable,
990
+ summarizeTable,
991
+ aggregateTable
466
992
  }
467
993
  };
468
994
 
995
+ const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
996
+
997
+ const getUser = (variables, signal) => controlPlaneFetch({
998
+ url: "/user",
999
+ method: "get",
1000
+ ...variables,
1001
+ signal
1002
+ });
1003
+ const updateUser = (variables, signal) => controlPlaneFetch({
1004
+ url: "/user",
1005
+ method: "put",
1006
+ ...variables,
1007
+ signal
1008
+ });
1009
+ const deleteUser = (variables, signal) => controlPlaneFetch({
1010
+ url: "/user",
1011
+ method: "delete",
1012
+ ...variables,
1013
+ signal
1014
+ });
1015
+ const getUserAPIKeys = (variables, signal) => controlPlaneFetch({
1016
+ url: "/user/keys",
1017
+ method: "get",
1018
+ ...variables,
1019
+ signal
1020
+ });
1021
+ const createUserAPIKey = (variables, signal) => controlPlaneFetch({
1022
+ url: "/user/keys/{keyName}",
1023
+ method: "post",
1024
+ ...variables,
1025
+ signal
1026
+ });
1027
+ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
1028
+ url: "/user/keys/{keyName}",
1029
+ method: "delete",
1030
+ ...variables,
1031
+ signal
1032
+ });
1033
+ const getWorkspacesList = (variables, signal) => controlPlaneFetch({
1034
+ url: "/workspaces",
1035
+ method: "get",
1036
+ ...variables,
1037
+ signal
1038
+ });
1039
+ const createWorkspace = (variables, signal) => controlPlaneFetch({
1040
+ url: "/workspaces",
1041
+ method: "post",
1042
+ ...variables,
1043
+ signal
1044
+ });
1045
+ const getWorkspace = (variables, signal) => controlPlaneFetch({
1046
+ url: "/workspaces/{workspaceId}",
1047
+ method: "get",
1048
+ ...variables,
1049
+ signal
1050
+ });
1051
+ const updateWorkspace = (variables, signal) => controlPlaneFetch({
1052
+ url: "/workspaces/{workspaceId}",
1053
+ method: "put",
1054
+ ...variables,
1055
+ signal
1056
+ });
1057
+ const deleteWorkspace = (variables, signal) => controlPlaneFetch({
1058
+ url: "/workspaces/{workspaceId}",
1059
+ method: "delete",
1060
+ ...variables,
1061
+ signal
1062
+ });
1063
+ const getWorkspaceMembersList = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/members", method: "get", ...variables, signal });
1064
+ const updateWorkspaceMemberRole = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables, signal });
1065
+ const removeWorkspaceMember = (variables, signal) => controlPlaneFetch({
1066
+ url: "/workspaces/{workspaceId}/members/{userId}",
1067
+ method: "delete",
1068
+ ...variables,
1069
+ signal
1070
+ });
1071
+ const inviteWorkspaceMember = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables, signal });
1072
+ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables, signal });
1073
+ const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
1074
+ const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
1075
+ const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1076
+ const getDatabaseList = (variables, signal) => controlPlaneFetch({
1077
+ url: "/workspaces/{workspaceId}/dbs",
1078
+ method: "get",
1079
+ ...variables,
1080
+ signal
1081
+ });
1082
+ const createDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables, signal });
1083
+ const deleteDatabase = (variables, signal) => controlPlaneFetch({
1084
+ url: "/workspaces/{workspaceId}/dbs/{dbName}",
1085
+ method: "delete",
1086
+ ...variables,
1087
+ signal
1088
+ });
1089
+ const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
1090
+ const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1091
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1092
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1093
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1094
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
1095
+ const listRegions = (variables, signal) => controlPlaneFetch({
1096
+ url: "/workspaces/{workspaceId}/regions",
1097
+ method: "get",
1098
+ ...variables,
1099
+ signal
1100
+ });
1101
+ const operationsByTag$1 = {
1102
+ users: { getUser, updateUser, deleteUser },
1103
+ authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
1104
+ workspaces: {
1105
+ getWorkspacesList,
1106
+ createWorkspace,
1107
+ getWorkspace,
1108
+ updateWorkspace,
1109
+ deleteWorkspace,
1110
+ getWorkspaceMembersList,
1111
+ updateWorkspaceMemberRole,
1112
+ removeWorkspaceMember
1113
+ },
1114
+ invites: {
1115
+ inviteWorkspaceMember,
1116
+ updateWorkspaceMemberInvite,
1117
+ cancelWorkspaceMemberInvite,
1118
+ acceptWorkspaceMemberInvite,
1119
+ resendWorkspaceMemberInvite
1120
+ },
1121
+ databases: {
1122
+ getDatabaseList,
1123
+ createDatabase,
1124
+ deleteDatabase,
1125
+ getDatabaseMetadata,
1126
+ updateDatabaseMetadata,
1127
+ renameDatabase,
1128
+ getDatabaseGithubSettings,
1129
+ updateDatabaseGithubSettings,
1130
+ deleteDatabaseGithubSettings,
1131
+ listRegions
1132
+ }
1133
+ };
1134
+
1135
+ const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);
1136
+
469
1137
  function getHostUrl(provider, type) {
470
- if (isValidAlias(provider)) {
1138
+ if (isHostProviderAlias(provider)) {
471
1139
  return providers[provider][type];
472
- } else if (isValidBuilder(provider)) {
1140
+ } else if (isHostProviderBuilder(provider)) {
473
1141
  return provider[type];
474
1142
  }
475
1143
  throw new Error("Invalid API provider");
@@ -477,19 +1145,49 @@ function getHostUrl(provider, type) {
477
1145
  const providers = {
478
1146
  production: {
479
1147
  main: "https://api.xata.io",
480
- workspaces: "https://{workspaceId}.xata.sh"
1148
+ workspaces: "https://{workspaceId}.{region}.xata.sh"
481
1149
  },
482
1150
  staging: {
483
- main: "https://staging.xatabase.co",
484
- workspaces: "https://{workspaceId}.staging.xatabase.co"
1151
+ main: "https://api.staging-xata.dev",
1152
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1153
+ },
1154
+ dev: {
1155
+ main: "https://api.dev-xata.dev",
1156
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
485
1157
  }
486
1158
  };
487
- function isValidAlias(alias) {
1159
+ function isHostProviderAlias(alias) {
488
1160
  return isString(alias) && Object.keys(providers).includes(alias);
489
1161
  }
490
- function isValidBuilder(builder) {
1162
+ function isHostProviderBuilder(builder) {
491
1163
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
492
1164
  }
1165
+ function parseProviderString(provider = "production") {
1166
+ if (isHostProviderAlias(provider)) {
1167
+ return provider;
1168
+ }
1169
+ const [main, workspaces] = provider.split(",");
1170
+ if (!main || !workspaces)
1171
+ return null;
1172
+ return { main, workspaces };
1173
+ }
1174
+ function buildProviderString(provider) {
1175
+ if (isHostProviderAlias(provider))
1176
+ return provider;
1177
+ return `${provider.main},${provider.workspaces}`;
1178
+ }
1179
+ function parseWorkspacesUrlParts(url) {
1180
+ if (!isString(url))
1181
+ return null;
1182
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
1183
+ const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1184
+ const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1185
+ const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1186
+ const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
1187
+ if (!match)
1188
+ return null;
1189
+ return { workspace: match[1], region: match[2] };
1190
+ }
493
1191
 
494
1192
  var __accessCheck$7 = (obj, member, msg) => {
495
1193
  if (!member.has(obj))
@@ -515,15 +1213,21 @@ class XataApiClient {
515
1213
  __privateAdd$7(this, _extraProps, void 0);
516
1214
  __privateAdd$7(this, _namespaces, {});
517
1215
  const provider = options.host ?? "production";
518
- const apiKey = options?.apiKey ?? getAPIKey();
1216
+ const apiKey = options.apiKey ?? getAPIKey();
1217
+ const trace = options.trace ?? defaultTrace;
1218
+ const clientID = generateUUID();
519
1219
  if (!apiKey) {
520
1220
  throw new Error("Could not resolve a valid apiKey");
521
1221
  }
522
1222
  __privateSet$7(this, _extraProps, {
523
1223
  apiUrl: getHostUrl(provider, "main"),
524
1224
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
525
- fetchImpl: getFetchImplementation(options.fetch),
526
- apiKey
1225
+ fetch: getFetchImplementation(options.fetch),
1226
+ apiKey,
1227
+ trace,
1228
+ clientName: options.clientName,
1229
+ xataAgentExtra: options.xataAgentExtra,
1230
+ clientID
527
1231
  });
528
1232
  }
529
1233
  get user() {
@@ -531,21 +1235,41 @@ class XataApiClient {
531
1235
  __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
532
1236
  return __privateGet$7(this, _namespaces).user;
533
1237
  }
1238
+ get authentication() {
1239
+ if (!__privateGet$7(this, _namespaces).authentication)
1240
+ __privateGet$7(this, _namespaces).authentication = new AuthenticationApi(__privateGet$7(this, _extraProps));
1241
+ return __privateGet$7(this, _namespaces).authentication;
1242
+ }
534
1243
  get workspaces() {
535
1244
  if (!__privateGet$7(this, _namespaces).workspaces)
536
1245
  __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
537
1246
  return __privateGet$7(this, _namespaces).workspaces;
538
1247
  }
539
- get databases() {
540
- if (!__privateGet$7(this, _namespaces).databases)
541
- __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
542
- return __privateGet$7(this, _namespaces).databases;
1248
+ get invites() {
1249
+ if (!__privateGet$7(this, _namespaces).invites)
1250
+ __privateGet$7(this, _namespaces).invites = new InvitesApi(__privateGet$7(this, _extraProps));
1251
+ return __privateGet$7(this, _namespaces).invites;
1252
+ }
1253
+ get database() {
1254
+ if (!__privateGet$7(this, _namespaces).database)
1255
+ __privateGet$7(this, _namespaces).database = new DatabaseApi(__privateGet$7(this, _extraProps));
1256
+ return __privateGet$7(this, _namespaces).database;
543
1257
  }
544
1258
  get branches() {
545
1259
  if (!__privateGet$7(this, _namespaces).branches)
546
1260
  __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
547
1261
  return __privateGet$7(this, _namespaces).branches;
548
1262
  }
1263
+ get migrations() {
1264
+ if (!__privateGet$7(this, _namespaces).migrations)
1265
+ __privateGet$7(this, _namespaces).migrations = new MigrationsApi(__privateGet$7(this, _extraProps));
1266
+ return __privateGet$7(this, _namespaces).migrations;
1267
+ }
1268
+ get migrationRequests() {
1269
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
1270
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
1271
+ return __privateGet$7(this, _namespaces).migrationRequests;
1272
+ }
549
1273
  get tables() {
550
1274
  if (!__privateGet$7(this, _namespaces).tables)
551
1275
  __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
@@ -556,6 +1280,16 @@ class XataApiClient {
556
1280
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
557
1281
  return __privateGet$7(this, _namespaces).records;
558
1282
  }
1283
+ get files() {
1284
+ if (!__privateGet$7(this, _namespaces).files)
1285
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1286
+ return __privateGet$7(this, _namespaces).files;
1287
+ }
1288
+ get searchAndFilter() {
1289
+ if (!__privateGet$7(this, _namespaces).searchAndFilter)
1290
+ __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
1291
+ return __privateGet$7(this, _namespaces).searchAndFilter;
1292
+ }
559
1293
  }
560
1294
  _extraProps = new WeakMap();
561
1295
  _namespaces = new WeakMap();
@@ -566,24 +1300,29 @@ class UserApi {
566
1300
  getUser() {
567
1301
  return operationsByTag.users.getUser({ ...this.extraProps });
568
1302
  }
569
- updateUser(user) {
1303
+ updateUser({ user }) {
570
1304
  return operationsByTag.users.updateUser({ body: user, ...this.extraProps });
571
1305
  }
572
1306
  deleteUser() {
573
1307
  return operationsByTag.users.deleteUser({ ...this.extraProps });
574
1308
  }
1309
+ }
1310
+ class AuthenticationApi {
1311
+ constructor(extraProps) {
1312
+ this.extraProps = extraProps;
1313
+ }
575
1314
  getUserAPIKeys() {
576
- return operationsByTag.users.getUserAPIKeys({ ...this.extraProps });
1315
+ return operationsByTag.authentication.getUserAPIKeys({ ...this.extraProps });
577
1316
  }
578
- createUserAPIKey(keyName) {
579
- return operationsByTag.users.createUserAPIKey({
580
- pathParams: { keyName },
1317
+ createUserAPIKey({ name }) {
1318
+ return operationsByTag.authentication.createUserAPIKey({
1319
+ pathParams: { keyName: name },
581
1320
  ...this.extraProps
582
1321
  });
583
1322
  }
584
- deleteUserAPIKey(keyName) {
585
- return operationsByTag.users.deleteUserAPIKey({
586
- pathParams: { keyName },
1323
+ deleteUserAPIKey({ name }) {
1324
+ return operationsByTag.authentication.deleteUserAPIKey({
1325
+ pathParams: { keyName: name },
587
1326
  ...this.extraProps
588
1327
  });
589
1328
  }
@@ -592,126 +1331,114 @@ class WorkspaceApi {
592
1331
  constructor(extraProps) {
593
1332
  this.extraProps = extraProps;
594
1333
  }
595
- createWorkspace(workspaceMeta) {
1334
+ getWorkspacesList() {
1335
+ return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
1336
+ }
1337
+ createWorkspace({ data }) {
596
1338
  return operationsByTag.workspaces.createWorkspace({
597
- body: workspaceMeta,
1339
+ body: data,
598
1340
  ...this.extraProps
599
1341
  });
600
1342
  }
601
- getWorkspacesList() {
602
- return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
603
- }
604
- getWorkspace(workspaceId) {
1343
+ getWorkspace({ workspace }) {
605
1344
  return operationsByTag.workspaces.getWorkspace({
606
- pathParams: { workspaceId },
1345
+ pathParams: { workspaceId: workspace },
607
1346
  ...this.extraProps
608
1347
  });
609
1348
  }
610
- updateWorkspace(workspaceId, workspaceMeta) {
1349
+ updateWorkspace({
1350
+ workspace,
1351
+ update
1352
+ }) {
611
1353
  return operationsByTag.workspaces.updateWorkspace({
612
- pathParams: { workspaceId },
613
- body: workspaceMeta,
1354
+ pathParams: { workspaceId: workspace },
1355
+ body: update,
614
1356
  ...this.extraProps
615
1357
  });
616
1358
  }
617
- deleteWorkspace(workspaceId) {
1359
+ deleteWorkspace({ workspace }) {
618
1360
  return operationsByTag.workspaces.deleteWorkspace({
619
- pathParams: { workspaceId },
1361
+ pathParams: { workspaceId: workspace },
620
1362
  ...this.extraProps
621
1363
  });
622
1364
  }
623
- getWorkspaceMembersList(workspaceId) {
1365
+ getWorkspaceMembersList({ workspace }) {
624
1366
  return operationsByTag.workspaces.getWorkspaceMembersList({
625
- pathParams: { workspaceId },
1367
+ pathParams: { workspaceId: workspace },
626
1368
  ...this.extraProps
627
1369
  });
628
1370
  }
629
- updateWorkspaceMemberRole(workspaceId, userId, role) {
1371
+ updateWorkspaceMemberRole({
1372
+ workspace,
1373
+ user,
1374
+ role
1375
+ }) {
630
1376
  return operationsByTag.workspaces.updateWorkspaceMemberRole({
631
- pathParams: { workspaceId, userId },
1377
+ pathParams: { workspaceId: workspace, userId: user },
632
1378
  body: { role },
633
1379
  ...this.extraProps
634
1380
  });
635
1381
  }
636
- removeWorkspaceMember(workspaceId, userId) {
1382
+ removeWorkspaceMember({
1383
+ workspace,
1384
+ user
1385
+ }) {
637
1386
  return operationsByTag.workspaces.removeWorkspaceMember({
638
- pathParams: { workspaceId, userId },
639
- ...this.extraProps
640
- });
641
- }
642
- inviteWorkspaceMember(workspaceId, email, role) {
643
- return operationsByTag.workspaces.inviteWorkspaceMember({
644
- pathParams: { workspaceId },
645
- body: { email, role },
646
- ...this.extraProps
647
- });
648
- }
649
- cancelWorkspaceMemberInvite(workspaceId, inviteId) {
650
- return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
651
- pathParams: { workspaceId, inviteId },
652
- ...this.extraProps
653
- });
654
- }
655
- resendWorkspaceMemberInvite(workspaceId, inviteId) {
656
- return operationsByTag.workspaces.resendWorkspaceMemberInvite({
657
- pathParams: { workspaceId, inviteId },
658
- ...this.extraProps
659
- });
660
- }
661
- acceptWorkspaceMemberInvite(workspaceId, inviteKey) {
662
- return operationsByTag.workspaces.acceptWorkspaceMemberInvite({
663
- pathParams: { workspaceId, inviteKey },
1387
+ pathParams: { workspaceId: workspace, userId: user },
664
1388
  ...this.extraProps
665
1389
  });
666
1390
  }
667
1391
  }
668
- class DatabaseApi {
1392
+ class InvitesApi {
669
1393
  constructor(extraProps) {
670
1394
  this.extraProps = extraProps;
671
1395
  }
672
- getDatabaseList(workspace) {
673
- return operationsByTag.database.getDatabaseList({
674
- pathParams: { workspace },
675
- ...this.extraProps
676
- });
677
- }
678
- createDatabase(workspace, dbName, options = {}) {
679
- return operationsByTag.database.createDatabase({
680
- pathParams: { workspace, dbName },
681
- body: options,
682
- ...this.extraProps
683
- });
684
- }
685
- deleteDatabase(workspace, dbName) {
686
- return operationsByTag.database.deleteDatabase({
687
- pathParams: { workspace, dbName },
1396
+ inviteWorkspaceMember({
1397
+ workspace,
1398
+ email,
1399
+ role
1400
+ }) {
1401
+ return operationsByTag.invites.inviteWorkspaceMember({
1402
+ pathParams: { workspaceId: workspace },
1403
+ body: { email, role },
688
1404
  ...this.extraProps
689
1405
  });
690
1406
  }
691
- getGitBranchesMapping(workspace, dbName) {
692
- return operationsByTag.database.getGitBranchesMapping({
693
- pathParams: { workspace, dbName },
1407
+ updateWorkspaceMemberInvite({
1408
+ workspace,
1409
+ invite,
1410
+ role
1411
+ }) {
1412
+ return operationsByTag.invites.updateWorkspaceMemberInvite({
1413
+ pathParams: { workspaceId: workspace, inviteId: invite },
1414
+ body: { role },
694
1415
  ...this.extraProps
695
1416
  });
696
1417
  }
697
- addGitBranchesEntry(workspace, dbName, body) {
698
- return operationsByTag.database.addGitBranchesEntry({
699
- pathParams: { workspace, dbName },
700
- body,
1418
+ cancelWorkspaceMemberInvite({
1419
+ workspace,
1420
+ invite
1421
+ }) {
1422
+ return operationsByTag.invites.cancelWorkspaceMemberInvite({
1423
+ pathParams: { workspaceId: workspace, inviteId: invite },
701
1424
  ...this.extraProps
702
1425
  });
703
1426
  }
704
- removeGitBranchesEntry(workspace, dbName, gitBranch) {
705
- return operationsByTag.database.removeGitBranchesEntry({
706
- pathParams: { workspace, dbName },
707
- queryParams: { gitBranch },
1427
+ acceptWorkspaceMemberInvite({
1428
+ workspace,
1429
+ key
1430
+ }) {
1431
+ return operationsByTag.invites.acceptWorkspaceMemberInvite({
1432
+ pathParams: { workspaceId: workspace, inviteKey: key },
708
1433
  ...this.extraProps
709
1434
  });
710
1435
  }
711
- resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
712
- return operationsByTag.database.resolveBranch({
713
- pathParams: { workspace, dbName },
714
- queryParams: { gitBranch, fallbackBranch },
1436
+ resendWorkspaceMemberInvite({
1437
+ workspace,
1438
+ invite
1439
+ }) {
1440
+ return operationsByTag.invites.resendWorkspaceMemberInvite({
1441
+ pathParams: { workspaceId: workspace, inviteId: invite },
715
1442
  ...this.extraProps
716
1443
  });
717
1444
  }
@@ -720,69 +1447,146 @@ class BranchApi {
720
1447
  constructor(extraProps) {
721
1448
  this.extraProps = extraProps;
722
1449
  }
723
- getBranchList(workspace, dbName) {
1450
+ getBranchList({
1451
+ workspace,
1452
+ region,
1453
+ database
1454
+ }) {
724
1455
  return operationsByTag.branch.getBranchList({
725
- pathParams: { workspace, dbName },
1456
+ pathParams: { workspace, region, dbName: database },
726
1457
  ...this.extraProps
727
1458
  });
728
1459
  }
729
- getBranchDetails(workspace, database, branch) {
1460
+ getBranchDetails({
1461
+ workspace,
1462
+ region,
1463
+ database,
1464
+ branch
1465
+ }) {
730
1466
  return operationsByTag.branch.getBranchDetails({
731
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1467
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
732
1468
  ...this.extraProps
733
1469
  });
734
1470
  }
735
- createBranch(workspace, database, branch, from, options = {}) {
1471
+ createBranch({
1472
+ workspace,
1473
+ region,
1474
+ database,
1475
+ branch,
1476
+ from,
1477
+ metadata
1478
+ }) {
736
1479
  return operationsByTag.branch.createBranch({
737
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
738
- queryParams: isString(from) ? { from } : void 0,
739
- body: options,
1480
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1481
+ body: { from, metadata },
740
1482
  ...this.extraProps
741
1483
  });
742
1484
  }
743
- deleteBranch(workspace, database, branch) {
1485
+ deleteBranch({
1486
+ workspace,
1487
+ region,
1488
+ database,
1489
+ branch
1490
+ }) {
744
1491
  return operationsByTag.branch.deleteBranch({
745
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1492
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
746
1493
  ...this.extraProps
747
1494
  });
748
1495
  }
749
- updateBranchMetadata(workspace, database, branch, metadata = {}) {
1496
+ copyBranch({
1497
+ workspace,
1498
+ region,
1499
+ database,
1500
+ branch,
1501
+ destinationBranch,
1502
+ limit
1503
+ }) {
1504
+ return operationsByTag.branch.copyBranch({
1505
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1506
+ body: { destinationBranch, limit },
1507
+ ...this.extraProps
1508
+ });
1509
+ }
1510
+ updateBranchMetadata({
1511
+ workspace,
1512
+ region,
1513
+ database,
1514
+ branch,
1515
+ metadata
1516
+ }) {
750
1517
  return operationsByTag.branch.updateBranchMetadata({
751
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1518
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
752
1519
  body: metadata,
753
1520
  ...this.extraProps
754
1521
  });
755
1522
  }
756
- getBranchMetadata(workspace, database, branch) {
1523
+ getBranchMetadata({
1524
+ workspace,
1525
+ region,
1526
+ database,
1527
+ branch
1528
+ }) {
757
1529
  return operationsByTag.branch.getBranchMetadata({
758
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1530
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
759
1531
  ...this.extraProps
760
1532
  });
761
1533
  }
762
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
763
- return operationsByTag.branch.getBranchMigrationHistory({
764
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
765
- body: options,
1534
+ getBranchStats({
1535
+ workspace,
1536
+ region,
1537
+ database,
1538
+ branch
1539
+ }) {
1540
+ return operationsByTag.branch.getBranchStats({
1541
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
766
1542
  ...this.extraProps
767
1543
  });
768
1544
  }
769
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
770
- return operationsByTag.branch.executeBranchMigrationPlan({
771
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
772
- body: migrationPlan,
1545
+ getGitBranchesMapping({
1546
+ workspace,
1547
+ region,
1548
+ database
1549
+ }) {
1550
+ return operationsByTag.branch.getGitBranchesMapping({
1551
+ pathParams: { workspace, region, dbName: database },
773
1552
  ...this.extraProps
774
1553
  });
775
1554
  }
776
- getBranchMigrationPlan(workspace, database, branch, schema) {
777
- return operationsByTag.branch.getBranchMigrationPlan({
778
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
779
- body: schema,
1555
+ addGitBranchesEntry({
1556
+ workspace,
1557
+ region,
1558
+ database,
1559
+ gitBranch,
1560
+ xataBranch
1561
+ }) {
1562
+ return operationsByTag.branch.addGitBranchesEntry({
1563
+ pathParams: { workspace, region, dbName: database },
1564
+ body: { gitBranch, xataBranch },
780
1565
  ...this.extraProps
781
1566
  });
782
1567
  }
783
- getBranchStats(workspace, database, branch) {
784
- return operationsByTag.branch.getBranchStats({
785
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1568
+ removeGitBranchesEntry({
1569
+ workspace,
1570
+ region,
1571
+ database,
1572
+ gitBranch
1573
+ }) {
1574
+ return operationsByTag.branch.removeGitBranchesEntry({
1575
+ pathParams: { workspace, region, dbName: database },
1576
+ queryParams: { gitBranch },
1577
+ ...this.extraProps
1578
+ });
1579
+ }
1580
+ resolveBranch({
1581
+ workspace,
1582
+ region,
1583
+ database,
1584
+ gitBranch,
1585
+ fallbackBranch
1586
+ }) {
1587
+ return operationsByTag.branch.resolveBranch({
1588
+ pathParams: { workspace, region, dbName: database },
1589
+ queryParams: { gitBranch, fallbackBranch },
786
1590
  ...this.extraProps
787
1591
  });
788
1592
  }
@@ -791,67 +1595,134 @@ class TableApi {
791
1595
  constructor(extraProps) {
792
1596
  this.extraProps = extraProps;
793
1597
  }
794
- createTable(workspace, database, branch, tableName) {
1598
+ createTable({
1599
+ workspace,
1600
+ region,
1601
+ database,
1602
+ branch,
1603
+ table
1604
+ }) {
795
1605
  return operationsByTag.table.createTable({
796
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1606
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
797
1607
  ...this.extraProps
798
1608
  });
799
1609
  }
800
- deleteTable(workspace, database, branch, tableName) {
1610
+ deleteTable({
1611
+ workspace,
1612
+ region,
1613
+ database,
1614
+ branch,
1615
+ table
1616
+ }) {
801
1617
  return operationsByTag.table.deleteTable({
802
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1618
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
803
1619
  ...this.extraProps
804
1620
  });
805
1621
  }
806
- updateTable(workspace, database, branch, tableName, options) {
1622
+ updateTable({
1623
+ workspace,
1624
+ region,
1625
+ database,
1626
+ branch,
1627
+ table,
1628
+ update
1629
+ }) {
807
1630
  return operationsByTag.table.updateTable({
808
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
809
- body: options,
1631
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1632
+ body: update,
810
1633
  ...this.extraProps
811
1634
  });
812
1635
  }
813
- getTableSchema(workspace, database, branch, tableName) {
1636
+ getTableSchema({
1637
+ workspace,
1638
+ region,
1639
+ database,
1640
+ branch,
1641
+ table
1642
+ }) {
814
1643
  return operationsByTag.table.getTableSchema({
815
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1644
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
816
1645
  ...this.extraProps
817
1646
  });
818
1647
  }
819
- setTableSchema(workspace, database, branch, tableName, options) {
1648
+ setTableSchema({
1649
+ workspace,
1650
+ region,
1651
+ database,
1652
+ branch,
1653
+ table,
1654
+ schema
1655
+ }) {
820
1656
  return operationsByTag.table.setTableSchema({
821
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
822
- body: options,
1657
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1658
+ body: schema,
823
1659
  ...this.extraProps
824
1660
  });
825
1661
  }
826
- getTableColumns(workspace, database, branch, tableName) {
1662
+ getTableColumns({
1663
+ workspace,
1664
+ region,
1665
+ database,
1666
+ branch,
1667
+ table
1668
+ }) {
827
1669
  return operationsByTag.table.getTableColumns({
828
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1670
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
829
1671
  ...this.extraProps
830
1672
  });
831
1673
  }
832
- addTableColumn(workspace, database, branch, tableName, column) {
1674
+ addTableColumn({
1675
+ workspace,
1676
+ region,
1677
+ database,
1678
+ branch,
1679
+ table,
1680
+ column
1681
+ }) {
833
1682
  return operationsByTag.table.addTableColumn({
834
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1683
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
835
1684
  body: column,
836
1685
  ...this.extraProps
837
1686
  });
838
1687
  }
839
- getColumn(workspace, database, branch, tableName, columnName) {
1688
+ getColumn({
1689
+ workspace,
1690
+ region,
1691
+ database,
1692
+ branch,
1693
+ table,
1694
+ column
1695
+ }) {
840
1696
  return operationsByTag.table.getColumn({
841
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
1697
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
842
1698
  ...this.extraProps
843
1699
  });
844
1700
  }
845
- deleteColumn(workspace, database, branch, tableName, columnName) {
846
- return operationsByTag.table.deleteColumn({
847
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
1701
+ updateColumn({
1702
+ workspace,
1703
+ region,
1704
+ database,
1705
+ branch,
1706
+ table,
1707
+ column,
1708
+ update
1709
+ }) {
1710
+ return operationsByTag.table.updateColumn({
1711
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
1712
+ body: update,
848
1713
  ...this.extraProps
849
1714
  });
850
1715
  }
851
- updateColumn(workspace, database, branch, tableName, columnName, options) {
852
- return operationsByTag.table.updateColumn({
853
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
854
- body: options,
1716
+ deleteColumn({
1717
+ workspace,
1718
+ region,
1719
+ database,
1720
+ branch,
1721
+ table,
1722
+ column
1723
+ }) {
1724
+ return operationsByTag.table.deleteColumn({
1725
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
855
1726
  ...this.extraProps
856
1727
  });
857
1728
  }
@@ -860,89 +1731,778 @@ class RecordsApi {
860
1731
  constructor(extraProps) {
861
1732
  this.extraProps = extraProps;
862
1733
  }
863
- insertRecord(workspace, database, branch, tableName, record) {
1734
+ insertRecord({
1735
+ workspace,
1736
+ region,
1737
+ database,
1738
+ branch,
1739
+ table,
1740
+ record,
1741
+ columns
1742
+ }) {
864
1743
  return operationsByTag.records.insertRecord({
865
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1744
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1745
+ queryParams: { columns },
1746
+ body: record,
1747
+ ...this.extraProps
1748
+ });
1749
+ }
1750
+ getRecord({
1751
+ workspace,
1752
+ region,
1753
+ database,
1754
+ branch,
1755
+ table,
1756
+ id,
1757
+ columns
1758
+ }) {
1759
+ return operationsByTag.records.getRecord({
1760
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1761
+ queryParams: { columns },
1762
+ ...this.extraProps
1763
+ });
1764
+ }
1765
+ insertRecordWithID({
1766
+ workspace,
1767
+ region,
1768
+ database,
1769
+ branch,
1770
+ table,
1771
+ id,
1772
+ record,
1773
+ columns,
1774
+ createOnly,
1775
+ ifVersion
1776
+ }) {
1777
+ return operationsByTag.records.insertRecordWithID({
1778
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1779
+ queryParams: { columns, createOnly, ifVersion },
1780
+ body: record,
1781
+ ...this.extraProps
1782
+ });
1783
+ }
1784
+ updateRecordWithID({
1785
+ workspace,
1786
+ region,
1787
+ database,
1788
+ branch,
1789
+ table,
1790
+ id,
1791
+ record,
1792
+ columns,
1793
+ ifVersion
1794
+ }) {
1795
+ return operationsByTag.records.updateRecordWithID({
1796
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1797
+ queryParams: { columns, ifVersion },
1798
+ body: record,
1799
+ ...this.extraProps
1800
+ });
1801
+ }
1802
+ upsertRecordWithID({
1803
+ workspace,
1804
+ region,
1805
+ database,
1806
+ branch,
1807
+ table,
1808
+ id,
1809
+ record,
1810
+ columns,
1811
+ ifVersion
1812
+ }) {
1813
+ return operationsByTag.records.upsertRecordWithID({
1814
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1815
+ queryParams: { columns, ifVersion },
866
1816
  body: record,
867
1817
  ...this.extraProps
868
1818
  });
869
1819
  }
870
- insertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
871
- return operationsByTag.records.insertRecordWithID({
872
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
873
- queryParams: options,
874
- body: record,
1820
+ deleteRecord({
1821
+ workspace,
1822
+ region,
1823
+ database,
1824
+ branch,
1825
+ table,
1826
+ id,
1827
+ columns
1828
+ }) {
1829
+ return operationsByTag.records.deleteRecord({
1830
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1831
+ queryParams: { columns },
1832
+ ...this.extraProps
1833
+ });
1834
+ }
1835
+ bulkInsertTableRecords({
1836
+ workspace,
1837
+ region,
1838
+ database,
1839
+ branch,
1840
+ table,
1841
+ records,
1842
+ columns
1843
+ }) {
1844
+ return operationsByTag.records.bulkInsertTableRecords({
1845
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1846
+ queryParams: { columns },
1847
+ body: { records },
1848
+ ...this.extraProps
1849
+ });
1850
+ }
1851
+ branchTransaction({
1852
+ workspace,
1853
+ region,
1854
+ database,
1855
+ branch,
1856
+ operations
1857
+ }) {
1858
+ return operationsByTag.records.branchTransaction({
1859
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1860
+ body: { operations },
1861
+ ...this.extraProps
1862
+ });
1863
+ }
1864
+ }
1865
+ class FilesApi {
1866
+ constructor(extraProps) {
1867
+ this.extraProps = extraProps;
1868
+ }
1869
+ getFileItem({
1870
+ workspace,
1871
+ region,
1872
+ database,
1873
+ branch,
1874
+ table,
1875
+ record,
1876
+ column,
1877
+ fileId
1878
+ }) {
1879
+ return operationsByTag.files.getFileItem({
1880
+ pathParams: {
1881
+ workspace,
1882
+ region,
1883
+ dbBranchName: `${database}:${branch}`,
1884
+ tableName: table,
1885
+ recordId: record,
1886
+ columnName: column,
1887
+ fileId
1888
+ },
1889
+ ...this.extraProps
1890
+ });
1891
+ }
1892
+ putFileItem({
1893
+ workspace,
1894
+ region,
1895
+ database,
1896
+ branch,
1897
+ table,
1898
+ record,
1899
+ column,
1900
+ fileId,
1901
+ file
1902
+ }) {
1903
+ return operationsByTag.files.putFileItem({
1904
+ pathParams: {
1905
+ workspace,
1906
+ region,
1907
+ dbBranchName: `${database}:${branch}`,
1908
+ tableName: table,
1909
+ recordId: record,
1910
+ columnName: column,
1911
+ fileId
1912
+ },
1913
+ // @ts-ignore
1914
+ body: file,
1915
+ ...this.extraProps
1916
+ });
1917
+ }
1918
+ deleteFileItem({
1919
+ workspace,
1920
+ region,
1921
+ database,
1922
+ branch,
1923
+ table,
1924
+ record,
1925
+ column,
1926
+ fileId
1927
+ }) {
1928
+ return operationsByTag.files.deleteFileItem({
1929
+ pathParams: {
1930
+ workspace,
1931
+ region,
1932
+ dbBranchName: `${database}:${branch}`,
1933
+ tableName: table,
1934
+ recordId: record,
1935
+ columnName: column,
1936
+ fileId
1937
+ },
1938
+ ...this.extraProps
1939
+ });
1940
+ }
1941
+ getFile({
1942
+ workspace,
1943
+ region,
1944
+ database,
1945
+ branch,
1946
+ table,
1947
+ record,
1948
+ column
1949
+ }) {
1950
+ return operationsByTag.files.getFile({
1951
+ pathParams: {
1952
+ workspace,
1953
+ region,
1954
+ dbBranchName: `${database}:${branch}`,
1955
+ tableName: table,
1956
+ recordId: record,
1957
+ columnName: column
1958
+ },
1959
+ ...this.extraProps
1960
+ });
1961
+ }
1962
+ putFile({
1963
+ workspace,
1964
+ region,
1965
+ database,
1966
+ branch,
1967
+ table,
1968
+ record,
1969
+ column,
1970
+ file
1971
+ }) {
1972
+ return operationsByTag.files.putFile({
1973
+ pathParams: {
1974
+ workspace,
1975
+ region,
1976
+ dbBranchName: `${database}:${branch}`,
1977
+ tableName: table,
1978
+ recordId: record,
1979
+ columnName: column
1980
+ },
1981
+ body: file,
1982
+ ...this.extraProps
1983
+ });
1984
+ }
1985
+ deleteFile({
1986
+ workspace,
1987
+ region,
1988
+ database,
1989
+ branch,
1990
+ table,
1991
+ record,
1992
+ column
1993
+ }) {
1994
+ return operationsByTag.files.deleteFile({
1995
+ pathParams: {
1996
+ workspace,
1997
+ region,
1998
+ dbBranchName: `${database}:${branch}`,
1999
+ tableName: table,
2000
+ recordId: record,
2001
+ columnName: column
2002
+ },
2003
+ ...this.extraProps
2004
+ });
2005
+ }
2006
+ fileAccess({
2007
+ workspace,
2008
+ region,
2009
+ fileId,
2010
+ verify
2011
+ }) {
2012
+ return operationsByTag.files.fileAccess({
2013
+ pathParams: {
2014
+ workspace,
2015
+ region,
2016
+ fileId
2017
+ },
2018
+ queryParams: { verify },
2019
+ ...this.extraProps
2020
+ });
2021
+ }
2022
+ }
2023
+ class SearchAndFilterApi {
2024
+ constructor(extraProps) {
2025
+ this.extraProps = extraProps;
2026
+ }
2027
+ queryTable({
2028
+ workspace,
2029
+ region,
2030
+ database,
2031
+ branch,
2032
+ table,
2033
+ filter,
2034
+ sort,
2035
+ page,
2036
+ columns,
2037
+ consistency
2038
+ }) {
2039
+ return operationsByTag.searchAndFilter.queryTable({
2040
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2041
+ body: { filter, sort, page, columns, consistency },
2042
+ ...this.extraProps
2043
+ });
2044
+ }
2045
+ searchTable({
2046
+ workspace,
2047
+ region,
2048
+ database,
2049
+ branch,
2050
+ table,
2051
+ query,
2052
+ fuzziness,
2053
+ target,
2054
+ prefix,
2055
+ filter,
2056
+ highlight,
2057
+ boosters
2058
+ }) {
2059
+ return operationsByTag.searchAndFilter.searchTable({
2060
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2061
+ body: { query, fuzziness, target, prefix, filter, highlight, boosters },
2062
+ ...this.extraProps
2063
+ });
2064
+ }
2065
+ searchBranch({
2066
+ workspace,
2067
+ region,
2068
+ database,
2069
+ branch,
2070
+ tables,
2071
+ query,
2072
+ fuzziness,
2073
+ prefix,
2074
+ highlight
2075
+ }) {
2076
+ return operationsByTag.searchAndFilter.searchBranch({
2077
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2078
+ body: { tables, query, fuzziness, prefix, highlight },
2079
+ ...this.extraProps
2080
+ });
2081
+ }
2082
+ vectorSearchTable({
2083
+ workspace,
2084
+ region,
2085
+ database,
2086
+ branch,
2087
+ table,
2088
+ queryVector,
2089
+ column,
2090
+ similarityFunction,
2091
+ size,
2092
+ filter
2093
+ }) {
2094
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2095
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2096
+ body: { queryVector, column, similarityFunction, size, filter },
2097
+ ...this.extraProps
2098
+ });
2099
+ }
2100
+ askTable({
2101
+ workspace,
2102
+ region,
2103
+ database,
2104
+ branch,
2105
+ table,
2106
+ options
2107
+ }) {
2108
+ return operationsByTag.searchAndFilter.askTable({
2109
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2110
+ body: { ...options },
2111
+ ...this.extraProps
2112
+ });
2113
+ }
2114
+ summarizeTable({
2115
+ workspace,
2116
+ region,
2117
+ database,
2118
+ branch,
2119
+ table,
2120
+ filter,
2121
+ columns,
2122
+ summaries,
2123
+ sort,
2124
+ summariesFilter,
2125
+ page,
2126
+ consistency
2127
+ }) {
2128
+ return operationsByTag.searchAndFilter.summarizeTable({
2129
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2130
+ body: { filter, columns, summaries, sort, summariesFilter, page, consistency },
2131
+ ...this.extraProps
2132
+ });
2133
+ }
2134
+ aggregateTable({
2135
+ workspace,
2136
+ region,
2137
+ database,
2138
+ branch,
2139
+ table,
2140
+ filter,
2141
+ aggs
2142
+ }) {
2143
+ return operationsByTag.searchAndFilter.aggregateTable({
2144
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2145
+ body: { filter, aggs },
2146
+ ...this.extraProps
2147
+ });
2148
+ }
2149
+ }
2150
+ class MigrationRequestsApi {
2151
+ constructor(extraProps) {
2152
+ this.extraProps = extraProps;
2153
+ }
2154
+ queryMigrationRequests({
2155
+ workspace,
2156
+ region,
2157
+ database,
2158
+ filter,
2159
+ sort,
2160
+ page,
2161
+ columns
2162
+ }) {
2163
+ return operationsByTag.migrationRequests.queryMigrationRequests({
2164
+ pathParams: { workspace, region, dbName: database },
2165
+ body: { filter, sort, page, columns },
2166
+ ...this.extraProps
2167
+ });
2168
+ }
2169
+ createMigrationRequest({
2170
+ workspace,
2171
+ region,
2172
+ database,
2173
+ migration
2174
+ }) {
2175
+ return operationsByTag.migrationRequests.createMigrationRequest({
2176
+ pathParams: { workspace, region, dbName: database },
2177
+ body: migration,
2178
+ ...this.extraProps
2179
+ });
2180
+ }
2181
+ getMigrationRequest({
2182
+ workspace,
2183
+ region,
2184
+ database,
2185
+ migrationRequest
2186
+ }) {
2187
+ return operationsByTag.migrationRequests.getMigrationRequest({
2188
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2189
+ ...this.extraProps
2190
+ });
2191
+ }
2192
+ updateMigrationRequest({
2193
+ workspace,
2194
+ region,
2195
+ database,
2196
+ migrationRequest,
2197
+ update
2198
+ }) {
2199
+ return operationsByTag.migrationRequests.updateMigrationRequest({
2200
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2201
+ body: update,
2202
+ ...this.extraProps
2203
+ });
2204
+ }
2205
+ listMigrationRequestsCommits({
2206
+ workspace,
2207
+ region,
2208
+ database,
2209
+ migrationRequest,
2210
+ page
2211
+ }) {
2212
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
2213
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2214
+ body: { page },
2215
+ ...this.extraProps
2216
+ });
2217
+ }
2218
+ compareMigrationRequest({
2219
+ workspace,
2220
+ region,
2221
+ database,
2222
+ migrationRequest
2223
+ }) {
2224
+ return operationsByTag.migrationRequests.compareMigrationRequest({
2225
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2226
+ ...this.extraProps
2227
+ });
2228
+ }
2229
+ getMigrationRequestIsMerged({
2230
+ workspace,
2231
+ region,
2232
+ database,
2233
+ migrationRequest
2234
+ }) {
2235
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
2236
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2237
+ ...this.extraProps
2238
+ });
2239
+ }
2240
+ mergeMigrationRequest({
2241
+ workspace,
2242
+ region,
2243
+ database,
2244
+ migrationRequest
2245
+ }) {
2246
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
2247
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2248
+ ...this.extraProps
2249
+ });
2250
+ }
2251
+ }
2252
+ class MigrationsApi {
2253
+ constructor(extraProps) {
2254
+ this.extraProps = extraProps;
2255
+ }
2256
+ getBranchMigrationHistory({
2257
+ workspace,
2258
+ region,
2259
+ database,
2260
+ branch,
2261
+ limit,
2262
+ startFrom
2263
+ }) {
2264
+ return operationsByTag.migrations.getBranchMigrationHistory({
2265
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2266
+ body: { limit, startFrom },
2267
+ ...this.extraProps
2268
+ });
2269
+ }
2270
+ getBranchMigrationPlan({
2271
+ workspace,
2272
+ region,
2273
+ database,
2274
+ branch,
2275
+ schema
2276
+ }) {
2277
+ return operationsByTag.migrations.getBranchMigrationPlan({
2278
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2279
+ body: schema,
2280
+ ...this.extraProps
2281
+ });
2282
+ }
2283
+ executeBranchMigrationPlan({
2284
+ workspace,
2285
+ region,
2286
+ database,
2287
+ branch,
2288
+ plan
2289
+ }) {
2290
+ return operationsByTag.migrations.executeBranchMigrationPlan({
2291
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2292
+ body: plan,
2293
+ ...this.extraProps
2294
+ });
2295
+ }
2296
+ getBranchSchemaHistory({
2297
+ workspace,
2298
+ region,
2299
+ database,
2300
+ branch,
2301
+ page
2302
+ }) {
2303
+ return operationsByTag.migrations.getBranchSchemaHistory({
2304
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2305
+ body: { page },
2306
+ ...this.extraProps
2307
+ });
2308
+ }
2309
+ compareBranchWithUserSchema({
2310
+ workspace,
2311
+ region,
2312
+ database,
2313
+ branch,
2314
+ schema,
2315
+ schemaOperations,
2316
+ branchOperations
2317
+ }) {
2318
+ return operationsByTag.migrations.compareBranchWithUserSchema({
2319
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2320
+ body: { schema, schemaOperations, branchOperations },
2321
+ ...this.extraProps
2322
+ });
2323
+ }
2324
+ compareBranchSchemas({
2325
+ workspace,
2326
+ region,
2327
+ database,
2328
+ branch,
2329
+ compare,
2330
+ sourceBranchOperations,
2331
+ targetBranchOperations
2332
+ }) {
2333
+ return operationsByTag.migrations.compareBranchSchemas({
2334
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
2335
+ body: { sourceBranchOperations, targetBranchOperations },
2336
+ ...this.extraProps
2337
+ });
2338
+ }
2339
+ updateBranchSchema({
2340
+ workspace,
2341
+ region,
2342
+ database,
2343
+ branch,
2344
+ migration
2345
+ }) {
2346
+ return operationsByTag.migrations.updateBranchSchema({
2347
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2348
+ body: migration,
2349
+ ...this.extraProps
2350
+ });
2351
+ }
2352
+ previewBranchSchemaEdit({
2353
+ workspace,
2354
+ region,
2355
+ database,
2356
+ branch,
2357
+ data
2358
+ }) {
2359
+ return operationsByTag.migrations.previewBranchSchemaEdit({
2360
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2361
+ body: data,
2362
+ ...this.extraProps
2363
+ });
2364
+ }
2365
+ applyBranchSchemaEdit({
2366
+ workspace,
2367
+ region,
2368
+ database,
2369
+ branch,
2370
+ edits
2371
+ }) {
2372
+ return operationsByTag.migrations.applyBranchSchemaEdit({
2373
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2374
+ body: { edits },
2375
+ ...this.extraProps
2376
+ });
2377
+ }
2378
+ pushBranchMigrations({
2379
+ workspace,
2380
+ region,
2381
+ database,
2382
+ branch,
2383
+ migrations
2384
+ }) {
2385
+ return operationsByTag.migrations.pushBranchMigrations({
2386
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2387
+ body: { migrations },
2388
+ ...this.extraProps
2389
+ });
2390
+ }
2391
+ }
2392
+ class DatabaseApi {
2393
+ constructor(extraProps) {
2394
+ this.extraProps = extraProps;
2395
+ }
2396
+ getDatabaseList({ workspace }) {
2397
+ return operationsByTag.databases.getDatabaseList({
2398
+ pathParams: { workspaceId: workspace },
2399
+ ...this.extraProps
2400
+ });
2401
+ }
2402
+ createDatabase({
2403
+ workspace,
2404
+ database,
2405
+ data
2406
+ }) {
2407
+ return operationsByTag.databases.createDatabase({
2408
+ pathParams: { workspaceId: workspace, dbName: database },
2409
+ body: data,
875
2410
  ...this.extraProps
876
2411
  });
877
2412
  }
878
- updateRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
879
- return operationsByTag.records.updateRecordWithID({
880
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
881
- queryParams: options,
882
- body: record,
2413
+ deleteDatabase({
2414
+ workspace,
2415
+ database
2416
+ }) {
2417
+ return operationsByTag.databases.deleteDatabase({
2418
+ pathParams: { workspaceId: workspace, dbName: database },
883
2419
  ...this.extraProps
884
2420
  });
885
2421
  }
886
- upsertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
887
- return operationsByTag.records.upsertRecordWithID({
888
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
889
- queryParams: options,
890
- body: record,
2422
+ getDatabaseMetadata({
2423
+ workspace,
2424
+ database
2425
+ }) {
2426
+ return operationsByTag.databases.getDatabaseMetadata({
2427
+ pathParams: { workspaceId: workspace, dbName: database },
891
2428
  ...this.extraProps
892
2429
  });
893
2430
  }
894
- deleteRecord(workspace, database, branch, tableName, recordId) {
895
- return operationsByTag.records.deleteRecord({
896
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
2431
+ updateDatabaseMetadata({
2432
+ workspace,
2433
+ database,
2434
+ metadata
2435
+ }) {
2436
+ return operationsByTag.databases.updateDatabaseMetadata({
2437
+ pathParams: { workspaceId: workspace, dbName: database },
2438
+ body: metadata,
897
2439
  ...this.extraProps
898
2440
  });
899
2441
  }
900
- getRecord(workspace, database, branch, tableName, recordId, options = {}) {
901
- return operationsByTag.records.getRecord({
902
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
2442
+ renameDatabase({
2443
+ workspace,
2444
+ database,
2445
+ newName
2446
+ }) {
2447
+ return operationsByTag.databases.renameDatabase({
2448
+ pathParams: { workspaceId: workspace, dbName: database },
2449
+ body: { newName },
903
2450
  ...this.extraProps
904
2451
  });
905
2452
  }
906
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
907
- return operationsByTag.records.bulkInsertTableRecords({
908
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
909
- body: { records },
2453
+ getDatabaseGithubSettings({
2454
+ workspace,
2455
+ database
2456
+ }) {
2457
+ return operationsByTag.databases.getDatabaseGithubSettings({
2458
+ pathParams: { workspaceId: workspace, dbName: database },
910
2459
  ...this.extraProps
911
2460
  });
912
2461
  }
913
- queryTable(workspace, database, branch, tableName, query) {
914
- return operationsByTag.records.queryTable({
915
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
916
- body: query,
2462
+ updateDatabaseGithubSettings({
2463
+ workspace,
2464
+ database,
2465
+ settings
2466
+ }) {
2467
+ return operationsByTag.databases.updateDatabaseGithubSettings({
2468
+ pathParams: { workspaceId: workspace, dbName: database },
2469
+ body: settings,
917
2470
  ...this.extraProps
918
2471
  });
919
2472
  }
920
- searchTable(workspace, database, branch, tableName, query) {
921
- return operationsByTag.records.searchTable({
922
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
923
- body: query,
2473
+ deleteDatabaseGithubSettings({
2474
+ workspace,
2475
+ database
2476
+ }) {
2477
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
2478
+ pathParams: { workspaceId: workspace, dbName: database },
924
2479
  ...this.extraProps
925
2480
  });
926
2481
  }
927
- searchBranch(workspace, database, branch, query) {
928
- return operationsByTag.records.searchBranch({
929
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
930
- body: query,
2482
+ listRegions({ workspace }) {
2483
+ return operationsByTag.databases.listRegions({
2484
+ pathParams: { workspaceId: workspace },
931
2485
  ...this.extraProps
932
2486
  });
933
2487
  }
934
2488
  }
935
2489
 
936
2490
  class XataApiPlugin {
937
- async build(options) {
938
- const { fetchImpl, apiKey } = await options.getFetchProps();
939
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2491
+ build(options) {
2492
+ return new XataApiClient(options);
940
2493
  }
941
2494
  }
942
2495
 
943
2496
  class XataPlugin {
944
2497
  }
945
2498
 
2499
+ function cleanFilter(filter) {
2500
+ if (!filter)
2501
+ return void 0;
2502
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
2503
+ return values.length > 0 ? filter : void 0;
2504
+ }
2505
+
946
2506
  var __accessCheck$6 = (obj, member, msg) => {
947
2507
  if (!member.has(obj))
948
2508
  throw TypeError("Cannot " + msg);
@@ -969,18 +2529,46 @@ class Page {
969
2529
  this.meta = meta;
970
2530
  this.records = new RecordArray(this, records);
971
2531
  }
2532
+ /**
2533
+ * Retrieves the next page of results.
2534
+ * @param size Maximum number of results to be retrieved.
2535
+ * @param offset Number of results to skip when retrieving the results.
2536
+ * @returns The next page or results.
2537
+ */
972
2538
  async nextPage(size, offset) {
973
2539
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
974
2540
  }
2541
+ /**
2542
+ * Retrieves the previous page of results.
2543
+ * @param size Maximum number of results to be retrieved.
2544
+ * @param offset Number of results to skip when retrieving the results.
2545
+ * @returns The previous page or results.
2546
+ */
975
2547
  async previousPage(size, offset) {
976
2548
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
977
2549
  }
978
- async firstPage(size, offset) {
979
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
980
- }
981
- async lastPage(size, offset) {
982
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
983
- }
2550
+ /**
2551
+ * Retrieves the start page of results.
2552
+ * @param size Maximum number of results to be retrieved.
2553
+ * @param offset Number of results to skip when retrieving the results.
2554
+ * @returns The start page or results.
2555
+ */
2556
+ async startPage(size, offset) {
2557
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
2558
+ }
2559
+ /**
2560
+ * Retrieves the end page of results.
2561
+ * @param size Maximum number of results to be retrieved.
2562
+ * @param offset Number of results to skip when retrieving the results.
2563
+ * @returns The end page or results.
2564
+ */
2565
+ async endPage(size, offset) {
2566
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
2567
+ }
2568
+ /**
2569
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
2570
+ * @returns Whether or not there will be additional results in the next page of results.
2571
+ */
984
2572
  hasNextPage() {
985
2573
  return this.meta.page.more;
986
2574
  }
@@ -991,13 +2579,13 @@ const PAGINATION_DEFAULT_SIZE = 20;
991
2579
  const PAGINATION_MAX_OFFSET = 800;
992
2580
  const PAGINATION_DEFAULT_OFFSET = 0;
993
2581
  function isCursorPaginationOptions(options) {
994
- return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
2582
+ return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
995
2583
  }
996
2584
  const _RecordArray = class extends Array {
997
2585
  constructor(...args) {
998
2586
  super(..._RecordArray.parseConstructorParams(...args));
999
2587
  __privateAdd$6(this, _page, void 0);
1000
- __privateSet$6(this, _page, args[0]);
2588
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1001
2589
  }
1002
2590
  static parseConstructorParams(...args) {
1003
2591
  if (args.length === 1 && typeof args[0] === "number") {
@@ -1009,22 +2597,57 @@ const _RecordArray = class extends Array {
1009
2597
  }
1010
2598
  return new Array(...args);
1011
2599
  }
2600
+ toArray() {
2601
+ return new Array(...this);
2602
+ }
2603
+ toSerializable() {
2604
+ return JSON.parse(this.toString());
2605
+ }
2606
+ toString() {
2607
+ return JSON.stringify(this.toArray());
2608
+ }
2609
+ map(callbackfn, thisArg) {
2610
+ return this.toArray().map(callbackfn, thisArg);
2611
+ }
2612
+ /**
2613
+ * Retrieve next page of records
2614
+ *
2615
+ * @returns A new array of objects
2616
+ */
1012
2617
  async nextPage(size, offset) {
1013
2618
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1014
2619
  return new _RecordArray(newPage);
1015
2620
  }
2621
+ /**
2622
+ * Retrieve previous page of records
2623
+ *
2624
+ * @returns A new array of objects
2625
+ */
1016
2626
  async previousPage(size, offset) {
1017
2627
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1018
2628
  return new _RecordArray(newPage);
1019
2629
  }
1020
- async firstPage(size, offset) {
1021
- const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
2630
+ /**
2631
+ * Retrieve start page of records
2632
+ *
2633
+ * @returns A new array of objects
2634
+ */
2635
+ async startPage(size, offset) {
2636
+ const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1022
2637
  return new _RecordArray(newPage);
1023
2638
  }
1024
- async lastPage(size, offset) {
1025
- const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
2639
+ /**
2640
+ * Retrieve end page of records
2641
+ *
2642
+ * @returns A new array of objects
2643
+ */
2644
+ async endPage(size, offset) {
2645
+ const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1026
2646
  return new _RecordArray(newPage);
1027
2647
  }
2648
+ /**
2649
+ * @returns Boolean indicating if there is a next page
2650
+ */
1028
2651
  hasNextPage() {
1029
2652
  return __privateGet$6(this, _page).meta.page.more;
1030
2653
  }
@@ -1050,13 +2673,19 @@ var __privateSet$5 = (obj, member, value, setter) => {
1050
2673
  setter ? setter.call(obj, value) : member.set(obj, value);
1051
2674
  return value;
1052
2675
  };
1053
- var _table$1, _repository, _data;
2676
+ var __privateMethod$3 = (obj, member, method) => {
2677
+ __accessCheck$5(obj, member, "access private method");
2678
+ return method;
2679
+ };
2680
+ var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
1054
2681
  const _Query = class {
1055
2682
  constructor(repository, table, data, rawParent) {
2683
+ __privateAdd$5(this, _cleanFilterConstraint);
1056
2684
  __privateAdd$5(this, _table$1, void 0);
1057
2685
  __privateAdd$5(this, _repository, void 0);
1058
2686
  __privateAdd$5(this, _data, { filter: {} });
1059
- this.meta = { page: { cursor: "start", more: true } };
2687
+ // Implements pagination
2688
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
1060
2689
  this.records = new RecordArray(this, []);
1061
2690
  __privateSet$5(this, _table$1, table);
1062
2691
  if (repository) {
@@ -1071,9 +2700,11 @@ const _Query = class {
1071
2700
  __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1072
2701
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1073
2702
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1074
- __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
2703
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
2704
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
1075
2705
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1076
2706
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
2707
+ __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
1077
2708
  this.any = this.any.bind(this);
1078
2709
  this.all = this.all.bind(this);
1079
2710
  this.not = this.not.bind(this);
@@ -1091,44 +2722,83 @@ const _Query = class {
1091
2722
  const key = JSON.stringify({ columns, filter, sort, pagination });
1092
2723
  return toBase64(key);
1093
2724
  }
2725
+ /**
2726
+ * Builds a new query object representing a logical OR between the given subqueries.
2727
+ * @param queries An array of subqueries.
2728
+ * @returns A new Query object.
2729
+ */
1094
2730
  any(...queries) {
1095
2731
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1096
2732
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
1097
2733
  }
2734
+ /**
2735
+ * Builds a new query object representing a logical AND between the given subqueries.
2736
+ * @param queries An array of subqueries.
2737
+ * @returns A new Query object.
2738
+ */
1098
2739
  all(...queries) {
1099
2740
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1100
2741
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1101
2742
  }
2743
+ /**
2744
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
2745
+ * @param queries An array of subqueries.
2746
+ * @returns A new Query object.
2747
+ */
1102
2748
  not(...queries) {
1103
2749
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1104
2750
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
1105
2751
  }
2752
+ /**
2753
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
2754
+ * @param queries An array of subqueries.
2755
+ * @returns A new Query object.
2756
+ */
1106
2757
  none(...queries) {
1107
2758
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1108
2759
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
1109
2760
  }
1110
2761
  filter(a, b) {
1111
2762
  if (arguments.length === 1) {
1112
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
2763
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
2764
+ [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
2765
+ }));
1113
2766
  const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1114
2767
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1115
2768
  } else {
1116
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
2769
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
2770
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1117
2771
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1118
2772
  }
1119
2773
  }
1120
- sort(column, direction) {
2774
+ sort(column, direction = "asc") {
1121
2775
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1122
2776
  const sort = [...originalSort, { column, direction }];
1123
2777
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1124
2778
  }
2779
+ /**
2780
+ * Builds a new query specifying the set of columns to be returned in the query response.
2781
+ * @param columns Array of column names to be returned by the query.
2782
+ * @returns A new Query object.
2783
+ */
1125
2784
  select(columns) {
1126
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
2785
+ return new _Query(
2786
+ __privateGet$5(this, _repository),
2787
+ __privateGet$5(this, _table$1),
2788
+ { columns },
2789
+ __privateGet$5(this, _data)
2790
+ );
1127
2791
  }
1128
2792
  getPaginated(options = {}) {
1129
2793
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1130
2794
  return __privateGet$5(this, _repository).query(query);
1131
2795
  }
2796
+ /**
2797
+ * Get results in an iterator
2798
+ *
2799
+ * @async
2800
+ * @returns Async interable of results
2801
+ */
1132
2802
  async *[Symbol.asyncIterator]() {
1133
2803
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
1134
2804
  yield record;
@@ -1146,11 +2816,20 @@ const _Query = class {
1146
2816
  }
1147
2817
  }
1148
2818
  async getMany(options = {}) {
1149
- const page = await this.getPaginated(options);
2819
+ const { pagination = {}, ...rest } = options;
2820
+ const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
2821
+ const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
2822
+ let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
2823
+ const results = [...page.records];
2824
+ while (page.hasNextPage() && results.length < size) {
2825
+ page = await page.nextPage();
2826
+ results.push(...page.records);
2827
+ }
1150
2828
  if (page.hasNextPage() && options.pagination?.size === void 0) {
1151
2829
  console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1152
2830
  }
1153
- return page.records;
2831
+ const array = new RecordArray(page, results.slice(0, size));
2832
+ return array;
1154
2833
  }
1155
2834
  async getAll(options = {}) {
1156
2835
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1164,21 +2843,65 @@ const _Query = class {
1164
2843
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1165
2844
  return records[0] ?? null;
1166
2845
  }
2846
+ async getFirstOrThrow(options = {}) {
2847
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
2848
+ if (records[0] === void 0)
2849
+ throw new Error("No results found.");
2850
+ return records[0];
2851
+ }
2852
+ async summarize(params = {}) {
2853
+ const { summaries, summariesFilter, ...options } = params;
2854
+ const query = new _Query(
2855
+ __privateGet$5(this, _repository),
2856
+ __privateGet$5(this, _table$1),
2857
+ options,
2858
+ __privateGet$5(this, _data)
2859
+ );
2860
+ return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2861
+ }
2862
+ /**
2863
+ * Builds a new query object adding a cache TTL in milliseconds.
2864
+ * @param ttl The cache TTL in milliseconds.
2865
+ * @returns A new Query object.
2866
+ */
1167
2867
  cache(ttl) {
1168
2868
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1169
2869
  }
2870
+ /**
2871
+ * Retrieve next page of records
2872
+ *
2873
+ * @returns A new page object.
2874
+ */
1170
2875
  nextPage(size, offset) {
1171
- return this.firstPage(size, offset);
2876
+ return this.startPage(size, offset);
1172
2877
  }
2878
+ /**
2879
+ * Retrieve previous page of records
2880
+ *
2881
+ * @returns A new page object
2882
+ */
1173
2883
  previousPage(size, offset) {
1174
- return this.firstPage(size, offset);
1175
- }
1176
- firstPage(size, offset) {
2884
+ return this.startPage(size, offset);
2885
+ }
2886
+ /**
2887
+ * Retrieve start page of records
2888
+ *
2889
+ * @returns A new page object
2890
+ */
2891
+ startPage(size, offset) {
1177
2892
  return this.getPaginated({ pagination: { size, offset } });
1178
2893
  }
1179
- lastPage(size, offset) {
2894
+ /**
2895
+ * Retrieve last page of records
2896
+ *
2897
+ * @returns A new page object
2898
+ */
2899
+ endPage(size, offset) {
1180
2900
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
1181
2901
  }
2902
+ /**
2903
+ * @returns Boolean indicating if there is a next page
2904
+ */
1182
2905
  hasNextPage() {
1183
2906
  return this.meta.page.more;
1184
2907
  }
@@ -1187,9 +2910,20 @@ let Query = _Query;
1187
2910
  _table$1 = new WeakMap();
1188
2911
  _repository = new WeakMap();
1189
2912
  _data = new WeakMap();
2913
+ _cleanFilterConstraint = new WeakSet();
2914
+ cleanFilterConstraint_fn = function(column, value) {
2915
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
2916
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
2917
+ return { $includes: value };
2918
+ }
2919
+ if (columnType === "link" && isObject(value) && isString(value.id)) {
2920
+ return value.id;
2921
+ }
2922
+ return value;
2923
+ };
1190
2924
  function cleanParent(data, parent) {
1191
2925
  if (isCursorPaginationOptions(data.pagination)) {
1192
- return { ...parent, sorting: void 0, filter: void 0 };
2926
+ return { ...parent, sort: void 0, filter: void 0 };
1193
2927
  }
1194
2928
  return parent;
1195
2929
  }
@@ -1207,7 +2941,11 @@ function isSortFilterString(value) {
1207
2941
  return isString(value);
1208
2942
  }
1209
2943
  function isSortFilterBase(filter) {
1210
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
2944
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
2945
+ if (key === "*")
2946
+ return value === "random";
2947
+ return value === "asc" || value === "desc";
2948
+ });
1211
2949
  }
1212
2950
  function isSortFilterObject(filter) {
1213
2951
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -1248,329 +2986,649 @@ var __privateMethod$2 = (obj, member, method) => {
1248
2986
  __accessCheck$4(obj, member, "access private method");
1249
2987
  return method;
1250
2988
  };
1251
- var _table, _getFetchProps, _cache, _schemaTables$2, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
2989
+ 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;
2990
+ const BULK_OPERATION_MAX_SIZE = 1e3;
1252
2991
  class Repository extends Query {
1253
2992
  }
1254
2993
  class RestRepository extends Query {
1255
2994
  constructor(options) {
1256
- super(null, options.table, {});
2995
+ super(
2996
+ null,
2997
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
2998
+ {}
2999
+ );
1257
3000
  __privateAdd$4(this, _insertRecordWithoutId);
1258
3001
  __privateAdd$4(this, _insertRecordWithId);
1259
- __privateAdd$4(this, _bulkInsertTableRecords);
3002
+ __privateAdd$4(this, _insertRecords);
1260
3003
  __privateAdd$4(this, _updateRecordWithID);
3004
+ __privateAdd$4(this, _updateRecords);
1261
3005
  __privateAdd$4(this, _upsertRecordWithID);
1262
3006
  __privateAdd$4(this, _deleteRecord);
1263
- __privateAdd$4(this, _invalidateCache);
1264
- __privateAdd$4(this, _setCacheRecord);
1265
- __privateAdd$4(this, _getCacheRecord);
3007
+ __privateAdd$4(this, _deleteRecords);
1266
3008
  __privateAdd$4(this, _setCacheQuery);
1267
3009
  __privateAdd$4(this, _getCacheQuery);
1268
3010
  __privateAdd$4(this, _getSchemaTables$1);
1269
3011
  __privateAdd$4(this, _table, void 0);
1270
3012
  __privateAdd$4(this, _getFetchProps, void 0);
3013
+ __privateAdd$4(this, _db, void 0);
1271
3014
  __privateAdd$4(this, _cache, void 0);
1272
3015
  __privateAdd$4(this, _schemaTables$2, void 0);
3016
+ __privateAdd$4(this, _trace, void 0);
1273
3017
  __privateSet$4(this, _table, options.table);
1274
- __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1275
- this.db = options.db;
3018
+ __privateSet$4(this, _db, options.db);
1276
3019
  __privateSet$4(this, _cache, options.pluginOptions.cache);
1277
3020
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
3021
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
3022
+ const trace = options.pluginOptions.trace ?? defaultTrace;
3023
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
3024
+ return trace(name, fn, {
3025
+ ...options2,
3026
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
3027
+ [TraceAttributes.KIND]: "sdk-operation",
3028
+ [TraceAttributes.VERSION]: VERSION
3029
+ });
3030
+ });
1278
3031
  }
1279
- async create(a, b) {
1280
- if (Array.isArray(a)) {
1281
- if (a.length === 0)
1282
- return [];
1283
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1284
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1285
- return records;
1286
- }
1287
- if (isString(a) && isObject(b)) {
1288
- if (a === "")
1289
- throw new Error("The id can't be empty");
1290
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1291
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1292
- return record;
1293
- }
1294
- if (isObject(a) && isString(a.id)) {
1295
- if (a.id === "")
1296
- throw new Error("The id can't be empty");
1297
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1298
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1299
- return record;
1300
- }
1301
- if (isObject(a)) {
1302
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1303
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1304
- return record;
1305
- }
1306
- throw new Error("Invalid arguments for create method");
1307
- }
1308
- async read(a) {
1309
- if (Array.isArray(a)) {
1310
- if (a.length === 0)
1311
- return [];
1312
- const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1313
- return this.getAll({ filter: { id: { $any: ids } } });
1314
- }
1315
- const id = isString(a) ? a : a.id;
1316
- if (isString(id)) {
1317
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1318
- if (cacheRecord)
1319
- return cacheRecord;
1320
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1321
- try {
1322
- const response = await getRecord({
1323
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1324
- ...fetchProps
3032
+ async create(a, b, c, d) {
3033
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
3034
+ const ifVersion = parseIfVersion(b, c, d);
3035
+ if (Array.isArray(a)) {
3036
+ if (a.length === 0)
3037
+ return [];
3038
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
3039
+ const columns = isStringArray(b) ? b : ["*"];
3040
+ const result = await this.read(ids, columns);
3041
+ return result;
3042
+ }
3043
+ if (isString(a) && isObject(b)) {
3044
+ if (a === "")
3045
+ throw new Error("The id can't be empty");
3046
+ const columns = isStringArray(c) ? c : void 0;
3047
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
3048
+ }
3049
+ if (isObject(a) && isString(a.id)) {
3050
+ if (a.id === "")
3051
+ throw new Error("The id can't be empty");
3052
+ const columns = isStringArray(b) ? b : void 0;
3053
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
3054
+ }
3055
+ if (isObject(a)) {
3056
+ const columns = isStringArray(b) ? b : void 0;
3057
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
3058
+ }
3059
+ throw new Error("Invalid arguments for create method");
3060
+ });
3061
+ }
3062
+ async read(a, b) {
3063
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
3064
+ const columns = isStringArray(b) ? b : ["*"];
3065
+ if (Array.isArray(a)) {
3066
+ if (a.length === 0)
3067
+ return [];
3068
+ const ids = a.map((item) => extractId(item));
3069
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
3070
+ const dictionary = finalObjects.reduce((acc, object) => {
3071
+ acc[object.id] = object;
3072
+ return acc;
3073
+ }, {});
3074
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
3075
+ }
3076
+ const id = extractId(a);
3077
+ if (id) {
3078
+ try {
3079
+ const response = await getRecord({
3080
+ pathParams: {
3081
+ workspace: "{workspaceId}",
3082
+ dbBranchName: "{dbBranch}",
3083
+ region: "{region}",
3084
+ tableName: __privateGet$4(this, _table),
3085
+ recordId: id
3086
+ },
3087
+ queryParams: { columns },
3088
+ ...__privateGet$4(this, _getFetchProps).call(this)
3089
+ });
3090
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3091
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3092
+ } catch (e) {
3093
+ if (isObject(e) && e.status === 404) {
3094
+ return null;
3095
+ }
3096
+ throw e;
3097
+ }
3098
+ }
3099
+ return null;
3100
+ });
3101
+ }
3102
+ async readOrThrow(a, b) {
3103
+ return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
3104
+ const result = await this.read(a, b);
3105
+ if (Array.isArray(result)) {
3106
+ const missingIds = compact(
3107
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
3108
+ );
3109
+ if (missingIds.length > 0) {
3110
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
3111
+ }
3112
+ return result;
3113
+ }
3114
+ if (result === null) {
3115
+ const id = extractId(a) ?? "unknown";
3116
+ throw new Error(`Record with id ${id} not found`);
3117
+ }
3118
+ return result;
3119
+ });
3120
+ }
3121
+ async update(a, b, c, d) {
3122
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
3123
+ const ifVersion = parseIfVersion(b, c, d);
3124
+ if (Array.isArray(a)) {
3125
+ if (a.length === 0)
3126
+ return [];
3127
+ const existing = await this.read(a, ["id"]);
3128
+ const updates = a.filter((_item, index) => existing[index] !== null);
3129
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
3130
+ ifVersion,
3131
+ upsert: false
1325
3132
  });
1326
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1327
- return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1328
- } catch (e) {
1329
- if (isObject(e) && e.status === 404) {
3133
+ const columns = isStringArray(b) ? b : ["*"];
3134
+ const result = await this.read(a, columns);
3135
+ return result;
3136
+ }
3137
+ try {
3138
+ if (isString(a) && isObject(b)) {
3139
+ const columns = isStringArray(c) ? c : void 0;
3140
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3141
+ }
3142
+ if (isObject(a) && isString(a.id)) {
3143
+ const columns = isStringArray(b) ? b : void 0;
3144
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3145
+ }
3146
+ } catch (error) {
3147
+ if (error.status === 422)
1330
3148
  return null;
3149
+ throw error;
3150
+ }
3151
+ throw new Error("Invalid arguments for update method");
3152
+ });
3153
+ }
3154
+ async updateOrThrow(a, b, c, d) {
3155
+ return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
3156
+ const result = await this.update(a, b, c, d);
3157
+ if (Array.isArray(result)) {
3158
+ const missingIds = compact(
3159
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
3160
+ );
3161
+ if (missingIds.length > 0) {
3162
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1331
3163
  }
1332
- throw e;
3164
+ return result;
1333
3165
  }
1334
- }
3166
+ if (result === null) {
3167
+ const id = extractId(a) ?? "unknown";
3168
+ throw new Error(`Record with id ${id} not found`);
3169
+ }
3170
+ return result;
3171
+ });
1335
3172
  }
1336
- async update(a, b) {
1337
- if (Array.isArray(a)) {
1338
- if (a.length === 0)
1339
- return [];
1340
- if (a.length > 100) {
1341
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
3173
+ async createOrUpdate(a, b, c, d) {
3174
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
3175
+ const ifVersion = parseIfVersion(b, c, d);
3176
+ if (Array.isArray(a)) {
3177
+ if (a.length === 0)
3178
+ return [];
3179
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
3180
+ ifVersion,
3181
+ upsert: true
3182
+ });
3183
+ const columns = isStringArray(b) ? b : ["*"];
3184
+ const result = await this.read(a, columns);
3185
+ return result;
1342
3186
  }
1343
- return Promise.all(a.map((object) => this.update(object)));
1344
- }
1345
- if (isString(a) && isObject(b)) {
1346
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1347
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1348
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1349
- return record;
1350
- }
1351
- if (isObject(a) && isString(a.id)) {
1352
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1353
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1354
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1355
- return record;
1356
- }
1357
- throw new Error("Invalid arguments for update method");
1358
- }
1359
- async createOrUpdate(a, b) {
1360
- if (Array.isArray(a)) {
1361
- if (a.length === 0)
1362
- return [];
1363
- if (a.length > 100) {
1364
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
3187
+ if (isString(a) && isObject(b)) {
3188
+ if (a === "")
3189
+ throw new Error("The id can't be empty");
3190
+ const columns = isStringArray(c) ? c : void 0;
3191
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
1365
3192
  }
1366
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1367
- }
1368
- if (isString(a) && isObject(b)) {
1369
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1370
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1371
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1372
- return record;
1373
- }
1374
- if (isObject(a) && isString(a.id)) {
1375
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1376
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1377
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1378
- return record;
1379
- }
1380
- throw new Error("Invalid arguments for createOrUpdate method");
1381
- }
1382
- async delete(a) {
1383
- if (Array.isArray(a)) {
1384
- if (a.length === 0)
1385
- return;
1386
- if (a.length > 100) {
1387
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
3193
+ if (isObject(a) && isString(a.id)) {
3194
+ if (a.id === "")
3195
+ throw new Error("The id can't be empty");
3196
+ const columns = isStringArray(c) ? c : void 0;
3197
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
1388
3198
  }
1389
- await Promise.all(a.map((id) => this.delete(id)));
1390
- return;
1391
- }
1392
- if (isString(a)) {
1393
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1394
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1395
- return;
1396
- }
1397
- if (isObject(a) && isString(a.id)) {
1398
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1399
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1400
- return;
1401
- }
1402
- throw new Error("Invalid arguments for delete method");
3199
+ if (!isDefined(a) && isObject(b)) {
3200
+ return await this.create(b, c);
3201
+ }
3202
+ if (isObject(a) && !isDefined(a.id)) {
3203
+ return await this.create(a, b);
3204
+ }
3205
+ throw new Error("Invalid arguments for createOrUpdate method");
3206
+ });
3207
+ }
3208
+ async createOrReplace(a, b, c, d) {
3209
+ return __privateGet$4(this, _trace).call(this, "createOrReplace", async () => {
3210
+ const ifVersion = parseIfVersion(b, c, d);
3211
+ if (Array.isArray(a)) {
3212
+ if (a.length === 0)
3213
+ return [];
3214
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
3215
+ const columns = isStringArray(b) ? b : ["*"];
3216
+ const result = await this.read(ids, columns);
3217
+ return result;
3218
+ }
3219
+ if (isString(a) && isObject(b)) {
3220
+ if (a === "")
3221
+ throw new Error("The id can't be empty");
3222
+ const columns = isStringArray(c) ? c : void 0;
3223
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3224
+ }
3225
+ if (isObject(a) && isString(a.id)) {
3226
+ if (a.id === "")
3227
+ throw new Error("The id can't be empty");
3228
+ const columns = isStringArray(c) ? c : void 0;
3229
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3230
+ }
3231
+ if (!isDefined(a) && isObject(b)) {
3232
+ return await this.create(b, c);
3233
+ }
3234
+ if (isObject(a) && !isDefined(a.id)) {
3235
+ return await this.create(a, b);
3236
+ }
3237
+ throw new Error("Invalid arguments for createOrReplace method");
3238
+ });
3239
+ }
3240
+ async delete(a, b) {
3241
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
3242
+ if (Array.isArray(a)) {
3243
+ if (a.length === 0)
3244
+ return [];
3245
+ const ids = a.map((o) => {
3246
+ if (isString(o))
3247
+ return o;
3248
+ if (isString(o.id))
3249
+ return o.id;
3250
+ throw new Error("Invalid arguments for delete method");
3251
+ });
3252
+ const columns = isStringArray(b) ? b : ["*"];
3253
+ const result = await this.read(a, columns);
3254
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
3255
+ return result;
3256
+ }
3257
+ if (isString(a)) {
3258
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
3259
+ }
3260
+ if (isObject(a) && isString(a.id)) {
3261
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
3262
+ }
3263
+ throw new Error("Invalid arguments for delete method");
3264
+ });
3265
+ }
3266
+ async deleteOrThrow(a, b) {
3267
+ return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
3268
+ const result = await this.delete(a, b);
3269
+ if (Array.isArray(result)) {
3270
+ const missingIds = compact(
3271
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
3272
+ );
3273
+ if (missingIds.length > 0) {
3274
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
3275
+ }
3276
+ return result;
3277
+ } else if (result === null) {
3278
+ const id = extractId(a) ?? "unknown";
3279
+ throw new Error(`Record with id ${id} not found`);
3280
+ }
3281
+ return result;
3282
+ });
1403
3283
  }
1404
3284
  async search(query, options = {}) {
1405
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1406
- const { records } = await searchTable({
1407
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1408
- body: {
1409
- query,
1410
- fuzziness: options.fuzziness,
1411
- highlight: options.highlight,
1412
- filter: options.filter
1413
- },
1414
- ...fetchProps
3285
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
3286
+ const { records } = await searchTable({
3287
+ pathParams: {
3288
+ workspace: "{workspaceId}",
3289
+ dbBranchName: "{dbBranch}",
3290
+ region: "{region}",
3291
+ tableName: __privateGet$4(this, _table)
3292
+ },
3293
+ body: {
3294
+ query,
3295
+ fuzziness: options.fuzziness,
3296
+ prefix: options.prefix,
3297
+ highlight: options.highlight,
3298
+ filter: options.filter,
3299
+ boosters: options.boosters,
3300
+ page: options.page,
3301
+ target: options.target
3302
+ },
3303
+ ...__privateGet$4(this, _getFetchProps).call(this)
3304
+ });
3305
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3306
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3307
+ });
3308
+ }
3309
+ async vectorSearch(column, query, options) {
3310
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3311
+ const { records } = await vectorSearchTable({
3312
+ pathParams: {
3313
+ workspace: "{workspaceId}",
3314
+ dbBranchName: "{dbBranch}",
3315
+ region: "{region}",
3316
+ tableName: __privateGet$4(this, _table)
3317
+ },
3318
+ body: {
3319
+ column,
3320
+ queryVector: query,
3321
+ similarityFunction: options?.similarityFunction,
3322
+ size: options?.size,
3323
+ filter: options?.filter
3324
+ },
3325
+ ...__privateGet$4(this, _getFetchProps).call(this)
3326
+ });
3327
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3328
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3329
+ });
3330
+ }
3331
+ async aggregate(aggs, filter) {
3332
+ return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
3333
+ const result = await aggregateTable({
3334
+ pathParams: {
3335
+ workspace: "{workspaceId}",
3336
+ dbBranchName: "{dbBranch}",
3337
+ region: "{region}",
3338
+ tableName: __privateGet$4(this, _table)
3339
+ },
3340
+ body: { aggs, filter },
3341
+ ...__privateGet$4(this, _getFetchProps).call(this)
3342
+ });
3343
+ return result;
1415
3344
  });
1416
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1417
- return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1418
3345
  }
1419
3346
  async query(query) {
1420
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1421
- if (cacheQuery)
1422
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1423
- const data = query.getQueryOptions();
1424
- const body = {
1425
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1426
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1427
- page: data.pagination,
1428
- columns: data.columns
1429
- };
1430
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1431
- const { meta, records: objects } = await queryTable({
1432
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1433
- body,
1434
- ...fetchProps
3347
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
3348
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
3349
+ if (cacheQuery)
3350
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
3351
+ const data = query.getQueryOptions();
3352
+ const { meta, records: objects } = await queryTable({
3353
+ pathParams: {
3354
+ workspace: "{workspaceId}",
3355
+ dbBranchName: "{dbBranch}",
3356
+ region: "{region}",
3357
+ tableName: __privateGet$4(this, _table)
3358
+ },
3359
+ body: {
3360
+ filter: cleanFilter(data.filter),
3361
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
3362
+ page: data.pagination,
3363
+ columns: data.columns ?? ["*"],
3364
+ consistency: data.consistency
3365
+ },
3366
+ fetchOptions: data.fetchOptions,
3367
+ ...__privateGet$4(this, _getFetchProps).call(this)
3368
+ });
3369
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3370
+ const records = objects.map(
3371
+ (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3372
+ );
3373
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
3374
+ return new Page(query, meta, records);
1435
3375
  });
1436
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1437
- const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1438
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1439
- return new Page(query, meta, records);
3376
+ }
3377
+ async summarizeTable(query, summaries, summariesFilter) {
3378
+ return __privateGet$4(this, _trace).call(this, "summarize", async () => {
3379
+ const data = query.getQueryOptions();
3380
+ const result = await summarizeTable({
3381
+ pathParams: {
3382
+ workspace: "{workspaceId}",
3383
+ dbBranchName: "{dbBranch}",
3384
+ region: "{region}",
3385
+ tableName: __privateGet$4(this, _table)
3386
+ },
3387
+ body: {
3388
+ filter: cleanFilter(data.filter),
3389
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
3390
+ columns: data.columns,
3391
+ consistency: data.consistency,
3392
+ page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
3393
+ summaries,
3394
+ summariesFilter
3395
+ },
3396
+ ...__privateGet$4(this, _getFetchProps).call(this)
3397
+ });
3398
+ return result;
3399
+ });
3400
+ }
3401
+ ask(question, options) {
3402
+ const params = {
3403
+ pathParams: {
3404
+ workspace: "{workspaceId}",
3405
+ dbBranchName: "{dbBranch}",
3406
+ region: "{region}",
3407
+ tableName: __privateGet$4(this, _table)
3408
+ },
3409
+ body: {
3410
+ question,
3411
+ ...options
3412
+ },
3413
+ ...__privateGet$4(this, _getFetchProps).call(this)
3414
+ };
3415
+ if (options?.onMessage) {
3416
+ fetchSSERequest({
3417
+ endpoint: "dataPlane",
3418
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
3419
+ method: "POST",
3420
+ onMessage: (message) => {
3421
+ options.onMessage?.({ answer: message.text, records: message.records });
3422
+ },
3423
+ ...params
3424
+ });
3425
+ } else {
3426
+ return askTable(params);
3427
+ }
1440
3428
  }
1441
3429
  }
1442
3430
  _table = new WeakMap();
1443
3431
  _getFetchProps = new WeakMap();
3432
+ _db = new WeakMap();
1444
3433
  _cache = new WeakMap();
1445
3434
  _schemaTables$2 = new WeakMap();
3435
+ _trace = new WeakMap();
1446
3436
  _insertRecordWithoutId = new WeakSet();
1447
- insertRecordWithoutId_fn = async function(object) {
1448
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3437
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1449
3438
  const record = transformObjectLinks(object);
1450
3439
  const response = await insertRecord({
1451
3440
  pathParams: {
1452
3441
  workspace: "{workspaceId}",
1453
3442
  dbBranchName: "{dbBranch}",
3443
+ region: "{region}",
1454
3444
  tableName: __privateGet$4(this, _table)
1455
3445
  },
3446
+ queryParams: { columns },
1456
3447
  body: record,
1457
- ...fetchProps
3448
+ ...__privateGet$4(this, _getFetchProps).call(this)
1458
3449
  });
1459
- const finalObject = await this.read(response.id);
1460
- if (!finalObject) {
1461
- throw new Error("The server failed to save the record");
1462
- }
1463
- return finalObject;
3450
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3451
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1464
3452
  };
1465
3453
  _insertRecordWithId = new WeakSet();
1466
- insertRecordWithId_fn = async function(recordId, object) {
1467
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3454
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
3455
+ if (!recordId)
3456
+ return null;
1468
3457
  const record = transformObjectLinks(object);
1469
3458
  const response = await insertRecordWithID({
1470
3459
  pathParams: {
1471
3460
  workspace: "{workspaceId}",
1472
3461
  dbBranchName: "{dbBranch}",
3462
+ region: "{region}",
1473
3463
  tableName: __privateGet$4(this, _table),
1474
3464
  recordId
1475
3465
  },
1476
3466
  body: record,
1477
- queryParams: { createOnly: true },
1478
- ...fetchProps
1479
- });
1480
- const finalObject = await this.read(response.id);
1481
- if (!finalObject) {
1482
- throw new Error("The server failed to save the record");
1483
- }
1484
- return finalObject;
1485
- };
1486
- _bulkInsertTableRecords = new WeakSet();
1487
- bulkInsertTableRecords_fn = async function(objects) {
1488
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1489
- const records = objects.map((object) => transformObjectLinks(object));
1490
- const { recordIDs } = await bulkInsertTableRecords({
1491
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1492
- body: { records },
1493
- ...fetchProps
3467
+ queryParams: { createOnly, columns, ifVersion },
3468
+ ...__privateGet$4(this, _getFetchProps).call(this)
1494
3469
  });
1495
- const finalObjects = await this.read(recordIDs);
1496
- if (finalObjects.length !== objects.length) {
1497
- throw new Error("The server failed to save some records");
3470
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3471
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3472
+ };
3473
+ _insertRecords = new WeakSet();
3474
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
3475
+ const chunkedOperations = chunk(
3476
+ objects.map((object) => ({
3477
+ insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
3478
+ })),
3479
+ BULK_OPERATION_MAX_SIZE
3480
+ );
3481
+ const ids = [];
3482
+ for (const operations of chunkedOperations) {
3483
+ const { results } = await branchTransaction({
3484
+ pathParams: {
3485
+ workspace: "{workspaceId}",
3486
+ dbBranchName: "{dbBranch}",
3487
+ region: "{region}"
3488
+ },
3489
+ body: { operations },
3490
+ ...__privateGet$4(this, _getFetchProps).call(this)
3491
+ });
3492
+ for (const result of results) {
3493
+ if (result.operation === "insert") {
3494
+ ids.push(result.id);
3495
+ } else {
3496
+ ids.push(null);
3497
+ }
3498
+ }
1498
3499
  }
1499
- const dictionary = finalObjects.reduce((acc, object) => {
1500
- acc[object.id] = object;
1501
- return acc;
1502
- }, {});
1503
- return recordIDs.map((id) => dictionary[id]);
3500
+ return ids;
1504
3501
  };
1505
3502
  _updateRecordWithID = new WeakSet();
1506
- updateRecordWithID_fn = async function(recordId, object) {
1507
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1508
- const record = transformObjectLinks(object);
1509
- const response = await updateRecordWithID({
1510
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1511
- body: record,
1512
- ...fetchProps
1513
- });
1514
- const item = await this.read(response.id);
1515
- if (!item)
1516
- throw new Error("The server failed to save the record");
1517
- return item;
3503
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
3504
+ if (!recordId)
3505
+ return null;
3506
+ const { id: _id, ...record } = transformObjectLinks(object);
3507
+ try {
3508
+ const response = await updateRecordWithID({
3509
+ pathParams: {
3510
+ workspace: "{workspaceId}",
3511
+ dbBranchName: "{dbBranch}",
3512
+ region: "{region}",
3513
+ tableName: __privateGet$4(this, _table),
3514
+ recordId
3515
+ },
3516
+ queryParams: { columns, ifVersion },
3517
+ body: record,
3518
+ ...__privateGet$4(this, _getFetchProps).call(this)
3519
+ });
3520
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3521
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3522
+ } catch (e) {
3523
+ if (isObject(e) && e.status === 404) {
3524
+ return null;
3525
+ }
3526
+ throw e;
3527
+ }
3528
+ };
3529
+ _updateRecords = new WeakSet();
3530
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
3531
+ const chunkedOperations = chunk(
3532
+ objects.map(({ id, ...object }) => ({
3533
+ update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
3534
+ })),
3535
+ BULK_OPERATION_MAX_SIZE
3536
+ );
3537
+ const ids = [];
3538
+ for (const operations of chunkedOperations) {
3539
+ const { results } = await branchTransaction({
3540
+ pathParams: {
3541
+ workspace: "{workspaceId}",
3542
+ dbBranchName: "{dbBranch}",
3543
+ region: "{region}"
3544
+ },
3545
+ body: { operations },
3546
+ ...__privateGet$4(this, _getFetchProps).call(this)
3547
+ });
3548
+ for (const result of results) {
3549
+ if (result.operation === "update") {
3550
+ ids.push(result.id);
3551
+ } else {
3552
+ ids.push(null);
3553
+ }
3554
+ }
3555
+ }
3556
+ return ids;
1518
3557
  };
1519
3558
  _upsertRecordWithID = new WeakSet();
1520
- upsertRecordWithID_fn = async function(recordId, object) {
1521
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3559
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
3560
+ if (!recordId)
3561
+ return null;
1522
3562
  const response = await upsertRecordWithID({
1523
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
3563
+ pathParams: {
3564
+ workspace: "{workspaceId}",
3565
+ dbBranchName: "{dbBranch}",
3566
+ region: "{region}",
3567
+ tableName: __privateGet$4(this, _table),
3568
+ recordId
3569
+ },
3570
+ queryParams: { columns, ifVersion },
1524
3571
  body: object,
1525
- ...fetchProps
3572
+ ...__privateGet$4(this, _getFetchProps).call(this)
1526
3573
  });
1527
- const item = await this.read(response.id);
1528
- if (!item)
1529
- throw new Error("The server failed to save the record");
1530
- return item;
3574
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3575
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1531
3576
  };
1532
3577
  _deleteRecord = new WeakSet();
1533
- deleteRecord_fn = async function(recordId) {
1534
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1535
- await deleteRecord({
1536
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1537
- ...fetchProps
1538
- });
1539
- };
1540
- _invalidateCache = new WeakSet();
1541
- invalidateCache_fn = async function(recordId) {
1542
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1543
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1544
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1545
- for (const [key, value] of queries) {
1546
- const ids = getIds(value);
1547
- if (ids.includes(recordId))
1548
- await __privateGet$4(this, _cache).delete(key);
1549
- }
1550
- };
1551
- _setCacheRecord = new WeakSet();
1552
- setCacheRecord_fn = async function(record) {
1553
- if (!__privateGet$4(this, _cache).cacheRecords)
1554
- return;
1555
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1556
- };
1557
- _getCacheRecord = new WeakSet();
1558
- getCacheRecord_fn = async function(recordId) {
1559
- if (!__privateGet$4(this, _cache).cacheRecords)
3578
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
3579
+ if (!recordId)
1560
3580
  return null;
1561
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
3581
+ try {
3582
+ const response = await deleteRecord({
3583
+ pathParams: {
3584
+ workspace: "{workspaceId}",
3585
+ dbBranchName: "{dbBranch}",
3586
+ region: "{region}",
3587
+ tableName: __privateGet$4(this, _table),
3588
+ recordId
3589
+ },
3590
+ queryParams: { columns },
3591
+ ...__privateGet$4(this, _getFetchProps).call(this)
3592
+ });
3593
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3594
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3595
+ } catch (e) {
3596
+ if (isObject(e) && e.status === 404) {
3597
+ return null;
3598
+ }
3599
+ throw e;
3600
+ }
3601
+ };
3602
+ _deleteRecords = new WeakSet();
3603
+ deleteRecords_fn = async function(recordIds) {
3604
+ const chunkedOperations = chunk(
3605
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
3606
+ BULK_OPERATION_MAX_SIZE
3607
+ );
3608
+ for (const operations of chunkedOperations) {
3609
+ await branchTransaction({
3610
+ pathParams: {
3611
+ workspace: "{workspaceId}",
3612
+ dbBranchName: "{dbBranch}",
3613
+ region: "{region}"
3614
+ },
3615
+ body: { operations },
3616
+ ...__privateGet$4(this, _getFetchProps).call(this)
3617
+ });
3618
+ }
1562
3619
  };
1563
3620
  _setCacheQuery = new WeakSet();
1564
3621
  setCacheQuery_fn = async function(query, meta, records) {
1565
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
3622
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
1566
3623
  };
1567
3624
  _getCacheQuery = new WeakSet();
1568
3625
  getCacheQuery_fn = async function(query) {
1569
3626
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1570
- const result = await __privateGet$4(this, _cache).get(key);
3627
+ const result = await __privateGet$4(this, _cache)?.get(key);
1571
3628
  if (!result)
1572
3629
  return null;
1573
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
3630
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
3631
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
1574
3632
  if (ttl < 0)
1575
3633
  return null;
1576
3634
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -1580,10 +3638,9 @@ _getSchemaTables$1 = new WeakSet();
1580
3638
  getSchemaTables_fn$1 = async function() {
1581
3639
  if (__privateGet$4(this, _schemaTables$2))
1582
3640
  return __privateGet$4(this, _schemaTables$2);
1583
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1584
3641
  const { schema } = await getBranchDetails({
1585
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1586
- ...fetchProps
3642
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3643
+ ...__privateGet$4(this, _getFetchProps).call(this)
1587
3644
  });
1588
3645
  __privateSet$4(this, _schemaTables$2, schema.tables);
1589
3646
  return schema.tables;
@@ -1595,22 +3652,24 @@ const transformObjectLinks = (object) => {
1595
3652
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1596
3653
  }, {});
1597
3654
  };
1598
- const initObject = (db, schemaTables, table, object) => {
1599
- const result = {};
3655
+ const initObject = (db, schemaTables, table, object, selectedColumns) => {
3656
+ const data = {};
1600
3657
  const { xata, ...rest } = object ?? {};
1601
- Object.assign(result, rest);
3658
+ Object.assign(data, rest);
1602
3659
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1603
3660
  if (!columns)
1604
3661
  console.error(`Table ${table} not found in schema`);
1605
3662
  for (const column of columns ?? []) {
1606
- const value = result[column.name];
3663
+ if (!isValidColumn(selectedColumns, column))
3664
+ continue;
3665
+ const value = data[column.name];
1607
3666
  switch (column.type) {
1608
3667
  case "datetime": {
1609
- const date = value !== void 0 ? new Date(value) : void 0;
1610
- if (date && isNaN(date.getTime())) {
3668
+ const date = value !== void 0 ? new Date(value) : null;
3669
+ if (date !== null && isNaN(date.getTime())) {
1611
3670
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1612
- } else if (date) {
1613
- result[column.name] = date;
3671
+ } else {
3672
+ data[column.name] = date;
1614
3673
  }
1615
3674
  break;
1616
3675
  }
@@ -1619,38 +3678,88 @@ const initObject = (db, schemaTables, table, object) => {
1619
3678
  if (!linkTable) {
1620
3679
  console.error(`Failed to parse link for field ${column.name}`);
1621
3680
  } else if (isObject(value)) {
1622
- result[column.name] = initObject(db, schemaTables, linkTable, value);
3681
+ const selectedLinkColumns = selectedColumns.reduce((acc, item) => {
3682
+ if (item === column.name) {
3683
+ return [...acc, "*"];
3684
+ }
3685
+ if (item.startsWith(`${column.name}.`)) {
3686
+ const [, ...path] = item.split(".");
3687
+ return [...acc, path.join(".")];
3688
+ }
3689
+ return acc;
3690
+ }, []);
3691
+ data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
3692
+ } else {
3693
+ data[column.name] = null;
1623
3694
  }
1624
3695
  break;
1625
3696
  }
3697
+ default:
3698
+ data[column.name] = value ?? null;
3699
+ if (column.notNull === true && value === null) {
3700
+ console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
3701
+ }
3702
+ break;
1626
3703
  }
1627
3704
  }
1628
- result.read = function() {
1629
- return db[table].read(result["id"]);
3705
+ const record = { ...data };
3706
+ const serializable = { xata, ...transformObjectLinks(data) };
3707
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
3708
+ record.read = function(columns2) {
3709
+ return db[table].read(record["id"], columns2);
3710
+ };
3711
+ record.update = function(data2, b, c) {
3712
+ const columns2 = isStringArray(b) ? b : ["*"];
3713
+ const ifVersion = parseIfVersion(b, c);
3714
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
3715
+ };
3716
+ record.replace = function(data2, b, c) {
3717
+ const columns2 = isStringArray(b) ? b : ["*"];
3718
+ const ifVersion = parseIfVersion(b, c);
3719
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
1630
3720
  };
1631
- result.update = function(data) {
1632
- return db[table].update(result["id"], data);
3721
+ record.delete = function() {
3722
+ return db[table].delete(record["id"]);
1633
3723
  };
1634
- result.delete = function() {
1635
- return db[table].delete(result["id"]);
3724
+ record.xata = Object.freeze(metadata);
3725
+ record.getMetadata = function() {
3726
+ return record.xata;
1636
3727
  };
1637
- result.getMetadata = function() {
1638
- return xata;
3728
+ record.toSerializable = function() {
3729
+ return JSON.parse(JSON.stringify(serializable));
1639
3730
  };
1640
- for (const prop of ["read", "update", "delete", "getMetadata"]) {
1641
- Object.defineProperty(result, prop, { enumerable: false });
3731
+ record.toString = function() {
3732
+ return JSON.stringify(transformObjectLinks(serializable));
3733
+ };
3734
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
3735
+ Object.defineProperty(record, prop, { enumerable: false });
1642
3736
  }
1643
- Object.freeze(result);
1644
- return result;
3737
+ Object.freeze(record);
3738
+ return record;
1645
3739
  };
1646
- function getIds(value) {
1647
- if (Array.isArray(value)) {
1648
- return value.map((item) => getIds(item)).flat();
3740
+ function extractId(value) {
3741
+ if (isString(value))
3742
+ return value;
3743
+ if (isObject(value) && isString(value.id))
3744
+ return value.id;
3745
+ return void 0;
3746
+ }
3747
+ function isValidColumn(columns, column) {
3748
+ if (columns.includes("*"))
3749
+ return true;
3750
+ if (column.type === "link") {
3751
+ const linkColumns = columns.filter((item) => item.startsWith(column.name));
3752
+ return linkColumns.length > 0;
3753
+ }
3754
+ return columns.includes(column.name);
3755
+ }
3756
+ function parseIfVersion(...args) {
3757
+ for (const arg of args) {
3758
+ if (isObject(arg) && isNumber(arg.ifVersion)) {
3759
+ return arg.ifVersion;
3760
+ }
1649
3761
  }
1650
- if (!isObject(value))
1651
- return [];
1652
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1653
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
3762
+ return void 0;
1654
3763
  }
1655
3764
 
1656
3765
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1677,7 +3786,6 @@ class SimpleCache {
1677
3786
  __privateAdd$3(this, _map, void 0);
1678
3787
  __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1679
3788
  this.capacity = options.max ?? 500;
1680
- this.cacheRecords = options.cacheRecords ?? true;
1681
3789
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1682
3790
  }
1683
3791
  async getAll() {
@@ -1703,18 +3811,25 @@ class SimpleCache {
1703
3811
  }
1704
3812
  _map = new WeakMap();
1705
3813
 
1706
- const gt = (value) => ({ $gt: value });
1707
- const ge = (value) => ({ $ge: value });
1708
- const gte = (value) => ({ $ge: value });
1709
- const lt = (value) => ({ $lt: value });
1710
- const lte = (value) => ({ $le: value });
1711
- const le = (value) => ({ $le: value });
3814
+ const greaterThan = (value) => ({ $gt: value });
3815
+ const gt = greaterThan;
3816
+ const greaterThanEquals = (value) => ({ $ge: value });
3817
+ const greaterEquals = greaterThanEquals;
3818
+ const gte = greaterThanEquals;
3819
+ const ge = greaterThanEquals;
3820
+ const lessThan = (value) => ({ $lt: value });
3821
+ const lt = lessThan;
3822
+ const lessThanEquals = (value) => ({ $le: value });
3823
+ const lessEquals = lessThanEquals;
3824
+ const lte = lessThanEquals;
3825
+ const le = lessThanEquals;
1712
3826
  const exists = (column) => ({ $exists: column });
1713
3827
  const notExists = (column) => ({ $notExists: column });
1714
3828
  const startsWith = (value) => ({ $startsWith: value });
1715
3829
  const endsWith = (value) => ({ $endsWith: value });
1716
3830
  const pattern = (value) => ({ $pattern: value });
1717
3831
  const is = (value) => ({ $is: value });
3832
+ const equals = is;
1718
3833
  const isNot = (value) => ({ $isNot: value });
1719
3834
  const contains = (value) => ({ $contains: value });
1720
3835
  const includes = (value) => ({ $includes: value });
@@ -1749,16 +3864,19 @@ class SchemaPlugin extends XataPlugin {
1749
3864
  __privateSet$2(this, _schemaTables$1, schemaTables);
1750
3865
  }
1751
3866
  build(pluginOptions) {
1752
- const db = new Proxy({}, {
1753
- get: (_target, table) => {
1754
- if (!isString(table))
1755
- throw new Error("Invalid table name");
1756
- if (__privateGet$2(this, _tables)[table] === void 0) {
1757
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
3867
+ const db = new Proxy(
3868
+ {},
3869
+ {
3870
+ get: (_target, table) => {
3871
+ if (!isString(table))
3872
+ throw new Error("Invalid table name");
3873
+ if (__privateGet$2(this, _tables)[table] === void 0) {
3874
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
3875
+ }
3876
+ return __privateGet$2(this, _tables)[table];
1758
3877
  }
1759
- return __privateGet$2(this, _tables)[table];
1760
3878
  }
1761
- });
3879
+ );
1762
3880
  const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1763
3881
  for (const table of tableNames) {
1764
3882
  db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
@@ -1801,23 +3919,23 @@ class SearchPlugin extends XataPlugin {
1801
3919
  __privateAdd$1(this, _schemaTables, void 0);
1802
3920
  __privateSet$1(this, _schemaTables, schemaTables);
1803
3921
  }
1804
- build({ getFetchProps }) {
3922
+ build(pluginOptions) {
1805
3923
  return {
1806
3924
  all: async (query, options = {}) => {
1807
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1808
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3925
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3926
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
1809
3927
  return records.map((record) => {
1810
3928
  const { table = "orphan" } = record.xata;
1811
- return { table, record: initObject(this.db, schemaTables, table, record) };
3929
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
1812
3930
  });
1813
3931
  },
1814
3932
  byTable: async (query, options = {}) => {
1815
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1816
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3933
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3934
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
1817
3935
  return records.reduce((acc, record) => {
1818
3936
  const { table = "orphan" } = record.xata;
1819
3937
  const items = acc[table] ?? [];
1820
- const item = initObject(this.db, schemaTables, table, record);
3938
+ const item = initObject(this.db, schemaTables, table, record, ["*"]);
1821
3939
  return { ...acc, [table]: [...items, item] };
1822
3940
  }, {});
1823
3941
  }
@@ -1826,114 +3944,40 @@ class SearchPlugin extends XataPlugin {
1826
3944
  }
1827
3945
  _schemaTables = new WeakMap();
1828
3946
  _search = new WeakSet();
1829
- search_fn = async function(query, options, getFetchProps) {
1830
- const fetchProps = await getFetchProps();
1831
- const { tables, fuzziness, highlight } = options ?? {};
3947
+ search_fn = async function(query, options, pluginOptions) {
3948
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
1832
3949
  const { records } = await searchBranch({
1833
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1834
- body: { tables, query, fuzziness, highlight },
1835
- ...fetchProps
3950
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3951
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
3952
+ body: { tables, query, fuzziness, prefix, highlight, page },
3953
+ ...pluginOptions
1836
3954
  });
1837
3955
  return records;
1838
3956
  };
1839
3957
  _getSchemaTables = new WeakSet();
1840
- getSchemaTables_fn = async function(getFetchProps) {
3958
+ getSchemaTables_fn = async function(pluginOptions) {
1841
3959
  if (__privateGet$1(this, _schemaTables))
1842
3960
  return __privateGet$1(this, _schemaTables);
1843
- const fetchProps = await getFetchProps();
1844
3961
  const { schema } = await getBranchDetails({
1845
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1846
- ...fetchProps
3962
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3963
+ ...pluginOptions
1847
3964
  });
1848
3965
  __privateSet$1(this, _schemaTables, schema.tables);
1849
3966
  return schema.tables;
1850
3967
  };
1851
3968
 
1852
- const isBranchStrategyBuilder = (strategy) => {
1853
- return typeof strategy === "function";
1854
- };
1855
-
1856
- const envBranchNames = [
1857
- "XATA_BRANCH",
1858
- "VERCEL_GIT_COMMIT_REF",
1859
- "CF_PAGES_BRANCH",
1860
- "BRANCH"
1861
- ];
1862
- async function getCurrentBranchName(options) {
1863
- const env = getBranchByEnvVariable();
1864
- if (env) {
1865
- const details = await getDatabaseBranch(env, options);
1866
- if (details)
1867
- return env;
1868
- console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1869
- }
1870
- const gitBranch = await getGitBranch();
1871
- return resolveXataBranch(gitBranch, options);
1872
- }
1873
- async function getCurrentBranchDetails(options) {
1874
- const branch = await getCurrentBranchName(options);
1875
- return getDatabaseBranch(branch, options);
1876
- }
1877
- async function resolveXataBranch(gitBranch, options) {
1878
- const databaseURL = options?.databaseURL || getDatabaseURL();
1879
- const apiKey = options?.apiKey || getAPIKey();
1880
- if (!databaseURL)
1881
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1882
- if (!apiKey)
1883
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1884
- const [protocol, , host, , dbName] = databaseURL.split("/");
1885
- const [workspace] = host.split(".");
1886
- const { branch } = await resolveBranch({
1887
- apiKey,
1888
- apiUrl: databaseURL,
1889
- fetchImpl: getFetchImplementation(options?.fetchImpl),
1890
- workspacesApiUrl: `${protocol}//${host}`,
1891
- pathParams: { dbName, workspace },
1892
- queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
1893
- });
1894
- return branch;
1895
- }
1896
- async function getDatabaseBranch(branch, options) {
1897
- const databaseURL = options?.databaseURL || getDatabaseURL();
1898
- const apiKey = options?.apiKey || getAPIKey();
1899
- if (!databaseURL)
1900
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1901
- if (!apiKey)
1902
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1903
- const [protocol, , host, , database] = databaseURL.split("/");
1904
- const [workspace] = host.split(".");
1905
- const dbBranchName = `${database}:${branch}`;
1906
- try {
1907
- return await getBranchDetails({
1908
- apiKey,
1909
- apiUrl: databaseURL,
1910
- fetchImpl: getFetchImplementation(options?.fetchImpl),
1911
- workspacesApiUrl: `${protocol}//${host}`,
1912
- pathParams: { dbBranchName, workspace }
1913
- });
1914
- } catch (err) {
1915
- if (isObject(err) && err.status === 404)
1916
- return null;
1917
- throw err;
1918
- }
1919
- }
1920
- function getBranchByEnvVariable() {
1921
- for (const name of envBranchNames) {
1922
- const value = getEnvVariable(name);
1923
- if (value) {
1924
- return value;
1925
- }
1926
- }
1927
- try {
1928
- return XATA_BRANCH;
1929
- } catch (err) {
1930
- }
1931
- }
1932
- function getDatabaseURL() {
1933
- try {
1934
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1935
- } catch (err) {
1936
- return void 0;
3969
+ class TransactionPlugin extends XataPlugin {
3970
+ build(pluginOptions) {
3971
+ return {
3972
+ run: async (operations) => {
3973
+ const response = await branchTransaction({
3974
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3975
+ body: { operations },
3976
+ ...pluginOptions
3977
+ });
3978
+ return response;
3979
+ }
3980
+ };
1937
3981
  }
1938
3982
  }
1939
3983
 
@@ -1960,85 +4004,203 @@ var __privateMethod = (obj, member, method) => {
1960
4004
  return method;
1961
4005
  };
1962
4006
  const buildClient = (plugins) => {
1963
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
4007
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
1964
4008
  return _a = class {
1965
4009
  constructor(options = {}, schemaTables) {
1966
4010
  __privateAdd(this, _parseOptions);
1967
4011
  __privateAdd(this, _getFetchProps);
1968
- __privateAdd(this, _evaluateBranch);
1969
- __privateAdd(this, _branch, void 0);
4012
+ __privateAdd(this, _options, void 0);
1970
4013
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
4014
+ __privateSet(this, _options, safeOptions);
1971
4015
  const pluginOptions = {
1972
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1973
- cache: safeOptions.cache
4016
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
4017
+ cache: safeOptions.cache,
4018
+ host: safeOptions.host
1974
4019
  };
1975
4020
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
1976
4021
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
4022
+ const transactions = new TransactionPlugin().build(pluginOptions);
1977
4023
  this.db = db;
1978
4024
  this.search = search;
4025
+ this.transactions = transactions;
1979
4026
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1980
4027
  if (namespace === void 0)
1981
4028
  continue;
1982
- const result = namespace.build(pluginOptions);
1983
- if (result instanceof Promise) {
1984
- void result.then((namespace2) => {
1985
- this[key] = namespace2;
1986
- });
1987
- } else {
1988
- this[key] = result;
1989
- }
4029
+ this[key] = namespace.build(pluginOptions);
1990
4030
  }
1991
4031
  }
1992
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4032
+ async getConfig() {
4033
+ const databaseURL = __privateGet(this, _options).databaseURL;
4034
+ const branch = __privateGet(this, _options).branch;
4035
+ return { databaseURL, branch };
4036
+ }
4037
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4038
+ const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
4039
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
4040
+ if (isBrowser && !enableBrowser) {
4041
+ throw new Error(
4042
+ "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."
4043
+ );
4044
+ }
1993
4045
  const fetch = getFetchImplementation(options?.fetch);
1994
4046
  const databaseURL = options?.databaseURL || getDatabaseURL();
1995
4047
  const apiKey = options?.apiKey || getAPIKey();
1996
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1997
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1998
- if (!databaseURL || !apiKey) {
1999
- throw new Error("Options databaseURL and apiKey are required");
4048
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
4049
+ const trace = options?.trace ?? defaultTrace;
4050
+ const clientName = options?.clientName;
4051
+ const host = options?.host ?? "production";
4052
+ const xataAgentExtra = options?.xataAgentExtra;
4053
+ if (!apiKey) {
4054
+ throw new Error("Option apiKey is required");
4055
+ }
4056
+ if (!databaseURL) {
4057
+ throw new Error("Option databaseURL is required");
2000
4058
  }
2001
- return { fetch, databaseURL, apiKey, branch, cache };
2002
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
4059
+ const envBranch = getBranch();
4060
+ const previewBranch = getPreviewBranch();
4061
+ const branch = options?.branch || previewBranch || envBranch || "main";
4062
+ if (!!previewBranch && branch !== previewBranch) {
4063
+ console.warn(
4064
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4065
+ );
4066
+ } else if (!!envBranch && branch !== envBranch) {
4067
+ console.warn(
4068
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4069
+ );
4070
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4071
+ console.warn(
4072
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4073
+ );
4074
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4075
+ console.warn(
4076
+ `No branch was passed to the client constructor. Using default branch ${branch}. You can set the branch with the environment variable XATA_BRANCH or by passing the branch option to the client constructor.`
4077
+ );
4078
+ }
4079
+ return {
4080
+ fetch,
4081
+ databaseURL,
4082
+ apiKey,
4083
+ branch,
4084
+ cache,
4085
+ trace,
4086
+ host,
4087
+ clientID: generateUUID(),
4088
+ enableBrowser,
4089
+ clientName,
4090
+ xataAgentExtra
4091
+ };
4092
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
2003
4093
  fetch,
2004
4094
  apiKey,
2005
4095
  databaseURL,
2006
- branch
4096
+ branch,
4097
+ trace,
4098
+ clientID,
4099
+ clientName,
4100
+ xataAgentExtra
2007
4101
  }) {
2008
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
2009
- if (!branchValue)
2010
- throw new Error("Unable to resolve branch value");
2011
4102
  return {
2012
- fetchImpl: fetch,
4103
+ fetch,
2013
4104
  apiKey,
2014
4105
  apiUrl: "",
4106
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
2015
4107
  workspacesApiUrl: (path, params) => {
2016
4108
  const hasBranch = params.dbBranchName ?? params.branch;
2017
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
4109
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
2018
4110
  return databaseURL + newPath;
2019
- }
2020
- };
2021
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
2022
- if (__privateGet(this, _branch))
2023
- return __privateGet(this, _branch);
2024
- if (param === void 0)
2025
- return void 0;
2026
- const strategies = Array.isArray(param) ? [...param] : [param];
2027
- const evaluateBranch = async (strategy) => {
2028
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
4111
+ },
4112
+ trace,
4113
+ clientID,
4114
+ clientName,
4115
+ xataAgentExtra
2029
4116
  };
2030
- for await (const strategy of strategies) {
2031
- const branch = await evaluateBranch(strategy);
2032
- if (branch) {
2033
- __privateSet(this, _branch, branch);
2034
- return branch;
2035
- }
2036
- }
2037
4117
  }, _a;
2038
4118
  };
2039
4119
  class BaseClient extends buildClient() {
2040
4120
  }
2041
4121
 
4122
+ const META = "__";
4123
+ const VALUE = "___";
4124
+ class Serializer {
4125
+ constructor() {
4126
+ this.classes = {};
4127
+ }
4128
+ add(clazz) {
4129
+ this.classes[clazz.name] = clazz;
4130
+ }
4131
+ toJSON(data) {
4132
+ function visit(obj) {
4133
+ if (Array.isArray(obj))
4134
+ return obj.map(visit);
4135
+ const type = typeof obj;
4136
+ if (type === "undefined")
4137
+ return { [META]: "undefined" };
4138
+ if (type === "bigint")
4139
+ return { [META]: "bigint", [VALUE]: obj.toString() };
4140
+ if (obj === null || type !== "object")
4141
+ return obj;
4142
+ const constructor = obj.constructor;
4143
+ const o = { [META]: constructor.name };
4144
+ for (const [key, value] of Object.entries(obj)) {
4145
+ o[key] = visit(value);
4146
+ }
4147
+ if (constructor === Date)
4148
+ o[VALUE] = obj.toISOString();
4149
+ if (constructor === Map)
4150
+ o[VALUE] = Object.fromEntries(obj);
4151
+ if (constructor === Set)
4152
+ o[VALUE] = [...obj];
4153
+ return o;
4154
+ }
4155
+ return JSON.stringify(visit(data));
4156
+ }
4157
+ fromJSON(json) {
4158
+ return JSON.parse(json, (key, value) => {
4159
+ if (value && typeof value === "object" && !Array.isArray(value)) {
4160
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
4161
+ const constructor = this.classes[clazz];
4162
+ if (constructor) {
4163
+ return Object.assign(Object.create(constructor.prototype), rest);
4164
+ }
4165
+ if (clazz === "Date")
4166
+ return new Date(val);
4167
+ if (clazz === "Set")
4168
+ return new Set(val);
4169
+ if (clazz === "Map")
4170
+ return new Map(Object.entries(val));
4171
+ if (clazz === "bigint")
4172
+ return BigInt(val);
4173
+ if (clazz === "undefined")
4174
+ return void 0;
4175
+ return rest;
4176
+ }
4177
+ return value;
4178
+ });
4179
+ }
4180
+ }
4181
+ const defaultSerializer = new Serializer();
4182
+ const serialize = (data) => {
4183
+ return defaultSerializer.toJSON(data);
4184
+ };
4185
+ const deserialize = (json) => {
4186
+ return defaultSerializer.fromJSON(json);
4187
+ };
4188
+
4189
+ function buildWorkerRunner(config) {
4190
+ return function xataWorker(name, worker) {
4191
+ return async (...args) => {
4192
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
4193
+ const result = await fetch(url, {
4194
+ method: "POST",
4195
+ headers: { "Content-Type": "application/json" },
4196
+ body: serialize({ args })
4197
+ });
4198
+ const text = await result.text();
4199
+ return deserialize(text);
4200
+ };
4201
+ };
4202
+ }
4203
+
2042
4204
  class XataError extends Error {
2043
4205
  constructor(message, status) {
2044
4206
  super(message);
@@ -2047,6 +4209,7 @@ class XataError extends Error {
2047
4209
  }
2048
4210
 
2049
4211
  exports.BaseClient = BaseClient;
4212
+ exports.FetcherError = FetcherError;
2050
4213
  exports.Operations = operationsByTag;
2051
4214
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
2052
4215
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -2059,6 +4222,7 @@ exports.Repository = Repository;
2059
4222
  exports.RestRepository = RestRepository;
2060
4223
  exports.SchemaPlugin = SchemaPlugin;
2061
4224
  exports.SearchPlugin = SearchPlugin;
4225
+ exports.Serializer = Serializer;
2062
4226
  exports.SimpleCache = SimpleCache;
2063
4227
  exports.XataApiClient = XataApiClient;
2064
4228
  exports.XataApiPlugin = XataApiPlugin;
@@ -2067,40 +4231,66 @@ exports.XataPlugin = XataPlugin;
2067
4231
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
2068
4232
  exports.addGitBranchesEntry = addGitBranchesEntry;
2069
4233
  exports.addTableColumn = addTableColumn;
4234
+ exports.aggregateTable = aggregateTable;
4235
+ exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
4236
+ exports.askTable = askTable;
4237
+ exports.branchTransaction = branchTransaction;
2070
4238
  exports.buildClient = buildClient;
4239
+ exports.buildPreviewBranchName = buildPreviewBranchName;
4240
+ exports.buildProviderString = buildProviderString;
4241
+ exports.buildWorkerRunner = buildWorkerRunner;
2071
4242
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
2072
4243
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
4244
+ exports.compareBranchSchemas = compareBranchSchemas;
4245
+ exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
4246
+ exports.compareMigrationRequest = compareMigrationRequest;
2073
4247
  exports.contains = contains;
4248
+ exports.copyBranch = copyBranch;
2074
4249
  exports.createBranch = createBranch;
2075
4250
  exports.createDatabase = createDatabase;
4251
+ exports.createMigrationRequest = createMigrationRequest;
2076
4252
  exports.createTable = createTable;
2077
4253
  exports.createUserAPIKey = createUserAPIKey;
2078
4254
  exports.createWorkspace = createWorkspace;
2079
4255
  exports.deleteBranch = deleteBranch;
2080
4256
  exports.deleteColumn = deleteColumn;
2081
4257
  exports.deleteDatabase = deleteDatabase;
4258
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
4259
+ exports.deleteFile = deleteFile;
4260
+ exports.deleteFileItem = deleteFileItem;
2082
4261
  exports.deleteRecord = deleteRecord;
2083
4262
  exports.deleteTable = deleteTable;
2084
4263
  exports.deleteUser = deleteUser;
2085
4264
  exports.deleteUserAPIKey = deleteUserAPIKey;
2086
4265
  exports.deleteWorkspace = deleteWorkspace;
4266
+ exports.deserialize = deserialize;
2087
4267
  exports.endsWith = endsWith;
4268
+ exports.equals = equals;
2088
4269
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
2089
4270
  exports.exists = exists;
4271
+ exports.fileAccess = fileAccess;
2090
4272
  exports.ge = ge;
2091
4273
  exports.getAPIKey = getAPIKey;
4274
+ exports.getBranch = getBranch;
2092
4275
  exports.getBranchDetails = getBranchDetails;
2093
4276
  exports.getBranchList = getBranchList;
2094
4277
  exports.getBranchMetadata = getBranchMetadata;
2095
4278
  exports.getBranchMigrationHistory = getBranchMigrationHistory;
2096
4279
  exports.getBranchMigrationPlan = getBranchMigrationPlan;
4280
+ exports.getBranchSchemaHistory = getBranchSchemaHistory;
2097
4281
  exports.getBranchStats = getBranchStats;
2098
4282
  exports.getColumn = getColumn;
2099
- exports.getCurrentBranchDetails = getCurrentBranchDetails;
2100
- exports.getCurrentBranchName = getCurrentBranchName;
4283
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
2101
4284
  exports.getDatabaseList = getDatabaseList;
4285
+ exports.getDatabaseMetadata = getDatabaseMetadata;
2102
4286
  exports.getDatabaseURL = getDatabaseURL;
4287
+ exports.getFile = getFile;
4288
+ exports.getFileItem = getFileItem;
2103
4289
  exports.getGitBranchesMapping = getGitBranchesMapping;
4290
+ exports.getHostUrl = getHostUrl;
4291
+ exports.getMigrationRequest = getMigrationRequest;
4292
+ exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
4293
+ exports.getPreviewBranch = getPreviewBranch;
2104
4294
  exports.getRecord = getRecord;
2105
4295
  exports.getTableColumns = getTableColumns;
2106
4296
  exports.getTableSchema = getTableSchema;
@@ -2109,6 +4299,9 @@ exports.getUserAPIKeys = getUserAPIKeys;
2109
4299
  exports.getWorkspace = getWorkspace;
2110
4300
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
2111
4301
  exports.getWorkspacesList = getWorkspacesList;
4302
+ exports.greaterEquals = greaterEquals;
4303
+ exports.greaterThan = greaterThan;
4304
+ exports.greaterThanEquals = greaterThanEquals;
2112
4305
  exports.gt = gt;
2113
4306
  exports.gte = gte;
2114
4307
  exports.includes = includes;
@@ -2120,30 +4313,55 @@ exports.insertRecordWithID = insertRecordWithID;
2120
4313
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
2121
4314
  exports.is = is;
2122
4315
  exports.isCursorPaginationOptions = isCursorPaginationOptions;
4316
+ exports.isHostProviderAlias = isHostProviderAlias;
4317
+ exports.isHostProviderBuilder = isHostProviderBuilder;
2123
4318
  exports.isIdentifiable = isIdentifiable;
2124
4319
  exports.isNot = isNot;
2125
4320
  exports.isXataRecord = isXataRecord;
2126
4321
  exports.le = le;
4322
+ exports.lessEquals = lessEquals;
4323
+ exports.lessThan = lessThan;
4324
+ exports.lessThanEquals = lessThanEquals;
4325
+ exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
4326
+ exports.listRegions = listRegions;
2127
4327
  exports.lt = lt;
2128
4328
  exports.lte = lte;
4329
+ exports.mergeMigrationRequest = mergeMigrationRequest;
2129
4330
  exports.notExists = notExists;
2130
4331
  exports.operationsByTag = operationsByTag;
4332
+ exports.parseProviderString = parseProviderString;
4333
+ exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
2131
4334
  exports.pattern = pattern;
4335
+ exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
4336
+ exports.pushBranchMigrations = pushBranchMigrations;
4337
+ exports.putFile = putFile;
4338
+ exports.putFileItem = putFileItem;
4339
+ exports.queryMigrationRequests = queryMigrationRequests;
2132
4340
  exports.queryTable = queryTable;
2133
4341
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
2134
4342
  exports.removeWorkspaceMember = removeWorkspaceMember;
4343
+ exports.renameDatabase = renameDatabase;
2135
4344
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
2136
4345
  exports.resolveBranch = resolveBranch;
2137
4346
  exports.searchBranch = searchBranch;
2138
4347
  exports.searchTable = searchTable;
4348
+ exports.serialize = serialize;
2139
4349
  exports.setTableSchema = setTableSchema;
4350
+ exports.sqlQuery = sqlQuery;
2140
4351
  exports.startsWith = startsWith;
4352
+ exports.summarizeTable = summarizeTable;
2141
4353
  exports.updateBranchMetadata = updateBranchMetadata;
4354
+ exports.updateBranchSchema = updateBranchSchema;
2142
4355
  exports.updateColumn = updateColumn;
4356
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
4357
+ exports.updateDatabaseMetadata = updateDatabaseMetadata;
4358
+ exports.updateMigrationRequest = updateMigrationRequest;
2143
4359
  exports.updateRecordWithID = updateRecordWithID;
2144
4360
  exports.updateTable = updateTable;
2145
4361
  exports.updateUser = updateUser;
2146
4362
  exports.updateWorkspace = updateWorkspace;
4363
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
2147
4364
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
2148
4365
  exports.upsertRecordWithID = upsertRecordWithID;
4366
+ exports.vectorSearchTable = vectorSearchTable;
2149
4367
  //# sourceMappingURL=index.cjs.map