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