@xata.io/client 0.0.0-alpha.vf4e6746 → 0.0.0-alpha.vf501d195ec7907e696637eff52ae02941341dca1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,8 @@
1
1
  'use strict';
2
2
 
3
- const defaultTrace = async (_name, fn, _options) => {
3
+ const defaultTrace = async (name, fn, _options) => {
4
4
  return await fn({
5
+ name,
5
6
  setAttributes: () => {
6
7
  return;
7
8
  }
@@ -19,7 +20,8 @@ const TraceAttributes = {
19
20
  HTTP_METHOD: "http.method",
20
21
  HTTP_URL: "http.url",
21
22
  HTTP_ROUTE: "http.route",
22
- HTTP_TARGET: "http.target"
23
+ HTTP_TARGET: "http.target",
24
+ CLOUDFLARE_RAY_ID: "cf.ray"
23
25
  };
24
26
 
25
27
  function notEmpty(value) {
@@ -28,8 +30,18 @@ function notEmpty(value) {
28
30
  function compact(arr) {
29
31
  return arr.filter(notEmpty);
30
32
  }
33
+ function compactObject(obj) {
34
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
35
+ }
36
+ function isBlob(value) {
37
+ try {
38
+ return value instanceof Blob;
39
+ } catch (error) {
40
+ return false;
41
+ }
42
+ }
31
43
  function isObject(value) {
32
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
44
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
33
45
  }
34
46
  function isDefined(value) {
35
47
  return value !== null && value !== void 0;
@@ -84,6 +96,27 @@ function chunk(array, chunkSize) {
84
96
  async function timeout(ms) {
85
97
  return new Promise((resolve) => setTimeout(resolve, ms));
86
98
  }
99
+ function timeoutWithCancel(ms) {
100
+ let timeoutId;
101
+ const promise = new Promise((resolve) => {
102
+ timeoutId = setTimeout(() => {
103
+ resolve();
104
+ }, ms);
105
+ });
106
+ return {
107
+ cancel: () => clearTimeout(timeoutId),
108
+ promise
109
+ };
110
+ }
111
+ function promiseMap(inputValues, mapper) {
112
+ const reducer = (acc$, inputValue) => acc$.then(
113
+ (acc) => mapper(inputValue).then((result) => {
114
+ acc.push(result);
115
+ return acc;
116
+ })
117
+ );
118
+ return inputValues.reduce(reducer, Promise.resolve([]));
119
+ }
87
120
 
88
121
  function getEnvironment() {
89
122
  try {
@@ -92,8 +125,10 @@ function getEnvironment() {
92
125
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
93
126
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
94
127
  branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
95
- envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
96
- fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
128
+ deployPreview: process.env.XATA_PREVIEW,
129
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
130
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
131
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
97
132
  };
98
133
  }
99
134
  } catch (err) {
@@ -104,8 +139,10 @@ function getEnvironment() {
104
139
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
105
140
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
106
141
  branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
107
- envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
108
- fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
142
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
143
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
144
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
145
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
109
146
  };
110
147
  }
111
148
  } catch (err) {
@@ -114,8 +151,10 @@ function getEnvironment() {
114
151
  apiKey: getGlobalApiKey(),
115
152
  databaseURL: getGlobalDatabaseURL(),
116
153
  branch: getGlobalBranch(),
117
- envBranch: void 0,
118
- fallbackBranch: getGlobalFallbackBranch()
154
+ deployPreview: void 0,
155
+ deployPreviewBranch: void 0,
156
+ vercelGitCommitRef: void 0,
157
+ vercelGitRepoOwner: void 0
119
158
  };
120
159
  }
121
160
  function getEnableBrowserVariable() {
@@ -158,39 +197,48 @@ function getGlobalBranch() {
158
197
  return void 0;
159
198
  }
160
199
  }
161
- function getGlobalFallbackBranch() {
200
+ function getDatabaseURL() {
162
201
  try {
163
- return XATA_FALLBACK_BRANCH;
202
+ const { databaseURL } = getEnvironment();
203
+ return databaseURL;
164
204
  } catch (err) {
165
205
  return void 0;
166
206
  }
167
207
  }
168
- async function getGitBranch() {
169
- const cmd = ["git", "branch", "--show-current"];
170
- const fullCmd = cmd.join(" ");
171
- const nodeModule = ["child", "process"].join("_");
172
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
208
+ function getAPIKey() {
173
209
  try {
174
- if (typeof require === "function") {
175
- return require(nodeModule).execSync(fullCmd, execOptions).trim();
176
- }
177
- const { execSync } = await import(nodeModule);
178
- return execSync(fullCmd, execOptions).toString().trim();
210
+ const { apiKey } = getEnvironment();
211
+ return apiKey;
179
212
  } catch (err) {
213
+ return void 0;
180
214
  }
215
+ }
216
+ function getBranch() {
181
217
  try {
182
- if (isObject(Deno)) {
183
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
184
- return new TextDecoder().decode(await process2.output()).trim();
185
- }
218
+ const { branch } = getEnvironment();
219
+ return branch;
186
220
  } catch (err) {
221
+ return void 0;
187
222
  }
188
223
  }
189
-
190
- function getAPIKey() {
224
+ function buildPreviewBranchName({ org, branch }) {
225
+ return `preview-${org}-${branch}`;
226
+ }
227
+ function getPreviewBranch() {
191
228
  try {
192
- const { apiKey } = getEnvironment();
193
- return apiKey;
229
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
230
+ if (deployPreviewBranch)
231
+ return deployPreviewBranch;
232
+ switch (deployPreview) {
233
+ case "vercel": {
234
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
235
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
236
+ return void 0;
237
+ }
238
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
239
+ }
240
+ }
241
+ return void 0;
194
242
  } catch (err) {
195
243
  return void 0;
196
244
  }
@@ -219,13 +267,13 @@ var __privateMethod$4 = (obj, member, method) => {
219
267
  return method;
220
268
  };
221
269
  var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
270
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
222
271
  function getFetchImplementation(userFetch) {
223
272
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
224
- const fetchImpl = userFetch ?? globalFetch;
273
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
274
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
225
275
  if (!fetchImpl) {
226
- throw new Error(
227
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
228
- );
276
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
229
277
  }
230
278
  return fetchImpl;
231
279
  }
@@ -250,18 +298,22 @@ class ApiRequestPool {
250
298
  return __privateGet$8(this, _fetch);
251
299
  }
252
300
  request(url, options) {
253
- const start = new Date();
254
- const fetch2 = this.getFetch();
301
+ const start = /* @__PURE__ */ new Date();
302
+ const fetchImpl = this.getFetch();
255
303
  const runRequest = async (stalled = false) => {
256
- const response = await fetch2(url, options);
304
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
305
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
306
+ if (!response) {
307
+ throw new Error("Request timed out");
308
+ }
257
309
  if (response.status === 429) {
258
310
  const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
259
311
  await timeout(rateLimitReset * 1e3);
260
312
  return await runRequest(true);
261
313
  }
262
314
  if (stalled) {
263
- const stalledTime = new Date().getTime() - start.getTime();
264
- console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
315
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
316
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
265
317
  }
266
318
  return response;
267
319
  };
@@ -296,7 +348,187 @@ enqueue_fn = function(task) {
296
348
  return promise;
297
349
  };
298
350
 
299
- const VERSION = "0.0.0-alpha.vf4e6746";
351
+ function generateUUID() {
352
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
353
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
354
+ return v.toString(16);
355
+ });
356
+ }
357
+
358
+ async function getBytes(stream, onChunk) {
359
+ const reader = stream.getReader();
360
+ let result;
361
+ while (!(result = await reader.read()).done) {
362
+ onChunk(result.value);
363
+ }
364
+ }
365
+ function getLines(onLine) {
366
+ let buffer;
367
+ let position;
368
+ let fieldLength;
369
+ let discardTrailingNewline = false;
370
+ return function onChunk(arr) {
371
+ if (buffer === void 0) {
372
+ buffer = arr;
373
+ position = 0;
374
+ fieldLength = -1;
375
+ } else {
376
+ buffer = concat(buffer, arr);
377
+ }
378
+ const bufLength = buffer.length;
379
+ let lineStart = 0;
380
+ while (position < bufLength) {
381
+ if (discardTrailingNewline) {
382
+ if (buffer[position] === 10 /* NewLine */) {
383
+ lineStart = ++position;
384
+ }
385
+ discardTrailingNewline = false;
386
+ }
387
+ let lineEnd = -1;
388
+ for (; position < bufLength && lineEnd === -1; ++position) {
389
+ switch (buffer[position]) {
390
+ case 58 /* Colon */:
391
+ if (fieldLength === -1) {
392
+ fieldLength = position - lineStart;
393
+ }
394
+ break;
395
+ case 13 /* CarriageReturn */:
396
+ discardTrailingNewline = true;
397
+ case 10 /* NewLine */:
398
+ lineEnd = position;
399
+ break;
400
+ }
401
+ }
402
+ if (lineEnd === -1) {
403
+ break;
404
+ }
405
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
406
+ lineStart = position;
407
+ fieldLength = -1;
408
+ }
409
+ if (lineStart === bufLength) {
410
+ buffer = void 0;
411
+ } else if (lineStart !== 0) {
412
+ buffer = buffer.subarray(lineStart);
413
+ position -= lineStart;
414
+ }
415
+ };
416
+ }
417
+ function getMessages(onId, onRetry, onMessage) {
418
+ let message = newMessage();
419
+ const decoder = new TextDecoder();
420
+ return function onLine(line, fieldLength) {
421
+ if (line.length === 0) {
422
+ onMessage?.(message);
423
+ message = newMessage();
424
+ } else if (fieldLength > 0) {
425
+ const field = decoder.decode(line.subarray(0, fieldLength));
426
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
427
+ const value = decoder.decode(line.subarray(valueOffset));
428
+ switch (field) {
429
+ case "data":
430
+ message.data = message.data ? message.data + "\n" + value : value;
431
+ break;
432
+ case "event":
433
+ message.event = value;
434
+ break;
435
+ case "id":
436
+ onId(message.id = value);
437
+ break;
438
+ case "retry":
439
+ const retry = parseInt(value, 10);
440
+ if (!isNaN(retry)) {
441
+ onRetry(message.retry = retry);
442
+ }
443
+ break;
444
+ }
445
+ }
446
+ };
447
+ }
448
+ function concat(a, b) {
449
+ const res = new Uint8Array(a.length + b.length);
450
+ res.set(a);
451
+ res.set(b, a.length);
452
+ return res;
453
+ }
454
+ function newMessage() {
455
+ return {
456
+ data: "",
457
+ event: "",
458
+ id: "",
459
+ retry: void 0
460
+ };
461
+ }
462
+ const EventStreamContentType = "text/event-stream";
463
+ const LastEventId = "last-event-id";
464
+ function fetchEventSource(input, {
465
+ signal: inputSignal,
466
+ headers: inputHeaders,
467
+ onopen: inputOnOpen,
468
+ onmessage,
469
+ onclose,
470
+ onerror,
471
+ fetch: inputFetch,
472
+ ...rest
473
+ }) {
474
+ return new Promise((resolve, reject) => {
475
+ const headers = { ...inputHeaders };
476
+ if (!headers.accept) {
477
+ headers.accept = EventStreamContentType;
478
+ }
479
+ let curRequestController;
480
+ function dispose() {
481
+ curRequestController.abort();
482
+ }
483
+ inputSignal?.addEventListener("abort", () => {
484
+ dispose();
485
+ resolve();
486
+ });
487
+ const fetchImpl = inputFetch ?? fetch;
488
+ const onopen = inputOnOpen ?? defaultOnOpen;
489
+ async function create() {
490
+ curRequestController = new AbortController();
491
+ try {
492
+ const response = await fetchImpl(input, {
493
+ ...rest,
494
+ headers,
495
+ signal: curRequestController.signal
496
+ });
497
+ await onopen(response);
498
+ await getBytes(
499
+ response.body,
500
+ getLines(
501
+ getMessages(
502
+ (id) => {
503
+ if (id) {
504
+ headers[LastEventId] = id;
505
+ } else {
506
+ delete headers[LastEventId];
507
+ }
508
+ },
509
+ (_retry) => {
510
+ },
511
+ onmessage
512
+ )
513
+ )
514
+ );
515
+ onclose?.();
516
+ dispose();
517
+ resolve();
518
+ } catch (err) {
519
+ }
520
+ }
521
+ create();
522
+ });
523
+ }
524
+ function defaultOnOpen(response) {
525
+ const contentType = response.headers?.get("content-type");
526
+ if (!contentType?.startsWith(EventStreamContentType)) {
527
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
528
+ }
529
+ }
530
+
531
+ const VERSION = "0.28.4";
300
532
 
301
533
  class ErrorWithCause extends Error {
302
534
  constructor(message, options) {
@@ -307,7 +539,7 @@ class FetcherError extends ErrorWithCause {
307
539
  constructor(status, data, requestId) {
308
540
  super(getMessage(data));
309
541
  this.status = status;
310
- this.errors = isBulkError(data) ? data.errors : void 0;
542
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
311
543
  this.requestId = requestId;
312
544
  if (data instanceof Error) {
313
545
  this.stack = data.stack;
@@ -339,6 +571,67 @@ function getMessage(data) {
339
571
  }
340
572
  }
341
573
 
574
+ function getHostUrl(provider, type) {
575
+ if (isHostProviderAlias(provider)) {
576
+ return providers[provider][type];
577
+ } else if (isHostProviderBuilder(provider)) {
578
+ return provider[type];
579
+ }
580
+ throw new Error("Invalid API provider");
581
+ }
582
+ const providers = {
583
+ production: {
584
+ main: "https://api.xata.io",
585
+ workspaces: "https://{workspaceId}.{region}.xata.sh"
586
+ },
587
+ staging: {
588
+ main: "https://api.staging-xata.dev",
589
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
590
+ },
591
+ dev: {
592
+ main: "https://api.dev-xata.dev",
593
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
594
+ },
595
+ local: {
596
+ main: "http://localhost:6001",
597
+ workspaces: "http://{workspaceId}.{region}.localhost:6001"
598
+ }
599
+ };
600
+ function isHostProviderAlias(alias) {
601
+ return isString(alias) && Object.keys(providers).includes(alias);
602
+ }
603
+ function isHostProviderBuilder(builder) {
604
+ return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
605
+ }
606
+ function parseProviderString(provider = "production") {
607
+ if (isHostProviderAlias(provider)) {
608
+ return provider;
609
+ }
610
+ const [main, workspaces] = provider.split(",");
611
+ if (!main || !workspaces)
612
+ return null;
613
+ return { main, workspaces };
614
+ }
615
+ function buildProviderString(provider) {
616
+ if (isHostProviderAlias(provider))
617
+ return provider;
618
+ return `${provider.main},${provider.workspaces}`;
619
+ }
620
+ function parseWorkspacesUrlParts(url) {
621
+ if (!isString(url))
622
+ return null;
623
+ const matches = {
624
+ production: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/),
625
+ staging: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/),
626
+ dev: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/),
627
+ local: url.match(/(?:https?:\/\/)?([^.]+)(?:\.([^.]+))\.localhost:(\d+)/)
628
+ };
629
+ const [host, match] = Object.entries(matches).find(([, match2]) => match2 !== null) ?? [];
630
+ if (!isHostProviderAlias(host) || !match)
631
+ return null;
632
+ return { workspace: match[1], region: match[2], host };
633
+ }
634
+
342
635
  const pool = new ApiRequestPool();
343
636
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
344
637
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
@@ -354,6 +647,7 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
354
647
  return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
355
648
  };
356
649
  function buildBaseUrl({
650
+ method,
357
651
  endpoint,
358
652
  path,
359
653
  workspacesApiUrl,
@@ -361,7 +655,24 @@ function buildBaseUrl({
361
655
  pathParams = {}
362
656
  }) {
363
657
  if (endpoint === "dataPlane") {
364
- const url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
658
+ let url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
659
+ if (method.toUpperCase() === "PUT" && [
660
+ "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
661
+ "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}"
662
+ ].includes(path)) {
663
+ const { host } = parseWorkspacesUrlParts(url) ?? {};
664
+ switch (host) {
665
+ case "production":
666
+ url = url.replace("xata.sh", "upload.xata.sh");
667
+ break;
668
+ case "staging":
669
+ url = url.replace("staging-xata.dev", "upload.staging-xata.dev");
670
+ break;
671
+ case "dev":
672
+ url = url.replace("dev-xata.dev", "upload.dev-xata.dev");
673
+ break;
674
+ }
675
+ }
365
676
  const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
366
677
  return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
367
678
  }
@@ -372,14 +683,27 @@ function hostHeader(url) {
372
683
  const { groups } = pattern.exec(url) ?? {};
373
684
  return groups?.host ? { Host: groups.host } : {};
374
685
  }
686
+ async function parseBody(body, headers) {
687
+ if (!isDefined(body))
688
+ return void 0;
689
+ if (isBlob(body) || typeof body.text === "function") {
690
+ return body;
691
+ }
692
+ const { "Content-Type": contentType } = headers ?? {};
693
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
694
+ return JSON.stringify(body);
695
+ }
696
+ return body;
697
+ }
698
+ const defaultClientID = generateUUID();
375
699
  async function fetch$1({
376
700
  url: path,
377
701
  method,
378
702
  body,
379
- headers,
703
+ headers: customHeaders,
380
704
  pathParams,
381
705
  queryParams,
382
- fetchImpl,
706
+ fetch: fetch2,
383
707
  apiKey,
384
708
  endpoint,
385
709
  apiUrl,
@@ -388,32 +712,43 @@ async function fetch$1({
388
712
  signal,
389
713
  clientID,
390
714
  sessionID,
391
- fetchOptions = {}
715
+ clientName,
716
+ xataAgentExtra,
717
+ fetchOptions = {},
718
+ rawResponse = false
392
719
  }) {
393
- pool.setFetch(fetchImpl);
720
+ pool.setFetch(fetch2);
394
721
  return await trace(
395
722
  `${method.toUpperCase()} ${path}`,
396
723
  async ({ setAttributes }) => {
397
- const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
724
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
398
725
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
399
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
726
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\.[^.]+\./, "http://") : fullUrl;
400
727
  setAttributes({
401
728
  [TraceAttributes.HTTP_URL]: url,
402
729
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
403
730
  });
731
+ const xataAgent = compact([
732
+ ["client", "TS_SDK"],
733
+ ["version", VERSION],
734
+ isDefined(clientName) ? ["service", clientName] : void 0,
735
+ ...Object.entries(xataAgentExtra ?? {})
736
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
737
+ const headers = compactObject({
738
+ "Accept-Encoding": "identity",
739
+ "Content-Type": "application/json",
740
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
741
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
742
+ "X-Xata-Agent": xataAgent,
743
+ ...customHeaders,
744
+ ...hostHeader(fullUrl),
745
+ Authorization: `Bearer ${apiKey}`
746
+ });
404
747
  const response = await pool.request(url, {
405
748
  ...fetchOptions,
406
749
  method: method.toUpperCase(),
407
- body: body ? JSON.stringify(body) : void 0,
408
- headers: {
409
- "Content-Type": "application/json",
410
- "User-Agent": `Xata client-ts/${VERSION}`,
411
- "X-Xata-Client-ID": clientID ?? "",
412
- "X-Xata-Session-ID": sessionID ?? "",
413
- ...headers,
414
- ...hostHeader(fullUrl),
415
- Authorization: `Bearer ${apiKey}`
416
- },
750
+ body: await parseBody(body, headers),
751
+ headers,
417
752
  signal
418
753
  });
419
754
  const { host, protocol } = parseUrl(response.url);
@@ -423,8 +758,12 @@ async function fetch$1({
423
758
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
424
759
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
425
760
  [TraceAttributes.HTTP_HOST]: host,
426
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
761
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
762
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
427
763
  });
764
+ const message = response.headers?.get("x-xata-message");
765
+ if (message)
766
+ console.warn(message);
428
767
  if (response.status === 204) {
429
768
  return {};
430
769
  }
@@ -432,7 +771,7 @@ async function fetch$1({
432
771
  throw new FetcherError(response.status, "Rate limit exceeded", requestId);
433
772
  }
434
773
  try {
435
- const jsonResponse = await response.json();
774
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
436
775
  if (response.ok) {
437
776
  return jsonResponse;
438
777
  }
@@ -444,6 +783,59 @@ async function fetch$1({
444
783
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
445
784
  );
446
785
  }
786
+ function fetchSSERequest({
787
+ url: path,
788
+ method,
789
+ body,
790
+ headers: customHeaders,
791
+ pathParams,
792
+ queryParams,
793
+ fetch: fetch2,
794
+ apiKey,
795
+ endpoint,
796
+ apiUrl,
797
+ workspacesApiUrl,
798
+ onMessage,
799
+ onError,
800
+ onClose,
801
+ signal,
802
+ clientID,
803
+ sessionID,
804
+ clientName,
805
+ xataAgentExtra
806
+ }) {
807
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
808
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
809
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
810
+ void fetchEventSource(url, {
811
+ method,
812
+ body: JSON.stringify(body),
813
+ fetch: fetch2,
814
+ signal,
815
+ headers: {
816
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
817
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
818
+ "X-Xata-Agent": compact([
819
+ ["client", "TS_SDK"],
820
+ ["version", VERSION],
821
+ isDefined(clientName) ? ["service", clientName] : void 0,
822
+ ...Object.entries(xataAgentExtra ?? {})
823
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
824
+ ...customHeaders,
825
+ Authorization: `Bearer ${apiKey}`,
826
+ "Content-Type": "application/json"
827
+ },
828
+ onmessage(ev) {
829
+ onMessage?.(JSON.parse(ev.data));
830
+ },
831
+ onerror(ev) {
832
+ onError?.(JSON.parse(ev.data));
833
+ },
834
+ onclose() {
835
+ onClose?.();
836
+ }
837
+ });
838
+ }
447
839
  function parseUrl(url) {
448
840
  try {
449
841
  const { host, protocol } = new URL(url);
@@ -455,17 +847,26 @@ function parseUrl(url) {
455
847
 
456
848
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
457
849
 
458
- const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
850
+ const applyMigration = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/pgroll/apply", method: "post", ...variables, signal });
851
+ const pgRollStatus = (variables, signal) => dataPlaneFetch({
852
+ url: "/db/{dbBranchName}/pgroll/status",
853
+ method: "get",
854
+ ...variables,
855
+ signal
856
+ });
857
+ const pgRollJobStatus = (variables, signal) => dataPlaneFetch({
858
+ url: "/db/{dbBranchName}/pgroll/jobs/{jobId}",
859
+ method: "get",
860
+ ...variables,
861
+ signal
862
+ });
863
+ const pgRollMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/pgroll/migrations", method: "get", ...variables, signal });
459
864
  const getBranchList = (variables, signal) => dataPlaneFetch({
460
865
  url: "/dbs/{dbName}",
461
866
  method: "get",
462
867
  ...variables,
463
868
  signal
464
869
  });
465
- const dEPRECATEDcreateDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
466
- const dEPRECATEDdeleteDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "delete", ...variables, signal });
467
- const dEPRECATEDgetDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "get", ...variables, signal });
468
- const dEPRECATEDupdateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
469
870
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
470
871
  url: "/db/{dbBranchName}",
471
872
  method: "get",
@@ -479,6 +880,18 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
479
880
  ...variables,
480
881
  signal
481
882
  });
883
+ const getSchema = (variables, signal) => dataPlaneFetch({
884
+ url: "/db/{dbBranchName}/schema",
885
+ method: "get",
886
+ ...variables,
887
+ signal
888
+ });
889
+ const copyBranch = (variables, signal) => dataPlaneFetch({
890
+ url: "/db/{dbBranchName}/copy",
891
+ method: "post",
892
+ ...variables,
893
+ signal
894
+ });
482
895
  const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
483
896
  url: "/db/{dbBranchName}/metadata",
484
897
  method: "put",
@@ -504,7 +917,6 @@ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName
504
917
  const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
505
918
  const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
506
919
  const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
507
- const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
508
920
  const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
509
921
  const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
510
922
  const getMigrationRequest = (variables, signal) => dataPlaneFetch({
@@ -529,6 +941,7 @@ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{
529
941
  const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
530
942
  const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
531
943
  const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
944
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
532
945
  const createTable = (variables, signal) => dataPlaneFetch({
533
946
  url: "/db/{dbBranchName}/tables/{tableName}",
534
947
  method: "put",
@@ -571,7 +984,44 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
571
984
  ...variables,
572
985
  signal
573
986
  });
987
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
574
988
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
989
+ const getFileItem = (variables, signal) => dataPlaneFetch({
990
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
991
+ method: "get",
992
+ ...variables,
993
+ signal
994
+ });
995
+ const putFileItem = (variables, signal) => dataPlaneFetch({
996
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
997
+ method: "put",
998
+ ...variables,
999
+ signal
1000
+ });
1001
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
1002
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
1003
+ method: "delete",
1004
+ ...variables,
1005
+ signal
1006
+ });
1007
+ const getFile = (variables, signal) => dataPlaneFetch({
1008
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1009
+ method: "get",
1010
+ ...variables,
1011
+ signal
1012
+ });
1013
+ const putFile = (variables, signal) => dataPlaneFetch({
1014
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1015
+ method: "put",
1016
+ ...variables,
1017
+ signal
1018
+ });
1019
+ const deleteFile = (variables, signal) => dataPlaneFetch({
1020
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1021
+ method: "delete",
1022
+ ...variables,
1023
+ signal
1024
+ });
575
1025
  const getRecord = (variables, signal) => dataPlaneFetch({
576
1026
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
577
1027
  method: "get",
@@ -601,21 +1051,45 @@ const searchTable = (variables, signal) => dataPlaneFetch({
601
1051
  ...variables,
602
1052
  signal
603
1053
  });
1054
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
1055
+ const askTable = (variables, signal) => dataPlaneFetch({
1056
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
1057
+ method: "post",
1058
+ ...variables,
1059
+ signal
1060
+ });
1061
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
604
1062
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
605
1063
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
1064
+ const fileAccess = (variables, signal) => dataPlaneFetch({
1065
+ url: "/file/{fileId}",
1066
+ method: "get",
1067
+ ...variables,
1068
+ signal
1069
+ });
1070
+ const fileUpload = (variables, signal) => dataPlaneFetch({
1071
+ url: "/file/{fileId}",
1072
+ method: "put",
1073
+ ...variables,
1074
+ signal
1075
+ });
1076
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
1077
+ url: "/db/{dbBranchName}/sql",
1078
+ method: "post",
1079
+ ...variables,
1080
+ signal
1081
+ });
606
1082
  const operationsByTag$2 = {
607
- database: {
608
- dEPRECATEDgetDatabaseList,
609
- dEPRECATEDcreateDatabase,
610
- dEPRECATEDdeleteDatabase,
611
- dEPRECATEDgetDatabaseMetadata,
612
- dEPRECATEDupdateDatabaseMetadata
613
- },
614
1083
  branch: {
1084
+ applyMigration,
1085
+ pgRollStatus,
1086
+ pgRollJobStatus,
1087
+ pgRollMigrationHistory,
615
1088
  getBranchList,
616
1089
  getBranchDetails,
617
1090
  createBranch,
618
1091
  deleteBranch,
1092
+ copyBranch,
619
1093
  updateBranchMetadata,
620
1094
  getBranchMetadata,
621
1095
  getBranchStats,
@@ -625,6 +1099,7 @@ const operationsByTag$2 = {
625
1099
  resolveBranch
626
1100
  },
627
1101
  migrations: {
1102
+ getSchema,
628
1103
  getBranchMigrationHistory,
629
1104
  getBranchMigrationPlan,
630
1105
  executeBranchMigrationPlan,
@@ -633,17 +1108,8 @@ const operationsByTag$2 = {
633
1108
  compareBranchSchemas,
634
1109
  updateBranchSchema,
635
1110
  previewBranchSchemaEdit,
636
- applyBranchSchemaEdit
637
- },
638
- records: {
639
- branchTransaction,
640
- insertRecord,
641
- getRecord,
642
- insertRecordWithID,
643
- updateRecordWithID,
644
- upsertRecordWithID,
645
- deleteRecord,
646
- bulkInsertTableRecords
1111
+ applyBranchSchemaEdit,
1112
+ pushBranchMigrations
647
1113
  },
648
1114
  migrationRequests: {
649
1115
  queryMigrationRequests,
@@ -667,11 +1133,34 @@ const operationsByTag$2 = {
667
1133
  updateColumn,
668
1134
  deleteColumn
669
1135
  },
670
- searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
1136
+ records: {
1137
+ branchTransaction,
1138
+ insertRecord,
1139
+ getRecord,
1140
+ insertRecordWithID,
1141
+ updateRecordWithID,
1142
+ upsertRecordWithID,
1143
+ deleteRecord,
1144
+ bulkInsertTableRecords
1145
+ },
1146
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess, fileUpload },
1147
+ searchAndFilter: {
1148
+ queryTable,
1149
+ searchBranch,
1150
+ searchTable,
1151
+ vectorSearchTable,
1152
+ askTable,
1153
+ askTableSession,
1154
+ summarizeTable,
1155
+ aggregateTable
1156
+ },
1157
+ sql: { sqlQuery }
671
1158
  };
672
1159
 
673
1160
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
674
1161
 
1162
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1163
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
675
1164
  const getUser = (variables, signal) => controlPlaneFetch({
676
1165
  url: "/user",
677
1166
  method: "get",
@@ -708,6 +1197,31 @@ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
708
1197
  ...variables,
709
1198
  signal
710
1199
  });
1200
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1201
+ url: "/user/oauth/clients",
1202
+ method: "get",
1203
+ ...variables,
1204
+ signal
1205
+ });
1206
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1207
+ url: "/user/oauth/clients/{clientId}",
1208
+ method: "delete",
1209
+ ...variables,
1210
+ signal
1211
+ });
1212
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1213
+ url: "/user/oauth/tokens",
1214
+ method: "get",
1215
+ ...variables,
1216
+ signal
1217
+ });
1218
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1219
+ url: "/user/oauth/tokens/{token}",
1220
+ method: "delete",
1221
+ ...variables,
1222
+ signal
1223
+ });
1224
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
711
1225
  const getWorkspacesList = (variables, signal) => controlPlaneFetch({
712
1226
  url: "/workspaces",
713
1227
  method: "get",
@@ -751,6 +1265,15 @@ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ u
751
1265
  const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
752
1266
  const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
753
1267
  const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1268
+ const listClusters = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "get", ...variables, signal });
1269
+ const createCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "post", ...variables, signal });
1270
+ const getCluster = (variables, signal) => controlPlaneFetch({
1271
+ url: "/workspaces/{workspaceId}/clusters/{clusterId}",
1272
+ method: "get",
1273
+ ...variables,
1274
+ signal
1275
+ });
1276
+ const updateCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters/{clusterId}", method: "patch", ...variables, signal });
754
1277
  const getDatabaseList = (variables, signal) => controlPlaneFetch({
755
1278
  url: "/workspaces/{workspaceId}/dbs",
756
1279
  method: "get",
@@ -766,6 +1289,10 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
766
1289
  });
767
1290
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
768
1291
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1292
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1293
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1294
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1295
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
769
1296
  const listRegions = (variables, signal) => controlPlaneFetch({
770
1297
  url: "/workspaces/{workspaceId}/regions",
771
1298
  method: "get",
@@ -773,6 +1300,15 @@ const listRegions = (variables, signal) => controlPlaneFetch({
773
1300
  signal
774
1301
  });
775
1302
  const operationsByTag$1 = {
1303
+ oAuth: {
1304
+ getAuthorizationCode,
1305
+ grantAuthorizationCode,
1306
+ getUserOAuthClients,
1307
+ deleteUserOAuthClient,
1308
+ getUserOAuthAccessTokens,
1309
+ deleteOAuthAccessToken,
1310
+ updateOAuthAccessToken
1311
+ },
776
1312
  users: { getUser, updateUser, deleteUser },
777
1313
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
778
1314
  workspaces: {
@@ -792,62 +1328,23 @@ const operationsByTag$1 = {
792
1328
  acceptWorkspaceMemberInvite,
793
1329
  resendWorkspaceMemberInvite
794
1330
  },
1331
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
795
1332
  databases: {
796
1333
  getDatabaseList,
797
1334
  createDatabase,
798
1335
  deleteDatabase,
799
1336
  getDatabaseMetadata,
800
1337
  updateDatabaseMetadata,
1338
+ renameDatabase,
1339
+ getDatabaseGithubSettings,
1340
+ updateDatabaseGithubSettings,
1341
+ deleteDatabaseGithubSettings,
801
1342
  listRegions
802
1343
  }
803
1344
  };
804
1345
 
805
1346
  const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);
806
1347
 
807
- function getHostUrl(provider, type) {
808
- if (isHostProviderAlias(provider)) {
809
- return providers[provider][type];
810
- } else if (isHostProviderBuilder(provider)) {
811
- return provider[type];
812
- }
813
- throw new Error("Invalid API provider");
814
- }
815
- const providers = {
816
- production: {
817
- main: "https://api.xata.io",
818
- workspaces: "https://{workspaceId}.{region}.xata.sh"
819
- },
820
- staging: {
821
- main: "https://staging.xatabase.co",
822
- workspaces: "https://{workspaceId}.staging.{region}.xatabase.co"
823
- }
824
- };
825
- function isHostProviderAlias(alias) {
826
- return isString(alias) && Object.keys(providers).includes(alias);
827
- }
828
- function isHostProviderBuilder(builder) {
829
- return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
830
- }
831
- function parseProviderString(provider = "production") {
832
- if (isHostProviderAlias(provider)) {
833
- return provider;
834
- }
835
- const [main, workspaces] = provider.split(",");
836
- if (!main || !workspaces)
837
- return null;
838
- return { main, workspaces };
839
- }
840
- function parseWorkspacesUrlParts(url) {
841
- if (!isString(url))
842
- return null;
843
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
844
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
845
- const match = url.match(regex) || url.match(regexStaging);
846
- if (!match)
847
- return null;
848
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
849
- }
850
-
851
1348
  var __accessCheck$7 = (obj, member, msg) => {
852
1349
  if (!member.has(obj))
853
1350
  throw TypeError("Cannot " + msg);
@@ -874,15 +1371,19 @@ class XataApiClient {
874
1371
  const provider = options.host ?? "production";
875
1372
  const apiKey = options.apiKey ?? getAPIKey();
876
1373
  const trace = options.trace ?? defaultTrace;
1374
+ const clientID = generateUUID();
877
1375
  if (!apiKey) {
878
1376
  throw new Error("Could not resolve a valid apiKey");
879
1377
  }
880
1378
  __privateSet$7(this, _extraProps, {
881
1379
  apiUrl: getHostUrl(provider, "main"),
882
1380
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
883
- fetchImpl: getFetchImplementation(options.fetch),
1381
+ fetch: getFetchImplementation(options.fetch),
884
1382
  apiKey,
885
- trace
1383
+ trace,
1384
+ clientName: options.clientName,
1385
+ xataAgentExtra: options.xataAgentExtra,
1386
+ clientID
886
1387
  });
887
1388
  }
888
1389
  get user() {
@@ -935,6 +1436,11 @@ class XataApiClient {
935
1436
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
936
1437
  return __privateGet$7(this, _namespaces).records;
937
1438
  }
1439
+ get files() {
1440
+ if (!__privateGet$7(this, _namespaces).files)
1441
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1442
+ return __privateGet$7(this, _namespaces).files;
1443
+ }
938
1444
  get searchAndFilter() {
939
1445
  if (!__privateGet$7(this, _namespaces).searchAndFilter)
940
1446
  __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
@@ -1143,6 +1649,20 @@ class BranchApi {
1143
1649
  ...this.extraProps
1144
1650
  });
1145
1651
  }
1652
+ copyBranch({
1653
+ workspace,
1654
+ region,
1655
+ database,
1656
+ branch,
1657
+ destinationBranch,
1658
+ limit
1659
+ }) {
1660
+ return operationsByTag.branch.copyBranch({
1661
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1662
+ body: { destinationBranch, limit },
1663
+ ...this.extraProps
1664
+ });
1665
+ }
1146
1666
  updateBranchMetadata({
1147
1667
  workspace,
1148
1668
  region,
@@ -1498,6 +2018,164 @@ class RecordsApi {
1498
2018
  });
1499
2019
  }
1500
2020
  }
2021
+ class FilesApi {
2022
+ constructor(extraProps) {
2023
+ this.extraProps = extraProps;
2024
+ }
2025
+ getFileItem({
2026
+ workspace,
2027
+ region,
2028
+ database,
2029
+ branch,
2030
+ table,
2031
+ record,
2032
+ column,
2033
+ fileId
2034
+ }) {
2035
+ return operationsByTag.files.getFileItem({
2036
+ pathParams: {
2037
+ workspace,
2038
+ region,
2039
+ dbBranchName: `${database}:${branch}`,
2040
+ tableName: table,
2041
+ recordId: record,
2042
+ columnName: column,
2043
+ fileId
2044
+ },
2045
+ ...this.extraProps
2046
+ });
2047
+ }
2048
+ putFileItem({
2049
+ workspace,
2050
+ region,
2051
+ database,
2052
+ branch,
2053
+ table,
2054
+ record,
2055
+ column,
2056
+ fileId,
2057
+ file
2058
+ }) {
2059
+ return operationsByTag.files.putFileItem({
2060
+ pathParams: {
2061
+ workspace,
2062
+ region,
2063
+ dbBranchName: `${database}:${branch}`,
2064
+ tableName: table,
2065
+ recordId: record,
2066
+ columnName: column,
2067
+ fileId
2068
+ },
2069
+ // @ts-ignore
2070
+ body: file,
2071
+ ...this.extraProps
2072
+ });
2073
+ }
2074
+ deleteFileItem({
2075
+ workspace,
2076
+ region,
2077
+ database,
2078
+ branch,
2079
+ table,
2080
+ record,
2081
+ column,
2082
+ fileId
2083
+ }) {
2084
+ return operationsByTag.files.deleteFileItem({
2085
+ pathParams: {
2086
+ workspace,
2087
+ region,
2088
+ dbBranchName: `${database}:${branch}`,
2089
+ tableName: table,
2090
+ recordId: record,
2091
+ columnName: column,
2092
+ fileId
2093
+ },
2094
+ ...this.extraProps
2095
+ });
2096
+ }
2097
+ getFile({
2098
+ workspace,
2099
+ region,
2100
+ database,
2101
+ branch,
2102
+ table,
2103
+ record,
2104
+ column
2105
+ }) {
2106
+ return operationsByTag.files.getFile({
2107
+ pathParams: {
2108
+ workspace,
2109
+ region,
2110
+ dbBranchName: `${database}:${branch}`,
2111
+ tableName: table,
2112
+ recordId: record,
2113
+ columnName: column
2114
+ },
2115
+ ...this.extraProps
2116
+ });
2117
+ }
2118
+ putFile({
2119
+ workspace,
2120
+ region,
2121
+ database,
2122
+ branch,
2123
+ table,
2124
+ record,
2125
+ column,
2126
+ file
2127
+ }) {
2128
+ return operationsByTag.files.putFile({
2129
+ pathParams: {
2130
+ workspace,
2131
+ region,
2132
+ dbBranchName: `${database}:${branch}`,
2133
+ tableName: table,
2134
+ recordId: record,
2135
+ columnName: column
2136
+ },
2137
+ body: file,
2138
+ ...this.extraProps
2139
+ });
2140
+ }
2141
+ deleteFile({
2142
+ workspace,
2143
+ region,
2144
+ database,
2145
+ branch,
2146
+ table,
2147
+ record,
2148
+ column
2149
+ }) {
2150
+ return operationsByTag.files.deleteFile({
2151
+ pathParams: {
2152
+ workspace,
2153
+ region,
2154
+ dbBranchName: `${database}:${branch}`,
2155
+ tableName: table,
2156
+ recordId: record,
2157
+ columnName: column
2158
+ },
2159
+ ...this.extraProps
2160
+ });
2161
+ }
2162
+ fileAccess({
2163
+ workspace,
2164
+ region,
2165
+ fileId,
2166
+ verify
2167
+ }) {
2168
+ return operationsByTag.files.fileAccess({
2169
+ pathParams: {
2170
+ workspace,
2171
+ region,
2172
+ fileId
2173
+ },
2174
+ queryParams: { verify },
2175
+ ...this.extraProps
2176
+ });
2177
+ }
2178
+ }
1501
2179
  class SearchAndFilterApi {
1502
2180
  constructor(extraProps) {
1503
2181
  this.extraProps = extraProps;
@@ -1557,6 +2235,53 @@ class SearchAndFilterApi {
1557
2235
  ...this.extraProps
1558
2236
  });
1559
2237
  }
2238
+ vectorSearchTable({
2239
+ workspace,
2240
+ region,
2241
+ database,
2242
+ branch,
2243
+ table,
2244
+ queryVector,
2245
+ column,
2246
+ similarityFunction,
2247
+ size,
2248
+ filter
2249
+ }) {
2250
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2251
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2252
+ body: { queryVector, column, similarityFunction, size, filter },
2253
+ ...this.extraProps
2254
+ });
2255
+ }
2256
+ askTable({
2257
+ workspace,
2258
+ region,
2259
+ database,
2260
+ branch,
2261
+ table,
2262
+ options
2263
+ }) {
2264
+ return operationsByTag.searchAndFilter.askTable({
2265
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2266
+ body: { ...options },
2267
+ ...this.extraProps
2268
+ });
2269
+ }
2270
+ askTableSession({
2271
+ workspace,
2272
+ region,
2273
+ database,
2274
+ branch,
2275
+ table,
2276
+ sessionId,
2277
+ message
2278
+ }) {
2279
+ return operationsByTag.searchAndFilter.askTableSession({
2280
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2281
+ body: { message },
2282
+ ...this.extraProps
2283
+ });
2284
+ }
1560
2285
  summarizeTable({
1561
2286
  workspace,
1562
2287
  region,
@@ -1757,11 +2482,13 @@ class MigrationsApi {
1757
2482
  region,
1758
2483
  database,
1759
2484
  branch,
1760
- schema
2485
+ schema,
2486
+ schemaOperations,
2487
+ branchOperations
1761
2488
  }) {
1762
2489
  return operationsByTag.migrations.compareBranchWithUserSchema({
1763
2490
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1764
- body: { schema },
2491
+ body: { schema, schemaOperations, branchOperations },
1765
2492
  ...this.extraProps
1766
2493
  });
1767
2494
  }
@@ -1771,11 +2498,12 @@ class MigrationsApi {
1771
2498
  database,
1772
2499
  branch,
1773
2500
  compare,
1774
- schema
2501
+ sourceBranchOperations,
2502
+ targetBranchOperations
1775
2503
  }) {
1776
2504
  return operationsByTag.migrations.compareBranchSchemas({
1777
2505
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1778
- body: { schema },
2506
+ body: { sourceBranchOperations, targetBranchOperations },
1779
2507
  ...this.extraProps
1780
2508
  });
1781
2509
  }
@@ -1818,6 +2546,19 @@ class MigrationsApi {
1818
2546
  ...this.extraProps
1819
2547
  });
1820
2548
  }
2549
+ pushBranchMigrations({
2550
+ workspace,
2551
+ region,
2552
+ database,
2553
+ branch,
2554
+ migrations
2555
+ }) {
2556
+ return operationsByTag.migrations.pushBranchMigrations({
2557
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2558
+ body: { migrations },
2559
+ ...this.extraProps
2560
+ });
2561
+ }
1821
2562
  }
1822
2563
  class DatabaseApi {
1823
2564
  constructor(extraProps) {
@@ -1832,11 +2573,13 @@ class DatabaseApi {
1832
2573
  createDatabase({
1833
2574
  workspace,
1834
2575
  database,
1835
- data
2576
+ data,
2577
+ headers
1836
2578
  }) {
1837
2579
  return operationsByTag.databases.createDatabase({
1838
2580
  pathParams: { workspaceId: workspace, dbName: database },
1839
2581
  body: data,
2582
+ headers,
1840
2583
  ...this.extraProps
1841
2584
  });
1842
2585
  }
@@ -1869,36 +2612,252 @@ class DatabaseApi {
1869
2612
  ...this.extraProps
1870
2613
  });
1871
2614
  }
1872
- listRegions({ workspace }) {
1873
- return operationsByTag.databases.listRegions({
1874
- pathParams: { workspaceId: workspace },
1875
- ...this.extraProps
1876
- });
2615
+ renameDatabase({
2616
+ workspace,
2617
+ database,
2618
+ newName
2619
+ }) {
2620
+ return operationsByTag.databases.renameDatabase({
2621
+ pathParams: { workspaceId: workspace, dbName: database },
2622
+ body: { newName },
2623
+ ...this.extraProps
2624
+ });
2625
+ }
2626
+ getDatabaseGithubSettings({
2627
+ workspace,
2628
+ database
2629
+ }) {
2630
+ return operationsByTag.databases.getDatabaseGithubSettings({
2631
+ pathParams: { workspaceId: workspace, dbName: database },
2632
+ ...this.extraProps
2633
+ });
2634
+ }
2635
+ updateDatabaseGithubSettings({
2636
+ workspace,
2637
+ database,
2638
+ settings
2639
+ }) {
2640
+ return operationsByTag.databases.updateDatabaseGithubSettings({
2641
+ pathParams: { workspaceId: workspace, dbName: database },
2642
+ body: settings,
2643
+ ...this.extraProps
2644
+ });
2645
+ }
2646
+ deleteDatabaseGithubSettings({
2647
+ workspace,
2648
+ database
2649
+ }) {
2650
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
2651
+ pathParams: { workspaceId: workspace, dbName: database },
2652
+ ...this.extraProps
2653
+ });
2654
+ }
2655
+ listRegions({ workspace }) {
2656
+ return operationsByTag.databases.listRegions({
2657
+ pathParams: { workspaceId: workspace },
2658
+ ...this.extraProps
2659
+ });
2660
+ }
2661
+ }
2662
+
2663
+ class XataApiPlugin {
2664
+ build(options) {
2665
+ return new XataApiClient(options);
2666
+ }
2667
+ }
2668
+
2669
+ class XataPlugin {
2670
+ }
2671
+
2672
+ function buildTransformString(transformations) {
2673
+ return transformations.flatMap(
2674
+ (t) => Object.entries(t).map(([key, value]) => {
2675
+ if (key === "trim") {
2676
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2677
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2678
+ }
2679
+ if (key === "gravity" && typeof value === "object") {
2680
+ const { x = 0.5, y = 0.5 } = value;
2681
+ return `${key}=${[x, y].join("x")}`;
2682
+ }
2683
+ return `${key}=${value}`;
2684
+ })
2685
+ ).join(",");
2686
+ }
2687
+ function transformImage(url, ...transformations) {
2688
+ if (!isDefined(url))
2689
+ return void 0;
2690
+ const newTransformations = buildTransformString(transformations);
2691
+ const { hostname, pathname, search } = new URL(url);
2692
+ const pathParts = pathname.split("/");
2693
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2694
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2695
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2696
+ const path = pathParts.join("/");
2697
+ return `https://${hostname}${transform}${path}${search}`;
2698
+ }
2699
+
2700
+ class XataFile {
2701
+ constructor(file) {
2702
+ this.id = file.id;
2703
+ this.name = file.name;
2704
+ this.mediaType = file.mediaType;
2705
+ this.base64Content = file.base64Content;
2706
+ this.enablePublicUrl = file.enablePublicUrl;
2707
+ this.signedUrlTimeout = file.signedUrlTimeout;
2708
+ this.uploadUrlTimeout = file.uploadUrlTimeout;
2709
+ this.size = file.size;
2710
+ this.version = file.version;
2711
+ this.url = file.url;
2712
+ this.signedUrl = file.signedUrl;
2713
+ this.uploadUrl = file.uploadUrl;
2714
+ this.attributes = file.attributes;
2715
+ }
2716
+ static fromBuffer(buffer, options = {}) {
2717
+ const base64Content = buffer.toString("base64");
2718
+ return new XataFile({ ...options, base64Content });
2719
+ }
2720
+ toBuffer() {
2721
+ if (!this.base64Content) {
2722
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2723
+ }
2724
+ return Buffer.from(this.base64Content, "base64");
2725
+ }
2726
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2727
+ const uint8Array = new Uint8Array(arrayBuffer);
2728
+ return this.fromUint8Array(uint8Array, options);
2729
+ }
2730
+ toArrayBuffer() {
2731
+ if (!this.base64Content) {
2732
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2733
+ }
2734
+ const binary = atob(this.base64Content);
2735
+ return new ArrayBuffer(binary.length);
2736
+ }
2737
+ static fromUint8Array(uint8Array, options = {}) {
2738
+ let binary = "";
2739
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2740
+ binary += String.fromCharCode(uint8Array[i]);
2741
+ }
2742
+ const base64Content = btoa(binary);
2743
+ return new XataFile({ ...options, base64Content });
2744
+ }
2745
+ toUint8Array() {
2746
+ if (!this.base64Content) {
2747
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2748
+ }
2749
+ const binary = atob(this.base64Content);
2750
+ const uint8Array = new Uint8Array(binary.length);
2751
+ for (let i = 0; i < binary.length; i++) {
2752
+ uint8Array[i] = binary.charCodeAt(i);
2753
+ }
2754
+ return uint8Array;
2755
+ }
2756
+ static async fromBlob(file, options = {}) {
2757
+ const name = options.name ?? file.name;
2758
+ const mediaType = file.type;
2759
+ const arrayBuffer = await file.arrayBuffer();
2760
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2761
+ }
2762
+ toBlob() {
2763
+ if (!this.base64Content) {
2764
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2765
+ }
2766
+ const binary = atob(this.base64Content);
2767
+ const uint8Array = new Uint8Array(binary.length);
2768
+ for (let i = 0; i < binary.length; i++) {
2769
+ uint8Array[i] = binary.charCodeAt(i);
2770
+ }
2771
+ return new Blob([uint8Array], { type: this.mediaType });
2772
+ }
2773
+ static fromString(string, options = {}) {
2774
+ const base64Content = btoa(string);
2775
+ return new XataFile({ ...options, base64Content });
2776
+ }
2777
+ toString() {
2778
+ if (!this.base64Content) {
2779
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2780
+ }
2781
+ return atob(this.base64Content);
2782
+ }
2783
+ static fromBase64(base64Content, options = {}) {
2784
+ return new XataFile({ ...options, base64Content });
1877
2785
  }
1878
- }
1879
-
1880
- class XataApiPlugin {
1881
- async build(options) {
1882
- const { fetchImpl, apiKey } = await options.getFetchProps();
1883
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2786
+ toBase64() {
2787
+ if (!this.base64Content) {
2788
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2789
+ }
2790
+ return this.base64Content;
2791
+ }
2792
+ transform(...options) {
2793
+ return {
2794
+ url: transformImage(this.url, ...options),
2795
+ signedUrl: transformImage(this.signedUrl, ...options),
2796
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2797
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2798
+ };
1884
2799
  }
1885
2800
  }
1886
-
1887
- class XataPlugin {
1888
- }
1889
-
1890
- function generateUUID() {
1891
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1892
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1893
- return v.toString(16);
2801
+ const parseInputFileEntry = async (entry) => {
2802
+ if (!isDefined(entry))
2803
+ return null;
2804
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout, uploadUrlTimeout } = await entry;
2805
+ return compactObject({
2806
+ id,
2807
+ // Name cannot be an empty string in our API
2808
+ name: name ? name : void 0,
2809
+ mediaType,
2810
+ base64Content,
2811
+ enablePublicUrl,
2812
+ signedUrlTimeout,
2813
+ uploadUrlTimeout
1894
2814
  });
1895
- }
2815
+ };
1896
2816
 
1897
2817
  function cleanFilter(filter) {
1898
- if (!filter)
2818
+ if (!isDefined(filter))
1899
2819
  return void 0;
1900
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1901
- return values.length > 0 ? filter : void 0;
2820
+ if (!isObject(filter))
2821
+ return filter;
2822
+ const values = Object.fromEntries(
2823
+ Object.entries(filter).reduce((acc, [key, value]) => {
2824
+ if (!isDefined(value))
2825
+ return acc;
2826
+ if (Array.isArray(value)) {
2827
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2828
+ if (clean.length === 0)
2829
+ return acc;
2830
+ return [...acc, [key, clean]];
2831
+ }
2832
+ if (isObject(value)) {
2833
+ const clean = cleanFilter(value);
2834
+ if (!isDefined(clean))
2835
+ return acc;
2836
+ return [...acc, [key, clean]];
2837
+ }
2838
+ return [...acc, [key, value]];
2839
+ }, [])
2840
+ );
2841
+ return Object.keys(values).length > 0 ? values : void 0;
2842
+ }
2843
+
2844
+ function stringifyJson(value) {
2845
+ if (!isDefined(value))
2846
+ return value;
2847
+ if (isString(value))
2848
+ return value;
2849
+ try {
2850
+ return JSON.stringify(value);
2851
+ } catch (e) {
2852
+ return value;
2853
+ }
2854
+ }
2855
+ function parseJson(value) {
2856
+ try {
2857
+ return JSON.parse(value);
2858
+ } catch (e) {
2859
+ return value;
2860
+ }
1902
2861
  }
1903
2862
 
1904
2863
  var __accessCheck$6 = (obj, member, msg) => {
@@ -1927,31 +2886,59 @@ class Page {
1927
2886
  this.meta = meta;
1928
2887
  this.records = new RecordArray(this, records);
1929
2888
  }
2889
+ /**
2890
+ * Retrieves the next page of results.
2891
+ * @param size Maximum number of results to be retrieved.
2892
+ * @param offset Number of results to skip when retrieving the results.
2893
+ * @returns The next page or results.
2894
+ */
1930
2895
  async nextPage(size, offset) {
1931
2896
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
1932
2897
  }
2898
+ /**
2899
+ * Retrieves the previous page of results.
2900
+ * @param size Maximum number of results to be retrieved.
2901
+ * @param offset Number of results to skip when retrieving the results.
2902
+ * @returns The previous page or results.
2903
+ */
1933
2904
  async previousPage(size, offset) {
1934
2905
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1935
2906
  }
2907
+ /**
2908
+ * Retrieves the start page of results.
2909
+ * @param size Maximum number of results to be retrieved.
2910
+ * @param offset Number of results to skip when retrieving the results.
2911
+ * @returns The start page or results.
2912
+ */
1936
2913
  async startPage(size, offset) {
1937
2914
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1938
2915
  }
2916
+ /**
2917
+ * Retrieves the end page of results.
2918
+ * @param size Maximum number of results to be retrieved.
2919
+ * @param offset Number of results to skip when retrieving the results.
2920
+ * @returns The end page or results.
2921
+ */
1939
2922
  async endPage(size, offset) {
1940
2923
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1941
2924
  }
2925
+ /**
2926
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
2927
+ * @returns Whether or not there will be additional results in the next page of results.
2928
+ */
1942
2929
  hasNextPage() {
1943
2930
  return this.meta.page.more;
1944
2931
  }
1945
2932
  }
1946
2933
  _query = new WeakMap();
1947
- const PAGINATION_MAX_SIZE = 200;
2934
+ const PAGINATION_MAX_SIZE = 1e3;
1948
2935
  const PAGINATION_DEFAULT_SIZE = 20;
1949
- const PAGINATION_MAX_OFFSET = 800;
2936
+ const PAGINATION_MAX_OFFSET = 49e3;
1950
2937
  const PAGINATION_DEFAULT_OFFSET = 0;
1951
2938
  function isCursorPaginationOptions(options) {
1952
2939
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1953
2940
  }
1954
- const _RecordArray = class extends Array {
2941
+ const _RecordArray = class _RecordArray extends Array {
1955
2942
  constructor(...args) {
1956
2943
  super(..._RecordArray.parseConstructorParams(...args));
1957
2944
  __privateAdd$6(this, _page, void 0);
@@ -1970,31 +2957,60 @@ const _RecordArray = class extends Array {
1970
2957
  toArray() {
1971
2958
  return new Array(...this);
1972
2959
  }
2960
+ toSerializable() {
2961
+ return JSON.parse(this.toString());
2962
+ }
2963
+ toString() {
2964
+ return JSON.stringify(this.toArray());
2965
+ }
1973
2966
  map(callbackfn, thisArg) {
1974
2967
  return this.toArray().map(callbackfn, thisArg);
1975
2968
  }
2969
+ /**
2970
+ * Retrieve next page of records
2971
+ *
2972
+ * @returns A new array of objects
2973
+ */
1976
2974
  async nextPage(size, offset) {
1977
2975
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1978
2976
  return new _RecordArray(newPage);
1979
2977
  }
2978
+ /**
2979
+ * Retrieve previous page of records
2980
+ *
2981
+ * @returns A new array of objects
2982
+ */
1980
2983
  async previousPage(size, offset) {
1981
2984
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1982
2985
  return new _RecordArray(newPage);
1983
2986
  }
2987
+ /**
2988
+ * Retrieve start page of records
2989
+ *
2990
+ * @returns A new array of objects
2991
+ */
1984
2992
  async startPage(size, offset) {
1985
2993
  const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1986
2994
  return new _RecordArray(newPage);
1987
2995
  }
2996
+ /**
2997
+ * Retrieve end page of records
2998
+ *
2999
+ * @returns A new array of objects
3000
+ */
1988
3001
  async endPage(size, offset) {
1989
3002
  const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1990
3003
  return new _RecordArray(newPage);
1991
3004
  }
3005
+ /**
3006
+ * @returns Boolean indicating if there is a next page
3007
+ */
1992
3008
  hasNextPage() {
1993
3009
  return __privateGet$6(this, _page).meta.page.more;
1994
3010
  }
1995
3011
  };
1996
- let RecordArray = _RecordArray;
1997
3012
  _page = new WeakMap();
3013
+ let RecordArray = _RecordArray;
1998
3014
 
1999
3015
  var __accessCheck$5 = (obj, member, msg) => {
2000
3016
  if (!member.has(obj))
@@ -2019,13 +3035,14 @@ var __privateMethod$3 = (obj, member, method) => {
2019
3035
  return method;
2020
3036
  };
2021
3037
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
2022
- const _Query = class {
3038
+ const _Query = class _Query {
2023
3039
  constructor(repository, table, data, rawParent) {
2024
3040
  __privateAdd$5(this, _cleanFilterConstraint);
2025
3041
  __privateAdd$5(this, _table$1, void 0);
2026
3042
  __privateAdd$5(this, _repository, void 0);
2027
3043
  __privateAdd$5(this, _data, { filter: {} });
2028
- this.meta = { page: { cursor: "start", more: true } };
3044
+ // Implements pagination
3045
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
2029
3046
  this.records = new RecordArray(this, []);
2030
3047
  __privateSet$5(this, _table$1, table);
2031
3048
  if (repository) {
@@ -2041,6 +3058,7 @@ const _Query = class {
2041
3058
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
2042
3059
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
2043
3060
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
3061
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
2044
3062
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
2045
3063
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
2046
3064
  __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
@@ -2061,18 +3079,38 @@ const _Query = class {
2061
3079
  const key = JSON.stringify({ columns, filter, sort, pagination });
2062
3080
  return toBase64(key);
2063
3081
  }
3082
+ /**
3083
+ * Builds a new query object representing a logical OR between the given subqueries.
3084
+ * @param queries An array of subqueries.
3085
+ * @returns A new Query object.
3086
+ */
2064
3087
  any(...queries) {
2065
3088
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
2066
3089
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
2067
3090
  }
3091
+ /**
3092
+ * Builds a new query object representing a logical AND between the given subqueries.
3093
+ * @param queries An array of subqueries.
3094
+ * @returns A new Query object.
3095
+ */
2068
3096
  all(...queries) {
2069
3097
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
2070
3098
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
2071
3099
  }
3100
+ /**
3101
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3102
+ * @param queries An array of subqueries.
3103
+ * @returns A new Query object.
3104
+ */
2072
3105
  not(...queries) {
2073
3106
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
2074
3107
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
2075
3108
  }
3109
+ /**
3110
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3111
+ * @param queries An array of subqueries.
3112
+ * @returns A new Query object.
3113
+ */
2076
3114
  none(...queries) {
2077
3115
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
2078
3116
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
@@ -2095,6 +3133,11 @@ const _Query = class {
2095
3133
  const sort = [...originalSort, { column, direction }];
2096
3134
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
2097
3135
  }
3136
+ /**
3137
+ * Builds a new query specifying the set of columns to be returned in the query response.
3138
+ * @param columns Array of column names to be returned by the query.
3139
+ * @returns A new Query object.
3140
+ */
2098
3141
  select(columns) {
2099
3142
  return new _Query(
2100
3143
  __privateGet$5(this, _repository),
@@ -2107,6 +3150,12 @@ const _Query = class {
2107
3150
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
2108
3151
  return __privateGet$5(this, _repository).query(query);
2109
3152
  }
3153
+ /**
3154
+ * Get results in an iterator
3155
+ *
3156
+ * @async
3157
+ * @returns Async interable of results
3158
+ */
2110
3159
  async *[Symbol.asyncIterator]() {
2111
3160
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
2112
3161
  yield record;
@@ -2167,26 +3216,53 @@ const _Query = class {
2167
3216
  );
2168
3217
  return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2169
3218
  }
3219
+ /**
3220
+ * Builds a new query object adding a cache TTL in milliseconds.
3221
+ * @param ttl The cache TTL in milliseconds.
3222
+ * @returns A new Query object.
3223
+ */
2170
3224
  cache(ttl) {
2171
3225
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2172
3226
  }
3227
+ /**
3228
+ * Retrieve next page of records
3229
+ *
3230
+ * @returns A new page object.
3231
+ */
2173
3232
  nextPage(size, offset) {
2174
3233
  return this.startPage(size, offset);
2175
3234
  }
3235
+ /**
3236
+ * Retrieve previous page of records
3237
+ *
3238
+ * @returns A new page object
3239
+ */
2176
3240
  previousPage(size, offset) {
2177
3241
  return this.startPage(size, offset);
2178
3242
  }
3243
+ /**
3244
+ * Retrieve start page of records
3245
+ *
3246
+ * @returns A new page object
3247
+ */
2179
3248
  startPage(size, offset) {
2180
3249
  return this.getPaginated({ pagination: { size, offset } });
2181
3250
  }
3251
+ /**
3252
+ * Retrieve last page of records
3253
+ *
3254
+ * @returns A new page object
3255
+ */
2182
3256
  endPage(size, offset) {
2183
3257
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2184
3258
  }
3259
+ /**
3260
+ * @returns Boolean indicating if there is a next page
3261
+ */
2185
3262
  hasNextPage() {
2186
3263
  return this.meta.page.more;
2187
3264
  }
2188
3265
  };
2189
- let Query = _Query;
2190
3266
  _table$1 = new WeakMap();
2191
3267
  _repository = new WeakMap();
2192
3268
  _data = new WeakMap();
@@ -2201,6 +3277,7 @@ cleanFilterConstraint_fn = function(column, value) {
2201
3277
  }
2202
3278
  return value;
2203
3279
  };
3280
+ let Query = _Query;
2204
3281
  function cleanParent(data, parent) {
2205
3282
  if (isCursorPaginationOptions(data.pagination)) {
2206
3283
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2208,6 +3285,21 @@ function cleanParent(data, parent) {
2208
3285
  return parent;
2209
3286
  }
2210
3287
 
3288
+ const RecordColumnTypes = [
3289
+ "bool",
3290
+ "int",
3291
+ "float",
3292
+ "string",
3293
+ "text",
3294
+ "email",
3295
+ "multiple",
3296
+ "link",
3297
+ "datetime",
3298
+ "vector",
3299
+ "file[]",
3300
+ "file",
3301
+ "json"
3302
+ ];
2211
3303
  function isIdentifiable(x) {
2212
3304
  return isObject(x) && isString(x?.id);
2213
3305
  }
@@ -2217,11 +3309,33 @@ function isXataRecord(x) {
2217
3309
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
2218
3310
  }
2219
3311
 
3312
+ function isValidExpandedColumn(column) {
3313
+ return isObject(column) && isString(column.name);
3314
+ }
3315
+ function isValidSelectableColumns(columns) {
3316
+ if (!Array.isArray(columns)) {
3317
+ return false;
3318
+ }
3319
+ return columns.every((column) => {
3320
+ if (typeof column === "string") {
3321
+ return true;
3322
+ }
3323
+ if (typeof column === "object") {
3324
+ return isValidExpandedColumn(column);
3325
+ }
3326
+ return false;
3327
+ });
3328
+ }
3329
+
2220
3330
  function isSortFilterString(value) {
2221
3331
  return isString(value);
2222
3332
  }
2223
3333
  function isSortFilterBase(filter) {
2224
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
3334
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
3335
+ if (key === "*")
3336
+ return value === "random";
3337
+ return value === "asc" || value === "desc";
3338
+ });
2225
3339
  }
2226
3340
  function isSortFilterObject(filter) {
2227
3341
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -2262,7 +3376,7 @@ var __privateMethod$2 = (obj, member, method) => {
2262
3376
  __accessCheck$4(obj, member, "access private method");
2263
3377
  return method;
2264
3378
  };
2265
- 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;
3379
+ 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;
2266
3380
  const BULK_OPERATION_MAX_SIZE = 1e3;
2267
3381
  class Repository extends Query {
2268
3382
  }
@@ -2284,6 +3398,7 @@ class RestRepository extends Query {
2284
3398
  __privateAdd$4(this, _setCacheQuery);
2285
3399
  __privateAdd$4(this, _getCacheQuery);
2286
3400
  __privateAdd$4(this, _getSchemaTables$1);
3401
+ __privateAdd$4(this, _transformObjectToApi);
2287
3402
  __privateAdd$4(this, _table, void 0);
2288
3403
  __privateAdd$4(this, _getFetchProps, void 0);
2289
3404
  __privateAdd$4(this, _db, void 0);
@@ -2294,10 +3409,7 @@ class RestRepository extends Query {
2294
3409
  __privateSet$4(this, _db, options.db);
2295
3410
  __privateSet$4(this, _cache, options.pluginOptions.cache);
2296
3411
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2297
- __privateSet$4(this, _getFetchProps, async () => {
2298
- const props = await options.pluginOptions.getFetchProps();
2299
- return { ...props, sessionID: generateUUID() };
2300
- });
3412
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2301
3413
  const trace = options.pluginOptions.trace ?? defaultTrace;
2302
3414
  __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2303
3415
  return trace(name, fn, {
@@ -2315,24 +3427,24 @@ class RestRepository extends Query {
2315
3427
  if (a.length === 0)
2316
3428
  return [];
2317
3429
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2318
- const columns = isStringArray(b) ? b : ["*"];
3430
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2319
3431
  const result = await this.read(ids, columns);
2320
3432
  return result;
2321
3433
  }
2322
3434
  if (isString(a) && isObject(b)) {
2323
3435
  if (a === "")
2324
3436
  throw new Error("The id can't be empty");
2325
- const columns = isStringArray(c) ? c : void 0;
3437
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2326
3438
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2327
3439
  }
2328
3440
  if (isObject(a) && isString(a.id)) {
2329
3441
  if (a.id === "")
2330
3442
  throw new Error("The id can't be empty");
2331
- const columns = isStringArray(b) ? b : void 0;
3443
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2332
3444
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2333
3445
  }
2334
3446
  if (isObject(a)) {
2335
- const columns = isStringArray(b) ? b : void 0;
3447
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2336
3448
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2337
3449
  }
2338
3450
  throw new Error("Invalid arguments for create method");
@@ -2340,7 +3452,7 @@ class RestRepository extends Query {
2340
3452
  }
2341
3453
  async read(a, b) {
2342
3454
  return __privateGet$4(this, _trace).call(this, "read", async () => {
2343
- const columns = isStringArray(b) ? b : ["*"];
3455
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2344
3456
  if (Array.isArray(a)) {
2345
3457
  if (a.length === 0)
2346
3458
  return [];
@@ -2354,7 +3466,6 @@ class RestRepository extends Query {
2354
3466
  }
2355
3467
  const id = extractId(a);
2356
3468
  if (id) {
2357
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2358
3469
  try {
2359
3470
  const response = await getRecord({
2360
3471
  pathParams: {
@@ -2365,10 +3476,16 @@ class RestRepository extends Query {
2365
3476
  recordId: id
2366
3477
  },
2367
3478
  queryParams: { columns },
2368
- ...fetchProps
3479
+ ...__privateGet$4(this, _getFetchProps).call(this)
2369
3480
  });
2370
3481
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2371
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3482
+ return initObject(
3483
+ __privateGet$4(this, _db),
3484
+ schemaTables,
3485
+ __privateGet$4(this, _table),
3486
+ response,
3487
+ columns
3488
+ );
2372
3489
  } catch (e) {
2373
3490
  if (isObject(e) && e.status === 404) {
2374
3491
  return null;
@@ -2410,17 +3527,23 @@ class RestRepository extends Query {
2410
3527
  ifVersion,
2411
3528
  upsert: false
2412
3529
  });
2413
- const columns = isStringArray(b) ? b : ["*"];
3530
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2414
3531
  const result = await this.read(a, columns);
2415
3532
  return result;
2416
3533
  }
2417
- if (isString(a) && isObject(b)) {
2418
- const columns = isStringArray(c) ? c : void 0;
2419
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2420
- }
2421
- if (isObject(a) && isString(a.id)) {
2422
- const columns = isStringArray(b) ? b : void 0;
2423
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3534
+ try {
3535
+ if (isString(a) && isObject(b)) {
3536
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3537
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3538
+ }
3539
+ if (isObject(a) && isString(a.id)) {
3540
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3541
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3542
+ }
3543
+ } catch (error) {
3544
+ if (error.status === 422)
3545
+ return null;
3546
+ throw error;
2424
3547
  }
2425
3548
  throw new Error("Invalid arguments for update method");
2426
3549
  });
@@ -2454,17 +3577,27 @@ class RestRepository extends Query {
2454
3577
  ifVersion,
2455
3578
  upsert: true
2456
3579
  });
2457
- const columns = isStringArray(b) ? b : ["*"];
3580
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2458
3581
  const result = await this.read(a, columns);
2459
3582
  return result;
2460
3583
  }
2461
3584
  if (isString(a) && isObject(b)) {
2462
- const columns = isStringArray(c) ? c : void 0;
2463
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3585
+ if (a === "")
3586
+ throw new Error("The id can't be empty");
3587
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3588
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2464
3589
  }
2465
3590
  if (isObject(a) && isString(a.id)) {
2466
- const columns = isStringArray(c) ? c : void 0;
2467
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3591
+ if (a.id === "")
3592
+ throw new Error("The id can't be empty");
3593
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3594
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3595
+ }
3596
+ if (!isDefined(a) && isObject(b)) {
3597
+ return await this.create(b, c);
3598
+ }
3599
+ if (isObject(a) && !isDefined(a.id)) {
3600
+ return await this.create(a, b);
2468
3601
  }
2469
3602
  throw new Error("Invalid arguments for createOrUpdate method");
2470
3603
  });
@@ -2476,17 +3609,27 @@ class RestRepository extends Query {
2476
3609
  if (a.length === 0)
2477
3610
  return [];
2478
3611
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2479
- const columns = isStringArray(b) ? b : ["*"];
3612
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2480
3613
  const result = await this.read(ids, columns);
2481
3614
  return result;
2482
3615
  }
2483
3616
  if (isString(a) && isObject(b)) {
2484
- const columns = isStringArray(c) ? c : void 0;
2485
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3617
+ if (a === "")
3618
+ throw new Error("The id can't be empty");
3619
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3620
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2486
3621
  }
2487
3622
  if (isObject(a) && isString(a.id)) {
2488
- const columns = isStringArray(c) ? c : void 0;
2489
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3623
+ if (a.id === "")
3624
+ throw new Error("The id can't be empty");
3625
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3626
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3627
+ }
3628
+ if (!isDefined(a) && isObject(b)) {
3629
+ return await this.create(b, c);
3630
+ }
3631
+ if (isObject(a) && !isDefined(a.id)) {
3632
+ return await this.create(a, b);
2490
3633
  }
2491
3634
  throw new Error("Invalid arguments for createOrReplace method");
2492
3635
  });
@@ -2503,7 +3646,7 @@ class RestRepository extends Query {
2503
3646
  return o.id;
2504
3647
  throw new Error("Invalid arguments for delete method");
2505
3648
  });
2506
- const columns = isStringArray(b) ? b : ["*"];
3649
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2507
3650
  const result = await this.read(a, columns);
2508
3651
  await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2509
3652
  return result;
@@ -2537,8 +3680,7 @@ class RestRepository extends Query {
2537
3680
  }
2538
3681
  async search(query, options = {}) {
2539
3682
  return __privateGet$4(this, _trace).call(this, "search", async () => {
2540
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2541
- const { records } = await searchTable({
3683
+ const { records, totalCount } = await searchTable({
2542
3684
  pathParams: {
2543
3685
  workspace: "{workspaceId}",
2544
3686
  dbBranchName: "{dbBranch}",
@@ -2551,17 +3693,46 @@ class RestRepository extends Query {
2551
3693
  prefix: options.prefix,
2552
3694
  highlight: options.highlight,
2553
3695
  filter: options.filter,
2554
- boosters: options.boosters
3696
+ boosters: options.boosters,
3697
+ page: options.page,
3698
+ target: options.target
2555
3699
  },
2556
- ...fetchProps
3700
+ ...__privateGet$4(this, _getFetchProps).call(this)
2557
3701
  });
2558
3702
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2559
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3703
+ return {
3704
+ records: records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"])),
3705
+ totalCount
3706
+ };
3707
+ });
3708
+ }
3709
+ async vectorSearch(column, query, options) {
3710
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3711
+ const { records, totalCount } = await vectorSearchTable({
3712
+ pathParams: {
3713
+ workspace: "{workspaceId}",
3714
+ dbBranchName: "{dbBranch}",
3715
+ region: "{region}",
3716
+ tableName: __privateGet$4(this, _table)
3717
+ },
3718
+ body: {
3719
+ column,
3720
+ queryVector: query,
3721
+ similarityFunction: options?.similarityFunction,
3722
+ size: options?.size,
3723
+ filter: options?.filter
3724
+ },
3725
+ ...__privateGet$4(this, _getFetchProps).call(this)
3726
+ });
3727
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3728
+ return {
3729
+ records: records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"])),
3730
+ totalCount
3731
+ };
2560
3732
  });
2561
3733
  }
2562
3734
  async aggregate(aggs, filter) {
2563
3735
  return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2564
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2565
3736
  const result = await aggregateTable({
2566
3737
  pathParams: {
2567
3738
  workspace: "{workspaceId}",
@@ -2570,7 +3741,7 @@ class RestRepository extends Query {
2570
3741
  tableName: __privateGet$4(this, _table)
2571
3742
  },
2572
3743
  body: { aggs, filter },
2573
- ...fetchProps
3744
+ ...__privateGet$4(this, _getFetchProps).call(this)
2574
3745
  });
2575
3746
  return result;
2576
3747
  });
@@ -2581,7 +3752,6 @@ class RestRepository extends Query {
2581
3752
  if (cacheQuery)
2582
3753
  return new Page(query, cacheQuery.meta, cacheQuery.records);
2583
3754
  const data = query.getQueryOptions();
2584
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2585
3755
  const { meta, records: objects } = await queryTable({
2586
3756
  pathParams: {
2587
3757
  workspace: "{workspaceId}",
@@ -2593,14 +3763,21 @@ class RestRepository extends Query {
2593
3763
  filter: cleanFilter(data.filter),
2594
3764
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2595
3765
  page: data.pagination,
2596
- columns: data.columns ?? ["*"]
3766
+ columns: data.columns ?? ["*"],
3767
+ consistency: data.consistency
2597
3768
  },
2598
3769
  fetchOptions: data.fetchOptions,
2599
- ...fetchProps
3770
+ ...__privateGet$4(this, _getFetchProps).call(this)
2600
3771
  });
2601
3772
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2602
3773
  const records = objects.map(
2603
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3774
+ (record) => initObject(
3775
+ __privateGet$4(this, _db),
3776
+ schemaTables,
3777
+ __privateGet$4(this, _table),
3778
+ record,
3779
+ data.columns ?? ["*"]
3780
+ )
2604
3781
  );
2605
3782
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
2606
3783
  return new Page(query, meta, records);
@@ -2609,7 +3786,6 @@ class RestRepository extends Query {
2609
3786
  async summarizeTable(query, summaries, summariesFilter) {
2610
3787
  return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2611
3788
  const data = query.getQueryOptions();
2612
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2613
3789
  const result = await summarizeTable({
2614
3790
  pathParams: {
2615
3791
  workspace: "{workspaceId}",
@@ -2621,15 +3797,55 @@ class RestRepository extends Query {
2621
3797
  filter: cleanFilter(data.filter),
2622
3798
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2623
3799
  columns: data.columns,
3800
+ consistency: data.consistency,
2624
3801
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2625
3802
  summaries,
2626
3803
  summariesFilter
2627
3804
  },
2628
- ...fetchProps
3805
+ ...__privateGet$4(this, _getFetchProps).call(this)
2629
3806
  });
2630
- return result;
3807
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3808
+ return {
3809
+ ...result,
3810
+ summaries: result.summaries.map(
3811
+ (summary) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), summary, data.columns ?? [])
3812
+ )
3813
+ };
2631
3814
  });
2632
3815
  }
3816
+ ask(question, options) {
3817
+ const questionParam = options?.sessionId ? { message: question } : { question };
3818
+ const params = {
3819
+ pathParams: {
3820
+ workspace: "{workspaceId}",
3821
+ dbBranchName: "{dbBranch}",
3822
+ region: "{region}",
3823
+ tableName: __privateGet$4(this, _table),
3824
+ sessionId: options?.sessionId
3825
+ },
3826
+ body: {
3827
+ ...questionParam,
3828
+ rules: options?.rules,
3829
+ searchType: options?.searchType,
3830
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3831
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3832
+ },
3833
+ ...__privateGet$4(this, _getFetchProps).call(this)
3834
+ };
3835
+ if (options?.onMessage) {
3836
+ fetchSSERequest({
3837
+ endpoint: "dataPlane",
3838
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3839
+ method: "POST",
3840
+ onMessage: (message) => {
3841
+ options.onMessage?.({ answer: message.text, records: message.records });
3842
+ },
3843
+ ...params
3844
+ });
3845
+ } else {
3846
+ return askTableSession(params);
3847
+ }
3848
+ }
2633
3849
  }
2634
3850
  _table = new WeakMap();
2635
3851
  _getFetchProps = new WeakMap();
@@ -2639,8 +3855,7 @@ _schemaTables$2 = new WeakMap();
2639
3855
  _trace = new WeakMap();
2640
3856
  _insertRecordWithoutId = new WeakSet();
2641
3857
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2642
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2643
- const record = transformObjectLinks(object);
3858
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2644
3859
  const response = await insertRecord({
2645
3860
  pathParams: {
2646
3861
  workspace: "{workspaceId}",
@@ -2650,15 +3865,16 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2650
3865
  },
2651
3866
  queryParams: { columns },
2652
3867
  body: record,
2653
- ...fetchProps
3868
+ ...__privateGet$4(this, _getFetchProps).call(this)
2654
3869
  });
2655
3870
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2656
3871
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2657
3872
  };
2658
3873
  _insertRecordWithId = new WeakSet();
2659
3874
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2660
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2661
- const record = transformObjectLinks(object);
3875
+ if (!recordId)
3876
+ return null;
3877
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2662
3878
  const response = await insertRecordWithID({
2663
3879
  pathParams: {
2664
3880
  workspace: "{workspaceId}",
@@ -2669,30 +3885,28 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2669
3885
  },
2670
3886
  body: record,
2671
3887
  queryParams: { createOnly, columns, ifVersion },
2672
- ...fetchProps
3888
+ ...__privateGet$4(this, _getFetchProps).call(this)
2673
3889
  });
2674
3890
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2675
3891
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2676
3892
  };
2677
3893
  _insertRecords = new WeakSet();
2678
3894
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2679
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2680
- const chunkedOperations = chunk(
2681
- objects.map((object) => ({
2682
- insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2683
- })),
2684
- BULK_OPERATION_MAX_SIZE
2685
- );
3895
+ const operations = await promiseMap(objects, async (object) => {
3896
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3897
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
3898
+ });
3899
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2686
3900
  const ids = [];
2687
- for (const operations of chunkedOperations) {
3901
+ for (const operations2 of chunkedOperations) {
2688
3902
  const { results } = await branchTransaction({
2689
3903
  pathParams: {
2690
3904
  workspace: "{workspaceId}",
2691
3905
  dbBranchName: "{dbBranch}",
2692
3906
  region: "{region}"
2693
3907
  },
2694
- body: { operations },
2695
- ...fetchProps
3908
+ body: { operations: operations2 },
3909
+ ...__privateGet$4(this, _getFetchProps).call(this)
2696
3910
  });
2697
3911
  for (const result of results) {
2698
3912
  if (result.operation === "insert") {
@@ -2706,8 +3920,9 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2706
3920
  };
2707
3921
  _updateRecordWithID = new WeakSet();
2708
3922
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2709
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2710
- const { id: _id, ...record } = transformObjectLinks(object);
3923
+ if (!recordId)
3924
+ return null;
3925
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2711
3926
  try {
2712
3927
  const response = await updateRecordWithID({
2713
3928
  pathParams: {
@@ -2719,7 +3934,7 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2719
3934
  },
2720
3935
  queryParams: { columns, ifVersion },
2721
3936
  body: record,
2722
- ...fetchProps
3937
+ ...__privateGet$4(this, _getFetchProps).call(this)
2723
3938
  });
2724
3939
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2725
3940
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2732,23 +3947,21 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2732
3947
  };
2733
3948
  _updateRecords = new WeakSet();
2734
3949
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2735
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2736
- const chunkedOperations = chunk(
2737
- objects.map(({ id, ...object }) => ({
2738
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2739
- })),
2740
- BULK_OPERATION_MAX_SIZE
2741
- );
3950
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
3951
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3952
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
3953
+ });
3954
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2742
3955
  const ids = [];
2743
- for (const operations of chunkedOperations) {
3956
+ for (const operations2 of chunkedOperations) {
2744
3957
  const { results } = await branchTransaction({
2745
3958
  pathParams: {
2746
3959
  workspace: "{workspaceId}",
2747
3960
  dbBranchName: "{dbBranch}",
2748
3961
  region: "{region}"
2749
3962
  },
2750
- body: { operations },
2751
- ...fetchProps
3963
+ body: { operations: operations2 },
3964
+ ...__privateGet$4(this, _getFetchProps).call(this)
2752
3965
  });
2753
3966
  for (const result of results) {
2754
3967
  if (result.operation === "update") {
@@ -2762,7 +3975,8 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2762
3975
  };
2763
3976
  _upsertRecordWithID = new WeakSet();
2764
3977
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2765
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3978
+ if (!recordId)
3979
+ return null;
2766
3980
  const response = await upsertRecordWithID({
2767
3981
  pathParams: {
2768
3982
  workspace: "{workspaceId}",
@@ -2773,14 +3987,15 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2773
3987
  },
2774
3988
  queryParams: { columns, ifVersion },
2775
3989
  body: object,
2776
- ...fetchProps
3990
+ ...__privateGet$4(this, _getFetchProps).call(this)
2777
3991
  });
2778
3992
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2779
3993
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2780
3994
  };
2781
3995
  _deleteRecord = new WeakSet();
2782
3996
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
2783
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3997
+ if (!recordId)
3998
+ return null;
2784
3999
  try {
2785
4000
  const response = await deleteRecord({
2786
4001
  pathParams: {
@@ -2791,7 +4006,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2791
4006
  recordId
2792
4007
  },
2793
4008
  queryParams: { columns },
2794
- ...fetchProps
4009
+ ...__privateGet$4(this, _getFetchProps).call(this)
2795
4010
  });
2796
4011
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2797
4012
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2804,9 +4019,8 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2804
4019
  };
2805
4020
  _deleteRecords = new WeakSet();
2806
4021
  deleteRecords_fn = async function(recordIds) {
2807
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2808
4022
  const chunkedOperations = chunk(
2809
- recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
4023
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2810
4024
  BULK_OPERATION_MAX_SIZE
2811
4025
  );
2812
4026
  for (const operations of chunkedOperations) {
@@ -2817,21 +4031,22 @@ deleteRecords_fn = async function(recordIds) {
2817
4031
  region: "{region}"
2818
4032
  },
2819
4033
  body: { operations },
2820
- ...fetchProps
4034
+ ...__privateGet$4(this, _getFetchProps).call(this)
2821
4035
  });
2822
4036
  }
2823
4037
  };
2824
4038
  _setCacheQuery = new WeakSet();
2825
4039
  setCacheQuery_fn = async function(query, meta, records) {
2826
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
4040
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
2827
4041
  };
2828
4042
  _getCacheQuery = new WeakSet();
2829
4043
  getCacheQuery_fn = async function(query) {
2830
4044
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2831
- const result = await __privateGet$4(this, _cache).get(key);
4045
+ const result = await __privateGet$4(this, _cache)?.get(key);
2832
4046
  if (!result)
2833
4047
  return null;
2834
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
4048
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
4049
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2835
4050
  if (ttl < 0)
2836
4051
  return null;
2837
4052
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2841,39 +4056,66 @@ _getSchemaTables$1 = new WeakSet();
2841
4056
  getSchemaTables_fn$1 = async function() {
2842
4057
  if (__privateGet$4(this, _schemaTables$2))
2843
4058
  return __privateGet$4(this, _schemaTables$2);
2844
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2845
4059
  const { schema } = await getBranchDetails({
2846
4060
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2847
- ...fetchProps
4061
+ ...__privateGet$4(this, _getFetchProps).call(this)
2848
4062
  });
2849
4063
  __privateSet$4(this, _schemaTables$2, schema.tables);
2850
4064
  return schema.tables;
2851
4065
  };
2852
- const transformObjectLinks = (object) => {
2853
- return Object.entries(object).reduce((acc, [key, value]) => {
4066
+ _transformObjectToApi = new WeakSet();
4067
+ transformObjectToApi_fn = async function(object) {
4068
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4069
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
4070
+ if (!schema)
4071
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
4072
+ const result = {};
4073
+ for (const [key, value] of Object.entries(object)) {
2854
4074
  if (key === "xata")
2855
- return acc;
2856
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
2857
- }, {});
4075
+ continue;
4076
+ const type = schema.columns.find((column) => column.name === key)?.type;
4077
+ switch (type) {
4078
+ case "link": {
4079
+ result[key] = isIdentifiable(value) ? value.id : value;
4080
+ break;
4081
+ }
4082
+ case "datetime": {
4083
+ result[key] = value instanceof Date ? value.toISOString() : value;
4084
+ break;
4085
+ }
4086
+ case `file`:
4087
+ result[key] = await parseInputFileEntry(value);
4088
+ break;
4089
+ case "file[]":
4090
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4091
+ break;
4092
+ case "json":
4093
+ result[key] = stringifyJson(value);
4094
+ break;
4095
+ default:
4096
+ result[key] = value;
4097
+ }
4098
+ }
4099
+ return result;
2858
4100
  };
2859
4101
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2860
- const result = {};
4102
+ const data = {};
2861
4103
  const { xata, ...rest } = object ?? {};
2862
- Object.assign(result, rest);
4104
+ Object.assign(data, rest);
2863
4105
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2864
4106
  if (!columns)
2865
4107
  console.error(`Table ${table} not found in schema`);
2866
4108
  for (const column of columns ?? []) {
2867
4109
  if (!isValidColumn(selectedColumns, column))
2868
4110
  continue;
2869
- const value = result[column.name];
4111
+ const value = data[column.name];
2870
4112
  switch (column.type) {
2871
4113
  case "datetime": {
2872
4114
  const date = value !== void 0 ? new Date(value) : null;
2873
4115
  if (date !== null && isNaN(date.getTime())) {
2874
4116
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2875
4117
  } else {
2876
- result[column.name] = date;
4118
+ data[column.name] = date;
2877
4119
  }
2878
4120
  break;
2879
4121
  }
@@ -2886,50 +4128,76 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2886
4128
  if (item === column.name) {
2887
4129
  return [...acc, "*"];
2888
4130
  }
2889
- if (item.startsWith(`${column.name}.`)) {
4131
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
2890
4132
  const [, ...path] = item.split(".");
2891
4133
  return [...acc, path.join(".")];
2892
4134
  }
2893
4135
  return acc;
2894
4136
  }, []);
2895
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4137
+ data[column.name] = initObject(
4138
+ db,
4139
+ schemaTables,
4140
+ linkTable,
4141
+ value,
4142
+ selectedLinkColumns
4143
+ );
2896
4144
  } else {
2897
- result[column.name] = null;
4145
+ data[column.name] = null;
2898
4146
  }
2899
4147
  break;
2900
4148
  }
4149
+ case "file":
4150
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4151
+ break;
4152
+ case "file[]":
4153
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4154
+ break;
4155
+ case "json":
4156
+ data[column.name] = parseJson(value);
4157
+ break;
2901
4158
  default:
2902
- result[column.name] = value ?? null;
4159
+ data[column.name] = value ?? null;
2903
4160
  if (column.notNull === true && value === null) {
2904
4161
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2905
4162
  }
2906
4163
  break;
2907
4164
  }
2908
4165
  }
2909
- result.read = function(columns2) {
2910
- return db[table].read(result["id"], columns2);
4166
+ const record = { ...data };
4167
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
4168
+ record.read = function(columns2) {
4169
+ return db[table].read(record["id"], columns2);
2911
4170
  };
2912
- result.update = function(data, b, c) {
2913
- const columns2 = isStringArray(b) ? b : ["*"];
4171
+ record.update = function(data2, b, c) {
4172
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2914
4173
  const ifVersion = parseIfVersion(b, c);
2915
- return db[table].update(result["id"], data, columns2, { ifVersion });
4174
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2916
4175
  };
2917
- result.replace = function(data, b, c) {
2918
- const columns2 = isStringArray(b) ? b : ["*"];
4176
+ record.replace = function(data2, b, c) {
4177
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2919
4178
  const ifVersion = parseIfVersion(b, c);
2920
- return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
4179
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2921
4180
  };
2922
- result.delete = function() {
2923
- return db[table].delete(result["id"]);
4181
+ record.delete = function() {
4182
+ return db[table].delete(record["id"]);
2924
4183
  };
2925
- result.getMetadata = function() {
2926
- return xata;
4184
+ if (metadata !== void 0) {
4185
+ record.xata = Object.freeze(metadata);
4186
+ }
4187
+ record.getMetadata = function() {
4188
+ return record.xata;
4189
+ };
4190
+ record.toSerializable = function() {
4191
+ return JSON.parse(JSON.stringify(record));
2927
4192
  };
2928
- for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
2929
- Object.defineProperty(result, prop, { enumerable: false });
4193
+ record.toString = function() {
4194
+ return JSON.stringify(record);
4195
+ };
4196
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
4197
+ Object.defineProperty(record, prop, { enumerable: false });
2930
4198
  }
2931
- Object.freeze(result);
2932
- return result;
4199
+ Object.freeze(record);
4200
+ return record;
2933
4201
  };
2934
4202
  function extractId(value) {
2935
4203
  if (isString(value))
@@ -2941,11 +4209,7 @@ function extractId(value) {
2941
4209
  function isValidColumn(columns, column) {
2942
4210
  if (columns.includes("*"))
2943
4211
  return true;
2944
- if (column.type === "link") {
2945
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
2946
- return linkColumns.length > 0;
2947
- }
2948
- return columns.includes(column.name);
4212
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
2949
4213
  }
2950
4214
  function parseIfVersion(...args) {
2951
4215
  for (const arg of args) {
@@ -3022,10 +4286,12 @@ const notExists = (column) => ({ $notExists: column });
3022
4286
  const startsWith = (value) => ({ $startsWith: value });
3023
4287
  const endsWith = (value) => ({ $endsWith: value });
3024
4288
  const pattern = (value) => ({ $pattern: value });
4289
+ const iPattern = (value) => ({ $iPattern: value });
3025
4290
  const is = (value) => ({ $is: value });
3026
4291
  const equals = is;
3027
4292
  const isNot = (value) => ({ $isNot: value });
3028
4293
  const contains = (value) => ({ $contains: value });
4294
+ const iContains = (value) => ({ $iContains: value });
3029
4295
  const includes = (value) => ({ $includes: value });
3030
4296
  const includesAll = (value) => ({ $includesAll: value });
3031
4297
  const includesNone = (value) => ({ $includesNone: value });
@@ -3081,6 +4347,80 @@ class SchemaPlugin extends XataPlugin {
3081
4347
  _tables = new WeakMap();
3082
4348
  _schemaTables$1 = new WeakMap();
3083
4349
 
4350
+ class FilesPlugin extends XataPlugin {
4351
+ build(pluginOptions) {
4352
+ return {
4353
+ download: async (location) => {
4354
+ const { table, record, column, fileId = "" } = location ?? {};
4355
+ return await getFileItem({
4356
+ pathParams: {
4357
+ workspace: "{workspaceId}",
4358
+ dbBranchName: "{dbBranch}",
4359
+ region: "{region}",
4360
+ tableName: table ?? "",
4361
+ recordId: record ?? "",
4362
+ columnName: column ?? "",
4363
+ fileId
4364
+ },
4365
+ ...pluginOptions,
4366
+ rawResponse: true
4367
+ });
4368
+ },
4369
+ upload: async (location, file, options) => {
4370
+ const { table, record, column, fileId = "" } = location ?? {};
4371
+ const resolvedFile = await file;
4372
+ const contentType = options?.mediaType || getContentType(resolvedFile);
4373
+ const body = resolvedFile instanceof XataFile ? resolvedFile.toBlob() : resolvedFile;
4374
+ return await putFileItem({
4375
+ ...pluginOptions,
4376
+ pathParams: {
4377
+ workspace: "{workspaceId}",
4378
+ dbBranchName: "{dbBranch}",
4379
+ region: "{region}",
4380
+ tableName: table ?? "",
4381
+ recordId: record ?? "",
4382
+ columnName: column ?? "",
4383
+ fileId
4384
+ },
4385
+ body,
4386
+ headers: { "Content-Type": contentType }
4387
+ });
4388
+ },
4389
+ delete: async (location) => {
4390
+ const { table, record, column, fileId = "" } = location ?? {};
4391
+ return await deleteFileItem({
4392
+ pathParams: {
4393
+ workspace: "{workspaceId}",
4394
+ dbBranchName: "{dbBranch}",
4395
+ region: "{region}",
4396
+ tableName: table ?? "",
4397
+ recordId: record ?? "",
4398
+ columnName: column ?? "",
4399
+ fileId
4400
+ },
4401
+ ...pluginOptions
4402
+ });
4403
+ }
4404
+ };
4405
+ }
4406
+ }
4407
+ function getContentType(file) {
4408
+ if (typeof file === "string") {
4409
+ return "text/plain";
4410
+ }
4411
+ if ("mediaType" in file && file.mediaType !== void 0) {
4412
+ return file.mediaType;
4413
+ }
4414
+ if (isBlob(file)) {
4415
+ return file.type;
4416
+ }
4417
+ try {
4418
+ return file.type;
4419
+ } catch (e) {
4420
+ }
4421
+ return "application/octet-stream";
4422
+ }
4423
+
3084
4424
  var __accessCheck$1 = (obj, member, msg) => {
3085
4425
  if (!member.has(obj))
3086
4426
  throw TypeError("Cannot " + msg);
@@ -3113,63 +4453,137 @@ class SearchPlugin extends XataPlugin {
3113
4453
  __privateAdd$1(this, _schemaTables, void 0);
3114
4454
  __privateSet$1(this, _schemaTables, schemaTables);
3115
4455
  }
3116
- build({ getFetchProps }) {
4456
+ build(pluginOptions) {
3117
4457
  return {
3118
4458
  all: async (query, options = {}) => {
3119
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3120
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3121
- return records.map((record) => {
3122
- const { table = "orphan" } = record.xata;
3123
- return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
3124
- });
4459
+ const { records, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4460
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
4461
+ return {
4462
+ totalCount,
4463
+ records: records.map((record) => {
4464
+ const { table = "orphan" } = record.xata;
4465
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
4466
+ })
4467
+ };
3125
4468
  },
3126
4469
  byTable: async (query, options = {}) => {
3127
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3128
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3129
- return records.reduce((acc, record) => {
4470
+ const { records: rawRecords, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4471
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
4472
+ const records = rawRecords.reduce((acc, record) => {
3130
4473
  const { table = "orphan" } = record.xata;
3131
4474
  const items = acc[table] ?? [];
3132
4475
  const item = initObject(this.db, schemaTables, table, record, ["*"]);
3133
4476
  return { ...acc, [table]: [...items, item] };
3134
4477
  }, {});
4478
+ return { totalCount, records };
3135
4479
  }
3136
4480
  };
3137
4481
  }
3138
4482
  }
3139
4483
  _schemaTables = new WeakMap();
3140
4484
  _search = new WeakSet();
3141
- search_fn = async function(query, options, getFetchProps) {
3142
- const fetchProps = await getFetchProps();
3143
- const { tables, fuzziness, highlight, prefix } = options ?? {};
3144
- const { records } = await searchBranch({
4485
+ search_fn = async function(query, options, pluginOptions) {
4486
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
4487
+ const { records, totalCount } = await searchBranch({
3145
4488
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3146
- body: { tables, query, fuzziness, prefix, highlight },
3147
- ...fetchProps
4489
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
4490
+ body: { tables, query, fuzziness, prefix, highlight, page },
4491
+ ...pluginOptions
3148
4492
  });
3149
- return records;
4493
+ return { records, totalCount };
3150
4494
  };
3151
4495
  _getSchemaTables = new WeakSet();
3152
- getSchemaTables_fn = async function(getFetchProps) {
4496
+ getSchemaTables_fn = async function(pluginOptions) {
3153
4497
  if (__privateGet$1(this, _schemaTables))
3154
4498
  return __privateGet$1(this, _schemaTables);
3155
- const fetchProps = await getFetchProps();
3156
4499
  const { schema } = await getBranchDetails({
3157
4500
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3158
- ...fetchProps
4501
+ ...pluginOptions
3159
4502
  });
3160
4503
  __privateSet$1(this, _schemaTables, schema.tables);
3161
4504
  return schema.tables;
3162
4505
  };
3163
4506
 
4507
+ function escapeElement(elementRepresentation) {
4508
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4509
+ return '"' + escaped + '"';
4510
+ }
4511
+ function arrayString(val) {
4512
+ let result = "{";
4513
+ for (let i = 0; i < val.length; i++) {
4514
+ if (i > 0) {
4515
+ result = result + ",";
4516
+ }
4517
+ if (val[i] === null || typeof val[i] === "undefined") {
4518
+ result = result + "NULL";
4519
+ } else if (Array.isArray(val[i])) {
4520
+ result = result + arrayString(val[i]);
4521
+ } else if (val[i] instanceof Buffer) {
4522
+ result += "\\\\x" + val[i].toString("hex");
4523
+ } else {
4524
+ result += escapeElement(prepareValue(val[i]));
4525
+ }
4526
+ }
4527
+ result = result + "}";
4528
+ return result;
4529
+ }
4530
+ function prepareValue(value) {
4531
+ if (!isDefined(value))
4532
+ return null;
4533
+ if (value instanceof Date) {
4534
+ return value.toISOString();
4535
+ }
4536
+ if (Array.isArray(value)) {
4537
+ return arrayString(value);
4538
+ }
4539
+ if (isObject(value)) {
4540
+ return JSON.stringify(value);
4541
+ }
4542
+ try {
4543
+ return value.toString();
4544
+ } catch (e) {
4545
+ return value;
4546
+ }
4547
+ }
4548
+ function prepareParams(param1, param2) {
4549
+ if (isString(param1)) {
4550
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4551
+ }
4552
+ if (isStringArray(param1)) {
4553
+ const statement = param1.reduce((acc, curr, index) => {
4554
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4555
+ }, "");
4556
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4557
+ }
4558
+ if (isObject(param1)) {
4559
+ const { statement, params, consistency } = param1;
4560
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
4561
+ }
4562
+ throw new Error("Invalid query");
4563
+ }
4564
+
4565
+ class SQLPlugin extends XataPlugin {
4566
+ build(pluginOptions) {
4567
+ return async (param1, ...param2) => {
4568
+ const { statement, params, consistency } = prepareParams(param1, param2);
4569
+ const { records, warning, columns } = await sqlQuery({
4570
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4571
+ body: { statement, params, consistency },
4572
+ ...pluginOptions
4573
+ });
4574
+ return { records, warning, columns };
4575
+ };
4576
+ }
4577
+ }
4578
+
3164
4579
  class TransactionPlugin extends XataPlugin {
3165
- build({ getFetchProps }) {
4580
+ build(pluginOptions) {
3166
4581
  return {
3167
4582
  run: async (operations) => {
3168
- const fetchProps = await getFetchProps();
3169
4583
  const response = await branchTransaction({
3170
4584
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3171
4585
  body: { operations },
3172
- ...fetchProps
4586
+ ...pluginOptions
3173
4587
  });
3174
4588
  return response;
3175
4589
  }
@@ -3177,93 +4591,6 @@ class TransactionPlugin extends XataPlugin {
3177
4591
  }
3178
4592
  }
3179
4593
 
3180
- const isBranchStrategyBuilder = (strategy) => {
3181
- return typeof strategy === "function";
3182
- };
3183
-
3184
- async function getCurrentBranchName(options) {
3185
- const { branch, envBranch } = getEnvironment();
3186
- if (branch) {
3187
- const details = await getDatabaseBranch(branch, options);
3188
- if (details)
3189
- return branch;
3190
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
3191
- }
3192
- const gitBranch = envBranch || await getGitBranch();
3193
- return resolveXataBranch(gitBranch, options);
3194
- }
3195
- async function getCurrentBranchDetails(options) {
3196
- const branch = await getCurrentBranchName(options);
3197
- return getDatabaseBranch(branch, options);
3198
- }
3199
- async function resolveXataBranch(gitBranch, options) {
3200
- const databaseURL = options?.databaseURL || getDatabaseURL();
3201
- const apiKey = options?.apiKey || getAPIKey();
3202
- if (!databaseURL)
3203
- throw new Error(
3204
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3205
- );
3206
- if (!apiKey)
3207
- throw new Error(
3208
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3209
- );
3210
- const [protocol, , host, , dbName] = databaseURL.split("/");
3211
- const urlParts = parseWorkspacesUrlParts(host);
3212
- if (!urlParts)
3213
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3214
- const { workspace, region } = urlParts;
3215
- const { fallbackBranch } = getEnvironment();
3216
- const { branch } = await resolveBranch({
3217
- apiKey,
3218
- apiUrl: databaseURL,
3219
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3220
- workspacesApiUrl: `${protocol}//${host}`,
3221
- pathParams: { dbName, workspace, region },
3222
- queryParams: { gitBranch, fallbackBranch },
3223
- trace: defaultTrace
3224
- });
3225
- return branch;
3226
- }
3227
- async function getDatabaseBranch(branch, options) {
3228
- const databaseURL = options?.databaseURL || getDatabaseURL();
3229
- const apiKey = options?.apiKey || getAPIKey();
3230
- if (!databaseURL)
3231
- throw new Error(
3232
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3233
- );
3234
- if (!apiKey)
3235
- throw new Error(
3236
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3237
- );
3238
- const [protocol, , host, , database] = databaseURL.split("/");
3239
- const urlParts = parseWorkspacesUrlParts(host);
3240
- if (!urlParts)
3241
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3242
- const { workspace, region } = urlParts;
3243
- try {
3244
- return await getBranchDetails({
3245
- apiKey,
3246
- apiUrl: databaseURL,
3247
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3248
- workspacesApiUrl: `${protocol}//${host}`,
3249
- pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3250
- trace: defaultTrace
3251
- });
3252
- } catch (err) {
3253
- if (isObject(err) && err.status === 404)
3254
- return null;
3255
- throw err;
3256
- }
3257
- }
3258
- function getDatabaseURL() {
3259
- try {
3260
- const { databaseURL } = getEnvironment();
3261
- return databaseURL;
3262
- } catch (err) {
3263
- return void 0;
3264
- }
3265
- }
3266
-
3267
4594
  var __accessCheck = (obj, member, msg) => {
3268
4595
  if (!member.has(obj))
3269
4596
  throw TypeError("Cannot " + msg);
@@ -3287,48 +4614,43 @@ var __privateMethod = (obj, member, method) => {
3287
4614
  return method;
3288
4615
  };
3289
4616
  const buildClient = (plugins) => {
3290
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
4617
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3291
4618
  return _a = class {
3292
4619
  constructor(options = {}, schemaTables) {
3293
4620
  __privateAdd(this, _parseOptions);
3294
4621
  __privateAdd(this, _getFetchProps);
3295
- __privateAdd(this, _evaluateBranch);
3296
- __privateAdd(this, _branch, void 0);
3297
4622
  __privateAdd(this, _options, void 0);
3298
4623
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3299
4624
  __privateSet(this, _options, safeOptions);
3300
4625
  const pluginOptions = {
3301
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
4626
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3302
4627
  cache: safeOptions.cache,
3303
- trace: safeOptions.trace
4628
+ host: safeOptions.host
3304
4629
  };
3305
4630
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3306
4631
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3307
4632
  const transactions = new TransactionPlugin().build(pluginOptions);
4633
+ const sql = new SQLPlugin().build(pluginOptions);
4634
+ const files = new FilesPlugin().build(pluginOptions);
3308
4635
  this.db = db;
3309
4636
  this.search = search;
3310
4637
  this.transactions = transactions;
4638
+ this.sql = sql;
4639
+ this.files = files;
3311
4640
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3312
4641
  if (namespace === void 0)
3313
4642
  continue;
3314
- const result = namespace.build(pluginOptions);
3315
- if (result instanceof Promise) {
3316
- void result.then((namespace2) => {
3317
- this[key] = namespace2;
3318
- });
3319
- } else {
3320
- this[key] = result;
3321
- }
4643
+ this[key] = namespace.build(pluginOptions);
3322
4644
  }
3323
4645
  }
3324
4646
  async getConfig() {
3325
4647
  const databaseURL = __privateGet(this, _options).databaseURL;
3326
- const branch = await __privateGet(this, _options).branch();
4648
+ const branch = __privateGet(this, _options).branch;
3327
4649
  return { databaseURL, branch };
3328
4650
  }
3329
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4651
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3330
4652
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3331
- const isBrowser = typeof window !== "undefined";
4653
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3332
4654
  if (isBrowser && !enableBrowser) {
3333
4655
  throw new Error(
3334
4656
  "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."
@@ -3339,46 +4661,73 @@ const buildClient = (plugins) => {
3339
4661
  const apiKey = options?.apiKey || getAPIKey();
3340
4662
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3341
4663
  const trace = options?.trace ?? defaultTrace;
3342
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
4664
+ const clientName = options?.clientName;
4665
+ const host = options?.host ?? "production";
4666
+ const xataAgentExtra = options?.xataAgentExtra;
3343
4667
  if (!apiKey) {
3344
4668
  throw new Error("Option apiKey is required");
3345
4669
  }
3346
4670
  if (!databaseURL) {
3347
4671
  throw new Error("Option databaseURL is required");
3348
4672
  }
3349
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser };
3350
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3351
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3352
- if (!branchValue)
3353
- throw new Error("Unable to resolve branch value");
4673
+ const envBranch = getBranch();
4674
+ const previewBranch = getPreviewBranch();
4675
+ const branch = options?.branch || previewBranch || envBranch || "main";
4676
+ if (!!previewBranch && branch !== previewBranch) {
4677
+ console.warn(
4678
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4679
+ );
4680
+ } else if (!!envBranch && branch !== envBranch) {
4681
+ console.warn(
4682
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4683
+ );
4684
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4685
+ console.warn(
4686
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4687
+ );
4688
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4689
+ console.warn(
4690
+ `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.`
4691
+ );
4692
+ }
4693
+ return {
4694
+ fetch,
4695
+ databaseURL,
4696
+ apiKey,
4697
+ branch,
4698
+ cache,
4699
+ trace,
4700
+ host,
4701
+ clientID: generateUUID(),
4702
+ enableBrowser,
4703
+ clientName,
4704
+ xataAgentExtra
4705
+ };
4706
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
4707
+ fetch,
4708
+ apiKey,
4709
+ databaseURL,
4710
+ branch,
4711
+ trace,
4712
+ clientID,
4713
+ clientName,
4714
+ xataAgentExtra
4715
+ }) {
3354
4716
  return {
3355
- fetchImpl: fetch,
4717
+ fetch,
3356
4718
  apiKey,
3357
4719
  apiUrl: "",
4720
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3358
4721
  workspacesApiUrl: (path, params) => {
3359
4722
  const hasBranch = params.dbBranchName ?? params.branch;
3360
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
4723
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
3361
4724
  return databaseURL + newPath;
3362
4725
  },
3363
4726
  trace,
3364
- clientID
3365
- };
3366
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3367
- if (__privateGet(this, _branch))
3368
- return __privateGet(this, _branch);
3369
- if (param === void 0)
3370
- return void 0;
3371
- const strategies = Array.isArray(param) ? [...param] : [param];
3372
- const evaluateBranch = async (strategy) => {
3373
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
4727
+ clientID,
4728
+ clientName,
4729
+ xataAgentExtra
3374
4730
  };
3375
- for await (const strategy of strategies) {
3376
- const branch = await evaluateBranch(strategy);
3377
- if (branch) {
3378
- __privateSet(this, _branch, branch);
3379
- return branch;
3380
- }
3381
- }
3382
4731
  }, _a;
3383
4732
  };
3384
4733
  class BaseClient extends buildClient() {
@@ -3451,21 +4800,6 @@ const deserialize = (json) => {
3451
4800
  return defaultSerializer.fromJSON(json);
3452
4801
  };
3453
4802
 
3454
- function buildWorkerRunner(config) {
3455
- return function xataWorker(name, _worker) {
3456
- return async (...args) => {
3457
- const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3458
- const result = await fetch(url, {
3459
- method: "POST",
3460
- headers: { "Content-Type": "application/json" },
3461
- body: serialize({ args })
3462
- });
3463
- const text = await result.text();
3464
- return deserialize(text);
3465
- };
3466
- };
3467
- }
3468
-
3469
4803
  class XataError extends Error {
3470
4804
  constructor(message, status) {
3471
4805
  super(message);
@@ -3474,6 +4808,8 @@ class XataError extends Error {
3474
4808
  }
3475
4809
 
3476
4810
  exports.BaseClient = BaseClient;
4811
+ exports.FetcherError = FetcherError;
4812
+ exports.FilesPlugin = FilesPlugin;
3477
4813
  exports.Operations = operationsByTag;
3478
4814
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
3479
4815
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -3482,56 +4818,70 @@ exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
3482
4818
  exports.Page = Page;
3483
4819
  exports.Query = Query;
3484
4820
  exports.RecordArray = RecordArray;
4821
+ exports.RecordColumnTypes = RecordColumnTypes;
3485
4822
  exports.Repository = Repository;
3486
4823
  exports.RestRepository = RestRepository;
4824
+ exports.SQLPlugin = SQLPlugin;
3487
4825
  exports.SchemaPlugin = SchemaPlugin;
3488
4826
  exports.SearchPlugin = SearchPlugin;
3489
4827
  exports.Serializer = Serializer;
3490
4828
  exports.SimpleCache = SimpleCache;
4829
+ exports.TransactionPlugin = TransactionPlugin;
3491
4830
  exports.XataApiClient = XataApiClient;
3492
4831
  exports.XataApiPlugin = XataApiPlugin;
3493
4832
  exports.XataError = XataError;
4833
+ exports.XataFile = XataFile;
3494
4834
  exports.XataPlugin = XataPlugin;
3495
4835
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
3496
4836
  exports.addGitBranchesEntry = addGitBranchesEntry;
3497
4837
  exports.addTableColumn = addTableColumn;
3498
4838
  exports.aggregateTable = aggregateTable;
3499
4839
  exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
4840
+ exports.applyMigration = applyMigration;
4841
+ exports.askTable = askTable;
4842
+ exports.askTableSession = askTableSession;
3500
4843
  exports.branchTransaction = branchTransaction;
3501
4844
  exports.buildClient = buildClient;
3502
- exports.buildWorkerRunner = buildWorkerRunner;
4845
+ exports.buildPreviewBranchName = buildPreviewBranchName;
4846
+ exports.buildProviderString = buildProviderString;
3503
4847
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
3504
4848
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
3505
4849
  exports.compareBranchSchemas = compareBranchSchemas;
3506
4850
  exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
3507
4851
  exports.compareMigrationRequest = compareMigrationRequest;
3508
4852
  exports.contains = contains;
4853
+ exports.copyBranch = copyBranch;
3509
4854
  exports.createBranch = createBranch;
4855
+ exports.createCluster = createCluster;
3510
4856
  exports.createDatabase = createDatabase;
3511
4857
  exports.createMigrationRequest = createMigrationRequest;
3512
4858
  exports.createTable = createTable;
3513
4859
  exports.createUserAPIKey = createUserAPIKey;
3514
4860
  exports.createWorkspace = createWorkspace;
3515
- exports.dEPRECATEDcreateDatabase = dEPRECATEDcreateDatabase;
3516
- exports.dEPRECATEDdeleteDatabase = dEPRECATEDdeleteDatabase;
3517
- exports.dEPRECATEDgetDatabaseList = dEPRECATEDgetDatabaseList;
3518
- exports.dEPRECATEDgetDatabaseMetadata = dEPRECATEDgetDatabaseMetadata;
3519
- exports.dEPRECATEDupdateDatabaseMetadata = dEPRECATEDupdateDatabaseMetadata;
3520
4861
  exports.deleteBranch = deleteBranch;
3521
4862
  exports.deleteColumn = deleteColumn;
3522
4863
  exports.deleteDatabase = deleteDatabase;
4864
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
4865
+ exports.deleteFile = deleteFile;
4866
+ exports.deleteFileItem = deleteFileItem;
4867
+ exports.deleteOAuthAccessToken = deleteOAuthAccessToken;
3523
4868
  exports.deleteRecord = deleteRecord;
3524
4869
  exports.deleteTable = deleteTable;
3525
4870
  exports.deleteUser = deleteUser;
3526
4871
  exports.deleteUserAPIKey = deleteUserAPIKey;
4872
+ exports.deleteUserOAuthClient = deleteUserOAuthClient;
3527
4873
  exports.deleteWorkspace = deleteWorkspace;
3528
4874
  exports.deserialize = deserialize;
3529
4875
  exports.endsWith = endsWith;
3530
4876
  exports.equals = equals;
3531
4877
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
3532
4878
  exports.exists = exists;
4879
+ exports.fileAccess = fileAccess;
4880
+ exports.fileUpload = fileUpload;
3533
4881
  exports.ge = ge;
3534
4882
  exports.getAPIKey = getAPIKey;
4883
+ exports.getAuthorizationCode = getAuthorizationCode;
4884
+ exports.getBranch = getBranch;
3535
4885
  exports.getBranchDetails = getBranchDetails;
3536
4886
  exports.getBranchList = getBranchList;
3537
4887
  exports.getBranchMetadata = getBranchMetadata;
@@ -3539,29 +4889,38 @@ exports.getBranchMigrationHistory = getBranchMigrationHistory;
3539
4889
  exports.getBranchMigrationPlan = getBranchMigrationPlan;
3540
4890
  exports.getBranchSchemaHistory = getBranchSchemaHistory;
3541
4891
  exports.getBranchStats = getBranchStats;
4892
+ exports.getCluster = getCluster;
3542
4893
  exports.getColumn = getColumn;
3543
- exports.getCurrentBranchDetails = getCurrentBranchDetails;
3544
- exports.getCurrentBranchName = getCurrentBranchName;
4894
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
3545
4895
  exports.getDatabaseList = getDatabaseList;
3546
4896
  exports.getDatabaseMetadata = getDatabaseMetadata;
3547
4897
  exports.getDatabaseURL = getDatabaseURL;
4898
+ exports.getFile = getFile;
4899
+ exports.getFileItem = getFileItem;
3548
4900
  exports.getGitBranchesMapping = getGitBranchesMapping;
3549
4901
  exports.getHostUrl = getHostUrl;
3550
4902
  exports.getMigrationRequest = getMigrationRequest;
3551
4903
  exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
4904
+ exports.getPreviewBranch = getPreviewBranch;
3552
4905
  exports.getRecord = getRecord;
4906
+ exports.getSchema = getSchema;
3553
4907
  exports.getTableColumns = getTableColumns;
3554
4908
  exports.getTableSchema = getTableSchema;
3555
4909
  exports.getUser = getUser;
3556
4910
  exports.getUserAPIKeys = getUserAPIKeys;
4911
+ exports.getUserOAuthAccessTokens = getUserOAuthAccessTokens;
4912
+ exports.getUserOAuthClients = getUserOAuthClients;
3557
4913
  exports.getWorkspace = getWorkspace;
3558
4914
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
3559
4915
  exports.getWorkspacesList = getWorkspacesList;
4916
+ exports.grantAuthorizationCode = grantAuthorizationCode;
3560
4917
  exports.greaterEquals = greaterEquals;
3561
4918
  exports.greaterThan = greaterThan;
3562
4919
  exports.greaterThanEquals = greaterThanEquals;
3563
4920
  exports.gt = gt;
3564
4921
  exports.gte = gte;
4922
+ exports.iContains = iContains;
4923
+ exports.iPattern = iPattern;
3565
4924
  exports.includes = includes;
3566
4925
  exports.includesAll = includesAll;
3567
4926
  exports.includesAny = includesAny;
@@ -3575,11 +4934,14 @@ exports.isHostProviderAlias = isHostProviderAlias;
3575
4934
  exports.isHostProviderBuilder = isHostProviderBuilder;
3576
4935
  exports.isIdentifiable = isIdentifiable;
3577
4936
  exports.isNot = isNot;
4937
+ exports.isValidExpandedColumn = isValidExpandedColumn;
4938
+ exports.isValidSelectableColumns = isValidSelectableColumns;
3578
4939
  exports.isXataRecord = isXataRecord;
3579
4940
  exports.le = le;
3580
4941
  exports.lessEquals = lessEquals;
3581
4942
  exports.lessThan = lessThan;
3582
4943
  exports.lessThanEquals = lessThanEquals;
4944
+ exports.listClusters = listClusters;
3583
4945
  exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
3584
4946
  exports.listRegions = listRegions;
3585
4947
  exports.lt = lt;
@@ -3590,24 +4952,36 @@ exports.operationsByTag = operationsByTag;
3590
4952
  exports.parseProviderString = parseProviderString;
3591
4953
  exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
3592
4954
  exports.pattern = pattern;
4955
+ exports.pgRollJobStatus = pgRollJobStatus;
4956
+ exports.pgRollMigrationHistory = pgRollMigrationHistory;
4957
+ exports.pgRollStatus = pgRollStatus;
3593
4958
  exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
4959
+ exports.pushBranchMigrations = pushBranchMigrations;
4960
+ exports.putFile = putFile;
4961
+ exports.putFileItem = putFileItem;
3594
4962
  exports.queryMigrationRequests = queryMigrationRequests;
3595
4963
  exports.queryTable = queryTable;
3596
4964
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
3597
4965
  exports.removeWorkspaceMember = removeWorkspaceMember;
4966
+ exports.renameDatabase = renameDatabase;
3598
4967
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
3599
4968
  exports.resolveBranch = resolveBranch;
3600
4969
  exports.searchBranch = searchBranch;
3601
4970
  exports.searchTable = searchTable;
3602
4971
  exports.serialize = serialize;
3603
4972
  exports.setTableSchema = setTableSchema;
4973
+ exports.sqlQuery = sqlQuery;
3604
4974
  exports.startsWith = startsWith;
3605
4975
  exports.summarizeTable = summarizeTable;
4976
+ exports.transformImage = transformImage;
3606
4977
  exports.updateBranchMetadata = updateBranchMetadata;
3607
4978
  exports.updateBranchSchema = updateBranchSchema;
4979
+ exports.updateCluster = updateCluster;
3608
4980
  exports.updateColumn = updateColumn;
4981
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
3609
4982
  exports.updateDatabaseMetadata = updateDatabaseMetadata;
3610
4983
  exports.updateMigrationRequest = updateMigrationRequest;
4984
+ exports.updateOAuthAccessToken = updateOAuthAccessToken;
3611
4985
  exports.updateRecordWithID = updateRecordWithID;
3612
4986
  exports.updateTable = updateTable;
3613
4987
  exports.updateUser = updateUser;
@@ -3615,4 +4989,5 @@ exports.updateWorkspace = updateWorkspace;
3615
4989
  exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
3616
4990
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
3617
4991
  exports.upsertRecordWithID = upsertRecordWithID;
4992
+ exports.vectorSearchTable = vectorSearchTable;
3618
4993
  //# sourceMappingURL=index.cjs.map