@xata.io/client 0.0.0-alpha.vf4b92f1 → 0.0.0-alpha.vf5ce72f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2,6 +2,48 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ function _interopNamespace(e) {
6
+ if (e && e.__esModule) return e;
7
+ var n = Object.create(null);
8
+ if (e) {
9
+ Object.keys(e).forEach(function (k) {
10
+ if (k !== 'default') {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: true,
14
+ get: function () { return e[k]; }
15
+ });
16
+ }
17
+ });
18
+ }
19
+ n["default"] = e;
20
+ return Object.freeze(n);
21
+ }
22
+
23
+ const defaultTrace = async (_name, fn, _options) => {
24
+ return await fn({
25
+ setAttributes: () => {
26
+ return;
27
+ },
28
+ onError: () => {
29
+ return;
30
+ }
31
+ });
32
+ };
33
+ const TraceAttributes = {
34
+ VERSION: "xata.sdk.version",
35
+ TABLE: "xata.table",
36
+ HTTP_REQUEST_ID: "http.request_id",
37
+ HTTP_STATUS_CODE: "http.status_code",
38
+ HTTP_HOST: "http.host",
39
+ HTTP_SCHEME: "http.scheme",
40
+ HTTP_USER_AGENT: "http.user_agent",
41
+ HTTP_METHOD: "http.method",
42
+ HTTP_URL: "http.url",
43
+ HTTP_ROUTE: "http.route",
44
+ HTTP_TARGET: "http.target"
45
+ };
46
+
5
47
  function notEmpty(value) {
6
48
  return value !== null && value !== void 0;
7
49
  }
@@ -11,43 +53,101 @@ function compact(arr) {
11
53
  function isObject(value) {
12
54
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
13
55
  }
56
+ function isDefined(value) {
57
+ return value !== null && value !== void 0;
58
+ }
14
59
  function isString(value) {
15
- return value !== void 0 && value !== null && typeof value === "string";
60
+ return isDefined(value) && typeof value === "string";
61
+ }
62
+ function isStringArray(value) {
63
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
16
64
  }
17
65
  function toBase64(value) {
18
66
  try {
19
67
  return btoa(value);
20
68
  } catch (err) {
21
- return Buffer.from(value).toString("base64");
69
+ const buf = Buffer;
70
+ return buf.from(value).toString("base64");
22
71
  }
23
72
  }
24
73
 
25
- function getEnvVariable(name) {
74
+ function getEnvironment() {
26
75
  try {
27
- if (isObject(process) && isString(process?.env?.[name])) {
28
- return process.env[name];
76
+ if (isObject(process) && isObject(process.env)) {
77
+ return {
78
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
79
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
80
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
81
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
82
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
83
+ };
29
84
  }
30
85
  } catch (err) {
31
86
  }
32
87
  try {
33
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
34
- return Deno.env.get(name);
88
+ if (isObject(Deno) && isObject(Deno.env)) {
89
+ return {
90
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
91
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
92
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
93
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
94
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
95
+ };
35
96
  }
36
97
  } catch (err) {
37
98
  }
99
+ return {
100
+ apiKey: getGlobalApiKey(),
101
+ databaseURL: getGlobalDatabaseURL(),
102
+ branch: getGlobalBranch(),
103
+ envBranch: void 0,
104
+ fallbackBranch: getGlobalFallbackBranch()
105
+ };
106
+ }
107
+ function getGlobalApiKey() {
108
+ try {
109
+ return XATA_API_KEY;
110
+ } catch (err) {
111
+ return void 0;
112
+ }
113
+ }
114
+ function getGlobalDatabaseURL() {
115
+ try {
116
+ return XATA_DATABASE_URL;
117
+ } catch (err) {
118
+ return void 0;
119
+ }
120
+ }
121
+ function getGlobalBranch() {
122
+ try {
123
+ return XATA_BRANCH;
124
+ } catch (err) {
125
+ return void 0;
126
+ }
127
+ }
128
+ function getGlobalFallbackBranch() {
129
+ try {
130
+ return XATA_FALLBACK_BRANCH;
131
+ } catch (err) {
132
+ return void 0;
133
+ }
38
134
  }
39
135
  async function getGitBranch() {
136
+ const cmd = ["git", "branch", "--show-current"];
137
+ const fullCmd = cmd.join(" ");
138
+ const nodeModule = ["child", "process"].join("_");
139
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
40
140
  try {
41
- return require("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
141
+ if (typeof require === "function") {
142
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
143
+ }
144
+ const { execSync } = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(nodeModule);
145
+ return execSync(fullCmd, execOptions).toString().trim();
42
146
  } catch (err) {
43
147
  }
44
148
  try {
45
149
  if (isObject(Deno)) {
46
- const process2 = Deno.run({
47
- cmd: ["git", "branch", "--show-current"],
48
- stdout: "piped",
49
- stderr: "piped"
50
- });
150
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
51
151
  return new TextDecoder().decode(await process2.output()).trim();
52
152
  }
53
153
  } catch (err) {
@@ -56,7 +156,8 @@ async function getGitBranch() {
56
156
 
57
157
  function getAPIKey() {
58
158
  try {
59
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
159
+ const { apiKey } = getEnvironment();
160
+ return apiKey;
60
161
  } catch (err) {
61
162
  return void 0;
62
163
  }
@@ -66,21 +167,35 @@ function getFetchImplementation(userFetch) {
66
167
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
67
168
  const fetchImpl = userFetch ?? globalFetch;
68
169
  if (!fetchImpl) {
69
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
170
+ throw new Error(
171
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
172
+ );
70
173
  }
71
174
  return fetchImpl;
72
175
  }
73
176
 
74
- class FetcherError extends Error {
75
- constructor(status, data) {
177
+ const VERSION = "0.0.0-alpha.vf5ce72f";
178
+
179
+ class ErrorWithCause extends Error {
180
+ constructor(message, options) {
181
+ super(message, options);
182
+ }
183
+ }
184
+ class FetcherError extends ErrorWithCause {
185
+ constructor(status, data, requestId) {
76
186
  super(getMessage(data));
77
187
  this.status = status;
78
188
  this.errors = isBulkError(data) ? data.errors : void 0;
189
+ this.requestId = requestId;
79
190
  if (data instanceof Error) {
80
191
  this.stack = data.stack;
81
192
  this.cause = data.cause;
82
193
  }
83
194
  }
195
+ toString() {
196
+ const error = super.toString();
197
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
198
+ }
84
199
  }
85
200
  function isBulkError(error) {
86
201
  return isObject(error) && Array.isArray(error.errors);
@@ -103,7 +218,12 @@ function getMessage(data) {
103
218
  }
104
219
 
105
220
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
106
- const query = new URLSearchParams(queryParams).toString();
221
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
222
+ if (value === void 0 || value === null)
223
+ return acc;
224
+ return { ...acc, [key]: value };
225
+ }, {});
226
+ const query = new URLSearchParams(cleanQueryParams).toString();
107
227
  const queryString = query.length > 0 ? `?${query}` : "";
108
228
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
109
229
  };
@@ -133,32 +253,62 @@ async function fetch$1({
133
253
  fetchImpl,
134
254
  apiKey,
135
255
  apiUrl,
136
- workspacesApiUrl
256
+ workspacesApiUrl,
257
+ trace
137
258
  }) {
138
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
139
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
140
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
141
- const response = await fetchImpl(url, {
142
- method: method.toUpperCase(),
143
- body: body ? JSON.stringify(body) : void 0,
144
- headers: {
145
- "Content-Type": "application/json",
146
- ...headers,
147
- ...hostHeader(fullUrl),
148
- Authorization: `Bearer ${apiKey}`
149
- }
150
- });
151
- if (response.status === 204) {
152
- return {};
153
- }
259
+ return trace(
260
+ `${method.toUpperCase()} ${path}`,
261
+ async ({ setAttributes, onError }) => {
262
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
263
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
264
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
265
+ setAttributes({
266
+ [TraceAttributes.HTTP_URL]: url,
267
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
268
+ });
269
+ const response = await fetchImpl(url, {
270
+ method: method.toUpperCase(),
271
+ body: body ? JSON.stringify(body) : void 0,
272
+ headers: {
273
+ "Content-Type": "application/json",
274
+ "User-Agent": `Xata client-ts/${VERSION}`,
275
+ ...headers,
276
+ ...hostHeader(fullUrl),
277
+ Authorization: `Bearer ${apiKey}`
278
+ }
279
+ });
280
+ if (response.status === 204) {
281
+ return {};
282
+ }
283
+ const { host, protocol } = parseUrl(response.url);
284
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
285
+ setAttributes({
286
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
287
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
288
+ [TraceAttributes.HTTP_HOST]: host,
289
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
290
+ });
291
+ try {
292
+ const jsonResponse = await response.json();
293
+ if (response.ok) {
294
+ return jsonResponse;
295
+ }
296
+ throw new FetcherError(response.status, jsonResponse, requestId);
297
+ } catch (error) {
298
+ const fetcherError = new FetcherError(response.status, error, requestId);
299
+ onError(fetcherError.message);
300
+ throw fetcherError;
301
+ }
302
+ },
303
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
304
+ );
305
+ }
306
+ function parseUrl(url) {
154
307
  try {
155
- const jsonResponse = await response.json();
156
- if (response.ok) {
157
- return jsonResponse;
158
- }
159
- throw new FetcherError(response.status, jsonResponse);
308
+ const { host, protocol } = new URL(url);
309
+ return { host, protocol };
160
310
  } catch (error) {
161
- throw new FetcherError(response.status, error);
311
+ return {};
162
312
  }
163
313
  }
164
314
 
@@ -217,6 +367,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
217
367
  ...variables
218
368
  });
219
369
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
370
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
220
371
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
221
372
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
222
373
  method: "delete",
@@ -252,16 +403,25 @@ const deleteDatabase = (variables) => fetch$1({
252
403
  method: "delete",
253
404
  ...variables
254
405
  });
255
- const getBranchDetails = (variables) => fetch$1({
256
- url: "/db/{dbBranchName}",
406
+ const getDatabaseMetadata = (variables) => fetch$1({
407
+ url: "/dbs/{dbName}/metadata",
257
408
  method: "get",
258
409
  ...variables
259
410
  });
260
- const createBranch = (variables) => fetch$1({
411
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
412
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
413
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
414
+ const resolveBranch = (variables) => fetch$1({
415
+ url: "/dbs/{dbName}/resolveBranch",
416
+ method: "get",
417
+ ...variables
418
+ });
419
+ const getBranchDetails = (variables) => fetch$1({
261
420
  url: "/db/{dbBranchName}",
262
- method: "put",
421
+ method: "get",
263
422
  ...variables
264
423
  });
424
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
265
425
  const deleteBranch = (variables) => fetch$1({
266
426
  url: "/db/{dbBranchName}",
267
427
  method: "delete",
@@ -335,11 +495,7 @@ const updateColumn = (variables) => fetch$1({
335
495
  method: "patch",
336
496
  ...variables
337
497
  });
338
- const insertRecord = (variables) => fetch$1({
339
- url: "/db/{dbBranchName}/tables/{tableName}/data",
340
- method: "post",
341
- ...variables
342
- });
498
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
343
499
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
344
500
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
345
501
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -359,6 +515,11 @@ const queryTable = (variables) => fetch$1({
359
515
  method: "post",
360
516
  ...variables
361
517
  });
518
+ const searchTable = (variables) => fetch$1({
519
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
520
+ method: "post",
521
+ ...variables
522
+ });
362
523
  const searchBranch = (variables) => fetch$1({
363
524
  url: "/db/{dbBranchName}/search",
364
525
  method: "post",
@@ -376,11 +537,21 @@ const operationsByTag = {
376
537
  updateWorkspaceMemberRole,
377
538
  removeWorkspaceMember,
378
539
  inviteWorkspaceMember,
540
+ updateWorkspaceMemberInvite,
379
541
  cancelWorkspaceMemberInvite,
380
542
  resendWorkspaceMemberInvite,
381
543
  acceptWorkspaceMemberInvite
382
544
  },
383
- database: { getDatabaseList, createDatabase, deleteDatabase },
545
+ database: {
546
+ getDatabaseList,
547
+ createDatabase,
548
+ deleteDatabase,
549
+ getDatabaseMetadata,
550
+ getGitBranchesMapping,
551
+ addGitBranchesEntry,
552
+ removeGitBranchesEntry,
553
+ resolveBranch
554
+ },
384
555
  branch: {
385
556
  getBranchList,
386
557
  getBranchDetails,
@@ -414,6 +585,7 @@ const operationsByTag = {
414
585
  getRecord,
415
586
  bulkInsertTableRecords,
416
587
  queryTable,
588
+ searchTable,
417
589
  searchBranch
418
590
  }
419
591
  };
@@ -447,7 +619,7 @@ var __accessCheck$7 = (obj, member, msg) => {
447
619
  if (!member.has(obj))
448
620
  throw TypeError("Cannot " + msg);
449
621
  };
450
- var __privateGet$6 = (obj, member, getter) => {
622
+ var __privateGet$7 = (obj, member, getter) => {
451
623
  __accessCheck$7(obj, member, "read from private field");
452
624
  return getter ? getter.call(obj) : member.get(obj);
453
625
  };
@@ -456,7 +628,7 @@ var __privateAdd$7 = (obj, member, value) => {
456
628
  throw TypeError("Cannot add the same private member more than once");
457
629
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
458
630
  };
459
- var __privateSet$5 = (obj, member, value, setter) => {
631
+ var __privateSet$7 = (obj, member, value, setter) => {
460
632
  __accessCheck$7(obj, member, "write to private field");
461
633
  setter ? setter.call(obj, value) : member.set(obj, value);
462
634
  return value;
@@ -467,46 +639,48 @@ class XataApiClient {
467
639
  __privateAdd$7(this, _extraProps, void 0);
468
640
  __privateAdd$7(this, _namespaces, {});
469
641
  const provider = options.host ?? "production";
470
- const apiKey = options?.apiKey ?? getAPIKey();
642
+ const apiKey = options.apiKey ?? getAPIKey();
643
+ const trace = options.trace ?? defaultTrace;
471
644
  if (!apiKey) {
472
645
  throw new Error("Could not resolve a valid apiKey");
473
646
  }
474
- __privateSet$5(this, _extraProps, {
647
+ __privateSet$7(this, _extraProps, {
475
648
  apiUrl: getHostUrl(provider, "main"),
476
649
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
477
650
  fetchImpl: getFetchImplementation(options.fetch),
478
- apiKey
651
+ apiKey,
652
+ trace
479
653
  });
480
654
  }
481
655
  get user() {
482
- if (!__privateGet$6(this, _namespaces).user)
483
- __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
484
- return __privateGet$6(this, _namespaces).user;
656
+ if (!__privateGet$7(this, _namespaces).user)
657
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
658
+ return __privateGet$7(this, _namespaces).user;
485
659
  }
486
660
  get workspaces() {
487
- if (!__privateGet$6(this, _namespaces).workspaces)
488
- __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
489
- return __privateGet$6(this, _namespaces).workspaces;
661
+ if (!__privateGet$7(this, _namespaces).workspaces)
662
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
663
+ return __privateGet$7(this, _namespaces).workspaces;
490
664
  }
491
665
  get databases() {
492
- if (!__privateGet$6(this, _namespaces).databases)
493
- __privateGet$6(this, _namespaces).databases = new DatabaseApi(__privateGet$6(this, _extraProps));
494
- return __privateGet$6(this, _namespaces).databases;
666
+ if (!__privateGet$7(this, _namespaces).databases)
667
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
668
+ return __privateGet$7(this, _namespaces).databases;
495
669
  }
496
670
  get branches() {
497
- if (!__privateGet$6(this, _namespaces).branches)
498
- __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
499
- return __privateGet$6(this, _namespaces).branches;
671
+ if (!__privateGet$7(this, _namespaces).branches)
672
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
673
+ return __privateGet$7(this, _namespaces).branches;
500
674
  }
501
675
  get tables() {
502
- if (!__privateGet$6(this, _namespaces).tables)
503
- __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
504
- return __privateGet$6(this, _namespaces).tables;
676
+ if (!__privateGet$7(this, _namespaces).tables)
677
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
678
+ return __privateGet$7(this, _namespaces).tables;
505
679
  }
506
680
  get records() {
507
- if (!__privateGet$6(this, _namespaces).records)
508
- __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
509
- return __privateGet$6(this, _namespaces).records;
681
+ if (!__privateGet$7(this, _namespaces).records)
682
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
683
+ return __privateGet$7(this, _namespaces).records;
510
684
  }
511
685
  }
512
686
  _extraProps = new WeakMap();
@@ -598,6 +772,13 @@ class WorkspaceApi {
598
772
  ...this.extraProps
599
773
  });
600
774
  }
775
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
776
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
777
+ pathParams: { workspaceId, inviteId },
778
+ body: { role },
779
+ ...this.extraProps
780
+ });
781
+ }
601
782
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
602
783
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
603
784
  pathParams: { workspaceId, inviteId },
@@ -640,6 +821,39 @@ class DatabaseApi {
640
821
  ...this.extraProps
641
822
  });
642
823
  }
824
+ getDatabaseMetadata(workspace, dbName) {
825
+ return operationsByTag.database.getDatabaseMetadata({
826
+ pathParams: { workspace, dbName },
827
+ ...this.extraProps
828
+ });
829
+ }
830
+ getGitBranchesMapping(workspace, dbName) {
831
+ return operationsByTag.database.getGitBranchesMapping({
832
+ pathParams: { workspace, dbName },
833
+ ...this.extraProps
834
+ });
835
+ }
836
+ addGitBranchesEntry(workspace, dbName, body) {
837
+ return operationsByTag.database.addGitBranchesEntry({
838
+ pathParams: { workspace, dbName },
839
+ body,
840
+ ...this.extraProps
841
+ });
842
+ }
843
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
844
+ return operationsByTag.database.removeGitBranchesEntry({
845
+ pathParams: { workspace, dbName },
846
+ queryParams: { gitBranch },
847
+ ...this.extraProps
848
+ });
849
+ }
850
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
851
+ return operationsByTag.database.resolveBranch({
852
+ pathParams: { workspace, dbName },
853
+ queryParams: { gitBranch, fallbackBranch },
854
+ ...this.extraProps
855
+ });
856
+ }
643
857
  }
644
858
  class BranchApi {
645
859
  constructor(extraProps) {
@@ -657,10 +871,10 @@ class BranchApi {
657
871
  ...this.extraProps
658
872
  });
659
873
  }
660
- createBranch(workspace, database, branch, from = "", options = {}) {
874
+ createBranch(workspace, database, branch, from, options = {}) {
661
875
  return operationsByTag.branch.createBranch({
662
876
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
663
- queryParams: { from },
877
+ queryParams: isString(from) ? { from } : void 0,
664
878
  body: options,
665
879
  ...this.extraProps
666
880
  });
@@ -785,9 +999,10 @@ class RecordsApi {
785
999
  constructor(extraProps) {
786
1000
  this.extraProps = extraProps;
787
1001
  }
788
- insertRecord(workspace, database, branch, tableName, record) {
1002
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
789
1003
  return operationsByTag.records.insertRecord({
790
1004
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1005
+ queryParams: options,
791
1006
  body: record,
792
1007
  ...this.extraProps
793
1008
  });
@@ -816,21 +1031,24 @@ class RecordsApi {
816
1031
  ...this.extraProps
817
1032
  });
818
1033
  }
819
- deleteRecord(workspace, database, branch, tableName, recordId) {
1034
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
820
1035
  return operationsByTag.records.deleteRecord({
821
1036
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1037
+ queryParams: options,
822
1038
  ...this.extraProps
823
1039
  });
824
1040
  }
825
1041
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
826
1042
  return operationsByTag.records.getRecord({
827
1043
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1044
+ queryParams: options,
828
1045
  ...this.extraProps
829
1046
  });
830
1047
  }
831
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1048
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
832
1049
  return operationsByTag.records.bulkInsertTableRecords({
833
1050
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1051
+ queryParams: options,
834
1052
  body: { records },
835
1053
  ...this.extraProps
836
1054
  });
@@ -842,6 +1060,13 @@ class RecordsApi {
842
1060
  ...this.extraProps
843
1061
  });
844
1062
  }
1063
+ searchTable(workspace, database, branch, tableName, query) {
1064
+ return operationsByTag.records.searchTable({
1065
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1066
+ body: query,
1067
+ ...this.extraProps
1068
+ });
1069
+ }
845
1070
  searchBranch(workspace, database, branch, query) {
846
1071
  return operationsByTag.records.searchBranch({
847
1072
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -865,7 +1090,7 @@ var __accessCheck$6 = (obj, member, msg) => {
865
1090
  if (!member.has(obj))
866
1091
  throw TypeError("Cannot " + msg);
867
1092
  };
868
- var __privateGet$5 = (obj, member, getter) => {
1093
+ var __privateGet$6 = (obj, member, getter) => {
869
1094
  __accessCheck$6(obj, member, "read from private field");
870
1095
  return getter ? getter.call(obj) : member.get(obj);
871
1096
  };
@@ -874,30 +1099,30 @@ var __privateAdd$6 = (obj, member, value) => {
874
1099
  throw TypeError("Cannot add the same private member more than once");
875
1100
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
876
1101
  };
877
- var __privateSet$4 = (obj, member, value, setter) => {
1102
+ var __privateSet$6 = (obj, member, value, setter) => {
878
1103
  __accessCheck$6(obj, member, "write to private field");
879
1104
  setter ? setter.call(obj, value) : member.set(obj, value);
880
1105
  return value;
881
1106
  };
882
- var _query;
1107
+ var _query, _page;
883
1108
  class Page {
884
1109
  constructor(query, meta, records = []) {
885
1110
  __privateAdd$6(this, _query, void 0);
886
- __privateSet$4(this, _query, query);
1111
+ __privateSet$6(this, _query, query);
887
1112
  this.meta = meta;
888
- this.records = records;
1113
+ this.records = new RecordArray(this, records);
889
1114
  }
890
1115
  async nextPage(size, offset) {
891
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1116
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
892
1117
  }
893
1118
  async previousPage(size, offset) {
894
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1119
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
895
1120
  }
896
1121
  async firstPage(size, offset) {
897
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1122
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
898
1123
  }
899
1124
  async lastPage(size, offset) {
900
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1125
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
901
1126
  }
902
1127
  hasNextPage() {
903
1128
  return this.meta.page.more;
@@ -905,15 +1130,62 @@ class Page {
905
1130
  }
906
1131
  _query = new WeakMap();
907
1132
  const PAGINATION_MAX_SIZE = 200;
908
- const PAGINATION_DEFAULT_SIZE = 200;
1133
+ const PAGINATION_DEFAULT_SIZE = 20;
909
1134
  const PAGINATION_MAX_OFFSET = 800;
910
1135
  const PAGINATION_DEFAULT_OFFSET = 0;
1136
+ function isCursorPaginationOptions(options) {
1137
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1138
+ }
1139
+ const _RecordArray = class extends Array {
1140
+ constructor(...args) {
1141
+ super(..._RecordArray.parseConstructorParams(...args));
1142
+ __privateAdd$6(this, _page, void 0);
1143
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1144
+ }
1145
+ static parseConstructorParams(...args) {
1146
+ if (args.length === 1 && typeof args[0] === "number") {
1147
+ return new Array(args[0]);
1148
+ }
1149
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1150
+ const result = args[1] ?? args[0].records ?? [];
1151
+ return new Array(...result);
1152
+ }
1153
+ return new Array(...args);
1154
+ }
1155
+ toArray() {
1156
+ return new Array(...this);
1157
+ }
1158
+ map(callbackfn, thisArg) {
1159
+ return this.toArray().map(callbackfn, thisArg);
1160
+ }
1161
+ async nextPage(size, offset) {
1162
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1163
+ return new _RecordArray(newPage);
1164
+ }
1165
+ async previousPage(size, offset) {
1166
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1167
+ return new _RecordArray(newPage);
1168
+ }
1169
+ async firstPage(size, offset) {
1170
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1171
+ return new _RecordArray(newPage);
1172
+ }
1173
+ async lastPage(size, offset) {
1174
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1175
+ return new _RecordArray(newPage);
1176
+ }
1177
+ hasNextPage() {
1178
+ return __privateGet$6(this, _page).meta.page.more;
1179
+ }
1180
+ };
1181
+ let RecordArray = _RecordArray;
1182
+ _page = new WeakMap();
911
1183
 
912
1184
  var __accessCheck$5 = (obj, member, msg) => {
913
1185
  if (!member.has(obj))
914
1186
  throw TypeError("Cannot " + msg);
915
1187
  };
916
- var __privateGet$4 = (obj, member, getter) => {
1188
+ var __privateGet$5 = (obj, member, getter) => {
917
1189
  __accessCheck$5(obj, member, "read from private field");
918
1190
  return getter ? getter.call(obj) : member.get(obj);
919
1191
  };
@@ -922,34 +1194,35 @@ var __privateAdd$5 = (obj, member, value) => {
922
1194
  throw TypeError("Cannot add the same private member more than once");
923
1195
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
924
1196
  };
925
- var __privateSet$3 = (obj, member, value, setter) => {
1197
+ var __privateSet$5 = (obj, member, value, setter) => {
926
1198
  __accessCheck$5(obj, member, "write to private field");
927
1199
  setter ? setter.call(obj, value) : member.set(obj, value);
928
1200
  return value;
929
1201
  };
930
1202
  var _table$1, _repository, _data;
931
1203
  const _Query = class {
932
- constructor(repository, table, data, parent) {
1204
+ constructor(repository, table, data, rawParent) {
933
1205
  __privateAdd$5(this, _table$1, void 0);
934
1206
  __privateAdd$5(this, _repository, void 0);
935
1207
  __privateAdd$5(this, _data, { filter: {} });
936
1208
  this.meta = { page: { cursor: "start", more: true } };
937
- this.records = [];
938
- __privateSet$3(this, _table$1, table);
1209
+ this.records = new RecordArray(this, []);
1210
+ __privateSet$5(this, _table$1, table);
939
1211
  if (repository) {
940
- __privateSet$3(this, _repository, repository);
1212
+ __privateSet$5(this, _repository, repository);
941
1213
  } else {
942
- __privateSet$3(this, _repository, this);
1214
+ __privateSet$5(this, _repository, this);
943
1215
  }
944
- __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
945
- __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
946
- __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
947
- __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
948
- __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
949
- __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
950
- __privateGet$4(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
951
- __privateGet$4(this, _data).page = data.page ?? parent?.page;
952
- __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
1216
+ const parent = cleanParent(data, rawParent);
1217
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1218
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1219
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1220
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1221
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1222
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1223
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1224
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1225
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
953
1226
  this.any = this.any.bind(this);
954
1227
  this.all = this.all.bind(this);
955
1228
  this.not = this.not.bind(this);
@@ -960,83 +1233,93 @@ const _Query = class {
960
1233
  Object.defineProperty(this, "repository", { enumerable: false });
961
1234
  }
962
1235
  getQueryOptions() {
963
- return __privateGet$4(this, _data);
1236
+ return __privateGet$5(this, _data);
964
1237
  }
965
1238
  key() {
966
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$4(this, _data);
967
- const key = JSON.stringify({ columns, filter, sort, page });
1239
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1240
+ const key = JSON.stringify({ columns, filter, sort, pagination });
968
1241
  return toBase64(key);
969
1242
  }
970
1243
  any(...queries) {
971
1244
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
972
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
1245
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
973
1246
  }
974
1247
  all(...queries) {
975
1248
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
976
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1249
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
977
1250
  }
978
1251
  not(...queries) {
979
1252
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
980
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
1253
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
981
1254
  }
982
1255
  none(...queries) {
983
1256
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
984
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
1257
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
985
1258
  }
986
1259
  filter(a, b) {
987
1260
  if (arguments.length === 1) {
988
1261
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
989
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
990
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1262
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1263
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
991
1264
  } else {
992
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
993
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1265
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1266
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
994
1267
  }
995
1268
  }
996
- sort(column, direction) {
997
- const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
1269
+ sort(column, direction = "asc") {
1270
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
998
1271
  const sort = [...originalSort, { column, direction }];
999
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
1272
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1000
1273
  }
1001
1274
  select(columns) {
1002
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { columns }, __privateGet$4(this, _data));
1275
+ return new _Query(
1276
+ __privateGet$5(this, _repository),
1277
+ __privateGet$5(this, _table$1),
1278
+ { columns },
1279
+ __privateGet$5(this, _data)
1280
+ );
1003
1281
  }
1004
1282
  getPaginated(options = {}) {
1005
- const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
1006
- return __privateGet$4(this, _repository).query(query);
1283
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1284
+ return __privateGet$5(this, _repository).query(query);
1007
1285
  }
1008
1286
  async *[Symbol.asyncIterator]() {
1009
- for await (const [record] of this.getIterator(1)) {
1287
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1010
1288
  yield record;
1011
1289
  }
1012
1290
  }
1013
- async *getIterator(chunk, options = {}) {
1014
- let offset = 0;
1015
- let end = false;
1016
- while (!end) {
1017
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1018
- yield records;
1019
- offset += chunk;
1020
- end = !meta.page.more;
1291
+ async *getIterator(options = {}) {
1292
+ const { batchSize = 1 } = options;
1293
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1294
+ let more = page.hasNextPage();
1295
+ yield page.records;
1296
+ while (more) {
1297
+ page = await page.nextPage();
1298
+ more = page.hasNextPage();
1299
+ yield page.records;
1021
1300
  }
1022
1301
  }
1023
1302
  async getMany(options = {}) {
1024
- const { records } = await this.getPaginated(options);
1025
- return records;
1303
+ const page = await this.getPaginated(options);
1304
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1305
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1306
+ }
1307
+ return page.records;
1026
1308
  }
1027
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1309
+ async getAll(options = {}) {
1310
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1028
1311
  const results = [];
1029
- for await (const page of this.getIterator(chunk, options)) {
1312
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1030
1313
  results.push(...page);
1031
1314
  }
1032
1315
  return results;
1033
1316
  }
1034
1317
  async getFirst(options = {}) {
1035
- const records = await this.getMany({ ...options, page: { size: 1 } });
1036
- return records[0] || null;
1318
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1319
+ return records[0] ?? null;
1037
1320
  }
1038
1321
  cache(ttl) {
1039
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
1322
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1040
1323
  }
1041
1324
  nextPage(size, offset) {
1042
1325
  return this.firstPage(size, offset);
@@ -1045,10 +1328,10 @@ const _Query = class {
1045
1328
  return this.firstPage(size, offset);
1046
1329
  }
1047
1330
  firstPage(size, offset) {
1048
- return this.getPaginated({ page: { size, offset } });
1331
+ return this.getPaginated({ pagination: { size, offset } });
1049
1332
  }
1050
1333
  lastPage(size, offset) {
1051
- return this.getPaginated({ page: { size, offset, before: "end" } });
1334
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1052
1335
  }
1053
1336
  hasNextPage() {
1054
1337
  return this.meta.page.more;
@@ -1058,12 +1341,20 @@ let Query = _Query;
1058
1341
  _table$1 = new WeakMap();
1059
1342
  _repository = new WeakMap();
1060
1343
  _data = new WeakMap();
1344
+ function cleanParent(data, parent) {
1345
+ if (isCursorPaginationOptions(data.pagination)) {
1346
+ return { ...parent, sorting: void 0, filter: void 0 };
1347
+ }
1348
+ return parent;
1349
+ }
1061
1350
 
1062
1351
  function isIdentifiable(x) {
1063
1352
  return isObject(x) && isString(x?.id);
1064
1353
  }
1065
1354
  function isXataRecord(x) {
1066
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1355
+ const record = x;
1356
+ const metadata = record?.getMetadata();
1357
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1067
1358
  }
1068
1359
 
1069
1360
  function isSortFilterString(value) {
@@ -1093,7 +1384,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1093
1384
  if (!member.has(obj))
1094
1385
  throw TypeError("Cannot " + msg);
1095
1386
  };
1096
- var __privateGet$3 = (obj, member, getter) => {
1387
+ var __privateGet$4 = (obj, member, getter) => {
1097
1388
  __accessCheck$4(obj, member, "read from private field");
1098
1389
  return getter ? getter.call(obj) : member.get(obj);
1099
1390
  };
@@ -1102,7 +1393,7 @@ var __privateAdd$4 = (obj, member, value) => {
1102
1393
  throw TypeError("Cannot add the same private member more than once");
1103
1394
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1104
1395
  };
1105
- var __privateSet$2 = (obj, member, value, setter) => {
1396
+ var __privateSet$4 = (obj, member, value, setter) => {
1106
1397
  __accessCheck$4(obj, member, "write to private field");
1107
1398
  setter ? setter.call(obj, value) : member.set(obj, value);
1108
1399
  return value;
@@ -1111,7 +1402,7 @@ var __privateMethod$2 = (obj, member, method) => {
1111
1402
  __accessCheck$4(obj, member, "access private method");
1112
1403
  return method;
1113
1404
  };
1114
- 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;
1405
+ 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;
1115
1406
  class Repository extends Query {
1116
1407
  }
1117
1408
  class RestRepository extends Query {
@@ -1123,292 +1414,338 @@ class RestRepository extends Query {
1123
1414
  __privateAdd$4(this, _updateRecordWithID);
1124
1415
  __privateAdd$4(this, _upsertRecordWithID);
1125
1416
  __privateAdd$4(this, _deleteRecord);
1126
- __privateAdd$4(this, _invalidateCache);
1127
- __privateAdd$4(this, _setCacheRecord);
1128
- __privateAdd$4(this, _getCacheRecord);
1129
1417
  __privateAdd$4(this, _setCacheQuery);
1130
1418
  __privateAdd$4(this, _getCacheQuery);
1419
+ __privateAdd$4(this, _getSchemaTables$1);
1131
1420
  __privateAdd$4(this, _table, void 0);
1132
- __privateAdd$4(this, _links, void 0);
1133
1421
  __privateAdd$4(this, _getFetchProps, void 0);
1422
+ __privateAdd$4(this, _db, void 0);
1134
1423
  __privateAdd$4(this, _cache, void 0);
1135
- __privateSet$2(this, _table, options.table);
1136
- __privateSet$2(this, _links, options.links ?? {});
1137
- __privateSet$2(this, _getFetchProps, options.pluginOptions.getFetchProps);
1138
- this.db = options.db;
1139
- __privateSet$2(this, _cache, options.pluginOptions.cache);
1140
- }
1141
- async create(a, b) {
1142
- if (Array.isArray(a)) {
1143
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1144
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1145
- return records;
1146
- }
1147
- if (isString(a) && isObject(b)) {
1148
- if (a === "")
1149
- throw new Error("The id can't be empty");
1150
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1151
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1152
- return record;
1153
- }
1154
- if (isObject(a) && isString(a.id)) {
1155
- if (a.id === "")
1156
- throw new Error("The id can't be empty");
1157
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1158
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1159
- return record;
1160
- }
1161
- if (isObject(a)) {
1162
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1163
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1164
- return record;
1165
- }
1166
- throw new Error("Invalid arguments for create method");
1167
- }
1168
- async read(recordId) {
1169
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1170
- if (cacheRecord)
1171
- return cacheRecord;
1172
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1173
- try {
1174
- const response = await getRecord({
1175
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1176
- ...fetchProps
1424
+ __privateAdd$4(this, _schemaTables$2, void 0);
1425
+ __privateAdd$4(this, _trace, void 0);
1426
+ __privateSet$4(this, _table, options.table);
1427
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1428
+ __privateSet$4(this, _db, options.db);
1429
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1430
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1431
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1432
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1433
+ return trace(name, fn, {
1434
+ ...options2,
1435
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1436
+ [TraceAttributes.VERSION]: VERSION
1177
1437
  });
1178
- return initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), response);
1179
- } catch (e) {
1180
- if (isObject(e) && e.status === 404) {
1181
- return null;
1438
+ });
1439
+ }
1440
+ async create(a, b, c) {
1441
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1442
+ if (Array.isArray(a)) {
1443
+ if (a.length === 0)
1444
+ return [];
1445
+ const columns = isStringArray(b) ? b : void 0;
1446
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1182
1447
  }
1183
- throw e;
1184
- }
1448
+ if (isString(a) && isObject(b)) {
1449
+ if (a === "")
1450
+ throw new Error("The id can't be empty");
1451
+ const columns = isStringArray(c) ? c : void 0;
1452
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1453
+ }
1454
+ if (isObject(a) && isString(a.id)) {
1455
+ if (a.id === "")
1456
+ throw new Error("The id can't be empty");
1457
+ const columns = isStringArray(b) ? b : void 0;
1458
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1459
+ }
1460
+ if (isObject(a)) {
1461
+ const columns = isStringArray(b) ? b : void 0;
1462
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1463
+ }
1464
+ throw new Error("Invalid arguments for create method");
1465
+ });
1185
1466
  }
1186
- async update(a, b) {
1187
- if (Array.isArray(a)) {
1188
- if (a.length > 100) {
1189
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1467
+ async read(a, b) {
1468
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1469
+ const columns = isStringArray(b) ? b : ["*"];
1470
+ if (Array.isArray(a)) {
1471
+ if (a.length === 0)
1472
+ return [];
1473
+ const ids = a.map((item) => extractId(item));
1474
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1475
+ const dictionary = finalObjects.reduce((acc, object) => {
1476
+ acc[object.id] = object;
1477
+ return acc;
1478
+ }, {});
1479
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1190
1480
  }
1191
- return Promise.all(a.map((object) => this.update(object)));
1192
- }
1193
- if (isString(a) && isObject(b)) {
1194
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1195
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1196
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1197
- return record;
1198
- }
1199
- if (isObject(a) && isString(a.id)) {
1200
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1201
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1202
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1203
- return record;
1204
- }
1205
- throw new Error("Invalid arguments for update method");
1481
+ const id = extractId(a);
1482
+ if (id) {
1483
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1484
+ try {
1485
+ const response = await getRecord({
1486
+ pathParams: {
1487
+ workspace: "{workspaceId}",
1488
+ dbBranchName: "{dbBranch}",
1489
+ tableName: __privateGet$4(this, _table),
1490
+ recordId: id
1491
+ },
1492
+ queryParams: { columns },
1493
+ ...fetchProps
1494
+ });
1495
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1496
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1497
+ } catch (e) {
1498
+ if (isObject(e) && e.status === 404) {
1499
+ return null;
1500
+ }
1501
+ throw e;
1502
+ }
1503
+ }
1504
+ return null;
1505
+ });
1206
1506
  }
1207
- async createOrUpdate(a, b) {
1208
- if (Array.isArray(a)) {
1209
- if (a.length > 100) {
1210
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1507
+ async update(a, b, c) {
1508
+ return __privateGet$4(this, _trace).call(this, "update", 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.update(object, columns)));
1211
1517
  }
1212
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1213
- }
1214
- if (isString(a) && isObject(b)) {
1215
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1216
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1217
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1218
- return record;
1219
- }
1220
- if (isObject(a) && isString(a.id)) {
1221
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1222
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1223
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1224
- return record;
1225
- }
1226
- throw new Error("Invalid arguments for createOrUpdate method");
1518
+ if (isString(a) && isObject(b)) {
1519
+ const columns = isStringArray(c) ? c : void 0;
1520
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1521
+ }
1522
+ if (isObject(a) && isString(a.id)) {
1523
+ const columns = isStringArray(b) ? b : void 0;
1524
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1525
+ }
1526
+ throw new Error("Invalid arguments for update method");
1527
+ });
1227
1528
  }
1228
- async delete(a) {
1229
- if (Array.isArray(a)) {
1230
- if (a.length > 100) {
1231
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1529
+ async createOrUpdate(a, b, c) {
1530
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1531
+ if (Array.isArray(a)) {
1532
+ if (a.length === 0)
1533
+ return [];
1534
+ if (a.length > 100) {
1535
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1536
+ }
1537
+ const columns = isStringArray(b) ? b : ["*"];
1538
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1232
1539
  }
1233
- await Promise.all(a.map((id) => this.delete(id)));
1234
- return;
1235
- }
1236
- if (isString(a)) {
1237
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1238
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1239
- return;
1240
- }
1241
- if (isObject(a) && isString(a.id)) {
1242
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1243
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1244
- return;
1245
- }
1246
- throw new Error("Invalid arguments for delete method");
1540
+ if (isString(a) && isObject(b)) {
1541
+ const columns = isStringArray(c) ? c : void 0;
1542
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1543
+ }
1544
+ if (isObject(a) && isString(a.id)) {
1545
+ const columns = isStringArray(c) ? c : void 0;
1546
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1547
+ }
1548
+ throw new Error("Invalid arguments for createOrUpdate method");
1549
+ });
1550
+ }
1551
+ async delete(a, b) {
1552
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1553
+ if (Array.isArray(a)) {
1554
+ if (a.length === 0)
1555
+ return [];
1556
+ if (a.length > 100) {
1557
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1558
+ }
1559
+ return Promise.all(a.map((id) => this.delete(id, b)));
1560
+ }
1561
+ if (isString(a)) {
1562
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1563
+ }
1564
+ if (isObject(a) && isString(a.id)) {
1565
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1566
+ }
1567
+ throw new Error("Invalid arguments for delete method");
1568
+ });
1247
1569
  }
1248
1570
  async search(query, options = {}) {
1249
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1250
- const { records } = await searchBranch({
1251
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1252
- body: { tables: [__privateGet$3(this, _table)], query, fuzziness: options.fuzziness },
1253
- ...fetchProps
1571
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1572
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1573
+ const { records } = await searchTable({
1574
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1575
+ body: {
1576
+ query,
1577
+ fuzziness: options.fuzziness,
1578
+ prefix: options.prefix,
1579
+ highlight: options.highlight,
1580
+ filter: options.filter,
1581
+ boosters: options.boosters
1582
+ },
1583
+ ...fetchProps
1584
+ });
1585
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1586
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1254
1587
  });
1255
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), item));
1256
1588
  }
1257
1589
  async query(query) {
1258
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1259
- if (cacheQuery)
1260
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1261
- const data = query.getQueryOptions();
1262
- const body = {
1263
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1264
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1265
- page: data.page,
1266
- columns: data.columns
1267
- };
1268
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1269
- const { meta, records: objects } = await queryTable({
1270
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1271
- body,
1272
- ...fetchProps
1590
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1591
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1592
+ if (cacheQuery)
1593
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1594
+ const data = query.getQueryOptions();
1595
+ const body = {
1596
+ filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1597
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1598
+ page: data.pagination,
1599
+ columns: data.columns
1600
+ };
1601
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1602
+ const { meta, records: objects } = await queryTable({
1603
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1604
+ body,
1605
+ ...fetchProps
1606
+ });
1607
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1608
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1609
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1610
+ return new Page(query, meta, records);
1273
1611
  });
1274
- const records = objects.map((record) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), record));
1275
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1276
- return new Page(query, meta, records);
1277
1612
  }
1278
1613
  }
1279
1614
  _table = new WeakMap();
1280
- _links = new WeakMap();
1281
1615
  _getFetchProps = new WeakMap();
1616
+ _db = new WeakMap();
1282
1617
  _cache = new WeakMap();
1618
+ _schemaTables$2 = new WeakMap();
1619
+ _trace = new WeakMap();
1283
1620
  _insertRecordWithoutId = new WeakSet();
1284
- insertRecordWithoutId_fn = async function(object) {
1285
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1621
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1622
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1286
1623
  const record = transformObjectLinks(object);
1287
1624
  const response = await insertRecord({
1288
1625
  pathParams: {
1289
1626
  workspace: "{workspaceId}",
1290
1627
  dbBranchName: "{dbBranch}",
1291
- tableName: __privateGet$3(this, _table)
1628
+ tableName: __privateGet$4(this, _table)
1292
1629
  },
1630
+ queryParams: { columns },
1293
1631
  body: record,
1294
1632
  ...fetchProps
1295
1633
  });
1296
- const finalObject = await this.read(response.id);
1297
- if (!finalObject) {
1298
- throw new Error("The server failed to save the record");
1299
- }
1300
- return finalObject;
1634
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1635
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1301
1636
  };
1302
1637
  _insertRecordWithId = new WeakSet();
1303
- insertRecordWithId_fn = async function(recordId, object) {
1304
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1638
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1639
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1305
1640
  const record = transformObjectLinks(object);
1306
1641
  const response = await insertRecordWithID({
1307
1642
  pathParams: {
1308
1643
  workspace: "{workspaceId}",
1309
1644
  dbBranchName: "{dbBranch}",
1310
- tableName: __privateGet$3(this, _table),
1645
+ tableName: __privateGet$4(this, _table),
1311
1646
  recordId
1312
1647
  },
1313
1648
  body: record,
1314
- queryParams: { createOnly: true },
1649
+ queryParams: { createOnly: true, columns },
1315
1650
  ...fetchProps
1316
1651
  });
1317
- const finalObject = await this.read(response.id);
1318
- if (!finalObject) {
1319
- throw new Error("The server failed to save the record");
1320
- }
1321
- return finalObject;
1652
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1653
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1322
1654
  };
1323
1655
  _bulkInsertTableRecords = new WeakSet();
1324
- bulkInsertTableRecords_fn = async function(objects) {
1325
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1656
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1657
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1326
1658
  const records = objects.map((object) => transformObjectLinks(object));
1327
1659
  const response = await bulkInsertTableRecords({
1328
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1660
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1661
+ queryParams: { columns },
1329
1662
  body: { records },
1330
1663
  ...fetchProps
1331
1664
  });
1332
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1333
- if (finalObjects.length !== objects.length) {
1334
- throw new Error("The server failed to save some records");
1665
+ if (!isResponseWithRecords(response)) {
1666
+ throw new Error("Request included columns but server didn't include them");
1335
1667
  }
1336
- return finalObjects;
1668
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1669
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1337
1670
  };
1338
1671
  _updateRecordWithID = new WeakSet();
1339
- updateRecordWithID_fn = async function(recordId, object) {
1340
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1672
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1673
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1341
1674
  const record = transformObjectLinks(object);
1342
- const response = await updateRecordWithID({
1343
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1344
- body: record,
1345
- ...fetchProps
1346
- });
1347
- const item = await this.read(response.id);
1348
- if (!item)
1349
- throw new Error("The server failed to save the record");
1350
- return item;
1675
+ try {
1676
+ const response = await updateRecordWithID({
1677
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1678
+ queryParams: { columns },
1679
+ body: record,
1680
+ ...fetchProps
1681
+ });
1682
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1683
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1684
+ } catch (e) {
1685
+ if (isObject(e) && e.status === 404) {
1686
+ return null;
1687
+ }
1688
+ throw e;
1689
+ }
1351
1690
  };
1352
1691
  _upsertRecordWithID = new WeakSet();
1353
- upsertRecordWithID_fn = async function(recordId, object) {
1354
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1692
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1693
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1355
1694
  const response = await upsertRecordWithID({
1356
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1695
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1696
+ queryParams: { columns },
1357
1697
  body: object,
1358
1698
  ...fetchProps
1359
1699
  });
1360
- const item = await this.read(response.id);
1361
- if (!item)
1362
- throw new Error("The server failed to save the record");
1363
- return item;
1700
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1701
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1364
1702
  };
1365
1703
  _deleteRecord = new WeakSet();
1366
- deleteRecord_fn = async function(recordId) {
1367
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1368
- await deleteRecord({
1369
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1370
- ...fetchProps
1371
- });
1372
- };
1373
- _invalidateCache = new WeakSet();
1374
- invalidateCache_fn = async function(recordId) {
1375
- await __privateGet$3(this, _cache).delete(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1376
- const cacheItems = await __privateGet$3(this, _cache).getAll();
1377
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1378
- for (const [key, value] of queries) {
1379
- const ids = getIds(value);
1380
- if (ids.includes(recordId))
1381
- await __privateGet$3(this, _cache).delete(key);
1704
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1705
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1706
+ try {
1707
+ const response = await deleteRecord({
1708
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1709
+ queryParams: { columns },
1710
+ ...fetchProps
1711
+ });
1712
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1713
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1714
+ } catch (e) {
1715
+ if (isObject(e) && e.status === 404) {
1716
+ return null;
1717
+ }
1718
+ throw e;
1382
1719
  }
1383
1720
  };
1384
- _setCacheRecord = new WeakSet();
1385
- setCacheRecord_fn = async function(record) {
1386
- if (!__privateGet$3(this, _cache).cacheRecords)
1387
- return;
1388
- await __privateGet$3(this, _cache).set(`rec_${__privateGet$3(this, _table)}:${record.id}`, record);
1389
- };
1390
- _getCacheRecord = new WeakSet();
1391
- getCacheRecord_fn = async function(recordId) {
1392
- if (!__privateGet$3(this, _cache).cacheRecords)
1393
- return null;
1394
- return __privateGet$3(this, _cache).get(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1395
- };
1396
1721
  _setCacheQuery = new WeakSet();
1397
1722
  setCacheQuery_fn = async function(query, meta, records) {
1398
- await __privateGet$3(this, _cache).set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1723
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1399
1724
  };
1400
1725
  _getCacheQuery = new WeakSet();
1401
1726
  getCacheQuery_fn = async function(query) {
1402
- const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
1403
- const result = await __privateGet$3(this, _cache).get(key);
1727
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1728
+ const result = await __privateGet$4(this, _cache).get(key);
1404
1729
  if (!result)
1405
1730
  return null;
1406
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1407
- if (!ttl || ttl < 0)
1408
- return result;
1731
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1732
+ if (ttl < 0)
1733
+ return null;
1409
1734
  const hasExpired = result.date.getTime() + ttl < Date.now();
1410
1735
  return hasExpired ? null : result;
1411
1736
  };
1737
+ _getSchemaTables$1 = new WeakSet();
1738
+ getSchemaTables_fn$1 = async function() {
1739
+ if (__privateGet$4(this, _schemaTables$2))
1740
+ return __privateGet$4(this, _schemaTables$2);
1741
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1742
+ const { schema } = await getBranchDetails({
1743
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1744
+ ...fetchProps
1745
+ });
1746
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1747
+ return schema.tables;
1748
+ };
1412
1749
  const transformObjectLinks = (object) => {
1413
1750
  return Object.entries(object).reduce((acc, [key, value]) => {
1414
1751
  if (key === "xata")
@@ -1416,47 +1753,70 @@ const transformObjectLinks = (object) => {
1416
1753
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1417
1754
  }, {});
1418
1755
  };
1419
- const initObject = (db, links, table, object) => {
1756
+ const initObject = (db, schemaTables, table, object) => {
1420
1757
  const result = {};
1421
- Object.assign(result, object);
1422
- const tableLinks = links[table] || [];
1423
- for (const link of tableLinks) {
1424
- const [field, linkTable] = link;
1425
- const value = result[field];
1426
- if (value && isObject(value)) {
1427
- result[field] = initObject(db, links, linkTable, value);
1758
+ const { xata, ...rest } = object ?? {};
1759
+ Object.assign(result, rest);
1760
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1761
+ if (!columns)
1762
+ console.error(`Table ${table} not found in schema`);
1763
+ for (const column of columns ?? []) {
1764
+ const value = result[column.name];
1765
+ switch (column.type) {
1766
+ case "datetime": {
1767
+ const date = value !== void 0 ? new Date(value) : void 0;
1768
+ if (date && isNaN(date.getTime())) {
1769
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1770
+ } else if (date) {
1771
+ result[column.name] = date;
1772
+ }
1773
+ break;
1774
+ }
1775
+ case "link": {
1776
+ const linkTable = column.link?.table;
1777
+ if (!linkTable) {
1778
+ console.error(`Failed to parse link for field ${column.name}`);
1779
+ } else if (isObject(value)) {
1780
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1781
+ }
1782
+ break;
1783
+ }
1428
1784
  }
1429
1785
  }
1430
- result.read = function() {
1431
- return db[table].read(result["id"]);
1786
+ result.read = function(columns2) {
1787
+ return db[table].read(result["id"], columns2);
1432
1788
  };
1433
- result.update = function(data) {
1434
- return db[table].update(result["id"], data);
1789
+ result.update = function(data, columns2) {
1790
+ return db[table].update(result["id"], data, columns2);
1435
1791
  };
1436
1792
  result.delete = function() {
1437
1793
  return db[table].delete(result["id"]);
1438
1794
  };
1439
- for (const prop of ["read", "update", "delete"]) {
1795
+ result.getMetadata = function() {
1796
+ return xata;
1797
+ };
1798
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1440
1799
  Object.defineProperty(result, prop, { enumerable: false });
1441
1800
  }
1442
1801
  Object.freeze(result);
1443
1802
  return result;
1444
1803
  };
1445
- function getIds(value) {
1446
- if (Array.isArray(value)) {
1447
- return value.map((item) => getIds(item)).flat();
1448
- }
1449
- if (!isObject(value))
1450
- return [];
1451
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1452
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1804
+ function isResponseWithRecords(value) {
1805
+ return isObject(value) && Array.isArray(value.records);
1806
+ }
1807
+ function extractId(value) {
1808
+ if (isString(value))
1809
+ return value;
1810
+ if (isObject(value) && isString(value.id))
1811
+ return value.id;
1812
+ return void 0;
1453
1813
  }
1454
1814
 
1455
1815
  var __accessCheck$3 = (obj, member, msg) => {
1456
1816
  if (!member.has(obj))
1457
1817
  throw TypeError("Cannot " + msg);
1458
1818
  };
1459
- var __privateGet$2 = (obj, member, getter) => {
1819
+ var __privateGet$3 = (obj, member, getter) => {
1460
1820
  __accessCheck$3(obj, member, "read from private field");
1461
1821
  return getter ? getter.call(obj) : member.get(obj);
1462
1822
  };
@@ -1465,7 +1825,7 @@ var __privateAdd$3 = (obj, member, value) => {
1465
1825
  throw TypeError("Cannot add the same private member more than once");
1466
1826
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1467
1827
  };
1468
- var __privateSet$1 = (obj, member, value, setter) => {
1828
+ var __privateSet$3 = (obj, member, value, setter) => {
1469
1829
  __accessCheck$3(obj, member, "write to private field");
1470
1830
  setter ? setter.call(obj, value) : member.set(obj, value);
1471
1831
  return value;
@@ -1474,46 +1834,52 @@ var _map;
1474
1834
  class SimpleCache {
1475
1835
  constructor(options = {}) {
1476
1836
  __privateAdd$3(this, _map, void 0);
1477
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
1837
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1478
1838
  this.capacity = options.max ?? 500;
1479
- this.cacheRecords = options.cacheRecords ?? true;
1480
1839
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1481
1840
  }
1482
1841
  async getAll() {
1483
- return Object.fromEntries(__privateGet$2(this, _map));
1842
+ return Object.fromEntries(__privateGet$3(this, _map));
1484
1843
  }
1485
1844
  async get(key) {
1486
- return __privateGet$2(this, _map).get(key) ?? null;
1845
+ return __privateGet$3(this, _map).get(key) ?? null;
1487
1846
  }
1488
1847
  async set(key, value) {
1489
1848
  await this.delete(key);
1490
- __privateGet$2(this, _map).set(key, value);
1491
- if (__privateGet$2(this, _map).size > this.capacity) {
1492
- const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
1849
+ __privateGet$3(this, _map).set(key, value);
1850
+ if (__privateGet$3(this, _map).size > this.capacity) {
1851
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1493
1852
  await this.delete(leastRecentlyUsed);
1494
1853
  }
1495
1854
  }
1496
1855
  async delete(key) {
1497
- __privateGet$2(this, _map).delete(key);
1856
+ __privateGet$3(this, _map).delete(key);
1498
1857
  }
1499
1858
  async clear() {
1500
- return __privateGet$2(this, _map).clear();
1859
+ return __privateGet$3(this, _map).clear();
1501
1860
  }
1502
1861
  }
1503
1862
  _map = new WeakMap();
1504
1863
 
1505
- const gt = (value) => ({ $gt: value });
1506
- const ge = (value) => ({ $ge: value });
1507
- const gte = (value) => ({ $ge: value });
1508
- const lt = (value) => ({ $lt: value });
1509
- const lte = (value) => ({ $le: value });
1510
- const le = (value) => ({ $le: value });
1864
+ const greaterThan = (value) => ({ $gt: value });
1865
+ const gt = greaterThan;
1866
+ const greaterThanEquals = (value) => ({ $ge: value });
1867
+ const greaterEquals = greaterThanEquals;
1868
+ const gte = greaterThanEquals;
1869
+ const ge = greaterThanEquals;
1870
+ const lessThan = (value) => ({ $lt: value });
1871
+ const lt = lessThan;
1872
+ const lessThanEquals = (value) => ({ $le: value });
1873
+ const lessEquals = lessThanEquals;
1874
+ const lte = lessThanEquals;
1875
+ const le = lessThanEquals;
1511
1876
  const exists = (column) => ({ $exists: column });
1512
1877
  const notExists = (column) => ({ $notExists: column });
1513
1878
  const startsWith = (value) => ({ $startsWith: value });
1514
1879
  const endsWith = (value) => ({ $endsWith: value });
1515
1880
  const pattern = (value) => ({ $pattern: value });
1516
1881
  const is = (value) => ({ $is: value });
1882
+ const equals = is;
1517
1883
  const isNot = (value) => ({ $isNot: value });
1518
1884
  const contains = (value) => ({ $contains: value });
1519
1885
  const includes = (value) => ({ $includes: value });
@@ -1525,7 +1891,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1525
1891
  if (!member.has(obj))
1526
1892
  throw TypeError("Cannot " + msg);
1527
1893
  };
1528
- var __privateGet$1 = (obj, member, getter) => {
1894
+ var __privateGet$2 = (obj, member, getter) => {
1529
1895
  __accessCheck$2(obj, member, "read from private field");
1530
1896
  return getter ? getter.call(obj) : member.get(obj);
1531
1897
  };
@@ -1534,130 +1900,178 @@ var __privateAdd$2 = (obj, member, value) => {
1534
1900
  throw TypeError("Cannot add the same private member more than once");
1535
1901
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1536
1902
  };
1537
- var _tables;
1903
+ var __privateSet$2 = (obj, member, value, setter) => {
1904
+ __accessCheck$2(obj, member, "write to private field");
1905
+ setter ? setter.call(obj, value) : member.set(obj, value);
1906
+ return value;
1907
+ };
1908
+ var _tables, _schemaTables$1;
1538
1909
  class SchemaPlugin extends XataPlugin {
1539
- constructor(links, tableNames) {
1910
+ constructor(schemaTables) {
1540
1911
  super();
1541
- this.links = links;
1542
- this.tableNames = tableNames;
1543
1912
  __privateAdd$2(this, _tables, {});
1913
+ __privateAdd$2(this, _schemaTables$1, void 0);
1914
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1544
1915
  }
1545
1916
  build(pluginOptions) {
1546
- const links = this.links;
1547
- const db = new Proxy({}, {
1548
- get: (_target, table) => {
1549
- if (!isString(table))
1550
- throw new Error("Invalid table name");
1551
- if (!__privateGet$1(this, _tables)[table]) {
1552
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, links });
1917
+ const db = new Proxy(
1918
+ {},
1919
+ {
1920
+ get: (_target, table) => {
1921
+ if (!isString(table))
1922
+ throw new Error("Invalid table name");
1923
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1924
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1925
+ }
1926
+ return __privateGet$2(this, _tables)[table];
1553
1927
  }
1554
- return __privateGet$1(this, _tables)[table];
1555
1928
  }
1556
- });
1557
- for (const table of this.tableNames ?? []) {
1558
- db[table] = new RestRepository({ db, pluginOptions, table, links });
1929
+ );
1930
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1931
+ for (const table of tableNames) {
1932
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1559
1933
  }
1560
1934
  return db;
1561
1935
  }
1562
1936
  }
1563
1937
  _tables = new WeakMap();
1938
+ _schemaTables$1 = new WeakMap();
1564
1939
 
1565
1940
  var __accessCheck$1 = (obj, member, msg) => {
1566
1941
  if (!member.has(obj))
1567
1942
  throw TypeError("Cannot " + msg);
1568
1943
  };
1944
+ var __privateGet$1 = (obj, member, getter) => {
1945
+ __accessCheck$1(obj, member, "read from private field");
1946
+ return getter ? getter.call(obj) : member.get(obj);
1947
+ };
1569
1948
  var __privateAdd$1 = (obj, member, value) => {
1570
1949
  if (member.has(obj))
1571
1950
  throw TypeError("Cannot add the same private member more than once");
1572
1951
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1573
1952
  };
1953
+ var __privateSet$1 = (obj, member, value, setter) => {
1954
+ __accessCheck$1(obj, member, "write to private field");
1955
+ setter ? setter.call(obj, value) : member.set(obj, value);
1956
+ return value;
1957
+ };
1574
1958
  var __privateMethod$1 = (obj, member, method) => {
1575
1959
  __accessCheck$1(obj, member, "access private method");
1576
1960
  return method;
1577
1961
  };
1578
- var _search, search_fn;
1962
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1579
1963
  class SearchPlugin extends XataPlugin {
1580
- constructor(db, links) {
1964
+ constructor(db, schemaTables) {
1581
1965
  super();
1582
1966
  this.db = db;
1583
- this.links = links;
1584
1967
  __privateAdd$1(this, _search);
1968
+ __privateAdd$1(this, _getSchemaTables);
1969
+ __privateAdd$1(this, _schemaTables, void 0);
1970
+ __privateSet$1(this, _schemaTables, schemaTables);
1585
1971
  }
1586
1972
  build({ getFetchProps }) {
1587
1973
  return {
1588
1974
  all: async (query, options = {}) => {
1589
1975
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1976
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1590
1977
  return records.map((record) => {
1591
1978
  const { table = "orphan" } = record.xata;
1592
- return { table, record: initObject(this.db, this.links, table, record) };
1979
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1593
1980
  });
1594
1981
  },
1595
1982
  byTable: async (query, options = {}) => {
1596
1983
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1984
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1597
1985
  return records.reduce((acc, record) => {
1598
1986
  const { table = "orphan" } = record.xata;
1599
1987
  const items = acc[table] ?? [];
1600
- const item = initObject(this.db, this.links, table, record);
1988
+ const item = initObject(this.db, schemaTables, table, record);
1601
1989
  return { ...acc, [table]: [...items, item] };
1602
1990
  }, {});
1603
1991
  }
1604
1992
  };
1605
1993
  }
1606
1994
  }
1995
+ _schemaTables = new WeakMap();
1607
1996
  _search = new WeakSet();
1608
1997
  search_fn = async function(query, options, getFetchProps) {
1609
1998
  const fetchProps = await getFetchProps();
1610
- const { tables, fuzziness } = options ?? {};
1999
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1611
2000
  const { records } = await searchBranch({
1612
2001
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1613
- body: { tables, query, fuzziness },
2002
+ body: { tables, query, fuzziness, prefix, highlight },
1614
2003
  ...fetchProps
1615
2004
  });
1616
2005
  return records;
1617
2006
  };
2007
+ _getSchemaTables = new WeakSet();
2008
+ getSchemaTables_fn = async function(getFetchProps) {
2009
+ if (__privateGet$1(this, _schemaTables))
2010
+ return __privateGet$1(this, _schemaTables);
2011
+ const fetchProps = await getFetchProps();
2012
+ const { schema } = await getBranchDetails({
2013
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2014
+ ...fetchProps
2015
+ });
2016
+ __privateSet$1(this, _schemaTables, schema.tables);
2017
+ return schema.tables;
2018
+ };
1618
2019
 
1619
2020
  const isBranchStrategyBuilder = (strategy) => {
1620
2021
  return typeof strategy === "function";
1621
2022
  };
1622
2023
 
1623
- const envBranchNames = [
1624
- "XATA_BRANCH",
1625
- "VERCEL_GIT_COMMIT_REF",
1626
- "CF_PAGES_BRANCH",
1627
- "BRANCH"
1628
- ];
1629
- const defaultBranch = "main";
1630
2024
  async function getCurrentBranchName(options) {
1631
- const env = await getBranchByEnvVariable();
1632
- if (env)
1633
- return env;
1634
- const branch = await getGitBranch();
1635
- if (!branch)
1636
- return defaultBranch;
1637
- const details = await getDatabaseBranch(branch, options);
1638
- if (details)
1639
- return branch;
1640
- return defaultBranch;
2025
+ const { branch, envBranch } = getEnvironment();
2026
+ if (branch) {
2027
+ const details = await getDatabaseBranch(branch, options);
2028
+ if (details)
2029
+ return branch;
2030
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2031
+ }
2032
+ const gitBranch = envBranch || await getGitBranch();
2033
+ return resolveXataBranch(gitBranch, options);
1641
2034
  }
1642
2035
  async function getCurrentBranchDetails(options) {
1643
- const env = await getBranchByEnvVariable();
1644
- if (env)
1645
- return getDatabaseBranch(env, options);
1646
- const branch = await getGitBranch();
1647
- if (!branch)
1648
- return getDatabaseBranch(defaultBranch, options);
1649
- const details = await getDatabaseBranch(branch, options);
1650
- if (details)
1651
- return details;
1652
- return getDatabaseBranch(defaultBranch, options);
2036
+ const branch = await getCurrentBranchName(options);
2037
+ return getDatabaseBranch(branch, options);
2038
+ }
2039
+ async function resolveXataBranch(gitBranch, options) {
2040
+ const databaseURL = options?.databaseURL || getDatabaseURL();
2041
+ const apiKey = options?.apiKey || getAPIKey();
2042
+ if (!databaseURL)
2043
+ throw new Error(
2044
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2045
+ );
2046
+ if (!apiKey)
2047
+ throw new Error(
2048
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2049
+ );
2050
+ const [protocol, , host, , dbName] = databaseURL.split("/");
2051
+ const [workspace] = host.split(".");
2052
+ const { fallbackBranch } = getEnvironment();
2053
+ const { branch } = await resolveBranch({
2054
+ apiKey,
2055
+ apiUrl: databaseURL,
2056
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
2057
+ workspacesApiUrl: `${protocol}//${host}`,
2058
+ pathParams: { dbName, workspace },
2059
+ queryParams: { gitBranch, fallbackBranch },
2060
+ trace: defaultTrace
2061
+ });
2062
+ return branch;
1653
2063
  }
1654
2064
  async function getDatabaseBranch(branch, options) {
1655
2065
  const databaseURL = options?.databaseURL || getDatabaseURL();
1656
2066
  const apiKey = options?.apiKey || getAPIKey();
1657
2067
  if (!databaseURL)
1658
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2068
+ throw new Error(
2069
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2070
+ );
1659
2071
  if (!apiKey)
1660
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2072
+ throw new Error(
2073
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2074
+ );
1661
2075
  const [protocol, , host, , database] = databaseURL.split("/");
1662
2076
  const [workspace] = host.split(".");
1663
2077
  const dbBranchName = `${database}:${branch}`;
@@ -1667,10 +2081,8 @@ async function getDatabaseBranch(branch, options) {
1667
2081
  apiUrl: databaseURL,
1668
2082
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1669
2083
  workspacesApiUrl: `${protocol}//${host}`,
1670
- pathParams: {
1671
- dbBranchName,
1672
- workspace
1673
- }
2084
+ pathParams: { dbBranchName, workspace },
2085
+ trace: defaultTrace
1674
2086
  });
1675
2087
  } catch (err) {
1676
2088
  if (isObject(err) && err.status === 404)
@@ -1678,21 +2090,10 @@ async function getDatabaseBranch(branch, options) {
1678
2090
  throw err;
1679
2091
  }
1680
2092
  }
1681
- function getBranchByEnvVariable() {
1682
- for (const name of envBranchNames) {
1683
- const value = getEnvVariable(name);
1684
- if (value) {
1685
- return value;
1686
- }
1687
- }
1688
- try {
1689
- return XATA_BRANCH;
1690
- } catch (err) {
1691
- }
1692
- }
1693
2093
  function getDatabaseURL() {
1694
2094
  try {
1695
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2095
+ const { databaseURL } = getEnvironment();
2096
+ return databaseURL;
1696
2097
  } catch (err) {
1697
2098
  return void 0;
1698
2099
  }
@@ -1721,24 +2122,27 @@ var __privateMethod = (obj, member, method) => {
1721
2122
  return method;
1722
2123
  };
1723
2124
  const buildClient = (plugins) => {
1724
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2125
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1725
2126
  return _a = class {
1726
- constructor(options = {}, links, tables) {
2127
+ constructor(options = {}, schemaTables) {
1727
2128
  __privateAdd(this, _parseOptions);
1728
2129
  __privateAdd(this, _getFetchProps);
1729
2130
  __privateAdd(this, _evaluateBranch);
1730
2131
  __privateAdd(this, _branch, void 0);
2132
+ __privateAdd(this, _options, void 0);
1731
2133
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2134
+ __privateSet(this, _options, safeOptions);
1732
2135
  const pluginOptions = {
1733
2136
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1734
- cache: safeOptions.cache
2137
+ cache: safeOptions.cache,
2138
+ trace: safeOptions.trace
1735
2139
  };
1736
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1737
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
2140
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2141
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1738
2142
  this.db = db;
1739
2143
  this.search = search;
1740
2144
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1741
- if (!namespace)
2145
+ if (namespace === void 0)
1742
2146
  continue;
1743
2147
  const result = namespace.build(pluginOptions);
1744
2148
  if (result instanceof Promise) {
@@ -1750,22 +2154,26 @@ const buildClient = (plugins) => {
1750
2154
  }
1751
2155
  }
1752
2156
  }
1753
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2157
+ async getConfig() {
2158
+ const databaseURL = __privateGet(this, _options).databaseURL;
2159
+ const branch = await __privateGet(this, _options).branch();
2160
+ return { databaseURL, branch };
2161
+ }
2162
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1754
2163
  const fetch = getFetchImplementation(options?.fetch);
1755
2164
  const databaseURL = options?.databaseURL || getDatabaseURL();
1756
2165
  const apiKey = options?.apiKey || getAPIKey();
1757
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1758
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1759
- if (!databaseURL || !apiKey) {
1760
- throw new Error("Options databaseURL and apiKey are required");
2166
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2167
+ const trace = options?.trace ?? defaultTrace;
2168
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2169
+ if (!apiKey) {
2170
+ throw new Error("Option apiKey is required");
1761
2171
  }
1762
- return { fetch, databaseURL, apiKey, branch, cache };
1763
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1764
- fetch,
1765
- apiKey,
1766
- databaseURL,
1767
- branch
1768
- }) {
2172
+ if (!databaseURL) {
2173
+ throw new Error("Option databaseURL is required");
2174
+ }
2175
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2176
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
1769
2177
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1770
2178
  if (!branchValue)
1771
2179
  throw new Error("Unable to resolve branch value");
@@ -1777,12 +2185,13 @@ const buildClient = (plugins) => {
1777
2185
  const hasBranch = params.dbBranchName ?? params.branch;
1778
2186
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
1779
2187
  return databaseURL + newPath;
1780
- }
2188
+ },
2189
+ trace
1781
2190
  };
1782
2191
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1783
2192
  if (__privateGet(this, _branch))
1784
2193
  return __privateGet(this, _branch);
1785
- if (!param)
2194
+ if (param === void 0)
1786
2195
  return void 0;
1787
2196
  const strategies = Array.isArray(param) ? [...param] : [param];
1788
2197
  const evaluateBranch = async (strategy) => {
@@ -1800,6 +2209,88 @@ const buildClient = (plugins) => {
1800
2209
  class BaseClient extends buildClient() {
1801
2210
  }
1802
2211
 
2212
+ const META = "__";
2213
+ const VALUE = "___";
2214
+ class Serializer {
2215
+ constructor() {
2216
+ this.classes = {};
2217
+ }
2218
+ add(clazz) {
2219
+ this.classes[clazz.name] = clazz;
2220
+ }
2221
+ toJSON(data) {
2222
+ function visit(obj) {
2223
+ if (Array.isArray(obj))
2224
+ return obj.map(visit);
2225
+ const type = typeof obj;
2226
+ if (type === "undefined")
2227
+ return { [META]: "undefined" };
2228
+ if (type === "bigint")
2229
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2230
+ if (obj === null || type !== "object")
2231
+ return obj;
2232
+ const constructor = obj.constructor;
2233
+ const o = { [META]: constructor.name };
2234
+ for (const [key, value] of Object.entries(obj)) {
2235
+ o[key] = visit(value);
2236
+ }
2237
+ if (constructor === Date)
2238
+ o[VALUE] = obj.toISOString();
2239
+ if (constructor === Map)
2240
+ o[VALUE] = Object.fromEntries(obj);
2241
+ if (constructor === Set)
2242
+ o[VALUE] = [...obj];
2243
+ return o;
2244
+ }
2245
+ return JSON.stringify(visit(data));
2246
+ }
2247
+ fromJSON(json) {
2248
+ return JSON.parse(json, (key, value) => {
2249
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2250
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2251
+ const constructor = this.classes[clazz];
2252
+ if (constructor) {
2253
+ return Object.assign(Object.create(constructor.prototype), rest);
2254
+ }
2255
+ if (clazz === "Date")
2256
+ return new Date(val);
2257
+ if (clazz === "Set")
2258
+ return new Set(val);
2259
+ if (clazz === "Map")
2260
+ return new Map(Object.entries(val));
2261
+ if (clazz === "bigint")
2262
+ return BigInt(val);
2263
+ if (clazz === "undefined")
2264
+ return void 0;
2265
+ return rest;
2266
+ }
2267
+ return value;
2268
+ });
2269
+ }
2270
+ }
2271
+ const defaultSerializer = new Serializer();
2272
+ const serialize = (data) => {
2273
+ return defaultSerializer.toJSON(data);
2274
+ };
2275
+ const deserialize = (json) => {
2276
+ return defaultSerializer.fromJSON(json);
2277
+ };
2278
+
2279
+ function buildWorkerRunner(config) {
2280
+ return function xataWorker(name, _worker) {
2281
+ return async (...args) => {
2282
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2283
+ const result = await fetch(url, {
2284
+ method: "POST",
2285
+ headers: { "Content-Type": "application/json" },
2286
+ body: serialize({ args })
2287
+ });
2288
+ const text = await result.text();
2289
+ return deserialize(text);
2290
+ };
2291
+ };
2292
+ }
2293
+
1803
2294
  class XataError extends Error {
1804
2295
  constructor(message, status) {
1805
2296
  super(message);
@@ -1815,18 +2306,22 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1815
2306
  exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1816
2307
  exports.Page = Page;
1817
2308
  exports.Query = Query;
2309
+ exports.RecordArray = RecordArray;
1818
2310
  exports.Repository = Repository;
1819
2311
  exports.RestRepository = RestRepository;
1820
2312
  exports.SchemaPlugin = SchemaPlugin;
1821
2313
  exports.SearchPlugin = SearchPlugin;
2314
+ exports.Serializer = Serializer;
1822
2315
  exports.SimpleCache = SimpleCache;
1823
2316
  exports.XataApiClient = XataApiClient;
1824
2317
  exports.XataApiPlugin = XataApiPlugin;
1825
2318
  exports.XataError = XataError;
1826
2319
  exports.XataPlugin = XataPlugin;
1827
2320
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
2321
+ exports.addGitBranchesEntry = addGitBranchesEntry;
1828
2322
  exports.addTableColumn = addTableColumn;
1829
2323
  exports.buildClient = buildClient;
2324
+ exports.buildWorkerRunner = buildWorkerRunner;
1830
2325
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
1831
2326
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
1832
2327
  exports.contains = contains;
@@ -1843,7 +2338,9 @@ exports.deleteTable = deleteTable;
1843
2338
  exports.deleteUser = deleteUser;
1844
2339
  exports.deleteUserAPIKey = deleteUserAPIKey;
1845
2340
  exports.deleteWorkspace = deleteWorkspace;
2341
+ exports.deserialize = deserialize;
1846
2342
  exports.endsWith = endsWith;
2343
+ exports.equals = equals;
1847
2344
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
1848
2345
  exports.exists = exists;
1849
2346
  exports.ge = ge;
@@ -1858,7 +2355,9 @@ exports.getColumn = getColumn;
1858
2355
  exports.getCurrentBranchDetails = getCurrentBranchDetails;
1859
2356
  exports.getCurrentBranchName = getCurrentBranchName;
1860
2357
  exports.getDatabaseList = getDatabaseList;
2358
+ exports.getDatabaseMetadata = getDatabaseMetadata;
1861
2359
  exports.getDatabaseURL = getDatabaseURL;
2360
+ exports.getGitBranchesMapping = getGitBranchesMapping;
1862
2361
  exports.getRecord = getRecord;
1863
2362
  exports.getTableColumns = getTableColumns;
1864
2363
  exports.getTableSchema = getTableSchema;
@@ -1867,6 +2366,9 @@ exports.getUserAPIKeys = getUserAPIKeys;
1867
2366
  exports.getWorkspace = getWorkspace;
1868
2367
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
1869
2368
  exports.getWorkspacesList = getWorkspacesList;
2369
+ exports.greaterEquals = greaterEquals;
2370
+ exports.greaterThan = greaterThan;
2371
+ exports.greaterThanEquals = greaterThanEquals;
1870
2372
  exports.gt = gt;
1871
2373
  exports.gte = gte;
1872
2374
  exports.includes = includes;
@@ -1877,19 +2379,27 @@ exports.insertRecord = insertRecord;
1877
2379
  exports.insertRecordWithID = insertRecordWithID;
1878
2380
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
1879
2381
  exports.is = is;
2382
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
1880
2383
  exports.isIdentifiable = isIdentifiable;
1881
2384
  exports.isNot = isNot;
1882
2385
  exports.isXataRecord = isXataRecord;
1883
2386
  exports.le = le;
2387
+ exports.lessEquals = lessEquals;
2388
+ exports.lessThan = lessThan;
2389
+ exports.lessThanEquals = lessThanEquals;
1884
2390
  exports.lt = lt;
1885
2391
  exports.lte = lte;
1886
2392
  exports.notExists = notExists;
1887
2393
  exports.operationsByTag = operationsByTag;
1888
2394
  exports.pattern = pattern;
1889
2395
  exports.queryTable = queryTable;
2396
+ exports.removeGitBranchesEntry = removeGitBranchesEntry;
1890
2397
  exports.removeWorkspaceMember = removeWorkspaceMember;
1891
2398
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
2399
+ exports.resolveBranch = resolveBranch;
1892
2400
  exports.searchBranch = searchBranch;
2401
+ exports.searchTable = searchTable;
2402
+ exports.serialize = serialize;
1893
2403
  exports.setTableSchema = setTableSchema;
1894
2404
  exports.startsWith = startsWith;
1895
2405
  exports.updateBranchMetadata = updateBranchMetadata;
@@ -1898,6 +2408,7 @@ exports.updateRecordWithID = updateRecordWithID;
1898
2408
  exports.updateTable = updateTable;
1899
2409
  exports.updateUser = updateUser;
1900
2410
  exports.updateWorkspace = updateWorkspace;
2411
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
1901
2412
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
1902
2413
  exports.upsertRecordWithID = upsertRecordWithID;
1903
2414
  //# sourceMappingURL=index.cjs.map