@xata.io/client 0.0.0-alpha.vf286f7d → 0.0.0-alpha.vf2894b5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -18,7 +18,8 @@ const TraceAttributes = {
18
18
  HTTP_METHOD: "http.method",
19
19
  HTTP_URL: "http.url",
20
20
  HTTP_ROUTE: "http.route",
21
- HTTP_TARGET: "http.target"
21
+ HTTP_TARGET: "http.target",
22
+ CLOUDFLARE_RAY_ID: "cf.ray"
22
23
  };
23
24
 
24
25
  function notEmpty(value) {
@@ -27,8 +28,18 @@ function notEmpty(value) {
27
28
  function compact(arr) {
28
29
  return arr.filter(notEmpty);
29
30
  }
31
+ function compactObject(obj) {
32
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
33
+ }
34
+ function isBlob(value) {
35
+ try {
36
+ return value instanceof Blob;
37
+ } catch (error) {
38
+ return false;
39
+ }
40
+ }
30
41
  function isObject(value) {
31
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
42
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
32
43
  }
33
44
  function isDefined(value) {
34
45
  return value !== null && value !== void 0;
@@ -83,6 +94,27 @@ function chunk(array, chunkSize) {
83
94
  async function timeout(ms) {
84
95
  return new Promise((resolve) => setTimeout(resolve, ms));
85
96
  }
97
+ function timeoutWithCancel(ms) {
98
+ let timeoutId;
99
+ const promise = new Promise((resolve) => {
100
+ timeoutId = setTimeout(() => {
101
+ resolve();
102
+ }, ms);
103
+ });
104
+ return {
105
+ cancel: () => clearTimeout(timeoutId),
106
+ promise
107
+ };
108
+ }
109
+ function promiseMap(inputValues, mapper) {
110
+ const reducer = (acc$, inputValue) => acc$.then(
111
+ (acc) => mapper(inputValue).then((result) => {
112
+ acc.push(result);
113
+ return acc;
114
+ })
115
+ );
116
+ return inputValues.reduce(reducer, Promise.resolve([]));
117
+ }
86
118
 
87
119
  function getEnvironment() {
88
120
  try {
@@ -182,7 +214,7 @@ function getAPIKey() {
182
214
  function getBranch() {
183
215
  try {
184
216
  const { branch } = getEnvironment();
185
- return branch ?? "main";
217
+ return branch;
186
218
  } catch (err) {
187
219
  return void 0;
188
220
  }
@@ -233,13 +265,13 @@ var __privateMethod$4 = (obj, member, method) => {
233
265
  return method;
234
266
  };
235
267
  var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
268
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
236
269
  function getFetchImplementation(userFetch) {
237
270
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
238
- const fetchImpl = userFetch ?? globalFetch;
271
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
272
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
239
273
  if (!fetchImpl) {
240
- throw new Error(
241
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
242
- );
274
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
243
275
  }
244
276
  return fetchImpl;
245
277
  }
@@ -265,9 +297,13 @@ class ApiRequestPool {
265
297
  }
266
298
  request(url, options) {
267
299
  const start = /* @__PURE__ */ new Date();
268
- const fetch2 = this.getFetch();
300
+ const fetchImpl = this.getFetch();
269
301
  const runRequest = async (stalled = false) => {
270
- const response = await fetch2(url, options);
302
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
303
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
304
+ if (!response) {
305
+ throw new Error("Request timed out");
306
+ }
271
307
  if (response.status === 429) {
272
308
  const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
273
309
  await timeout(rateLimitReset * 1e3);
@@ -275,7 +311,7 @@ class ApiRequestPool {
275
311
  }
276
312
  if (stalled) {
277
313
  const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
278
- console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
314
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
279
315
  }
280
316
  return response;
281
317
  };
@@ -490,7 +526,7 @@ function defaultOnOpen(response) {
490
526
  }
491
527
  }
492
528
 
493
- const VERSION = "0.24.0";
529
+ const VERSION = "0.26.6";
494
530
 
495
531
  class ErrorWithCause extends Error {
496
532
  constructor(message, options) {
@@ -566,6 +602,18 @@ function hostHeader(url) {
566
602
  const { groups } = pattern.exec(url) ?? {};
567
603
  return groups?.host ? { Host: groups.host } : {};
568
604
  }
605
+ async function parseBody(body, headers) {
606
+ if (!isDefined(body))
607
+ return void 0;
608
+ if (isBlob(body) || typeof body.text === "function") {
609
+ return body;
610
+ }
611
+ const { "Content-Type": contentType } = headers ?? {};
612
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
613
+ return JSON.stringify(body);
614
+ }
615
+ return body;
616
+ }
569
617
  const defaultClientID = generateUUID();
570
618
  async function fetch$1({
571
619
  url: path,
@@ -585,7 +633,8 @@ async function fetch$1({
585
633
  sessionID,
586
634
  clientName,
587
635
  xataAgentExtra,
588
- fetchOptions = {}
636
+ fetchOptions = {},
637
+ rawResponse = false
589
638
  }) {
590
639
  pool.setFetch(fetch2);
591
640
  return await trace(
@@ -604,7 +653,7 @@ async function fetch$1({
604
653
  isDefined(clientName) ? ["service", clientName] : void 0,
605
654
  ...Object.entries(xataAgentExtra ?? {})
606
655
  ]).map(([key, value]) => `${key}=${value}`).join("; ");
607
- const headers = {
656
+ const headers = compactObject({
608
657
  "Accept-Encoding": "identity",
609
658
  "Content-Type": "application/json",
610
659
  "X-Xata-Client-ID": clientID ?? defaultClientID,
@@ -613,11 +662,11 @@ async function fetch$1({
613
662
  ...customHeaders,
614
663
  ...hostHeader(fullUrl),
615
664
  Authorization: `Bearer ${apiKey}`
616
- };
665
+ });
617
666
  const response = await pool.request(url, {
618
667
  ...fetchOptions,
619
668
  method: method.toUpperCase(),
620
- body: body ? JSON.stringify(body) : void 0,
669
+ body: await parseBody(body, headers),
621
670
  headers,
622
671
  signal
623
672
  });
@@ -628,8 +677,12 @@ async function fetch$1({
628
677
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
629
678
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
630
679
  [TraceAttributes.HTTP_HOST]: host,
631
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
680
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
681
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
632
682
  });
683
+ const message = response.headers?.get("x-xata-message");
684
+ if (message)
685
+ console.warn(message);
633
686
  if (response.status === 204) {
634
687
  return {};
635
688
  }
@@ -637,7 +690,7 @@ async function fetch$1({
637
690
  throw new FetcherError(response.status, "Rate limit exceeded", requestId);
638
691
  }
639
692
  try {
640
- const jsonResponse = await response.json();
693
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
641
694
  if (response.ok) {
642
695
  return jsonResponse;
643
696
  }
@@ -897,12 +950,6 @@ const searchTable = (variables, signal) => dataPlaneFetch({
897
950
  ...variables,
898
951
  signal
899
952
  });
900
- const sqlQuery = (variables, signal) => dataPlaneFetch({
901
- url: "/db/{dbBranchName}/sql",
902
- method: "post",
903
- ...variables,
904
- signal
905
- });
906
953
  const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
907
954
  const askTable = (variables, signal) => dataPlaneFetch({
908
955
  url: "/db/{dbBranchName}/tables/{tableName}/ask",
@@ -910,6 +957,7 @@ const askTable = (variables, signal) => dataPlaneFetch({
910
957
  ...variables,
911
958
  signal
912
959
  });
960
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
913
961
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
914
962
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
915
963
  const fileAccess = (variables, signal) => dataPlaneFetch({
@@ -918,6 +966,12 @@ const fileAccess = (variables, signal) => dataPlaneFetch({
918
966
  ...variables,
919
967
  signal
920
968
  });
969
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
970
+ url: "/db/{dbBranchName}/sql",
971
+ method: "post",
972
+ ...variables,
973
+ signal
974
+ });
921
975
  const operationsByTag$2 = {
922
976
  branch: {
923
977
  getBranchList,
@@ -982,16 +1036,19 @@ const operationsByTag$2 = {
982
1036
  queryTable,
983
1037
  searchBranch,
984
1038
  searchTable,
985
- sqlQuery,
986
1039
  vectorSearchTable,
987
1040
  askTable,
1041
+ askTableSession,
988
1042
  summarizeTable,
989
1043
  aggregateTable
990
- }
1044
+ },
1045
+ sql: { sqlQuery }
991
1046
  };
992
1047
 
993
1048
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
994
1049
 
1050
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1051
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
995
1052
  const getUser = (variables, signal) => controlPlaneFetch({
996
1053
  url: "/user",
997
1054
  method: "get",
@@ -1028,6 +1085,31 @@ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
1028
1085
  ...variables,
1029
1086
  signal
1030
1087
  });
1088
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1089
+ url: "/user/oauth/clients",
1090
+ method: "get",
1091
+ ...variables,
1092
+ signal
1093
+ });
1094
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1095
+ url: "/user/oauth/clients/{clientId}",
1096
+ method: "delete",
1097
+ ...variables,
1098
+ signal
1099
+ });
1100
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1101
+ url: "/user/oauth/tokens",
1102
+ method: "get",
1103
+ ...variables,
1104
+ signal
1105
+ });
1106
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1107
+ url: "/user/oauth/tokens/{token}",
1108
+ method: "delete",
1109
+ ...variables,
1110
+ signal
1111
+ });
1112
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
1031
1113
  const getWorkspacesList = (variables, signal) => controlPlaneFetch({
1032
1114
  url: "/workspaces",
1033
1115
  method: "get",
@@ -1071,6 +1153,20 @@ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ u
1071
1153
  const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
1072
1154
  const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
1073
1155
  const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1156
+ const listClusters = (variables, signal) => controlPlaneFetch({
1157
+ url: "/workspaces/{workspaceId}/clusters",
1158
+ method: "get",
1159
+ ...variables,
1160
+ signal
1161
+ });
1162
+ const createCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "post", ...variables, signal });
1163
+ const getCluster = (variables, signal) => controlPlaneFetch({
1164
+ url: "/workspaces/{workspaceId}/clusters/{clusterId}",
1165
+ method: "get",
1166
+ ...variables,
1167
+ signal
1168
+ });
1169
+ const updateCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters/{clusterId}", method: "patch", ...variables, signal });
1074
1170
  const getDatabaseList = (variables, signal) => controlPlaneFetch({
1075
1171
  url: "/workspaces/{workspaceId}/dbs",
1076
1172
  method: "get",
@@ -1097,6 +1193,15 @@ const listRegions = (variables, signal) => controlPlaneFetch({
1097
1193
  signal
1098
1194
  });
1099
1195
  const operationsByTag$1 = {
1196
+ oAuth: {
1197
+ getAuthorizationCode,
1198
+ grantAuthorizationCode,
1199
+ getUserOAuthClients,
1200
+ deleteUserOAuthClient,
1201
+ getUserOAuthAccessTokens,
1202
+ deleteOAuthAccessToken,
1203
+ updateOAuthAccessToken
1204
+ },
1100
1205
  users: { getUser, updateUser, deleteUser },
1101
1206
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
1102
1207
  workspaces: {
@@ -1116,6 +1221,7 @@ const operationsByTag$1 = {
1116
1221
  acceptWorkspaceMemberInvite,
1117
1222
  resendWorkspaceMemberInvite
1118
1223
  },
1224
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
1119
1225
  databases: {
1120
1226
  getDatabaseList,
1121
1227
  createDatabase,
@@ -2109,6 +2215,21 @@ class SearchAndFilterApi {
2109
2215
  ...this.extraProps
2110
2216
  });
2111
2217
  }
2218
+ askTableSession({
2219
+ workspace,
2220
+ region,
2221
+ database,
2222
+ branch,
2223
+ table,
2224
+ sessionId,
2225
+ message
2226
+ }) {
2227
+ return operationsByTag.searchAndFilter.askTableSession({
2228
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2229
+ body: { message },
2230
+ ...this.extraProps
2231
+ });
2232
+ }
2112
2233
  summarizeTable({
2113
2234
  workspace,
2114
2235
  region,
@@ -2400,11 +2521,13 @@ class DatabaseApi {
2400
2521
  createDatabase({
2401
2522
  workspace,
2402
2523
  database,
2403
- data
2524
+ data,
2525
+ headers
2404
2526
  }) {
2405
2527
  return operationsByTag.databases.createDatabase({
2406
2528
  pathParams: { workspaceId: workspace, dbName: database },
2407
2529
  body: data,
2530
+ headers,
2408
2531
  ...this.extraProps
2409
2532
  });
2410
2533
  }
@@ -2494,11 +2617,261 @@ class XataApiPlugin {
2494
2617
  class XataPlugin {
2495
2618
  }
2496
2619
 
2620
+ class FilesPlugin extends XataPlugin {
2621
+ build(pluginOptions) {
2622
+ return {
2623
+ download: async (location) => {
2624
+ const { table, record, column, fileId = "" } = location ?? {};
2625
+ return await getFileItem({
2626
+ pathParams: {
2627
+ workspace: "{workspaceId}",
2628
+ dbBranchName: "{dbBranch}",
2629
+ region: "{region}",
2630
+ tableName: table ?? "",
2631
+ recordId: record ?? "",
2632
+ columnName: column ?? "",
2633
+ fileId
2634
+ },
2635
+ ...pluginOptions,
2636
+ rawResponse: true
2637
+ });
2638
+ },
2639
+ upload: async (location, file) => {
2640
+ const { table, record, column, fileId = "" } = location ?? {};
2641
+ const contentType = getContentType(file);
2642
+ return await putFileItem({
2643
+ ...pluginOptions,
2644
+ pathParams: {
2645
+ workspace: "{workspaceId}",
2646
+ dbBranchName: "{dbBranch}",
2647
+ region: "{region}",
2648
+ tableName: table ?? "",
2649
+ recordId: record ?? "",
2650
+ columnName: column ?? "",
2651
+ fileId
2652
+ },
2653
+ body: file,
2654
+ headers: { "Content-Type": contentType }
2655
+ });
2656
+ },
2657
+ delete: async (location) => {
2658
+ const { table, record, column, fileId = "" } = location ?? {};
2659
+ return await deleteFileItem({
2660
+ pathParams: {
2661
+ workspace: "{workspaceId}",
2662
+ dbBranchName: "{dbBranch}",
2663
+ region: "{region}",
2664
+ tableName: table ?? "",
2665
+ recordId: record ?? "",
2666
+ columnName: column ?? "",
2667
+ fileId
2668
+ },
2669
+ ...pluginOptions
2670
+ });
2671
+ }
2672
+ };
2673
+ }
2674
+ }
2675
+ function getContentType(file) {
2676
+ if (typeof file === "string") {
2677
+ return "text/plain";
2678
+ }
2679
+ if (isBlob(file)) {
2680
+ return file.type;
2681
+ }
2682
+ try {
2683
+ return file.type;
2684
+ } catch (e) {
2685
+ }
2686
+ return "application/octet-stream";
2687
+ }
2688
+
2689
+ function buildTransformString(transformations) {
2690
+ return transformations.flatMap(
2691
+ (t) => Object.entries(t).map(([key, value]) => {
2692
+ if (key === "trim") {
2693
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2694
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2695
+ }
2696
+ if (key === "gravity" && typeof value === "object") {
2697
+ const { x = 0.5, y = 0.5 } = value;
2698
+ return `${key}=${[x, y].join("x")}`;
2699
+ }
2700
+ return `${key}=${value}`;
2701
+ })
2702
+ ).join(",");
2703
+ }
2704
+ function transformImage(url, ...transformations) {
2705
+ if (!isDefined(url))
2706
+ return void 0;
2707
+ const newTransformations = buildTransformString(transformations);
2708
+ const { hostname, pathname, search } = new URL(url);
2709
+ const pathParts = pathname.split("/");
2710
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2711
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2712
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2713
+ const path = pathParts.join("/");
2714
+ return `https://${hostname}${transform}${path}${search}`;
2715
+ }
2716
+
2717
+ class XataFile {
2718
+ constructor(file) {
2719
+ this.id = file.id;
2720
+ this.name = file.name || "";
2721
+ this.mediaType = file.mediaType || "application/octet-stream";
2722
+ this.base64Content = file.base64Content;
2723
+ this.enablePublicUrl = file.enablePublicUrl ?? false;
2724
+ this.signedUrlTimeout = file.signedUrlTimeout ?? 300;
2725
+ this.size = file.size ?? 0;
2726
+ this.version = file.version ?? 1;
2727
+ this.url = file.url || "";
2728
+ this.signedUrl = file.signedUrl;
2729
+ this.attributes = file.attributes || {};
2730
+ }
2731
+ static fromBuffer(buffer, options = {}) {
2732
+ const base64Content = buffer.toString("base64");
2733
+ return new XataFile({ ...options, base64Content });
2734
+ }
2735
+ toBuffer() {
2736
+ if (!this.base64Content) {
2737
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2738
+ }
2739
+ return Buffer.from(this.base64Content, "base64");
2740
+ }
2741
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2742
+ const uint8Array = new Uint8Array(arrayBuffer);
2743
+ return this.fromUint8Array(uint8Array, options);
2744
+ }
2745
+ toArrayBuffer() {
2746
+ if (!this.base64Content) {
2747
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2748
+ }
2749
+ const binary = atob(this.base64Content);
2750
+ return new ArrayBuffer(binary.length);
2751
+ }
2752
+ static fromUint8Array(uint8Array, options = {}) {
2753
+ let binary = "";
2754
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2755
+ binary += String.fromCharCode(uint8Array[i]);
2756
+ }
2757
+ const base64Content = btoa(binary);
2758
+ return new XataFile({ ...options, base64Content });
2759
+ }
2760
+ toUint8Array() {
2761
+ if (!this.base64Content) {
2762
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2763
+ }
2764
+ const binary = atob(this.base64Content);
2765
+ const uint8Array = new Uint8Array(binary.length);
2766
+ for (let i = 0; i < binary.length; i++) {
2767
+ uint8Array[i] = binary.charCodeAt(i);
2768
+ }
2769
+ return uint8Array;
2770
+ }
2771
+ static async fromBlob(file, options = {}) {
2772
+ const name = options.name ?? file.name;
2773
+ const mediaType = file.type;
2774
+ const arrayBuffer = await file.arrayBuffer();
2775
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2776
+ }
2777
+ toBlob() {
2778
+ if (!this.base64Content) {
2779
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2780
+ }
2781
+ const binary = atob(this.base64Content);
2782
+ const uint8Array = new Uint8Array(binary.length);
2783
+ for (let i = 0; i < binary.length; i++) {
2784
+ uint8Array[i] = binary.charCodeAt(i);
2785
+ }
2786
+ return new Blob([uint8Array], { type: this.mediaType });
2787
+ }
2788
+ static fromString(string, options = {}) {
2789
+ const base64Content = btoa(string);
2790
+ return new XataFile({ ...options, base64Content });
2791
+ }
2792
+ toString() {
2793
+ if (!this.base64Content) {
2794
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2795
+ }
2796
+ return atob(this.base64Content);
2797
+ }
2798
+ static fromBase64(base64Content, options = {}) {
2799
+ return new XataFile({ ...options, base64Content });
2800
+ }
2801
+ toBase64() {
2802
+ if (!this.base64Content) {
2803
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2804
+ }
2805
+ return this.base64Content;
2806
+ }
2807
+ transform(...options) {
2808
+ return {
2809
+ url: transformImage(this.url, ...options),
2810
+ signedUrl: transformImage(this.signedUrl, ...options),
2811
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2812
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2813
+ };
2814
+ }
2815
+ }
2816
+ const parseInputFileEntry = async (entry) => {
2817
+ if (!isDefined(entry))
2818
+ return null;
2819
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout } = await entry;
2820
+ return compactObject({
2821
+ id,
2822
+ // Name cannot be an empty string in our API
2823
+ name: name ? name : void 0,
2824
+ mediaType,
2825
+ base64Content,
2826
+ enablePublicUrl,
2827
+ signedUrlTimeout
2828
+ });
2829
+ };
2830
+
2497
2831
  function cleanFilter(filter) {
2498
- if (!filter)
2832
+ if (!isDefined(filter))
2499
2833
  return void 0;
2500
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
2501
- return values.length > 0 ? filter : void 0;
2834
+ if (!isObject(filter))
2835
+ return filter;
2836
+ const values = Object.fromEntries(
2837
+ Object.entries(filter).reduce((acc, [key, value]) => {
2838
+ if (!isDefined(value))
2839
+ return acc;
2840
+ if (Array.isArray(value)) {
2841
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2842
+ if (clean.length === 0)
2843
+ return acc;
2844
+ return [...acc, [key, clean]];
2845
+ }
2846
+ if (isObject(value)) {
2847
+ const clean = cleanFilter(value);
2848
+ if (!isDefined(clean))
2849
+ return acc;
2850
+ return [...acc, [key, clean]];
2851
+ }
2852
+ return [...acc, [key, value]];
2853
+ }, [])
2854
+ );
2855
+ return Object.keys(values).length > 0 ? values : void 0;
2856
+ }
2857
+
2858
+ function stringifyJson(value) {
2859
+ if (!isDefined(value))
2860
+ return value;
2861
+ if (isString(value))
2862
+ return value;
2863
+ try {
2864
+ return JSON.stringify(value);
2865
+ } catch (e) {
2866
+ return value;
2867
+ }
2868
+ }
2869
+ function parseJson(value) {
2870
+ try {
2871
+ return JSON.parse(value);
2872
+ } catch (e) {
2873
+ return value;
2874
+ }
2502
2875
  }
2503
2876
 
2504
2877
  var __accessCheck$6 = (obj, member, msg) => {
@@ -2572,14 +2945,14 @@ class Page {
2572
2945
  }
2573
2946
  }
2574
2947
  _query = new WeakMap();
2575
- const PAGINATION_MAX_SIZE = 200;
2948
+ const PAGINATION_MAX_SIZE = 1e3;
2576
2949
  const PAGINATION_DEFAULT_SIZE = 20;
2577
- const PAGINATION_MAX_OFFSET = 800;
2950
+ const PAGINATION_MAX_OFFSET = 49e3;
2578
2951
  const PAGINATION_DEFAULT_OFFSET = 0;
2579
2952
  function isCursorPaginationOptions(options) {
2580
2953
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
2581
2954
  }
2582
- const _RecordArray = class extends Array {
2955
+ const _RecordArray = class _RecordArray extends Array {
2583
2956
  constructor(...args) {
2584
2957
  super(..._RecordArray.parseConstructorParams(...args));
2585
2958
  __privateAdd$6(this, _page, void 0);
@@ -2650,8 +3023,8 @@ const _RecordArray = class extends Array {
2650
3023
  return __privateGet$6(this, _page).meta.page.more;
2651
3024
  }
2652
3025
  };
2653
- let RecordArray = _RecordArray;
2654
3026
  _page = new WeakMap();
3027
+ let RecordArray = _RecordArray;
2655
3028
 
2656
3029
  var __accessCheck$5 = (obj, member, msg) => {
2657
3030
  if (!member.has(obj))
@@ -2676,7 +3049,7 @@ var __privateMethod$3 = (obj, member, method) => {
2676
3049
  return method;
2677
3050
  };
2678
3051
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
2679
- const _Query = class {
3052
+ const _Query = class _Query {
2680
3053
  constructor(repository, table, data, rawParent) {
2681
3054
  __privateAdd$5(this, _cleanFilterConstraint);
2682
3055
  __privateAdd$5(this, _table$1, void 0);
@@ -2904,7 +3277,6 @@ const _Query = class {
2904
3277
  return this.meta.page.more;
2905
3278
  }
2906
3279
  };
2907
- let Query = _Query;
2908
3280
  _table$1 = new WeakMap();
2909
3281
  _repository = new WeakMap();
2910
3282
  _data = new WeakMap();
@@ -2919,6 +3291,7 @@ cleanFilterConstraint_fn = function(column, value) {
2919
3291
  }
2920
3292
  return value;
2921
3293
  };
3294
+ let Query = _Query;
2922
3295
  function cleanParent(data, parent) {
2923
3296
  if (isCursorPaginationOptions(data.pagination)) {
2924
3297
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2926,6 +3299,22 @@ function cleanParent(data, parent) {
2926
3299
  return parent;
2927
3300
  }
2928
3301
 
3302
+ const RecordColumnTypes = [
3303
+ "bool",
3304
+ "int",
3305
+ "float",
3306
+ "string",
3307
+ "text",
3308
+ "email",
3309
+ "multiple",
3310
+ "link",
3311
+ "object",
3312
+ "datetime",
3313
+ "vector",
3314
+ "file[]",
3315
+ "file",
3316
+ "json"
3317
+ ];
2929
3318
  function isIdentifiable(x) {
2930
3319
  return isObject(x) && isString(x?.id);
2931
3320
  }
@@ -2935,6 +3324,24 @@ function isXataRecord(x) {
2935
3324
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
2936
3325
  }
2937
3326
 
3327
+ function isValidExpandedColumn(column) {
3328
+ return isObject(column) && isString(column.name);
3329
+ }
3330
+ function isValidSelectableColumns(columns) {
3331
+ if (!Array.isArray(columns)) {
3332
+ return false;
3333
+ }
3334
+ return columns.every((column) => {
3335
+ if (typeof column === "string") {
3336
+ return true;
3337
+ }
3338
+ if (typeof column === "object") {
3339
+ return isValidExpandedColumn(column);
3340
+ }
3341
+ return false;
3342
+ });
3343
+ }
3344
+
2938
3345
  function isSortFilterString(value) {
2939
3346
  return isString(value);
2940
3347
  }
@@ -2984,7 +3391,7 @@ var __privateMethod$2 = (obj, member, method) => {
2984
3391
  __accessCheck$4(obj, member, "access private method");
2985
3392
  return method;
2986
3393
  };
2987
- 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;
3394
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1, _transformObjectToApi, transformObjectToApi_fn;
2988
3395
  const BULK_OPERATION_MAX_SIZE = 1e3;
2989
3396
  class Repository extends Query {
2990
3397
  }
@@ -3006,6 +3413,7 @@ class RestRepository extends Query {
3006
3413
  __privateAdd$4(this, _setCacheQuery);
3007
3414
  __privateAdd$4(this, _getCacheQuery);
3008
3415
  __privateAdd$4(this, _getSchemaTables$1);
3416
+ __privateAdd$4(this, _transformObjectToApi);
3009
3417
  __privateAdd$4(this, _table, void 0);
3010
3418
  __privateAdd$4(this, _getFetchProps, void 0);
3011
3419
  __privateAdd$4(this, _db, void 0);
@@ -3034,24 +3442,24 @@ class RestRepository extends Query {
3034
3442
  if (a.length === 0)
3035
3443
  return [];
3036
3444
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
3037
- const columns = isStringArray(b) ? b : ["*"];
3445
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3038
3446
  const result = await this.read(ids, columns);
3039
3447
  return result;
3040
3448
  }
3041
3449
  if (isString(a) && isObject(b)) {
3042
3450
  if (a === "")
3043
3451
  throw new Error("The id can't be empty");
3044
- const columns = isStringArray(c) ? c : void 0;
3452
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3045
3453
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
3046
3454
  }
3047
3455
  if (isObject(a) && isString(a.id)) {
3048
3456
  if (a.id === "")
3049
3457
  throw new Error("The id can't be empty");
3050
- const columns = isStringArray(b) ? b : void 0;
3458
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3051
3459
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
3052
3460
  }
3053
3461
  if (isObject(a)) {
3054
- const columns = isStringArray(b) ? b : void 0;
3462
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3055
3463
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
3056
3464
  }
3057
3465
  throw new Error("Invalid arguments for create method");
@@ -3059,7 +3467,7 @@ class RestRepository extends Query {
3059
3467
  }
3060
3468
  async read(a, b) {
3061
3469
  return __privateGet$4(this, _trace).call(this, "read", async () => {
3062
- const columns = isStringArray(b) ? b : ["*"];
3470
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3063
3471
  if (Array.isArray(a)) {
3064
3472
  if (a.length === 0)
3065
3473
  return [];
@@ -3086,7 +3494,13 @@ class RestRepository extends Query {
3086
3494
  ...__privateGet$4(this, _getFetchProps).call(this)
3087
3495
  });
3088
3496
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3089
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3497
+ return initObject(
3498
+ __privateGet$4(this, _db),
3499
+ schemaTables,
3500
+ __privateGet$4(this, _table),
3501
+ response,
3502
+ columns
3503
+ );
3090
3504
  } catch (e) {
3091
3505
  if (isObject(e) && e.status === 404) {
3092
3506
  return null;
@@ -3128,17 +3542,17 @@ class RestRepository extends Query {
3128
3542
  ifVersion,
3129
3543
  upsert: false
3130
3544
  });
3131
- const columns = isStringArray(b) ? b : ["*"];
3545
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3132
3546
  const result = await this.read(a, columns);
3133
3547
  return result;
3134
3548
  }
3135
3549
  try {
3136
3550
  if (isString(a) && isObject(b)) {
3137
- const columns = isStringArray(c) ? c : void 0;
3551
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3138
3552
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3139
3553
  }
3140
3554
  if (isObject(a) && isString(a.id)) {
3141
- const columns = isStringArray(b) ? b : void 0;
3555
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3142
3556
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3143
3557
  }
3144
3558
  } catch (error) {
@@ -3178,17 +3592,27 @@ class RestRepository extends Query {
3178
3592
  ifVersion,
3179
3593
  upsert: true
3180
3594
  });
3181
- const columns = isStringArray(b) ? b : ["*"];
3595
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3182
3596
  const result = await this.read(a, columns);
3183
3597
  return result;
3184
3598
  }
3185
3599
  if (isString(a) && isObject(b)) {
3186
- const columns = isStringArray(c) ? c : void 0;
3187
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3600
+ if (a === "")
3601
+ throw new Error("The id can't be empty");
3602
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3603
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3188
3604
  }
3189
3605
  if (isObject(a) && isString(a.id)) {
3190
- const columns = isStringArray(c) ? c : void 0;
3191
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3606
+ if (a.id === "")
3607
+ throw new Error("The id can't be empty");
3608
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3609
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3610
+ }
3611
+ if (!isDefined(a) && isObject(b)) {
3612
+ return await this.create(b, c);
3613
+ }
3614
+ if (isObject(a) && !isDefined(a.id)) {
3615
+ return await this.create(a, b);
3192
3616
  }
3193
3617
  throw new Error("Invalid arguments for createOrUpdate method");
3194
3618
  });
@@ -3200,17 +3624,27 @@ class RestRepository extends Query {
3200
3624
  if (a.length === 0)
3201
3625
  return [];
3202
3626
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
3203
- const columns = isStringArray(b) ? b : ["*"];
3627
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3204
3628
  const result = await this.read(ids, columns);
3205
3629
  return result;
3206
3630
  }
3207
3631
  if (isString(a) && isObject(b)) {
3208
- const columns = isStringArray(c) ? c : void 0;
3209
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3632
+ if (a === "")
3633
+ throw new Error("The id can't be empty");
3634
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3635
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3210
3636
  }
3211
3637
  if (isObject(a) && isString(a.id)) {
3212
- const columns = isStringArray(c) ? c : void 0;
3213
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3638
+ if (a.id === "")
3639
+ throw new Error("The id can't be empty");
3640
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3641
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3642
+ }
3643
+ if (!isDefined(a) && isObject(b)) {
3644
+ return await this.create(b, c);
3645
+ }
3646
+ if (isObject(a) && !isDefined(a.id)) {
3647
+ return await this.create(a, b);
3214
3648
  }
3215
3649
  throw new Error("Invalid arguments for createOrReplace method");
3216
3650
  });
@@ -3227,7 +3661,7 @@ class RestRepository extends Query {
3227
3661
  return o.id;
3228
3662
  throw new Error("Invalid arguments for delete method");
3229
3663
  });
3230
- const columns = isStringArray(b) ? b : ["*"];
3664
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3231
3665
  const result = await this.read(a, columns);
3232
3666
  await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
3233
3667
  return result;
@@ -3346,7 +3780,13 @@ class RestRepository extends Query {
3346
3780
  });
3347
3781
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3348
3782
  const records = objects.map(
3349
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3783
+ (record) => initObject(
3784
+ __privateGet$4(this, _db),
3785
+ schemaTables,
3786
+ __privateGet$4(this, _table),
3787
+ record,
3788
+ data.columns ?? ["*"]
3789
+ )
3350
3790
  );
3351
3791
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
3352
3792
  return new Page(query, meta, records);
@@ -3377,23 +3817,28 @@ class RestRepository extends Query {
3377
3817
  });
3378
3818
  }
3379
3819
  ask(question, options) {
3820
+ const questionParam = options?.sessionId ? { message: question } : { question };
3380
3821
  const params = {
3381
3822
  pathParams: {
3382
3823
  workspace: "{workspaceId}",
3383
3824
  dbBranchName: "{dbBranch}",
3384
3825
  region: "{region}",
3385
- tableName: __privateGet$4(this, _table)
3826
+ tableName: __privateGet$4(this, _table),
3827
+ sessionId: options?.sessionId
3386
3828
  },
3387
3829
  body: {
3388
- question,
3389
- ...options
3830
+ ...questionParam,
3831
+ rules: options?.rules,
3832
+ searchType: options?.searchType,
3833
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3834
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3390
3835
  },
3391
3836
  ...__privateGet$4(this, _getFetchProps).call(this)
3392
3837
  };
3393
3838
  if (options?.onMessage) {
3394
3839
  fetchSSERequest({
3395
3840
  endpoint: "dataPlane",
3396
- url: "/db/{dbBranchName}/tables/{tableName}/ask",
3841
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3397
3842
  method: "POST",
3398
3843
  onMessage: (message) => {
3399
3844
  options.onMessage?.({ answer: message.text, records: message.records });
@@ -3401,7 +3846,7 @@ class RestRepository extends Query {
3401
3846
  ...params
3402
3847
  });
3403
3848
  } else {
3404
- return askTable(params);
3849
+ return askTableSession(params);
3405
3850
  }
3406
3851
  }
3407
3852
  }
@@ -3413,7 +3858,7 @@ _schemaTables$2 = new WeakMap();
3413
3858
  _trace = new WeakMap();
3414
3859
  _insertRecordWithoutId = new WeakSet();
3415
3860
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
3416
- const record = transformObjectLinks(object);
3861
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3417
3862
  const response = await insertRecord({
3418
3863
  pathParams: {
3419
3864
  workspace: "{workspaceId}",
@@ -3430,7 +3875,9 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
3430
3875
  };
3431
3876
  _insertRecordWithId = new WeakSet();
3432
3877
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
3433
- const record = transformObjectLinks(object);
3878
+ if (!recordId)
3879
+ return null;
3880
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3434
3881
  const response = await insertRecordWithID({
3435
3882
  pathParams: {
3436
3883
  workspace: "{workspaceId}",
@@ -3448,21 +3895,20 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
3448
3895
  };
3449
3896
  _insertRecords = new WeakSet();
3450
3897
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
3451
- const chunkedOperations = chunk(
3452
- objects.map((object) => ({
3453
- insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
3454
- })),
3455
- BULK_OPERATION_MAX_SIZE
3456
- );
3898
+ const operations = await promiseMap(objects, async (object) => {
3899
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3900
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
3901
+ });
3902
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
3457
3903
  const ids = [];
3458
- for (const operations of chunkedOperations) {
3904
+ for (const operations2 of chunkedOperations) {
3459
3905
  const { results } = await branchTransaction({
3460
3906
  pathParams: {
3461
3907
  workspace: "{workspaceId}",
3462
3908
  dbBranchName: "{dbBranch}",
3463
3909
  region: "{region}"
3464
3910
  },
3465
- body: { operations },
3911
+ body: { operations: operations2 },
3466
3912
  ...__privateGet$4(this, _getFetchProps).call(this)
3467
3913
  });
3468
3914
  for (const result of results) {
@@ -3477,7 +3923,9 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
3477
3923
  };
3478
3924
  _updateRecordWithID = new WeakSet();
3479
3925
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
3480
- const { id: _id, ...record } = transformObjectLinks(object);
3926
+ if (!recordId)
3927
+ return null;
3928
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3481
3929
  try {
3482
3930
  const response = await updateRecordWithID({
3483
3931
  pathParams: {
@@ -3502,21 +3950,20 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
3502
3950
  };
3503
3951
  _updateRecords = new WeakSet();
3504
3952
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
3505
- const chunkedOperations = chunk(
3506
- objects.map(({ id, ...object }) => ({
3507
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
3508
- })),
3509
- BULK_OPERATION_MAX_SIZE
3510
- );
3953
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
3954
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3955
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
3956
+ });
3957
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
3511
3958
  const ids = [];
3512
- for (const operations of chunkedOperations) {
3959
+ for (const operations2 of chunkedOperations) {
3513
3960
  const { results } = await branchTransaction({
3514
3961
  pathParams: {
3515
3962
  workspace: "{workspaceId}",
3516
3963
  dbBranchName: "{dbBranch}",
3517
3964
  region: "{region}"
3518
3965
  },
3519
- body: { operations },
3966
+ body: { operations: operations2 },
3520
3967
  ...__privateGet$4(this, _getFetchProps).call(this)
3521
3968
  });
3522
3969
  for (const result of results) {
@@ -3531,6 +3978,8 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
3531
3978
  };
3532
3979
  _upsertRecordWithID = new WeakSet();
3533
3980
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
3981
+ if (!recordId)
3982
+ return null;
3534
3983
  const response = await upsertRecordWithID({
3535
3984
  pathParams: {
3536
3985
  workspace: "{workspaceId}",
@@ -3548,6 +3997,8 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
3548
3997
  };
3549
3998
  _deleteRecord = new WeakSet();
3550
3999
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
4000
+ if (!recordId)
4001
+ return null;
3551
4002
  try {
3552
4003
  const response = await deleteRecord({
3553
4004
  pathParams: {
@@ -3572,7 +4023,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
3572
4023
  _deleteRecords = new WeakSet();
3573
4024
  deleteRecords_fn = async function(recordIds) {
3574
4025
  const chunkedOperations = chunk(
3575
- recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
4026
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
3576
4027
  BULK_OPERATION_MAX_SIZE
3577
4028
  );
3578
4029
  for (const operations of chunkedOperations) {
@@ -3615,12 +4066,40 @@ getSchemaTables_fn$1 = async function() {
3615
4066
  __privateSet$4(this, _schemaTables$2, schema.tables);
3616
4067
  return schema.tables;
3617
4068
  };
3618
- const transformObjectLinks = (object) => {
3619
- return Object.entries(object).reduce((acc, [key, value]) => {
4069
+ _transformObjectToApi = new WeakSet();
4070
+ transformObjectToApi_fn = async function(object) {
4071
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4072
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
4073
+ if (!schema)
4074
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
4075
+ const result = {};
4076
+ for (const [key, value] of Object.entries(object)) {
3620
4077
  if (key === "xata")
3621
- return acc;
3622
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
3623
- }, {});
4078
+ continue;
4079
+ const type = schema.columns.find((column) => column.name === key)?.type;
4080
+ switch (type) {
4081
+ case "link": {
4082
+ result[key] = isIdentifiable(value) ? value.id : value;
4083
+ break;
4084
+ }
4085
+ case "datetime": {
4086
+ result[key] = value instanceof Date ? value.toISOString() : value;
4087
+ break;
4088
+ }
4089
+ case `file`:
4090
+ result[key] = await parseInputFileEntry(value);
4091
+ break;
4092
+ case "file[]":
4093
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4094
+ break;
4095
+ case "json":
4096
+ result[key] = stringifyJson(value);
4097
+ break;
4098
+ default:
4099
+ result[key] = value;
4100
+ }
4101
+ }
4102
+ return result;
3624
4103
  };
3625
4104
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
3626
4105
  const data = {};
@@ -3652,18 +4131,33 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
3652
4131
  if (item === column.name) {
3653
4132
  return [...acc, "*"];
3654
4133
  }
3655
- if (item.startsWith(`${column.name}.`)) {
4134
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
3656
4135
  const [, ...path] = item.split(".");
3657
4136
  return [...acc, path.join(".")];
3658
4137
  }
3659
4138
  return acc;
3660
4139
  }, []);
3661
- data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4140
+ data[column.name] = initObject(
4141
+ db,
4142
+ schemaTables,
4143
+ linkTable,
4144
+ value,
4145
+ selectedLinkColumns
4146
+ );
3662
4147
  } else {
3663
4148
  data[column.name] = null;
3664
4149
  }
3665
4150
  break;
3666
4151
  }
4152
+ case "file":
4153
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4154
+ break;
4155
+ case "file[]":
4156
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4157
+ break;
4158
+ case "json":
4159
+ data[column.name] = parseJson(value);
4160
+ break;
3667
4161
  default:
3668
4162
  data[column.name] = value ?? null;
3669
4163
  if (column.notNull === true && value === null) {
@@ -3673,18 +4167,17 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
3673
4167
  }
3674
4168
  }
3675
4169
  const record = { ...data };
3676
- const serializable = { xata, ...transformObjectLinks(data) };
3677
4170
  const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
3678
4171
  record.read = function(columns2) {
3679
4172
  return db[table].read(record["id"], columns2);
3680
4173
  };
3681
4174
  record.update = function(data2, b, c) {
3682
- const columns2 = isStringArray(b) ? b : ["*"];
4175
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
3683
4176
  const ifVersion = parseIfVersion(b, c);
3684
4177
  return db[table].update(record["id"], data2, columns2, { ifVersion });
3685
4178
  };
3686
4179
  record.replace = function(data2, b, c) {
3687
- const columns2 = isStringArray(b) ? b : ["*"];
4180
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
3688
4181
  const ifVersion = parseIfVersion(b, c);
3689
4182
  return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
3690
4183
  };
@@ -3696,10 +4189,10 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
3696
4189
  return record.xata;
3697
4190
  };
3698
4191
  record.toSerializable = function() {
3699
- return JSON.parse(JSON.stringify(serializable));
4192
+ return JSON.parse(JSON.stringify(record));
3700
4193
  };
3701
4194
  record.toString = function() {
3702
- return JSON.stringify(transformObjectLinks(serializable));
4195
+ return JSON.stringify(record);
3703
4196
  };
3704
4197
  for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
3705
4198
  Object.defineProperty(record, prop, { enumerable: false });
@@ -3717,11 +4210,7 @@ function extractId(value) {
3717
4210
  function isValidColumn(columns, column) {
3718
4211
  if (columns.includes("*"))
3719
4212
  return true;
3720
- if (column.type === "link") {
3721
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
3722
- return linkColumns.length > 0;
3723
- }
3724
- return columns.includes(column.name);
4213
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
3725
4214
  }
3726
4215
  function parseIfVersion(...args) {
3727
4216
  for (const arg of args) {
@@ -3936,6 +4425,78 @@ getSchemaTables_fn = async function(pluginOptions) {
3936
4425
  return schema.tables;
3937
4426
  };
3938
4427
 
4428
+ function escapeElement(elementRepresentation) {
4429
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4430
+ return '"' + escaped + '"';
4431
+ }
4432
+ function arrayString(val) {
4433
+ let result = "{";
4434
+ for (let i = 0; i < val.length; i++) {
4435
+ if (i > 0) {
4436
+ result = result + ",";
4437
+ }
4438
+ if (val[i] === null || typeof val[i] === "undefined") {
4439
+ result = result + "NULL";
4440
+ } else if (Array.isArray(val[i])) {
4441
+ result = result + arrayString(val[i]);
4442
+ } else if (val[i] instanceof Buffer) {
4443
+ result += "\\\\x" + val[i].toString("hex");
4444
+ } else {
4445
+ result += escapeElement(prepareValue(val[i]));
4446
+ }
4447
+ }
4448
+ result = result + "}";
4449
+ return result;
4450
+ }
4451
+ function prepareValue(value) {
4452
+ if (!isDefined(value))
4453
+ return null;
4454
+ if (value instanceof Date) {
4455
+ return value.toISOString();
4456
+ }
4457
+ if (Array.isArray(value)) {
4458
+ return arrayString(value);
4459
+ }
4460
+ if (isObject(value)) {
4461
+ return JSON.stringify(value);
4462
+ }
4463
+ try {
4464
+ return value.toString();
4465
+ } catch (e) {
4466
+ return value;
4467
+ }
4468
+ }
4469
+ function prepareParams(param1, param2) {
4470
+ if (isString(param1)) {
4471
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4472
+ }
4473
+ if (isStringArray(param1)) {
4474
+ const statement = param1.reduce((acc, curr, index) => {
4475
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4476
+ }, "");
4477
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4478
+ }
4479
+ if (isObject(param1)) {
4480
+ const { statement, params, consistency } = param1;
4481
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
4482
+ }
4483
+ throw new Error("Invalid query");
4484
+ }
4485
+
4486
+ class SQLPlugin extends XataPlugin {
4487
+ build(pluginOptions) {
4488
+ return async (param1, ...param2) => {
4489
+ const { statement, params, consistency } = prepareParams(param1, param2);
4490
+ const { records, warning } = await sqlQuery({
4491
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4492
+ body: { statement, params, consistency },
4493
+ ...pluginOptions
4494
+ });
4495
+ return { records, warning };
4496
+ };
4497
+ }
4498
+ }
4499
+
3939
4500
  class TransactionPlugin extends XataPlugin {
3940
4501
  build(pluginOptions) {
3941
4502
  return {
@@ -3990,9 +4551,13 @@ const buildClient = (plugins) => {
3990
4551
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3991
4552
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3992
4553
  const transactions = new TransactionPlugin().build(pluginOptions);
4554
+ const sql = new SQLPlugin().build(pluginOptions);
4555
+ const files = new FilesPlugin().build(pluginOptions);
3993
4556
  this.db = db;
3994
4557
  this.search = search;
3995
4558
  this.transactions = transactions;
4559
+ this.sql = sql;
4560
+ this.files = files;
3996
4561
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3997
4562
  if (namespace === void 0)
3998
4563
  continue;
@@ -4178,5 +4743,5 @@ class XataError extends Error {
4178
4743
  }
4179
4744
  }
4180
4745
 
4181
- export { BaseClient, FetcherError, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, askTable, branchTransaction, buildClient, buildPreviewBranchName, buildProviderString, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, copyBranch, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteFile, deleteFileItem, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, fileAccess, ge, getAPIKey, getBranch, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getFile, getFileItem, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getPreviewBranch, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, pushBranchMigrations, putFile, putFileItem, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, renameDatabase, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, sqlQuery, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID, vectorSearchTable };
4746
+ export { BaseClient, FetcherError, FilesPlugin, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, RecordColumnTypes, Repository, RestRepository, SQLPlugin, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataFile, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, askTable, askTableSession, branchTransaction, buildClient, buildPreviewBranchName, buildProviderString, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, copyBranch, createBranch, createCluster, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteFile, deleteFileItem, deleteOAuthAccessToken, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteUserOAuthClient, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, fileAccess, ge, getAPIKey, getAuthorizationCode, getBranch, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getCluster, getColumn, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getFile, getFileItem, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getPreviewBranch, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getUserOAuthAccessTokens, getUserOAuthClients, getWorkspace, getWorkspaceMembersList, getWorkspacesList, grantAuthorizationCode, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isValidExpandedColumn, isValidSelectableColumns, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listClusters, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, pushBranchMigrations, putFile, putFileItem, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, renameDatabase, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, sqlQuery, startsWith, summarizeTable, transformImage, updateBranchMetadata, updateBranchSchema, updateCluster, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateOAuthAccessToken, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID, vectorSearchTable };
4182
4747
  //# sourceMappingURL=index.mjs.map