@xata.io/client 0.0.0-alpha.vebf0406 → 0.0.0-alpha.vec0147b

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