@xata.io/client 0.0.0-alpha.vf27674a → 0.0.0-alpha.vf3111df

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
  }
@@ -7,46 +31,101 @@ function compact(arr) {
7
31
  function isObject(value) {
8
32
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
33
  }
34
+ function isDefined(value) {
35
+ return value !== null && value !== void 0;
36
+ }
10
37
  function isString(value) {
11
- return value !== void 0 && value !== null && typeof value === "string";
38
+ return isDefined(value) && typeof value === "string";
39
+ }
40
+ function isStringArray(value) {
41
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
12
42
  }
13
43
  function toBase64(value) {
14
44
  try {
15
45
  return btoa(value);
16
46
  } catch (err) {
17
- return Buffer.from(value).toString("base64");
47
+ const buf = Buffer;
48
+ return buf.from(value).toString("base64");
18
49
  }
19
50
  }
20
51
 
21
- function getEnvVariable(name) {
52
+ function getEnvironment() {
22
53
  try {
23
- if (isObject(process) && isString(process?.env?.[name])) {
24
- 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
+ };
25
62
  }
26
63
  } catch (err) {
27
64
  }
28
65
  try {
29
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
30
- 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
+ };
31
74
  }
32
75
  } catch (err) {
33
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
+ }
34
112
  }
35
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"] };
36
118
  try {
37
119
  if (typeof require === "function") {
38
- const req = require;
39
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
120
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
40
121
  }
122
+ const { execSync } = await import(nodeModule);
123
+ return execSync(fullCmd, execOptions).toString().trim();
41
124
  } catch (err) {
42
125
  }
43
126
  try {
44
127
  if (isObject(Deno)) {
45
- const process2 = Deno.run({
46
- cmd: ["git", "branch", "--show-current"],
47
- stdout: "piped",
48
- stderr: "piped"
49
- });
128
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
50
129
  return new TextDecoder().decode(await process2.output()).trim();
51
130
  }
52
131
  } catch (err) {
@@ -55,7 +134,8 @@ async function getGitBranch() {
55
134
 
56
135
  function getAPIKey() {
57
136
  try {
58
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
137
+ const { apiKey } = getEnvironment();
138
+ return apiKey;
59
139
  } catch (err) {
60
140
  return void 0;
61
141
  }
@@ -65,21 +145,35 @@ function getFetchImplementation(userFetch) {
65
145
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
66
146
  const fetchImpl = userFetch ?? globalFetch;
67
147
  if (!fetchImpl) {
68
- 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
+ );
69
151
  }
70
152
  return fetchImpl;
71
153
  }
72
154
 
73
- class FetcherError extends Error {
74
- constructor(status, data) {
155
+ const VERSION = "0.0.0-alpha.vf3111df";
156
+
157
+ class ErrorWithCause extends Error {
158
+ constructor(message, options) {
159
+ super(message, options);
160
+ }
161
+ }
162
+ class FetcherError extends ErrorWithCause {
163
+ constructor(status, data, requestId) {
75
164
  super(getMessage(data));
76
165
  this.status = status;
77
166
  this.errors = isBulkError(data) ? data.errors : void 0;
167
+ this.requestId = requestId;
78
168
  if (data instanceof Error) {
79
169
  this.stack = data.stack;
80
170
  this.cause = data.cause;
81
171
  }
82
172
  }
173
+ toString() {
174
+ const error = super.toString();
175
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
176
+ }
83
177
  }
84
178
  function isBulkError(error) {
85
179
  return isObject(error) && Array.isArray(error.errors);
@@ -102,7 +196,12 @@ function getMessage(data) {
102
196
  }
103
197
 
104
198
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
105
- 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();
106
205
  const queryString = query.length > 0 ? `?${query}` : "";
107
206
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
108
207
  };
@@ -132,32 +231,62 @@ async function fetch$1({
132
231
  fetchImpl,
133
232
  apiKey,
134
233
  apiUrl,
135
- workspacesApiUrl
234
+ workspacesApiUrl,
235
+ trace
136
236
  }) {
137
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
138
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
139
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
140
- const response = await fetchImpl(url, {
141
- method: method.toUpperCase(),
142
- body: body ? JSON.stringify(body) : void 0,
143
- headers: {
144
- "Content-Type": "application/json",
145
- ...headers,
146
- ...hostHeader(fullUrl),
147
- Authorization: `Bearer ${apiKey}`
148
- }
149
- });
150
- if (response.status === 204) {
151
- return {};
152
- }
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) {
153
285
  try {
154
- const jsonResponse = await response.json();
155
- if (response.ok) {
156
- return jsonResponse;
157
- }
158
- throw new FetcherError(response.status, jsonResponse);
286
+ const { host, protocol } = new URL(url);
287
+ return { host, protocol };
159
288
  } catch (error) {
160
- throw new FetcherError(response.status, error);
289
+ return {};
161
290
  }
162
291
  }
163
292
 
@@ -216,6 +345,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
216
345
  ...variables
217
346
  });
218
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 });
219
349
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
220
350
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
221
351
  method: "delete",
@@ -251,6 +381,11 @@ const deleteDatabase = (variables) => fetch$1({
251
381
  method: "delete",
252
382
  ...variables
253
383
  });
384
+ const getDatabaseMetadata = (variables) => fetch$1({
385
+ url: "/dbs/{dbName}/metadata",
386
+ method: "get",
387
+ ...variables
388
+ });
254
389
  const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
255
390
  const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
256
391
  const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
@@ -264,11 +399,7 @@ const getBranchDetails = (variables) => fetch$1({
264
399
  method: "get",
265
400
  ...variables
266
401
  });
267
- const createBranch = (variables) => fetch$1({
268
- url: "/db/{dbBranchName}",
269
- method: "put",
270
- ...variables
271
- });
402
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
272
403
  const deleteBranch = (variables) => fetch$1({
273
404
  url: "/db/{dbBranchName}",
274
405
  method: "delete",
@@ -342,11 +473,7 @@ const updateColumn = (variables) => fetch$1({
342
473
  method: "patch",
343
474
  ...variables
344
475
  });
345
- const insertRecord = (variables) => fetch$1({
346
- url: "/db/{dbBranchName}/tables/{tableName}/data",
347
- method: "post",
348
- ...variables
349
- });
476
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
350
477
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
351
478
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
352
479
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -366,6 +493,11 @@ const queryTable = (variables) => fetch$1({
366
493
  method: "post",
367
494
  ...variables
368
495
  });
496
+ const searchTable = (variables) => fetch$1({
497
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
498
+ method: "post",
499
+ ...variables
500
+ });
369
501
  const searchBranch = (variables) => fetch$1({
370
502
  url: "/db/{dbBranchName}/search",
371
503
  method: "post",
@@ -383,6 +515,7 @@ const operationsByTag = {
383
515
  updateWorkspaceMemberRole,
384
516
  removeWorkspaceMember,
385
517
  inviteWorkspaceMember,
518
+ updateWorkspaceMemberInvite,
386
519
  cancelWorkspaceMemberInvite,
387
520
  resendWorkspaceMemberInvite,
388
521
  acceptWorkspaceMemberInvite
@@ -391,6 +524,7 @@ const operationsByTag = {
391
524
  getDatabaseList,
392
525
  createDatabase,
393
526
  deleteDatabase,
527
+ getDatabaseMetadata,
394
528
  getGitBranchesMapping,
395
529
  addGitBranchesEntry,
396
530
  removeGitBranchesEntry,
@@ -429,6 +563,7 @@ const operationsByTag = {
429
563
  getRecord,
430
564
  bulkInsertTableRecords,
431
565
  queryTable,
566
+ searchTable,
432
567
  searchBranch
433
568
  }
434
569
  };
@@ -471,7 +606,7 @@ var __privateAdd$7 = (obj, member, value) => {
471
606
  throw TypeError("Cannot add the same private member more than once");
472
607
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
473
608
  };
474
- var __privateSet$6 = (obj, member, value, setter) => {
609
+ var __privateSet$7 = (obj, member, value, setter) => {
475
610
  __accessCheck$7(obj, member, "write to private field");
476
611
  setter ? setter.call(obj, value) : member.set(obj, value);
477
612
  return value;
@@ -482,15 +617,17 @@ class XataApiClient {
482
617
  __privateAdd$7(this, _extraProps, void 0);
483
618
  __privateAdd$7(this, _namespaces, {});
484
619
  const provider = options.host ?? "production";
485
- const apiKey = options?.apiKey ?? getAPIKey();
620
+ const apiKey = options.apiKey ?? getAPIKey();
621
+ const trace = options.trace ?? defaultTrace;
486
622
  if (!apiKey) {
487
623
  throw new Error("Could not resolve a valid apiKey");
488
624
  }
489
- __privateSet$6(this, _extraProps, {
625
+ __privateSet$7(this, _extraProps, {
490
626
  apiUrl: getHostUrl(provider, "main"),
491
627
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
492
628
  fetchImpl: getFetchImplementation(options.fetch),
493
- apiKey
629
+ apiKey,
630
+ trace
494
631
  });
495
632
  }
496
633
  get user() {
@@ -613,6 +750,13 @@ class WorkspaceApi {
613
750
  ...this.extraProps
614
751
  });
615
752
  }
753
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
754
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
755
+ pathParams: { workspaceId, inviteId },
756
+ body: { role },
757
+ ...this.extraProps
758
+ });
759
+ }
616
760
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
617
761
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
618
762
  pathParams: { workspaceId, inviteId },
@@ -655,6 +799,12 @@ class DatabaseApi {
655
799
  ...this.extraProps
656
800
  });
657
801
  }
802
+ getDatabaseMetadata(workspace, dbName) {
803
+ return operationsByTag.database.getDatabaseMetadata({
804
+ pathParams: { workspace, dbName },
805
+ ...this.extraProps
806
+ });
807
+ }
658
808
  getGitBranchesMapping(workspace, dbName) {
659
809
  return operationsByTag.database.getGitBranchesMapping({
660
810
  pathParams: { workspace, dbName },
@@ -675,10 +825,10 @@ class DatabaseApi {
675
825
  ...this.extraProps
676
826
  });
677
827
  }
678
- resolveBranch(workspace, dbName, gitBranch) {
828
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
679
829
  return operationsByTag.database.resolveBranch({
680
830
  pathParams: { workspace, dbName },
681
- queryParams: { gitBranch },
831
+ queryParams: { gitBranch, fallbackBranch },
682
832
  ...this.extraProps
683
833
  });
684
834
  }
@@ -827,9 +977,10 @@ class RecordsApi {
827
977
  constructor(extraProps) {
828
978
  this.extraProps = extraProps;
829
979
  }
830
- insertRecord(workspace, database, branch, tableName, record) {
980
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
831
981
  return operationsByTag.records.insertRecord({
832
982
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
983
+ queryParams: options,
833
984
  body: record,
834
985
  ...this.extraProps
835
986
  });
@@ -858,21 +1009,24 @@ class RecordsApi {
858
1009
  ...this.extraProps
859
1010
  });
860
1011
  }
861
- deleteRecord(workspace, database, branch, tableName, recordId) {
1012
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
862
1013
  return operationsByTag.records.deleteRecord({
863
1014
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1015
+ queryParams: options,
864
1016
  ...this.extraProps
865
1017
  });
866
1018
  }
867
1019
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
868
1020
  return operationsByTag.records.getRecord({
869
1021
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1022
+ queryParams: options,
870
1023
  ...this.extraProps
871
1024
  });
872
1025
  }
873
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1026
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
874
1027
  return operationsByTag.records.bulkInsertTableRecords({
875
1028
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1029
+ queryParams: options,
876
1030
  body: { records },
877
1031
  ...this.extraProps
878
1032
  });
@@ -884,6 +1038,13 @@ class RecordsApi {
884
1038
  ...this.extraProps
885
1039
  });
886
1040
  }
1041
+ searchTable(workspace, database, branch, tableName, query) {
1042
+ return operationsByTag.records.searchTable({
1043
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1044
+ body: query,
1045
+ ...this.extraProps
1046
+ });
1047
+ }
887
1048
  searchBranch(workspace, database, branch, query) {
888
1049
  return operationsByTag.records.searchBranch({
889
1050
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -916,18 +1077,18 @@ var __privateAdd$6 = (obj, member, value) => {
916
1077
  throw TypeError("Cannot add the same private member more than once");
917
1078
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
918
1079
  };
919
- var __privateSet$5 = (obj, member, value, setter) => {
1080
+ var __privateSet$6 = (obj, member, value, setter) => {
920
1081
  __accessCheck$6(obj, member, "write to private field");
921
1082
  setter ? setter.call(obj, value) : member.set(obj, value);
922
1083
  return value;
923
1084
  };
924
- var _query;
1085
+ var _query, _page;
925
1086
  class Page {
926
1087
  constructor(query, meta, records = []) {
927
1088
  __privateAdd$6(this, _query, void 0);
928
- __privateSet$5(this, _query, query);
1089
+ __privateSet$6(this, _query, query);
929
1090
  this.meta = meta;
930
- this.records = records;
1091
+ this.records = new RecordArray(this, records);
931
1092
  }
932
1093
  async nextPage(size, offset) {
933
1094
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
@@ -947,9 +1108,56 @@ class Page {
947
1108
  }
948
1109
  _query = new WeakMap();
949
1110
  const PAGINATION_MAX_SIZE = 200;
950
- const PAGINATION_DEFAULT_SIZE = 200;
1111
+ const PAGINATION_DEFAULT_SIZE = 20;
951
1112
  const PAGINATION_MAX_OFFSET = 800;
952
1113
  const PAGINATION_DEFAULT_OFFSET = 0;
1114
+ function isCursorPaginationOptions(options) {
1115
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
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();
953
1161
 
954
1162
  var __accessCheck$5 = (obj, member, msg) => {
955
1163
  if (!member.has(obj))
@@ -964,25 +1172,26 @@ var __privateAdd$5 = (obj, member, value) => {
964
1172
  throw TypeError("Cannot add the same private member more than once");
965
1173
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
966
1174
  };
967
- var __privateSet$4 = (obj, member, value, setter) => {
1175
+ var __privateSet$5 = (obj, member, value, setter) => {
968
1176
  __accessCheck$5(obj, member, "write to private field");
969
1177
  setter ? setter.call(obj, value) : member.set(obj, value);
970
1178
  return value;
971
1179
  };
972
1180
  var _table$1, _repository, _data;
973
1181
  const _Query = class {
974
- constructor(repository, table, data, parent) {
1182
+ constructor(repository, table, data, rawParent) {
975
1183
  __privateAdd$5(this, _table$1, void 0);
976
1184
  __privateAdd$5(this, _repository, void 0);
977
1185
  __privateAdd$5(this, _data, { filter: {} });
978
1186
  this.meta = { page: { cursor: "start", more: true } };
979
- this.records = [];
980
- __privateSet$4(this, _table$1, table);
1187
+ this.records = new RecordArray(this, []);
1188
+ __privateSet$5(this, _table$1, table);
981
1189
  if (repository) {
982
- __privateSet$4(this, _repository, repository);
1190
+ __privateSet$5(this, _repository, repository);
983
1191
  } else {
984
- __privateSet$4(this, _repository, this);
1192
+ __privateSet$5(this, _repository, this);
985
1193
  }
1194
+ const parent = cleanParent(data, rawParent);
986
1195
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
987
1196
  __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
988
1197
  __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
@@ -1035,13 +1244,18 @@ const _Query = class {
1035
1244
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1036
1245
  }
1037
1246
  }
1038
- sort(column, direction) {
1247
+ sort(column, direction = "asc") {
1039
1248
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1040
1249
  const sort = [...originalSort, { column, direction }];
1041
1250
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1042
1251
  }
1043
1252
  select(columns) {
1044
- 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
+ );
1045
1259
  }
1046
1260
  getPaginated(options = {}) {
1047
1261
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1054,18 +1268,21 @@ const _Query = class {
1054
1268
  }
1055
1269
  async *getIterator(options = {}) {
1056
1270
  const { batchSize = 1 } = options;
1057
- let offset = 0;
1058
- let end = false;
1059
- while (!end) {
1060
- const { records, meta } = await this.getPaginated({ ...options, pagination: { size: batchSize, offset } });
1061
- yield records;
1062
- offset += batchSize;
1063
- end = !meta.page.more;
1271
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1272
+ let more = page.hasNextPage();
1273
+ yield page.records;
1274
+ while (more) {
1275
+ page = await page.nextPage();
1276
+ more = page.hasNextPage();
1277
+ yield page.records;
1064
1278
  }
1065
1279
  }
1066
1280
  async getMany(options = {}) {
1067
- const { records } = await this.getPaginated(options);
1068
- 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;
1069
1286
  }
1070
1287
  async getAll(options = {}) {
1071
1288
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1077,7 +1294,7 @@ const _Query = class {
1077
1294
  }
1078
1295
  async getFirst(options = {}) {
1079
1296
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1080
- return records[0] || null;
1297
+ return records[0] ?? null;
1081
1298
  }
1082
1299
  cache(ttl) {
1083
1300
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
@@ -1102,12 +1319,20 @@ let Query = _Query;
1102
1319
  _table$1 = new WeakMap();
1103
1320
  _repository = new WeakMap();
1104
1321
  _data = new WeakMap();
1322
+ function cleanParent(data, parent) {
1323
+ if (isCursorPaginationOptions(data.pagination)) {
1324
+ return { ...parent, sorting: void 0, filter: void 0 };
1325
+ }
1326
+ return parent;
1327
+ }
1105
1328
 
1106
1329
  function isIdentifiable(x) {
1107
1330
  return isObject(x) && isString(x?.id);
1108
1331
  }
1109
1332
  function isXataRecord(x) {
1110
- 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";
1111
1336
  }
1112
1337
 
1113
1338
  function isSortFilterString(value) {
@@ -1146,7 +1371,7 @@ var __privateAdd$4 = (obj, member, value) => {
1146
1371
  throw TypeError("Cannot add the same private member more than once");
1147
1372
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1148
1373
  };
1149
- var __privateSet$3 = (obj, member, value, setter) => {
1374
+ var __privateSet$4 = (obj, member, value, setter) => {
1150
1375
  __accessCheck$4(obj, member, "write to private field");
1151
1376
  setter ? setter.call(obj, value) : member.set(obj, value);
1152
1377
  return value;
@@ -1155,7 +1380,7 @@ var __privateMethod$2 = (obj, member, method) => {
1155
1380
  __accessCheck$4(obj, member, "access private method");
1156
1381
  return method;
1157
1382
  };
1158
- 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;
1159
1384
  class Repository extends Query {
1160
1385
  }
1161
1386
  class RestRepository extends Query {
@@ -1167,168 +1392,214 @@ class RestRepository extends Query {
1167
1392
  __privateAdd$4(this, _updateRecordWithID);
1168
1393
  __privateAdd$4(this, _upsertRecordWithID);
1169
1394
  __privateAdd$4(this, _deleteRecord);
1170
- __privateAdd$4(this, _invalidateCache);
1171
- __privateAdd$4(this, _setCacheRecord);
1172
- __privateAdd$4(this, _getCacheRecord);
1173
1395
  __privateAdd$4(this, _setCacheQuery);
1174
1396
  __privateAdd$4(this, _getCacheQuery);
1175
- __privateAdd$4(this, _getSchema$1);
1397
+ __privateAdd$4(this, _getSchemaTables$1);
1176
1398
  __privateAdd$4(this, _table, void 0);
1177
1399
  __privateAdd$4(this, _getFetchProps, void 0);
1400
+ __privateAdd$4(this, _db, void 0);
1178
1401
  __privateAdd$4(this, _cache, void 0);
1179
- __privateAdd$4(this, _schema$1, void 0);
1180
- __privateSet$3(this, _table, options.table);
1181
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1182
- this.db = options.db;
1183
- __privateSet$3(this, _cache, options.pluginOptions.cache);
1184
- }
1185
- async create(a, b) {
1186
- if (Array.isArray(a)) {
1187
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1188
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1189
- return records;
1190
- }
1191
- if (isString(a) && isObject(b)) {
1192
- if (a === "")
1193
- throw new Error("The id can't be empty");
1194
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1195
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1196
- return record;
1197
- }
1198
- if (isObject(a) && isString(a.id)) {
1199
- if (a.id === "")
1200
- throw new Error("The id can't be empty");
1201
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1202
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1203
- return record;
1204
- }
1205
- if (isObject(a)) {
1206
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1207
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1208
- return record;
1209
- }
1210
- throw new Error("Invalid arguments for create method");
1211
- }
1212
- async read(recordId) {
1213
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1214
- if (cacheRecord)
1215
- return cacheRecord;
1216
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1217
- try {
1218
- const response = await getRecord({
1219
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1220
- ...fetchProps
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
1221
1415
  });
1222
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1223
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1224
- } catch (e) {
1225
- if (isObject(e) && e.status === 404) {
1226
- return null;
1416
+ });
1417
+ }
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);
1227
1425
  }
1228
- throw e;
1229
- }
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
+ });
1230
1444
  }
1231
- async update(a, b) {
1232
- if (Array.isArray(a)) {
1233
- if (a.length > 100) {
1234
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
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);
1235
1458
  }
1236
- return Promise.all(a.map((object) => this.update(object)));
1237
- }
1238
- if (isString(a) && isObject(b)) {
1239
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1240
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1241
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1242
- return record;
1243
- }
1244
- if (isObject(a) && isString(a.id)) {
1245
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1246
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1247
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1248
- return record;
1249
- }
1250
- throw new Error("Invalid arguments for update method");
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;
1480
+ }
1481
+ }
1482
+ return null;
1483
+ });
1484
+ }
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)));
1495
+ }
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);
1499
+ }
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
+ });
1251
1506
  }
1252
- async createOrUpdate(a, b) {
1253
- if (Array.isArray(a)) {
1254
- if (a.length > 100) {
1255
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
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)));
1256
1517
  }
1257
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1258
- }
1259
- if (isString(a) && isObject(b)) {
1260
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1261
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1262
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1263
- return record;
1264
- }
1265
- if (isObject(a) && isString(a.id)) {
1266
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1267
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1268
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1269
- return record;
1270
- }
1271
- throw new Error("Invalid arguments for createOrUpdate method");
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
+ });
1272
1528
  }
1273
1529
  async delete(a) {
1274
- if (Array.isArray(a)) {
1275
- if (a.length > 100) {
1276
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
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)));
1538
+ return;
1277
1539
  }
1278
- await Promise.all(a.map((id) => this.delete(id)));
1279
- return;
1280
- }
1281
- if (isString(a)) {
1282
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1283
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1284
- return;
1285
- }
1286
- if (isObject(a) && isString(a.id)) {
1287
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1288
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1289
- return;
1290
- }
1291
- 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
+ });
1292
1550
  }
1293
1551
  async search(query, options = {}) {
1294
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1295
- const { records } = await searchBranch({
1296
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1297
- body: { tables: [__privateGet$4(this, _table)], query, fuzziness: options.fuzziness },
1298
- ...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));
1299
1568
  });
1300
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1301
- return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1302
1569
  }
1303
1570
  async query(query) {
1304
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1305
- if (cacheQuery)
1306
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1307
- const data = query.getQueryOptions();
1308
- const body = {
1309
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1310
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1311
- page: data.pagination,
1312
- columns: data.columns
1313
- };
1314
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1315
- const { meta, records: objects } = await queryTable({
1316
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1317
- body,
1318
- ...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);
1319
1592
  });
1320
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1321
- const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1322
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1323
- return new Page(query, meta, records);
1324
1593
  }
1325
1594
  }
1326
1595
  _table = new WeakMap();
1327
1596
  _getFetchProps = new WeakMap();
1597
+ _db = new WeakMap();
1328
1598
  _cache = new WeakMap();
1329
- _schema$1 = new WeakMap();
1599
+ _schemaTables$2 = new WeakMap();
1600
+ _trace = new WeakMap();
1330
1601
  _insertRecordWithoutId = new WeakSet();
1331
- insertRecordWithoutId_fn = async function(object) {
1602
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1332
1603
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1333
1604
  const record = transformObjectLinks(object);
1334
1605
  const response = await insertRecord({
@@ -1337,17 +1608,15 @@ insertRecordWithoutId_fn = async function(object) {
1337
1608
  dbBranchName: "{dbBranch}",
1338
1609
  tableName: __privateGet$4(this, _table)
1339
1610
  },
1611
+ queryParams: { columns },
1340
1612
  body: record,
1341
1613
  ...fetchProps
1342
1614
  });
1343
- const finalObject = await this.read(response.id);
1344
- if (!finalObject) {
1345
- throw new Error("The server failed to save the record");
1346
- }
1347
- 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);
1348
1617
  };
1349
1618
  _insertRecordWithId = new WeakSet();
1350
- insertRecordWithId_fn = async function(recordId, object) {
1619
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1351
1620
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1352
1621
  const record = transformObjectLinks(object);
1353
1622
  const response = await insertRecordWithID({
@@ -1358,56 +1627,52 @@ insertRecordWithId_fn = async function(recordId, object) {
1358
1627
  recordId
1359
1628
  },
1360
1629
  body: record,
1361
- queryParams: { createOnly: true },
1630
+ queryParams: { createOnly: true, columns },
1362
1631
  ...fetchProps
1363
1632
  });
1364
- const finalObject = await this.read(response.id);
1365
- if (!finalObject) {
1366
- throw new Error("The server failed to save the record");
1367
- }
1368
- 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);
1369
1635
  };
1370
1636
  _bulkInsertTableRecords = new WeakSet();
1371
- bulkInsertTableRecords_fn = async function(objects) {
1637
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1372
1638
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1373
1639
  const records = objects.map((object) => transformObjectLinks(object));
1374
1640
  const response = await bulkInsertTableRecords({
1375
1641
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1642
+ queryParams: { columns },
1376
1643
  body: { records },
1377
1644
  ...fetchProps
1378
1645
  });
1379
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1380
- if (finalObjects.length !== objects.length) {
1381
- 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");
1382
1648
  }
1383
- 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));
1384
1651
  };
1385
1652
  _updateRecordWithID = new WeakSet();
1386
- updateRecordWithID_fn = async function(recordId, object) {
1653
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1387
1654
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1388
1655
  const record = transformObjectLinks(object);
1389
1656
  const response = await updateRecordWithID({
1390
1657
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1658
+ queryParams: { columns },
1391
1659
  body: record,
1392
1660
  ...fetchProps
1393
1661
  });
1394
- const item = await this.read(response.id);
1395
- if (!item)
1396
- throw new Error("The server failed to save the record");
1397
- 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);
1398
1664
  };
1399
1665
  _upsertRecordWithID = new WeakSet();
1400
- upsertRecordWithID_fn = async function(recordId, object) {
1666
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1401
1667
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1402
1668
  const response = await upsertRecordWithID({
1403
1669
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1670
+ queryParams: { columns },
1404
1671
  body: object,
1405
1672
  ...fetchProps
1406
1673
  });
1407
- const item = await this.read(response.id);
1408
- if (!item)
1409
- throw new Error("The server failed to save the record");
1410
- 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);
1411
1676
  };
1412
1677
  _deleteRecord = new WeakSet();
1413
1678
  deleteRecord_fn = async function(recordId) {
@@ -1417,29 +1682,6 @@ deleteRecord_fn = async function(recordId) {
1417
1682
  ...fetchProps
1418
1683
  });
1419
1684
  };
1420
- _invalidateCache = new WeakSet();
1421
- invalidateCache_fn = async function(recordId) {
1422
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1423
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1424
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1425
- for (const [key, value] of queries) {
1426
- const ids = getIds(value);
1427
- if (ids.includes(recordId))
1428
- await __privateGet$4(this, _cache).delete(key);
1429
- }
1430
- };
1431
- _setCacheRecord = new WeakSet();
1432
- setCacheRecord_fn = async function(record) {
1433
- if (!__privateGet$4(this, _cache).cacheRecords)
1434
- return;
1435
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1436
- };
1437
- _getCacheRecord = new WeakSet();
1438
- getCacheRecord_fn = async function(recordId) {
1439
- if (!__privateGet$4(this, _cache).cacheRecords)
1440
- return null;
1441
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1442
- };
1443
1685
  _setCacheQuery = new WeakSet();
1444
1686
  setCacheQuery_fn = async function(query, meta, records) {
1445
1687
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -1456,17 +1698,17 @@ getCacheQuery_fn = async function(query) {
1456
1698
  const hasExpired = result.date.getTime() + ttl < Date.now();
1457
1699
  return hasExpired ? null : result;
1458
1700
  };
1459
- _getSchema$1 = new WeakSet();
1460
- getSchema_fn$1 = async function() {
1461
- if (__privateGet$4(this, _schema$1))
1462
- 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);
1463
1705
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1464
1706
  const { schema } = await getBranchDetails({
1465
1707
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1466
1708
  ...fetchProps
1467
1709
  });
1468
- __privateSet$3(this, _schema$1, schema);
1469
- return schema;
1710
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1711
+ return schema.tables;
1470
1712
  };
1471
1713
  const transformObjectLinks = (object) => {
1472
1714
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1475,20 +1717,21 @@ const transformObjectLinks = (object) => {
1475
1717
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1476
1718
  }, {});
1477
1719
  };
1478
- const initObject = (db, schema, table, object) => {
1720
+ const initObject = (db, schemaTables, table, object) => {
1479
1721
  const result = {};
1480
- Object.assign(result, object);
1481
- 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) ?? {};
1482
1725
  if (!columns)
1483
1726
  console.error(`Table ${table} not found in schema`);
1484
1727
  for (const column of columns ?? []) {
1485
1728
  const value = result[column.name];
1486
1729
  switch (column.type) {
1487
1730
  case "datetime": {
1488
- const date = new Date(value);
1489
- if (isNaN(date.getTime())) {
1731
+ const date = value !== void 0 ? new Date(value) : void 0;
1732
+ if (date && isNaN(date.getTime())) {
1490
1733
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1491
- } else {
1734
+ } else if (date) {
1492
1735
  result[column.name] = date;
1493
1736
  }
1494
1737
  break;
@@ -1497,36 +1740,33 @@ const initObject = (db, schema, table, object) => {
1497
1740
  const linkTable = column.link?.table;
1498
1741
  if (!linkTable) {
1499
1742
  console.error(`Failed to parse link for field ${column.name}`);
1500
- } else if (value && isObject(value)) {
1501
- result[column.name] = initObject(db, schema, linkTable, value);
1743
+ } else if (isObject(value)) {
1744
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1502
1745
  }
1503
1746
  break;
1504
1747
  }
1505
1748
  }
1506
1749
  }
1507
- result.read = function() {
1508
- return db[table].read(result["id"]);
1750
+ result.read = function(columns2) {
1751
+ return db[table].read(result["id"], columns2);
1509
1752
  };
1510
- result.update = function(data) {
1511
- return db[table].update(result["id"], data);
1753
+ result.update = function(data, columns2) {
1754
+ return db[table].update(result["id"], data, columns2);
1512
1755
  };
1513
1756
  result.delete = function() {
1514
1757
  return db[table].delete(result["id"]);
1515
1758
  };
1516
- for (const prop of ["read", "update", "delete"]) {
1759
+ result.getMetadata = function() {
1760
+ return xata;
1761
+ };
1762
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1517
1763
  Object.defineProperty(result, prop, { enumerable: false });
1518
1764
  }
1519
1765
  Object.freeze(result);
1520
1766
  return result;
1521
1767
  };
1522
- function getIds(value) {
1523
- if (Array.isArray(value)) {
1524
- return value.map((item) => getIds(item)).flat();
1525
- }
1526
- if (!isObject(value))
1527
- return [];
1528
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1529
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1768
+ function isResponseWithRecords(value) {
1769
+ return isObject(value) && Array.isArray(value.records);
1530
1770
  }
1531
1771
 
1532
1772
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1542,7 +1782,7 @@ var __privateAdd$3 = (obj, member, value) => {
1542
1782
  throw TypeError("Cannot add the same private member more than once");
1543
1783
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1544
1784
  };
1545
- var __privateSet$2 = (obj, member, value, setter) => {
1785
+ var __privateSet$3 = (obj, member, value, setter) => {
1546
1786
  __accessCheck$3(obj, member, "write to private field");
1547
1787
  setter ? setter.call(obj, value) : member.set(obj, value);
1548
1788
  return value;
@@ -1551,9 +1791,8 @@ var _map;
1551
1791
  class SimpleCache {
1552
1792
  constructor(options = {}) {
1553
1793
  __privateAdd$3(this, _map, void 0);
1554
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1794
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1555
1795
  this.capacity = options.max ?? 500;
1556
- this.cacheRecords = options.cacheRecords ?? true;
1557
1796
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1558
1797
  }
1559
1798
  async getAll() {
@@ -1611,31 +1850,42 @@ var __privateAdd$2 = (obj, member, value) => {
1611
1850
  throw TypeError("Cannot add the same private member more than once");
1612
1851
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1613
1852
  };
1614
- var _tables;
1853
+ var __privateSet$2 = (obj, member, value, setter) => {
1854
+ __accessCheck$2(obj, member, "write to private field");
1855
+ setter ? setter.call(obj, value) : member.set(obj, value);
1856
+ return value;
1857
+ };
1858
+ var _tables, _schemaTables$1;
1615
1859
  class SchemaPlugin extends XataPlugin {
1616
- constructor(tableNames) {
1860
+ constructor(schemaTables) {
1617
1861
  super();
1618
- this.tableNames = tableNames;
1619
1862
  __privateAdd$2(this, _tables, {});
1863
+ __privateAdd$2(this, _schemaTables$1, void 0);
1864
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1620
1865
  }
1621
1866
  build(pluginOptions) {
1622
- const db = new Proxy({}, {
1623
- get: (_target, table) => {
1624
- if (!isString(table))
1625
- throw new Error("Invalid table name");
1626
- if (!__privateGet$2(this, _tables)[table]) {
1627
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1867
+ const db = new Proxy(
1868
+ {},
1869
+ {
1870
+ get: (_target, table) => {
1871
+ if (!isString(table))
1872
+ throw new Error("Invalid table name");
1873
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1874
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1875
+ }
1876
+ return __privateGet$2(this, _tables)[table];
1628
1877
  }
1629
- return __privateGet$2(this, _tables)[table];
1630
1878
  }
1631
- });
1632
- for (const table of this.tableNames ?? []) {
1633
- db[table] = new RestRepository({ db, pluginOptions, table });
1879
+ );
1880
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1881
+ for (const table of tableNames) {
1882
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1634
1883
  }
1635
1884
  return db;
1636
1885
  }
1637
1886
  }
1638
1887
  _tables = new WeakMap();
1888
+ _schemaTables$1 = new WeakMap();
1639
1889
 
1640
1890
  var __accessCheck$1 = (obj, member, msg) => {
1641
1891
  if (!member.has(obj))
@@ -1659,105 +1909,119 @@ var __privateMethod$1 = (obj, member, method) => {
1659
1909
  __accessCheck$1(obj, member, "access private method");
1660
1910
  return method;
1661
1911
  };
1662
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
1912
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1663
1913
  class SearchPlugin extends XataPlugin {
1664
- constructor(db) {
1914
+ constructor(db, schemaTables) {
1665
1915
  super();
1666
1916
  this.db = db;
1667
1917
  __privateAdd$1(this, _search);
1668
- __privateAdd$1(this, _getSchema);
1669
- __privateAdd$1(this, _schema, void 0);
1918
+ __privateAdd$1(this, _getSchemaTables);
1919
+ __privateAdd$1(this, _schemaTables, void 0);
1920
+ __privateSet$1(this, _schemaTables, schemaTables);
1670
1921
  }
1671
1922
  build({ getFetchProps }) {
1672
1923
  return {
1673
1924
  all: async (query, options = {}) => {
1674
1925
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1675
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1926
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1676
1927
  return records.map((record) => {
1677
1928
  const { table = "orphan" } = record.xata;
1678
- return { table, record: initObject(this.db, schema, table, record) };
1929
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1679
1930
  });
1680
1931
  },
1681
1932
  byTable: async (query, options = {}) => {
1682
1933
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1683
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1934
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1684
1935
  return records.reduce((acc, record) => {
1685
1936
  const { table = "orphan" } = record.xata;
1686
1937
  const items = acc[table] ?? [];
1687
- const item = initObject(this.db, schema, table, record);
1938
+ const item = initObject(this.db, schemaTables, table, record);
1688
1939
  return { ...acc, [table]: [...items, item] };
1689
1940
  }, {});
1690
1941
  }
1691
1942
  };
1692
1943
  }
1693
1944
  }
1694
- _schema = new WeakMap();
1945
+ _schemaTables = new WeakMap();
1695
1946
  _search = new WeakSet();
1696
1947
  search_fn = async function(query, options, getFetchProps) {
1697
1948
  const fetchProps = await getFetchProps();
1698
- const { tables, fuzziness } = options ?? {};
1949
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1699
1950
  const { records } = await searchBranch({
1700
1951
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1701
- body: { tables, query, fuzziness },
1952
+ body: { tables, query, fuzziness, prefix, highlight },
1702
1953
  ...fetchProps
1703
1954
  });
1704
1955
  return records;
1705
1956
  };
1706
- _getSchema = new WeakSet();
1707
- getSchema_fn = async function(getFetchProps) {
1708
- if (__privateGet$1(this, _schema))
1709
- return __privateGet$1(this, _schema);
1957
+ _getSchemaTables = new WeakSet();
1958
+ getSchemaTables_fn = async function(getFetchProps) {
1959
+ if (__privateGet$1(this, _schemaTables))
1960
+ return __privateGet$1(this, _schemaTables);
1710
1961
  const fetchProps = await getFetchProps();
1711
1962
  const { schema } = await getBranchDetails({
1712
1963
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1713
1964
  ...fetchProps
1714
1965
  });
1715
- __privateSet$1(this, _schema, schema);
1716
- return schema;
1966
+ __privateSet$1(this, _schemaTables, schema.tables);
1967
+ return schema.tables;
1717
1968
  };
1718
1969
 
1719
1970
  const isBranchStrategyBuilder = (strategy) => {
1720
1971
  return typeof strategy === "function";
1721
1972
  };
1722
1973
 
1723
- const envBranchNames = [
1724
- "XATA_BRANCH",
1725
- "VERCEL_GIT_COMMIT_REF",
1726
- "CF_PAGES_BRANCH",
1727
- "BRANCH"
1728
- ];
1729
- const defaultBranch = "main";
1730
1974
  async function getCurrentBranchName(options) {
1731
- const env = getBranchByEnvVariable();
1732
- if (env)
1733
- return env;
1734
- const branch = await getGitBranch();
1735
- if (!branch)
1736
- return void 0;
1737
- const details = await getDatabaseBranch(branch, options);
1738
- if (details)
1739
- return branch;
1740
- return void 0;
1975
+ const { branch, envBranch } = getEnvironment();
1976
+ if (branch) {
1977
+ const details = await getDatabaseBranch(branch, options);
1978
+ if (details)
1979
+ return branch;
1980
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1981
+ }
1982
+ const gitBranch = envBranch || await getGitBranch();
1983
+ return resolveXataBranch(gitBranch, options);
1741
1984
  }
1742
1985
  async function getCurrentBranchDetails(options) {
1743
- const env = getBranchByEnvVariable();
1744
- if (env)
1745
- return getDatabaseBranch(env, options);
1746
- const branch = await getGitBranch();
1747
- if (!branch)
1748
- return getDatabaseBranch(defaultBranch, options);
1749
- const details = await getDatabaseBranch(branch, options);
1750
- if (details)
1751
- return details;
1752
- return getDatabaseBranch(defaultBranch, options);
1986
+ const branch = await getCurrentBranchName(options);
1987
+ return getDatabaseBranch(branch, options);
1988
+ }
1989
+ async function resolveXataBranch(gitBranch, options) {
1990
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1991
+ const apiKey = options?.apiKey || getAPIKey();
1992
+ if (!databaseURL)
1993
+ throw new Error(
1994
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
1995
+ );
1996
+ if (!apiKey)
1997
+ throw new Error(
1998
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
1999
+ );
2000
+ const [protocol, , host, , dbName] = databaseURL.split("/");
2001
+ const [workspace] = host.split(".");
2002
+ const { fallbackBranch } = getEnvironment();
2003
+ const { branch } = await resolveBranch({
2004
+ apiKey,
2005
+ apiUrl: databaseURL,
2006
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
2007
+ workspacesApiUrl: `${protocol}//${host}`,
2008
+ pathParams: { dbName, workspace },
2009
+ queryParams: { gitBranch, fallbackBranch },
2010
+ trace: defaultTrace
2011
+ });
2012
+ return branch;
1753
2013
  }
1754
2014
  async function getDatabaseBranch(branch, options) {
1755
2015
  const databaseURL = options?.databaseURL || getDatabaseURL();
1756
2016
  const apiKey = options?.apiKey || getAPIKey();
1757
2017
  if (!databaseURL)
1758
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2018
+ throw new Error(
2019
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2020
+ );
1759
2021
  if (!apiKey)
1760
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2022
+ throw new Error(
2023
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2024
+ );
1761
2025
  const [protocol, , host, , database] = databaseURL.split("/");
1762
2026
  const [workspace] = host.split(".");
1763
2027
  const dbBranchName = `${database}:${branch}`;
@@ -1767,10 +2031,8 @@ async function getDatabaseBranch(branch, options) {
1767
2031
  apiUrl: databaseURL,
1768
2032
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1769
2033
  workspacesApiUrl: `${protocol}//${host}`,
1770
- pathParams: {
1771
- dbBranchName,
1772
- workspace
1773
- }
2034
+ pathParams: { dbBranchName, workspace },
2035
+ trace: defaultTrace
1774
2036
  });
1775
2037
  } catch (err) {
1776
2038
  if (isObject(err) && err.status === 404)
@@ -1778,21 +2040,10 @@ async function getDatabaseBranch(branch, options) {
1778
2040
  throw err;
1779
2041
  }
1780
2042
  }
1781
- function getBranchByEnvVariable() {
1782
- for (const name of envBranchNames) {
1783
- const value = getEnvVariable(name);
1784
- if (value) {
1785
- return value;
1786
- }
1787
- }
1788
- try {
1789
- return XATA_BRANCH;
1790
- } catch (err) {
1791
- }
1792
- }
1793
2043
  function getDatabaseURL() {
1794
2044
  try {
1795
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2045
+ const { databaseURL } = getEnvironment();
2046
+ return databaseURL;
1796
2047
  } catch (err) {
1797
2048
  return void 0;
1798
2049
  }
@@ -1821,24 +2072,27 @@ var __privateMethod = (obj, member, method) => {
1821
2072
  return method;
1822
2073
  };
1823
2074
  const buildClient = (plugins) => {
1824
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2075
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1825
2076
  return _a = class {
1826
- constructor(options = {}, tables) {
2077
+ constructor(options = {}, schemaTables) {
1827
2078
  __privateAdd(this, _parseOptions);
1828
2079
  __privateAdd(this, _getFetchProps);
1829
2080
  __privateAdd(this, _evaluateBranch);
1830
2081
  __privateAdd(this, _branch, void 0);
2082
+ __privateAdd(this, _options, void 0);
1831
2083
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2084
+ __privateSet(this, _options, safeOptions);
1832
2085
  const pluginOptions = {
1833
2086
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1834
- cache: safeOptions.cache
2087
+ cache: safeOptions.cache,
2088
+ trace: safeOptions.trace
1835
2089
  };
1836
- const db = new SchemaPlugin(tables).build(pluginOptions);
1837
- const search = new SearchPlugin(db).build(pluginOptions);
2090
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2091
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1838
2092
  this.db = db;
1839
2093
  this.search = search;
1840
2094
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1841
- if (!namespace)
2095
+ if (namespace === void 0)
1842
2096
  continue;
1843
2097
  const result = namespace.build(pluginOptions);
1844
2098
  if (result instanceof Promise) {
@@ -1850,22 +2104,23 @@ const buildClient = (plugins) => {
1850
2104
  }
1851
2105
  }
1852
2106
  }
1853
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2107
+ async getConfig() {
2108
+ const databaseURL = __privateGet(this, _options).databaseURL;
2109
+ const branch = await __privateGet(this, _options).branch();
2110
+ return { databaseURL, branch };
2111
+ }
2112
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1854
2113
  const fetch = getFetchImplementation(options?.fetch);
1855
2114
  const databaseURL = options?.databaseURL || getDatabaseURL();
1856
2115
  const apiKey = options?.apiKey || getAPIKey();
1857
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1858
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch }) ?? defaultBranch;
2116
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2117
+ const trace = options?.trace ?? defaultTrace;
2118
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1859
2119
  if (!databaseURL || !apiKey) {
1860
2120
  throw new Error("Options databaseURL and apiKey are required");
1861
2121
  }
1862
- return { fetch, databaseURL, apiKey, branch, cache };
1863
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1864
- fetch,
1865
- apiKey,
1866
- databaseURL,
1867
- branch
1868
- }) {
2122
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2123
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
1869
2124
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1870
2125
  if (!branchValue)
1871
2126
  throw new Error("Unable to resolve branch value");
@@ -1877,12 +2132,13 @@ const buildClient = (plugins) => {
1877
2132
  const hasBranch = params.dbBranchName ?? params.branch;
1878
2133
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
1879
2134
  return databaseURL + newPath;
1880
- }
2135
+ },
2136
+ trace
1881
2137
  };
1882
2138
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1883
2139
  if (__privateGet(this, _branch))
1884
2140
  return __privateGet(this, _branch);
1885
- if (!param)
2141
+ if (param === void 0)
1886
2142
  return void 0;
1887
2143
  const strategies = Array.isArray(param) ? [...param] : [param];
1888
2144
  const evaluateBranch = async (strategy) => {
@@ -1900,6 +2156,88 @@ const buildClient = (plugins) => {
1900
2156
  class BaseClient extends buildClient() {
1901
2157
  }
1902
2158
 
2159
+ const META = "__";
2160
+ const VALUE = "___";
2161
+ class Serializer {
2162
+ constructor() {
2163
+ this.classes = {};
2164
+ }
2165
+ add(clazz) {
2166
+ this.classes[clazz.name] = clazz;
2167
+ }
2168
+ toJSON(data) {
2169
+ function visit(obj) {
2170
+ if (Array.isArray(obj))
2171
+ return obj.map(visit);
2172
+ const type = typeof obj;
2173
+ if (type === "undefined")
2174
+ return { [META]: "undefined" };
2175
+ if (type === "bigint")
2176
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2177
+ if (obj === null || type !== "object")
2178
+ return obj;
2179
+ const constructor = obj.constructor;
2180
+ const o = { [META]: constructor.name };
2181
+ for (const [key, value] of Object.entries(obj)) {
2182
+ o[key] = visit(value);
2183
+ }
2184
+ if (constructor === Date)
2185
+ o[VALUE] = obj.toISOString();
2186
+ if (constructor === Map)
2187
+ o[VALUE] = Object.fromEntries(obj);
2188
+ if (constructor === Set)
2189
+ o[VALUE] = [...obj];
2190
+ return o;
2191
+ }
2192
+ return JSON.stringify(visit(data));
2193
+ }
2194
+ fromJSON(json) {
2195
+ return JSON.parse(json, (key, value) => {
2196
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2197
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2198
+ const constructor = this.classes[clazz];
2199
+ if (constructor) {
2200
+ return Object.assign(Object.create(constructor.prototype), rest);
2201
+ }
2202
+ if (clazz === "Date")
2203
+ return new Date(val);
2204
+ if (clazz === "Set")
2205
+ return new Set(val);
2206
+ if (clazz === "Map")
2207
+ return new Map(Object.entries(val));
2208
+ if (clazz === "bigint")
2209
+ return BigInt(val);
2210
+ if (clazz === "undefined")
2211
+ return void 0;
2212
+ return rest;
2213
+ }
2214
+ return value;
2215
+ });
2216
+ }
2217
+ }
2218
+ const defaultSerializer = new Serializer();
2219
+ const serialize = (data) => {
2220
+ return defaultSerializer.toJSON(data);
2221
+ };
2222
+ const deserialize = (json) => {
2223
+ return defaultSerializer.fromJSON(json);
2224
+ };
2225
+
2226
+ function buildWorkerRunner(config) {
2227
+ return function xataWorker(name, _worker) {
2228
+ return async (...args) => {
2229
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2230
+ const result = await fetch(url, {
2231
+ method: "POST",
2232
+ headers: { "Content-Type": "application/json" },
2233
+ body: serialize({ args })
2234
+ });
2235
+ const text = await result.text();
2236
+ return deserialize(text);
2237
+ };
2238
+ };
2239
+ }
2240
+
1903
2241
  class XataError extends Error {
1904
2242
  constructor(message, status) {
1905
2243
  super(message);
@@ -1907,5 +2245,5 @@ class XataError extends Error {
1907
2245
  }
1908
2246
  }
1909
2247
 
1910
- 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, defaultBranch, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2248
+ 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, 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, 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, serialize, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
1911
2249
  //# sourceMappingURL=index.mjs.map