@xata.io/client 0.0.0-alpha.vfd071d9 → 0.0.0-alpha.vfd6aaf3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -11,14 +11,18 @@ function compact(arr) {
11
11
  function isObject(value) {
12
12
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
13
13
  }
14
+ function isDefined(value) {
15
+ return value !== null && value !== void 0;
16
+ }
14
17
  function isString(value) {
15
- return value !== void 0 && value !== null && typeof value === "string";
18
+ return isDefined(value) && typeof value === "string";
16
19
  }
17
20
  function toBase64(value) {
18
21
  try {
19
22
  return btoa(value);
20
23
  } catch (err) {
21
- return Buffer.from(value).toString("base64");
24
+ const buf = Buffer;
25
+ return buf.from(value).toString("base64");
22
26
  }
23
27
  }
24
28
 
@@ -74,16 +78,28 @@ function getFetchImplementation(userFetch) {
74
78
  return fetchImpl;
75
79
  }
76
80
 
77
- class FetcherError extends Error {
78
- constructor(status, data) {
81
+ const VERSION = "0.0.0-alpha.vfd6aaf3";
82
+
83
+ class ErrorWithCause extends Error {
84
+ constructor(message, options) {
85
+ super(message, options);
86
+ }
87
+ }
88
+ class FetcherError extends ErrorWithCause {
89
+ constructor(status, data, requestId) {
79
90
  super(getMessage(data));
80
91
  this.status = status;
81
92
  this.errors = isBulkError(data) ? data.errors : void 0;
93
+ this.requestId = requestId;
82
94
  if (data instanceof Error) {
83
95
  this.stack = data.stack;
84
96
  this.cause = data.cause;
85
97
  }
86
98
  }
99
+ toString() {
100
+ const error = super.toString();
101
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
102
+ }
87
103
  }
88
104
  function isBulkError(error) {
89
105
  return isObject(error) && Array.isArray(error.errors);
@@ -106,7 +122,12 @@ function getMessage(data) {
106
122
  }
107
123
 
108
124
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
109
- const query = new URLSearchParams(queryParams).toString();
125
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
126
+ if (value === void 0 || value === null)
127
+ return acc;
128
+ return { ...acc, [key]: value };
129
+ }, {});
130
+ const query = new URLSearchParams(cleanQueryParams).toString();
110
131
  const queryString = query.length > 0 ? `?${query}` : "";
111
132
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
112
133
  };
@@ -146,6 +167,7 @@ async function fetch$1({
146
167
  body: body ? JSON.stringify(body) : void 0,
147
168
  headers: {
148
169
  "Content-Type": "application/json",
170
+ "User-Agent": `Xata client-ts/${VERSION}`,
149
171
  ...headers,
150
172
  ...hostHeader(fullUrl),
151
173
  Authorization: `Bearer ${apiKey}`
@@ -154,14 +176,15 @@ async function fetch$1({
154
176
  if (response.status === 204) {
155
177
  return {};
156
178
  }
179
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
157
180
  try {
158
181
  const jsonResponse = await response.json();
159
182
  if (response.ok) {
160
183
  return jsonResponse;
161
184
  }
162
- throw new FetcherError(response.status, jsonResponse);
185
+ throw new FetcherError(response.status, jsonResponse, requestId);
163
186
  } catch (error) {
164
- throw new FetcherError(response.status, error);
187
+ throw new FetcherError(response.status, error, requestId);
165
188
  }
166
189
  }
167
190
 
@@ -370,6 +393,11 @@ const queryTable = (variables) => fetch$1({
370
393
  method: "post",
371
394
  ...variables
372
395
  });
396
+ const searchTable = (variables) => fetch$1({
397
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
398
+ method: "post",
399
+ ...variables
400
+ });
373
401
  const searchBranch = (variables) => fetch$1({
374
402
  url: "/db/{dbBranchName}/search",
375
403
  method: "post",
@@ -433,6 +461,7 @@ const operationsByTag = {
433
461
  getRecord,
434
462
  bulkInsertTableRecords,
435
463
  queryTable,
464
+ searchTable,
436
465
  searchBranch
437
466
  }
438
467
  };
@@ -466,7 +495,7 @@ var __accessCheck$7 = (obj, member, msg) => {
466
495
  if (!member.has(obj))
467
496
  throw TypeError("Cannot " + msg);
468
497
  };
469
- var __privateGet$6 = (obj, member, getter) => {
498
+ var __privateGet$7 = (obj, member, getter) => {
470
499
  __accessCheck$7(obj, member, "read from private field");
471
500
  return getter ? getter.call(obj) : member.get(obj);
472
501
  };
@@ -475,7 +504,7 @@ var __privateAdd$7 = (obj, member, value) => {
475
504
  throw TypeError("Cannot add the same private member more than once");
476
505
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
477
506
  };
478
- var __privateSet$5 = (obj, member, value, setter) => {
507
+ var __privateSet$6 = (obj, member, value, setter) => {
479
508
  __accessCheck$7(obj, member, "write to private field");
480
509
  setter ? setter.call(obj, value) : member.set(obj, value);
481
510
  return value;
@@ -490,7 +519,7 @@ class XataApiClient {
490
519
  if (!apiKey) {
491
520
  throw new Error("Could not resolve a valid apiKey");
492
521
  }
493
- __privateSet$5(this, _extraProps, {
522
+ __privateSet$6(this, _extraProps, {
494
523
  apiUrl: getHostUrl(provider, "main"),
495
524
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
496
525
  fetchImpl: getFetchImplementation(options.fetch),
@@ -498,34 +527,34 @@ class XataApiClient {
498
527
  });
499
528
  }
500
529
  get user() {
501
- if (!__privateGet$6(this, _namespaces).user)
502
- __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
503
- return __privateGet$6(this, _namespaces).user;
530
+ if (!__privateGet$7(this, _namespaces).user)
531
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
532
+ return __privateGet$7(this, _namespaces).user;
504
533
  }
505
534
  get workspaces() {
506
- if (!__privateGet$6(this, _namespaces).workspaces)
507
- __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
508
- return __privateGet$6(this, _namespaces).workspaces;
535
+ if (!__privateGet$7(this, _namespaces).workspaces)
536
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
537
+ return __privateGet$7(this, _namespaces).workspaces;
509
538
  }
510
539
  get databases() {
511
- if (!__privateGet$6(this, _namespaces).databases)
512
- __privateGet$6(this, _namespaces).databases = new DatabaseApi(__privateGet$6(this, _extraProps));
513
- return __privateGet$6(this, _namespaces).databases;
540
+ if (!__privateGet$7(this, _namespaces).databases)
541
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
542
+ return __privateGet$7(this, _namespaces).databases;
514
543
  }
515
544
  get branches() {
516
- if (!__privateGet$6(this, _namespaces).branches)
517
- __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
518
- return __privateGet$6(this, _namespaces).branches;
545
+ if (!__privateGet$7(this, _namespaces).branches)
546
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
547
+ return __privateGet$7(this, _namespaces).branches;
519
548
  }
520
549
  get tables() {
521
- if (!__privateGet$6(this, _namespaces).tables)
522
- __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
523
- return __privateGet$6(this, _namespaces).tables;
550
+ if (!__privateGet$7(this, _namespaces).tables)
551
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
552
+ return __privateGet$7(this, _namespaces).tables;
524
553
  }
525
554
  get records() {
526
- if (!__privateGet$6(this, _namespaces).records)
527
- __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
528
- return __privateGet$6(this, _namespaces).records;
555
+ if (!__privateGet$7(this, _namespaces).records)
556
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
557
+ return __privateGet$7(this, _namespaces).records;
529
558
  }
530
559
  }
531
560
  _extraProps = new WeakMap();
@@ -679,10 +708,10 @@ class DatabaseApi {
679
708
  ...this.extraProps
680
709
  });
681
710
  }
682
- resolveBranch(workspace, dbName, gitBranch) {
711
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
683
712
  return operationsByTag.database.resolveBranch({
684
713
  pathParams: { workspace, dbName },
685
- queryParams: { gitBranch },
714
+ queryParams: { gitBranch, fallbackBranch },
686
715
  ...this.extraProps
687
716
  });
688
717
  }
@@ -703,10 +732,10 @@ class BranchApi {
703
732
  ...this.extraProps
704
733
  });
705
734
  }
706
- createBranch(workspace, database, branch, from = "", options = {}) {
735
+ createBranch(workspace, database, branch, from, options = {}) {
707
736
  return operationsByTag.branch.createBranch({
708
737
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
709
- queryParams: { from },
738
+ queryParams: isString(from) ? { from } : void 0,
710
739
  body: options,
711
740
  ...this.extraProps
712
741
  });
@@ -888,6 +917,13 @@ class RecordsApi {
888
917
  ...this.extraProps
889
918
  });
890
919
  }
920
+ searchTable(workspace, database, branch, tableName, query) {
921
+ return operationsByTag.records.searchTable({
922
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
923
+ body: query,
924
+ ...this.extraProps
925
+ });
926
+ }
891
927
  searchBranch(workspace, database, branch, query) {
892
928
  return operationsByTag.records.searchBranch({
893
929
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -911,7 +947,7 @@ var __accessCheck$6 = (obj, member, msg) => {
911
947
  if (!member.has(obj))
912
948
  throw TypeError("Cannot " + msg);
913
949
  };
914
- var __privateGet$5 = (obj, member, getter) => {
950
+ var __privateGet$6 = (obj, member, getter) => {
915
951
  __accessCheck$6(obj, member, "read from private field");
916
952
  return getter ? getter.call(obj) : member.get(obj);
917
953
  };
@@ -920,30 +956,30 @@ var __privateAdd$6 = (obj, member, value) => {
920
956
  throw TypeError("Cannot add the same private member more than once");
921
957
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
922
958
  };
923
- var __privateSet$4 = (obj, member, value, setter) => {
959
+ var __privateSet$5 = (obj, member, value, setter) => {
924
960
  __accessCheck$6(obj, member, "write to private field");
925
961
  setter ? setter.call(obj, value) : member.set(obj, value);
926
962
  return value;
927
963
  };
928
- var _query;
964
+ var _query, _page;
929
965
  class Page {
930
966
  constructor(query, meta, records = []) {
931
967
  __privateAdd$6(this, _query, void 0);
932
- __privateSet$4(this, _query, query);
968
+ __privateSet$5(this, _query, query);
933
969
  this.meta = meta;
934
- this.records = records;
970
+ this.records = new RecordArray(this, records);
935
971
  }
936
972
  async nextPage(size, offset) {
937
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
973
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
938
974
  }
939
975
  async previousPage(size, offset) {
940
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
976
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
941
977
  }
942
978
  async firstPage(size, offset) {
943
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
979
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
944
980
  }
945
981
  async lastPage(size, offset) {
946
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
982
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
947
983
  }
948
984
  hasNextPage() {
949
985
  return this.meta.page.more;
@@ -951,15 +987,56 @@ class Page {
951
987
  }
952
988
  _query = new WeakMap();
953
989
  const PAGINATION_MAX_SIZE = 200;
954
- const PAGINATION_DEFAULT_SIZE = 200;
990
+ const PAGINATION_DEFAULT_SIZE = 20;
955
991
  const PAGINATION_MAX_OFFSET = 800;
956
992
  const PAGINATION_DEFAULT_OFFSET = 0;
993
+ function isCursorPaginationOptions(options) {
994
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
995
+ }
996
+ const _RecordArray = class extends Array {
997
+ constructor(page, overrideRecords) {
998
+ super(..._RecordArray.parseConstructorParams(page, overrideRecords));
999
+ __privateAdd$6(this, _page, void 0);
1000
+ __privateSet$5(this, _page, page);
1001
+ }
1002
+ static parseConstructorParams(...args) {
1003
+ if (args.length === 1 && typeof args[0] === "number") {
1004
+ return new Array(args[0]);
1005
+ }
1006
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1007
+ const result = args[1] ?? args[0].records ?? [];
1008
+ return new Array(...result);
1009
+ }
1010
+ return new Array(...args);
1011
+ }
1012
+ async nextPage(size, offset) {
1013
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1014
+ return new _RecordArray(newPage);
1015
+ }
1016
+ async previousPage(size, offset) {
1017
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1018
+ return new _RecordArray(newPage);
1019
+ }
1020
+ async firstPage(size, offset) {
1021
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1022
+ return new _RecordArray(newPage);
1023
+ }
1024
+ async lastPage(size, offset) {
1025
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1026
+ return new _RecordArray(newPage);
1027
+ }
1028
+ hasNextPage() {
1029
+ return __privateGet$6(this, _page).meta.page.more;
1030
+ }
1031
+ };
1032
+ let RecordArray = _RecordArray;
1033
+ _page = new WeakMap();
957
1034
 
958
1035
  var __accessCheck$5 = (obj, member, msg) => {
959
1036
  if (!member.has(obj))
960
1037
  throw TypeError("Cannot " + msg);
961
1038
  };
962
- var __privateGet$4 = (obj, member, getter) => {
1039
+ var __privateGet$5 = (obj, member, getter) => {
963
1040
  __accessCheck$5(obj, member, "read from private field");
964
1041
  return getter ? getter.call(obj) : member.get(obj);
965
1042
  };
@@ -968,34 +1045,35 @@ var __privateAdd$5 = (obj, member, value) => {
968
1045
  throw TypeError("Cannot add the same private member more than once");
969
1046
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
970
1047
  };
971
- var __privateSet$3 = (obj, member, value, setter) => {
1048
+ var __privateSet$4 = (obj, member, value, setter) => {
972
1049
  __accessCheck$5(obj, member, "write to private field");
973
1050
  setter ? setter.call(obj, value) : member.set(obj, value);
974
1051
  return value;
975
1052
  };
976
1053
  var _table$1, _repository, _data;
977
1054
  const _Query = class {
978
- constructor(repository, table, data, parent) {
1055
+ constructor(repository, table, data, rawParent) {
979
1056
  __privateAdd$5(this, _table$1, void 0);
980
1057
  __privateAdd$5(this, _repository, void 0);
981
1058
  __privateAdd$5(this, _data, { filter: {} });
982
1059
  this.meta = { page: { cursor: "start", more: true } };
983
- this.records = [];
984
- __privateSet$3(this, _table$1, table);
1060
+ this.records = new RecordArray(this, []);
1061
+ __privateSet$4(this, _table$1, table);
985
1062
  if (repository) {
986
- __privateSet$3(this, _repository, repository);
1063
+ __privateSet$4(this, _repository, repository);
987
1064
  } else {
988
- __privateSet$3(this, _repository, this);
1065
+ __privateSet$4(this, _repository, this);
989
1066
  }
990
- __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
991
- __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
992
- __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
993
- __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
994
- __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
995
- __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
996
- __privateGet$4(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
997
- __privateGet$4(this, _data).page = data.page ?? parent?.page;
998
- __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
1067
+ const parent = cleanParent(data, rawParent);
1068
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1069
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1070
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1071
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1072
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1073
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1074
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1075
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1076
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
999
1077
  this.any = this.any.bind(this);
1000
1078
  this.all = this.all.bind(this);
1001
1079
  this.not = this.not.bind(this);
@@ -1006,83 +1084,88 @@ const _Query = class {
1006
1084
  Object.defineProperty(this, "repository", { enumerable: false });
1007
1085
  }
1008
1086
  getQueryOptions() {
1009
- return __privateGet$4(this, _data);
1087
+ return __privateGet$5(this, _data);
1010
1088
  }
1011
1089
  key() {
1012
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$4(this, _data);
1013
- const key = JSON.stringify({ columns, filter, sort, page });
1090
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1091
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1014
1092
  return toBase64(key);
1015
1093
  }
1016
1094
  any(...queries) {
1017
1095
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1018
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
1096
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
1019
1097
  }
1020
1098
  all(...queries) {
1021
1099
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1022
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1100
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1023
1101
  }
1024
1102
  not(...queries) {
1025
1103
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1026
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
1104
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
1027
1105
  }
1028
1106
  none(...queries) {
1029
1107
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1030
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
1108
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
1031
1109
  }
1032
1110
  filter(a, b) {
1033
1111
  if (arguments.length === 1) {
1034
1112
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1035
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
1036
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1113
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1114
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1037
1115
  } else {
1038
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1039
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1116
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1117
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1040
1118
  }
1041
1119
  }
1042
1120
  sort(column, direction) {
1043
- const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
1121
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1044
1122
  const sort = [...originalSort, { column, direction }];
1045
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
1123
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1046
1124
  }
1047
1125
  select(columns) {
1048
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { columns }, __privateGet$4(this, _data));
1126
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1049
1127
  }
1050
1128
  getPaginated(options = {}) {
1051
- const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
1052
- return __privateGet$4(this, _repository).query(query);
1129
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1130
+ return __privateGet$5(this, _repository).query(query);
1053
1131
  }
1054
1132
  async *[Symbol.asyncIterator]() {
1055
- for await (const [record] of this.getIterator(1)) {
1133
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1056
1134
  yield record;
1057
1135
  }
1058
1136
  }
1059
- async *getIterator(chunk, options = {}) {
1060
- let offset = 0;
1061
- let end = false;
1062
- while (!end) {
1063
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1064
- yield records;
1065
- offset += chunk;
1066
- end = !meta.page.more;
1137
+ async *getIterator(options = {}) {
1138
+ const { batchSize = 1 } = options;
1139
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1140
+ let more = page.hasNextPage();
1141
+ yield page.records;
1142
+ while (more) {
1143
+ page = await page.nextPage();
1144
+ more = page.hasNextPage();
1145
+ yield page.records;
1067
1146
  }
1068
1147
  }
1069
1148
  async getMany(options = {}) {
1070
- const { records } = await this.getPaginated(options);
1071
- return records;
1149
+ const page = await this.getPaginated(options);
1150
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1151
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1152
+ }
1153
+ return page.records;
1072
1154
  }
1073
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1155
+ async getAll(options = {}) {
1156
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1074
1157
  const results = [];
1075
- for await (const page of this.getIterator(chunk, options)) {
1158
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1076
1159
  results.push(...page);
1077
1160
  }
1078
1161
  return results;
1079
1162
  }
1080
1163
  async getFirst(options = {}) {
1081
- const records = await this.getMany({ ...options, page: { size: 1 } });
1082
- return records[0] || null;
1164
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1165
+ return records[0] ?? null;
1083
1166
  }
1084
1167
  cache(ttl) {
1085
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
1168
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1086
1169
  }
1087
1170
  nextPage(size, offset) {
1088
1171
  return this.firstPage(size, offset);
@@ -1091,10 +1174,10 @@ const _Query = class {
1091
1174
  return this.firstPage(size, offset);
1092
1175
  }
1093
1176
  firstPage(size, offset) {
1094
- return this.getPaginated({ page: { size, offset } });
1177
+ return this.getPaginated({ pagination: { size, offset } });
1095
1178
  }
1096
1179
  lastPage(size, offset) {
1097
- return this.getPaginated({ page: { size, offset, before: "end" } });
1180
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1098
1181
  }
1099
1182
  hasNextPage() {
1100
1183
  return this.meta.page.more;
@@ -1104,12 +1187,20 @@ let Query = _Query;
1104
1187
  _table$1 = new WeakMap();
1105
1188
  _repository = new WeakMap();
1106
1189
  _data = new WeakMap();
1190
+ function cleanParent(data, parent) {
1191
+ if (isCursorPaginationOptions(data.pagination)) {
1192
+ return { ...parent, sorting: void 0, filter: void 0 };
1193
+ }
1194
+ return parent;
1195
+ }
1107
1196
 
1108
1197
  function isIdentifiable(x) {
1109
1198
  return isObject(x) && isString(x?.id);
1110
1199
  }
1111
1200
  function isXataRecord(x) {
1112
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1201
+ const record = x;
1202
+ const metadata = record?.getMetadata();
1203
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1113
1204
  }
1114
1205
 
1115
1206
  function isSortFilterString(value) {
@@ -1139,7 +1230,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1139
1230
  if (!member.has(obj))
1140
1231
  throw TypeError("Cannot " + msg);
1141
1232
  };
1142
- var __privateGet$3 = (obj, member, getter) => {
1233
+ var __privateGet$4 = (obj, member, getter) => {
1143
1234
  __accessCheck$4(obj, member, "read from private field");
1144
1235
  return getter ? getter.call(obj) : member.get(obj);
1145
1236
  };
@@ -1148,7 +1239,7 @@ var __privateAdd$4 = (obj, member, value) => {
1148
1239
  throw TypeError("Cannot add the same private member more than once");
1149
1240
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1150
1241
  };
1151
- var __privateSet$2 = (obj, member, value, setter) => {
1242
+ var __privateSet$3 = (obj, member, value, setter) => {
1152
1243
  __accessCheck$4(obj, member, "write to private field");
1153
1244
  setter ? setter.call(obj, value) : member.set(obj, value);
1154
1245
  return value;
@@ -1157,7 +1248,7 @@ var __privateMethod$2 = (obj, member, method) => {
1157
1248
  __accessCheck$4(obj, member, "access private method");
1158
1249
  return method;
1159
1250
  };
1160
- var _table, _links, _getFetchProps, _cache, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn;
1251
+ var _table, _getFetchProps, _cache, _schema$1, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchema$1, getSchema_fn$1;
1161
1252
  class Repository extends Query {
1162
1253
  }
1163
1254
  class RestRepository extends Query {
@@ -1174,21 +1265,43 @@ class RestRepository extends Query {
1174
1265
  __privateAdd$4(this, _getCacheRecord);
1175
1266
  __privateAdd$4(this, _setCacheQuery);
1176
1267
  __privateAdd$4(this, _getCacheQuery);
1268
+ __privateAdd$4(this, _getSchema$1);
1177
1269
  __privateAdd$4(this, _table, void 0);
1178
- __privateAdd$4(this, _links, void 0);
1179
1270
  __privateAdd$4(this, _getFetchProps, void 0);
1180
1271
  __privateAdd$4(this, _cache, void 0);
1181
- __privateSet$2(this, _table, options.table);
1182
- __privateSet$2(this, _links, options.links ?? {});
1183
- __privateSet$2(this, _getFetchProps, options.pluginOptions.getFetchProps);
1272
+ __privateAdd$4(this, _schema$1, void 0);
1273
+ __privateSet$3(this, _table, options.table);
1274
+ __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1184
1275
  this.db = options.db;
1185
- __privateSet$2(this, _cache, options.pluginOptions.cache);
1276
+ __privateSet$3(this, _cache, options.pluginOptions.cache);
1186
1277
  }
1187
1278
  async create(a, b) {
1188
1279
  if (Array.isArray(a)) {
1189
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1190
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1191
- return records;
1280
+ if (a.length === 0)
1281
+ return [];
1282
+ const [itemsWithoutIds, itemsWithIds, order] = a.reduce(([accWithoutIds, accWithIds, accOrder], item) => {
1283
+ const condition = isString(item.id);
1284
+ accOrder.push(condition);
1285
+ if (condition) {
1286
+ accWithIds.push(item);
1287
+ } else {
1288
+ accWithoutIds.push(item);
1289
+ }
1290
+ return [accWithoutIds, accWithIds, accOrder];
1291
+ }, [[], [], []]);
1292
+ const recordsWithoutId = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, itemsWithoutIds);
1293
+ await Promise.all(recordsWithoutId.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1294
+ if (itemsWithIds.length > 100) {
1295
+ console.warn("Bulk create operation with id is not optimized in the Xata API yet, this request might be slow");
1296
+ }
1297
+ const recordsWithId = await Promise.all(itemsWithIds.map((object) => this.create(object)));
1298
+ return order.map((condition) => {
1299
+ if (condition) {
1300
+ return recordsWithId.shift();
1301
+ } else {
1302
+ return recordsWithoutId.shift();
1303
+ }
1304
+ }).filter((record) => !!record);
1192
1305
  }
1193
1306
  if (isString(a) && isObject(b)) {
1194
1307
  if (a === "")
@@ -1211,26 +1324,38 @@ class RestRepository extends Query {
1211
1324
  }
1212
1325
  throw new Error("Invalid arguments for create method");
1213
1326
  }
1214
- async read(recordId) {
1215
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1216
- if (cacheRecord)
1217
- return cacheRecord;
1218
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1219
- try {
1220
- const response = await getRecord({
1221
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1222
- ...fetchProps
1223
- });
1224
- return initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), response);
1225
- } catch (e) {
1226
- if (isObject(e) && e.status === 404) {
1227
- return null;
1327
+ async read(a) {
1328
+ if (Array.isArray(a)) {
1329
+ if (a.length === 0)
1330
+ return [];
1331
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1332
+ return this.getAll({ filter: { id: { $any: ids } } });
1333
+ }
1334
+ const id = isString(a) ? a : a.id;
1335
+ if (isString(id)) {
1336
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1337
+ if (cacheRecord)
1338
+ return cacheRecord;
1339
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1340
+ try {
1341
+ const response = await getRecord({
1342
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1343
+ ...fetchProps
1344
+ });
1345
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1346
+ return initObject(this.db, schema, __privateGet$4(this, _table), response);
1347
+ } catch (e) {
1348
+ if (isObject(e) && e.status === 404) {
1349
+ return null;
1350
+ }
1351
+ throw e;
1228
1352
  }
1229
- throw e;
1230
1353
  }
1231
1354
  }
1232
1355
  async update(a, b) {
1233
1356
  if (Array.isArray(a)) {
1357
+ if (a.length === 0)
1358
+ return [];
1234
1359
  if (a.length > 100) {
1235
1360
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1236
1361
  }
@@ -1252,6 +1377,8 @@ class RestRepository extends Query {
1252
1377
  }
1253
1378
  async createOrUpdate(a, b) {
1254
1379
  if (Array.isArray(a)) {
1380
+ if (a.length === 0)
1381
+ return [];
1255
1382
  if (a.length > 100) {
1256
1383
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1257
1384
  }
@@ -1273,6 +1400,8 @@ class RestRepository extends Query {
1273
1400
  }
1274
1401
  async delete(a) {
1275
1402
  if (Array.isArray(a)) {
1403
+ if (a.length === 0)
1404
+ return;
1276
1405
  if (a.length > 100) {
1277
1406
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1278
1407
  }
@@ -1292,13 +1421,19 @@ class RestRepository extends Query {
1292
1421
  throw new Error("Invalid arguments for delete method");
1293
1422
  }
1294
1423
  async search(query, options = {}) {
1295
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1296
- const { records } = await searchBranch({
1297
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1298
- body: { tables: [__privateGet$3(this, _table)], query, fuzziness: options.fuzziness },
1424
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1425
+ const { records } = await searchTable({
1426
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1427
+ body: {
1428
+ query,
1429
+ fuzziness: options.fuzziness,
1430
+ highlight: options.highlight,
1431
+ filter: options.filter
1432
+ },
1299
1433
  ...fetchProps
1300
1434
  });
1301
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), item));
1435
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1436
+ return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1302
1437
  }
1303
1438
  async query(query) {
1304
1439
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
@@ -1307,34 +1442,35 @@ class RestRepository extends Query {
1307
1442
  const data = query.getQueryOptions();
1308
1443
  const body = {
1309
1444
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1310
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1311
- page: data.page,
1445
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1446
+ page: data.pagination,
1312
1447
  columns: data.columns
1313
1448
  };
1314
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1449
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1315
1450
  const { meta, records: objects } = await queryTable({
1316
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1451
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1317
1452
  body,
1318
1453
  ...fetchProps
1319
1454
  });
1320
- const records = objects.map((record) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), record));
1455
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1456
+ const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1321
1457
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1322
1458
  return new Page(query, meta, records);
1323
1459
  }
1324
1460
  }
1325
1461
  _table = new WeakMap();
1326
- _links = new WeakMap();
1327
1462
  _getFetchProps = new WeakMap();
1328
1463
  _cache = new WeakMap();
1464
+ _schema$1 = new WeakMap();
1329
1465
  _insertRecordWithoutId = new WeakSet();
1330
1466
  insertRecordWithoutId_fn = async function(object) {
1331
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1467
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1332
1468
  const record = transformObjectLinks(object);
1333
1469
  const response = await insertRecord({
1334
1470
  pathParams: {
1335
1471
  workspace: "{workspaceId}",
1336
1472
  dbBranchName: "{dbBranch}",
1337
- tableName: __privateGet$3(this, _table)
1473
+ tableName: __privateGet$4(this, _table)
1338
1474
  },
1339
1475
  body: record,
1340
1476
  ...fetchProps
@@ -1347,13 +1483,13 @@ insertRecordWithoutId_fn = async function(object) {
1347
1483
  };
1348
1484
  _insertRecordWithId = new WeakSet();
1349
1485
  insertRecordWithId_fn = async function(recordId, object) {
1350
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1486
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1351
1487
  const record = transformObjectLinks(object);
1352
1488
  const response = await insertRecordWithID({
1353
1489
  pathParams: {
1354
1490
  workspace: "{workspaceId}",
1355
1491
  dbBranchName: "{dbBranch}",
1356
- tableName: __privateGet$3(this, _table),
1492
+ tableName: __privateGet$4(this, _table),
1357
1493
  recordId
1358
1494
  },
1359
1495
  body: record,
@@ -1368,14 +1504,14 @@ insertRecordWithId_fn = async function(recordId, object) {
1368
1504
  };
1369
1505
  _bulkInsertTableRecords = new WeakSet();
1370
1506
  bulkInsertTableRecords_fn = async function(objects) {
1371
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1507
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1372
1508
  const records = objects.map((object) => transformObjectLinks(object));
1373
1509
  const response = await bulkInsertTableRecords({
1374
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1510
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1375
1511
  body: { records },
1376
1512
  ...fetchProps
1377
1513
  });
1378
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1514
+ const finalObjects = await this.read(response.recordIDs);
1379
1515
  if (finalObjects.length !== objects.length) {
1380
1516
  throw new Error("The server failed to save some records");
1381
1517
  }
@@ -1383,10 +1519,10 @@ bulkInsertTableRecords_fn = async function(objects) {
1383
1519
  };
1384
1520
  _updateRecordWithID = new WeakSet();
1385
1521
  updateRecordWithID_fn = async function(recordId, object) {
1386
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1522
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1387
1523
  const record = transformObjectLinks(object);
1388
1524
  const response = await updateRecordWithID({
1389
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1525
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1390
1526
  body: record,
1391
1527
  ...fetchProps
1392
1528
  });
@@ -1397,9 +1533,9 @@ updateRecordWithID_fn = async function(recordId, object) {
1397
1533
  };
1398
1534
  _upsertRecordWithID = new WeakSet();
1399
1535
  upsertRecordWithID_fn = async function(recordId, object) {
1400
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1536
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1401
1537
  const response = await upsertRecordWithID({
1402
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1538
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1403
1539
  body: object,
1404
1540
  ...fetchProps
1405
1541
  });
@@ -1410,51 +1546,63 @@ upsertRecordWithID_fn = async function(recordId, object) {
1410
1546
  };
1411
1547
  _deleteRecord = new WeakSet();
1412
1548
  deleteRecord_fn = async function(recordId) {
1413
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1549
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1414
1550
  await deleteRecord({
1415
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1551
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1416
1552
  ...fetchProps
1417
1553
  });
1418
1554
  };
1419
1555
  _invalidateCache = new WeakSet();
1420
1556
  invalidateCache_fn = async function(recordId) {
1421
- await __privateGet$3(this, _cache).delete(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1422
- const cacheItems = await __privateGet$3(this, _cache).getAll();
1557
+ await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1558
+ const cacheItems = await __privateGet$4(this, _cache).getAll();
1423
1559
  const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1424
1560
  for (const [key, value] of queries) {
1425
1561
  const ids = getIds(value);
1426
1562
  if (ids.includes(recordId))
1427
- await __privateGet$3(this, _cache).delete(key);
1563
+ await __privateGet$4(this, _cache).delete(key);
1428
1564
  }
1429
1565
  };
1430
1566
  _setCacheRecord = new WeakSet();
1431
1567
  setCacheRecord_fn = async function(record) {
1432
- if (!__privateGet$3(this, _cache).cacheRecords)
1568
+ if (!__privateGet$4(this, _cache).cacheRecords)
1433
1569
  return;
1434
- await __privateGet$3(this, _cache).set(`rec_${__privateGet$3(this, _table)}:${record.id}`, record);
1570
+ await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1435
1571
  };
1436
1572
  _getCacheRecord = new WeakSet();
1437
1573
  getCacheRecord_fn = async function(recordId) {
1438
- if (!__privateGet$3(this, _cache).cacheRecords)
1574
+ if (!__privateGet$4(this, _cache).cacheRecords)
1439
1575
  return null;
1440
- return __privateGet$3(this, _cache).get(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1576
+ return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1441
1577
  };
1442
1578
  _setCacheQuery = new WeakSet();
1443
1579
  setCacheQuery_fn = async function(query, meta, records) {
1444
- await __privateGet$3(this, _cache).set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1580
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1445
1581
  };
1446
1582
  _getCacheQuery = new WeakSet();
1447
1583
  getCacheQuery_fn = async function(query) {
1448
- const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
1449
- const result = await __privateGet$3(this, _cache).get(key);
1584
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1585
+ const result = await __privateGet$4(this, _cache).get(key);
1450
1586
  if (!result)
1451
1587
  return null;
1452
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1453
- if (!ttl || ttl < 0)
1454
- return result;
1588
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1589
+ if (ttl < 0)
1590
+ return null;
1455
1591
  const hasExpired = result.date.getTime() + ttl < Date.now();
1456
1592
  return hasExpired ? null : result;
1457
1593
  };
1594
+ _getSchema$1 = new WeakSet();
1595
+ getSchema_fn$1 = async function() {
1596
+ if (__privateGet$4(this, _schema$1))
1597
+ return __privateGet$4(this, _schema$1);
1598
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1599
+ const { schema } = await getBranchDetails({
1600
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1601
+ ...fetchProps
1602
+ });
1603
+ __privateSet$3(this, _schema$1, schema);
1604
+ return schema;
1605
+ };
1458
1606
  const transformObjectLinks = (object) => {
1459
1607
  return Object.entries(object).reduce((acc, [key, value]) => {
1460
1608
  if (key === "xata")
@@ -1462,15 +1610,34 @@ const transformObjectLinks = (object) => {
1462
1610
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1463
1611
  }, {});
1464
1612
  };
1465
- const initObject = (db, links, table, object) => {
1613
+ const initObject = (db, schema, table, object) => {
1466
1614
  const result = {};
1467
- Object.assign(result, object);
1468
- const tableLinks = links[table] || [];
1469
- for (const link of tableLinks) {
1470
- const [field, linkTable] = link;
1471
- const value = result[field];
1472
- if (value && isObject(value)) {
1473
- result[field] = initObject(db, links, linkTable, value);
1615
+ const { xata, ...rest } = object ?? {};
1616
+ Object.assign(result, rest);
1617
+ const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1618
+ if (!columns)
1619
+ console.error(`Table ${table} not found in schema`);
1620
+ for (const column of columns ?? []) {
1621
+ const value = result[column.name];
1622
+ switch (column.type) {
1623
+ case "datetime": {
1624
+ const date = value !== void 0 ? new Date(value) : void 0;
1625
+ if (date && isNaN(date.getTime())) {
1626
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1627
+ } else if (date) {
1628
+ result[column.name] = date;
1629
+ }
1630
+ break;
1631
+ }
1632
+ case "link": {
1633
+ const linkTable = column.link?.table;
1634
+ if (!linkTable) {
1635
+ console.error(`Failed to parse link for field ${column.name}`);
1636
+ } else if (isObject(value)) {
1637
+ result[column.name] = initObject(db, schema, linkTable, value);
1638
+ }
1639
+ break;
1640
+ }
1474
1641
  }
1475
1642
  }
1476
1643
  result.read = function() {
@@ -1482,7 +1649,10 @@ const initObject = (db, links, table, object) => {
1482
1649
  result.delete = function() {
1483
1650
  return db[table].delete(result["id"]);
1484
1651
  };
1485
- for (const prop of ["read", "update", "delete"]) {
1652
+ result.getMetadata = function() {
1653
+ return xata;
1654
+ };
1655
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1486
1656
  Object.defineProperty(result, prop, { enumerable: false });
1487
1657
  }
1488
1658
  Object.freeze(result);
@@ -1502,7 +1672,7 @@ var __accessCheck$3 = (obj, member, msg) => {
1502
1672
  if (!member.has(obj))
1503
1673
  throw TypeError("Cannot " + msg);
1504
1674
  };
1505
- var __privateGet$2 = (obj, member, getter) => {
1675
+ var __privateGet$3 = (obj, member, getter) => {
1506
1676
  __accessCheck$3(obj, member, "read from private field");
1507
1677
  return getter ? getter.call(obj) : member.get(obj);
1508
1678
  };
@@ -1511,7 +1681,7 @@ var __privateAdd$3 = (obj, member, value) => {
1511
1681
  throw TypeError("Cannot add the same private member more than once");
1512
1682
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1513
1683
  };
1514
- var __privateSet$1 = (obj, member, value, setter) => {
1684
+ var __privateSet$2 = (obj, member, value, setter) => {
1515
1685
  __accessCheck$3(obj, member, "write to private field");
1516
1686
  setter ? setter.call(obj, value) : member.set(obj, value);
1517
1687
  return value;
@@ -1520,30 +1690,30 @@ var _map;
1520
1690
  class SimpleCache {
1521
1691
  constructor(options = {}) {
1522
1692
  __privateAdd$3(this, _map, void 0);
1523
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
1693
+ __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1524
1694
  this.capacity = options.max ?? 500;
1525
1695
  this.cacheRecords = options.cacheRecords ?? true;
1526
1696
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1527
1697
  }
1528
1698
  async getAll() {
1529
- return Object.fromEntries(__privateGet$2(this, _map));
1699
+ return Object.fromEntries(__privateGet$3(this, _map));
1530
1700
  }
1531
1701
  async get(key) {
1532
- return __privateGet$2(this, _map).get(key) ?? null;
1702
+ return __privateGet$3(this, _map).get(key) ?? null;
1533
1703
  }
1534
1704
  async set(key, value) {
1535
1705
  await this.delete(key);
1536
- __privateGet$2(this, _map).set(key, value);
1537
- if (__privateGet$2(this, _map).size > this.capacity) {
1538
- const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
1706
+ __privateGet$3(this, _map).set(key, value);
1707
+ if (__privateGet$3(this, _map).size > this.capacity) {
1708
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1539
1709
  await this.delete(leastRecentlyUsed);
1540
1710
  }
1541
1711
  }
1542
1712
  async delete(key) {
1543
- __privateGet$2(this, _map).delete(key);
1713
+ __privateGet$3(this, _map).delete(key);
1544
1714
  }
1545
1715
  async clear() {
1546
- return __privateGet$2(this, _map).clear();
1716
+ return __privateGet$3(this, _map).clear();
1547
1717
  }
1548
1718
  }
1549
1719
  _map = new WeakMap();
@@ -1571,7 +1741,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1571
1741
  if (!member.has(obj))
1572
1742
  throw TypeError("Cannot " + msg);
1573
1743
  };
1574
- var __privateGet$1 = (obj, member, getter) => {
1744
+ var __privateGet$2 = (obj, member, getter) => {
1575
1745
  __accessCheck$2(obj, member, "read from private field");
1576
1746
  return getter ? getter.call(obj) : member.get(obj);
1577
1747
  };
@@ -1582,26 +1752,24 @@ var __privateAdd$2 = (obj, member, value) => {
1582
1752
  };
1583
1753
  var _tables;
1584
1754
  class SchemaPlugin extends XataPlugin {
1585
- constructor(links, tableNames) {
1755
+ constructor(tableNames) {
1586
1756
  super();
1587
- this.links = links;
1588
1757
  this.tableNames = tableNames;
1589
1758
  __privateAdd$2(this, _tables, {});
1590
1759
  }
1591
1760
  build(pluginOptions) {
1592
- const links = this.links;
1593
1761
  const db = new Proxy({}, {
1594
1762
  get: (_target, table) => {
1595
1763
  if (!isString(table))
1596
1764
  throw new Error("Invalid table name");
1597
- if (!__privateGet$1(this, _tables)[table]) {
1598
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, links });
1765
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1766
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1599
1767
  }
1600
- return __privateGet$1(this, _tables)[table];
1768
+ return __privateGet$2(this, _tables)[table];
1601
1769
  }
1602
1770
  });
1603
1771
  for (const table of this.tableNames ?? []) {
1604
- db[table] = new RestRepository({ db, pluginOptions, table, links });
1772
+ db[table] = new RestRepository({ db, pluginOptions, table });
1605
1773
  }
1606
1774
  return db;
1607
1775
  }
@@ -1612,55 +1780,80 @@ var __accessCheck$1 = (obj, member, msg) => {
1612
1780
  if (!member.has(obj))
1613
1781
  throw TypeError("Cannot " + msg);
1614
1782
  };
1783
+ var __privateGet$1 = (obj, member, getter) => {
1784
+ __accessCheck$1(obj, member, "read from private field");
1785
+ return getter ? getter.call(obj) : member.get(obj);
1786
+ };
1615
1787
  var __privateAdd$1 = (obj, member, value) => {
1616
1788
  if (member.has(obj))
1617
1789
  throw TypeError("Cannot add the same private member more than once");
1618
1790
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1619
1791
  };
1792
+ var __privateSet$1 = (obj, member, value, setter) => {
1793
+ __accessCheck$1(obj, member, "write to private field");
1794
+ setter ? setter.call(obj, value) : member.set(obj, value);
1795
+ return value;
1796
+ };
1620
1797
  var __privateMethod$1 = (obj, member, method) => {
1621
1798
  __accessCheck$1(obj, member, "access private method");
1622
1799
  return method;
1623
1800
  };
1624
- var _search, search_fn;
1801
+ var _schema, _search, search_fn, _getSchema, getSchema_fn;
1625
1802
  class SearchPlugin extends XataPlugin {
1626
- constructor(db, links) {
1803
+ constructor(db) {
1627
1804
  super();
1628
1805
  this.db = db;
1629
- this.links = links;
1630
1806
  __privateAdd$1(this, _search);
1807
+ __privateAdd$1(this, _getSchema);
1808
+ __privateAdd$1(this, _schema, void 0);
1631
1809
  }
1632
1810
  build({ getFetchProps }) {
1633
1811
  return {
1634
1812
  all: async (query, options = {}) => {
1635
1813
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1814
+ const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1636
1815
  return records.map((record) => {
1637
1816
  const { table = "orphan" } = record.xata;
1638
- return { table, record: initObject(this.db, this.links, table, record) };
1817
+ return { table, record: initObject(this.db, schema, table, record) };
1639
1818
  });
1640
1819
  },
1641
1820
  byTable: async (query, options = {}) => {
1642
1821
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1822
+ const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1643
1823
  return records.reduce((acc, record) => {
1644
1824
  const { table = "orphan" } = record.xata;
1645
1825
  const items = acc[table] ?? [];
1646
- const item = initObject(this.db, this.links, table, record);
1826
+ const item = initObject(this.db, schema, table, record);
1647
1827
  return { ...acc, [table]: [...items, item] };
1648
1828
  }, {});
1649
1829
  }
1650
1830
  };
1651
1831
  }
1652
1832
  }
1833
+ _schema = new WeakMap();
1653
1834
  _search = new WeakSet();
1654
1835
  search_fn = async function(query, options, getFetchProps) {
1655
1836
  const fetchProps = await getFetchProps();
1656
- const { tables, fuzziness } = options ?? {};
1837
+ const { tables, fuzziness, highlight } = options ?? {};
1657
1838
  const { records } = await searchBranch({
1658
1839
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1659
- body: { tables, query, fuzziness },
1840
+ body: { tables, query, fuzziness, highlight },
1660
1841
  ...fetchProps
1661
1842
  });
1662
1843
  return records;
1663
1844
  };
1845
+ _getSchema = new WeakSet();
1846
+ getSchema_fn = async function(getFetchProps) {
1847
+ if (__privateGet$1(this, _schema))
1848
+ return __privateGet$1(this, _schema);
1849
+ const fetchProps = await getFetchProps();
1850
+ const { schema } = await getBranchDetails({
1851
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1852
+ ...fetchProps
1853
+ });
1854
+ __privateSet$1(this, _schema, schema);
1855
+ return schema;
1856
+ };
1664
1857
 
1665
1858
  const isBranchStrategyBuilder = (strategy) => {
1666
1859
  return typeof strategy === "function";
@@ -1672,30 +1865,39 @@ const envBranchNames = [
1672
1865
  "CF_PAGES_BRANCH",
1673
1866
  "BRANCH"
1674
1867
  ];
1675
- const defaultBranch = "main";
1676
1868
  async function getCurrentBranchName(options) {
1677
- const env = await getBranchByEnvVariable();
1678
- if (env)
1679
- return env;
1680
- const branch = await getGitBranch();
1681
- if (!branch)
1682
- return defaultBranch;
1683
- const details = await getDatabaseBranch(branch, options);
1684
- if (details)
1685
- return branch;
1686
- return defaultBranch;
1869
+ const env = getBranchByEnvVariable();
1870
+ if (env) {
1871
+ const details = await getDatabaseBranch(env, options);
1872
+ if (details)
1873
+ return env;
1874
+ console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1875
+ }
1876
+ const gitBranch = await getGitBranch();
1877
+ return resolveXataBranch(gitBranch, options);
1687
1878
  }
1688
1879
  async function getCurrentBranchDetails(options) {
1689
- const env = await getBranchByEnvVariable();
1690
- if (env)
1691
- return getDatabaseBranch(env, options);
1692
- const branch = await getGitBranch();
1693
- if (!branch)
1694
- return getDatabaseBranch(defaultBranch, options);
1695
- const details = await getDatabaseBranch(branch, options);
1696
- if (details)
1697
- return details;
1698
- return getDatabaseBranch(defaultBranch, options);
1880
+ const branch = await getCurrentBranchName(options);
1881
+ return getDatabaseBranch(branch, options);
1882
+ }
1883
+ async function resolveXataBranch(gitBranch, options) {
1884
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1885
+ const apiKey = options?.apiKey || getAPIKey();
1886
+ if (!databaseURL)
1887
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1888
+ if (!apiKey)
1889
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1890
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1891
+ const [workspace] = host.split(".");
1892
+ const { branch } = await resolveBranch({
1893
+ apiKey,
1894
+ apiUrl: databaseURL,
1895
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1896
+ workspacesApiUrl: `${protocol}//${host}`,
1897
+ pathParams: { dbName, workspace },
1898
+ queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
1899
+ });
1900
+ return branch;
1699
1901
  }
1700
1902
  async function getDatabaseBranch(branch, options) {
1701
1903
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1713,10 +1915,7 @@ async function getDatabaseBranch(branch, options) {
1713
1915
  apiUrl: databaseURL,
1714
1916
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1715
1917
  workspacesApiUrl: `${protocol}//${host}`,
1716
- pathParams: {
1717
- dbBranchName,
1718
- workspace
1719
- }
1918
+ pathParams: { dbBranchName, workspace }
1720
1919
  });
1721
1920
  } catch (err) {
1722
1921
  if (isObject(err) && err.status === 404)
@@ -1769,7 +1968,7 @@ var __privateMethod = (obj, member, method) => {
1769
1968
  const buildClient = (plugins) => {
1770
1969
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1771
1970
  return _a = class {
1772
- constructor(options = {}, links, tables) {
1971
+ constructor(options = {}, tables) {
1773
1972
  __privateAdd(this, _parseOptions);
1774
1973
  __privateAdd(this, _getFetchProps);
1775
1974
  __privateAdd(this, _evaluateBranch);
@@ -1779,12 +1978,12 @@ const buildClient = (plugins) => {
1779
1978
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1780
1979
  cache: safeOptions.cache
1781
1980
  };
1782
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1783
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
1981
+ const db = new SchemaPlugin(tables).build(pluginOptions);
1982
+ const search = new SearchPlugin(db).build(pluginOptions);
1784
1983
  this.db = db;
1785
1984
  this.search = search;
1786
1985
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1787
- if (!namespace)
1986
+ if (namespace === void 0)
1788
1987
  continue;
1789
1988
  const result = namespace.build(pluginOptions);
1790
1989
  if (result instanceof Promise) {
@@ -1801,7 +2000,7 @@ const buildClient = (plugins) => {
1801
2000
  const databaseURL = options?.databaseURL || getDatabaseURL();
1802
2001
  const apiKey = options?.apiKey || getAPIKey();
1803
2002
  const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1804
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2003
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1805
2004
  if (!databaseURL || !apiKey) {
1806
2005
  throw new Error("Options databaseURL and apiKey are required");
1807
2006
  }
@@ -1828,7 +2027,7 @@ const buildClient = (plugins) => {
1828
2027
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1829
2028
  if (__privateGet(this, _branch))
1830
2029
  return __privateGet(this, _branch);
1831
- if (!param)
2030
+ if (param === void 0)
1832
2031
  return void 0;
1833
2032
  const strategies = Array.isArray(param) ? [...param] : [param];
1834
2033
  const evaluateBranch = async (strategy) => {
@@ -1861,6 +2060,7 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1861
2060
  exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1862
2061
  exports.Page = Page;
1863
2062
  exports.Query = Query;
2063
+ exports.RecordArray = RecordArray;
1864
2064
  exports.Repository = Repository;
1865
2065
  exports.RestRepository = RestRepository;
1866
2066
  exports.SchemaPlugin = SchemaPlugin;
@@ -1925,6 +2125,7 @@ exports.insertRecord = insertRecord;
1925
2125
  exports.insertRecordWithID = insertRecordWithID;
1926
2126
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
1927
2127
  exports.is = is;
2128
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
1928
2129
  exports.isIdentifiable = isIdentifiable;
1929
2130
  exports.isNot = isNot;
1930
2131
  exports.isXataRecord = isXataRecord;
@@ -1940,6 +2141,7 @@ exports.removeWorkspaceMember = removeWorkspaceMember;
1940
2141
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
1941
2142
  exports.resolveBranch = resolveBranch;
1942
2143
  exports.searchBranch = searchBranch;
2144
+ exports.searchTable = searchTable;
1943
2145
  exports.setTableSchema = setTableSchema;
1944
2146
  exports.startsWith = startsWith;
1945
2147
  exports.updateBranchMetadata = updateBranchMetadata;