@xata.io/client 0.0.0-alpha.vf38f30b → 0.0.0-alpha.vf4789c2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -7,36 +7,98 @@ function compact(arr) {
7
7
  function isObject(value) {
8
8
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
9
  }
10
+ function isDefined(value) {
11
+ return value !== null && value !== void 0;
12
+ }
10
13
  function isString(value) {
11
- return value !== void 0 && value !== null && typeof value === "string";
14
+ return isDefined(value) && typeof value === "string";
15
+ }
16
+ function toBase64(value) {
17
+ try {
18
+ return btoa(value);
19
+ } catch (err) {
20
+ const buf = Buffer;
21
+ return buf.from(value).toString("base64");
22
+ }
12
23
  }
13
24
 
14
- function getEnvVariable(name) {
25
+ function getEnvironment() {
15
26
  try {
16
- if (isObject(process) && isString(process?.env?.[name])) {
17
- return process.env[name];
27
+ if (isObject(process) && isObject(process.env)) {
28
+ return {
29
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
30
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
31
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
32
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
33
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
34
+ };
18
35
  }
19
36
  } catch (err) {
20
37
  }
21
38
  try {
22
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
23
- return Deno.env.get(name);
39
+ if (isObject(Deno) && isObject(Deno.env)) {
40
+ return {
41
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
42
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
43
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
44
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
45
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
46
+ };
24
47
  }
25
48
  } catch (err) {
26
49
  }
50
+ return {
51
+ apiKey: getGlobalApiKey(),
52
+ databaseURL: getGlobalDatabaseURL(),
53
+ branch: getGlobalBranch(),
54
+ envBranch: void 0,
55
+ fallbackBranch: getGlobalFallbackBranch()
56
+ };
57
+ }
58
+ function getGlobalApiKey() {
59
+ try {
60
+ return XATA_API_KEY;
61
+ } catch (err) {
62
+ return void 0;
63
+ }
64
+ }
65
+ function getGlobalDatabaseURL() {
66
+ try {
67
+ return XATA_DATABASE_URL;
68
+ } catch (err) {
69
+ return void 0;
70
+ }
71
+ }
72
+ function getGlobalBranch() {
73
+ try {
74
+ return XATA_BRANCH;
75
+ } catch (err) {
76
+ return void 0;
77
+ }
78
+ }
79
+ function getGlobalFallbackBranch() {
80
+ try {
81
+ return XATA_FALLBACK_BRANCH;
82
+ } catch (err) {
83
+ return void 0;
84
+ }
27
85
  }
28
86
  async function getGitBranch() {
87
+ const cmd = ["git", "branch", "--show-current"];
88
+ const fullCmd = cmd.join(" ");
89
+ const nodeModule = ["child", "process"].join("_");
90
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
29
91
  try {
30
- return require("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
92
+ if (typeof require === "function") {
93
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
94
+ }
95
+ const { execSync } = await import(nodeModule);
96
+ return execSync(fullCmd, execOptions).toString().trim();
31
97
  } catch (err) {
32
98
  }
33
99
  try {
34
100
  if (isObject(Deno)) {
35
- const process2 = Deno.run({
36
- cmd: ["git", "branch", "--show-current"],
37
- stdout: "piped",
38
- stderr: "piped"
39
- });
101
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
40
102
  return new TextDecoder().decode(await process2.output()).trim();
41
103
  }
42
104
  } catch (err) {
@@ -45,7 +107,8 @@ async function getGitBranch() {
45
107
 
46
108
  function getAPIKey() {
47
109
  try {
48
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
110
+ const { apiKey } = getEnvironment();
111
+ return apiKey;
49
112
  } catch (err) {
50
113
  return void 0;
51
114
  }
@@ -60,16 +123,28 @@ function getFetchImplementation(userFetch) {
60
123
  return fetchImpl;
61
124
  }
62
125
 
63
- class FetcherError extends Error {
64
- constructor(status, data) {
126
+ const VERSION = "0.0.0-alpha.vf4789c2";
127
+
128
+ class ErrorWithCause extends Error {
129
+ constructor(message, options) {
130
+ super(message, options);
131
+ }
132
+ }
133
+ class FetcherError extends ErrorWithCause {
134
+ constructor(status, data, requestId) {
65
135
  super(getMessage(data));
66
136
  this.status = status;
67
137
  this.errors = isBulkError(data) ? data.errors : void 0;
138
+ this.requestId = requestId;
68
139
  if (data instanceof Error) {
69
140
  this.stack = data.stack;
70
141
  this.cause = data.cause;
71
142
  }
72
143
  }
144
+ toString() {
145
+ const error = super.toString();
146
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
147
+ }
73
148
  }
74
149
  function isBulkError(error) {
75
150
  return isObject(error) && Array.isArray(error.errors);
@@ -92,7 +167,12 @@ function getMessage(data) {
92
167
  }
93
168
 
94
169
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
95
- const query = new URLSearchParams(queryParams).toString();
170
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
171
+ if (value === void 0 || value === null)
172
+ return acc;
173
+ return { ...acc, [key]: value };
174
+ }, {});
175
+ const query = new URLSearchParams(cleanQueryParams).toString();
96
176
  const queryString = query.length > 0 ? `?${query}` : "";
97
177
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
98
178
  };
@@ -132,6 +212,7 @@ async function fetch$1({
132
212
  body: body ? JSON.stringify(body) : void 0,
133
213
  headers: {
134
214
  "Content-Type": "application/json",
215
+ "User-Agent": `Xata client-ts/${VERSION}`,
135
216
  ...headers,
136
217
  ...hostHeader(fullUrl),
137
218
  Authorization: `Bearer ${apiKey}`
@@ -140,14 +221,15 @@ async function fetch$1({
140
221
  if (response.status === 204) {
141
222
  return {};
142
223
  }
224
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
143
225
  try {
144
226
  const jsonResponse = await response.json();
145
227
  if (response.ok) {
146
228
  return jsonResponse;
147
229
  }
148
- throw new FetcherError(response.status, jsonResponse);
230
+ throw new FetcherError(response.status, jsonResponse, requestId);
149
231
  } catch (error) {
150
- throw new FetcherError(response.status, error);
232
+ throw new FetcherError(response.status, error, requestId);
151
233
  }
152
234
  }
153
235
 
@@ -206,6 +288,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
206
288
  ...variables
207
289
  });
208
290
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
291
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
209
292
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
210
293
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
211
294
  method: "delete",
@@ -241,6 +324,14 @@ const deleteDatabase = (variables) => fetch$1({
241
324
  method: "delete",
242
325
  ...variables
243
326
  });
327
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
328
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
329
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
330
+ const resolveBranch = (variables) => fetch$1({
331
+ url: "/dbs/{dbName}/resolveBranch",
332
+ method: "get",
333
+ ...variables
334
+ });
244
335
  const getBranchDetails = (variables) => fetch$1({
245
336
  url: "/db/{dbBranchName}",
246
337
  method: "get",
@@ -348,6 +439,11 @@ const queryTable = (variables) => fetch$1({
348
439
  method: "post",
349
440
  ...variables
350
441
  });
442
+ const searchTable = (variables) => fetch$1({
443
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
444
+ method: "post",
445
+ ...variables
446
+ });
351
447
  const searchBranch = (variables) => fetch$1({
352
448
  url: "/db/{dbBranchName}/search",
353
449
  method: "post",
@@ -365,11 +461,20 @@ const operationsByTag = {
365
461
  updateWorkspaceMemberRole,
366
462
  removeWorkspaceMember,
367
463
  inviteWorkspaceMember,
464
+ updateWorkspaceMemberInvite,
368
465
  cancelWorkspaceMemberInvite,
369
466
  resendWorkspaceMemberInvite,
370
467
  acceptWorkspaceMemberInvite
371
468
  },
372
- database: { getDatabaseList, createDatabase, deleteDatabase },
469
+ database: {
470
+ getDatabaseList,
471
+ createDatabase,
472
+ deleteDatabase,
473
+ getGitBranchesMapping,
474
+ addGitBranchesEntry,
475
+ removeGitBranchesEntry,
476
+ resolveBranch
477
+ },
373
478
  branch: {
374
479
  getBranchList,
375
480
  getBranchDetails,
@@ -403,6 +508,7 @@ const operationsByTag = {
403
508
  getRecord,
404
509
  bulkInsertTableRecords,
405
510
  queryTable,
511
+ searchTable,
406
512
  searchBranch
407
513
  }
408
514
  };
@@ -432,35 +538,35 @@ function isValidBuilder(builder) {
432
538
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
433
539
  }
434
540
 
435
- var __accessCheck$6 = (obj, member, msg) => {
541
+ var __accessCheck$7 = (obj, member, msg) => {
436
542
  if (!member.has(obj))
437
543
  throw TypeError("Cannot " + msg);
438
544
  };
439
- var __privateGet$5 = (obj, member, getter) => {
440
- __accessCheck$6(obj, member, "read from private field");
545
+ var __privateGet$7 = (obj, member, getter) => {
546
+ __accessCheck$7(obj, member, "read from private field");
441
547
  return getter ? getter.call(obj) : member.get(obj);
442
548
  };
443
- var __privateAdd$6 = (obj, member, value) => {
549
+ var __privateAdd$7 = (obj, member, value) => {
444
550
  if (member.has(obj))
445
551
  throw TypeError("Cannot add the same private member more than once");
446
552
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
447
553
  };
448
- var __privateSet$4 = (obj, member, value, setter) => {
449
- __accessCheck$6(obj, member, "write to private field");
554
+ var __privateSet$7 = (obj, member, value, setter) => {
555
+ __accessCheck$7(obj, member, "write to private field");
450
556
  setter ? setter.call(obj, value) : member.set(obj, value);
451
557
  return value;
452
558
  };
453
559
  var _extraProps, _namespaces;
454
560
  class XataApiClient {
455
561
  constructor(options = {}) {
456
- __privateAdd$6(this, _extraProps, void 0);
457
- __privateAdd$6(this, _namespaces, {});
562
+ __privateAdd$7(this, _extraProps, void 0);
563
+ __privateAdd$7(this, _namespaces, {});
458
564
  const provider = options.host ?? "production";
459
565
  const apiKey = options?.apiKey ?? getAPIKey();
460
566
  if (!apiKey) {
461
567
  throw new Error("Could not resolve a valid apiKey");
462
568
  }
463
- __privateSet$4(this, _extraProps, {
569
+ __privateSet$7(this, _extraProps, {
464
570
  apiUrl: getHostUrl(provider, "main"),
465
571
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
466
572
  fetchImpl: getFetchImplementation(options.fetch),
@@ -468,34 +574,34 @@ class XataApiClient {
468
574
  });
469
575
  }
470
576
  get user() {
471
- if (!__privateGet$5(this, _namespaces).user)
472
- __privateGet$5(this, _namespaces).user = new UserApi(__privateGet$5(this, _extraProps));
473
- return __privateGet$5(this, _namespaces).user;
577
+ if (!__privateGet$7(this, _namespaces).user)
578
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
579
+ return __privateGet$7(this, _namespaces).user;
474
580
  }
475
581
  get workspaces() {
476
- if (!__privateGet$5(this, _namespaces).workspaces)
477
- __privateGet$5(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$5(this, _extraProps));
478
- return __privateGet$5(this, _namespaces).workspaces;
582
+ if (!__privateGet$7(this, _namespaces).workspaces)
583
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
584
+ return __privateGet$7(this, _namespaces).workspaces;
479
585
  }
480
586
  get databases() {
481
- if (!__privateGet$5(this, _namespaces).databases)
482
- __privateGet$5(this, _namespaces).databases = new DatabaseApi(__privateGet$5(this, _extraProps));
483
- return __privateGet$5(this, _namespaces).databases;
587
+ if (!__privateGet$7(this, _namespaces).databases)
588
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
589
+ return __privateGet$7(this, _namespaces).databases;
484
590
  }
485
591
  get branches() {
486
- if (!__privateGet$5(this, _namespaces).branches)
487
- __privateGet$5(this, _namespaces).branches = new BranchApi(__privateGet$5(this, _extraProps));
488
- return __privateGet$5(this, _namespaces).branches;
592
+ if (!__privateGet$7(this, _namespaces).branches)
593
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
594
+ return __privateGet$7(this, _namespaces).branches;
489
595
  }
490
596
  get tables() {
491
- if (!__privateGet$5(this, _namespaces).tables)
492
- __privateGet$5(this, _namespaces).tables = new TableApi(__privateGet$5(this, _extraProps));
493
- return __privateGet$5(this, _namespaces).tables;
597
+ if (!__privateGet$7(this, _namespaces).tables)
598
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
599
+ return __privateGet$7(this, _namespaces).tables;
494
600
  }
495
601
  get records() {
496
- if (!__privateGet$5(this, _namespaces).records)
497
- __privateGet$5(this, _namespaces).records = new RecordsApi(__privateGet$5(this, _extraProps));
498
- return __privateGet$5(this, _namespaces).records;
602
+ if (!__privateGet$7(this, _namespaces).records)
603
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
604
+ return __privateGet$7(this, _namespaces).records;
499
605
  }
500
606
  }
501
607
  _extraProps = new WeakMap();
@@ -587,6 +693,13 @@ class WorkspaceApi {
587
693
  ...this.extraProps
588
694
  });
589
695
  }
696
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
697
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
698
+ pathParams: { workspaceId, inviteId },
699
+ body: { role },
700
+ ...this.extraProps
701
+ });
702
+ }
590
703
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
591
704
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
592
705
  pathParams: { workspaceId, inviteId },
@@ -629,6 +742,33 @@ class DatabaseApi {
629
742
  ...this.extraProps
630
743
  });
631
744
  }
745
+ getGitBranchesMapping(workspace, dbName) {
746
+ return operationsByTag.database.getGitBranchesMapping({
747
+ pathParams: { workspace, dbName },
748
+ ...this.extraProps
749
+ });
750
+ }
751
+ addGitBranchesEntry(workspace, dbName, body) {
752
+ return operationsByTag.database.addGitBranchesEntry({
753
+ pathParams: { workspace, dbName },
754
+ body,
755
+ ...this.extraProps
756
+ });
757
+ }
758
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
759
+ return operationsByTag.database.removeGitBranchesEntry({
760
+ pathParams: { workspace, dbName },
761
+ queryParams: { gitBranch },
762
+ ...this.extraProps
763
+ });
764
+ }
765
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
766
+ return operationsByTag.database.resolveBranch({
767
+ pathParams: { workspace, dbName },
768
+ queryParams: { gitBranch, fallbackBranch },
769
+ ...this.extraProps
770
+ });
771
+ }
632
772
  }
633
773
  class BranchApi {
634
774
  constructor(extraProps) {
@@ -646,10 +786,10 @@ class BranchApi {
646
786
  ...this.extraProps
647
787
  });
648
788
  }
649
- createBranch(workspace, database, branch, from = "", options = {}) {
789
+ createBranch(workspace, database, branch, from, options = {}) {
650
790
  return operationsByTag.branch.createBranch({
651
791
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
652
- queryParams: { from },
792
+ queryParams: isString(from) ? { from } : void 0,
653
793
  body: options,
654
794
  ...this.extraProps
655
795
  });
@@ -831,6 +971,13 @@ class RecordsApi {
831
971
  ...this.extraProps
832
972
  });
833
973
  }
974
+ searchTable(workspace, database, branch, tableName, query) {
975
+ return operationsByTag.records.searchTable({
976
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
977
+ body: query,
978
+ ...this.extraProps
979
+ });
980
+ }
834
981
  searchBranch(workspace, database, branch, query) {
835
982
  return operationsByTag.records.searchBranch({
836
983
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -850,43 +997,43 @@ class XataApiPlugin {
850
997
  class XataPlugin {
851
998
  }
852
999
 
853
- var __accessCheck$5 = (obj, member, msg) => {
1000
+ var __accessCheck$6 = (obj, member, msg) => {
854
1001
  if (!member.has(obj))
855
1002
  throw TypeError("Cannot " + msg);
856
1003
  };
857
- var __privateGet$4 = (obj, member, getter) => {
858
- __accessCheck$5(obj, member, "read from private field");
1004
+ var __privateGet$6 = (obj, member, getter) => {
1005
+ __accessCheck$6(obj, member, "read from private field");
859
1006
  return getter ? getter.call(obj) : member.get(obj);
860
1007
  };
861
- var __privateAdd$5 = (obj, member, value) => {
1008
+ var __privateAdd$6 = (obj, member, value) => {
862
1009
  if (member.has(obj))
863
1010
  throw TypeError("Cannot add the same private member more than once");
864
1011
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
865
1012
  };
866
- var __privateSet$3 = (obj, member, value, setter) => {
867
- __accessCheck$5(obj, member, "write to private field");
1013
+ var __privateSet$6 = (obj, member, value, setter) => {
1014
+ __accessCheck$6(obj, member, "write to private field");
868
1015
  setter ? setter.call(obj, value) : member.set(obj, value);
869
1016
  return value;
870
1017
  };
871
- var _query;
1018
+ var _query, _page;
872
1019
  class Page {
873
1020
  constructor(query, meta, records = []) {
874
- __privateAdd$5(this, _query, void 0);
875
- __privateSet$3(this, _query, query);
1021
+ __privateAdd$6(this, _query, void 0);
1022
+ __privateSet$6(this, _query, query);
876
1023
  this.meta = meta;
877
- this.records = records;
1024
+ this.records = new RecordArray(this, records);
878
1025
  }
879
1026
  async nextPage(size, offset) {
880
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1027
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
881
1028
  }
882
1029
  async previousPage(size, offset) {
883
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1030
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
884
1031
  }
885
1032
  async firstPage(size, offset) {
886
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1033
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
887
1034
  }
888
1035
  async lastPage(size, offset) {
889
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1036
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
890
1037
  }
891
1038
  hasNextPage() {
892
1039
  return this.meta.page.more;
@@ -894,50 +1041,99 @@ class Page {
894
1041
  }
895
1042
  _query = new WeakMap();
896
1043
  const PAGINATION_MAX_SIZE = 200;
897
- const PAGINATION_DEFAULT_SIZE = 200;
1044
+ const PAGINATION_DEFAULT_SIZE = 20;
898
1045
  const PAGINATION_MAX_OFFSET = 800;
899
1046
  const PAGINATION_DEFAULT_OFFSET = 0;
1047
+ function isCursorPaginationOptions(options) {
1048
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1049
+ }
1050
+ const _RecordArray = class extends Array {
1051
+ constructor(...args) {
1052
+ super(..._RecordArray.parseConstructorParams(...args));
1053
+ __privateAdd$6(this, _page, void 0);
1054
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1055
+ }
1056
+ static parseConstructorParams(...args) {
1057
+ if (args.length === 1 && typeof args[0] === "number") {
1058
+ return new Array(args[0]);
1059
+ }
1060
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1061
+ const result = args[1] ?? args[0].records ?? [];
1062
+ return new Array(...result);
1063
+ }
1064
+ return new Array(...args);
1065
+ }
1066
+ toArray() {
1067
+ return new Array(...this);
1068
+ }
1069
+ map(callbackfn, thisArg) {
1070
+ return this.toArray().map(callbackfn, thisArg);
1071
+ }
1072
+ async nextPage(size, offset) {
1073
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1074
+ return new _RecordArray(newPage);
1075
+ }
1076
+ async previousPage(size, offset) {
1077
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1078
+ return new _RecordArray(newPage);
1079
+ }
1080
+ async firstPage(size, offset) {
1081
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1082
+ return new _RecordArray(newPage);
1083
+ }
1084
+ async lastPage(size, offset) {
1085
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1086
+ return new _RecordArray(newPage);
1087
+ }
1088
+ hasNextPage() {
1089
+ return __privateGet$6(this, _page).meta.page.more;
1090
+ }
1091
+ };
1092
+ let RecordArray = _RecordArray;
1093
+ _page = new WeakMap();
900
1094
 
901
- var __accessCheck$4 = (obj, member, msg) => {
1095
+ var __accessCheck$5 = (obj, member, msg) => {
902
1096
  if (!member.has(obj))
903
1097
  throw TypeError("Cannot " + msg);
904
1098
  };
905
- var __privateGet$3 = (obj, member, getter) => {
906
- __accessCheck$4(obj, member, "read from private field");
1099
+ var __privateGet$5 = (obj, member, getter) => {
1100
+ __accessCheck$5(obj, member, "read from private field");
907
1101
  return getter ? getter.call(obj) : member.get(obj);
908
1102
  };
909
- var __privateAdd$4 = (obj, member, value) => {
1103
+ var __privateAdd$5 = (obj, member, value) => {
910
1104
  if (member.has(obj))
911
1105
  throw TypeError("Cannot add the same private member more than once");
912
1106
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
913
1107
  };
914
- var __privateSet$2 = (obj, member, value, setter) => {
915
- __accessCheck$4(obj, member, "write to private field");
1108
+ var __privateSet$5 = (obj, member, value, setter) => {
1109
+ __accessCheck$5(obj, member, "write to private field");
916
1110
  setter ? setter.call(obj, value) : member.set(obj, value);
917
1111
  return value;
918
1112
  };
919
1113
  var _table$1, _repository, _data;
920
1114
  const _Query = class {
921
- constructor(repository, table, data, parent) {
922
- __privateAdd$4(this, _table$1, void 0);
923
- __privateAdd$4(this, _repository, void 0);
924
- __privateAdd$4(this, _data, { filter: {} });
1115
+ constructor(repository, table, data, rawParent) {
1116
+ __privateAdd$5(this, _table$1, void 0);
1117
+ __privateAdd$5(this, _repository, void 0);
1118
+ __privateAdd$5(this, _data, { filter: {} });
925
1119
  this.meta = { page: { cursor: "start", more: true } };
926
- this.records = [];
927
- __privateSet$2(this, _table$1, table);
1120
+ this.records = new RecordArray(this, []);
1121
+ __privateSet$5(this, _table$1, table);
928
1122
  if (repository) {
929
- __privateSet$2(this, _repository, repository);
1123
+ __privateSet$5(this, _repository, repository);
930
1124
  } else {
931
- __privateSet$2(this, _repository, this);
1125
+ __privateSet$5(this, _repository, this);
932
1126
  }
933
- __privateGet$3(this, _data).filter = data.filter ?? parent?.filter ?? {};
934
- __privateGet$3(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
935
- __privateGet$3(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
936
- __privateGet$3(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
937
- __privateGet$3(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
938
- __privateGet$3(this, _data).sort = data.sort ?? parent?.sort;
939
- __privateGet$3(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
940
- __privateGet$3(this, _data).page = data.page ?? parent?.page;
1127
+ const parent = cleanParent(data, rawParent);
1128
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1129
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1130
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1131
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1132
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1133
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1134
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1135
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1136
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
941
1137
  this.any = this.any.bind(this);
942
1138
  this.all = this.all.bind(this);
943
1139
  this.not = this.not.bind(this);
@@ -948,75 +1144,88 @@ const _Query = class {
948
1144
  Object.defineProperty(this, "repository", { enumerable: false });
949
1145
  }
950
1146
  getQueryOptions() {
951
- return __privateGet$3(this, _data);
1147
+ return __privateGet$5(this, _data);
1148
+ }
1149
+ key() {
1150
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1151
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1152
+ return toBase64(key);
952
1153
  }
953
1154
  any(...queries) {
954
1155
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
955
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $any } }, __privateGet$3(this, _data));
1156
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
956
1157
  }
957
1158
  all(...queries) {
958
1159
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
959
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1160
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
960
1161
  }
961
1162
  not(...queries) {
962
1163
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
963
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $not } }, __privateGet$3(this, _data));
1164
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
964
1165
  }
965
1166
  none(...queries) {
966
1167
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
967
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $none } }, __privateGet$3(this, _data));
1168
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
968
1169
  }
969
1170
  filter(a, b) {
970
1171
  if (arguments.length === 1) {
971
1172
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
972
- const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat(constraints));
973
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1173
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1174
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
974
1175
  } else {
975
- const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
976
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1176
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1177
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
977
1178
  }
978
1179
  }
979
1180
  sort(column, direction) {
980
- const originalSort = [__privateGet$3(this, _data).sort ?? []].flat();
1181
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
981
1182
  const sort = [...originalSort, { column, direction }];
982
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { sort }, __privateGet$3(this, _data));
1183
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
983
1184
  }
984
1185
  select(columns) {
985
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { columns }, __privateGet$3(this, _data));
1186
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
986
1187
  }
987
1188
  getPaginated(options = {}) {
988
- const query = new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), options, __privateGet$3(this, _data));
989
- return __privateGet$3(this, _repository).query(query);
1189
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1190
+ return __privateGet$5(this, _repository).query(query);
990
1191
  }
991
1192
  async *[Symbol.asyncIterator]() {
992
- for await (const [record] of this.getIterator(1)) {
1193
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
993
1194
  yield record;
994
1195
  }
995
1196
  }
996
- async *getIterator(chunk, options = {}) {
997
- let offset = 0;
998
- let end = false;
999
- while (!end) {
1000
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1001
- yield records;
1002
- offset += chunk;
1003
- end = !meta.page.more;
1197
+ async *getIterator(options = {}) {
1198
+ const { batchSize = 1 } = options;
1199
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1200
+ let more = page.hasNextPage();
1201
+ yield page.records;
1202
+ while (more) {
1203
+ page = await page.nextPage();
1204
+ more = page.hasNextPage();
1205
+ yield page.records;
1004
1206
  }
1005
1207
  }
1006
1208
  async getMany(options = {}) {
1007
- const { records } = await this.getPaginated(options);
1008
- return records;
1209
+ const page = await this.getPaginated(options);
1210
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1211
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1212
+ }
1213
+ return page.records;
1009
1214
  }
1010
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1215
+ async getAll(options = {}) {
1216
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1011
1217
  const results = [];
1012
- for await (const page of this.getIterator(chunk, options)) {
1218
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1013
1219
  results.push(...page);
1014
1220
  }
1015
1221
  return results;
1016
1222
  }
1017
- async getOne(options = {}) {
1018
- const records = await this.getMany({ ...options, page: { size: 1 } });
1019
- return records[0] || null;
1223
+ async getFirst(options = {}) {
1224
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1225
+ return records[0] ?? null;
1226
+ }
1227
+ cache(ttl) {
1228
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1020
1229
  }
1021
1230
  nextPage(size, offset) {
1022
1231
  return this.firstPage(size, offset);
@@ -1025,10 +1234,10 @@ const _Query = class {
1025
1234
  return this.firstPage(size, offset);
1026
1235
  }
1027
1236
  firstPage(size, offset) {
1028
- return this.getPaginated({ page: { size, offset } });
1237
+ return this.getPaginated({ pagination: { size, offset } });
1029
1238
  }
1030
1239
  lastPage(size, offset) {
1031
- return this.getPaginated({ page: { size, offset, before: "end" } });
1240
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1032
1241
  }
1033
1242
  hasNextPage() {
1034
1243
  return this.meta.page.more;
@@ -1038,12 +1247,20 @@ let Query = _Query;
1038
1247
  _table$1 = new WeakMap();
1039
1248
  _repository = new WeakMap();
1040
1249
  _data = new WeakMap();
1250
+ function cleanParent(data, parent) {
1251
+ if (isCursorPaginationOptions(data.pagination)) {
1252
+ return { ...parent, sorting: void 0, filter: void 0 };
1253
+ }
1254
+ return parent;
1255
+ }
1041
1256
 
1042
1257
  function isIdentifiable(x) {
1043
1258
  return isObject(x) && isString(x?.id);
1044
1259
  }
1045
1260
  function isXataRecord(x) {
1046
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1261
+ const record = x;
1262
+ const metadata = record?.getMetadata();
1263
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1047
1264
  }
1048
1265
 
1049
1266
  function isSortFilterString(value) {
@@ -1069,169 +1286,232 @@ function buildSortFilter(filter) {
1069
1286
  }
1070
1287
  }
1071
1288
 
1072
- var __accessCheck$3 = (obj, member, msg) => {
1289
+ var __accessCheck$4 = (obj, member, msg) => {
1073
1290
  if (!member.has(obj))
1074
1291
  throw TypeError("Cannot " + msg);
1075
1292
  };
1076
- var __privateGet$2 = (obj, member, getter) => {
1077
- __accessCheck$3(obj, member, "read from private field");
1293
+ var __privateGet$4 = (obj, member, getter) => {
1294
+ __accessCheck$4(obj, member, "read from private field");
1078
1295
  return getter ? getter.call(obj) : member.get(obj);
1079
1296
  };
1080
- var __privateAdd$3 = (obj, member, value) => {
1297
+ var __privateAdd$4 = (obj, member, value) => {
1081
1298
  if (member.has(obj))
1082
1299
  throw TypeError("Cannot add the same private member more than once");
1083
1300
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1084
1301
  };
1085
- var __privateSet$1 = (obj, member, value, setter) => {
1086
- __accessCheck$3(obj, member, "write to private field");
1302
+ var __privateSet$4 = (obj, member, value, setter) => {
1303
+ __accessCheck$4(obj, member, "write to private field");
1087
1304
  setter ? setter.call(obj, value) : member.set(obj, value);
1088
1305
  return value;
1089
1306
  };
1090
1307
  var __privateMethod$2 = (obj, member, method) => {
1091
- __accessCheck$3(obj, member, "access private method");
1308
+ __accessCheck$4(obj, member, "access private method");
1092
1309
  return method;
1093
1310
  };
1094
- var _table, _links, _getFetchProps, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn;
1311
+ var _table, _getFetchProps, _cache, _schemaTables$2, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
1095
1312
  class Repository extends Query {
1096
1313
  }
1097
1314
  class RestRepository extends Query {
1098
1315
  constructor(options) {
1099
1316
  super(null, options.table, {});
1100
- __privateAdd$3(this, _insertRecordWithoutId);
1101
- __privateAdd$3(this, _insertRecordWithId);
1102
- __privateAdd$3(this, _bulkInsertTableRecords);
1103
- __privateAdd$3(this, _updateRecordWithID);
1104
- __privateAdd$3(this, _upsertRecordWithID);
1105
- __privateAdd$3(this, _deleteRecord);
1106
- __privateAdd$3(this, _table, void 0);
1107
- __privateAdd$3(this, _links, void 0);
1108
- __privateAdd$3(this, _getFetchProps, void 0);
1109
- __privateSet$1(this, _table, options.table);
1110
- __privateSet$1(this, _links, options.links ?? {});
1111
- __privateSet$1(this, _getFetchProps, options.getFetchProps);
1317
+ __privateAdd$4(this, _insertRecordWithoutId);
1318
+ __privateAdd$4(this, _insertRecordWithId);
1319
+ __privateAdd$4(this, _bulkInsertTableRecords);
1320
+ __privateAdd$4(this, _updateRecordWithID);
1321
+ __privateAdd$4(this, _upsertRecordWithID);
1322
+ __privateAdd$4(this, _deleteRecord);
1323
+ __privateAdd$4(this, _invalidateCache);
1324
+ __privateAdd$4(this, _setCacheRecord);
1325
+ __privateAdd$4(this, _getCacheRecord);
1326
+ __privateAdd$4(this, _setCacheQuery);
1327
+ __privateAdd$4(this, _getCacheQuery);
1328
+ __privateAdd$4(this, _getSchemaTables$1);
1329
+ __privateAdd$4(this, _table, void 0);
1330
+ __privateAdd$4(this, _getFetchProps, void 0);
1331
+ __privateAdd$4(this, _cache, void 0);
1332
+ __privateAdd$4(this, _schemaTables$2, void 0);
1333
+ __privateSet$4(this, _table, options.table);
1334
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1112
1335
  this.db = options.db;
1336
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1337
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1113
1338
  }
1114
1339
  async create(a, b) {
1115
1340
  if (Array.isArray(a)) {
1116
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1341
+ if (a.length === 0)
1342
+ return [];
1343
+ const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1344
+ await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1345
+ return records;
1117
1346
  }
1118
1347
  if (isString(a) && isObject(b)) {
1119
1348
  if (a === "")
1120
1349
  throw new Error("The id can't be empty");
1121
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1350
+ const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1351
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1352
+ return record;
1122
1353
  }
1123
1354
  if (isObject(a) && isString(a.id)) {
1124
1355
  if (a.id === "")
1125
1356
  throw new Error("The id can't be empty");
1126
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1357
+ const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1358
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1359
+ return record;
1127
1360
  }
1128
1361
  if (isObject(a)) {
1129
- return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1362
+ const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1363
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1364
+ return record;
1130
1365
  }
1131
1366
  throw new Error("Invalid arguments for create method");
1132
1367
  }
1133
- async read(recordId) {
1134
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1135
- try {
1136
- const response = await getRecord({
1137
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1138
- ...fetchProps
1139
- });
1140
- return initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), response);
1141
- } catch (e) {
1142
- if (isObject(e) && e.status === 404) {
1143
- return null;
1368
+ async read(a) {
1369
+ if (Array.isArray(a)) {
1370
+ if (a.length === 0)
1371
+ return [];
1372
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1373
+ return this.getAll({ filter: { id: { $any: ids } } });
1374
+ }
1375
+ const id = isString(a) ? a : a.id;
1376
+ if (isString(id)) {
1377
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1378
+ if (cacheRecord)
1379
+ return cacheRecord;
1380
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1381
+ try {
1382
+ const response = await getRecord({
1383
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1384
+ ...fetchProps
1385
+ });
1386
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1387
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1388
+ } catch (e) {
1389
+ if (isObject(e) && e.status === 404) {
1390
+ return null;
1391
+ }
1392
+ throw e;
1144
1393
  }
1145
- throw e;
1146
1394
  }
1147
1395
  }
1148
1396
  async update(a, b) {
1149
1397
  if (Array.isArray(a)) {
1398
+ if (a.length === 0)
1399
+ return [];
1150
1400
  if (a.length > 100) {
1151
1401
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1152
1402
  }
1153
1403
  return Promise.all(a.map((object) => this.update(object)));
1154
1404
  }
1155
1405
  if (isString(a) && isObject(b)) {
1156
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1406
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1407
+ const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1408
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1409
+ return record;
1157
1410
  }
1158
1411
  if (isObject(a) && isString(a.id)) {
1159
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1412
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1413
+ const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1414
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1415
+ return record;
1160
1416
  }
1161
1417
  throw new Error("Invalid arguments for update method");
1162
1418
  }
1163
1419
  async createOrUpdate(a, b) {
1164
1420
  if (Array.isArray(a)) {
1421
+ if (a.length === 0)
1422
+ return [];
1165
1423
  if (a.length > 100) {
1166
1424
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1167
1425
  }
1168
1426
  return Promise.all(a.map((object) => this.createOrUpdate(object)));
1169
1427
  }
1170
1428
  if (isString(a) && isObject(b)) {
1171
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1429
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1430
+ const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1431
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1432
+ return record;
1172
1433
  }
1173
1434
  if (isObject(a) && isString(a.id)) {
1174
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1435
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1436
+ const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1437
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1438
+ return record;
1175
1439
  }
1176
1440
  throw new Error("Invalid arguments for createOrUpdate method");
1177
1441
  }
1178
- async delete(recordId) {
1179
- if (Array.isArray(recordId)) {
1180
- if (recordId.length > 100) {
1442
+ async delete(a) {
1443
+ if (Array.isArray(a)) {
1444
+ if (a.length === 0)
1445
+ return;
1446
+ if (a.length > 100) {
1181
1447
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1182
1448
  }
1183
- await Promise.all(recordId.map((id) => this.delete(id)));
1449
+ await Promise.all(a.map((id) => this.delete(id)));
1184
1450
  return;
1185
1451
  }
1186
- if (isString(recordId)) {
1187
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId);
1452
+ if (isString(a)) {
1453
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1454
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1188
1455
  return;
1189
1456
  }
1190
- if (isObject(recordId) && isString(recordId.id)) {
1191
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId.id);
1457
+ if (isObject(a) && isString(a.id)) {
1458
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1459
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1192
1460
  return;
1193
1461
  }
1194
1462
  throw new Error("Invalid arguments for delete method");
1195
1463
  }
1196
1464
  async search(query, options = {}) {
1197
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1198
- const { records } = await searchBranch({
1199
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1200
- body: { tables: [__privateGet$2(this, _table)], query, fuzziness: options.fuzziness },
1465
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1466
+ const { records } = await searchTable({
1467
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1468
+ body: {
1469
+ query,
1470
+ fuzziness: options.fuzziness,
1471
+ highlight: options.highlight,
1472
+ filter: options.filter
1473
+ },
1201
1474
  ...fetchProps
1202
1475
  });
1203
- return records.map((item) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), item));
1476
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1477
+ return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1204
1478
  }
1205
1479
  async query(query) {
1480
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1481
+ if (cacheQuery)
1482
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1206
1483
  const data = query.getQueryOptions();
1207
1484
  const body = {
1208
1485
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1209
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1210
- page: data.page,
1486
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1487
+ page: data.pagination,
1211
1488
  columns: data.columns
1212
1489
  };
1213
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1490
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1214
1491
  const { meta, records: objects } = await queryTable({
1215
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1492
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1216
1493
  body,
1217
1494
  ...fetchProps
1218
1495
  });
1219
- const records = objects.map((record) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), record));
1496
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1497
+ const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1498
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1220
1499
  return new Page(query, meta, records);
1221
1500
  }
1222
1501
  }
1223
1502
  _table = new WeakMap();
1224
- _links = new WeakMap();
1225
1503
  _getFetchProps = new WeakMap();
1504
+ _cache = new WeakMap();
1505
+ _schemaTables$2 = new WeakMap();
1226
1506
  _insertRecordWithoutId = new WeakSet();
1227
1507
  insertRecordWithoutId_fn = async function(object) {
1228
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1508
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1229
1509
  const record = transformObjectLinks(object);
1230
1510
  const response = await insertRecord({
1231
1511
  pathParams: {
1232
1512
  workspace: "{workspaceId}",
1233
1513
  dbBranchName: "{dbBranch}",
1234
- tableName: __privateGet$2(this, _table)
1514
+ tableName: __privateGet$4(this, _table)
1235
1515
  },
1236
1516
  body: record,
1237
1517
  ...fetchProps
@@ -1244,13 +1524,13 @@ insertRecordWithoutId_fn = async function(object) {
1244
1524
  };
1245
1525
  _insertRecordWithId = new WeakSet();
1246
1526
  insertRecordWithId_fn = async function(recordId, object) {
1247
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1527
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1248
1528
  const record = transformObjectLinks(object);
1249
1529
  const response = await insertRecordWithID({
1250
1530
  pathParams: {
1251
1531
  workspace: "{workspaceId}",
1252
1532
  dbBranchName: "{dbBranch}",
1253
- tableName: __privateGet$2(this, _table),
1533
+ tableName: __privateGet$4(this, _table),
1254
1534
  recordId
1255
1535
  },
1256
1536
  body: record,
@@ -1265,25 +1545,29 @@ insertRecordWithId_fn = async function(recordId, object) {
1265
1545
  };
1266
1546
  _bulkInsertTableRecords = new WeakSet();
1267
1547
  bulkInsertTableRecords_fn = async function(objects) {
1268
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1548
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1269
1549
  const records = objects.map((object) => transformObjectLinks(object));
1270
- const response = await bulkInsertTableRecords({
1271
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1550
+ const { recordIDs } = await bulkInsertTableRecords({
1551
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1272
1552
  body: { records },
1273
1553
  ...fetchProps
1274
1554
  });
1275
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1555
+ const finalObjects = await this.read(recordIDs);
1276
1556
  if (finalObjects.length !== objects.length) {
1277
1557
  throw new Error("The server failed to save some records");
1278
1558
  }
1279
- return finalObjects;
1559
+ const dictionary = finalObjects.reduce((acc, object) => {
1560
+ acc[object.id] = object;
1561
+ return acc;
1562
+ }, {});
1563
+ return recordIDs.map((id) => dictionary[id]);
1280
1564
  };
1281
1565
  _updateRecordWithID = new WeakSet();
1282
1566
  updateRecordWithID_fn = async function(recordId, object) {
1283
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1567
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1284
1568
  const record = transformObjectLinks(object);
1285
1569
  const response = await updateRecordWithID({
1286
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1570
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1287
1571
  body: record,
1288
1572
  ...fetchProps
1289
1573
  });
@@ -1294,9 +1578,9 @@ updateRecordWithID_fn = async function(recordId, object) {
1294
1578
  };
1295
1579
  _upsertRecordWithID = new WeakSet();
1296
1580
  upsertRecordWithID_fn = async function(recordId, object) {
1297
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1581
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1298
1582
  const response = await upsertRecordWithID({
1299
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1583
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1300
1584
  body: object,
1301
1585
  ...fetchProps
1302
1586
  });
@@ -1307,11 +1591,62 @@ upsertRecordWithID_fn = async function(recordId, object) {
1307
1591
  };
1308
1592
  _deleteRecord = new WeakSet();
1309
1593
  deleteRecord_fn = async function(recordId) {
1310
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1594
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1311
1595
  await deleteRecord({
1312
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1596
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1597
+ ...fetchProps
1598
+ });
1599
+ };
1600
+ _invalidateCache = new WeakSet();
1601
+ invalidateCache_fn = async function(recordId) {
1602
+ await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1603
+ const cacheItems = await __privateGet$4(this, _cache).getAll();
1604
+ const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1605
+ for (const [key, value] of queries) {
1606
+ const ids = getIds(value);
1607
+ if (ids.includes(recordId))
1608
+ await __privateGet$4(this, _cache).delete(key);
1609
+ }
1610
+ };
1611
+ _setCacheRecord = new WeakSet();
1612
+ setCacheRecord_fn = async function(record) {
1613
+ if (!__privateGet$4(this, _cache).cacheRecords)
1614
+ return;
1615
+ await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1616
+ };
1617
+ _getCacheRecord = new WeakSet();
1618
+ getCacheRecord_fn = async function(recordId) {
1619
+ if (!__privateGet$4(this, _cache).cacheRecords)
1620
+ return null;
1621
+ return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1622
+ };
1623
+ _setCacheQuery = new WeakSet();
1624
+ setCacheQuery_fn = async function(query, meta, records) {
1625
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1626
+ };
1627
+ _getCacheQuery = new WeakSet();
1628
+ getCacheQuery_fn = async function(query) {
1629
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1630
+ const result = await __privateGet$4(this, _cache).get(key);
1631
+ if (!result)
1632
+ return null;
1633
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1634
+ if (ttl < 0)
1635
+ return null;
1636
+ const hasExpired = result.date.getTime() + ttl < Date.now();
1637
+ return hasExpired ? null : result;
1638
+ };
1639
+ _getSchemaTables$1 = new WeakSet();
1640
+ getSchemaTables_fn$1 = async function() {
1641
+ if (__privateGet$4(this, _schemaTables$2))
1642
+ return __privateGet$4(this, _schemaTables$2);
1643
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1644
+ const { schema } = await getBranchDetails({
1645
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1313
1646
  ...fetchProps
1314
1647
  });
1648
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1649
+ return schema.tables;
1315
1650
  };
1316
1651
  const transformObjectLinks = (object) => {
1317
1652
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1320,15 +1655,34 @@ const transformObjectLinks = (object) => {
1320
1655
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1321
1656
  }, {});
1322
1657
  };
1323
- const initObject = (db, links, table, object) => {
1658
+ const initObject = (db, schemaTables, table, object) => {
1324
1659
  const result = {};
1325
- Object.assign(result, object);
1326
- const tableLinks = links[table] || [];
1327
- for (const link of tableLinks) {
1328
- const [field, linkTable] = link;
1329
- const value = result[field];
1330
- if (value && isObject(value)) {
1331
- result[field] = initObject(db, links, linkTable, value);
1660
+ const { xata, ...rest } = object ?? {};
1661
+ Object.assign(result, rest);
1662
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1663
+ if (!columns)
1664
+ console.error(`Table ${table} not found in schema`);
1665
+ for (const column of columns ?? []) {
1666
+ const value = result[column.name];
1667
+ switch (column.type) {
1668
+ case "datetime": {
1669
+ const date = value !== void 0 ? new Date(value) : void 0;
1670
+ if (date && isNaN(date.getTime())) {
1671
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1672
+ } else if (date) {
1673
+ result[column.name] = date;
1674
+ }
1675
+ break;
1676
+ }
1677
+ case "link": {
1678
+ const linkTable = column.link?.table;
1679
+ if (!linkTable) {
1680
+ console.error(`Failed to parse link for field ${column.name}`);
1681
+ } else if (isObject(value)) {
1682
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1683
+ }
1684
+ break;
1685
+ }
1332
1686
  }
1333
1687
  }
1334
1688
  result.read = function() {
@@ -1340,12 +1694,74 @@ const initObject = (db, links, table, object) => {
1340
1694
  result.delete = function() {
1341
1695
  return db[table].delete(result["id"]);
1342
1696
  };
1343
- for (const prop of ["read", "update", "delete"]) {
1697
+ result.getMetadata = function() {
1698
+ return xata;
1699
+ };
1700
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1344
1701
  Object.defineProperty(result, prop, { enumerable: false });
1345
1702
  }
1346
1703
  Object.freeze(result);
1347
1704
  return result;
1348
1705
  };
1706
+ function getIds(value) {
1707
+ if (Array.isArray(value)) {
1708
+ return value.map((item) => getIds(item)).flat();
1709
+ }
1710
+ if (!isObject(value))
1711
+ return [];
1712
+ const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1713
+ return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1714
+ }
1715
+
1716
+ var __accessCheck$3 = (obj, member, msg) => {
1717
+ if (!member.has(obj))
1718
+ throw TypeError("Cannot " + msg);
1719
+ };
1720
+ var __privateGet$3 = (obj, member, getter) => {
1721
+ __accessCheck$3(obj, member, "read from private field");
1722
+ return getter ? getter.call(obj) : member.get(obj);
1723
+ };
1724
+ var __privateAdd$3 = (obj, member, value) => {
1725
+ if (member.has(obj))
1726
+ throw TypeError("Cannot add the same private member more than once");
1727
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1728
+ };
1729
+ var __privateSet$3 = (obj, member, value, setter) => {
1730
+ __accessCheck$3(obj, member, "write to private field");
1731
+ setter ? setter.call(obj, value) : member.set(obj, value);
1732
+ return value;
1733
+ };
1734
+ var _map;
1735
+ class SimpleCache {
1736
+ constructor(options = {}) {
1737
+ __privateAdd$3(this, _map, void 0);
1738
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1739
+ this.capacity = options.max ?? 500;
1740
+ this.cacheRecords = options.cacheRecords ?? true;
1741
+ this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1742
+ }
1743
+ async getAll() {
1744
+ return Object.fromEntries(__privateGet$3(this, _map));
1745
+ }
1746
+ async get(key) {
1747
+ return __privateGet$3(this, _map).get(key) ?? null;
1748
+ }
1749
+ async set(key, value) {
1750
+ await this.delete(key);
1751
+ __privateGet$3(this, _map).set(key, value);
1752
+ if (__privateGet$3(this, _map).size > this.capacity) {
1753
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1754
+ await this.delete(leastRecentlyUsed);
1755
+ }
1756
+ }
1757
+ async delete(key) {
1758
+ __privateGet$3(this, _map).delete(key);
1759
+ }
1760
+ async clear() {
1761
+ return __privateGet$3(this, _map).clear();
1762
+ }
1763
+ }
1764
+ _map = new WeakMap();
1349
1765
 
1350
1766
  const gt = (value) => ({ $gt: value });
1351
1767
  const ge = (value) => ({ $ge: value });
@@ -1370,7 +1786,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1370
1786
  if (!member.has(obj))
1371
1787
  throw TypeError("Cannot " + msg);
1372
1788
  };
1373
- var __privateGet$1 = (obj, member, getter) => {
1789
+ var __privateGet$2 = (obj, member, getter) => {
1374
1790
  __accessCheck$2(obj, member, "read from private field");
1375
1791
  return getter ? getter.call(obj) : member.get(obj);
1376
1792
  };
@@ -1379,122 +1795,158 @@ var __privateAdd$2 = (obj, member, value) => {
1379
1795
  throw TypeError("Cannot add the same private member more than once");
1380
1796
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1381
1797
  };
1382
- var _tables;
1798
+ var __privateSet$2 = (obj, member, value, setter) => {
1799
+ __accessCheck$2(obj, member, "write to private field");
1800
+ setter ? setter.call(obj, value) : member.set(obj, value);
1801
+ return value;
1802
+ };
1803
+ var _tables, _schemaTables$1;
1383
1804
  class SchemaPlugin extends XataPlugin {
1384
- constructor(links, tableNames) {
1805
+ constructor(schemaTables) {
1385
1806
  super();
1386
- this.links = links;
1387
- this.tableNames = tableNames;
1388
1807
  __privateAdd$2(this, _tables, {});
1808
+ __privateAdd$2(this, _schemaTables$1, void 0);
1809
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1389
1810
  }
1390
- build(options) {
1391
- const { getFetchProps } = options;
1392
- const links = this.links;
1811
+ build(pluginOptions) {
1393
1812
  const db = new Proxy({}, {
1394
1813
  get: (_target, table) => {
1395
1814
  if (!isString(table))
1396
1815
  throw new Error("Invalid table name");
1397
- if (!__privateGet$1(this, _tables)[table])
1398
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, getFetchProps, table, links });
1399
- return __privateGet$1(this, _tables)[table];
1816
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1817
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1818
+ }
1819
+ return __privateGet$2(this, _tables)[table];
1400
1820
  }
1401
1821
  });
1402
- for (const table of this.tableNames ?? []) {
1403
- db[table] = new RestRepository({ db, getFetchProps, table, links });
1822
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1823
+ for (const table of tableNames) {
1824
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1404
1825
  }
1405
1826
  return db;
1406
1827
  }
1407
1828
  }
1408
1829
  _tables = new WeakMap();
1830
+ _schemaTables$1 = new WeakMap();
1409
1831
 
1410
1832
  var __accessCheck$1 = (obj, member, msg) => {
1411
1833
  if (!member.has(obj))
1412
1834
  throw TypeError("Cannot " + msg);
1413
1835
  };
1836
+ var __privateGet$1 = (obj, member, getter) => {
1837
+ __accessCheck$1(obj, member, "read from private field");
1838
+ return getter ? getter.call(obj) : member.get(obj);
1839
+ };
1414
1840
  var __privateAdd$1 = (obj, member, value) => {
1415
1841
  if (member.has(obj))
1416
1842
  throw TypeError("Cannot add the same private member more than once");
1417
1843
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1418
1844
  };
1845
+ var __privateSet$1 = (obj, member, value, setter) => {
1846
+ __accessCheck$1(obj, member, "write to private field");
1847
+ setter ? setter.call(obj, value) : member.set(obj, value);
1848
+ return value;
1849
+ };
1419
1850
  var __privateMethod$1 = (obj, member, method) => {
1420
1851
  __accessCheck$1(obj, member, "access private method");
1421
1852
  return method;
1422
1853
  };
1423
- var _search, search_fn;
1854
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1424
1855
  class SearchPlugin extends XataPlugin {
1425
- constructor(db, links) {
1856
+ constructor(db, schemaTables) {
1426
1857
  super();
1427
1858
  this.db = db;
1428
- this.links = links;
1429
1859
  __privateAdd$1(this, _search);
1860
+ __privateAdd$1(this, _getSchemaTables);
1861
+ __privateAdd$1(this, _schemaTables, void 0);
1862
+ __privateSet$1(this, _schemaTables, schemaTables);
1430
1863
  }
1431
1864
  build({ getFetchProps }) {
1432
1865
  return {
1433
1866
  all: async (query, options = {}) => {
1434
1867
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1868
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1435
1869
  return records.map((record) => {
1436
1870
  const { table = "orphan" } = record.xata;
1437
- return { table, record: initObject(this.db, this.links, table, record) };
1871
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1438
1872
  });
1439
1873
  },
1440
1874
  byTable: async (query, options = {}) => {
1441
1875
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1876
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1442
1877
  return records.reduce((acc, record) => {
1443
1878
  const { table = "orphan" } = record.xata;
1444
1879
  const items = acc[table] ?? [];
1445
- const item = initObject(this.db, this.links, table, record);
1880
+ const item = initObject(this.db, schemaTables, table, record);
1446
1881
  return { ...acc, [table]: [...items, item] };
1447
1882
  }, {});
1448
1883
  }
1449
1884
  };
1450
1885
  }
1451
1886
  }
1887
+ _schemaTables = new WeakMap();
1452
1888
  _search = new WeakSet();
1453
1889
  search_fn = async function(query, options, getFetchProps) {
1454
1890
  const fetchProps = await getFetchProps();
1455
- const { tables, fuzziness } = options ?? {};
1891
+ const { tables, fuzziness, highlight } = options ?? {};
1456
1892
  const { records } = await searchBranch({
1457
1893
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1458
- body: { tables, query, fuzziness },
1894
+ body: { tables, query, fuzziness, highlight },
1459
1895
  ...fetchProps
1460
1896
  });
1461
1897
  return records;
1462
1898
  };
1899
+ _getSchemaTables = new WeakSet();
1900
+ getSchemaTables_fn = async function(getFetchProps) {
1901
+ if (__privateGet$1(this, _schemaTables))
1902
+ return __privateGet$1(this, _schemaTables);
1903
+ const fetchProps = await getFetchProps();
1904
+ const { schema } = await getBranchDetails({
1905
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1906
+ ...fetchProps
1907
+ });
1908
+ __privateSet$1(this, _schemaTables, schema.tables);
1909
+ return schema.tables;
1910
+ };
1463
1911
 
1464
1912
  const isBranchStrategyBuilder = (strategy) => {
1465
1913
  return typeof strategy === "function";
1466
1914
  };
1467
1915
 
1468
- const envBranchNames = [
1469
- "XATA_BRANCH",
1470
- "VERCEL_GIT_COMMIT_REF",
1471
- "CF_PAGES_BRANCH",
1472
- "BRANCH"
1473
- ];
1474
- const defaultBranch = "main";
1475
1916
  async function getCurrentBranchName(options) {
1476
- const env = await getBranchByEnvVariable();
1477
- if (env)
1478
- return env;
1479
- const branch = await getGitBranch();
1480
- if (!branch)
1481
- return defaultBranch;
1482
- const details = await getDatabaseBranch(branch, options);
1483
- if (details)
1484
- return branch;
1485
- return defaultBranch;
1917
+ const { branch, envBranch } = getEnvironment();
1918
+ if (branch) {
1919
+ const details = await getDatabaseBranch(branch, options);
1920
+ if (details)
1921
+ return branch;
1922
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1923
+ }
1924
+ const gitBranch = envBranch || await getGitBranch();
1925
+ return resolveXataBranch(gitBranch, options);
1486
1926
  }
1487
1927
  async function getCurrentBranchDetails(options) {
1488
- const env = await getBranchByEnvVariable();
1489
- if (env)
1490
- return getDatabaseBranch(env, options);
1491
- const branch = await getGitBranch();
1492
- if (!branch)
1493
- return getDatabaseBranch(defaultBranch, options);
1494
- const details = await getDatabaseBranch(branch, options);
1495
- if (details)
1496
- return details;
1497
- return getDatabaseBranch(defaultBranch, options);
1928
+ const branch = await getCurrentBranchName(options);
1929
+ return getDatabaseBranch(branch, options);
1930
+ }
1931
+ async function resolveXataBranch(gitBranch, options) {
1932
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1933
+ const apiKey = options?.apiKey || getAPIKey();
1934
+ if (!databaseURL)
1935
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1936
+ if (!apiKey)
1937
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1938
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1939
+ const [workspace] = host.split(".");
1940
+ const { fallbackBranch } = getEnvironment();
1941
+ const { branch } = await resolveBranch({
1942
+ apiKey,
1943
+ apiUrl: databaseURL,
1944
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1945
+ workspacesApiUrl: `${protocol}//${host}`,
1946
+ pathParams: { dbName, workspace },
1947
+ queryParams: { gitBranch, fallbackBranch }
1948
+ });
1949
+ return branch;
1498
1950
  }
1499
1951
  async function getDatabaseBranch(branch, options) {
1500
1952
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1512,10 +1964,7 @@ async function getDatabaseBranch(branch, options) {
1512
1964
  apiUrl: databaseURL,
1513
1965
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1514
1966
  workspacesApiUrl: `${protocol}//${host}`,
1515
- pathParams: {
1516
- dbBranchName,
1517
- workspace
1518
- }
1967
+ pathParams: { dbBranchName, workspace }
1519
1968
  });
1520
1969
  } catch (err) {
1521
1970
  if (isObject(err) && err.status === 404)
@@ -1523,21 +1972,10 @@ async function getDatabaseBranch(branch, options) {
1523
1972
  throw err;
1524
1973
  }
1525
1974
  }
1526
- function getBranchByEnvVariable() {
1527
- for (const name of envBranchNames) {
1528
- const value = getEnvVariable(name);
1529
- if (value) {
1530
- return value;
1531
- }
1532
- }
1533
- try {
1534
- return XATA_BRANCH;
1535
- } catch (err) {
1536
- }
1537
- }
1538
1975
  function getDatabaseURL() {
1539
1976
  try {
1540
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1977
+ const { databaseURL } = getEnvironment();
1978
+ return databaseURL;
1541
1979
  } catch (err) {
1542
1980
  return void 0;
1543
1981
  }
@@ -1568,22 +2006,24 @@ var __privateMethod = (obj, member, method) => {
1568
2006
  const buildClient = (plugins) => {
1569
2007
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1570
2008
  return _a = class {
1571
- constructor(options = {}, links, tables) {
2009
+ constructor(options = {}, schemaTables) {
1572
2010
  __privateAdd(this, _parseOptions);
1573
2011
  __privateAdd(this, _getFetchProps);
1574
2012
  __privateAdd(this, _evaluateBranch);
1575
2013
  __privateAdd(this, _branch, void 0);
1576
2014
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
1577
- const db = new SchemaPlugin(links, tables).build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
1578
- const search = new SearchPlugin(db, links ?? {}).build({
1579
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions)
1580
- });
2015
+ const pluginOptions = {
2016
+ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
2017
+ cache: safeOptions.cache
2018
+ };
2019
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2020
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1581
2021
  this.db = db;
1582
2022
  this.search = search;
1583
2023
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1584
- if (!namespace)
2024
+ if (namespace === void 0)
1585
2025
  continue;
1586
- const result = namespace.build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
2026
+ const result = namespace.build(pluginOptions);
1587
2027
  if (result instanceof Promise) {
1588
2028
  void result.then((namespace2) => {
1589
2029
  this[key] = namespace2;
@@ -1597,11 +2037,12 @@ const buildClient = (plugins) => {
1597
2037
  const fetch = getFetchImplementation(options?.fetch);
1598
2038
  const databaseURL = options?.databaseURL || getDatabaseURL();
1599
2039
  const apiKey = options?.apiKey || getAPIKey();
1600
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2040
+ const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2041
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1601
2042
  if (!databaseURL || !apiKey) {
1602
2043
  throw new Error("Options databaseURL and apiKey are required");
1603
2044
  }
1604
- return { fetch, databaseURL, apiKey, branch };
2045
+ return { fetch, databaseURL, apiKey, branch, cache };
1605
2046
  }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1606
2047
  fetch,
1607
2048
  apiKey,
@@ -1624,7 +2065,7 @@ const buildClient = (plugins) => {
1624
2065
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1625
2066
  if (__privateGet(this, _branch))
1626
2067
  return __privateGet(this, _branch);
1627
- if (!param)
2068
+ if (param === void 0)
1628
2069
  return void 0;
1629
2070
  const strategies = Array.isArray(param) ? [...param] : [param];
1630
2071
  const evaluateBranch = async (strategy) => {
@@ -1649,5 +2090,5 @@ class XataError extends Error {
1649
2090
  }
1650
2091
  }
1651
2092
 
1652
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeWorkspaceMember, resendWorkspaceMemberInvite, searchBranch, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2093
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
1653
2094
  //# sourceMappingURL=index.mjs.map