@xata.io/client 0.0.0-alpha.vf85aa00 → 0.0.0-alpha.vf864fe862f895317faad5b0041a40e871fe5ad03

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
@@ -20,7 +20,8 @@ const TraceAttributes = {
20
20
  HTTP_METHOD: "http.method",
21
21
  HTTP_URL: "http.url",
22
22
  HTTP_ROUTE: "http.route",
23
- HTTP_TARGET: "http.target"
23
+ HTTP_TARGET: "http.target",
24
+ CLOUDFLARE_RAY_ID: "cf.ray"
24
25
  };
25
26
 
26
27
  function notEmpty(value) {
@@ -29,8 +30,18 @@ function notEmpty(value) {
29
30
  function compact(arr) {
30
31
  return arr.filter(notEmpty);
31
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
+ }
32
43
  function isObject(value) {
33
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
44
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
34
45
  }
35
46
  function isDefined(value) {
36
47
  return value !== null && value !== void 0;
@@ -85,6 +96,27 @@ function chunk(array, chunkSize) {
85
96
  async function timeout(ms) {
86
97
  return new Promise((resolve) => setTimeout(resolve, ms));
87
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
+ }
88
120
 
89
121
  function getEnvironment() {
90
122
  try {
@@ -184,7 +216,7 @@ function getAPIKey() {
184
216
  function getBranch() {
185
217
  try {
186
218
  const { branch } = getEnvironment();
187
- return branch ?? "main";
219
+ return branch;
188
220
  } catch (err) {
189
221
  return void 0;
190
222
  }
@@ -216,7 +248,7 @@ var __accessCheck$8 = (obj, member, msg) => {
216
248
  if (!member.has(obj))
217
249
  throw TypeError("Cannot " + msg);
218
250
  };
219
- var __privateGet$8 = (obj, member, getter) => {
251
+ var __privateGet$7 = (obj, member, getter) => {
220
252
  __accessCheck$8(obj, member, "read from private field");
221
253
  return getter ? getter.call(obj) : member.get(obj);
222
254
  };
@@ -225,7 +257,7 @@ var __privateAdd$8 = (obj, member, value) => {
225
257
  throw TypeError("Cannot add the same private member more than once");
226
258
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
227
259
  };
228
- var __privateSet$8 = (obj, member, value, setter) => {
260
+ var __privateSet$6 = (obj, member, value, setter) => {
229
261
  __accessCheck$8(obj, member, "write to private field");
230
262
  setter ? setter.call(obj, value) : member.set(obj, value);
231
263
  return value;
@@ -235,13 +267,13 @@ var __privateMethod$4 = (obj, member, method) => {
235
267
  return method;
236
268
  };
237
269
  var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
270
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
238
271
  function getFetchImplementation(userFetch) {
239
272
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
240
- const fetchImpl = userFetch ?? globalFetch;
273
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
274
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
241
275
  if (!fetchImpl) {
242
- throw new Error(
243
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
244
- );
276
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
245
277
  }
246
278
  return fetchImpl;
247
279
  }
@@ -251,33 +283,37 @@ class ApiRequestPool {
251
283
  __privateAdd$8(this, _fetch, void 0);
252
284
  __privateAdd$8(this, _queue, void 0);
253
285
  __privateAdd$8(this, _concurrency, void 0);
254
- __privateSet$8(this, _queue, []);
255
- __privateSet$8(this, _concurrency, concurrency);
286
+ __privateSet$6(this, _queue, []);
287
+ __privateSet$6(this, _concurrency, concurrency);
256
288
  this.running = 0;
257
289
  this.started = 0;
258
290
  }
259
291
  setFetch(fetch2) {
260
- __privateSet$8(this, _fetch, fetch2);
292
+ __privateSet$6(this, _fetch, fetch2);
261
293
  }
262
294
  getFetch() {
263
- if (!__privateGet$8(this, _fetch)) {
295
+ if (!__privateGet$7(this, _fetch)) {
264
296
  throw new Error("Fetch not set");
265
297
  }
266
- return __privateGet$8(this, _fetch);
298
+ return __privateGet$7(this, _fetch);
267
299
  }
268
300
  request(url, options) {
269
- const start = new Date();
270
- const fetch2 = this.getFetch();
301
+ const start = /* @__PURE__ */ new Date();
302
+ const fetchImpl = this.getFetch();
271
303
  const runRequest = async (stalled = false) => {
272
- 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
+ }
273
309
  if (response.status === 429) {
274
310
  const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
275
311
  await timeout(rateLimitReset * 1e3);
276
312
  return await runRequest(true);
277
313
  }
278
314
  if (stalled) {
279
- const stalledTime = new Date().getTime() - start.getTime();
280
- console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
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`);
281
317
  }
282
318
  return response;
283
319
  };
@@ -291,19 +327,19 @@ _queue = new WeakMap();
291
327
  _concurrency = new WeakMap();
292
328
  _enqueue = new WeakSet();
293
329
  enqueue_fn = function(task) {
294
- const promise = new Promise((resolve) => __privateGet$8(this, _queue).push(resolve)).finally(() => {
330
+ const promise = new Promise((resolve) => __privateGet$7(this, _queue).push(resolve)).finally(() => {
295
331
  this.started--;
296
332
  this.running++;
297
333
  }).then(() => task()).finally(() => {
298
334
  this.running--;
299
- const next = __privateGet$8(this, _queue).shift();
335
+ const next = __privateGet$7(this, _queue).shift();
300
336
  if (next !== void 0) {
301
337
  this.started++;
302
338
  next();
303
339
  }
304
340
  });
305
- if (this.running + this.started < __privateGet$8(this, _concurrency)) {
306
- const next = __privateGet$8(this, _queue).shift();
341
+ if (this.running + this.started < __privateGet$7(this, _concurrency)) {
342
+ const next = __privateGet$7(this, _queue).shift();
307
343
  if (next !== void 0) {
308
344
  this.started++;
309
345
  next();
@@ -492,7 +528,7 @@ function defaultOnOpen(response) {
492
528
  }
493
529
  }
494
530
 
495
- const VERSION = "0.23.4";
531
+ const VERSION = "0.29.0";
496
532
 
497
533
  class ErrorWithCause extends Error {
498
534
  constructor(message, options) {
@@ -535,6 +571,67 @@ function getMessage(data) {
535
571
  }
536
572
  }
537
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
+
538
635
  const pool = new ApiRequestPool();
539
636
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
540
637
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
@@ -550,6 +647,7 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
550
647
  return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
551
648
  };
552
649
  function buildBaseUrl({
650
+ method,
553
651
  endpoint,
554
652
  path,
555
653
  workspacesApiUrl,
@@ -557,7 +655,24 @@ function buildBaseUrl({
557
655
  pathParams = {}
558
656
  }) {
559
657
  if (endpoint === "dataPlane") {
560
- 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
+ }
561
676
  const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
562
677
  return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
563
678
  }
@@ -568,6 +683,18 @@ function hostHeader(url) {
568
683
  const { groups } = pattern.exec(url) ?? {};
569
684
  return groups?.host ? { Host: groups.host } : {};
570
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
+ }
571
698
  const defaultClientID = generateUUID();
572
699
  async function fetch$1({
573
700
  url: path,
@@ -587,15 +714,16 @@ async function fetch$1({
587
714
  sessionID,
588
715
  clientName,
589
716
  xataAgentExtra,
590
- fetchOptions = {}
717
+ fetchOptions = {},
718
+ rawResponse = false
591
719
  }) {
592
720
  pool.setFetch(fetch2);
593
721
  return await trace(
594
722
  `${method.toUpperCase()} ${path}`,
595
723
  async ({ setAttributes }) => {
596
- const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
724
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
597
725
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
598
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
726
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\.[^.]+\./, "http://") : fullUrl;
599
727
  setAttributes({
600
728
  [TraceAttributes.HTTP_URL]: url,
601
729
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
@@ -606,7 +734,7 @@ async function fetch$1({
606
734
  isDefined(clientName) ? ["service", clientName] : void 0,
607
735
  ...Object.entries(xataAgentExtra ?? {})
608
736
  ]).map(([key, value]) => `${key}=${value}`).join("; ");
609
- const headers = {
737
+ const headers = compactObject({
610
738
  "Accept-Encoding": "identity",
611
739
  "Content-Type": "application/json",
612
740
  "X-Xata-Client-ID": clientID ?? defaultClientID,
@@ -615,11 +743,11 @@ async function fetch$1({
615
743
  ...customHeaders,
616
744
  ...hostHeader(fullUrl),
617
745
  Authorization: `Bearer ${apiKey}`
618
- };
746
+ });
619
747
  const response = await pool.request(url, {
620
748
  ...fetchOptions,
621
749
  method: method.toUpperCase(),
622
- body: body ? JSON.stringify(body) : void 0,
750
+ body: await parseBody(body, headers),
623
751
  headers,
624
752
  signal
625
753
  });
@@ -630,8 +758,12 @@ async function fetch$1({
630
758
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
631
759
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
632
760
  [TraceAttributes.HTTP_HOST]: host,
633
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
761
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
762
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
634
763
  });
764
+ const message = response.headers?.get("x-xata-message");
765
+ if (message)
766
+ console.warn(message);
635
767
  if (response.status === 204) {
636
768
  return {};
637
769
  }
@@ -639,7 +771,7 @@ async function fetch$1({
639
771
  throw new FetcherError(response.status, "Rate limit exceeded", requestId);
640
772
  }
641
773
  try {
642
- const jsonResponse = await response.json();
774
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
643
775
  if (response.ok) {
644
776
  return jsonResponse;
645
777
  }
@@ -672,7 +804,7 @@ function fetchSSERequest({
672
804
  clientName,
673
805
  xataAgentExtra
674
806
  }) {
675
- const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
807
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
676
808
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
677
809
  const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
678
810
  void fetchEventSource(url, {
@@ -715,6 +847,20 @@ function parseUrl(url) {
715
847
 
716
848
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
717
849
 
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 });
718
864
  const getBranchList = (variables, signal) => dataPlaneFetch({
719
865
  url: "/dbs/{dbName}",
720
866
  method: "get",
@@ -734,6 +880,12 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
734
880
  ...variables,
735
881
  signal
736
882
  });
883
+ const getSchema = (variables, signal) => dataPlaneFetch({
884
+ url: "/db/{dbBranchName}/schema",
885
+ method: "get",
886
+ ...variables,
887
+ signal
888
+ });
737
889
  const copyBranch = (variables, signal) => dataPlaneFetch({
738
890
  url: "/db/{dbBranchName}/copy",
739
891
  method: "post",
@@ -834,6 +986,42 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
834
986
  });
835
987
  const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
836
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
+ });
837
1025
  const getRecord = (variables, signal) => dataPlaneFetch({
838
1026
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
839
1027
  method: "get",
@@ -863,12 +1051,6 @@ const searchTable = (variables, signal) => dataPlaneFetch({
863
1051
  ...variables,
864
1052
  signal
865
1053
  });
866
- const sqlQuery = (variables, signal) => dataPlaneFetch({
867
- url: "/db/{dbBranchName}/sql",
868
- method: "post",
869
- ...variables,
870
- signal
871
- });
872
1054
  const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
873
1055
  const askTable = (variables, signal) => dataPlaneFetch({
874
1056
  url: "/db/{dbBranchName}/tables/{tableName}/ask",
@@ -876,10 +1058,33 @@ const askTable = (variables, signal) => dataPlaneFetch({
876
1058
  ...variables,
877
1059
  signal
878
1060
  });
1061
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
879
1062
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
880
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
+ });
881
1082
  const operationsByTag$2 = {
882
1083
  branch: {
1084
+ applyMigration,
1085
+ pgRollStatus,
1086
+ pgRollJobStatus,
1087
+ pgRollMigrationHistory,
883
1088
  getBranchList,
884
1089
  getBranchDetails,
885
1090
  createBranch,
@@ -894,6 +1099,7 @@ const operationsByTag$2 = {
894
1099
  resolveBranch
895
1100
  },
896
1101
  migrations: {
1102
+ getSchema,
897
1103
  getBranchMigrationHistory,
898
1104
  getBranchMigrationPlan,
899
1105
  executeBranchMigrationPlan,
@@ -937,20 +1143,24 @@ const operationsByTag$2 = {
937
1143
  deleteRecord,
938
1144
  bulkInsertTableRecords
939
1145
  },
1146
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess, fileUpload },
940
1147
  searchAndFilter: {
941
1148
  queryTable,
942
1149
  searchBranch,
943
1150
  searchTable,
944
- sqlQuery,
945
1151
  vectorSearchTable,
946
1152
  askTable,
1153
+ askTableSession,
947
1154
  summarizeTable,
948
1155
  aggregateTable
949
- }
1156
+ },
1157
+ sql: { sqlQuery }
950
1158
  };
951
1159
 
952
1160
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
953
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 });
954
1164
  const getUser = (variables, signal) => controlPlaneFetch({
955
1165
  url: "/user",
956
1166
  method: "get",
@@ -987,6 +1197,31 @@ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
987
1197
  ...variables,
988
1198
  signal
989
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 });
990
1225
  const getWorkspacesList = (variables, signal) => controlPlaneFetch({
991
1226
  url: "/workspaces",
992
1227
  method: "get",
@@ -1030,6 +1265,15 @@ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ u
1030
1265
  const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
1031
1266
  const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
1032
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 });
1033
1277
  const getDatabaseList = (variables, signal) => controlPlaneFetch({
1034
1278
  url: "/workspaces/{workspaceId}/dbs",
1035
1279
  method: "get",
@@ -1045,6 +1289,7 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
1045
1289
  });
1046
1290
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
1047
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 });
1048
1293
  const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1049
1294
  const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1050
1295
  const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
@@ -1055,6 +1300,15 @@ const listRegions = (variables, signal) => controlPlaneFetch({
1055
1300
  signal
1056
1301
  });
1057
1302
  const operationsByTag$1 = {
1303
+ oAuth: {
1304
+ getAuthorizationCode,
1305
+ grantAuthorizationCode,
1306
+ getUserOAuthClients,
1307
+ deleteUserOAuthClient,
1308
+ getUserOAuthAccessTokens,
1309
+ deleteOAuthAccessToken,
1310
+ updateOAuthAccessToken
1311
+ },
1058
1312
  users: { getUser, updateUser, deleteUser },
1059
1313
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
1060
1314
  workspaces: {
@@ -1074,12 +1328,14 @@ const operationsByTag$1 = {
1074
1328
  acceptWorkspaceMemberInvite,
1075
1329
  resendWorkspaceMemberInvite
1076
1330
  },
1331
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
1077
1332
  databases: {
1078
1333
  getDatabaseList,
1079
1334
  createDatabase,
1080
1335
  deleteDatabase,
1081
1336
  getDatabaseMetadata,
1082
1337
  updateDatabaseMetadata,
1338
+ renameDatabase,
1083
1339
  getDatabaseGithubSettings,
1084
1340
  updateDatabaseGithubSettings,
1085
1341
  deleteDatabaseGithubSettings,
@@ -1089,66 +1345,11 @@ const operationsByTag$1 = {
1089
1345
 
1090
1346
  const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);
1091
1347
 
1092
- function getHostUrl(provider, type) {
1093
- if (isHostProviderAlias(provider)) {
1094
- return providers[provider][type];
1095
- } else if (isHostProviderBuilder(provider)) {
1096
- return provider[type];
1097
- }
1098
- throw new Error("Invalid API provider");
1099
- }
1100
- const providers = {
1101
- production: {
1102
- main: "https://api.xata.io",
1103
- workspaces: "https://{workspaceId}.{region}.xata.sh"
1104
- },
1105
- staging: {
1106
- main: "https://api.staging-xata.dev",
1107
- workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1108
- },
1109
- dev: {
1110
- main: "https://api.dev-xata.dev",
1111
- workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
1112
- }
1113
- };
1114
- function isHostProviderAlias(alias) {
1115
- return isString(alias) && Object.keys(providers).includes(alias);
1116
- }
1117
- function isHostProviderBuilder(builder) {
1118
- return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
1119
- }
1120
- function parseProviderString(provider = "production") {
1121
- if (isHostProviderAlias(provider)) {
1122
- return provider;
1123
- }
1124
- const [main, workspaces] = provider.split(",");
1125
- if (!main || !workspaces)
1126
- return null;
1127
- return { main, workspaces };
1128
- }
1129
- function buildProviderString(provider) {
1130
- if (isHostProviderAlias(provider))
1131
- return provider;
1132
- return `${provider.main},${provider.workspaces}`;
1133
- }
1134
- function parseWorkspacesUrlParts(url) {
1135
- if (!isString(url))
1136
- return null;
1137
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
1138
- const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1139
- const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1140
- const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1141
- const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
1142
- if (!match)
1143
- return null;
1144
- return { workspace: match[1], region: match[2] };
1145
- }
1146
-
1147
1348
  var __accessCheck$7 = (obj, member, msg) => {
1148
1349
  if (!member.has(obj))
1149
1350
  throw TypeError("Cannot " + msg);
1150
1351
  };
1151
- var __privateGet$7 = (obj, member, getter) => {
1352
+ var __privateGet$6 = (obj, member, getter) => {
1152
1353
  __accessCheck$7(obj, member, "read from private field");
1153
1354
  return getter ? getter.call(obj) : member.get(obj);
1154
1355
  };
@@ -1157,7 +1358,7 @@ var __privateAdd$7 = (obj, member, value) => {
1157
1358
  throw TypeError("Cannot add the same private member more than once");
1158
1359
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1159
1360
  };
1160
- var __privateSet$7 = (obj, member, value, setter) => {
1361
+ var __privateSet$5 = (obj, member, value, setter) => {
1161
1362
  __accessCheck$7(obj, member, "write to private field");
1162
1363
  setter ? setter.call(obj, value) : member.set(obj, value);
1163
1364
  return value;
@@ -1174,7 +1375,7 @@ class XataApiClient {
1174
1375
  if (!apiKey) {
1175
1376
  throw new Error("Could not resolve a valid apiKey");
1176
1377
  }
1177
- __privateSet$7(this, _extraProps, {
1378
+ __privateSet$5(this, _extraProps, {
1178
1379
  apiUrl: getHostUrl(provider, "main"),
1179
1380
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
1180
1381
  fetch: getFetchImplementation(options.fetch),
@@ -1186,59 +1387,64 @@ class XataApiClient {
1186
1387
  });
1187
1388
  }
1188
1389
  get user() {
1189
- if (!__privateGet$7(this, _namespaces).user)
1190
- __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
1191
- return __privateGet$7(this, _namespaces).user;
1390
+ if (!__privateGet$6(this, _namespaces).user)
1391
+ __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
1392
+ return __privateGet$6(this, _namespaces).user;
1192
1393
  }
1193
1394
  get authentication() {
1194
- if (!__privateGet$7(this, _namespaces).authentication)
1195
- __privateGet$7(this, _namespaces).authentication = new AuthenticationApi(__privateGet$7(this, _extraProps));
1196
- return __privateGet$7(this, _namespaces).authentication;
1395
+ if (!__privateGet$6(this, _namespaces).authentication)
1396
+ __privateGet$6(this, _namespaces).authentication = new AuthenticationApi(__privateGet$6(this, _extraProps));
1397
+ return __privateGet$6(this, _namespaces).authentication;
1197
1398
  }
1198
1399
  get workspaces() {
1199
- if (!__privateGet$7(this, _namespaces).workspaces)
1200
- __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
1201
- return __privateGet$7(this, _namespaces).workspaces;
1400
+ if (!__privateGet$6(this, _namespaces).workspaces)
1401
+ __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
1402
+ return __privateGet$6(this, _namespaces).workspaces;
1202
1403
  }
1203
1404
  get invites() {
1204
- if (!__privateGet$7(this, _namespaces).invites)
1205
- __privateGet$7(this, _namespaces).invites = new InvitesApi(__privateGet$7(this, _extraProps));
1206
- return __privateGet$7(this, _namespaces).invites;
1405
+ if (!__privateGet$6(this, _namespaces).invites)
1406
+ __privateGet$6(this, _namespaces).invites = new InvitesApi(__privateGet$6(this, _extraProps));
1407
+ return __privateGet$6(this, _namespaces).invites;
1207
1408
  }
1208
1409
  get database() {
1209
- if (!__privateGet$7(this, _namespaces).database)
1210
- __privateGet$7(this, _namespaces).database = new DatabaseApi(__privateGet$7(this, _extraProps));
1211
- return __privateGet$7(this, _namespaces).database;
1410
+ if (!__privateGet$6(this, _namespaces).database)
1411
+ __privateGet$6(this, _namespaces).database = new DatabaseApi(__privateGet$6(this, _extraProps));
1412
+ return __privateGet$6(this, _namespaces).database;
1212
1413
  }
1213
1414
  get branches() {
1214
- if (!__privateGet$7(this, _namespaces).branches)
1215
- __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
1216
- return __privateGet$7(this, _namespaces).branches;
1415
+ if (!__privateGet$6(this, _namespaces).branches)
1416
+ __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
1417
+ return __privateGet$6(this, _namespaces).branches;
1217
1418
  }
1218
1419
  get migrations() {
1219
- if (!__privateGet$7(this, _namespaces).migrations)
1220
- __privateGet$7(this, _namespaces).migrations = new MigrationsApi(__privateGet$7(this, _extraProps));
1221
- return __privateGet$7(this, _namespaces).migrations;
1420
+ if (!__privateGet$6(this, _namespaces).migrations)
1421
+ __privateGet$6(this, _namespaces).migrations = new MigrationsApi(__privateGet$6(this, _extraProps));
1422
+ return __privateGet$6(this, _namespaces).migrations;
1222
1423
  }
1223
1424
  get migrationRequests() {
1224
- if (!__privateGet$7(this, _namespaces).migrationRequests)
1225
- __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
1226
- return __privateGet$7(this, _namespaces).migrationRequests;
1425
+ if (!__privateGet$6(this, _namespaces).migrationRequests)
1426
+ __privateGet$6(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$6(this, _extraProps));
1427
+ return __privateGet$6(this, _namespaces).migrationRequests;
1227
1428
  }
1228
1429
  get tables() {
1229
- if (!__privateGet$7(this, _namespaces).tables)
1230
- __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
1231
- return __privateGet$7(this, _namespaces).tables;
1430
+ if (!__privateGet$6(this, _namespaces).tables)
1431
+ __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
1432
+ return __privateGet$6(this, _namespaces).tables;
1232
1433
  }
1233
1434
  get records() {
1234
- if (!__privateGet$7(this, _namespaces).records)
1235
- __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
1236
- return __privateGet$7(this, _namespaces).records;
1435
+ if (!__privateGet$6(this, _namespaces).records)
1436
+ __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
1437
+ return __privateGet$6(this, _namespaces).records;
1438
+ }
1439
+ get files() {
1440
+ if (!__privateGet$6(this, _namespaces).files)
1441
+ __privateGet$6(this, _namespaces).files = new FilesApi(__privateGet$6(this, _extraProps));
1442
+ return __privateGet$6(this, _namespaces).files;
1237
1443
  }
1238
1444
  get searchAndFilter() {
1239
- if (!__privateGet$7(this, _namespaces).searchAndFilter)
1240
- __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
1241
- return __privateGet$7(this, _namespaces).searchAndFilter;
1445
+ if (!__privateGet$6(this, _namespaces).searchAndFilter)
1446
+ __privateGet$6(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$6(this, _extraProps));
1447
+ return __privateGet$6(this, _namespaces).searchAndFilter;
1242
1448
  }
1243
1449
  }
1244
1450
  _extraProps = new WeakMap();
@@ -1540,6 +1746,30 @@ class BranchApi {
1540
1746
  ...this.extraProps
1541
1747
  });
1542
1748
  }
1749
+ pgRollMigrationHistory({
1750
+ workspace,
1751
+ region,
1752
+ database,
1753
+ branch
1754
+ }) {
1755
+ return operationsByTag.branch.pgRollMigrationHistory({
1756
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1757
+ ...this.extraProps
1758
+ });
1759
+ }
1760
+ applyMigration({
1761
+ workspace,
1762
+ region,
1763
+ database,
1764
+ branch,
1765
+ migration
1766
+ }) {
1767
+ return operationsByTag.branch.applyMigration({
1768
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1769
+ body: migration,
1770
+ ...this.extraProps
1771
+ });
1772
+ }
1543
1773
  }
1544
1774
  class TableApi {
1545
1775
  constructor(extraProps) {
@@ -1805,9 +2035,167 @@ class RecordsApi {
1805
2035
  branch,
1806
2036
  operations
1807
2037
  }) {
1808
- return operationsByTag.records.branchTransaction({
1809
- pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1810
- body: { operations },
2038
+ return operationsByTag.records.branchTransaction({
2039
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2040
+ body: { operations },
2041
+ ...this.extraProps
2042
+ });
2043
+ }
2044
+ }
2045
+ class FilesApi {
2046
+ constructor(extraProps) {
2047
+ this.extraProps = extraProps;
2048
+ }
2049
+ getFileItem({
2050
+ workspace,
2051
+ region,
2052
+ database,
2053
+ branch,
2054
+ table,
2055
+ record,
2056
+ column,
2057
+ fileId
2058
+ }) {
2059
+ return operationsByTag.files.getFileItem({
2060
+ pathParams: {
2061
+ workspace,
2062
+ region,
2063
+ dbBranchName: `${database}:${branch}`,
2064
+ tableName: table,
2065
+ recordId: record,
2066
+ columnName: column,
2067
+ fileId
2068
+ },
2069
+ ...this.extraProps
2070
+ });
2071
+ }
2072
+ putFileItem({
2073
+ workspace,
2074
+ region,
2075
+ database,
2076
+ branch,
2077
+ table,
2078
+ record,
2079
+ column,
2080
+ fileId,
2081
+ file
2082
+ }) {
2083
+ return operationsByTag.files.putFileItem({
2084
+ pathParams: {
2085
+ workspace,
2086
+ region,
2087
+ dbBranchName: `${database}:${branch}`,
2088
+ tableName: table,
2089
+ recordId: record,
2090
+ columnName: column,
2091
+ fileId
2092
+ },
2093
+ // @ts-ignore
2094
+ body: file,
2095
+ ...this.extraProps
2096
+ });
2097
+ }
2098
+ deleteFileItem({
2099
+ workspace,
2100
+ region,
2101
+ database,
2102
+ branch,
2103
+ table,
2104
+ record,
2105
+ column,
2106
+ fileId
2107
+ }) {
2108
+ return operationsByTag.files.deleteFileItem({
2109
+ pathParams: {
2110
+ workspace,
2111
+ region,
2112
+ dbBranchName: `${database}:${branch}`,
2113
+ tableName: table,
2114
+ recordId: record,
2115
+ columnName: column,
2116
+ fileId
2117
+ },
2118
+ ...this.extraProps
2119
+ });
2120
+ }
2121
+ getFile({
2122
+ workspace,
2123
+ region,
2124
+ database,
2125
+ branch,
2126
+ table,
2127
+ record,
2128
+ column
2129
+ }) {
2130
+ return operationsByTag.files.getFile({
2131
+ pathParams: {
2132
+ workspace,
2133
+ region,
2134
+ dbBranchName: `${database}:${branch}`,
2135
+ tableName: table,
2136
+ recordId: record,
2137
+ columnName: column
2138
+ },
2139
+ ...this.extraProps
2140
+ });
2141
+ }
2142
+ putFile({
2143
+ workspace,
2144
+ region,
2145
+ database,
2146
+ branch,
2147
+ table,
2148
+ record,
2149
+ column,
2150
+ file
2151
+ }) {
2152
+ return operationsByTag.files.putFile({
2153
+ pathParams: {
2154
+ workspace,
2155
+ region,
2156
+ dbBranchName: `${database}:${branch}`,
2157
+ tableName: table,
2158
+ recordId: record,
2159
+ columnName: column
2160
+ },
2161
+ body: file,
2162
+ ...this.extraProps
2163
+ });
2164
+ }
2165
+ deleteFile({
2166
+ workspace,
2167
+ region,
2168
+ database,
2169
+ branch,
2170
+ table,
2171
+ record,
2172
+ column
2173
+ }) {
2174
+ return operationsByTag.files.deleteFile({
2175
+ pathParams: {
2176
+ workspace,
2177
+ region,
2178
+ dbBranchName: `${database}:${branch}`,
2179
+ tableName: table,
2180
+ recordId: record,
2181
+ columnName: column
2182
+ },
2183
+ ...this.extraProps
2184
+ });
2185
+ }
2186
+ fileAccess({
2187
+ workspace,
2188
+ region,
2189
+ fileId,
2190
+ verify
2191
+ }) {
2192
+ return operationsByTag.files.fileAccess({
2193
+ pathParams: {
2194
+ workspace,
2195
+ region,
2196
+ fileId
2197
+ },
2198
+ queryParams: { verify },
1811
2199
  ...this.extraProps
1812
2200
  });
1813
2201
  }
@@ -1903,6 +2291,21 @@ class SearchAndFilterApi {
1903
2291
  ...this.extraProps
1904
2292
  });
1905
2293
  }
2294
+ askTableSession({
2295
+ workspace,
2296
+ region,
2297
+ database,
2298
+ branch,
2299
+ table,
2300
+ sessionId,
2301
+ message
2302
+ }) {
2303
+ return operationsByTag.searchAndFilter.askTableSession({
2304
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2305
+ body: { message },
2306
+ ...this.extraProps
2307
+ });
2308
+ }
1906
2309
  summarizeTable({
1907
2310
  workspace,
1908
2311
  region,
@@ -2180,6 +2583,17 @@ class MigrationsApi {
2180
2583
  ...this.extraProps
2181
2584
  });
2182
2585
  }
2586
+ getSchema({
2587
+ workspace,
2588
+ region,
2589
+ database,
2590
+ branch
2591
+ }) {
2592
+ return operationsByTag.migrations.getSchema({
2593
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2594
+ ...this.extraProps
2595
+ });
2596
+ }
2183
2597
  }
2184
2598
  class DatabaseApi {
2185
2599
  constructor(extraProps) {
@@ -2194,11 +2608,13 @@ class DatabaseApi {
2194
2608
  createDatabase({
2195
2609
  workspace,
2196
2610
  database,
2197
- data
2611
+ data,
2612
+ headers
2198
2613
  }) {
2199
2614
  return operationsByTag.databases.createDatabase({
2200
2615
  pathParams: { workspaceId: workspace, dbName: database },
2201
2616
  body: data,
2617
+ headers,
2202
2618
  ...this.extraProps
2203
2619
  });
2204
2620
  }
@@ -2231,6 +2647,17 @@ class DatabaseApi {
2231
2647
  ...this.extraProps
2232
2648
  });
2233
2649
  }
2650
+ renameDatabase({
2651
+ workspace,
2652
+ database,
2653
+ newName
2654
+ }) {
2655
+ return operationsByTag.databases.renameDatabase({
2656
+ pathParams: { workspaceId: workspace, dbName: database },
2657
+ body: { newName },
2658
+ ...this.extraProps
2659
+ });
2660
+ }
2234
2661
  getDatabaseGithubSettings({
2235
2662
  workspace,
2236
2663
  database
@@ -2277,18 +2704,202 @@ class XataApiPlugin {
2277
2704
  class XataPlugin {
2278
2705
  }
2279
2706
 
2707
+ function buildTransformString(transformations) {
2708
+ return transformations.flatMap(
2709
+ (t) => Object.entries(t).map(([key, value]) => {
2710
+ if (key === "trim") {
2711
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2712
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2713
+ }
2714
+ if (key === "gravity" && typeof value === "object") {
2715
+ const { x = 0.5, y = 0.5 } = value;
2716
+ return `${key}=${[x, y].join("x")}`;
2717
+ }
2718
+ return `${key}=${value}`;
2719
+ })
2720
+ ).join(",");
2721
+ }
2722
+ function transformImage(url, ...transformations) {
2723
+ if (!isDefined(url))
2724
+ return void 0;
2725
+ const newTransformations = buildTransformString(transformations);
2726
+ const { hostname, pathname, search } = new URL(url);
2727
+ const pathParts = pathname.split("/");
2728
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2729
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2730
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2731
+ const path = pathParts.join("/");
2732
+ return `https://${hostname}${transform}${path}${search}`;
2733
+ }
2734
+
2735
+ class XataFile {
2736
+ constructor(file) {
2737
+ this.id = file.id;
2738
+ this.name = file.name;
2739
+ this.mediaType = file.mediaType;
2740
+ this.base64Content = file.base64Content;
2741
+ this.enablePublicUrl = file.enablePublicUrl;
2742
+ this.signedUrlTimeout = file.signedUrlTimeout;
2743
+ this.uploadUrlTimeout = file.uploadUrlTimeout;
2744
+ this.size = file.size;
2745
+ this.version = file.version;
2746
+ this.url = file.url;
2747
+ this.signedUrl = file.signedUrl;
2748
+ this.uploadUrl = file.uploadUrl;
2749
+ this.attributes = file.attributes;
2750
+ }
2751
+ static fromBuffer(buffer, options = {}) {
2752
+ const base64Content = buffer.toString("base64");
2753
+ return new XataFile({ ...options, base64Content });
2754
+ }
2755
+ toBuffer() {
2756
+ if (!this.base64Content) {
2757
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2758
+ }
2759
+ return Buffer.from(this.base64Content, "base64");
2760
+ }
2761
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2762
+ const uint8Array = new Uint8Array(arrayBuffer);
2763
+ return this.fromUint8Array(uint8Array, options);
2764
+ }
2765
+ toArrayBuffer() {
2766
+ if (!this.base64Content) {
2767
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2768
+ }
2769
+ const binary = atob(this.base64Content);
2770
+ return new ArrayBuffer(binary.length);
2771
+ }
2772
+ static fromUint8Array(uint8Array, options = {}) {
2773
+ let binary = "";
2774
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2775
+ binary += String.fromCharCode(uint8Array[i]);
2776
+ }
2777
+ const base64Content = btoa(binary);
2778
+ return new XataFile({ ...options, base64Content });
2779
+ }
2780
+ toUint8Array() {
2781
+ if (!this.base64Content) {
2782
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2783
+ }
2784
+ const binary = atob(this.base64Content);
2785
+ const uint8Array = new Uint8Array(binary.length);
2786
+ for (let i = 0; i < binary.length; i++) {
2787
+ uint8Array[i] = binary.charCodeAt(i);
2788
+ }
2789
+ return uint8Array;
2790
+ }
2791
+ static async fromBlob(file, options = {}) {
2792
+ const name = options.name ?? file.name;
2793
+ const mediaType = file.type;
2794
+ const arrayBuffer = await file.arrayBuffer();
2795
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2796
+ }
2797
+ toBlob() {
2798
+ if (!this.base64Content) {
2799
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2800
+ }
2801
+ const binary = atob(this.base64Content);
2802
+ const uint8Array = new Uint8Array(binary.length);
2803
+ for (let i = 0; i < binary.length; i++) {
2804
+ uint8Array[i] = binary.charCodeAt(i);
2805
+ }
2806
+ return new Blob([uint8Array], { type: this.mediaType });
2807
+ }
2808
+ static fromString(string, options = {}) {
2809
+ const base64Content = btoa(string);
2810
+ return new XataFile({ ...options, base64Content });
2811
+ }
2812
+ toString() {
2813
+ if (!this.base64Content) {
2814
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2815
+ }
2816
+ return atob(this.base64Content);
2817
+ }
2818
+ static fromBase64(base64Content, options = {}) {
2819
+ return new XataFile({ ...options, base64Content });
2820
+ }
2821
+ toBase64() {
2822
+ if (!this.base64Content) {
2823
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2824
+ }
2825
+ return this.base64Content;
2826
+ }
2827
+ transform(...options) {
2828
+ return {
2829
+ url: transformImage(this.url, ...options),
2830
+ signedUrl: transformImage(this.signedUrl, ...options),
2831
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2832
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2833
+ };
2834
+ }
2835
+ }
2836
+ const parseInputFileEntry = async (entry) => {
2837
+ if (!isDefined(entry))
2838
+ return null;
2839
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout, uploadUrlTimeout } = await entry;
2840
+ return compactObject({
2841
+ id,
2842
+ // Name cannot be an empty string in our API
2843
+ name: name ? name : void 0,
2844
+ mediaType,
2845
+ base64Content,
2846
+ enablePublicUrl,
2847
+ signedUrlTimeout,
2848
+ uploadUrlTimeout
2849
+ });
2850
+ };
2851
+
2280
2852
  function cleanFilter(filter) {
2281
- if (!filter)
2853
+ if (!isDefined(filter))
2282
2854
  return void 0;
2283
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
2284
- return values.length > 0 ? filter : void 0;
2855
+ if (!isObject(filter))
2856
+ return filter;
2857
+ const values = Object.fromEntries(
2858
+ Object.entries(filter).reduce((acc, [key, value]) => {
2859
+ if (!isDefined(value))
2860
+ return acc;
2861
+ if (Array.isArray(value)) {
2862
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2863
+ if (clean.length === 0)
2864
+ return acc;
2865
+ return [...acc, [key, clean]];
2866
+ }
2867
+ if (isObject(value)) {
2868
+ const clean = cleanFilter(value);
2869
+ if (!isDefined(clean))
2870
+ return acc;
2871
+ return [...acc, [key, clean]];
2872
+ }
2873
+ return [...acc, [key, value]];
2874
+ }, [])
2875
+ );
2876
+ return Object.keys(values).length > 0 ? values : void 0;
2877
+ }
2878
+
2879
+ function stringifyJson(value) {
2880
+ if (!isDefined(value))
2881
+ return value;
2882
+ if (isString(value))
2883
+ return value;
2884
+ try {
2885
+ return JSON.stringify(value);
2886
+ } catch (e) {
2887
+ return value;
2888
+ }
2889
+ }
2890
+ function parseJson(value) {
2891
+ try {
2892
+ return JSON.parse(value);
2893
+ } catch (e) {
2894
+ return value;
2895
+ }
2285
2896
  }
2286
2897
 
2287
2898
  var __accessCheck$6 = (obj, member, msg) => {
2288
2899
  if (!member.has(obj))
2289
2900
  throw TypeError("Cannot " + msg);
2290
2901
  };
2291
- var __privateGet$6 = (obj, member, getter) => {
2902
+ var __privateGet$5 = (obj, member, getter) => {
2292
2903
  __accessCheck$6(obj, member, "read from private field");
2293
2904
  return getter ? getter.call(obj) : member.get(obj);
2294
2905
  };
@@ -2297,7 +2908,7 @@ var __privateAdd$6 = (obj, member, value) => {
2297
2908
  throw TypeError("Cannot add the same private member more than once");
2298
2909
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2299
2910
  };
2300
- var __privateSet$6 = (obj, member, value, setter) => {
2911
+ var __privateSet$4 = (obj, member, value, setter) => {
2301
2912
  __accessCheck$6(obj, member, "write to private field");
2302
2913
  setter ? setter.call(obj, value) : member.set(obj, value);
2303
2914
  return value;
@@ -2306,39 +2917,67 @@ var _query, _page;
2306
2917
  class Page {
2307
2918
  constructor(query, meta, records = []) {
2308
2919
  __privateAdd$6(this, _query, void 0);
2309
- __privateSet$6(this, _query, query);
2920
+ __privateSet$4(this, _query, query);
2310
2921
  this.meta = meta;
2311
2922
  this.records = new RecordArray(this, records);
2312
2923
  }
2924
+ /**
2925
+ * Retrieves the next page of results.
2926
+ * @param size Maximum number of results to be retrieved.
2927
+ * @param offset Number of results to skip when retrieving the results.
2928
+ * @returns The next page or results.
2929
+ */
2313
2930
  async nextPage(size, offset) {
2314
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
2315
- }
2931
+ return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
2932
+ }
2933
+ /**
2934
+ * Retrieves the previous page of results.
2935
+ * @param size Maximum number of results to be retrieved.
2936
+ * @param offset Number of results to skip when retrieving the results.
2937
+ * @returns The previous page or results.
2938
+ */
2316
2939
  async previousPage(size, offset) {
2317
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
2318
- }
2940
+ return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
2941
+ }
2942
+ /**
2943
+ * Retrieves the start page of results.
2944
+ * @param size Maximum number of results to be retrieved.
2945
+ * @param offset Number of results to skip when retrieving the results.
2946
+ * @returns The start page or results.
2947
+ */
2319
2948
  async startPage(size, offset) {
2320
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
2321
- }
2949
+ return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
2950
+ }
2951
+ /**
2952
+ * Retrieves the end page of results.
2953
+ * @param size Maximum number of results to be retrieved.
2954
+ * @param offset Number of results to skip when retrieving the results.
2955
+ * @returns The end page or results.
2956
+ */
2322
2957
  async endPage(size, offset) {
2323
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
2958
+ return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
2324
2959
  }
2960
+ /**
2961
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
2962
+ * @returns Whether or not there will be additional results in the next page of results.
2963
+ */
2325
2964
  hasNextPage() {
2326
2965
  return this.meta.page.more;
2327
2966
  }
2328
2967
  }
2329
2968
  _query = new WeakMap();
2330
- const PAGINATION_MAX_SIZE = 200;
2969
+ const PAGINATION_MAX_SIZE = 1e3;
2331
2970
  const PAGINATION_DEFAULT_SIZE = 20;
2332
- const PAGINATION_MAX_OFFSET = 800;
2971
+ const PAGINATION_MAX_OFFSET = 49e3;
2333
2972
  const PAGINATION_DEFAULT_OFFSET = 0;
2334
2973
  function isCursorPaginationOptions(options) {
2335
2974
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
2336
2975
  }
2337
- const _RecordArray = class extends Array {
2976
+ const _RecordArray = class _RecordArray extends Array {
2338
2977
  constructor(...args) {
2339
2978
  super(..._RecordArray.parseConstructorParams(...args));
2340
2979
  __privateAdd$6(this, _page, void 0);
2341
- __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
2980
+ __privateSet$4(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
2342
2981
  }
2343
2982
  static parseConstructorParams(...args) {
2344
2983
  if (args.length === 1 && typeof args[0] === "number") {
@@ -2362,34 +3001,57 @@ const _RecordArray = class extends Array {
2362
3001
  map(callbackfn, thisArg) {
2363
3002
  return this.toArray().map(callbackfn, thisArg);
2364
3003
  }
3004
+ /**
3005
+ * Retrieve next page of records
3006
+ *
3007
+ * @returns A new array of objects
3008
+ */
2365
3009
  async nextPage(size, offset) {
2366
- const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
3010
+ const newPage = await __privateGet$5(this, _page).nextPage(size, offset);
2367
3011
  return new _RecordArray(newPage);
2368
3012
  }
3013
+ /**
3014
+ * Retrieve previous page of records
3015
+ *
3016
+ * @returns A new array of objects
3017
+ */
2369
3018
  async previousPage(size, offset) {
2370
- const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
3019
+ const newPage = await __privateGet$5(this, _page).previousPage(size, offset);
2371
3020
  return new _RecordArray(newPage);
2372
3021
  }
3022
+ /**
3023
+ * Retrieve start page of records
3024
+ *
3025
+ * @returns A new array of objects
3026
+ */
2373
3027
  async startPage(size, offset) {
2374
- const newPage = await __privateGet$6(this, _page).startPage(size, offset);
3028
+ const newPage = await __privateGet$5(this, _page).startPage(size, offset);
2375
3029
  return new _RecordArray(newPage);
2376
3030
  }
3031
+ /**
3032
+ * Retrieve end page of records
3033
+ *
3034
+ * @returns A new array of objects
3035
+ */
2377
3036
  async endPage(size, offset) {
2378
- const newPage = await __privateGet$6(this, _page).endPage(size, offset);
3037
+ const newPage = await __privateGet$5(this, _page).endPage(size, offset);
2379
3038
  return new _RecordArray(newPage);
2380
3039
  }
3040
+ /**
3041
+ * @returns Boolean indicating if there is a next page
3042
+ */
2381
3043
  hasNextPage() {
2382
- return __privateGet$6(this, _page).meta.page.more;
3044
+ return __privateGet$5(this, _page).meta.page.more;
2383
3045
  }
2384
3046
  };
2385
- let RecordArray = _RecordArray;
2386
3047
  _page = new WeakMap();
3048
+ let RecordArray = _RecordArray;
2387
3049
 
2388
3050
  var __accessCheck$5 = (obj, member, msg) => {
2389
3051
  if (!member.has(obj))
2390
3052
  throw TypeError("Cannot " + msg);
2391
3053
  };
2392
- var __privateGet$5 = (obj, member, getter) => {
3054
+ var __privateGet$4 = (obj, member, getter) => {
2393
3055
  __accessCheck$5(obj, member, "read from private field");
2394
3056
  return getter ? getter.call(obj) : member.get(obj);
2395
3057
  };
@@ -2398,7 +3060,7 @@ var __privateAdd$5 = (obj, member, value) => {
2398
3060
  throw TypeError("Cannot add the same private member more than once");
2399
3061
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2400
3062
  };
2401
- var __privateSet$5 = (obj, member, value, setter) => {
3063
+ var __privateSet$3 = (obj, member, value, setter) => {
2402
3064
  __accessCheck$5(obj, member, "write to private field");
2403
3065
  setter ? setter.call(obj, value) : member.set(obj, value);
2404
3066
  return value;
@@ -2408,32 +3070,33 @@ var __privateMethod$3 = (obj, member, method) => {
2408
3070
  return method;
2409
3071
  };
2410
3072
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
2411
- const _Query = class {
3073
+ const _Query = class _Query {
2412
3074
  constructor(repository, table, data, rawParent) {
2413
3075
  __privateAdd$5(this, _cleanFilterConstraint);
2414
3076
  __privateAdd$5(this, _table$1, void 0);
2415
3077
  __privateAdd$5(this, _repository, void 0);
2416
3078
  __privateAdd$5(this, _data, { filter: {} });
2417
- this.meta = { page: { cursor: "start", more: true } };
3079
+ // Implements pagination
3080
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
2418
3081
  this.records = new RecordArray(this, []);
2419
- __privateSet$5(this, _table$1, table);
3082
+ __privateSet$3(this, _table$1, table);
2420
3083
  if (repository) {
2421
- __privateSet$5(this, _repository, repository);
3084
+ __privateSet$3(this, _repository, repository);
2422
3085
  } else {
2423
- __privateSet$5(this, _repository, this);
3086
+ __privateSet$3(this, _repository, this);
2424
3087
  }
2425
3088
  const parent = cleanParent(data, rawParent);
2426
- __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
2427
- __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
2428
- __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
2429
- __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
2430
- __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
2431
- __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
2432
- __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
2433
- __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
2434
- __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
2435
- __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
2436
- __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
3089
+ __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
3090
+ __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
3091
+ __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
3092
+ __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
3093
+ __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
3094
+ __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
3095
+ __privateGet$4(this, _data).columns = data.columns ?? parent?.columns;
3096
+ __privateGet$4(this, _data).consistency = data.consistency ?? parent?.consistency;
3097
+ __privateGet$4(this, _data).pagination = data.pagination ?? parent?.pagination;
3098
+ __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
3099
+ __privateGet$4(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
2437
3100
  this.any = this.any.bind(this);
2438
3101
  this.all = this.all.bind(this);
2439
3102
  this.not = this.not.bind(this);
@@ -2444,59 +3107,90 @@ const _Query = class {
2444
3107
  Object.defineProperty(this, "repository", { enumerable: false });
2445
3108
  }
2446
3109
  getQueryOptions() {
2447
- return __privateGet$5(this, _data);
3110
+ return __privateGet$4(this, _data);
2448
3111
  }
2449
3112
  key() {
2450
- const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
3113
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$4(this, _data);
2451
3114
  const key = JSON.stringify({ columns, filter, sort, pagination });
2452
3115
  return toBase64(key);
2453
3116
  }
3117
+ /**
3118
+ * Builds a new query object representing a logical OR between the given subqueries.
3119
+ * @param queries An array of subqueries.
3120
+ * @returns A new Query object.
3121
+ */
2454
3122
  any(...queries) {
2455
3123
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
2456
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
3124
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
2457
3125
  }
3126
+ /**
3127
+ * Builds a new query object representing a logical AND between the given subqueries.
3128
+ * @param queries An array of subqueries.
3129
+ * @returns A new Query object.
3130
+ */
2458
3131
  all(...queries) {
2459
3132
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
2460
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
3133
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
2461
3134
  }
3135
+ /**
3136
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3137
+ * @param queries An array of subqueries.
3138
+ * @returns A new Query object.
3139
+ */
2462
3140
  not(...queries) {
2463
3141
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
2464
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
3142
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
2465
3143
  }
3144
+ /**
3145
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3146
+ * @param queries An array of subqueries.
3147
+ * @returns A new Query object.
3148
+ */
2466
3149
  none(...queries) {
2467
3150
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
2468
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
3151
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
2469
3152
  }
2470
3153
  filter(a, b) {
2471
3154
  if (arguments.length === 1) {
2472
3155
  const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
2473
3156
  [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
2474
3157
  }));
2475
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
2476
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
3158
+ const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
3159
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
2477
3160
  } else {
2478
3161
  const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
2479
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
2480
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
3162
+ const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
3163
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
2481
3164
  }
2482
3165
  }
2483
3166
  sort(column, direction = "asc") {
2484
- const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
3167
+ const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
2485
3168
  const sort = [...originalSort, { column, direction }];
2486
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
3169
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
2487
3170
  }
3171
+ /**
3172
+ * Builds a new query specifying the set of columns to be returned in the query response.
3173
+ * @param columns Array of column names to be returned by the query.
3174
+ * @returns A new Query object.
3175
+ */
2488
3176
  select(columns) {
2489
3177
  return new _Query(
2490
- __privateGet$5(this, _repository),
2491
- __privateGet$5(this, _table$1),
3178
+ __privateGet$4(this, _repository),
3179
+ __privateGet$4(this, _table$1),
2492
3180
  { columns },
2493
- __privateGet$5(this, _data)
3181
+ __privateGet$4(this, _data)
2494
3182
  );
2495
3183
  }
2496
3184
  getPaginated(options = {}) {
2497
- const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
2498
- return __privateGet$5(this, _repository).query(query);
2499
- }
3185
+ const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
3186
+ return __privateGet$4(this, _repository).query(query);
3187
+ }
3188
+ /**
3189
+ * Get results in an iterator
3190
+ *
3191
+ * @async
3192
+ * @returns Async interable of results
3193
+ */
2500
3194
  async *[Symbol.asyncIterator]() {
2501
3195
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
2502
3196
  yield record;
@@ -2550,39 +3244,66 @@ const _Query = class {
2550
3244
  async summarize(params = {}) {
2551
3245
  const { summaries, summariesFilter, ...options } = params;
2552
3246
  const query = new _Query(
2553
- __privateGet$5(this, _repository),
2554
- __privateGet$5(this, _table$1),
3247
+ __privateGet$4(this, _repository),
3248
+ __privateGet$4(this, _table$1),
2555
3249
  options,
2556
- __privateGet$5(this, _data)
3250
+ __privateGet$4(this, _data)
2557
3251
  );
2558
- return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
3252
+ return __privateGet$4(this, _repository).summarizeTable(query, summaries, summariesFilter);
2559
3253
  }
3254
+ /**
3255
+ * Builds a new query object adding a cache TTL in milliseconds.
3256
+ * @param ttl The cache TTL in milliseconds.
3257
+ * @returns A new Query object.
3258
+ */
2560
3259
  cache(ttl) {
2561
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
3260
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
2562
3261
  }
3262
+ /**
3263
+ * Retrieve next page of records
3264
+ *
3265
+ * @returns A new page object.
3266
+ */
2563
3267
  nextPage(size, offset) {
2564
3268
  return this.startPage(size, offset);
2565
3269
  }
3270
+ /**
3271
+ * Retrieve previous page of records
3272
+ *
3273
+ * @returns A new page object
3274
+ */
2566
3275
  previousPage(size, offset) {
2567
3276
  return this.startPage(size, offset);
2568
3277
  }
3278
+ /**
3279
+ * Retrieve start page of records
3280
+ *
3281
+ * @returns A new page object
3282
+ */
2569
3283
  startPage(size, offset) {
2570
3284
  return this.getPaginated({ pagination: { size, offset } });
2571
3285
  }
3286
+ /**
3287
+ * Retrieve last page of records
3288
+ *
3289
+ * @returns A new page object
3290
+ */
2572
3291
  endPage(size, offset) {
2573
3292
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2574
3293
  }
3294
+ /**
3295
+ * @returns Boolean indicating if there is a next page
3296
+ */
2575
3297
  hasNextPage() {
2576
3298
  return this.meta.page.more;
2577
3299
  }
2578
3300
  };
2579
- let Query = _Query;
2580
3301
  _table$1 = new WeakMap();
2581
3302
  _repository = new WeakMap();
2582
3303
  _data = new WeakMap();
2583
3304
  _cleanFilterConstraint = new WeakSet();
2584
3305
  cleanFilterConstraint_fn = function(column, value) {
2585
- const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
3306
+ const columnType = __privateGet$4(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
2586
3307
  if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
2587
3308
  return { $includes: value };
2588
3309
  }
@@ -2591,6 +3312,7 @@ cleanFilterConstraint_fn = function(column, value) {
2591
3312
  }
2592
3313
  return value;
2593
3314
  };
3315
+ let Query = _Query;
2594
3316
  function cleanParent(data, parent) {
2595
3317
  if (isCursorPaginationOptions(data.pagination)) {
2596
3318
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2598,6 +3320,21 @@ function cleanParent(data, parent) {
2598
3320
  return parent;
2599
3321
  }
2600
3322
 
3323
+ const RecordColumnTypes = [
3324
+ "bool",
3325
+ "int",
3326
+ "float",
3327
+ "string",
3328
+ "text",
3329
+ "email",
3330
+ "multiple",
3331
+ "link",
3332
+ "datetime",
3333
+ "vector",
3334
+ "file[]",
3335
+ "file",
3336
+ "json"
3337
+ ];
2601
3338
  function isIdentifiable(x) {
2602
3339
  return isObject(x) && isString(x?.id);
2603
3340
  }
@@ -2607,6 +3344,24 @@ function isXataRecord(x) {
2607
3344
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
2608
3345
  }
2609
3346
 
3347
+ function isValidExpandedColumn(column) {
3348
+ return isObject(column) && isString(column.name);
3349
+ }
3350
+ function isValidSelectableColumns(columns) {
3351
+ if (!Array.isArray(columns)) {
3352
+ return false;
3353
+ }
3354
+ return columns.every((column) => {
3355
+ if (typeof column === "string") {
3356
+ return true;
3357
+ }
3358
+ if (typeof column === "object") {
3359
+ return isValidExpandedColumn(column);
3360
+ }
3361
+ return false;
3362
+ });
3363
+ }
3364
+
2610
3365
  function isSortFilterString(value) {
2611
3366
  return isString(value);
2612
3367
  }
@@ -2638,7 +3393,7 @@ var __accessCheck$4 = (obj, member, msg) => {
2638
3393
  if (!member.has(obj))
2639
3394
  throw TypeError("Cannot " + msg);
2640
3395
  };
2641
- var __privateGet$4 = (obj, member, getter) => {
3396
+ var __privateGet$3 = (obj, member, getter) => {
2642
3397
  __accessCheck$4(obj, member, "read from private field");
2643
3398
  return getter ? getter.call(obj) : member.get(obj);
2644
3399
  };
@@ -2647,7 +3402,7 @@ var __privateAdd$4 = (obj, member, value) => {
2647
3402
  throw TypeError("Cannot add the same private member more than once");
2648
3403
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2649
3404
  };
2650
- var __privateSet$4 = (obj, member, value, setter) => {
3405
+ var __privateSet$2 = (obj, member, value, setter) => {
2651
3406
  __accessCheck$4(obj, member, "write to private field");
2652
3407
  setter ? setter.call(obj, value) : member.set(obj, value);
2653
3408
  return value;
@@ -2656,7 +3411,7 @@ var __privateMethod$2 = (obj, member, method) => {
2656
3411
  __accessCheck$4(obj, member, "access private method");
2657
3412
  return method;
2658
3413
  };
2659
- var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
3414
+ var _table, _getFetchProps, _db, _cache, _schemaTables, _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, getSchemaTables_fn, _transformObjectToApi, transformObjectToApi_fn;
2660
3415
  const BULK_OPERATION_MAX_SIZE = 1e3;
2661
3416
  class Repository extends Query {
2662
3417
  }
@@ -2677,61 +3432,62 @@ class RestRepository extends Query {
2677
3432
  __privateAdd$4(this, _deleteRecords);
2678
3433
  __privateAdd$4(this, _setCacheQuery);
2679
3434
  __privateAdd$4(this, _getCacheQuery);
2680
- __privateAdd$4(this, _getSchemaTables$1);
3435
+ __privateAdd$4(this, _getSchemaTables);
3436
+ __privateAdd$4(this, _transformObjectToApi);
2681
3437
  __privateAdd$4(this, _table, void 0);
2682
3438
  __privateAdd$4(this, _getFetchProps, void 0);
2683
3439
  __privateAdd$4(this, _db, void 0);
2684
3440
  __privateAdd$4(this, _cache, void 0);
2685
- __privateAdd$4(this, _schemaTables$2, void 0);
3441
+ __privateAdd$4(this, _schemaTables, void 0);
2686
3442
  __privateAdd$4(this, _trace, void 0);
2687
- __privateSet$4(this, _table, options.table);
2688
- __privateSet$4(this, _db, options.db);
2689
- __privateSet$4(this, _cache, options.pluginOptions.cache);
2690
- __privateSet$4(this, _schemaTables$2, options.schemaTables);
2691
- __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
3443
+ __privateSet$2(this, _table, options.table);
3444
+ __privateSet$2(this, _db, options.db);
3445
+ __privateSet$2(this, _cache, options.pluginOptions.cache);
3446
+ __privateSet$2(this, _schemaTables, options.schemaTables);
3447
+ __privateSet$2(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2692
3448
  const trace = options.pluginOptions.trace ?? defaultTrace;
2693
- __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
3449
+ __privateSet$2(this, _trace, async (name, fn, options2 = {}) => {
2694
3450
  return trace(name, fn, {
2695
3451
  ...options2,
2696
- [TraceAttributes.TABLE]: __privateGet$4(this, _table),
3452
+ [TraceAttributes.TABLE]: __privateGet$3(this, _table),
2697
3453
  [TraceAttributes.KIND]: "sdk-operation",
2698
3454
  [TraceAttributes.VERSION]: VERSION
2699
3455
  });
2700
3456
  });
2701
3457
  }
2702
3458
  async create(a, b, c, d) {
2703
- return __privateGet$4(this, _trace).call(this, "create", async () => {
3459
+ return __privateGet$3(this, _trace).call(this, "create", async () => {
2704
3460
  const ifVersion = parseIfVersion(b, c, d);
2705
3461
  if (Array.isArray(a)) {
2706
3462
  if (a.length === 0)
2707
3463
  return [];
2708
3464
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2709
- const columns = isStringArray(b) ? b : ["*"];
3465
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2710
3466
  const result = await this.read(ids, columns);
2711
3467
  return result;
2712
3468
  }
2713
3469
  if (isString(a) && isObject(b)) {
2714
3470
  if (a === "")
2715
3471
  throw new Error("The id can't be empty");
2716
- const columns = isStringArray(c) ? c : void 0;
3472
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2717
3473
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2718
3474
  }
2719
3475
  if (isObject(a) && isString(a.id)) {
2720
3476
  if (a.id === "")
2721
3477
  throw new Error("The id can't be empty");
2722
- const columns = isStringArray(b) ? b : void 0;
3478
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2723
3479
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2724
3480
  }
2725
3481
  if (isObject(a)) {
2726
- const columns = isStringArray(b) ? b : void 0;
3482
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2727
3483
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2728
3484
  }
2729
3485
  throw new Error("Invalid arguments for create method");
2730
3486
  });
2731
3487
  }
2732
3488
  async read(a, b) {
2733
- return __privateGet$4(this, _trace).call(this, "read", async () => {
2734
- const columns = isStringArray(b) ? b : ["*"];
3489
+ return __privateGet$3(this, _trace).call(this, "read", async () => {
3490
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2735
3491
  if (Array.isArray(a)) {
2736
3492
  if (a.length === 0)
2737
3493
  return [];
@@ -2751,14 +3507,20 @@ class RestRepository extends Query {
2751
3507
  workspace: "{workspaceId}",
2752
3508
  dbBranchName: "{dbBranch}",
2753
3509
  region: "{region}",
2754
- tableName: __privateGet$4(this, _table),
3510
+ tableName: __privateGet$3(this, _table),
2755
3511
  recordId: id
2756
3512
  },
2757
3513
  queryParams: { columns },
2758
- ...__privateGet$4(this, _getFetchProps).call(this)
3514
+ ...__privateGet$3(this, _getFetchProps).call(this)
2759
3515
  });
2760
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2761
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3516
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3517
+ return initObject(
3518
+ __privateGet$3(this, _db),
3519
+ schemaTables,
3520
+ __privateGet$3(this, _table),
3521
+ response,
3522
+ columns
3523
+ );
2762
3524
  } catch (e) {
2763
3525
  if (isObject(e) && e.status === 404) {
2764
3526
  return null;
@@ -2770,7 +3532,7 @@ class RestRepository extends Query {
2770
3532
  });
2771
3533
  }
2772
3534
  async readOrThrow(a, b) {
2773
- return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
3535
+ return __privateGet$3(this, _trace).call(this, "readOrThrow", async () => {
2774
3536
  const result = await this.read(a, b);
2775
3537
  if (Array.isArray(result)) {
2776
3538
  const missingIds = compact(
@@ -2789,7 +3551,7 @@ class RestRepository extends Query {
2789
3551
  });
2790
3552
  }
2791
3553
  async update(a, b, c, d) {
2792
- return __privateGet$4(this, _trace).call(this, "update", async () => {
3554
+ return __privateGet$3(this, _trace).call(this, "update", async () => {
2793
3555
  const ifVersion = parseIfVersion(b, c, d);
2794
3556
  if (Array.isArray(a)) {
2795
3557
  if (a.length === 0)
@@ -2800,17 +3562,17 @@ class RestRepository extends Query {
2800
3562
  ifVersion,
2801
3563
  upsert: false
2802
3564
  });
2803
- const columns = isStringArray(b) ? b : ["*"];
3565
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2804
3566
  const result = await this.read(a, columns);
2805
3567
  return result;
2806
3568
  }
2807
3569
  try {
2808
3570
  if (isString(a) && isObject(b)) {
2809
- const columns = isStringArray(c) ? c : void 0;
3571
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2810
3572
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2811
3573
  }
2812
3574
  if (isObject(a) && isString(a.id)) {
2813
- const columns = isStringArray(b) ? b : void 0;
3575
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2814
3576
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2815
3577
  }
2816
3578
  } catch (error) {
@@ -2822,7 +3584,7 @@ class RestRepository extends Query {
2822
3584
  });
2823
3585
  }
2824
3586
  async updateOrThrow(a, b, c, d) {
2825
- return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
3587
+ return __privateGet$3(this, _trace).call(this, "updateOrThrow", async () => {
2826
3588
  const result = await this.update(a, b, c, d);
2827
3589
  if (Array.isArray(result)) {
2828
3590
  const missingIds = compact(
@@ -2841,7 +3603,7 @@ class RestRepository extends Query {
2841
3603
  });
2842
3604
  }
2843
3605
  async createOrUpdate(a, b, c, d) {
2844
- return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
3606
+ return __privateGet$3(this, _trace).call(this, "createOrUpdate", async () => {
2845
3607
  const ifVersion = parseIfVersion(b, c, d);
2846
3608
  if (Array.isArray(a)) {
2847
3609
  if (a.length === 0)
@@ -2850,45 +3612,65 @@ class RestRepository extends Query {
2850
3612
  ifVersion,
2851
3613
  upsert: true
2852
3614
  });
2853
- const columns = isStringArray(b) ? b : ["*"];
3615
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2854
3616
  const result = await this.read(a, columns);
2855
3617
  return result;
2856
3618
  }
2857
3619
  if (isString(a) && isObject(b)) {
2858
- const columns = isStringArray(c) ? c : void 0;
2859
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3620
+ if (a === "")
3621
+ throw new Error("The id can't be empty");
3622
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3623
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2860
3624
  }
2861
3625
  if (isObject(a) && isString(a.id)) {
2862
- const columns = isStringArray(c) ? c : void 0;
2863
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3626
+ if (a.id === "")
3627
+ throw new Error("The id can't be empty");
3628
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3629
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3630
+ }
3631
+ if (!isDefined(a) && isObject(b)) {
3632
+ return await this.create(b, c);
3633
+ }
3634
+ if (isObject(a) && !isDefined(a.id)) {
3635
+ return await this.create(a, b);
2864
3636
  }
2865
3637
  throw new Error("Invalid arguments for createOrUpdate method");
2866
3638
  });
2867
3639
  }
2868
3640
  async createOrReplace(a, b, c, d) {
2869
- return __privateGet$4(this, _trace).call(this, "createOrReplace", async () => {
3641
+ return __privateGet$3(this, _trace).call(this, "createOrReplace", async () => {
2870
3642
  const ifVersion = parseIfVersion(b, c, d);
2871
3643
  if (Array.isArray(a)) {
2872
3644
  if (a.length === 0)
2873
3645
  return [];
2874
3646
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2875
- const columns = isStringArray(b) ? b : ["*"];
3647
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2876
3648
  const result = await this.read(ids, columns);
2877
3649
  return result;
2878
3650
  }
2879
3651
  if (isString(a) && isObject(b)) {
2880
- const columns = isStringArray(c) ? c : void 0;
2881
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3652
+ if (a === "")
3653
+ throw new Error("The id can't be empty");
3654
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3655
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2882
3656
  }
2883
3657
  if (isObject(a) && isString(a.id)) {
2884
- const columns = isStringArray(c) ? c : void 0;
2885
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3658
+ if (a.id === "")
3659
+ throw new Error("The id can't be empty");
3660
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3661
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3662
+ }
3663
+ if (!isDefined(a) && isObject(b)) {
3664
+ return await this.create(b, c);
3665
+ }
3666
+ if (isObject(a) && !isDefined(a.id)) {
3667
+ return await this.create(a, b);
2886
3668
  }
2887
3669
  throw new Error("Invalid arguments for createOrReplace method");
2888
3670
  });
2889
3671
  }
2890
3672
  async delete(a, b) {
2891
- return __privateGet$4(this, _trace).call(this, "delete", async () => {
3673
+ return __privateGet$3(this, _trace).call(this, "delete", async () => {
2892
3674
  if (Array.isArray(a)) {
2893
3675
  if (a.length === 0)
2894
3676
  return [];
@@ -2899,7 +3681,7 @@ class RestRepository extends Query {
2899
3681
  return o.id;
2900
3682
  throw new Error("Invalid arguments for delete method");
2901
3683
  });
2902
- const columns = isStringArray(b) ? b : ["*"];
3684
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2903
3685
  const result = await this.read(a, columns);
2904
3686
  await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2905
3687
  return result;
@@ -2914,7 +3696,7 @@ class RestRepository extends Query {
2914
3696
  });
2915
3697
  }
2916
3698
  async deleteOrThrow(a, b) {
2917
- return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
3699
+ return __privateGet$3(this, _trace).call(this, "deleteOrThrow", async () => {
2918
3700
  const result = await this.delete(a, b);
2919
3701
  if (Array.isArray(result)) {
2920
3702
  const missingIds = compact(
@@ -2932,13 +3714,13 @@ class RestRepository extends Query {
2932
3714
  });
2933
3715
  }
2934
3716
  async search(query, options = {}) {
2935
- return __privateGet$4(this, _trace).call(this, "search", async () => {
2936
- const { records } = await searchTable({
3717
+ return __privateGet$3(this, _trace).call(this, "search", async () => {
3718
+ const { records, totalCount } = await searchTable({
2937
3719
  pathParams: {
2938
3720
  workspace: "{workspaceId}",
2939
3721
  dbBranchName: "{dbBranch}",
2940
3722
  region: "{region}",
2941
- tableName: __privateGet$4(this, _table)
3723
+ tableName: __privateGet$3(this, _table)
2942
3724
  },
2943
3725
  body: {
2944
3726
  query,
@@ -2950,20 +3732,23 @@ class RestRepository extends Query {
2950
3732
  page: options.page,
2951
3733
  target: options.target
2952
3734
  },
2953
- ...__privateGet$4(this, _getFetchProps).call(this)
3735
+ ...__privateGet$3(this, _getFetchProps).call(this)
2954
3736
  });
2955
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2956
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3737
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3738
+ return {
3739
+ records: records.map((item) => initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), item, ["*"])),
3740
+ totalCount
3741
+ };
2957
3742
  });
2958
3743
  }
2959
3744
  async vectorSearch(column, query, options) {
2960
- return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
2961
- const { records } = await vectorSearchTable({
3745
+ return __privateGet$3(this, _trace).call(this, "vectorSearch", async () => {
3746
+ const { records, totalCount } = await vectorSearchTable({
2962
3747
  pathParams: {
2963
3748
  workspace: "{workspaceId}",
2964
3749
  dbBranchName: "{dbBranch}",
2965
3750
  region: "{region}",
2966
- tableName: __privateGet$4(this, _table)
3751
+ tableName: __privateGet$3(this, _table)
2967
3752
  },
2968
3753
  body: {
2969
3754
  column,
@@ -2972,29 +3757,32 @@ class RestRepository extends Query {
2972
3757
  size: options?.size,
2973
3758
  filter: options?.filter
2974
3759
  },
2975
- ...__privateGet$4(this, _getFetchProps).call(this)
3760
+ ...__privateGet$3(this, _getFetchProps).call(this)
2976
3761
  });
2977
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2978
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3762
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3763
+ return {
3764
+ records: records.map((item) => initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), item, ["*"])),
3765
+ totalCount
3766
+ };
2979
3767
  });
2980
3768
  }
2981
3769
  async aggregate(aggs, filter) {
2982
- return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
3770
+ return __privateGet$3(this, _trace).call(this, "aggregate", async () => {
2983
3771
  const result = await aggregateTable({
2984
3772
  pathParams: {
2985
3773
  workspace: "{workspaceId}",
2986
3774
  dbBranchName: "{dbBranch}",
2987
3775
  region: "{region}",
2988
- tableName: __privateGet$4(this, _table)
3776
+ tableName: __privateGet$3(this, _table)
2989
3777
  },
2990
3778
  body: { aggs, filter },
2991
- ...__privateGet$4(this, _getFetchProps).call(this)
3779
+ ...__privateGet$3(this, _getFetchProps).call(this)
2992
3780
  });
2993
3781
  return result;
2994
3782
  });
2995
3783
  }
2996
3784
  async query(query) {
2997
- return __privateGet$4(this, _trace).call(this, "query", async () => {
3785
+ return __privateGet$3(this, _trace).call(this, "query", async () => {
2998
3786
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
2999
3787
  if (cacheQuery)
3000
3788
  return new Page(query, cacheQuery.meta, cacheQuery.records);
@@ -3004,7 +3792,7 @@ class RestRepository extends Query {
3004
3792
  workspace: "{workspaceId}",
3005
3793
  dbBranchName: "{dbBranch}",
3006
3794
  region: "{region}",
3007
- tableName: __privateGet$4(this, _table)
3795
+ tableName: __privateGet$3(this, _table)
3008
3796
  },
3009
3797
  body: {
3010
3798
  filter: cleanFilter(data.filter),
@@ -3014,25 +3802,31 @@ class RestRepository extends Query {
3014
3802
  consistency: data.consistency
3015
3803
  },
3016
3804
  fetchOptions: data.fetchOptions,
3017
- ...__privateGet$4(this, _getFetchProps).call(this)
3805
+ ...__privateGet$3(this, _getFetchProps).call(this)
3018
3806
  });
3019
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3807
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3020
3808
  const records = objects.map(
3021
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3809
+ (record) => initObject(
3810
+ __privateGet$3(this, _db),
3811
+ schemaTables,
3812
+ __privateGet$3(this, _table),
3813
+ record,
3814
+ data.columns ?? ["*"]
3815
+ )
3022
3816
  );
3023
3817
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
3024
3818
  return new Page(query, meta, records);
3025
3819
  });
3026
3820
  }
3027
3821
  async summarizeTable(query, summaries, summariesFilter) {
3028
- return __privateGet$4(this, _trace).call(this, "summarize", async () => {
3822
+ return __privateGet$3(this, _trace).call(this, "summarize", async () => {
3029
3823
  const data = query.getQueryOptions();
3030
3824
  const result = await summarizeTable({
3031
3825
  pathParams: {
3032
3826
  workspace: "{workspaceId}",
3033
3827
  dbBranchName: "{dbBranch}",
3034
3828
  region: "{region}",
3035
- tableName: __privateGet$4(this, _table)
3829
+ tableName: __privateGet$3(this, _table)
3036
3830
  },
3037
3831
  body: {
3038
3832
  filter: cleanFilter(data.filter),
@@ -3043,29 +3837,40 @@ class RestRepository extends Query {
3043
3837
  summaries,
3044
3838
  summariesFilter
3045
3839
  },
3046
- ...__privateGet$4(this, _getFetchProps).call(this)
3840
+ ...__privateGet$3(this, _getFetchProps).call(this)
3047
3841
  });
3048
- return result;
3842
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3843
+ return {
3844
+ ...result,
3845
+ summaries: result.summaries.map(
3846
+ (summary) => initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), summary, data.columns ?? [])
3847
+ )
3848
+ };
3049
3849
  });
3050
3850
  }
3051
3851
  ask(question, options) {
3852
+ const questionParam = options?.sessionId ? { message: question } : { question };
3052
3853
  const params = {
3053
3854
  pathParams: {
3054
3855
  workspace: "{workspaceId}",
3055
3856
  dbBranchName: "{dbBranch}",
3056
3857
  region: "{region}",
3057
- tableName: __privateGet$4(this, _table)
3858
+ tableName: __privateGet$3(this, _table),
3859
+ sessionId: options?.sessionId
3058
3860
  },
3059
3861
  body: {
3060
- question,
3061
- ...options
3862
+ ...questionParam,
3863
+ rules: options?.rules,
3864
+ searchType: options?.searchType,
3865
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3866
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3062
3867
  },
3063
- ...__privateGet$4(this, _getFetchProps).call(this)
3868
+ ...__privateGet$3(this, _getFetchProps).call(this)
3064
3869
  };
3065
3870
  if (options?.onMessage) {
3066
3871
  fetchSSERequest({
3067
3872
  endpoint: "dataPlane",
3068
- url: "/db/{dbBranchName}/tables/{tableName}/ask",
3873
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3069
3874
  method: "POST",
3070
3875
  onMessage: (message) => {
3071
3876
  options.onMessage?.({ answer: message.text, records: message.records });
@@ -3073,7 +3878,7 @@ class RestRepository extends Query {
3073
3878
  ...params
3074
3879
  });
3075
3880
  } else {
3076
- return askTable(params);
3881
+ return askTableSession(params);
3077
3882
  }
3078
3883
  }
3079
3884
  }
@@ -3081,61 +3886,62 @@ _table = new WeakMap();
3081
3886
  _getFetchProps = new WeakMap();
3082
3887
  _db = new WeakMap();
3083
3888
  _cache = new WeakMap();
3084
- _schemaTables$2 = new WeakMap();
3889
+ _schemaTables = new WeakMap();
3085
3890
  _trace = new WeakMap();
3086
3891
  _insertRecordWithoutId = new WeakSet();
3087
3892
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
3088
- const record = transformObjectLinks(object);
3893
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3089
3894
  const response = await insertRecord({
3090
3895
  pathParams: {
3091
3896
  workspace: "{workspaceId}",
3092
3897
  dbBranchName: "{dbBranch}",
3093
3898
  region: "{region}",
3094
- tableName: __privateGet$4(this, _table)
3899
+ tableName: __privateGet$3(this, _table)
3095
3900
  },
3096
3901
  queryParams: { columns },
3097
3902
  body: record,
3098
- ...__privateGet$4(this, _getFetchProps).call(this)
3903
+ ...__privateGet$3(this, _getFetchProps).call(this)
3099
3904
  });
3100
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3101
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3905
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3906
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
3102
3907
  };
3103
3908
  _insertRecordWithId = new WeakSet();
3104
3909
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
3105
- const record = transformObjectLinks(object);
3910
+ if (!recordId)
3911
+ return null;
3912
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3106
3913
  const response = await insertRecordWithID({
3107
3914
  pathParams: {
3108
3915
  workspace: "{workspaceId}",
3109
3916
  dbBranchName: "{dbBranch}",
3110
3917
  region: "{region}",
3111
- tableName: __privateGet$4(this, _table),
3918
+ tableName: __privateGet$3(this, _table),
3112
3919
  recordId
3113
3920
  },
3114
3921
  body: record,
3115
3922
  queryParams: { createOnly, columns, ifVersion },
3116
- ...__privateGet$4(this, _getFetchProps).call(this)
3923
+ ...__privateGet$3(this, _getFetchProps).call(this)
3117
3924
  });
3118
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3119
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3925
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3926
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
3120
3927
  };
3121
3928
  _insertRecords = new WeakSet();
3122
3929
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
3123
- const chunkedOperations = chunk(
3124
- objects.map((object) => ({
3125
- insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
3126
- })),
3127
- BULK_OPERATION_MAX_SIZE
3128
- );
3930
+ const operations = await promiseMap(objects, async (object) => {
3931
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3932
+ return { insert: { table: __privateGet$3(this, _table), record, createOnly, ifVersion } };
3933
+ });
3934
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
3129
3935
  const ids = [];
3130
- for (const operations of chunkedOperations) {
3936
+ for (const operations2 of chunkedOperations) {
3131
3937
  const { results } = await branchTransaction({
3132
3938
  pathParams: {
3133
3939
  workspace: "{workspaceId}",
3134
3940
  dbBranchName: "{dbBranch}",
3135
3941
  region: "{region}"
3136
3942
  },
3137
- body: { operations },
3138
- ...__privateGet$4(this, _getFetchProps).call(this)
3943
+ body: { operations: operations2 },
3944
+ ...__privateGet$3(this, _getFetchProps).call(this)
3139
3945
  });
3140
3946
  for (const result of results) {
3141
3947
  if (result.operation === "insert") {
@@ -3149,22 +3955,24 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
3149
3955
  };
3150
3956
  _updateRecordWithID = new WeakSet();
3151
3957
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
3152
- const { id: _id, ...record } = transformObjectLinks(object);
3958
+ if (!recordId)
3959
+ return null;
3960
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3153
3961
  try {
3154
3962
  const response = await updateRecordWithID({
3155
3963
  pathParams: {
3156
3964
  workspace: "{workspaceId}",
3157
3965
  dbBranchName: "{dbBranch}",
3158
3966
  region: "{region}",
3159
- tableName: __privateGet$4(this, _table),
3967
+ tableName: __privateGet$3(this, _table),
3160
3968
  recordId
3161
3969
  },
3162
3970
  queryParams: { columns, ifVersion },
3163
3971
  body: record,
3164
- ...__privateGet$4(this, _getFetchProps).call(this)
3972
+ ...__privateGet$3(this, _getFetchProps).call(this)
3165
3973
  });
3166
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3167
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3974
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3975
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
3168
3976
  } catch (e) {
3169
3977
  if (isObject(e) && e.status === 404) {
3170
3978
  return null;
@@ -3174,22 +3982,21 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
3174
3982
  };
3175
3983
  _updateRecords = new WeakSet();
3176
3984
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
3177
- const chunkedOperations = chunk(
3178
- objects.map(({ id, ...object }) => ({
3179
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
3180
- })),
3181
- BULK_OPERATION_MAX_SIZE
3182
- );
3985
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
3986
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3987
+ return { update: { table: __privateGet$3(this, _table), id, ifVersion, upsert, fields } };
3988
+ });
3989
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
3183
3990
  const ids = [];
3184
- for (const operations of chunkedOperations) {
3991
+ for (const operations2 of chunkedOperations) {
3185
3992
  const { results } = await branchTransaction({
3186
3993
  pathParams: {
3187
3994
  workspace: "{workspaceId}",
3188
3995
  dbBranchName: "{dbBranch}",
3189
3996
  region: "{region}"
3190
3997
  },
3191
- body: { operations },
3192
- ...__privateGet$4(this, _getFetchProps).call(this)
3998
+ body: { operations: operations2 },
3999
+ ...__privateGet$3(this, _getFetchProps).call(this)
3193
4000
  });
3194
4001
  for (const result of results) {
3195
4002
  if (result.operation === "update") {
@@ -3203,37 +4010,41 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
3203
4010
  };
3204
4011
  _upsertRecordWithID = new WeakSet();
3205
4012
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
4013
+ if (!recordId)
4014
+ return null;
3206
4015
  const response = await upsertRecordWithID({
3207
4016
  pathParams: {
3208
4017
  workspace: "{workspaceId}",
3209
4018
  dbBranchName: "{dbBranch}",
3210
4019
  region: "{region}",
3211
- tableName: __privateGet$4(this, _table),
4020
+ tableName: __privateGet$3(this, _table),
3212
4021
  recordId
3213
4022
  },
3214
4023
  queryParams: { columns, ifVersion },
3215
4024
  body: object,
3216
- ...__privateGet$4(this, _getFetchProps).call(this)
4025
+ ...__privateGet$3(this, _getFetchProps).call(this)
3217
4026
  });
3218
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3219
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
4027
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
4028
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
3220
4029
  };
3221
4030
  _deleteRecord = new WeakSet();
3222
4031
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
4032
+ if (!recordId)
4033
+ return null;
3223
4034
  try {
3224
4035
  const response = await deleteRecord({
3225
4036
  pathParams: {
3226
4037
  workspace: "{workspaceId}",
3227
4038
  dbBranchName: "{dbBranch}",
3228
4039
  region: "{region}",
3229
- tableName: __privateGet$4(this, _table),
4040
+ tableName: __privateGet$3(this, _table),
3230
4041
  recordId
3231
4042
  },
3232
4043
  queryParams: { columns },
3233
- ...__privateGet$4(this, _getFetchProps).call(this)
4044
+ ...__privateGet$3(this, _getFetchProps).call(this)
3234
4045
  });
3235
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3236
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
4046
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
4047
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
3237
4048
  } catch (e) {
3238
4049
  if (isObject(e) && e.status === 404) {
3239
4050
  return null;
@@ -3244,7 +4055,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
3244
4055
  _deleteRecords = new WeakSet();
3245
4056
  deleteRecords_fn = async function(recordIds) {
3246
4057
  const chunkedOperations = chunk(
3247
- recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
4058
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$3(this, _table), id } })),
3248
4059
  BULK_OPERATION_MAX_SIZE
3249
4060
  );
3250
4061
  for (const operations of chunkedOperations) {
@@ -3255,44 +4066,72 @@ deleteRecords_fn = async function(recordIds) {
3255
4066
  region: "{region}"
3256
4067
  },
3257
4068
  body: { operations },
3258
- ...__privateGet$4(this, _getFetchProps).call(this)
4069
+ ...__privateGet$3(this, _getFetchProps).call(this)
3259
4070
  });
3260
4071
  }
3261
4072
  };
3262
4073
  _setCacheQuery = new WeakSet();
3263
4074
  setCacheQuery_fn = async function(query, meta, records) {
3264
- await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
4075
+ await __privateGet$3(this, _cache)?.set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
3265
4076
  };
3266
4077
  _getCacheQuery = new WeakSet();
3267
4078
  getCacheQuery_fn = async function(query) {
3268
- const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
3269
- const result = await __privateGet$4(this, _cache)?.get(key);
4079
+ const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
4080
+ const result = await __privateGet$3(this, _cache)?.get(key);
3270
4081
  if (!result)
3271
4082
  return null;
3272
- const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
4083
+ const defaultTTL = __privateGet$3(this, _cache)?.defaultQueryTTL ?? -1;
3273
4084
  const { cache: ttl = defaultTTL } = query.getQueryOptions();
3274
4085
  if (ttl < 0)
3275
4086
  return null;
3276
4087
  const hasExpired = result.date.getTime() + ttl < Date.now();
3277
4088
  return hasExpired ? null : result;
3278
4089
  };
3279
- _getSchemaTables$1 = new WeakSet();
3280
- getSchemaTables_fn$1 = async function() {
3281
- if (__privateGet$4(this, _schemaTables$2))
3282
- return __privateGet$4(this, _schemaTables$2);
4090
+ _getSchemaTables = new WeakSet();
4091
+ getSchemaTables_fn = async function() {
4092
+ if (__privateGet$3(this, _schemaTables))
4093
+ return __privateGet$3(this, _schemaTables);
3283
4094
  const { schema } = await getBranchDetails({
3284
4095
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3285
- ...__privateGet$4(this, _getFetchProps).call(this)
4096
+ ...__privateGet$3(this, _getFetchProps).call(this)
3286
4097
  });
3287
- __privateSet$4(this, _schemaTables$2, schema.tables);
4098
+ __privateSet$2(this, _schemaTables, schema.tables);
3288
4099
  return schema.tables;
3289
4100
  };
3290
- const transformObjectLinks = (object) => {
3291
- return Object.entries(object).reduce((acc, [key, value]) => {
4101
+ _transformObjectToApi = new WeakSet();
4102
+ transformObjectToApi_fn = async function(object) {
4103
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
4104
+ const schema = schemaTables.find((table) => table.name === __privateGet$3(this, _table));
4105
+ if (!schema)
4106
+ throw new Error(`Table ${__privateGet$3(this, _table)} not found in schema`);
4107
+ const result = {};
4108
+ for (const [key, value] of Object.entries(object)) {
3292
4109
  if (key === "xata")
3293
- return acc;
3294
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
3295
- }, {});
4110
+ continue;
4111
+ const type = schema.columns.find((column) => column.name === key)?.type;
4112
+ switch (type) {
4113
+ case "link": {
4114
+ result[key] = isIdentifiable(value) ? value.id : value;
4115
+ break;
4116
+ }
4117
+ case "datetime": {
4118
+ result[key] = value instanceof Date ? value.toISOString() : value;
4119
+ break;
4120
+ }
4121
+ case `file`:
4122
+ result[key] = await parseInputFileEntry(value);
4123
+ break;
4124
+ case "file[]":
4125
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4126
+ break;
4127
+ case "json":
4128
+ result[key] = stringifyJson(value);
4129
+ break;
4130
+ default:
4131
+ result[key] = value;
4132
+ }
4133
+ }
4134
+ return result;
3296
4135
  };
3297
4136
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
3298
4137
  const data = {};
@@ -3324,18 +4163,33 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
3324
4163
  if (item === column.name) {
3325
4164
  return [...acc, "*"];
3326
4165
  }
3327
- if (item.startsWith(`${column.name}.`)) {
4166
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
3328
4167
  const [, ...path] = item.split(".");
3329
4168
  return [...acc, path.join(".")];
3330
4169
  }
3331
4170
  return acc;
3332
4171
  }, []);
3333
- data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4172
+ data[column.name] = initObject(
4173
+ db,
4174
+ schemaTables,
4175
+ linkTable,
4176
+ value,
4177
+ selectedLinkColumns
4178
+ );
3334
4179
  } else {
3335
4180
  data[column.name] = null;
3336
4181
  }
3337
4182
  break;
3338
4183
  }
4184
+ case "file":
4185
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4186
+ break;
4187
+ case "file[]":
4188
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4189
+ break;
4190
+ case "json":
4191
+ data[column.name] = parseJson(value);
4192
+ break;
3339
4193
  default:
3340
4194
  data[column.name] = value ?? null;
3341
4195
  if (column.notNull === true && value === null) {
@@ -3345,30 +4199,34 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
3345
4199
  }
3346
4200
  }
3347
4201
  const record = { ...data };
4202
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
3348
4203
  record.read = function(columns2) {
3349
4204
  return db[table].read(record["id"], columns2);
3350
4205
  };
3351
4206
  record.update = function(data2, b, c) {
3352
- const columns2 = isStringArray(b) ? b : ["*"];
4207
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
3353
4208
  const ifVersion = parseIfVersion(b, c);
3354
4209
  return db[table].update(record["id"], data2, columns2, { ifVersion });
3355
4210
  };
3356
4211
  record.replace = function(data2, b, c) {
3357
- const columns2 = isStringArray(b) ? b : ["*"];
4212
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
3358
4213
  const ifVersion = parseIfVersion(b, c);
3359
4214
  return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
3360
4215
  };
3361
4216
  record.delete = function() {
3362
4217
  return db[table].delete(record["id"]);
3363
4218
  };
4219
+ if (metadata !== void 0) {
4220
+ record.xata = Object.freeze(metadata);
4221
+ }
3364
4222
  record.getMetadata = function() {
3365
- return xata;
4223
+ return record.xata;
3366
4224
  };
3367
4225
  record.toSerializable = function() {
3368
- return JSON.parse(JSON.stringify(transformObjectLinks(data)));
4226
+ return JSON.parse(JSON.stringify(record));
3369
4227
  };
3370
4228
  record.toString = function() {
3371
- return JSON.stringify(transformObjectLinks(data));
4229
+ return JSON.stringify(record);
3372
4230
  };
3373
4231
  for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
3374
4232
  Object.defineProperty(record, prop, { enumerable: false });
@@ -3386,11 +4244,7 @@ function extractId(value) {
3386
4244
  function isValidColumn(columns, column) {
3387
4245
  if (columns.includes("*"))
3388
4246
  return true;
3389
- if (column.type === "link") {
3390
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
3391
- return linkColumns.length > 0;
3392
- }
3393
- return columns.includes(column.name);
4247
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
3394
4248
  }
3395
4249
  function parseIfVersion(...args) {
3396
4250
  for (const arg of args) {
@@ -3405,7 +4259,7 @@ var __accessCheck$3 = (obj, member, msg) => {
3405
4259
  if (!member.has(obj))
3406
4260
  throw TypeError("Cannot " + msg);
3407
4261
  };
3408
- var __privateGet$3 = (obj, member, getter) => {
4262
+ var __privateGet$2 = (obj, member, getter) => {
3409
4263
  __accessCheck$3(obj, member, "read from private field");
3410
4264
  return getter ? getter.call(obj) : member.get(obj);
3411
4265
  };
@@ -3414,7 +4268,7 @@ var __privateAdd$3 = (obj, member, value) => {
3414
4268
  throw TypeError("Cannot add the same private member more than once");
3415
4269
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3416
4270
  };
3417
- var __privateSet$3 = (obj, member, value, setter) => {
4271
+ var __privateSet$1 = (obj, member, value, setter) => {
3418
4272
  __accessCheck$3(obj, member, "write to private field");
3419
4273
  setter ? setter.call(obj, value) : member.set(obj, value);
3420
4274
  return value;
@@ -3423,29 +4277,29 @@ var _map;
3423
4277
  class SimpleCache {
3424
4278
  constructor(options = {}) {
3425
4279
  __privateAdd$3(this, _map, void 0);
3426
- __privateSet$3(this, _map, /* @__PURE__ */ new Map());
4280
+ __privateSet$1(this, _map, /* @__PURE__ */ new Map());
3427
4281
  this.capacity = options.max ?? 500;
3428
4282
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
3429
4283
  }
3430
4284
  async getAll() {
3431
- return Object.fromEntries(__privateGet$3(this, _map));
4285
+ return Object.fromEntries(__privateGet$2(this, _map));
3432
4286
  }
3433
4287
  async get(key) {
3434
- return __privateGet$3(this, _map).get(key) ?? null;
4288
+ return __privateGet$2(this, _map).get(key) ?? null;
3435
4289
  }
3436
4290
  async set(key, value) {
3437
4291
  await this.delete(key);
3438
- __privateGet$3(this, _map).set(key, value);
3439
- if (__privateGet$3(this, _map).size > this.capacity) {
3440
- const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
4292
+ __privateGet$2(this, _map).set(key, value);
4293
+ if (__privateGet$2(this, _map).size > this.capacity) {
4294
+ const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
3441
4295
  await this.delete(leastRecentlyUsed);
3442
4296
  }
3443
4297
  }
3444
4298
  async delete(key) {
3445
- __privateGet$3(this, _map).delete(key);
4299
+ __privateGet$2(this, _map).delete(key);
3446
4300
  }
3447
4301
  async clear() {
3448
- return __privateGet$3(this, _map).clear();
4302
+ return __privateGet$2(this, _map).clear();
3449
4303
  }
3450
4304
  }
3451
4305
  _map = new WeakMap();
@@ -3467,10 +4321,12 @@ const notExists = (column) => ({ $notExists: column });
3467
4321
  const startsWith = (value) => ({ $startsWith: value });
3468
4322
  const endsWith = (value) => ({ $endsWith: value });
3469
4323
  const pattern = (value) => ({ $pattern: value });
4324
+ const iPattern = (value) => ({ $iPattern: value });
3470
4325
  const is = (value) => ({ $is: value });
3471
4326
  const equals = is;
3472
4327
  const isNot = (value) => ({ $isNot: value });
3473
4328
  const contains = (value) => ({ $contains: value });
4329
+ const iContains = (value) => ({ $iContains: value });
3474
4330
  const includes = (value) => ({ $includes: value });
3475
4331
  const includesAll = (value) => ({ $includesAll: value });
3476
4332
  const includesNone = (value) => ({ $includesNone: value });
@@ -3480,7 +4336,7 @@ var __accessCheck$2 = (obj, member, msg) => {
3480
4336
  if (!member.has(obj))
3481
4337
  throw TypeError("Cannot " + msg);
3482
4338
  };
3483
- var __privateGet$2 = (obj, member, getter) => {
4339
+ var __privateGet$1 = (obj, member, getter) => {
3484
4340
  __accessCheck$2(obj, member, "read from private field");
3485
4341
  return getter ? getter.call(obj) : member.get(obj);
3486
4342
  };
@@ -3489,18 +4345,11 @@ var __privateAdd$2 = (obj, member, value) => {
3489
4345
  throw TypeError("Cannot add the same private member more than once");
3490
4346
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3491
4347
  };
3492
- var __privateSet$2 = (obj, member, value, setter) => {
3493
- __accessCheck$2(obj, member, "write to private field");
3494
- setter ? setter.call(obj, value) : member.set(obj, value);
3495
- return value;
3496
- };
3497
- var _tables, _schemaTables$1;
4348
+ var _tables;
3498
4349
  class SchemaPlugin extends XataPlugin {
3499
- constructor(schemaTables) {
4350
+ constructor() {
3500
4351
  super();
3501
4352
  __privateAdd$2(this, _tables, {});
3502
- __privateAdd$2(this, _schemaTables$1, void 0);
3503
- __privateSet$2(this, _schemaTables$1, schemaTables);
3504
4353
  }
3505
4354
  build(pluginOptions) {
3506
4355
  const db = new Proxy(
@@ -3509,101 +4358,234 @@ class SchemaPlugin extends XataPlugin {
3509
4358
  get: (_target, table) => {
3510
4359
  if (!isString(table))
3511
4360
  throw new Error("Invalid table name");
3512
- if (__privateGet$2(this, _tables)[table] === void 0) {
3513
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
4361
+ if (__privateGet$1(this, _tables)[table] === void 0) {
4362
+ __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: pluginOptions.tables });
3514
4363
  }
3515
- return __privateGet$2(this, _tables)[table];
4364
+ return __privateGet$1(this, _tables)[table];
3516
4365
  }
3517
4366
  }
3518
4367
  );
3519
- const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
4368
+ const tableNames = pluginOptions.tables?.map(({ name }) => name) ?? [];
3520
4369
  for (const table of tableNames) {
3521
- db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
4370
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: pluginOptions.tables });
3522
4371
  }
3523
4372
  return db;
3524
4373
  }
3525
4374
  }
3526
4375
  _tables = new WeakMap();
3527
- _schemaTables$1 = new WeakMap();
4376
+
4377
+ class FilesPlugin extends XataPlugin {
4378
+ build(pluginOptions) {
4379
+ return {
4380
+ download: async (location) => {
4381
+ const { table, record, column, fileId = "" } = location ?? {};
4382
+ return await getFileItem({
4383
+ pathParams: {
4384
+ workspace: "{workspaceId}",
4385
+ dbBranchName: "{dbBranch}",
4386
+ region: "{region}",
4387
+ tableName: table ?? "",
4388
+ recordId: record ?? "",
4389
+ columnName: column ?? "",
4390
+ fileId
4391
+ },
4392
+ ...pluginOptions,
4393
+ rawResponse: true
4394
+ });
4395
+ },
4396
+ upload: async (location, file, options) => {
4397
+ const { table, record, column, fileId = "" } = location ?? {};
4398
+ const resolvedFile = await file;
4399
+ const contentType = options?.mediaType || getContentType(resolvedFile);
4400
+ const body = resolvedFile instanceof XataFile ? resolvedFile.toBlob() : resolvedFile;
4401
+ return await putFileItem({
4402
+ ...pluginOptions,
4403
+ pathParams: {
4404
+ workspace: "{workspaceId}",
4405
+ dbBranchName: "{dbBranch}",
4406
+ region: "{region}",
4407
+ tableName: table ?? "",
4408
+ recordId: record ?? "",
4409
+ columnName: column ?? "",
4410
+ fileId
4411
+ },
4412
+ body,
4413
+ headers: { "Content-Type": contentType }
4414
+ });
4415
+ },
4416
+ delete: async (location) => {
4417
+ const { table, record, column, fileId = "" } = location ?? {};
4418
+ return await deleteFileItem({
4419
+ pathParams: {
4420
+ workspace: "{workspaceId}",
4421
+ dbBranchName: "{dbBranch}",
4422
+ region: "{region}",
4423
+ tableName: table ?? "",
4424
+ recordId: record ?? "",
4425
+ columnName: column ?? "",
4426
+ fileId
4427
+ },
4428
+ ...pluginOptions
4429
+ });
4430
+ }
4431
+ };
4432
+ }
4433
+ }
4434
+ function getContentType(file) {
4435
+ if (typeof file === "string") {
4436
+ return "text/plain";
4437
+ }
4438
+ if ("mediaType" in file && file.mediaType !== void 0) {
4439
+ return file.mediaType;
4440
+ }
4441
+ if (isBlob(file)) {
4442
+ return file.type;
4443
+ }
4444
+ try {
4445
+ return file.type;
4446
+ } catch (e) {
4447
+ }
4448
+ return "application/octet-stream";
4449
+ }
3528
4450
 
3529
4451
  var __accessCheck$1 = (obj, member, msg) => {
3530
4452
  if (!member.has(obj))
3531
4453
  throw TypeError("Cannot " + msg);
3532
4454
  };
3533
- var __privateGet$1 = (obj, member, getter) => {
3534
- __accessCheck$1(obj, member, "read from private field");
3535
- return getter ? getter.call(obj) : member.get(obj);
3536
- };
3537
4455
  var __privateAdd$1 = (obj, member, value) => {
3538
4456
  if (member.has(obj))
3539
4457
  throw TypeError("Cannot add the same private member more than once");
3540
4458
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3541
4459
  };
3542
- var __privateSet$1 = (obj, member, value, setter) => {
3543
- __accessCheck$1(obj, member, "write to private field");
3544
- setter ? setter.call(obj, value) : member.set(obj, value);
3545
- return value;
3546
- };
3547
4460
  var __privateMethod$1 = (obj, member, method) => {
3548
4461
  __accessCheck$1(obj, member, "access private method");
3549
4462
  return method;
3550
4463
  };
3551
- var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
4464
+ var _search, search_fn;
3552
4465
  class SearchPlugin extends XataPlugin {
3553
- constructor(db, schemaTables) {
4466
+ constructor(db) {
3554
4467
  super();
3555
4468
  this.db = db;
3556
4469
  __privateAdd$1(this, _search);
3557
- __privateAdd$1(this, _getSchemaTables);
3558
- __privateAdd$1(this, _schemaTables, void 0);
3559
- __privateSet$1(this, _schemaTables, schemaTables);
3560
4470
  }
3561
4471
  build(pluginOptions) {
3562
4472
  return {
3563
4473
  all: async (query, options = {}) => {
3564
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3565
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3566
- return records.map((record) => {
3567
- const { table = "orphan" } = record.xata;
3568
- return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
3569
- });
4474
+ const { records, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4475
+ return {
4476
+ totalCount,
4477
+ records: records.map((record) => {
4478
+ const { table = "orphan" } = record.xata;
4479
+ return { table, record: initObject(this.db, pluginOptions.tables, table, record, ["*"]) };
4480
+ })
4481
+ };
3570
4482
  },
3571
4483
  byTable: async (query, options = {}) => {
3572
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3573
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3574
- return records.reduce((acc, record) => {
4484
+ const { records: rawRecords, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4485
+ const records = rawRecords.reduce((acc, record) => {
3575
4486
  const { table = "orphan" } = record.xata;
3576
4487
  const items = acc[table] ?? [];
3577
- const item = initObject(this.db, schemaTables, table, record, ["*"]);
4488
+ const item = initObject(this.db, pluginOptions.tables, table, record, ["*"]);
3578
4489
  return { ...acc, [table]: [...items, item] };
3579
4490
  }, {});
4491
+ return { totalCount, records };
3580
4492
  }
3581
4493
  };
3582
4494
  }
3583
4495
  }
3584
- _schemaTables = new WeakMap();
3585
4496
  _search = new WeakSet();
3586
4497
  search_fn = async function(query, options, pluginOptions) {
3587
4498
  const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3588
- const { records } = await searchBranch({
4499
+ const { records, totalCount } = await searchBranch({
3589
4500
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4501
+ // @ts-expect-error Filter properties do not match inferred type
3590
4502
  body: { tables, query, fuzziness, prefix, highlight, page },
3591
4503
  ...pluginOptions
3592
4504
  });
3593
- return records;
3594
- };
3595
- _getSchemaTables = new WeakSet();
3596
- getSchemaTables_fn = async function(pluginOptions) {
3597
- if (__privateGet$1(this, _schemaTables))
3598
- return __privateGet$1(this, _schemaTables);
3599
- const { schema } = await getBranchDetails({
3600
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3601
- ...pluginOptions
3602
- });
3603
- __privateSet$1(this, _schemaTables, schema.tables);
3604
- return schema.tables;
4505
+ return { records, totalCount };
3605
4506
  };
3606
4507
 
4508
+ function escapeElement(elementRepresentation) {
4509
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4510
+ return '"' + escaped + '"';
4511
+ }
4512
+ function arrayString(val) {
4513
+ let result = "{";
4514
+ for (let i = 0; i < val.length; i++) {
4515
+ if (i > 0) {
4516
+ result = result + ",";
4517
+ }
4518
+ if (val[i] === null || typeof val[i] === "undefined") {
4519
+ result = result + "NULL";
4520
+ } else if (Array.isArray(val[i])) {
4521
+ result = result + arrayString(val[i]);
4522
+ } else if (val[i] instanceof Buffer) {
4523
+ result += "\\\\x" + val[i].toString("hex");
4524
+ } else {
4525
+ result += escapeElement(prepareValue(val[i]));
4526
+ }
4527
+ }
4528
+ result = result + "}";
4529
+ return result;
4530
+ }
4531
+ function prepareValue(value) {
4532
+ if (!isDefined(value))
4533
+ return null;
4534
+ if (value instanceof Date) {
4535
+ return value.toISOString();
4536
+ }
4537
+ if (Array.isArray(value)) {
4538
+ return arrayString(value);
4539
+ }
4540
+ if (isObject(value)) {
4541
+ return JSON.stringify(value);
4542
+ }
4543
+ try {
4544
+ return value.toString();
4545
+ } catch (e) {
4546
+ return value;
4547
+ }
4548
+ }
4549
+ function prepareParams(param1, param2) {
4550
+ if (isString(param1)) {
4551
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4552
+ }
4553
+ if (isStringArray(param1)) {
4554
+ const statement = param1.reduce((acc, curr, index) => {
4555
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4556
+ }, "");
4557
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4558
+ }
4559
+ if (isObject(param1)) {
4560
+ const { statement, params, consistency } = param1;
4561
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
4562
+ }
4563
+ throw new Error("Invalid query");
4564
+ }
4565
+
4566
+ class SQLPlugin extends XataPlugin {
4567
+ build(pluginOptions) {
4568
+ return async (query, ...parameters) => {
4569
+ if (!isParamsObject(query) && (!isTemplateStringsArray(query) || !Array.isArray(parameters))) {
4570
+ throw new Error("Invalid usage of `xata.sql`. Please use it as a tagged template or with an object.");
4571
+ }
4572
+ const { statement, params, consistency } = prepareParams(query, parameters);
4573
+ const { records, warning, columns } = await sqlQuery({
4574
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4575
+ body: { statement, params, consistency },
4576
+ ...pluginOptions
4577
+ });
4578
+ return { records, warning, columns };
4579
+ };
4580
+ }
4581
+ }
4582
+ function isTemplateStringsArray(strings) {
4583
+ return Array.isArray(strings) && "raw" in strings && Array.isArray(strings.raw);
4584
+ }
4585
+ function isParamsObject(params) {
4586
+ return isObject(params) && "statement" in params;
4587
+ }
4588
+
3607
4589
  class TransactionPlugin extends XataPlugin {
3608
4590
  build(pluginOptions) {
3609
4591
  return {
@@ -3644,7 +4626,7 @@ var __privateMethod = (obj, member, method) => {
3644
4626
  const buildClient = (plugins) => {
3645
4627
  var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3646
4628
  return _a = class {
3647
- constructor(options = {}, schemaTables) {
4629
+ constructor(options = {}, tables) {
3648
4630
  __privateAdd(this, _parseOptions);
3649
4631
  __privateAdd(this, _getFetchProps);
3650
4632
  __privateAdd(this, _options, void 0);
@@ -3653,14 +4635,20 @@ const buildClient = (plugins) => {
3653
4635
  const pluginOptions = {
3654
4636
  ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3655
4637
  cache: safeOptions.cache,
3656
- host: safeOptions.host
4638
+ host: safeOptions.host,
4639
+ tables
3657
4640
  };
3658
- const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3659
- const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
4641
+ const db = new SchemaPlugin().build(pluginOptions);
4642
+ const search = new SearchPlugin(db).build(pluginOptions);
3660
4643
  const transactions = new TransactionPlugin().build(pluginOptions);
4644
+ const sql = new SQLPlugin().build(pluginOptions);
4645
+ const files = new FilesPlugin().build(pluginOptions);
4646
+ this.schema = { tables };
3661
4647
  this.db = db;
3662
4648
  this.search = search;
3663
4649
  this.transactions = transactions;
4650
+ this.sql = sql;
4651
+ this.files = files;
3664
4652
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3665
4653
  if (namespace === void 0)
3666
4654
  continue;
@@ -3741,6 +4729,7 @@ const buildClient = (plugins) => {
3741
4729
  fetch,
3742
4730
  apiKey,
3743
4731
  apiUrl: "",
4732
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3744
4733
  workspacesApiUrl: (path, params) => {
3745
4734
  const hasBranch = params.dbBranchName ?? params.branch;
3746
4735
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
@@ -3823,21 +4812,6 @@ const deserialize = (json) => {
3823
4812
  return defaultSerializer.fromJSON(json);
3824
4813
  };
3825
4814
 
3826
- function buildWorkerRunner(config) {
3827
- return function xataWorker(name, worker) {
3828
- return async (...args) => {
3829
- const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3830
- const result = await fetch(url, {
3831
- method: "POST",
3832
- headers: { "Content-Type": "application/json" },
3833
- body: serialize({ args })
3834
- });
3835
- const text = await result.text();
3836
- return deserialize(text);
3837
- };
3838
- };
3839
- }
3840
-
3841
4815
  class XataError extends Error {
3842
4816
  constructor(message, status) {
3843
4817
  super(message);
@@ -3847,6 +4821,7 @@ class XataError extends Error {
3847
4821
 
3848
4822
  exports.BaseClient = BaseClient;
3849
4823
  exports.FetcherError = FetcherError;
4824
+ exports.FilesPlugin = FilesPlugin;
3850
4825
  exports.Operations = operationsByTag;
3851
4826
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
3852
4827
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -3855,27 +4830,32 @@ exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
3855
4830
  exports.Page = Page;
3856
4831
  exports.Query = Query;
3857
4832
  exports.RecordArray = RecordArray;
4833
+ exports.RecordColumnTypes = RecordColumnTypes;
3858
4834
  exports.Repository = Repository;
3859
4835
  exports.RestRepository = RestRepository;
4836
+ exports.SQLPlugin = SQLPlugin;
3860
4837
  exports.SchemaPlugin = SchemaPlugin;
3861
4838
  exports.SearchPlugin = SearchPlugin;
3862
4839
  exports.Serializer = Serializer;
3863
4840
  exports.SimpleCache = SimpleCache;
4841
+ exports.TransactionPlugin = TransactionPlugin;
3864
4842
  exports.XataApiClient = XataApiClient;
3865
4843
  exports.XataApiPlugin = XataApiPlugin;
3866
4844
  exports.XataError = XataError;
4845
+ exports.XataFile = XataFile;
3867
4846
  exports.XataPlugin = XataPlugin;
3868
4847
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
3869
4848
  exports.addGitBranchesEntry = addGitBranchesEntry;
3870
4849
  exports.addTableColumn = addTableColumn;
3871
4850
  exports.aggregateTable = aggregateTable;
3872
4851
  exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
4852
+ exports.applyMigration = applyMigration;
3873
4853
  exports.askTable = askTable;
4854
+ exports.askTableSession = askTableSession;
3874
4855
  exports.branchTransaction = branchTransaction;
3875
4856
  exports.buildClient = buildClient;
3876
4857
  exports.buildPreviewBranchName = buildPreviewBranchName;
3877
4858
  exports.buildProviderString = buildProviderString;
3878
- exports.buildWorkerRunner = buildWorkerRunner;
3879
4859
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
3880
4860
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
3881
4861
  exports.compareBranchSchemas = compareBranchSchemas;
@@ -3884,6 +4864,7 @@ exports.compareMigrationRequest = compareMigrationRequest;
3884
4864
  exports.contains = contains;
3885
4865
  exports.copyBranch = copyBranch;
3886
4866
  exports.createBranch = createBranch;
4867
+ exports.createCluster = createCluster;
3887
4868
  exports.createDatabase = createDatabase;
3888
4869
  exports.createMigrationRequest = createMigrationRequest;
3889
4870
  exports.createTable = createTable;
@@ -3893,18 +4874,25 @@ exports.deleteBranch = deleteBranch;
3893
4874
  exports.deleteColumn = deleteColumn;
3894
4875
  exports.deleteDatabase = deleteDatabase;
3895
4876
  exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
4877
+ exports.deleteFile = deleteFile;
4878
+ exports.deleteFileItem = deleteFileItem;
4879
+ exports.deleteOAuthAccessToken = deleteOAuthAccessToken;
3896
4880
  exports.deleteRecord = deleteRecord;
3897
4881
  exports.deleteTable = deleteTable;
3898
4882
  exports.deleteUser = deleteUser;
3899
4883
  exports.deleteUserAPIKey = deleteUserAPIKey;
4884
+ exports.deleteUserOAuthClient = deleteUserOAuthClient;
3900
4885
  exports.deleteWorkspace = deleteWorkspace;
3901
4886
  exports.deserialize = deserialize;
3902
4887
  exports.endsWith = endsWith;
3903
4888
  exports.equals = equals;
3904
4889
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
3905
4890
  exports.exists = exists;
4891
+ exports.fileAccess = fileAccess;
4892
+ exports.fileUpload = fileUpload;
3906
4893
  exports.ge = ge;
3907
4894
  exports.getAPIKey = getAPIKey;
4895
+ exports.getAuthorizationCode = getAuthorizationCode;
3908
4896
  exports.getBranch = getBranch;
3909
4897
  exports.getBranchDetails = getBranchDetails;
3910
4898
  exports.getBranchList = getBranchList;
@@ -3913,29 +4901,38 @@ exports.getBranchMigrationHistory = getBranchMigrationHistory;
3913
4901
  exports.getBranchMigrationPlan = getBranchMigrationPlan;
3914
4902
  exports.getBranchSchemaHistory = getBranchSchemaHistory;
3915
4903
  exports.getBranchStats = getBranchStats;
4904
+ exports.getCluster = getCluster;
3916
4905
  exports.getColumn = getColumn;
3917
4906
  exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
3918
4907
  exports.getDatabaseList = getDatabaseList;
3919
4908
  exports.getDatabaseMetadata = getDatabaseMetadata;
3920
4909
  exports.getDatabaseURL = getDatabaseURL;
4910
+ exports.getFile = getFile;
4911
+ exports.getFileItem = getFileItem;
3921
4912
  exports.getGitBranchesMapping = getGitBranchesMapping;
3922
4913
  exports.getHostUrl = getHostUrl;
3923
4914
  exports.getMigrationRequest = getMigrationRequest;
3924
4915
  exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
3925
4916
  exports.getPreviewBranch = getPreviewBranch;
3926
4917
  exports.getRecord = getRecord;
4918
+ exports.getSchema = getSchema;
3927
4919
  exports.getTableColumns = getTableColumns;
3928
4920
  exports.getTableSchema = getTableSchema;
3929
4921
  exports.getUser = getUser;
3930
4922
  exports.getUserAPIKeys = getUserAPIKeys;
4923
+ exports.getUserOAuthAccessTokens = getUserOAuthAccessTokens;
4924
+ exports.getUserOAuthClients = getUserOAuthClients;
3931
4925
  exports.getWorkspace = getWorkspace;
3932
4926
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
3933
4927
  exports.getWorkspacesList = getWorkspacesList;
4928
+ exports.grantAuthorizationCode = grantAuthorizationCode;
3934
4929
  exports.greaterEquals = greaterEquals;
3935
4930
  exports.greaterThan = greaterThan;
3936
4931
  exports.greaterThanEquals = greaterThanEquals;
3937
4932
  exports.gt = gt;
3938
4933
  exports.gte = gte;
4934
+ exports.iContains = iContains;
4935
+ exports.iPattern = iPattern;
3939
4936
  exports.includes = includes;
3940
4937
  exports.includesAll = includesAll;
3941
4938
  exports.includesAny = includesAny;
@@ -3949,11 +4946,14 @@ exports.isHostProviderAlias = isHostProviderAlias;
3949
4946
  exports.isHostProviderBuilder = isHostProviderBuilder;
3950
4947
  exports.isIdentifiable = isIdentifiable;
3951
4948
  exports.isNot = isNot;
4949
+ exports.isValidExpandedColumn = isValidExpandedColumn;
4950
+ exports.isValidSelectableColumns = isValidSelectableColumns;
3952
4951
  exports.isXataRecord = isXataRecord;
3953
4952
  exports.le = le;
3954
4953
  exports.lessEquals = lessEquals;
3955
4954
  exports.lessThan = lessThan;
3956
4955
  exports.lessThanEquals = lessThanEquals;
4956
+ exports.listClusters = listClusters;
3957
4957
  exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
3958
4958
  exports.listRegions = listRegions;
3959
4959
  exports.lt = lt;
@@ -3964,12 +4964,18 @@ exports.operationsByTag = operationsByTag;
3964
4964
  exports.parseProviderString = parseProviderString;
3965
4965
  exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
3966
4966
  exports.pattern = pattern;
4967
+ exports.pgRollJobStatus = pgRollJobStatus;
4968
+ exports.pgRollMigrationHistory = pgRollMigrationHistory;
4969
+ exports.pgRollStatus = pgRollStatus;
3967
4970
  exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
3968
4971
  exports.pushBranchMigrations = pushBranchMigrations;
4972
+ exports.putFile = putFile;
4973
+ exports.putFileItem = putFileItem;
3969
4974
  exports.queryMigrationRequests = queryMigrationRequests;
3970
4975
  exports.queryTable = queryTable;
3971
4976
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
3972
4977
  exports.removeWorkspaceMember = removeWorkspaceMember;
4978
+ exports.renameDatabase = renameDatabase;
3973
4979
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
3974
4980
  exports.resolveBranch = resolveBranch;
3975
4981
  exports.searchBranch = searchBranch;
@@ -3979,12 +4985,15 @@ exports.setTableSchema = setTableSchema;
3979
4985
  exports.sqlQuery = sqlQuery;
3980
4986
  exports.startsWith = startsWith;
3981
4987
  exports.summarizeTable = summarizeTable;
4988
+ exports.transformImage = transformImage;
3982
4989
  exports.updateBranchMetadata = updateBranchMetadata;
3983
4990
  exports.updateBranchSchema = updateBranchSchema;
4991
+ exports.updateCluster = updateCluster;
3984
4992
  exports.updateColumn = updateColumn;
3985
4993
  exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
3986
4994
  exports.updateDatabaseMetadata = updateDatabaseMetadata;
3987
4995
  exports.updateMigrationRequest = updateMigrationRequest;
4996
+ exports.updateOAuthAccessToken = updateOAuthAccessToken;
3988
4997
  exports.updateRecordWithID = updateRecordWithID;
3989
4998
  exports.updateTable = updateTable;
3990
4999
  exports.updateUser = updateUser;