@xata.io/client 0.0.0-alpha.vfd071d9 → 0.0.0-alpha.vfe4a947

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.vfe4a947";
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
  };
@@ -462,7 +597,7 @@ var __accessCheck$7 = (obj, member, msg) => {
462
597
  if (!member.has(obj))
463
598
  throw TypeError("Cannot " + msg);
464
599
  };
465
- var __privateGet$6 = (obj, member, getter) => {
600
+ var __privateGet$7 = (obj, member, getter) => {
466
601
  __accessCheck$7(obj, member, "read from private field");
467
602
  return getter ? getter.call(obj) : member.get(obj);
468
603
  };
@@ -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$5 = (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,46 +617,48 @@ 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$5(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() {
497
- if (!__privateGet$6(this, _namespaces).user)
498
- __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
499
- return __privateGet$6(this, _namespaces).user;
634
+ if (!__privateGet$7(this, _namespaces).user)
635
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
636
+ return __privateGet$7(this, _namespaces).user;
500
637
  }
501
638
  get workspaces() {
502
- if (!__privateGet$6(this, _namespaces).workspaces)
503
- __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
504
- return __privateGet$6(this, _namespaces).workspaces;
639
+ if (!__privateGet$7(this, _namespaces).workspaces)
640
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
641
+ return __privateGet$7(this, _namespaces).workspaces;
505
642
  }
506
643
  get databases() {
507
- if (!__privateGet$6(this, _namespaces).databases)
508
- __privateGet$6(this, _namespaces).databases = new DatabaseApi(__privateGet$6(this, _extraProps));
509
- return __privateGet$6(this, _namespaces).databases;
644
+ if (!__privateGet$7(this, _namespaces).databases)
645
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
646
+ return __privateGet$7(this, _namespaces).databases;
510
647
  }
511
648
  get branches() {
512
- if (!__privateGet$6(this, _namespaces).branches)
513
- __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
514
- return __privateGet$6(this, _namespaces).branches;
649
+ if (!__privateGet$7(this, _namespaces).branches)
650
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
651
+ return __privateGet$7(this, _namespaces).branches;
515
652
  }
516
653
  get tables() {
517
- if (!__privateGet$6(this, _namespaces).tables)
518
- __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
519
- return __privateGet$6(this, _namespaces).tables;
654
+ if (!__privateGet$7(this, _namespaces).tables)
655
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
656
+ return __privateGet$7(this, _namespaces).tables;
520
657
  }
521
658
  get records() {
522
- if (!__privateGet$6(this, _namespaces).records)
523
- __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
524
- return __privateGet$6(this, _namespaces).records;
659
+ if (!__privateGet$7(this, _namespaces).records)
660
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
661
+ return __privateGet$7(this, _namespaces).records;
525
662
  }
526
663
  }
527
664
  _extraProps = new WeakMap();
@@ -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
  }
@@ -699,10 +849,10 @@ class BranchApi {
699
849
  ...this.extraProps
700
850
  });
701
851
  }
702
- createBranch(workspace, database, branch, from = "", options = {}) {
852
+ createBranch(workspace, database, branch, from, options = {}) {
703
853
  return operationsByTag.branch.createBranch({
704
854
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
705
- queryParams: { from },
855
+ queryParams: isString(from) ? { from } : void 0,
706
856
  body: options,
707
857
  ...this.extraProps
708
858
  });
@@ -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}` },
@@ -907,7 +1068,7 @@ var __accessCheck$6 = (obj, member, msg) => {
907
1068
  if (!member.has(obj))
908
1069
  throw TypeError("Cannot " + msg);
909
1070
  };
910
- var __privateGet$5 = (obj, member, getter) => {
1071
+ var __privateGet$6 = (obj, member, getter) => {
911
1072
  __accessCheck$6(obj, member, "read from private field");
912
1073
  return getter ? getter.call(obj) : member.get(obj);
913
1074
  };
@@ -916,30 +1077,30 @@ 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$4 = (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$4(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
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1094
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
934
1095
  }
935
1096
  async previousPage(size, offset) {
936
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1097
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
937
1098
  }
938
1099
  async firstPage(size, offset) {
939
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1100
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
940
1101
  }
941
1102
  async lastPage(size, offset) {
942
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1103
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
943
1104
  }
944
1105
  hasNextPage() {
945
1106
  return this.meta.page.more;
@@ -947,15 +1108,62 @@ 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))
956
1164
  throw TypeError("Cannot " + msg);
957
1165
  };
958
- var __privateGet$4 = (obj, member, getter) => {
1166
+ var __privateGet$5 = (obj, member, getter) => {
959
1167
  __accessCheck$5(obj, member, "read from private field");
960
1168
  return getter ? getter.call(obj) : member.get(obj);
961
1169
  };
@@ -964,34 +1172,35 @@ 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$3 = (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$3(this, _table$1, table);
1187
+ this.records = new RecordArray(this, []);
1188
+ __privateSet$5(this, _table$1, table);
981
1189
  if (repository) {
982
- __privateSet$3(this, _repository, repository);
1190
+ __privateSet$5(this, _repository, repository);
983
1191
  } else {
984
- __privateSet$3(this, _repository, this);
1192
+ __privateSet$5(this, _repository, this);
985
1193
  }
986
- __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
987
- __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
988
- __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
989
- __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
990
- __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
991
- __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
992
- __privateGet$4(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
993
- __privateGet$4(this, _data).page = data.page ?? parent?.page;
994
- __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
1194
+ const parent = cleanParent(data, rawParent);
1195
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1196
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1197
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1198
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1199
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1200
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1201
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1202
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1203
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
995
1204
  this.any = this.any.bind(this);
996
1205
  this.all = this.all.bind(this);
997
1206
  this.not = this.not.bind(this);
@@ -1002,83 +1211,93 @@ const _Query = class {
1002
1211
  Object.defineProperty(this, "repository", { enumerable: false });
1003
1212
  }
1004
1213
  getQueryOptions() {
1005
- return __privateGet$4(this, _data);
1214
+ return __privateGet$5(this, _data);
1006
1215
  }
1007
1216
  key() {
1008
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$4(this, _data);
1009
- const key = JSON.stringify({ columns, filter, sort, page });
1217
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1218
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1010
1219
  return toBase64(key);
1011
1220
  }
1012
1221
  any(...queries) {
1013
1222
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1014
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
1223
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
1015
1224
  }
1016
1225
  all(...queries) {
1017
1226
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1018
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1227
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1019
1228
  }
1020
1229
  not(...queries) {
1021
1230
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1022
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
1231
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
1023
1232
  }
1024
1233
  none(...queries) {
1025
1234
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1026
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
1235
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
1027
1236
  }
1028
1237
  filter(a, b) {
1029
1238
  if (arguments.length === 1) {
1030
1239
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1031
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
1032
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1240
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1241
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1033
1242
  } else {
1034
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1035
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1243
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
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) {
1039
- const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
1247
+ sort(column, direction = "asc") {
1248
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1040
1249
  const sort = [...originalSort, { column, direction }];
1041
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
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$4(this, _repository), __privateGet$4(this, _table$1), { columns }, __privateGet$4(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
- const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
1048
- return __privateGet$4(this, _repository).query(query);
1261
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1262
+ return __privateGet$5(this, _repository).query(query);
1049
1263
  }
1050
1264
  async *[Symbol.asyncIterator]() {
1051
- for await (const [record] of this.getIterator(1)) {
1265
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1052
1266
  yield record;
1053
1267
  }
1054
1268
  }
1055
- async *getIterator(chunk, options = {}) {
1056
- let offset = 0;
1057
- let end = false;
1058
- while (!end) {
1059
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1060
- yield records;
1061
- offset += chunk;
1062
- end = !meta.page.more;
1269
+ async *getIterator(options = {}) {
1270
+ const { batchSize = 1 } = options;
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;
1063
1278
  }
1064
1279
  }
1065
1280
  async getMany(options = {}) {
1066
- const { records } = await this.getPaginated(options);
1067
- 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;
1068
1286
  }
1069
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1287
+ async getAll(options = {}) {
1288
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1070
1289
  const results = [];
1071
- for await (const page of this.getIterator(chunk, options)) {
1290
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1072
1291
  results.push(...page);
1073
1292
  }
1074
1293
  return results;
1075
1294
  }
1076
1295
  async getFirst(options = {}) {
1077
- const records = await this.getMany({ ...options, page: { size: 1 } });
1078
- return records[0] || null;
1296
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1297
+ return records[0] ?? null;
1079
1298
  }
1080
1299
  cache(ttl) {
1081
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
1300
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1082
1301
  }
1083
1302
  nextPage(size, offset) {
1084
1303
  return this.firstPage(size, offset);
@@ -1087,10 +1306,10 @@ const _Query = class {
1087
1306
  return this.firstPage(size, offset);
1088
1307
  }
1089
1308
  firstPage(size, offset) {
1090
- return this.getPaginated({ page: { size, offset } });
1309
+ return this.getPaginated({ pagination: { size, offset } });
1091
1310
  }
1092
1311
  lastPage(size, offset) {
1093
- return this.getPaginated({ page: { size, offset, before: "end" } });
1312
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1094
1313
  }
1095
1314
  hasNextPage() {
1096
1315
  return this.meta.page.more;
@@ -1100,12 +1319,20 @@ let Query = _Query;
1100
1319
  _table$1 = new WeakMap();
1101
1320
  _repository = new WeakMap();
1102
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
+ }
1103
1328
 
1104
1329
  function isIdentifiable(x) {
1105
1330
  return isObject(x) && isString(x?.id);
1106
1331
  }
1107
1332
  function isXataRecord(x) {
1108
- 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";
1109
1336
  }
1110
1337
 
1111
1338
  function isSortFilterString(value) {
@@ -1135,7 +1362,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1135
1362
  if (!member.has(obj))
1136
1363
  throw TypeError("Cannot " + msg);
1137
1364
  };
1138
- var __privateGet$3 = (obj, member, getter) => {
1365
+ var __privateGet$4 = (obj, member, getter) => {
1139
1366
  __accessCheck$4(obj, member, "read from private field");
1140
1367
  return getter ? getter.call(obj) : member.get(obj);
1141
1368
  };
@@ -1144,7 +1371,7 @@ var __privateAdd$4 = (obj, member, value) => {
1144
1371
  throw TypeError("Cannot add the same private member more than once");
1145
1372
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1146
1373
  };
1147
- var __privateSet$2 = (obj, member, value, setter) => {
1374
+ var __privateSet$4 = (obj, member, value, setter) => {
1148
1375
  __accessCheck$4(obj, member, "write to private field");
1149
1376
  setter ? setter.call(obj, value) : member.set(obj, value);
1150
1377
  return value;
@@ -1153,7 +1380,7 @@ var __privateMethod$2 = (obj, member, method) => {
1153
1380
  __accessCheck$4(obj, member, "access private method");
1154
1381
  return method;
1155
1382
  };
1156
- var _table, _links, _getFetchProps, _cache, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn;
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;
1157
1384
  class Repository extends Query {
1158
1385
  }
1159
1386
  class RestRepository extends Query {
@@ -1165,292 +1392,324 @@ class RestRepository extends Query {
1165
1392
  __privateAdd$4(this, _updateRecordWithID);
1166
1393
  __privateAdd$4(this, _upsertRecordWithID);
1167
1394
  __privateAdd$4(this, _deleteRecord);
1168
- __privateAdd$4(this, _invalidateCache);
1169
- __privateAdd$4(this, _setCacheRecord);
1170
- __privateAdd$4(this, _getCacheRecord);
1171
1395
  __privateAdd$4(this, _setCacheQuery);
1172
1396
  __privateAdd$4(this, _getCacheQuery);
1397
+ __privateAdd$4(this, _getSchemaTables$1);
1173
1398
  __privateAdd$4(this, _table, void 0);
1174
- __privateAdd$4(this, _links, void 0);
1175
1399
  __privateAdd$4(this, _getFetchProps, void 0);
1400
+ __privateAdd$4(this, _db, void 0);
1176
1401
  __privateAdd$4(this, _cache, void 0);
1177
- __privateSet$2(this, _table, options.table);
1178
- __privateSet$2(this, _links, options.links ?? {});
1179
- __privateSet$2(this, _getFetchProps, options.pluginOptions.getFetchProps);
1180
- this.db = options.db;
1181
- __privateSet$2(this, _cache, options.pluginOptions.cache);
1182
- }
1183
- async create(a, b) {
1184
- if (Array.isArray(a)) {
1185
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1186
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1187
- return records;
1188
- }
1189
- if (isString(a) && isObject(b)) {
1190
- if (a === "")
1191
- throw new Error("The id can't be empty");
1192
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1193
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1194
- return record;
1195
- }
1196
- if (isObject(a) && isString(a.id)) {
1197
- if (a.id === "")
1198
- throw new Error("The id can't be empty");
1199
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1200
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1201
- return record;
1202
- }
1203
- if (isObject(a)) {
1204
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1205
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1206
- return record;
1207
- }
1208
- throw new Error("Invalid arguments for create method");
1209
- }
1210
- async read(recordId) {
1211
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1212
- if (cacheRecord)
1213
- return cacheRecord;
1214
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1215
- try {
1216
- const response = await getRecord({
1217
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1218
- ...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
1219
1415
  });
1220
- return initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), response);
1221
- } catch (e) {
1222
- if (isObject(e) && e.status === 404) {
1223
- 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);
1224
1425
  }
1225
- throw e;
1226
- }
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
+ });
1227
1444
  }
1228
- async update(a, b) {
1229
- if (Array.isArray(a)) {
1230
- if (a.length > 100) {
1231
- 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);
1232
1458
  }
1233
- return Promise.all(a.map((object) => this.update(object)));
1234
- }
1235
- if (isString(a) && isObject(b)) {
1236
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1237
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1238
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1239
- return record;
1240
- }
1241
- if (isObject(a) && isString(a.id)) {
1242
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1243
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1244
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1245
- return record;
1246
- }
1247
- 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
+ });
1248
1484
  }
1249
- async createOrUpdate(a, b) {
1250
- if (Array.isArray(a)) {
1251
- if (a.length > 100) {
1252
- 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)));
1253
1495
  }
1254
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1255
- }
1256
- if (isString(a) && isObject(b)) {
1257
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1258
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1259
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1260
- return record;
1261
- }
1262
- if (isObject(a) && isString(a.id)) {
1263
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1264
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1265
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1266
- return record;
1267
- }
1268
- throw new Error("Invalid arguments for createOrUpdate method");
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
+ });
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
+ });
1269
1528
  }
1270
1529
  async delete(a) {
1271
- if (Array.isArray(a)) {
1272
- if (a.length > 100) {
1273
- 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;
1274
1539
  }
1275
- await Promise.all(a.map((id) => this.delete(id)));
1276
- return;
1277
- }
1278
- if (isString(a)) {
1279
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1280
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1281
- return;
1282
- }
1283
- if (isObject(a) && isString(a.id)) {
1284
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1285
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1286
- return;
1287
- }
1288
- 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
+ });
1289
1550
  }
1290
1551
  async search(query, options = {}) {
1291
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1292
- const { records } = await searchBranch({
1293
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1294
- body: { tables: [__privateGet$3(this, _table)], query, fuzziness: options.fuzziness },
1295
- ...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));
1296
1568
  });
1297
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), item));
1298
1569
  }
1299
1570
  async query(query) {
1300
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1301
- if (cacheQuery)
1302
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1303
- const data = query.getQueryOptions();
1304
- const body = {
1305
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1306
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1307
- page: data.page,
1308
- columns: data.columns
1309
- };
1310
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1311
- const { meta, records: objects } = await queryTable({
1312
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1313
- body,
1314
- ...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);
1315
1592
  });
1316
- const records = objects.map((record) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), record));
1317
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1318
- return new Page(query, meta, records);
1319
1593
  }
1320
1594
  }
1321
1595
  _table = new WeakMap();
1322
- _links = new WeakMap();
1323
1596
  _getFetchProps = new WeakMap();
1597
+ _db = new WeakMap();
1324
1598
  _cache = new WeakMap();
1599
+ _schemaTables$2 = new WeakMap();
1600
+ _trace = new WeakMap();
1325
1601
  _insertRecordWithoutId = new WeakSet();
1326
- insertRecordWithoutId_fn = async function(object) {
1327
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1602
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1603
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1328
1604
  const record = transformObjectLinks(object);
1329
1605
  const response = await insertRecord({
1330
1606
  pathParams: {
1331
1607
  workspace: "{workspaceId}",
1332
1608
  dbBranchName: "{dbBranch}",
1333
- tableName: __privateGet$3(this, _table)
1609
+ tableName: __privateGet$4(this, _table)
1334
1610
  },
1611
+ queryParams: { columns },
1335
1612
  body: record,
1336
1613
  ...fetchProps
1337
1614
  });
1338
- const finalObject = await this.read(response.id);
1339
- if (!finalObject) {
1340
- throw new Error("The server failed to save the record");
1341
- }
1342
- 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);
1343
1617
  };
1344
1618
  _insertRecordWithId = new WeakSet();
1345
- insertRecordWithId_fn = async function(recordId, object) {
1346
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1619
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1620
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1347
1621
  const record = transformObjectLinks(object);
1348
1622
  const response = await insertRecordWithID({
1349
1623
  pathParams: {
1350
1624
  workspace: "{workspaceId}",
1351
1625
  dbBranchName: "{dbBranch}",
1352
- tableName: __privateGet$3(this, _table),
1626
+ tableName: __privateGet$4(this, _table),
1353
1627
  recordId
1354
1628
  },
1355
1629
  body: record,
1356
- queryParams: { createOnly: true },
1630
+ queryParams: { createOnly: true, columns },
1357
1631
  ...fetchProps
1358
1632
  });
1359
- const finalObject = await this.read(response.id);
1360
- if (!finalObject) {
1361
- throw new Error("The server failed to save the record");
1362
- }
1363
- 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);
1364
1635
  };
1365
1636
  _bulkInsertTableRecords = new WeakSet();
1366
- bulkInsertTableRecords_fn = async function(objects) {
1367
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1637
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1638
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1368
1639
  const records = objects.map((object) => transformObjectLinks(object));
1369
1640
  const response = await bulkInsertTableRecords({
1370
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1641
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1642
+ queryParams: { columns },
1371
1643
  body: { records },
1372
1644
  ...fetchProps
1373
1645
  });
1374
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1375
- if (finalObjects.length !== objects.length) {
1376
- 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");
1377
1648
  }
1378
- 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));
1379
1651
  };
1380
1652
  _updateRecordWithID = new WeakSet();
1381
- updateRecordWithID_fn = async function(recordId, object) {
1382
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1653
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1654
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1383
1655
  const record = transformObjectLinks(object);
1384
1656
  const response = await updateRecordWithID({
1385
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1657
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1658
+ queryParams: { columns },
1386
1659
  body: record,
1387
1660
  ...fetchProps
1388
1661
  });
1389
- const item = await this.read(response.id);
1390
- if (!item)
1391
- throw new Error("The server failed to save the record");
1392
- 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);
1393
1664
  };
1394
1665
  _upsertRecordWithID = new WeakSet();
1395
- upsertRecordWithID_fn = async function(recordId, object) {
1396
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1666
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1667
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1397
1668
  const response = await upsertRecordWithID({
1398
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1669
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1670
+ queryParams: { columns },
1399
1671
  body: object,
1400
1672
  ...fetchProps
1401
1673
  });
1402
- const item = await this.read(response.id);
1403
- if (!item)
1404
- throw new Error("The server failed to save the record");
1405
- 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);
1406
1676
  };
1407
1677
  _deleteRecord = new WeakSet();
1408
1678
  deleteRecord_fn = async function(recordId) {
1409
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1679
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1410
1680
  await deleteRecord({
1411
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1681
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1412
1682
  ...fetchProps
1413
1683
  });
1414
1684
  };
1415
- _invalidateCache = new WeakSet();
1416
- invalidateCache_fn = async function(recordId) {
1417
- await __privateGet$3(this, _cache).delete(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1418
- const cacheItems = await __privateGet$3(this, _cache).getAll();
1419
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1420
- for (const [key, value] of queries) {
1421
- const ids = getIds(value);
1422
- if (ids.includes(recordId))
1423
- await __privateGet$3(this, _cache).delete(key);
1424
- }
1425
- };
1426
- _setCacheRecord = new WeakSet();
1427
- setCacheRecord_fn = async function(record) {
1428
- if (!__privateGet$3(this, _cache).cacheRecords)
1429
- return;
1430
- await __privateGet$3(this, _cache).set(`rec_${__privateGet$3(this, _table)}:${record.id}`, record);
1431
- };
1432
- _getCacheRecord = new WeakSet();
1433
- getCacheRecord_fn = async function(recordId) {
1434
- if (!__privateGet$3(this, _cache).cacheRecords)
1435
- return null;
1436
- return __privateGet$3(this, _cache).get(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1437
- };
1438
1685
  _setCacheQuery = new WeakSet();
1439
1686
  setCacheQuery_fn = async function(query, meta, records) {
1440
- await __privateGet$3(this, _cache).set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1687
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1441
1688
  };
1442
1689
  _getCacheQuery = new WeakSet();
1443
1690
  getCacheQuery_fn = async function(query) {
1444
- const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
1445
- const result = await __privateGet$3(this, _cache).get(key);
1691
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1692
+ const result = await __privateGet$4(this, _cache).get(key);
1446
1693
  if (!result)
1447
1694
  return null;
1448
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1449
- if (!ttl || ttl < 0)
1450
- return result;
1695
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1696
+ if (ttl < 0)
1697
+ return null;
1451
1698
  const hasExpired = result.date.getTime() + ttl < Date.now();
1452
1699
  return hasExpired ? null : result;
1453
1700
  };
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);
1705
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1706
+ const { schema } = await getBranchDetails({
1707
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1708
+ ...fetchProps
1709
+ });
1710
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1711
+ return schema.tables;
1712
+ };
1454
1713
  const transformObjectLinks = (object) => {
1455
1714
  return Object.entries(object).reduce((acc, [key, value]) => {
1456
1715
  if (key === "xata")
@@ -1458,47 +1717,63 @@ const transformObjectLinks = (object) => {
1458
1717
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1459
1718
  }, {});
1460
1719
  };
1461
- const initObject = (db, links, table, object) => {
1720
+ const initObject = (db, schemaTables, table, object) => {
1462
1721
  const result = {};
1463
- Object.assign(result, object);
1464
- const tableLinks = links[table] || [];
1465
- for (const link of tableLinks) {
1466
- const [field, linkTable] = link;
1467
- const value = result[field];
1468
- if (value && isObject(value)) {
1469
- result[field] = initObject(db, links, linkTable, value);
1722
+ const { xata, ...rest } = object ?? {};
1723
+ Object.assign(result, rest);
1724
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1725
+ if (!columns)
1726
+ console.error(`Table ${table} not found in schema`);
1727
+ for (const column of columns ?? []) {
1728
+ const value = result[column.name];
1729
+ switch (column.type) {
1730
+ case "datetime": {
1731
+ const date = value !== void 0 ? new Date(value) : void 0;
1732
+ if (date && isNaN(date.getTime())) {
1733
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1734
+ } else if (date) {
1735
+ result[column.name] = date;
1736
+ }
1737
+ break;
1738
+ }
1739
+ case "link": {
1740
+ const linkTable = column.link?.table;
1741
+ if (!linkTable) {
1742
+ console.error(`Failed to parse link for field ${column.name}`);
1743
+ } else if (isObject(value)) {
1744
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1745
+ }
1746
+ break;
1747
+ }
1470
1748
  }
1471
1749
  }
1472
- result.read = function() {
1473
- return db[table].read(result["id"]);
1750
+ result.read = function(columns2) {
1751
+ return db[table].read(result["id"], columns2);
1474
1752
  };
1475
- result.update = function(data) {
1476
- return db[table].update(result["id"], data);
1753
+ result.update = function(data, columns2) {
1754
+ return db[table].update(result["id"], data, columns2);
1477
1755
  };
1478
1756
  result.delete = function() {
1479
1757
  return db[table].delete(result["id"]);
1480
1758
  };
1481
- for (const prop of ["read", "update", "delete"]) {
1759
+ result.getMetadata = function() {
1760
+ return xata;
1761
+ };
1762
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1482
1763
  Object.defineProperty(result, prop, { enumerable: false });
1483
1764
  }
1484
1765
  Object.freeze(result);
1485
1766
  return result;
1486
1767
  };
1487
- function getIds(value) {
1488
- if (Array.isArray(value)) {
1489
- return value.map((item) => getIds(item)).flat();
1490
- }
1491
- if (!isObject(value))
1492
- return [];
1493
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1494
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1768
+ function isResponseWithRecords(value) {
1769
+ return isObject(value) && Array.isArray(value.records);
1495
1770
  }
1496
1771
 
1497
1772
  var __accessCheck$3 = (obj, member, msg) => {
1498
1773
  if (!member.has(obj))
1499
1774
  throw TypeError("Cannot " + msg);
1500
1775
  };
1501
- var __privateGet$2 = (obj, member, getter) => {
1776
+ var __privateGet$3 = (obj, member, getter) => {
1502
1777
  __accessCheck$3(obj, member, "read from private field");
1503
1778
  return getter ? getter.call(obj) : member.get(obj);
1504
1779
  };
@@ -1507,7 +1782,7 @@ var __privateAdd$3 = (obj, member, value) => {
1507
1782
  throw TypeError("Cannot add the same private member more than once");
1508
1783
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1509
1784
  };
1510
- var __privateSet$1 = (obj, member, value, setter) => {
1785
+ var __privateSet$3 = (obj, member, value, setter) => {
1511
1786
  __accessCheck$3(obj, member, "write to private field");
1512
1787
  setter ? setter.call(obj, value) : member.set(obj, value);
1513
1788
  return value;
@@ -1516,46 +1791,52 @@ var _map;
1516
1791
  class SimpleCache {
1517
1792
  constructor(options = {}) {
1518
1793
  __privateAdd$3(this, _map, void 0);
1519
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
1794
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1520
1795
  this.capacity = options.max ?? 500;
1521
- this.cacheRecords = options.cacheRecords ?? true;
1522
1796
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1523
1797
  }
1524
1798
  async getAll() {
1525
- return Object.fromEntries(__privateGet$2(this, _map));
1799
+ return Object.fromEntries(__privateGet$3(this, _map));
1526
1800
  }
1527
1801
  async get(key) {
1528
- return __privateGet$2(this, _map).get(key) ?? null;
1802
+ return __privateGet$3(this, _map).get(key) ?? null;
1529
1803
  }
1530
1804
  async set(key, value) {
1531
1805
  await this.delete(key);
1532
- __privateGet$2(this, _map).set(key, value);
1533
- if (__privateGet$2(this, _map).size > this.capacity) {
1534
- const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
1806
+ __privateGet$3(this, _map).set(key, value);
1807
+ if (__privateGet$3(this, _map).size > this.capacity) {
1808
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1535
1809
  await this.delete(leastRecentlyUsed);
1536
1810
  }
1537
1811
  }
1538
1812
  async delete(key) {
1539
- __privateGet$2(this, _map).delete(key);
1813
+ __privateGet$3(this, _map).delete(key);
1540
1814
  }
1541
1815
  async clear() {
1542
- return __privateGet$2(this, _map).clear();
1816
+ return __privateGet$3(this, _map).clear();
1543
1817
  }
1544
1818
  }
1545
1819
  _map = new WeakMap();
1546
1820
 
1547
- const gt = (value) => ({ $gt: value });
1548
- const ge = (value) => ({ $ge: value });
1549
- const gte = (value) => ({ $ge: value });
1550
- const lt = (value) => ({ $lt: value });
1551
- const lte = (value) => ({ $le: value });
1552
- 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;
1553
1833
  const exists = (column) => ({ $exists: column });
1554
1834
  const notExists = (column) => ({ $notExists: column });
1555
1835
  const startsWith = (value) => ({ $startsWith: value });
1556
1836
  const endsWith = (value) => ({ $endsWith: value });
1557
1837
  const pattern = (value) => ({ $pattern: value });
1558
1838
  const is = (value) => ({ $is: value });
1839
+ const equals = is;
1559
1840
  const isNot = (value) => ({ $isNot: value });
1560
1841
  const contains = (value) => ({ $contains: value });
1561
1842
  const includes = (value) => ({ $includes: value });
@@ -1567,7 +1848,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1567
1848
  if (!member.has(obj))
1568
1849
  throw TypeError("Cannot " + msg);
1569
1850
  };
1570
- var __privateGet$1 = (obj, member, getter) => {
1851
+ var __privateGet$2 = (obj, member, getter) => {
1571
1852
  __accessCheck$2(obj, member, "read from private field");
1572
1853
  return getter ? getter.call(obj) : member.get(obj);
1573
1854
  };
@@ -1576,130 +1857,178 @@ var __privateAdd$2 = (obj, member, value) => {
1576
1857
  throw TypeError("Cannot add the same private member more than once");
1577
1858
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1578
1859
  };
1579
- 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;
1580
1866
  class SchemaPlugin extends XataPlugin {
1581
- constructor(links, tableNames) {
1867
+ constructor(schemaTables) {
1582
1868
  super();
1583
- this.links = links;
1584
- this.tableNames = tableNames;
1585
1869
  __privateAdd$2(this, _tables, {});
1870
+ __privateAdd$2(this, _schemaTables$1, void 0);
1871
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1586
1872
  }
1587
1873
  build(pluginOptions) {
1588
- const links = this.links;
1589
- const db = new Proxy({}, {
1590
- get: (_target, table) => {
1591
- if (!isString(table))
1592
- throw new Error("Invalid table name");
1593
- if (!__privateGet$1(this, _tables)[table]) {
1594
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, links });
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];
1595
1884
  }
1596
- return __privateGet$1(this, _tables)[table];
1597
1885
  }
1598
- });
1599
- for (const table of this.tableNames ?? []) {
1600
- db[table] = new RestRepository({ db, pluginOptions, table, links });
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) });
1601
1890
  }
1602
1891
  return db;
1603
1892
  }
1604
1893
  }
1605
1894
  _tables = new WeakMap();
1895
+ _schemaTables$1 = new WeakMap();
1606
1896
 
1607
1897
  var __accessCheck$1 = (obj, member, msg) => {
1608
1898
  if (!member.has(obj))
1609
1899
  throw TypeError("Cannot " + msg);
1610
1900
  };
1901
+ var __privateGet$1 = (obj, member, getter) => {
1902
+ __accessCheck$1(obj, member, "read from private field");
1903
+ return getter ? getter.call(obj) : member.get(obj);
1904
+ };
1611
1905
  var __privateAdd$1 = (obj, member, value) => {
1612
1906
  if (member.has(obj))
1613
1907
  throw TypeError("Cannot add the same private member more than once");
1614
1908
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1615
1909
  };
1910
+ var __privateSet$1 = (obj, member, value, setter) => {
1911
+ __accessCheck$1(obj, member, "write to private field");
1912
+ setter ? setter.call(obj, value) : member.set(obj, value);
1913
+ return value;
1914
+ };
1616
1915
  var __privateMethod$1 = (obj, member, method) => {
1617
1916
  __accessCheck$1(obj, member, "access private method");
1618
1917
  return method;
1619
1918
  };
1620
- var _search, search_fn;
1919
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1621
1920
  class SearchPlugin extends XataPlugin {
1622
- constructor(db, links) {
1921
+ constructor(db, schemaTables) {
1623
1922
  super();
1624
1923
  this.db = db;
1625
- this.links = links;
1626
1924
  __privateAdd$1(this, _search);
1925
+ __privateAdd$1(this, _getSchemaTables);
1926
+ __privateAdd$1(this, _schemaTables, void 0);
1927
+ __privateSet$1(this, _schemaTables, schemaTables);
1627
1928
  }
1628
1929
  build({ getFetchProps }) {
1629
1930
  return {
1630
1931
  all: async (query, options = {}) => {
1631
1932
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1933
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1632
1934
  return records.map((record) => {
1633
1935
  const { table = "orphan" } = record.xata;
1634
- return { table, record: initObject(this.db, this.links, table, record) };
1936
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1635
1937
  });
1636
1938
  },
1637
1939
  byTable: async (query, options = {}) => {
1638
1940
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1941
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1639
1942
  return records.reduce((acc, record) => {
1640
1943
  const { table = "orphan" } = record.xata;
1641
1944
  const items = acc[table] ?? [];
1642
- const item = initObject(this.db, this.links, table, record);
1945
+ const item = initObject(this.db, schemaTables, table, record);
1643
1946
  return { ...acc, [table]: [...items, item] };
1644
1947
  }, {});
1645
1948
  }
1646
1949
  };
1647
1950
  }
1648
1951
  }
1952
+ _schemaTables = new WeakMap();
1649
1953
  _search = new WeakSet();
1650
1954
  search_fn = async function(query, options, getFetchProps) {
1651
1955
  const fetchProps = await getFetchProps();
1652
- const { tables, fuzziness } = options ?? {};
1956
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1653
1957
  const { records } = await searchBranch({
1654
1958
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1655
- body: { tables, query, fuzziness },
1959
+ body: { tables, query, fuzziness, prefix, highlight },
1656
1960
  ...fetchProps
1657
1961
  });
1658
1962
  return records;
1659
1963
  };
1964
+ _getSchemaTables = new WeakSet();
1965
+ getSchemaTables_fn = async function(getFetchProps) {
1966
+ if (__privateGet$1(this, _schemaTables))
1967
+ return __privateGet$1(this, _schemaTables);
1968
+ const fetchProps = await getFetchProps();
1969
+ const { schema } = await getBranchDetails({
1970
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1971
+ ...fetchProps
1972
+ });
1973
+ __privateSet$1(this, _schemaTables, schema.tables);
1974
+ return schema.tables;
1975
+ };
1660
1976
 
1661
1977
  const isBranchStrategyBuilder = (strategy) => {
1662
1978
  return typeof strategy === "function";
1663
1979
  };
1664
1980
 
1665
- const envBranchNames = [
1666
- "XATA_BRANCH",
1667
- "VERCEL_GIT_COMMIT_REF",
1668
- "CF_PAGES_BRANCH",
1669
- "BRANCH"
1670
- ];
1671
- const defaultBranch = "main";
1672
1981
  async function getCurrentBranchName(options) {
1673
- const env = await getBranchByEnvVariable();
1674
- if (env)
1675
- return env;
1676
- const branch = await getGitBranch();
1677
- if (!branch)
1678
- return defaultBranch;
1679
- const details = await getDatabaseBranch(branch, options);
1680
- if (details)
1681
- return branch;
1682
- return defaultBranch;
1982
+ const { branch, envBranch } = getEnvironment();
1983
+ if (branch) {
1984
+ const details = await getDatabaseBranch(branch, options);
1985
+ if (details)
1986
+ return branch;
1987
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1988
+ }
1989
+ const gitBranch = envBranch || await getGitBranch();
1990
+ return resolveXataBranch(gitBranch, options);
1683
1991
  }
1684
1992
  async function getCurrentBranchDetails(options) {
1685
- const env = await getBranchByEnvVariable();
1686
- if (env)
1687
- return getDatabaseBranch(env, options);
1688
- const branch = await getGitBranch();
1689
- if (!branch)
1690
- return getDatabaseBranch(defaultBranch, options);
1691
- const details = await getDatabaseBranch(branch, options);
1692
- if (details)
1693
- return details;
1694
- return getDatabaseBranch(defaultBranch, options);
1993
+ const branch = await getCurrentBranchName(options);
1994
+ return getDatabaseBranch(branch, options);
1995
+ }
1996
+ async function resolveXataBranch(gitBranch, options) {
1997
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1998
+ const apiKey = options?.apiKey || getAPIKey();
1999
+ if (!databaseURL)
2000
+ throw new Error(
2001
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2002
+ );
2003
+ if (!apiKey)
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
+ );
2007
+ const [protocol, , host, , dbName] = databaseURL.split("/");
2008
+ const [workspace] = host.split(".");
2009
+ const { fallbackBranch } = getEnvironment();
2010
+ const { branch } = await resolveBranch({
2011
+ apiKey,
2012
+ apiUrl: databaseURL,
2013
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
2014
+ workspacesApiUrl: `${protocol}//${host}`,
2015
+ pathParams: { dbName, workspace },
2016
+ queryParams: { gitBranch, fallbackBranch },
2017
+ trace: defaultTrace
2018
+ });
2019
+ return branch;
1695
2020
  }
1696
2021
  async function getDatabaseBranch(branch, options) {
1697
2022
  const databaseURL = options?.databaseURL || getDatabaseURL();
1698
2023
  const apiKey = options?.apiKey || getAPIKey();
1699
2024
  if (!databaseURL)
1700
- 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
+ );
1701
2028
  if (!apiKey)
1702
- 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
+ );
1703
2032
  const [protocol, , host, , database] = databaseURL.split("/");
1704
2033
  const [workspace] = host.split(".");
1705
2034
  const dbBranchName = `${database}:${branch}`;
@@ -1709,10 +2038,8 @@ async function getDatabaseBranch(branch, options) {
1709
2038
  apiUrl: databaseURL,
1710
2039
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1711
2040
  workspacesApiUrl: `${protocol}//${host}`,
1712
- pathParams: {
1713
- dbBranchName,
1714
- workspace
1715
- }
2041
+ pathParams: { dbBranchName, workspace },
2042
+ trace: defaultTrace
1716
2043
  });
1717
2044
  } catch (err) {
1718
2045
  if (isObject(err) && err.status === 404)
@@ -1720,21 +2047,10 @@ async function getDatabaseBranch(branch, options) {
1720
2047
  throw err;
1721
2048
  }
1722
2049
  }
1723
- function getBranchByEnvVariable() {
1724
- for (const name of envBranchNames) {
1725
- const value = getEnvVariable(name);
1726
- if (value) {
1727
- return value;
1728
- }
1729
- }
1730
- try {
1731
- return XATA_BRANCH;
1732
- } catch (err) {
1733
- }
1734
- }
1735
2050
  function getDatabaseURL() {
1736
2051
  try {
1737
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2052
+ const { databaseURL } = getEnvironment();
2053
+ return databaseURL;
1738
2054
  } catch (err) {
1739
2055
  return void 0;
1740
2056
  }
@@ -1763,24 +2079,27 @@ var __privateMethod = (obj, member, method) => {
1763
2079
  return method;
1764
2080
  };
1765
2081
  const buildClient = (plugins) => {
1766
- 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;
1767
2083
  return _a = class {
1768
- constructor(options = {}, links, tables) {
2084
+ constructor(options = {}, schemaTables) {
1769
2085
  __privateAdd(this, _parseOptions);
1770
2086
  __privateAdd(this, _getFetchProps);
1771
2087
  __privateAdd(this, _evaluateBranch);
1772
2088
  __privateAdd(this, _branch, void 0);
2089
+ __privateAdd(this, _options, void 0);
1773
2090
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2091
+ __privateSet(this, _options, safeOptions);
1774
2092
  const pluginOptions = {
1775
2093
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1776
- cache: safeOptions.cache
2094
+ cache: safeOptions.cache,
2095
+ trace: safeOptions.trace
1777
2096
  };
1778
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1779
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
2097
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2098
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1780
2099
  this.db = db;
1781
2100
  this.search = search;
1782
2101
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1783
- if (!namespace)
2102
+ if (namespace === void 0)
1784
2103
  continue;
1785
2104
  const result = namespace.build(pluginOptions);
1786
2105
  if (result instanceof Promise) {
@@ -1792,22 +2111,26 @@ const buildClient = (plugins) => {
1792
2111
  }
1793
2112
  }
1794
2113
  }
1795
- }, _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) {
1796
2120
  const fetch = getFetchImplementation(options?.fetch);
1797
2121
  const databaseURL = options?.databaseURL || getDatabaseURL();
1798
2122
  const apiKey = options?.apiKey || getAPIKey();
1799
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1800
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1801
- if (!databaseURL || !apiKey) {
1802
- throw new Error("Options databaseURL and apiKey are required");
2123
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2124
+ const trace = options?.trace ?? defaultTrace;
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 });
2126
+ if (!apiKey) {
2127
+ throw new Error("Option apiKey is required");
1803
2128
  }
1804
- return { fetch, databaseURL, apiKey, branch, cache };
1805
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1806
- fetch,
1807
- apiKey,
1808
- databaseURL,
1809
- branch
1810
- }) {
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 }) {
1811
2134
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1812
2135
  if (!branchValue)
1813
2136
  throw new Error("Unable to resolve branch value");
@@ -1819,12 +2142,13 @@ const buildClient = (plugins) => {
1819
2142
  const hasBranch = params.dbBranchName ?? params.branch;
1820
2143
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
1821
2144
  return databaseURL + newPath;
1822
- }
2145
+ },
2146
+ trace
1823
2147
  };
1824
2148
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1825
2149
  if (__privateGet(this, _branch))
1826
2150
  return __privateGet(this, _branch);
1827
- if (!param)
2151
+ if (param === void 0)
1828
2152
  return void 0;
1829
2153
  const strategies = Array.isArray(param) ? [...param] : [param];
1830
2154
  const evaluateBranch = async (strategy) => {
@@ -1842,6 +2166,88 @@ const buildClient = (plugins) => {
1842
2166
  class BaseClient extends buildClient() {
1843
2167
  }
1844
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
+
1845
2251
  class XataError extends Error {
1846
2252
  constructor(message, status) {
1847
2253
  super(message);
@@ -1849,5 +2255,5 @@ class XataError extends Error {
1849
2255
  }
1850
2256
  }
1851
2257
 
1852
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, 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 };
1853
2259
  //# sourceMappingURL=index.mjs.map