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

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.vf38b6da";
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
  }
@@ -703,10 +817,10 @@ class BranchApi {
703
817
  ...this.extraProps
704
818
  });
705
819
  }
706
- createBranch(workspace, database, branch, from = "", options = {}) {
820
+ createBranch(workspace, database, branch, from, options = {}) {
707
821
  return operationsByTag.branch.createBranch({
708
822
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
709
- queryParams: { from },
823
+ queryParams: isString(from) ? { from } : void 0,
710
824
  body: options,
711
825
  ...this.extraProps
712
826
  });
@@ -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,30 +1045,30 @@ 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
- return __privateGet$6(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1062
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
938
1063
  }
939
1064
  async previousPage(size, offset) {
940
- return __privateGet$6(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1065
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
941
1066
  }
942
1067
  async firstPage(size, offset) {
943
- return __privateGet$6(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1068
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
944
1069
  }
945
1070
  async lastPage(size, offset) {
946
- return __privateGet$6(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1071
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
947
1072
  }
948
1073
  hasNextPage() {
949
1074
  return this.meta.page.more;
@@ -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;
@@ -994,7 +1167,7 @@ const _Query = class {
994
1167
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
995
1168
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
996
1169
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
997
- __privateGet$5(this, _data).page = data.page ?? parent?.page;
1170
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
998
1171
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
999
1172
  this.any = this.any.bind(this);
1000
1173
  this.all = this.all.bind(this);
@@ -1009,8 +1182,8 @@ const _Query = class {
1009
1182
  return __privateGet$5(this, _data);
1010
1183
  }
1011
1184
  key() {
1012
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$5(this, _data);
1013
- const key = JSON.stringify({ columns, filter, sort, page });
1185
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1186
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1014
1187
  return toBase64(key);
1015
1188
  }
1016
1189
  any(...queries) {
@@ -1039,47 +1212,57 @@ const _Query = class {
1039
1212
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1040
1213
  }
1041
1214
  }
1042
- sort(column, direction) {
1215
+ sort(column, direction = "asc") {
1043
1216
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1044
1217
  const sort = [...originalSort, { column, direction }];
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));
1052
1230
  return __privateGet$5(this, _repository).query(query);
1053
1231
  }
1054
1232
  async *[Symbol.asyncIterator]() {
1055
- for await (const [record] of this.getIterator(1)) {
1233
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1056
1234
  yield record;
1057
1235
  }
1058
1236
  }
1059
- async *getIterator(chunk, options = {}) {
1060
- let offset = 0;
1061
- let end = false;
1062
- while (!end) {
1063
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1064
- yield records;
1065
- offset += chunk;
1066
- end = !meta.page.more;
1237
+ async *getIterator(options = {}) {
1238
+ const { batchSize = 1 } = options;
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;
1067
1246
  }
1068
1247
  }
1069
1248
  async getMany(options = {}) {
1070
- const { records } = await this.getPaginated(options);
1071
- 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;
1072
1254
  }
1073
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1255
+ async getAll(options = {}) {
1256
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1074
1257
  const results = [];
1075
- for await (const page of this.getIterator(chunk, options)) {
1258
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1076
1259
  results.push(...page);
1077
1260
  }
1078
1261
  return results;
1079
1262
  }
1080
1263
  async getFirst(options = {}) {
1081
- const records = await this.getMany({ ...options, page: { size: 1 } });
1082
- return records[0] || null;
1264
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1265
+ return records[0] ?? null;
1083
1266
  }
1084
1267
  cache(ttl) {
1085
1268
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
@@ -1091,10 +1274,10 @@ const _Query = class {
1091
1274
  return this.firstPage(size, offset);
1092
1275
  }
1093
1276
  firstPage(size, offset) {
1094
- return this.getPaginated({ page: { size, offset } });
1277
+ return this.getPaginated({ pagination: { size, offset } });
1095
1278
  }
1096
1279
  lastPage(size, offset) {
1097
- return this.getPaginated({ page: { size, offset, before: "end" } });
1280
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1098
1281
  }
1099
1282
  hasNextPage() {
1100
1283
  return this.meta.page.more;
@@ -1104,12 +1287,20 @@ let Query = _Query;
1104
1287
  _table$1 = new WeakMap();
1105
1288
  _repository = new WeakMap();
1106
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
+ }
1107
1296
 
1108
1297
  function isIdentifiable(x) {
1109
1298
  return isObject(x) && isString(x?.id);
1110
1299
  }
1111
1300
  function isXataRecord(x) {
1112
- 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";
1113
1304
  }
1114
1305
 
1115
1306
  function isSortFilterString(value) {
@@ -1148,7 +1339,7 @@ var __privateAdd$4 = (obj, member, value) => {
1148
1339
  throw TypeError("Cannot add the same private member more than once");
1149
1340
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1150
1341
  };
1151
- var __privateSet$3 = (obj, member, value, setter) => {
1342
+ var __privateSet$4 = (obj, member, value, setter) => {
1152
1343
  __accessCheck$4(obj, member, "write to private field");
1153
1344
  setter ? setter.call(obj, value) : member.set(obj, value);
1154
1345
  return value;
@@ -1157,7 +1348,7 @@ var __privateMethod$2 = (obj, member, method) => {
1157
1348
  __accessCheck$4(obj, member, "access private method");
1158
1349
  return method;
1159
1350
  };
1160
- var _table, _getFetchProps, _cache, _schemaColumns, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaColumns, getSchemaColumns_fn;
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;
1161
1352
  class Repository extends Query {
1162
1353
  }
1163
1354
  class RestRepository extends Query {
@@ -1169,111 +1360,122 @@ class RestRepository extends Query {
1169
1360
  __privateAdd$4(this, _updateRecordWithID);
1170
1361
  __privateAdd$4(this, _upsertRecordWithID);
1171
1362
  __privateAdd$4(this, _deleteRecord);
1172
- __privateAdd$4(this, _invalidateCache);
1173
- __privateAdd$4(this, _setCacheRecord);
1174
- __privateAdd$4(this, _getCacheRecord);
1175
1363
  __privateAdd$4(this, _setCacheQuery);
1176
1364
  __privateAdd$4(this, _getCacheQuery);
1177
- __privateAdd$4(this, _getSchemaColumns);
1365
+ __privateAdd$4(this, _getSchemaTables$1);
1178
1366
  __privateAdd$4(this, _table, void 0);
1179
1367
  __privateAdd$4(this, _getFetchProps, void 0);
1368
+ __privateAdd$4(this, _db, void 0);
1180
1369
  __privateAdd$4(this, _cache, void 0);
1181
- __privateAdd$4(this, _schemaColumns, void 0);
1182
- __privateSet$3(this, _table, options.table);
1183
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1184
- this.db = options.db;
1185
- __privateSet$3(this, _cache, options.pluginOptions.cache);
1186
- }
1187
- 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) {
1188
1378
  if (Array.isArray(a)) {
1189
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1190
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1191
- return records;
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);
1192
1383
  }
1193
1384
  if (isString(a) && isObject(b)) {
1194
1385
  if (a === "")
1195
1386
  throw new Error("The id can't be empty");
1196
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1197
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1198
- return record;
1387
+ const columns = isStringArray(c) ? c : void 0;
1388
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1199
1389
  }
1200
1390
  if (isObject(a) && isString(a.id)) {
1201
1391
  if (a.id === "")
1202
1392
  throw new Error("The id can't be empty");
1203
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1204
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1205
- 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);
1206
1395
  }
1207
1396
  if (isObject(a)) {
1208
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1209
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1210
- return record;
1397
+ const columns = isStringArray(b) ? b : void 0;
1398
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1211
1399
  }
1212
1400
  throw new Error("Invalid arguments for create method");
1213
1401
  }
1214
- async read(recordId) {
1215
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1216
- if (cacheRecord)
1217
- return cacheRecord;
1218
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1219
- try {
1220
- const response = await getRecord({
1221
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1222
- ...fetchProps
1223
- });
1224
- const columns = await __privateMethod$2(this, _getSchemaColumns, getSchemaColumns_fn).call(this);
1225
- return initObject(this.db, columns, __privateGet$4(this, _table), response);
1226
- } catch (e) {
1227
- if (isObject(e) && e.status === 404) {
1228
- 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;
1229
1431
  }
1230
- throw e;
1231
1432
  }
1433
+ return null;
1232
1434
  }
1233
- async update(a, b) {
1435
+ async update(a, b, c) {
1234
1436
  if (Array.isArray(a)) {
1437
+ if (a.length === 0)
1438
+ return [];
1235
1439
  if (a.length > 100) {
1236
1440
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1237
1441
  }
1238
- 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)));
1239
1444
  }
1240
1445
  if (isString(a) && isObject(b)) {
1241
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1242
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1243
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1244
- return record;
1446
+ const columns = isStringArray(c) ? c : void 0;
1447
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1245
1448
  }
1246
1449
  if (isObject(a) && isString(a.id)) {
1247
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1248
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1249
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1250
- 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);
1251
1452
  }
1252
1453
  throw new Error("Invalid arguments for update method");
1253
1454
  }
1254
- async createOrUpdate(a, b) {
1455
+ async createOrUpdate(a, b, c) {
1255
1456
  if (Array.isArray(a)) {
1457
+ if (a.length === 0)
1458
+ return [];
1256
1459
  if (a.length > 100) {
1257
1460
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1258
1461
  }
1259
- 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)));
1260
1464
  }
1261
1465
  if (isString(a) && isObject(b)) {
1262
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1263
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1264
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1265
- return record;
1466
+ const columns = isStringArray(c) ? c : void 0;
1467
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1266
1468
  }
1267
1469
  if (isObject(a) && isString(a.id)) {
1268
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1269
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1270
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1271
- 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);
1272
1472
  }
1273
1473
  throw new Error("Invalid arguments for createOrUpdate method");
1274
1474
  }
1275
1475
  async delete(a) {
1276
1476
  if (Array.isArray(a)) {
1477
+ if (a.length === 0)
1478
+ return;
1277
1479
  if (a.length > 100) {
1278
1480
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1279
1481
  }
@@ -1282,25 +1484,30 @@ class RestRepository extends Query {
1282
1484
  }
1283
1485
  if (isString(a)) {
1284
1486
  await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1285
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1286
1487
  return;
1287
1488
  }
1288
1489
  if (isObject(a) && isString(a.id)) {
1289
1490
  await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1290
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1291
1491
  return;
1292
1492
  }
1293
1493
  throw new Error("Invalid arguments for delete method");
1294
1494
  }
1295
1495
  async search(query, options = {}) {
1296
1496
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1297
- const { records } = await searchBranch({
1298
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1299
- 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
+ },
1300
1507
  ...fetchProps
1301
1508
  });
1302
- const columns = await __privateMethod$2(this, _getSchemaColumns, getSchemaColumns_fn).call(this);
1303
- return records.map((item) => initObject(this.db, columns, __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));
1304
1511
  }
1305
1512
  async query(query) {
1306
1513
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
@@ -1309,8 +1516,8 @@ class RestRepository extends Query {
1309
1516
  const data = query.getQueryOptions();
1310
1517
  const body = {
1311
1518
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1312
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1313
- page: data.page,
1519
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1520
+ page: data.pagination,
1314
1521
  columns: data.columns
1315
1522
  };
1316
1523
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
@@ -1319,18 +1526,19 @@ class RestRepository extends Query {
1319
1526
  body,
1320
1527
  ...fetchProps
1321
1528
  });
1322
- const columns = await __privateMethod$2(this, _getSchemaColumns, getSchemaColumns_fn).call(this);
1323
- const records = objects.map((record) => initObject(this.db, columns, __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));
1324
1531
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1325
1532
  return new Page(query, meta, records);
1326
1533
  }
1327
1534
  }
1328
1535
  _table = new WeakMap();
1329
1536
  _getFetchProps = new WeakMap();
1537
+ _db = new WeakMap();
1330
1538
  _cache = new WeakMap();
1331
- _schemaColumns = new WeakMap();
1539
+ _schemaTables$2 = new WeakMap();
1332
1540
  _insertRecordWithoutId = new WeakSet();
1333
- insertRecordWithoutId_fn = async function(object) {
1541
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1334
1542
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1335
1543
  const record = transformObjectLinks(object);
1336
1544
  const response = await insertRecord({
@@ -1339,17 +1547,15 @@ insertRecordWithoutId_fn = async function(object) {
1339
1547
  dbBranchName: "{dbBranch}",
1340
1548
  tableName: __privateGet$4(this, _table)
1341
1549
  },
1550
+ queryParams: { columns },
1342
1551
  body: record,
1343
1552
  ...fetchProps
1344
1553
  });
1345
- const finalObject = await this.read(response.id);
1346
- if (!finalObject) {
1347
- throw new Error("The server failed to save the record");
1348
- }
1349
- 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);
1350
1556
  };
1351
1557
  _insertRecordWithId = new WeakSet();
1352
- insertRecordWithId_fn = async function(recordId, object) {
1558
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1353
1559
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1354
1560
  const record = transformObjectLinks(object);
1355
1561
  const response = await insertRecordWithID({
@@ -1360,56 +1566,52 @@ insertRecordWithId_fn = async function(recordId, object) {
1360
1566
  recordId
1361
1567
  },
1362
1568
  body: record,
1363
- queryParams: { createOnly: true },
1569
+ queryParams: { createOnly: true, columns },
1364
1570
  ...fetchProps
1365
1571
  });
1366
- const finalObject = await this.read(response.id);
1367
- if (!finalObject) {
1368
- throw new Error("The server failed to save the record");
1369
- }
1370
- 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);
1371
1574
  };
1372
1575
  _bulkInsertTableRecords = new WeakSet();
1373
- bulkInsertTableRecords_fn = async function(objects) {
1576
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1374
1577
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1375
1578
  const records = objects.map((object) => transformObjectLinks(object));
1376
1579
  const response = await bulkInsertTableRecords({
1377
1580
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1581
+ queryParams: { columns },
1378
1582
  body: { records },
1379
1583
  ...fetchProps
1380
1584
  });
1381
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1382
- if (finalObjects.length !== objects.length) {
1383
- 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");
1384
1587
  }
1385
- 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));
1386
1590
  };
1387
1591
  _updateRecordWithID = new WeakSet();
1388
- updateRecordWithID_fn = async function(recordId, object) {
1592
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1389
1593
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1390
1594
  const record = transformObjectLinks(object);
1391
1595
  const response = await updateRecordWithID({
1392
1596
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1597
+ queryParams: { columns },
1393
1598
  body: record,
1394
1599
  ...fetchProps
1395
1600
  });
1396
- const item = await this.read(response.id);
1397
- if (!item)
1398
- throw new Error("The server failed to save the record");
1399
- 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);
1400
1603
  };
1401
1604
  _upsertRecordWithID = new WeakSet();
1402
- upsertRecordWithID_fn = async function(recordId, object) {
1605
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1403
1606
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1404
1607
  const response = await upsertRecordWithID({
1405
1608
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1609
+ queryParams: { columns },
1406
1610
  body: object,
1407
1611
  ...fetchProps
1408
1612
  });
1409
- const item = await this.read(response.id);
1410
- if (!item)
1411
- throw new Error("The server failed to save the record");
1412
- 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);
1413
1615
  };
1414
1616
  _deleteRecord = new WeakSet();
1415
1617
  deleteRecord_fn = async function(recordId) {
@@ -1419,29 +1621,6 @@ deleteRecord_fn = async function(recordId) {
1419
1621
  ...fetchProps
1420
1622
  });
1421
1623
  };
1422
- _invalidateCache = new WeakSet();
1423
- invalidateCache_fn = async function(recordId) {
1424
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1425
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1426
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1427
- for (const [key, value] of queries) {
1428
- const ids = getIds(value);
1429
- if (ids.includes(recordId))
1430
- await __privateGet$4(this, _cache).delete(key);
1431
- }
1432
- };
1433
- _setCacheRecord = new WeakSet();
1434
- setCacheRecord_fn = async function(record) {
1435
- if (!__privateGet$4(this, _cache).cacheRecords)
1436
- return;
1437
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1438
- };
1439
- _getCacheRecord = new WeakSet();
1440
- getCacheRecord_fn = async function(recordId) {
1441
- if (!__privateGet$4(this, _cache).cacheRecords)
1442
- return null;
1443
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1444
- };
1445
1624
  _setCacheQuery = new WeakSet();
1446
1625
  setCacheQuery_fn = async function(query, meta, records) {
1447
1626
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -1453,21 +1632,22 @@ getCacheQuery_fn = async function(query) {
1453
1632
  if (!result)
1454
1633
  return null;
1455
1634
  const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1456
- if (!ttl || ttl < 0)
1457
- return result;
1635
+ if (ttl < 0)
1636
+ return null;
1458
1637
  const hasExpired = result.date.getTime() + ttl < Date.now();
1459
1638
  return hasExpired ? null : result;
1460
1639
  };
1461
- _getSchemaColumns = new WeakSet();
1462
- getSchemaColumns_fn = async function() {
1463
- if (__privateGet$4(this, _schemaColumns))
1464
- return __privateGet$4(this, _schemaColumns);
1465
- const { columns } = await getTableSchema({
1466
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1467
- ...await __privateGet$4(this, _getFetchProps).call(this)
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);
1644
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1645
+ const { schema } = await getBranchDetails({
1646
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1647
+ ...fetchProps
1468
1648
  });
1469
- __privateSet$3(this, _schemaColumns, columns);
1470
- return columns;
1649
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1650
+ return schema.tables;
1471
1651
  };
1472
1652
  const transformObjectLinks = (object) => {
1473
1653
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1476,17 +1656,21 @@ const transformObjectLinks = (object) => {
1476
1656
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1477
1657
  }, {});
1478
1658
  };
1479
- const initObject = (db, columns, table, object) => {
1659
+ const initObject = (db, schemaTables, table, object) => {
1480
1660
  const result = {};
1481
- Object.assign(result, object);
1482
- for (const column of columns) {
1661
+ const { xata, ...rest } = object ?? {};
1662
+ Object.assign(result, rest);
1663
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1664
+ if (!columns)
1665
+ console.error(`Table ${table} not found in schema`);
1666
+ for (const column of columns ?? []) {
1483
1667
  const value = result[column.name];
1484
1668
  switch (column.type) {
1485
1669
  case "datetime": {
1486
- const date = new Date(value);
1487
- if (isNaN(date.getTime())) {
1670
+ const date = value !== void 0 ? new Date(value) : void 0;
1671
+ if (date && isNaN(date.getTime())) {
1488
1672
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1489
- } else {
1673
+ } else if (date) {
1490
1674
  result[column.name] = date;
1491
1675
  }
1492
1676
  break;
@@ -1495,36 +1679,33 @@ const initObject = (db, columns, table, object) => {
1495
1679
  const linkTable = column.link?.table;
1496
1680
  if (!linkTable) {
1497
1681
  console.error(`Failed to parse link for field ${column.name}`);
1498
- } else if (value && isObject(value)) {
1499
- result[column.name] = initObject(db, columns, linkTable, value);
1682
+ } else if (isObject(value)) {
1683
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1500
1684
  }
1501
1685
  break;
1502
1686
  }
1503
1687
  }
1504
1688
  }
1505
- result.read = function() {
1506
- return db[table].read(result["id"]);
1689
+ result.read = function(columns2) {
1690
+ return db[table].read(result["id"], columns2);
1507
1691
  };
1508
- result.update = function(data) {
1509
- return db[table].update(result["id"], data);
1692
+ result.update = function(data, columns2) {
1693
+ return db[table].update(result["id"], data, columns2);
1510
1694
  };
1511
1695
  result.delete = function() {
1512
1696
  return db[table].delete(result["id"]);
1513
1697
  };
1514
- for (const prop of ["read", "update", "delete"]) {
1698
+ result.getMetadata = function() {
1699
+ return xata;
1700
+ };
1701
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1515
1702
  Object.defineProperty(result, prop, { enumerable: false });
1516
1703
  }
1517
1704
  Object.freeze(result);
1518
1705
  return result;
1519
1706
  };
1520
- function getIds(value) {
1521
- if (Array.isArray(value)) {
1522
- return value.map((item) => getIds(item)).flat();
1523
- }
1524
- if (!isObject(value))
1525
- return [];
1526
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1527
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1707
+ function isResponseWithRecords(value) {
1708
+ return isObject(value) && Array.isArray(value.records);
1528
1709
  }
1529
1710
 
1530
1711
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1540,7 +1721,7 @@ var __privateAdd$3 = (obj, member, value) => {
1540
1721
  throw TypeError("Cannot add the same private member more than once");
1541
1722
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1542
1723
  };
1543
- var __privateSet$2 = (obj, member, value, setter) => {
1724
+ var __privateSet$3 = (obj, member, value, setter) => {
1544
1725
  __accessCheck$3(obj, member, "write to private field");
1545
1726
  setter ? setter.call(obj, value) : member.set(obj, value);
1546
1727
  return value;
@@ -1549,9 +1730,8 @@ var _map;
1549
1730
  class SimpleCache {
1550
1731
  constructor(options = {}) {
1551
1732
  __privateAdd$3(this, _map, void 0);
1552
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1733
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1553
1734
  this.capacity = options.max ?? 500;
1554
- this.cacheRecords = options.cacheRecords ?? true;
1555
1735
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1556
1736
  }
1557
1737
  async getAll() {
@@ -1609,31 +1789,42 @@ var __privateAdd$2 = (obj, member, value) => {
1609
1789
  throw TypeError("Cannot add the same private member more than once");
1610
1790
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1611
1791
  };
1612
- 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;
1613
1798
  class SchemaPlugin extends XataPlugin {
1614
- constructor(tableNames) {
1799
+ constructor(schemaTables) {
1615
1800
  super();
1616
- this.tableNames = tableNames;
1617
1801
  __privateAdd$2(this, _tables, {});
1802
+ __privateAdd$2(this, _schemaTables$1, void 0);
1803
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1618
1804
  }
1619
1805
  build(pluginOptions) {
1620
- const db = new Proxy({}, {
1621
- get: (_target, table) => {
1622
- if (!isString(table))
1623
- throw new Error("Invalid table name");
1624
- if (!__privateGet$2(this, _tables)[table]) {
1625
- __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];
1626
1816
  }
1627
- return __privateGet$2(this, _tables)[table];
1628
1817
  }
1629
- });
1630
- for (const table of this.tableNames ?? []) {
1631
- 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) });
1632
1822
  }
1633
1823
  return db;
1634
1824
  }
1635
1825
  }
1636
1826
  _tables = new WeakMap();
1827
+ _schemaTables$1 = new WeakMap();
1637
1828
 
1638
1829
  var __accessCheck$1 = (obj, member, msg) => {
1639
1830
  if (!member.has(obj))
@@ -1657,113 +1848,118 @@ var __privateMethod$1 = (obj, member, method) => {
1657
1848
  __accessCheck$1(obj, member, "access private method");
1658
1849
  return method;
1659
1850
  };
1660
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
1851
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1661
1852
  class SearchPlugin extends XataPlugin {
1662
- constructor(db) {
1853
+ constructor(db, schemaTables) {
1663
1854
  super();
1664
1855
  this.db = db;
1665
1856
  __privateAdd$1(this, _search);
1666
- __privateAdd$1(this, _getSchema);
1667
- __privateAdd$1(this, _schema, void 0);
1857
+ __privateAdd$1(this, _getSchemaTables);
1858
+ __privateAdd$1(this, _schemaTables, void 0);
1859
+ __privateSet$1(this, _schemaTables, schemaTables);
1668
1860
  }
1669
1861
  build({ getFetchProps }) {
1670
1862
  return {
1671
1863
  all: async (query, options = {}) => {
1672
1864
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1673
- 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);
1674
1866
  return records.map((record) => {
1675
1867
  const { table = "orphan" } = record.xata;
1676
- const columns = schema.tables.find((t) => t.name === table)?.columns;
1677
- if (!columns) {
1678
- console.error(`No schema columns found for table ${table}`);
1679
- }
1680
- return { table, record: initObject(this.db, columns ?? [], table, record) };
1868
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1681
1869
  });
1682
1870
  },
1683
1871
  byTable: async (query, options = {}) => {
1684
1872
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1685
- 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);
1686
1874
  return records.reduce((acc, record) => {
1687
1875
  const { table = "orphan" } = record.xata;
1688
- const columns = schema.tables.find((t) => t.name === table)?.columns;
1689
- if (!columns) {
1690
- console.error(`No schema columns found for table ${table}`);
1691
- }
1692
1876
  const items = acc[table] ?? [];
1693
- const item = initObject(this.db, columns ?? [], table, record);
1877
+ const item = initObject(this.db, schemaTables, table, record);
1694
1878
  return { ...acc, [table]: [...items, item] };
1695
1879
  }, {});
1696
1880
  }
1697
1881
  };
1698
1882
  }
1699
1883
  }
1700
- _schema = new WeakMap();
1884
+ _schemaTables = new WeakMap();
1701
1885
  _search = new WeakSet();
1702
1886
  search_fn = async function(query, options, getFetchProps) {
1703
1887
  const fetchProps = await getFetchProps();
1704
- const { tables, fuzziness } = options ?? {};
1888
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1705
1889
  const { records } = await searchBranch({
1706
1890
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1707
- body: { tables, query, fuzziness },
1891
+ body: { tables, query, fuzziness, prefix, highlight },
1708
1892
  ...fetchProps
1709
1893
  });
1710
1894
  return records;
1711
1895
  };
1712
- _getSchema = new WeakSet();
1713
- getSchema_fn = async function(getFetchProps) {
1714
- if (__privateGet$1(this, _schema))
1715
- 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);
1716
1900
  const fetchProps = await getFetchProps();
1717
1901
  const { schema } = await getBranchDetails({
1718
1902
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1719
1903
  ...fetchProps
1720
1904
  });
1721
- __privateSet$1(this, _schema, schema);
1722
- return schema;
1905
+ __privateSet$1(this, _schemaTables, schema.tables);
1906
+ return schema.tables;
1723
1907
  };
1724
1908
 
1725
1909
  const isBranchStrategyBuilder = (strategy) => {
1726
1910
  return typeof strategy === "function";
1727
1911
  };
1728
1912
 
1729
- const envBranchNames = [
1730
- "XATA_BRANCH",
1731
- "VERCEL_GIT_COMMIT_REF",
1732
- "CF_PAGES_BRANCH",
1733
- "BRANCH"
1734
- ];
1735
- const defaultBranch = "main";
1736
1913
  async function getCurrentBranchName(options) {
1737
- const env = await getBranchByEnvVariable();
1738
- if (env)
1739
- return env;
1740
- const branch = await getGitBranch();
1741
- if (!branch)
1742
- return defaultBranch;
1743
- const details = await getDatabaseBranch(branch, options);
1744
- if (details)
1745
- return branch;
1746
- 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);
1747
1923
  }
1748
1924
  async function getCurrentBranchDetails(options) {
1749
- const env = await getBranchByEnvVariable();
1750
- if (env)
1751
- return getDatabaseBranch(env, options);
1752
- const branch = await getGitBranch();
1753
- if (!branch)
1754
- return getDatabaseBranch(defaultBranch, options);
1755
- const details = await getDatabaseBranch(branch, options);
1756
- if (details)
1757
- return details;
1758
- 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;
1759
1951
  }
1760
1952
  async function getDatabaseBranch(branch, options) {
1761
1953
  const databaseURL = options?.databaseURL || getDatabaseURL();
1762
1954
  const apiKey = options?.apiKey || getAPIKey();
1763
1955
  if (!databaseURL)
1764
- 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
+ );
1765
1959
  if (!apiKey)
1766
- 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
+ );
1767
1963
  const [protocol, , host, , database] = databaseURL.split("/");
1768
1964
  const [workspace] = host.split(".");
1769
1965
  const dbBranchName = `${database}:${branch}`;
@@ -1773,10 +1969,7 @@ async function getDatabaseBranch(branch, options) {
1773
1969
  apiUrl: databaseURL,
1774
1970
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1775
1971
  workspacesApiUrl: `${protocol}//${host}`,
1776
- pathParams: {
1777
- dbBranchName,
1778
- workspace
1779
- }
1972
+ pathParams: { dbBranchName, workspace }
1780
1973
  });
1781
1974
  } catch (err) {
1782
1975
  if (isObject(err) && err.status === 404)
@@ -1784,21 +1977,10 @@ async function getDatabaseBranch(branch, options) {
1784
1977
  throw err;
1785
1978
  }
1786
1979
  }
1787
- function getBranchByEnvVariable() {
1788
- for (const name of envBranchNames) {
1789
- const value = getEnvVariable(name);
1790
- if (value) {
1791
- return value;
1792
- }
1793
- }
1794
- try {
1795
- return XATA_BRANCH;
1796
- } catch (err) {
1797
- }
1798
- }
1799
1980
  function getDatabaseURL() {
1800
1981
  try {
1801
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1982
+ const { databaseURL } = getEnvironment();
1983
+ return databaseURL;
1802
1984
  } catch (err) {
1803
1985
  return void 0;
1804
1986
  }
@@ -1827,24 +2009,26 @@ var __privateMethod = (obj, member, method) => {
1827
2009
  return method;
1828
2010
  };
1829
2011
  const buildClient = (plugins) => {
1830
- 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;
1831
2013
  return _a = class {
1832
- constructor(options = {}, tables) {
2014
+ constructor(options = {}, schemaTables) {
1833
2015
  __privateAdd(this, _parseOptions);
1834
2016
  __privateAdd(this, _getFetchProps);
1835
2017
  __privateAdd(this, _evaluateBranch);
1836
2018
  __privateAdd(this, _branch, void 0);
2019
+ __privateAdd(this, _options, void 0);
1837
2020
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2021
+ __privateSet(this, _options, safeOptions);
1838
2022
  const pluginOptions = {
1839
2023
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1840
2024
  cache: safeOptions.cache
1841
2025
  };
1842
- const db = new SchemaPlugin(tables).build(pluginOptions);
1843
- const search = new SearchPlugin(db).build(pluginOptions);
2026
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2027
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1844
2028
  this.db = db;
1845
2029
  this.search = search;
1846
2030
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1847
- if (!namespace)
2031
+ if (namespace === void 0)
1848
2032
  continue;
1849
2033
  const result = namespace.build(pluginOptions);
1850
2034
  if (result instanceof Promise) {
@@ -1856,22 +2040,22 @@ const buildClient = (plugins) => {
1856
2040
  }
1857
2041
  }
1858
2042
  }
1859
- }, _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) {
1860
2049
  const fetch = getFetchImplementation(options?.fetch);
1861
2050
  const databaseURL = options?.databaseURL || getDatabaseURL();
1862
2051
  const apiKey = options?.apiKey || getAPIKey();
1863
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1864
- 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 });
1865
2054
  if (!databaseURL || !apiKey) {
1866
2055
  throw new Error("Options databaseURL and apiKey are required");
1867
2056
  }
1868
2057
  return { fetch, databaseURL, apiKey, branch, cache };
1869
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1870
- fetch,
1871
- apiKey,
1872
- databaseURL,
1873
- branch
1874
- }) {
2058
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch }) {
1875
2059
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1876
2060
  if (!branchValue)
1877
2061
  throw new Error("Unable to resolve branch value");
@@ -1888,7 +2072,7 @@ const buildClient = (plugins) => {
1888
2072
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1889
2073
  if (__privateGet(this, _branch))
1890
2074
  return __privateGet(this, _branch);
1891
- if (!param)
2075
+ if (param === void 0)
1892
2076
  return void 0;
1893
2077
  const strategies = Array.isArray(param) ? [...param] : [param];
1894
2078
  const evaluateBranch = async (strategy) => {
@@ -1906,6 +2090,88 @@ const buildClient = (plugins) => {
1906
2090
  class BaseClient extends buildClient() {
1907
2091
  }
1908
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
+
1909
2175
  class XataError extends Error {
1910
2176
  constructor(message, status) {
1911
2177
  super(message);
@@ -1921,10 +2187,12 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1921
2187
  exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1922
2188
  exports.Page = Page;
1923
2189
  exports.Query = Query;
2190
+ exports.RecordArray = RecordArray;
1924
2191
  exports.Repository = Repository;
1925
2192
  exports.RestRepository = RestRepository;
1926
2193
  exports.SchemaPlugin = SchemaPlugin;
1927
2194
  exports.SearchPlugin = SearchPlugin;
2195
+ exports.Serializer = Serializer;
1928
2196
  exports.SimpleCache = SimpleCache;
1929
2197
  exports.XataApiClient = XataApiClient;
1930
2198
  exports.XataApiPlugin = XataApiPlugin;
@@ -1934,6 +2202,7 @@ exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
1934
2202
  exports.addGitBranchesEntry = addGitBranchesEntry;
1935
2203
  exports.addTableColumn = addTableColumn;
1936
2204
  exports.buildClient = buildClient;
2205
+ exports.buildWorkerRunner = buildWorkerRunner;
1937
2206
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
1938
2207
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
1939
2208
  exports.contains = contains;
@@ -1950,6 +2219,7 @@ exports.deleteTable = deleteTable;
1950
2219
  exports.deleteUser = deleteUser;
1951
2220
  exports.deleteUserAPIKey = deleteUserAPIKey;
1952
2221
  exports.deleteWorkspace = deleteWorkspace;
2222
+ exports.deserialize = deserialize;
1953
2223
  exports.endsWith = endsWith;
1954
2224
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
1955
2225
  exports.exists = exists;
@@ -1965,6 +2235,7 @@ exports.getColumn = getColumn;
1965
2235
  exports.getCurrentBranchDetails = getCurrentBranchDetails;
1966
2236
  exports.getCurrentBranchName = getCurrentBranchName;
1967
2237
  exports.getDatabaseList = getDatabaseList;
2238
+ exports.getDatabaseMetadata = getDatabaseMetadata;
1968
2239
  exports.getDatabaseURL = getDatabaseURL;
1969
2240
  exports.getGitBranchesMapping = getGitBranchesMapping;
1970
2241
  exports.getRecord = getRecord;
@@ -1985,6 +2256,7 @@ exports.insertRecord = insertRecord;
1985
2256
  exports.insertRecordWithID = insertRecordWithID;
1986
2257
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
1987
2258
  exports.is = is;
2259
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
1988
2260
  exports.isIdentifiable = isIdentifiable;
1989
2261
  exports.isNot = isNot;
1990
2262
  exports.isXataRecord = isXataRecord;
@@ -2000,6 +2272,8 @@ exports.removeWorkspaceMember = removeWorkspaceMember;
2000
2272
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
2001
2273
  exports.resolveBranch = resolveBranch;
2002
2274
  exports.searchBranch = searchBranch;
2275
+ exports.searchTable = searchTable;
2276
+ exports.serialize = serialize;
2003
2277
  exports.setTableSchema = setTableSchema;
2004
2278
  exports.startsWith = startsWith;
2005
2279
  exports.updateBranchMetadata = updateBranchMetadata;
@@ -2008,6 +2282,7 @@ exports.updateRecordWithID = updateRecordWithID;
2008
2282
  exports.updateTable = updateTable;
2009
2283
  exports.updateUser = updateUser;
2010
2284
  exports.updateWorkspace = updateWorkspace;
2285
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
2011
2286
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
2012
2287
  exports.upsertRecordWithID = upsertRecordWithID;
2013
2288
  //# sourceMappingURL=index.cjs.map