@xata.io/client 0.0.0-alpha.vf6f2567 → 0.0.0-alpha.vf79e7d8

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.vf79e7d8";
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,14 +585,15 @@ const operationsByTag = {
414
585
  getRecord,
415
586
  bulkInsertTableRecords,
416
587
  queryTable,
588
+ searchTable,
417
589
  searchBranch
418
590
  }
419
591
  };
420
592
 
421
593
  function getHostUrl(provider, type) {
422
- if (isValidAlias(provider)) {
594
+ if (isHostProviderAlias(provider)) {
423
595
  return providers[provider][type];
424
- } else if (isValidBuilder(provider)) {
596
+ } else if (isHostProviderBuilder(provider)) {
425
597
  return provider[type];
426
598
  }
427
599
  throw new Error("Invalid API provider");
@@ -436,10 +608,10 @@ const providers = {
436
608
  workspaces: "https://{workspaceId}.staging.xatabase.co"
437
609
  }
438
610
  };
439
- function isValidAlias(alias) {
611
+ function isHostProviderAlias(alias) {
440
612
  return isString(alias) && Object.keys(providers).includes(alias);
441
613
  }
442
- function isValidBuilder(builder) {
614
+ function isHostProviderBuilder(builder) {
443
615
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
444
616
  }
445
617
 
@@ -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,94 @@ 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
- 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));
1261
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({ [column]: constraint }));
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 constraints = isDefined(a) && isDefined(b) ? [{ [a]: b }] : void 0;
1266
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1267
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
994
1268
  }
995
1269
  }
996
- sort(column, direction) {
997
- const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
1270
+ sort(column, direction = "asc") {
1271
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
998
1272
  const sort = [...originalSort, { column, direction }];
999
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
1273
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1000
1274
  }
1001
1275
  select(columns) {
1002
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { columns }, __privateGet$4(this, _data));
1276
+ return new _Query(
1277
+ __privateGet$5(this, _repository),
1278
+ __privateGet$5(this, _table$1),
1279
+ { columns },
1280
+ __privateGet$5(this, _data)
1281
+ );
1003
1282
  }
1004
1283
  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);
1284
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1285
+ return __privateGet$5(this, _repository).query(query);
1007
1286
  }
1008
1287
  async *[Symbol.asyncIterator]() {
1009
- for await (const [record] of this.getIterator(1)) {
1288
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1010
1289
  yield record;
1011
1290
  }
1012
1291
  }
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;
1292
+ async *getIterator(options = {}) {
1293
+ const { batchSize = 1 } = options;
1294
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1295
+ let more = page.hasNextPage();
1296
+ yield page.records;
1297
+ while (more) {
1298
+ page = await page.nextPage();
1299
+ more = page.hasNextPage();
1300
+ yield page.records;
1021
1301
  }
1022
1302
  }
1023
1303
  async getMany(options = {}) {
1024
- const { records } = await this.getPaginated(options);
1025
- return records;
1304
+ const page = await this.getPaginated(options);
1305
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1306
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1307
+ }
1308
+ return page.records;
1026
1309
  }
1027
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1310
+ async getAll(options = {}) {
1311
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1028
1312
  const results = [];
1029
- for await (const page of this.getIterator(chunk, options)) {
1313
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1030
1314
  results.push(...page);
1031
1315
  }
1032
1316
  return results;
1033
1317
  }
1034
1318
  async getFirst(options = {}) {
1035
- const records = await this.getMany({ ...options, page: { size: 1 } });
1036
- return records[0] || null;
1319
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1320
+ return records[0] ?? null;
1037
1321
  }
1038
1322
  cache(ttl) {
1039
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
1323
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1040
1324
  }
1041
1325
  nextPage(size, offset) {
1042
1326
  return this.firstPage(size, offset);
@@ -1045,10 +1329,10 @@ const _Query = class {
1045
1329
  return this.firstPage(size, offset);
1046
1330
  }
1047
1331
  firstPage(size, offset) {
1048
- return this.getPaginated({ page: { size, offset } });
1332
+ return this.getPaginated({ pagination: { size, offset } });
1049
1333
  }
1050
1334
  lastPage(size, offset) {
1051
- return this.getPaginated({ page: { size, offset, before: "end" } });
1335
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1052
1336
  }
1053
1337
  hasNextPage() {
1054
1338
  return this.meta.page.more;
@@ -1058,12 +1342,20 @@ let Query = _Query;
1058
1342
  _table$1 = new WeakMap();
1059
1343
  _repository = new WeakMap();
1060
1344
  _data = new WeakMap();
1345
+ function cleanParent(data, parent) {
1346
+ if (isCursorPaginationOptions(data.pagination)) {
1347
+ return { ...parent, sorting: void 0, filter: void 0 };
1348
+ }
1349
+ return parent;
1350
+ }
1061
1351
 
1062
1352
  function isIdentifiable(x) {
1063
1353
  return isObject(x) && isString(x?.id);
1064
1354
  }
1065
1355
  function isXataRecord(x) {
1066
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1356
+ const record = x;
1357
+ const metadata = record?.getMetadata();
1358
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1067
1359
  }
1068
1360
 
1069
1361
  function isSortFilterString(value) {
@@ -1093,7 +1385,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1093
1385
  if (!member.has(obj))
1094
1386
  throw TypeError("Cannot " + msg);
1095
1387
  };
1096
- var __privateGet$3 = (obj, member, getter) => {
1388
+ var __privateGet$4 = (obj, member, getter) => {
1097
1389
  __accessCheck$4(obj, member, "read from private field");
1098
1390
  return getter ? getter.call(obj) : member.get(obj);
1099
1391
  };
@@ -1102,7 +1394,7 @@ var __privateAdd$4 = (obj, member, value) => {
1102
1394
  throw TypeError("Cannot add the same private member more than once");
1103
1395
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1104
1396
  };
1105
- var __privateSet$2 = (obj, member, value, setter) => {
1397
+ var __privateSet$4 = (obj, member, value, setter) => {
1106
1398
  __accessCheck$4(obj, member, "write to private field");
1107
1399
  setter ? setter.call(obj, value) : member.set(obj, value);
1108
1400
  return value;
@@ -1111,7 +1403,7 @@ var __privateMethod$2 = (obj, member, method) => {
1111
1403
  __accessCheck$4(obj, member, "access private method");
1112
1404
  return method;
1113
1405
  };
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;
1406
+ 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
1407
  class Repository extends Query {
1116
1408
  }
1117
1409
  class RestRepository extends Query {
@@ -1123,292 +1415,338 @@ class RestRepository extends Query {
1123
1415
  __privateAdd$4(this, _updateRecordWithID);
1124
1416
  __privateAdd$4(this, _upsertRecordWithID);
1125
1417
  __privateAdd$4(this, _deleteRecord);
1126
- __privateAdd$4(this, _invalidateCache);
1127
- __privateAdd$4(this, _setCacheRecord);
1128
- __privateAdd$4(this, _getCacheRecord);
1129
1418
  __privateAdd$4(this, _setCacheQuery);
1130
1419
  __privateAdd$4(this, _getCacheQuery);
1420
+ __privateAdd$4(this, _getSchemaTables$1);
1131
1421
  __privateAdd$4(this, _table, void 0);
1132
- __privateAdd$4(this, _links, void 0);
1133
1422
  __privateAdd$4(this, _getFetchProps, void 0);
1423
+ __privateAdd$4(this, _db, void 0);
1134
1424
  __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
1425
+ __privateAdd$4(this, _schemaTables$2, void 0);
1426
+ __privateAdd$4(this, _trace, void 0);
1427
+ __privateSet$4(this, _table, options.table);
1428
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1429
+ __privateSet$4(this, _db, options.db);
1430
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1431
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1432
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1433
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1434
+ return trace(name, fn, {
1435
+ ...options2,
1436
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1437
+ [TraceAttributes.VERSION]: VERSION
1177
1438
  });
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;
1439
+ });
1440
+ }
1441
+ async create(a, b, c) {
1442
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1443
+ if (Array.isArray(a)) {
1444
+ if (a.length === 0)
1445
+ return [];
1446
+ const columns = isStringArray(b) ? b : void 0;
1447
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1182
1448
  }
1183
- throw e;
1184
- }
1449
+ if (isString(a) && isObject(b)) {
1450
+ if (a === "")
1451
+ throw new Error("The id can't be empty");
1452
+ const columns = isStringArray(c) ? c : void 0;
1453
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1454
+ }
1455
+ if (isObject(a) && isString(a.id)) {
1456
+ if (a.id === "")
1457
+ throw new Error("The id can't be empty");
1458
+ const columns = isStringArray(b) ? b : void 0;
1459
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1460
+ }
1461
+ if (isObject(a)) {
1462
+ const columns = isStringArray(b) ? b : void 0;
1463
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1464
+ }
1465
+ throw new Error("Invalid arguments for create method");
1466
+ });
1185
1467
  }
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");
1468
+ async read(a, b) {
1469
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1470
+ const columns = isStringArray(b) ? b : ["*"];
1471
+ if (Array.isArray(a)) {
1472
+ if (a.length === 0)
1473
+ return [];
1474
+ const ids = a.map((item) => extractId(item));
1475
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1476
+ const dictionary = finalObjects.reduce((acc, object) => {
1477
+ acc[object.id] = object;
1478
+ return acc;
1479
+ }, {});
1480
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1190
1481
  }
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");
1482
+ const id = extractId(a);
1483
+ if (id) {
1484
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1485
+ try {
1486
+ const response = await getRecord({
1487
+ pathParams: {
1488
+ workspace: "{workspaceId}",
1489
+ dbBranchName: "{dbBranch}",
1490
+ tableName: __privateGet$4(this, _table),
1491
+ recordId: id
1492
+ },
1493
+ queryParams: { columns },
1494
+ ...fetchProps
1495
+ });
1496
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1497
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1498
+ } catch (e) {
1499
+ if (isObject(e) && e.status === 404) {
1500
+ return null;
1501
+ }
1502
+ throw e;
1503
+ }
1504
+ }
1505
+ return null;
1506
+ });
1206
1507
  }
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");
1508
+ async update(a, b, c) {
1509
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1510
+ if (Array.isArray(a)) {
1511
+ if (a.length === 0)
1512
+ return [];
1513
+ if (a.length > 100) {
1514
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1515
+ }
1516
+ const columns = isStringArray(b) ? b : ["*"];
1517
+ return Promise.all(a.map((object) => this.update(object, columns)));
1211
1518
  }
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");
1519
+ if (isString(a) && isObject(b)) {
1520
+ const columns = isStringArray(c) ? c : void 0;
1521
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1522
+ }
1523
+ if (isObject(a) && isString(a.id)) {
1524
+ const columns = isStringArray(b) ? b : void 0;
1525
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1526
+ }
1527
+ throw new Error("Invalid arguments for update method");
1528
+ });
1227
1529
  }
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");
1530
+ async createOrUpdate(a, b, c) {
1531
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1532
+ if (Array.isArray(a)) {
1533
+ if (a.length === 0)
1534
+ return [];
1535
+ if (a.length > 100) {
1536
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1537
+ }
1538
+ const columns = isStringArray(b) ? b : ["*"];
1539
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1232
1540
  }
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");
1541
+ if (isString(a) && isObject(b)) {
1542
+ const columns = isStringArray(c) ? c : void 0;
1543
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1544
+ }
1545
+ if (isObject(a) && isString(a.id)) {
1546
+ const columns = isStringArray(c) ? c : void 0;
1547
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1548
+ }
1549
+ throw new Error("Invalid arguments for createOrUpdate method");
1550
+ });
1551
+ }
1552
+ async delete(a, b) {
1553
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1554
+ if (Array.isArray(a)) {
1555
+ if (a.length === 0)
1556
+ return [];
1557
+ if (a.length > 100) {
1558
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1559
+ }
1560
+ return Promise.all(a.map((id) => this.delete(id, b)));
1561
+ }
1562
+ if (isString(a)) {
1563
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1564
+ }
1565
+ if (isObject(a) && isString(a.id)) {
1566
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1567
+ }
1568
+ throw new Error("Invalid arguments for delete method");
1569
+ });
1247
1570
  }
1248
1571
  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
1572
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1573
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1574
+ const { records } = await searchTable({
1575
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1576
+ body: {
1577
+ query,
1578
+ fuzziness: options.fuzziness,
1579
+ prefix: options.prefix,
1580
+ highlight: options.highlight,
1581
+ filter: options.filter,
1582
+ boosters: options.boosters
1583
+ },
1584
+ ...fetchProps
1585
+ });
1586
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1587
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1254
1588
  });
1255
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), item));
1256
1589
  }
1257
1590
  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
1591
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1592
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1593
+ if (cacheQuery)
1594
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1595
+ const data = query.getQueryOptions();
1596
+ const body = {
1597
+ filter: cleanFilter(data.filter),
1598
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1599
+ page: data.pagination,
1600
+ columns: data.columns
1601
+ };
1602
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1603
+ const { meta, records: objects } = await queryTable({
1604
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1605
+ body,
1606
+ ...fetchProps
1607
+ });
1608
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1609
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1610
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1611
+ return new Page(query, meta, records);
1273
1612
  });
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
1613
  }
1278
1614
  }
1279
1615
  _table = new WeakMap();
1280
- _links = new WeakMap();
1281
1616
  _getFetchProps = new WeakMap();
1617
+ _db = new WeakMap();
1282
1618
  _cache = new WeakMap();
1619
+ _schemaTables$2 = new WeakMap();
1620
+ _trace = new WeakMap();
1283
1621
  _insertRecordWithoutId = new WeakSet();
1284
- insertRecordWithoutId_fn = async function(object) {
1285
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1622
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1623
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1286
1624
  const record = transformObjectLinks(object);
1287
1625
  const response = await insertRecord({
1288
1626
  pathParams: {
1289
1627
  workspace: "{workspaceId}",
1290
1628
  dbBranchName: "{dbBranch}",
1291
- tableName: __privateGet$3(this, _table)
1629
+ tableName: __privateGet$4(this, _table)
1292
1630
  },
1631
+ queryParams: { columns },
1293
1632
  body: record,
1294
1633
  ...fetchProps
1295
1634
  });
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;
1635
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1636
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1301
1637
  };
1302
1638
  _insertRecordWithId = new WeakSet();
1303
- insertRecordWithId_fn = async function(recordId, object) {
1304
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1639
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1640
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1305
1641
  const record = transformObjectLinks(object);
1306
1642
  const response = await insertRecordWithID({
1307
1643
  pathParams: {
1308
1644
  workspace: "{workspaceId}",
1309
1645
  dbBranchName: "{dbBranch}",
1310
- tableName: __privateGet$3(this, _table),
1646
+ tableName: __privateGet$4(this, _table),
1311
1647
  recordId
1312
1648
  },
1313
1649
  body: record,
1314
- queryParams: { createOnly: true },
1650
+ queryParams: { createOnly: true, columns },
1315
1651
  ...fetchProps
1316
1652
  });
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;
1653
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1654
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1322
1655
  };
1323
1656
  _bulkInsertTableRecords = new WeakSet();
1324
- bulkInsertTableRecords_fn = async function(objects) {
1325
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1657
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1658
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1326
1659
  const records = objects.map((object) => transformObjectLinks(object));
1327
1660
  const response = await bulkInsertTableRecords({
1328
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1661
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1662
+ queryParams: { columns },
1329
1663
  body: { records },
1330
1664
  ...fetchProps
1331
1665
  });
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");
1666
+ if (!isResponseWithRecords(response)) {
1667
+ throw new Error("Request included columns but server didn't include them");
1335
1668
  }
1336
- return finalObjects;
1669
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1670
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1337
1671
  };
1338
1672
  _updateRecordWithID = new WeakSet();
1339
- updateRecordWithID_fn = async function(recordId, object) {
1340
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1673
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1674
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1341
1675
  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;
1676
+ try {
1677
+ const response = await updateRecordWithID({
1678
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1679
+ queryParams: { columns },
1680
+ body: record,
1681
+ ...fetchProps
1682
+ });
1683
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1684
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1685
+ } catch (e) {
1686
+ if (isObject(e) && e.status === 404) {
1687
+ return null;
1688
+ }
1689
+ throw e;
1690
+ }
1351
1691
  };
1352
1692
  _upsertRecordWithID = new WeakSet();
1353
- upsertRecordWithID_fn = async function(recordId, object) {
1354
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1693
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1694
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1355
1695
  const response = await upsertRecordWithID({
1356
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1696
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1697
+ queryParams: { columns },
1357
1698
  body: object,
1358
1699
  ...fetchProps
1359
1700
  });
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;
1701
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1702
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1364
1703
  };
1365
1704
  _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);
1705
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1706
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1707
+ try {
1708
+ const response = await deleteRecord({
1709
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1710
+ queryParams: { columns },
1711
+ ...fetchProps
1712
+ });
1713
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1714
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1715
+ } catch (e) {
1716
+ if (isObject(e) && e.status === 404) {
1717
+ return null;
1718
+ }
1719
+ throw e;
1382
1720
  }
1383
1721
  };
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
1722
  _setCacheQuery = new WeakSet();
1397
1723
  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 });
1724
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1399
1725
  };
1400
1726
  _getCacheQuery = new WeakSet();
1401
1727
  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);
1728
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1729
+ const result = await __privateGet$4(this, _cache).get(key);
1404
1730
  if (!result)
1405
1731
  return null;
1406
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1407
- if (!ttl || ttl < 0)
1408
- return result;
1732
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1733
+ if (ttl < 0)
1734
+ return null;
1409
1735
  const hasExpired = result.date.getTime() + ttl < Date.now();
1410
1736
  return hasExpired ? null : result;
1411
1737
  };
1738
+ _getSchemaTables$1 = new WeakSet();
1739
+ getSchemaTables_fn$1 = async function() {
1740
+ if (__privateGet$4(this, _schemaTables$2))
1741
+ return __privateGet$4(this, _schemaTables$2);
1742
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1743
+ const { schema } = await getBranchDetails({
1744
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1745
+ ...fetchProps
1746
+ });
1747
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1748
+ return schema.tables;
1749
+ };
1412
1750
  const transformObjectLinks = (object) => {
1413
1751
  return Object.entries(object).reduce((acc, [key, value]) => {
1414
1752
  if (key === "xata")
@@ -1416,47 +1754,76 @@ const transformObjectLinks = (object) => {
1416
1754
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1417
1755
  }, {});
1418
1756
  };
1419
- const initObject = (db, links, table, object) => {
1757
+ const initObject = (db, schemaTables, table, object) => {
1420
1758
  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);
1759
+ const { xata, ...rest } = object ?? {};
1760
+ Object.assign(result, rest);
1761
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1762
+ if (!columns)
1763
+ console.error(`Table ${table} not found in schema`);
1764
+ for (const column of columns ?? []) {
1765
+ const value = result[column.name];
1766
+ switch (column.type) {
1767
+ case "datetime": {
1768
+ const date = value !== void 0 ? new Date(value) : void 0;
1769
+ if (date && isNaN(date.getTime())) {
1770
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1771
+ } else if (date) {
1772
+ result[column.name] = date;
1773
+ }
1774
+ break;
1775
+ }
1776
+ case "link": {
1777
+ const linkTable = column.link?.table;
1778
+ if (!linkTable) {
1779
+ console.error(`Failed to parse link for field ${column.name}`);
1780
+ } else if (isObject(value)) {
1781
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1782
+ }
1783
+ break;
1784
+ }
1428
1785
  }
1429
1786
  }
1430
- result.read = function() {
1431
- return db[table].read(result["id"]);
1787
+ result.read = function(columns2) {
1788
+ return db[table].read(result["id"], columns2);
1432
1789
  };
1433
- result.update = function(data) {
1434
- return db[table].update(result["id"], data);
1790
+ result.update = function(data, columns2) {
1791
+ return db[table].update(result["id"], data, columns2);
1435
1792
  };
1436
1793
  result.delete = function() {
1437
1794
  return db[table].delete(result["id"]);
1438
1795
  };
1439
- for (const prop of ["read", "update", "delete"]) {
1796
+ result.getMetadata = function() {
1797
+ return xata;
1798
+ };
1799
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1440
1800
  Object.defineProperty(result, prop, { enumerable: false });
1441
1801
  }
1442
1802
  Object.freeze(result);
1443
1803
  return result;
1444
1804
  };
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;
1805
+ function isResponseWithRecords(value) {
1806
+ return isObject(value) && Array.isArray(value.records);
1807
+ }
1808
+ function extractId(value) {
1809
+ if (isString(value))
1810
+ return value;
1811
+ if (isObject(value) && isString(value.id))
1812
+ return value.id;
1813
+ return void 0;
1814
+ }
1815
+ function cleanFilter(filter) {
1816
+ if (!filter)
1817
+ return void 0;
1818
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1819
+ return values.length > 0 ? filter : void 0;
1453
1820
  }
1454
1821
 
1455
1822
  var __accessCheck$3 = (obj, member, msg) => {
1456
1823
  if (!member.has(obj))
1457
1824
  throw TypeError("Cannot " + msg);
1458
1825
  };
1459
- var __privateGet$2 = (obj, member, getter) => {
1826
+ var __privateGet$3 = (obj, member, getter) => {
1460
1827
  __accessCheck$3(obj, member, "read from private field");
1461
1828
  return getter ? getter.call(obj) : member.get(obj);
1462
1829
  };
@@ -1465,7 +1832,7 @@ var __privateAdd$3 = (obj, member, value) => {
1465
1832
  throw TypeError("Cannot add the same private member more than once");
1466
1833
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1467
1834
  };
1468
- var __privateSet$1 = (obj, member, value, setter) => {
1835
+ var __privateSet$3 = (obj, member, value, setter) => {
1469
1836
  __accessCheck$3(obj, member, "write to private field");
1470
1837
  setter ? setter.call(obj, value) : member.set(obj, value);
1471
1838
  return value;
@@ -1474,46 +1841,52 @@ var _map;
1474
1841
  class SimpleCache {
1475
1842
  constructor(options = {}) {
1476
1843
  __privateAdd$3(this, _map, void 0);
1477
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
1844
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1478
1845
  this.capacity = options.max ?? 500;
1479
- this.cacheRecords = options.cacheRecords ?? true;
1480
1846
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1481
1847
  }
1482
1848
  async getAll() {
1483
- return Object.fromEntries(__privateGet$2(this, _map));
1849
+ return Object.fromEntries(__privateGet$3(this, _map));
1484
1850
  }
1485
1851
  async get(key) {
1486
- return __privateGet$2(this, _map).get(key) ?? null;
1852
+ return __privateGet$3(this, _map).get(key) ?? null;
1487
1853
  }
1488
1854
  async set(key, value) {
1489
1855
  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;
1856
+ __privateGet$3(this, _map).set(key, value);
1857
+ if (__privateGet$3(this, _map).size > this.capacity) {
1858
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1493
1859
  await this.delete(leastRecentlyUsed);
1494
1860
  }
1495
1861
  }
1496
1862
  async delete(key) {
1497
- __privateGet$2(this, _map).delete(key);
1863
+ __privateGet$3(this, _map).delete(key);
1498
1864
  }
1499
1865
  async clear() {
1500
- return __privateGet$2(this, _map).clear();
1866
+ return __privateGet$3(this, _map).clear();
1501
1867
  }
1502
1868
  }
1503
1869
  _map = new WeakMap();
1504
1870
 
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 });
1871
+ const greaterThan = (value) => ({ $gt: value });
1872
+ const gt = greaterThan;
1873
+ const greaterThanEquals = (value) => ({ $ge: value });
1874
+ const greaterEquals = greaterThanEquals;
1875
+ const gte = greaterThanEquals;
1876
+ const ge = greaterThanEquals;
1877
+ const lessThan = (value) => ({ $lt: value });
1878
+ const lt = lessThan;
1879
+ const lessThanEquals = (value) => ({ $le: value });
1880
+ const lessEquals = lessThanEquals;
1881
+ const lte = lessThanEquals;
1882
+ const le = lessThanEquals;
1511
1883
  const exists = (column) => ({ $exists: column });
1512
1884
  const notExists = (column) => ({ $notExists: column });
1513
1885
  const startsWith = (value) => ({ $startsWith: value });
1514
1886
  const endsWith = (value) => ({ $endsWith: value });
1515
1887
  const pattern = (value) => ({ $pattern: value });
1516
1888
  const is = (value) => ({ $is: value });
1889
+ const equals = is;
1517
1890
  const isNot = (value) => ({ $isNot: value });
1518
1891
  const contains = (value) => ({ $contains: value });
1519
1892
  const includes = (value) => ({ $includes: value });
@@ -1525,7 +1898,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1525
1898
  if (!member.has(obj))
1526
1899
  throw TypeError("Cannot " + msg);
1527
1900
  };
1528
- var __privateGet$1 = (obj, member, getter) => {
1901
+ var __privateGet$2 = (obj, member, getter) => {
1529
1902
  __accessCheck$2(obj, member, "read from private field");
1530
1903
  return getter ? getter.call(obj) : member.get(obj);
1531
1904
  };
@@ -1534,130 +1907,178 @@ var __privateAdd$2 = (obj, member, value) => {
1534
1907
  throw TypeError("Cannot add the same private member more than once");
1535
1908
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1536
1909
  };
1537
- var _tables;
1910
+ var __privateSet$2 = (obj, member, value, setter) => {
1911
+ __accessCheck$2(obj, member, "write to private field");
1912
+ setter ? setter.call(obj, value) : member.set(obj, value);
1913
+ return value;
1914
+ };
1915
+ var _tables, _schemaTables$1;
1538
1916
  class SchemaPlugin extends XataPlugin {
1539
- constructor(links, tableNames) {
1917
+ constructor(schemaTables) {
1540
1918
  super();
1541
- this.links = links;
1542
- this.tableNames = tableNames;
1543
1919
  __privateAdd$2(this, _tables, {});
1920
+ __privateAdd$2(this, _schemaTables$1, void 0);
1921
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1544
1922
  }
1545
1923
  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 });
1924
+ const db = new Proxy(
1925
+ {},
1926
+ {
1927
+ get: (_target, table) => {
1928
+ if (!isString(table))
1929
+ throw new Error("Invalid table name");
1930
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1931
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1932
+ }
1933
+ return __privateGet$2(this, _tables)[table];
1553
1934
  }
1554
- return __privateGet$1(this, _tables)[table];
1555
1935
  }
1556
- });
1557
- for (const table of this.tableNames ?? []) {
1558
- db[table] = new RestRepository({ db, pluginOptions, table, links });
1936
+ );
1937
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1938
+ for (const table of tableNames) {
1939
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1559
1940
  }
1560
1941
  return db;
1561
1942
  }
1562
1943
  }
1563
1944
  _tables = new WeakMap();
1945
+ _schemaTables$1 = new WeakMap();
1564
1946
 
1565
1947
  var __accessCheck$1 = (obj, member, msg) => {
1566
1948
  if (!member.has(obj))
1567
1949
  throw TypeError("Cannot " + msg);
1568
1950
  };
1951
+ var __privateGet$1 = (obj, member, getter) => {
1952
+ __accessCheck$1(obj, member, "read from private field");
1953
+ return getter ? getter.call(obj) : member.get(obj);
1954
+ };
1569
1955
  var __privateAdd$1 = (obj, member, value) => {
1570
1956
  if (member.has(obj))
1571
1957
  throw TypeError("Cannot add the same private member more than once");
1572
1958
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1573
1959
  };
1960
+ var __privateSet$1 = (obj, member, value, setter) => {
1961
+ __accessCheck$1(obj, member, "write to private field");
1962
+ setter ? setter.call(obj, value) : member.set(obj, value);
1963
+ return value;
1964
+ };
1574
1965
  var __privateMethod$1 = (obj, member, method) => {
1575
1966
  __accessCheck$1(obj, member, "access private method");
1576
1967
  return method;
1577
1968
  };
1578
- var _search, search_fn;
1969
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1579
1970
  class SearchPlugin extends XataPlugin {
1580
- constructor(db, links) {
1971
+ constructor(db, schemaTables) {
1581
1972
  super();
1582
1973
  this.db = db;
1583
- this.links = links;
1584
1974
  __privateAdd$1(this, _search);
1975
+ __privateAdd$1(this, _getSchemaTables);
1976
+ __privateAdd$1(this, _schemaTables, void 0);
1977
+ __privateSet$1(this, _schemaTables, schemaTables);
1585
1978
  }
1586
1979
  build({ getFetchProps }) {
1587
1980
  return {
1588
1981
  all: async (query, options = {}) => {
1589
1982
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1983
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1590
1984
  return records.map((record) => {
1591
1985
  const { table = "orphan" } = record.xata;
1592
- return { table, record: initObject(this.db, this.links, table, record) };
1986
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1593
1987
  });
1594
1988
  },
1595
1989
  byTable: async (query, options = {}) => {
1596
1990
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1991
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1597
1992
  return records.reduce((acc, record) => {
1598
1993
  const { table = "orphan" } = record.xata;
1599
1994
  const items = acc[table] ?? [];
1600
- const item = initObject(this.db, this.links, table, record);
1995
+ const item = initObject(this.db, schemaTables, table, record);
1601
1996
  return { ...acc, [table]: [...items, item] };
1602
1997
  }, {});
1603
1998
  }
1604
1999
  };
1605
2000
  }
1606
2001
  }
2002
+ _schemaTables = new WeakMap();
1607
2003
  _search = new WeakSet();
1608
2004
  search_fn = async function(query, options, getFetchProps) {
1609
2005
  const fetchProps = await getFetchProps();
1610
- const { tables, fuzziness } = options ?? {};
2006
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1611
2007
  const { records } = await searchBranch({
1612
2008
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1613
- body: { tables, query, fuzziness },
2009
+ body: { tables, query, fuzziness, prefix, highlight },
1614
2010
  ...fetchProps
1615
2011
  });
1616
2012
  return records;
1617
2013
  };
2014
+ _getSchemaTables = new WeakSet();
2015
+ getSchemaTables_fn = async function(getFetchProps) {
2016
+ if (__privateGet$1(this, _schemaTables))
2017
+ return __privateGet$1(this, _schemaTables);
2018
+ const fetchProps = await getFetchProps();
2019
+ const { schema } = await getBranchDetails({
2020
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2021
+ ...fetchProps
2022
+ });
2023
+ __privateSet$1(this, _schemaTables, schema.tables);
2024
+ return schema.tables;
2025
+ };
1618
2026
 
1619
2027
  const isBranchStrategyBuilder = (strategy) => {
1620
2028
  return typeof strategy === "function";
1621
2029
  };
1622
2030
 
1623
- const envBranchNames = [
1624
- "XATA_BRANCH",
1625
- "VERCEL_GIT_COMMIT_REF",
1626
- "CF_PAGES_BRANCH",
1627
- "BRANCH"
1628
- ];
1629
- const defaultBranch = "main";
1630
2031
  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;
2032
+ const { branch, envBranch } = getEnvironment();
2033
+ if (branch) {
2034
+ const details = await getDatabaseBranch(branch, options);
2035
+ if (details)
2036
+ return branch;
2037
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2038
+ }
2039
+ const gitBranch = envBranch || await getGitBranch();
2040
+ return resolveXataBranch(gitBranch, options);
1641
2041
  }
1642
2042
  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);
2043
+ const branch = await getCurrentBranchName(options);
2044
+ return getDatabaseBranch(branch, options);
2045
+ }
2046
+ async function resolveXataBranch(gitBranch, options) {
2047
+ const databaseURL = options?.databaseURL || getDatabaseURL();
2048
+ const apiKey = options?.apiKey || getAPIKey();
2049
+ if (!databaseURL)
2050
+ throw new Error(
2051
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2052
+ );
2053
+ if (!apiKey)
2054
+ throw new Error(
2055
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2056
+ );
2057
+ const [protocol, , host, , dbName] = databaseURL.split("/");
2058
+ const [workspace] = host.split(".");
2059
+ const { fallbackBranch } = getEnvironment();
2060
+ const { branch } = await resolveBranch({
2061
+ apiKey,
2062
+ apiUrl: databaseURL,
2063
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
2064
+ workspacesApiUrl: `${protocol}//${host}`,
2065
+ pathParams: { dbName, workspace },
2066
+ queryParams: { gitBranch, fallbackBranch },
2067
+ trace: defaultTrace
2068
+ });
2069
+ return branch;
1653
2070
  }
1654
2071
  async function getDatabaseBranch(branch, options) {
1655
2072
  const databaseURL = options?.databaseURL || getDatabaseURL();
1656
2073
  const apiKey = options?.apiKey || getAPIKey();
1657
2074
  if (!databaseURL)
1658
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2075
+ throw new Error(
2076
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2077
+ );
1659
2078
  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");
2079
+ throw new Error(
2080
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2081
+ );
1661
2082
  const [protocol, , host, , database] = databaseURL.split("/");
1662
2083
  const [workspace] = host.split(".");
1663
2084
  const dbBranchName = `${database}:${branch}`;
@@ -1667,10 +2088,8 @@ async function getDatabaseBranch(branch, options) {
1667
2088
  apiUrl: databaseURL,
1668
2089
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1669
2090
  workspacesApiUrl: `${protocol}//${host}`,
1670
- pathParams: {
1671
- dbBranchName,
1672
- workspace
1673
- }
2091
+ pathParams: { dbBranchName, workspace },
2092
+ trace: defaultTrace
1674
2093
  });
1675
2094
  } catch (err) {
1676
2095
  if (isObject(err) && err.status === 404)
@@ -1678,21 +2097,10 @@ async function getDatabaseBranch(branch, options) {
1678
2097
  throw err;
1679
2098
  }
1680
2099
  }
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
2100
  function getDatabaseURL() {
1694
2101
  try {
1695
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2102
+ const { databaseURL } = getEnvironment();
2103
+ return databaseURL;
1696
2104
  } catch (err) {
1697
2105
  return void 0;
1698
2106
  }
@@ -1721,24 +2129,27 @@ var __privateMethod = (obj, member, method) => {
1721
2129
  return method;
1722
2130
  };
1723
2131
  const buildClient = (plugins) => {
1724
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2132
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1725
2133
  return _a = class {
1726
- constructor(options = {}, links, tables) {
2134
+ constructor(options = {}, schemaTables) {
1727
2135
  __privateAdd(this, _parseOptions);
1728
2136
  __privateAdd(this, _getFetchProps);
1729
2137
  __privateAdd(this, _evaluateBranch);
1730
2138
  __privateAdd(this, _branch, void 0);
2139
+ __privateAdd(this, _options, void 0);
1731
2140
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2141
+ __privateSet(this, _options, safeOptions);
1732
2142
  const pluginOptions = {
1733
2143
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1734
- cache: safeOptions.cache
2144
+ cache: safeOptions.cache,
2145
+ trace: safeOptions.trace
1735
2146
  };
1736
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1737
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
2147
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2148
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1738
2149
  this.db = db;
1739
2150
  this.search = search;
1740
2151
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1741
- if (!namespace)
2152
+ if (namespace === void 0)
1742
2153
  continue;
1743
2154
  const result = namespace.build(pluginOptions);
1744
2155
  if (result instanceof Promise) {
@@ -1750,22 +2161,26 @@ const buildClient = (plugins) => {
1750
2161
  }
1751
2162
  }
1752
2163
  }
1753
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2164
+ async getConfig() {
2165
+ const databaseURL = __privateGet(this, _options).databaseURL;
2166
+ const branch = await __privateGet(this, _options).branch();
2167
+ return { databaseURL, branch };
2168
+ }
2169
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1754
2170
  const fetch = getFetchImplementation(options?.fetch);
1755
2171
  const databaseURL = options?.databaseURL || getDatabaseURL();
1756
2172
  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");
2173
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2174
+ const trace = options?.trace ?? defaultTrace;
2175
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2176
+ if (!apiKey) {
2177
+ throw new Error("Option apiKey is required");
1761
2178
  }
1762
- return { fetch, databaseURL, apiKey, branch, cache };
1763
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1764
- fetch,
1765
- apiKey,
1766
- databaseURL,
1767
- branch
1768
- }) {
2179
+ if (!databaseURL) {
2180
+ throw new Error("Option databaseURL is required");
2181
+ }
2182
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2183
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
1769
2184
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1770
2185
  if (!branchValue)
1771
2186
  throw new Error("Unable to resolve branch value");
@@ -1777,12 +2192,13 @@ const buildClient = (plugins) => {
1777
2192
  const hasBranch = params.dbBranchName ?? params.branch;
1778
2193
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
1779
2194
  return databaseURL + newPath;
1780
- }
2195
+ },
2196
+ trace
1781
2197
  };
1782
2198
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1783
2199
  if (__privateGet(this, _branch))
1784
2200
  return __privateGet(this, _branch);
1785
- if (!param)
2201
+ if (param === void 0)
1786
2202
  return void 0;
1787
2203
  const strategies = Array.isArray(param) ? [...param] : [param];
1788
2204
  const evaluateBranch = async (strategy) => {
@@ -1800,6 +2216,88 @@ const buildClient = (plugins) => {
1800
2216
  class BaseClient extends buildClient() {
1801
2217
  }
1802
2218
 
2219
+ const META = "__";
2220
+ const VALUE = "___";
2221
+ class Serializer {
2222
+ constructor() {
2223
+ this.classes = {};
2224
+ }
2225
+ add(clazz) {
2226
+ this.classes[clazz.name] = clazz;
2227
+ }
2228
+ toJSON(data) {
2229
+ function visit(obj) {
2230
+ if (Array.isArray(obj))
2231
+ return obj.map(visit);
2232
+ const type = typeof obj;
2233
+ if (type === "undefined")
2234
+ return { [META]: "undefined" };
2235
+ if (type === "bigint")
2236
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2237
+ if (obj === null || type !== "object")
2238
+ return obj;
2239
+ const constructor = obj.constructor;
2240
+ const o = { [META]: constructor.name };
2241
+ for (const [key, value] of Object.entries(obj)) {
2242
+ o[key] = visit(value);
2243
+ }
2244
+ if (constructor === Date)
2245
+ o[VALUE] = obj.toISOString();
2246
+ if (constructor === Map)
2247
+ o[VALUE] = Object.fromEntries(obj);
2248
+ if (constructor === Set)
2249
+ o[VALUE] = [...obj];
2250
+ return o;
2251
+ }
2252
+ return JSON.stringify(visit(data));
2253
+ }
2254
+ fromJSON(json) {
2255
+ return JSON.parse(json, (key, value) => {
2256
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2257
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2258
+ const constructor = this.classes[clazz];
2259
+ if (constructor) {
2260
+ return Object.assign(Object.create(constructor.prototype), rest);
2261
+ }
2262
+ if (clazz === "Date")
2263
+ return new Date(val);
2264
+ if (clazz === "Set")
2265
+ return new Set(val);
2266
+ if (clazz === "Map")
2267
+ return new Map(Object.entries(val));
2268
+ if (clazz === "bigint")
2269
+ return BigInt(val);
2270
+ if (clazz === "undefined")
2271
+ return void 0;
2272
+ return rest;
2273
+ }
2274
+ return value;
2275
+ });
2276
+ }
2277
+ }
2278
+ const defaultSerializer = new Serializer();
2279
+ const serialize = (data) => {
2280
+ return defaultSerializer.toJSON(data);
2281
+ };
2282
+ const deserialize = (json) => {
2283
+ return defaultSerializer.fromJSON(json);
2284
+ };
2285
+
2286
+ function buildWorkerRunner(config) {
2287
+ return function xataWorker(name, _worker) {
2288
+ return async (...args) => {
2289
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2290
+ const result = await fetch(url, {
2291
+ method: "POST",
2292
+ headers: { "Content-Type": "application/json" },
2293
+ body: serialize({ args })
2294
+ });
2295
+ const text = await result.text();
2296
+ return deserialize(text);
2297
+ };
2298
+ };
2299
+ }
2300
+
1803
2301
  class XataError extends Error {
1804
2302
  constructor(message, status) {
1805
2303
  super(message);
@@ -1815,18 +2313,22 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1815
2313
  exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1816
2314
  exports.Page = Page;
1817
2315
  exports.Query = Query;
2316
+ exports.RecordArray = RecordArray;
1818
2317
  exports.Repository = Repository;
1819
2318
  exports.RestRepository = RestRepository;
1820
2319
  exports.SchemaPlugin = SchemaPlugin;
1821
2320
  exports.SearchPlugin = SearchPlugin;
2321
+ exports.Serializer = Serializer;
1822
2322
  exports.SimpleCache = SimpleCache;
1823
2323
  exports.XataApiClient = XataApiClient;
1824
2324
  exports.XataApiPlugin = XataApiPlugin;
1825
2325
  exports.XataError = XataError;
1826
2326
  exports.XataPlugin = XataPlugin;
1827
2327
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
2328
+ exports.addGitBranchesEntry = addGitBranchesEntry;
1828
2329
  exports.addTableColumn = addTableColumn;
1829
2330
  exports.buildClient = buildClient;
2331
+ exports.buildWorkerRunner = buildWorkerRunner;
1830
2332
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
1831
2333
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
1832
2334
  exports.contains = contains;
@@ -1843,7 +2345,9 @@ exports.deleteTable = deleteTable;
1843
2345
  exports.deleteUser = deleteUser;
1844
2346
  exports.deleteUserAPIKey = deleteUserAPIKey;
1845
2347
  exports.deleteWorkspace = deleteWorkspace;
2348
+ exports.deserialize = deserialize;
1846
2349
  exports.endsWith = endsWith;
2350
+ exports.equals = equals;
1847
2351
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
1848
2352
  exports.exists = exists;
1849
2353
  exports.ge = ge;
@@ -1858,7 +2362,9 @@ exports.getColumn = getColumn;
1858
2362
  exports.getCurrentBranchDetails = getCurrentBranchDetails;
1859
2363
  exports.getCurrentBranchName = getCurrentBranchName;
1860
2364
  exports.getDatabaseList = getDatabaseList;
2365
+ exports.getDatabaseMetadata = getDatabaseMetadata;
1861
2366
  exports.getDatabaseURL = getDatabaseURL;
2367
+ exports.getGitBranchesMapping = getGitBranchesMapping;
1862
2368
  exports.getRecord = getRecord;
1863
2369
  exports.getTableColumns = getTableColumns;
1864
2370
  exports.getTableSchema = getTableSchema;
@@ -1867,6 +2373,9 @@ exports.getUserAPIKeys = getUserAPIKeys;
1867
2373
  exports.getWorkspace = getWorkspace;
1868
2374
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
1869
2375
  exports.getWorkspacesList = getWorkspacesList;
2376
+ exports.greaterEquals = greaterEquals;
2377
+ exports.greaterThan = greaterThan;
2378
+ exports.greaterThanEquals = greaterThanEquals;
1870
2379
  exports.gt = gt;
1871
2380
  exports.gte = gte;
1872
2381
  exports.includes = includes;
@@ -1877,19 +2386,27 @@ exports.insertRecord = insertRecord;
1877
2386
  exports.insertRecordWithID = insertRecordWithID;
1878
2387
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
1879
2388
  exports.is = is;
2389
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
1880
2390
  exports.isIdentifiable = isIdentifiable;
1881
2391
  exports.isNot = isNot;
1882
2392
  exports.isXataRecord = isXataRecord;
1883
2393
  exports.le = le;
2394
+ exports.lessEquals = lessEquals;
2395
+ exports.lessThan = lessThan;
2396
+ exports.lessThanEquals = lessThanEquals;
1884
2397
  exports.lt = lt;
1885
2398
  exports.lte = lte;
1886
2399
  exports.notExists = notExists;
1887
2400
  exports.operationsByTag = operationsByTag;
1888
2401
  exports.pattern = pattern;
1889
2402
  exports.queryTable = queryTable;
2403
+ exports.removeGitBranchesEntry = removeGitBranchesEntry;
1890
2404
  exports.removeWorkspaceMember = removeWorkspaceMember;
1891
2405
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
2406
+ exports.resolveBranch = resolveBranch;
1892
2407
  exports.searchBranch = searchBranch;
2408
+ exports.searchTable = searchTable;
2409
+ exports.serialize = serialize;
1893
2410
  exports.setTableSchema = setTableSchema;
1894
2411
  exports.startsWith = startsWith;
1895
2412
  exports.updateBranchMetadata = updateBranchMetadata;
@@ -1898,6 +2415,7 @@ exports.updateRecordWithID = updateRecordWithID;
1898
2415
  exports.updateTable = updateTable;
1899
2416
  exports.updateUser = updateUser;
1900
2417
  exports.updateWorkspace = updateWorkspace;
2418
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
1901
2419
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
1902
2420
  exports.upsertRecordWithID = upsertRecordWithID;
1903
2421
  //# sourceMappingURL=index.cjs.map