@xata.io/client 0.0.0-alpha.vfee45b2 → 0.0.0-alpha.vfef462e

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
@@ -13,43 +13,95 @@ function isDefined(value) {
13
13
  function isString(value) {
14
14
  return isDefined(value) && typeof value === "string";
15
15
  }
16
+ function isStringArray(value) {
17
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
18
+ }
16
19
  function toBase64(value) {
17
20
  try {
18
21
  return btoa(value);
19
22
  } catch (err) {
20
- return Buffer.from(value).toString("base64");
23
+ const buf = Buffer;
24
+ return buf.from(value).toString("base64");
21
25
  }
22
26
  }
23
27
 
24
- function getEnvVariable(name) {
28
+ function getEnvironment() {
25
29
  try {
26
- if (isObject(process) && isString(process?.env?.[name])) {
27
- return process.env[name];
30
+ if (isObject(process) && isObject(process.env)) {
31
+ return {
32
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
33
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
34
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
35
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
36
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
37
+ };
28
38
  }
29
39
  } catch (err) {
30
40
  }
31
41
  try {
32
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
33
- return Deno.env.get(name);
42
+ if (isObject(Deno) && isObject(Deno.env)) {
43
+ return {
44
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
45
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
46
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
47
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
48
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
49
+ };
34
50
  }
35
51
  } catch (err) {
36
52
  }
53
+ return {
54
+ apiKey: getGlobalApiKey(),
55
+ databaseURL: getGlobalDatabaseURL(),
56
+ branch: getGlobalBranch(),
57
+ envBranch: void 0,
58
+ fallbackBranch: getGlobalFallbackBranch()
59
+ };
60
+ }
61
+ function getGlobalApiKey() {
62
+ try {
63
+ return XATA_API_KEY;
64
+ } catch (err) {
65
+ return void 0;
66
+ }
67
+ }
68
+ function getGlobalDatabaseURL() {
69
+ try {
70
+ return XATA_DATABASE_URL;
71
+ } catch (err) {
72
+ return void 0;
73
+ }
74
+ }
75
+ function getGlobalBranch() {
76
+ try {
77
+ return XATA_BRANCH;
78
+ } catch (err) {
79
+ return void 0;
80
+ }
81
+ }
82
+ function getGlobalFallbackBranch() {
83
+ try {
84
+ return XATA_FALLBACK_BRANCH;
85
+ } catch (err) {
86
+ return void 0;
87
+ }
37
88
  }
38
89
  async function getGitBranch() {
90
+ const cmd = ["git", "branch", "--show-current"];
91
+ const fullCmd = cmd.join(" ");
92
+ const nodeModule = ["child", "process"].join("_");
93
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
39
94
  try {
40
95
  if (typeof require === "function") {
41
- const req = require;
42
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
96
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
43
97
  }
98
+ const { execSync } = await import(nodeModule);
99
+ return execSync(fullCmd, execOptions).toString().trim();
44
100
  } catch (err) {
45
101
  }
46
102
  try {
47
103
  if (isObject(Deno)) {
48
- const process2 = Deno.run({
49
- cmd: ["git", "branch", "--show-current"],
50
- stdout: "piped",
51
- stderr: "piped"
52
- });
104
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
53
105
  return new TextDecoder().decode(await process2.output()).trim();
54
106
  }
55
107
  } catch (err) {
@@ -58,7 +110,8 @@ async function getGitBranch() {
58
110
 
59
111
  function getAPIKey() {
60
112
  try {
61
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
113
+ const { apiKey } = getEnvironment();
114
+ return apiKey;
62
115
  } catch (err) {
63
116
  return void 0;
64
117
  }
@@ -68,26 +121,35 @@ function getFetchImplementation(userFetch) {
68
121
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
69
122
  const fetchImpl = userFetch ?? globalFetch;
70
123
  if (!fetchImpl) {
71
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
124
+ throw new Error(
125
+ `The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`
126
+ );
72
127
  }
73
128
  return fetchImpl;
74
129
  }
75
130
 
131
+ const VERSION = "0.0.0-alpha.vfef462e";
132
+
76
133
  class ErrorWithCause extends Error {
77
134
  constructor(message, options) {
78
135
  super(message, options);
79
136
  }
80
137
  }
81
138
  class FetcherError extends ErrorWithCause {
82
- constructor(status, data) {
139
+ constructor(status, data, requestId) {
83
140
  super(getMessage(data));
84
141
  this.status = status;
85
142
  this.errors = isBulkError(data) ? data.errors : void 0;
143
+ this.requestId = requestId;
86
144
  if (data instanceof Error) {
87
145
  this.stack = data.stack;
88
146
  this.cause = data.cause;
89
147
  }
90
148
  }
149
+ toString() {
150
+ const error = super.toString();
151
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
152
+ }
91
153
  }
92
154
  function isBulkError(error) {
93
155
  return isObject(error) && Array.isArray(error.errors);
@@ -110,7 +172,12 @@ function getMessage(data) {
110
172
  }
111
173
 
112
174
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
113
- const query = new URLSearchParams(queryParams).toString();
175
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
176
+ if (value === void 0 || value === null)
177
+ return acc;
178
+ return { ...acc, [key]: value };
179
+ }, {});
180
+ const query = new URLSearchParams(cleanQueryParams).toString();
114
181
  const queryString = query.length > 0 ? `?${query}` : "";
115
182
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
116
183
  };
@@ -150,6 +217,7 @@ async function fetch$1({
150
217
  body: body ? JSON.stringify(body) : void 0,
151
218
  headers: {
152
219
  "Content-Type": "application/json",
220
+ "User-Agent": `Xata client-ts/${VERSION}`,
153
221
  ...headers,
154
222
  ...hostHeader(fullUrl),
155
223
  Authorization: `Bearer ${apiKey}`
@@ -158,14 +226,15 @@ async function fetch$1({
158
226
  if (response.status === 204) {
159
227
  return {};
160
228
  }
229
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
161
230
  try {
162
231
  const jsonResponse = await response.json();
163
232
  if (response.ok) {
164
233
  return jsonResponse;
165
234
  }
166
- throw new FetcherError(response.status, jsonResponse);
235
+ throw new FetcherError(response.status, jsonResponse, requestId);
167
236
  } catch (error) {
168
- throw new FetcherError(response.status, error);
237
+ throw new FetcherError(response.status, error, requestId);
169
238
  }
170
239
  }
171
240
 
@@ -224,6 +293,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
224
293
  ...variables
225
294
  });
226
295
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
296
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
227
297
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
228
298
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
229
299
  method: "delete",
@@ -272,11 +342,7 @@ const getBranchDetails = (variables) => fetch$1({
272
342
  method: "get",
273
343
  ...variables
274
344
  });
275
- const createBranch = (variables) => fetch$1({
276
- url: "/db/{dbBranchName}",
277
- method: "put",
278
- ...variables
279
- });
345
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
280
346
  const deleteBranch = (variables) => fetch$1({
281
347
  url: "/db/{dbBranchName}",
282
348
  method: "delete",
@@ -350,11 +416,7 @@ const updateColumn = (variables) => fetch$1({
350
416
  method: "patch",
351
417
  ...variables
352
418
  });
353
- const insertRecord = (variables) => fetch$1({
354
- url: "/db/{dbBranchName}/tables/{tableName}/data",
355
- method: "post",
356
- ...variables
357
- });
419
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
358
420
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
359
421
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
360
422
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -396,6 +458,7 @@ const operationsByTag = {
396
458
  updateWorkspaceMemberRole,
397
459
  removeWorkspaceMember,
398
460
  inviteWorkspaceMember,
461
+ updateWorkspaceMemberInvite,
399
462
  cancelWorkspaceMemberInvite,
400
463
  resendWorkspaceMemberInvite,
401
464
  acceptWorkspaceMemberInvite
@@ -485,7 +548,7 @@ var __privateAdd$7 = (obj, member, value) => {
485
548
  throw TypeError("Cannot add the same private member more than once");
486
549
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
487
550
  };
488
- var __privateSet$6 = (obj, member, value, setter) => {
551
+ var __privateSet$7 = (obj, member, value, setter) => {
489
552
  __accessCheck$7(obj, member, "write to private field");
490
553
  setter ? setter.call(obj, value) : member.set(obj, value);
491
554
  return value;
@@ -500,7 +563,7 @@ class XataApiClient {
500
563
  if (!apiKey) {
501
564
  throw new Error("Could not resolve a valid apiKey");
502
565
  }
503
- __privateSet$6(this, _extraProps, {
566
+ __privateSet$7(this, _extraProps, {
504
567
  apiUrl: getHostUrl(provider, "main"),
505
568
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
506
569
  fetchImpl: getFetchImplementation(options.fetch),
@@ -627,6 +690,13 @@ class WorkspaceApi {
627
690
  ...this.extraProps
628
691
  });
629
692
  }
693
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
694
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
695
+ pathParams: { workspaceId, inviteId },
696
+ body: { role },
697
+ ...this.extraProps
698
+ });
699
+ }
630
700
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
631
701
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
632
702
  pathParams: { workspaceId, inviteId },
@@ -689,10 +759,10 @@ class DatabaseApi {
689
759
  ...this.extraProps
690
760
  });
691
761
  }
692
- resolveBranch(workspace, dbName, gitBranch) {
762
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
693
763
  return operationsByTag.database.resolveBranch({
694
764
  pathParams: { workspace, dbName },
695
- queryParams: { gitBranch },
765
+ queryParams: { gitBranch, fallbackBranch },
696
766
  ...this.extraProps
697
767
  });
698
768
  }
@@ -841,9 +911,10 @@ class RecordsApi {
841
911
  constructor(extraProps) {
842
912
  this.extraProps = extraProps;
843
913
  }
844
- insertRecord(workspace, database, branch, tableName, record) {
914
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
845
915
  return operationsByTag.records.insertRecord({
846
916
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
917
+ queryParams: options,
847
918
  body: record,
848
919
  ...this.extraProps
849
920
  });
@@ -872,21 +943,24 @@ class RecordsApi {
872
943
  ...this.extraProps
873
944
  });
874
945
  }
875
- deleteRecord(workspace, database, branch, tableName, recordId) {
946
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
876
947
  return operationsByTag.records.deleteRecord({
877
948
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
949
+ queryParams: options,
878
950
  ...this.extraProps
879
951
  });
880
952
  }
881
953
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
882
954
  return operationsByTag.records.getRecord({
883
955
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
956
+ queryParams: options,
884
957
  ...this.extraProps
885
958
  });
886
959
  }
887
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
960
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
888
961
  return operationsByTag.records.bulkInsertTableRecords({
889
962
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
963
+ queryParams: options,
890
964
  body: { records },
891
965
  ...this.extraProps
892
966
  });
@@ -937,18 +1011,18 @@ var __privateAdd$6 = (obj, member, value) => {
937
1011
  throw TypeError("Cannot add the same private member more than once");
938
1012
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
939
1013
  };
940
- var __privateSet$5 = (obj, member, value, setter) => {
1014
+ var __privateSet$6 = (obj, member, value, setter) => {
941
1015
  __accessCheck$6(obj, member, "write to private field");
942
1016
  setter ? setter.call(obj, value) : member.set(obj, value);
943
1017
  return value;
944
1018
  };
945
- var _query;
1019
+ var _query, _page;
946
1020
  class Page {
947
1021
  constructor(query, meta, records = []) {
948
1022
  __privateAdd$6(this, _query, void 0);
949
- __privateSet$5(this, _query, query);
1023
+ __privateSet$6(this, _query, query);
950
1024
  this.meta = meta;
951
- this.records = records;
1025
+ this.records = new RecordArray(this, records);
952
1026
  }
953
1027
  async nextPage(size, offset) {
954
1028
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
@@ -968,12 +1042,56 @@ class Page {
968
1042
  }
969
1043
  _query = new WeakMap();
970
1044
  const PAGINATION_MAX_SIZE = 200;
971
- const PAGINATION_DEFAULT_SIZE = 200;
1045
+ const PAGINATION_DEFAULT_SIZE = 20;
972
1046
  const PAGINATION_MAX_OFFSET = 800;
973
1047
  const PAGINATION_DEFAULT_OFFSET = 0;
974
1048
  function isCursorPaginationOptions(options) {
975
1049
  return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
976
1050
  }
1051
+ const _RecordArray = class extends Array {
1052
+ constructor(...args) {
1053
+ super(..._RecordArray.parseConstructorParams(...args));
1054
+ __privateAdd$6(this, _page, void 0);
1055
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1056
+ }
1057
+ static parseConstructorParams(...args) {
1058
+ if (args.length === 1 && typeof args[0] === "number") {
1059
+ return new Array(args[0]);
1060
+ }
1061
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1062
+ const result = args[1] ?? args[0].records ?? [];
1063
+ return new Array(...result);
1064
+ }
1065
+ return new Array(...args);
1066
+ }
1067
+ toArray() {
1068
+ return new Array(...this);
1069
+ }
1070
+ map(callbackfn, thisArg) {
1071
+ return this.toArray().map(callbackfn, thisArg);
1072
+ }
1073
+ async nextPage(size, offset) {
1074
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1075
+ return new _RecordArray(newPage);
1076
+ }
1077
+ async previousPage(size, offset) {
1078
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1079
+ return new _RecordArray(newPage);
1080
+ }
1081
+ async firstPage(size, offset) {
1082
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1083
+ return new _RecordArray(newPage);
1084
+ }
1085
+ async lastPage(size, offset) {
1086
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1087
+ return new _RecordArray(newPage);
1088
+ }
1089
+ hasNextPage() {
1090
+ return __privateGet$6(this, _page).meta.page.more;
1091
+ }
1092
+ };
1093
+ let RecordArray = _RecordArray;
1094
+ _page = new WeakMap();
977
1095
 
978
1096
  var __accessCheck$5 = (obj, member, msg) => {
979
1097
  if (!member.has(obj))
@@ -988,7 +1106,7 @@ var __privateAdd$5 = (obj, member, value) => {
988
1106
  throw TypeError("Cannot add the same private member more than once");
989
1107
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
990
1108
  };
991
- var __privateSet$4 = (obj, member, value, setter) => {
1109
+ var __privateSet$5 = (obj, member, value, setter) => {
992
1110
  __accessCheck$5(obj, member, "write to private field");
993
1111
  setter ? setter.call(obj, value) : member.set(obj, value);
994
1112
  return value;
@@ -1000,12 +1118,12 @@ const _Query = class {
1000
1118
  __privateAdd$5(this, _repository, void 0);
1001
1119
  __privateAdd$5(this, _data, { filter: {} });
1002
1120
  this.meta = { page: { cursor: "start", more: true } };
1003
- this.records = [];
1004
- __privateSet$4(this, _table$1, table);
1121
+ this.records = new RecordArray(this, []);
1122
+ __privateSet$5(this, _table$1, table);
1005
1123
  if (repository) {
1006
- __privateSet$4(this, _repository, repository);
1124
+ __privateSet$5(this, _repository, repository);
1007
1125
  } else {
1008
- __privateSet$4(this, _repository, this);
1126
+ __privateSet$5(this, _repository, this);
1009
1127
  }
1010
1128
  const parent = cleanParent(data, rawParent);
1011
1129
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
@@ -1066,7 +1184,12 @@ const _Query = class {
1066
1184
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1067
1185
  }
1068
1186
  select(columns) {
1069
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1187
+ return new _Query(
1188
+ __privateGet$5(this, _repository),
1189
+ __privateGet$5(this, _table$1),
1190
+ { columns },
1191
+ __privateGet$5(this, _data)
1192
+ );
1070
1193
  }
1071
1194
  getPaginated(options = {}) {
1072
1195
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1089,8 +1212,11 @@ const _Query = class {
1089
1212
  }
1090
1213
  }
1091
1214
  async getMany(options = {}) {
1092
- const { records } = await this.getPaginated(options);
1093
- return records;
1215
+ const page = await this.getPaginated(options);
1216
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1217
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1218
+ }
1219
+ return page.records;
1094
1220
  }
1095
1221
  async getAll(options = {}) {
1096
1222
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1138,7 +1264,9 @@ function isIdentifiable(x) {
1138
1264
  return isObject(x) && isString(x?.id);
1139
1265
  }
1140
1266
  function isXataRecord(x) {
1141
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1267
+ const record = x;
1268
+ const metadata = record?.getMetadata();
1269
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1142
1270
  }
1143
1271
 
1144
1272
  function isSortFilterString(value) {
@@ -1177,7 +1305,7 @@ var __privateAdd$4 = (obj, member, value) => {
1177
1305
  throw TypeError("Cannot add the same private member more than once");
1178
1306
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1179
1307
  };
1180
- var __privateSet$3 = (obj, member, value, setter) => {
1308
+ var __privateSet$4 = (obj, member, value, setter) => {
1181
1309
  __accessCheck$4(obj, member, "write to private field");
1182
1310
  setter ? setter.call(obj, value) : member.set(obj, value);
1183
1311
  return value;
@@ -1186,7 +1314,7 @@ var __privateMethod$2 = (obj, member, method) => {
1186
1314
  __accessCheck$4(obj, member, "access private method");
1187
1315
  return method;
1188
1316
  };
1189
- 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;
1317
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
1190
1318
  class Repository extends Query {
1191
1319
  }
1192
1320
  class RestRepository extends Query {
@@ -1198,111 +1326,122 @@ class RestRepository extends Query {
1198
1326
  __privateAdd$4(this, _updateRecordWithID);
1199
1327
  __privateAdd$4(this, _upsertRecordWithID);
1200
1328
  __privateAdd$4(this, _deleteRecord);
1201
- __privateAdd$4(this, _invalidateCache);
1202
- __privateAdd$4(this, _setCacheRecord);
1203
- __privateAdd$4(this, _getCacheRecord);
1204
1329
  __privateAdd$4(this, _setCacheQuery);
1205
1330
  __privateAdd$4(this, _getCacheQuery);
1206
- __privateAdd$4(this, _getSchema$1);
1331
+ __privateAdd$4(this, _getSchemaTables$1);
1207
1332
  __privateAdd$4(this, _table, void 0);
1208
1333
  __privateAdd$4(this, _getFetchProps, void 0);
1334
+ __privateAdd$4(this, _db, void 0);
1209
1335
  __privateAdd$4(this, _cache, void 0);
1210
- __privateAdd$4(this, _schema$1, void 0);
1211
- __privateSet$3(this, _table, options.table);
1212
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1213
- this.db = options.db;
1214
- __privateSet$3(this, _cache, options.pluginOptions.cache);
1215
- }
1216
- async create(a, b) {
1336
+ __privateAdd$4(this, _schemaTables$2, void 0);
1337
+ __privateSet$4(this, _table, options.table);
1338
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1339
+ __privateSet$4(this, _db, options.db);
1340
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1341
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1342
+ }
1343
+ async create(a, b, c) {
1217
1344
  if (Array.isArray(a)) {
1218
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1219
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1220
- return records;
1345
+ if (a.length === 0)
1346
+ return [];
1347
+ const columns = isStringArray(b) ? b : void 0;
1348
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1221
1349
  }
1222
1350
  if (isString(a) && isObject(b)) {
1223
1351
  if (a === "")
1224
1352
  throw new Error("The id can't be empty");
1225
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1226
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1227
- return record;
1353
+ const columns = isStringArray(c) ? c : void 0;
1354
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1228
1355
  }
1229
1356
  if (isObject(a) && isString(a.id)) {
1230
1357
  if (a.id === "")
1231
1358
  throw new Error("The id can't be empty");
1232
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1233
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1234
- return record;
1359
+ const columns = isStringArray(b) ? b : void 0;
1360
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1235
1361
  }
1236
1362
  if (isObject(a)) {
1237
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1238
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1239
- return record;
1363
+ const columns = isStringArray(b) ? b : void 0;
1364
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1240
1365
  }
1241
1366
  throw new Error("Invalid arguments for create method");
1242
1367
  }
1243
- async read(recordId) {
1244
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1245
- if (cacheRecord)
1246
- return cacheRecord;
1247
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1248
- try {
1249
- const response = await getRecord({
1250
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1251
- ...fetchProps
1252
- });
1253
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1254
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1255
- } catch (e) {
1256
- if (isObject(e) && e.status === 404) {
1257
- return null;
1368
+ async read(a, b) {
1369
+ const columns = isStringArray(b) ? b : ["*"];
1370
+ if (Array.isArray(a)) {
1371
+ if (a.length === 0)
1372
+ return [];
1373
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1374
+ const finalObjects = await this.getAll({ filter: { id: { $any: ids } }, columns });
1375
+ const dictionary = finalObjects.reduce((acc, object) => {
1376
+ acc[object.id] = object;
1377
+ return acc;
1378
+ }, {});
1379
+ return ids.map((id2) => dictionary[id2] ?? null);
1380
+ }
1381
+ const id = isString(a) ? a : a.id;
1382
+ if (isString(id)) {
1383
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1384
+ try {
1385
+ const response = await getRecord({
1386
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1387
+ queryParams: { columns },
1388
+ ...fetchProps
1389
+ });
1390
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1391
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1392
+ } catch (e) {
1393
+ if (isObject(e) && e.status === 404) {
1394
+ return null;
1395
+ }
1396
+ throw e;
1258
1397
  }
1259
- throw e;
1260
1398
  }
1399
+ return null;
1261
1400
  }
1262
- async update(a, b) {
1401
+ async update(a, b, c) {
1263
1402
  if (Array.isArray(a)) {
1403
+ if (a.length === 0)
1404
+ return [];
1264
1405
  if (a.length > 100) {
1265
1406
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1266
1407
  }
1267
- return Promise.all(a.map((object) => this.update(object)));
1408
+ const columns = isStringArray(b) ? b : ["*"];
1409
+ return Promise.all(a.map((object) => this.update(object, columns)));
1268
1410
  }
1269
1411
  if (isString(a) && isObject(b)) {
1270
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1271
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1272
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1273
- return record;
1412
+ const columns = isStringArray(c) ? c : void 0;
1413
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1274
1414
  }
1275
1415
  if (isObject(a) && isString(a.id)) {
1276
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1277
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1278
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1279
- return record;
1416
+ const columns = isStringArray(b) ? b : void 0;
1417
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1280
1418
  }
1281
1419
  throw new Error("Invalid arguments for update method");
1282
1420
  }
1283
- async createOrUpdate(a, b) {
1421
+ async createOrUpdate(a, b, c) {
1284
1422
  if (Array.isArray(a)) {
1423
+ if (a.length === 0)
1424
+ return [];
1285
1425
  if (a.length > 100) {
1286
1426
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1287
1427
  }
1288
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1428
+ const columns = isStringArray(b) ? b : ["*"];
1429
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1289
1430
  }
1290
1431
  if (isString(a) && isObject(b)) {
1291
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1292
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1293
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1294
- return record;
1432
+ const columns = isStringArray(c) ? c : void 0;
1433
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1295
1434
  }
1296
1435
  if (isObject(a) && isString(a.id)) {
1297
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1298
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1299
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1300
- return record;
1436
+ const columns = isStringArray(c) ? c : void 0;
1437
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1301
1438
  }
1302
1439
  throw new Error("Invalid arguments for createOrUpdate method");
1303
1440
  }
1304
1441
  async delete(a) {
1305
1442
  if (Array.isArray(a)) {
1443
+ if (a.length === 0)
1444
+ return;
1306
1445
  if (a.length > 100) {
1307
1446
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1308
1447
  }
@@ -1311,12 +1450,10 @@ class RestRepository extends Query {
1311
1450
  }
1312
1451
  if (isString(a)) {
1313
1452
  await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1314
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1315
1453
  return;
1316
1454
  }
1317
1455
  if (isObject(a) && isString(a.id)) {
1318
1456
  await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1319
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1320
1457
  return;
1321
1458
  }
1322
1459
  throw new Error("Invalid arguments for delete method");
@@ -1328,12 +1465,15 @@ class RestRepository extends Query {
1328
1465
  body: {
1329
1466
  query,
1330
1467
  fuzziness: options.fuzziness,
1331
- filter: options.filter
1468
+ prefix: options.prefix,
1469
+ highlight: options.highlight,
1470
+ filter: options.filter,
1471
+ boosters: options.boosters
1332
1472
  },
1333
1473
  ...fetchProps
1334
1474
  });
1335
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1336
- return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1475
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1476
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1337
1477
  }
1338
1478
  async query(query) {
1339
1479
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
@@ -1352,18 +1492,19 @@ class RestRepository extends Query {
1352
1492
  body,
1353
1493
  ...fetchProps
1354
1494
  });
1355
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1356
- const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1495
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1496
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1357
1497
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1358
1498
  return new Page(query, meta, records);
1359
1499
  }
1360
1500
  }
1361
1501
  _table = new WeakMap();
1362
1502
  _getFetchProps = new WeakMap();
1503
+ _db = new WeakMap();
1363
1504
  _cache = new WeakMap();
1364
- _schema$1 = new WeakMap();
1505
+ _schemaTables$2 = new WeakMap();
1365
1506
  _insertRecordWithoutId = new WeakSet();
1366
- insertRecordWithoutId_fn = async function(object) {
1507
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1367
1508
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1368
1509
  const record = transformObjectLinks(object);
1369
1510
  const response = await insertRecord({
@@ -1372,17 +1513,15 @@ insertRecordWithoutId_fn = async function(object) {
1372
1513
  dbBranchName: "{dbBranch}",
1373
1514
  tableName: __privateGet$4(this, _table)
1374
1515
  },
1516
+ queryParams: { columns },
1375
1517
  body: record,
1376
1518
  ...fetchProps
1377
1519
  });
1378
- const finalObject = await this.read(response.id);
1379
- if (!finalObject) {
1380
- throw new Error("The server failed to save the record");
1381
- }
1382
- return finalObject;
1520
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1521
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1383
1522
  };
1384
1523
  _insertRecordWithId = new WeakSet();
1385
- insertRecordWithId_fn = async function(recordId, object) {
1524
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1386
1525
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1387
1526
  const record = transformObjectLinks(object);
1388
1527
  const response = await insertRecordWithID({
@@ -1393,56 +1532,52 @@ insertRecordWithId_fn = async function(recordId, object) {
1393
1532
  recordId
1394
1533
  },
1395
1534
  body: record,
1396
- queryParams: { createOnly: true },
1535
+ queryParams: { createOnly: true, columns },
1397
1536
  ...fetchProps
1398
1537
  });
1399
- const finalObject = await this.read(response.id);
1400
- if (!finalObject) {
1401
- throw new Error("The server failed to save the record");
1402
- }
1403
- return finalObject;
1538
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1539
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1404
1540
  };
1405
1541
  _bulkInsertTableRecords = new WeakSet();
1406
- bulkInsertTableRecords_fn = async function(objects) {
1542
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1407
1543
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1408
1544
  const records = objects.map((object) => transformObjectLinks(object));
1409
1545
  const response = await bulkInsertTableRecords({
1410
1546
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1547
+ queryParams: { columns },
1411
1548
  body: { records },
1412
1549
  ...fetchProps
1413
1550
  });
1414
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1415
- if (finalObjects.length !== objects.length) {
1416
- throw new Error("The server failed to save some records");
1551
+ if (!isResponseWithRecords(response)) {
1552
+ throw new Error("Request included columns but server didn't include them");
1417
1553
  }
1418
- return finalObjects;
1554
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1555
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1419
1556
  };
1420
1557
  _updateRecordWithID = new WeakSet();
1421
- updateRecordWithID_fn = async function(recordId, object) {
1558
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1422
1559
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1423
1560
  const record = transformObjectLinks(object);
1424
1561
  const response = await updateRecordWithID({
1425
1562
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1563
+ queryParams: { columns },
1426
1564
  body: record,
1427
1565
  ...fetchProps
1428
1566
  });
1429
- const item = await this.read(response.id);
1430
- if (!item)
1431
- throw new Error("The server failed to save the record");
1432
- return item;
1567
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1568
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1433
1569
  };
1434
1570
  _upsertRecordWithID = new WeakSet();
1435
- upsertRecordWithID_fn = async function(recordId, object) {
1571
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1436
1572
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1437
1573
  const response = await upsertRecordWithID({
1438
1574
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1575
+ queryParams: { columns },
1439
1576
  body: object,
1440
1577
  ...fetchProps
1441
1578
  });
1442
- const item = await this.read(response.id);
1443
- if (!item)
1444
- throw new Error("The server failed to save the record");
1445
- return item;
1579
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1580
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1446
1581
  };
1447
1582
  _deleteRecord = new WeakSet();
1448
1583
  deleteRecord_fn = async function(recordId) {
@@ -1452,29 +1587,6 @@ deleteRecord_fn = async function(recordId) {
1452
1587
  ...fetchProps
1453
1588
  });
1454
1589
  };
1455
- _invalidateCache = new WeakSet();
1456
- invalidateCache_fn = async function(recordId) {
1457
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1458
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1459
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1460
- for (const [key, value] of queries) {
1461
- const ids = getIds(value);
1462
- if (ids.includes(recordId))
1463
- await __privateGet$4(this, _cache).delete(key);
1464
- }
1465
- };
1466
- _setCacheRecord = new WeakSet();
1467
- setCacheRecord_fn = async function(record) {
1468
- if (!__privateGet$4(this, _cache).cacheRecords)
1469
- return;
1470
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1471
- };
1472
- _getCacheRecord = new WeakSet();
1473
- getCacheRecord_fn = async function(recordId) {
1474
- if (!__privateGet$4(this, _cache).cacheRecords)
1475
- return null;
1476
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1477
- };
1478
1590
  _setCacheQuery = new WeakSet();
1479
1591
  setCacheQuery_fn = async function(query, meta, records) {
1480
1592
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -1491,17 +1603,17 @@ getCacheQuery_fn = async function(query) {
1491
1603
  const hasExpired = result.date.getTime() + ttl < Date.now();
1492
1604
  return hasExpired ? null : result;
1493
1605
  };
1494
- _getSchema$1 = new WeakSet();
1495
- getSchema_fn$1 = async function() {
1496
- if (__privateGet$4(this, _schema$1))
1497
- return __privateGet$4(this, _schema$1);
1606
+ _getSchemaTables$1 = new WeakSet();
1607
+ getSchemaTables_fn$1 = async function() {
1608
+ if (__privateGet$4(this, _schemaTables$2))
1609
+ return __privateGet$4(this, _schemaTables$2);
1498
1610
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1499
1611
  const { schema } = await getBranchDetails({
1500
1612
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1501
1613
  ...fetchProps
1502
1614
  });
1503
- __privateSet$3(this, _schema$1, schema);
1504
- return schema;
1615
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1616
+ return schema.tables;
1505
1617
  };
1506
1618
  const transformObjectLinks = (object) => {
1507
1619
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1510,20 +1622,21 @@ const transformObjectLinks = (object) => {
1510
1622
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1511
1623
  }, {});
1512
1624
  };
1513
- const initObject = (db, schema, table, object) => {
1625
+ const initObject = (db, schemaTables, table, object) => {
1514
1626
  const result = {};
1515
- Object.assign(result, object);
1516
- const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1627
+ const { xata, ...rest } = object ?? {};
1628
+ Object.assign(result, rest);
1629
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1517
1630
  if (!columns)
1518
1631
  console.error(`Table ${table} not found in schema`);
1519
1632
  for (const column of columns ?? []) {
1520
1633
  const value = result[column.name];
1521
1634
  switch (column.type) {
1522
1635
  case "datetime": {
1523
- const date = new Date(value);
1524
- if (isNaN(date.getTime())) {
1636
+ const date = value !== void 0 ? new Date(value) : void 0;
1637
+ if (date && isNaN(date.getTime())) {
1525
1638
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1526
- } else {
1639
+ } else if (date) {
1527
1640
  result[column.name] = date;
1528
1641
  }
1529
1642
  break;
@@ -1533,35 +1646,32 @@ const initObject = (db, schema, table, object) => {
1533
1646
  if (!linkTable) {
1534
1647
  console.error(`Failed to parse link for field ${column.name}`);
1535
1648
  } else if (isObject(value)) {
1536
- result[column.name] = initObject(db, schema, linkTable, value);
1649
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1537
1650
  }
1538
1651
  break;
1539
1652
  }
1540
1653
  }
1541
1654
  }
1542
- result.read = function() {
1543
- return db[table].read(result["id"]);
1655
+ result.read = function(columns2) {
1656
+ return db[table].read(result["id"], columns2);
1544
1657
  };
1545
- result.update = function(data) {
1546
- return db[table].update(result["id"], data);
1658
+ result.update = function(data, columns2) {
1659
+ return db[table].update(result["id"], data, columns2);
1547
1660
  };
1548
1661
  result.delete = function() {
1549
1662
  return db[table].delete(result["id"]);
1550
1663
  };
1551
- for (const prop of ["read", "update", "delete"]) {
1664
+ result.getMetadata = function() {
1665
+ return xata;
1666
+ };
1667
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1552
1668
  Object.defineProperty(result, prop, { enumerable: false });
1553
1669
  }
1554
1670
  Object.freeze(result);
1555
1671
  return result;
1556
1672
  };
1557
- function getIds(value) {
1558
- if (Array.isArray(value)) {
1559
- return value.map((item) => getIds(item)).flat();
1560
- }
1561
- if (!isObject(value))
1562
- return [];
1563
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1564
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1673
+ function isResponseWithRecords(value) {
1674
+ return isObject(value) && Array.isArray(value.records);
1565
1675
  }
1566
1676
 
1567
1677
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1577,7 +1687,7 @@ var __privateAdd$3 = (obj, member, value) => {
1577
1687
  throw TypeError("Cannot add the same private member more than once");
1578
1688
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1579
1689
  };
1580
- var __privateSet$2 = (obj, member, value, setter) => {
1690
+ var __privateSet$3 = (obj, member, value, setter) => {
1581
1691
  __accessCheck$3(obj, member, "write to private field");
1582
1692
  setter ? setter.call(obj, value) : member.set(obj, value);
1583
1693
  return value;
@@ -1586,9 +1696,8 @@ var _map;
1586
1696
  class SimpleCache {
1587
1697
  constructor(options = {}) {
1588
1698
  __privateAdd$3(this, _map, void 0);
1589
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1699
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1590
1700
  this.capacity = options.max ?? 500;
1591
- this.cacheRecords = options.cacheRecords ?? true;
1592
1701
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1593
1702
  }
1594
1703
  async getAll() {
@@ -1646,31 +1755,42 @@ var __privateAdd$2 = (obj, member, value) => {
1646
1755
  throw TypeError("Cannot add the same private member more than once");
1647
1756
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1648
1757
  };
1649
- var _tables;
1758
+ var __privateSet$2 = (obj, member, value, setter) => {
1759
+ __accessCheck$2(obj, member, "write to private field");
1760
+ setter ? setter.call(obj, value) : member.set(obj, value);
1761
+ return value;
1762
+ };
1763
+ var _tables, _schemaTables$1;
1650
1764
  class SchemaPlugin extends XataPlugin {
1651
- constructor(tableNames) {
1765
+ constructor(schemaTables) {
1652
1766
  super();
1653
- this.tableNames = tableNames;
1654
1767
  __privateAdd$2(this, _tables, {});
1768
+ __privateAdd$2(this, _schemaTables$1, void 0);
1769
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1655
1770
  }
1656
1771
  build(pluginOptions) {
1657
- const db = new Proxy({}, {
1658
- get: (_target, table) => {
1659
- if (!isString(table))
1660
- throw new Error("Invalid table name");
1661
- if (__privateGet$2(this, _tables)[table] === void 0) {
1662
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1772
+ const db = new Proxy(
1773
+ {},
1774
+ {
1775
+ get: (_target, table) => {
1776
+ if (!isString(table))
1777
+ throw new Error("Invalid table name");
1778
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1779
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1780
+ }
1781
+ return __privateGet$2(this, _tables)[table];
1663
1782
  }
1664
- return __privateGet$2(this, _tables)[table];
1665
1783
  }
1666
- });
1667
- for (const table of this.tableNames ?? []) {
1668
- db[table] = new RestRepository({ db, pluginOptions, table });
1784
+ );
1785
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1786
+ for (const table of tableNames) {
1787
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1669
1788
  }
1670
1789
  return db;
1671
1790
  }
1672
1791
  }
1673
1792
  _tables = new WeakMap();
1793
+ _schemaTables$1 = new WeakMap();
1674
1794
 
1675
1795
  var __accessCheck$1 = (obj, member, msg) => {
1676
1796
  if (!member.has(obj))
@@ -1694,82 +1814,77 @@ var __privateMethod$1 = (obj, member, method) => {
1694
1814
  __accessCheck$1(obj, member, "access private method");
1695
1815
  return method;
1696
1816
  };
1697
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
1817
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1698
1818
  class SearchPlugin extends XataPlugin {
1699
- constructor(db) {
1819
+ constructor(db, schemaTables) {
1700
1820
  super();
1701
1821
  this.db = db;
1702
1822
  __privateAdd$1(this, _search);
1703
- __privateAdd$1(this, _getSchema);
1704
- __privateAdd$1(this, _schema, void 0);
1823
+ __privateAdd$1(this, _getSchemaTables);
1824
+ __privateAdd$1(this, _schemaTables, void 0);
1825
+ __privateSet$1(this, _schemaTables, schemaTables);
1705
1826
  }
1706
1827
  build({ getFetchProps }) {
1707
1828
  return {
1708
1829
  all: async (query, options = {}) => {
1709
1830
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1710
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1831
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1711
1832
  return records.map((record) => {
1712
1833
  const { table = "orphan" } = record.xata;
1713
- return { table, record: initObject(this.db, schema, table, record) };
1834
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1714
1835
  });
1715
1836
  },
1716
1837
  byTable: async (query, options = {}) => {
1717
1838
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1718
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1839
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1719
1840
  return records.reduce((acc, record) => {
1720
1841
  const { table = "orphan" } = record.xata;
1721
1842
  const items = acc[table] ?? [];
1722
- const item = initObject(this.db, schema, table, record);
1843
+ const item = initObject(this.db, schemaTables, table, record);
1723
1844
  return { ...acc, [table]: [...items, item] };
1724
1845
  }, {});
1725
1846
  }
1726
1847
  };
1727
1848
  }
1728
1849
  }
1729
- _schema = new WeakMap();
1850
+ _schemaTables = new WeakMap();
1730
1851
  _search = new WeakSet();
1731
1852
  search_fn = async function(query, options, getFetchProps) {
1732
1853
  const fetchProps = await getFetchProps();
1733
- const { tables, fuzziness } = options ?? {};
1854
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1734
1855
  const { records } = await searchBranch({
1735
1856
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1736
- body: { tables, query, fuzziness },
1857
+ body: { tables, query, fuzziness, prefix, highlight },
1737
1858
  ...fetchProps
1738
1859
  });
1739
1860
  return records;
1740
1861
  };
1741
- _getSchema = new WeakSet();
1742
- getSchema_fn = async function(getFetchProps) {
1743
- if (__privateGet$1(this, _schema))
1744
- return __privateGet$1(this, _schema);
1862
+ _getSchemaTables = new WeakSet();
1863
+ getSchemaTables_fn = async function(getFetchProps) {
1864
+ if (__privateGet$1(this, _schemaTables))
1865
+ return __privateGet$1(this, _schemaTables);
1745
1866
  const fetchProps = await getFetchProps();
1746
1867
  const { schema } = await getBranchDetails({
1747
1868
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1748
1869
  ...fetchProps
1749
1870
  });
1750
- __privateSet$1(this, _schema, schema);
1751
- return schema;
1871
+ __privateSet$1(this, _schemaTables, schema.tables);
1872
+ return schema.tables;
1752
1873
  };
1753
1874
 
1754
1875
  const isBranchStrategyBuilder = (strategy) => {
1755
1876
  return typeof strategy === "function";
1756
1877
  };
1757
1878
 
1758
- const envBranchNames = [
1759
- "XATA_BRANCH",
1760
- "VERCEL_GIT_COMMIT_REF",
1761
- "CF_PAGES_BRANCH",
1762
- "BRANCH"
1763
- ];
1764
1879
  async function getCurrentBranchName(options) {
1765
- const env = getBranchByEnvVariable();
1766
- if (env) {
1767
- const details = await getDatabaseBranch(env, options);
1880
+ const { branch, envBranch } = getEnvironment();
1881
+ if (branch) {
1882
+ const details = await getDatabaseBranch(branch, options);
1768
1883
  if (details)
1769
- return env;
1770
- console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1884
+ return branch;
1885
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1771
1886
  }
1772
- const gitBranch = await getGitBranch();
1887
+ const gitBranch = envBranch || await getGitBranch();
1773
1888
  return resolveXataBranch(gitBranch, options);
1774
1889
  }
1775
1890
  async function getCurrentBranchDetails(options) {
@@ -1780,18 +1895,23 @@ async function resolveXataBranch(gitBranch, options) {
1780
1895
  const databaseURL = options?.databaseURL || getDatabaseURL();
1781
1896
  const apiKey = options?.apiKey || getAPIKey();
1782
1897
  if (!databaseURL)
1783
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1898
+ throw new Error(
1899
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
1900
+ );
1784
1901
  if (!apiKey)
1785
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1902
+ throw new Error(
1903
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
1904
+ );
1786
1905
  const [protocol, , host, , dbName] = databaseURL.split("/");
1787
1906
  const [workspace] = host.split(".");
1907
+ const { fallbackBranch } = getEnvironment();
1788
1908
  const { branch } = await resolveBranch({
1789
1909
  apiKey,
1790
1910
  apiUrl: databaseURL,
1791
1911
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1792
1912
  workspacesApiUrl: `${protocol}//${host}`,
1793
1913
  pathParams: { dbName, workspace },
1794
- queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
1914
+ queryParams: { gitBranch, fallbackBranch }
1795
1915
  });
1796
1916
  return branch;
1797
1917
  }
@@ -1799,9 +1919,13 @@ async function getDatabaseBranch(branch, options) {
1799
1919
  const databaseURL = options?.databaseURL || getDatabaseURL();
1800
1920
  const apiKey = options?.apiKey || getAPIKey();
1801
1921
  if (!databaseURL)
1802
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1922
+ throw new Error(
1923
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
1924
+ );
1803
1925
  if (!apiKey)
1804
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1926
+ throw new Error(
1927
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
1928
+ );
1805
1929
  const [protocol, , host, , database] = databaseURL.split("/");
1806
1930
  const [workspace] = host.split(".");
1807
1931
  const dbBranchName = `${database}:${branch}`;
@@ -1811,10 +1935,7 @@ async function getDatabaseBranch(branch, options) {
1811
1935
  apiUrl: databaseURL,
1812
1936
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1813
1937
  workspacesApiUrl: `${protocol}//${host}`,
1814
- pathParams: {
1815
- dbBranchName,
1816
- workspace
1817
- }
1938
+ pathParams: { dbBranchName, workspace }
1818
1939
  });
1819
1940
  } catch (err) {
1820
1941
  if (isObject(err) && err.status === 404)
@@ -1822,21 +1943,10 @@ async function getDatabaseBranch(branch, options) {
1822
1943
  throw err;
1823
1944
  }
1824
1945
  }
1825
- function getBranchByEnvVariable() {
1826
- for (const name of envBranchNames) {
1827
- const value = getEnvVariable(name);
1828
- if (value) {
1829
- return value;
1830
- }
1831
- }
1832
- try {
1833
- return XATA_BRANCH;
1834
- } catch (err) {
1835
- }
1836
- }
1837
1946
  function getDatabaseURL() {
1838
1947
  try {
1839
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1948
+ const { databaseURL } = getEnvironment();
1949
+ return databaseURL;
1840
1950
  } catch (err) {
1841
1951
  return void 0;
1842
1952
  }
@@ -1865,20 +1975,22 @@ var __privateMethod = (obj, member, method) => {
1865
1975
  return method;
1866
1976
  };
1867
1977
  const buildClient = (plugins) => {
1868
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1978
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1869
1979
  return _a = class {
1870
- constructor(options = {}, tables) {
1980
+ constructor(options = {}, schemaTables) {
1871
1981
  __privateAdd(this, _parseOptions);
1872
1982
  __privateAdd(this, _getFetchProps);
1873
1983
  __privateAdd(this, _evaluateBranch);
1874
1984
  __privateAdd(this, _branch, void 0);
1985
+ __privateAdd(this, _options, void 0);
1875
1986
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
1987
+ __privateSet(this, _options, safeOptions);
1876
1988
  const pluginOptions = {
1877
1989
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1878
1990
  cache: safeOptions.cache
1879
1991
  };
1880
- const db = new SchemaPlugin(tables).build(pluginOptions);
1881
- const search = new SearchPlugin(db).build(pluginOptions);
1992
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
1993
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1882
1994
  this.db = db;
1883
1995
  this.search = search;
1884
1996
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
@@ -1894,22 +2006,22 @@ const buildClient = (plugins) => {
1894
2006
  }
1895
2007
  }
1896
2008
  }
1897
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2009
+ async getConfig() {
2010
+ const databaseURL = __privateGet(this, _options).databaseURL;
2011
+ const branch = await __privateGet(this, _options).branch();
2012
+ return { databaseURL, branch };
2013
+ }
2014
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1898
2015
  const fetch = getFetchImplementation(options?.fetch);
1899
2016
  const databaseURL = options?.databaseURL || getDatabaseURL();
1900
2017
  const apiKey = options?.apiKey || getAPIKey();
1901
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2018
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
1902
2019
  const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1903
2020
  if (!databaseURL || !apiKey) {
1904
2021
  throw new Error("Options databaseURL and apiKey are required");
1905
2022
  }
1906
2023
  return { fetch, databaseURL, apiKey, branch, cache };
1907
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1908
- fetch,
1909
- apiKey,
1910
- databaseURL,
1911
- branch
1912
- }) {
2024
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch }) {
1913
2025
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1914
2026
  if (!branchValue)
1915
2027
  throw new Error("Unable to resolve branch value");
@@ -1951,5 +2063,5 @@ class XataError extends Error {
1951
2063
  }
1952
2064
  }
1953
2065
 
1954
- 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, 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 };
2066
+ 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, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
1955
2067
  //# sourceMappingURL=index.mjs.map