@xata.io/client 0.0.0-alpha.vf2043e7 → 0.0.0-alpha.vf221157

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
@@ -10,6 +10,13 @@ function isObject(value) {
10
10
  function isString(value) {
11
11
  return value !== void 0 && value !== null && typeof value === "string";
12
12
  }
13
+ function toBase64(value) {
14
+ try {
15
+ return btoa(value);
16
+ } catch (err) {
17
+ return Buffer.from(value).toString("base64");
18
+ }
19
+ }
13
20
 
14
21
  function getEnvVariable(name) {
15
22
  try {
@@ -27,7 +34,10 @@ function getEnvVariable(name) {
27
34
  }
28
35
  async function getGitBranch() {
29
36
  try {
30
- return require("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
37
+ if (typeof require === "function") {
38
+ const req = require;
39
+ return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
40
+ }
31
41
  } catch (err) {
32
42
  }
33
43
  try {
@@ -241,6 +251,14 @@ const deleteDatabase = (variables) => fetch$1({
241
251
  method: "delete",
242
252
  ...variables
243
253
  });
254
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
255
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
256
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
257
+ const resolveBranch = (variables) => fetch$1({
258
+ url: "/dbs/{dbName}/resolveBranch",
259
+ method: "get",
260
+ ...variables
261
+ });
244
262
  const getBranchDetails = (variables) => fetch$1({
245
263
  url: "/db/{dbBranchName}",
246
264
  method: "get",
@@ -348,6 +366,11 @@ const queryTable = (variables) => fetch$1({
348
366
  method: "post",
349
367
  ...variables
350
368
  });
369
+ const searchTable = (variables) => fetch$1({
370
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
371
+ method: "post",
372
+ ...variables
373
+ });
351
374
  const searchBranch = (variables) => fetch$1({
352
375
  url: "/db/{dbBranchName}/search",
353
376
  method: "post",
@@ -369,7 +392,15 @@ const operationsByTag = {
369
392
  resendWorkspaceMemberInvite,
370
393
  acceptWorkspaceMemberInvite
371
394
  },
372
- database: { getDatabaseList, createDatabase, deleteDatabase },
395
+ database: {
396
+ getDatabaseList,
397
+ createDatabase,
398
+ deleteDatabase,
399
+ getGitBranchesMapping,
400
+ addGitBranchesEntry,
401
+ removeGitBranchesEntry,
402
+ resolveBranch
403
+ },
373
404
  branch: {
374
405
  getBranchList,
375
406
  getBranchDetails,
@@ -403,6 +434,7 @@ const operationsByTag = {
403
434
  getRecord,
404
435
  bulkInsertTableRecords,
405
436
  queryTable,
437
+ searchTable,
406
438
  searchBranch
407
439
  }
408
440
  };
@@ -432,35 +464,35 @@ function isValidBuilder(builder) {
432
464
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
433
465
  }
434
466
 
435
- var __accessCheck$6 = (obj, member, msg) => {
467
+ var __accessCheck$7 = (obj, member, msg) => {
436
468
  if (!member.has(obj))
437
469
  throw TypeError("Cannot " + msg);
438
470
  };
439
- var __privateGet$5 = (obj, member, getter) => {
440
- __accessCheck$6(obj, member, "read from private field");
471
+ var __privateGet$7 = (obj, member, getter) => {
472
+ __accessCheck$7(obj, member, "read from private field");
441
473
  return getter ? getter.call(obj) : member.get(obj);
442
474
  };
443
- var __privateAdd$6 = (obj, member, value) => {
475
+ var __privateAdd$7 = (obj, member, value) => {
444
476
  if (member.has(obj))
445
477
  throw TypeError("Cannot add the same private member more than once");
446
478
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
447
479
  };
448
- var __privateSet$4 = (obj, member, value, setter) => {
449
- __accessCheck$6(obj, member, "write to private field");
480
+ var __privateSet$6 = (obj, member, value, setter) => {
481
+ __accessCheck$7(obj, member, "write to private field");
450
482
  setter ? setter.call(obj, value) : member.set(obj, value);
451
483
  return value;
452
484
  };
453
485
  var _extraProps, _namespaces;
454
486
  class XataApiClient {
455
487
  constructor(options = {}) {
456
- __privateAdd$6(this, _extraProps, void 0);
457
- __privateAdd$6(this, _namespaces, {});
488
+ __privateAdd$7(this, _extraProps, void 0);
489
+ __privateAdd$7(this, _namespaces, {});
458
490
  const provider = options.host ?? "production";
459
491
  const apiKey = options?.apiKey ?? getAPIKey();
460
492
  if (!apiKey) {
461
493
  throw new Error("Could not resolve a valid apiKey");
462
494
  }
463
- __privateSet$4(this, _extraProps, {
495
+ __privateSet$6(this, _extraProps, {
464
496
  apiUrl: getHostUrl(provider, "main"),
465
497
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
466
498
  fetchImpl: getFetchImplementation(options.fetch),
@@ -468,34 +500,34 @@ class XataApiClient {
468
500
  });
469
501
  }
470
502
  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;
503
+ if (!__privateGet$7(this, _namespaces).user)
504
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
505
+ return __privateGet$7(this, _namespaces).user;
474
506
  }
475
507
  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;
508
+ if (!__privateGet$7(this, _namespaces).workspaces)
509
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
510
+ return __privateGet$7(this, _namespaces).workspaces;
479
511
  }
480
512
  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;
513
+ if (!__privateGet$7(this, _namespaces).databases)
514
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
515
+ return __privateGet$7(this, _namespaces).databases;
484
516
  }
485
517
  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;
518
+ if (!__privateGet$7(this, _namespaces).branches)
519
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
520
+ return __privateGet$7(this, _namespaces).branches;
489
521
  }
490
522
  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;
523
+ if (!__privateGet$7(this, _namespaces).tables)
524
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
525
+ return __privateGet$7(this, _namespaces).tables;
494
526
  }
495
527
  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;
528
+ if (!__privateGet$7(this, _namespaces).records)
529
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
530
+ return __privateGet$7(this, _namespaces).records;
499
531
  }
500
532
  }
501
533
  _extraProps = new WeakMap();
@@ -629,6 +661,33 @@ class DatabaseApi {
629
661
  ...this.extraProps
630
662
  });
631
663
  }
664
+ getGitBranchesMapping(workspace, dbName) {
665
+ return operationsByTag.database.getGitBranchesMapping({
666
+ pathParams: { workspace, dbName },
667
+ ...this.extraProps
668
+ });
669
+ }
670
+ addGitBranchesEntry(workspace, dbName, body) {
671
+ return operationsByTag.database.addGitBranchesEntry({
672
+ pathParams: { workspace, dbName },
673
+ body,
674
+ ...this.extraProps
675
+ });
676
+ }
677
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
678
+ return operationsByTag.database.removeGitBranchesEntry({
679
+ pathParams: { workspace, dbName },
680
+ queryParams: { gitBranch },
681
+ ...this.extraProps
682
+ });
683
+ }
684
+ resolveBranch(workspace, dbName, gitBranch) {
685
+ return operationsByTag.database.resolveBranch({
686
+ pathParams: { workspace, dbName },
687
+ queryParams: { gitBranch },
688
+ ...this.extraProps
689
+ });
690
+ }
632
691
  }
633
692
  class BranchApi {
634
693
  constructor(extraProps) {
@@ -646,10 +705,10 @@ class BranchApi {
646
705
  ...this.extraProps
647
706
  });
648
707
  }
649
- createBranch(workspace, database, branch, from = "", options = {}) {
708
+ createBranch(workspace, database, branch, from, options = {}) {
650
709
  return operationsByTag.branch.createBranch({
651
710
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
652
- queryParams: { from },
711
+ queryParams: isString(from) ? { from } : void 0,
653
712
  body: options,
654
713
  ...this.extraProps
655
714
  });
@@ -831,6 +890,13 @@ class RecordsApi {
831
890
  ...this.extraProps
832
891
  });
833
892
  }
893
+ searchTable(workspace, database, branch, tableName, query) {
894
+ return operationsByTag.records.searchTable({
895
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
896
+ body: query,
897
+ ...this.extraProps
898
+ });
899
+ }
834
900
  searchBranch(workspace, database, branch, query) {
835
901
  return operationsByTag.records.searchBranch({
836
902
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -850,43 +916,43 @@ class XataApiPlugin {
850
916
  class XataPlugin {
851
917
  }
852
918
 
853
- var __accessCheck$5 = (obj, member, msg) => {
919
+ var __accessCheck$6 = (obj, member, msg) => {
854
920
  if (!member.has(obj))
855
921
  throw TypeError("Cannot " + msg);
856
922
  };
857
- var __privateGet$4 = (obj, member, getter) => {
858
- __accessCheck$5(obj, member, "read from private field");
923
+ var __privateGet$6 = (obj, member, getter) => {
924
+ __accessCheck$6(obj, member, "read from private field");
859
925
  return getter ? getter.call(obj) : member.get(obj);
860
926
  };
861
- var __privateAdd$5 = (obj, member, value) => {
927
+ var __privateAdd$6 = (obj, member, value) => {
862
928
  if (member.has(obj))
863
929
  throw TypeError("Cannot add the same private member more than once");
864
930
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
865
931
  };
866
- var __privateSet$3 = (obj, member, value, setter) => {
867
- __accessCheck$5(obj, member, "write to private field");
932
+ var __privateSet$5 = (obj, member, value, setter) => {
933
+ __accessCheck$6(obj, member, "write to private field");
868
934
  setter ? setter.call(obj, value) : member.set(obj, value);
869
935
  return value;
870
936
  };
871
937
  var _query;
872
938
  class Page {
873
939
  constructor(query, meta, records = []) {
874
- __privateAdd$5(this, _query, void 0);
875
- __privateSet$3(this, _query, query);
940
+ __privateAdd$6(this, _query, void 0);
941
+ __privateSet$5(this, _query, query);
876
942
  this.meta = meta;
877
943
  this.records = records;
878
944
  }
879
945
  async nextPage(size, offset) {
880
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
946
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
881
947
  }
882
948
  async previousPage(size, offset) {
883
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
949
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
884
950
  }
885
951
  async firstPage(size, offset) {
886
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
952
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
887
953
  }
888
954
  async lastPage(size, offset) {
889
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
955
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
890
956
  }
891
957
  hasNextPage() {
892
958
  return this.meta.page.more;
@@ -898,46 +964,47 @@ const PAGINATION_DEFAULT_SIZE = 200;
898
964
  const PAGINATION_MAX_OFFSET = 800;
899
965
  const PAGINATION_DEFAULT_OFFSET = 0;
900
966
 
901
- var __accessCheck$4 = (obj, member, msg) => {
967
+ var __accessCheck$5 = (obj, member, msg) => {
902
968
  if (!member.has(obj))
903
969
  throw TypeError("Cannot " + msg);
904
970
  };
905
- var __privateGet$3 = (obj, member, getter) => {
906
- __accessCheck$4(obj, member, "read from private field");
971
+ var __privateGet$5 = (obj, member, getter) => {
972
+ __accessCheck$5(obj, member, "read from private field");
907
973
  return getter ? getter.call(obj) : member.get(obj);
908
974
  };
909
- var __privateAdd$4 = (obj, member, value) => {
975
+ var __privateAdd$5 = (obj, member, value) => {
910
976
  if (member.has(obj))
911
977
  throw TypeError("Cannot add the same private member more than once");
912
978
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
913
979
  };
914
- var __privateSet$2 = (obj, member, value, setter) => {
915
- __accessCheck$4(obj, member, "write to private field");
980
+ var __privateSet$4 = (obj, member, value, setter) => {
981
+ __accessCheck$5(obj, member, "write to private field");
916
982
  setter ? setter.call(obj, value) : member.set(obj, value);
917
983
  return value;
918
984
  };
919
985
  var _table$1, _repository, _data;
920
986
  const _Query = class {
921
987
  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: {} });
988
+ __privateAdd$5(this, _table$1, void 0);
989
+ __privateAdd$5(this, _repository, void 0);
990
+ __privateAdd$5(this, _data, { filter: {} });
925
991
  this.meta = { page: { cursor: "start", more: true } };
926
992
  this.records = [];
927
- __privateSet$2(this, _table$1, table);
993
+ __privateSet$4(this, _table$1, table);
928
994
  if (repository) {
929
- __privateSet$2(this, _repository, repository);
995
+ __privateSet$4(this, _repository, repository);
930
996
  } else {
931
- __privateSet$2(this, _repository, this);
997
+ __privateSet$4(this, _repository, this);
932
998
  }
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;
999
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1000
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1001
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1002
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1003
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1004
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1005
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1006
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1007
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
941
1008
  this.any = this.any.bind(this);
942
1009
  this.all = this.all.bind(this);
943
1010
  this.not = this.not.bind(this);
@@ -948,58 +1015,64 @@ const _Query = class {
948
1015
  Object.defineProperty(this, "repository", { enumerable: false });
949
1016
  }
950
1017
  getQueryOptions() {
951
- return __privateGet$3(this, _data);
1018
+ return __privateGet$5(this, _data);
1019
+ }
1020
+ key() {
1021
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1022
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1023
+ return toBase64(key);
952
1024
  }
953
1025
  any(...queries) {
954
1026
  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));
1027
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
956
1028
  }
957
1029
  all(...queries) {
958
1030
  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));
1031
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
960
1032
  }
961
1033
  not(...queries) {
962
1034
  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));
1035
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
964
1036
  }
965
1037
  none(...queries) {
966
1038
  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));
1039
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
968
1040
  }
969
1041
  filter(a, b) {
970
1042
  if (arguments.length === 1) {
971
1043
  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));
1044
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1045
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
974
1046
  } 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));
1047
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1048
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
977
1049
  }
978
1050
  }
979
1051
  sort(column, direction) {
980
- const originalSort = [__privateGet$3(this, _data).sort ?? []].flat();
1052
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
981
1053
  const sort = [...originalSort, { column, direction }];
982
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { sort }, __privateGet$3(this, _data));
1054
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
983
1055
  }
984
1056
  select(columns) {
985
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { columns }, __privateGet$3(this, _data));
1057
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
986
1058
  }
987
1059
  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);
1060
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1061
+ return __privateGet$5(this, _repository).query(query);
990
1062
  }
991
1063
  async *[Symbol.asyncIterator]() {
992
- for await (const [record] of this.getIterator(1)) {
1064
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
993
1065
  yield record;
994
1066
  }
995
1067
  }
996
- async *getIterator(chunk, options = {}) {
1068
+ async *getIterator(options = {}) {
1069
+ const { batchSize = 1 } = options;
997
1070
  let offset = 0;
998
1071
  let end = false;
999
1072
  while (!end) {
1000
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1073
+ const { records, meta } = await this.getPaginated({ ...options, pagination: { size: batchSize, offset } });
1001
1074
  yield records;
1002
- offset += chunk;
1075
+ offset += batchSize;
1003
1076
  end = !meta.page.more;
1004
1077
  }
1005
1078
  }
@@ -1007,16 +1080,20 @@ const _Query = class {
1007
1080
  const { records } = await this.getPaginated(options);
1008
1081
  return records;
1009
1082
  }
1010
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1083
+ async getAll(options = {}) {
1084
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1011
1085
  const results = [];
1012
- for await (const page of this.getIterator(chunk, options)) {
1086
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1013
1087
  results.push(...page);
1014
1088
  }
1015
1089
  return results;
1016
1090
  }
1017
- async getOne(options = {}) {
1018
- const records = await this.getMany({ ...options, page: { size: 1 } });
1019
- return records[0] || null;
1091
+ async getFirst(options = {}) {
1092
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1093
+ return records[0] ?? null;
1094
+ }
1095
+ cache(ttl) {
1096
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1020
1097
  }
1021
1098
  nextPage(size, offset) {
1022
1099
  return this.firstPage(size, offset);
@@ -1025,10 +1102,10 @@ const _Query = class {
1025
1102
  return this.firstPage(size, offset);
1026
1103
  }
1027
1104
  firstPage(size, offset) {
1028
- return this.getPaginated({ page: { size, offset } });
1105
+ return this.getPaginated({ pagination: { size, offset } });
1029
1106
  }
1030
1107
  lastPage(size, offset) {
1031
- return this.getPaginated({ page: { size, offset, before: "end" } });
1108
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1032
1109
  }
1033
1110
  hasNextPage() {
1034
1111
  return this.meta.page.more;
@@ -1069,75 +1146,94 @@ function buildSortFilter(filter) {
1069
1146
  }
1070
1147
  }
1071
1148
 
1072
- var __accessCheck$3 = (obj, member, msg) => {
1149
+ var __accessCheck$4 = (obj, member, msg) => {
1073
1150
  if (!member.has(obj))
1074
1151
  throw TypeError("Cannot " + msg);
1075
1152
  };
1076
- var __privateGet$2 = (obj, member, getter) => {
1077
- __accessCheck$3(obj, member, "read from private field");
1153
+ var __privateGet$4 = (obj, member, getter) => {
1154
+ __accessCheck$4(obj, member, "read from private field");
1078
1155
  return getter ? getter.call(obj) : member.get(obj);
1079
1156
  };
1080
- var __privateAdd$3 = (obj, member, value) => {
1157
+ var __privateAdd$4 = (obj, member, value) => {
1081
1158
  if (member.has(obj))
1082
1159
  throw TypeError("Cannot add the same private member more than once");
1083
1160
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1084
1161
  };
1085
- var __privateSet$1 = (obj, member, value, setter) => {
1086
- __accessCheck$3(obj, member, "write to private field");
1162
+ var __privateSet$3 = (obj, member, value, setter) => {
1163
+ __accessCheck$4(obj, member, "write to private field");
1087
1164
  setter ? setter.call(obj, value) : member.set(obj, value);
1088
1165
  return value;
1089
1166
  };
1090
1167
  var __privateMethod$2 = (obj, member, method) => {
1091
- __accessCheck$3(obj, member, "access private method");
1168
+ __accessCheck$4(obj, member, "access private method");
1092
1169
  return method;
1093
1170
  };
1094
- var _table, _links, _getFetchProps, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn;
1171
+ var _table, _getFetchProps, _cache, _schema$1, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchema$1, getSchema_fn$1;
1095
1172
  class Repository extends Query {
1096
1173
  }
1097
1174
  class RestRepository extends Query {
1098
1175
  constructor(options) {
1099
1176
  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);
1177
+ __privateAdd$4(this, _insertRecordWithoutId);
1178
+ __privateAdd$4(this, _insertRecordWithId);
1179
+ __privateAdd$4(this, _bulkInsertTableRecords);
1180
+ __privateAdd$4(this, _updateRecordWithID);
1181
+ __privateAdd$4(this, _upsertRecordWithID);
1182
+ __privateAdd$4(this, _deleteRecord);
1183
+ __privateAdd$4(this, _invalidateCache);
1184
+ __privateAdd$4(this, _setCacheRecord);
1185
+ __privateAdd$4(this, _getCacheRecord);
1186
+ __privateAdd$4(this, _setCacheQuery);
1187
+ __privateAdd$4(this, _getCacheQuery);
1188
+ __privateAdd$4(this, _getSchema$1);
1189
+ __privateAdd$4(this, _table, void 0);
1190
+ __privateAdd$4(this, _getFetchProps, void 0);
1191
+ __privateAdd$4(this, _cache, void 0);
1192
+ __privateAdd$4(this, _schema$1, void 0);
1193
+ __privateSet$3(this, _table, options.table);
1194
+ __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1112
1195
  this.db = options.db;
1196
+ __privateSet$3(this, _cache, options.pluginOptions.cache);
1113
1197
  }
1114
1198
  async create(a, b) {
1115
1199
  if (Array.isArray(a)) {
1116
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1200
+ const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1201
+ await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1202
+ return records;
1117
1203
  }
1118
1204
  if (isString(a) && isObject(b)) {
1119
1205
  if (a === "")
1120
1206
  throw new Error("The id can't be empty");
1121
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1207
+ const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1208
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1209
+ return record;
1122
1210
  }
1123
1211
  if (isObject(a) && isString(a.id)) {
1124
1212
  if (a.id === "")
1125
1213
  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 });
1214
+ const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1215
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1216
+ return record;
1127
1217
  }
1128
1218
  if (isObject(a)) {
1129
- return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1219
+ const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1220
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1221
+ return record;
1130
1222
  }
1131
1223
  throw new Error("Invalid arguments for create method");
1132
1224
  }
1133
1225
  async read(recordId) {
1134
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1226
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1227
+ if (cacheRecord)
1228
+ return cacheRecord;
1229
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1135
1230
  try {
1136
1231
  const response = await getRecord({
1137
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1232
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1138
1233
  ...fetchProps
1139
1234
  });
1140
- return initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), response);
1235
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1236
+ return initObject(this.db, schema, __privateGet$4(this, _table), response);
1141
1237
  } catch (e) {
1142
1238
  if (isObject(e) && e.status === 404) {
1143
1239
  return null;
@@ -1153,10 +1249,16 @@ class RestRepository extends Query {
1153
1249
  return Promise.all(a.map((object) => this.update(object)));
1154
1250
  }
1155
1251
  if (isString(a) && isObject(b)) {
1156
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1252
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1253
+ const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1254
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1255
+ return record;
1157
1256
  }
1158
1257
  if (isObject(a) && isString(a.id)) {
1159
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1258
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1259
+ const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1260
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1261
+ return record;
1160
1262
  }
1161
1263
  throw new Error("Invalid arguments for update method");
1162
1264
  }
@@ -1168,70 +1270,89 @@ class RestRepository extends Query {
1168
1270
  return Promise.all(a.map((object) => this.createOrUpdate(object)));
1169
1271
  }
1170
1272
  if (isString(a) && isObject(b)) {
1171
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1273
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1274
+ const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1275
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1276
+ return record;
1172
1277
  }
1173
1278
  if (isObject(a) && isString(a.id)) {
1174
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1279
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1280
+ const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1281
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1282
+ return record;
1175
1283
  }
1176
1284
  throw new Error("Invalid arguments for createOrUpdate method");
1177
1285
  }
1178
- async delete(recordId) {
1179
- if (Array.isArray(recordId)) {
1180
- if (recordId.length > 100) {
1286
+ async delete(a) {
1287
+ if (Array.isArray(a)) {
1288
+ if (a.length > 100) {
1181
1289
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1182
1290
  }
1183
- await Promise.all(recordId.map((id) => this.delete(id)));
1291
+ await Promise.all(a.map((id) => this.delete(id)));
1184
1292
  return;
1185
1293
  }
1186
- if (isString(recordId)) {
1187
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId);
1294
+ if (isString(a)) {
1295
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1296
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1188
1297
  return;
1189
1298
  }
1190
- if (isObject(recordId) && isString(recordId.id)) {
1191
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId.id);
1299
+ if (isObject(a) && isString(a.id)) {
1300
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1301
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1192
1302
  return;
1193
1303
  }
1194
1304
  throw new Error("Invalid arguments for delete method");
1195
1305
  }
1196
1306
  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 },
1307
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1308
+ const { records } = await searchTable({
1309
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1310
+ body: {
1311
+ query,
1312
+ fuzziness: options.fuzziness,
1313
+ filter: options.filter
1314
+ },
1201
1315
  ...fetchProps
1202
1316
  });
1203
- return records.map((item) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), item));
1317
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1318
+ return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1204
1319
  }
1205
1320
  async query(query) {
1321
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1322
+ if (cacheQuery)
1323
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1206
1324
  const data = query.getQueryOptions();
1207
1325
  const body = {
1208
1326
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1209
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1210
- page: data.page,
1327
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1328
+ page: data.pagination,
1211
1329
  columns: data.columns
1212
1330
  };
1213
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1331
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1214
1332
  const { meta, records: objects } = await queryTable({
1215
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1333
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1216
1334
  body,
1217
1335
  ...fetchProps
1218
1336
  });
1219
- const records = objects.map((record) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), record));
1337
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1338
+ const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1339
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1220
1340
  return new Page(query, meta, records);
1221
1341
  }
1222
1342
  }
1223
1343
  _table = new WeakMap();
1224
- _links = new WeakMap();
1225
1344
  _getFetchProps = new WeakMap();
1345
+ _cache = new WeakMap();
1346
+ _schema$1 = new WeakMap();
1226
1347
  _insertRecordWithoutId = new WeakSet();
1227
1348
  insertRecordWithoutId_fn = async function(object) {
1228
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1349
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1229
1350
  const record = transformObjectLinks(object);
1230
1351
  const response = await insertRecord({
1231
1352
  pathParams: {
1232
1353
  workspace: "{workspaceId}",
1233
1354
  dbBranchName: "{dbBranch}",
1234
- tableName: __privateGet$2(this, _table)
1355
+ tableName: __privateGet$4(this, _table)
1235
1356
  },
1236
1357
  body: record,
1237
1358
  ...fetchProps
@@ -1244,13 +1365,13 @@ insertRecordWithoutId_fn = async function(object) {
1244
1365
  };
1245
1366
  _insertRecordWithId = new WeakSet();
1246
1367
  insertRecordWithId_fn = async function(recordId, object) {
1247
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1368
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1248
1369
  const record = transformObjectLinks(object);
1249
1370
  const response = await insertRecordWithID({
1250
1371
  pathParams: {
1251
1372
  workspace: "{workspaceId}",
1252
1373
  dbBranchName: "{dbBranch}",
1253
- tableName: __privateGet$2(this, _table),
1374
+ tableName: __privateGet$4(this, _table),
1254
1375
  recordId
1255
1376
  },
1256
1377
  body: record,
@@ -1265,10 +1386,10 @@ insertRecordWithId_fn = async function(recordId, object) {
1265
1386
  };
1266
1387
  _bulkInsertTableRecords = new WeakSet();
1267
1388
  bulkInsertTableRecords_fn = async function(objects) {
1268
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1389
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1269
1390
  const records = objects.map((object) => transformObjectLinks(object));
1270
1391
  const response = await bulkInsertTableRecords({
1271
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1392
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1272
1393
  body: { records },
1273
1394
  ...fetchProps
1274
1395
  });
@@ -1280,10 +1401,10 @@ bulkInsertTableRecords_fn = async function(objects) {
1280
1401
  };
1281
1402
  _updateRecordWithID = new WeakSet();
1282
1403
  updateRecordWithID_fn = async function(recordId, object) {
1283
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1404
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1284
1405
  const record = transformObjectLinks(object);
1285
1406
  const response = await updateRecordWithID({
1286
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1407
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1287
1408
  body: record,
1288
1409
  ...fetchProps
1289
1410
  });
@@ -1294,9 +1415,9 @@ updateRecordWithID_fn = async function(recordId, object) {
1294
1415
  };
1295
1416
  _upsertRecordWithID = new WeakSet();
1296
1417
  upsertRecordWithID_fn = async function(recordId, object) {
1297
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1418
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1298
1419
  const response = await upsertRecordWithID({
1299
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1420
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1300
1421
  body: object,
1301
1422
  ...fetchProps
1302
1423
  });
@@ -1307,12 +1428,63 @@ upsertRecordWithID_fn = async function(recordId, object) {
1307
1428
  };
1308
1429
  _deleteRecord = new WeakSet();
1309
1430
  deleteRecord_fn = async function(recordId) {
1310
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1431
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1311
1432
  await deleteRecord({
1312
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1433
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1313
1434
  ...fetchProps
1314
1435
  });
1315
1436
  };
1437
+ _invalidateCache = new WeakSet();
1438
+ invalidateCache_fn = async function(recordId) {
1439
+ await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1440
+ const cacheItems = await __privateGet$4(this, _cache).getAll();
1441
+ const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1442
+ for (const [key, value] of queries) {
1443
+ const ids = getIds(value);
1444
+ if (ids.includes(recordId))
1445
+ await __privateGet$4(this, _cache).delete(key);
1446
+ }
1447
+ };
1448
+ _setCacheRecord = new WeakSet();
1449
+ setCacheRecord_fn = async function(record) {
1450
+ if (!__privateGet$4(this, _cache).cacheRecords)
1451
+ return;
1452
+ await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1453
+ };
1454
+ _getCacheRecord = new WeakSet();
1455
+ getCacheRecord_fn = async function(recordId) {
1456
+ if (!__privateGet$4(this, _cache).cacheRecords)
1457
+ return null;
1458
+ return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1459
+ };
1460
+ _setCacheQuery = new WeakSet();
1461
+ setCacheQuery_fn = async function(query, meta, records) {
1462
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1463
+ };
1464
+ _getCacheQuery = new WeakSet();
1465
+ getCacheQuery_fn = async function(query) {
1466
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1467
+ const result = await __privateGet$4(this, _cache).get(key);
1468
+ if (!result)
1469
+ return null;
1470
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1471
+ if (ttl < 0)
1472
+ return null;
1473
+ const hasExpired = result.date.getTime() + ttl < Date.now();
1474
+ return hasExpired ? null : result;
1475
+ };
1476
+ _getSchema$1 = new WeakSet();
1477
+ getSchema_fn$1 = async function() {
1478
+ if (__privateGet$4(this, _schema$1))
1479
+ return __privateGet$4(this, _schema$1);
1480
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1481
+ const { schema } = await getBranchDetails({
1482
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1483
+ ...fetchProps
1484
+ });
1485
+ __privateSet$3(this, _schema$1, schema);
1486
+ return schema;
1487
+ };
1316
1488
  const transformObjectLinks = (object) => {
1317
1489
  return Object.entries(object).reduce((acc, [key, value]) => {
1318
1490
  if (key === "xata")
@@ -1320,15 +1492,33 @@ const transformObjectLinks = (object) => {
1320
1492
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1321
1493
  }, {});
1322
1494
  };
1323
- const initObject = (db, links, table, object) => {
1495
+ const initObject = (db, schema, table, object) => {
1324
1496
  const result = {};
1325
1497
  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);
1498
+ const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1499
+ if (!columns)
1500
+ console.error(`Table ${table} not found in schema`);
1501
+ for (const column of columns ?? []) {
1502
+ const value = result[column.name];
1503
+ switch (column.type) {
1504
+ case "datetime": {
1505
+ const date = new Date(value);
1506
+ if (isNaN(date.getTime())) {
1507
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1508
+ } else {
1509
+ result[column.name] = date;
1510
+ }
1511
+ break;
1512
+ }
1513
+ case "link": {
1514
+ const linkTable = column.link?.table;
1515
+ if (!linkTable) {
1516
+ console.error(`Failed to parse link for field ${column.name}`);
1517
+ } else if (isObject(value)) {
1518
+ result[column.name] = initObject(db, schema, linkTable, value);
1519
+ }
1520
+ break;
1521
+ }
1332
1522
  }
1333
1523
  }
1334
1524
  result.read = function() {
@@ -1346,6 +1536,65 @@ const initObject = (db, links, table, object) => {
1346
1536
  Object.freeze(result);
1347
1537
  return result;
1348
1538
  };
1539
+ function getIds(value) {
1540
+ if (Array.isArray(value)) {
1541
+ return value.map((item) => getIds(item)).flat();
1542
+ }
1543
+ if (!isObject(value))
1544
+ return [];
1545
+ const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1546
+ return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1547
+ }
1548
+
1549
+ var __accessCheck$3 = (obj, member, msg) => {
1550
+ if (!member.has(obj))
1551
+ throw TypeError("Cannot " + msg);
1552
+ };
1553
+ var __privateGet$3 = (obj, member, getter) => {
1554
+ __accessCheck$3(obj, member, "read from private field");
1555
+ return getter ? getter.call(obj) : member.get(obj);
1556
+ };
1557
+ var __privateAdd$3 = (obj, member, value) => {
1558
+ if (member.has(obj))
1559
+ throw TypeError("Cannot add the same private member more than once");
1560
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1561
+ };
1562
+ var __privateSet$2 = (obj, member, value, setter) => {
1563
+ __accessCheck$3(obj, member, "write to private field");
1564
+ setter ? setter.call(obj, value) : member.set(obj, value);
1565
+ return value;
1566
+ };
1567
+ var _map;
1568
+ class SimpleCache {
1569
+ constructor(options = {}) {
1570
+ __privateAdd$3(this, _map, void 0);
1571
+ __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1572
+ this.capacity = options.max ?? 500;
1573
+ this.cacheRecords = options.cacheRecords ?? true;
1574
+ this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1575
+ }
1576
+ async getAll() {
1577
+ return Object.fromEntries(__privateGet$3(this, _map));
1578
+ }
1579
+ async get(key) {
1580
+ return __privateGet$3(this, _map).get(key) ?? null;
1581
+ }
1582
+ async set(key, value) {
1583
+ await this.delete(key);
1584
+ __privateGet$3(this, _map).set(key, value);
1585
+ if (__privateGet$3(this, _map).size > this.capacity) {
1586
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1587
+ await this.delete(leastRecentlyUsed);
1588
+ }
1589
+ }
1590
+ async delete(key) {
1591
+ __privateGet$3(this, _map).delete(key);
1592
+ }
1593
+ async clear() {
1594
+ return __privateGet$3(this, _map).clear();
1595
+ }
1596
+ }
1597
+ _map = new WeakMap();
1349
1598
 
1350
1599
  const gt = (value) => ({ $gt: value });
1351
1600
  const ge = (value) => ({ $ge: value });
@@ -1370,7 +1619,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1370
1619
  if (!member.has(obj))
1371
1620
  throw TypeError("Cannot " + msg);
1372
1621
  };
1373
- var __privateGet$1 = (obj, member, getter) => {
1622
+ var __privateGet$2 = (obj, member, getter) => {
1374
1623
  __accessCheck$2(obj, member, "read from private field");
1375
1624
  return getter ? getter.call(obj) : member.get(obj);
1376
1625
  };
@@ -1381,26 +1630,24 @@ var __privateAdd$2 = (obj, member, value) => {
1381
1630
  };
1382
1631
  var _tables;
1383
1632
  class SchemaPlugin extends XataPlugin {
1384
- constructor(links, tableNames) {
1633
+ constructor(tableNames) {
1385
1634
  super();
1386
- this.links = links;
1387
1635
  this.tableNames = tableNames;
1388
1636
  __privateAdd$2(this, _tables, {});
1389
1637
  }
1390
- build(options) {
1391
- const { getFetchProps } = options;
1392
- const links = this.links;
1638
+ build(pluginOptions) {
1393
1639
  const db = new Proxy({}, {
1394
1640
  get: (_target, table) => {
1395
1641
  if (!isString(table))
1396
1642
  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];
1643
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1644
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1645
+ }
1646
+ return __privateGet$2(this, _tables)[table];
1400
1647
  }
1401
1648
  });
1402
1649
  for (const table of this.tableNames ?? []) {
1403
- db[table] = new RestRepository({ db, getFetchProps, table, links });
1650
+ db[table] = new RestRepository({ db, pluginOptions, table });
1404
1651
  }
1405
1652
  return db;
1406
1653
  }
@@ -1411,44 +1658,57 @@ var __accessCheck$1 = (obj, member, msg) => {
1411
1658
  if (!member.has(obj))
1412
1659
  throw TypeError("Cannot " + msg);
1413
1660
  };
1661
+ var __privateGet$1 = (obj, member, getter) => {
1662
+ __accessCheck$1(obj, member, "read from private field");
1663
+ return getter ? getter.call(obj) : member.get(obj);
1664
+ };
1414
1665
  var __privateAdd$1 = (obj, member, value) => {
1415
1666
  if (member.has(obj))
1416
1667
  throw TypeError("Cannot add the same private member more than once");
1417
1668
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1418
1669
  };
1670
+ var __privateSet$1 = (obj, member, value, setter) => {
1671
+ __accessCheck$1(obj, member, "write to private field");
1672
+ setter ? setter.call(obj, value) : member.set(obj, value);
1673
+ return value;
1674
+ };
1419
1675
  var __privateMethod$1 = (obj, member, method) => {
1420
1676
  __accessCheck$1(obj, member, "access private method");
1421
1677
  return method;
1422
1678
  };
1423
- var _search, search_fn;
1679
+ var _schema, _search, search_fn, _getSchema, getSchema_fn;
1424
1680
  class SearchPlugin extends XataPlugin {
1425
- constructor(db, links) {
1681
+ constructor(db) {
1426
1682
  super();
1427
1683
  this.db = db;
1428
- this.links = links;
1429
1684
  __privateAdd$1(this, _search);
1685
+ __privateAdd$1(this, _getSchema);
1686
+ __privateAdd$1(this, _schema, void 0);
1430
1687
  }
1431
1688
  build({ getFetchProps }) {
1432
1689
  return {
1433
1690
  all: async (query, options = {}) => {
1434
1691
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1692
+ const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1435
1693
  return records.map((record) => {
1436
1694
  const { table = "orphan" } = record.xata;
1437
- return { table, record: initObject(this.db, this.links, table, record) };
1695
+ return { table, record: initObject(this.db, schema, table, record) };
1438
1696
  });
1439
1697
  },
1440
1698
  byTable: async (query, options = {}) => {
1441
1699
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1700
+ const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1442
1701
  return records.reduce((acc, record) => {
1443
1702
  const { table = "orphan" } = record.xata;
1444
1703
  const items = acc[table] ?? [];
1445
- const item = initObject(this.db, this.links, table, record);
1704
+ const item = initObject(this.db, schema, table, record);
1446
1705
  return { ...acc, [table]: [...items, item] };
1447
1706
  }, {});
1448
1707
  }
1449
1708
  };
1450
1709
  }
1451
1710
  }
1711
+ _schema = new WeakMap();
1452
1712
  _search = new WeakSet();
1453
1713
  search_fn = async function(query, options, getFetchProps) {
1454
1714
  const fetchProps = await getFetchProps();
@@ -1460,6 +1720,18 @@ search_fn = async function(query, options, getFetchProps) {
1460
1720
  });
1461
1721
  return records;
1462
1722
  };
1723
+ _getSchema = new WeakSet();
1724
+ getSchema_fn = async function(getFetchProps) {
1725
+ if (__privateGet$1(this, _schema))
1726
+ return __privateGet$1(this, _schema);
1727
+ const fetchProps = await getFetchProps();
1728
+ const { schema } = await getBranchDetails({
1729
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1730
+ ...fetchProps
1731
+ });
1732
+ __privateSet$1(this, _schema, schema);
1733
+ return schema;
1734
+ };
1463
1735
 
1464
1736
  const isBranchStrategyBuilder = (strategy) => {
1465
1737
  return typeof strategy === "function";
@@ -1471,30 +1743,39 @@ const envBranchNames = [
1471
1743
  "CF_PAGES_BRANCH",
1472
1744
  "BRANCH"
1473
1745
  ];
1474
- const defaultBranch = "main";
1475
1746
  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;
1747
+ const env = getBranchByEnvVariable();
1748
+ if (env) {
1749
+ const details = await getDatabaseBranch(env, options);
1750
+ if (details)
1751
+ return env;
1752
+ console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1753
+ }
1754
+ const gitBranch = await getGitBranch();
1755
+ return resolveXataBranch(gitBranch, options);
1486
1756
  }
1487
1757
  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);
1758
+ const branch = await getCurrentBranchName(options);
1759
+ return getDatabaseBranch(branch, options);
1760
+ }
1761
+ async function resolveXataBranch(gitBranch, options) {
1762
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1763
+ const apiKey = options?.apiKey || getAPIKey();
1764
+ if (!databaseURL)
1765
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1766
+ if (!apiKey)
1767
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1768
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1769
+ const [workspace] = host.split(".");
1770
+ const { branch } = await resolveBranch({
1771
+ apiKey,
1772
+ apiUrl: databaseURL,
1773
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1774
+ workspacesApiUrl: `${protocol}//${host}`,
1775
+ pathParams: { dbName, workspace },
1776
+ queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
1777
+ });
1778
+ return branch;
1498
1779
  }
1499
1780
  async function getDatabaseBranch(branch, options) {
1500
1781
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1568,22 +1849,24 @@ var __privateMethod = (obj, member, method) => {
1568
1849
  const buildClient = (plugins) => {
1569
1850
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1570
1851
  return _a = class {
1571
- constructor(options = {}, links, tables) {
1852
+ constructor(options = {}, tables) {
1572
1853
  __privateAdd(this, _parseOptions);
1573
1854
  __privateAdd(this, _getFetchProps);
1574
1855
  __privateAdd(this, _evaluateBranch);
1575
1856
  __privateAdd(this, _branch, void 0);
1576
1857
  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
- });
1858
+ const pluginOptions = {
1859
+ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1860
+ cache: safeOptions.cache
1861
+ };
1862
+ const db = new SchemaPlugin(tables).build(pluginOptions);
1863
+ const search = new SearchPlugin(db).build(pluginOptions);
1581
1864
  this.db = db;
1582
1865
  this.search = search;
1583
1866
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1584
- if (!namespace)
1867
+ if (namespace === void 0)
1585
1868
  continue;
1586
- const result = namespace.build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
1869
+ const result = namespace.build(pluginOptions);
1587
1870
  if (result instanceof Promise) {
1588
1871
  void result.then((namespace2) => {
1589
1872
  this[key] = namespace2;
@@ -1597,11 +1880,12 @@ const buildClient = (plugins) => {
1597
1880
  const fetch = getFetchImplementation(options?.fetch);
1598
1881
  const databaseURL = options?.databaseURL || getDatabaseURL();
1599
1882
  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 });
1883
+ const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1884
+ 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
1885
  if (!databaseURL || !apiKey) {
1602
1886
  throw new Error("Options databaseURL and apiKey are required");
1603
1887
  }
1604
- return { fetch, databaseURL, apiKey, branch };
1888
+ return { fetch, databaseURL, apiKey, branch, cache };
1605
1889
  }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1606
1890
  fetch,
1607
1891
  apiKey,
@@ -1624,7 +1908,7 @@ const buildClient = (plugins) => {
1624
1908
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1625
1909
  if (__privateGet(this, _branch))
1626
1910
  return __privateGet(this, _branch);
1627
- if (!param)
1911
+ if (param === void 0)
1628
1912
  return void 0;
1629
1913
  const strategies = Array.isArray(param) ? [...param] : [param];
1630
1914
  const evaluateBranch = async (strategy) => {
@@ -1649,5 +1933,5 @@ class XataError extends Error {
1649
1933
  }
1650
1934
  }
1651
1935
 
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 };
1936
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
1653
1937
  //# sourceMappingURL=index.mjs.map