@xata.io/client 0.0.0-alpha.vfb4a018 → 0.0.0-alpha.vfbbe3c7

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
  }
@@ -74,16 +148,28 @@ function getFetchImplementation(userFetch) {
74
148
  return fetchImpl;
75
149
  }
76
150
 
77
- class FetcherError extends Error {
78
- constructor(status, data) {
151
+ const VERSION = "0.0.0-alpha.vfbbe3c7";
152
+
153
+ class ErrorWithCause extends Error {
154
+ constructor(message, options) {
155
+ super(message, options);
156
+ }
157
+ }
158
+ class FetcherError extends ErrorWithCause {
159
+ constructor(status, data, requestId) {
79
160
  super(getMessage(data));
80
161
  this.status = status;
81
162
  this.errors = isBulkError(data) ? data.errors : void 0;
163
+ this.requestId = requestId;
82
164
  if (data instanceof Error) {
83
165
  this.stack = data.stack;
84
166
  this.cause = data.cause;
85
167
  }
86
168
  }
169
+ toString() {
170
+ const error = super.toString();
171
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
172
+ }
87
173
  }
88
174
  function isBulkError(error) {
89
175
  return isObject(error) && Array.isArray(error.errors);
@@ -106,7 +192,12 @@ function getMessage(data) {
106
192
  }
107
193
 
108
194
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
109
- const query = new URLSearchParams(queryParams).toString();
195
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
196
+ if (value === void 0 || value === null)
197
+ return acc;
198
+ return { ...acc, [key]: value };
199
+ }, {});
200
+ const query = new URLSearchParams(cleanQueryParams).toString();
110
201
  const queryString = query.length > 0 ? `?${query}` : "";
111
202
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
112
203
  };
@@ -146,6 +237,7 @@ async function fetch$1({
146
237
  body: body ? JSON.stringify(body) : void 0,
147
238
  headers: {
148
239
  "Content-Type": "application/json",
240
+ "User-Agent": `Xata client-ts/${VERSION}`,
149
241
  ...headers,
150
242
  ...hostHeader(fullUrl),
151
243
  Authorization: `Bearer ${apiKey}`
@@ -154,14 +246,15 @@ async function fetch$1({
154
246
  if (response.status === 204) {
155
247
  return {};
156
248
  }
249
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
157
250
  try {
158
251
  const jsonResponse = await response.json();
159
252
  if (response.ok) {
160
253
  return jsonResponse;
161
254
  }
162
- throw new FetcherError(response.status, jsonResponse);
255
+ throw new FetcherError(response.status, jsonResponse, requestId);
163
256
  } catch (error) {
164
- throw new FetcherError(response.status, error);
257
+ throw new FetcherError(response.status, error, requestId);
165
258
  }
166
259
  }
167
260
 
@@ -220,6 +313,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
220
313
  ...variables
221
314
  });
222
315
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
316
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
223
317
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
224
318
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
225
319
  method: "delete",
@@ -268,11 +362,7 @@ const getBranchDetails = (variables) => fetch$1({
268
362
  method: "get",
269
363
  ...variables
270
364
  });
271
- const createBranch = (variables) => fetch$1({
272
- url: "/db/{dbBranchName}",
273
- method: "put",
274
- ...variables
275
- });
365
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
276
366
  const deleteBranch = (variables) => fetch$1({
277
367
  url: "/db/{dbBranchName}",
278
368
  method: "delete",
@@ -346,11 +436,7 @@ const updateColumn = (variables) => fetch$1({
346
436
  method: "patch",
347
437
  ...variables
348
438
  });
349
- const insertRecord = (variables) => fetch$1({
350
- url: "/db/{dbBranchName}/tables/{tableName}/data",
351
- method: "post",
352
- ...variables
353
- });
439
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
354
440
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
355
441
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
356
442
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -370,6 +456,11 @@ const queryTable = (variables) => fetch$1({
370
456
  method: "post",
371
457
  ...variables
372
458
  });
459
+ const searchTable = (variables) => fetch$1({
460
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
461
+ method: "post",
462
+ ...variables
463
+ });
373
464
  const searchBranch = (variables) => fetch$1({
374
465
  url: "/db/{dbBranchName}/search",
375
466
  method: "post",
@@ -387,6 +478,7 @@ const operationsByTag = {
387
478
  updateWorkspaceMemberRole,
388
479
  removeWorkspaceMember,
389
480
  inviteWorkspaceMember,
481
+ updateWorkspaceMemberInvite,
390
482
  cancelWorkspaceMemberInvite,
391
483
  resendWorkspaceMemberInvite,
392
484
  acceptWorkspaceMemberInvite
@@ -433,6 +525,7 @@ const operationsByTag = {
433
525
  getRecord,
434
526
  bulkInsertTableRecords,
435
527
  queryTable,
528
+ searchTable,
436
529
  searchBranch
437
530
  }
438
531
  };
@@ -466,7 +559,7 @@ var __accessCheck$7 = (obj, member, msg) => {
466
559
  if (!member.has(obj))
467
560
  throw TypeError("Cannot " + msg);
468
561
  };
469
- var __privateGet$6 = (obj, member, getter) => {
562
+ var __privateGet$7 = (obj, member, getter) => {
470
563
  __accessCheck$7(obj, member, "read from private field");
471
564
  return getter ? getter.call(obj) : member.get(obj);
472
565
  };
@@ -475,7 +568,7 @@ var __privateAdd$7 = (obj, member, value) => {
475
568
  throw TypeError("Cannot add the same private member more than once");
476
569
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
477
570
  };
478
- var __privateSet$5 = (obj, member, value, setter) => {
571
+ var __privateSet$7 = (obj, member, value, setter) => {
479
572
  __accessCheck$7(obj, member, "write to private field");
480
573
  setter ? setter.call(obj, value) : member.set(obj, value);
481
574
  return value;
@@ -490,7 +583,7 @@ class XataApiClient {
490
583
  if (!apiKey) {
491
584
  throw new Error("Could not resolve a valid apiKey");
492
585
  }
493
- __privateSet$5(this, _extraProps, {
586
+ __privateSet$7(this, _extraProps, {
494
587
  apiUrl: getHostUrl(provider, "main"),
495
588
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
496
589
  fetchImpl: getFetchImplementation(options.fetch),
@@ -498,34 +591,34 @@ class XataApiClient {
498
591
  });
499
592
  }
500
593
  get user() {
501
- if (!__privateGet$6(this, _namespaces).user)
502
- __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
503
- return __privateGet$6(this, _namespaces).user;
594
+ if (!__privateGet$7(this, _namespaces).user)
595
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
596
+ return __privateGet$7(this, _namespaces).user;
504
597
  }
505
598
  get workspaces() {
506
- if (!__privateGet$6(this, _namespaces).workspaces)
507
- __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
508
- return __privateGet$6(this, _namespaces).workspaces;
599
+ if (!__privateGet$7(this, _namespaces).workspaces)
600
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
601
+ return __privateGet$7(this, _namespaces).workspaces;
509
602
  }
510
603
  get databases() {
511
- if (!__privateGet$6(this, _namespaces).databases)
512
- __privateGet$6(this, _namespaces).databases = new DatabaseApi(__privateGet$6(this, _extraProps));
513
- return __privateGet$6(this, _namespaces).databases;
604
+ if (!__privateGet$7(this, _namespaces).databases)
605
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
606
+ return __privateGet$7(this, _namespaces).databases;
514
607
  }
515
608
  get branches() {
516
- if (!__privateGet$6(this, _namespaces).branches)
517
- __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
518
- return __privateGet$6(this, _namespaces).branches;
609
+ if (!__privateGet$7(this, _namespaces).branches)
610
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
611
+ return __privateGet$7(this, _namespaces).branches;
519
612
  }
520
613
  get tables() {
521
- if (!__privateGet$6(this, _namespaces).tables)
522
- __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
523
- return __privateGet$6(this, _namespaces).tables;
614
+ if (!__privateGet$7(this, _namespaces).tables)
615
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
616
+ return __privateGet$7(this, _namespaces).tables;
524
617
  }
525
618
  get records() {
526
- if (!__privateGet$6(this, _namespaces).records)
527
- __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
528
- return __privateGet$6(this, _namespaces).records;
619
+ if (!__privateGet$7(this, _namespaces).records)
620
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
621
+ return __privateGet$7(this, _namespaces).records;
529
622
  }
530
623
  }
531
624
  _extraProps = new WeakMap();
@@ -617,6 +710,13 @@ class WorkspaceApi {
617
710
  ...this.extraProps
618
711
  });
619
712
  }
713
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
714
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
715
+ pathParams: { workspaceId, inviteId },
716
+ body: { role },
717
+ ...this.extraProps
718
+ });
719
+ }
620
720
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
621
721
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
622
722
  pathParams: { workspaceId, inviteId },
@@ -679,10 +779,10 @@ class DatabaseApi {
679
779
  ...this.extraProps
680
780
  });
681
781
  }
682
- resolveBranch(workspace, dbName, gitBranch) {
782
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
683
783
  return operationsByTag.database.resolveBranch({
684
784
  pathParams: { workspace, dbName },
685
- queryParams: { gitBranch },
785
+ queryParams: { gitBranch, fallbackBranch },
686
786
  ...this.extraProps
687
787
  });
688
788
  }
@@ -703,10 +803,10 @@ class BranchApi {
703
803
  ...this.extraProps
704
804
  });
705
805
  }
706
- createBranch(workspace, database, branch, from = "", options = {}) {
806
+ createBranch(workspace, database, branch, from, options = {}) {
707
807
  return operationsByTag.branch.createBranch({
708
808
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
709
- queryParams: { from },
809
+ queryParams: isString(from) ? { from } : void 0,
710
810
  body: options,
711
811
  ...this.extraProps
712
812
  });
@@ -831,9 +931,10 @@ class RecordsApi {
831
931
  constructor(extraProps) {
832
932
  this.extraProps = extraProps;
833
933
  }
834
- insertRecord(workspace, database, branch, tableName, record) {
934
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
835
935
  return operationsByTag.records.insertRecord({
836
936
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
937
+ queryParams: options,
837
938
  body: record,
838
939
  ...this.extraProps
839
940
  });
@@ -862,21 +963,24 @@ class RecordsApi {
862
963
  ...this.extraProps
863
964
  });
864
965
  }
865
- deleteRecord(workspace, database, branch, tableName, recordId) {
966
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
866
967
  return operationsByTag.records.deleteRecord({
867
968
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
969
+ queryParams: options,
868
970
  ...this.extraProps
869
971
  });
870
972
  }
871
973
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
872
974
  return operationsByTag.records.getRecord({
873
975
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
976
+ queryParams: options,
874
977
  ...this.extraProps
875
978
  });
876
979
  }
877
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
980
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
878
981
  return operationsByTag.records.bulkInsertTableRecords({
879
982
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
983
+ queryParams: options,
880
984
  body: { records },
881
985
  ...this.extraProps
882
986
  });
@@ -888,6 +992,13 @@ class RecordsApi {
888
992
  ...this.extraProps
889
993
  });
890
994
  }
995
+ searchTable(workspace, database, branch, tableName, query) {
996
+ return operationsByTag.records.searchTable({
997
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
998
+ body: query,
999
+ ...this.extraProps
1000
+ });
1001
+ }
891
1002
  searchBranch(workspace, database, branch, query) {
892
1003
  return operationsByTag.records.searchBranch({
893
1004
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -911,7 +1022,7 @@ var __accessCheck$6 = (obj, member, msg) => {
911
1022
  if (!member.has(obj))
912
1023
  throw TypeError("Cannot " + msg);
913
1024
  };
914
- var __privateGet$5 = (obj, member, getter) => {
1025
+ var __privateGet$6 = (obj, member, getter) => {
915
1026
  __accessCheck$6(obj, member, "read from private field");
916
1027
  return getter ? getter.call(obj) : member.get(obj);
917
1028
  };
@@ -920,30 +1031,30 @@ var __privateAdd$6 = (obj, member, value) => {
920
1031
  throw TypeError("Cannot add the same private member more than once");
921
1032
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
922
1033
  };
923
- var __privateSet$4 = (obj, member, value, setter) => {
1034
+ var __privateSet$6 = (obj, member, value, setter) => {
924
1035
  __accessCheck$6(obj, member, "write to private field");
925
1036
  setter ? setter.call(obj, value) : member.set(obj, value);
926
1037
  return value;
927
1038
  };
928
- var _query;
1039
+ var _query, _page;
929
1040
  class Page {
930
1041
  constructor(query, meta, records = []) {
931
1042
  __privateAdd$6(this, _query, void 0);
932
- __privateSet$4(this, _query, query);
1043
+ __privateSet$6(this, _query, query);
933
1044
  this.meta = meta;
934
- this.records = records;
1045
+ this.records = new RecordArray(this, records);
935
1046
  }
936
1047
  async nextPage(size, offset) {
937
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1048
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
938
1049
  }
939
1050
  async previousPage(size, offset) {
940
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1051
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
941
1052
  }
942
1053
  async firstPage(size, offset) {
943
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1054
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
944
1055
  }
945
1056
  async lastPage(size, offset) {
946
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1057
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
947
1058
  }
948
1059
  hasNextPage() {
949
1060
  return this.meta.page.more;
@@ -951,15 +1062,62 @@ class Page {
951
1062
  }
952
1063
  _query = new WeakMap();
953
1064
  const PAGINATION_MAX_SIZE = 200;
954
- const PAGINATION_DEFAULT_SIZE = 200;
1065
+ const PAGINATION_DEFAULT_SIZE = 20;
955
1066
  const PAGINATION_MAX_OFFSET = 800;
956
1067
  const PAGINATION_DEFAULT_OFFSET = 0;
1068
+ function isCursorPaginationOptions(options) {
1069
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1070
+ }
1071
+ const _RecordArray = class extends Array {
1072
+ constructor(...args) {
1073
+ super(..._RecordArray.parseConstructorParams(...args));
1074
+ __privateAdd$6(this, _page, void 0);
1075
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1076
+ }
1077
+ static parseConstructorParams(...args) {
1078
+ if (args.length === 1 && typeof args[0] === "number") {
1079
+ return new Array(args[0]);
1080
+ }
1081
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1082
+ const result = args[1] ?? args[0].records ?? [];
1083
+ return new Array(...result);
1084
+ }
1085
+ return new Array(...args);
1086
+ }
1087
+ toArray() {
1088
+ return new Array(...this);
1089
+ }
1090
+ map(callbackfn, thisArg) {
1091
+ return this.toArray().map(callbackfn, thisArg);
1092
+ }
1093
+ async nextPage(size, offset) {
1094
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1095
+ return new _RecordArray(newPage);
1096
+ }
1097
+ async previousPage(size, offset) {
1098
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1099
+ return new _RecordArray(newPage);
1100
+ }
1101
+ async firstPage(size, offset) {
1102
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1103
+ return new _RecordArray(newPage);
1104
+ }
1105
+ async lastPage(size, offset) {
1106
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1107
+ return new _RecordArray(newPage);
1108
+ }
1109
+ hasNextPage() {
1110
+ return __privateGet$6(this, _page).meta.page.more;
1111
+ }
1112
+ };
1113
+ let RecordArray = _RecordArray;
1114
+ _page = new WeakMap();
957
1115
 
958
1116
  var __accessCheck$5 = (obj, member, msg) => {
959
1117
  if (!member.has(obj))
960
1118
  throw TypeError("Cannot " + msg);
961
1119
  };
962
- var __privateGet$4 = (obj, member, getter) => {
1120
+ var __privateGet$5 = (obj, member, getter) => {
963
1121
  __accessCheck$5(obj, member, "read from private field");
964
1122
  return getter ? getter.call(obj) : member.get(obj);
965
1123
  };
@@ -968,34 +1126,35 @@ var __privateAdd$5 = (obj, member, value) => {
968
1126
  throw TypeError("Cannot add the same private member more than once");
969
1127
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
970
1128
  };
971
- var __privateSet$3 = (obj, member, value, setter) => {
1129
+ var __privateSet$5 = (obj, member, value, setter) => {
972
1130
  __accessCheck$5(obj, member, "write to private field");
973
1131
  setter ? setter.call(obj, value) : member.set(obj, value);
974
1132
  return value;
975
1133
  };
976
1134
  var _table$1, _repository, _data;
977
1135
  const _Query = class {
978
- constructor(repository, table, data, parent) {
1136
+ constructor(repository, table, data, rawParent) {
979
1137
  __privateAdd$5(this, _table$1, void 0);
980
1138
  __privateAdd$5(this, _repository, void 0);
981
1139
  __privateAdd$5(this, _data, { filter: {} });
982
1140
  this.meta = { page: { cursor: "start", more: true } };
983
- this.records = [];
984
- __privateSet$3(this, _table$1, table);
1141
+ this.records = new RecordArray(this, []);
1142
+ __privateSet$5(this, _table$1, table);
985
1143
  if (repository) {
986
- __privateSet$3(this, _repository, repository);
1144
+ __privateSet$5(this, _repository, repository);
987
1145
  } else {
988
- __privateSet$3(this, _repository, this);
1146
+ __privateSet$5(this, _repository, this);
989
1147
  }
990
- __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
991
- __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
992
- __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
993
- __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
994
- __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
995
- __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
996
- __privateGet$4(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
997
- __privateGet$4(this, _data).page = data.page ?? parent?.page;
998
- __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
1148
+ const parent = cleanParent(data, rawParent);
1149
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1150
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1151
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1152
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1153
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1154
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1155
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1156
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1157
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
999
1158
  this.any = this.any.bind(this);
1000
1159
  this.all = this.all.bind(this);
1001
1160
  this.not = this.not.bind(this);
@@ -1006,50 +1165,50 @@ const _Query = class {
1006
1165
  Object.defineProperty(this, "repository", { enumerable: false });
1007
1166
  }
1008
1167
  getQueryOptions() {
1009
- return __privateGet$4(this, _data);
1168
+ return __privateGet$5(this, _data);
1010
1169
  }
1011
1170
  key() {
1012
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$4(this, _data);
1013
- const key = JSON.stringify({ columns, filter, sort, page });
1171
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1172
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1014
1173
  return toBase64(key);
1015
1174
  }
1016
1175
  any(...queries) {
1017
1176
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1018
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
1177
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
1019
1178
  }
1020
1179
  all(...queries) {
1021
1180
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1022
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1181
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1023
1182
  }
1024
1183
  not(...queries) {
1025
1184
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1026
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
1185
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
1027
1186
  }
1028
1187
  none(...queries) {
1029
1188
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1030
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
1189
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
1031
1190
  }
1032
1191
  filter(a, b) {
1033
1192
  if (arguments.length === 1) {
1034
1193
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1035
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
1036
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1194
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1195
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1037
1196
  } else {
1038
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1039
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1197
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1198
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1040
1199
  }
1041
1200
  }
1042
1201
  sort(column, direction) {
1043
- const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
1202
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1044
1203
  const sort = [...originalSort, { column, direction }];
1045
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
1204
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1046
1205
  }
1047
1206
  select(columns) {
1048
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { columns }, __privateGet$4(this, _data));
1207
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1049
1208
  }
1050
1209
  getPaginated(options = {}) {
1051
- const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
1052
- return __privateGet$4(this, _repository).query(query);
1210
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1211
+ return __privateGet$5(this, _repository).query(query);
1053
1212
  }
1054
1213
  async *[Symbol.asyncIterator]() {
1055
1214
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
@@ -1058,18 +1217,21 @@ const _Query = class {
1058
1217
  }
1059
1218
  async *getIterator(options = {}) {
1060
1219
  const { batchSize = 1 } = options;
1061
- let offset = 0;
1062
- let end = false;
1063
- while (!end) {
1064
- const { records, meta } = await this.getPaginated({ ...options, page: { size: batchSize, offset } });
1065
- yield records;
1066
- offset += batchSize;
1067
- end = !meta.page.more;
1220
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1221
+ let more = page.hasNextPage();
1222
+ yield page.records;
1223
+ while (more) {
1224
+ page = await page.nextPage();
1225
+ more = page.hasNextPage();
1226
+ yield page.records;
1068
1227
  }
1069
1228
  }
1070
1229
  async getMany(options = {}) {
1071
- const { records } = await this.getPaginated(options);
1072
- return records;
1230
+ const page = await this.getPaginated(options);
1231
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1232
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1233
+ }
1234
+ return page.records;
1073
1235
  }
1074
1236
  async getAll(options = {}) {
1075
1237
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1080,11 +1242,11 @@ const _Query = class {
1080
1242
  return results;
1081
1243
  }
1082
1244
  async getFirst(options = {}) {
1083
- const records = await this.getMany({ ...options, page: { size: 1 } });
1084
- return records[0] || null;
1245
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1246
+ return records[0] ?? null;
1085
1247
  }
1086
1248
  cache(ttl) {
1087
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
1249
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1088
1250
  }
1089
1251
  nextPage(size, offset) {
1090
1252
  return this.firstPage(size, offset);
@@ -1093,10 +1255,10 @@ const _Query = class {
1093
1255
  return this.firstPage(size, offset);
1094
1256
  }
1095
1257
  firstPage(size, offset) {
1096
- return this.getPaginated({ page: { size, offset } });
1258
+ return this.getPaginated({ pagination: { size, offset } });
1097
1259
  }
1098
1260
  lastPage(size, offset) {
1099
- return this.getPaginated({ page: { size, offset, before: "end" } });
1261
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1100
1262
  }
1101
1263
  hasNextPage() {
1102
1264
  return this.meta.page.more;
@@ -1106,12 +1268,20 @@ let Query = _Query;
1106
1268
  _table$1 = new WeakMap();
1107
1269
  _repository = new WeakMap();
1108
1270
  _data = new WeakMap();
1271
+ function cleanParent(data, parent) {
1272
+ if (isCursorPaginationOptions(data.pagination)) {
1273
+ return { ...parent, sorting: void 0, filter: void 0 };
1274
+ }
1275
+ return parent;
1276
+ }
1109
1277
 
1110
1278
  function isIdentifiable(x) {
1111
1279
  return isObject(x) && isString(x?.id);
1112
1280
  }
1113
1281
  function isXataRecord(x) {
1114
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1282
+ const record = x;
1283
+ const metadata = record?.getMetadata();
1284
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1115
1285
  }
1116
1286
 
1117
1287
  function isSortFilterString(value) {
@@ -1141,7 +1311,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1141
1311
  if (!member.has(obj))
1142
1312
  throw TypeError("Cannot " + msg);
1143
1313
  };
1144
- var __privateGet$3 = (obj, member, getter) => {
1314
+ var __privateGet$4 = (obj, member, getter) => {
1145
1315
  __accessCheck$4(obj, member, "read from private field");
1146
1316
  return getter ? getter.call(obj) : member.get(obj);
1147
1317
  };
@@ -1150,7 +1320,7 @@ var __privateAdd$4 = (obj, member, value) => {
1150
1320
  throw TypeError("Cannot add the same private member more than once");
1151
1321
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1152
1322
  };
1153
- var __privateSet$2 = (obj, member, value, setter) => {
1323
+ var __privateSet$4 = (obj, member, value, setter) => {
1154
1324
  __accessCheck$4(obj, member, "write to private field");
1155
1325
  setter ? setter.call(obj, value) : member.set(obj, value);
1156
1326
  return value;
@@ -1159,7 +1329,7 @@ var __privateMethod$2 = (obj, member, method) => {
1159
1329
  __accessCheck$4(obj, member, "access private method");
1160
1330
  return method;
1161
1331
  };
1162
- var _table, _links, _getFetchProps, _cache, _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;
1332
+ var _table, _getFetchProps, _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
1333
  class Repository extends Query {
1164
1334
  }
1165
1335
  class RestRepository extends Query {
@@ -1171,110 +1341,121 @@ class RestRepository extends Query {
1171
1341
  __privateAdd$4(this, _updateRecordWithID);
1172
1342
  __privateAdd$4(this, _upsertRecordWithID);
1173
1343
  __privateAdd$4(this, _deleteRecord);
1174
- __privateAdd$4(this, _invalidateCache);
1175
- __privateAdd$4(this, _setCacheRecord);
1176
- __privateAdd$4(this, _getCacheRecord);
1177
1344
  __privateAdd$4(this, _setCacheQuery);
1178
1345
  __privateAdd$4(this, _getCacheQuery);
1346
+ __privateAdd$4(this, _getSchemaTables$1);
1179
1347
  __privateAdd$4(this, _table, void 0);
1180
- __privateAdd$4(this, _links, void 0);
1181
1348
  __privateAdd$4(this, _getFetchProps, void 0);
1182
1349
  __privateAdd$4(this, _cache, void 0);
1183
- __privateSet$2(this, _table, options.table);
1184
- __privateSet$2(this, _links, options.links ?? {});
1185
- __privateSet$2(this, _getFetchProps, options.pluginOptions.getFetchProps);
1350
+ __privateAdd$4(this, _schemaTables$2, void 0);
1351
+ __privateSet$4(this, _table, options.table);
1352
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1186
1353
  this.db = options.db;
1187
- __privateSet$2(this, _cache, options.pluginOptions.cache);
1354
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1355
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1188
1356
  }
1189
- async create(a, b) {
1357
+ async create(a, b, c) {
1190
1358
  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;
1359
+ if (a.length === 0)
1360
+ return [];
1361
+ const columns = isStringArray(b) ? b : void 0;
1362
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1194
1363
  }
1195
1364
  if (isString(a) && isObject(b)) {
1196
1365
  if (a === "")
1197
1366
  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;
1367
+ const columns = isStringArray(c) ? c : void 0;
1368
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1201
1369
  }
1202
1370
  if (isObject(a) && isString(a.id)) {
1203
1371
  if (a.id === "")
1204
1372
  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;
1373
+ const columns = isStringArray(b) ? b : void 0;
1374
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1208
1375
  }
1209
1376
  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;
1377
+ const columns = isStringArray(b) ? b : void 0;
1378
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1213
1379
  }
1214
1380
  throw new Error("Invalid arguments for create method");
1215
1381
  }
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$3(this, _getFetchProps).call(this);
1221
- try {
1222
- const response = await getRecord({
1223
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1224
- ...fetchProps
1225
- });
1226
- return initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), response);
1227
- } catch (e) {
1228
- if (isObject(e) && e.status === 404) {
1229
- return null;
1382
+ async read(a, b) {
1383
+ const columns = isStringArray(b) ? b : ["*"];
1384
+ if (Array.isArray(a)) {
1385
+ if (a.length === 0)
1386
+ return [];
1387
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1388
+ const finalObjects = await this.getAll({ filter: { id: { $any: ids } }, columns });
1389
+ const dictionary = finalObjects.reduce((acc, object) => {
1390
+ acc[object.id] = object;
1391
+ return acc;
1392
+ }, {});
1393
+ return ids.map((id2) => dictionary[id2] ?? null);
1394
+ }
1395
+ const id = isString(a) ? a : a.id;
1396
+ if (isString(id)) {
1397
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1398
+ try {
1399
+ const response = await getRecord({
1400
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1401
+ queryParams: { columns },
1402
+ ...fetchProps
1403
+ });
1404
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1405
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1406
+ } catch (e) {
1407
+ if (isObject(e) && e.status === 404) {
1408
+ return null;
1409
+ }
1410
+ throw e;
1230
1411
  }
1231
- throw e;
1232
1412
  }
1413
+ return null;
1233
1414
  }
1234
- async update(a, b) {
1415
+ async update(a, b, c) {
1235
1416
  if (Array.isArray(a)) {
1417
+ if (a.length === 0)
1418
+ return [];
1236
1419
  if (a.length > 100) {
1237
1420
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1238
1421
  }
1239
- return Promise.all(a.map((object) => this.update(object)));
1422
+ const columns = isStringArray(b) ? b : ["*"];
1423
+ return Promise.all(a.map((object) => this.update(object, columns)));
1240
1424
  }
1241
1425
  if (isString(a) && isObject(b)) {
1242
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1243
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1244
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1245
- return record;
1426
+ const columns = isStringArray(c) ? c : void 0;
1427
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1246
1428
  }
1247
1429
  if (isObject(a) && isString(a.id)) {
1248
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1249
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1250
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1251
- return record;
1430
+ const columns = isStringArray(b) ? b : void 0;
1431
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1252
1432
  }
1253
1433
  throw new Error("Invalid arguments for update method");
1254
1434
  }
1255
- async createOrUpdate(a, b) {
1435
+ async createOrUpdate(a, b, c) {
1256
1436
  if (Array.isArray(a)) {
1437
+ if (a.length === 0)
1438
+ return [];
1257
1439
  if (a.length > 100) {
1258
1440
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1259
1441
  }
1260
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1442
+ const columns = isStringArray(b) ? b : ["*"];
1443
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1261
1444
  }
1262
1445
  if (isString(a) && isObject(b)) {
1263
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1264
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1265
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1266
- return record;
1446
+ const columns = isStringArray(c) ? c : void 0;
1447
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1267
1448
  }
1268
1449
  if (isObject(a) && isString(a.id)) {
1269
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1270
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1271
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1272
- return record;
1450
+ const columns = isStringArray(c) ? c : void 0;
1451
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1273
1452
  }
1274
1453
  throw new Error("Invalid arguments for createOrUpdate method");
1275
1454
  }
1276
1455
  async delete(a) {
1277
1456
  if (Array.isArray(a)) {
1457
+ if (a.length === 0)
1458
+ return;
1278
1459
  if (a.length > 100) {
1279
1460
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1280
1461
  }
@@ -1283,24 +1464,30 @@ class RestRepository extends Query {
1283
1464
  }
1284
1465
  if (isString(a)) {
1285
1466
  await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1286
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1287
1467
  return;
1288
1468
  }
1289
1469
  if (isObject(a) && isString(a.id)) {
1290
1470
  await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1291
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1292
1471
  return;
1293
1472
  }
1294
1473
  throw new Error("Invalid arguments for delete method");
1295
1474
  }
1296
1475
  async search(query, options = {}) {
1297
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1298
- const { records } = await searchBranch({
1299
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1300
- body: { tables: [__privateGet$3(this, _table)], query, fuzziness: options.fuzziness },
1476
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1477
+ const { records } = await searchTable({
1478
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1479
+ body: {
1480
+ query,
1481
+ fuzziness: options.fuzziness,
1482
+ prefix: options.prefix,
1483
+ highlight: options.highlight,
1484
+ filter: options.filter,
1485
+ boosters: options.boosters
1486
+ },
1301
1487
  ...fetchProps
1302
1488
  });
1303
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), item));
1489
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1490
+ return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1304
1491
  }
1305
1492
  async query(query) {
1306
1493
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
@@ -1309,154 +1496,138 @@ class RestRepository extends Query {
1309
1496
  const data = query.getQueryOptions();
1310
1497
  const body = {
1311
1498
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1312
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1313
- page: data.page,
1499
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1500
+ page: data.pagination,
1314
1501
  columns: data.columns
1315
1502
  };
1316
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1503
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1317
1504
  const { meta, records: objects } = await queryTable({
1318
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1505
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1319
1506
  body,
1320
1507
  ...fetchProps
1321
1508
  });
1322
- const records = objects.map((record) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), record));
1509
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1510
+ const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1323
1511
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1324
1512
  return new Page(query, meta, records);
1325
1513
  }
1326
1514
  }
1327
1515
  _table = new WeakMap();
1328
- _links = new WeakMap();
1329
1516
  _getFetchProps = new WeakMap();
1330
1517
  _cache = new WeakMap();
1518
+ _schemaTables$2 = new WeakMap();
1331
1519
  _insertRecordWithoutId = new WeakSet();
1332
- insertRecordWithoutId_fn = async function(object) {
1333
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1520
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1521
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1334
1522
  const record = transformObjectLinks(object);
1335
1523
  const response = await insertRecord({
1336
1524
  pathParams: {
1337
1525
  workspace: "{workspaceId}",
1338
1526
  dbBranchName: "{dbBranch}",
1339
- tableName: __privateGet$3(this, _table)
1527
+ tableName: __privateGet$4(this, _table)
1340
1528
  },
1529
+ queryParams: { columns },
1341
1530
  body: record,
1342
1531
  ...fetchProps
1343
1532
  });
1344
- const finalObject = await this.read(response.id);
1345
- if (!finalObject) {
1346
- throw new Error("The server failed to save the record");
1347
- }
1348
- return finalObject;
1533
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1534
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1349
1535
  };
1350
1536
  _insertRecordWithId = new WeakSet();
1351
- insertRecordWithId_fn = async function(recordId, object) {
1352
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1537
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1538
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1353
1539
  const record = transformObjectLinks(object);
1354
1540
  const response = await insertRecordWithID({
1355
1541
  pathParams: {
1356
1542
  workspace: "{workspaceId}",
1357
1543
  dbBranchName: "{dbBranch}",
1358
- tableName: __privateGet$3(this, _table),
1544
+ tableName: __privateGet$4(this, _table),
1359
1545
  recordId
1360
1546
  },
1361
1547
  body: record,
1362
- queryParams: { createOnly: true },
1548
+ queryParams: { createOnly: true, columns },
1363
1549
  ...fetchProps
1364
1550
  });
1365
- const finalObject = await this.read(response.id);
1366
- if (!finalObject) {
1367
- throw new Error("The server failed to save the record");
1368
- }
1369
- return finalObject;
1551
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1552
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1370
1553
  };
1371
1554
  _bulkInsertTableRecords = new WeakSet();
1372
- bulkInsertTableRecords_fn = async function(objects) {
1373
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1555
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1556
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1374
1557
  const records = objects.map((object) => transformObjectLinks(object));
1375
1558
  const response = await bulkInsertTableRecords({
1376
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1559
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1560
+ queryParams: { columns },
1377
1561
  body: { records },
1378
1562
  ...fetchProps
1379
1563
  });
1380
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1381
- if (finalObjects.length !== objects.length) {
1382
- throw new Error("The server failed to save some records");
1564
+ if (!isResponseWithRecords(response)) {
1565
+ throw new Error("Request included columns but server didn't include them");
1383
1566
  }
1384
- return finalObjects;
1567
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1568
+ return response.records?.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1385
1569
  };
1386
1570
  _updateRecordWithID = new WeakSet();
1387
- updateRecordWithID_fn = async function(recordId, object) {
1388
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1571
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1572
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1389
1573
  const record = transformObjectLinks(object);
1390
1574
  const response = await updateRecordWithID({
1391
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1575
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1576
+ queryParams: { columns },
1392
1577
  body: record,
1393
1578
  ...fetchProps
1394
1579
  });
1395
- const item = await this.read(response.id);
1396
- if (!item)
1397
- throw new Error("The server failed to save the record");
1398
- return item;
1580
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1581
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1399
1582
  };
1400
1583
  _upsertRecordWithID = new WeakSet();
1401
- upsertRecordWithID_fn = async function(recordId, object) {
1402
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1584
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1585
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1403
1586
  const response = await upsertRecordWithID({
1404
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1587
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1588
+ queryParams: { columns },
1405
1589
  body: object,
1406
1590
  ...fetchProps
1407
1591
  });
1408
- const item = await this.read(response.id);
1409
- if (!item)
1410
- throw new Error("The server failed to save the record");
1411
- return item;
1592
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1593
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1412
1594
  };
1413
1595
  _deleteRecord = new WeakSet();
1414
1596
  deleteRecord_fn = async function(recordId) {
1415
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1597
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1416
1598
  await deleteRecord({
1417
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1599
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1418
1600
  ...fetchProps
1419
1601
  });
1420
1602
  };
1421
- _invalidateCache = new WeakSet();
1422
- invalidateCache_fn = async function(recordId) {
1423
- await __privateGet$3(this, _cache).delete(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1424
- const cacheItems = await __privateGet$3(this, _cache).getAll();
1425
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1426
- for (const [key, value] of queries) {
1427
- const ids = getIds(value);
1428
- if (ids.includes(recordId))
1429
- await __privateGet$3(this, _cache).delete(key);
1430
- }
1431
- };
1432
- _setCacheRecord = new WeakSet();
1433
- setCacheRecord_fn = async function(record) {
1434
- if (!__privateGet$3(this, _cache).cacheRecords)
1435
- return;
1436
- await __privateGet$3(this, _cache).set(`rec_${__privateGet$3(this, _table)}:${record.id}`, record);
1437
- };
1438
- _getCacheRecord = new WeakSet();
1439
- getCacheRecord_fn = async function(recordId) {
1440
- if (!__privateGet$3(this, _cache).cacheRecords)
1441
- return null;
1442
- return __privateGet$3(this, _cache).get(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1443
- };
1444
1603
  _setCacheQuery = new WeakSet();
1445
1604
  setCacheQuery_fn = async function(query, meta, records) {
1446
- await __privateGet$3(this, _cache).set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1605
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1447
1606
  };
1448
1607
  _getCacheQuery = new WeakSet();
1449
1608
  getCacheQuery_fn = async function(query) {
1450
- const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
1451
- const result = await __privateGet$3(this, _cache).get(key);
1609
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1610
+ const result = await __privateGet$4(this, _cache).get(key);
1452
1611
  if (!result)
1453
1612
  return null;
1454
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1455
- if (!ttl || ttl < 0)
1456
- return result;
1613
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1614
+ if (ttl < 0)
1615
+ return null;
1457
1616
  const hasExpired = result.date.getTime() + ttl < Date.now();
1458
1617
  return hasExpired ? null : result;
1459
1618
  };
1619
+ _getSchemaTables$1 = new WeakSet();
1620
+ getSchemaTables_fn$1 = async function() {
1621
+ if (__privateGet$4(this, _schemaTables$2))
1622
+ return __privateGet$4(this, _schemaTables$2);
1623
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1624
+ const { schema } = await getBranchDetails({
1625
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1626
+ ...fetchProps
1627
+ });
1628
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1629
+ return schema.tables;
1630
+ };
1460
1631
  const transformObjectLinks = (object) => {
1461
1632
  return Object.entries(object).reduce((acc, [key, value]) => {
1462
1633
  if (key === "xata")
@@ -1464,47 +1635,63 @@ const transformObjectLinks = (object) => {
1464
1635
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1465
1636
  }, {});
1466
1637
  };
1467
- const initObject = (db, links, table, object) => {
1638
+ const initObject = (db, schemaTables, table, object) => {
1468
1639
  const result = {};
1469
- Object.assign(result, object);
1470
- const tableLinks = links[table] || [];
1471
- for (const link of tableLinks) {
1472
- const [field, linkTable] = link;
1473
- const value = result[field];
1474
- if (value && isObject(value)) {
1475
- result[field] = initObject(db, links, linkTable, value);
1640
+ const { xata, ...rest } = object ?? {};
1641
+ Object.assign(result, rest);
1642
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1643
+ if (!columns)
1644
+ console.error(`Table ${table} not found in schema`);
1645
+ for (const column of columns ?? []) {
1646
+ const value = result[column.name];
1647
+ switch (column.type) {
1648
+ case "datetime": {
1649
+ const date = value !== void 0 ? new Date(value) : void 0;
1650
+ if (date && isNaN(date.getTime())) {
1651
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1652
+ } else if (date) {
1653
+ result[column.name] = date;
1654
+ }
1655
+ break;
1656
+ }
1657
+ case "link": {
1658
+ const linkTable = column.link?.table;
1659
+ if (!linkTable) {
1660
+ console.error(`Failed to parse link for field ${column.name}`);
1661
+ } else if (isObject(value)) {
1662
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1663
+ }
1664
+ break;
1665
+ }
1476
1666
  }
1477
1667
  }
1478
- result.read = function() {
1479
- return db[table].read(result["id"]);
1668
+ result.read = function(columns2) {
1669
+ return db[table].read(result["id"], columns2);
1480
1670
  };
1481
- result.update = function(data) {
1482
- return db[table].update(result["id"], data);
1671
+ result.update = function(data, columns2) {
1672
+ return db[table].update(result["id"], data, columns2);
1483
1673
  };
1484
1674
  result.delete = function() {
1485
1675
  return db[table].delete(result["id"]);
1486
1676
  };
1487
- for (const prop of ["read", "update", "delete"]) {
1677
+ result.getMetadata = function() {
1678
+ return xata;
1679
+ };
1680
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1488
1681
  Object.defineProperty(result, prop, { enumerable: false });
1489
1682
  }
1490
1683
  Object.freeze(result);
1491
1684
  return result;
1492
1685
  };
1493
- function getIds(value) {
1494
- if (Array.isArray(value)) {
1495
- return value.map((item) => getIds(item)).flat();
1496
- }
1497
- if (!isObject(value))
1498
- return [];
1499
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1500
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1686
+ function isResponseWithRecords(value) {
1687
+ return isObject(value) && Array.isArray(value.records);
1501
1688
  }
1502
1689
 
1503
1690
  var __accessCheck$3 = (obj, member, msg) => {
1504
1691
  if (!member.has(obj))
1505
1692
  throw TypeError("Cannot " + msg);
1506
1693
  };
1507
- var __privateGet$2 = (obj, member, getter) => {
1694
+ var __privateGet$3 = (obj, member, getter) => {
1508
1695
  __accessCheck$3(obj, member, "read from private field");
1509
1696
  return getter ? getter.call(obj) : member.get(obj);
1510
1697
  };
@@ -1513,7 +1700,7 @@ var __privateAdd$3 = (obj, member, value) => {
1513
1700
  throw TypeError("Cannot add the same private member more than once");
1514
1701
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1515
1702
  };
1516
- var __privateSet$1 = (obj, member, value, setter) => {
1703
+ var __privateSet$3 = (obj, member, value, setter) => {
1517
1704
  __accessCheck$3(obj, member, "write to private field");
1518
1705
  setter ? setter.call(obj, value) : member.set(obj, value);
1519
1706
  return value;
@@ -1522,30 +1709,29 @@ var _map;
1522
1709
  class SimpleCache {
1523
1710
  constructor(options = {}) {
1524
1711
  __privateAdd$3(this, _map, void 0);
1525
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
1712
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1526
1713
  this.capacity = options.max ?? 500;
1527
- this.cacheRecords = options.cacheRecords ?? true;
1528
1714
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1529
1715
  }
1530
1716
  async getAll() {
1531
- return Object.fromEntries(__privateGet$2(this, _map));
1717
+ return Object.fromEntries(__privateGet$3(this, _map));
1532
1718
  }
1533
1719
  async get(key) {
1534
- return __privateGet$2(this, _map).get(key) ?? null;
1720
+ return __privateGet$3(this, _map).get(key) ?? null;
1535
1721
  }
1536
1722
  async set(key, value) {
1537
1723
  await this.delete(key);
1538
- __privateGet$2(this, _map).set(key, value);
1539
- if (__privateGet$2(this, _map).size > this.capacity) {
1540
- const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
1724
+ __privateGet$3(this, _map).set(key, value);
1725
+ if (__privateGet$3(this, _map).size > this.capacity) {
1726
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1541
1727
  await this.delete(leastRecentlyUsed);
1542
1728
  }
1543
1729
  }
1544
1730
  async delete(key) {
1545
- __privateGet$2(this, _map).delete(key);
1731
+ __privateGet$3(this, _map).delete(key);
1546
1732
  }
1547
1733
  async clear() {
1548
- return __privateGet$2(this, _map).clear();
1734
+ return __privateGet$3(this, _map).clear();
1549
1735
  }
1550
1736
  }
1551
1737
  _map = new WeakMap();
@@ -1573,7 +1759,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1573
1759
  if (!member.has(obj))
1574
1760
  throw TypeError("Cannot " + msg);
1575
1761
  };
1576
- var __privateGet$1 = (obj, member, getter) => {
1762
+ var __privateGet$2 = (obj, member, getter) => {
1577
1763
  __accessCheck$2(obj, member, "read from private field");
1578
1764
  return getter ? getter.call(obj) : member.get(obj);
1579
1765
  };
@@ -1582,122 +1768,158 @@ var __privateAdd$2 = (obj, member, value) => {
1582
1768
  throw TypeError("Cannot add the same private member more than once");
1583
1769
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1584
1770
  };
1585
- var _tables;
1771
+ var __privateSet$2 = (obj, member, value, setter) => {
1772
+ __accessCheck$2(obj, member, "write to private field");
1773
+ setter ? setter.call(obj, value) : member.set(obj, value);
1774
+ return value;
1775
+ };
1776
+ var _tables, _schemaTables$1;
1586
1777
  class SchemaPlugin extends XataPlugin {
1587
- constructor(links, tableNames) {
1778
+ constructor(schemaTables) {
1588
1779
  super();
1589
- this.links = links;
1590
- this.tableNames = tableNames;
1591
1780
  __privateAdd$2(this, _tables, {});
1781
+ __privateAdd$2(this, _schemaTables$1, void 0);
1782
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1592
1783
  }
1593
1784
  build(pluginOptions) {
1594
- const links = this.links;
1595
1785
  const db = new Proxy({}, {
1596
1786
  get: (_target, table) => {
1597
1787
  if (!isString(table))
1598
1788
  throw new Error("Invalid table name");
1599
- if (!__privateGet$1(this, _tables)[table]) {
1600
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, links });
1789
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1790
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1601
1791
  }
1602
- return __privateGet$1(this, _tables)[table];
1792
+ return __privateGet$2(this, _tables)[table];
1603
1793
  }
1604
1794
  });
1605
- for (const table of this.tableNames ?? []) {
1606
- db[table] = new RestRepository({ db, pluginOptions, table, links });
1795
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1796
+ for (const table of tableNames) {
1797
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1607
1798
  }
1608
1799
  return db;
1609
1800
  }
1610
1801
  }
1611
1802
  _tables = new WeakMap();
1803
+ _schemaTables$1 = new WeakMap();
1612
1804
 
1613
1805
  var __accessCheck$1 = (obj, member, msg) => {
1614
1806
  if (!member.has(obj))
1615
1807
  throw TypeError("Cannot " + msg);
1616
1808
  };
1809
+ var __privateGet$1 = (obj, member, getter) => {
1810
+ __accessCheck$1(obj, member, "read from private field");
1811
+ return getter ? getter.call(obj) : member.get(obj);
1812
+ };
1617
1813
  var __privateAdd$1 = (obj, member, value) => {
1618
1814
  if (member.has(obj))
1619
1815
  throw TypeError("Cannot add the same private member more than once");
1620
1816
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1621
1817
  };
1818
+ var __privateSet$1 = (obj, member, value, setter) => {
1819
+ __accessCheck$1(obj, member, "write to private field");
1820
+ setter ? setter.call(obj, value) : member.set(obj, value);
1821
+ return value;
1822
+ };
1622
1823
  var __privateMethod$1 = (obj, member, method) => {
1623
1824
  __accessCheck$1(obj, member, "access private method");
1624
1825
  return method;
1625
1826
  };
1626
- var _search, search_fn;
1827
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1627
1828
  class SearchPlugin extends XataPlugin {
1628
- constructor(db, links) {
1829
+ constructor(db, schemaTables) {
1629
1830
  super();
1630
1831
  this.db = db;
1631
- this.links = links;
1632
1832
  __privateAdd$1(this, _search);
1833
+ __privateAdd$1(this, _getSchemaTables);
1834
+ __privateAdd$1(this, _schemaTables, void 0);
1835
+ __privateSet$1(this, _schemaTables, schemaTables);
1633
1836
  }
1634
1837
  build({ getFetchProps }) {
1635
1838
  return {
1636
1839
  all: async (query, options = {}) => {
1637
1840
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1841
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1638
1842
  return records.map((record) => {
1639
1843
  const { table = "orphan" } = record.xata;
1640
- return { table, record: initObject(this.db, this.links, table, record) };
1844
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1641
1845
  });
1642
1846
  },
1643
1847
  byTable: async (query, options = {}) => {
1644
1848
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1849
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1645
1850
  return records.reduce((acc, record) => {
1646
1851
  const { table = "orphan" } = record.xata;
1647
1852
  const items = acc[table] ?? [];
1648
- const item = initObject(this.db, this.links, table, record);
1853
+ const item = initObject(this.db, schemaTables, table, record);
1649
1854
  return { ...acc, [table]: [...items, item] };
1650
1855
  }, {});
1651
1856
  }
1652
1857
  };
1653
1858
  }
1654
1859
  }
1860
+ _schemaTables = new WeakMap();
1655
1861
  _search = new WeakSet();
1656
1862
  search_fn = async function(query, options, getFetchProps) {
1657
1863
  const fetchProps = await getFetchProps();
1658
- const { tables, fuzziness } = options ?? {};
1864
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1659
1865
  const { records } = await searchBranch({
1660
1866
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1661
- body: { tables, query, fuzziness },
1867
+ body: { tables, query, fuzziness, prefix, highlight },
1662
1868
  ...fetchProps
1663
1869
  });
1664
1870
  return records;
1665
1871
  };
1872
+ _getSchemaTables = new WeakSet();
1873
+ getSchemaTables_fn = async function(getFetchProps) {
1874
+ if (__privateGet$1(this, _schemaTables))
1875
+ return __privateGet$1(this, _schemaTables);
1876
+ const fetchProps = await getFetchProps();
1877
+ const { schema } = await getBranchDetails({
1878
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1879
+ ...fetchProps
1880
+ });
1881
+ __privateSet$1(this, _schemaTables, schema.tables);
1882
+ return schema.tables;
1883
+ };
1666
1884
 
1667
1885
  const isBranchStrategyBuilder = (strategy) => {
1668
1886
  return typeof strategy === "function";
1669
1887
  };
1670
1888
 
1671
- const envBranchNames = [
1672
- "XATA_BRANCH",
1673
- "VERCEL_GIT_COMMIT_REF",
1674
- "CF_PAGES_BRANCH",
1675
- "BRANCH"
1676
- ];
1677
- const defaultBranch = "main";
1678
1889
  async function getCurrentBranchName(options) {
1679
- const env = await getBranchByEnvVariable();
1680
- if (env)
1681
- return env;
1682
- const branch = await getGitBranch();
1683
- if (!branch)
1684
- return defaultBranch;
1685
- const details = await getDatabaseBranch(branch, options);
1686
- if (details)
1687
- return branch;
1688
- return defaultBranch;
1890
+ const { branch, envBranch } = getEnvironment();
1891
+ if (branch) {
1892
+ const details = await getDatabaseBranch(branch, options);
1893
+ if (details)
1894
+ return branch;
1895
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1896
+ }
1897
+ const gitBranch = envBranch || await getGitBranch();
1898
+ return resolveXataBranch(gitBranch, options);
1689
1899
  }
1690
1900
  async function getCurrentBranchDetails(options) {
1691
- const env = await getBranchByEnvVariable();
1692
- if (env)
1693
- return getDatabaseBranch(env, options);
1694
- const branch = await getGitBranch();
1695
- if (!branch)
1696
- return getDatabaseBranch(defaultBranch, options);
1697
- const details = await getDatabaseBranch(branch, options);
1698
- if (details)
1699
- return details;
1700
- return getDatabaseBranch(defaultBranch, options);
1901
+ const branch = await getCurrentBranchName(options);
1902
+ return getDatabaseBranch(branch, options);
1903
+ }
1904
+ async function resolveXataBranch(gitBranch, options) {
1905
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1906
+ const apiKey = options?.apiKey || getAPIKey();
1907
+ if (!databaseURL)
1908
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1909
+ if (!apiKey)
1910
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1911
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1912
+ const [workspace] = host.split(".");
1913
+ const { fallbackBranch } = getEnvironment();
1914
+ const { branch } = await resolveBranch({
1915
+ apiKey,
1916
+ apiUrl: databaseURL,
1917
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1918
+ workspacesApiUrl: `${protocol}//${host}`,
1919
+ pathParams: { dbName, workspace },
1920
+ queryParams: { gitBranch, fallbackBranch }
1921
+ });
1922
+ return branch;
1701
1923
  }
1702
1924
  async function getDatabaseBranch(branch, options) {
1703
1925
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1715,10 +1937,7 @@ async function getDatabaseBranch(branch, options) {
1715
1937
  apiUrl: databaseURL,
1716
1938
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1717
1939
  workspacesApiUrl: `${protocol}//${host}`,
1718
- pathParams: {
1719
- dbBranchName,
1720
- workspace
1721
- }
1940
+ pathParams: { dbBranchName, workspace }
1722
1941
  });
1723
1942
  } catch (err) {
1724
1943
  if (isObject(err) && err.status === 404)
@@ -1726,21 +1945,10 @@ async function getDatabaseBranch(branch, options) {
1726
1945
  throw err;
1727
1946
  }
1728
1947
  }
1729
- function getBranchByEnvVariable() {
1730
- for (const name of envBranchNames) {
1731
- const value = getEnvVariable(name);
1732
- if (value) {
1733
- return value;
1734
- }
1735
- }
1736
- try {
1737
- return XATA_BRANCH;
1738
- } catch (err) {
1739
- }
1740
- }
1741
1948
  function getDatabaseURL() {
1742
1949
  try {
1743
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1950
+ const { databaseURL } = getEnvironment();
1951
+ return databaseURL;
1744
1952
  } catch (err) {
1745
1953
  return void 0;
1746
1954
  }
@@ -1771,7 +1979,7 @@ var __privateMethod = (obj, member, method) => {
1771
1979
  const buildClient = (plugins) => {
1772
1980
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1773
1981
  return _a = class {
1774
- constructor(options = {}, links, tables) {
1982
+ constructor(options = {}, schemaTables) {
1775
1983
  __privateAdd(this, _parseOptions);
1776
1984
  __privateAdd(this, _getFetchProps);
1777
1985
  __privateAdd(this, _evaluateBranch);
@@ -1781,12 +1989,12 @@ const buildClient = (plugins) => {
1781
1989
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1782
1990
  cache: safeOptions.cache
1783
1991
  };
1784
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1785
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
1992
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
1993
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1786
1994
  this.db = db;
1787
1995
  this.search = search;
1788
1996
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1789
- if (!namespace)
1997
+ if (namespace === void 0)
1790
1998
  continue;
1791
1999
  const result = namespace.build(pluginOptions);
1792
2000
  if (result instanceof Promise) {
@@ -1802,8 +2010,8 @@ const buildClient = (plugins) => {
1802
2010
  const fetch = getFetchImplementation(options?.fetch);
1803
2011
  const databaseURL = options?.databaseURL || getDatabaseURL();
1804
2012
  const apiKey = options?.apiKey || getAPIKey();
1805
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1806
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2013
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2014
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1807
2015
  if (!databaseURL || !apiKey) {
1808
2016
  throw new Error("Options databaseURL and apiKey are required");
1809
2017
  }
@@ -1830,7 +2038,7 @@ const buildClient = (plugins) => {
1830
2038
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1831
2039
  if (__privateGet(this, _branch))
1832
2040
  return __privateGet(this, _branch);
1833
- if (!param)
2041
+ if (param === void 0)
1834
2042
  return void 0;
1835
2043
  const strategies = Array.isArray(param) ? [...param] : [param];
1836
2044
  const evaluateBranch = async (strategy) => {
@@ -1863,6 +2071,7 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1863
2071
  exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1864
2072
  exports.Page = Page;
1865
2073
  exports.Query = Query;
2074
+ exports.RecordArray = RecordArray;
1866
2075
  exports.Repository = Repository;
1867
2076
  exports.RestRepository = RestRepository;
1868
2077
  exports.SchemaPlugin = SchemaPlugin;
@@ -1927,6 +2136,7 @@ exports.insertRecord = insertRecord;
1927
2136
  exports.insertRecordWithID = insertRecordWithID;
1928
2137
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
1929
2138
  exports.is = is;
2139
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
1930
2140
  exports.isIdentifiable = isIdentifiable;
1931
2141
  exports.isNot = isNot;
1932
2142
  exports.isXataRecord = isXataRecord;
@@ -1942,6 +2152,7 @@ exports.removeWorkspaceMember = removeWorkspaceMember;
1942
2152
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
1943
2153
  exports.resolveBranch = resolveBranch;
1944
2154
  exports.searchBranch = searchBranch;
2155
+ exports.searchTable = searchTable;
1945
2156
  exports.setTableSchema = setTableSchema;
1946
2157
  exports.startsWith = startsWith;
1947
2158
  exports.updateBranchMetadata = updateBranchMetadata;
@@ -1950,6 +2161,7 @@ exports.updateRecordWithID = updateRecordWithID;
1950
2161
  exports.updateTable = updateTable;
1951
2162
  exports.updateUser = updateUser;
1952
2163
  exports.updateWorkspace = updateWorkspace;
2164
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
1953
2165
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
1954
2166
  exports.upsertRecordWithID = upsertRecordWithID;
1955
2167
  //# sourceMappingURL=index.cjs.map