@xata.io/client 0.0.0-alpha.vf9819fa → 0.0.0-alpha.vf9f8ac6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2,6 +2,24 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ function _interopNamespace(e) {
6
+ if (e && e.__esModule) return e;
7
+ var n = Object.create(null);
8
+ if (e) {
9
+ Object.keys(e).forEach(function (k) {
10
+ if (k !== 'default') {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: true,
14
+ get: function () { return e[k]; }
15
+ });
16
+ }
17
+ });
18
+ }
19
+ n["default"] = e;
20
+ return Object.freeze(n);
21
+ }
22
+
5
23
  function notEmpty(value) {
6
24
  return value !== null && value !== void 0;
7
25
  }
@@ -11,46 +29,101 @@ function compact(arr) {
11
29
  function isObject(value) {
12
30
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
13
31
  }
32
+ function isDefined(value) {
33
+ return value !== null && value !== void 0;
34
+ }
14
35
  function isString(value) {
15
- return value !== void 0 && value !== null && typeof value === "string";
36
+ return isDefined(value) && typeof value === "string";
37
+ }
38
+ function isStringArray(value) {
39
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
16
40
  }
17
41
  function toBase64(value) {
18
42
  try {
19
43
  return btoa(value);
20
44
  } catch (err) {
21
- return Buffer.from(value).toString("base64");
45
+ const buf = Buffer;
46
+ return buf.from(value).toString("base64");
22
47
  }
23
48
  }
24
49
 
25
- function getEnvVariable(name) {
50
+ function getEnvironment() {
26
51
  try {
27
- if (isObject(process) && isString(process?.env?.[name])) {
28
- return process.env[name];
52
+ if (isObject(process) && isObject(process.env)) {
53
+ return {
54
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
55
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
56
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
57
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
58
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
59
+ };
29
60
  }
30
61
  } catch (err) {
31
62
  }
32
63
  try {
33
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
34
- return Deno.env.get(name);
64
+ if (isObject(Deno) && isObject(Deno.env)) {
65
+ return {
66
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
67
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
68
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
69
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
70
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
71
+ };
35
72
  }
36
73
  } catch (err) {
37
74
  }
75
+ return {
76
+ apiKey: getGlobalApiKey(),
77
+ databaseURL: getGlobalDatabaseURL(),
78
+ branch: getGlobalBranch(),
79
+ envBranch: void 0,
80
+ fallbackBranch: getGlobalFallbackBranch()
81
+ };
82
+ }
83
+ function getGlobalApiKey() {
84
+ try {
85
+ return XATA_API_KEY;
86
+ } catch (err) {
87
+ return void 0;
88
+ }
89
+ }
90
+ function getGlobalDatabaseURL() {
91
+ try {
92
+ return XATA_DATABASE_URL;
93
+ } catch (err) {
94
+ return void 0;
95
+ }
96
+ }
97
+ function getGlobalBranch() {
98
+ try {
99
+ return XATA_BRANCH;
100
+ } catch (err) {
101
+ return void 0;
102
+ }
103
+ }
104
+ function getGlobalFallbackBranch() {
105
+ try {
106
+ return XATA_FALLBACK_BRANCH;
107
+ } catch (err) {
108
+ return void 0;
109
+ }
38
110
  }
39
111
  async function getGitBranch() {
112
+ const cmd = ["git", "branch", "--show-current"];
113
+ const fullCmd = cmd.join(" ");
114
+ const nodeModule = ["child", "process"].join("_");
115
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
40
116
  try {
41
117
  if (typeof require === "function") {
42
- const req = require;
43
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
118
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
44
119
  }
120
+ const { execSync } = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(nodeModule);
121
+ return execSync(fullCmd, execOptions).toString().trim();
45
122
  } catch (err) {
46
123
  }
47
124
  try {
48
125
  if (isObject(Deno)) {
49
- const process2 = Deno.run({
50
- cmd: ["git", "branch", "--show-current"],
51
- stdout: "piped",
52
- stderr: "piped"
53
- });
126
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
54
127
  return new TextDecoder().decode(await process2.output()).trim();
55
128
  }
56
129
  } catch (err) {
@@ -59,7 +132,8 @@ async function getGitBranch() {
59
132
 
60
133
  function getAPIKey() {
61
134
  try {
62
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
135
+ const { apiKey } = getEnvironment();
136
+ return apiKey;
63
137
  } catch (err) {
64
138
  return void 0;
65
139
  }
@@ -69,21 +143,35 @@ function getFetchImplementation(userFetch) {
69
143
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
70
144
  const fetchImpl = userFetch ?? globalFetch;
71
145
  if (!fetchImpl) {
72
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
146
+ throw new Error(
147
+ `The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`
148
+ );
73
149
  }
74
150
  return fetchImpl;
75
151
  }
76
152
 
77
- class FetcherError extends Error {
78
- constructor(status, data) {
153
+ const VERSION = "0.0.0-alpha.vf9f8ac6";
154
+
155
+ class ErrorWithCause extends Error {
156
+ constructor(message, options) {
157
+ super(message, options);
158
+ }
159
+ }
160
+ class FetcherError extends ErrorWithCause {
161
+ constructor(status, data, requestId) {
79
162
  super(getMessage(data));
80
163
  this.status = status;
81
164
  this.errors = isBulkError(data) ? data.errors : void 0;
165
+ this.requestId = requestId;
82
166
  if (data instanceof Error) {
83
167
  this.stack = data.stack;
84
168
  this.cause = data.cause;
85
169
  }
86
170
  }
171
+ toString() {
172
+ const error = super.toString();
173
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
174
+ }
87
175
  }
88
176
  function isBulkError(error) {
89
177
  return isObject(error) && Array.isArray(error.errors);
@@ -106,7 +194,12 @@ function getMessage(data) {
106
194
  }
107
195
 
108
196
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
109
- const query = new URLSearchParams(queryParams).toString();
197
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
198
+ if (value === void 0 || value === null)
199
+ return acc;
200
+ return { ...acc, [key]: value };
201
+ }, {});
202
+ const query = new URLSearchParams(cleanQueryParams).toString();
110
203
  const queryString = query.length > 0 ? `?${query}` : "";
111
204
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
112
205
  };
@@ -146,6 +239,7 @@ async function fetch$1({
146
239
  body: body ? JSON.stringify(body) : void 0,
147
240
  headers: {
148
241
  "Content-Type": "application/json",
242
+ "User-Agent": `Xata client-ts/${VERSION}`,
149
243
  ...headers,
150
244
  ...hostHeader(fullUrl),
151
245
  Authorization: `Bearer ${apiKey}`
@@ -154,14 +248,15 @@ async function fetch$1({
154
248
  if (response.status === 204) {
155
249
  return {};
156
250
  }
251
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
157
252
  try {
158
253
  const jsonResponse = await response.json();
159
254
  if (response.ok) {
160
255
  return jsonResponse;
161
256
  }
162
- throw new FetcherError(response.status, jsonResponse);
257
+ throw new FetcherError(response.status, jsonResponse, requestId);
163
258
  } catch (error) {
164
- throw new FetcherError(response.status, error);
259
+ throw new FetcherError(response.status, error, requestId);
165
260
  }
166
261
  }
167
262
 
@@ -220,6 +315,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
220
315
  ...variables
221
316
  });
222
317
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
318
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
223
319
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
224
320
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
225
321
  method: "delete",
@@ -255,6 +351,11 @@ const deleteDatabase = (variables) => fetch$1({
255
351
  method: "delete",
256
352
  ...variables
257
353
  });
354
+ const getDatabaseMetadata = (variables) => fetch$1({
355
+ url: "/dbs/{dbName}/metadata",
356
+ method: "get",
357
+ ...variables
358
+ });
258
359
  const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
259
360
  const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
260
361
  const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
@@ -268,11 +369,7 @@ const getBranchDetails = (variables) => fetch$1({
268
369
  method: "get",
269
370
  ...variables
270
371
  });
271
- const createBranch = (variables) => fetch$1({
272
- url: "/db/{dbBranchName}",
273
- method: "put",
274
- ...variables
275
- });
372
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
276
373
  const deleteBranch = (variables) => fetch$1({
277
374
  url: "/db/{dbBranchName}",
278
375
  method: "delete",
@@ -346,11 +443,7 @@ const updateColumn = (variables) => fetch$1({
346
443
  method: "patch",
347
444
  ...variables
348
445
  });
349
- const insertRecord = (variables) => fetch$1({
350
- url: "/db/{dbBranchName}/tables/{tableName}/data",
351
- method: "post",
352
- ...variables
353
- });
446
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
354
447
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
355
448
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
356
449
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -370,6 +463,11 @@ const queryTable = (variables) => fetch$1({
370
463
  method: "post",
371
464
  ...variables
372
465
  });
466
+ const searchTable = (variables) => fetch$1({
467
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
468
+ method: "post",
469
+ ...variables
470
+ });
373
471
  const searchBranch = (variables) => fetch$1({
374
472
  url: "/db/{dbBranchName}/search",
375
473
  method: "post",
@@ -387,6 +485,7 @@ const operationsByTag = {
387
485
  updateWorkspaceMemberRole,
388
486
  removeWorkspaceMember,
389
487
  inviteWorkspaceMember,
488
+ updateWorkspaceMemberInvite,
390
489
  cancelWorkspaceMemberInvite,
391
490
  resendWorkspaceMemberInvite,
392
491
  acceptWorkspaceMemberInvite
@@ -395,6 +494,7 @@ const operationsByTag = {
395
494
  getDatabaseList,
396
495
  createDatabase,
397
496
  deleteDatabase,
497
+ getDatabaseMetadata,
398
498
  getGitBranchesMapping,
399
499
  addGitBranchesEntry,
400
500
  removeGitBranchesEntry,
@@ -433,6 +533,7 @@ const operationsByTag = {
433
533
  getRecord,
434
534
  bulkInsertTableRecords,
435
535
  queryTable,
536
+ searchTable,
436
537
  searchBranch
437
538
  }
438
539
  };
@@ -475,7 +576,7 @@ var __privateAdd$7 = (obj, member, value) => {
475
576
  throw TypeError("Cannot add the same private member more than once");
476
577
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
477
578
  };
478
- var __privateSet$6 = (obj, member, value, setter) => {
579
+ var __privateSet$7 = (obj, member, value, setter) => {
479
580
  __accessCheck$7(obj, member, "write to private field");
480
581
  setter ? setter.call(obj, value) : member.set(obj, value);
481
582
  return value;
@@ -490,7 +591,7 @@ class XataApiClient {
490
591
  if (!apiKey) {
491
592
  throw new Error("Could not resolve a valid apiKey");
492
593
  }
493
- __privateSet$6(this, _extraProps, {
594
+ __privateSet$7(this, _extraProps, {
494
595
  apiUrl: getHostUrl(provider, "main"),
495
596
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
496
597
  fetchImpl: getFetchImplementation(options.fetch),
@@ -617,6 +718,13 @@ class WorkspaceApi {
617
718
  ...this.extraProps
618
719
  });
619
720
  }
721
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
722
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
723
+ pathParams: { workspaceId, inviteId },
724
+ body: { role },
725
+ ...this.extraProps
726
+ });
727
+ }
620
728
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
621
729
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
622
730
  pathParams: { workspaceId, inviteId },
@@ -659,6 +767,12 @@ class DatabaseApi {
659
767
  ...this.extraProps
660
768
  });
661
769
  }
770
+ getDatabaseMetadata(workspace, dbName) {
771
+ return operationsByTag.database.getDatabaseMetadata({
772
+ pathParams: { workspace, dbName },
773
+ ...this.extraProps
774
+ });
775
+ }
662
776
  getGitBranchesMapping(workspace, dbName) {
663
777
  return operationsByTag.database.getGitBranchesMapping({
664
778
  pathParams: { workspace, dbName },
@@ -679,10 +793,10 @@ class DatabaseApi {
679
793
  ...this.extraProps
680
794
  });
681
795
  }
682
- resolveBranch(workspace, dbName, gitBranch) {
796
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
683
797
  return operationsByTag.database.resolveBranch({
684
798
  pathParams: { workspace, dbName },
685
- queryParams: { gitBranch },
799
+ queryParams: { gitBranch, fallbackBranch },
686
800
  ...this.extraProps
687
801
  });
688
802
  }
@@ -831,9 +945,10 @@ class RecordsApi {
831
945
  constructor(extraProps) {
832
946
  this.extraProps = extraProps;
833
947
  }
834
- insertRecord(workspace, database, branch, tableName, record) {
948
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
835
949
  return operationsByTag.records.insertRecord({
836
950
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
951
+ queryParams: options,
837
952
  body: record,
838
953
  ...this.extraProps
839
954
  });
@@ -862,21 +977,24 @@ class RecordsApi {
862
977
  ...this.extraProps
863
978
  });
864
979
  }
865
- deleteRecord(workspace, database, branch, tableName, recordId) {
980
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
866
981
  return operationsByTag.records.deleteRecord({
867
982
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
983
+ queryParams: options,
868
984
  ...this.extraProps
869
985
  });
870
986
  }
871
987
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
872
988
  return operationsByTag.records.getRecord({
873
989
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
990
+ queryParams: options,
874
991
  ...this.extraProps
875
992
  });
876
993
  }
877
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
994
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
878
995
  return operationsByTag.records.bulkInsertTableRecords({
879
996
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
997
+ queryParams: options,
880
998
  body: { records },
881
999
  ...this.extraProps
882
1000
  });
@@ -888,6 +1006,13 @@ class RecordsApi {
888
1006
  ...this.extraProps
889
1007
  });
890
1008
  }
1009
+ searchTable(workspace, database, branch, tableName, query) {
1010
+ return operationsByTag.records.searchTable({
1011
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1012
+ body: query,
1013
+ ...this.extraProps
1014
+ });
1015
+ }
891
1016
  searchBranch(workspace, database, branch, query) {
892
1017
  return operationsByTag.records.searchBranch({
893
1018
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -920,18 +1045,18 @@ var __privateAdd$6 = (obj, member, value) => {
920
1045
  throw TypeError("Cannot add the same private member more than once");
921
1046
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
922
1047
  };
923
- var __privateSet$5 = (obj, member, value, setter) => {
1048
+ var __privateSet$6 = (obj, member, value, setter) => {
924
1049
  __accessCheck$6(obj, member, "write to private field");
925
1050
  setter ? setter.call(obj, value) : member.set(obj, value);
926
1051
  return value;
927
1052
  };
928
- var _query;
1053
+ var _query, _page;
929
1054
  class Page {
930
1055
  constructor(query, meta, records = []) {
931
1056
  __privateAdd$6(this, _query, void 0);
932
- __privateSet$5(this, _query, query);
1057
+ __privateSet$6(this, _query, query);
933
1058
  this.meta = meta;
934
- this.records = records;
1059
+ this.records = new RecordArray(this, records);
935
1060
  }
936
1061
  async nextPage(size, offset) {
937
1062
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
@@ -951,9 +1076,56 @@ class Page {
951
1076
  }
952
1077
  _query = new WeakMap();
953
1078
  const PAGINATION_MAX_SIZE = 200;
954
- const PAGINATION_DEFAULT_SIZE = 200;
1079
+ const PAGINATION_DEFAULT_SIZE = 20;
955
1080
  const PAGINATION_MAX_OFFSET = 800;
956
1081
  const PAGINATION_DEFAULT_OFFSET = 0;
1082
+ function isCursorPaginationOptions(options) {
1083
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1084
+ }
1085
+ const _RecordArray = class extends Array {
1086
+ constructor(...args) {
1087
+ super(..._RecordArray.parseConstructorParams(...args));
1088
+ __privateAdd$6(this, _page, void 0);
1089
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1090
+ }
1091
+ static parseConstructorParams(...args) {
1092
+ if (args.length === 1 && typeof args[0] === "number") {
1093
+ return new Array(args[0]);
1094
+ }
1095
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1096
+ const result = args[1] ?? args[0].records ?? [];
1097
+ return new Array(...result);
1098
+ }
1099
+ return new Array(...args);
1100
+ }
1101
+ toArray() {
1102
+ return new Array(...this);
1103
+ }
1104
+ map(callbackfn, thisArg) {
1105
+ return this.toArray().map(callbackfn, thisArg);
1106
+ }
1107
+ async nextPage(size, offset) {
1108
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1109
+ return new _RecordArray(newPage);
1110
+ }
1111
+ async previousPage(size, offset) {
1112
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1113
+ return new _RecordArray(newPage);
1114
+ }
1115
+ async firstPage(size, offset) {
1116
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1117
+ return new _RecordArray(newPage);
1118
+ }
1119
+ async lastPage(size, offset) {
1120
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1121
+ return new _RecordArray(newPage);
1122
+ }
1123
+ hasNextPage() {
1124
+ return __privateGet$6(this, _page).meta.page.more;
1125
+ }
1126
+ };
1127
+ let RecordArray = _RecordArray;
1128
+ _page = new WeakMap();
957
1129
 
958
1130
  var __accessCheck$5 = (obj, member, msg) => {
959
1131
  if (!member.has(obj))
@@ -968,25 +1140,26 @@ var __privateAdd$5 = (obj, member, value) => {
968
1140
  throw TypeError("Cannot add the same private member more than once");
969
1141
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
970
1142
  };
971
- var __privateSet$4 = (obj, member, value, setter) => {
1143
+ var __privateSet$5 = (obj, member, value, setter) => {
972
1144
  __accessCheck$5(obj, member, "write to private field");
973
1145
  setter ? setter.call(obj, value) : member.set(obj, value);
974
1146
  return value;
975
1147
  };
976
1148
  var _table$1, _repository, _data;
977
1149
  const _Query = class {
978
- constructor(repository, table, data, parent) {
1150
+ constructor(repository, table, data, rawParent) {
979
1151
  __privateAdd$5(this, _table$1, void 0);
980
1152
  __privateAdd$5(this, _repository, void 0);
981
1153
  __privateAdd$5(this, _data, { filter: {} });
982
1154
  this.meta = { page: { cursor: "start", more: true } };
983
- this.records = [];
984
- __privateSet$4(this, _table$1, table);
1155
+ this.records = new RecordArray(this, []);
1156
+ __privateSet$5(this, _table$1, table);
985
1157
  if (repository) {
986
- __privateSet$4(this, _repository, repository);
1158
+ __privateSet$5(this, _repository, repository);
987
1159
  } else {
988
- __privateSet$4(this, _repository, this);
1160
+ __privateSet$5(this, _repository, this);
989
1161
  }
1162
+ const parent = cleanParent(data, rawParent);
990
1163
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
991
1164
  __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
992
1165
  __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
@@ -1045,7 +1218,12 @@ const _Query = class {
1045
1218
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1046
1219
  }
1047
1220
  select(columns) {
1048
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1221
+ return new _Query(
1222
+ __privateGet$5(this, _repository),
1223
+ __privateGet$5(this, _table$1),
1224
+ { columns },
1225
+ __privateGet$5(this, _data)
1226
+ );
1049
1227
  }
1050
1228
  getPaginated(options = {}) {
1051
1229
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1058,18 +1236,21 @@ const _Query = class {
1058
1236
  }
1059
1237
  async *getIterator(options = {}) {
1060
1238
  const { batchSize = 1 } = options;
1061
- let offset = 0;
1062
- let end = false;
1063
- while (!end) {
1064
- const { records, meta } = await this.getPaginated({ ...options, pagination: { size: batchSize, offset } });
1065
- yield records;
1066
- offset += batchSize;
1067
- end = !meta.page.more;
1239
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1240
+ let more = page.hasNextPage();
1241
+ yield page.records;
1242
+ while (more) {
1243
+ page = await page.nextPage();
1244
+ more = page.hasNextPage();
1245
+ yield page.records;
1068
1246
  }
1069
1247
  }
1070
1248
  async getMany(options = {}) {
1071
- const { records } = await this.getPaginated(options);
1072
- return records;
1249
+ const page = await this.getPaginated(options);
1250
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1251
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1252
+ }
1253
+ return page.records;
1073
1254
  }
1074
1255
  async getAll(options = {}) {
1075
1256
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1081,7 +1262,7 @@ const _Query = class {
1081
1262
  }
1082
1263
  async getFirst(options = {}) {
1083
1264
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1084
- return records[0] || null;
1265
+ return records[0] ?? null;
1085
1266
  }
1086
1267
  cache(ttl) {
1087
1268
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
@@ -1106,12 +1287,20 @@ let Query = _Query;
1106
1287
  _table$1 = new WeakMap();
1107
1288
  _repository = new WeakMap();
1108
1289
  _data = new WeakMap();
1290
+ function cleanParent(data, parent) {
1291
+ if (isCursorPaginationOptions(data.pagination)) {
1292
+ return { ...parent, sorting: void 0, filter: void 0 };
1293
+ }
1294
+ return parent;
1295
+ }
1109
1296
 
1110
1297
  function isIdentifiable(x) {
1111
1298
  return isObject(x) && isString(x?.id);
1112
1299
  }
1113
1300
  function isXataRecord(x) {
1114
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1301
+ const record = x;
1302
+ const metadata = record?.getMetadata();
1303
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1115
1304
  }
1116
1305
 
1117
1306
  function isSortFilterString(value) {
@@ -1150,7 +1339,7 @@ var __privateAdd$4 = (obj, member, value) => {
1150
1339
  throw TypeError("Cannot add the same private member more than once");
1151
1340
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1152
1341
  };
1153
- var __privateSet$3 = (obj, member, value, setter) => {
1342
+ var __privateSet$4 = (obj, member, value, setter) => {
1154
1343
  __accessCheck$4(obj, member, "write to private field");
1155
1344
  setter ? setter.call(obj, value) : member.set(obj, value);
1156
1345
  return value;
@@ -1159,7 +1348,7 @@ var __privateMethod$2 = (obj, member, method) => {
1159
1348
  __accessCheck$4(obj, member, "access private method");
1160
1349
  return method;
1161
1350
  };
1162
- 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;
1351
+ 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;
1163
1352
  class Repository extends Query {
1164
1353
  }
1165
1354
  class RestRepository extends Query {
@@ -1171,111 +1360,122 @@ class RestRepository extends Query {
1171
1360
  __privateAdd$4(this, _updateRecordWithID);
1172
1361
  __privateAdd$4(this, _upsertRecordWithID);
1173
1362
  __privateAdd$4(this, _deleteRecord);
1174
- __privateAdd$4(this, _invalidateCache);
1175
- __privateAdd$4(this, _setCacheRecord);
1176
- __privateAdd$4(this, _getCacheRecord);
1177
1363
  __privateAdd$4(this, _setCacheQuery);
1178
1364
  __privateAdd$4(this, _getCacheQuery);
1179
- __privateAdd$4(this, _getSchema$1);
1365
+ __privateAdd$4(this, _getSchemaTables$1);
1180
1366
  __privateAdd$4(this, _table, void 0);
1181
1367
  __privateAdd$4(this, _getFetchProps, void 0);
1368
+ __privateAdd$4(this, _db, void 0);
1182
1369
  __privateAdd$4(this, _cache, void 0);
1183
- __privateAdd$4(this, _schema$1, void 0);
1184
- __privateSet$3(this, _table, options.table);
1185
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1186
- this.db = options.db;
1187
- __privateSet$3(this, _cache, options.pluginOptions.cache);
1188
- }
1189
- async create(a, b) {
1370
+ __privateAdd$4(this, _schemaTables$2, void 0);
1371
+ __privateSet$4(this, _table, options.table);
1372
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1373
+ __privateSet$4(this, _db, options.db);
1374
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1375
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1376
+ }
1377
+ async create(a, b, c) {
1190
1378
  if (Array.isArray(a)) {
1191
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1192
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1193
- return records;
1379
+ if (a.length === 0)
1380
+ return [];
1381
+ const columns = isStringArray(b) ? b : void 0;
1382
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1194
1383
  }
1195
1384
  if (isString(a) && isObject(b)) {
1196
1385
  if (a === "")
1197
1386
  throw new Error("The id can't be empty");
1198
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1199
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1200
- return record;
1387
+ const columns = isStringArray(c) ? c : void 0;
1388
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1201
1389
  }
1202
1390
  if (isObject(a) && isString(a.id)) {
1203
1391
  if (a.id === "")
1204
1392
  throw new Error("The id can't be empty");
1205
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1206
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1207
- return record;
1393
+ const columns = isStringArray(b) ? b : void 0;
1394
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1208
1395
  }
1209
1396
  if (isObject(a)) {
1210
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1211
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1212
- return record;
1397
+ const columns = isStringArray(b) ? b : void 0;
1398
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1213
1399
  }
1214
1400
  throw new Error("Invalid arguments for create method");
1215
1401
  }
1216
- async read(recordId) {
1217
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1218
- if (cacheRecord)
1219
- return cacheRecord;
1220
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1221
- try {
1222
- const response = await getRecord({
1223
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1224
- ...fetchProps
1225
- });
1226
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1227
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1228
- } catch (e) {
1229
- if (isObject(e) && e.status === 404) {
1230
- return null;
1402
+ async read(a, b) {
1403
+ const columns = isStringArray(b) ? b : ["*"];
1404
+ if (Array.isArray(a)) {
1405
+ if (a.length === 0)
1406
+ return [];
1407
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1408
+ const finalObjects = await this.getAll({ filter: { id: { $any: ids } }, columns });
1409
+ const dictionary = finalObjects.reduce((acc, object) => {
1410
+ acc[object.id] = object;
1411
+ return acc;
1412
+ }, {});
1413
+ return ids.map((id2) => dictionary[id2] ?? null);
1414
+ }
1415
+ const id = isString(a) ? a : a.id;
1416
+ if (isString(id)) {
1417
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1418
+ try {
1419
+ const response = await getRecord({
1420
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1421
+ queryParams: { columns },
1422
+ ...fetchProps
1423
+ });
1424
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1425
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1426
+ } catch (e) {
1427
+ if (isObject(e) && e.status === 404) {
1428
+ return null;
1429
+ }
1430
+ throw e;
1231
1431
  }
1232
- throw e;
1233
1432
  }
1433
+ return null;
1234
1434
  }
1235
- async update(a, b) {
1435
+ async update(a, b, c) {
1236
1436
  if (Array.isArray(a)) {
1437
+ if (a.length === 0)
1438
+ return [];
1237
1439
  if (a.length > 100) {
1238
1440
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1239
1441
  }
1240
- return Promise.all(a.map((object) => this.update(object)));
1442
+ const columns = isStringArray(b) ? b : ["*"];
1443
+ return Promise.all(a.map((object) => this.update(object, columns)));
1241
1444
  }
1242
1445
  if (isString(a) && isObject(b)) {
1243
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1244
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1245
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1246
- return record;
1446
+ const columns = isStringArray(c) ? c : void 0;
1447
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1247
1448
  }
1248
1449
  if (isObject(a) && isString(a.id)) {
1249
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1250
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1251
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1252
- return record;
1450
+ const columns = isStringArray(b) ? b : void 0;
1451
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1253
1452
  }
1254
1453
  throw new Error("Invalid arguments for update method");
1255
1454
  }
1256
- async createOrUpdate(a, b) {
1455
+ async createOrUpdate(a, b, c) {
1257
1456
  if (Array.isArray(a)) {
1457
+ if (a.length === 0)
1458
+ return [];
1258
1459
  if (a.length > 100) {
1259
1460
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1260
1461
  }
1261
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1462
+ const columns = isStringArray(b) ? b : ["*"];
1463
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1262
1464
  }
1263
1465
  if (isString(a) && isObject(b)) {
1264
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1265
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1266
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1267
- return record;
1466
+ const columns = isStringArray(c) ? c : void 0;
1467
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1268
1468
  }
1269
1469
  if (isObject(a) && isString(a.id)) {
1270
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1271
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1272
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1273
- return record;
1470
+ const columns = isStringArray(c) ? c : void 0;
1471
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1274
1472
  }
1275
1473
  throw new Error("Invalid arguments for createOrUpdate method");
1276
1474
  }
1277
1475
  async delete(a) {
1278
1476
  if (Array.isArray(a)) {
1477
+ if (a.length === 0)
1478
+ return;
1279
1479
  if (a.length > 100) {
1280
1480
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1281
1481
  }
@@ -1284,25 +1484,30 @@ class RestRepository extends Query {
1284
1484
  }
1285
1485
  if (isString(a)) {
1286
1486
  await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1287
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1288
1487
  return;
1289
1488
  }
1290
1489
  if (isObject(a) && isString(a.id)) {
1291
1490
  await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1292
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1293
1491
  return;
1294
1492
  }
1295
1493
  throw new Error("Invalid arguments for delete method");
1296
1494
  }
1297
1495
  async search(query, options = {}) {
1298
1496
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1299
- const { records } = await searchBranch({
1300
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1301
- body: { tables: [__privateGet$4(this, _table)], query, fuzziness: options.fuzziness },
1497
+ const { records } = await searchTable({
1498
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1499
+ body: {
1500
+ query,
1501
+ fuzziness: options.fuzziness,
1502
+ prefix: options.prefix,
1503
+ highlight: options.highlight,
1504
+ filter: options.filter,
1505
+ boosters: options.boosters
1506
+ },
1302
1507
  ...fetchProps
1303
1508
  });
1304
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1305
- return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1509
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1510
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1306
1511
  }
1307
1512
  async query(query) {
1308
1513
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
@@ -1311,7 +1516,7 @@ class RestRepository extends Query {
1311
1516
  const data = query.getQueryOptions();
1312
1517
  const body = {
1313
1518
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1314
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1519
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1315
1520
  page: data.pagination,
1316
1521
  columns: data.columns
1317
1522
  };
@@ -1321,18 +1526,19 @@ class RestRepository extends Query {
1321
1526
  body,
1322
1527
  ...fetchProps
1323
1528
  });
1324
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1325
- const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1529
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1530
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1326
1531
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1327
1532
  return new Page(query, meta, records);
1328
1533
  }
1329
1534
  }
1330
1535
  _table = new WeakMap();
1331
1536
  _getFetchProps = new WeakMap();
1537
+ _db = new WeakMap();
1332
1538
  _cache = new WeakMap();
1333
- _schema$1 = new WeakMap();
1539
+ _schemaTables$2 = new WeakMap();
1334
1540
  _insertRecordWithoutId = new WeakSet();
1335
- insertRecordWithoutId_fn = async function(object) {
1541
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1336
1542
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1337
1543
  const record = transformObjectLinks(object);
1338
1544
  const response = await insertRecord({
@@ -1341,17 +1547,15 @@ insertRecordWithoutId_fn = async function(object) {
1341
1547
  dbBranchName: "{dbBranch}",
1342
1548
  tableName: __privateGet$4(this, _table)
1343
1549
  },
1550
+ queryParams: { columns },
1344
1551
  body: record,
1345
1552
  ...fetchProps
1346
1553
  });
1347
- const finalObject = await this.read(response.id);
1348
- if (!finalObject) {
1349
- throw new Error("The server failed to save the record");
1350
- }
1351
- return finalObject;
1554
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1555
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1352
1556
  };
1353
1557
  _insertRecordWithId = new WeakSet();
1354
- insertRecordWithId_fn = async function(recordId, object) {
1558
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1355
1559
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1356
1560
  const record = transformObjectLinks(object);
1357
1561
  const response = await insertRecordWithID({
@@ -1362,56 +1566,52 @@ insertRecordWithId_fn = async function(recordId, object) {
1362
1566
  recordId
1363
1567
  },
1364
1568
  body: record,
1365
- queryParams: { createOnly: true },
1569
+ queryParams: { createOnly: true, columns },
1366
1570
  ...fetchProps
1367
1571
  });
1368
- const finalObject = await this.read(response.id);
1369
- if (!finalObject) {
1370
- throw new Error("The server failed to save the record");
1371
- }
1372
- return finalObject;
1572
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1573
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1373
1574
  };
1374
1575
  _bulkInsertTableRecords = new WeakSet();
1375
- bulkInsertTableRecords_fn = async function(objects) {
1576
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1376
1577
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1377
1578
  const records = objects.map((object) => transformObjectLinks(object));
1378
1579
  const response = await bulkInsertTableRecords({
1379
1580
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1581
+ queryParams: { columns },
1380
1582
  body: { records },
1381
1583
  ...fetchProps
1382
1584
  });
1383
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1384
- if (finalObjects.length !== objects.length) {
1385
- throw new Error("The server failed to save some records");
1585
+ if (!isResponseWithRecords(response)) {
1586
+ throw new Error("Request included columns but server didn't include them");
1386
1587
  }
1387
- return finalObjects;
1588
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1589
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1388
1590
  };
1389
1591
  _updateRecordWithID = new WeakSet();
1390
- updateRecordWithID_fn = async function(recordId, object) {
1592
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1391
1593
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1392
1594
  const record = transformObjectLinks(object);
1393
1595
  const response = await updateRecordWithID({
1394
1596
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1597
+ queryParams: { columns },
1395
1598
  body: record,
1396
1599
  ...fetchProps
1397
1600
  });
1398
- const item = await this.read(response.id);
1399
- if (!item)
1400
- throw new Error("The server failed to save the record");
1401
- return item;
1601
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1602
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1402
1603
  };
1403
1604
  _upsertRecordWithID = new WeakSet();
1404
- upsertRecordWithID_fn = async function(recordId, object) {
1605
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1405
1606
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1406
1607
  const response = await upsertRecordWithID({
1407
1608
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1609
+ queryParams: { columns },
1408
1610
  body: object,
1409
1611
  ...fetchProps
1410
1612
  });
1411
- const item = await this.read(response.id);
1412
- if (!item)
1413
- throw new Error("The server failed to save the record");
1414
- return item;
1613
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1614
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1415
1615
  };
1416
1616
  _deleteRecord = new WeakSet();
1417
1617
  deleteRecord_fn = async function(recordId) {
@@ -1421,29 +1621,6 @@ deleteRecord_fn = async function(recordId) {
1421
1621
  ...fetchProps
1422
1622
  });
1423
1623
  };
1424
- _invalidateCache = new WeakSet();
1425
- invalidateCache_fn = async function(recordId) {
1426
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1427
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1428
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1429
- for (const [key, value] of queries) {
1430
- const ids = getIds(value);
1431
- if (ids.includes(recordId))
1432
- await __privateGet$4(this, _cache).delete(key);
1433
- }
1434
- };
1435
- _setCacheRecord = new WeakSet();
1436
- setCacheRecord_fn = async function(record) {
1437
- if (!__privateGet$4(this, _cache).cacheRecords)
1438
- return;
1439
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1440
- };
1441
- _getCacheRecord = new WeakSet();
1442
- getCacheRecord_fn = async function(recordId) {
1443
- if (!__privateGet$4(this, _cache).cacheRecords)
1444
- return null;
1445
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1446
- };
1447
1624
  _setCacheQuery = new WeakSet();
1448
1625
  setCacheQuery_fn = async function(query, meta, records) {
1449
1626
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -1460,17 +1637,17 @@ getCacheQuery_fn = async function(query) {
1460
1637
  const hasExpired = result.date.getTime() + ttl < Date.now();
1461
1638
  return hasExpired ? null : result;
1462
1639
  };
1463
- _getSchema$1 = new WeakSet();
1464
- getSchema_fn$1 = async function() {
1465
- if (__privateGet$4(this, _schema$1))
1466
- return __privateGet$4(this, _schema$1);
1640
+ _getSchemaTables$1 = new WeakSet();
1641
+ getSchemaTables_fn$1 = async function() {
1642
+ if (__privateGet$4(this, _schemaTables$2))
1643
+ return __privateGet$4(this, _schemaTables$2);
1467
1644
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1468
1645
  const { schema } = await getBranchDetails({
1469
1646
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1470
1647
  ...fetchProps
1471
1648
  });
1472
- __privateSet$3(this, _schema$1, schema);
1473
- return schema;
1649
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1650
+ return schema.tables;
1474
1651
  };
1475
1652
  const transformObjectLinks = (object) => {
1476
1653
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1479,20 +1656,21 @@ const transformObjectLinks = (object) => {
1479
1656
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1480
1657
  }, {});
1481
1658
  };
1482
- const initObject = (db, schema, table, object) => {
1659
+ const initObject = (db, schemaTables, table, object) => {
1483
1660
  const result = {};
1484
- Object.assign(result, object);
1485
- const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1661
+ const { xata, ...rest } = object ?? {};
1662
+ Object.assign(result, rest);
1663
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1486
1664
  if (!columns)
1487
1665
  console.error(`Table ${table} not found in schema`);
1488
1666
  for (const column of columns ?? []) {
1489
1667
  const value = result[column.name];
1490
1668
  switch (column.type) {
1491
1669
  case "datetime": {
1492
- const date = new Date(value);
1493
- if (isNaN(date.getTime())) {
1670
+ const date = value !== void 0 ? new Date(value) : void 0;
1671
+ if (date && isNaN(date.getTime())) {
1494
1672
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1495
- } else {
1673
+ } else if (date) {
1496
1674
  result[column.name] = date;
1497
1675
  }
1498
1676
  break;
@@ -1501,36 +1679,33 @@ const initObject = (db, schema, table, object) => {
1501
1679
  const linkTable = column.link?.table;
1502
1680
  if (!linkTable) {
1503
1681
  console.error(`Failed to parse link for field ${column.name}`);
1504
- } else if (value && isObject(value)) {
1505
- result[column.name] = initObject(db, schema, linkTable, value);
1682
+ } else if (isObject(value)) {
1683
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1506
1684
  }
1507
1685
  break;
1508
1686
  }
1509
1687
  }
1510
1688
  }
1511
- result.read = function() {
1512
- return db[table].read(result["id"]);
1689
+ result.read = function(columns2) {
1690
+ return db[table].read(result["id"], columns2);
1513
1691
  };
1514
- result.update = function(data) {
1515
- return db[table].update(result["id"], data);
1692
+ result.update = function(data, columns2) {
1693
+ return db[table].update(result["id"], data, columns2);
1516
1694
  };
1517
1695
  result.delete = function() {
1518
1696
  return db[table].delete(result["id"]);
1519
1697
  };
1520
- for (const prop of ["read", "update", "delete"]) {
1698
+ result.getMetadata = function() {
1699
+ return xata;
1700
+ };
1701
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1521
1702
  Object.defineProperty(result, prop, { enumerable: false });
1522
1703
  }
1523
1704
  Object.freeze(result);
1524
1705
  return result;
1525
1706
  };
1526
- function getIds(value) {
1527
- if (Array.isArray(value)) {
1528
- return value.map((item) => getIds(item)).flat();
1529
- }
1530
- if (!isObject(value))
1531
- return [];
1532
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1533
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1707
+ function isResponseWithRecords(value) {
1708
+ return isObject(value) && Array.isArray(value.records);
1534
1709
  }
1535
1710
 
1536
1711
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1546,7 +1721,7 @@ var __privateAdd$3 = (obj, member, value) => {
1546
1721
  throw TypeError("Cannot add the same private member more than once");
1547
1722
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1548
1723
  };
1549
- var __privateSet$2 = (obj, member, value, setter) => {
1724
+ var __privateSet$3 = (obj, member, value, setter) => {
1550
1725
  __accessCheck$3(obj, member, "write to private field");
1551
1726
  setter ? setter.call(obj, value) : member.set(obj, value);
1552
1727
  return value;
@@ -1555,9 +1730,8 @@ var _map;
1555
1730
  class SimpleCache {
1556
1731
  constructor(options = {}) {
1557
1732
  __privateAdd$3(this, _map, void 0);
1558
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1733
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1559
1734
  this.capacity = options.max ?? 500;
1560
- this.cacheRecords = options.cacheRecords ?? true;
1561
1735
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1562
1736
  }
1563
1737
  async getAll() {
@@ -1615,31 +1789,42 @@ var __privateAdd$2 = (obj, member, value) => {
1615
1789
  throw TypeError("Cannot add the same private member more than once");
1616
1790
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1617
1791
  };
1618
- var _tables;
1792
+ var __privateSet$2 = (obj, member, value, setter) => {
1793
+ __accessCheck$2(obj, member, "write to private field");
1794
+ setter ? setter.call(obj, value) : member.set(obj, value);
1795
+ return value;
1796
+ };
1797
+ var _tables, _schemaTables$1;
1619
1798
  class SchemaPlugin extends XataPlugin {
1620
- constructor(tableNames) {
1799
+ constructor(schemaTables) {
1621
1800
  super();
1622
- this.tableNames = tableNames;
1623
1801
  __privateAdd$2(this, _tables, {});
1802
+ __privateAdd$2(this, _schemaTables$1, void 0);
1803
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1624
1804
  }
1625
1805
  build(pluginOptions) {
1626
- const db = new Proxy({}, {
1627
- get: (_target, table) => {
1628
- if (!isString(table))
1629
- throw new Error("Invalid table name");
1630
- if (!__privateGet$2(this, _tables)[table]) {
1631
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1806
+ const db = new Proxy(
1807
+ {},
1808
+ {
1809
+ get: (_target, table) => {
1810
+ if (!isString(table))
1811
+ throw new Error("Invalid table name");
1812
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1813
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1814
+ }
1815
+ return __privateGet$2(this, _tables)[table];
1632
1816
  }
1633
- return __privateGet$2(this, _tables)[table];
1634
1817
  }
1635
- });
1636
- for (const table of this.tableNames ?? []) {
1637
- db[table] = new RestRepository({ db, pluginOptions, table });
1818
+ );
1819
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1820
+ for (const table of tableNames) {
1821
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1638
1822
  }
1639
1823
  return db;
1640
1824
  }
1641
1825
  }
1642
1826
  _tables = new WeakMap();
1827
+ _schemaTables$1 = new WeakMap();
1643
1828
 
1644
1829
  var __accessCheck$1 = (obj, member, msg) => {
1645
1830
  if (!member.has(obj))
@@ -1663,105 +1848,118 @@ var __privateMethod$1 = (obj, member, method) => {
1663
1848
  __accessCheck$1(obj, member, "access private method");
1664
1849
  return method;
1665
1850
  };
1666
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
1851
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1667
1852
  class SearchPlugin extends XataPlugin {
1668
- constructor(db) {
1853
+ constructor(db, schemaTables) {
1669
1854
  super();
1670
1855
  this.db = db;
1671
1856
  __privateAdd$1(this, _search);
1672
- __privateAdd$1(this, _getSchema);
1673
- __privateAdd$1(this, _schema, void 0);
1857
+ __privateAdd$1(this, _getSchemaTables);
1858
+ __privateAdd$1(this, _schemaTables, void 0);
1859
+ __privateSet$1(this, _schemaTables, schemaTables);
1674
1860
  }
1675
1861
  build({ getFetchProps }) {
1676
1862
  return {
1677
1863
  all: async (query, options = {}) => {
1678
1864
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1679
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1865
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1680
1866
  return records.map((record) => {
1681
1867
  const { table = "orphan" } = record.xata;
1682
- return { table, record: initObject(this.db, schema, table, record) };
1868
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1683
1869
  });
1684
1870
  },
1685
1871
  byTable: async (query, options = {}) => {
1686
1872
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1687
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1873
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1688
1874
  return records.reduce((acc, record) => {
1689
1875
  const { table = "orphan" } = record.xata;
1690
1876
  const items = acc[table] ?? [];
1691
- const item = initObject(this.db, schema, table, record);
1877
+ const item = initObject(this.db, schemaTables, table, record);
1692
1878
  return { ...acc, [table]: [...items, item] };
1693
1879
  }, {});
1694
1880
  }
1695
1881
  };
1696
1882
  }
1697
1883
  }
1698
- _schema = new WeakMap();
1884
+ _schemaTables = new WeakMap();
1699
1885
  _search = new WeakSet();
1700
1886
  search_fn = async function(query, options, getFetchProps) {
1701
1887
  const fetchProps = await getFetchProps();
1702
- const { tables, fuzziness } = options ?? {};
1888
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1703
1889
  const { records } = await searchBranch({
1704
1890
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1705
- body: { tables, query, fuzziness },
1891
+ body: { tables, query, fuzziness, prefix, highlight },
1706
1892
  ...fetchProps
1707
1893
  });
1708
1894
  return records;
1709
1895
  };
1710
- _getSchema = new WeakSet();
1711
- getSchema_fn = async function(getFetchProps) {
1712
- if (__privateGet$1(this, _schema))
1713
- return __privateGet$1(this, _schema);
1896
+ _getSchemaTables = new WeakSet();
1897
+ getSchemaTables_fn = async function(getFetchProps) {
1898
+ if (__privateGet$1(this, _schemaTables))
1899
+ return __privateGet$1(this, _schemaTables);
1714
1900
  const fetchProps = await getFetchProps();
1715
1901
  const { schema } = await getBranchDetails({
1716
1902
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1717
1903
  ...fetchProps
1718
1904
  });
1719
- __privateSet$1(this, _schema, schema);
1720
- return schema;
1905
+ __privateSet$1(this, _schemaTables, schema.tables);
1906
+ return schema.tables;
1721
1907
  };
1722
1908
 
1723
1909
  const isBranchStrategyBuilder = (strategy) => {
1724
1910
  return typeof strategy === "function";
1725
1911
  };
1726
1912
 
1727
- const envBranchNames = [
1728
- "XATA_BRANCH",
1729
- "VERCEL_GIT_COMMIT_REF",
1730
- "CF_PAGES_BRANCH",
1731
- "BRANCH"
1732
- ];
1733
- const defaultBranch = "main";
1734
1913
  async function getCurrentBranchName(options) {
1735
- const env = await getBranchByEnvVariable();
1736
- if (env)
1737
- return env;
1738
- const branch = await getGitBranch();
1739
- if (!branch)
1740
- return defaultBranch;
1741
- const details = await getDatabaseBranch(branch, options);
1742
- if (details)
1743
- return branch;
1744
- return defaultBranch;
1914
+ const { branch, envBranch } = getEnvironment();
1915
+ if (branch) {
1916
+ const details = await getDatabaseBranch(branch, options);
1917
+ if (details)
1918
+ return branch;
1919
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1920
+ }
1921
+ const gitBranch = envBranch || await getGitBranch();
1922
+ return resolveXataBranch(gitBranch, options);
1745
1923
  }
1746
1924
  async function getCurrentBranchDetails(options) {
1747
- const env = await getBranchByEnvVariable();
1748
- if (env)
1749
- return getDatabaseBranch(env, options);
1750
- const branch = await getGitBranch();
1751
- if (!branch)
1752
- return getDatabaseBranch(defaultBranch, options);
1753
- const details = await getDatabaseBranch(branch, options);
1754
- if (details)
1755
- return details;
1756
- return getDatabaseBranch(defaultBranch, options);
1925
+ const branch = await getCurrentBranchName(options);
1926
+ return getDatabaseBranch(branch, options);
1927
+ }
1928
+ async function resolveXataBranch(gitBranch, options) {
1929
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1930
+ const apiKey = options?.apiKey || getAPIKey();
1931
+ if (!databaseURL)
1932
+ throw new Error(
1933
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
1934
+ );
1935
+ if (!apiKey)
1936
+ throw new Error(
1937
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
1938
+ );
1939
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1940
+ const [workspace] = host.split(".");
1941
+ const { fallbackBranch } = getEnvironment();
1942
+ const { branch } = await resolveBranch({
1943
+ apiKey,
1944
+ apiUrl: databaseURL,
1945
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1946
+ workspacesApiUrl: `${protocol}//${host}`,
1947
+ pathParams: { dbName, workspace },
1948
+ queryParams: { gitBranch, fallbackBranch }
1949
+ });
1950
+ return branch;
1757
1951
  }
1758
1952
  async function getDatabaseBranch(branch, options) {
1759
1953
  const databaseURL = options?.databaseURL || getDatabaseURL();
1760
1954
  const apiKey = options?.apiKey || getAPIKey();
1761
1955
  if (!databaseURL)
1762
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1956
+ throw new Error(
1957
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
1958
+ );
1763
1959
  if (!apiKey)
1764
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1960
+ throw new Error(
1961
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
1962
+ );
1765
1963
  const [protocol, , host, , database] = databaseURL.split("/");
1766
1964
  const [workspace] = host.split(".");
1767
1965
  const dbBranchName = `${database}:${branch}`;
@@ -1771,10 +1969,7 @@ async function getDatabaseBranch(branch, options) {
1771
1969
  apiUrl: databaseURL,
1772
1970
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1773
1971
  workspacesApiUrl: `${protocol}//${host}`,
1774
- pathParams: {
1775
- dbBranchName,
1776
- workspace
1777
- }
1972
+ pathParams: { dbBranchName, workspace }
1778
1973
  });
1779
1974
  } catch (err) {
1780
1975
  if (isObject(err) && err.status === 404)
@@ -1782,21 +1977,10 @@ async function getDatabaseBranch(branch, options) {
1782
1977
  throw err;
1783
1978
  }
1784
1979
  }
1785
- function getBranchByEnvVariable() {
1786
- for (const name of envBranchNames) {
1787
- const value = getEnvVariable(name);
1788
- if (value) {
1789
- return value;
1790
- }
1791
- }
1792
- try {
1793
- return XATA_BRANCH;
1794
- } catch (err) {
1795
- }
1796
- }
1797
1980
  function getDatabaseURL() {
1798
1981
  try {
1799
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1982
+ const { databaseURL } = getEnvironment();
1983
+ return databaseURL;
1800
1984
  } catch (err) {
1801
1985
  return void 0;
1802
1986
  }
@@ -1825,24 +2009,26 @@ var __privateMethod = (obj, member, method) => {
1825
2009
  return method;
1826
2010
  };
1827
2011
  const buildClient = (plugins) => {
1828
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2012
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1829
2013
  return _a = class {
1830
- constructor(options = {}, tables) {
2014
+ constructor(options = {}, schemaTables) {
1831
2015
  __privateAdd(this, _parseOptions);
1832
2016
  __privateAdd(this, _getFetchProps);
1833
2017
  __privateAdd(this, _evaluateBranch);
1834
2018
  __privateAdd(this, _branch, void 0);
2019
+ __privateAdd(this, _options, void 0);
1835
2020
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2021
+ __privateSet(this, _options, safeOptions);
1836
2022
  const pluginOptions = {
1837
2023
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1838
2024
  cache: safeOptions.cache
1839
2025
  };
1840
- const db = new SchemaPlugin(tables).build(pluginOptions);
1841
- const search = new SearchPlugin(db).build(pluginOptions);
2026
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2027
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1842
2028
  this.db = db;
1843
2029
  this.search = search;
1844
2030
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1845
- if (!namespace)
2031
+ if (namespace === void 0)
1846
2032
  continue;
1847
2033
  const result = namespace.build(pluginOptions);
1848
2034
  if (result instanceof Promise) {
@@ -1854,22 +2040,22 @@ const buildClient = (plugins) => {
1854
2040
  }
1855
2041
  }
1856
2042
  }
1857
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2043
+ async getConfig() {
2044
+ const databaseURL = __privateGet(this, _options).databaseURL;
2045
+ const branch = await __privateGet(this, _options).branch();
2046
+ return { databaseURL, branch };
2047
+ }
2048
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1858
2049
  const fetch = getFetchImplementation(options?.fetch);
1859
2050
  const databaseURL = options?.databaseURL || getDatabaseURL();
1860
2051
  const apiKey = options?.apiKey || getAPIKey();
1861
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1862
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2052
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2053
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1863
2054
  if (!databaseURL || !apiKey) {
1864
2055
  throw new Error("Options databaseURL and apiKey are required");
1865
2056
  }
1866
2057
  return { fetch, databaseURL, apiKey, branch, cache };
1867
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1868
- fetch,
1869
- apiKey,
1870
- databaseURL,
1871
- branch
1872
- }) {
2058
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch }) {
1873
2059
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1874
2060
  if (!branchValue)
1875
2061
  throw new Error("Unable to resolve branch value");
@@ -1886,7 +2072,7 @@ const buildClient = (plugins) => {
1886
2072
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1887
2073
  if (__privateGet(this, _branch))
1888
2074
  return __privateGet(this, _branch);
1889
- if (!param)
2075
+ if (param === void 0)
1890
2076
  return void 0;
1891
2077
  const strategies = Array.isArray(param) ? [...param] : [param];
1892
2078
  const evaluateBranch = async (strategy) => {
@@ -1904,6 +2090,88 @@ const buildClient = (plugins) => {
1904
2090
  class BaseClient extends buildClient() {
1905
2091
  }
1906
2092
 
2093
+ const META = "__";
2094
+ const VALUE = "___";
2095
+ class Serializer {
2096
+ constructor() {
2097
+ this.classes = {};
2098
+ }
2099
+ add(clazz) {
2100
+ this.classes[clazz.name] = clazz;
2101
+ }
2102
+ toJSON(data) {
2103
+ function visit(obj) {
2104
+ if (Array.isArray(obj))
2105
+ return obj.map(visit);
2106
+ const type = typeof obj;
2107
+ if (type === "undefined")
2108
+ return { [META]: "undefined" };
2109
+ if (type === "bigint")
2110
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2111
+ if (obj === null || type !== "object")
2112
+ return obj;
2113
+ const constructor = obj.constructor;
2114
+ const o = { [META]: constructor.name };
2115
+ for (const [key, value] of Object.entries(obj)) {
2116
+ o[key] = visit(value);
2117
+ }
2118
+ if (constructor === Date)
2119
+ o[VALUE] = obj.toISOString();
2120
+ if (constructor === Map)
2121
+ o[VALUE] = Object.fromEntries(obj);
2122
+ if (constructor === Set)
2123
+ o[VALUE] = [...obj];
2124
+ return o;
2125
+ }
2126
+ return JSON.stringify(visit(data));
2127
+ }
2128
+ fromJSON(json) {
2129
+ return JSON.parse(json, (key, value) => {
2130
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2131
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2132
+ const constructor = this.classes[clazz];
2133
+ if (constructor) {
2134
+ return Object.assign(Object.create(constructor.prototype), rest);
2135
+ }
2136
+ if (clazz === "Date")
2137
+ return new Date(val);
2138
+ if (clazz === "Set")
2139
+ return new Set(val);
2140
+ if (clazz === "Map")
2141
+ return new Map(Object.entries(val));
2142
+ if (clazz === "bigint")
2143
+ return BigInt(val);
2144
+ if (clazz === "undefined")
2145
+ return void 0;
2146
+ return rest;
2147
+ }
2148
+ return value;
2149
+ });
2150
+ }
2151
+ }
2152
+ const defaultSerializer = new Serializer();
2153
+ const serialize = (data) => {
2154
+ return defaultSerializer.toJSON(data);
2155
+ };
2156
+ const deserialize = (json) => {
2157
+ return defaultSerializer.fromJSON(json);
2158
+ };
2159
+
2160
+ function buildWorkerRunner(config) {
2161
+ return function xataWorker(name, _worker) {
2162
+ return async (...args) => {
2163
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2164
+ const result = await fetch(url, {
2165
+ method: "POST",
2166
+ headers: { "Content-Type": "application/json" },
2167
+ body: serialize({ args })
2168
+ });
2169
+ const text = await result.text();
2170
+ return deserialize(text);
2171
+ };
2172
+ };
2173
+ }
2174
+
1907
2175
  class XataError extends Error {
1908
2176
  constructor(message, status) {
1909
2177
  super(message);
@@ -1919,10 +2187,12 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1919
2187
  exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1920
2188
  exports.Page = Page;
1921
2189
  exports.Query = Query;
2190
+ exports.RecordArray = RecordArray;
1922
2191
  exports.Repository = Repository;
1923
2192
  exports.RestRepository = RestRepository;
1924
2193
  exports.SchemaPlugin = SchemaPlugin;
1925
2194
  exports.SearchPlugin = SearchPlugin;
2195
+ exports.Serializer = Serializer;
1926
2196
  exports.SimpleCache = SimpleCache;
1927
2197
  exports.XataApiClient = XataApiClient;
1928
2198
  exports.XataApiPlugin = XataApiPlugin;
@@ -1932,6 +2202,7 @@ exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
1932
2202
  exports.addGitBranchesEntry = addGitBranchesEntry;
1933
2203
  exports.addTableColumn = addTableColumn;
1934
2204
  exports.buildClient = buildClient;
2205
+ exports.buildWorkerRunner = buildWorkerRunner;
1935
2206
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
1936
2207
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
1937
2208
  exports.contains = contains;
@@ -1948,6 +2219,7 @@ exports.deleteTable = deleteTable;
1948
2219
  exports.deleteUser = deleteUser;
1949
2220
  exports.deleteUserAPIKey = deleteUserAPIKey;
1950
2221
  exports.deleteWorkspace = deleteWorkspace;
2222
+ exports.deserialize = deserialize;
1951
2223
  exports.endsWith = endsWith;
1952
2224
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
1953
2225
  exports.exists = exists;
@@ -1963,6 +2235,7 @@ exports.getColumn = getColumn;
1963
2235
  exports.getCurrentBranchDetails = getCurrentBranchDetails;
1964
2236
  exports.getCurrentBranchName = getCurrentBranchName;
1965
2237
  exports.getDatabaseList = getDatabaseList;
2238
+ exports.getDatabaseMetadata = getDatabaseMetadata;
1966
2239
  exports.getDatabaseURL = getDatabaseURL;
1967
2240
  exports.getGitBranchesMapping = getGitBranchesMapping;
1968
2241
  exports.getRecord = getRecord;
@@ -1983,6 +2256,7 @@ exports.insertRecord = insertRecord;
1983
2256
  exports.insertRecordWithID = insertRecordWithID;
1984
2257
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
1985
2258
  exports.is = is;
2259
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
1986
2260
  exports.isIdentifiable = isIdentifiable;
1987
2261
  exports.isNot = isNot;
1988
2262
  exports.isXataRecord = isXataRecord;
@@ -1998,6 +2272,8 @@ exports.removeWorkspaceMember = removeWorkspaceMember;
1998
2272
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
1999
2273
  exports.resolveBranch = resolveBranch;
2000
2274
  exports.searchBranch = searchBranch;
2275
+ exports.searchTable = searchTable;
2276
+ exports.serialize = serialize;
2001
2277
  exports.setTableSchema = setTableSchema;
2002
2278
  exports.startsWith = startsWith;
2003
2279
  exports.updateBranchMetadata = updateBranchMetadata;
@@ -2006,6 +2282,7 @@ exports.updateRecordWithID = updateRecordWithID;
2006
2282
  exports.updateTable = updateTable;
2007
2283
  exports.updateUser = updateUser;
2008
2284
  exports.updateWorkspace = updateWorkspace;
2285
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
2009
2286
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
2010
2287
  exports.upsertRecordWithID = upsertRecordWithID;
2011
2288
  //# sourceMappingURL=index.cjs.map