@xata.io/client 0.0.0-alpha.vf350c0a → 0.0.0-alpha.vf45a2df

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
@@ -7,14 +7,18 @@ function compact(arr) {
7
7
  function isObject(value) {
8
8
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
9
  }
10
+ function isDefined(value) {
11
+ return value !== null && value !== void 0;
12
+ }
10
13
  function isString(value) {
11
- return value !== void 0 && value !== null && typeof value === "string";
14
+ return isDefined(value) && typeof value === "string";
12
15
  }
13
16
  function toBase64(value) {
14
17
  try {
15
18
  return btoa(value);
16
19
  } catch (err) {
17
- return Buffer.from(value).toString("base64");
20
+ const buf = Buffer;
21
+ return buf.from(value).toString("base64");
18
22
  }
19
23
  }
20
24
 
@@ -70,16 +74,28 @@ function getFetchImplementation(userFetch) {
70
74
  return fetchImpl;
71
75
  }
72
76
 
73
- class FetcherError extends Error {
74
- constructor(status, data) {
77
+ const VERSION = "0.0.0-alpha.vf45a2df";
78
+
79
+ class ErrorWithCause extends Error {
80
+ constructor(message, options) {
81
+ super(message, options);
82
+ }
83
+ }
84
+ class FetcherError extends ErrorWithCause {
85
+ constructor(status, data, requestId) {
75
86
  super(getMessage(data));
76
87
  this.status = status;
77
88
  this.errors = isBulkError(data) ? data.errors : void 0;
89
+ this.requestId = requestId;
78
90
  if (data instanceof Error) {
79
91
  this.stack = data.stack;
80
92
  this.cause = data.cause;
81
93
  }
82
94
  }
95
+ toString() {
96
+ const error = super.toString();
97
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
98
+ }
83
99
  }
84
100
  function isBulkError(error) {
85
101
  return isObject(error) && Array.isArray(error.errors);
@@ -102,7 +118,12 @@ function getMessage(data) {
102
118
  }
103
119
 
104
120
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
105
- const query = new URLSearchParams(queryParams).toString();
121
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
122
+ if (value === void 0 || value === null)
123
+ return acc;
124
+ return { ...acc, [key]: value };
125
+ }, {});
126
+ const query = new URLSearchParams(cleanQueryParams).toString();
106
127
  const queryString = query.length > 0 ? `?${query}` : "";
107
128
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
108
129
  };
@@ -142,6 +163,7 @@ async function fetch$1({
142
163
  body: body ? JSON.stringify(body) : void 0,
143
164
  headers: {
144
165
  "Content-Type": "application/json",
166
+ "User-Agent": `Xata client-ts/${VERSION}`,
145
167
  ...headers,
146
168
  ...hostHeader(fullUrl),
147
169
  Authorization: `Bearer ${apiKey}`
@@ -150,14 +172,15 @@ async function fetch$1({
150
172
  if (response.status === 204) {
151
173
  return {};
152
174
  }
175
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
153
176
  try {
154
177
  const jsonResponse = await response.json();
155
178
  if (response.ok) {
156
179
  return jsonResponse;
157
180
  }
158
- throw new FetcherError(response.status, jsonResponse);
181
+ throw new FetcherError(response.status, jsonResponse, requestId);
159
182
  } catch (error) {
160
- throw new FetcherError(response.status, error);
183
+ throw new FetcherError(response.status, error, requestId);
161
184
  }
162
185
  }
163
186
 
@@ -366,6 +389,11 @@ const queryTable = (variables) => fetch$1({
366
389
  method: "post",
367
390
  ...variables
368
391
  });
392
+ const searchTable = (variables) => fetch$1({
393
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
394
+ method: "post",
395
+ ...variables
396
+ });
369
397
  const searchBranch = (variables) => fetch$1({
370
398
  url: "/db/{dbBranchName}/search",
371
399
  method: "post",
@@ -429,6 +457,7 @@ const operationsByTag = {
429
457
  getRecord,
430
458
  bulkInsertTableRecords,
431
459
  queryTable,
460
+ searchTable,
432
461
  searchBranch
433
462
  }
434
463
  };
@@ -675,10 +704,10 @@ class DatabaseApi {
675
704
  ...this.extraProps
676
705
  });
677
706
  }
678
- resolveBranch(workspace, dbName, gitBranch) {
707
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
679
708
  return operationsByTag.database.resolveBranch({
680
709
  pathParams: { workspace, dbName },
681
- queryParams: { gitBranch },
710
+ queryParams: { gitBranch, fallbackBranch },
682
711
  ...this.extraProps
683
712
  });
684
713
  }
@@ -699,10 +728,10 @@ class BranchApi {
699
728
  ...this.extraProps
700
729
  });
701
730
  }
702
- createBranch(workspace, database, branch, from = "", options = {}) {
731
+ createBranch(workspace, database, branch, from, options = {}) {
703
732
  return operationsByTag.branch.createBranch({
704
733
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
705
- queryParams: { from },
734
+ queryParams: isString(from) ? { from } : void 0,
706
735
  body: options,
707
736
  ...this.extraProps
708
737
  });
@@ -884,6 +913,13 @@ class RecordsApi {
884
913
  ...this.extraProps
885
914
  });
886
915
  }
916
+ searchTable(workspace, database, branch, tableName, query) {
917
+ return operationsByTag.records.searchTable({
918
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
919
+ body: query,
920
+ ...this.extraProps
921
+ });
922
+ }
887
923
  searchBranch(workspace, database, branch, query) {
888
924
  return operationsByTag.records.searchBranch({
889
925
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -921,25 +957,25 @@ var __privateSet$5 = (obj, member, value, setter) => {
921
957
  setter ? setter.call(obj, value) : member.set(obj, value);
922
958
  return value;
923
959
  };
924
- var _query;
960
+ var _query, _page;
925
961
  class Page {
926
962
  constructor(query, meta, records = []) {
927
963
  __privateAdd$6(this, _query, void 0);
928
964
  __privateSet$5(this, _query, query);
929
965
  this.meta = meta;
930
- this.records = records;
966
+ this.records = new RecordArray(this, records);
931
967
  }
932
968
  async nextPage(size, offset) {
933
- return __privateGet$6(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
969
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
934
970
  }
935
971
  async previousPage(size, offset) {
936
- return __privateGet$6(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
972
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
937
973
  }
938
974
  async firstPage(size, offset) {
939
- return __privateGet$6(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
975
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
940
976
  }
941
977
  async lastPage(size, offset) {
942
- return __privateGet$6(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
978
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
943
979
  }
944
980
  hasNextPage() {
945
981
  return this.meta.page.more;
@@ -947,9 +983,50 @@ class Page {
947
983
  }
948
984
  _query = new WeakMap();
949
985
  const PAGINATION_MAX_SIZE = 200;
950
- const PAGINATION_DEFAULT_SIZE = 200;
986
+ const PAGINATION_DEFAULT_SIZE = 20;
951
987
  const PAGINATION_MAX_OFFSET = 800;
952
988
  const PAGINATION_DEFAULT_OFFSET = 0;
989
+ function isCursorPaginationOptions(options) {
990
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
991
+ }
992
+ const _RecordArray = class extends Array {
993
+ constructor(page, overrideRecords) {
994
+ super(..._RecordArray.parseConstructorParams(page, overrideRecords));
995
+ __privateAdd$6(this, _page, void 0);
996
+ __privateSet$5(this, _page, page);
997
+ }
998
+ static parseConstructorParams(...args) {
999
+ if (args.length === 1 && typeof args[0] === "number") {
1000
+ return new Array(args[0]);
1001
+ }
1002
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1003
+ const result = args[1] ?? args[0].records ?? [];
1004
+ return new Array(...result);
1005
+ }
1006
+ return new Array(...args);
1007
+ }
1008
+ async nextPage(size, offset) {
1009
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1010
+ return new _RecordArray(newPage);
1011
+ }
1012
+ async previousPage(size, offset) {
1013
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1014
+ return new _RecordArray(newPage);
1015
+ }
1016
+ async firstPage(size, offset) {
1017
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1018
+ return new _RecordArray(newPage);
1019
+ }
1020
+ async lastPage(size, offset) {
1021
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1022
+ return new _RecordArray(newPage);
1023
+ }
1024
+ hasNextPage() {
1025
+ return __privateGet$6(this, _page).meta.page.more;
1026
+ }
1027
+ };
1028
+ let RecordArray = _RecordArray;
1029
+ _page = new WeakMap();
953
1030
 
954
1031
  var __accessCheck$5 = (obj, member, msg) => {
955
1032
  if (!member.has(obj))
@@ -971,18 +1048,19 @@ var __privateSet$4 = (obj, member, value, setter) => {
971
1048
  };
972
1049
  var _table$1, _repository, _data;
973
1050
  const _Query = class {
974
- constructor(repository, table, data, parent) {
1051
+ constructor(repository, table, data, rawParent) {
975
1052
  __privateAdd$5(this, _table$1, void 0);
976
1053
  __privateAdd$5(this, _repository, void 0);
977
1054
  __privateAdd$5(this, _data, { filter: {} });
978
1055
  this.meta = { page: { cursor: "start", more: true } };
979
- this.records = [];
1056
+ this.records = new RecordArray(this, []);
980
1057
  __privateSet$4(this, _table$1, table);
981
1058
  if (repository) {
982
1059
  __privateSet$4(this, _repository, repository);
983
1060
  } else {
984
1061
  __privateSet$4(this, _repository, this);
985
1062
  }
1063
+ const parent = cleanParent(data, rawParent);
986
1064
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
987
1065
  __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
988
1066
  __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
@@ -990,7 +1068,7 @@ const _Query = class {
990
1068
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
991
1069
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
992
1070
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
993
- __privateGet$5(this, _data).page = data.page ?? parent?.page;
1071
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
994
1072
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
995
1073
  this.any = this.any.bind(this);
996
1074
  this.all = this.all.bind(this);
@@ -1005,8 +1083,8 @@ const _Query = class {
1005
1083
  return __privateGet$5(this, _data);
1006
1084
  }
1007
1085
  key() {
1008
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$5(this, _data);
1009
- const key = JSON.stringify({ columns, filter, sort, page });
1086
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1087
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1010
1088
  return toBase64(key);
1011
1089
  }
1012
1090
  any(...queries) {
@@ -1048,34 +1126,39 @@ const _Query = class {
1048
1126
  return __privateGet$5(this, _repository).query(query);
1049
1127
  }
1050
1128
  async *[Symbol.asyncIterator]() {
1051
- for await (const [record] of this.getIterator(1)) {
1129
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1052
1130
  yield record;
1053
1131
  }
1054
1132
  }
1055
- async *getIterator(chunk, options = {}) {
1056
- let offset = 0;
1057
- let end = false;
1058
- while (!end) {
1059
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1060
- yield records;
1061
- offset += chunk;
1062
- end = !meta.page.more;
1133
+ async *getIterator(options = {}) {
1134
+ const { batchSize = 1 } = options;
1135
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1136
+ let more = page.hasNextPage();
1137
+ yield page.records;
1138
+ while (more) {
1139
+ page = await page.nextPage();
1140
+ more = page.hasNextPage();
1141
+ yield page.records;
1063
1142
  }
1064
1143
  }
1065
1144
  async getMany(options = {}) {
1066
- const { records } = await this.getPaginated(options);
1067
- return records;
1145
+ const page = await this.getPaginated(options);
1146
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1147
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1148
+ }
1149
+ return page.records;
1068
1150
  }
1069
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1151
+ async getAll(options = {}) {
1152
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1070
1153
  const results = [];
1071
- for await (const page of this.getIterator(chunk, options)) {
1154
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1072
1155
  results.push(...page);
1073
1156
  }
1074
1157
  return results;
1075
1158
  }
1076
1159
  async getFirst(options = {}) {
1077
- const records = await this.getMany({ ...options, page: { size: 1 } });
1078
- return records[0] || null;
1160
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1161
+ return records[0] ?? null;
1079
1162
  }
1080
1163
  cache(ttl) {
1081
1164
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
@@ -1087,10 +1170,10 @@ const _Query = class {
1087
1170
  return this.firstPage(size, offset);
1088
1171
  }
1089
1172
  firstPage(size, offset) {
1090
- return this.getPaginated({ page: { size, offset } });
1173
+ return this.getPaginated({ pagination: { size, offset } });
1091
1174
  }
1092
1175
  lastPage(size, offset) {
1093
- return this.getPaginated({ page: { size, offset, before: "end" } });
1176
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1094
1177
  }
1095
1178
  hasNextPage() {
1096
1179
  return this.meta.page.more;
@@ -1100,12 +1183,20 @@ let Query = _Query;
1100
1183
  _table$1 = new WeakMap();
1101
1184
  _repository = new WeakMap();
1102
1185
  _data = new WeakMap();
1186
+ function cleanParent(data, parent) {
1187
+ if (isCursorPaginationOptions(data.pagination)) {
1188
+ return { ...parent, sorting: void 0, filter: void 0 };
1189
+ }
1190
+ return parent;
1191
+ }
1103
1192
 
1104
1193
  function isIdentifiable(x) {
1105
1194
  return isObject(x) && isString(x?.id);
1106
1195
  }
1107
1196
  function isXataRecord(x) {
1108
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1197
+ const record = x;
1198
+ const metadata = record?.getMetadata();
1199
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1109
1200
  }
1110
1201
 
1111
1202
  function isSortFilterString(value) {
@@ -1153,7 +1244,7 @@ var __privateMethod$2 = (obj, member, method) => {
1153
1244
  __accessCheck$4(obj, member, "access private method");
1154
1245
  return method;
1155
1246
  };
1156
- var _table, _getFetchProps, _cache, _schemaColumns, _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, _getSchemaColumns, getSchemaColumns_fn;
1247
+ 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;
1157
1248
  class Repository extends Query {
1158
1249
  }
1159
1250
  class RestRepository extends Query {
@@ -1170,11 +1261,11 @@ class RestRepository extends Query {
1170
1261
  __privateAdd$4(this, _getCacheRecord);
1171
1262
  __privateAdd$4(this, _setCacheQuery);
1172
1263
  __privateAdd$4(this, _getCacheQuery);
1173
- __privateAdd$4(this, _getSchemaColumns);
1264
+ __privateAdd$4(this, _getSchema$1);
1174
1265
  __privateAdd$4(this, _table, void 0);
1175
1266
  __privateAdd$4(this, _getFetchProps, void 0);
1176
1267
  __privateAdd$4(this, _cache, void 0);
1177
- __privateAdd$4(this, _schemaColumns, void 0);
1268
+ __privateAdd$4(this, _schema$1, void 0);
1178
1269
  __privateSet$3(this, _table, options.table);
1179
1270
  __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1180
1271
  this.db = options.db;
@@ -1182,6 +1273,8 @@ class RestRepository extends Query {
1182
1273
  }
1183
1274
  async create(a, b) {
1184
1275
  if (Array.isArray(a)) {
1276
+ if (a.length === 0)
1277
+ return [];
1185
1278
  const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1186
1279
  await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1187
1280
  return records;
@@ -1207,27 +1300,38 @@ class RestRepository extends Query {
1207
1300
  }
1208
1301
  throw new Error("Invalid arguments for create method");
1209
1302
  }
1210
- async read(recordId) {
1211
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1212
- if (cacheRecord)
1213
- return cacheRecord;
1214
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1215
- try {
1216
- const response = await getRecord({
1217
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1218
- ...fetchProps
1219
- });
1220
- const columns = await __privateMethod$2(this, _getSchemaColumns, getSchemaColumns_fn).call(this);
1221
- return initObject(this.db, columns, __privateGet$4(this, _table), response);
1222
- } catch (e) {
1223
- if (isObject(e) && e.status === 404) {
1224
- return null;
1303
+ async read(a) {
1304
+ if (Array.isArray(a)) {
1305
+ if (a.length === 0)
1306
+ return [];
1307
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1308
+ return this.getAll({ filter: { id: { $any: ids } } });
1309
+ }
1310
+ const id = isString(a) ? a : a.id;
1311
+ if (isString(id)) {
1312
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1313
+ if (cacheRecord)
1314
+ return cacheRecord;
1315
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1316
+ try {
1317
+ const response = await getRecord({
1318
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1319
+ ...fetchProps
1320
+ });
1321
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1322
+ return initObject(this.db, schema, __privateGet$4(this, _table), response);
1323
+ } catch (e) {
1324
+ if (isObject(e) && e.status === 404) {
1325
+ return null;
1326
+ }
1327
+ throw e;
1225
1328
  }
1226
- throw e;
1227
1329
  }
1228
1330
  }
1229
1331
  async update(a, b) {
1230
1332
  if (Array.isArray(a)) {
1333
+ if (a.length === 0)
1334
+ return [];
1231
1335
  if (a.length > 100) {
1232
1336
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1233
1337
  }
@@ -1249,6 +1353,8 @@ class RestRepository extends Query {
1249
1353
  }
1250
1354
  async createOrUpdate(a, b) {
1251
1355
  if (Array.isArray(a)) {
1356
+ if (a.length === 0)
1357
+ return [];
1252
1358
  if (a.length > 100) {
1253
1359
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1254
1360
  }
@@ -1270,6 +1376,8 @@ class RestRepository extends Query {
1270
1376
  }
1271
1377
  async delete(a) {
1272
1378
  if (Array.isArray(a)) {
1379
+ if (a.length === 0)
1380
+ return;
1273
1381
  if (a.length > 100) {
1274
1382
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1275
1383
  }
@@ -1290,13 +1398,18 @@ class RestRepository extends Query {
1290
1398
  }
1291
1399
  async search(query, options = {}) {
1292
1400
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1293
- const { records } = await searchBranch({
1294
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1295
- body: { tables: [__privateGet$4(this, _table)], query, fuzziness: options.fuzziness },
1401
+ const { records } = await searchTable({
1402
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1403
+ body: {
1404
+ query,
1405
+ fuzziness: options.fuzziness,
1406
+ highlight: options.highlight,
1407
+ filter: options.filter
1408
+ },
1296
1409
  ...fetchProps
1297
1410
  });
1298
- const columns = await __privateMethod$2(this, _getSchemaColumns, getSchemaColumns_fn).call(this);
1299
- return records.map((item) => initObject(this.db, columns, __privateGet$4(this, _table), item));
1411
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1412
+ return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1300
1413
  }
1301
1414
  async query(query) {
1302
1415
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
@@ -1305,8 +1418,8 @@ class RestRepository extends Query {
1305
1418
  const data = query.getQueryOptions();
1306
1419
  const body = {
1307
1420
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1308
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1309
- page: data.page,
1421
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1422
+ page: data.pagination,
1310
1423
  columns: data.columns
1311
1424
  };
1312
1425
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
@@ -1315,8 +1428,8 @@ class RestRepository extends Query {
1315
1428
  body,
1316
1429
  ...fetchProps
1317
1430
  });
1318
- const columns = await __privateMethod$2(this, _getSchemaColumns, getSchemaColumns_fn).call(this);
1319
- const records = objects.map((record) => initObject(this.db, columns, __privateGet$4(this, _table), record));
1431
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1432
+ const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1320
1433
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1321
1434
  return new Page(query, meta, records);
1322
1435
  }
@@ -1324,7 +1437,7 @@ class RestRepository extends Query {
1324
1437
  _table = new WeakMap();
1325
1438
  _getFetchProps = new WeakMap();
1326
1439
  _cache = new WeakMap();
1327
- _schemaColumns = new WeakMap();
1440
+ _schema$1 = new WeakMap();
1328
1441
  _insertRecordWithoutId = new WeakSet();
1329
1442
  insertRecordWithoutId_fn = async function(object) {
1330
1443
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
@@ -1369,16 +1482,20 @@ _bulkInsertTableRecords = new WeakSet();
1369
1482
  bulkInsertTableRecords_fn = async function(objects) {
1370
1483
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1371
1484
  const records = objects.map((object) => transformObjectLinks(object));
1372
- const response = await bulkInsertTableRecords({
1485
+ const { recordIDs } = await bulkInsertTableRecords({
1373
1486
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1374
1487
  body: { records },
1375
1488
  ...fetchProps
1376
1489
  });
1377
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1490
+ const finalObjects = await this.read(recordIDs);
1378
1491
  if (finalObjects.length !== objects.length) {
1379
1492
  throw new Error("The server failed to save some records");
1380
1493
  }
1381
- return finalObjects;
1494
+ const dictionary = finalObjects.reduce((acc, object) => {
1495
+ acc[object.id] = object;
1496
+ return acc;
1497
+ }, {});
1498
+ return recordIDs.map((id) => dictionary[id]);
1382
1499
  };
1383
1500
  _updateRecordWithID = new WeakSet();
1384
1501
  updateRecordWithID_fn = async function(recordId, object) {
@@ -1449,21 +1566,22 @@ getCacheQuery_fn = async function(query) {
1449
1566
  if (!result)
1450
1567
  return null;
1451
1568
  const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1452
- if (!ttl || ttl < 0)
1453
- return result;
1569
+ if (ttl < 0)
1570
+ return null;
1454
1571
  const hasExpired = result.date.getTime() + ttl < Date.now();
1455
1572
  return hasExpired ? null : result;
1456
1573
  };
1457
- _getSchemaColumns = new WeakSet();
1458
- getSchemaColumns_fn = async function() {
1459
- if (__privateGet$4(this, _schemaColumns))
1460
- return __privateGet$4(this, _schemaColumns);
1461
- const { columns } = await getTableSchema({
1462
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1463
- ...await __privateGet$4(this, _getFetchProps).call(this)
1574
+ _getSchema$1 = new WeakSet();
1575
+ getSchema_fn$1 = async function() {
1576
+ if (__privateGet$4(this, _schema$1))
1577
+ return __privateGet$4(this, _schema$1);
1578
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1579
+ const { schema } = await getBranchDetails({
1580
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1581
+ ...fetchProps
1464
1582
  });
1465
- __privateSet$3(this, _schemaColumns, columns);
1466
- return columns;
1583
+ __privateSet$3(this, _schema$1, schema);
1584
+ return schema;
1467
1585
  };
1468
1586
  const transformObjectLinks = (object) => {
1469
1587
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1472,17 +1590,21 @@ const transformObjectLinks = (object) => {
1472
1590
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1473
1591
  }, {});
1474
1592
  };
1475
- const initObject = (db, columns, table, object) => {
1593
+ const initObject = (db, schema, table, object) => {
1476
1594
  const result = {};
1477
- Object.assign(result, object);
1478
- for (const column of columns) {
1595
+ const { xata, ...rest } = object ?? {};
1596
+ Object.assign(result, rest);
1597
+ const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1598
+ if (!columns)
1599
+ console.error(`Table ${table} not found in schema`);
1600
+ for (const column of columns ?? []) {
1479
1601
  const value = result[column.name];
1480
1602
  switch (column.type) {
1481
1603
  case "datetime": {
1482
- const date = new Date(value);
1483
- if (isNaN(date.getTime())) {
1604
+ const date = value !== void 0 ? new Date(value) : void 0;
1605
+ if (date && isNaN(date.getTime())) {
1484
1606
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1485
- } else {
1607
+ } else if (date) {
1486
1608
  result[column.name] = date;
1487
1609
  }
1488
1610
  break;
@@ -1491,8 +1613,8 @@ const initObject = (db, columns, table, object) => {
1491
1613
  const linkTable = column.link?.table;
1492
1614
  if (!linkTable) {
1493
1615
  console.error(`Failed to parse link for field ${column.name}`);
1494
- } else if (value && isObject(value)) {
1495
- result[column.name] = initObject(db, columns, linkTable, value);
1616
+ } else if (isObject(value)) {
1617
+ result[column.name] = initObject(db, schema, linkTable, value);
1496
1618
  }
1497
1619
  break;
1498
1620
  }
@@ -1507,7 +1629,10 @@ const initObject = (db, columns, table, object) => {
1507
1629
  result.delete = function() {
1508
1630
  return db[table].delete(result["id"]);
1509
1631
  };
1510
- for (const prop of ["read", "update", "delete"]) {
1632
+ result.getMetadata = function() {
1633
+ return xata;
1634
+ };
1635
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1511
1636
  Object.defineProperty(result, prop, { enumerable: false });
1512
1637
  }
1513
1638
  Object.freeze(result);
@@ -1617,7 +1742,7 @@ class SchemaPlugin extends XataPlugin {
1617
1742
  get: (_target, table) => {
1618
1743
  if (!isString(table))
1619
1744
  throw new Error("Invalid table name");
1620
- if (!__privateGet$2(this, _tables)[table]) {
1745
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1621
1746
  __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1622
1747
  }
1623
1748
  return __privateGet$2(this, _tables)[table];
@@ -1669,11 +1794,7 @@ class SearchPlugin extends XataPlugin {
1669
1794
  const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1670
1795
  return records.map((record) => {
1671
1796
  const { table = "orphan" } = record.xata;
1672
- const columns = schema.tables.find((t) => t.name === table)?.columns;
1673
- if (!columns) {
1674
- console.error(`No schema columns found for table ${table}`);
1675
- }
1676
- return { table, record: initObject(this.db, columns ?? [], table, record) };
1797
+ return { table, record: initObject(this.db, schema, table, record) };
1677
1798
  });
1678
1799
  },
1679
1800
  byTable: async (query, options = {}) => {
@@ -1681,12 +1802,8 @@ class SearchPlugin extends XataPlugin {
1681
1802
  const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1682
1803
  return records.reduce((acc, record) => {
1683
1804
  const { table = "orphan" } = record.xata;
1684
- const columns = schema.tables.find((t) => t.name === table)?.columns;
1685
- if (!columns) {
1686
- console.error(`No schema columns found for table ${table}`);
1687
- }
1688
1805
  const items = acc[table] ?? [];
1689
- const item = initObject(this.db, columns ?? [], table, record);
1806
+ const item = initObject(this.db, schema, table, record);
1690
1807
  return { ...acc, [table]: [...items, item] };
1691
1808
  }, {});
1692
1809
  }
@@ -1697,10 +1814,10 @@ _schema = new WeakMap();
1697
1814
  _search = new WeakSet();
1698
1815
  search_fn = async function(query, options, getFetchProps) {
1699
1816
  const fetchProps = await getFetchProps();
1700
- const { tables, fuzziness } = options ?? {};
1817
+ const { tables, fuzziness, highlight } = options ?? {};
1701
1818
  const { records } = await searchBranch({
1702
1819
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1703
- body: { tables, query, fuzziness },
1820
+ body: { tables, query, fuzziness, highlight },
1704
1821
  ...fetchProps
1705
1822
  });
1706
1823
  return records;
@@ -1728,30 +1845,39 @@ const envBranchNames = [
1728
1845
  "CF_PAGES_BRANCH",
1729
1846
  "BRANCH"
1730
1847
  ];
1731
- const defaultBranch = "main";
1732
1848
  async function getCurrentBranchName(options) {
1733
- const env = await getBranchByEnvVariable();
1734
- if (env)
1735
- return env;
1736
- const branch = await getGitBranch();
1737
- if (!branch)
1738
- return defaultBranch;
1739
- const details = await getDatabaseBranch(branch, options);
1740
- if (details)
1741
- return branch;
1742
- return defaultBranch;
1849
+ const env = getBranchByEnvVariable();
1850
+ if (env) {
1851
+ const details = await getDatabaseBranch(env, options);
1852
+ if (details)
1853
+ return env;
1854
+ console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1855
+ }
1856
+ const gitBranch = await getGitBranch();
1857
+ return resolveXataBranch(gitBranch, options);
1743
1858
  }
1744
1859
  async function getCurrentBranchDetails(options) {
1745
- const env = await getBranchByEnvVariable();
1746
- if (env)
1747
- return getDatabaseBranch(env, options);
1748
- const branch = await getGitBranch();
1749
- if (!branch)
1750
- return getDatabaseBranch(defaultBranch, options);
1751
- const details = await getDatabaseBranch(branch, options);
1752
- if (details)
1753
- return details;
1754
- return getDatabaseBranch(defaultBranch, options);
1860
+ const branch = await getCurrentBranchName(options);
1861
+ return getDatabaseBranch(branch, options);
1862
+ }
1863
+ async function resolveXataBranch(gitBranch, options) {
1864
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1865
+ const apiKey = options?.apiKey || getAPIKey();
1866
+ if (!databaseURL)
1867
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1868
+ if (!apiKey)
1869
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1870
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1871
+ const [workspace] = host.split(".");
1872
+ const { branch } = await resolveBranch({
1873
+ apiKey,
1874
+ apiUrl: databaseURL,
1875
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1876
+ workspacesApiUrl: `${protocol}//${host}`,
1877
+ pathParams: { dbName, workspace },
1878
+ queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
1879
+ });
1880
+ return branch;
1755
1881
  }
1756
1882
  async function getDatabaseBranch(branch, options) {
1757
1883
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1769,10 +1895,7 @@ async function getDatabaseBranch(branch, options) {
1769
1895
  apiUrl: databaseURL,
1770
1896
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1771
1897
  workspacesApiUrl: `${protocol}//${host}`,
1772
- pathParams: {
1773
- dbBranchName,
1774
- workspace
1775
- }
1898
+ pathParams: { dbBranchName, workspace }
1776
1899
  });
1777
1900
  } catch (err) {
1778
1901
  if (isObject(err) && err.status === 404)
@@ -1840,7 +1963,7 @@ const buildClient = (plugins) => {
1840
1963
  this.db = db;
1841
1964
  this.search = search;
1842
1965
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1843
- if (!namespace)
1966
+ if (namespace === void 0)
1844
1967
  continue;
1845
1968
  const result = namespace.build(pluginOptions);
1846
1969
  if (result instanceof Promise) {
@@ -1857,7 +1980,7 @@ const buildClient = (plugins) => {
1857
1980
  const databaseURL = options?.databaseURL || getDatabaseURL();
1858
1981
  const apiKey = options?.apiKey || getAPIKey();
1859
1982
  const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1860
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1983
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1861
1984
  if (!databaseURL || !apiKey) {
1862
1985
  throw new Error("Options databaseURL and apiKey are required");
1863
1986
  }
@@ -1884,7 +2007,7 @@ const buildClient = (plugins) => {
1884
2007
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1885
2008
  if (__privateGet(this, _branch))
1886
2009
  return __privateGet(this, _branch);
1887
- if (!param)
2010
+ if (param === void 0)
1888
2011
  return void 0;
1889
2012
  const strategies = Array.isArray(param) ? [...param] : [param];
1890
2013
  const evaluateBranch = async (strategy) => {
@@ -1909,5 +2032,5 @@ class XataError extends Error {
1909
2032
  }
1910
2033
  }
1911
2034
 
1912
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2035
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
1913
2036
  //# sourceMappingURL=index.mjs.map