@xata.io/client 0.0.0-alpha.ved00a04 → 0.0.0-alpha.ved669cc

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,34 +7,85 @@ 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";
12
15
  }
13
16
  function toBase64(value) {
14
17
  try {
15
18
  return btoa(value);
16
19
  } catch (err) {
17
- return Buffer.from(value).toString("base64");
20
+ const buf = Buffer;
21
+ return buf.from(value).toString("base64");
18
22
  }
19
23
  }
20
24
 
21
- function getEnvVariable(name) {
25
+ function getEnvironment() {
22
26
  try {
23
- if (isObject(process) && isString(process?.env?.[name])) {
24
- 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 ?? process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH ?? getGlobalBranch(),
32
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
33
+ };
25
34
  }
26
35
  } catch (err) {
27
36
  }
28
37
  try {
29
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
30
- return Deno.env.get(name);
38
+ if (isObject(Deno) && isObject(Deno.env)) {
39
+ return {
40
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
41
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
42
+ branch: Deno.env.get("XATA_BRANCH") ?? Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH") ?? getGlobalBranch(),
43
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
44
+ };
31
45
  }
32
46
  } catch (err) {
33
47
  }
48
+ return {
49
+ apiKey: getGlobalApiKey(),
50
+ databaseURL: getGlobalDatabaseURL(),
51
+ branch: getGlobalBranch(),
52
+ fallbackBranch: getGlobalFallbackBranch()
53
+ };
54
+ }
55
+ function getGlobalApiKey() {
56
+ try {
57
+ return XATA_API_KEY;
58
+ } catch (err) {
59
+ return void 0;
60
+ }
61
+ }
62
+ function getGlobalDatabaseURL() {
63
+ try {
64
+ return XATA_DATABASE_URL;
65
+ } catch (err) {
66
+ return void 0;
67
+ }
68
+ }
69
+ function getGlobalBranch() {
70
+ try {
71
+ return XATA_BRANCH;
72
+ } catch (err) {
73
+ return void 0;
74
+ }
75
+ }
76
+ function getGlobalFallbackBranch() {
77
+ try {
78
+ return XATA_FALLBACK_BRANCH;
79
+ } catch (err) {
80
+ return void 0;
81
+ }
34
82
  }
35
83
  async function getGitBranch() {
36
84
  try {
37
- return require("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
85
+ if (typeof require === "function") {
86
+ const req = require;
87
+ return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
88
+ }
38
89
  } catch (err) {
39
90
  }
40
91
  try {
@@ -52,7 +103,8 @@ async function getGitBranch() {
52
103
 
53
104
  function getAPIKey() {
54
105
  try {
55
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
106
+ const { apiKey } = getEnvironment();
107
+ return apiKey;
56
108
  } catch (err) {
57
109
  return void 0;
58
110
  }
@@ -67,16 +119,28 @@ function getFetchImplementation(userFetch) {
67
119
  return fetchImpl;
68
120
  }
69
121
 
70
- class FetcherError extends Error {
71
- constructor(status, data) {
122
+ const VERSION = "0.0.0-alpha.ved669cc";
123
+
124
+ class ErrorWithCause extends Error {
125
+ constructor(message, options) {
126
+ super(message, options);
127
+ }
128
+ }
129
+ class FetcherError extends ErrorWithCause {
130
+ constructor(status, data, requestId) {
72
131
  super(getMessage(data));
73
132
  this.status = status;
74
133
  this.errors = isBulkError(data) ? data.errors : void 0;
134
+ this.requestId = requestId;
75
135
  if (data instanceof Error) {
76
136
  this.stack = data.stack;
77
137
  this.cause = data.cause;
78
138
  }
79
139
  }
140
+ toString() {
141
+ const error = super.toString();
142
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
143
+ }
80
144
  }
81
145
  function isBulkError(error) {
82
146
  return isObject(error) && Array.isArray(error.errors);
@@ -99,7 +163,12 @@ function getMessage(data) {
99
163
  }
100
164
 
101
165
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
102
- const query = new URLSearchParams(queryParams).toString();
166
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
167
+ if (value === void 0 || value === null)
168
+ return acc;
169
+ return { ...acc, [key]: value };
170
+ }, {});
171
+ const query = new URLSearchParams(cleanQueryParams).toString();
103
172
  const queryString = query.length > 0 ? `?${query}` : "";
104
173
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
105
174
  };
@@ -139,6 +208,7 @@ async function fetch$1({
139
208
  body: body ? JSON.stringify(body) : void 0,
140
209
  headers: {
141
210
  "Content-Type": "application/json",
211
+ "User-Agent": `Xata client-ts/${VERSION}`,
142
212
  ...headers,
143
213
  ...hostHeader(fullUrl),
144
214
  Authorization: `Bearer ${apiKey}`
@@ -147,14 +217,15 @@ async function fetch$1({
147
217
  if (response.status === 204) {
148
218
  return {};
149
219
  }
220
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
150
221
  try {
151
222
  const jsonResponse = await response.json();
152
223
  if (response.ok) {
153
224
  return jsonResponse;
154
225
  }
155
- throw new FetcherError(response.status, jsonResponse);
226
+ throw new FetcherError(response.status, jsonResponse, requestId);
156
227
  } catch (error) {
157
- throw new FetcherError(response.status, error);
228
+ throw new FetcherError(response.status, error, requestId);
158
229
  }
159
230
  }
160
231
 
@@ -248,6 +319,14 @@ const deleteDatabase = (variables) => fetch$1({
248
319
  method: "delete",
249
320
  ...variables
250
321
  });
322
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
323
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
324
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
325
+ const resolveBranch = (variables) => fetch$1({
326
+ url: "/dbs/{dbName}/resolveBranch",
327
+ method: "get",
328
+ ...variables
329
+ });
251
330
  const getBranchDetails = (variables) => fetch$1({
252
331
  url: "/db/{dbBranchName}",
253
332
  method: "get",
@@ -276,17 +355,6 @@ const getBranchMetadata = (variables) => fetch$1({
276
355
  const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
277
356
  const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
278
357
  const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
279
- const compareBranchSchema = (variables) => fetch$1({
280
- url: "/db/{dbBranchName}/schema/compare/{branchName}",
281
- method: "post",
282
- ...variables
283
- });
284
- const updateBranchSchema = (variables) => fetch$1({
285
- url: "/db/{dbBranchName}/schema/update",
286
- method: "post",
287
- ...variables
288
- });
289
- const getBranchSchemaHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables });
290
358
  const getBranchStats = (variables) => fetch$1({
291
359
  url: "/db/{dbBranchName}/stats",
292
360
  method: "get",
@@ -366,6 +434,11 @@ const queryTable = (variables) => fetch$1({
366
434
  method: "post",
367
435
  ...variables
368
436
  });
437
+ const searchTable = (variables) => fetch$1({
438
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
439
+ method: "post",
440
+ ...variables
441
+ });
369
442
  const searchBranch = (variables) => fetch$1({
370
443
  url: "/db/{dbBranchName}/search",
371
444
  method: "post",
@@ -387,7 +460,15 @@ const operationsByTag = {
387
460
  resendWorkspaceMemberInvite,
388
461
  acceptWorkspaceMemberInvite
389
462
  },
390
- database: { getDatabaseList, createDatabase, deleteDatabase },
463
+ database: {
464
+ getDatabaseList,
465
+ createDatabase,
466
+ deleteDatabase,
467
+ getGitBranchesMapping,
468
+ addGitBranchesEntry,
469
+ removeGitBranchesEntry,
470
+ resolveBranch
471
+ },
391
472
  branch: {
392
473
  getBranchList,
393
474
  getBranchDetails,
@@ -398,9 +479,6 @@ const operationsByTag = {
398
479
  getBranchMigrationHistory,
399
480
  executeBranchMigrationPlan,
400
481
  getBranchMigrationPlan,
401
- compareBranchSchema,
402
- updateBranchSchema,
403
- getBranchSchemaHistory,
404
482
  getBranchStats
405
483
  },
406
484
  table: {
@@ -424,6 +502,7 @@ const operationsByTag = {
424
502
  getRecord,
425
503
  bulkInsertTableRecords,
426
504
  queryTable,
505
+ searchTable,
427
506
  searchBranch
428
507
  }
429
508
  };
@@ -457,7 +536,7 @@ var __accessCheck$7 = (obj, member, msg) => {
457
536
  if (!member.has(obj))
458
537
  throw TypeError("Cannot " + msg);
459
538
  };
460
- var __privateGet$6 = (obj, member, getter) => {
539
+ var __privateGet$7 = (obj, member, getter) => {
461
540
  __accessCheck$7(obj, member, "read from private field");
462
541
  return getter ? getter.call(obj) : member.get(obj);
463
542
  };
@@ -466,7 +545,7 @@ var __privateAdd$7 = (obj, member, value) => {
466
545
  throw TypeError("Cannot add the same private member more than once");
467
546
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
468
547
  };
469
- var __privateSet$5 = (obj, member, value, setter) => {
548
+ var __privateSet$7 = (obj, member, value, setter) => {
470
549
  __accessCheck$7(obj, member, "write to private field");
471
550
  setter ? setter.call(obj, value) : member.set(obj, value);
472
551
  return value;
@@ -481,7 +560,7 @@ class XataApiClient {
481
560
  if (!apiKey) {
482
561
  throw new Error("Could not resolve a valid apiKey");
483
562
  }
484
- __privateSet$5(this, _extraProps, {
563
+ __privateSet$7(this, _extraProps, {
485
564
  apiUrl: getHostUrl(provider, "main"),
486
565
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
487
566
  fetchImpl: getFetchImplementation(options.fetch),
@@ -489,34 +568,34 @@ class XataApiClient {
489
568
  });
490
569
  }
491
570
  get user() {
492
- if (!__privateGet$6(this, _namespaces).user)
493
- __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
494
- return __privateGet$6(this, _namespaces).user;
571
+ if (!__privateGet$7(this, _namespaces).user)
572
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
573
+ return __privateGet$7(this, _namespaces).user;
495
574
  }
496
575
  get workspaces() {
497
- if (!__privateGet$6(this, _namespaces).workspaces)
498
- __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
499
- return __privateGet$6(this, _namespaces).workspaces;
576
+ if (!__privateGet$7(this, _namespaces).workspaces)
577
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
578
+ return __privateGet$7(this, _namespaces).workspaces;
500
579
  }
501
580
  get databases() {
502
- if (!__privateGet$6(this, _namespaces).databases)
503
- __privateGet$6(this, _namespaces).databases = new DatabaseApi(__privateGet$6(this, _extraProps));
504
- return __privateGet$6(this, _namespaces).databases;
581
+ if (!__privateGet$7(this, _namespaces).databases)
582
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
583
+ return __privateGet$7(this, _namespaces).databases;
505
584
  }
506
585
  get branches() {
507
- if (!__privateGet$6(this, _namespaces).branches)
508
- __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
509
- return __privateGet$6(this, _namespaces).branches;
586
+ if (!__privateGet$7(this, _namespaces).branches)
587
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
588
+ return __privateGet$7(this, _namespaces).branches;
510
589
  }
511
590
  get tables() {
512
- if (!__privateGet$6(this, _namespaces).tables)
513
- __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
514
- return __privateGet$6(this, _namespaces).tables;
591
+ if (!__privateGet$7(this, _namespaces).tables)
592
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
593
+ return __privateGet$7(this, _namespaces).tables;
515
594
  }
516
595
  get records() {
517
- if (!__privateGet$6(this, _namespaces).records)
518
- __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
519
- return __privateGet$6(this, _namespaces).records;
596
+ if (!__privateGet$7(this, _namespaces).records)
597
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
598
+ return __privateGet$7(this, _namespaces).records;
520
599
  }
521
600
  }
522
601
  _extraProps = new WeakMap();
@@ -650,6 +729,33 @@ class DatabaseApi {
650
729
  ...this.extraProps
651
730
  });
652
731
  }
732
+ getGitBranchesMapping(workspace, dbName) {
733
+ return operationsByTag.database.getGitBranchesMapping({
734
+ pathParams: { workspace, dbName },
735
+ ...this.extraProps
736
+ });
737
+ }
738
+ addGitBranchesEntry(workspace, dbName, body) {
739
+ return operationsByTag.database.addGitBranchesEntry({
740
+ pathParams: { workspace, dbName },
741
+ body,
742
+ ...this.extraProps
743
+ });
744
+ }
745
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
746
+ return operationsByTag.database.removeGitBranchesEntry({
747
+ pathParams: { workspace, dbName },
748
+ queryParams: { gitBranch },
749
+ ...this.extraProps
750
+ });
751
+ }
752
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
753
+ return operationsByTag.database.resolveBranch({
754
+ pathParams: { workspace, dbName },
755
+ queryParams: { gitBranch, fallbackBranch },
756
+ ...this.extraProps
757
+ });
758
+ }
653
759
  }
654
760
  class BranchApi {
655
761
  constructor(extraProps) {
@@ -667,10 +773,10 @@ class BranchApi {
667
773
  ...this.extraProps
668
774
  });
669
775
  }
670
- createBranch(workspace, database, branch, from = "", options = {}) {
776
+ createBranch(workspace, database, branch, from, options = {}) {
671
777
  return operationsByTag.branch.createBranch({
672
778
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
673
- queryParams: { from },
779
+ queryParams: isString(from) ? { from } : void 0,
674
780
  body: options,
675
781
  ...this.extraProps
676
782
  });
@@ -852,6 +958,13 @@ class RecordsApi {
852
958
  ...this.extraProps
853
959
  });
854
960
  }
961
+ searchTable(workspace, database, branch, tableName, query) {
962
+ return operationsByTag.records.searchTable({
963
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
964
+ body: query,
965
+ ...this.extraProps
966
+ });
967
+ }
855
968
  searchBranch(workspace, database, branch, query) {
856
969
  return operationsByTag.records.searchBranch({
857
970
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -875,7 +988,7 @@ var __accessCheck$6 = (obj, member, msg) => {
875
988
  if (!member.has(obj))
876
989
  throw TypeError("Cannot " + msg);
877
990
  };
878
- var __privateGet$5 = (obj, member, getter) => {
991
+ var __privateGet$6 = (obj, member, getter) => {
879
992
  __accessCheck$6(obj, member, "read from private field");
880
993
  return getter ? getter.call(obj) : member.get(obj);
881
994
  };
@@ -884,30 +997,30 @@ var __privateAdd$6 = (obj, member, value) => {
884
997
  throw TypeError("Cannot add the same private member more than once");
885
998
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
886
999
  };
887
- var __privateSet$4 = (obj, member, value, setter) => {
1000
+ var __privateSet$6 = (obj, member, value, setter) => {
888
1001
  __accessCheck$6(obj, member, "write to private field");
889
1002
  setter ? setter.call(obj, value) : member.set(obj, value);
890
1003
  return value;
891
1004
  };
892
- var _query;
1005
+ var _query, _page;
893
1006
  class Page {
894
1007
  constructor(query, meta, records = []) {
895
1008
  __privateAdd$6(this, _query, void 0);
896
- __privateSet$4(this, _query, query);
1009
+ __privateSet$6(this, _query, query);
897
1010
  this.meta = meta;
898
- this.records = records;
1011
+ this.records = new RecordArray(this, records);
899
1012
  }
900
1013
  async nextPage(size, offset) {
901
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1014
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
902
1015
  }
903
1016
  async previousPage(size, offset) {
904
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1017
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
905
1018
  }
906
1019
  async firstPage(size, offset) {
907
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1020
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
908
1021
  }
909
1022
  async lastPage(size, offset) {
910
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1023
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
911
1024
  }
912
1025
  hasNextPage() {
913
1026
  return this.meta.page.more;
@@ -915,15 +1028,56 @@ class Page {
915
1028
  }
916
1029
  _query = new WeakMap();
917
1030
  const PAGINATION_MAX_SIZE = 200;
918
- const PAGINATION_DEFAULT_SIZE = 200;
1031
+ const PAGINATION_DEFAULT_SIZE = 20;
919
1032
  const PAGINATION_MAX_OFFSET = 800;
920
1033
  const PAGINATION_DEFAULT_OFFSET = 0;
1034
+ function isCursorPaginationOptions(options) {
1035
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1036
+ }
1037
+ const _RecordArray = class extends Array {
1038
+ constructor(page, overrideRecords) {
1039
+ super(..._RecordArray.parseConstructorParams(page, overrideRecords));
1040
+ __privateAdd$6(this, _page, void 0);
1041
+ __privateSet$6(this, _page, page);
1042
+ }
1043
+ static parseConstructorParams(...args) {
1044
+ if (args.length === 1 && typeof args[0] === "number") {
1045
+ return new Array(args[0]);
1046
+ }
1047
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1048
+ const result = args[1] ?? args[0].records ?? [];
1049
+ return new Array(...result);
1050
+ }
1051
+ return new Array(...args);
1052
+ }
1053
+ async nextPage(size, offset) {
1054
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1055
+ return new _RecordArray(newPage);
1056
+ }
1057
+ async previousPage(size, offset) {
1058
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1059
+ return new _RecordArray(newPage);
1060
+ }
1061
+ async firstPage(size, offset) {
1062
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1063
+ return new _RecordArray(newPage);
1064
+ }
1065
+ async lastPage(size, offset) {
1066
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1067
+ return new _RecordArray(newPage);
1068
+ }
1069
+ hasNextPage() {
1070
+ return __privateGet$6(this, _page).meta.page.more;
1071
+ }
1072
+ };
1073
+ let RecordArray = _RecordArray;
1074
+ _page = new WeakMap();
921
1075
 
922
1076
  var __accessCheck$5 = (obj, member, msg) => {
923
1077
  if (!member.has(obj))
924
1078
  throw TypeError("Cannot " + msg);
925
1079
  };
926
- var __privateGet$4 = (obj, member, getter) => {
1080
+ var __privateGet$5 = (obj, member, getter) => {
927
1081
  __accessCheck$5(obj, member, "read from private field");
928
1082
  return getter ? getter.call(obj) : member.get(obj);
929
1083
  };
@@ -932,34 +1086,35 @@ var __privateAdd$5 = (obj, member, value) => {
932
1086
  throw TypeError("Cannot add the same private member more than once");
933
1087
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
934
1088
  };
935
- var __privateSet$3 = (obj, member, value, setter) => {
1089
+ var __privateSet$5 = (obj, member, value, setter) => {
936
1090
  __accessCheck$5(obj, member, "write to private field");
937
1091
  setter ? setter.call(obj, value) : member.set(obj, value);
938
1092
  return value;
939
1093
  };
940
1094
  var _table$1, _repository, _data;
941
1095
  const _Query = class {
942
- constructor(repository, table, data, parent) {
1096
+ constructor(repository, table, data, rawParent) {
943
1097
  __privateAdd$5(this, _table$1, void 0);
944
1098
  __privateAdd$5(this, _repository, void 0);
945
1099
  __privateAdd$5(this, _data, { filter: {} });
946
1100
  this.meta = { page: { cursor: "start", more: true } };
947
- this.records = [];
948
- __privateSet$3(this, _table$1, table);
1101
+ this.records = new RecordArray(this, []);
1102
+ __privateSet$5(this, _table$1, table);
949
1103
  if (repository) {
950
- __privateSet$3(this, _repository, repository);
1104
+ __privateSet$5(this, _repository, repository);
951
1105
  } else {
952
- __privateSet$3(this, _repository, this);
1106
+ __privateSet$5(this, _repository, this);
953
1107
  }
954
- __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
955
- __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
956
- __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
957
- __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
958
- __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
959
- __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
960
- __privateGet$4(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
961
- __privateGet$4(this, _data).page = data.page ?? parent?.page;
962
- __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
1108
+ const parent = cleanParent(data, rawParent);
1109
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1110
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1111
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1112
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1113
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1114
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1115
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1116
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1117
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
963
1118
  this.any = this.any.bind(this);
964
1119
  this.all = this.all.bind(this);
965
1120
  this.not = this.not.bind(this);
@@ -970,83 +1125,88 @@ const _Query = class {
970
1125
  Object.defineProperty(this, "repository", { enumerable: false });
971
1126
  }
972
1127
  getQueryOptions() {
973
- return __privateGet$4(this, _data);
1128
+ return __privateGet$5(this, _data);
974
1129
  }
975
1130
  key() {
976
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$4(this, _data);
977
- const key = JSON.stringify({ columns, filter, sort, page });
1131
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1132
+ const key = JSON.stringify({ columns, filter, sort, pagination });
978
1133
  return toBase64(key);
979
1134
  }
980
1135
  any(...queries) {
981
1136
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
982
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
1137
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
983
1138
  }
984
1139
  all(...queries) {
985
1140
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
986
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1141
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
987
1142
  }
988
1143
  not(...queries) {
989
1144
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
990
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
1145
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
991
1146
  }
992
1147
  none(...queries) {
993
1148
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
994
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
1149
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
995
1150
  }
996
1151
  filter(a, b) {
997
1152
  if (arguments.length === 1) {
998
1153
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
999
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
1000
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1154
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1155
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1001
1156
  } else {
1002
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1003
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1157
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1158
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1004
1159
  }
1005
1160
  }
1006
1161
  sort(column, direction) {
1007
- const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
1162
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1008
1163
  const sort = [...originalSort, { column, direction }];
1009
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
1164
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1010
1165
  }
1011
1166
  select(columns) {
1012
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { columns }, __privateGet$4(this, _data));
1167
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1013
1168
  }
1014
1169
  getPaginated(options = {}) {
1015
- const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
1016
- return __privateGet$4(this, _repository).query(query);
1170
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1171
+ return __privateGet$5(this, _repository).query(query);
1017
1172
  }
1018
1173
  async *[Symbol.asyncIterator]() {
1019
- for await (const [record] of this.getIterator(1)) {
1174
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1020
1175
  yield record;
1021
1176
  }
1022
1177
  }
1023
- async *getIterator(chunk, options = {}) {
1024
- let offset = 0;
1025
- let end = false;
1026
- while (!end) {
1027
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1028
- yield records;
1029
- offset += chunk;
1030
- end = !meta.page.more;
1178
+ async *getIterator(options = {}) {
1179
+ const { batchSize = 1 } = options;
1180
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1181
+ let more = page.hasNextPage();
1182
+ yield page.records;
1183
+ while (more) {
1184
+ page = await page.nextPage();
1185
+ more = page.hasNextPage();
1186
+ yield page.records;
1031
1187
  }
1032
1188
  }
1033
1189
  async getMany(options = {}) {
1034
- const { records } = await this.getPaginated(options);
1035
- return records;
1190
+ const page = await this.getPaginated(options);
1191
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1192
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1193
+ }
1194
+ return page.records;
1036
1195
  }
1037
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1196
+ async getAll(options = {}) {
1197
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1038
1198
  const results = [];
1039
- for await (const page of this.getIterator(chunk, options)) {
1199
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1040
1200
  results.push(...page);
1041
1201
  }
1042
1202
  return results;
1043
1203
  }
1044
1204
  async getFirst(options = {}) {
1045
- const records = await this.getMany({ ...options, page: { size: 1 } });
1046
- return records[0] || null;
1205
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1206
+ return records[0] ?? null;
1047
1207
  }
1048
1208
  cache(ttl) {
1049
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
1209
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1050
1210
  }
1051
1211
  nextPage(size, offset) {
1052
1212
  return this.firstPage(size, offset);
@@ -1055,10 +1215,10 @@ const _Query = class {
1055
1215
  return this.firstPage(size, offset);
1056
1216
  }
1057
1217
  firstPage(size, offset) {
1058
- return this.getPaginated({ page: { size, offset } });
1218
+ return this.getPaginated({ pagination: { size, offset } });
1059
1219
  }
1060
1220
  lastPage(size, offset) {
1061
- return this.getPaginated({ page: { size, offset, before: "end" } });
1221
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1062
1222
  }
1063
1223
  hasNextPage() {
1064
1224
  return this.meta.page.more;
@@ -1068,12 +1228,20 @@ let Query = _Query;
1068
1228
  _table$1 = new WeakMap();
1069
1229
  _repository = new WeakMap();
1070
1230
  _data = new WeakMap();
1231
+ function cleanParent(data, parent) {
1232
+ if (isCursorPaginationOptions(data.pagination)) {
1233
+ return { ...parent, sorting: void 0, filter: void 0 };
1234
+ }
1235
+ return parent;
1236
+ }
1071
1237
 
1072
1238
  function isIdentifiable(x) {
1073
1239
  return isObject(x) && isString(x?.id);
1074
1240
  }
1075
1241
  function isXataRecord(x) {
1076
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1242
+ const record = x;
1243
+ const metadata = record?.getMetadata();
1244
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1077
1245
  }
1078
1246
 
1079
1247
  function isSortFilterString(value) {
@@ -1103,7 +1271,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1103
1271
  if (!member.has(obj))
1104
1272
  throw TypeError("Cannot " + msg);
1105
1273
  };
1106
- var __privateGet$3 = (obj, member, getter) => {
1274
+ var __privateGet$4 = (obj, member, getter) => {
1107
1275
  __accessCheck$4(obj, member, "read from private field");
1108
1276
  return getter ? getter.call(obj) : member.get(obj);
1109
1277
  };
@@ -1112,7 +1280,7 @@ var __privateAdd$4 = (obj, member, value) => {
1112
1280
  throw TypeError("Cannot add the same private member more than once");
1113
1281
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1114
1282
  };
1115
- var __privateSet$2 = (obj, member, value, setter) => {
1283
+ var __privateSet$4 = (obj, member, value, setter) => {
1116
1284
  __accessCheck$4(obj, member, "write to private field");
1117
1285
  setter ? setter.call(obj, value) : member.set(obj, value);
1118
1286
  return value;
@@ -1121,7 +1289,7 @@ var __privateMethod$2 = (obj, member, method) => {
1121
1289
  __accessCheck$4(obj, member, "access private method");
1122
1290
  return method;
1123
1291
  };
1124
- var _table, _links, _getFetchProps, _cache, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn;
1292
+ 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;
1125
1293
  class Repository extends Query {
1126
1294
  }
1127
1295
  class RestRepository extends Query {
@@ -1138,18 +1306,21 @@ class RestRepository extends Query {
1138
1306
  __privateAdd$4(this, _getCacheRecord);
1139
1307
  __privateAdd$4(this, _setCacheQuery);
1140
1308
  __privateAdd$4(this, _getCacheQuery);
1309
+ __privateAdd$4(this, _getSchemaTables$1);
1141
1310
  __privateAdd$4(this, _table, void 0);
1142
- __privateAdd$4(this, _links, void 0);
1143
1311
  __privateAdd$4(this, _getFetchProps, void 0);
1144
1312
  __privateAdd$4(this, _cache, void 0);
1145
- __privateSet$2(this, _table, options.table);
1146
- __privateSet$2(this, _links, options.links ?? {});
1147
- __privateSet$2(this, _getFetchProps, options.pluginOptions.getFetchProps);
1313
+ __privateAdd$4(this, _schemaTables$2, void 0);
1314
+ __privateSet$4(this, _table, options.table);
1315
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1148
1316
  this.db = options.db;
1149
- __privateSet$2(this, _cache, options.pluginOptions.cache);
1317
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1318
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1150
1319
  }
1151
1320
  async create(a, b) {
1152
1321
  if (Array.isArray(a)) {
1322
+ if (a.length === 0)
1323
+ return [];
1153
1324
  const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1154
1325
  await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1155
1326
  return records;
@@ -1175,26 +1346,38 @@ class RestRepository extends Query {
1175
1346
  }
1176
1347
  throw new Error("Invalid arguments for create method");
1177
1348
  }
1178
- async read(recordId) {
1179
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1180
- if (cacheRecord)
1181
- return cacheRecord;
1182
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1183
- try {
1184
- const response = await getRecord({
1185
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1186
- ...fetchProps
1187
- });
1188
- return initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), response);
1189
- } catch (e) {
1190
- if (isObject(e) && e.status === 404) {
1191
- return null;
1349
+ async read(a) {
1350
+ if (Array.isArray(a)) {
1351
+ if (a.length === 0)
1352
+ return [];
1353
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1354
+ return this.getAll({ filter: { id: { $any: ids } } });
1355
+ }
1356
+ const id = isString(a) ? a : a.id;
1357
+ if (isString(id)) {
1358
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1359
+ if (cacheRecord)
1360
+ return cacheRecord;
1361
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1362
+ try {
1363
+ const response = await getRecord({
1364
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1365
+ ...fetchProps
1366
+ });
1367
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1368
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1369
+ } catch (e) {
1370
+ if (isObject(e) && e.status === 404) {
1371
+ return null;
1372
+ }
1373
+ throw e;
1192
1374
  }
1193
- throw e;
1194
1375
  }
1195
1376
  }
1196
1377
  async update(a, b) {
1197
1378
  if (Array.isArray(a)) {
1379
+ if (a.length === 0)
1380
+ return [];
1198
1381
  if (a.length > 100) {
1199
1382
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1200
1383
  }
@@ -1216,6 +1399,8 @@ class RestRepository extends Query {
1216
1399
  }
1217
1400
  async createOrUpdate(a, b) {
1218
1401
  if (Array.isArray(a)) {
1402
+ if (a.length === 0)
1403
+ return [];
1219
1404
  if (a.length > 100) {
1220
1405
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1221
1406
  }
@@ -1237,6 +1422,8 @@ class RestRepository extends Query {
1237
1422
  }
1238
1423
  async delete(a) {
1239
1424
  if (Array.isArray(a)) {
1425
+ if (a.length === 0)
1426
+ return;
1240
1427
  if (a.length > 100) {
1241
1428
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1242
1429
  }
@@ -1256,13 +1443,19 @@ class RestRepository extends Query {
1256
1443
  throw new Error("Invalid arguments for delete method");
1257
1444
  }
1258
1445
  async search(query, options = {}) {
1259
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1260
- const { records } = await searchBranch({
1261
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1262
- body: { tables: [__privateGet$3(this, _table)], query, fuzziness: options.fuzziness },
1446
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1447
+ const { records } = await searchTable({
1448
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1449
+ body: {
1450
+ query,
1451
+ fuzziness: options.fuzziness,
1452
+ highlight: options.highlight,
1453
+ filter: options.filter
1454
+ },
1263
1455
  ...fetchProps
1264
1456
  });
1265
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), item));
1457
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1458
+ return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1266
1459
  }
1267
1460
  async query(query) {
1268
1461
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
@@ -1271,34 +1464,35 @@ class RestRepository extends Query {
1271
1464
  const data = query.getQueryOptions();
1272
1465
  const body = {
1273
1466
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1274
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1275
- page: data.page,
1467
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1468
+ page: data.pagination,
1276
1469
  columns: data.columns
1277
1470
  };
1278
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1471
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1279
1472
  const { meta, records: objects } = await queryTable({
1280
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1473
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1281
1474
  body,
1282
1475
  ...fetchProps
1283
1476
  });
1284
- const records = objects.map((record) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), record));
1477
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1478
+ const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1285
1479
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1286
1480
  return new Page(query, meta, records);
1287
1481
  }
1288
1482
  }
1289
1483
  _table = new WeakMap();
1290
- _links = new WeakMap();
1291
1484
  _getFetchProps = new WeakMap();
1292
1485
  _cache = new WeakMap();
1486
+ _schemaTables$2 = new WeakMap();
1293
1487
  _insertRecordWithoutId = new WeakSet();
1294
1488
  insertRecordWithoutId_fn = async function(object) {
1295
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1489
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1296
1490
  const record = transformObjectLinks(object);
1297
1491
  const response = await insertRecord({
1298
1492
  pathParams: {
1299
1493
  workspace: "{workspaceId}",
1300
1494
  dbBranchName: "{dbBranch}",
1301
- tableName: __privateGet$3(this, _table)
1495
+ tableName: __privateGet$4(this, _table)
1302
1496
  },
1303
1497
  body: record,
1304
1498
  ...fetchProps
@@ -1311,13 +1505,13 @@ insertRecordWithoutId_fn = async function(object) {
1311
1505
  };
1312
1506
  _insertRecordWithId = new WeakSet();
1313
1507
  insertRecordWithId_fn = async function(recordId, object) {
1314
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1508
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1315
1509
  const record = transformObjectLinks(object);
1316
1510
  const response = await insertRecordWithID({
1317
1511
  pathParams: {
1318
1512
  workspace: "{workspaceId}",
1319
1513
  dbBranchName: "{dbBranch}",
1320
- tableName: __privateGet$3(this, _table),
1514
+ tableName: __privateGet$4(this, _table),
1321
1515
  recordId
1322
1516
  },
1323
1517
  body: record,
@@ -1332,25 +1526,29 @@ insertRecordWithId_fn = async function(recordId, object) {
1332
1526
  };
1333
1527
  _bulkInsertTableRecords = new WeakSet();
1334
1528
  bulkInsertTableRecords_fn = async function(objects) {
1335
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1529
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1336
1530
  const records = objects.map((object) => transformObjectLinks(object));
1337
- const response = await bulkInsertTableRecords({
1338
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1531
+ const { recordIDs } = await bulkInsertTableRecords({
1532
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1339
1533
  body: { records },
1340
1534
  ...fetchProps
1341
1535
  });
1342
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1536
+ const finalObjects = await this.read(recordIDs);
1343
1537
  if (finalObjects.length !== objects.length) {
1344
1538
  throw new Error("The server failed to save some records");
1345
1539
  }
1346
- return finalObjects;
1540
+ const dictionary = finalObjects.reduce((acc, object) => {
1541
+ acc[object.id] = object;
1542
+ return acc;
1543
+ }, {});
1544
+ return recordIDs.map((id) => dictionary[id]);
1347
1545
  };
1348
1546
  _updateRecordWithID = new WeakSet();
1349
1547
  updateRecordWithID_fn = async function(recordId, object) {
1350
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1548
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1351
1549
  const record = transformObjectLinks(object);
1352
1550
  const response = await updateRecordWithID({
1353
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1551
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1354
1552
  body: record,
1355
1553
  ...fetchProps
1356
1554
  });
@@ -1361,9 +1559,9 @@ updateRecordWithID_fn = async function(recordId, object) {
1361
1559
  };
1362
1560
  _upsertRecordWithID = new WeakSet();
1363
1561
  upsertRecordWithID_fn = async function(recordId, object) {
1364
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1562
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1365
1563
  const response = await upsertRecordWithID({
1366
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1564
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1367
1565
  body: object,
1368
1566
  ...fetchProps
1369
1567
  });
@@ -1374,51 +1572,63 @@ upsertRecordWithID_fn = async function(recordId, object) {
1374
1572
  };
1375
1573
  _deleteRecord = new WeakSet();
1376
1574
  deleteRecord_fn = async function(recordId) {
1377
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1575
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1378
1576
  await deleteRecord({
1379
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1577
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1380
1578
  ...fetchProps
1381
1579
  });
1382
1580
  };
1383
1581
  _invalidateCache = new WeakSet();
1384
1582
  invalidateCache_fn = async function(recordId) {
1385
- await __privateGet$3(this, _cache).delete(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1386
- const cacheItems = await __privateGet$3(this, _cache).getAll();
1583
+ await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1584
+ const cacheItems = await __privateGet$4(this, _cache).getAll();
1387
1585
  const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1388
1586
  for (const [key, value] of queries) {
1389
1587
  const ids = getIds(value);
1390
1588
  if (ids.includes(recordId))
1391
- await __privateGet$3(this, _cache).delete(key);
1589
+ await __privateGet$4(this, _cache).delete(key);
1392
1590
  }
1393
1591
  };
1394
1592
  _setCacheRecord = new WeakSet();
1395
1593
  setCacheRecord_fn = async function(record) {
1396
- if (!__privateGet$3(this, _cache).cacheRecords)
1594
+ if (!__privateGet$4(this, _cache).cacheRecords)
1397
1595
  return;
1398
- await __privateGet$3(this, _cache).set(`rec_${__privateGet$3(this, _table)}:${record.id}`, record);
1596
+ await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1399
1597
  };
1400
1598
  _getCacheRecord = new WeakSet();
1401
1599
  getCacheRecord_fn = async function(recordId) {
1402
- if (!__privateGet$3(this, _cache).cacheRecords)
1600
+ if (!__privateGet$4(this, _cache).cacheRecords)
1403
1601
  return null;
1404
- return __privateGet$3(this, _cache).get(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1602
+ return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1405
1603
  };
1406
1604
  _setCacheQuery = new WeakSet();
1407
1605
  setCacheQuery_fn = async function(query, meta, records) {
1408
- await __privateGet$3(this, _cache).set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1606
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1409
1607
  };
1410
1608
  _getCacheQuery = new WeakSet();
1411
1609
  getCacheQuery_fn = async function(query) {
1412
- const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
1413
- const result = await __privateGet$3(this, _cache).get(key);
1610
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1611
+ const result = await __privateGet$4(this, _cache).get(key);
1414
1612
  if (!result)
1415
1613
  return null;
1416
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1417
- if (!ttl || ttl < 0)
1418
- return result;
1614
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1615
+ if (ttl < 0)
1616
+ return null;
1419
1617
  const hasExpired = result.date.getTime() + ttl < Date.now();
1420
1618
  return hasExpired ? null : result;
1421
1619
  };
1620
+ _getSchemaTables$1 = new WeakSet();
1621
+ getSchemaTables_fn$1 = async function() {
1622
+ if (__privateGet$4(this, _schemaTables$2))
1623
+ return __privateGet$4(this, _schemaTables$2);
1624
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1625
+ const { schema } = await getBranchDetails({
1626
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1627
+ ...fetchProps
1628
+ });
1629
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1630
+ return schema.tables;
1631
+ };
1422
1632
  const transformObjectLinks = (object) => {
1423
1633
  return Object.entries(object).reduce((acc, [key, value]) => {
1424
1634
  if (key === "xata")
@@ -1426,15 +1636,34 @@ const transformObjectLinks = (object) => {
1426
1636
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1427
1637
  }, {});
1428
1638
  };
1429
- const initObject = (db, links, table, object) => {
1639
+ const initObject = (db, schemaTables, table, object) => {
1430
1640
  const result = {};
1431
- Object.assign(result, object);
1432
- const tableLinks = links[table] || [];
1433
- for (const link of tableLinks) {
1434
- const [field, linkTable] = link;
1435
- const value = result[field];
1436
- if (value && isObject(value)) {
1437
- result[field] = initObject(db, links, linkTable, value);
1641
+ const { xata, ...rest } = object ?? {};
1642
+ Object.assign(result, rest);
1643
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1644
+ if (!columns)
1645
+ console.error(`Table ${table} not found in schema`);
1646
+ for (const column of columns ?? []) {
1647
+ const value = result[column.name];
1648
+ switch (column.type) {
1649
+ case "datetime": {
1650
+ const date = value !== void 0 ? new Date(value) : void 0;
1651
+ if (date && isNaN(date.getTime())) {
1652
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1653
+ } else if (date) {
1654
+ result[column.name] = date;
1655
+ }
1656
+ break;
1657
+ }
1658
+ case "link": {
1659
+ const linkTable = column.link?.table;
1660
+ if (!linkTable) {
1661
+ console.error(`Failed to parse link for field ${column.name}`);
1662
+ } else if (isObject(value)) {
1663
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1664
+ }
1665
+ break;
1666
+ }
1438
1667
  }
1439
1668
  }
1440
1669
  result.read = function() {
@@ -1446,7 +1675,10 @@ const initObject = (db, links, table, object) => {
1446
1675
  result.delete = function() {
1447
1676
  return db[table].delete(result["id"]);
1448
1677
  };
1449
- for (const prop of ["read", "update", "delete"]) {
1678
+ result.getMetadata = function() {
1679
+ return xata;
1680
+ };
1681
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1450
1682
  Object.defineProperty(result, prop, { enumerable: false });
1451
1683
  }
1452
1684
  Object.freeze(result);
@@ -1466,7 +1698,7 @@ var __accessCheck$3 = (obj, member, msg) => {
1466
1698
  if (!member.has(obj))
1467
1699
  throw TypeError("Cannot " + msg);
1468
1700
  };
1469
- var __privateGet$2 = (obj, member, getter) => {
1701
+ var __privateGet$3 = (obj, member, getter) => {
1470
1702
  __accessCheck$3(obj, member, "read from private field");
1471
1703
  return getter ? getter.call(obj) : member.get(obj);
1472
1704
  };
@@ -1475,7 +1707,7 @@ var __privateAdd$3 = (obj, member, value) => {
1475
1707
  throw TypeError("Cannot add the same private member more than once");
1476
1708
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1477
1709
  };
1478
- var __privateSet$1 = (obj, member, value, setter) => {
1710
+ var __privateSet$3 = (obj, member, value, setter) => {
1479
1711
  __accessCheck$3(obj, member, "write to private field");
1480
1712
  setter ? setter.call(obj, value) : member.set(obj, value);
1481
1713
  return value;
@@ -1484,30 +1716,30 @@ var _map;
1484
1716
  class SimpleCache {
1485
1717
  constructor(options = {}) {
1486
1718
  __privateAdd$3(this, _map, void 0);
1487
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
1719
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1488
1720
  this.capacity = options.max ?? 500;
1489
1721
  this.cacheRecords = options.cacheRecords ?? true;
1490
1722
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1491
1723
  }
1492
1724
  async getAll() {
1493
- return Object.fromEntries(__privateGet$2(this, _map));
1725
+ return Object.fromEntries(__privateGet$3(this, _map));
1494
1726
  }
1495
1727
  async get(key) {
1496
- return __privateGet$2(this, _map).get(key) ?? null;
1728
+ return __privateGet$3(this, _map).get(key) ?? null;
1497
1729
  }
1498
1730
  async set(key, value) {
1499
1731
  await this.delete(key);
1500
- __privateGet$2(this, _map).set(key, value);
1501
- if (__privateGet$2(this, _map).size > this.capacity) {
1502
- const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
1732
+ __privateGet$3(this, _map).set(key, value);
1733
+ if (__privateGet$3(this, _map).size > this.capacity) {
1734
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1503
1735
  await this.delete(leastRecentlyUsed);
1504
1736
  }
1505
1737
  }
1506
1738
  async delete(key) {
1507
- __privateGet$2(this, _map).delete(key);
1739
+ __privateGet$3(this, _map).delete(key);
1508
1740
  }
1509
1741
  async clear() {
1510
- return __privateGet$2(this, _map).clear();
1742
+ return __privateGet$3(this, _map).clear();
1511
1743
  }
1512
1744
  }
1513
1745
  _map = new WeakMap();
@@ -1535,7 +1767,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1535
1767
  if (!member.has(obj))
1536
1768
  throw TypeError("Cannot " + msg);
1537
1769
  };
1538
- var __privateGet$1 = (obj, member, getter) => {
1770
+ var __privateGet$2 = (obj, member, getter) => {
1539
1771
  __accessCheck$2(obj, member, "read from private field");
1540
1772
  return getter ? getter.call(obj) : member.get(obj);
1541
1773
  };
@@ -1544,122 +1776,158 @@ var __privateAdd$2 = (obj, member, value) => {
1544
1776
  throw TypeError("Cannot add the same private member more than once");
1545
1777
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1546
1778
  };
1547
- var _tables;
1779
+ var __privateSet$2 = (obj, member, value, setter) => {
1780
+ __accessCheck$2(obj, member, "write to private field");
1781
+ setter ? setter.call(obj, value) : member.set(obj, value);
1782
+ return value;
1783
+ };
1784
+ var _tables, _schemaTables$1;
1548
1785
  class SchemaPlugin extends XataPlugin {
1549
- constructor(links, tableNames) {
1786
+ constructor(schemaTables) {
1550
1787
  super();
1551
- this.links = links;
1552
- this.tableNames = tableNames;
1553
1788
  __privateAdd$2(this, _tables, {});
1789
+ __privateAdd$2(this, _schemaTables$1, void 0);
1790
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1554
1791
  }
1555
1792
  build(pluginOptions) {
1556
- const links = this.links;
1557
1793
  const db = new Proxy({}, {
1558
1794
  get: (_target, table) => {
1559
1795
  if (!isString(table))
1560
1796
  throw new Error("Invalid table name");
1561
- if (!__privateGet$1(this, _tables)[table]) {
1562
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, links });
1797
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1798
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1563
1799
  }
1564
- return __privateGet$1(this, _tables)[table];
1800
+ return __privateGet$2(this, _tables)[table];
1565
1801
  }
1566
1802
  });
1567
- for (const table of this.tableNames ?? []) {
1568
- db[table] = new RestRepository({ db, pluginOptions, table, links });
1803
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1804
+ for (const table of tableNames) {
1805
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1569
1806
  }
1570
1807
  return db;
1571
1808
  }
1572
1809
  }
1573
1810
  _tables = new WeakMap();
1811
+ _schemaTables$1 = new WeakMap();
1574
1812
 
1575
1813
  var __accessCheck$1 = (obj, member, msg) => {
1576
1814
  if (!member.has(obj))
1577
1815
  throw TypeError("Cannot " + msg);
1578
1816
  };
1817
+ var __privateGet$1 = (obj, member, getter) => {
1818
+ __accessCheck$1(obj, member, "read from private field");
1819
+ return getter ? getter.call(obj) : member.get(obj);
1820
+ };
1579
1821
  var __privateAdd$1 = (obj, member, value) => {
1580
1822
  if (member.has(obj))
1581
1823
  throw TypeError("Cannot add the same private member more than once");
1582
1824
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1583
1825
  };
1826
+ var __privateSet$1 = (obj, member, value, setter) => {
1827
+ __accessCheck$1(obj, member, "write to private field");
1828
+ setter ? setter.call(obj, value) : member.set(obj, value);
1829
+ return value;
1830
+ };
1584
1831
  var __privateMethod$1 = (obj, member, method) => {
1585
1832
  __accessCheck$1(obj, member, "access private method");
1586
1833
  return method;
1587
1834
  };
1588
- var _search, search_fn;
1835
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1589
1836
  class SearchPlugin extends XataPlugin {
1590
- constructor(db, links) {
1837
+ constructor(db, schemaTables) {
1591
1838
  super();
1592
1839
  this.db = db;
1593
- this.links = links;
1594
1840
  __privateAdd$1(this, _search);
1841
+ __privateAdd$1(this, _getSchemaTables);
1842
+ __privateAdd$1(this, _schemaTables, void 0);
1843
+ __privateSet$1(this, _schemaTables, schemaTables);
1595
1844
  }
1596
1845
  build({ getFetchProps }) {
1597
1846
  return {
1598
1847
  all: async (query, options = {}) => {
1599
1848
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1849
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1600
1850
  return records.map((record) => {
1601
1851
  const { table = "orphan" } = record.xata;
1602
- return { table, record: initObject(this.db, this.links, table, record) };
1852
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1603
1853
  });
1604
1854
  },
1605
1855
  byTable: async (query, options = {}) => {
1606
1856
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1857
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1607
1858
  return records.reduce((acc, record) => {
1608
1859
  const { table = "orphan" } = record.xata;
1609
1860
  const items = acc[table] ?? [];
1610
- const item = initObject(this.db, this.links, table, record);
1861
+ const item = initObject(this.db, schemaTables, table, record);
1611
1862
  return { ...acc, [table]: [...items, item] };
1612
1863
  }, {});
1613
1864
  }
1614
1865
  };
1615
1866
  }
1616
1867
  }
1868
+ _schemaTables = new WeakMap();
1617
1869
  _search = new WeakSet();
1618
1870
  search_fn = async function(query, options, getFetchProps) {
1619
1871
  const fetchProps = await getFetchProps();
1620
- const { tables, fuzziness } = options ?? {};
1872
+ const { tables, fuzziness, highlight } = options ?? {};
1621
1873
  const { records } = await searchBranch({
1622
1874
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1623
- body: { tables, query, fuzziness },
1875
+ body: { tables, query, fuzziness, highlight },
1624
1876
  ...fetchProps
1625
1877
  });
1626
1878
  return records;
1627
1879
  };
1880
+ _getSchemaTables = new WeakSet();
1881
+ getSchemaTables_fn = async function(getFetchProps) {
1882
+ if (__privateGet$1(this, _schemaTables))
1883
+ return __privateGet$1(this, _schemaTables);
1884
+ const fetchProps = await getFetchProps();
1885
+ const { schema } = await getBranchDetails({
1886
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1887
+ ...fetchProps
1888
+ });
1889
+ __privateSet$1(this, _schemaTables, schema.tables);
1890
+ return schema.tables;
1891
+ };
1628
1892
 
1629
1893
  const isBranchStrategyBuilder = (strategy) => {
1630
1894
  return typeof strategy === "function";
1631
1895
  };
1632
1896
 
1633
- const envBranchNames = [
1634
- "XATA_BRANCH",
1635
- "VERCEL_GIT_COMMIT_REF",
1636
- "CF_PAGES_BRANCH",
1637
- "BRANCH"
1638
- ];
1639
- const defaultBranch = "main";
1640
1897
  async function getCurrentBranchName(options) {
1641
- const env = await getBranchByEnvVariable();
1642
- if (env)
1643
- return env;
1644
- const branch = await getGitBranch();
1645
- if (!branch)
1646
- return defaultBranch;
1647
- const details = await getDatabaseBranch(branch, options);
1648
- if (details)
1649
- return branch;
1650
- return defaultBranch;
1898
+ const { branch } = getEnvironment();
1899
+ if (branch) {
1900
+ const details = await getDatabaseBranch(branch, options);
1901
+ if (details)
1902
+ return branch;
1903
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1904
+ }
1905
+ const gitBranch = await getGitBranch();
1906
+ return resolveXataBranch(gitBranch, options);
1651
1907
  }
1652
1908
  async function getCurrentBranchDetails(options) {
1653
- const env = await getBranchByEnvVariable();
1654
- if (env)
1655
- return getDatabaseBranch(env, options);
1656
- const branch = await getGitBranch();
1657
- if (!branch)
1658
- return getDatabaseBranch(defaultBranch, options);
1659
- const details = await getDatabaseBranch(branch, options);
1660
- if (details)
1661
- return details;
1662
- return getDatabaseBranch(defaultBranch, options);
1909
+ const branch = await getCurrentBranchName(options);
1910
+ return getDatabaseBranch(branch, options);
1911
+ }
1912
+ async function resolveXataBranch(gitBranch, options) {
1913
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1914
+ const apiKey = options?.apiKey || getAPIKey();
1915
+ if (!databaseURL)
1916
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1917
+ if (!apiKey)
1918
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1919
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1920
+ const [workspace] = host.split(".");
1921
+ const { fallbackBranch } = getEnvironment();
1922
+ const { branch } = await resolveBranch({
1923
+ apiKey,
1924
+ apiUrl: databaseURL,
1925
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1926
+ workspacesApiUrl: `${protocol}//${host}`,
1927
+ pathParams: { dbName, workspace },
1928
+ queryParams: { gitBranch, fallbackBranch }
1929
+ });
1930
+ return branch;
1663
1931
  }
1664
1932
  async function getDatabaseBranch(branch, options) {
1665
1933
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1677,10 +1945,7 @@ async function getDatabaseBranch(branch, options) {
1677
1945
  apiUrl: databaseURL,
1678
1946
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1679
1947
  workspacesApiUrl: `${protocol}//${host}`,
1680
- pathParams: {
1681
- dbBranchName,
1682
- workspace
1683
- }
1948
+ pathParams: { dbBranchName, workspace }
1684
1949
  });
1685
1950
  } catch (err) {
1686
1951
  if (isObject(err) && err.status === 404)
@@ -1688,21 +1953,10 @@ async function getDatabaseBranch(branch, options) {
1688
1953
  throw err;
1689
1954
  }
1690
1955
  }
1691
- function getBranchByEnvVariable() {
1692
- for (const name of envBranchNames) {
1693
- const value = getEnvVariable(name);
1694
- if (value) {
1695
- return value;
1696
- }
1697
- }
1698
- try {
1699
- return XATA_BRANCH;
1700
- } catch (err) {
1701
- }
1702
- }
1703
1956
  function getDatabaseURL() {
1704
1957
  try {
1705
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1958
+ const { databaseURL } = getEnvironment();
1959
+ return databaseURL;
1706
1960
  } catch (err) {
1707
1961
  return void 0;
1708
1962
  }
@@ -1733,7 +1987,7 @@ var __privateMethod = (obj, member, method) => {
1733
1987
  const buildClient = (plugins) => {
1734
1988
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1735
1989
  return _a = class {
1736
- constructor(options = {}, links, tables) {
1990
+ constructor(options = {}, schemaTables) {
1737
1991
  __privateAdd(this, _parseOptions);
1738
1992
  __privateAdd(this, _getFetchProps);
1739
1993
  __privateAdd(this, _evaluateBranch);
@@ -1743,12 +1997,12 @@ const buildClient = (plugins) => {
1743
1997
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1744
1998
  cache: safeOptions.cache
1745
1999
  };
1746
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1747
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
2000
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2001
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1748
2002
  this.db = db;
1749
2003
  this.search = search;
1750
2004
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1751
- if (!namespace)
2005
+ if (namespace === void 0)
1752
2006
  continue;
1753
2007
  const result = namespace.build(pluginOptions);
1754
2008
  if (result instanceof Promise) {
@@ -1765,7 +2019,7 @@ const buildClient = (plugins) => {
1765
2019
  const databaseURL = options?.databaseURL || getDatabaseURL();
1766
2020
  const apiKey = options?.apiKey || getAPIKey();
1767
2021
  const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1768
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2022
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1769
2023
  if (!databaseURL || !apiKey) {
1770
2024
  throw new Error("Options databaseURL and apiKey are required");
1771
2025
  }
@@ -1792,7 +2046,7 @@ const buildClient = (plugins) => {
1792
2046
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1793
2047
  if (__privateGet(this, _branch))
1794
2048
  return __privateGet(this, _branch);
1795
- if (!param)
2049
+ if (param === void 0)
1796
2050
  return void 0;
1797
2051
  const strategies = Array.isArray(param) ? [...param] : [param];
1798
2052
  const evaluateBranch = async (strategy) => {
@@ -1817,5 +2071,5 @@ class XataError extends Error {
1817
2071
  }
1818
2072
  }
1819
2073
 
1820
- 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, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchema, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, 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, updateBranchSchema, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2074
+ 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, updateWorkspaceMemberRole, upsertRecordWithID };
1821
2075
  //# sourceMappingURL=index.mjs.map