@xata.io/client 0.0.0-alpha.vf54e954 → 0.0.0-alpha.vf55585d9b3ddcdd6254b3a79c108fa99863f7685

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) {
@@ -30,8 +31,15 @@ function compact(arr) {
30
31
  function compactObject(obj) {
31
32
  return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
32
33
  }
34
+ function isBlob(value) {
35
+ try {
36
+ return value instanceof Blob;
37
+ } catch (error) {
38
+ return false;
39
+ }
40
+ }
33
41
  function isObject(value) {
34
- return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
42
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
35
43
  }
36
44
  function isDefined(value) {
37
45
  return value !== null && value !== void 0;
@@ -234,12 +242,6 @@ function getPreviewBranch() {
234
242
  }
235
243
  }
236
244
 
237
- var __defProp$8 = Object.defineProperty;
238
- var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
239
- var __publicField$8 = (obj, key, value) => {
240
- __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
241
- return value;
242
- };
243
245
  var __accessCheck$8 = (obj, member, msg) => {
244
246
  if (!member.has(obj))
245
247
  throw TypeError("Cannot " + msg);
@@ -263,14 +265,13 @@ var __privateMethod$4 = (obj, member, method) => {
263
265
  return method;
264
266
  };
265
267
  var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
266
- const REQUEST_TIMEOUT = 3e4;
268
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
267
269
  function getFetchImplementation(userFetch) {
268
270
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
269
- const fetchImpl = userFetch ?? globalFetch;
271
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
272
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
270
273
  if (!fetchImpl) {
271
- throw new Error(
272
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
273
- );
274
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
274
275
  }
275
276
  return fetchImpl;
276
277
  }
@@ -280,8 +281,6 @@ class ApiRequestPool {
280
281
  __privateAdd$8(this, _fetch, void 0);
281
282
  __privateAdd$8(this, _queue, void 0);
282
283
  __privateAdd$8(this, _concurrency, void 0);
283
- __publicField$8(this, "running");
284
- __publicField$8(this, "started");
285
284
  __privateSet$8(this, _queue, []);
286
285
  __privateSet$8(this, _concurrency, concurrency);
287
286
  this.running = 0;
@@ -527,26 +526,16 @@ function defaultOnOpen(response) {
527
526
  }
528
527
  }
529
528
 
530
- const VERSION = "0.26.0";
529
+ const VERSION = "0.28.4";
531
530
 
532
- var __defProp$7 = Object.defineProperty;
533
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
534
- var __publicField$7 = (obj, key, value) => {
535
- __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
536
- return value;
537
- };
538
531
  class ErrorWithCause extends Error {
539
532
  constructor(message, options) {
540
533
  super(message, options);
541
- __publicField$7(this, "cause");
542
534
  }
543
535
  }
544
536
  class FetcherError extends ErrorWithCause {
545
537
  constructor(status, data, requestId) {
546
538
  super(getMessage(data));
547
- __publicField$7(this, "status");
548
- __publicField$7(this, "requestId");
549
- __publicField$7(this, "errors");
550
539
  this.status = status;
551
540
  this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
552
541
  this.requestId = requestId;
@@ -580,6 +569,67 @@ function getMessage(data) {
580
569
  }
581
570
  }
582
571
 
572
+ function getHostUrl(provider, type) {
573
+ if (isHostProviderAlias(provider)) {
574
+ return providers[provider][type];
575
+ } else if (isHostProviderBuilder(provider)) {
576
+ return provider[type];
577
+ }
578
+ throw new Error("Invalid API provider");
579
+ }
580
+ const providers = {
581
+ production: {
582
+ main: "https://api.xata.io",
583
+ workspaces: "https://{workspaceId}.{region}.xata.sh"
584
+ },
585
+ staging: {
586
+ main: "https://api.staging-xata.dev",
587
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
588
+ },
589
+ dev: {
590
+ main: "https://api.dev-xata.dev",
591
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
592
+ },
593
+ local: {
594
+ main: "http://localhost:6001",
595
+ workspaces: "http://{workspaceId}.{region}.localhost:6001"
596
+ }
597
+ };
598
+ function isHostProviderAlias(alias) {
599
+ return isString(alias) && Object.keys(providers).includes(alias);
600
+ }
601
+ function isHostProviderBuilder(builder) {
602
+ return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
603
+ }
604
+ function parseProviderString(provider = "production") {
605
+ if (isHostProviderAlias(provider)) {
606
+ return provider;
607
+ }
608
+ const [main, workspaces] = provider.split(",");
609
+ if (!main || !workspaces)
610
+ return null;
611
+ return { main, workspaces };
612
+ }
613
+ function buildProviderString(provider) {
614
+ if (isHostProviderAlias(provider))
615
+ return provider;
616
+ return `${provider.main},${provider.workspaces}`;
617
+ }
618
+ function parseWorkspacesUrlParts(url) {
619
+ if (!isString(url))
620
+ return null;
621
+ const matches = {
622
+ production: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/),
623
+ staging: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/),
624
+ dev: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/),
625
+ local: url.match(/(?:https?:\/\/)?([^.]+)(?:\.([^.]+))\.localhost:(\d+)/)
626
+ };
627
+ const [host, match] = Object.entries(matches).find(([, match2]) => match2 !== null) ?? [];
628
+ if (!isHostProviderAlias(host) || !match)
629
+ return null;
630
+ return { workspace: match[1], region: match[2], host };
631
+ }
632
+
583
633
  const pool = new ApiRequestPool();
584
634
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
585
635
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
@@ -595,6 +645,7 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
595
645
  return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
596
646
  };
597
647
  function buildBaseUrl({
648
+ method,
598
649
  endpoint,
599
650
  path,
600
651
  workspacesApiUrl,
@@ -602,7 +653,24 @@ function buildBaseUrl({
602
653
  pathParams = {}
603
654
  }) {
604
655
  if (endpoint === "dataPlane") {
605
- const url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
656
+ let url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
657
+ if (method.toUpperCase() === "PUT" && [
658
+ "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
659
+ "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}"
660
+ ].includes(path)) {
661
+ const { host } = parseWorkspacesUrlParts(url) ?? {};
662
+ switch (host) {
663
+ case "production":
664
+ url = url.replace("xata.sh", "upload.xata.sh");
665
+ break;
666
+ case "staging":
667
+ url = url.replace("staging-xata.dev", "upload.staging-xata.dev");
668
+ break;
669
+ case "dev":
670
+ url = url.replace("dev-xata.dev", "upload.dev-xata.dev");
671
+ break;
672
+ }
673
+ }
606
674
  const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
607
675
  return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
608
676
  }
@@ -613,11 +681,14 @@ function hostHeader(url) {
613
681
  const { groups } = pattern.exec(url) ?? {};
614
682
  return groups?.host ? { Host: groups.host } : {};
615
683
  }
616
- function parseBody(body, headers) {
684
+ async function parseBody(body, headers) {
617
685
  if (!isDefined(body))
618
686
  return void 0;
687
+ if (isBlob(body) || typeof body.text === "function") {
688
+ return body;
689
+ }
619
690
  const { "Content-Type": contentType } = headers ?? {};
620
- if (String(contentType).toLowerCase() === "application/json") {
691
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
621
692
  return JSON.stringify(body);
622
693
  }
623
694
  return body;
@@ -648,9 +719,9 @@ async function fetch$1({
648
719
  return await trace(
649
720
  `${method.toUpperCase()} ${path}`,
650
721
  async ({ setAttributes }) => {
651
- const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
722
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
652
723
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
653
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
724
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\.[^.]+\./, "http://") : fullUrl;
654
725
  setAttributes({
655
726
  [TraceAttributes.HTTP_URL]: url,
656
727
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
@@ -674,7 +745,7 @@ async function fetch$1({
674
745
  const response = await pool.request(url, {
675
746
  ...fetchOptions,
676
747
  method: method.toUpperCase(),
677
- body: parseBody(body, headers),
748
+ body: await parseBody(body, headers),
678
749
  headers,
679
750
  signal
680
751
  });
@@ -685,7 +756,8 @@ async function fetch$1({
685
756
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
686
757
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
687
758
  [TraceAttributes.HTTP_HOST]: host,
688
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
759
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
760
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
689
761
  });
690
762
  const message = response.headers?.get("x-xata-message");
691
763
  if (message)
@@ -730,7 +802,7 @@ function fetchSSERequest({
730
802
  clientName,
731
803
  xataAgentExtra
732
804
  }) {
733
- const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
805
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
734
806
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
735
807
  const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
736
808
  void fetchEventSource(url, {
@@ -773,6 +845,20 @@ function parseUrl(url) {
773
845
 
774
846
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
775
847
 
848
+ const applyMigration = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/pgroll/apply", method: "post", ...variables, signal });
849
+ const pgRollStatus = (variables, signal) => dataPlaneFetch({
850
+ url: "/db/{dbBranchName}/pgroll/status",
851
+ method: "get",
852
+ ...variables,
853
+ signal
854
+ });
855
+ const pgRollJobStatus = (variables, signal) => dataPlaneFetch({
856
+ url: "/db/{dbBranchName}/pgroll/jobs/{jobId}",
857
+ method: "get",
858
+ ...variables,
859
+ signal
860
+ });
861
+ const pgRollMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/pgroll/migrations", method: "get", ...variables, signal });
776
862
  const getBranchList = (variables, signal) => dataPlaneFetch({
777
863
  url: "/dbs/{dbName}",
778
864
  method: "get",
@@ -792,6 +878,12 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
792
878
  ...variables,
793
879
  signal
794
880
  });
881
+ const getSchema = (variables, signal) => dataPlaneFetch({
882
+ url: "/db/{dbBranchName}/schema",
883
+ method: "get",
884
+ ...variables,
885
+ signal
886
+ });
795
887
  const copyBranch = (variables, signal) => dataPlaneFetch({
796
888
  url: "/db/{dbBranchName}/copy",
797
889
  method: "post",
@@ -973,6 +1065,12 @@ const fileAccess = (variables, signal) => dataPlaneFetch({
973
1065
  ...variables,
974
1066
  signal
975
1067
  });
1068
+ const fileUpload = (variables, signal) => dataPlaneFetch({
1069
+ url: "/file/{fileId}",
1070
+ method: "put",
1071
+ ...variables,
1072
+ signal
1073
+ });
976
1074
  const sqlQuery = (variables, signal) => dataPlaneFetch({
977
1075
  url: "/db/{dbBranchName}/sql",
978
1076
  method: "post",
@@ -981,6 +1079,10 @@ const sqlQuery = (variables, signal) => dataPlaneFetch({
981
1079
  });
982
1080
  const operationsByTag$2 = {
983
1081
  branch: {
1082
+ applyMigration,
1083
+ pgRollStatus,
1084
+ pgRollJobStatus,
1085
+ pgRollMigrationHistory,
984
1086
  getBranchList,
985
1087
  getBranchDetails,
986
1088
  createBranch,
@@ -995,6 +1097,7 @@ const operationsByTag$2 = {
995
1097
  resolveBranch
996
1098
  },
997
1099
  migrations: {
1100
+ getSchema,
998
1101
  getBranchMigrationHistory,
999
1102
  getBranchMigrationPlan,
1000
1103
  executeBranchMigrationPlan,
@@ -1038,7 +1141,7 @@ const operationsByTag$2 = {
1038
1141
  deleteRecord,
1039
1142
  bulkInsertTableRecords
1040
1143
  },
1041
- files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess },
1144
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess, fileUpload },
1042
1145
  searchAndFilter: {
1043
1146
  queryTable,
1044
1147
  searchBranch,
@@ -1160,6 +1263,15 @@ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ u
1160
1263
  const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
1161
1264
  const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
1162
1265
  const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1266
+ const listClusters = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "get", ...variables, signal });
1267
+ const createCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "post", ...variables, signal });
1268
+ const getCluster = (variables, signal) => controlPlaneFetch({
1269
+ url: "/workspaces/{workspaceId}/clusters/{clusterId}",
1270
+ method: "get",
1271
+ ...variables,
1272
+ signal
1273
+ });
1274
+ const updateCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters/{clusterId}", method: "patch", ...variables, signal });
1163
1275
  const getDatabaseList = (variables, signal) => controlPlaneFetch({
1164
1276
  url: "/workspaces/{workspaceId}/dbs",
1165
1277
  method: "get",
@@ -1214,6 +1326,7 @@ const operationsByTag$1 = {
1214
1326
  acceptWorkspaceMemberInvite,
1215
1327
  resendWorkspaceMemberInvite
1216
1328
  },
1329
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
1217
1330
  databases: {
1218
1331
  getDatabaseList,
1219
1332
  createDatabase,
@@ -1230,61 +1343,6 @@ const operationsByTag$1 = {
1230
1343
 
1231
1344
  const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);
1232
1345
 
1233
- function getHostUrl(provider, type) {
1234
- if (isHostProviderAlias(provider)) {
1235
- return providers[provider][type];
1236
- } else if (isHostProviderBuilder(provider)) {
1237
- return provider[type];
1238
- }
1239
- throw new Error("Invalid API provider");
1240
- }
1241
- const providers = {
1242
- production: {
1243
- main: "https://api.xata.io",
1244
- workspaces: "https://{workspaceId}.{region}.xata.sh"
1245
- },
1246
- staging: {
1247
- main: "https://api.staging-xata.dev",
1248
- workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1249
- },
1250
- dev: {
1251
- main: "https://api.dev-xata.dev",
1252
- workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
1253
- }
1254
- };
1255
- function isHostProviderAlias(alias) {
1256
- return isString(alias) && Object.keys(providers).includes(alias);
1257
- }
1258
- function isHostProviderBuilder(builder) {
1259
- return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
1260
- }
1261
- function parseProviderString(provider = "production") {
1262
- if (isHostProviderAlias(provider)) {
1263
- return provider;
1264
- }
1265
- const [main, workspaces] = provider.split(",");
1266
- if (!main || !workspaces)
1267
- return null;
1268
- return { main, workspaces };
1269
- }
1270
- function buildProviderString(provider) {
1271
- if (isHostProviderAlias(provider))
1272
- return provider;
1273
- return `${provider.main},${provider.workspaces}`;
1274
- }
1275
- function parseWorkspacesUrlParts(url) {
1276
- if (!isString(url))
1277
- return null;
1278
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
1279
- const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1280
- const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1281
- const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1282
- const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
1283
- if (!match)
1284
- return null;
1285
- return { workspace: match[1], region: match[2] };
1286
- }
1287
-
1288
1346
  var __accessCheck$7 = (obj, member, msg) => {
1289
1347
  if (!member.has(obj))
1290
1348
  throw TypeError("Cannot " + msg);
@@ -2609,60 +2667,6 @@ class XataApiPlugin {
2609
2667
  class XataPlugin {
2610
2668
  }
2611
2669
 
2612
- class FilesPlugin extends XataPlugin {
2613
- build(pluginOptions) {
2614
- return {
2615
- download: async (location) => {
2616
- const { table, record, column, fileId = "" } = location ?? {};
2617
- return await getFileItem({
2618
- pathParams: {
2619
- workspace: "{workspaceId}",
2620
- dbBranchName: "{dbBranch}",
2621
- region: "{region}",
2622
- tableName: table ?? "",
2623
- recordId: record ?? "",
2624
- columnName: column ?? "",
2625
- fileId
2626
- },
2627
- ...pluginOptions,
2628
- rawResponse: true
2629
- });
2630
- },
2631
- upload: async (location, file) => {
2632
- const { table, record, column, fileId = "" } = location ?? {};
2633
- return await putFileItem({
2634
- pathParams: {
2635
- workspace: "{workspaceId}",
2636
- dbBranchName: "{dbBranch}",
2637
- region: "{region}",
2638
- tableName: table ?? "",
2639
- recordId: record ?? "",
2640
- columnName: column ?? "",
2641
- fileId
2642
- },
2643
- body: file,
2644
- ...pluginOptions
2645
- });
2646
- },
2647
- delete: async (location) => {
2648
- const { table, record, column, fileId = "" } = location ?? {};
2649
- return await deleteFileItem({
2650
- pathParams: {
2651
- workspace: "{workspaceId}",
2652
- dbBranchName: "{dbBranch}",
2653
- region: "{region}",
2654
- tableName: table ?? "",
2655
- recordId: record ?? "",
2656
- columnName: column ?? "",
2657
- fileId
2658
- },
2659
- ...pluginOptions
2660
- });
2661
- }
2662
- };
2663
- }
2664
- }
2665
-
2666
2670
  function buildTransformString(transformations) {
2667
2671
  return transformations.flatMap(
2668
2672
  (t) => Object.entries(t).map(([key, value]) => {
@@ -2681,69 +2685,31 @@ function buildTransformString(transformations) {
2681
2685
  function transformImage(url, ...transformations) {
2682
2686
  if (!isDefined(url))
2683
2687
  return void 0;
2684
- const transformationsString = buildTransformString(transformations);
2688
+ const newTransformations = buildTransformString(transformations);
2685
2689
  const { hostname, pathname, search } = new URL(url);
2686
- return `https://${hostname}/transform/${transformationsString}${pathname}${search}`;
2690
+ const pathParts = pathname.split("/");
2691
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2692
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2693
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2694
+ const path = pathParts.join("/");
2695
+ return `https://${hostname}${transform}${path}${search}`;
2687
2696
  }
2688
2697
 
2689
- var __defProp$6 = Object.defineProperty;
2690
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2691
- var __publicField$6 = (obj, key, value) => {
2692
- __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
2693
- return value;
2694
- };
2695
2698
  class XataFile {
2696
2699
  constructor(file) {
2697
- /**
2698
- * Name of this file.
2699
- */
2700
- __publicField$6(this, "name");
2701
- /**
2702
- * Media type of this file.
2703
- */
2704
- __publicField$6(this, "mediaType");
2705
- /**
2706
- * Base64 encoded content of this file.
2707
- */
2708
- __publicField$6(this, "base64Content");
2709
- /**
2710
- * Whether to enable public url for this file.
2711
- */
2712
- __publicField$6(this, "enablePublicUrl");
2713
- /**
2714
- * Timeout for the signed url.
2715
- */
2716
- __publicField$6(this, "signedUrlTimeout");
2717
- /**
2718
- * Size of this file.
2719
- */
2720
- __publicField$6(this, "size");
2721
- /**
2722
- * Version of this file.
2723
- */
2724
- __publicField$6(this, "version");
2725
- /**
2726
- * Url of this file.
2727
- */
2728
- __publicField$6(this, "url");
2729
- /**
2730
- * Signed url of this file.
2731
- */
2732
- __publicField$6(this, "signedUrl");
2733
- /**
2734
- * Attributes of this file.
2735
- */
2736
- __publicField$6(this, "attributes");
2737
- this.name = file.name || "";
2738
- this.mediaType = file.mediaType || "application/octet-stream";
2700
+ this.id = file.id;
2701
+ this.name = file.name;
2702
+ this.mediaType = file.mediaType;
2739
2703
  this.base64Content = file.base64Content;
2740
- this.enablePublicUrl = file.enablePublicUrl ?? false;
2741
- this.signedUrlTimeout = file.signedUrlTimeout ?? 300;
2742
- this.size = file.size ?? 0;
2743
- this.version = file.version ?? 1;
2744
- this.url = file.url || "";
2704
+ this.enablePublicUrl = file.enablePublicUrl;
2705
+ this.signedUrlTimeout = file.signedUrlTimeout;
2706
+ this.uploadUrlTimeout = file.uploadUrlTimeout;
2707
+ this.size = file.size;
2708
+ this.version = file.version;
2709
+ this.url = file.url;
2745
2710
  this.signedUrl = file.signedUrl;
2746
- this.attributes = file.attributes || {};
2711
+ this.uploadUrl = file.uploadUrl;
2712
+ this.attributes = file.attributes;
2747
2713
  }
2748
2714
  static fromBuffer(buffer, options = {}) {
2749
2715
  const base64Content = buffer.toString("base64");
@@ -2795,8 +2761,12 @@ class XataFile {
2795
2761
  if (!this.base64Content) {
2796
2762
  throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2797
2763
  }
2798
- const arrayBuffer = this.toArrayBuffer();
2799
- return new Blob([arrayBuffer], { type: this.mediaType });
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 new Blob([uint8Array], { type: this.mediaType });
2800
2770
  }
2801
2771
  static fromString(string, options = {}) {
2802
2772
  const base64Content = btoa(string);
@@ -2820,15 +2790,26 @@ class XataFile {
2820
2790
  transform(...options) {
2821
2791
  return {
2822
2792
  url: transformImage(this.url, ...options),
2823
- signedUrl: transformImage(this.signedUrl, ...options)
2793
+ signedUrl: transformImage(this.signedUrl, ...options),
2794
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2795
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2824
2796
  };
2825
2797
  }
2826
2798
  }
2827
2799
  const parseInputFileEntry = async (entry) => {
2828
2800
  if (!isDefined(entry))
2829
2801
  return null;
2830
- const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout } = await entry;
2831
- return compactObject({ id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout });
2802
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout, uploadUrlTimeout } = await entry;
2803
+ return compactObject({
2804
+ id,
2805
+ // Name cannot be an empty string in our API
2806
+ name: name ? name : void 0,
2807
+ mediaType,
2808
+ base64Content,
2809
+ enablePublicUrl,
2810
+ signedUrlTimeout,
2811
+ uploadUrlTimeout
2812
+ });
2832
2813
  };
2833
2814
 
2834
2815
  function cleanFilter(filter) {
@@ -2858,12 +2839,25 @@ function cleanFilter(filter) {
2858
2839
  return Object.keys(values).length > 0 ? values : void 0;
2859
2840
  }
2860
2841
 
2861
- var __defProp$5 = Object.defineProperty;
2862
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2863
- var __publicField$5 = (obj, key, value) => {
2864
- __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
2865
- return value;
2866
- };
2842
+ function stringifyJson(value) {
2843
+ if (!isDefined(value))
2844
+ return value;
2845
+ if (isString(value))
2846
+ return value;
2847
+ try {
2848
+ return JSON.stringify(value);
2849
+ } catch (e) {
2850
+ return value;
2851
+ }
2852
+ }
2853
+ function parseJson(value) {
2854
+ try {
2855
+ return JSON.parse(value);
2856
+ } catch (e) {
2857
+ return value;
2858
+ }
2859
+ }
2860
+
2867
2861
  var __accessCheck$6 = (obj, member, msg) => {
2868
2862
  if (!member.has(obj))
2869
2863
  throw TypeError("Cannot " + msg);
@@ -2886,14 +2880,6 @@ var _query, _page;
2886
2880
  class Page {
2887
2881
  constructor(query, meta, records = []) {
2888
2882
  __privateAdd$6(this, _query, void 0);
2889
- /**
2890
- * Page metadata, required to retrieve additional records.
2891
- */
2892
- __publicField$5(this, "meta");
2893
- /**
2894
- * The set of results for this page.
2895
- */
2896
- __publicField$5(this, "records");
2897
2883
  __privateSet$6(this, _query, query);
2898
2884
  this.meta = meta;
2899
2885
  this.records = new RecordArray(this, records);
@@ -2943,9 +2929,9 @@ class Page {
2943
2929
  }
2944
2930
  }
2945
2931
  _query = new WeakMap();
2946
- const PAGINATION_MAX_SIZE = 200;
2932
+ const PAGINATION_MAX_SIZE = 1e3;
2947
2933
  const PAGINATION_DEFAULT_SIZE = 20;
2948
- const PAGINATION_MAX_OFFSET = 800;
2934
+ const PAGINATION_MAX_OFFSET = 49e3;
2949
2935
  const PAGINATION_DEFAULT_OFFSET = 0;
2950
2936
  function isCursorPaginationOptions(options) {
2951
2937
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
@@ -3024,12 +3010,6 @@ const _RecordArray = class _RecordArray extends Array {
3024
3010
  _page = new WeakMap();
3025
3011
  let RecordArray = _RecordArray;
3026
3012
 
3027
- var __defProp$4 = Object.defineProperty;
3028
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3029
- var __publicField$4 = (obj, key, value) => {
3030
- __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
3031
- return value;
3032
- };
3033
3013
  var __accessCheck$5 = (obj, member, msg) => {
3034
3014
  if (!member.has(obj))
3035
3015
  throw TypeError("Cannot " + msg);
@@ -3060,8 +3040,8 @@ const _Query = class _Query {
3060
3040
  __privateAdd$5(this, _repository, void 0);
3061
3041
  __privateAdd$5(this, _data, { filter: {} });
3062
3042
  // Implements pagination
3063
- __publicField$4(this, "meta", { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } });
3064
- __publicField$4(this, "records", new RecordArray(this, []));
3043
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
3044
+ this.records = new RecordArray(this, []);
3065
3045
  __privateSet$5(this, _table$1, table);
3066
3046
  if (repository) {
3067
3047
  __privateSet$5(this, _repository, repository);
@@ -3312,7 +3292,6 @@ const RecordColumnTypes = [
3312
3292
  "email",
3313
3293
  "multiple",
3314
3294
  "link",
3315
- "object",
3316
3295
  "datetime",
3317
3296
  "vector",
3318
3297
  "file[]",
@@ -3328,6 +3307,24 @@ function isXataRecord(x) {
3328
3307
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
3329
3308
  }
3330
3309
 
3310
+ function isValidExpandedColumn(column) {
3311
+ return isObject(column) && isString(column.name);
3312
+ }
3313
+ function isValidSelectableColumns(columns) {
3314
+ if (!Array.isArray(columns)) {
3315
+ return false;
3316
+ }
3317
+ return columns.every((column) => {
3318
+ if (typeof column === "string") {
3319
+ return true;
3320
+ }
3321
+ if (typeof column === "object") {
3322
+ return isValidExpandedColumn(column);
3323
+ }
3324
+ return false;
3325
+ });
3326
+ }
3327
+
3331
3328
  function isSortFilterString(value) {
3332
3329
  return isString(value);
3333
3330
  }
@@ -3428,24 +3425,24 @@ class RestRepository extends Query {
3428
3425
  if (a.length === 0)
3429
3426
  return [];
3430
3427
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
3431
- const columns = isStringArray(b) ? b : ["*"];
3428
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3432
3429
  const result = await this.read(ids, columns);
3433
3430
  return result;
3434
3431
  }
3435
3432
  if (isString(a) && isObject(b)) {
3436
3433
  if (a === "")
3437
3434
  throw new Error("The id can't be empty");
3438
- const columns = isStringArray(c) ? c : void 0;
3435
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3439
3436
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
3440
3437
  }
3441
3438
  if (isObject(a) && isString(a.id)) {
3442
3439
  if (a.id === "")
3443
3440
  throw new Error("The id can't be empty");
3444
- const columns = isStringArray(b) ? b : void 0;
3441
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3445
3442
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
3446
3443
  }
3447
3444
  if (isObject(a)) {
3448
- const columns = isStringArray(b) ? b : void 0;
3445
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3449
3446
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
3450
3447
  }
3451
3448
  throw new Error("Invalid arguments for create method");
@@ -3453,7 +3450,7 @@ class RestRepository extends Query {
3453
3450
  }
3454
3451
  async read(a, b) {
3455
3452
  return __privateGet$4(this, _trace).call(this, "read", async () => {
3456
- const columns = isStringArray(b) ? b : ["*"];
3453
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3457
3454
  if (Array.isArray(a)) {
3458
3455
  if (a.length === 0)
3459
3456
  return [];
@@ -3480,7 +3477,13 @@ class RestRepository extends Query {
3480
3477
  ...__privateGet$4(this, _getFetchProps).call(this)
3481
3478
  });
3482
3479
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3483
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3480
+ return initObject(
3481
+ __privateGet$4(this, _db),
3482
+ schemaTables,
3483
+ __privateGet$4(this, _table),
3484
+ response,
3485
+ columns
3486
+ );
3484
3487
  } catch (e) {
3485
3488
  if (isObject(e) && e.status === 404) {
3486
3489
  return null;
@@ -3522,17 +3525,17 @@ class RestRepository extends Query {
3522
3525
  ifVersion,
3523
3526
  upsert: false
3524
3527
  });
3525
- const columns = isStringArray(b) ? b : ["*"];
3528
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3526
3529
  const result = await this.read(a, columns);
3527
3530
  return result;
3528
3531
  }
3529
3532
  try {
3530
3533
  if (isString(a) && isObject(b)) {
3531
- const columns = isStringArray(c) ? c : void 0;
3534
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3532
3535
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3533
3536
  }
3534
3537
  if (isObject(a) && isString(a.id)) {
3535
- const columns = isStringArray(b) ? b : void 0;
3538
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3536
3539
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3537
3540
  }
3538
3541
  } catch (error) {
@@ -3572,20 +3575,20 @@ class RestRepository extends Query {
3572
3575
  ifVersion,
3573
3576
  upsert: true
3574
3577
  });
3575
- const columns = isStringArray(b) ? b : ["*"];
3578
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3576
3579
  const result = await this.read(a, columns);
3577
3580
  return result;
3578
3581
  }
3579
3582
  if (isString(a) && isObject(b)) {
3580
3583
  if (a === "")
3581
3584
  throw new Error("The id can't be empty");
3582
- const columns = isStringArray(c) ? c : void 0;
3585
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3583
3586
  return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3584
3587
  }
3585
3588
  if (isObject(a) && isString(a.id)) {
3586
3589
  if (a.id === "")
3587
3590
  throw new Error("The id can't be empty");
3588
- const columns = isStringArray(c) ? c : void 0;
3591
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3589
3592
  return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3590
3593
  }
3591
3594
  if (!isDefined(a) && isObject(b)) {
@@ -3604,20 +3607,20 @@ class RestRepository extends Query {
3604
3607
  if (a.length === 0)
3605
3608
  return [];
3606
3609
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
3607
- const columns = isStringArray(b) ? b : ["*"];
3610
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3608
3611
  const result = await this.read(ids, columns);
3609
3612
  return result;
3610
3613
  }
3611
3614
  if (isString(a) && isObject(b)) {
3612
3615
  if (a === "")
3613
3616
  throw new Error("The id can't be empty");
3614
- const columns = isStringArray(c) ? c : void 0;
3617
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3615
3618
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3616
3619
  }
3617
3620
  if (isObject(a) && isString(a.id)) {
3618
3621
  if (a.id === "")
3619
3622
  throw new Error("The id can't be empty");
3620
- const columns = isStringArray(c) ? c : void 0;
3623
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3621
3624
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3622
3625
  }
3623
3626
  if (!isDefined(a) && isObject(b)) {
@@ -3641,7 +3644,7 @@ class RestRepository extends Query {
3641
3644
  return o.id;
3642
3645
  throw new Error("Invalid arguments for delete method");
3643
3646
  });
3644
- const columns = isStringArray(b) ? b : ["*"];
3647
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3645
3648
  const result = await this.read(a, columns);
3646
3649
  await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
3647
3650
  return result;
@@ -3675,7 +3678,7 @@ class RestRepository extends Query {
3675
3678
  }
3676
3679
  async search(query, options = {}) {
3677
3680
  return __privateGet$4(this, _trace).call(this, "search", async () => {
3678
- const { records } = await searchTable({
3681
+ const { records, totalCount } = await searchTable({
3679
3682
  pathParams: {
3680
3683
  workspace: "{workspaceId}",
3681
3684
  dbBranchName: "{dbBranch}",
@@ -3695,12 +3698,15 @@ class RestRepository extends Query {
3695
3698
  ...__privateGet$4(this, _getFetchProps).call(this)
3696
3699
  });
3697
3700
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3698
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3701
+ return {
3702
+ records: records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"])),
3703
+ totalCount
3704
+ };
3699
3705
  });
3700
3706
  }
3701
3707
  async vectorSearch(column, query, options) {
3702
3708
  return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3703
- const { records } = await vectorSearchTable({
3709
+ const { records, totalCount } = await vectorSearchTable({
3704
3710
  pathParams: {
3705
3711
  workspace: "{workspaceId}",
3706
3712
  dbBranchName: "{dbBranch}",
@@ -3717,7 +3723,10 @@ class RestRepository extends Query {
3717
3723
  ...__privateGet$4(this, _getFetchProps).call(this)
3718
3724
  });
3719
3725
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3720
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3726
+ return {
3727
+ records: records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"])),
3728
+ totalCount
3729
+ };
3721
3730
  });
3722
3731
  }
3723
3732
  async aggregate(aggs, filter) {
@@ -3760,7 +3769,13 @@ class RestRepository extends Query {
3760
3769
  });
3761
3770
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3762
3771
  const records = objects.map(
3763
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3772
+ (record) => initObject(
3773
+ __privateGet$4(this, _db),
3774
+ schemaTables,
3775
+ __privateGet$4(this, _table),
3776
+ record,
3777
+ data.columns ?? ["*"]
3778
+ )
3764
3779
  );
3765
3780
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
3766
3781
  return new Page(query, meta, records);
@@ -3787,7 +3802,13 @@ class RestRepository extends Query {
3787
3802
  },
3788
3803
  ...__privateGet$4(this, _getFetchProps).call(this)
3789
3804
  });
3790
- return result;
3805
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3806
+ return {
3807
+ ...result,
3808
+ summaries: result.summaries.map(
3809
+ (summary) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), summary, data.columns ?? [])
3810
+ )
3811
+ };
3791
3812
  });
3792
3813
  }
3793
3814
  ask(question, options) {
@@ -4066,19 +4087,15 @@ transformObjectToApi_fn = async function(object) {
4066
4087
  case "file[]":
4067
4088
  result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4068
4089
  break;
4090
+ case "json":
4091
+ result[key] = stringifyJson(value);
4092
+ break;
4069
4093
  default:
4070
4094
  result[key] = value;
4071
4095
  }
4072
4096
  }
4073
4097
  return result;
4074
4098
  };
4075
- const removeLinksFromObject = (object) => {
4076
- return Object.entries(object).reduce((acc, [key, value]) => {
4077
- if (key === "xata")
4078
- return acc;
4079
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
4080
- }, {});
4081
- };
4082
4099
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
4083
4100
  const data = {};
4084
4101
  const { xata, ...rest } = object ?? {};
@@ -4109,13 +4126,19 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
4109
4126
  if (item === column.name) {
4110
4127
  return [...acc, "*"];
4111
4128
  }
4112
- if (item.startsWith(`${column.name}.`)) {
4129
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
4113
4130
  const [, ...path] = item.split(".");
4114
4131
  return [...acc, path.join(".")];
4115
4132
  }
4116
4133
  return acc;
4117
4134
  }, []);
4118
- data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4135
+ data[column.name] = initObject(
4136
+ db,
4137
+ schemaTables,
4138
+ linkTable,
4139
+ value,
4140
+ selectedLinkColumns
4141
+ );
4119
4142
  } else {
4120
4143
  data[column.name] = null;
4121
4144
  }
@@ -4127,6 +4150,9 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
4127
4150
  case "file[]":
4128
4151
  data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4129
4152
  break;
4153
+ case "json":
4154
+ data[column.name] = parseJson(value);
4155
+ break;
4130
4156
  default:
4131
4157
  data[column.name] = value ?? null;
4132
4158
  if (column.notNull === true && value === null) {
@@ -4136,33 +4162,34 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
4136
4162
  }
4137
4163
  }
4138
4164
  const record = { ...data };
4139
- const serializable = { xata, ...removeLinksFromObject(data) };
4140
4165
  const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
4141
4166
  record.read = function(columns2) {
4142
4167
  return db[table].read(record["id"], columns2);
4143
4168
  };
4144
4169
  record.update = function(data2, b, c) {
4145
- const columns2 = isStringArray(b) ? b : ["*"];
4170
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
4146
4171
  const ifVersion = parseIfVersion(b, c);
4147
4172
  return db[table].update(record["id"], data2, columns2, { ifVersion });
4148
4173
  };
4149
4174
  record.replace = function(data2, b, c) {
4150
- const columns2 = isStringArray(b) ? b : ["*"];
4175
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
4151
4176
  const ifVersion = parseIfVersion(b, c);
4152
4177
  return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
4153
4178
  };
4154
4179
  record.delete = function() {
4155
4180
  return db[table].delete(record["id"]);
4156
4181
  };
4157
- record.xata = Object.freeze(metadata);
4182
+ if (metadata !== void 0) {
4183
+ record.xata = Object.freeze(metadata);
4184
+ }
4158
4185
  record.getMetadata = function() {
4159
4186
  return record.xata;
4160
4187
  };
4161
4188
  record.toSerializable = function() {
4162
- return JSON.parse(JSON.stringify(serializable));
4189
+ return JSON.parse(JSON.stringify(record));
4163
4190
  };
4164
4191
  record.toString = function() {
4165
- return JSON.stringify(serializable);
4192
+ return JSON.stringify(record);
4166
4193
  };
4167
4194
  for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
4168
4195
  Object.defineProperty(record, prop, { enumerable: false });
@@ -4180,7 +4207,7 @@ function extractId(value) {
4180
4207
  function isValidColumn(columns, column) {
4181
4208
  if (columns.includes("*"))
4182
4209
  return true;
4183
- return columns.filter((item) => item.startsWith(column.name)).length > 0;
4210
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
4184
4211
  }
4185
4212
  function parseIfVersion(...args) {
4186
4213
  for (const arg of args) {
@@ -4191,12 +4218,6 @@ function parseIfVersion(...args) {
4191
4218
  return void 0;
4192
4219
  }
4193
4220
 
4194
- var __defProp$3 = Object.defineProperty;
4195
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4196
- var __publicField$3 = (obj, key, value) => {
4197
- __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
4198
- return value;
4199
- };
4200
4221
  var __accessCheck$3 = (obj, member, msg) => {
4201
4222
  if (!member.has(obj))
4202
4223
  throw TypeError("Cannot " + msg);
@@ -4219,8 +4240,6 @@ var _map;
4219
4240
  class SimpleCache {
4220
4241
  constructor(options = {}) {
4221
4242
  __privateAdd$3(this, _map, void 0);
4222
- __publicField$3(this, "capacity");
4223
- __publicField$3(this, "defaultQueryTTL");
4224
4243
  __privateSet$3(this, _map, /* @__PURE__ */ new Map());
4225
4244
  this.capacity = options.max ?? 500;
4226
4245
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
@@ -4265,10 +4284,12 @@ const notExists = (column) => ({ $notExists: column });
4265
4284
  const startsWith = (value) => ({ $startsWith: value });
4266
4285
  const endsWith = (value) => ({ $endsWith: value });
4267
4286
  const pattern = (value) => ({ $pattern: value });
4287
+ const iPattern = (value) => ({ $iPattern: value });
4268
4288
  const is = (value) => ({ $is: value });
4269
4289
  const equals = is;
4270
4290
  const isNot = (value) => ({ $isNot: value });
4271
4291
  const contains = (value) => ({ $contains: value });
4292
+ const iContains = (value) => ({ $iContains: value });
4272
4293
  const includes = (value) => ({ $includes: value });
4273
4294
  const includesAll = (value) => ({ $includesAll: value });
4274
4295
  const includesNone = (value) => ({ $includesNone: value });
@@ -4324,6 +4345,80 @@ class SchemaPlugin extends XataPlugin {
4324
4345
  _tables = new WeakMap();
4325
4346
  _schemaTables$1 = new WeakMap();
4326
4347
 
4348
+ class FilesPlugin extends XataPlugin {
4349
+ build(pluginOptions) {
4350
+ return {
4351
+ download: async (location) => {
4352
+ const { table, record, column, fileId = "" } = location ?? {};
4353
+ return await getFileItem({
4354
+ pathParams: {
4355
+ workspace: "{workspaceId}",
4356
+ dbBranchName: "{dbBranch}",
4357
+ region: "{region}",
4358
+ tableName: table ?? "",
4359
+ recordId: record ?? "",
4360
+ columnName: column ?? "",
4361
+ fileId
4362
+ },
4363
+ ...pluginOptions,
4364
+ rawResponse: true
4365
+ });
4366
+ },
4367
+ upload: async (location, file, options) => {
4368
+ const { table, record, column, fileId = "" } = location ?? {};
4369
+ const resolvedFile = await file;
4370
+ const contentType = options?.mediaType || getContentType(resolvedFile);
4371
+ const body = resolvedFile instanceof XataFile ? resolvedFile.toBlob() : resolvedFile;
4372
+ return await putFileItem({
4373
+ ...pluginOptions,
4374
+ pathParams: {
4375
+ workspace: "{workspaceId}",
4376
+ dbBranchName: "{dbBranch}",
4377
+ region: "{region}",
4378
+ tableName: table ?? "",
4379
+ recordId: record ?? "",
4380
+ columnName: column ?? "",
4381
+ fileId
4382
+ },
4383
+ body,
4384
+ headers: { "Content-Type": contentType }
4385
+ });
4386
+ },
4387
+ delete: async (location) => {
4388
+ const { table, record, column, fileId = "" } = location ?? {};
4389
+ return await deleteFileItem({
4390
+ pathParams: {
4391
+ workspace: "{workspaceId}",
4392
+ dbBranchName: "{dbBranch}",
4393
+ region: "{region}",
4394
+ tableName: table ?? "",
4395
+ recordId: record ?? "",
4396
+ columnName: column ?? "",
4397
+ fileId
4398
+ },
4399
+ ...pluginOptions
4400
+ });
4401
+ }
4402
+ };
4403
+ }
4404
+ }
4405
+ function getContentType(file) {
4406
+ if (typeof file === "string") {
4407
+ return "text/plain";
4408
+ }
4409
+ if ("mediaType" in file && file.mediaType !== void 0) {
4410
+ return file.mediaType;
4411
+ }
4412
+ if (isBlob(file)) {
4413
+ return file.type;
4414
+ }
4415
+ try {
4416
+ return file.type;
4417
+ } catch (e) {
4418
+ }
4419
+ return "application/octet-stream";
4420
+ }
4421
+
4327
4422
  var __accessCheck$1 = (obj, member, msg) => {
4328
4423
  if (!member.has(obj))
4329
4424
  throw TypeError("Cannot " + msg);
@@ -4359,22 +4454,26 @@ class SearchPlugin extends XataPlugin {
4359
4454
  build(pluginOptions) {
4360
4455
  return {
4361
4456
  all: async (query, options = {}) => {
4362
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4457
+ const { records, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4363
4458
  const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
4364
- return records.map((record) => {
4365
- const { table = "orphan" } = record.xata;
4366
- return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
4367
- });
4459
+ return {
4460
+ totalCount,
4461
+ records: records.map((record) => {
4462
+ const { table = "orphan" } = record.xata;
4463
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
4464
+ })
4465
+ };
4368
4466
  },
4369
4467
  byTable: async (query, options = {}) => {
4370
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4468
+ const { records: rawRecords, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4371
4469
  const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
4372
- return records.reduce((acc, record) => {
4470
+ const records = rawRecords.reduce((acc, record) => {
4373
4471
  const { table = "orphan" } = record.xata;
4374
4472
  const items = acc[table] ?? [];
4375
4473
  const item = initObject(this.db, schemaTables, table, record, ["*"]);
4376
4474
  return { ...acc, [table]: [...items, item] };
4377
4475
  }, {});
4476
+ return { totalCount, records };
4378
4477
  }
4379
4478
  };
4380
4479
  }
@@ -4383,13 +4482,13 @@ _schemaTables = new WeakMap();
4383
4482
  _search = new WeakSet();
4384
4483
  search_fn = async function(query, options, pluginOptions) {
4385
4484
  const { tables, fuzziness, highlight, prefix, page } = options ?? {};
4386
- const { records } = await searchBranch({
4485
+ const { records, totalCount } = await searchBranch({
4387
4486
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4388
4487
  // @ts-ignore https://github.com/xataio/client-ts/issues/313
4389
4488
  body: { tables, query, fuzziness, prefix, highlight, page },
4390
4489
  ...pluginOptions
4391
4490
  });
4392
- return records;
4491
+ return { records, totalCount };
4393
4492
  };
4394
4493
  _getSchemaTables = new WeakSet();
4395
4494
  getSchemaTables_fn = async function(pluginOptions) {
@@ -4464,6 +4563,11 @@ function prepareParams(param1, param2) {
4464
4563
  class SQLPlugin extends XataPlugin {
4465
4564
  build(pluginOptions) {
4466
4565
  return async (param1, ...param2) => {
4566
+ if (!isParamsObject(param1) && (!isTemplateStringsArray(param1) || !Array.isArray(param2))) {
4567
+ throw new Error(
4568
+ "Calling `xata.sql` as a function is not safe. Make sure to use it as a tagged template or with an object."
4569
+ );
4570
+ }
4467
4571
  const { statement, params, consistency } = prepareParams(param1, param2);
4468
4572
  const { records, warning } = await sqlQuery({
4469
4573
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
@@ -4474,6 +4578,12 @@ class SQLPlugin extends XataPlugin {
4474
4578
  };
4475
4579
  }
4476
4580
  }
4581
+ function isTemplateStringsArray(strings) {
4582
+ return Array.isArray(strings) && "raw" in strings && Array.isArray(strings.raw);
4583
+ }
4584
+ function isParamsObject(params) {
4585
+ return isObject(params) && "statement" in params;
4586
+ }
4477
4587
 
4478
4588
  class TransactionPlugin extends XataPlugin {
4479
4589
  build(pluginOptions) {
@@ -4490,12 +4600,6 @@ class TransactionPlugin extends XataPlugin {
4490
4600
  }
4491
4601
  }
4492
4602
 
4493
- var __defProp$2 = Object.defineProperty;
4494
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4495
- var __publicField$2 = (obj, key, value) => {
4496
- __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
4497
- return value;
4498
- };
4499
4603
  var __accessCheck = (obj, member, msg) => {
4500
4604
  if (!member.has(obj))
4501
4605
  throw TypeError("Cannot " + msg);
@@ -4525,11 +4629,6 @@ const buildClient = (plugins) => {
4525
4629
  __privateAdd(this, _parseOptions);
4526
4630
  __privateAdd(this, _getFetchProps);
4527
4631
  __privateAdd(this, _options, void 0);
4528
- __publicField$2(this, "db");
4529
- __publicField$2(this, "search");
4530
- __publicField$2(this, "transactions");
4531
- __publicField$2(this, "sql");
4532
- __publicField$2(this, "files");
4533
4632
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
4534
4633
  __privateSet(this, _options, safeOptions);
4535
4634
  const pluginOptions = {
@@ -4643,17 +4742,11 @@ const buildClient = (plugins) => {
4643
4742
  class BaseClient extends buildClient() {
4644
4743
  }
4645
4744
 
4646
- var __defProp$1 = Object.defineProperty;
4647
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4648
- var __publicField$1 = (obj, key, value) => {
4649
- __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
4650
- return value;
4651
- };
4652
4745
  const META = "__";
4653
4746
  const VALUE = "___";
4654
4747
  class Serializer {
4655
4748
  constructor() {
4656
- __publicField$1(this, "classes", {});
4749
+ this.classes = {};
4657
4750
  }
4658
4751
  add(clazz) {
4659
4752
  this.classes[clazz.name] = clazz;
@@ -4716,34 +4809,12 @@ const deserialize = (json) => {
4716
4809
  return defaultSerializer.fromJSON(json);
4717
4810
  };
4718
4811
 
4719
- function buildWorkerRunner(config) {
4720
- return function xataWorker(name, worker) {
4721
- return async (...args) => {
4722
- const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
4723
- const result = await fetch(url, {
4724
- method: "POST",
4725
- headers: { "Content-Type": "application/json" },
4726
- body: serialize({ args })
4727
- });
4728
- const text = await result.text();
4729
- return deserialize(text);
4730
- };
4731
- };
4732
- }
4733
-
4734
- var __defProp = Object.defineProperty;
4735
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4736
- var __publicField = (obj, key, value) => {
4737
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4738
- return value;
4739
- };
4740
4812
  class XataError extends Error {
4741
4813
  constructor(message, status) {
4742
4814
  super(message);
4743
- __publicField(this, "status");
4744
4815
  this.status = status;
4745
4816
  }
4746
4817
  }
4747
4818
 
4748
- 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, 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, 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, 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, transformImage, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateOAuthAccessToken, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID, vectorSearchTable };
4819
+ export { BaseClient, FetcherError, FilesPlugin, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, RecordColumnTypes, Repository, RestRepository, SQLPlugin, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, TransactionPlugin, XataApiClient, XataApiPlugin, XataError, XataFile, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, applyMigration, askTable, askTableSession, branchTransaction, buildClient, buildPreviewBranchName, buildProviderString, 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, fileUpload, ge, getAPIKey, getAuthorizationCode, getBranch, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getCluster, getColumn, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getFile, getFileItem, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getPreviewBranch, getRecord, getSchema, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getUserOAuthAccessTokens, getUserOAuthClients, getWorkspace, getWorkspaceMembersList, getWorkspacesList, grantAuthorizationCode, greaterEquals, greaterThan, greaterThanEquals, gt, gte, iContains, iPattern, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isValidExpandedColumn, isValidSelectableColumns, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listClusters, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, pgRollJobStatus, pgRollMigrationHistory, pgRollStatus, 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 };
4749
4820
  //# sourceMappingURL=index.mjs.map