@xata.io/client 0.0.0-alpha.veb4417f → 0.0.0-alpha.vec88a57

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
@@ -1,3 +1,27 @@
1
+ const defaultTrace = async (_name, fn, _options) => {
2
+ return await fn({
3
+ setAttributes: () => {
4
+ return;
5
+ },
6
+ onError: () => {
7
+ return;
8
+ }
9
+ });
10
+ };
11
+ const TraceAttributes = {
12
+ VERSION: "xata.sdk.version",
13
+ TABLE: "xata.table",
14
+ HTTP_REQUEST_ID: "http.request_id",
15
+ HTTP_STATUS_CODE: "http.status_code",
16
+ HTTP_HOST: "http.host",
17
+ HTTP_SCHEME: "http.scheme",
18
+ HTTP_USER_AGENT: "http.user_agent",
19
+ HTTP_METHOD: "http.method",
20
+ HTTP_URL: "http.url",
21
+ HTTP_ROUTE: "http.route",
22
+ HTTP_TARGET: "http.target"
23
+ };
24
+
1
25
  function notEmpty(value) {
2
26
  return value !== null && value !== void 0;
3
27
  }
@@ -13,43 +37,95 @@ function isDefined(value) {
13
37
  function isString(value) {
14
38
  return isDefined(value) && typeof value === "string";
15
39
  }
40
+ function isStringArray(value) {
41
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
42
+ }
16
43
  function toBase64(value) {
17
44
  try {
18
45
  return btoa(value);
19
46
  } catch (err) {
20
- return Buffer.from(value).toString("base64");
47
+ const buf = Buffer;
48
+ return buf.from(value).toString("base64");
21
49
  }
22
50
  }
23
51
 
24
- function getEnvVariable(name) {
52
+ function getEnvironment() {
25
53
  try {
26
- if (isObject(process) && isString(process?.env?.[name])) {
27
- return process.env[name];
54
+ if (isObject(process) && isObject(process.env)) {
55
+ return {
56
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
57
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
58
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
59
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
60
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
61
+ };
28
62
  }
29
63
  } catch (err) {
30
64
  }
31
65
  try {
32
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
33
- return Deno.env.get(name);
66
+ if (isObject(Deno) && isObject(Deno.env)) {
67
+ return {
68
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
69
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
70
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
71
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
72
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
73
+ };
34
74
  }
35
75
  } catch (err) {
36
76
  }
77
+ return {
78
+ apiKey: getGlobalApiKey(),
79
+ databaseURL: getGlobalDatabaseURL(),
80
+ branch: getGlobalBranch(),
81
+ envBranch: void 0,
82
+ fallbackBranch: getGlobalFallbackBranch()
83
+ };
84
+ }
85
+ function getGlobalApiKey() {
86
+ try {
87
+ return XATA_API_KEY;
88
+ } catch (err) {
89
+ return void 0;
90
+ }
91
+ }
92
+ function getGlobalDatabaseURL() {
93
+ try {
94
+ return XATA_DATABASE_URL;
95
+ } catch (err) {
96
+ return void 0;
97
+ }
98
+ }
99
+ function getGlobalBranch() {
100
+ try {
101
+ return XATA_BRANCH;
102
+ } catch (err) {
103
+ return void 0;
104
+ }
105
+ }
106
+ function getGlobalFallbackBranch() {
107
+ try {
108
+ return XATA_FALLBACK_BRANCH;
109
+ } catch (err) {
110
+ return void 0;
111
+ }
37
112
  }
38
113
  async function getGitBranch() {
114
+ const cmd = ["git", "branch", "--show-current"];
115
+ const fullCmd = cmd.join(" ");
116
+ const nodeModule = ["child", "process"].join("_");
117
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
39
118
  try {
40
119
  if (typeof require === "function") {
41
- const req = require;
42
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
120
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
43
121
  }
122
+ const { execSync } = await import(nodeModule);
123
+ return execSync(fullCmd, execOptions).toString().trim();
44
124
  } catch (err) {
45
125
  }
46
126
  try {
47
127
  if (isObject(Deno)) {
48
- const process2 = Deno.run({
49
- cmd: ["git", "branch", "--show-current"],
50
- stdout: "piped",
51
- stderr: "piped"
52
- });
128
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
53
129
  return new TextDecoder().decode(await process2.output()).trim();
54
130
  }
55
131
  } catch (err) {
@@ -58,7 +134,8 @@ async function getGitBranch() {
58
134
 
59
135
  function getAPIKey() {
60
136
  try {
61
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
137
+ const { apiKey } = getEnvironment();
138
+ return apiKey;
62
139
  } catch (err) {
63
140
  return void 0;
64
141
  }
@@ -68,26 +145,35 @@ function getFetchImplementation(userFetch) {
68
145
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
69
146
  const fetchImpl = userFetch ?? globalFetch;
70
147
  if (!fetchImpl) {
71
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
148
+ throw new Error(
149
+ `The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`
150
+ );
72
151
  }
73
152
  return fetchImpl;
74
153
  }
75
154
 
155
+ const VERSION = "0.0.0-alpha.vec88a57";
156
+
76
157
  class ErrorWithCause extends Error {
77
158
  constructor(message, options) {
78
159
  super(message, options);
79
160
  }
80
161
  }
81
162
  class FetcherError extends ErrorWithCause {
82
- constructor(status, data) {
163
+ constructor(status, data, requestId) {
83
164
  super(getMessage(data));
84
165
  this.status = status;
85
166
  this.errors = isBulkError(data) ? data.errors : void 0;
167
+ this.requestId = requestId;
86
168
  if (data instanceof Error) {
87
169
  this.stack = data.stack;
88
170
  this.cause = data.cause;
89
171
  }
90
172
  }
173
+ toString() {
174
+ const error = super.toString();
175
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
176
+ }
91
177
  }
92
178
  function isBulkError(error) {
93
179
  return isObject(error) && Array.isArray(error.errors);
@@ -110,7 +196,12 @@ function getMessage(data) {
110
196
  }
111
197
 
112
198
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
113
- const query = new URLSearchParams(queryParams).toString();
199
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
200
+ if (value === void 0 || value === null)
201
+ return acc;
202
+ return { ...acc, [key]: value };
203
+ }, {});
204
+ const query = new URLSearchParams(cleanQueryParams).toString();
114
205
  const queryString = query.length > 0 ? `?${query}` : "";
115
206
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
116
207
  };
@@ -140,32 +231,62 @@ async function fetch$1({
140
231
  fetchImpl,
141
232
  apiKey,
142
233
  apiUrl,
143
- workspacesApiUrl
234
+ workspacesApiUrl,
235
+ trace
144
236
  }) {
145
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
146
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
147
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
148
- const response = await fetchImpl(url, {
149
- method: method.toUpperCase(),
150
- body: body ? JSON.stringify(body) : void 0,
151
- headers: {
152
- "Content-Type": "application/json",
153
- ...headers,
154
- ...hostHeader(fullUrl),
155
- Authorization: `Bearer ${apiKey}`
156
- }
157
- });
158
- if (response.status === 204) {
159
- return {};
160
- }
237
+ return trace(
238
+ `${method.toUpperCase()} ${path}`,
239
+ async ({ setAttributes, onError }) => {
240
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
241
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
242
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
243
+ setAttributes({
244
+ [TraceAttributes.HTTP_URL]: url,
245
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
246
+ });
247
+ const response = await fetchImpl(url, {
248
+ method: method.toUpperCase(),
249
+ body: body ? JSON.stringify(body) : void 0,
250
+ headers: {
251
+ "Content-Type": "application/json",
252
+ "User-Agent": `Xata client-ts/${VERSION}`,
253
+ ...headers,
254
+ ...hostHeader(fullUrl),
255
+ Authorization: `Bearer ${apiKey}`
256
+ }
257
+ });
258
+ if (response.status === 204) {
259
+ return {};
260
+ }
261
+ const { host, protocol } = parseUrl(response.url);
262
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
263
+ setAttributes({
264
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
265
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
266
+ [TraceAttributes.HTTP_HOST]: host,
267
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
268
+ });
269
+ try {
270
+ const jsonResponse = await response.json();
271
+ if (response.ok) {
272
+ return jsonResponse;
273
+ }
274
+ throw new FetcherError(response.status, jsonResponse, requestId);
275
+ } catch (error) {
276
+ const fetcherError = new FetcherError(response.status, error, requestId);
277
+ onError(fetcherError.message);
278
+ throw fetcherError;
279
+ }
280
+ },
281
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
282
+ );
283
+ }
284
+ function parseUrl(url) {
161
285
  try {
162
- const jsonResponse = await response.json();
163
- if (response.ok) {
164
- return jsonResponse;
165
- }
166
- throw new FetcherError(response.status, jsonResponse);
286
+ const { host, protocol } = new URL(url);
287
+ return { host, protocol };
167
288
  } catch (error) {
168
- throw new FetcherError(response.status, error);
289
+ return {};
169
290
  }
170
291
  }
171
292
 
@@ -224,6 +345,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
224
345
  ...variables
225
346
  });
226
347
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
348
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
227
349
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
228
350
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
229
351
  method: "delete",
@@ -259,6 +381,11 @@ const deleteDatabase = (variables) => fetch$1({
259
381
  method: "delete",
260
382
  ...variables
261
383
  });
384
+ const getDatabaseMetadata = (variables) => fetch$1({
385
+ url: "/dbs/{dbName}/metadata",
386
+ method: "get",
387
+ ...variables
388
+ });
262
389
  const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
263
390
  const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
264
391
  const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
@@ -272,11 +399,7 @@ const getBranchDetails = (variables) => fetch$1({
272
399
  method: "get",
273
400
  ...variables
274
401
  });
275
- const createBranch = (variables) => fetch$1({
276
- url: "/db/{dbBranchName}",
277
- method: "put",
278
- ...variables
279
- });
402
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
280
403
  const deleteBranch = (variables) => fetch$1({
281
404
  url: "/db/{dbBranchName}",
282
405
  method: "delete",
@@ -350,11 +473,7 @@ const updateColumn = (variables) => fetch$1({
350
473
  method: "patch",
351
474
  ...variables
352
475
  });
353
- const insertRecord = (variables) => fetch$1({
354
- url: "/db/{dbBranchName}/tables/{tableName}/data",
355
- method: "post",
356
- ...variables
357
- });
476
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
358
477
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
359
478
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
360
479
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -396,6 +515,7 @@ const operationsByTag = {
396
515
  updateWorkspaceMemberRole,
397
516
  removeWorkspaceMember,
398
517
  inviteWorkspaceMember,
518
+ updateWorkspaceMemberInvite,
399
519
  cancelWorkspaceMemberInvite,
400
520
  resendWorkspaceMemberInvite,
401
521
  acceptWorkspaceMemberInvite
@@ -404,6 +524,7 @@ const operationsByTag = {
404
524
  getDatabaseList,
405
525
  createDatabase,
406
526
  deleteDatabase,
527
+ getDatabaseMetadata,
407
528
  getGitBranchesMapping,
408
529
  addGitBranchesEntry,
409
530
  removeGitBranchesEntry,
@@ -485,7 +606,7 @@ var __privateAdd$7 = (obj, member, value) => {
485
606
  throw TypeError("Cannot add the same private member more than once");
486
607
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
487
608
  };
488
- var __privateSet$6 = (obj, member, value, setter) => {
609
+ var __privateSet$7 = (obj, member, value, setter) => {
489
610
  __accessCheck$7(obj, member, "write to private field");
490
611
  setter ? setter.call(obj, value) : member.set(obj, value);
491
612
  return value;
@@ -496,15 +617,17 @@ class XataApiClient {
496
617
  __privateAdd$7(this, _extraProps, void 0);
497
618
  __privateAdd$7(this, _namespaces, {});
498
619
  const provider = options.host ?? "production";
499
- const apiKey = options?.apiKey ?? getAPIKey();
620
+ const apiKey = options.apiKey ?? getAPIKey();
621
+ const trace = options.trace ?? defaultTrace;
500
622
  if (!apiKey) {
501
623
  throw new Error("Could not resolve a valid apiKey");
502
624
  }
503
- __privateSet$6(this, _extraProps, {
625
+ __privateSet$7(this, _extraProps, {
504
626
  apiUrl: getHostUrl(provider, "main"),
505
627
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
506
628
  fetchImpl: getFetchImplementation(options.fetch),
507
- apiKey
629
+ apiKey,
630
+ trace
508
631
  });
509
632
  }
510
633
  get user() {
@@ -627,6 +750,13 @@ class WorkspaceApi {
627
750
  ...this.extraProps
628
751
  });
629
752
  }
753
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
754
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
755
+ pathParams: { workspaceId, inviteId },
756
+ body: { role },
757
+ ...this.extraProps
758
+ });
759
+ }
630
760
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
631
761
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
632
762
  pathParams: { workspaceId, inviteId },
@@ -669,6 +799,12 @@ class DatabaseApi {
669
799
  ...this.extraProps
670
800
  });
671
801
  }
802
+ getDatabaseMetadata(workspace, dbName) {
803
+ return operationsByTag.database.getDatabaseMetadata({
804
+ pathParams: { workspace, dbName },
805
+ ...this.extraProps
806
+ });
807
+ }
672
808
  getGitBranchesMapping(workspace, dbName) {
673
809
  return operationsByTag.database.getGitBranchesMapping({
674
810
  pathParams: { workspace, dbName },
@@ -689,10 +825,10 @@ class DatabaseApi {
689
825
  ...this.extraProps
690
826
  });
691
827
  }
692
- resolveBranch(workspace, dbName, gitBranch) {
828
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
693
829
  return operationsByTag.database.resolveBranch({
694
830
  pathParams: { workspace, dbName },
695
- queryParams: { gitBranch },
831
+ queryParams: { gitBranch, fallbackBranch },
696
832
  ...this.extraProps
697
833
  });
698
834
  }
@@ -841,9 +977,10 @@ class RecordsApi {
841
977
  constructor(extraProps) {
842
978
  this.extraProps = extraProps;
843
979
  }
844
- insertRecord(workspace, database, branch, tableName, record) {
980
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
845
981
  return operationsByTag.records.insertRecord({
846
982
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
983
+ queryParams: options,
847
984
  body: record,
848
985
  ...this.extraProps
849
986
  });
@@ -872,21 +1009,24 @@ class RecordsApi {
872
1009
  ...this.extraProps
873
1010
  });
874
1011
  }
875
- deleteRecord(workspace, database, branch, tableName, recordId) {
1012
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
876
1013
  return operationsByTag.records.deleteRecord({
877
1014
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1015
+ queryParams: options,
878
1016
  ...this.extraProps
879
1017
  });
880
1018
  }
881
1019
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
882
1020
  return operationsByTag.records.getRecord({
883
1021
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1022
+ queryParams: options,
884
1023
  ...this.extraProps
885
1024
  });
886
1025
  }
887
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1026
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
888
1027
  return operationsByTag.records.bulkInsertTableRecords({
889
1028
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1029
+ queryParams: options,
890
1030
  body: { records },
891
1031
  ...this.extraProps
892
1032
  });
@@ -937,18 +1077,18 @@ var __privateAdd$6 = (obj, member, value) => {
937
1077
  throw TypeError("Cannot add the same private member more than once");
938
1078
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
939
1079
  };
940
- var __privateSet$5 = (obj, member, value, setter) => {
1080
+ var __privateSet$6 = (obj, member, value, setter) => {
941
1081
  __accessCheck$6(obj, member, "write to private field");
942
1082
  setter ? setter.call(obj, value) : member.set(obj, value);
943
1083
  return value;
944
1084
  };
945
- var _query;
1085
+ var _query, _page;
946
1086
  class Page {
947
1087
  constructor(query, meta, records = []) {
948
1088
  __privateAdd$6(this, _query, void 0);
949
- __privateSet$5(this, _query, query);
1089
+ __privateSet$6(this, _query, query);
950
1090
  this.meta = meta;
951
- this.records = records;
1091
+ this.records = new RecordArray(this, records);
952
1092
  }
953
1093
  async nextPage(size, offset) {
954
1094
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
@@ -968,12 +1108,56 @@ class Page {
968
1108
  }
969
1109
  _query = new WeakMap();
970
1110
  const PAGINATION_MAX_SIZE = 200;
971
- const PAGINATION_DEFAULT_SIZE = 200;
1111
+ const PAGINATION_DEFAULT_SIZE = 20;
972
1112
  const PAGINATION_MAX_OFFSET = 800;
973
1113
  const PAGINATION_DEFAULT_OFFSET = 0;
974
1114
  function isCursorPaginationOptions(options) {
975
1115
  return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
976
1116
  }
1117
+ const _RecordArray = class extends Array {
1118
+ constructor(...args) {
1119
+ super(..._RecordArray.parseConstructorParams(...args));
1120
+ __privateAdd$6(this, _page, void 0);
1121
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1122
+ }
1123
+ static parseConstructorParams(...args) {
1124
+ if (args.length === 1 && typeof args[0] === "number") {
1125
+ return new Array(args[0]);
1126
+ }
1127
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1128
+ const result = args[1] ?? args[0].records ?? [];
1129
+ return new Array(...result);
1130
+ }
1131
+ return new Array(...args);
1132
+ }
1133
+ toArray() {
1134
+ return new Array(...this);
1135
+ }
1136
+ map(callbackfn, thisArg) {
1137
+ return this.toArray().map(callbackfn, thisArg);
1138
+ }
1139
+ async nextPage(size, offset) {
1140
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1141
+ return new _RecordArray(newPage);
1142
+ }
1143
+ async previousPage(size, offset) {
1144
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1145
+ return new _RecordArray(newPage);
1146
+ }
1147
+ async firstPage(size, offset) {
1148
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1149
+ return new _RecordArray(newPage);
1150
+ }
1151
+ async lastPage(size, offset) {
1152
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1153
+ return new _RecordArray(newPage);
1154
+ }
1155
+ hasNextPage() {
1156
+ return __privateGet$6(this, _page).meta.page.more;
1157
+ }
1158
+ };
1159
+ let RecordArray = _RecordArray;
1160
+ _page = new WeakMap();
977
1161
 
978
1162
  var __accessCheck$5 = (obj, member, msg) => {
979
1163
  if (!member.has(obj))
@@ -988,7 +1172,7 @@ var __privateAdd$5 = (obj, member, value) => {
988
1172
  throw TypeError("Cannot add the same private member more than once");
989
1173
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
990
1174
  };
991
- var __privateSet$4 = (obj, member, value, setter) => {
1175
+ var __privateSet$5 = (obj, member, value, setter) => {
992
1176
  __accessCheck$5(obj, member, "write to private field");
993
1177
  setter ? setter.call(obj, value) : member.set(obj, value);
994
1178
  return value;
@@ -1000,12 +1184,12 @@ const _Query = class {
1000
1184
  __privateAdd$5(this, _repository, void 0);
1001
1185
  __privateAdd$5(this, _data, { filter: {} });
1002
1186
  this.meta = { page: { cursor: "start", more: true } };
1003
- this.records = [];
1004
- __privateSet$4(this, _table$1, table);
1187
+ this.records = new RecordArray(this, []);
1188
+ __privateSet$5(this, _table$1, table);
1005
1189
  if (repository) {
1006
- __privateSet$4(this, _repository, repository);
1190
+ __privateSet$5(this, _repository, repository);
1007
1191
  } else {
1008
- __privateSet$4(this, _repository, this);
1192
+ __privateSet$5(this, _repository, this);
1009
1193
  }
1010
1194
  const parent = cleanParent(data, rawParent);
1011
1195
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
@@ -1060,13 +1244,18 @@ const _Query = class {
1060
1244
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1061
1245
  }
1062
1246
  }
1063
- sort(column, direction) {
1247
+ sort(column, direction = "asc") {
1064
1248
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1065
1249
  const sort = [...originalSort, { column, direction }];
1066
1250
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1067
1251
  }
1068
1252
  select(columns) {
1069
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1253
+ return new _Query(
1254
+ __privateGet$5(this, _repository),
1255
+ __privateGet$5(this, _table$1),
1256
+ { columns },
1257
+ __privateGet$5(this, _data)
1258
+ );
1070
1259
  }
1071
1260
  getPaginated(options = {}) {
1072
1261
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1089,8 +1278,11 @@ const _Query = class {
1089
1278
  }
1090
1279
  }
1091
1280
  async getMany(options = {}) {
1092
- const { records } = await this.getPaginated(options);
1093
- return records;
1281
+ const page = await this.getPaginated(options);
1282
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1283
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1284
+ }
1285
+ return page.records;
1094
1286
  }
1095
1287
  async getAll(options = {}) {
1096
1288
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1138,7 +1330,9 @@ function isIdentifiable(x) {
1138
1330
  return isObject(x) && isString(x?.id);
1139
1331
  }
1140
1332
  function isXataRecord(x) {
1141
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1333
+ const record = x;
1334
+ const metadata = record?.getMetadata();
1335
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1142
1336
  }
1143
1337
 
1144
1338
  function isSortFilterString(value) {
@@ -1177,7 +1371,7 @@ var __privateAdd$4 = (obj, member, value) => {
1177
1371
  throw TypeError("Cannot add the same private member more than once");
1178
1372
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1179
1373
  };
1180
- var __privateSet$3 = (obj, member, value, setter) => {
1374
+ var __privateSet$4 = (obj, member, value, setter) => {
1181
1375
  __accessCheck$4(obj, member, "write to private field");
1182
1376
  setter ? setter.call(obj, value) : member.set(obj, value);
1183
1377
  return value;
@@ -1186,7 +1380,7 @@ var __privateMethod$2 = (obj, member, method) => {
1186
1380
  __accessCheck$4(obj, member, "access private method");
1187
1381
  return method;
1188
1382
  };
1189
- var _table, _getFetchProps, _cache, _schema$1, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchema$1, getSchema_fn$1;
1383
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
1190
1384
  class Repository extends Query {
1191
1385
  }
1192
1386
  class RestRepository extends Query {
@@ -1198,188 +1392,214 @@ class RestRepository extends Query {
1198
1392
  __privateAdd$4(this, _updateRecordWithID);
1199
1393
  __privateAdd$4(this, _upsertRecordWithID);
1200
1394
  __privateAdd$4(this, _deleteRecord);
1201
- __privateAdd$4(this, _invalidateCache);
1202
- __privateAdd$4(this, _setCacheRecord);
1203
- __privateAdd$4(this, _getCacheRecord);
1204
1395
  __privateAdd$4(this, _setCacheQuery);
1205
1396
  __privateAdd$4(this, _getCacheQuery);
1206
- __privateAdd$4(this, _getSchema$1);
1397
+ __privateAdd$4(this, _getSchemaTables$1);
1207
1398
  __privateAdd$4(this, _table, void 0);
1208
1399
  __privateAdd$4(this, _getFetchProps, void 0);
1400
+ __privateAdd$4(this, _db, void 0);
1209
1401
  __privateAdd$4(this, _cache, void 0);
1210
- __privateAdd$4(this, _schema$1, void 0);
1211
- __privateSet$3(this, _table, options.table);
1212
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1213
- this.db = options.db;
1214
- __privateSet$3(this, _cache, options.pluginOptions.cache);
1215
- }
1216
- async create(a, b) {
1217
- if (Array.isArray(a)) {
1218
- if (a.length === 0)
1219
- return [];
1220
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1221
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1222
- return records;
1223
- }
1224
- if (isString(a) && isObject(b)) {
1225
- if (a === "")
1226
- throw new Error("The id can't be empty");
1227
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1228
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1229
- return record;
1230
- }
1231
- if (isObject(a) && isString(a.id)) {
1232
- if (a.id === "")
1233
- throw new Error("The id can't be empty");
1234
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1235
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1236
- return record;
1237
- }
1238
- if (isObject(a)) {
1239
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1240
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1241
- return record;
1242
- }
1243
- throw new Error("Invalid arguments for create method");
1402
+ __privateAdd$4(this, _schemaTables$2, void 0);
1403
+ __privateAdd$4(this, _trace, void 0);
1404
+ __privateSet$4(this, _table, options.table);
1405
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1406
+ __privateSet$4(this, _db, options.db);
1407
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1408
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1409
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1410
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1411
+ return trace(name, fn, {
1412
+ ...options2,
1413
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1414
+ [TraceAttributes.VERSION]: VERSION
1415
+ });
1416
+ });
1244
1417
  }
1245
- async read(a) {
1246
- if (Array.isArray(a)) {
1247
- if (a.length === 0)
1248
- return [];
1249
- return this.getAll({ filter: { id: { $any: a } } });
1250
- }
1251
- if (isString(a)) {
1252
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, a);
1253
- if (cacheRecord)
1254
- return cacheRecord;
1255
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1256
- try {
1257
- const response = await getRecord({
1258
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: a },
1259
- ...fetchProps
1260
- });
1261
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1262
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1263
- } catch (e) {
1264
- if (isObject(e) && e.status === 404) {
1265
- return null;
1418
+ async create(a, b, c) {
1419
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1420
+ if (Array.isArray(a)) {
1421
+ if (a.length === 0)
1422
+ return [];
1423
+ const columns = isStringArray(b) ? b : void 0;
1424
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1425
+ }
1426
+ if (isString(a) && isObject(b)) {
1427
+ if (a === "")
1428
+ throw new Error("The id can't be empty");
1429
+ const columns = isStringArray(c) ? c : void 0;
1430
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1431
+ }
1432
+ if (isObject(a) && isString(a.id)) {
1433
+ if (a.id === "")
1434
+ throw new Error("The id can't be empty");
1435
+ const columns = isStringArray(b) ? b : void 0;
1436
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1437
+ }
1438
+ if (isObject(a)) {
1439
+ const columns = isStringArray(b) ? b : void 0;
1440
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1441
+ }
1442
+ throw new Error("Invalid arguments for create method");
1443
+ });
1444
+ }
1445
+ async read(a, b) {
1446
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1447
+ const columns = isStringArray(b) ? b : ["*"];
1448
+ if (Array.isArray(a)) {
1449
+ if (a.length === 0)
1450
+ return [];
1451
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1452
+ const finalObjects = await this.getAll({ filter: { id: { $any: ids } }, columns });
1453
+ const dictionary = finalObjects.reduce((acc, object) => {
1454
+ acc[object.id] = object;
1455
+ return acc;
1456
+ }, {});
1457
+ return ids.map((id2) => dictionary[id2] ?? null);
1458
+ }
1459
+ const id = isString(a) ? a : a.id;
1460
+ if (isString(id)) {
1461
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1462
+ try {
1463
+ const response = await getRecord({
1464
+ pathParams: {
1465
+ workspace: "{workspaceId}",
1466
+ dbBranchName: "{dbBranch}",
1467
+ tableName: __privateGet$4(this, _table),
1468
+ recordId: id
1469
+ },
1470
+ queryParams: { columns },
1471
+ ...fetchProps
1472
+ });
1473
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1474
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1475
+ } catch (e) {
1476
+ if (isObject(e) && e.status === 404) {
1477
+ return null;
1478
+ }
1479
+ throw e;
1266
1480
  }
1267
- throw e;
1268
1481
  }
1269
- }
1482
+ return null;
1483
+ });
1270
1484
  }
1271
- async update(a, b) {
1272
- if (Array.isArray(a)) {
1273
- if (a.length === 0)
1274
- return [];
1275
- if (a.length > 100) {
1276
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1485
+ async update(a, b, c) {
1486
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1487
+ if (Array.isArray(a)) {
1488
+ if (a.length === 0)
1489
+ return [];
1490
+ if (a.length > 100) {
1491
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1492
+ }
1493
+ const columns = isStringArray(b) ? b : ["*"];
1494
+ return Promise.all(a.map((object) => this.update(object, columns)));
1277
1495
  }
1278
- return Promise.all(a.map((object) => this.update(object)));
1279
- }
1280
- if (isString(a) && isObject(b)) {
1281
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1282
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1283
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1284
- return record;
1285
- }
1286
- if (isObject(a) && isString(a.id)) {
1287
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1288
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1289
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1290
- return record;
1291
- }
1292
- throw new Error("Invalid arguments for update method");
1293
- }
1294
- async createOrUpdate(a, b) {
1295
- if (Array.isArray(a)) {
1296
- if (a.length === 0)
1297
- return [];
1298
- if (a.length > 100) {
1299
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1496
+ if (isString(a) && isObject(b)) {
1497
+ const columns = isStringArray(c) ? c : void 0;
1498
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1300
1499
  }
1301
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1302
- }
1303
- if (isString(a) && isObject(b)) {
1304
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1305
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1306
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1307
- return record;
1308
- }
1309
- if (isObject(a) && isString(a.id)) {
1310
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1311
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1312
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1313
- return record;
1314
- }
1315
- throw new Error("Invalid arguments for createOrUpdate method");
1500
+ if (isObject(a) && isString(a.id)) {
1501
+ const columns = isStringArray(b) ? b : void 0;
1502
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1503
+ }
1504
+ throw new Error("Invalid arguments for update method");
1505
+ });
1506
+ }
1507
+ async createOrUpdate(a, b, c) {
1508
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1509
+ if (Array.isArray(a)) {
1510
+ if (a.length === 0)
1511
+ return [];
1512
+ if (a.length > 100) {
1513
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1514
+ }
1515
+ const columns = isStringArray(b) ? b : ["*"];
1516
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1517
+ }
1518
+ if (isString(a) && isObject(b)) {
1519
+ const columns = isStringArray(c) ? c : void 0;
1520
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1521
+ }
1522
+ if (isObject(a) && isString(a.id)) {
1523
+ const columns = isStringArray(c) ? c : void 0;
1524
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1525
+ }
1526
+ throw new Error("Invalid arguments for createOrUpdate method");
1527
+ });
1316
1528
  }
1317
1529
  async delete(a) {
1318
- if (Array.isArray(a)) {
1319
- if (a.length === 0)
1530
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1531
+ if (Array.isArray(a)) {
1532
+ if (a.length === 0)
1533
+ return;
1534
+ if (a.length > 100) {
1535
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1536
+ }
1537
+ await Promise.all(a.map((id) => this.delete(id)));
1320
1538
  return;
1321
- if (a.length > 100) {
1322
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1323
1539
  }
1324
- await Promise.all(a.map((id) => this.delete(id)));
1325
- return;
1326
- }
1327
- if (isString(a)) {
1328
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1329
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1330
- return;
1331
- }
1332
- if (isObject(a) && isString(a.id)) {
1333
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1334
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1335
- return;
1336
- }
1337
- throw new Error("Invalid arguments for delete method");
1540
+ if (isString(a)) {
1541
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1542
+ return;
1543
+ }
1544
+ if (isObject(a) && isString(a.id)) {
1545
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1546
+ return;
1547
+ }
1548
+ throw new Error("Invalid arguments for delete method");
1549
+ });
1338
1550
  }
1339
1551
  async search(query, options = {}) {
1340
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1341
- const { records } = await searchTable({
1342
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1343
- body: {
1344
- query,
1345
- fuzziness: options.fuzziness,
1346
- highlight: options.highlight,
1347
- filter: options.filter
1348
- },
1349
- ...fetchProps
1552
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1553
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1554
+ const { records } = await searchTable({
1555
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1556
+ body: {
1557
+ query,
1558
+ fuzziness: options.fuzziness,
1559
+ prefix: options.prefix,
1560
+ highlight: options.highlight,
1561
+ filter: options.filter,
1562
+ boosters: options.boosters
1563
+ },
1564
+ ...fetchProps
1565
+ });
1566
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1567
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1350
1568
  });
1351
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1352
- return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1353
1569
  }
1354
1570
  async query(query) {
1355
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1356
- if (cacheQuery)
1357
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1358
- const data = query.getQueryOptions();
1359
- const body = {
1360
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1361
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1362
- page: data.pagination,
1363
- columns: data.columns
1364
- };
1365
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1366
- const { meta, records: objects } = await queryTable({
1367
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1368
- body,
1369
- ...fetchProps
1571
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1572
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1573
+ if (cacheQuery)
1574
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1575
+ const data = query.getQueryOptions();
1576
+ const body = {
1577
+ filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1578
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1579
+ page: data.pagination,
1580
+ columns: data.columns
1581
+ };
1582
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1583
+ const { meta, records: objects } = await queryTable({
1584
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1585
+ body,
1586
+ ...fetchProps
1587
+ });
1588
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1589
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1590
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1591
+ return new Page(query, meta, records);
1370
1592
  });
1371
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1372
- const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1373
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1374
- return new Page(query, meta, records);
1375
1593
  }
1376
1594
  }
1377
1595
  _table = new WeakMap();
1378
1596
  _getFetchProps = new WeakMap();
1597
+ _db = new WeakMap();
1379
1598
  _cache = new WeakMap();
1380
- _schema$1 = new WeakMap();
1599
+ _schemaTables$2 = new WeakMap();
1600
+ _trace = new WeakMap();
1381
1601
  _insertRecordWithoutId = new WeakSet();
1382
- insertRecordWithoutId_fn = async function(object) {
1602
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1383
1603
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1384
1604
  const record = transformObjectLinks(object);
1385
1605
  const response = await insertRecord({
@@ -1388,17 +1608,15 @@ insertRecordWithoutId_fn = async function(object) {
1388
1608
  dbBranchName: "{dbBranch}",
1389
1609
  tableName: __privateGet$4(this, _table)
1390
1610
  },
1611
+ queryParams: { columns },
1391
1612
  body: record,
1392
1613
  ...fetchProps
1393
1614
  });
1394
- const finalObject = await this.read(response.id);
1395
- if (!finalObject) {
1396
- throw new Error("The server failed to save the record");
1397
- }
1398
- return finalObject;
1615
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1616
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1399
1617
  };
1400
1618
  _insertRecordWithId = new WeakSet();
1401
- insertRecordWithId_fn = async function(recordId, object) {
1619
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1402
1620
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1403
1621
  const record = transformObjectLinks(object);
1404
1622
  const response = await insertRecordWithID({
@@ -1409,56 +1627,52 @@ insertRecordWithId_fn = async function(recordId, object) {
1409
1627
  recordId
1410
1628
  },
1411
1629
  body: record,
1412
- queryParams: { createOnly: true },
1630
+ queryParams: { createOnly: true, columns },
1413
1631
  ...fetchProps
1414
1632
  });
1415
- const finalObject = await this.read(response.id);
1416
- if (!finalObject) {
1417
- throw new Error("The server failed to save the record");
1418
- }
1419
- return finalObject;
1633
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1634
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1420
1635
  };
1421
1636
  _bulkInsertTableRecords = new WeakSet();
1422
- bulkInsertTableRecords_fn = async function(objects) {
1637
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1423
1638
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1424
1639
  const records = objects.map((object) => transformObjectLinks(object));
1425
1640
  const response = await bulkInsertTableRecords({
1426
1641
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1642
+ queryParams: { columns },
1427
1643
  body: { records },
1428
1644
  ...fetchProps
1429
1645
  });
1430
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1431
- if (finalObjects.length !== objects.length) {
1432
- throw new Error("The server failed to save some records");
1646
+ if (!isResponseWithRecords(response)) {
1647
+ throw new Error("Request included columns but server didn't include them");
1433
1648
  }
1434
- return finalObjects;
1649
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1650
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1435
1651
  };
1436
1652
  _updateRecordWithID = new WeakSet();
1437
- updateRecordWithID_fn = async function(recordId, object) {
1653
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1438
1654
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1439
1655
  const record = transformObjectLinks(object);
1440
1656
  const response = await updateRecordWithID({
1441
1657
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1658
+ queryParams: { columns },
1442
1659
  body: record,
1443
1660
  ...fetchProps
1444
1661
  });
1445
- const item = await this.read(response.id);
1446
- if (!item)
1447
- throw new Error("The server failed to save the record");
1448
- return item;
1662
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1663
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1449
1664
  };
1450
1665
  _upsertRecordWithID = new WeakSet();
1451
- upsertRecordWithID_fn = async function(recordId, object) {
1666
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1452
1667
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1453
1668
  const response = await upsertRecordWithID({
1454
1669
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1670
+ queryParams: { columns },
1455
1671
  body: object,
1456
1672
  ...fetchProps
1457
1673
  });
1458
- const item = await this.read(response.id);
1459
- if (!item)
1460
- throw new Error("The server failed to save the record");
1461
- return item;
1674
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1675
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1462
1676
  };
1463
1677
  _deleteRecord = new WeakSet();
1464
1678
  deleteRecord_fn = async function(recordId) {
@@ -1468,29 +1682,6 @@ deleteRecord_fn = async function(recordId) {
1468
1682
  ...fetchProps
1469
1683
  });
1470
1684
  };
1471
- _invalidateCache = new WeakSet();
1472
- invalidateCache_fn = async function(recordId) {
1473
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1474
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1475
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1476
- for (const [key, value] of queries) {
1477
- const ids = getIds(value);
1478
- if (ids.includes(recordId))
1479
- await __privateGet$4(this, _cache).delete(key);
1480
- }
1481
- };
1482
- _setCacheRecord = new WeakSet();
1483
- setCacheRecord_fn = async function(record) {
1484
- if (!__privateGet$4(this, _cache).cacheRecords)
1485
- return;
1486
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1487
- };
1488
- _getCacheRecord = new WeakSet();
1489
- getCacheRecord_fn = async function(recordId) {
1490
- if (!__privateGet$4(this, _cache).cacheRecords)
1491
- return null;
1492
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1493
- };
1494
1685
  _setCacheQuery = new WeakSet();
1495
1686
  setCacheQuery_fn = async function(query, meta, records) {
1496
1687
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -1507,17 +1698,17 @@ getCacheQuery_fn = async function(query) {
1507
1698
  const hasExpired = result.date.getTime() + ttl < Date.now();
1508
1699
  return hasExpired ? null : result;
1509
1700
  };
1510
- _getSchema$1 = new WeakSet();
1511
- getSchema_fn$1 = async function() {
1512
- if (__privateGet$4(this, _schema$1))
1513
- return __privateGet$4(this, _schema$1);
1701
+ _getSchemaTables$1 = new WeakSet();
1702
+ getSchemaTables_fn$1 = async function() {
1703
+ if (__privateGet$4(this, _schemaTables$2))
1704
+ return __privateGet$4(this, _schemaTables$2);
1514
1705
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1515
1706
  const { schema } = await getBranchDetails({
1516
1707
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1517
1708
  ...fetchProps
1518
1709
  });
1519
- __privateSet$3(this, _schema$1, schema);
1520
- return schema;
1710
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1711
+ return schema.tables;
1521
1712
  };
1522
1713
  const transformObjectLinks = (object) => {
1523
1714
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1526,10 +1717,11 @@ const transformObjectLinks = (object) => {
1526
1717
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1527
1718
  }, {});
1528
1719
  };
1529
- const initObject = (db, schema, table, object) => {
1720
+ const initObject = (db, schemaTables, table, object) => {
1530
1721
  const result = {};
1531
- Object.assign(result, object);
1532
- const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1722
+ const { xata, ...rest } = object ?? {};
1723
+ Object.assign(result, rest);
1724
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1533
1725
  if (!columns)
1534
1726
  console.error(`Table ${table} not found in schema`);
1535
1727
  for (const column of columns ?? []) {
@@ -1549,35 +1741,32 @@ const initObject = (db, schema, table, object) => {
1549
1741
  if (!linkTable) {
1550
1742
  console.error(`Failed to parse link for field ${column.name}`);
1551
1743
  } else if (isObject(value)) {
1552
- result[column.name] = initObject(db, schema, linkTable, value);
1744
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1553
1745
  }
1554
1746
  break;
1555
1747
  }
1556
1748
  }
1557
1749
  }
1558
- result.read = function() {
1559
- return db[table].read(result["id"]);
1750
+ result.read = function(columns2) {
1751
+ return db[table].read(result["id"], columns2);
1560
1752
  };
1561
- result.update = function(data) {
1562
- return db[table].update(result["id"], data);
1753
+ result.update = function(data, columns2) {
1754
+ return db[table].update(result["id"], data, columns2);
1563
1755
  };
1564
1756
  result.delete = function() {
1565
1757
  return db[table].delete(result["id"]);
1566
1758
  };
1567
- for (const prop of ["read", "update", "delete"]) {
1759
+ result.getMetadata = function() {
1760
+ return xata;
1761
+ };
1762
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1568
1763
  Object.defineProperty(result, prop, { enumerable: false });
1569
1764
  }
1570
1765
  Object.freeze(result);
1571
1766
  return result;
1572
1767
  };
1573
- function getIds(value) {
1574
- if (Array.isArray(value)) {
1575
- return value.map((item) => getIds(item)).flat();
1576
- }
1577
- if (!isObject(value))
1578
- return [];
1579
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1580
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1768
+ function isResponseWithRecords(value) {
1769
+ return isObject(value) && Array.isArray(value.records);
1581
1770
  }
1582
1771
 
1583
1772
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1593,7 +1782,7 @@ var __privateAdd$3 = (obj, member, value) => {
1593
1782
  throw TypeError("Cannot add the same private member more than once");
1594
1783
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1595
1784
  };
1596
- var __privateSet$2 = (obj, member, value, setter) => {
1785
+ var __privateSet$3 = (obj, member, value, setter) => {
1597
1786
  __accessCheck$3(obj, member, "write to private field");
1598
1787
  setter ? setter.call(obj, value) : member.set(obj, value);
1599
1788
  return value;
@@ -1602,9 +1791,8 @@ var _map;
1602
1791
  class SimpleCache {
1603
1792
  constructor(options = {}) {
1604
1793
  __privateAdd$3(this, _map, void 0);
1605
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1794
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1606
1795
  this.capacity = options.max ?? 500;
1607
- this.cacheRecords = options.cacheRecords ?? true;
1608
1796
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1609
1797
  }
1610
1798
  async getAll() {
@@ -1630,18 +1818,25 @@ class SimpleCache {
1630
1818
  }
1631
1819
  _map = new WeakMap();
1632
1820
 
1633
- const gt = (value) => ({ $gt: value });
1634
- const ge = (value) => ({ $ge: value });
1635
- const gte = (value) => ({ $ge: value });
1636
- const lt = (value) => ({ $lt: value });
1637
- const lte = (value) => ({ $le: value });
1638
- const le = (value) => ({ $le: value });
1821
+ const greaterThan = (value) => ({ $gt: value });
1822
+ const gt = greaterThan;
1823
+ const greaterThanEquals = (value) => ({ $ge: value });
1824
+ const greaterEquals = greaterThanEquals;
1825
+ const gte = greaterThanEquals;
1826
+ const ge = greaterThanEquals;
1827
+ const lessThan = (value) => ({ $lt: value });
1828
+ const lt = lessThan;
1829
+ const lessThanEquals = (value) => ({ $le: value });
1830
+ const lessEquals = lessThanEquals;
1831
+ const lte = lessThanEquals;
1832
+ const le = lessThanEquals;
1639
1833
  const exists = (column) => ({ $exists: column });
1640
1834
  const notExists = (column) => ({ $notExists: column });
1641
1835
  const startsWith = (value) => ({ $startsWith: value });
1642
1836
  const endsWith = (value) => ({ $endsWith: value });
1643
1837
  const pattern = (value) => ({ $pattern: value });
1644
1838
  const is = (value) => ({ $is: value });
1839
+ const equals = is;
1645
1840
  const isNot = (value) => ({ $isNot: value });
1646
1841
  const contains = (value) => ({ $contains: value });
1647
1842
  const includes = (value) => ({ $includes: value });
@@ -1662,31 +1857,42 @@ var __privateAdd$2 = (obj, member, value) => {
1662
1857
  throw TypeError("Cannot add the same private member more than once");
1663
1858
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1664
1859
  };
1665
- var _tables;
1860
+ var __privateSet$2 = (obj, member, value, setter) => {
1861
+ __accessCheck$2(obj, member, "write to private field");
1862
+ setter ? setter.call(obj, value) : member.set(obj, value);
1863
+ return value;
1864
+ };
1865
+ var _tables, _schemaTables$1;
1666
1866
  class SchemaPlugin extends XataPlugin {
1667
- constructor(tableNames) {
1867
+ constructor(schemaTables) {
1668
1868
  super();
1669
- this.tableNames = tableNames;
1670
1869
  __privateAdd$2(this, _tables, {});
1870
+ __privateAdd$2(this, _schemaTables$1, void 0);
1871
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1671
1872
  }
1672
1873
  build(pluginOptions) {
1673
- const db = new Proxy({}, {
1674
- get: (_target, table) => {
1675
- if (!isString(table))
1676
- throw new Error("Invalid table name");
1677
- if (__privateGet$2(this, _tables)[table] === void 0) {
1678
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1874
+ const db = new Proxy(
1875
+ {},
1876
+ {
1877
+ get: (_target, table) => {
1878
+ if (!isString(table))
1879
+ throw new Error("Invalid table name");
1880
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1881
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1882
+ }
1883
+ return __privateGet$2(this, _tables)[table];
1679
1884
  }
1680
- return __privateGet$2(this, _tables)[table];
1681
1885
  }
1682
- });
1683
- for (const table of this.tableNames ?? []) {
1684
- db[table] = new RestRepository({ db, pluginOptions, table });
1886
+ );
1887
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1888
+ for (const table of tableNames) {
1889
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1685
1890
  }
1686
1891
  return db;
1687
1892
  }
1688
1893
  }
1689
1894
  _tables = new WeakMap();
1895
+ _schemaTables$1 = new WeakMap();
1690
1896
 
1691
1897
  var __accessCheck$1 = (obj, member, msg) => {
1692
1898
  if (!member.has(obj))
@@ -1710,82 +1916,77 @@ var __privateMethod$1 = (obj, member, method) => {
1710
1916
  __accessCheck$1(obj, member, "access private method");
1711
1917
  return method;
1712
1918
  };
1713
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
1919
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1714
1920
  class SearchPlugin extends XataPlugin {
1715
- constructor(db) {
1921
+ constructor(db, schemaTables) {
1716
1922
  super();
1717
1923
  this.db = db;
1718
1924
  __privateAdd$1(this, _search);
1719
- __privateAdd$1(this, _getSchema);
1720
- __privateAdd$1(this, _schema, void 0);
1925
+ __privateAdd$1(this, _getSchemaTables);
1926
+ __privateAdd$1(this, _schemaTables, void 0);
1927
+ __privateSet$1(this, _schemaTables, schemaTables);
1721
1928
  }
1722
1929
  build({ getFetchProps }) {
1723
1930
  return {
1724
1931
  all: async (query, options = {}) => {
1725
1932
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1726
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1933
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1727
1934
  return records.map((record) => {
1728
1935
  const { table = "orphan" } = record.xata;
1729
- return { table, record: initObject(this.db, schema, table, record) };
1936
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1730
1937
  });
1731
1938
  },
1732
1939
  byTable: async (query, options = {}) => {
1733
1940
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1734
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1941
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1735
1942
  return records.reduce((acc, record) => {
1736
1943
  const { table = "orphan" } = record.xata;
1737
1944
  const items = acc[table] ?? [];
1738
- const item = initObject(this.db, schema, table, record);
1945
+ const item = initObject(this.db, schemaTables, table, record);
1739
1946
  return { ...acc, [table]: [...items, item] };
1740
1947
  }, {});
1741
1948
  }
1742
1949
  };
1743
1950
  }
1744
1951
  }
1745
- _schema = new WeakMap();
1952
+ _schemaTables = new WeakMap();
1746
1953
  _search = new WeakSet();
1747
1954
  search_fn = async function(query, options, getFetchProps) {
1748
1955
  const fetchProps = await getFetchProps();
1749
- const { tables, fuzziness, highlight } = options ?? {};
1956
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1750
1957
  const { records } = await searchBranch({
1751
1958
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1752
- body: { tables, query, fuzziness, highlight },
1959
+ body: { tables, query, fuzziness, prefix, highlight },
1753
1960
  ...fetchProps
1754
1961
  });
1755
1962
  return records;
1756
1963
  };
1757
- _getSchema = new WeakSet();
1758
- getSchema_fn = async function(getFetchProps) {
1759
- if (__privateGet$1(this, _schema))
1760
- return __privateGet$1(this, _schema);
1964
+ _getSchemaTables = new WeakSet();
1965
+ getSchemaTables_fn = async function(getFetchProps) {
1966
+ if (__privateGet$1(this, _schemaTables))
1967
+ return __privateGet$1(this, _schemaTables);
1761
1968
  const fetchProps = await getFetchProps();
1762
1969
  const { schema } = await getBranchDetails({
1763
1970
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1764
1971
  ...fetchProps
1765
1972
  });
1766
- __privateSet$1(this, _schema, schema);
1767
- return schema;
1973
+ __privateSet$1(this, _schemaTables, schema.tables);
1974
+ return schema.tables;
1768
1975
  };
1769
1976
 
1770
1977
  const isBranchStrategyBuilder = (strategy) => {
1771
1978
  return typeof strategy === "function";
1772
1979
  };
1773
1980
 
1774
- const envBranchNames = [
1775
- "XATA_BRANCH",
1776
- "VERCEL_GIT_COMMIT_REF",
1777
- "CF_PAGES_BRANCH",
1778
- "BRANCH"
1779
- ];
1780
1981
  async function getCurrentBranchName(options) {
1781
- const env = getBranchByEnvVariable();
1782
- if (env) {
1783
- const details = await getDatabaseBranch(env, options);
1982
+ const { branch, envBranch } = getEnvironment();
1983
+ if (branch) {
1984
+ const details = await getDatabaseBranch(branch, options);
1784
1985
  if (details)
1785
- return env;
1786
- console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1986
+ return branch;
1987
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1787
1988
  }
1788
- const gitBranch = await getGitBranch();
1989
+ const gitBranch = envBranch || await getGitBranch();
1789
1990
  return resolveXataBranch(gitBranch, options);
1790
1991
  }
1791
1992
  async function getCurrentBranchDetails(options) {
@@ -1796,18 +1997,24 @@ async function resolveXataBranch(gitBranch, options) {
1796
1997
  const databaseURL = options?.databaseURL || getDatabaseURL();
1797
1998
  const apiKey = options?.apiKey || getAPIKey();
1798
1999
  if (!databaseURL)
1799
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2000
+ throw new Error(
2001
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2002
+ );
1800
2003
  if (!apiKey)
1801
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2004
+ throw new Error(
2005
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2006
+ );
1802
2007
  const [protocol, , host, , dbName] = databaseURL.split("/");
1803
2008
  const [workspace] = host.split(".");
2009
+ const { fallbackBranch } = getEnvironment();
1804
2010
  const { branch } = await resolveBranch({
1805
2011
  apiKey,
1806
2012
  apiUrl: databaseURL,
1807
2013
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1808
2014
  workspacesApiUrl: `${protocol}//${host}`,
1809
2015
  pathParams: { dbName, workspace },
1810
- queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
2016
+ queryParams: { gitBranch, fallbackBranch },
2017
+ trace: defaultTrace
1811
2018
  });
1812
2019
  return branch;
1813
2020
  }
@@ -1815,9 +2022,13 @@ async function getDatabaseBranch(branch, options) {
1815
2022
  const databaseURL = options?.databaseURL || getDatabaseURL();
1816
2023
  const apiKey = options?.apiKey || getAPIKey();
1817
2024
  if (!databaseURL)
1818
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2025
+ throw new Error(
2026
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2027
+ );
1819
2028
  if (!apiKey)
1820
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2029
+ throw new Error(
2030
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2031
+ );
1821
2032
  const [protocol, , host, , database] = databaseURL.split("/");
1822
2033
  const [workspace] = host.split(".");
1823
2034
  const dbBranchName = `${database}:${branch}`;
@@ -1827,10 +2038,8 @@ async function getDatabaseBranch(branch, options) {
1827
2038
  apiUrl: databaseURL,
1828
2039
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1829
2040
  workspacesApiUrl: `${protocol}//${host}`,
1830
- pathParams: {
1831
- dbBranchName,
1832
- workspace
1833
- }
2041
+ pathParams: { dbBranchName, workspace },
2042
+ trace: defaultTrace
1834
2043
  });
1835
2044
  } catch (err) {
1836
2045
  if (isObject(err) && err.status === 404)
@@ -1838,21 +2047,10 @@ async function getDatabaseBranch(branch, options) {
1838
2047
  throw err;
1839
2048
  }
1840
2049
  }
1841
- function getBranchByEnvVariable() {
1842
- for (const name of envBranchNames) {
1843
- const value = getEnvVariable(name);
1844
- if (value) {
1845
- return value;
1846
- }
1847
- }
1848
- try {
1849
- return XATA_BRANCH;
1850
- } catch (err) {
1851
- }
1852
- }
1853
2050
  function getDatabaseURL() {
1854
2051
  try {
1855
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2052
+ const { databaseURL } = getEnvironment();
2053
+ return databaseURL;
1856
2054
  } catch (err) {
1857
2055
  return void 0;
1858
2056
  }
@@ -1881,20 +2079,23 @@ var __privateMethod = (obj, member, method) => {
1881
2079
  return method;
1882
2080
  };
1883
2081
  const buildClient = (plugins) => {
1884
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2082
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1885
2083
  return _a = class {
1886
- constructor(options = {}, tables) {
2084
+ constructor(options = {}, schemaTables) {
1887
2085
  __privateAdd(this, _parseOptions);
1888
2086
  __privateAdd(this, _getFetchProps);
1889
2087
  __privateAdd(this, _evaluateBranch);
1890
2088
  __privateAdd(this, _branch, void 0);
2089
+ __privateAdd(this, _options, void 0);
1891
2090
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2091
+ __privateSet(this, _options, safeOptions);
1892
2092
  const pluginOptions = {
1893
2093
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1894
- cache: safeOptions.cache
2094
+ cache: safeOptions.cache,
2095
+ trace: safeOptions.trace
1895
2096
  };
1896
- const db = new SchemaPlugin(tables).build(pluginOptions);
1897
- const search = new SearchPlugin(db).build(pluginOptions);
2097
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2098
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1898
2099
  this.db = db;
1899
2100
  this.search = search;
1900
2101
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
@@ -1910,22 +2111,26 @@ const buildClient = (plugins) => {
1910
2111
  }
1911
2112
  }
1912
2113
  }
1913
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2114
+ async getConfig() {
2115
+ const databaseURL = __privateGet(this, _options).databaseURL;
2116
+ const branch = await __privateGet(this, _options).branch();
2117
+ return { databaseURL, branch };
2118
+ }
2119
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1914
2120
  const fetch = getFetchImplementation(options?.fetch);
1915
2121
  const databaseURL = options?.databaseURL || getDatabaseURL();
1916
2122
  const apiKey = options?.apiKey || getAPIKey();
1917
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2123
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2124
+ const trace = options?.trace ?? defaultTrace;
1918
2125
  const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1919
- if (!databaseURL || !apiKey) {
1920
- throw new Error("Options databaseURL and apiKey are required");
2126
+ if (!apiKey) {
2127
+ throw new Error("Option apiKey is required");
1921
2128
  }
1922
- return { fetch, databaseURL, apiKey, branch, cache };
1923
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1924
- fetch,
1925
- apiKey,
1926
- databaseURL,
1927
- branch
1928
- }) {
2129
+ if (!databaseURL) {
2130
+ throw new Error("Option databaseURL is required");
2131
+ }
2132
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2133
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
1929
2134
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1930
2135
  if (!branchValue)
1931
2136
  throw new Error("Unable to resolve branch value");
@@ -1937,7 +2142,8 @@ const buildClient = (plugins) => {
1937
2142
  const hasBranch = params.dbBranchName ?? params.branch;
1938
2143
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
1939
2144
  return databaseURL + newPath;
1940
- }
2145
+ },
2146
+ trace
1941
2147
  };
1942
2148
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1943
2149
  if (__privateGet(this, _branch))
@@ -1960,6 +2166,88 @@ const buildClient = (plugins) => {
1960
2166
  class BaseClient extends buildClient() {
1961
2167
  }
1962
2168
 
2169
+ const META = "__";
2170
+ const VALUE = "___";
2171
+ class Serializer {
2172
+ constructor() {
2173
+ this.classes = {};
2174
+ }
2175
+ add(clazz) {
2176
+ this.classes[clazz.name] = clazz;
2177
+ }
2178
+ toJSON(data) {
2179
+ function visit(obj) {
2180
+ if (Array.isArray(obj))
2181
+ return obj.map(visit);
2182
+ const type = typeof obj;
2183
+ if (type === "undefined")
2184
+ return { [META]: "undefined" };
2185
+ if (type === "bigint")
2186
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2187
+ if (obj === null || type !== "object")
2188
+ return obj;
2189
+ const constructor = obj.constructor;
2190
+ const o = { [META]: constructor.name };
2191
+ for (const [key, value] of Object.entries(obj)) {
2192
+ o[key] = visit(value);
2193
+ }
2194
+ if (constructor === Date)
2195
+ o[VALUE] = obj.toISOString();
2196
+ if (constructor === Map)
2197
+ o[VALUE] = Object.fromEntries(obj);
2198
+ if (constructor === Set)
2199
+ o[VALUE] = [...obj];
2200
+ return o;
2201
+ }
2202
+ return JSON.stringify(visit(data));
2203
+ }
2204
+ fromJSON(json) {
2205
+ return JSON.parse(json, (key, value) => {
2206
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2207
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2208
+ const constructor = this.classes[clazz];
2209
+ if (constructor) {
2210
+ return Object.assign(Object.create(constructor.prototype), rest);
2211
+ }
2212
+ if (clazz === "Date")
2213
+ return new Date(val);
2214
+ if (clazz === "Set")
2215
+ return new Set(val);
2216
+ if (clazz === "Map")
2217
+ return new Map(Object.entries(val));
2218
+ if (clazz === "bigint")
2219
+ return BigInt(val);
2220
+ if (clazz === "undefined")
2221
+ return void 0;
2222
+ return rest;
2223
+ }
2224
+ return value;
2225
+ });
2226
+ }
2227
+ }
2228
+ const defaultSerializer = new Serializer();
2229
+ const serialize = (data) => {
2230
+ return defaultSerializer.toJSON(data);
2231
+ };
2232
+ const deserialize = (json) => {
2233
+ return defaultSerializer.fromJSON(json);
2234
+ };
2235
+
2236
+ function buildWorkerRunner(config) {
2237
+ return function xataWorker(name, _worker) {
2238
+ return async (...args) => {
2239
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2240
+ const result = await fetch(url, {
2241
+ method: "POST",
2242
+ headers: { "Content-Type": "application/json" },
2243
+ body: serialize({ args })
2244
+ });
2245
+ const text = await result.text();
2246
+ return deserialize(text);
2247
+ };
2248
+ };
2249
+ }
2250
+
1963
2251
  class XataError extends Error {
1964
2252
  constructor(message, status) {
1965
2253
  super(message);
@@ -1967,5 +2255,5 @@ class XataError extends Error {
1967
2255
  }
1968
2256
  }
1969
2257
 
1970
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, 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 };
2258
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
1971
2259
  //# sourceMappingURL=index.mjs.map