@xata.io/client 0.8.3 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -16,15 +16,14 @@ function isString(value) {
16
16
  }
17
17
 
18
18
  function getEnvVariable(name) {
19
- var _a, _b;
20
19
  try {
21
- if (isObject(process) && isString((_a = process == null ? void 0 : process.env) == null ? void 0 : _a[name])) {
20
+ if (isObject(process) && isString(process?.env?.[name])) {
22
21
  return process.env[name];
23
22
  }
24
23
  } catch (err) {
25
24
  }
26
25
  try {
27
- if (isObject(Deno) && isString((_b = Deno == null ? void 0 : Deno.env) == null ? void 0 : _b.get(name))) {
26
+ if (isObject(Deno) && isString(Deno?.env?.get(name))) {
28
27
  return Deno.env.get(name);
29
28
  }
30
29
  } catch (err) {
@@ -48,99 +47,51 @@ async function getGitBranch() {
48
47
  }
49
48
  }
50
49
 
50
+ function getAPIKey() {
51
+ try {
52
+ return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
53
+ } catch (err) {
54
+ return void 0;
55
+ }
56
+ }
57
+
51
58
  function getFetchImplementation(userFetch) {
52
59
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
53
- const fetchImpl = userFetch != null ? userFetch : globalFetch;
60
+ const fetchImpl = userFetch ?? globalFetch;
54
61
  if (!fetchImpl) {
55
62
  throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
56
63
  }
57
64
  return fetchImpl;
58
65
  }
59
66
 
60
- const envBranchNames = [
61
- "XATA_BRANCH",
62
- "VERCEL_GIT_COMMIT_REF",
63
- "CF_PAGES_BRANCH",
64
- "BRANCH"
65
- ];
66
- const defaultBranch = "main";
67
- async function getCurrentBranchName(options) {
68
- const env = await getBranchByEnvVariable();
69
- if (env)
70
- return env;
71
- const branch = await getGitBranch();
72
- if (!branch)
73
- return defaultBranch;
74
- const details = await getDatabaseBranch(branch, options);
75
- if (details)
76
- return branch;
77
- return defaultBranch;
78
- }
79
- async function getCurrentBranchDetails(options) {
80
- const env = await getBranchByEnvVariable();
81
- if (env)
82
- return getDatabaseBranch(env, options);
83
- const branch = await getGitBranch();
84
- if (!branch)
85
- return getDatabaseBranch(defaultBranch, options);
86
- const details = await getDatabaseBranch(branch, options);
87
- if (details)
88
- return details;
89
- return getDatabaseBranch(defaultBranch, options);
90
- }
91
- async function getDatabaseBranch(branch, options) {
92
- const databaseURL = (options == null ? void 0 : options.databaseURL) || getDatabaseURL();
93
- const apiKey = (options == null ? void 0 : options.apiKey) || getAPIKey();
94
- if (!databaseURL)
95
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
96
- if (!apiKey)
97
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
98
- const [protocol, , host, , database] = databaseURL.split("/");
99
- const [workspace] = host.split(".");
100
- const dbBranchName = `${database}:${branch}`;
101
- try {
102
- return await getBranchDetails({
103
- apiKey,
104
- apiUrl: databaseURL,
105
- fetchImpl: getFetchImplementation(options == null ? void 0 : options.fetchImpl),
106
- workspacesApiUrl: `${protocol}//${host}`,
107
- pathParams: {
108
- dbBranchName,
109
- workspace
110
- }
111
- });
112
- } catch (err) {
113
- if (isObject(err) && err.status === 404)
114
- return null;
115
- throw err;
116
- }
117
- }
118
- function getBranchByEnvVariable() {
119
- for (const name of envBranchNames) {
120
- const value = getEnvVariable(name);
121
- if (value) {
122
- return value;
67
+ class FetcherError extends Error {
68
+ constructor(status, data) {
69
+ super(getMessage(data));
70
+ this.status = status;
71
+ this.errors = isBulkError(data) ? data.errors : void 0;
72
+ if (data instanceof Error) {
73
+ this.stack = data.stack;
74
+ this.cause = data.cause;
123
75
  }
124
76
  }
125
- try {
126
- return XATA_BRANCH;
127
- } catch (err) {
128
- }
129
77
  }
130
- function getDatabaseURL() {
131
- var _a;
132
- try {
133
- return (_a = getEnvVariable("XATA_DATABASE_URL")) != null ? _a : XATA_DATABASE_URL;
134
- } catch (err) {
135
- return void 0;
136
- }
78
+ function isBulkError(error) {
79
+ return isObject(error) && Array.isArray(error.errors);
137
80
  }
138
- function getAPIKey() {
139
- var _a;
140
- try {
141
- return (_a = getEnvVariable("XATA_API_KEY")) != null ? _a : XATA_API_KEY;
142
- } catch (err) {
143
- return void 0;
81
+ function isErrorWithMessage(error) {
82
+ return isObject(error) && isString(error.message);
83
+ }
84
+ function getMessage(data) {
85
+ if (data instanceof Error) {
86
+ return data.message;
87
+ } else if (isString(data)) {
88
+ return data;
89
+ } else if (isErrorWithMessage(data)) {
90
+ return data.message;
91
+ } else if (isBulkError(data)) {
92
+ return "Bulk operation failed";
93
+ } else {
94
+ return "Unexpected error";
144
95
  }
145
96
  }
146
97
 
@@ -155,16 +106,15 @@ function buildBaseUrl({
155
106
  apiUrl,
156
107
  pathParams
157
108
  }) {
158
- if (!(pathParams == null ? void 0 : pathParams.workspace))
109
+ if (!pathParams?.workspace)
159
110
  return `${apiUrl}${path}`;
160
111
  const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
161
112
  return url.replace("{workspaceId}", pathParams.workspace);
162
113
  }
163
114
  function hostHeader(url) {
164
- var _a;
165
115
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
166
- const { groups } = (_a = pattern.exec(url)) != null ? _a : {};
167
- return (groups == null ? void 0 : groups.host) ? { Host: groups.host } : {};
116
+ const { groups } = pattern.exec(url) ?? {};
117
+ return groups?.host ? { Host: groups.host } : {};
168
118
  }
169
119
  async function fetch$1({
170
120
  url: path,
@@ -199,33 +149,20 @@ async function fetch$1({
199
149
  if (response.ok) {
200
150
  return jsonResponse;
201
151
  }
202
- const { message = "Unknown error", errors } = jsonResponse;
203
- throw new FetcherError({ message, status: response.status, errors });
152
+ throw new FetcherError(response.status, jsonResponse);
204
153
  } catch (error) {
205
- const message = hasMessage(error) ? error.message : "Unknown network error";
206
- const parent = error instanceof Error ? error : void 0;
207
- throw new FetcherError({ message, status: response.status }, parent);
208
- }
209
- }
210
- const hasMessage = (error) => {
211
- return isObject(error) && isString(error.message);
212
- };
213
- class FetcherError extends Error {
214
- constructor(data, parent) {
215
- super(data.message);
216
- this.status = data.status;
217
- this.errors = data.errors;
218
- if (parent) {
219
- this.stack = parent.stack;
220
- this.cause = parent.cause;
221
- }
154
+ throw new FetcherError(response.status, error);
222
155
  }
223
156
  }
224
157
 
225
158
  const getUser = (variables) => fetch$1({ url: "/user", method: "get", ...variables });
226
159
  const updateUser = (variables) => fetch$1({ url: "/user", method: "put", ...variables });
227
160
  const deleteUser = (variables) => fetch$1({ url: "/user", method: "delete", ...variables });
228
- const getUserAPIKeys = (variables) => fetch$1({ url: "/user/keys", method: "get", ...variables });
161
+ const getUserAPIKeys = (variables) => fetch$1({
162
+ url: "/user/keys",
163
+ method: "get",
164
+ ...variables
165
+ });
229
166
  const createUserAPIKey = (variables) => fetch$1({
230
167
  url: "/user/keys/{keyName}",
231
168
  method: "post",
@@ -236,8 +173,16 @@ const deleteUserAPIKey = (variables) => fetch$1({
236
173
  method: "delete",
237
174
  ...variables
238
175
  });
239
- const createWorkspace = (variables) => fetch$1({ url: "/workspaces", method: "post", ...variables });
240
- const getWorkspacesList = (variables) => fetch$1({ url: "/workspaces", method: "get", ...variables });
176
+ const createWorkspace = (variables) => fetch$1({
177
+ url: "/workspaces",
178
+ method: "post",
179
+ ...variables
180
+ });
181
+ const getWorkspacesList = (variables) => fetch$1({
182
+ url: "/workspaces",
183
+ method: "get",
184
+ ...variables
185
+ });
241
186
  const getWorkspace = (variables) => fetch$1({
242
187
  url: "/workspaces/{workspaceId}",
243
188
  method: "get",
@@ -258,21 +203,13 @@ const getWorkspaceMembersList = (variables) => fetch$1({
258
203
  method: "get",
259
204
  ...variables
260
205
  });
261
- const updateWorkspaceMemberRole = (variables) => fetch$1({
262
- url: "/workspaces/{workspaceId}/members/{userId}",
263
- method: "put",
264
- ...variables
265
- });
206
+ const updateWorkspaceMemberRole = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables });
266
207
  const removeWorkspaceMember = (variables) => fetch$1({
267
208
  url: "/workspaces/{workspaceId}/members/{userId}",
268
209
  method: "delete",
269
210
  ...variables
270
211
  });
271
- const inviteWorkspaceMember = (variables) => fetch$1({
272
- url: "/workspaces/{workspaceId}/invites",
273
- method: "post",
274
- ...variables
275
- });
212
+ const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
276
213
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
277
214
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
278
215
  method: "delete",
@@ -334,16 +271,8 @@ const getBranchMetadata = (variables) => fetch$1({
334
271
  ...variables
335
272
  });
336
273
  const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
337
- const executeBranchMigrationPlan = (variables) => fetch$1({
338
- url: "/db/{dbBranchName}/migrations/execute",
339
- method: "post",
340
- ...variables
341
- });
342
- const getBranchMigrationPlan = (variables) => fetch$1({
343
- url: "/db/{dbBranchName}/migrations/plan",
344
- method: "post",
345
- ...variables
346
- });
274
+ const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
275
+ const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
347
276
  const getBranchStats = (variables) => fetch$1({
348
277
  url: "/db/{dbBranchName}/stats",
349
278
  method: "get",
@@ -417,11 +346,7 @@ const getRecord = (variables) => fetch$1({
417
346
  method: "get",
418
347
  ...variables
419
348
  });
420
- const bulkInsertTableRecords = (variables) => fetch$1({
421
- url: "/db/{dbBranchName}/tables/{tableName}/bulk",
422
- method: "post",
423
- ...variables
424
- });
349
+ const bulkInsertTableRecords = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables });
425
350
  const queryTable = (variables) => fetch$1({
426
351
  url: "/db/{dbBranchName}/tables/{tableName}/query",
427
352
  method: "post",
@@ -531,12 +456,11 @@ var __privateSet$4 = (obj, member, value, setter) => {
531
456
  };
532
457
  var _extraProps, _namespaces;
533
458
  class XataApiClient {
534
- constructor(options) {
459
+ constructor(options = {}) {
535
460
  __privateAdd$6(this, _extraProps, void 0);
536
461
  __privateAdd$6(this, _namespaces, {});
537
- var _a, _b;
538
- const provider = (_a = options.host) != null ? _a : "production";
539
- const apiKey = (_b = options == null ? void 0 : options.apiKey) != null ? _b : getAPIKey();
462
+ const provider = options.host ?? "production";
463
+ const apiKey = options?.apiKey ?? getAPIKey();
540
464
  if (!apiKey) {
541
465
  throw new Error("Could not resolve a valid apiKey");
542
466
  }
@@ -1004,21 +928,20 @@ const _Query = class {
1004
928
  __privateAdd$4(this, _data, { filter: {} });
1005
929
  this.meta = { page: { cursor: "start", more: true } };
1006
930
  this.records = [];
1007
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
1008
931
  __privateSet$2(this, _table$1, table);
1009
932
  if (repository) {
1010
933
  __privateSet$2(this, _repository, repository);
1011
934
  } else {
1012
935
  __privateSet$2(this, _repository, this);
1013
936
  }
1014
- __privateGet$3(this, _data).filter = (_b = (_a = data.filter) != null ? _a : parent == null ? void 0 : parent.filter) != null ? _b : {};
1015
- __privateGet$3(this, _data).filter.$any = (_e = (_c = data.filter) == null ? void 0 : _c.$any) != null ? _e : (_d = parent == null ? void 0 : parent.filter) == null ? void 0 : _d.$any;
1016
- __privateGet$3(this, _data).filter.$all = (_h = (_f = data.filter) == null ? void 0 : _f.$all) != null ? _h : (_g = parent == null ? void 0 : parent.filter) == null ? void 0 : _g.$all;
1017
- __privateGet$3(this, _data).filter.$not = (_k = (_i = data.filter) == null ? void 0 : _i.$not) != null ? _k : (_j = parent == null ? void 0 : parent.filter) == null ? void 0 : _j.$not;
1018
- __privateGet$3(this, _data).filter.$none = (_n = (_l = data.filter) == null ? void 0 : _l.$none) != null ? _n : (_m = parent == null ? void 0 : parent.filter) == null ? void 0 : _m.$none;
1019
- __privateGet$3(this, _data).sort = (_o = data.sort) != null ? _o : parent == null ? void 0 : parent.sort;
1020
- __privateGet$3(this, _data).columns = (_q = (_p = data.columns) != null ? _p : parent == null ? void 0 : parent.columns) != null ? _q : ["*"];
1021
- __privateGet$3(this, _data).page = (_r = data.page) != null ? _r : parent == null ? void 0 : parent.page;
937
+ __privateGet$3(this, _data).filter = data.filter ?? parent?.filter ?? {};
938
+ __privateGet$3(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
939
+ __privateGet$3(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
940
+ __privateGet$3(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
941
+ __privateGet$3(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
942
+ __privateGet$3(this, _data).sort = data.sort ?? parent?.sort;
943
+ __privateGet$3(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
944
+ __privateGet$3(this, _data).page = data.page ?? parent?.page;
1022
945
  this.any = this.any.bind(this);
1023
946
  this.all = this.all.bind(this);
1024
947
  this.not = this.not.bind(this);
@@ -1032,47 +955,33 @@ const _Query = class {
1032
955
  return __privateGet$3(this, _data);
1033
956
  }
1034
957
  any(...queries) {
1035
- const $any = queries.map((query) => {
1036
- var _a;
1037
- return (_a = query.getQueryOptions().filter) != null ? _a : {};
1038
- });
958
+ const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1039
959
  return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $any } }, __privateGet$3(this, _data));
1040
960
  }
1041
961
  all(...queries) {
1042
- const $all = queries.map((query) => {
1043
- var _a;
1044
- return (_a = query.getQueryOptions().filter) != null ? _a : {};
1045
- });
962
+ const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1046
963
  return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1047
964
  }
1048
965
  not(...queries) {
1049
- const $not = queries.map((query) => {
1050
- var _a;
1051
- return (_a = query.getQueryOptions().filter) != null ? _a : {};
1052
- });
966
+ const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1053
967
  return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $not } }, __privateGet$3(this, _data));
1054
968
  }
1055
969
  none(...queries) {
1056
- const $none = queries.map((query) => {
1057
- var _a;
1058
- return (_a = query.getQueryOptions().filter) != null ? _a : {};
1059
- });
970
+ const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1060
971
  return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $none } }, __privateGet$3(this, _data));
1061
972
  }
1062
973
  filter(a, b) {
1063
- var _a, _b;
1064
974
  if (arguments.length === 1) {
1065
975
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1066
- const $all = compact([(_a = __privateGet$3(this, _data).filter) == null ? void 0 : _a.$all].flat().concat(constraints));
976
+ const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat(constraints));
1067
977
  return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1068
978
  } else {
1069
- const $all = compact([(_b = __privateGet$3(this, _data).filter) == null ? void 0 : _b.$all].flat().concat([{ [a]: b }]));
979
+ const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1070
980
  return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1071
981
  }
1072
982
  }
1073
983
  sort(column, direction) {
1074
- var _a;
1075
- const originalSort = [(_a = __privateGet$3(this, _data).sort) != null ? _a : []].flat();
984
+ const originalSort = [__privateGet$3(this, _data).sort ?? []].flat();
1076
985
  const sort = [...originalSort, { column, direction }];
1077
986
  return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { sort }, __privateGet$3(this, _data));
1078
987
  }
@@ -1135,11 +1044,10 @@ _repository = new WeakMap();
1135
1044
  _data = new WeakMap();
1136
1045
 
1137
1046
  function isIdentifiable(x) {
1138
- return isObject(x) && isString(x == null ? void 0 : x.id);
1047
+ return isObject(x) && isString(x?.id);
1139
1048
  }
1140
1049
  function isXataRecord(x) {
1141
- var _a;
1142
- return isIdentifiable(x) && typeof (x == null ? void 0 : x.xata) === "object" && typeof ((_a = x == null ? void 0 : x.xata) == null ? void 0 : _a.version) === "number";
1050
+ return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1143
1051
  }
1144
1052
 
1145
1053
  function isSortFilterString(value) {
@@ -1152,7 +1060,6 @@ function isSortFilterObject(filter) {
1152
1060
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
1153
1061
  }
1154
1062
  function buildSortFilter(filter) {
1155
- var _a;
1156
1063
  if (isSortFilterString(filter)) {
1157
1064
  return { [filter]: "asc" };
1158
1065
  } else if (Array.isArray(filter)) {
@@ -1160,7 +1067,7 @@ function buildSortFilter(filter) {
1160
1067
  } else if (isSortFilterBase(filter)) {
1161
1068
  return filter;
1162
1069
  } else if (isSortFilterObject(filter)) {
1163
- return { [filter.column]: (_a = filter.direction) != null ? _a : "asc" };
1070
+ return { [filter.column]: filter.direction ?? "asc" };
1164
1071
  } else {
1165
1072
  throw new Error(`Invalid sort filter: ${filter}`);
1166
1073
  }
@@ -1188,7 +1095,7 @@ var __privateMethod$2 = (obj, member, method) => {
1188
1095
  __accessCheck$3(obj, member, "access private method");
1189
1096
  return method;
1190
1097
  };
1191
- var _table, _links, _getFetchProps, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _initObject, initObject_fn;
1098
+ var _table, _links, _getFetchProps, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn;
1192
1099
  class Repository extends Query {
1193
1100
  }
1194
1101
  class RestRepository extends Query {
@@ -1200,13 +1107,11 @@ class RestRepository extends Query {
1200
1107
  __privateAdd$3(this, _updateRecordWithID);
1201
1108
  __privateAdd$3(this, _upsertRecordWithID);
1202
1109
  __privateAdd$3(this, _deleteRecord);
1203
- __privateAdd$3(this, _initObject);
1204
1110
  __privateAdd$3(this, _table, void 0);
1205
1111
  __privateAdd$3(this, _links, void 0);
1206
1112
  __privateAdd$3(this, _getFetchProps, void 0);
1207
- var _a;
1208
1113
  __privateSet$1(this, _table, options.table);
1209
- __privateSet$1(this, _links, (_a = options.links) != null ? _a : {});
1114
+ __privateSet$1(this, _links, options.links ?? {});
1210
1115
  __privateSet$1(this, _getFetchProps, options.getFetchProps);
1211
1116
  this.db = options.db;
1212
1117
  }
@@ -1236,7 +1141,7 @@ class RestRepository extends Query {
1236
1141
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1237
1142
  ...fetchProps
1238
1143
  });
1239
- return __privateMethod$2(this, _initObject, initObject_fn).call(this, __privateGet$2(this, _table), response);
1144
+ return initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), response);
1240
1145
  } catch (e) {
1241
1146
  if (isObject(e) && e.status === 404) {
1242
1147
  return null;
@@ -1299,13 +1204,12 @@ class RestRepository extends Query {
1299
1204
  body: { tables: [__privateGet$2(this, _table)], query, fuzziness: options.fuzziness },
1300
1205
  ...fetchProps
1301
1206
  });
1302
- return records.map((item) => __privateMethod$2(this, _initObject, initObject_fn).call(this, __privateGet$2(this, _table), item));
1207
+ return records.map((item) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), item));
1303
1208
  }
1304
1209
  async query(query) {
1305
- var _a;
1306
1210
  const data = query.getQueryOptions();
1307
1211
  const body = {
1308
- filter: Object.values((_a = data.filter) != null ? _a : {}).some(Boolean) ? data.filter : void 0,
1212
+ filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1309
1213
  sort: data.sort ? buildSortFilter(data.sort) : void 0,
1310
1214
  page: data.page,
1311
1215
  columns: data.columns
@@ -1316,7 +1220,7 @@ class RestRepository extends Query {
1316
1220
  body,
1317
1221
  ...fetchProps
1318
1222
  });
1319
- const records = objects.map((record) => __privateMethod$2(this, _initObject, initObject_fn).call(this, __privateGet$2(this, _table), record));
1223
+ const records = objects.map((record) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), record));
1320
1224
  return new Page(query, meta, records);
1321
1225
  }
1322
1226
  }
@@ -1413,19 +1317,24 @@ deleteRecord_fn = async function(recordId) {
1413
1317
  ...fetchProps
1414
1318
  });
1415
1319
  };
1416
- _initObject = new WeakSet();
1417
- initObject_fn = function(table, object) {
1320
+ const transformObjectLinks = (object) => {
1321
+ return Object.entries(object).reduce((acc, [key, value]) => {
1322
+ if (key === "xata")
1323
+ return acc;
1324
+ return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1325
+ }, {});
1326
+ };
1327
+ const initObject = (db, links, table, object) => {
1418
1328
  const result = {};
1419
1329
  Object.assign(result, object);
1420
- const tableLinks = __privateGet$2(this, _links)[table] || [];
1330
+ const tableLinks = links[table] || [];
1421
1331
  for (const link of tableLinks) {
1422
1332
  const [field, linkTable] = link;
1423
1333
  const value = result[field];
1424
1334
  if (value && isObject(value)) {
1425
- result[field] = __privateMethod$2(this, _initObject, initObject_fn).call(this, linkTable, value);
1335
+ result[field] = initObject(db, links, linkTable, value);
1426
1336
  }
1427
1337
  }
1428
- const db = this.db;
1429
1338
  result.read = function() {
1430
1339
  return db[table].read(result["id"]);
1431
1340
  };
@@ -1441,13 +1350,6 @@ initObject_fn = function(table, object) {
1441
1350
  Object.freeze(result);
1442
1351
  return result;
1443
1352
  };
1444
- const transformObjectLinks = (object) => {
1445
- return Object.entries(object).reduce((acc, [key, value]) => {
1446
- if (key === "xata")
1447
- return acc;
1448
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1449
- }, {});
1450
- };
1451
1353
 
1452
1354
  const gt = (value) => ({ $gt: value });
1453
1355
  const ge = (value) => ({ $ge: value });
@@ -1520,8 +1422,10 @@ var __privateMethod$1 = (obj, member, method) => {
1520
1422
  };
1521
1423
  var _search, search_fn;
1522
1424
  class SearchPlugin extends XataPlugin {
1523
- constructor() {
1524
- super(...arguments);
1425
+ constructor(db, links) {
1426
+ super();
1427
+ this.db = db;
1428
+ this.links = links;
1525
1429
  __privateAdd$1(this, _search);
1526
1430
  }
1527
1431
  build({ getFetchProps }) {
@@ -1530,16 +1434,16 @@ class SearchPlugin extends XataPlugin {
1530
1434
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1531
1435
  return records.map((record) => {
1532
1436
  const { table = "orphan" } = record.xata;
1533
- return { table, record };
1437
+ return { table, record: initObject(this.db, this.links, table, record) };
1534
1438
  });
1535
1439
  },
1536
1440
  byTable: async (query, options = {}) => {
1537
1441
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1538
1442
  return records.reduce((acc, record) => {
1539
- var _a;
1540
1443
  const { table = "orphan" } = record.xata;
1541
- const items = (_a = acc[table]) != null ? _a : [];
1542
- return { ...acc, [table]: [...items, record] };
1444
+ const items = acc[table] ?? [];
1445
+ const item = initObject(this.db, this.links, table, record);
1446
+ return { ...acc, [table]: [...items, item] };
1543
1447
  }, {});
1544
1448
  }
1545
1449
  };
@@ -1548,7 +1452,7 @@ class SearchPlugin extends XataPlugin {
1548
1452
  _search = new WeakSet();
1549
1453
  search_fn = async function(query, options, getFetchProps) {
1550
1454
  const fetchProps = await getFetchProps();
1551
- const { tables, fuzziness } = options != null ? options : {};
1455
+ const { tables, fuzziness } = options ?? {};
1552
1456
  const { records } = await searchBranch({
1553
1457
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1554
1458
  body: { tables, query, fuzziness },
@@ -1561,6 +1465,84 @@ const isBranchStrategyBuilder = (strategy) => {
1561
1465
  return typeof strategy === "function";
1562
1466
  };
1563
1467
 
1468
+ const envBranchNames = [
1469
+ "XATA_BRANCH",
1470
+ "VERCEL_GIT_COMMIT_REF",
1471
+ "CF_PAGES_BRANCH",
1472
+ "BRANCH"
1473
+ ];
1474
+ const defaultBranch = "main";
1475
+ 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;
1486
+ }
1487
+ 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);
1498
+ }
1499
+ async function getDatabaseBranch(branch, options) {
1500
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1501
+ const apiKey = options?.apiKey || getAPIKey();
1502
+ if (!databaseURL)
1503
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1504
+ if (!apiKey)
1505
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1506
+ const [protocol, , host, , database] = databaseURL.split("/");
1507
+ const [workspace] = host.split(".");
1508
+ const dbBranchName = `${database}:${branch}`;
1509
+ try {
1510
+ return await getBranchDetails({
1511
+ apiKey,
1512
+ apiUrl: databaseURL,
1513
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1514
+ workspacesApiUrl: `${protocol}//${host}`,
1515
+ pathParams: {
1516
+ dbBranchName,
1517
+ workspace
1518
+ }
1519
+ });
1520
+ } catch (err) {
1521
+ if (isObject(err) && err.status === 404)
1522
+ return null;
1523
+ throw err;
1524
+ }
1525
+ }
1526
+ function getBranchByEnvVariable() {
1527
+ for (const name of envBranchNames) {
1528
+ const value = getEnvVariable(name);
1529
+ if (value) {
1530
+ return value;
1531
+ }
1532
+ }
1533
+ try {
1534
+ return XATA_BRANCH;
1535
+ } catch (err) {
1536
+ }
1537
+ }
1538
+ function getDatabaseURL() {
1539
+ try {
1540
+ return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1541
+ } catch (err) {
1542
+ return void 0;
1543
+ }
1544
+ }
1545
+
1564
1546
  var __accessCheck = (obj, member, msg) => {
1565
1547
  if (!member.has(obj))
1566
1548
  throw TypeError("Cannot " + msg);
@@ -1592,12 +1574,13 @@ const buildClient = (plugins) => {
1592
1574
  __privateAdd(this, _evaluateBranch);
1593
1575
  __privateAdd(this, _branch, void 0);
1594
1576
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
1595
- const namespaces = {
1596
- db: new SchemaPlugin(links),
1597
- search: new SearchPlugin(),
1598
- ...plugins
1599
- };
1600
- for (const [key, namespace] of Object.entries(namespaces)) {
1577
+ const db = new SchemaPlugin(links).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
+ });
1581
+ this.db = db;
1582
+ this.search = search;
1583
+ for (const [key, namespace] of Object.entries(plugins ?? {})) {
1601
1584
  if (!namespace)
1602
1585
  continue;
1603
1586
  const result = namespace.build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
@@ -1611,10 +1594,10 @@ const buildClient = (plugins) => {
1611
1594
  }
1612
1595
  }
1613
1596
  }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1614
- const fetch = getFetchImplementation(options == null ? void 0 : options.fetch);
1615
- const databaseURL = (options == null ? void 0 : options.databaseURL) || getDatabaseURL();
1616
- const apiKey = (options == null ? void 0 : options.apiKey) || getAPIKey();
1617
- const branch = async () => (options == null ? void 0 : options.branch) ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options == null ? void 0 : options.fetch });
1597
+ const fetch = getFetchImplementation(options?.fetch);
1598
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1599
+ 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 });
1618
1601
  if (!databaseURL || !apiKey) {
1619
1602
  throw new Error("Options databaseURL and apiKey are required");
1620
1603
  }
@@ -1633,8 +1616,7 @@ const buildClient = (plugins) => {
1633
1616
  apiKey,
1634
1617
  apiUrl: "",
1635
1618
  workspacesApiUrl: (path, params) => {
1636
- var _a2;
1637
- const hasBranch = (_a2 = params.dbBranchName) != null ? _a2 : params.branch;
1619
+ const hasBranch = params.dbBranchName ?? params.branch;
1638
1620
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
1639
1621
  return databaseURL + newPath;
1640
1622
  }