@xata.io/client 0.0.0-alpha.vfda8f2e → 0.0.0-alpha.vfdc5c07

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,7 +1,8 @@
1
1
  'use strict';
2
2
 
3
- const defaultTrace = async (_name, fn, _options) => {
3
+ const defaultTrace = async (name, fn, _options) => {
4
4
  return await fn({
5
+ name,
5
6
  setAttributes: () => {
6
7
  return;
7
8
  }
@@ -19,7 +20,8 @@ const TraceAttributes = {
19
20
  HTTP_METHOD: "http.method",
20
21
  HTTP_URL: "http.url",
21
22
  HTTP_ROUTE: "http.route",
22
- HTTP_TARGET: "http.target"
23
+ HTTP_TARGET: "http.target",
24
+ CLOUDFLARE_RAY_ID: "cf.ray"
23
25
  };
24
26
 
25
27
  function notEmpty(value) {
@@ -28,8 +30,18 @@ function notEmpty(value) {
28
30
  function compact(arr) {
29
31
  return arr.filter(notEmpty);
30
32
  }
33
+ function compactObject(obj) {
34
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
35
+ }
36
+ function isBlob(value) {
37
+ try {
38
+ return value instanceof Blob;
39
+ } catch (error) {
40
+ return false;
41
+ }
42
+ }
31
43
  function isObject(value) {
32
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
44
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
33
45
  }
34
46
  function isDefined(value) {
35
47
  return value !== null && value !== void 0;
@@ -84,16 +96,39 @@ function chunk(array, chunkSize) {
84
96
  async function timeout(ms) {
85
97
  return new Promise((resolve) => setTimeout(resolve, ms));
86
98
  }
99
+ function timeoutWithCancel(ms) {
100
+ let timeoutId;
101
+ const promise = new Promise((resolve) => {
102
+ timeoutId = setTimeout(() => {
103
+ resolve();
104
+ }, ms);
105
+ });
106
+ return {
107
+ cancel: () => clearTimeout(timeoutId),
108
+ promise
109
+ };
110
+ }
111
+ function promiseMap(inputValues, mapper) {
112
+ const reducer = (acc$, inputValue) => acc$.then(
113
+ (acc) => mapper(inputValue).then((result) => {
114
+ acc.push(result);
115
+ return acc;
116
+ })
117
+ );
118
+ return inputValues.reduce(reducer, Promise.resolve([]));
119
+ }
87
120
 
88
121
  function getEnvironment() {
89
122
  try {
90
- if (isObject(process) && isObject(process.env)) {
123
+ if (isDefined(process) && isDefined(process.env)) {
91
124
  return {
92
125
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
93
126
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
94
127
  branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
95
- envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
96
- fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
128
+ deployPreview: process.env.XATA_PREVIEW,
129
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
130
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
131
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
97
132
  };
98
133
  }
99
134
  } catch (err) {
@@ -104,8 +139,10 @@ function getEnvironment() {
104
139
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
105
140
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
106
141
  branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
107
- envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
108
- fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
142
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
143
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
144
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
145
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
109
146
  };
110
147
  }
111
148
  } catch (err) {
@@ -114,8 +151,10 @@ function getEnvironment() {
114
151
  apiKey: getGlobalApiKey(),
115
152
  databaseURL: getGlobalDatabaseURL(),
116
153
  branch: getGlobalBranch(),
117
- envBranch: void 0,
118
- fallbackBranch: getGlobalFallbackBranch()
154
+ deployPreview: void 0,
155
+ deployPreviewBranch: void 0,
156
+ vercelGitCommitRef: void 0,
157
+ vercelGitRepoOwner: void 0
119
158
  };
120
159
  }
121
160
  function getEnableBrowserVariable() {
@@ -158,39 +197,48 @@ function getGlobalBranch() {
158
197
  return void 0;
159
198
  }
160
199
  }
161
- function getGlobalFallbackBranch() {
200
+ function getDatabaseURL() {
162
201
  try {
163
- return XATA_FALLBACK_BRANCH;
202
+ const { databaseURL } = getEnvironment();
203
+ return databaseURL;
164
204
  } catch (err) {
165
205
  return void 0;
166
206
  }
167
207
  }
168
- async function getGitBranch() {
169
- const cmd = ["git", "branch", "--show-current"];
170
- const fullCmd = cmd.join(" ");
171
- const nodeModule = ["child", "process"].join("_");
172
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
208
+ function getAPIKey() {
173
209
  try {
174
- if (typeof require === "function") {
175
- return require(nodeModule).execSync(fullCmd, execOptions).trim();
176
- }
177
- const { execSync } = await import(nodeModule);
178
- return execSync(fullCmd, execOptions).toString().trim();
210
+ const { apiKey } = getEnvironment();
211
+ return apiKey;
179
212
  } catch (err) {
213
+ return void 0;
180
214
  }
215
+ }
216
+ function getBranch() {
181
217
  try {
182
- if (isObject(Deno)) {
183
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
184
- return new TextDecoder().decode(await process2.output()).trim();
185
- }
218
+ const { branch } = getEnvironment();
219
+ return branch;
186
220
  } catch (err) {
221
+ return void 0;
187
222
  }
188
223
  }
189
-
190
- function getAPIKey() {
224
+ function buildPreviewBranchName({ org, branch }) {
225
+ return `preview-${org}-${branch}`;
226
+ }
227
+ function getPreviewBranch() {
191
228
  try {
192
- const { apiKey } = getEnvironment();
193
- return apiKey;
229
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
230
+ if (deployPreviewBranch)
231
+ return deployPreviewBranch;
232
+ switch (deployPreview) {
233
+ case "vercel": {
234
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
235
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
236
+ return void 0;
237
+ }
238
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
239
+ }
240
+ }
241
+ return void 0;
194
242
  } catch (err) {
195
243
  return void 0;
196
244
  }
@@ -219,13 +267,13 @@ var __privateMethod$4 = (obj, member, method) => {
219
267
  return method;
220
268
  };
221
269
  var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
270
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
222
271
  function getFetchImplementation(userFetch) {
223
272
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
224
- const fetchImpl = userFetch ?? globalFetch;
273
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
274
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
225
275
  if (!fetchImpl) {
226
- throw new Error(
227
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
228
- );
276
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
229
277
  }
230
278
  return fetchImpl;
231
279
  }
@@ -249,20 +297,28 @@ class ApiRequestPool {
249
297
  }
250
298
  return __privateGet$8(this, _fetch);
251
299
  }
252
- request(url, options, context = { start: new Date(), stalled: false }) {
253
- const fetch2 = this.getFetch();
254
- return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
255
- const response = await fetch2(url, options);
300
+ request(url, options) {
301
+ const start = /* @__PURE__ */ new Date();
302
+ const fetchImpl = this.getFetch();
303
+ const runRequest = async (stalled = false) => {
304
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
305
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
306
+ if (!response) {
307
+ throw new Error("Request timed out");
308
+ }
256
309
  if (response.status === 429) {
257
310
  const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
258
311
  await timeout(rateLimitReset * 1e3);
259
- return await this.request(url, options, { ...context, stalled: true });
312
+ return await runRequest(true);
260
313
  }
261
- if (context.stalled) {
262
- const stalledTime = new Date().getTime() - context.start.getTime();
263
- console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
314
+ if (stalled) {
315
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
316
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
264
317
  }
265
318
  return response;
319
+ };
320
+ return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
321
+ return await runRequest();
266
322
  });
267
323
  }
268
324
  }
@@ -292,7 +348,187 @@ enqueue_fn = function(task) {
292
348
  return promise;
293
349
  };
294
350
 
295
- const VERSION = "0.0.0-alpha.vfda8f2e";
351
+ function generateUUID() {
352
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
353
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
354
+ return v.toString(16);
355
+ });
356
+ }
357
+
358
+ async function getBytes(stream, onChunk) {
359
+ const reader = stream.getReader();
360
+ let result;
361
+ while (!(result = await reader.read()).done) {
362
+ onChunk(result.value);
363
+ }
364
+ }
365
+ function getLines(onLine) {
366
+ let buffer;
367
+ let position;
368
+ let fieldLength;
369
+ let discardTrailingNewline = false;
370
+ return function onChunk(arr) {
371
+ if (buffer === void 0) {
372
+ buffer = arr;
373
+ position = 0;
374
+ fieldLength = -1;
375
+ } else {
376
+ buffer = concat(buffer, arr);
377
+ }
378
+ const bufLength = buffer.length;
379
+ let lineStart = 0;
380
+ while (position < bufLength) {
381
+ if (discardTrailingNewline) {
382
+ if (buffer[position] === 10 /* NewLine */) {
383
+ lineStart = ++position;
384
+ }
385
+ discardTrailingNewline = false;
386
+ }
387
+ let lineEnd = -1;
388
+ for (; position < bufLength && lineEnd === -1; ++position) {
389
+ switch (buffer[position]) {
390
+ case 58 /* Colon */:
391
+ if (fieldLength === -1) {
392
+ fieldLength = position - lineStart;
393
+ }
394
+ break;
395
+ case 13 /* CarriageReturn */:
396
+ discardTrailingNewline = true;
397
+ case 10 /* NewLine */:
398
+ lineEnd = position;
399
+ break;
400
+ }
401
+ }
402
+ if (lineEnd === -1) {
403
+ break;
404
+ }
405
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
406
+ lineStart = position;
407
+ fieldLength = -1;
408
+ }
409
+ if (lineStart === bufLength) {
410
+ buffer = void 0;
411
+ } else if (lineStart !== 0) {
412
+ buffer = buffer.subarray(lineStart);
413
+ position -= lineStart;
414
+ }
415
+ };
416
+ }
417
+ function getMessages(onId, onRetry, onMessage) {
418
+ let message = newMessage();
419
+ const decoder = new TextDecoder();
420
+ return function onLine(line, fieldLength) {
421
+ if (line.length === 0) {
422
+ onMessage?.(message);
423
+ message = newMessage();
424
+ } else if (fieldLength > 0) {
425
+ const field = decoder.decode(line.subarray(0, fieldLength));
426
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
427
+ const value = decoder.decode(line.subarray(valueOffset));
428
+ switch (field) {
429
+ case "data":
430
+ message.data = message.data ? message.data + "\n" + value : value;
431
+ break;
432
+ case "event":
433
+ message.event = value;
434
+ break;
435
+ case "id":
436
+ onId(message.id = value);
437
+ break;
438
+ case "retry":
439
+ const retry = parseInt(value, 10);
440
+ if (!isNaN(retry)) {
441
+ onRetry(message.retry = retry);
442
+ }
443
+ break;
444
+ }
445
+ }
446
+ };
447
+ }
448
+ function concat(a, b) {
449
+ const res = new Uint8Array(a.length + b.length);
450
+ res.set(a);
451
+ res.set(b, a.length);
452
+ return res;
453
+ }
454
+ function newMessage() {
455
+ return {
456
+ data: "",
457
+ event: "",
458
+ id: "",
459
+ retry: void 0
460
+ };
461
+ }
462
+ const EventStreamContentType = "text/event-stream";
463
+ const LastEventId = "last-event-id";
464
+ function fetchEventSource(input, {
465
+ signal: inputSignal,
466
+ headers: inputHeaders,
467
+ onopen: inputOnOpen,
468
+ onmessage,
469
+ onclose,
470
+ onerror,
471
+ fetch: inputFetch,
472
+ ...rest
473
+ }) {
474
+ return new Promise((resolve, reject) => {
475
+ const headers = { ...inputHeaders };
476
+ if (!headers.accept) {
477
+ headers.accept = EventStreamContentType;
478
+ }
479
+ let curRequestController;
480
+ function dispose() {
481
+ curRequestController.abort();
482
+ }
483
+ inputSignal?.addEventListener("abort", () => {
484
+ dispose();
485
+ resolve();
486
+ });
487
+ const fetchImpl = inputFetch ?? fetch;
488
+ const onopen = inputOnOpen ?? defaultOnOpen;
489
+ async function create() {
490
+ curRequestController = new AbortController();
491
+ try {
492
+ const response = await fetchImpl(input, {
493
+ ...rest,
494
+ headers,
495
+ signal: curRequestController.signal
496
+ });
497
+ await onopen(response);
498
+ await getBytes(
499
+ response.body,
500
+ getLines(
501
+ getMessages(
502
+ (id) => {
503
+ if (id) {
504
+ headers[LastEventId] = id;
505
+ } else {
506
+ delete headers[LastEventId];
507
+ }
508
+ },
509
+ (_retry) => {
510
+ },
511
+ onmessage
512
+ )
513
+ )
514
+ );
515
+ onclose?.();
516
+ dispose();
517
+ resolve();
518
+ } catch (err) {
519
+ }
520
+ }
521
+ create();
522
+ });
523
+ }
524
+ function defaultOnOpen(response) {
525
+ const contentType = response.headers?.get("content-type");
526
+ if (!contentType?.startsWith(EventStreamContentType)) {
527
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
528
+ }
529
+ }
530
+
531
+ const VERSION = "0.26.8";
296
532
 
297
533
  class ErrorWithCause extends Error {
298
534
  constructor(message, options) {
@@ -303,7 +539,7 @@ class FetcherError extends ErrorWithCause {
303
539
  constructor(status, data, requestId) {
304
540
  super(getMessage(data));
305
541
  this.status = status;
306
- this.errors = isBulkError(data) ? data.errors : void 0;
542
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
307
543
  this.requestId = requestId;
308
544
  if (data instanceof Error) {
309
545
  this.stack = data.stack;
@@ -368,14 +604,27 @@ function hostHeader(url) {
368
604
  const { groups } = pattern.exec(url) ?? {};
369
605
  return groups?.host ? { Host: groups.host } : {};
370
606
  }
607
+ async function parseBody(body, headers) {
608
+ if (!isDefined(body))
609
+ return void 0;
610
+ if (isBlob(body) || typeof body.text === "function") {
611
+ return body;
612
+ }
613
+ const { "Content-Type": contentType } = headers ?? {};
614
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
615
+ return JSON.stringify(body);
616
+ }
617
+ return body;
618
+ }
619
+ const defaultClientID = generateUUID();
371
620
  async function fetch$1({
372
621
  url: path,
373
622
  method,
374
623
  body,
375
- headers,
624
+ headers: customHeaders,
376
625
  pathParams,
377
626
  queryParams,
378
- fetchImpl,
627
+ fetch: fetch2,
379
628
  apiKey,
380
629
  endpoint,
381
630
  apiUrl,
@@ -384,9 +633,12 @@ async function fetch$1({
384
633
  signal,
385
634
  clientID,
386
635
  sessionID,
387
- fetchOptions = {}
636
+ clientName,
637
+ xataAgentExtra,
638
+ fetchOptions = {},
639
+ rawResponse = false
388
640
  }) {
389
- pool.setFetch(fetchImpl);
641
+ pool.setFetch(fetch2);
390
642
  return await trace(
391
643
  `${method.toUpperCase()} ${path}`,
392
644
  async ({ setAttributes }) => {
@@ -397,19 +649,27 @@ async function fetch$1({
397
649
  [TraceAttributes.HTTP_URL]: url,
398
650
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
399
651
  });
652
+ const xataAgent = compact([
653
+ ["client", "TS_SDK"],
654
+ ["version", VERSION],
655
+ isDefined(clientName) ? ["service", clientName] : void 0,
656
+ ...Object.entries(xataAgentExtra ?? {})
657
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
658
+ const headers = compactObject({
659
+ "Accept-Encoding": "identity",
660
+ "Content-Type": "application/json",
661
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
662
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
663
+ "X-Xata-Agent": xataAgent,
664
+ ...customHeaders,
665
+ ...hostHeader(fullUrl),
666
+ Authorization: `Bearer ${apiKey}`
667
+ });
400
668
  const response = await pool.request(url, {
401
669
  ...fetchOptions,
402
670
  method: method.toUpperCase(),
403
- body: body ? JSON.stringify(body) : void 0,
404
- headers: {
405
- "Content-Type": "application/json",
406
- "User-Agent": `Xata client-ts/${VERSION}`,
407
- "X-Xata-Client-ID": clientID ?? "",
408
- "X-Xata-Session-ID": sessionID ?? "",
409
- ...headers,
410
- ...hostHeader(fullUrl),
411
- Authorization: `Bearer ${apiKey}`
412
- },
671
+ body: await parseBody(body, headers),
672
+ headers,
413
673
  signal
414
674
  });
415
675
  const { host, protocol } = parseUrl(response.url);
@@ -419,8 +679,12 @@ async function fetch$1({
419
679
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
420
680
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
421
681
  [TraceAttributes.HTTP_HOST]: host,
422
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
682
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
683
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
423
684
  });
685
+ const message = response.headers?.get("x-xata-message");
686
+ if (message)
687
+ console.warn(message);
424
688
  if (response.status === 204) {
425
689
  return {};
426
690
  }
@@ -428,7 +692,7 @@ async function fetch$1({
428
692
  throw new FetcherError(response.status, "Rate limit exceeded", requestId);
429
693
  }
430
694
  try {
431
- const jsonResponse = await response.json();
695
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
432
696
  if (response.ok) {
433
697
  return jsonResponse;
434
698
  }
@@ -440,6 +704,59 @@ async function fetch$1({
440
704
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
441
705
  );
442
706
  }
707
+ function fetchSSERequest({
708
+ url: path,
709
+ method,
710
+ body,
711
+ headers: customHeaders,
712
+ pathParams,
713
+ queryParams,
714
+ fetch: fetch2,
715
+ apiKey,
716
+ endpoint,
717
+ apiUrl,
718
+ workspacesApiUrl,
719
+ onMessage,
720
+ onError,
721
+ onClose,
722
+ signal,
723
+ clientID,
724
+ sessionID,
725
+ clientName,
726
+ xataAgentExtra
727
+ }) {
728
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
729
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
730
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
731
+ void fetchEventSource(url, {
732
+ method,
733
+ body: JSON.stringify(body),
734
+ fetch: fetch2,
735
+ signal,
736
+ headers: {
737
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
738
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
739
+ "X-Xata-Agent": compact([
740
+ ["client", "TS_SDK"],
741
+ ["version", VERSION],
742
+ isDefined(clientName) ? ["service", clientName] : void 0,
743
+ ...Object.entries(xataAgentExtra ?? {})
744
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
745
+ ...customHeaders,
746
+ Authorization: `Bearer ${apiKey}`,
747
+ "Content-Type": "application/json"
748
+ },
749
+ onmessage(ev) {
750
+ onMessage?.(JSON.parse(ev.data));
751
+ },
752
+ onerror(ev) {
753
+ onError?.(JSON.parse(ev.data));
754
+ },
755
+ onclose() {
756
+ onClose?.();
757
+ }
758
+ });
759
+ }
443
760
  function parseUrl(url) {
444
761
  try {
445
762
  const { host, protocol } = new URL(url);
@@ -451,17 +768,12 @@ function parseUrl(url) {
451
768
 
452
769
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
453
770
 
454
- const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
455
771
  const getBranchList = (variables, signal) => dataPlaneFetch({
456
772
  url: "/dbs/{dbName}",
457
773
  method: "get",
458
774
  ...variables,
459
775
  signal
460
776
  });
461
- const dEPRECATEDcreateDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
462
- const dEPRECATEDdeleteDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "delete", ...variables, signal });
463
- const dEPRECATEDgetDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "get", ...variables, signal });
464
- const dEPRECATEDupdateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
465
777
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
466
778
  url: "/db/{dbBranchName}",
467
779
  method: "get",
@@ -475,6 +787,18 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
475
787
  ...variables,
476
788
  signal
477
789
  });
790
+ const getSchema = (variables, signal) => dataPlaneFetch({
791
+ url: "/db/{dbBranchName}/schema",
792
+ method: "get",
793
+ ...variables,
794
+ signal
795
+ });
796
+ const copyBranch = (variables, signal) => dataPlaneFetch({
797
+ url: "/db/{dbBranchName}/copy",
798
+ method: "post",
799
+ ...variables,
800
+ signal
801
+ });
478
802
  const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
479
803
  url: "/db/{dbBranchName}/metadata",
480
804
  method: "put",
@@ -500,7 +824,6 @@ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName
500
824
  const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
501
825
  const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
502
826
  const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
503
- const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
504
827
  const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
505
828
  const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
506
829
  const getMigrationRequest = (variables, signal) => dataPlaneFetch({
@@ -525,6 +848,7 @@ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{
525
848
  const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
526
849
  const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
527
850
  const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
851
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
528
852
  const createTable = (variables, signal) => dataPlaneFetch({
529
853
  url: "/db/{dbBranchName}/tables/{tableName}",
530
854
  method: "put",
@@ -567,7 +891,44 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
567
891
  ...variables,
568
892
  signal
569
893
  });
894
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
570
895
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
896
+ const getFileItem = (variables, signal) => dataPlaneFetch({
897
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
898
+ method: "get",
899
+ ...variables,
900
+ signal
901
+ });
902
+ const putFileItem = (variables, signal) => dataPlaneFetch({
903
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
904
+ method: "put",
905
+ ...variables,
906
+ signal
907
+ });
908
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
909
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
910
+ method: "delete",
911
+ ...variables,
912
+ signal
913
+ });
914
+ const getFile = (variables, signal) => dataPlaneFetch({
915
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
916
+ method: "get",
917
+ ...variables,
918
+ signal
919
+ });
920
+ const putFile = (variables, signal) => dataPlaneFetch({
921
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
922
+ method: "put",
923
+ ...variables,
924
+ signal
925
+ });
926
+ const deleteFile = (variables, signal) => dataPlaneFetch({
927
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
928
+ method: "delete",
929
+ ...variables,
930
+ signal
931
+ });
571
932
  const getRecord = (variables, signal) => dataPlaneFetch({
572
933
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
573
934
  method: "get",
@@ -597,21 +958,35 @@ const searchTable = (variables, signal) => dataPlaneFetch({
597
958
  ...variables,
598
959
  signal
599
960
  });
961
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
962
+ const askTable = (variables, signal) => dataPlaneFetch({
963
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
964
+ method: "post",
965
+ ...variables,
966
+ signal
967
+ });
968
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
600
969
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
601
970
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
971
+ const fileAccess = (variables, signal) => dataPlaneFetch({
972
+ url: "/file/{fileId}",
973
+ method: "get",
974
+ ...variables,
975
+ signal
976
+ });
977
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
978
+ url: "/db/{dbBranchName}/sql",
979
+ method: "post",
980
+ ...variables,
981
+ signal
982
+ });
602
983
  const operationsByTag$2 = {
603
- database: {
604
- dEPRECATEDgetDatabaseList,
605
- dEPRECATEDcreateDatabase,
606
- dEPRECATEDdeleteDatabase,
607
- dEPRECATEDgetDatabaseMetadata,
608
- dEPRECATEDupdateDatabaseMetadata
609
- },
610
984
  branch: {
611
985
  getBranchList,
612
986
  getBranchDetails,
613
987
  createBranch,
614
988
  deleteBranch,
989
+ copyBranch,
615
990
  updateBranchMetadata,
616
991
  getBranchMetadata,
617
992
  getBranchStats,
@@ -621,6 +996,7 @@ const operationsByTag$2 = {
621
996
  resolveBranch
622
997
  },
623
998
  migrations: {
999
+ getSchema,
624
1000
  getBranchMigrationHistory,
625
1001
  getBranchMigrationPlan,
626
1002
  executeBranchMigrationPlan,
@@ -629,17 +1005,8 @@ const operationsByTag$2 = {
629
1005
  compareBranchSchemas,
630
1006
  updateBranchSchema,
631
1007
  previewBranchSchemaEdit,
632
- applyBranchSchemaEdit
633
- },
634
- records: {
635
- branchTransaction,
636
- insertRecord,
637
- getRecord,
638
- insertRecordWithID,
639
- updateRecordWithID,
640
- upsertRecordWithID,
641
- deleteRecord,
642
- bulkInsertTableRecords
1008
+ applyBranchSchemaEdit,
1009
+ pushBranchMigrations
643
1010
  },
644
1011
  migrationRequests: {
645
1012
  queryMigrationRequests,
@@ -663,11 +1030,34 @@ const operationsByTag$2 = {
663
1030
  updateColumn,
664
1031
  deleteColumn
665
1032
  },
666
- searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
1033
+ records: {
1034
+ branchTransaction,
1035
+ insertRecord,
1036
+ getRecord,
1037
+ insertRecordWithID,
1038
+ updateRecordWithID,
1039
+ upsertRecordWithID,
1040
+ deleteRecord,
1041
+ bulkInsertTableRecords
1042
+ },
1043
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess },
1044
+ searchAndFilter: {
1045
+ queryTable,
1046
+ searchBranch,
1047
+ searchTable,
1048
+ vectorSearchTable,
1049
+ askTable,
1050
+ askTableSession,
1051
+ summarizeTable,
1052
+ aggregateTable
1053
+ },
1054
+ sql: { sqlQuery }
667
1055
  };
668
1056
 
669
1057
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
670
1058
 
1059
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1060
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
671
1061
  const getUser = (variables, signal) => controlPlaneFetch({
672
1062
  url: "/user",
673
1063
  method: "get",
@@ -704,6 +1094,31 @@ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
704
1094
  ...variables,
705
1095
  signal
706
1096
  });
1097
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1098
+ url: "/user/oauth/clients",
1099
+ method: "get",
1100
+ ...variables,
1101
+ signal
1102
+ });
1103
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1104
+ url: "/user/oauth/clients/{clientId}",
1105
+ method: "delete",
1106
+ ...variables,
1107
+ signal
1108
+ });
1109
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1110
+ url: "/user/oauth/tokens",
1111
+ method: "get",
1112
+ ...variables,
1113
+ signal
1114
+ });
1115
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1116
+ url: "/user/oauth/tokens/{token}",
1117
+ method: "delete",
1118
+ ...variables,
1119
+ signal
1120
+ });
1121
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
707
1122
  const getWorkspacesList = (variables, signal) => controlPlaneFetch({
708
1123
  url: "/workspaces",
709
1124
  method: "get",
@@ -747,6 +1162,20 @@ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ u
747
1162
  const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
748
1163
  const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
749
1164
  const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1165
+ const listClusters = (variables, signal) => controlPlaneFetch({
1166
+ url: "/workspaces/{workspaceId}/clusters",
1167
+ method: "get",
1168
+ ...variables,
1169
+ signal
1170
+ });
1171
+ const createCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "post", ...variables, signal });
1172
+ const getCluster = (variables, signal) => controlPlaneFetch({
1173
+ url: "/workspaces/{workspaceId}/clusters/{clusterId}",
1174
+ method: "get",
1175
+ ...variables,
1176
+ signal
1177
+ });
1178
+ const updateCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters/{clusterId}", method: "patch", ...variables, signal });
750
1179
  const getDatabaseList = (variables, signal) => controlPlaneFetch({
751
1180
  url: "/workspaces/{workspaceId}/dbs",
752
1181
  method: "get",
@@ -762,6 +1191,10 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
762
1191
  });
763
1192
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
764
1193
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1194
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1195
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1196
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1197
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
765
1198
  const listRegions = (variables, signal) => controlPlaneFetch({
766
1199
  url: "/workspaces/{workspaceId}/regions",
767
1200
  method: "get",
@@ -769,6 +1202,15 @@ const listRegions = (variables, signal) => controlPlaneFetch({
769
1202
  signal
770
1203
  });
771
1204
  const operationsByTag$1 = {
1205
+ oAuth: {
1206
+ getAuthorizationCode,
1207
+ grantAuthorizationCode,
1208
+ getUserOAuthClients,
1209
+ deleteUserOAuthClient,
1210
+ getUserOAuthAccessTokens,
1211
+ deleteOAuthAccessToken,
1212
+ updateOAuthAccessToken
1213
+ },
772
1214
  users: { getUser, updateUser, deleteUser },
773
1215
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
774
1216
  workspaces: {
@@ -788,12 +1230,17 @@ const operationsByTag$1 = {
788
1230
  acceptWorkspaceMemberInvite,
789
1231
  resendWorkspaceMemberInvite
790
1232
  },
1233
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
791
1234
  databases: {
792
1235
  getDatabaseList,
793
1236
  createDatabase,
794
1237
  deleteDatabase,
795
1238
  getDatabaseMetadata,
796
1239
  updateDatabaseMetadata,
1240
+ renameDatabase,
1241
+ getDatabaseGithubSettings,
1242
+ updateDatabaseGithubSettings,
1243
+ deleteDatabaseGithubSettings,
797
1244
  listRegions
798
1245
  }
799
1246
  };
@@ -814,8 +1261,12 @@ const providers = {
814
1261
  workspaces: "https://{workspaceId}.{region}.xata.sh"
815
1262
  },
816
1263
  staging: {
817
- main: "https://staging.xatabase.co",
818
- workspaces: "https://{workspaceId}.staging.{region}.xatabase.co"
1264
+ main: "https://api.staging-xata.dev",
1265
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1266
+ },
1267
+ dev: {
1268
+ main: "https://api.dev-xata.dev",
1269
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
819
1270
  }
820
1271
  };
821
1272
  function isHostProviderAlias(alias) {
@@ -833,15 +1284,22 @@ function parseProviderString(provider = "production") {
833
1284
  return null;
834
1285
  return { main, workspaces };
835
1286
  }
1287
+ function buildProviderString(provider) {
1288
+ if (isHostProviderAlias(provider))
1289
+ return provider;
1290
+ return `${provider.main},${provider.workspaces}`;
1291
+ }
836
1292
  function parseWorkspacesUrlParts(url) {
837
1293
  if (!isString(url))
838
1294
  return null;
839
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
840
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
841
- const match = url.match(regex) || url.match(regexStaging);
1295
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
1296
+ const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1297
+ const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1298
+ const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1299
+ const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
842
1300
  if (!match)
843
1301
  return null;
844
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
1302
+ return { workspace: match[1], region: match[2] };
845
1303
  }
846
1304
 
847
1305
  var __accessCheck$7 = (obj, member, msg) => {
@@ -870,15 +1328,19 @@ class XataApiClient {
870
1328
  const provider = options.host ?? "production";
871
1329
  const apiKey = options.apiKey ?? getAPIKey();
872
1330
  const trace = options.trace ?? defaultTrace;
1331
+ const clientID = generateUUID();
873
1332
  if (!apiKey) {
874
1333
  throw new Error("Could not resolve a valid apiKey");
875
1334
  }
876
1335
  __privateSet$7(this, _extraProps, {
877
1336
  apiUrl: getHostUrl(provider, "main"),
878
1337
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
879
- fetchImpl: getFetchImplementation(options.fetch),
1338
+ fetch: getFetchImplementation(options.fetch),
880
1339
  apiKey,
881
- trace
1340
+ trace,
1341
+ clientName: options.clientName,
1342
+ xataAgentExtra: options.xataAgentExtra,
1343
+ clientID
882
1344
  });
883
1345
  }
884
1346
  get user() {
@@ -931,6 +1393,11 @@ class XataApiClient {
931
1393
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
932
1394
  return __privateGet$7(this, _namespaces).records;
933
1395
  }
1396
+ get files() {
1397
+ if (!__privateGet$7(this, _namespaces).files)
1398
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1399
+ return __privateGet$7(this, _namespaces).files;
1400
+ }
934
1401
  get searchAndFilter() {
935
1402
  if (!__privateGet$7(this, _namespaces).searchAndFilter)
936
1403
  __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
@@ -1139,6 +1606,20 @@ class BranchApi {
1139
1606
  ...this.extraProps
1140
1607
  });
1141
1608
  }
1609
+ copyBranch({
1610
+ workspace,
1611
+ region,
1612
+ database,
1613
+ branch,
1614
+ destinationBranch,
1615
+ limit
1616
+ }) {
1617
+ return operationsByTag.branch.copyBranch({
1618
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1619
+ body: { destinationBranch, limit },
1620
+ ...this.extraProps
1621
+ });
1622
+ }
1142
1623
  updateBranchMetadata({
1143
1624
  workspace,
1144
1625
  region,
@@ -1494,65 +1975,270 @@ class RecordsApi {
1494
1975
  });
1495
1976
  }
1496
1977
  }
1497
- class SearchAndFilterApi {
1978
+ class FilesApi {
1498
1979
  constructor(extraProps) {
1499
1980
  this.extraProps = extraProps;
1500
1981
  }
1501
- queryTable({
1982
+ getFileItem({
1502
1983
  workspace,
1503
1984
  region,
1504
1985
  database,
1505
1986
  branch,
1506
1987
  table,
1507
- filter,
1508
- sort,
1509
- page,
1510
- columns,
1511
- consistency
1988
+ record,
1989
+ column,
1990
+ fileId
1512
1991
  }) {
1513
- return operationsByTag.searchAndFilter.queryTable({
1514
- pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1515
- body: { filter, sort, page, columns, consistency },
1992
+ return operationsByTag.files.getFileItem({
1993
+ pathParams: {
1994
+ workspace,
1995
+ region,
1996
+ dbBranchName: `${database}:${branch}`,
1997
+ tableName: table,
1998
+ recordId: record,
1999
+ columnName: column,
2000
+ fileId
2001
+ },
1516
2002
  ...this.extraProps
1517
2003
  });
1518
2004
  }
1519
- searchTable({
2005
+ putFileItem({
1520
2006
  workspace,
1521
2007
  region,
1522
2008
  database,
1523
2009
  branch,
1524
2010
  table,
1525
- query,
1526
- fuzziness,
1527
- target,
1528
- prefix,
1529
- filter,
1530
- highlight,
1531
- boosters
2011
+ record,
2012
+ column,
2013
+ fileId,
2014
+ file
1532
2015
  }) {
1533
- return operationsByTag.searchAndFilter.searchTable({
1534
- pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1535
- body: { query, fuzziness, target, prefix, filter, highlight, boosters },
2016
+ return operationsByTag.files.putFileItem({
2017
+ pathParams: {
2018
+ workspace,
2019
+ region,
2020
+ dbBranchName: `${database}:${branch}`,
2021
+ tableName: table,
2022
+ recordId: record,
2023
+ columnName: column,
2024
+ fileId
2025
+ },
2026
+ // @ts-ignore
2027
+ body: file,
1536
2028
  ...this.extraProps
1537
2029
  });
1538
2030
  }
1539
- searchBranch({
2031
+ deleteFileItem({
1540
2032
  workspace,
1541
2033
  region,
1542
2034
  database,
1543
2035
  branch,
1544
- tables,
1545
- query,
1546
- fuzziness,
1547
- prefix,
1548
- highlight
2036
+ table,
2037
+ record,
2038
+ column,
2039
+ fileId
1549
2040
  }) {
1550
- return operationsByTag.searchAndFilter.searchBranch({
1551
- pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2041
+ return operationsByTag.files.deleteFileItem({
2042
+ pathParams: {
2043
+ workspace,
2044
+ region,
2045
+ dbBranchName: `${database}:${branch}`,
2046
+ tableName: table,
2047
+ recordId: record,
2048
+ columnName: column,
2049
+ fileId
2050
+ },
2051
+ ...this.extraProps
2052
+ });
2053
+ }
2054
+ getFile({
2055
+ workspace,
2056
+ region,
2057
+ database,
2058
+ branch,
2059
+ table,
2060
+ record,
2061
+ column
2062
+ }) {
2063
+ return operationsByTag.files.getFile({
2064
+ pathParams: {
2065
+ workspace,
2066
+ region,
2067
+ dbBranchName: `${database}:${branch}`,
2068
+ tableName: table,
2069
+ recordId: record,
2070
+ columnName: column
2071
+ },
2072
+ ...this.extraProps
2073
+ });
2074
+ }
2075
+ putFile({
2076
+ workspace,
2077
+ region,
2078
+ database,
2079
+ branch,
2080
+ table,
2081
+ record,
2082
+ column,
2083
+ file
2084
+ }) {
2085
+ return operationsByTag.files.putFile({
2086
+ pathParams: {
2087
+ workspace,
2088
+ region,
2089
+ dbBranchName: `${database}:${branch}`,
2090
+ tableName: table,
2091
+ recordId: record,
2092
+ columnName: column
2093
+ },
2094
+ body: file,
2095
+ ...this.extraProps
2096
+ });
2097
+ }
2098
+ deleteFile({
2099
+ workspace,
2100
+ region,
2101
+ database,
2102
+ branch,
2103
+ table,
2104
+ record,
2105
+ column
2106
+ }) {
2107
+ return operationsByTag.files.deleteFile({
2108
+ pathParams: {
2109
+ workspace,
2110
+ region,
2111
+ dbBranchName: `${database}:${branch}`,
2112
+ tableName: table,
2113
+ recordId: record,
2114
+ columnName: column
2115
+ },
2116
+ ...this.extraProps
2117
+ });
2118
+ }
2119
+ fileAccess({
2120
+ workspace,
2121
+ region,
2122
+ fileId,
2123
+ verify
2124
+ }) {
2125
+ return operationsByTag.files.fileAccess({
2126
+ pathParams: {
2127
+ workspace,
2128
+ region,
2129
+ fileId
2130
+ },
2131
+ queryParams: { verify },
2132
+ ...this.extraProps
2133
+ });
2134
+ }
2135
+ }
2136
+ class SearchAndFilterApi {
2137
+ constructor(extraProps) {
2138
+ this.extraProps = extraProps;
2139
+ }
2140
+ queryTable({
2141
+ workspace,
2142
+ region,
2143
+ database,
2144
+ branch,
2145
+ table,
2146
+ filter,
2147
+ sort,
2148
+ page,
2149
+ columns,
2150
+ consistency
2151
+ }) {
2152
+ return operationsByTag.searchAndFilter.queryTable({
2153
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2154
+ body: { filter, sort, page, columns, consistency },
2155
+ ...this.extraProps
2156
+ });
2157
+ }
2158
+ searchTable({
2159
+ workspace,
2160
+ region,
2161
+ database,
2162
+ branch,
2163
+ table,
2164
+ query,
2165
+ fuzziness,
2166
+ target,
2167
+ prefix,
2168
+ filter,
2169
+ highlight,
2170
+ boosters
2171
+ }) {
2172
+ return operationsByTag.searchAndFilter.searchTable({
2173
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2174
+ body: { query, fuzziness, target, prefix, filter, highlight, boosters },
2175
+ ...this.extraProps
2176
+ });
2177
+ }
2178
+ searchBranch({
2179
+ workspace,
2180
+ region,
2181
+ database,
2182
+ branch,
2183
+ tables,
2184
+ query,
2185
+ fuzziness,
2186
+ prefix,
2187
+ highlight
2188
+ }) {
2189
+ return operationsByTag.searchAndFilter.searchBranch({
2190
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1552
2191
  body: { tables, query, fuzziness, prefix, highlight },
1553
2192
  ...this.extraProps
1554
2193
  });
1555
2194
  }
2195
+ vectorSearchTable({
2196
+ workspace,
2197
+ region,
2198
+ database,
2199
+ branch,
2200
+ table,
2201
+ queryVector,
2202
+ column,
2203
+ similarityFunction,
2204
+ size,
2205
+ filter
2206
+ }) {
2207
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2208
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2209
+ body: { queryVector, column, similarityFunction, size, filter },
2210
+ ...this.extraProps
2211
+ });
2212
+ }
2213
+ askTable({
2214
+ workspace,
2215
+ region,
2216
+ database,
2217
+ branch,
2218
+ table,
2219
+ options
2220
+ }) {
2221
+ return operationsByTag.searchAndFilter.askTable({
2222
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2223
+ body: { ...options },
2224
+ ...this.extraProps
2225
+ });
2226
+ }
2227
+ askTableSession({
2228
+ workspace,
2229
+ region,
2230
+ database,
2231
+ branch,
2232
+ table,
2233
+ sessionId,
2234
+ message
2235
+ }) {
2236
+ return operationsByTag.searchAndFilter.askTableSession({
2237
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2238
+ body: { message },
2239
+ ...this.extraProps
2240
+ });
2241
+ }
1556
2242
  summarizeTable({
1557
2243
  workspace,
1558
2244
  region,
@@ -1753,11 +2439,13 @@ class MigrationsApi {
1753
2439
  region,
1754
2440
  database,
1755
2441
  branch,
1756
- schema
2442
+ schema,
2443
+ schemaOperations,
2444
+ branchOperations
1757
2445
  }) {
1758
2446
  return operationsByTag.migrations.compareBranchWithUserSchema({
1759
2447
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1760
- body: { schema },
2448
+ body: { schema, schemaOperations, branchOperations },
1761
2449
  ...this.extraProps
1762
2450
  });
1763
2451
  }
@@ -1767,11 +2455,12 @@ class MigrationsApi {
1767
2455
  database,
1768
2456
  branch,
1769
2457
  compare,
1770
- schema
2458
+ sourceBranchOperations,
2459
+ targetBranchOperations
1771
2460
  }) {
1772
2461
  return operationsByTag.migrations.compareBranchSchemas({
1773
2462
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1774
- body: { schema },
2463
+ body: { sourceBranchOperations, targetBranchOperations },
1775
2464
  ...this.extraProps
1776
2465
  });
1777
2466
  }
@@ -1814,6 +2503,19 @@ class MigrationsApi {
1814
2503
  ...this.extraProps
1815
2504
  });
1816
2505
  }
2506
+ pushBranchMigrations({
2507
+ workspace,
2508
+ region,
2509
+ database,
2510
+ branch,
2511
+ migrations
2512
+ }) {
2513
+ return operationsByTag.migrations.pushBranchMigrations({
2514
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2515
+ body: { migrations },
2516
+ ...this.extraProps
2517
+ });
2518
+ }
1817
2519
  }
1818
2520
  class DatabaseApi {
1819
2521
  constructor(extraProps) {
@@ -1828,11 +2530,13 @@ class DatabaseApi {
1828
2530
  createDatabase({
1829
2531
  workspace,
1830
2532
  database,
1831
- data
2533
+ data,
2534
+ headers
1832
2535
  }) {
1833
2536
  return operationsByTag.databases.createDatabase({
1834
2537
  pathParams: { workspaceId: workspace, dbName: database },
1835
2538
  body: data,
2539
+ headers,
1836
2540
  ...this.extraProps
1837
2541
  });
1838
2542
  }
@@ -1865,6 +2569,46 @@ class DatabaseApi {
1865
2569
  ...this.extraProps
1866
2570
  });
1867
2571
  }
2572
+ renameDatabase({
2573
+ workspace,
2574
+ database,
2575
+ newName
2576
+ }) {
2577
+ return operationsByTag.databases.renameDatabase({
2578
+ pathParams: { workspaceId: workspace, dbName: database },
2579
+ body: { newName },
2580
+ ...this.extraProps
2581
+ });
2582
+ }
2583
+ getDatabaseGithubSettings({
2584
+ workspace,
2585
+ database
2586
+ }) {
2587
+ return operationsByTag.databases.getDatabaseGithubSettings({
2588
+ pathParams: { workspaceId: workspace, dbName: database },
2589
+ ...this.extraProps
2590
+ });
2591
+ }
2592
+ updateDatabaseGithubSettings({
2593
+ workspace,
2594
+ database,
2595
+ settings
2596
+ }) {
2597
+ return operationsByTag.databases.updateDatabaseGithubSettings({
2598
+ pathParams: { workspaceId: workspace, dbName: database },
2599
+ body: settings,
2600
+ ...this.extraProps
2601
+ });
2602
+ }
2603
+ deleteDatabaseGithubSettings({
2604
+ workspace,
2605
+ database
2606
+ }) {
2607
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
2608
+ pathParams: { workspaceId: workspace, dbName: database },
2609
+ ...this.extraProps
2610
+ });
2611
+ }
1868
2612
  listRegions({ workspace }) {
1869
2613
  return operationsByTag.databases.listRegions({
1870
2614
  pathParams: { workspaceId: workspace },
@@ -1874,27 +2618,200 @@ class DatabaseApi {
1874
2618
  }
1875
2619
 
1876
2620
  class XataApiPlugin {
1877
- async build(options) {
1878
- const { fetchImpl, apiKey } = await options.getFetchProps();
1879
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2621
+ build(options) {
2622
+ return new XataApiClient(options);
1880
2623
  }
1881
2624
  }
1882
2625
 
1883
2626
  class XataPlugin {
1884
2627
  }
1885
2628
 
1886
- function generateUUID() {
1887
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1888
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1889
- return v.toString(16);
1890
- });
2629
+ function buildTransformString(transformations) {
2630
+ return transformations.flatMap(
2631
+ (t) => Object.entries(t).map(([key, value]) => {
2632
+ if (key === "trim") {
2633
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2634
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2635
+ }
2636
+ if (key === "gravity" && typeof value === "object") {
2637
+ const { x = 0.5, y = 0.5 } = value;
2638
+ return `${key}=${[x, y].join("x")}`;
2639
+ }
2640
+ return `${key}=${value}`;
2641
+ })
2642
+ ).join(",");
2643
+ }
2644
+ function transformImage(url, ...transformations) {
2645
+ if (!isDefined(url))
2646
+ return void 0;
2647
+ const newTransformations = buildTransformString(transformations);
2648
+ const { hostname, pathname, search } = new URL(url);
2649
+ const pathParts = pathname.split("/");
2650
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2651
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2652
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2653
+ const path = pathParts.join("/");
2654
+ return `https://${hostname}${transform}${path}${search}`;
2655
+ }
2656
+
2657
+ class XataFile {
2658
+ constructor(file) {
2659
+ this.id = file.id;
2660
+ this.name = file.name || "";
2661
+ this.mediaType = file.mediaType || "application/octet-stream";
2662
+ this.base64Content = file.base64Content;
2663
+ this.enablePublicUrl = file.enablePublicUrl ?? false;
2664
+ this.signedUrlTimeout = file.signedUrlTimeout ?? 300;
2665
+ this.size = file.size ?? 0;
2666
+ this.version = file.version ?? 1;
2667
+ this.url = file.url || "";
2668
+ this.signedUrl = file.signedUrl;
2669
+ this.attributes = file.attributes || {};
2670
+ }
2671
+ static fromBuffer(buffer, options = {}) {
2672
+ const base64Content = buffer.toString("base64");
2673
+ return new XataFile({ ...options, base64Content });
2674
+ }
2675
+ toBuffer() {
2676
+ if (!this.base64Content) {
2677
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2678
+ }
2679
+ return Buffer.from(this.base64Content, "base64");
2680
+ }
2681
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2682
+ const uint8Array = new Uint8Array(arrayBuffer);
2683
+ return this.fromUint8Array(uint8Array, options);
2684
+ }
2685
+ toArrayBuffer() {
2686
+ if (!this.base64Content) {
2687
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2688
+ }
2689
+ const binary = atob(this.base64Content);
2690
+ return new ArrayBuffer(binary.length);
2691
+ }
2692
+ static fromUint8Array(uint8Array, options = {}) {
2693
+ let binary = "";
2694
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2695
+ binary += String.fromCharCode(uint8Array[i]);
2696
+ }
2697
+ const base64Content = btoa(binary);
2698
+ return new XataFile({ ...options, base64Content });
2699
+ }
2700
+ toUint8Array() {
2701
+ if (!this.base64Content) {
2702
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2703
+ }
2704
+ const binary = atob(this.base64Content);
2705
+ const uint8Array = new Uint8Array(binary.length);
2706
+ for (let i = 0; i < binary.length; i++) {
2707
+ uint8Array[i] = binary.charCodeAt(i);
2708
+ }
2709
+ return uint8Array;
2710
+ }
2711
+ static async fromBlob(file, options = {}) {
2712
+ const name = options.name ?? file.name;
2713
+ const mediaType = file.type;
2714
+ const arrayBuffer = await file.arrayBuffer();
2715
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2716
+ }
2717
+ toBlob() {
2718
+ if (!this.base64Content) {
2719
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2720
+ }
2721
+ const binary = atob(this.base64Content);
2722
+ const uint8Array = new Uint8Array(binary.length);
2723
+ for (let i = 0; i < binary.length; i++) {
2724
+ uint8Array[i] = binary.charCodeAt(i);
2725
+ }
2726
+ return new Blob([uint8Array], { type: this.mediaType });
2727
+ }
2728
+ static fromString(string, options = {}) {
2729
+ const base64Content = btoa(string);
2730
+ return new XataFile({ ...options, base64Content });
2731
+ }
2732
+ toString() {
2733
+ if (!this.base64Content) {
2734
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2735
+ }
2736
+ return atob(this.base64Content);
2737
+ }
2738
+ static fromBase64(base64Content, options = {}) {
2739
+ return new XataFile({ ...options, base64Content });
2740
+ }
2741
+ toBase64() {
2742
+ if (!this.base64Content) {
2743
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2744
+ }
2745
+ return this.base64Content;
2746
+ }
2747
+ transform(...options) {
2748
+ return {
2749
+ url: transformImage(this.url, ...options),
2750
+ signedUrl: transformImage(this.signedUrl, ...options),
2751
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2752
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2753
+ };
2754
+ }
1891
2755
  }
2756
+ const parseInputFileEntry = async (entry) => {
2757
+ if (!isDefined(entry))
2758
+ return null;
2759
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout } = await entry;
2760
+ return compactObject({
2761
+ id,
2762
+ // Name cannot be an empty string in our API
2763
+ name: name ? name : void 0,
2764
+ mediaType,
2765
+ base64Content,
2766
+ enablePublicUrl,
2767
+ signedUrlTimeout
2768
+ });
2769
+ };
1892
2770
 
1893
2771
  function cleanFilter(filter) {
1894
- if (!filter)
2772
+ if (!isDefined(filter))
1895
2773
  return void 0;
1896
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1897
- return values.length > 0 ? filter : void 0;
2774
+ if (!isObject(filter))
2775
+ return filter;
2776
+ const values = Object.fromEntries(
2777
+ Object.entries(filter).reduce((acc, [key, value]) => {
2778
+ if (!isDefined(value))
2779
+ return acc;
2780
+ if (Array.isArray(value)) {
2781
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2782
+ if (clean.length === 0)
2783
+ return acc;
2784
+ return [...acc, [key, clean]];
2785
+ }
2786
+ if (isObject(value)) {
2787
+ const clean = cleanFilter(value);
2788
+ if (!isDefined(clean))
2789
+ return acc;
2790
+ return [...acc, [key, clean]];
2791
+ }
2792
+ return [...acc, [key, value]];
2793
+ }, [])
2794
+ );
2795
+ return Object.keys(values).length > 0 ? values : void 0;
2796
+ }
2797
+
2798
+ function stringifyJson(value) {
2799
+ if (!isDefined(value))
2800
+ return value;
2801
+ if (isString(value))
2802
+ return value;
2803
+ try {
2804
+ return JSON.stringify(value);
2805
+ } catch (e) {
2806
+ return value;
2807
+ }
2808
+ }
2809
+ function parseJson(value) {
2810
+ try {
2811
+ return JSON.parse(value);
2812
+ } catch (e) {
2813
+ return value;
2814
+ }
1898
2815
  }
1899
2816
 
1900
2817
  var __accessCheck$6 = (obj, member, msg) => {
@@ -1923,31 +2840,59 @@ class Page {
1923
2840
  this.meta = meta;
1924
2841
  this.records = new RecordArray(this, records);
1925
2842
  }
2843
+ /**
2844
+ * Retrieves the next page of results.
2845
+ * @param size Maximum number of results to be retrieved.
2846
+ * @param offset Number of results to skip when retrieving the results.
2847
+ * @returns The next page or results.
2848
+ */
1926
2849
  async nextPage(size, offset) {
1927
2850
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
1928
2851
  }
2852
+ /**
2853
+ * Retrieves the previous page of results.
2854
+ * @param size Maximum number of results to be retrieved.
2855
+ * @param offset Number of results to skip when retrieving the results.
2856
+ * @returns The previous page or results.
2857
+ */
1929
2858
  async previousPage(size, offset) {
1930
2859
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1931
2860
  }
2861
+ /**
2862
+ * Retrieves the start page of results.
2863
+ * @param size Maximum number of results to be retrieved.
2864
+ * @param offset Number of results to skip when retrieving the results.
2865
+ * @returns The start page or results.
2866
+ */
1932
2867
  async startPage(size, offset) {
1933
2868
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1934
2869
  }
2870
+ /**
2871
+ * Retrieves the end page of results.
2872
+ * @param size Maximum number of results to be retrieved.
2873
+ * @param offset Number of results to skip when retrieving the results.
2874
+ * @returns The end page or results.
2875
+ */
1935
2876
  async endPage(size, offset) {
1936
2877
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1937
2878
  }
2879
+ /**
2880
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
2881
+ * @returns Whether or not there will be additional results in the next page of results.
2882
+ */
1938
2883
  hasNextPage() {
1939
2884
  return this.meta.page.more;
1940
2885
  }
1941
2886
  }
1942
2887
  _query = new WeakMap();
1943
- const PAGINATION_MAX_SIZE = 200;
2888
+ const PAGINATION_MAX_SIZE = 1e3;
1944
2889
  const PAGINATION_DEFAULT_SIZE = 20;
1945
- const PAGINATION_MAX_OFFSET = 800;
2890
+ const PAGINATION_MAX_OFFSET = 49e3;
1946
2891
  const PAGINATION_DEFAULT_OFFSET = 0;
1947
2892
  function isCursorPaginationOptions(options) {
1948
2893
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1949
2894
  }
1950
- const _RecordArray = class extends Array {
2895
+ const _RecordArray = class _RecordArray extends Array {
1951
2896
  constructor(...args) {
1952
2897
  super(..._RecordArray.parseConstructorParams(...args));
1953
2898
  __privateAdd$6(this, _page, void 0);
@@ -1966,31 +2911,60 @@ const _RecordArray = class extends Array {
1966
2911
  toArray() {
1967
2912
  return new Array(...this);
1968
2913
  }
2914
+ toSerializable() {
2915
+ return JSON.parse(this.toString());
2916
+ }
2917
+ toString() {
2918
+ return JSON.stringify(this.toArray());
2919
+ }
1969
2920
  map(callbackfn, thisArg) {
1970
2921
  return this.toArray().map(callbackfn, thisArg);
1971
2922
  }
2923
+ /**
2924
+ * Retrieve next page of records
2925
+ *
2926
+ * @returns A new array of objects
2927
+ */
1972
2928
  async nextPage(size, offset) {
1973
2929
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1974
2930
  return new _RecordArray(newPage);
1975
2931
  }
2932
+ /**
2933
+ * Retrieve previous page of records
2934
+ *
2935
+ * @returns A new array of objects
2936
+ */
1976
2937
  async previousPage(size, offset) {
1977
2938
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1978
2939
  return new _RecordArray(newPage);
1979
2940
  }
2941
+ /**
2942
+ * Retrieve start page of records
2943
+ *
2944
+ * @returns A new array of objects
2945
+ */
1980
2946
  async startPage(size, offset) {
1981
2947
  const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1982
2948
  return new _RecordArray(newPage);
1983
2949
  }
2950
+ /**
2951
+ * Retrieve end page of records
2952
+ *
2953
+ * @returns A new array of objects
2954
+ */
1984
2955
  async endPage(size, offset) {
1985
2956
  const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1986
2957
  return new _RecordArray(newPage);
1987
2958
  }
2959
+ /**
2960
+ * @returns Boolean indicating if there is a next page
2961
+ */
1988
2962
  hasNextPage() {
1989
2963
  return __privateGet$6(this, _page).meta.page.more;
1990
2964
  }
1991
2965
  };
1992
- let RecordArray = _RecordArray;
1993
2966
  _page = new WeakMap();
2967
+ let RecordArray = _RecordArray;
1994
2968
 
1995
2969
  var __accessCheck$5 = (obj, member, msg) => {
1996
2970
  if (!member.has(obj))
@@ -2015,13 +2989,14 @@ var __privateMethod$3 = (obj, member, method) => {
2015
2989
  return method;
2016
2990
  };
2017
2991
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
2018
- const _Query = class {
2992
+ const _Query = class _Query {
2019
2993
  constructor(repository, table, data, rawParent) {
2020
2994
  __privateAdd$5(this, _cleanFilterConstraint);
2021
2995
  __privateAdd$5(this, _table$1, void 0);
2022
2996
  __privateAdd$5(this, _repository, void 0);
2023
2997
  __privateAdd$5(this, _data, { filter: {} });
2024
- this.meta = { page: { cursor: "start", more: true } };
2998
+ // Implements pagination
2999
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
2025
3000
  this.records = new RecordArray(this, []);
2026
3001
  __privateSet$5(this, _table$1, table);
2027
3002
  if (repository) {
@@ -2037,6 +3012,7 @@ const _Query = class {
2037
3012
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
2038
3013
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
2039
3014
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
3015
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
2040
3016
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
2041
3017
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
2042
3018
  __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
@@ -2057,18 +3033,38 @@ const _Query = class {
2057
3033
  const key = JSON.stringify({ columns, filter, sort, pagination });
2058
3034
  return toBase64(key);
2059
3035
  }
3036
+ /**
3037
+ * Builds a new query object representing a logical OR between the given subqueries.
3038
+ * @param queries An array of subqueries.
3039
+ * @returns A new Query object.
3040
+ */
2060
3041
  any(...queries) {
2061
3042
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
2062
3043
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
2063
3044
  }
3045
+ /**
3046
+ * Builds a new query object representing a logical AND between the given subqueries.
3047
+ * @param queries An array of subqueries.
3048
+ * @returns A new Query object.
3049
+ */
2064
3050
  all(...queries) {
2065
3051
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
2066
3052
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
2067
3053
  }
3054
+ /**
3055
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3056
+ * @param queries An array of subqueries.
3057
+ * @returns A new Query object.
3058
+ */
2068
3059
  not(...queries) {
2069
3060
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
2070
3061
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
2071
3062
  }
3063
+ /**
3064
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3065
+ * @param queries An array of subqueries.
3066
+ * @returns A new Query object.
3067
+ */
2072
3068
  none(...queries) {
2073
3069
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
2074
3070
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
@@ -2091,6 +3087,11 @@ const _Query = class {
2091
3087
  const sort = [...originalSort, { column, direction }];
2092
3088
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
2093
3089
  }
3090
+ /**
3091
+ * Builds a new query specifying the set of columns to be returned in the query response.
3092
+ * @param columns Array of column names to be returned by the query.
3093
+ * @returns A new Query object.
3094
+ */
2094
3095
  select(columns) {
2095
3096
  return new _Query(
2096
3097
  __privateGet$5(this, _repository),
@@ -2103,6 +3104,12 @@ const _Query = class {
2103
3104
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
2104
3105
  return __privateGet$5(this, _repository).query(query);
2105
3106
  }
3107
+ /**
3108
+ * Get results in an iterator
3109
+ *
3110
+ * @async
3111
+ * @returns Async interable of results
3112
+ */
2106
3113
  async *[Symbol.asyncIterator]() {
2107
3114
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
2108
3115
  yield record;
@@ -2163,26 +3170,53 @@ const _Query = class {
2163
3170
  );
2164
3171
  return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2165
3172
  }
3173
+ /**
3174
+ * Builds a new query object adding a cache TTL in milliseconds.
3175
+ * @param ttl The cache TTL in milliseconds.
3176
+ * @returns A new Query object.
3177
+ */
2166
3178
  cache(ttl) {
2167
3179
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2168
3180
  }
3181
+ /**
3182
+ * Retrieve next page of records
3183
+ *
3184
+ * @returns A new page object.
3185
+ */
2169
3186
  nextPage(size, offset) {
2170
3187
  return this.startPage(size, offset);
2171
3188
  }
3189
+ /**
3190
+ * Retrieve previous page of records
3191
+ *
3192
+ * @returns A new page object
3193
+ */
2172
3194
  previousPage(size, offset) {
2173
3195
  return this.startPage(size, offset);
2174
3196
  }
3197
+ /**
3198
+ * Retrieve start page of records
3199
+ *
3200
+ * @returns A new page object
3201
+ */
2175
3202
  startPage(size, offset) {
2176
3203
  return this.getPaginated({ pagination: { size, offset } });
2177
3204
  }
3205
+ /**
3206
+ * Retrieve last page of records
3207
+ *
3208
+ * @returns A new page object
3209
+ */
2178
3210
  endPage(size, offset) {
2179
3211
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2180
3212
  }
3213
+ /**
3214
+ * @returns Boolean indicating if there is a next page
3215
+ */
2181
3216
  hasNextPage() {
2182
3217
  return this.meta.page.more;
2183
3218
  }
2184
3219
  };
2185
- let Query = _Query;
2186
3220
  _table$1 = new WeakMap();
2187
3221
  _repository = new WeakMap();
2188
3222
  _data = new WeakMap();
@@ -2197,6 +3231,7 @@ cleanFilterConstraint_fn = function(column, value) {
2197
3231
  }
2198
3232
  return value;
2199
3233
  };
3234
+ let Query = _Query;
2200
3235
  function cleanParent(data, parent) {
2201
3236
  if (isCursorPaginationOptions(data.pagination)) {
2202
3237
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2204,6 +3239,22 @@ function cleanParent(data, parent) {
2204
3239
  return parent;
2205
3240
  }
2206
3241
 
3242
+ const RecordColumnTypes = [
3243
+ "bool",
3244
+ "int",
3245
+ "float",
3246
+ "string",
3247
+ "text",
3248
+ "email",
3249
+ "multiple",
3250
+ "link",
3251
+ "object",
3252
+ "datetime",
3253
+ "vector",
3254
+ "file[]",
3255
+ "file",
3256
+ "json"
3257
+ ];
2207
3258
  function isIdentifiable(x) {
2208
3259
  return isObject(x) && isString(x?.id);
2209
3260
  }
@@ -2213,11 +3264,33 @@ function isXataRecord(x) {
2213
3264
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
2214
3265
  }
2215
3266
 
3267
+ function isValidExpandedColumn(column) {
3268
+ return isObject(column) && isString(column.name);
3269
+ }
3270
+ function isValidSelectableColumns(columns) {
3271
+ if (!Array.isArray(columns)) {
3272
+ return false;
3273
+ }
3274
+ return columns.every((column) => {
3275
+ if (typeof column === "string") {
3276
+ return true;
3277
+ }
3278
+ if (typeof column === "object") {
3279
+ return isValidExpandedColumn(column);
3280
+ }
3281
+ return false;
3282
+ });
3283
+ }
3284
+
2216
3285
  function isSortFilterString(value) {
2217
3286
  return isString(value);
2218
3287
  }
2219
3288
  function isSortFilterBase(filter) {
2220
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
3289
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
3290
+ if (key === "*")
3291
+ return value === "random";
3292
+ return value === "asc" || value === "desc";
3293
+ });
2221
3294
  }
2222
3295
  function isSortFilterObject(filter) {
2223
3296
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -2258,7 +3331,7 @@ var __privateMethod$2 = (obj, member, method) => {
2258
3331
  __accessCheck$4(obj, member, "access private method");
2259
3332
  return method;
2260
3333
  };
2261
- 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;
3334
+ 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, _transformObjectToApi, transformObjectToApi_fn;
2262
3335
  const BULK_OPERATION_MAX_SIZE = 1e3;
2263
3336
  class Repository extends Query {
2264
3337
  }
@@ -2280,6 +3353,7 @@ class RestRepository extends Query {
2280
3353
  __privateAdd$4(this, _setCacheQuery);
2281
3354
  __privateAdd$4(this, _getCacheQuery);
2282
3355
  __privateAdd$4(this, _getSchemaTables$1);
3356
+ __privateAdd$4(this, _transformObjectToApi);
2283
3357
  __privateAdd$4(this, _table, void 0);
2284
3358
  __privateAdd$4(this, _getFetchProps, void 0);
2285
3359
  __privateAdd$4(this, _db, void 0);
@@ -2290,10 +3364,7 @@ class RestRepository extends Query {
2290
3364
  __privateSet$4(this, _db, options.db);
2291
3365
  __privateSet$4(this, _cache, options.pluginOptions.cache);
2292
3366
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2293
- __privateSet$4(this, _getFetchProps, async () => {
2294
- const props = await options.pluginOptions.getFetchProps();
2295
- return { ...props, sessionID: generateUUID() };
2296
- });
3367
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2297
3368
  const trace = options.pluginOptions.trace ?? defaultTrace;
2298
3369
  __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2299
3370
  return trace(name, fn, {
@@ -2311,24 +3382,24 @@ class RestRepository extends Query {
2311
3382
  if (a.length === 0)
2312
3383
  return [];
2313
3384
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2314
- const columns = isStringArray(b) ? b : ["*"];
3385
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2315
3386
  const result = await this.read(ids, columns);
2316
3387
  return result;
2317
3388
  }
2318
3389
  if (isString(a) && isObject(b)) {
2319
3390
  if (a === "")
2320
3391
  throw new Error("The id can't be empty");
2321
- const columns = isStringArray(c) ? c : void 0;
3392
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2322
3393
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2323
3394
  }
2324
3395
  if (isObject(a) && isString(a.id)) {
2325
3396
  if (a.id === "")
2326
3397
  throw new Error("The id can't be empty");
2327
- const columns = isStringArray(b) ? b : void 0;
3398
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2328
3399
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2329
3400
  }
2330
3401
  if (isObject(a)) {
2331
- const columns = isStringArray(b) ? b : void 0;
3402
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2332
3403
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2333
3404
  }
2334
3405
  throw new Error("Invalid arguments for create method");
@@ -2336,7 +3407,7 @@ class RestRepository extends Query {
2336
3407
  }
2337
3408
  async read(a, b) {
2338
3409
  return __privateGet$4(this, _trace).call(this, "read", async () => {
2339
- const columns = isStringArray(b) ? b : ["*"];
3410
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2340
3411
  if (Array.isArray(a)) {
2341
3412
  if (a.length === 0)
2342
3413
  return [];
@@ -2350,7 +3421,6 @@ class RestRepository extends Query {
2350
3421
  }
2351
3422
  const id = extractId(a);
2352
3423
  if (id) {
2353
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2354
3424
  try {
2355
3425
  const response = await getRecord({
2356
3426
  pathParams: {
@@ -2361,10 +3431,16 @@ class RestRepository extends Query {
2361
3431
  recordId: id
2362
3432
  },
2363
3433
  queryParams: { columns },
2364
- ...fetchProps
3434
+ ...__privateGet$4(this, _getFetchProps).call(this)
2365
3435
  });
2366
3436
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2367
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3437
+ return initObject(
3438
+ __privateGet$4(this, _db),
3439
+ schemaTables,
3440
+ __privateGet$4(this, _table),
3441
+ response,
3442
+ columns
3443
+ );
2368
3444
  } catch (e) {
2369
3445
  if (isObject(e) && e.status === 404) {
2370
3446
  return null;
@@ -2406,17 +3482,23 @@ class RestRepository extends Query {
2406
3482
  ifVersion,
2407
3483
  upsert: false
2408
3484
  });
2409
- const columns = isStringArray(b) ? b : ["*"];
3485
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2410
3486
  const result = await this.read(a, columns);
2411
3487
  return result;
2412
3488
  }
2413
- if (isString(a) && isObject(b)) {
2414
- const columns = isStringArray(c) ? c : void 0;
2415
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2416
- }
2417
- if (isObject(a) && isString(a.id)) {
2418
- const columns = isStringArray(b) ? b : void 0;
2419
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3489
+ try {
3490
+ if (isString(a) && isObject(b)) {
3491
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3492
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3493
+ }
3494
+ if (isObject(a) && isString(a.id)) {
3495
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3496
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3497
+ }
3498
+ } catch (error) {
3499
+ if (error.status === 422)
3500
+ return null;
3501
+ throw error;
2420
3502
  }
2421
3503
  throw new Error("Invalid arguments for update method");
2422
3504
  });
@@ -2450,17 +3532,27 @@ class RestRepository extends Query {
2450
3532
  ifVersion,
2451
3533
  upsert: true
2452
3534
  });
2453
- const columns = isStringArray(b) ? b : ["*"];
3535
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2454
3536
  const result = await this.read(a, columns);
2455
3537
  return result;
2456
3538
  }
2457
3539
  if (isString(a) && isObject(b)) {
2458
- const columns = isStringArray(c) ? c : void 0;
2459
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3540
+ if (a === "")
3541
+ throw new Error("The id can't be empty");
3542
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3543
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2460
3544
  }
2461
3545
  if (isObject(a) && isString(a.id)) {
2462
- const columns = isStringArray(c) ? c : void 0;
2463
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3546
+ if (a.id === "")
3547
+ throw new Error("The id can't be empty");
3548
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3549
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3550
+ }
3551
+ if (!isDefined(a) && isObject(b)) {
3552
+ return await this.create(b, c);
3553
+ }
3554
+ if (isObject(a) && !isDefined(a.id)) {
3555
+ return await this.create(a, b);
2464
3556
  }
2465
3557
  throw new Error("Invalid arguments for createOrUpdate method");
2466
3558
  });
@@ -2472,17 +3564,27 @@ class RestRepository extends Query {
2472
3564
  if (a.length === 0)
2473
3565
  return [];
2474
3566
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2475
- const columns = isStringArray(b) ? b : ["*"];
3567
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2476
3568
  const result = await this.read(ids, columns);
2477
3569
  return result;
2478
3570
  }
2479
3571
  if (isString(a) && isObject(b)) {
2480
- const columns = isStringArray(c) ? c : void 0;
2481
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3572
+ if (a === "")
3573
+ throw new Error("The id can't be empty");
3574
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3575
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2482
3576
  }
2483
3577
  if (isObject(a) && isString(a.id)) {
2484
- const columns = isStringArray(c) ? c : void 0;
2485
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3578
+ if (a.id === "")
3579
+ throw new Error("The id can't be empty");
3580
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3581
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3582
+ }
3583
+ if (!isDefined(a) && isObject(b)) {
3584
+ return await this.create(b, c);
3585
+ }
3586
+ if (isObject(a) && !isDefined(a.id)) {
3587
+ return await this.create(a, b);
2486
3588
  }
2487
3589
  throw new Error("Invalid arguments for createOrReplace method");
2488
3590
  });
@@ -2499,7 +3601,7 @@ class RestRepository extends Query {
2499
3601
  return o.id;
2500
3602
  throw new Error("Invalid arguments for delete method");
2501
3603
  });
2502
- const columns = isStringArray(b) ? b : ["*"];
3604
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2503
3605
  const result = await this.read(a, columns);
2504
3606
  await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2505
3607
  return result;
@@ -2533,7 +3635,6 @@ class RestRepository extends Query {
2533
3635
  }
2534
3636
  async search(query, options = {}) {
2535
3637
  return __privateGet$4(this, _trace).call(this, "search", async () => {
2536
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2537
3638
  const { records } = await searchTable({
2538
3639
  pathParams: {
2539
3640
  workspace: "{workspaceId}",
@@ -2547,9 +3648,33 @@ class RestRepository extends Query {
2547
3648
  prefix: options.prefix,
2548
3649
  highlight: options.highlight,
2549
3650
  filter: options.filter,
2550
- boosters: options.boosters
3651
+ boosters: options.boosters,
3652
+ page: options.page,
3653
+ target: options.target
3654
+ },
3655
+ ...__privateGet$4(this, _getFetchProps).call(this)
3656
+ });
3657
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3658
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3659
+ });
3660
+ }
3661
+ async vectorSearch(column, query, options) {
3662
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3663
+ const { records } = await vectorSearchTable({
3664
+ pathParams: {
3665
+ workspace: "{workspaceId}",
3666
+ dbBranchName: "{dbBranch}",
3667
+ region: "{region}",
3668
+ tableName: __privateGet$4(this, _table)
3669
+ },
3670
+ body: {
3671
+ column,
3672
+ queryVector: query,
3673
+ similarityFunction: options?.similarityFunction,
3674
+ size: options?.size,
3675
+ filter: options?.filter
2551
3676
  },
2552
- ...fetchProps
3677
+ ...__privateGet$4(this, _getFetchProps).call(this)
2553
3678
  });
2554
3679
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2555
3680
  return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
@@ -2557,7 +3682,6 @@ class RestRepository extends Query {
2557
3682
  }
2558
3683
  async aggregate(aggs, filter) {
2559
3684
  return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2560
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2561
3685
  const result = await aggregateTable({
2562
3686
  pathParams: {
2563
3687
  workspace: "{workspaceId}",
@@ -2566,7 +3690,7 @@ class RestRepository extends Query {
2566
3690
  tableName: __privateGet$4(this, _table)
2567
3691
  },
2568
3692
  body: { aggs, filter },
2569
- ...fetchProps
3693
+ ...__privateGet$4(this, _getFetchProps).call(this)
2570
3694
  });
2571
3695
  return result;
2572
3696
  });
@@ -2577,7 +3701,6 @@ class RestRepository extends Query {
2577
3701
  if (cacheQuery)
2578
3702
  return new Page(query, cacheQuery.meta, cacheQuery.records);
2579
3703
  const data = query.getQueryOptions();
2580
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2581
3704
  const { meta, records: objects } = await queryTable({
2582
3705
  pathParams: {
2583
3706
  workspace: "{workspaceId}",
@@ -2589,14 +3712,21 @@ class RestRepository extends Query {
2589
3712
  filter: cleanFilter(data.filter),
2590
3713
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2591
3714
  page: data.pagination,
2592
- columns: data.columns ?? ["*"]
3715
+ columns: data.columns ?? ["*"],
3716
+ consistency: data.consistency
2593
3717
  },
2594
3718
  fetchOptions: data.fetchOptions,
2595
- ...fetchProps
3719
+ ...__privateGet$4(this, _getFetchProps).call(this)
2596
3720
  });
2597
3721
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2598
3722
  const records = objects.map(
2599
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3723
+ (record) => initObject(
3724
+ __privateGet$4(this, _db),
3725
+ schemaTables,
3726
+ __privateGet$4(this, _table),
3727
+ record,
3728
+ data.columns ?? ["*"]
3729
+ )
2600
3730
  );
2601
3731
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
2602
3732
  return new Page(query, meta, records);
@@ -2605,7 +3735,6 @@ class RestRepository extends Query {
2605
3735
  async summarizeTable(query, summaries, summariesFilter) {
2606
3736
  return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2607
3737
  const data = query.getQueryOptions();
2608
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2609
3738
  const result = await summarizeTable({
2610
3739
  pathParams: {
2611
3740
  workspace: "{workspaceId}",
@@ -2617,15 +3746,55 @@ class RestRepository extends Query {
2617
3746
  filter: cleanFilter(data.filter),
2618
3747
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2619
3748
  columns: data.columns,
3749
+ consistency: data.consistency,
2620
3750
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2621
3751
  summaries,
2622
3752
  summariesFilter
2623
3753
  },
2624
- ...fetchProps
3754
+ ...__privateGet$4(this, _getFetchProps).call(this)
2625
3755
  });
2626
- return result;
3756
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3757
+ return {
3758
+ ...result,
3759
+ summaries: result.summaries.map(
3760
+ (summary) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), summary, data.columns ?? [])
3761
+ )
3762
+ };
2627
3763
  });
2628
3764
  }
3765
+ ask(question, options) {
3766
+ const questionParam = options?.sessionId ? { message: question } : { question };
3767
+ const params = {
3768
+ pathParams: {
3769
+ workspace: "{workspaceId}",
3770
+ dbBranchName: "{dbBranch}",
3771
+ region: "{region}",
3772
+ tableName: __privateGet$4(this, _table),
3773
+ sessionId: options?.sessionId
3774
+ },
3775
+ body: {
3776
+ ...questionParam,
3777
+ rules: options?.rules,
3778
+ searchType: options?.searchType,
3779
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3780
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3781
+ },
3782
+ ...__privateGet$4(this, _getFetchProps).call(this)
3783
+ };
3784
+ if (options?.onMessage) {
3785
+ fetchSSERequest({
3786
+ endpoint: "dataPlane",
3787
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3788
+ method: "POST",
3789
+ onMessage: (message) => {
3790
+ options.onMessage?.({ answer: message.text, records: message.records });
3791
+ },
3792
+ ...params
3793
+ });
3794
+ } else {
3795
+ return askTableSession(params);
3796
+ }
3797
+ }
2629
3798
  }
2630
3799
  _table = new WeakMap();
2631
3800
  _getFetchProps = new WeakMap();
@@ -2635,8 +3804,7 @@ _schemaTables$2 = new WeakMap();
2635
3804
  _trace = new WeakMap();
2636
3805
  _insertRecordWithoutId = new WeakSet();
2637
3806
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2638
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2639
- const record = transformObjectLinks(object);
3807
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2640
3808
  const response = await insertRecord({
2641
3809
  pathParams: {
2642
3810
  workspace: "{workspaceId}",
@@ -2646,15 +3814,16 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2646
3814
  },
2647
3815
  queryParams: { columns },
2648
3816
  body: record,
2649
- ...fetchProps
3817
+ ...__privateGet$4(this, _getFetchProps).call(this)
2650
3818
  });
2651
3819
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2652
3820
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2653
3821
  };
2654
3822
  _insertRecordWithId = new WeakSet();
2655
3823
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2656
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2657
- const record = transformObjectLinks(object);
3824
+ if (!recordId)
3825
+ return null;
3826
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2658
3827
  const response = await insertRecordWithID({
2659
3828
  pathParams: {
2660
3829
  workspace: "{workspaceId}",
@@ -2665,30 +3834,28 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2665
3834
  },
2666
3835
  body: record,
2667
3836
  queryParams: { createOnly, columns, ifVersion },
2668
- ...fetchProps
3837
+ ...__privateGet$4(this, _getFetchProps).call(this)
2669
3838
  });
2670
3839
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2671
3840
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2672
3841
  };
2673
3842
  _insertRecords = new WeakSet();
2674
3843
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2675
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2676
- const chunkedOperations = chunk(
2677
- objects.map((object) => ({
2678
- insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2679
- })),
2680
- BULK_OPERATION_MAX_SIZE
2681
- );
3844
+ const operations = await promiseMap(objects, async (object) => {
3845
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3846
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
3847
+ });
3848
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2682
3849
  const ids = [];
2683
- for (const operations of chunkedOperations) {
3850
+ for (const operations2 of chunkedOperations) {
2684
3851
  const { results } = await branchTransaction({
2685
3852
  pathParams: {
2686
3853
  workspace: "{workspaceId}",
2687
3854
  dbBranchName: "{dbBranch}",
2688
3855
  region: "{region}"
2689
3856
  },
2690
- body: { operations },
2691
- ...fetchProps
3857
+ body: { operations: operations2 },
3858
+ ...__privateGet$4(this, _getFetchProps).call(this)
2692
3859
  });
2693
3860
  for (const result of results) {
2694
3861
  if (result.operation === "insert") {
@@ -2702,8 +3869,9 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2702
3869
  };
2703
3870
  _updateRecordWithID = new WeakSet();
2704
3871
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2705
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2706
- const { id: _id, ...record } = transformObjectLinks(object);
3872
+ if (!recordId)
3873
+ return null;
3874
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2707
3875
  try {
2708
3876
  const response = await updateRecordWithID({
2709
3877
  pathParams: {
@@ -2715,7 +3883,7 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2715
3883
  },
2716
3884
  queryParams: { columns, ifVersion },
2717
3885
  body: record,
2718
- ...fetchProps
3886
+ ...__privateGet$4(this, _getFetchProps).call(this)
2719
3887
  });
2720
3888
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2721
3889
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2728,23 +3896,21 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2728
3896
  };
2729
3897
  _updateRecords = new WeakSet();
2730
3898
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2731
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2732
- const chunkedOperations = chunk(
2733
- objects.map(({ id, ...object }) => ({
2734
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2735
- })),
2736
- BULK_OPERATION_MAX_SIZE
2737
- );
3899
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
3900
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3901
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
3902
+ });
3903
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2738
3904
  const ids = [];
2739
- for (const operations of chunkedOperations) {
3905
+ for (const operations2 of chunkedOperations) {
2740
3906
  const { results } = await branchTransaction({
2741
3907
  pathParams: {
2742
3908
  workspace: "{workspaceId}",
2743
3909
  dbBranchName: "{dbBranch}",
2744
3910
  region: "{region}"
2745
3911
  },
2746
- body: { operations },
2747
- ...fetchProps
3912
+ body: { operations: operations2 },
3913
+ ...__privateGet$4(this, _getFetchProps).call(this)
2748
3914
  });
2749
3915
  for (const result of results) {
2750
3916
  if (result.operation === "update") {
@@ -2758,7 +3924,8 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2758
3924
  };
2759
3925
  _upsertRecordWithID = new WeakSet();
2760
3926
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2761
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3927
+ if (!recordId)
3928
+ return null;
2762
3929
  const response = await upsertRecordWithID({
2763
3930
  pathParams: {
2764
3931
  workspace: "{workspaceId}",
@@ -2769,14 +3936,15 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2769
3936
  },
2770
3937
  queryParams: { columns, ifVersion },
2771
3938
  body: object,
2772
- ...fetchProps
3939
+ ...__privateGet$4(this, _getFetchProps).call(this)
2773
3940
  });
2774
3941
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2775
3942
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2776
3943
  };
2777
3944
  _deleteRecord = new WeakSet();
2778
3945
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
2779
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3946
+ if (!recordId)
3947
+ return null;
2780
3948
  try {
2781
3949
  const response = await deleteRecord({
2782
3950
  pathParams: {
@@ -2787,7 +3955,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2787
3955
  recordId
2788
3956
  },
2789
3957
  queryParams: { columns },
2790
- ...fetchProps
3958
+ ...__privateGet$4(this, _getFetchProps).call(this)
2791
3959
  });
2792
3960
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2793
3961
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2800,9 +3968,8 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2800
3968
  };
2801
3969
  _deleteRecords = new WeakSet();
2802
3970
  deleteRecords_fn = async function(recordIds) {
2803
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2804
3971
  const chunkedOperations = chunk(
2805
- recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
3972
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2806
3973
  BULK_OPERATION_MAX_SIZE
2807
3974
  );
2808
3975
  for (const operations of chunkedOperations) {
@@ -2813,21 +3980,22 @@ deleteRecords_fn = async function(recordIds) {
2813
3980
  region: "{region}"
2814
3981
  },
2815
3982
  body: { operations },
2816
- ...fetchProps
3983
+ ...__privateGet$4(this, _getFetchProps).call(this)
2817
3984
  });
2818
3985
  }
2819
3986
  };
2820
3987
  _setCacheQuery = new WeakSet();
2821
3988
  setCacheQuery_fn = async function(query, meta, records) {
2822
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
3989
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
2823
3990
  };
2824
3991
  _getCacheQuery = new WeakSet();
2825
3992
  getCacheQuery_fn = async function(query) {
2826
3993
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2827
- const result = await __privateGet$4(this, _cache).get(key);
3994
+ const result = await __privateGet$4(this, _cache)?.get(key);
2828
3995
  if (!result)
2829
3996
  return null;
2830
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
3997
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
3998
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2831
3999
  if (ttl < 0)
2832
4000
  return null;
2833
4001
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2837,39 +4005,66 @@ _getSchemaTables$1 = new WeakSet();
2837
4005
  getSchemaTables_fn$1 = async function() {
2838
4006
  if (__privateGet$4(this, _schemaTables$2))
2839
4007
  return __privateGet$4(this, _schemaTables$2);
2840
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2841
4008
  const { schema } = await getBranchDetails({
2842
4009
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2843
- ...fetchProps
4010
+ ...__privateGet$4(this, _getFetchProps).call(this)
2844
4011
  });
2845
4012
  __privateSet$4(this, _schemaTables$2, schema.tables);
2846
4013
  return schema.tables;
2847
4014
  };
2848
- const transformObjectLinks = (object) => {
2849
- return Object.entries(object).reduce((acc, [key, value]) => {
4015
+ _transformObjectToApi = new WeakSet();
4016
+ transformObjectToApi_fn = async function(object) {
4017
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4018
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
4019
+ if (!schema)
4020
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
4021
+ const result = {};
4022
+ for (const [key, value] of Object.entries(object)) {
2850
4023
  if (key === "xata")
2851
- return acc;
2852
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
2853
- }, {});
4024
+ continue;
4025
+ const type = schema.columns.find((column) => column.name === key)?.type;
4026
+ switch (type) {
4027
+ case "link": {
4028
+ result[key] = isIdentifiable(value) ? value.id : value;
4029
+ break;
4030
+ }
4031
+ case "datetime": {
4032
+ result[key] = value instanceof Date ? value.toISOString() : value;
4033
+ break;
4034
+ }
4035
+ case `file`:
4036
+ result[key] = await parseInputFileEntry(value);
4037
+ break;
4038
+ case "file[]":
4039
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4040
+ break;
4041
+ case "json":
4042
+ result[key] = stringifyJson(value);
4043
+ break;
4044
+ default:
4045
+ result[key] = value;
4046
+ }
4047
+ }
4048
+ return result;
2854
4049
  };
2855
4050
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2856
- const result = {};
4051
+ const data = {};
2857
4052
  const { xata, ...rest } = object ?? {};
2858
- Object.assign(result, rest);
4053
+ Object.assign(data, rest);
2859
4054
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2860
4055
  if (!columns)
2861
4056
  console.error(`Table ${table} not found in schema`);
2862
4057
  for (const column of columns ?? []) {
2863
4058
  if (!isValidColumn(selectedColumns, column))
2864
4059
  continue;
2865
- const value = result[column.name];
4060
+ const value = data[column.name];
2866
4061
  switch (column.type) {
2867
4062
  case "datetime": {
2868
- const date = value !== void 0 ? new Date(value) : void 0;
2869
- if (date && isNaN(date.getTime())) {
4063
+ const date = value !== void 0 ? new Date(value) : null;
4064
+ if (date !== null && isNaN(date.getTime())) {
2870
4065
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2871
- } else if (date) {
2872
- result[column.name] = date;
4066
+ } else {
4067
+ data[column.name] = date;
2873
4068
  }
2874
4069
  break;
2875
4070
  }
@@ -2882,50 +4077,76 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2882
4077
  if (item === column.name) {
2883
4078
  return [...acc, "*"];
2884
4079
  }
2885
- if (item.startsWith(`${column.name}.`)) {
4080
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
2886
4081
  const [, ...path] = item.split(".");
2887
4082
  return [...acc, path.join(".")];
2888
4083
  }
2889
4084
  return acc;
2890
4085
  }, []);
2891
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4086
+ data[column.name] = initObject(
4087
+ db,
4088
+ schemaTables,
4089
+ linkTable,
4090
+ value,
4091
+ selectedLinkColumns
4092
+ );
2892
4093
  } else {
2893
- result[column.name] = null;
4094
+ data[column.name] = null;
2894
4095
  }
2895
4096
  break;
2896
4097
  }
4098
+ case "file":
4099
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4100
+ break;
4101
+ case "file[]":
4102
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4103
+ break;
4104
+ case "json":
4105
+ data[column.name] = parseJson(value);
4106
+ break;
2897
4107
  default:
2898
- result[column.name] = value ?? null;
4108
+ data[column.name] = value ?? null;
2899
4109
  if (column.notNull === true && value === null) {
2900
4110
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2901
4111
  }
2902
4112
  break;
2903
4113
  }
2904
4114
  }
2905
- result.read = function(columns2) {
2906
- return db[table].read(result["id"], columns2);
4115
+ const record = { ...data };
4116
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
4117
+ record.read = function(columns2) {
4118
+ return db[table].read(record["id"], columns2);
2907
4119
  };
2908
- result.update = function(data, b, c) {
2909
- const columns2 = isStringArray(b) ? b : ["*"];
4120
+ record.update = function(data2, b, c) {
4121
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2910
4122
  const ifVersion = parseIfVersion(b, c);
2911
- return db[table].update(result["id"], data, columns2, { ifVersion });
4123
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2912
4124
  };
2913
- result.replace = function(data, b, c) {
2914
- const columns2 = isStringArray(b) ? b : ["*"];
4125
+ record.replace = function(data2, b, c) {
4126
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2915
4127
  const ifVersion = parseIfVersion(b, c);
2916
- return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
4128
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2917
4129
  };
2918
- result.delete = function() {
2919
- return db[table].delete(result["id"]);
4130
+ record.delete = function() {
4131
+ return db[table].delete(record["id"]);
2920
4132
  };
2921
- result.getMetadata = function() {
2922
- return xata;
4133
+ if (metadata !== void 0) {
4134
+ record.xata = Object.freeze(metadata);
4135
+ }
4136
+ record.getMetadata = function() {
4137
+ return record.xata;
2923
4138
  };
2924
- for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
2925
- Object.defineProperty(result, prop, { enumerable: false });
4139
+ record.toSerializable = function() {
4140
+ return JSON.parse(JSON.stringify(record));
4141
+ };
4142
+ record.toString = function() {
4143
+ return JSON.stringify(record);
4144
+ };
4145
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
4146
+ Object.defineProperty(record, prop, { enumerable: false });
2926
4147
  }
2927
- Object.freeze(result);
2928
- return result;
4148
+ Object.freeze(record);
4149
+ return record;
2929
4150
  };
2930
4151
  function extractId(value) {
2931
4152
  if (isString(value))
@@ -2937,11 +4158,7 @@ function extractId(value) {
2937
4158
  function isValidColumn(columns, column) {
2938
4159
  if (columns.includes("*"))
2939
4160
  return true;
2940
- if (column.type === "link") {
2941
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
2942
- return linkColumns.length > 0;
2943
- }
2944
- return columns.includes(column.name);
4161
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
2945
4162
  }
2946
4163
  function parseIfVersion(...args) {
2947
4164
  for (const arg of args) {
@@ -3018,10 +4235,12 @@ const notExists = (column) => ({ $notExists: column });
3018
4235
  const startsWith = (value) => ({ $startsWith: value });
3019
4236
  const endsWith = (value) => ({ $endsWith: value });
3020
4237
  const pattern = (value) => ({ $pattern: value });
4238
+ const iPattern = (value) => ({ $iPattern: value });
3021
4239
  const is = (value) => ({ $is: value });
3022
4240
  const equals = is;
3023
4241
  const isNot = (value) => ({ $isNot: value });
3024
4242
  const contains = (value) => ({ $contains: value });
4243
+ const iContains = (value) => ({ $iContains: value });
3025
4244
  const includes = (value) => ({ $includes: value });
3026
4245
  const includesAll = (value) => ({ $includesAll: value });
3027
4246
  const includesNone = (value) => ({ $includesNone: value });
@@ -3077,6 +4296,80 @@ class SchemaPlugin extends XataPlugin {
3077
4296
  _tables = new WeakMap();
3078
4297
  _schemaTables$1 = new WeakMap();
3079
4298
 
4299
+ class FilesPlugin extends XataPlugin {
4300
+ build(pluginOptions) {
4301
+ return {
4302
+ download: async (location) => {
4303
+ const { table, record, column, fileId = "" } = location ?? {};
4304
+ return await getFileItem({
4305
+ pathParams: {
4306
+ workspace: "{workspaceId}",
4307
+ dbBranchName: "{dbBranch}",
4308
+ region: "{region}",
4309
+ tableName: table ?? "",
4310
+ recordId: record ?? "",
4311
+ columnName: column ?? "",
4312
+ fileId
4313
+ },
4314
+ ...pluginOptions,
4315
+ rawResponse: true
4316
+ });
4317
+ },
4318
+ upload: async (location, file, options) => {
4319
+ const { table, record, column, fileId = "" } = location ?? {};
4320
+ const resolvedFile = await file;
4321
+ const contentType = options?.mediaType || getContentType(resolvedFile);
4322
+ const body = resolvedFile instanceof XataFile ? resolvedFile.toBlob() : resolvedFile;
4323
+ return await putFileItem({
4324
+ ...pluginOptions,
4325
+ pathParams: {
4326
+ workspace: "{workspaceId}",
4327
+ dbBranchName: "{dbBranch}",
4328
+ region: "{region}",
4329
+ tableName: table ?? "",
4330
+ recordId: record ?? "",
4331
+ columnName: column ?? "",
4332
+ fileId
4333
+ },
4334
+ body,
4335
+ headers: { "Content-Type": contentType }
4336
+ });
4337
+ },
4338
+ delete: async (location) => {
4339
+ const { table, record, column, fileId = "" } = location ?? {};
4340
+ return await deleteFileItem({
4341
+ pathParams: {
4342
+ workspace: "{workspaceId}",
4343
+ dbBranchName: "{dbBranch}",
4344
+ region: "{region}",
4345
+ tableName: table ?? "",
4346
+ recordId: record ?? "",
4347
+ columnName: column ?? "",
4348
+ fileId
4349
+ },
4350
+ ...pluginOptions
4351
+ });
4352
+ }
4353
+ };
4354
+ }
4355
+ }
4356
+ function getContentType(file) {
4357
+ if (typeof file === "string") {
4358
+ return "text/plain";
4359
+ }
4360
+ if ("mediaType" in file) {
4361
+ return file.mediaType;
4362
+ }
4363
+ if (isBlob(file)) {
4364
+ return file.type;
4365
+ }
4366
+ try {
4367
+ return file.type;
4368
+ } catch (e) {
4369
+ }
4370
+ return "application/octet-stream";
4371
+ }
4372
+
3080
4373
  var __accessCheck$1 = (obj, member, msg) => {
3081
4374
  if (!member.has(obj))
3082
4375
  throw TypeError("Cannot " + msg);
@@ -3109,19 +4402,19 @@ class SearchPlugin extends XataPlugin {
3109
4402
  __privateAdd$1(this, _schemaTables, void 0);
3110
4403
  __privateSet$1(this, _schemaTables, schemaTables);
3111
4404
  }
3112
- build({ getFetchProps }) {
4405
+ build(pluginOptions) {
3113
4406
  return {
3114
4407
  all: async (query, options = {}) => {
3115
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3116
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
4408
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4409
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3117
4410
  return records.map((record) => {
3118
4411
  const { table = "orphan" } = record.xata;
3119
4412
  return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
3120
4413
  });
3121
4414
  },
3122
4415
  byTable: async (query, options = {}) => {
3123
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3124
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
4416
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4417
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3125
4418
  return records.reduce((acc, record) => {
3126
4419
  const { table = "orphan" } = record.xata;
3127
4420
  const items = acc[table] ?? [];
@@ -3134,113 +4427,112 @@ class SearchPlugin extends XataPlugin {
3134
4427
  }
3135
4428
  _schemaTables = new WeakMap();
3136
4429
  _search = new WeakSet();
3137
- search_fn = async function(query, options, getFetchProps) {
3138
- const fetchProps = await getFetchProps();
3139
- const { tables, fuzziness, highlight, prefix } = options ?? {};
4430
+ search_fn = async function(query, options, pluginOptions) {
4431
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3140
4432
  const { records } = await searchBranch({
3141
4433
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3142
- body: { tables, query, fuzziness, prefix, highlight },
3143
- ...fetchProps
4434
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
4435
+ body: { tables, query, fuzziness, prefix, highlight, page },
4436
+ ...pluginOptions
3144
4437
  });
3145
4438
  return records;
3146
4439
  };
3147
4440
  _getSchemaTables = new WeakSet();
3148
- getSchemaTables_fn = async function(getFetchProps) {
4441
+ getSchemaTables_fn = async function(pluginOptions) {
3149
4442
  if (__privateGet$1(this, _schemaTables))
3150
4443
  return __privateGet$1(this, _schemaTables);
3151
- const fetchProps = await getFetchProps();
3152
4444
  const { schema } = await getBranchDetails({
3153
4445
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3154
- ...fetchProps
4446
+ ...pluginOptions
3155
4447
  });
3156
4448
  __privateSet$1(this, _schemaTables, schema.tables);
3157
4449
  return schema.tables;
3158
4450
  };
3159
4451
 
3160
- const isBranchStrategyBuilder = (strategy) => {
3161
- return typeof strategy === "function";
3162
- };
3163
-
3164
- async function getCurrentBranchName(options) {
3165
- const { branch, envBranch } = getEnvironment();
3166
- if (branch) {
3167
- const details = await getDatabaseBranch(branch, options);
3168
- if (details)
3169
- return branch;
3170
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
3171
- }
3172
- const gitBranch = envBranch || await getGitBranch();
3173
- return resolveXataBranch(gitBranch, options);
3174
- }
3175
- async function getCurrentBranchDetails(options) {
3176
- const branch = await getCurrentBranchName(options);
3177
- return getDatabaseBranch(branch, options);
3178
- }
3179
- async function resolveXataBranch(gitBranch, options) {
3180
- const databaseURL = options?.databaseURL || getDatabaseURL();
3181
- const apiKey = options?.apiKey || getAPIKey();
3182
- if (!databaseURL)
3183
- throw new Error(
3184
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3185
- );
3186
- if (!apiKey)
3187
- throw new Error(
3188
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3189
- );
3190
- const [protocol, , host, , dbName] = databaseURL.split("/");
3191
- const urlParts = parseWorkspacesUrlParts(host);
3192
- if (!urlParts)
3193
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3194
- const { workspace, region } = urlParts;
3195
- const { fallbackBranch } = getEnvironment();
3196
- const { branch } = await resolveBranch({
3197
- apiKey,
3198
- apiUrl: databaseURL,
3199
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3200
- workspacesApiUrl: `${protocol}//${host}`,
3201
- pathParams: { dbName, workspace, region },
3202
- queryParams: { gitBranch, fallbackBranch },
3203
- trace: defaultTrace
3204
- });
3205
- return branch;
3206
- }
3207
- async function getDatabaseBranch(branch, options) {
3208
- const databaseURL = options?.databaseURL || getDatabaseURL();
3209
- const apiKey = options?.apiKey || getAPIKey();
3210
- if (!databaseURL)
3211
- throw new Error(
3212
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3213
- );
3214
- if (!apiKey)
3215
- throw new Error(
3216
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3217
- );
3218
- const [protocol, , host, , database] = databaseURL.split("/");
3219
- const urlParts = parseWorkspacesUrlParts(host);
3220
- if (!urlParts)
3221
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3222
- const { workspace, region } = urlParts;
3223
- try {
3224
- return await getBranchDetails({
3225
- apiKey,
3226
- apiUrl: databaseURL,
3227
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3228
- workspacesApiUrl: `${protocol}//${host}`,
3229
- pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3230
- trace: defaultTrace
3231
- });
3232
- } catch (err) {
3233
- if (isObject(err) && err.status === 404)
3234
- return null;
3235
- throw err;
4452
+ function escapeElement(elementRepresentation) {
4453
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4454
+ return '"' + escaped + '"';
4455
+ }
4456
+ function arrayString(val) {
4457
+ let result = "{";
4458
+ for (let i = 0; i < val.length; i++) {
4459
+ if (i > 0) {
4460
+ result = result + ",";
4461
+ }
4462
+ if (val[i] === null || typeof val[i] === "undefined") {
4463
+ result = result + "NULL";
4464
+ } else if (Array.isArray(val[i])) {
4465
+ result = result + arrayString(val[i]);
4466
+ } else if (val[i] instanceof Buffer) {
4467
+ result += "\\\\x" + val[i].toString("hex");
4468
+ } else {
4469
+ result += escapeElement(prepareValue(val[i]));
4470
+ }
3236
4471
  }
4472
+ result = result + "}";
4473
+ return result;
3237
4474
  }
3238
- function getDatabaseURL() {
4475
+ function prepareValue(value) {
4476
+ if (!isDefined(value))
4477
+ return null;
4478
+ if (value instanceof Date) {
4479
+ return value.toISOString();
4480
+ }
4481
+ if (Array.isArray(value)) {
4482
+ return arrayString(value);
4483
+ }
4484
+ if (isObject(value)) {
4485
+ return JSON.stringify(value);
4486
+ }
3239
4487
  try {
3240
- const { databaseURL } = getEnvironment();
3241
- return databaseURL;
3242
- } catch (err) {
3243
- return void 0;
4488
+ return value.toString();
4489
+ } catch (e) {
4490
+ return value;
4491
+ }
4492
+ }
4493
+ function prepareParams(param1, param2) {
4494
+ if (isString(param1)) {
4495
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4496
+ }
4497
+ if (isStringArray(param1)) {
4498
+ const statement = param1.reduce((acc, curr, index) => {
4499
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4500
+ }, "");
4501
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4502
+ }
4503
+ if (isObject(param1)) {
4504
+ const { statement, params, consistency } = param1;
4505
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
4506
+ }
4507
+ throw new Error("Invalid query");
4508
+ }
4509
+
4510
+ class SQLPlugin extends XataPlugin {
4511
+ build(pluginOptions) {
4512
+ return async (param1, ...param2) => {
4513
+ const { statement, params, consistency } = prepareParams(param1, param2);
4514
+ const { records, warning } = await sqlQuery({
4515
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4516
+ body: { statement, params, consistency },
4517
+ ...pluginOptions
4518
+ });
4519
+ return { records, warning };
4520
+ };
4521
+ }
4522
+ }
4523
+
4524
+ class TransactionPlugin extends XataPlugin {
4525
+ build(pluginOptions) {
4526
+ return {
4527
+ run: async (operations) => {
4528
+ const response = await branchTransaction({
4529
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4530
+ body: { operations },
4531
+ ...pluginOptions
4532
+ });
4533
+ return response;
4534
+ }
4535
+ };
3244
4536
  }
3245
4537
  }
3246
4538
 
@@ -3267,46 +4559,43 @@ var __privateMethod = (obj, member, method) => {
3267
4559
  return method;
3268
4560
  };
3269
4561
  const buildClient = (plugins) => {
3270
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
4562
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3271
4563
  return _a = class {
3272
4564
  constructor(options = {}, schemaTables) {
3273
4565
  __privateAdd(this, _parseOptions);
3274
4566
  __privateAdd(this, _getFetchProps);
3275
- __privateAdd(this, _evaluateBranch);
3276
- __privateAdd(this, _branch, void 0);
3277
4567
  __privateAdd(this, _options, void 0);
3278
4568
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3279
4569
  __privateSet(this, _options, safeOptions);
3280
4570
  const pluginOptions = {
3281
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
4571
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3282
4572
  cache: safeOptions.cache,
3283
- trace: safeOptions.trace
4573
+ host: safeOptions.host
3284
4574
  };
3285
4575
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3286
4576
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
4577
+ const transactions = new TransactionPlugin().build(pluginOptions);
4578
+ const sql = new SQLPlugin().build(pluginOptions);
4579
+ const files = new FilesPlugin().build(pluginOptions);
3287
4580
  this.db = db;
3288
4581
  this.search = search;
4582
+ this.transactions = transactions;
4583
+ this.sql = sql;
4584
+ this.files = files;
3289
4585
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3290
4586
  if (namespace === void 0)
3291
4587
  continue;
3292
- const result = namespace.build(pluginOptions);
3293
- if (result instanceof Promise) {
3294
- void result.then((namespace2) => {
3295
- this[key] = namespace2;
3296
- });
3297
- } else {
3298
- this[key] = result;
3299
- }
4588
+ this[key] = namespace.build(pluginOptions);
3300
4589
  }
3301
4590
  }
3302
4591
  async getConfig() {
3303
4592
  const databaseURL = __privateGet(this, _options).databaseURL;
3304
- const branch = await __privateGet(this, _options).branch();
4593
+ const branch = __privateGet(this, _options).branch;
3305
4594
  return { databaseURL, branch };
3306
4595
  }
3307
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4596
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3308
4597
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3309
- const isBrowser = typeof window !== "undefined";
4598
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3310
4599
  if (isBrowser && !enableBrowser) {
3311
4600
  throw new Error(
3312
4601
  "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."
@@ -3317,46 +4606,73 @@ const buildClient = (plugins) => {
3317
4606
  const apiKey = options?.apiKey || getAPIKey();
3318
4607
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3319
4608
  const trace = options?.trace ?? defaultTrace;
3320
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
4609
+ const clientName = options?.clientName;
4610
+ const host = options?.host ?? "production";
4611
+ const xataAgentExtra = options?.xataAgentExtra;
3321
4612
  if (!apiKey) {
3322
4613
  throw new Error("Option apiKey is required");
3323
4614
  }
3324
4615
  if (!databaseURL) {
3325
4616
  throw new Error("Option databaseURL is required");
3326
4617
  }
3327
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser };
3328
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3329
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3330
- if (!branchValue)
3331
- throw new Error("Unable to resolve branch value");
4618
+ const envBranch = getBranch();
4619
+ const previewBranch = getPreviewBranch();
4620
+ const branch = options?.branch || previewBranch || envBranch || "main";
4621
+ if (!!previewBranch && branch !== previewBranch) {
4622
+ console.warn(
4623
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4624
+ );
4625
+ } else if (!!envBranch && branch !== envBranch) {
4626
+ console.warn(
4627
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4628
+ );
4629
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4630
+ console.warn(
4631
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4632
+ );
4633
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4634
+ console.warn(
4635
+ `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.`
4636
+ );
4637
+ }
3332
4638
  return {
3333
- fetchImpl: fetch,
4639
+ fetch,
4640
+ databaseURL,
4641
+ apiKey,
4642
+ branch,
4643
+ cache,
4644
+ trace,
4645
+ host,
4646
+ clientID: generateUUID(),
4647
+ enableBrowser,
4648
+ clientName,
4649
+ xataAgentExtra
4650
+ };
4651
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
4652
+ fetch,
4653
+ apiKey,
4654
+ databaseURL,
4655
+ branch,
4656
+ trace,
4657
+ clientID,
4658
+ clientName,
4659
+ xataAgentExtra
4660
+ }) {
4661
+ return {
4662
+ fetch,
3334
4663
  apiKey,
3335
4664
  apiUrl: "",
4665
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3336
4666
  workspacesApiUrl: (path, params) => {
3337
4667
  const hasBranch = params.dbBranchName ?? params.branch;
3338
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
4668
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
3339
4669
  return databaseURL + newPath;
3340
4670
  },
3341
4671
  trace,
3342
- clientID
4672
+ clientID,
4673
+ clientName,
4674
+ xataAgentExtra
3343
4675
  };
3344
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3345
- if (__privateGet(this, _branch))
3346
- return __privateGet(this, _branch);
3347
- if (param === void 0)
3348
- return void 0;
3349
- const strategies = Array.isArray(param) ? [...param] : [param];
3350
- const evaluateBranch = async (strategy) => {
3351
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
3352
- };
3353
- for await (const strategy of strategies) {
3354
- const branch = await evaluateBranch(strategy);
3355
- if (branch) {
3356
- __privateSet(this, _branch, branch);
3357
- return branch;
3358
- }
3359
- }
3360
4676
  }, _a;
3361
4677
  };
3362
4678
  class BaseClient extends buildClient() {
@@ -3430,7 +4746,7 @@ const deserialize = (json) => {
3430
4746
  };
3431
4747
 
3432
4748
  function buildWorkerRunner(config) {
3433
- return function xataWorker(name, _worker) {
4749
+ return function xataWorker(name, worker) {
3434
4750
  return async (...args) => {
3435
4751
  const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3436
4752
  const result = await fetch(url, {
@@ -3452,6 +4768,8 @@ class XataError extends Error {
3452
4768
  }
3453
4769
 
3454
4770
  exports.BaseClient = BaseClient;
4771
+ exports.FetcherError = FetcherError;
4772
+ exports.FilesPlugin = FilesPlugin;
3455
4773
  exports.Operations = operationsByTag;
3456
4774
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
3457
4775
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -3460,23 +4778,31 @@ exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
3460
4778
  exports.Page = Page;
3461
4779
  exports.Query = Query;
3462
4780
  exports.RecordArray = RecordArray;
4781
+ exports.RecordColumnTypes = RecordColumnTypes;
3463
4782
  exports.Repository = Repository;
3464
4783
  exports.RestRepository = RestRepository;
4784
+ exports.SQLPlugin = SQLPlugin;
3465
4785
  exports.SchemaPlugin = SchemaPlugin;
3466
4786
  exports.SearchPlugin = SearchPlugin;
3467
4787
  exports.Serializer = Serializer;
3468
4788
  exports.SimpleCache = SimpleCache;
4789
+ exports.TransactionPlugin = TransactionPlugin;
3469
4790
  exports.XataApiClient = XataApiClient;
3470
4791
  exports.XataApiPlugin = XataApiPlugin;
3471
4792
  exports.XataError = XataError;
4793
+ exports.XataFile = XataFile;
3472
4794
  exports.XataPlugin = XataPlugin;
3473
4795
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
3474
4796
  exports.addGitBranchesEntry = addGitBranchesEntry;
3475
4797
  exports.addTableColumn = addTableColumn;
3476
4798
  exports.aggregateTable = aggregateTable;
3477
4799
  exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
4800
+ exports.askTable = askTable;
4801
+ exports.askTableSession = askTableSession;
3478
4802
  exports.branchTransaction = branchTransaction;
3479
4803
  exports.buildClient = buildClient;
4804
+ exports.buildPreviewBranchName = buildPreviewBranchName;
4805
+ exports.buildProviderString = buildProviderString;
3480
4806
  exports.buildWorkerRunner = buildWorkerRunner;
3481
4807
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
3482
4808
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
@@ -3484,32 +4810,37 @@ exports.compareBranchSchemas = compareBranchSchemas;
3484
4810
  exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
3485
4811
  exports.compareMigrationRequest = compareMigrationRequest;
3486
4812
  exports.contains = contains;
4813
+ exports.copyBranch = copyBranch;
3487
4814
  exports.createBranch = createBranch;
4815
+ exports.createCluster = createCluster;
3488
4816
  exports.createDatabase = createDatabase;
3489
4817
  exports.createMigrationRequest = createMigrationRequest;
3490
4818
  exports.createTable = createTable;
3491
4819
  exports.createUserAPIKey = createUserAPIKey;
3492
4820
  exports.createWorkspace = createWorkspace;
3493
- exports.dEPRECATEDcreateDatabase = dEPRECATEDcreateDatabase;
3494
- exports.dEPRECATEDdeleteDatabase = dEPRECATEDdeleteDatabase;
3495
- exports.dEPRECATEDgetDatabaseList = dEPRECATEDgetDatabaseList;
3496
- exports.dEPRECATEDgetDatabaseMetadata = dEPRECATEDgetDatabaseMetadata;
3497
- exports.dEPRECATEDupdateDatabaseMetadata = dEPRECATEDupdateDatabaseMetadata;
3498
4821
  exports.deleteBranch = deleteBranch;
3499
4822
  exports.deleteColumn = deleteColumn;
3500
4823
  exports.deleteDatabase = deleteDatabase;
4824
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
4825
+ exports.deleteFile = deleteFile;
4826
+ exports.deleteFileItem = deleteFileItem;
4827
+ exports.deleteOAuthAccessToken = deleteOAuthAccessToken;
3501
4828
  exports.deleteRecord = deleteRecord;
3502
4829
  exports.deleteTable = deleteTable;
3503
4830
  exports.deleteUser = deleteUser;
3504
4831
  exports.deleteUserAPIKey = deleteUserAPIKey;
4832
+ exports.deleteUserOAuthClient = deleteUserOAuthClient;
3505
4833
  exports.deleteWorkspace = deleteWorkspace;
3506
4834
  exports.deserialize = deserialize;
3507
4835
  exports.endsWith = endsWith;
3508
4836
  exports.equals = equals;
3509
4837
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
3510
4838
  exports.exists = exists;
4839
+ exports.fileAccess = fileAccess;
3511
4840
  exports.ge = ge;
3512
4841
  exports.getAPIKey = getAPIKey;
4842
+ exports.getAuthorizationCode = getAuthorizationCode;
4843
+ exports.getBranch = getBranch;
3513
4844
  exports.getBranchDetails = getBranchDetails;
3514
4845
  exports.getBranchList = getBranchList;
3515
4846
  exports.getBranchMetadata = getBranchMetadata;
@@ -3517,29 +4848,38 @@ exports.getBranchMigrationHistory = getBranchMigrationHistory;
3517
4848
  exports.getBranchMigrationPlan = getBranchMigrationPlan;
3518
4849
  exports.getBranchSchemaHistory = getBranchSchemaHistory;
3519
4850
  exports.getBranchStats = getBranchStats;
4851
+ exports.getCluster = getCluster;
3520
4852
  exports.getColumn = getColumn;
3521
- exports.getCurrentBranchDetails = getCurrentBranchDetails;
3522
- exports.getCurrentBranchName = getCurrentBranchName;
4853
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
3523
4854
  exports.getDatabaseList = getDatabaseList;
3524
4855
  exports.getDatabaseMetadata = getDatabaseMetadata;
3525
4856
  exports.getDatabaseURL = getDatabaseURL;
4857
+ exports.getFile = getFile;
4858
+ exports.getFileItem = getFileItem;
3526
4859
  exports.getGitBranchesMapping = getGitBranchesMapping;
3527
4860
  exports.getHostUrl = getHostUrl;
3528
4861
  exports.getMigrationRequest = getMigrationRequest;
3529
4862
  exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
4863
+ exports.getPreviewBranch = getPreviewBranch;
3530
4864
  exports.getRecord = getRecord;
4865
+ exports.getSchema = getSchema;
3531
4866
  exports.getTableColumns = getTableColumns;
3532
4867
  exports.getTableSchema = getTableSchema;
3533
4868
  exports.getUser = getUser;
3534
4869
  exports.getUserAPIKeys = getUserAPIKeys;
4870
+ exports.getUserOAuthAccessTokens = getUserOAuthAccessTokens;
4871
+ exports.getUserOAuthClients = getUserOAuthClients;
3535
4872
  exports.getWorkspace = getWorkspace;
3536
4873
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
3537
4874
  exports.getWorkspacesList = getWorkspacesList;
4875
+ exports.grantAuthorizationCode = grantAuthorizationCode;
3538
4876
  exports.greaterEquals = greaterEquals;
3539
4877
  exports.greaterThan = greaterThan;
3540
4878
  exports.greaterThanEquals = greaterThanEquals;
3541
4879
  exports.gt = gt;
3542
4880
  exports.gte = gte;
4881
+ exports.iContains = iContains;
4882
+ exports.iPattern = iPattern;
3543
4883
  exports.includes = includes;
3544
4884
  exports.includesAll = includesAll;
3545
4885
  exports.includesAny = includesAny;
@@ -3553,11 +4893,14 @@ exports.isHostProviderAlias = isHostProviderAlias;
3553
4893
  exports.isHostProviderBuilder = isHostProviderBuilder;
3554
4894
  exports.isIdentifiable = isIdentifiable;
3555
4895
  exports.isNot = isNot;
4896
+ exports.isValidExpandedColumn = isValidExpandedColumn;
4897
+ exports.isValidSelectableColumns = isValidSelectableColumns;
3556
4898
  exports.isXataRecord = isXataRecord;
3557
4899
  exports.le = le;
3558
4900
  exports.lessEquals = lessEquals;
3559
4901
  exports.lessThan = lessThan;
3560
4902
  exports.lessThanEquals = lessThanEquals;
4903
+ exports.listClusters = listClusters;
3561
4904
  exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
3562
4905
  exports.listRegions = listRegions;
3563
4906
  exports.lt = lt;
@@ -3569,23 +4912,32 @@ exports.parseProviderString = parseProviderString;
3569
4912
  exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
3570
4913
  exports.pattern = pattern;
3571
4914
  exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
4915
+ exports.pushBranchMigrations = pushBranchMigrations;
4916
+ exports.putFile = putFile;
4917
+ exports.putFileItem = putFileItem;
3572
4918
  exports.queryMigrationRequests = queryMigrationRequests;
3573
4919
  exports.queryTable = queryTable;
3574
4920
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
3575
4921
  exports.removeWorkspaceMember = removeWorkspaceMember;
4922
+ exports.renameDatabase = renameDatabase;
3576
4923
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
3577
4924
  exports.resolveBranch = resolveBranch;
3578
4925
  exports.searchBranch = searchBranch;
3579
4926
  exports.searchTable = searchTable;
3580
4927
  exports.serialize = serialize;
3581
4928
  exports.setTableSchema = setTableSchema;
4929
+ exports.sqlQuery = sqlQuery;
3582
4930
  exports.startsWith = startsWith;
3583
4931
  exports.summarizeTable = summarizeTable;
4932
+ exports.transformImage = transformImage;
3584
4933
  exports.updateBranchMetadata = updateBranchMetadata;
3585
4934
  exports.updateBranchSchema = updateBranchSchema;
4935
+ exports.updateCluster = updateCluster;
3586
4936
  exports.updateColumn = updateColumn;
4937
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
3587
4938
  exports.updateDatabaseMetadata = updateDatabaseMetadata;
3588
4939
  exports.updateMigrationRequest = updateMigrationRequest;
4940
+ exports.updateOAuthAccessToken = updateOAuthAccessToken;
3589
4941
  exports.updateRecordWithID = updateRecordWithID;
3590
4942
  exports.updateTable = updateTable;
3591
4943
  exports.updateUser = updateUser;
@@ -3593,4 +4945,5 @@ exports.updateWorkspace = updateWorkspace;
3593
4945
  exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
3594
4946
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
3595
4947
  exports.upsertRecordWithID = upsertRecordWithID;
4948
+ exports.vectorSearchTable = vectorSearchTable;
3596
4949
  //# sourceMappingURL=index.cjs.map