@xata.io/client 0.0.0-alpha.vecada6d → 0.0.0-alpha.ved669cc

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,30 +7,78 @@ 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
 
21
- function getEnvVariable(name) {
25
+ function getEnvironment() {
22
26
  try {
23
- if (isObject(process) && isString(process?.env?.[name])) {
24
- return process.env[name];
27
+ if (isObject(process) && isObject(process.env)) {
28
+ return {
29
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
30
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
31
+ branch: process.env.XATA_BRANCH ?? process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH ?? getGlobalBranch(),
32
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
33
+ };
25
34
  }
26
35
  } catch (err) {
27
36
  }
28
37
  try {
29
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
30
- return Deno.env.get(name);
38
+ if (isObject(Deno) && isObject(Deno.env)) {
39
+ return {
40
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
41
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
42
+ branch: Deno.env.get("XATA_BRANCH") ?? Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH") ?? getGlobalBranch(),
43
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
44
+ };
31
45
  }
32
46
  } catch (err) {
33
47
  }
48
+ return {
49
+ apiKey: getGlobalApiKey(),
50
+ databaseURL: getGlobalDatabaseURL(),
51
+ branch: getGlobalBranch(),
52
+ fallbackBranch: getGlobalFallbackBranch()
53
+ };
54
+ }
55
+ function getGlobalApiKey() {
56
+ try {
57
+ return XATA_API_KEY;
58
+ } catch (err) {
59
+ return void 0;
60
+ }
61
+ }
62
+ function getGlobalDatabaseURL() {
63
+ try {
64
+ return XATA_DATABASE_URL;
65
+ } catch (err) {
66
+ return void 0;
67
+ }
68
+ }
69
+ function getGlobalBranch() {
70
+ try {
71
+ return XATA_BRANCH;
72
+ } catch (err) {
73
+ return void 0;
74
+ }
75
+ }
76
+ function getGlobalFallbackBranch() {
77
+ try {
78
+ return XATA_FALLBACK_BRANCH;
79
+ } catch (err) {
80
+ return void 0;
81
+ }
34
82
  }
35
83
  async function getGitBranch() {
36
84
  try {
@@ -55,7 +103,8 @@ async function getGitBranch() {
55
103
 
56
104
  function getAPIKey() {
57
105
  try {
58
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
106
+ const { apiKey } = getEnvironment();
107
+ return apiKey;
59
108
  } catch (err) {
60
109
  return void 0;
61
110
  }
@@ -70,16 +119,28 @@ function getFetchImplementation(userFetch) {
70
119
  return fetchImpl;
71
120
  }
72
121
 
73
- class FetcherError extends Error {
74
- constructor(status, data) {
122
+ const VERSION = "0.0.0-alpha.ved669cc";
123
+
124
+ class ErrorWithCause extends Error {
125
+ constructor(message, options) {
126
+ super(message, options);
127
+ }
128
+ }
129
+ class FetcherError extends ErrorWithCause {
130
+ constructor(status, data, requestId) {
75
131
  super(getMessage(data));
76
132
  this.status = status;
77
133
  this.errors = isBulkError(data) ? data.errors : void 0;
134
+ this.requestId = requestId;
78
135
  if (data instanceof Error) {
79
136
  this.stack = data.stack;
80
137
  this.cause = data.cause;
81
138
  }
82
139
  }
140
+ toString() {
141
+ const error = super.toString();
142
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
143
+ }
83
144
  }
84
145
  function isBulkError(error) {
85
146
  return isObject(error) && Array.isArray(error.errors);
@@ -102,7 +163,12 @@ function getMessage(data) {
102
163
  }
103
164
 
104
165
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
105
- const query = new URLSearchParams(queryParams).toString();
166
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
167
+ if (value === void 0 || value === null)
168
+ return acc;
169
+ return { ...acc, [key]: value };
170
+ }, {});
171
+ const query = new URLSearchParams(cleanQueryParams).toString();
106
172
  const queryString = query.length > 0 ? `?${query}` : "";
107
173
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
108
174
  };
@@ -142,6 +208,7 @@ async function fetch$1({
142
208
  body: body ? JSON.stringify(body) : void 0,
143
209
  headers: {
144
210
  "Content-Type": "application/json",
211
+ "User-Agent": `Xata client-ts/${VERSION}`,
145
212
  ...headers,
146
213
  ...hostHeader(fullUrl),
147
214
  Authorization: `Bearer ${apiKey}`
@@ -150,14 +217,15 @@ async function fetch$1({
150
217
  if (response.status === 204) {
151
218
  return {};
152
219
  }
220
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
153
221
  try {
154
222
  const jsonResponse = await response.json();
155
223
  if (response.ok) {
156
224
  return jsonResponse;
157
225
  }
158
- throw new FetcherError(response.status, jsonResponse);
226
+ throw new FetcherError(response.status, jsonResponse, requestId);
159
227
  } catch (error) {
160
- throw new FetcherError(response.status, error);
228
+ throw new FetcherError(response.status, error, requestId);
161
229
  }
162
230
  }
163
231
 
@@ -477,7 +545,7 @@ var __privateAdd$7 = (obj, member, value) => {
477
545
  throw TypeError("Cannot add the same private member more than once");
478
546
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
479
547
  };
480
- var __privateSet$6 = (obj, member, value, setter) => {
548
+ var __privateSet$7 = (obj, member, value, setter) => {
481
549
  __accessCheck$7(obj, member, "write to private field");
482
550
  setter ? setter.call(obj, value) : member.set(obj, value);
483
551
  return value;
@@ -492,7 +560,7 @@ class XataApiClient {
492
560
  if (!apiKey) {
493
561
  throw new Error("Could not resolve a valid apiKey");
494
562
  }
495
- __privateSet$6(this, _extraProps, {
563
+ __privateSet$7(this, _extraProps, {
496
564
  apiUrl: getHostUrl(provider, "main"),
497
565
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
498
566
  fetchImpl: getFetchImplementation(options.fetch),
@@ -681,10 +749,10 @@ class DatabaseApi {
681
749
  ...this.extraProps
682
750
  });
683
751
  }
684
- resolveBranch(workspace, dbName, gitBranch) {
752
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
685
753
  return operationsByTag.database.resolveBranch({
686
754
  pathParams: { workspace, dbName },
687
- queryParams: { gitBranch },
755
+ queryParams: { gitBranch, fallbackBranch },
688
756
  ...this.extraProps
689
757
  });
690
758
  }
@@ -929,18 +997,18 @@ var __privateAdd$6 = (obj, member, value) => {
929
997
  throw TypeError("Cannot add the same private member more than once");
930
998
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
931
999
  };
932
- var __privateSet$5 = (obj, member, value, setter) => {
1000
+ var __privateSet$6 = (obj, member, value, setter) => {
933
1001
  __accessCheck$6(obj, member, "write to private field");
934
1002
  setter ? setter.call(obj, value) : member.set(obj, value);
935
1003
  return value;
936
1004
  };
937
- var _query;
1005
+ var _query, _page;
938
1006
  class Page {
939
1007
  constructor(query, meta, records = []) {
940
1008
  __privateAdd$6(this, _query, void 0);
941
- __privateSet$5(this, _query, query);
1009
+ __privateSet$6(this, _query, query);
942
1010
  this.meta = meta;
943
- this.records = records;
1011
+ this.records = new RecordArray(this, records);
944
1012
  }
945
1013
  async nextPage(size, offset) {
946
1014
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
@@ -960,9 +1028,50 @@ class Page {
960
1028
  }
961
1029
  _query = new WeakMap();
962
1030
  const PAGINATION_MAX_SIZE = 200;
963
- const PAGINATION_DEFAULT_SIZE = 200;
1031
+ const PAGINATION_DEFAULT_SIZE = 20;
964
1032
  const PAGINATION_MAX_OFFSET = 800;
965
1033
  const PAGINATION_DEFAULT_OFFSET = 0;
1034
+ function isCursorPaginationOptions(options) {
1035
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1036
+ }
1037
+ const _RecordArray = class extends Array {
1038
+ constructor(page, overrideRecords) {
1039
+ super(..._RecordArray.parseConstructorParams(page, overrideRecords));
1040
+ __privateAdd$6(this, _page, void 0);
1041
+ __privateSet$6(this, _page, page);
1042
+ }
1043
+ static parseConstructorParams(...args) {
1044
+ if (args.length === 1 && typeof args[0] === "number") {
1045
+ return new Array(args[0]);
1046
+ }
1047
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1048
+ const result = args[1] ?? args[0].records ?? [];
1049
+ return new Array(...result);
1050
+ }
1051
+ return new Array(...args);
1052
+ }
1053
+ async nextPage(size, offset) {
1054
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1055
+ return new _RecordArray(newPage);
1056
+ }
1057
+ async previousPage(size, offset) {
1058
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1059
+ return new _RecordArray(newPage);
1060
+ }
1061
+ async firstPage(size, offset) {
1062
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1063
+ return new _RecordArray(newPage);
1064
+ }
1065
+ async lastPage(size, offset) {
1066
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1067
+ return new _RecordArray(newPage);
1068
+ }
1069
+ hasNextPage() {
1070
+ return __privateGet$6(this, _page).meta.page.more;
1071
+ }
1072
+ };
1073
+ let RecordArray = _RecordArray;
1074
+ _page = new WeakMap();
966
1075
 
967
1076
  var __accessCheck$5 = (obj, member, msg) => {
968
1077
  if (!member.has(obj))
@@ -977,25 +1086,26 @@ var __privateAdd$5 = (obj, member, value) => {
977
1086
  throw TypeError("Cannot add the same private member more than once");
978
1087
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
979
1088
  };
980
- var __privateSet$4 = (obj, member, value, setter) => {
1089
+ var __privateSet$5 = (obj, member, value, setter) => {
981
1090
  __accessCheck$5(obj, member, "write to private field");
982
1091
  setter ? setter.call(obj, value) : member.set(obj, value);
983
1092
  return value;
984
1093
  };
985
1094
  var _table$1, _repository, _data;
986
1095
  const _Query = class {
987
- constructor(repository, table, data, parent) {
1096
+ constructor(repository, table, data, rawParent) {
988
1097
  __privateAdd$5(this, _table$1, void 0);
989
1098
  __privateAdd$5(this, _repository, void 0);
990
1099
  __privateAdd$5(this, _data, { filter: {} });
991
1100
  this.meta = { page: { cursor: "start", more: true } };
992
- this.records = [];
993
- __privateSet$4(this, _table$1, table);
1101
+ this.records = new RecordArray(this, []);
1102
+ __privateSet$5(this, _table$1, table);
994
1103
  if (repository) {
995
- __privateSet$4(this, _repository, repository);
1104
+ __privateSet$5(this, _repository, repository);
996
1105
  } else {
997
- __privateSet$4(this, _repository, this);
1106
+ __privateSet$5(this, _repository, this);
998
1107
  }
1108
+ const parent = cleanParent(data, rawParent);
999
1109
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1000
1110
  __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1001
1111
  __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
@@ -1067,18 +1177,21 @@ const _Query = class {
1067
1177
  }
1068
1178
  async *getIterator(options = {}) {
1069
1179
  const { batchSize = 1 } = options;
1070
- let offset = 0;
1071
- let end = false;
1072
- while (!end) {
1073
- const { records, meta } = await this.getPaginated({ ...options, pagination: { size: batchSize, offset } });
1074
- yield records;
1075
- offset += batchSize;
1076
- end = !meta.page.more;
1180
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1181
+ let more = page.hasNextPage();
1182
+ yield page.records;
1183
+ while (more) {
1184
+ page = await page.nextPage();
1185
+ more = page.hasNextPage();
1186
+ yield page.records;
1077
1187
  }
1078
1188
  }
1079
1189
  async getMany(options = {}) {
1080
- const { records } = await this.getPaginated(options);
1081
- return records;
1190
+ const page = await this.getPaginated(options);
1191
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1192
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1193
+ }
1194
+ return page.records;
1082
1195
  }
1083
1196
  async getAll(options = {}) {
1084
1197
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1115,12 +1228,20 @@ let Query = _Query;
1115
1228
  _table$1 = new WeakMap();
1116
1229
  _repository = new WeakMap();
1117
1230
  _data = new WeakMap();
1231
+ function cleanParent(data, parent) {
1232
+ if (isCursorPaginationOptions(data.pagination)) {
1233
+ return { ...parent, sorting: void 0, filter: void 0 };
1234
+ }
1235
+ return parent;
1236
+ }
1118
1237
 
1119
1238
  function isIdentifiable(x) {
1120
1239
  return isObject(x) && isString(x?.id);
1121
1240
  }
1122
1241
  function isXataRecord(x) {
1123
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1242
+ const record = x;
1243
+ const metadata = record?.getMetadata();
1244
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1124
1245
  }
1125
1246
 
1126
1247
  function isSortFilterString(value) {
@@ -1159,7 +1280,7 @@ var __privateAdd$4 = (obj, member, value) => {
1159
1280
  throw TypeError("Cannot add the same private member more than once");
1160
1281
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1161
1282
  };
1162
- var __privateSet$3 = (obj, member, value, setter) => {
1283
+ var __privateSet$4 = (obj, member, value, setter) => {
1163
1284
  __accessCheck$4(obj, member, "write to private field");
1164
1285
  setter ? setter.call(obj, value) : member.set(obj, value);
1165
1286
  return value;
@@ -1168,7 +1289,7 @@ var __privateMethod$2 = (obj, member, method) => {
1168
1289
  __accessCheck$4(obj, member, "access private method");
1169
1290
  return method;
1170
1291
  };
1171
- 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;
1292
+ var _table, _getFetchProps, _cache, _schemaTables$2, _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, _getSchemaTables$1, getSchemaTables_fn$1;
1172
1293
  class Repository extends Query {
1173
1294
  }
1174
1295
  class RestRepository extends Query {
@@ -1185,18 +1306,21 @@ class RestRepository extends Query {
1185
1306
  __privateAdd$4(this, _getCacheRecord);
1186
1307
  __privateAdd$4(this, _setCacheQuery);
1187
1308
  __privateAdd$4(this, _getCacheQuery);
1188
- __privateAdd$4(this, _getSchema$1);
1309
+ __privateAdd$4(this, _getSchemaTables$1);
1189
1310
  __privateAdd$4(this, _table, void 0);
1190
1311
  __privateAdd$4(this, _getFetchProps, void 0);
1191
1312
  __privateAdd$4(this, _cache, void 0);
1192
- __privateAdd$4(this, _schema$1, void 0);
1193
- __privateSet$3(this, _table, options.table);
1194
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1313
+ __privateAdd$4(this, _schemaTables$2, void 0);
1314
+ __privateSet$4(this, _table, options.table);
1315
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1195
1316
  this.db = options.db;
1196
- __privateSet$3(this, _cache, options.pluginOptions.cache);
1317
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1318
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1197
1319
  }
1198
1320
  async create(a, b) {
1199
1321
  if (Array.isArray(a)) {
1322
+ if (a.length === 0)
1323
+ return [];
1200
1324
  const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1201
1325
  await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1202
1326
  return records;
@@ -1222,27 +1346,38 @@ class RestRepository extends Query {
1222
1346
  }
1223
1347
  throw new Error("Invalid arguments for create method");
1224
1348
  }
1225
- async read(recordId) {
1226
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1227
- if (cacheRecord)
1228
- return cacheRecord;
1229
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1230
- try {
1231
- const response = await getRecord({
1232
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1233
- ...fetchProps
1234
- });
1235
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1236
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1237
- } catch (e) {
1238
- if (isObject(e) && e.status === 404) {
1239
- return null;
1349
+ async read(a) {
1350
+ if (Array.isArray(a)) {
1351
+ if (a.length === 0)
1352
+ return [];
1353
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1354
+ return this.getAll({ filter: { id: { $any: ids } } });
1355
+ }
1356
+ const id = isString(a) ? a : a.id;
1357
+ if (isString(id)) {
1358
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1359
+ if (cacheRecord)
1360
+ return cacheRecord;
1361
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1362
+ try {
1363
+ const response = await getRecord({
1364
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1365
+ ...fetchProps
1366
+ });
1367
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1368
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1369
+ } catch (e) {
1370
+ if (isObject(e) && e.status === 404) {
1371
+ return null;
1372
+ }
1373
+ throw e;
1240
1374
  }
1241
- throw e;
1242
1375
  }
1243
1376
  }
1244
1377
  async update(a, b) {
1245
1378
  if (Array.isArray(a)) {
1379
+ if (a.length === 0)
1380
+ return [];
1246
1381
  if (a.length > 100) {
1247
1382
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1248
1383
  }
@@ -1264,6 +1399,8 @@ class RestRepository extends Query {
1264
1399
  }
1265
1400
  async createOrUpdate(a, b) {
1266
1401
  if (Array.isArray(a)) {
1402
+ if (a.length === 0)
1403
+ return [];
1267
1404
  if (a.length > 100) {
1268
1405
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1269
1406
  }
@@ -1285,6 +1422,8 @@ class RestRepository extends Query {
1285
1422
  }
1286
1423
  async delete(a) {
1287
1424
  if (Array.isArray(a)) {
1425
+ if (a.length === 0)
1426
+ return;
1288
1427
  if (a.length > 100) {
1289
1428
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1290
1429
  }
@@ -1310,12 +1449,13 @@ class RestRepository extends Query {
1310
1449
  body: {
1311
1450
  query,
1312
1451
  fuzziness: options.fuzziness,
1452
+ highlight: options.highlight,
1313
1453
  filter: options.filter
1314
1454
  },
1315
1455
  ...fetchProps
1316
1456
  });
1317
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1318
- return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1457
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1458
+ return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1319
1459
  }
1320
1460
  async query(query) {
1321
1461
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
@@ -1334,8 +1474,8 @@ class RestRepository extends Query {
1334
1474
  body,
1335
1475
  ...fetchProps
1336
1476
  });
1337
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1338
- const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1477
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1478
+ const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1339
1479
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1340
1480
  return new Page(query, meta, records);
1341
1481
  }
@@ -1343,7 +1483,7 @@ class RestRepository extends Query {
1343
1483
  _table = new WeakMap();
1344
1484
  _getFetchProps = new WeakMap();
1345
1485
  _cache = new WeakMap();
1346
- _schema$1 = new WeakMap();
1486
+ _schemaTables$2 = new WeakMap();
1347
1487
  _insertRecordWithoutId = new WeakSet();
1348
1488
  insertRecordWithoutId_fn = async function(object) {
1349
1489
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
@@ -1388,16 +1528,20 @@ _bulkInsertTableRecords = new WeakSet();
1388
1528
  bulkInsertTableRecords_fn = async function(objects) {
1389
1529
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1390
1530
  const records = objects.map((object) => transformObjectLinks(object));
1391
- const response = await bulkInsertTableRecords({
1531
+ const { recordIDs } = await bulkInsertTableRecords({
1392
1532
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1393
1533
  body: { records },
1394
1534
  ...fetchProps
1395
1535
  });
1396
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1536
+ const finalObjects = await this.read(recordIDs);
1397
1537
  if (finalObjects.length !== objects.length) {
1398
1538
  throw new Error("The server failed to save some records");
1399
1539
  }
1400
- return finalObjects;
1540
+ const dictionary = finalObjects.reduce((acc, object) => {
1541
+ acc[object.id] = object;
1542
+ return acc;
1543
+ }, {});
1544
+ return recordIDs.map((id) => dictionary[id]);
1401
1545
  };
1402
1546
  _updateRecordWithID = new WeakSet();
1403
1547
  updateRecordWithID_fn = async function(recordId, object) {
@@ -1473,17 +1617,17 @@ getCacheQuery_fn = async function(query) {
1473
1617
  const hasExpired = result.date.getTime() + ttl < Date.now();
1474
1618
  return hasExpired ? null : result;
1475
1619
  };
1476
- _getSchema$1 = new WeakSet();
1477
- getSchema_fn$1 = async function() {
1478
- if (__privateGet$4(this, _schema$1))
1479
- return __privateGet$4(this, _schema$1);
1620
+ _getSchemaTables$1 = new WeakSet();
1621
+ getSchemaTables_fn$1 = async function() {
1622
+ if (__privateGet$4(this, _schemaTables$2))
1623
+ return __privateGet$4(this, _schemaTables$2);
1480
1624
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1481
1625
  const { schema } = await getBranchDetails({
1482
1626
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1483
1627
  ...fetchProps
1484
1628
  });
1485
- __privateSet$3(this, _schema$1, schema);
1486
- return schema;
1629
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1630
+ return schema.tables;
1487
1631
  };
1488
1632
  const transformObjectLinks = (object) => {
1489
1633
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1492,20 +1636,21 @@ const transformObjectLinks = (object) => {
1492
1636
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1493
1637
  }, {});
1494
1638
  };
1495
- const initObject = (db, schema, table, object) => {
1639
+ const initObject = (db, schemaTables, table, object) => {
1496
1640
  const result = {};
1497
- Object.assign(result, object);
1498
- const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1641
+ const { xata, ...rest } = object ?? {};
1642
+ Object.assign(result, rest);
1643
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1499
1644
  if (!columns)
1500
1645
  console.error(`Table ${table} not found in schema`);
1501
1646
  for (const column of columns ?? []) {
1502
1647
  const value = result[column.name];
1503
1648
  switch (column.type) {
1504
1649
  case "datetime": {
1505
- const date = new Date(value);
1506
- if (isNaN(date.getTime())) {
1650
+ const date = value !== void 0 ? new Date(value) : void 0;
1651
+ if (date && isNaN(date.getTime())) {
1507
1652
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1508
- } else {
1653
+ } else if (date) {
1509
1654
  result[column.name] = date;
1510
1655
  }
1511
1656
  break;
@@ -1515,7 +1660,7 @@ const initObject = (db, schema, table, object) => {
1515
1660
  if (!linkTable) {
1516
1661
  console.error(`Failed to parse link for field ${column.name}`);
1517
1662
  } else if (isObject(value)) {
1518
- result[column.name] = initObject(db, schema, linkTable, value);
1663
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1519
1664
  }
1520
1665
  break;
1521
1666
  }
@@ -1530,7 +1675,10 @@ const initObject = (db, schema, table, object) => {
1530
1675
  result.delete = function() {
1531
1676
  return db[table].delete(result["id"]);
1532
1677
  };
1533
- for (const prop of ["read", "update", "delete"]) {
1678
+ result.getMetadata = function() {
1679
+ return xata;
1680
+ };
1681
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1534
1682
  Object.defineProperty(result, prop, { enumerable: false });
1535
1683
  }
1536
1684
  Object.freeze(result);
@@ -1559,7 +1707,7 @@ var __privateAdd$3 = (obj, member, value) => {
1559
1707
  throw TypeError("Cannot add the same private member more than once");
1560
1708
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1561
1709
  };
1562
- var __privateSet$2 = (obj, member, value, setter) => {
1710
+ var __privateSet$3 = (obj, member, value, setter) => {
1563
1711
  __accessCheck$3(obj, member, "write to private field");
1564
1712
  setter ? setter.call(obj, value) : member.set(obj, value);
1565
1713
  return value;
@@ -1568,7 +1716,7 @@ var _map;
1568
1716
  class SimpleCache {
1569
1717
  constructor(options = {}) {
1570
1718
  __privateAdd$3(this, _map, void 0);
1571
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1719
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1572
1720
  this.capacity = options.max ?? 500;
1573
1721
  this.cacheRecords = options.cacheRecords ?? true;
1574
1722
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
@@ -1628,12 +1776,18 @@ var __privateAdd$2 = (obj, member, value) => {
1628
1776
  throw TypeError("Cannot add the same private member more than once");
1629
1777
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1630
1778
  };
1631
- var _tables;
1779
+ var __privateSet$2 = (obj, member, value, setter) => {
1780
+ __accessCheck$2(obj, member, "write to private field");
1781
+ setter ? setter.call(obj, value) : member.set(obj, value);
1782
+ return value;
1783
+ };
1784
+ var _tables, _schemaTables$1;
1632
1785
  class SchemaPlugin extends XataPlugin {
1633
- constructor(tableNames) {
1786
+ constructor(schemaTables) {
1634
1787
  super();
1635
- this.tableNames = tableNames;
1636
1788
  __privateAdd$2(this, _tables, {});
1789
+ __privateAdd$2(this, _schemaTables$1, void 0);
1790
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1637
1791
  }
1638
1792
  build(pluginOptions) {
1639
1793
  const db = new Proxy({}, {
@@ -1646,13 +1800,15 @@ class SchemaPlugin extends XataPlugin {
1646
1800
  return __privateGet$2(this, _tables)[table];
1647
1801
  }
1648
1802
  });
1649
- for (const table of this.tableNames ?? []) {
1650
- db[table] = new RestRepository({ db, pluginOptions, table });
1803
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1804
+ for (const table of tableNames) {
1805
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1651
1806
  }
1652
1807
  return db;
1653
1808
  }
1654
1809
  }
1655
1810
  _tables = new WeakMap();
1811
+ _schemaTables$1 = new WeakMap();
1656
1812
 
1657
1813
  var __accessCheck$1 = (obj, member, msg) => {
1658
1814
  if (!member.has(obj))
@@ -1676,80 +1832,75 @@ var __privateMethod$1 = (obj, member, method) => {
1676
1832
  __accessCheck$1(obj, member, "access private method");
1677
1833
  return method;
1678
1834
  };
1679
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
1835
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1680
1836
  class SearchPlugin extends XataPlugin {
1681
- constructor(db) {
1837
+ constructor(db, schemaTables) {
1682
1838
  super();
1683
1839
  this.db = db;
1684
1840
  __privateAdd$1(this, _search);
1685
- __privateAdd$1(this, _getSchema);
1686
- __privateAdd$1(this, _schema, void 0);
1841
+ __privateAdd$1(this, _getSchemaTables);
1842
+ __privateAdd$1(this, _schemaTables, void 0);
1843
+ __privateSet$1(this, _schemaTables, schemaTables);
1687
1844
  }
1688
1845
  build({ getFetchProps }) {
1689
1846
  return {
1690
1847
  all: async (query, options = {}) => {
1691
1848
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1692
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1849
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1693
1850
  return records.map((record) => {
1694
1851
  const { table = "orphan" } = record.xata;
1695
- return { table, record: initObject(this.db, schema, table, record) };
1852
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1696
1853
  });
1697
1854
  },
1698
1855
  byTable: async (query, options = {}) => {
1699
1856
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1700
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1857
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1701
1858
  return records.reduce((acc, record) => {
1702
1859
  const { table = "orphan" } = record.xata;
1703
1860
  const items = acc[table] ?? [];
1704
- const item = initObject(this.db, schema, table, record);
1861
+ const item = initObject(this.db, schemaTables, table, record);
1705
1862
  return { ...acc, [table]: [...items, item] };
1706
1863
  }, {});
1707
1864
  }
1708
1865
  };
1709
1866
  }
1710
1867
  }
1711
- _schema = new WeakMap();
1868
+ _schemaTables = new WeakMap();
1712
1869
  _search = new WeakSet();
1713
1870
  search_fn = async function(query, options, getFetchProps) {
1714
1871
  const fetchProps = await getFetchProps();
1715
- const { tables, fuzziness } = options ?? {};
1872
+ const { tables, fuzziness, highlight } = options ?? {};
1716
1873
  const { records } = await searchBranch({
1717
1874
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1718
- body: { tables, query, fuzziness },
1875
+ body: { tables, query, fuzziness, highlight },
1719
1876
  ...fetchProps
1720
1877
  });
1721
1878
  return records;
1722
1879
  };
1723
- _getSchema = new WeakSet();
1724
- getSchema_fn = async function(getFetchProps) {
1725
- if (__privateGet$1(this, _schema))
1726
- return __privateGet$1(this, _schema);
1880
+ _getSchemaTables = new WeakSet();
1881
+ getSchemaTables_fn = async function(getFetchProps) {
1882
+ if (__privateGet$1(this, _schemaTables))
1883
+ return __privateGet$1(this, _schemaTables);
1727
1884
  const fetchProps = await getFetchProps();
1728
1885
  const { schema } = await getBranchDetails({
1729
1886
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1730
1887
  ...fetchProps
1731
1888
  });
1732
- __privateSet$1(this, _schema, schema);
1733
- return schema;
1889
+ __privateSet$1(this, _schemaTables, schema.tables);
1890
+ return schema.tables;
1734
1891
  };
1735
1892
 
1736
1893
  const isBranchStrategyBuilder = (strategy) => {
1737
1894
  return typeof strategy === "function";
1738
1895
  };
1739
1896
 
1740
- const envBranchNames = [
1741
- "XATA_BRANCH",
1742
- "VERCEL_GIT_COMMIT_REF",
1743
- "CF_PAGES_BRANCH",
1744
- "BRANCH"
1745
- ];
1746
1897
  async function getCurrentBranchName(options) {
1747
- const env = getBranchByEnvVariable();
1748
- if (env) {
1749
- const details = await getDatabaseBranch(env, options);
1898
+ const { branch } = getEnvironment();
1899
+ if (branch) {
1900
+ const details = await getDatabaseBranch(branch, options);
1750
1901
  if (details)
1751
- return env;
1752
- console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1902
+ return branch;
1903
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1753
1904
  }
1754
1905
  const gitBranch = await getGitBranch();
1755
1906
  return resolveXataBranch(gitBranch, options);
@@ -1767,13 +1918,14 @@ async function resolveXataBranch(gitBranch, options) {
1767
1918
  throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1768
1919
  const [protocol, , host, , dbName] = databaseURL.split("/");
1769
1920
  const [workspace] = host.split(".");
1921
+ const { fallbackBranch } = getEnvironment();
1770
1922
  const { branch } = await resolveBranch({
1771
1923
  apiKey,
1772
1924
  apiUrl: databaseURL,
1773
1925
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1774
1926
  workspacesApiUrl: `${protocol}//${host}`,
1775
1927
  pathParams: { dbName, workspace },
1776
- queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
1928
+ queryParams: { gitBranch, fallbackBranch }
1777
1929
  });
1778
1930
  return branch;
1779
1931
  }
@@ -1793,10 +1945,7 @@ async function getDatabaseBranch(branch, options) {
1793
1945
  apiUrl: databaseURL,
1794
1946
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1795
1947
  workspacesApiUrl: `${protocol}//${host}`,
1796
- pathParams: {
1797
- dbBranchName,
1798
- workspace
1799
- }
1948
+ pathParams: { dbBranchName, workspace }
1800
1949
  });
1801
1950
  } catch (err) {
1802
1951
  if (isObject(err) && err.status === 404)
@@ -1804,21 +1953,10 @@ async function getDatabaseBranch(branch, options) {
1804
1953
  throw err;
1805
1954
  }
1806
1955
  }
1807
- function getBranchByEnvVariable() {
1808
- for (const name of envBranchNames) {
1809
- const value = getEnvVariable(name);
1810
- if (value) {
1811
- return value;
1812
- }
1813
- }
1814
- try {
1815
- return XATA_BRANCH;
1816
- } catch (err) {
1817
- }
1818
- }
1819
1956
  function getDatabaseURL() {
1820
1957
  try {
1821
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1958
+ const { databaseURL } = getEnvironment();
1959
+ return databaseURL;
1822
1960
  } catch (err) {
1823
1961
  return void 0;
1824
1962
  }
@@ -1849,7 +1987,7 @@ var __privateMethod = (obj, member, method) => {
1849
1987
  const buildClient = (plugins) => {
1850
1988
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1851
1989
  return _a = class {
1852
- constructor(options = {}, tables) {
1990
+ constructor(options = {}, schemaTables) {
1853
1991
  __privateAdd(this, _parseOptions);
1854
1992
  __privateAdd(this, _getFetchProps);
1855
1993
  __privateAdd(this, _evaluateBranch);
@@ -1859,8 +1997,8 @@ const buildClient = (plugins) => {
1859
1997
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1860
1998
  cache: safeOptions.cache
1861
1999
  };
1862
- const db = new SchemaPlugin(tables).build(pluginOptions);
1863
- const search = new SearchPlugin(db).build(pluginOptions);
2000
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2001
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1864
2002
  this.db = db;
1865
2003
  this.search = search;
1866
2004
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
@@ -1933,5 +2071,5 @@ class XataError extends Error {
1933
2071
  }
1934
2072
  }
1935
2073
 
1936
- 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, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2074
+ 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 };
1937
2075
  //# sourceMappingURL=index.mjs.map