@xata.io/client 0.0.0-alpha.vebf0406 → 0.0.0-alpha.vec0bff6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -7,36 +7,101 @@ function compact(arr) {
7
7
  function isObject(value) {
8
8
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
9
  }
10
+ function isDefined(value) {
11
+ return value !== null && value !== void 0;
12
+ }
10
13
  function isString(value) {
11
- return value !== void 0 && value !== null && typeof value === "string";
14
+ return isDefined(value) && typeof value === "string";
15
+ }
16
+ function isStringArray(value) {
17
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
18
+ }
19
+ function toBase64(value) {
20
+ try {
21
+ return btoa(value);
22
+ } catch (err) {
23
+ const buf = Buffer;
24
+ return buf.from(value).toString("base64");
25
+ }
12
26
  }
13
27
 
14
- function getEnvVariable(name) {
28
+ function getEnvironment() {
15
29
  try {
16
- if (isObject(process) && isString(process?.env?.[name])) {
17
- return process.env[name];
30
+ if (isObject(process) && isObject(process.env)) {
31
+ return {
32
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
33
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
34
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
35
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
36
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
37
+ };
18
38
  }
19
39
  } catch (err) {
20
40
  }
21
41
  try {
22
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
23
- return Deno.env.get(name);
42
+ if (isObject(Deno) && isObject(Deno.env)) {
43
+ return {
44
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
45
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
46
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
47
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
48
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
49
+ };
24
50
  }
25
51
  } catch (err) {
26
52
  }
53
+ return {
54
+ apiKey: getGlobalApiKey(),
55
+ databaseURL: getGlobalDatabaseURL(),
56
+ branch: getGlobalBranch(),
57
+ envBranch: void 0,
58
+ fallbackBranch: getGlobalFallbackBranch()
59
+ };
60
+ }
61
+ function getGlobalApiKey() {
62
+ try {
63
+ return XATA_API_KEY;
64
+ } catch (err) {
65
+ return void 0;
66
+ }
67
+ }
68
+ function getGlobalDatabaseURL() {
69
+ try {
70
+ return XATA_DATABASE_URL;
71
+ } catch (err) {
72
+ return void 0;
73
+ }
74
+ }
75
+ function getGlobalBranch() {
76
+ try {
77
+ return XATA_BRANCH;
78
+ } catch (err) {
79
+ return void 0;
80
+ }
81
+ }
82
+ function getGlobalFallbackBranch() {
83
+ try {
84
+ return XATA_FALLBACK_BRANCH;
85
+ } catch (err) {
86
+ return void 0;
87
+ }
27
88
  }
28
89
  async function getGitBranch() {
90
+ const cmd = ["git", "branch", "--show-current"];
91
+ const fullCmd = cmd.join(" ");
92
+ const nodeModule = ["child", "process"].join("_");
93
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
29
94
  try {
30
- return require("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
95
+ if (typeof require === "function") {
96
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
97
+ }
98
+ const { execSync } = await import(nodeModule);
99
+ return execSync(fullCmd, execOptions).toString().trim();
31
100
  } catch (err) {
32
101
  }
33
102
  try {
34
103
  if (isObject(Deno)) {
35
- const process2 = Deno.run({
36
- cmd: ["git", "branch", "--show-current"],
37
- stdout: "piped",
38
- stderr: "piped"
39
- });
104
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
40
105
  return new TextDecoder().decode(await process2.output()).trim();
41
106
  }
42
107
  } catch (err) {
@@ -45,7 +110,8 @@ async function getGitBranch() {
45
110
 
46
111
  function getAPIKey() {
47
112
  try {
48
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
113
+ const { apiKey } = getEnvironment();
114
+ return apiKey;
49
115
  } catch (err) {
50
116
  return void 0;
51
117
  }
@@ -55,21 +121,35 @@ function getFetchImplementation(userFetch) {
55
121
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
56
122
  const fetchImpl = userFetch ?? globalFetch;
57
123
  if (!fetchImpl) {
58
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
124
+ throw new Error(
125
+ `The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`
126
+ );
59
127
  }
60
128
  return fetchImpl;
61
129
  }
62
130
 
63
- class FetcherError extends Error {
64
- constructor(status, data) {
131
+ const VERSION = "0.0.0-alpha.vec0bff6";
132
+
133
+ class ErrorWithCause extends Error {
134
+ constructor(message, options) {
135
+ super(message, options);
136
+ }
137
+ }
138
+ class FetcherError extends ErrorWithCause {
139
+ constructor(status, data, requestId) {
65
140
  super(getMessage(data));
66
141
  this.status = status;
67
142
  this.errors = isBulkError(data) ? data.errors : void 0;
143
+ this.requestId = requestId;
68
144
  if (data instanceof Error) {
69
145
  this.stack = data.stack;
70
146
  this.cause = data.cause;
71
147
  }
72
148
  }
149
+ toString() {
150
+ const error = super.toString();
151
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
152
+ }
73
153
  }
74
154
  function isBulkError(error) {
75
155
  return isObject(error) && Array.isArray(error.errors);
@@ -92,7 +172,12 @@ function getMessage(data) {
92
172
  }
93
173
 
94
174
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
95
- const query = new URLSearchParams(queryParams).toString();
175
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
176
+ if (value === void 0 || value === null)
177
+ return acc;
178
+ return { ...acc, [key]: value };
179
+ }, {});
180
+ const query = new URLSearchParams(cleanQueryParams).toString();
96
181
  const queryString = query.length > 0 ? `?${query}` : "";
97
182
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
98
183
  };
@@ -132,6 +217,7 @@ async function fetch$1({
132
217
  body: body ? JSON.stringify(body) : void 0,
133
218
  headers: {
134
219
  "Content-Type": "application/json",
220
+ "User-Agent": `Xata client-ts/${VERSION}`,
135
221
  ...headers,
136
222
  ...hostHeader(fullUrl),
137
223
  Authorization: `Bearer ${apiKey}`
@@ -140,14 +226,15 @@ async function fetch$1({
140
226
  if (response.status === 204) {
141
227
  return {};
142
228
  }
229
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
143
230
  try {
144
231
  const jsonResponse = await response.json();
145
232
  if (response.ok) {
146
233
  return jsonResponse;
147
234
  }
148
- throw new FetcherError(response.status, jsonResponse);
235
+ throw new FetcherError(response.status, jsonResponse, requestId);
149
236
  } catch (error) {
150
- throw new FetcherError(response.status, error);
237
+ throw new FetcherError(response.status, error, requestId);
151
238
  }
152
239
  }
153
240
 
@@ -206,6 +293,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
206
293
  ...variables
207
294
  });
208
295
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
296
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
209
297
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
210
298
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
211
299
  method: "delete",
@@ -241,16 +329,20 @@ const deleteDatabase = (variables) => fetch$1({
241
329
  method: "delete",
242
330
  ...variables
243
331
  });
244
- const getBranchDetails = (variables) => fetch$1({
245
- url: "/db/{dbBranchName}",
332
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
333
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
334
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
335
+ const resolveBranch = (variables) => fetch$1({
336
+ url: "/dbs/{dbName}/resolveBranch",
246
337
  method: "get",
247
338
  ...variables
248
339
  });
249
- const createBranch = (variables) => fetch$1({
340
+ const getBranchDetails = (variables) => fetch$1({
250
341
  url: "/db/{dbBranchName}",
251
- method: "put",
342
+ method: "get",
252
343
  ...variables
253
344
  });
345
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
254
346
  const deleteBranch = (variables) => fetch$1({
255
347
  url: "/db/{dbBranchName}",
256
348
  method: "delete",
@@ -324,11 +416,7 @@ const updateColumn = (variables) => fetch$1({
324
416
  method: "patch",
325
417
  ...variables
326
418
  });
327
- const insertRecord = (variables) => fetch$1({
328
- url: "/db/{dbBranchName}/tables/{tableName}/data",
329
- method: "post",
330
- ...variables
331
- });
419
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
332
420
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
333
421
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
334
422
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -348,6 +436,11 @@ const queryTable = (variables) => fetch$1({
348
436
  method: "post",
349
437
  ...variables
350
438
  });
439
+ const searchTable = (variables) => fetch$1({
440
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
441
+ method: "post",
442
+ ...variables
443
+ });
351
444
  const searchBranch = (variables) => fetch$1({
352
445
  url: "/db/{dbBranchName}/search",
353
446
  method: "post",
@@ -365,11 +458,20 @@ const operationsByTag = {
365
458
  updateWorkspaceMemberRole,
366
459
  removeWorkspaceMember,
367
460
  inviteWorkspaceMember,
461
+ updateWorkspaceMemberInvite,
368
462
  cancelWorkspaceMemberInvite,
369
463
  resendWorkspaceMemberInvite,
370
464
  acceptWorkspaceMemberInvite
371
465
  },
372
- database: { getDatabaseList, createDatabase, deleteDatabase },
466
+ database: {
467
+ getDatabaseList,
468
+ createDatabase,
469
+ deleteDatabase,
470
+ getGitBranchesMapping,
471
+ addGitBranchesEntry,
472
+ removeGitBranchesEntry,
473
+ resolveBranch
474
+ },
373
475
  branch: {
374
476
  getBranchList,
375
477
  getBranchDetails,
@@ -403,6 +505,7 @@ const operationsByTag = {
403
505
  getRecord,
404
506
  bulkInsertTableRecords,
405
507
  queryTable,
508
+ searchTable,
406
509
  searchBranch
407
510
  }
408
511
  };
@@ -432,35 +535,35 @@ function isValidBuilder(builder) {
432
535
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
433
536
  }
434
537
 
435
- var __accessCheck$6 = (obj, member, msg) => {
538
+ var __accessCheck$7 = (obj, member, msg) => {
436
539
  if (!member.has(obj))
437
540
  throw TypeError("Cannot " + msg);
438
541
  };
439
- var __privateGet$5 = (obj, member, getter) => {
440
- __accessCheck$6(obj, member, "read from private field");
542
+ var __privateGet$7 = (obj, member, getter) => {
543
+ __accessCheck$7(obj, member, "read from private field");
441
544
  return getter ? getter.call(obj) : member.get(obj);
442
545
  };
443
- var __privateAdd$6 = (obj, member, value) => {
546
+ var __privateAdd$7 = (obj, member, value) => {
444
547
  if (member.has(obj))
445
548
  throw TypeError("Cannot add the same private member more than once");
446
549
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
447
550
  };
448
- var __privateSet$4 = (obj, member, value, setter) => {
449
- __accessCheck$6(obj, member, "write to private field");
551
+ var __privateSet$7 = (obj, member, value, setter) => {
552
+ __accessCheck$7(obj, member, "write to private field");
450
553
  setter ? setter.call(obj, value) : member.set(obj, value);
451
554
  return value;
452
555
  };
453
556
  var _extraProps, _namespaces;
454
557
  class XataApiClient {
455
558
  constructor(options = {}) {
456
- __privateAdd$6(this, _extraProps, void 0);
457
- __privateAdd$6(this, _namespaces, {});
559
+ __privateAdd$7(this, _extraProps, void 0);
560
+ __privateAdd$7(this, _namespaces, {});
458
561
  const provider = options.host ?? "production";
459
562
  const apiKey = options?.apiKey ?? getAPIKey();
460
563
  if (!apiKey) {
461
564
  throw new Error("Could not resolve a valid apiKey");
462
565
  }
463
- __privateSet$4(this, _extraProps, {
566
+ __privateSet$7(this, _extraProps, {
464
567
  apiUrl: getHostUrl(provider, "main"),
465
568
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
466
569
  fetchImpl: getFetchImplementation(options.fetch),
@@ -468,34 +571,34 @@ class XataApiClient {
468
571
  });
469
572
  }
470
573
  get user() {
471
- if (!__privateGet$5(this, _namespaces).user)
472
- __privateGet$5(this, _namespaces).user = new UserApi(__privateGet$5(this, _extraProps));
473
- return __privateGet$5(this, _namespaces).user;
574
+ if (!__privateGet$7(this, _namespaces).user)
575
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
576
+ return __privateGet$7(this, _namespaces).user;
474
577
  }
475
578
  get workspaces() {
476
- if (!__privateGet$5(this, _namespaces).workspaces)
477
- __privateGet$5(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$5(this, _extraProps));
478
- return __privateGet$5(this, _namespaces).workspaces;
579
+ if (!__privateGet$7(this, _namespaces).workspaces)
580
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
581
+ return __privateGet$7(this, _namespaces).workspaces;
479
582
  }
480
583
  get databases() {
481
- if (!__privateGet$5(this, _namespaces).databases)
482
- __privateGet$5(this, _namespaces).databases = new DatabaseApi(__privateGet$5(this, _extraProps));
483
- return __privateGet$5(this, _namespaces).databases;
584
+ if (!__privateGet$7(this, _namespaces).databases)
585
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
586
+ return __privateGet$7(this, _namespaces).databases;
484
587
  }
485
588
  get branches() {
486
- if (!__privateGet$5(this, _namespaces).branches)
487
- __privateGet$5(this, _namespaces).branches = new BranchApi(__privateGet$5(this, _extraProps));
488
- return __privateGet$5(this, _namespaces).branches;
589
+ if (!__privateGet$7(this, _namespaces).branches)
590
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
591
+ return __privateGet$7(this, _namespaces).branches;
489
592
  }
490
593
  get tables() {
491
- if (!__privateGet$5(this, _namespaces).tables)
492
- __privateGet$5(this, _namespaces).tables = new TableApi(__privateGet$5(this, _extraProps));
493
- return __privateGet$5(this, _namespaces).tables;
594
+ if (!__privateGet$7(this, _namespaces).tables)
595
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
596
+ return __privateGet$7(this, _namespaces).tables;
494
597
  }
495
598
  get records() {
496
- if (!__privateGet$5(this, _namespaces).records)
497
- __privateGet$5(this, _namespaces).records = new RecordsApi(__privateGet$5(this, _extraProps));
498
- return __privateGet$5(this, _namespaces).records;
599
+ if (!__privateGet$7(this, _namespaces).records)
600
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
601
+ return __privateGet$7(this, _namespaces).records;
499
602
  }
500
603
  }
501
604
  _extraProps = new WeakMap();
@@ -587,6 +690,13 @@ class WorkspaceApi {
587
690
  ...this.extraProps
588
691
  });
589
692
  }
693
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
694
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
695
+ pathParams: { workspaceId, inviteId },
696
+ body: { role },
697
+ ...this.extraProps
698
+ });
699
+ }
590
700
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
591
701
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
592
702
  pathParams: { workspaceId, inviteId },
@@ -629,6 +739,33 @@ class DatabaseApi {
629
739
  ...this.extraProps
630
740
  });
631
741
  }
742
+ getGitBranchesMapping(workspace, dbName) {
743
+ return operationsByTag.database.getGitBranchesMapping({
744
+ pathParams: { workspace, dbName },
745
+ ...this.extraProps
746
+ });
747
+ }
748
+ addGitBranchesEntry(workspace, dbName, body) {
749
+ return operationsByTag.database.addGitBranchesEntry({
750
+ pathParams: { workspace, dbName },
751
+ body,
752
+ ...this.extraProps
753
+ });
754
+ }
755
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
756
+ return operationsByTag.database.removeGitBranchesEntry({
757
+ pathParams: { workspace, dbName },
758
+ queryParams: { gitBranch },
759
+ ...this.extraProps
760
+ });
761
+ }
762
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
763
+ return operationsByTag.database.resolveBranch({
764
+ pathParams: { workspace, dbName },
765
+ queryParams: { gitBranch, fallbackBranch },
766
+ ...this.extraProps
767
+ });
768
+ }
632
769
  }
633
770
  class BranchApi {
634
771
  constructor(extraProps) {
@@ -646,10 +783,10 @@ class BranchApi {
646
783
  ...this.extraProps
647
784
  });
648
785
  }
649
- createBranch(workspace, database, branch, from = "", options = {}) {
786
+ createBranch(workspace, database, branch, from, options = {}) {
650
787
  return operationsByTag.branch.createBranch({
651
788
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
652
- queryParams: { from },
789
+ queryParams: isString(from) ? { from } : void 0,
653
790
  body: options,
654
791
  ...this.extraProps
655
792
  });
@@ -774,9 +911,10 @@ class RecordsApi {
774
911
  constructor(extraProps) {
775
912
  this.extraProps = extraProps;
776
913
  }
777
- insertRecord(workspace, database, branch, tableName, record) {
914
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
778
915
  return operationsByTag.records.insertRecord({
779
916
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
917
+ queryParams: options,
780
918
  body: record,
781
919
  ...this.extraProps
782
920
  });
@@ -805,21 +943,24 @@ class RecordsApi {
805
943
  ...this.extraProps
806
944
  });
807
945
  }
808
- deleteRecord(workspace, database, branch, tableName, recordId) {
946
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
809
947
  return operationsByTag.records.deleteRecord({
810
948
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
949
+ queryParams: options,
811
950
  ...this.extraProps
812
951
  });
813
952
  }
814
953
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
815
954
  return operationsByTag.records.getRecord({
816
955
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
956
+ queryParams: options,
817
957
  ...this.extraProps
818
958
  });
819
959
  }
820
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
960
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
821
961
  return operationsByTag.records.bulkInsertTableRecords({
822
962
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
963
+ queryParams: options,
823
964
  body: { records },
824
965
  ...this.extraProps
825
966
  });
@@ -831,6 +972,13 @@ class RecordsApi {
831
972
  ...this.extraProps
832
973
  });
833
974
  }
975
+ searchTable(workspace, database, branch, tableName, query) {
976
+ return operationsByTag.records.searchTable({
977
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
978
+ body: query,
979
+ ...this.extraProps
980
+ });
981
+ }
834
982
  searchBranch(workspace, database, branch, query) {
835
983
  return operationsByTag.records.searchBranch({
836
984
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -850,43 +998,43 @@ class XataApiPlugin {
850
998
  class XataPlugin {
851
999
  }
852
1000
 
853
- var __accessCheck$5 = (obj, member, msg) => {
1001
+ var __accessCheck$6 = (obj, member, msg) => {
854
1002
  if (!member.has(obj))
855
1003
  throw TypeError("Cannot " + msg);
856
1004
  };
857
- var __privateGet$4 = (obj, member, getter) => {
858
- __accessCheck$5(obj, member, "read from private field");
1005
+ var __privateGet$6 = (obj, member, getter) => {
1006
+ __accessCheck$6(obj, member, "read from private field");
859
1007
  return getter ? getter.call(obj) : member.get(obj);
860
1008
  };
861
- var __privateAdd$5 = (obj, member, value) => {
1009
+ var __privateAdd$6 = (obj, member, value) => {
862
1010
  if (member.has(obj))
863
1011
  throw TypeError("Cannot add the same private member more than once");
864
1012
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
865
1013
  };
866
- var __privateSet$3 = (obj, member, value, setter) => {
867
- __accessCheck$5(obj, member, "write to private field");
1014
+ var __privateSet$6 = (obj, member, value, setter) => {
1015
+ __accessCheck$6(obj, member, "write to private field");
868
1016
  setter ? setter.call(obj, value) : member.set(obj, value);
869
1017
  return value;
870
1018
  };
871
- var _query;
1019
+ var _query, _page;
872
1020
  class Page {
873
1021
  constructor(query, meta, records = []) {
874
- __privateAdd$5(this, _query, void 0);
875
- __privateSet$3(this, _query, query);
1022
+ __privateAdd$6(this, _query, void 0);
1023
+ __privateSet$6(this, _query, query);
876
1024
  this.meta = meta;
877
- this.records = records;
1025
+ this.records = new RecordArray(this, records);
878
1026
  }
879
1027
  async nextPage(size, offset) {
880
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1028
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
881
1029
  }
882
1030
  async previousPage(size, offset) {
883
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1031
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
884
1032
  }
885
1033
  async firstPage(size, offset) {
886
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1034
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
887
1035
  }
888
1036
  async lastPage(size, offset) {
889
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1037
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
890
1038
  }
891
1039
  hasNextPage() {
892
1040
  return this.meta.page.more;
@@ -894,50 +1042,99 @@ class Page {
894
1042
  }
895
1043
  _query = new WeakMap();
896
1044
  const PAGINATION_MAX_SIZE = 200;
897
- const PAGINATION_DEFAULT_SIZE = 200;
1045
+ const PAGINATION_DEFAULT_SIZE = 20;
898
1046
  const PAGINATION_MAX_OFFSET = 800;
899
1047
  const PAGINATION_DEFAULT_OFFSET = 0;
1048
+ function isCursorPaginationOptions(options) {
1049
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1050
+ }
1051
+ const _RecordArray = class extends Array {
1052
+ constructor(...args) {
1053
+ super(..._RecordArray.parseConstructorParams(...args));
1054
+ __privateAdd$6(this, _page, void 0);
1055
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1056
+ }
1057
+ static parseConstructorParams(...args) {
1058
+ if (args.length === 1 && typeof args[0] === "number") {
1059
+ return new Array(args[0]);
1060
+ }
1061
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1062
+ const result = args[1] ?? args[0].records ?? [];
1063
+ return new Array(...result);
1064
+ }
1065
+ return new Array(...args);
1066
+ }
1067
+ toArray() {
1068
+ return new Array(...this);
1069
+ }
1070
+ map(callbackfn, thisArg) {
1071
+ return this.toArray().map(callbackfn, thisArg);
1072
+ }
1073
+ async nextPage(size, offset) {
1074
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1075
+ return new _RecordArray(newPage);
1076
+ }
1077
+ async previousPage(size, offset) {
1078
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1079
+ return new _RecordArray(newPage);
1080
+ }
1081
+ async firstPage(size, offset) {
1082
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1083
+ return new _RecordArray(newPage);
1084
+ }
1085
+ async lastPage(size, offset) {
1086
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1087
+ return new _RecordArray(newPage);
1088
+ }
1089
+ hasNextPage() {
1090
+ return __privateGet$6(this, _page).meta.page.more;
1091
+ }
1092
+ };
1093
+ let RecordArray = _RecordArray;
1094
+ _page = new WeakMap();
900
1095
 
901
- var __accessCheck$4 = (obj, member, msg) => {
1096
+ var __accessCheck$5 = (obj, member, msg) => {
902
1097
  if (!member.has(obj))
903
1098
  throw TypeError("Cannot " + msg);
904
1099
  };
905
- var __privateGet$3 = (obj, member, getter) => {
906
- __accessCheck$4(obj, member, "read from private field");
1100
+ var __privateGet$5 = (obj, member, getter) => {
1101
+ __accessCheck$5(obj, member, "read from private field");
907
1102
  return getter ? getter.call(obj) : member.get(obj);
908
1103
  };
909
- var __privateAdd$4 = (obj, member, value) => {
1104
+ var __privateAdd$5 = (obj, member, value) => {
910
1105
  if (member.has(obj))
911
1106
  throw TypeError("Cannot add the same private member more than once");
912
1107
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
913
1108
  };
914
- var __privateSet$2 = (obj, member, value, setter) => {
915
- __accessCheck$4(obj, member, "write to private field");
1109
+ var __privateSet$5 = (obj, member, value, setter) => {
1110
+ __accessCheck$5(obj, member, "write to private field");
916
1111
  setter ? setter.call(obj, value) : member.set(obj, value);
917
1112
  return value;
918
1113
  };
919
1114
  var _table$1, _repository, _data;
920
1115
  const _Query = class {
921
- constructor(repository, table, data, parent) {
922
- __privateAdd$4(this, _table$1, void 0);
923
- __privateAdd$4(this, _repository, void 0);
924
- __privateAdd$4(this, _data, { filter: {} });
1116
+ constructor(repository, table, data, rawParent) {
1117
+ __privateAdd$5(this, _table$1, void 0);
1118
+ __privateAdd$5(this, _repository, void 0);
1119
+ __privateAdd$5(this, _data, { filter: {} });
925
1120
  this.meta = { page: { cursor: "start", more: true } };
926
- this.records = [];
927
- __privateSet$2(this, _table$1, table);
1121
+ this.records = new RecordArray(this, []);
1122
+ __privateSet$5(this, _table$1, table);
928
1123
  if (repository) {
929
- __privateSet$2(this, _repository, repository);
1124
+ __privateSet$5(this, _repository, repository);
930
1125
  } else {
931
- __privateSet$2(this, _repository, this);
1126
+ __privateSet$5(this, _repository, this);
932
1127
  }
933
- __privateGet$3(this, _data).filter = data.filter ?? parent?.filter ?? {};
934
- __privateGet$3(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
935
- __privateGet$3(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
936
- __privateGet$3(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
937
- __privateGet$3(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
938
- __privateGet$3(this, _data).sort = data.sort ?? parent?.sort;
939
- __privateGet$3(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
940
- __privateGet$3(this, _data).page = data.page ?? parent?.page;
1128
+ const parent = cleanParent(data, rawParent);
1129
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1130
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1131
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1132
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1133
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1134
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1135
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1136
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1137
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
941
1138
  this.any = this.any.bind(this);
942
1139
  this.all = this.all.bind(this);
943
1140
  this.not = this.not.bind(this);
@@ -948,75 +1145,93 @@ const _Query = class {
948
1145
  Object.defineProperty(this, "repository", { enumerable: false });
949
1146
  }
950
1147
  getQueryOptions() {
951
- return __privateGet$3(this, _data);
1148
+ return __privateGet$5(this, _data);
1149
+ }
1150
+ key() {
1151
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1152
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1153
+ return toBase64(key);
952
1154
  }
953
1155
  any(...queries) {
954
1156
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
955
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $any } }, __privateGet$3(this, _data));
1157
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
956
1158
  }
957
1159
  all(...queries) {
958
1160
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
959
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1161
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
960
1162
  }
961
1163
  not(...queries) {
962
1164
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
963
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $not } }, __privateGet$3(this, _data));
1165
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
964
1166
  }
965
1167
  none(...queries) {
966
1168
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
967
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $none } }, __privateGet$3(this, _data));
1169
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
968
1170
  }
969
1171
  filter(a, b) {
970
1172
  if (arguments.length === 1) {
971
1173
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
972
- const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat(constraints));
973
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1174
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1175
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
974
1176
  } else {
975
- const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
976
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1177
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1178
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
977
1179
  }
978
1180
  }
979
1181
  sort(column, direction) {
980
- const originalSort = [__privateGet$3(this, _data).sort ?? []].flat();
1182
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
981
1183
  const sort = [...originalSort, { column, direction }];
982
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { sort }, __privateGet$3(this, _data));
1184
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
983
1185
  }
984
1186
  select(columns) {
985
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { columns }, __privateGet$3(this, _data));
1187
+ return new _Query(
1188
+ __privateGet$5(this, _repository),
1189
+ __privateGet$5(this, _table$1),
1190
+ { columns },
1191
+ __privateGet$5(this, _data)
1192
+ );
986
1193
  }
987
1194
  getPaginated(options = {}) {
988
- const query = new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), options, __privateGet$3(this, _data));
989
- return __privateGet$3(this, _repository).query(query);
1195
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1196
+ return __privateGet$5(this, _repository).query(query);
990
1197
  }
991
1198
  async *[Symbol.asyncIterator]() {
992
- for await (const [record] of this.getIterator(1)) {
1199
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
993
1200
  yield record;
994
1201
  }
995
1202
  }
996
- async *getIterator(chunk, options = {}) {
997
- let offset = 0;
998
- let end = false;
999
- while (!end) {
1000
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1001
- yield records;
1002
- offset += chunk;
1003
- end = !meta.page.more;
1203
+ async *getIterator(options = {}) {
1204
+ const { batchSize = 1 } = options;
1205
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1206
+ let more = page.hasNextPage();
1207
+ yield page.records;
1208
+ while (more) {
1209
+ page = await page.nextPage();
1210
+ more = page.hasNextPage();
1211
+ yield page.records;
1004
1212
  }
1005
1213
  }
1006
1214
  async getMany(options = {}) {
1007
- const { records } = await this.getPaginated(options);
1008
- return records;
1215
+ const page = await this.getPaginated(options);
1216
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1217
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1218
+ }
1219
+ return page.records;
1009
1220
  }
1010
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1221
+ async getAll(options = {}) {
1222
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1011
1223
  const results = [];
1012
- for await (const page of this.getIterator(chunk, options)) {
1224
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1013
1225
  results.push(...page);
1014
1226
  }
1015
1227
  return results;
1016
1228
  }
1017
- async getOne(options = {}) {
1018
- const records = await this.getMany({ ...options, page: { size: 1 } });
1019
- return records[0] || null;
1229
+ async getFirst(options = {}) {
1230
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1231
+ return records[0] ?? null;
1232
+ }
1233
+ cache(ttl) {
1234
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1020
1235
  }
1021
1236
  nextPage(size, offset) {
1022
1237
  return this.firstPage(size, offset);
@@ -1025,10 +1240,10 @@ const _Query = class {
1025
1240
  return this.firstPage(size, offset);
1026
1241
  }
1027
1242
  firstPage(size, offset) {
1028
- return this.getPaginated({ page: { size, offset } });
1243
+ return this.getPaginated({ pagination: { size, offset } });
1029
1244
  }
1030
1245
  lastPage(size, offset) {
1031
- return this.getPaginated({ page: { size, offset, before: "end" } });
1246
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1032
1247
  }
1033
1248
  hasNextPage() {
1034
1249
  return this.meta.page.more;
@@ -1038,12 +1253,20 @@ let Query = _Query;
1038
1253
  _table$1 = new WeakMap();
1039
1254
  _repository = new WeakMap();
1040
1255
  _data = new WeakMap();
1256
+ function cleanParent(data, parent) {
1257
+ if (isCursorPaginationOptions(data.pagination)) {
1258
+ return { ...parent, sorting: void 0, filter: void 0 };
1259
+ }
1260
+ return parent;
1261
+ }
1041
1262
 
1042
1263
  function isIdentifiable(x) {
1043
1264
  return isObject(x) && isString(x?.id);
1044
1265
  }
1045
1266
  function isXataRecord(x) {
1046
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1267
+ const record = x;
1268
+ const metadata = record?.getMetadata();
1269
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1047
1270
  }
1048
1271
 
1049
1272
  function isSortFilterString(value) {
@@ -1069,249 +1292,328 @@ function buildSortFilter(filter) {
1069
1292
  }
1070
1293
  }
1071
1294
 
1072
- var __accessCheck$3 = (obj, member, msg) => {
1295
+ var __accessCheck$4 = (obj, member, msg) => {
1073
1296
  if (!member.has(obj))
1074
1297
  throw TypeError("Cannot " + msg);
1075
1298
  };
1076
- var __privateGet$2 = (obj, member, getter) => {
1077
- __accessCheck$3(obj, member, "read from private field");
1299
+ var __privateGet$4 = (obj, member, getter) => {
1300
+ __accessCheck$4(obj, member, "read from private field");
1078
1301
  return getter ? getter.call(obj) : member.get(obj);
1079
1302
  };
1080
- var __privateAdd$3 = (obj, member, value) => {
1303
+ var __privateAdd$4 = (obj, member, value) => {
1081
1304
  if (member.has(obj))
1082
1305
  throw TypeError("Cannot add the same private member more than once");
1083
1306
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1084
1307
  };
1085
- var __privateSet$1 = (obj, member, value, setter) => {
1086
- __accessCheck$3(obj, member, "write to private field");
1308
+ var __privateSet$4 = (obj, member, value, setter) => {
1309
+ __accessCheck$4(obj, member, "write to private field");
1087
1310
  setter ? setter.call(obj, value) : member.set(obj, value);
1088
1311
  return value;
1089
1312
  };
1090
1313
  var __privateMethod$2 = (obj, member, method) => {
1091
- __accessCheck$3(obj, member, "access private method");
1314
+ __accessCheck$4(obj, member, "access private method");
1092
1315
  return method;
1093
1316
  };
1094
- var _table, _links, _getFetchProps, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn;
1317
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _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;
1095
1318
  class Repository extends Query {
1096
1319
  }
1097
1320
  class RestRepository extends Query {
1098
1321
  constructor(options) {
1099
1322
  super(null, options.table, {});
1100
- __privateAdd$3(this, _insertRecordWithoutId);
1101
- __privateAdd$3(this, _insertRecordWithId);
1102
- __privateAdd$3(this, _bulkInsertTableRecords);
1103
- __privateAdd$3(this, _updateRecordWithID);
1104
- __privateAdd$3(this, _upsertRecordWithID);
1105
- __privateAdd$3(this, _deleteRecord);
1106
- __privateAdd$3(this, _table, void 0);
1107
- __privateAdd$3(this, _links, void 0);
1108
- __privateAdd$3(this, _getFetchProps, void 0);
1109
- __privateSet$1(this, _table, options.table);
1110
- __privateSet$1(this, _links, options.links ?? {});
1111
- __privateSet$1(this, _getFetchProps, options.getFetchProps);
1112
- this.db = options.db;
1113
- }
1114
- async create(a, b) {
1323
+ __privateAdd$4(this, _insertRecordWithoutId);
1324
+ __privateAdd$4(this, _insertRecordWithId);
1325
+ __privateAdd$4(this, _bulkInsertTableRecords);
1326
+ __privateAdd$4(this, _updateRecordWithID);
1327
+ __privateAdd$4(this, _upsertRecordWithID);
1328
+ __privateAdd$4(this, _deleteRecord);
1329
+ __privateAdd$4(this, _setCacheQuery);
1330
+ __privateAdd$4(this, _getCacheQuery);
1331
+ __privateAdd$4(this, _getSchemaTables$1);
1332
+ __privateAdd$4(this, _table, void 0);
1333
+ __privateAdd$4(this, _getFetchProps, void 0);
1334
+ __privateAdd$4(this, _db, void 0);
1335
+ __privateAdd$4(this, _cache, void 0);
1336
+ __privateAdd$4(this, _schemaTables$2, void 0);
1337
+ __privateSet$4(this, _table, options.table);
1338
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1339
+ __privateSet$4(this, _db, options.db);
1340
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1341
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1342
+ }
1343
+ async create(a, b, c) {
1115
1344
  if (Array.isArray(a)) {
1116
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1345
+ if (a.length === 0)
1346
+ return [];
1347
+ const columns = isStringArray(b) ? b : void 0;
1348
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1117
1349
  }
1118
1350
  if (isString(a) && isObject(b)) {
1119
1351
  if (a === "")
1120
1352
  throw new Error("The id can't be empty");
1121
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1353
+ const columns = isStringArray(c) ? c : void 0;
1354
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1122
1355
  }
1123
1356
  if (isObject(a) && isString(a.id)) {
1124
1357
  if (a.id === "")
1125
1358
  throw new Error("The id can't be empty");
1126
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1359
+ const columns = isStringArray(b) ? b : void 0;
1360
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1127
1361
  }
1128
1362
  if (isObject(a)) {
1129
- return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1363
+ const columns = isStringArray(b) ? b : void 0;
1364
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1130
1365
  }
1131
1366
  throw new Error("Invalid arguments for create method");
1132
1367
  }
1133
- async read(recordId) {
1134
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1135
- try {
1136
- const response = await getRecord({
1137
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1138
- ...fetchProps
1139
- });
1140
- return initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), response);
1141
- } catch (e) {
1142
- if (isObject(e) && e.status === 404) {
1143
- return null;
1368
+ async read(a, b) {
1369
+ const columns = isStringArray(b) ? b : ["*"];
1370
+ if (Array.isArray(a)) {
1371
+ if (a.length === 0)
1372
+ return [];
1373
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1374
+ const finalObjects = await this.getAll({ filter: { id: { $any: ids } }, columns });
1375
+ const dictionary = finalObjects.reduce((acc, object) => {
1376
+ acc[object.id] = object;
1377
+ return acc;
1378
+ }, {});
1379
+ return ids.map((id2) => dictionary[id2] ?? null);
1380
+ }
1381
+ const id = isString(a) ? a : a.id;
1382
+ if (isString(id)) {
1383
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1384
+ try {
1385
+ const response = await getRecord({
1386
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1387
+ queryParams: { columns },
1388
+ ...fetchProps
1389
+ });
1390
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1391
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1392
+ } catch (e) {
1393
+ if (isObject(e) && e.status === 404) {
1394
+ return null;
1395
+ }
1396
+ throw e;
1144
1397
  }
1145
- throw e;
1146
1398
  }
1399
+ return null;
1147
1400
  }
1148
- async update(a, b) {
1401
+ async update(a, b, c) {
1149
1402
  if (Array.isArray(a)) {
1403
+ if (a.length === 0)
1404
+ return [];
1150
1405
  if (a.length > 100) {
1151
1406
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1152
1407
  }
1153
- return Promise.all(a.map((object) => this.update(object)));
1408
+ const columns = isStringArray(b) ? b : ["*"];
1409
+ return Promise.all(a.map((object) => this.update(object, columns)));
1154
1410
  }
1155
1411
  if (isString(a) && isObject(b)) {
1156
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1412
+ const columns = isStringArray(c) ? c : void 0;
1413
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1157
1414
  }
1158
1415
  if (isObject(a) && isString(a.id)) {
1159
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1416
+ const columns = isStringArray(b) ? b : void 0;
1417
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1160
1418
  }
1161
1419
  throw new Error("Invalid arguments for update method");
1162
1420
  }
1163
- async createOrUpdate(a, b) {
1421
+ async createOrUpdate(a, b, c) {
1164
1422
  if (Array.isArray(a)) {
1423
+ if (a.length === 0)
1424
+ return [];
1165
1425
  if (a.length > 100) {
1166
1426
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1167
1427
  }
1168
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1428
+ const columns = isStringArray(b) ? b : ["*"];
1429
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1169
1430
  }
1170
1431
  if (isString(a) && isObject(b)) {
1171
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1432
+ const columns = isStringArray(c) ? c : void 0;
1433
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1172
1434
  }
1173
1435
  if (isObject(a) && isString(a.id)) {
1174
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1436
+ const columns = isStringArray(c) ? c : void 0;
1437
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1175
1438
  }
1176
1439
  throw new Error("Invalid arguments for createOrUpdate method");
1177
1440
  }
1178
- async delete(recordId) {
1179
- if (Array.isArray(recordId)) {
1180
- if (recordId.length > 100) {
1441
+ async delete(a) {
1442
+ if (Array.isArray(a)) {
1443
+ if (a.length === 0)
1444
+ return;
1445
+ if (a.length > 100) {
1181
1446
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1182
1447
  }
1183
- await Promise.all(recordId.map((id) => this.delete(id)));
1448
+ await Promise.all(a.map((id) => this.delete(id)));
1184
1449
  return;
1185
1450
  }
1186
- if (isString(recordId)) {
1187
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId);
1451
+ if (isString(a)) {
1452
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1188
1453
  return;
1189
1454
  }
1190
- if (isObject(recordId) && isString(recordId.id)) {
1191
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId.id);
1455
+ if (isObject(a) && isString(a.id)) {
1456
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1192
1457
  return;
1193
1458
  }
1194
1459
  throw new Error("Invalid arguments for delete method");
1195
1460
  }
1196
1461
  async search(query, options = {}) {
1197
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1198
- const { records } = await searchBranch({
1199
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1200
- body: { tables: [__privateGet$2(this, _table)], query, fuzziness: options.fuzziness },
1462
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1463
+ const { records } = await searchTable({
1464
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1465
+ body: {
1466
+ query,
1467
+ fuzziness: options.fuzziness,
1468
+ prefix: options.prefix,
1469
+ highlight: options.highlight,
1470
+ filter: options.filter,
1471
+ boosters: options.boosters
1472
+ },
1201
1473
  ...fetchProps
1202
1474
  });
1203
- return records.map((item) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), item));
1475
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1476
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1204
1477
  }
1205
1478
  async query(query) {
1479
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1480
+ if (cacheQuery)
1481
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1206
1482
  const data = query.getQueryOptions();
1207
1483
  const body = {
1208
1484
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1209
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1210
- page: data.page,
1485
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1486
+ page: data.pagination,
1211
1487
  columns: data.columns
1212
1488
  };
1213
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1489
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1214
1490
  const { meta, records: objects } = await queryTable({
1215
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1491
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1216
1492
  body,
1217
1493
  ...fetchProps
1218
1494
  });
1219
- const records = objects.map((record) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), record));
1495
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1496
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1497
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1220
1498
  return new Page(query, meta, records);
1221
1499
  }
1222
1500
  }
1223
1501
  _table = new WeakMap();
1224
- _links = new WeakMap();
1225
1502
  _getFetchProps = new WeakMap();
1503
+ _db = new WeakMap();
1504
+ _cache = new WeakMap();
1505
+ _schemaTables$2 = new WeakMap();
1226
1506
  _insertRecordWithoutId = new WeakSet();
1227
- insertRecordWithoutId_fn = async function(object) {
1228
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1507
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1508
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1229
1509
  const record = transformObjectLinks(object);
1230
1510
  const response = await insertRecord({
1231
1511
  pathParams: {
1232
1512
  workspace: "{workspaceId}",
1233
1513
  dbBranchName: "{dbBranch}",
1234
- tableName: __privateGet$2(this, _table)
1514
+ tableName: __privateGet$4(this, _table)
1235
1515
  },
1516
+ queryParams: { columns },
1236
1517
  body: record,
1237
1518
  ...fetchProps
1238
1519
  });
1239
- const finalObject = await this.read(response.id);
1240
- if (!finalObject) {
1241
- throw new Error("The server failed to save the record");
1242
- }
1243
- return finalObject;
1520
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1521
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1244
1522
  };
1245
1523
  _insertRecordWithId = new WeakSet();
1246
- insertRecordWithId_fn = async function(recordId, object) {
1247
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1524
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1525
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1248
1526
  const record = transformObjectLinks(object);
1249
1527
  const response = await insertRecordWithID({
1250
1528
  pathParams: {
1251
1529
  workspace: "{workspaceId}",
1252
1530
  dbBranchName: "{dbBranch}",
1253
- tableName: __privateGet$2(this, _table),
1531
+ tableName: __privateGet$4(this, _table),
1254
1532
  recordId
1255
1533
  },
1256
1534
  body: record,
1257
- queryParams: { createOnly: true },
1535
+ queryParams: { createOnly: true, columns },
1258
1536
  ...fetchProps
1259
1537
  });
1260
- const finalObject = await this.read(response.id);
1261
- if (!finalObject) {
1262
- throw new Error("The server failed to save the record");
1263
- }
1264
- return finalObject;
1538
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1539
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1265
1540
  };
1266
1541
  _bulkInsertTableRecords = new WeakSet();
1267
- bulkInsertTableRecords_fn = async function(objects) {
1268
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1542
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1543
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1269
1544
  const records = objects.map((object) => transformObjectLinks(object));
1270
1545
  const response = await bulkInsertTableRecords({
1271
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1546
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1547
+ queryParams: { columns },
1272
1548
  body: { records },
1273
1549
  ...fetchProps
1274
1550
  });
1275
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1276
- if (finalObjects.length !== objects.length) {
1277
- throw new Error("The server failed to save some records");
1551
+ if (!isResponseWithRecords(response)) {
1552
+ throw new Error("Request included columns but server didn't include them");
1278
1553
  }
1279
- return finalObjects;
1554
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1555
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1280
1556
  };
1281
1557
  _updateRecordWithID = new WeakSet();
1282
- updateRecordWithID_fn = async function(recordId, object) {
1283
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1558
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1559
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1284
1560
  const record = transformObjectLinks(object);
1285
1561
  const response = await updateRecordWithID({
1286
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1562
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1563
+ queryParams: { columns },
1287
1564
  body: record,
1288
1565
  ...fetchProps
1289
1566
  });
1290
- const item = await this.read(response.id);
1291
- if (!item)
1292
- throw new Error("The server failed to save the record");
1293
- return item;
1567
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1568
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1294
1569
  };
1295
1570
  _upsertRecordWithID = new WeakSet();
1296
- upsertRecordWithID_fn = async function(recordId, object) {
1297
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1571
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1572
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1298
1573
  const response = await upsertRecordWithID({
1299
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1574
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1575
+ queryParams: { columns },
1300
1576
  body: object,
1301
1577
  ...fetchProps
1302
1578
  });
1303
- const item = await this.read(response.id);
1304
- if (!item)
1305
- throw new Error("The server failed to save the record");
1306
- return item;
1579
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1580
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1307
1581
  };
1308
1582
  _deleteRecord = new WeakSet();
1309
1583
  deleteRecord_fn = async function(recordId) {
1310
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1584
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1311
1585
  await deleteRecord({
1312
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1586
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1587
+ ...fetchProps
1588
+ });
1589
+ };
1590
+ _setCacheQuery = new WeakSet();
1591
+ setCacheQuery_fn = async function(query, meta, records) {
1592
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1593
+ };
1594
+ _getCacheQuery = new WeakSet();
1595
+ getCacheQuery_fn = async function(query) {
1596
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1597
+ const result = await __privateGet$4(this, _cache).get(key);
1598
+ if (!result)
1599
+ return null;
1600
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1601
+ if (ttl < 0)
1602
+ return null;
1603
+ const hasExpired = result.date.getTime() + ttl < Date.now();
1604
+ return hasExpired ? null : result;
1605
+ };
1606
+ _getSchemaTables$1 = new WeakSet();
1607
+ getSchemaTables_fn$1 = async function() {
1608
+ if (__privateGet$4(this, _schemaTables$2))
1609
+ return __privateGet$4(this, _schemaTables$2);
1610
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1611
+ const { schema } = await getBranchDetails({
1612
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1313
1613
  ...fetchProps
1314
1614
  });
1615
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1616
+ return schema.tables;
1315
1617
  };
1316
1618
  const transformObjectLinks = (object) => {
1317
1619
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1320,32 +1622,106 @@ const transformObjectLinks = (object) => {
1320
1622
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1321
1623
  }, {});
1322
1624
  };
1323
- const initObject = (db, links, table, object) => {
1625
+ const initObject = (db, schemaTables, table, object) => {
1324
1626
  const result = {};
1325
- Object.assign(result, object);
1326
- const tableLinks = links[table] || [];
1327
- for (const link of tableLinks) {
1328
- const [field, linkTable] = link;
1329
- const value = result[field];
1330
- if (value && isObject(value)) {
1331
- result[field] = initObject(db, links, linkTable, value);
1627
+ const { xata, ...rest } = object ?? {};
1628
+ Object.assign(result, rest);
1629
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1630
+ if (!columns)
1631
+ console.error(`Table ${table} not found in schema`);
1632
+ for (const column of columns ?? []) {
1633
+ const value = result[column.name];
1634
+ switch (column.type) {
1635
+ case "datetime": {
1636
+ const date = value !== void 0 ? new Date(value) : void 0;
1637
+ if (date && isNaN(date.getTime())) {
1638
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1639
+ } else if (date) {
1640
+ result[column.name] = date;
1641
+ }
1642
+ break;
1643
+ }
1644
+ case "link": {
1645
+ const linkTable = column.link?.table;
1646
+ if (!linkTable) {
1647
+ console.error(`Failed to parse link for field ${column.name}`);
1648
+ } else if (isObject(value)) {
1649
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1650
+ }
1651
+ break;
1652
+ }
1332
1653
  }
1333
1654
  }
1334
- result.read = function() {
1335
- return db[table].read(result["id"]);
1655
+ result.read = function(columns2) {
1656
+ return db[table].read(result["id"], columns2);
1336
1657
  };
1337
- result.update = function(data) {
1338
- return db[table].update(result["id"], data);
1658
+ result.update = function(data, columns2) {
1659
+ return db[table].update(result["id"], data, columns2);
1339
1660
  };
1340
1661
  result.delete = function() {
1341
1662
  return db[table].delete(result["id"]);
1342
1663
  };
1343
- for (const prop of ["read", "update", "delete"]) {
1664
+ result.getMetadata = function() {
1665
+ return xata;
1666
+ };
1667
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1344
1668
  Object.defineProperty(result, prop, { enumerable: false });
1345
1669
  }
1346
1670
  Object.freeze(result);
1347
1671
  return result;
1348
1672
  };
1673
+ function isResponseWithRecords(value) {
1674
+ return isObject(value) && Array.isArray(value.records);
1675
+ }
1676
+
1677
+ var __accessCheck$3 = (obj, member, msg) => {
1678
+ if (!member.has(obj))
1679
+ throw TypeError("Cannot " + msg);
1680
+ };
1681
+ var __privateGet$3 = (obj, member, getter) => {
1682
+ __accessCheck$3(obj, member, "read from private field");
1683
+ return getter ? getter.call(obj) : member.get(obj);
1684
+ };
1685
+ var __privateAdd$3 = (obj, member, value) => {
1686
+ if (member.has(obj))
1687
+ throw TypeError("Cannot add the same private member more than once");
1688
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1689
+ };
1690
+ var __privateSet$3 = (obj, member, value, setter) => {
1691
+ __accessCheck$3(obj, member, "write to private field");
1692
+ setter ? setter.call(obj, value) : member.set(obj, value);
1693
+ return value;
1694
+ };
1695
+ var _map;
1696
+ class SimpleCache {
1697
+ constructor(options = {}) {
1698
+ __privateAdd$3(this, _map, void 0);
1699
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1700
+ this.capacity = options.max ?? 500;
1701
+ this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1702
+ }
1703
+ async getAll() {
1704
+ return Object.fromEntries(__privateGet$3(this, _map));
1705
+ }
1706
+ async get(key) {
1707
+ return __privateGet$3(this, _map).get(key) ?? null;
1708
+ }
1709
+ async set(key, value) {
1710
+ await this.delete(key);
1711
+ __privateGet$3(this, _map).set(key, value);
1712
+ if (__privateGet$3(this, _map).size > this.capacity) {
1713
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1714
+ await this.delete(leastRecentlyUsed);
1715
+ }
1716
+ }
1717
+ async delete(key) {
1718
+ __privateGet$3(this, _map).delete(key);
1719
+ }
1720
+ async clear() {
1721
+ return __privateGet$3(this, _map).clear();
1722
+ }
1723
+ }
1724
+ _map = new WeakMap();
1349
1725
 
1350
1726
  const gt = (value) => ({ $gt: value });
1351
1727
  const ge = (value) => ({ $ge: value });
@@ -1370,7 +1746,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1370
1746
  if (!member.has(obj))
1371
1747
  throw TypeError("Cannot " + msg);
1372
1748
  };
1373
- var __privateGet$1 = (obj, member, getter) => {
1749
+ var __privateGet$2 = (obj, member, getter) => {
1374
1750
  __accessCheck$2(obj, member, "read from private field");
1375
1751
  return getter ? getter.call(obj) : member.get(obj);
1376
1752
  };
@@ -1379,130 +1755,177 @@ var __privateAdd$2 = (obj, member, value) => {
1379
1755
  throw TypeError("Cannot add the same private member more than once");
1380
1756
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1381
1757
  };
1382
- var _tables;
1758
+ var __privateSet$2 = (obj, member, value, setter) => {
1759
+ __accessCheck$2(obj, member, "write to private field");
1760
+ setter ? setter.call(obj, value) : member.set(obj, value);
1761
+ return value;
1762
+ };
1763
+ var _tables, _schemaTables$1;
1383
1764
  class SchemaPlugin extends XataPlugin {
1384
- constructor(links, tableNames) {
1765
+ constructor(schemaTables) {
1385
1766
  super();
1386
- this.links = links;
1387
- this.tableNames = tableNames;
1388
1767
  __privateAdd$2(this, _tables, {});
1389
- }
1390
- build(options) {
1391
- const { getFetchProps } = options;
1392
- const links = this.links;
1393
- const db = new Proxy({}, {
1394
- get: (_target, table) => {
1395
- if (!isString(table))
1396
- throw new Error("Invalid table name");
1397
- if (!__privateGet$1(this, _tables)[table])
1398
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, getFetchProps, table, links });
1399
- return __privateGet$1(this, _tables)[table];
1768
+ __privateAdd$2(this, _schemaTables$1, void 0);
1769
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1770
+ }
1771
+ build(pluginOptions) {
1772
+ const db = new Proxy(
1773
+ {},
1774
+ {
1775
+ get: (_target, table) => {
1776
+ if (!isString(table))
1777
+ throw new Error("Invalid table name");
1778
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1779
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1780
+ }
1781
+ return __privateGet$2(this, _tables)[table];
1782
+ }
1400
1783
  }
1401
- });
1402
- for (const table of this.tableNames ?? []) {
1403
- db[table] = new RestRepository({ db, getFetchProps, table, links });
1784
+ );
1785
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1786
+ for (const table of tableNames) {
1787
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1404
1788
  }
1405
1789
  return db;
1406
1790
  }
1407
1791
  }
1408
1792
  _tables = new WeakMap();
1793
+ _schemaTables$1 = new WeakMap();
1409
1794
 
1410
1795
  var __accessCheck$1 = (obj, member, msg) => {
1411
1796
  if (!member.has(obj))
1412
1797
  throw TypeError("Cannot " + msg);
1413
1798
  };
1799
+ var __privateGet$1 = (obj, member, getter) => {
1800
+ __accessCheck$1(obj, member, "read from private field");
1801
+ return getter ? getter.call(obj) : member.get(obj);
1802
+ };
1414
1803
  var __privateAdd$1 = (obj, member, value) => {
1415
1804
  if (member.has(obj))
1416
1805
  throw TypeError("Cannot add the same private member more than once");
1417
1806
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1418
1807
  };
1808
+ var __privateSet$1 = (obj, member, value, setter) => {
1809
+ __accessCheck$1(obj, member, "write to private field");
1810
+ setter ? setter.call(obj, value) : member.set(obj, value);
1811
+ return value;
1812
+ };
1419
1813
  var __privateMethod$1 = (obj, member, method) => {
1420
1814
  __accessCheck$1(obj, member, "access private method");
1421
1815
  return method;
1422
1816
  };
1423
- var _search, search_fn;
1817
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1424
1818
  class SearchPlugin extends XataPlugin {
1425
- constructor(db, links) {
1819
+ constructor(db, schemaTables) {
1426
1820
  super();
1427
1821
  this.db = db;
1428
- this.links = links;
1429
1822
  __privateAdd$1(this, _search);
1823
+ __privateAdd$1(this, _getSchemaTables);
1824
+ __privateAdd$1(this, _schemaTables, void 0);
1825
+ __privateSet$1(this, _schemaTables, schemaTables);
1430
1826
  }
1431
1827
  build({ getFetchProps }) {
1432
1828
  return {
1433
1829
  all: async (query, options = {}) => {
1434
1830
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1831
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1435
1832
  return records.map((record) => {
1436
1833
  const { table = "orphan" } = record.xata;
1437
- return { table, record: initObject(this.db, this.links, table, record) };
1834
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1438
1835
  });
1439
1836
  },
1440
1837
  byTable: async (query, options = {}) => {
1441
1838
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1839
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1442
1840
  return records.reduce((acc, record) => {
1443
1841
  const { table = "orphan" } = record.xata;
1444
1842
  const items = acc[table] ?? [];
1445
- const item = initObject(this.db, this.links, table, record);
1843
+ const item = initObject(this.db, schemaTables, table, record);
1446
1844
  return { ...acc, [table]: [...items, item] };
1447
1845
  }, {});
1448
1846
  }
1449
1847
  };
1450
1848
  }
1451
1849
  }
1850
+ _schemaTables = new WeakMap();
1452
1851
  _search = new WeakSet();
1453
1852
  search_fn = async function(query, options, getFetchProps) {
1454
1853
  const fetchProps = await getFetchProps();
1455
- const { tables, fuzziness } = options ?? {};
1854
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1456
1855
  const { records } = await searchBranch({
1457
1856
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1458
- body: { tables, query, fuzziness },
1857
+ body: { tables, query, fuzziness, prefix, highlight },
1459
1858
  ...fetchProps
1460
1859
  });
1461
1860
  return records;
1462
1861
  };
1862
+ _getSchemaTables = new WeakSet();
1863
+ getSchemaTables_fn = async function(getFetchProps) {
1864
+ if (__privateGet$1(this, _schemaTables))
1865
+ return __privateGet$1(this, _schemaTables);
1866
+ const fetchProps = await getFetchProps();
1867
+ const { schema } = await getBranchDetails({
1868
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1869
+ ...fetchProps
1870
+ });
1871
+ __privateSet$1(this, _schemaTables, schema.tables);
1872
+ return schema.tables;
1873
+ };
1463
1874
 
1464
1875
  const isBranchStrategyBuilder = (strategy) => {
1465
1876
  return typeof strategy === "function";
1466
1877
  };
1467
1878
 
1468
- const envBranchNames = [
1469
- "XATA_BRANCH",
1470
- "VERCEL_GIT_COMMIT_REF",
1471
- "CF_PAGES_BRANCH",
1472
- "BRANCH"
1473
- ];
1474
- const defaultBranch = "main";
1475
1879
  async function getCurrentBranchName(options) {
1476
- const env = await getBranchByEnvVariable();
1477
- if (env)
1478
- return env;
1479
- const branch = await getGitBranch();
1480
- if (!branch)
1481
- return defaultBranch;
1482
- const details = await getDatabaseBranch(branch, options);
1483
- if (details)
1484
- return branch;
1485
- return defaultBranch;
1880
+ const { branch, envBranch } = getEnvironment();
1881
+ if (branch) {
1882
+ const details = await getDatabaseBranch(branch, options);
1883
+ if (details)
1884
+ return branch;
1885
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1886
+ }
1887
+ const gitBranch = envBranch || await getGitBranch();
1888
+ return resolveXataBranch(gitBranch, options);
1486
1889
  }
1487
1890
  async function getCurrentBranchDetails(options) {
1488
- const env = await getBranchByEnvVariable();
1489
- if (env)
1490
- return getDatabaseBranch(env, options);
1491
- const branch = await getGitBranch();
1492
- if (!branch)
1493
- return getDatabaseBranch(defaultBranch, options);
1494
- const details = await getDatabaseBranch(branch, options);
1495
- if (details)
1496
- return details;
1497
- return getDatabaseBranch(defaultBranch, options);
1891
+ const branch = await getCurrentBranchName(options);
1892
+ return getDatabaseBranch(branch, options);
1893
+ }
1894
+ async function resolveXataBranch(gitBranch, options) {
1895
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1896
+ const apiKey = options?.apiKey || getAPIKey();
1897
+ if (!databaseURL)
1898
+ throw new Error(
1899
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
1900
+ );
1901
+ if (!apiKey)
1902
+ throw new Error(
1903
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
1904
+ );
1905
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1906
+ const [workspace] = host.split(".");
1907
+ const { fallbackBranch } = getEnvironment();
1908
+ const { branch } = await resolveBranch({
1909
+ apiKey,
1910
+ apiUrl: databaseURL,
1911
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1912
+ workspacesApiUrl: `${protocol}//${host}`,
1913
+ pathParams: { dbName, workspace },
1914
+ queryParams: { gitBranch, fallbackBranch }
1915
+ });
1916
+ return branch;
1498
1917
  }
1499
1918
  async function getDatabaseBranch(branch, options) {
1500
1919
  const databaseURL = options?.databaseURL || getDatabaseURL();
1501
1920
  const apiKey = options?.apiKey || getAPIKey();
1502
1921
  if (!databaseURL)
1503
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1922
+ throw new Error(
1923
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
1924
+ );
1504
1925
  if (!apiKey)
1505
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1926
+ throw new Error(
1927
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
1928
+ );
1506
1929
  const [protocol, , host, , database] = databaseURL.split("/");
1507
1930
  const [workspace] = host.split(".");
1508
1931
  const dbBranchName = `${database}:${branch}`;
@@ -1512,10 +1935,7 @@ async function getDatabaseBranch(branch, options) {
1512
1935
  apiUrl: databaseURL,
1513
1936
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1514
1937
  workspacesApiUrl: `${protocol}//${host}`,
1515
- pathParams: {
1516
- dbBranchName,
1517
- workspace
1518
- }
1938
+ pathParams: { dbBranchName, workspace }
1519
1939
  });
1520
1940
  } catch (err) {
1521
1941
  if (isObject(err) && err.status === 404)
@@ -1523,21 +1943,10 @@ async function getDatabaseBranch(branch, options) {
1523
1943
  throw err;
1524
1944
  }
1525
1945
  }
1526
- function getBranchByEnvVariable() {
1527
- for (const name of envBranchNames) {
1528
- const value = getEnvVariable(name);
1529
- if (value) {
1530
- return value;
1531
- }
1532
- }
1533
- try {
1534
- return XATA_BRANCH;
1535
- } catch (err) {
1536
- }
1537
- }
1538
1946
  function getDatabaseURL() {
1539
1947
  try {
1540
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1948
+ const { databaseURL } = getEnvironment();
1949
+ return databaseURL;
1541
1950
  } catch (err) {
1542
1951
  return void 0;
1543
1952
  }
@@ -1566,24 +1975,28 @@ var __privateMethod = (obj, member, method) => {
1566
1975
  return method;
1567
1976
  };
1568
1977
  const buildClient = (plugins) => {
1569
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1978
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1570
1979
  return _a = class {
1571
- constructor(options = {}, links, tables) {
1980
+ constructor(options = {}, schemaTables) {
1572
1981
  __privateAdd(this, _parseOptions);
1573
1982
  __privateAdd(this, _getFetchProps);
1574
1983
  __privateAdd(this, _evaluateBranch);
1575
1984
  __privateAdd(this, _branch, void 0);
1985
+ __privateAdd(this, _options, void 0);
1576
1986
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
1577
- const db = new SchemaPlugin(links, tables).build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
1578
- const search = new SearchPlugin(db, links ?? {}).build({
1579
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions)
1580
- });
1987
+ __privateSet(this, _options, safeOptions);
1988
+ const pluginOptions = {
1989
+ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1990
+ cache: safeOptions.cache
1991
+ };
1992
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
1993
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1581
1994
  this.db = db;
1582
1995
  this.search = search;
1583
1996
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1584
- if (!namespace)
1997
+ if (namespace === void 0)
1585
1998
  continue;
1586
- const result = namespace.build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
1999
+ const result = namespace.build(pluginOptions);
1587
2000
  if (result instanceof Promise) {
1588
2001
  void result.then((namespace2) => {
1589
2002
  this[key] = namespace2;
@@ -1593,21 +2006,22 @@ const buildClient = (plugins) => {
1593
2006
  }
1594
2007
  }
1595
2008
  }
1596
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2009
+ async getConfig() {
2010
+ const databaseURL = __privateGet(this, _options).databaseURL;
2011
+ const branch = await __privateGet(this, _options).branch();
2012
+ return { databaseURL, branch };
2013
+ }
2014
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1597
2015
  const fetch = getFetchImplementation(options?.fetch);
1598
2016
  const databaseURL = options?.databaseURL || getDatabaseURL();
1599
2017
  const apiKey = options?.apiKey || getAPIKey();
1600
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2018
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2019
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1601
2020
  if (!databaseURL || !apiKey) {
1602
2021
  throw new Error("Options databaseURL and apiKey are required");
1603
2022
  }
1604
- return { fetch, databaseURL, apiKey, branch };
1605
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1606
- fetch,
1607
- apiKey,
1608
- databaseURL,
1609
- branch
1610
- }) {
2023
+ return { fetch, databaseURL, apiKey, branch, cache };
2024
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch }) {
1611
2025
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1612
2026
  if (!branchValue)
1613
2027
  throw new Error("Unable to resolve branch value");
@@ -1624,7 +2038,7 @@ const buildClient = (plugins) => {
1624
2038
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1625
2039
  if (__privateGet(this, _branch))
1626
2040
  return __privateGet(this, _branch);
1627
- if (!param)
2041
+ if (param === void 0)
1628
2042
  return void 0;
1629
2043
  const strategies = Array.isArray(param) ? [...param] : [param];
1630
2044
  const evaluateBranch = async (strategy) => {
@@ -1649,5 +2063,5 @@ class XataError extends Error {
1649
2063
  }
1650
2064
  }
1651
2065
 
1652
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeWorkspaceMember, resendWorkspaceMemberInvite, searchBranch, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2066
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
1653
2067
  //# sourceMappingURL=index.mjs.map