@xata.io/client 0.0.0-alpha.vf231460 → 0.0.0-alpha.vf28813b

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.vf28813b";
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,25 @@ 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 getDatabaseMetadata = (variables) => fetch$1({
333
+ url: "/dbs/{dbName}/metadata",
246
334
  method: "get",
247
335
  ...variables
248
336
  });
249
- const createBranch = (variables) => fetch$1({
337
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
338
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
339
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
340
+ const resolveBranch = (variables) => fetch$1({
341
+ url: "/dbs/{dbName}/resolveBranch",
342
+ method: "get",
343
+ ...variables
344
+ });
345
+ const getBranchDetails = (variables) => fetch$1({
250
346
  url: "/db/{dbBranchName}",
251
- method: "put",
347
+ method: "get",
252
348
  ...variables
253
349
  });
350
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
254
351
  const deleteBranch = (variables) => fetch$1({
255
352
  url: "/db/{dbBranchName}",
256
353
  method: "delete",
@@ -324,11 +421,7 @@ const updateColumn = (variables) => fetch$1({
324
421
  method: "patch",
325
422
  ...variables
326
423
  });
327
- const insertRecord = (variables) => fetch$1({
328
- url: "/db/{dbBranchName}/tables/{tableName}/data",
329
- method: "post",
330
- ...variables
331
- });
424
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
332
425
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
333
426
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
334
427
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -348,6 +441,11 @@ const queryTable = (variables) => fetch$1({
348
441
  method: "post",
349
442
  ...variables
350
443
  });
444
+ const searchTable = (variables) => fetch$1({
445
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
446
+ method: "post",
447
+ ...variables
448
+ });
351
449
  const searchBranch = (variables) => fetch$1({
352
450
  url: "/db/{dbBranchName}/search",
353
451
  method: "post",
@@ -365,13 +463,23 @@ const operationsByTag = {
365
463
  updateWorkspaceMemberRole,
366
464
  removeWorkspaceMember,
367
465
  inviteWorkspaceMember,
466
+ updateWorkspaceMemberInvite,
368
467
  cancelWorkspaceMemberInvite,
369
468
  resendWorkspaceMemberInvite,
370
469
  acceptWorkspaceMemberInvite
371
470
  },
372
- database: { getDatabaseList, createDatabase, deleteDatabase },
471
+ database: {
472
+ getDatabaseList,
473
+ createDatabase,
474
+ deleteDatabase,
475
+ getGitBranchesMapping,
476
+ addGitBranchesEntry,
477
+ removeGitBranchesEntry,
478
+ resolveBranch
479
+ },
373
480
  branch: {
374
481
  getBranchList,
482
+ getDatabaseMetadata,
375
483
  getBranchDetails,
376
484
  createBranch,
377
485
  deleteBranch,
@@ -403,6 +511,7 @@ const operationsByTag = {
403
511
  getRecord,
404
512
  bulkInsertTableRecords,
405
513
  queryTable,
514
+ searchTable,
406
515
  searchBranch
407
516
  }
408
517
  };
@@ -432,35 +541,35 @@ function isValidBuilder(builder) {
432
541
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
433
542
  }
434
543
 
435
- var __accessCheck$6 = (obj, member, msg) => {
544
+ var __accessCheck$7 = (obj, member, msg) => {
436
545
  if (!member.has(obj))
437
546
  throw TypeError("Cannot " + msg);
438
547
  };
439
- var __privateGet$5 = (obj, member, getter) => {
440
- __accessCheck$6(obj, member, "read from private field");
548
+ var __privateGet$7 = (obj, member, getter) => {
549
+ __accessCheck$7(obj, member, "read from private field");
441
550
  return getter ? getter.call(obj) : member.get(obj);
442
551
  };
443
- var __privateAdd$6 = (obj, member, value) => {
552
+ var __privateAdd$7 = (obj, member, value) => {
444
553
  if (member.has(obj))
445
554
  throw TypeError("Cannot add the same private member more than once");
446
555
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
447
556
  };
448
- var __privateSet$4 = (obj, member, value, setter) => {
449
- __accessCheck$6(obj, member, "write to private field");
557
+ var __privateSet$7 = (obj, member, value, setter) => {
558
+ __accessCheck$7(obj, member, "write to private field");
450
559
  setter ? setter.call(obj, value) : member.set(obj, value);
451
560
  return value;
452
561
  };
453
562
  var _extraProps, _namespaces;
454
563
  class XataApiClient {
455
564
  constructor(options = {}) {
456
- __privateAdd$6(this, _extraProps, void 0);
457
- __privateAdd$6(this, _namespaces, {});
565
+ __privateAdd$7(this, _extraProps, void 0);
566
+ __privateAdd$7(this, _namespaces, {});
458
567
  const provider = options.host ?? "production";
459
568
  const apiKey = options?.apiKey ?? getAPIKey();
460
569
  if (!apiKey) {
461
570
  throw new Error("Could not resolve a valid apiKey");
462
571
  }
463
- __privateSet$4(this, _extraProps, {
572
+ __privateSet$7(this, _extraProps, {
464
573
  apiUrl: getHostUrl(provider, "main"),
465
574
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
466
575
  fetchImpl: getFetchImplementation(options.fetch),
@@ -468,34 +577,34 @@ class XataApiClient {
468
577
  });
469
578
  }
470
579
  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;
580
+ if (!__privateGet$7(this, _namespaces).user)
581
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
582
+ return __privateGet$7(this, _namespaces).user;
474
583
  }
475
584
  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;
585
+ if (!__privateGet$7(this, _namespaces).workspaces)
586
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
587
+ return __privateGet$7(this, _namespaces).workspaces;
479
588
  }
480
589
  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;
590
+ if (!__privateGet$7(this, _namespaces).databases)
591
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
592
+ return __privateGet$7(this, _namespaces).databases;
484
593
  }
485
594
  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;
595
+ if (!__privateGet$7(this, _namespaces).branches)
596
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
597
+ return __privateGet$7(this, _namespaces).branches;
489
598
  }
490
599
  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;
600
+ if (!__privateGet$7(this, _namespaces).tables)
601
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
602
+ return __privateGet$7(this, _namespaces).tables;
494
603
  }
495
604
  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;
605
+ if (!__privateGet$7(this, _namespaces).records)
606
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
607
+ return __privateGet$7(this, _namespaces).records;
499
608
  }
500
609
  }
501
610
  _extraProps = new WeakMap();
@@ -587,6 +696,13 @@ class WorkspaceApi {
587
696
  ...this.extraProps
588
697
  });
589
698
  }
699
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
700
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
701
+ pathParams: { workspaceId, inviteId },
702
+ body: { role },
703
+ ...this.extraProps
704
+ });
705
+ }
590
706
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
591
707
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
592
708
  pathParams: { workspaceId, inviteId },
@@ -629,6 +745,33 @@ class DatabaseApi {
629
745
  ...this.extraProps
630
746
  });
631
747
  }
748
+ getGitBranchesMapping(workspace, dbName) {
749
+ return operationsByTag.database.getGitBranchesMapping({
750
+ pathParams: { workspace, dbName },
751
+ ...this.extraProps
752
+ });
753
+ }
754
+ addGitBranchesEntry(workspace, dbName, body) {
755
+ return operationsByTag.database.addGitBranchesEntry({
756
+ pathParams: { workspace, dbName },
757
+ body,
758
+ ...this.extraProps
759
+ });
760
+ }
761
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
762
+ return operationsByTag.database.removeGitBranchesEntry({
763
+ pathParams: { workspace, dbName },
764
+ queryParams: { gitBranch },
765
+ ...this.extraProps
766
+ });
767
+ }
768
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
769
+ return operationsByTag.database.resolveBranch({
770
+ pathParams: { workspace, dbName },
771
+ queryParams: { gitBranch, fallbackBranch },
772
+ ...this.extraProps
773
+ });
774
+ }
632
775
  }
633
776
  class BranchApi {
634
777
  constructor(extraProps) {
@@ -646,10 +789,10 @@ class BranchApi {
646
789
  ...this.extraProps
647
790
  });
648
791
  }
649
- createBranch(workspace, database, branch, from = "", options = {}) {
792
+ createBranch(workspace, database, branch, from, options = {}) {
650
793
  return operationsByTag.branch.createBranch({
651
794
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
652
- queryParams: { from },
795
+ queryParams: isString(from) ? { from } : void 0,
653
796
  body: options,
654
797
  ...this.extraProps
655
798
  });
@@ -774,9 +917,10 @@ class RecordsApi {
774
917
  constructor(extraProps) {
775
918
  this.extraProps = extraProps;
776
919
  }
777
- insertRecord(workspace, database, branch, tableName, record) {
920
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
778
921
  return operationsByTag.records.insertRecord({
779
922
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
923
+ queryParams: options,
780
924
  body: record,
781
925
  ...this.extraProps
782
926
  });
@@ -805,21 +949,24 @@ class RecordsApi {
805
949
  ...this.extraProps
806
950
  });
807
951
  }
808
- deleteRecord(workspace, database, branch, tableName, recordId) {
952
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
809
953
  return operationsByTag.records.deleteRecord({
810
954
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
955
+ queryParams: options,
811
956
  ...this.extraProps
812
957
  });
813
958
  }
814
959
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
815
960
  return operationsByTag.records.getRecord({
816
961
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
962
+ queryParams: options,
817
963
  ...this.extraProps
818
964
  });
819
965
  }
820
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
966
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
821
967
  return operationsByTag.records.bulkInsertTableRecords({
822
968
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
969
+ queryParams: options,
823
970
  body: { records },
824
971
  ...this.extraProps
825
972
  });
@@ -831,6 +978,13 @@ class RecordsApi {
831
978
  ...this.extraProps
832
979
  });
833
980
  }
981
+ searchTable(workspace, database, branch, tableName, query) {
982
+ return operationsByTag.records.searchTable({
983
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
984
+ body: query,
985
+ ...this.extraProps
986
+ });
987
+ }
834
988
  searchBranch(workspace, database, branch, query) {
835
989
  return operationsByTag.records.searchBranch({
836
990
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -850,43 +1004,43 @@ class XataApiPlugin {
850
1004
  class XataPlugin {
851
1005
  }
852
1006
 
853
- var __accessCheck$5 = (obj, member, msg) => {
1007
+ var __accessCheck$6 = (obj, member, msg) => {
854
1008
  if (!member.has(obj))
855
1009
  throw TypeError("Cannot " + msg);
856
1010
  };
857
- var __privateGet$4 = (obj, member, getter) => {
858
- __accessCheck$5(obj, member, "read from private field");
1011
+ var __privateGet$6 = (obj, member, getter) => {
1012
+ __accessCheck$6(obj, member, "read from private field");
859
1013
  return getter ? getter.call(obj) : member.get(obj);
860
1014
  };
861
- var __privateAdd$5 = (obj, member, value) => {
1015
+ var __privateAdd$6 = (obj, member, value) => {
862
1016
  if (member.has(obj))
863
1017
  throw TypeError("Cannot add the same private member more than once");
864
1018
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
865
1019
  };
866
- var __privateSet$3 = (obj, member, value, setter) => {
867
- __accessCheck$5(obj, member, "write to private field");
1020
+ var __privateSet$6 = (obj, member, value, setter) => {
1021
+ __accessCheck$6(obj, member, "write to private field");
868
1022
  setter ? setter.call(obj, value) : member.set(obj, value);
869
1023
  return value;
870
1024
  };
871
- var _query;
1025
+ var _query, _page;
872
1026
  class Page {
873
1027
  constructor(query, meta, records = []) {
874
- __privateAdd$5(this, _query, void 0);
875
- __privateSet$3(this, _query, query);
1028
+ __privateAdd$6(this, _query, void 0);
1029
+ __privateSet$6(this, _query, query);
876
1030
  this.meta = meta;
877
- this.records = records;
1031
+ this.records = new RecordArray(this, records);
878
1032
  }
879
1033
  async nextPage(size, offset) {
880
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1034
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
881
1035
  }
882
1036
  async previousPage(size, offset) {
883
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1037
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
884
1038
  }
885
1039
  async firstPage(size, offset) {
886
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1040
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
887
1041
  }
888
1042
  async lastPage(size, offset) {
889
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1043
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
890
1044
  }
891
1045
  hasNextPage() {
892
1046
  return this.meta.page.more;
@@ -894,50 +1048,99 @@ class Page {
894
1048
  }
895
1049
  _query = new WeakMap();
896
1050
  const PAGINATION_MAX_SIZE = 200;
897
- const PAGINATION_DEFAULT_SIZE = 200;
1051
+ const PAGINATION_DEFAULT_SIZE = 20;
898
1052
  const PAGINATION_MAX_OFFSET = 800;
899
1053
  const PAGINATION_DEFAULT_OFFSET = 0;
1054
+ function isCursorPaginationOptions(options) {
1055
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1056
+ }
1057
+ const _RecordArray = class extends Array {
1058
+ constructor(...args) {
1059
+ super(..._RecordArray.parseConstructorParams(...args));
1060
+ __privateAdd$6(this, _page, void 0);
1061
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1062
+ }
1063
+ static parseConstructorParams(...args) {
1064
+ if (args.length === 1 && typeof args[0] === "number") {
1065
+ return new Array(args[0]);
1066
+ }
1067
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1068
+ const result = args[1] ?? args[0].records ?? [];
1069
+ return new Array(...result);
1070
+ }
1071
+ return new Array(...args);
1072
+ }
1073
+ toArray() {
1074
+ return new Array(...this);
1075
+ }
1076
+ map(callbackfn, thisArg) {
1077
+ return this.toArray().map(callbackfn, thisArg);
1078
+ }
1079
+ async nextPage(size, offset) {
1080
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1081
+ return new _RecordArray(newPage);
1082
+ }
1083
+ async previousPage(size, offset) {
1084
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1085
+ return new _RecordArray(newPage);
1086
+ }
1087
+ async firstPage(size, offset) {
1088
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1089
+ return new _RecordArray(newPage);
1090
+ }
1091
+ async lastPage(size, offset) {
1092
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1093
+ return new _RecordArray(newPage);
1094
+ }
1095
+ hasNextPage() {
1096
+ return __privateGet$6(this, _page).meta.page.more;
1097
+ }
1098
+ };
1099
+ let RecordArray = _RecordArray;
1100
+ _page = new WeakMap();
900
1101
 
901
- var __accessCheck$4 = (obj, member, msg) => {
1102
+ var __accessCheck$5 = (obj, member, msg) => {
902
1103
  if (!member.has(obj))
903
1104
  throw TypeError("Cannot " + msg);
904
1105
  };
905
- var __privateGet$3 = (obj, member, getter) => {
906
- __accessCheck$4(obj, member, "read from private field");
1106
+ var __privateGet$5 = (obj, member, getter) => {
1107
+ __accessCheck$5(obj, member, "read from private field");
907
1108
  return getter ? getter.call(obj) : member.get(obj);
908
1109
  };
909
- var __privateAdd$4 = (obj, member, value) => {
1110
+ var __privateAdd$5 = (obj, member, value) => {
910
1111
  if (member.has(obj))
911
1112
  throw TypeError("Cannot add the same private member more than once");
912
1113
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
913
1114
  };
914
- var __privateSet$2 = (obj, member, value, setter) => {
915
- __accessCheck$4(obj, member, "write to private field");
1115
+ var __privateSet$5 = (obj, member, value, setter) => {
1116
+ __accessCheck$5(obj, member, "write to private field");
916
1117
  setter ? setter.call(obj, value) : member.set(obj, value);
917
1118
  return value;
918
1119
  };
919
1120
  var _table$1, _repository, _data;
920
1121
  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: {} });
1122
+ constructor(repository, table, data, rawParent) {
1123
+ __privateAdd$5(this, _table$1, void 0);
1124
+ __privateAdd$5(this, _repository, void 0);
1125
+ __privateAdd$5(this, _data, { filter: {} });
925
1126
  this.meta = { page: { cursor: "start", more: true } };
926
- this.records = [];
927
- __privateSet$2(this, _table$1, table);
1127
+ this.records = new RecordArray(this, []);
1128
+ __privateSet$5(this, _table$1, table);
928
1129
  if (repository) {
929
- __privateSet$2(this, _repository, repository);
1130
+ __privateSet$5(this, _repository, repository);
930
1131
  } else {
931
- __privateSet$2(this, _repository, this);
1132
+ __privateSet$5(this, _repository, this);
932
1133
  }
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;
1134
+ const parent = cleanParent(data, rawParent);
1135
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1136
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1137
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1138
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1139
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1140
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1141
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1142
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1143
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
941
1144
  this.any = this.any.bind(this);
942
1145
  this.all = this.all.bind(this);
943
1146
  this.not = this.not.bind(this);
@@ -948,75 +1151,93 @@ const _Query = class {
948
1151
  Object.defineProperty(this, "repository", { enumerable: false });
949
1152
  }
950
1153
  getQueryOptions() {
951
- return __privateGet$3(this, _data);
1154
+ return __privateGet$5(this, _data);
1155
+ }
1156
+ key() {
1157
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1158
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1159
+ return toBase64(key);
952
1160
  }
953
1161
  any(...queries) {
954
1162
  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));
1163
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
956
1164
  }
957
1165
  all(...queries) {
958
1166
  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));
1167
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
960
1168
  }
961
1169
  not(...queries) {
962
1170
  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));
1171
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
964
1172
  }
965
1173
  none(...queries) {
966
1174
  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));
1175
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
968
1176
  }
969
1177
  filter(a, b) {
970
1178
  if (arguments.length === 1) {
971
1179
  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));
1180
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1181
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
974
1182
  } 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));
1183
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1184
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
977
1185
  }
978
1186
  }
979
1187
  sort(column, direction) {
980
- const originalSort = [__privateGet$3(this, _data).sort ?? []].flat();
1188
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
981
1189
  const sort = [...originalSort, { column, direction }];
982
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { sort }, __privateGet$3(this, _data));
1190
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
983
1191
  }
984
1192
  select(columns) {
985
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { columns }, __privateGet$3(this, _data));
1193
+ return new _Query(
1194
+ __privateGet$5(this, _repository),
1195
+ __privateGet$5(this, _table$1),
1196
+ { columns },
1197
+ __privateGet$5(this, _data)
1198
+ );
986
1199
  }
987
1200
  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);
1201
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1202
+ return __privateGet$5(this, _repository).query(query);
990
1203
  }
991
1204
  async *[Symbol.asyncIterator]() {
992
- for await (const [record] of this.getIterator(1)) {
1205
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
993
1206
  yield record;
994
1207
  }
995
1208
  }
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;
1209
+ async *getIterator(options = {}) {
1210
+ const { batchSize = 1 } = options;
1211
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1212
+ let more = page.hasNextPage();
1213
+ yield page.records;
1214
+ while (more) {
1215
+ page = await page.nextPage();
1216
+ more = page.hasNextPage();
1217
+ yield page.records;
1004
1218
  }
1005
1219
  }
1006
1220
  async getMany(options = {}) {
1007
- const { records } = await this.getPaginated(options);
1008
- return records;
1221
+ const page = await this.getPaginated(options);
1222
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1223
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1224
+ }
1225
+ return page.records;
1009
1226
  }
1010
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1227
+ async getAll(options = {}) {
1228
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1011
1229
  const results = [];
1012
- for await (const page of this.getIterator(chunk, options)) {
1230
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1013
1231
  results.push(...page);
1014
1232
  }
1015
1233
  return results;
1016
1234
  }
1017
- async getOne(options = {}) {
1018
- const records = await this.getMany({ ...options, page: { size: 1 } });
1019
- return records[0] || null;
1235
+ async getFirst(options = {}) {
1236
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1237
+ return records[0] ?? null;
1238
+ }
1239
+ cache(ttl) {
1240
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1020
1241
  }
1021
1242
  nextPage(size, offset) {
1022
1243
  return this.firstPage(size, offset);
@@ -1025,10 +1246,10 @@ const _Query = class {
1025
1246
  return this.firstPage(size, offset);
1026
1247
  }
1027
1248
  firstPage(size, offset) {
1028
- return this.getPaginated({ page: { size, offset } });
1249
+ return this.getPaginated({ pagination: { size, offset } });
1029
1250
  }
1030
1251
  lastPage(size, offset) {
1031
- return this.getPaginated({ page: { size, offset, before: "end" } });
1252
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1032
1253
  }
1033
1254
  hasNextPage() {
1034
1255
  return this.meta.page.more;
@@ -1038,12 +1259,20 @@ let Query = _Query;
1038
1259
  _table$1 = new WeakMap();
1039
1260
  _repository = new WeakMap();
1040
1261
  _data = new WeakMap();
1262
+ function cleanParent(data, parent) {
1263
+ if (isCursorPaginationOptions(data.pagination)) {
1264
+ return { ...parent, sorting: void 0, filter: void 0 };
1265
+ }
1266
+ return parent;
1267
+ }
1041
1268
 
1042
1269
  function isIdentifiable(x) {
1043
1270
  return isObject(x) && isString(x?.id);
1044
1271
  }
1045
1272
  function isXataRecord(x) {
1046
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1273
+ const record = x;
1274
+ const metadata = record?.getMetadata();
1275
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1047
1276
  }
1048
1277
 
1049
1278
  function isSortFilterString(value) {
@@ -1069,249 +1298,326 @@ function buildSortFilter(filter) {
1069
1298
  }
1070
1299
  }
1071
1300
 
1072
- var __accessCheck$3 = (obj, member, msg) => {
1301
+ var __accessCheck$4 = (obj, member, msg) => {
1073
1302
  if (!member.has(obj))
1074
1303
  throw TypeError("Cannot " + msg);
1075
1304
  };
1076
- var __privateGet$2 = (obj, member, getter) => {
1077
- __accessCheck$3(obj, member, "read from private field");
1305
+ var __privateGet$4 = (obj, member, getter) => {
1306
+ __accessCheck$4(obj, member, "read from private field");
1078
1307
  return getter ? getter.call(obj) : member.get(obj);
1079
1308
  };
1080
- var __privateAdd$3 = (obj, member, value) => {
1309
+ var __privateAdd$4 = (obj, member, value) => {
1081
1310
  if (member.has(obj))
1082
1311
  throw TypeError("Cannot add the same private member more than once");
1083
1312
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1084
1313
  };
1085
- var __privateSet$1 = (obj, member, value, setter) => {
1086
- __accessCheck$3(obj, member, "write to private field");
1314
+ var __privateSet$4 = (obj, member, value, setter) => {
1315
+ __accessCheck$4(obj, member, "write to private field");
1087
1316
  setter ? setter.call(obj, value) : member.set(obj, value);
1088
1317
  return value;
1089
1318
  };
1090
1319
  var __privateMethod$2 = (obj, member, method) => {
1091
- __accessCheck$3(obj, member, "access private method");
1320
+ __accessCheck$4(obj, member, "access private method");
1092
1321
  return method;
1093
1322
  };
1094
- var _table, _links, _getFetchProps, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn;
1323
+ var _table, _getFetchProps, _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
1324
  class Repository extends Query {
1096
1325
  }
1097
1326
  class RestRepository extends Query {
1098
1327
  constructor(options) {
1099
1328
  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);
1329
+ __privateAdd$4(this, _insertRecordWithoutId);
1330
+ __privateAdd$4(this, _insertRecordWithId);
1331
+ __privateAdd$4(this, _bulkInsertTableRecords);
1332
+ __privateAdd$4(this, _updateRecordWithID);
1333
+ __privateAdd$4(this, _upsertRecordWithID);
1334
+ __privateAdd$4(this, _deleteRecord);
1335
+ __privateAdd$4(this, _setCacheQuery);
1336
+ __privateAdd$4(this, _getCacheQuery);
1337
+ __privateAdd$4(this, _getSchemaTables$1);
1338
+ __privateAdd$4(this, _table, void 0);
1339
+ __privateAdd$4(this, _getFetchProps, void 0);
1340
+ __privateAdd$4(this, _cache, void 0);
1341
+ __privateAdd$4(this, _schemaTables$2, void 0);
1342
+ __privateSet$4(this, _table, options.table);
1343
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1112
1344
  this.db = options.db;
1345
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1346
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1113
1347
  }
1114
- async create(a, b) {
1348
+ async create(a, b, c) {
1115
1349
  if (Array.isArray(a)) {
1116
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1350
+ if (a.length === 0)
1351
+ return [];
1352
+ const columns = isStringArray(b) ? b : void 0;
1353
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1117
1354
  }
1118
1355
  if (isString(a) && isObject(b)) {
1119
1356
  if (a === "")
1120
1357
  throw new Error("The id can't be empty");
1121
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1358
+ const columns = isStringArray(c) ? c : void 0;
1359
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1122
1360
  }
1123
1361
  if (isObject(a) && isString(a.id)) {
1124
1362
  if (a.id === "")
1125
1363
  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 });
1364
+ const columns = isStringArray(b) ? b : void 0;
1365
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1127
1366
  }
1128
1367
  if (isObject(a)) {
1129
- return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1368
+ const columns = isStringArray(b) ? b : void 0;
1369
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1130
1370
  }
1131
1371
  throw new Error("Invalid arguments for create method");
1132
1372
  }
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;
1373
+ async read(a, b) {
1374
+ const columns = isStringArray(b) ? b : ["*"];
1375
+ if (Array.isArray(a)) {
1376
+ if (a.length === 0)
1377
+ return [];
1378
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1379
+ const finalObjects = await this.getAll({ filter: { id: { $any: ids } }, columns });
1380
+ const dictionary = finalObjects.reduce((acc, object) => {
1381
+ acc[object.id] = object;
1382
+ return acc;
1383
+ }, {});
1384
+ return ids.map((id2) => dictionary[id2] ?? null);
1385
+ }
1386
+ const id = isString(a) ? a : a.id;
1387
+ if (isString(id)) {
1388
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1389
+ try {
1390
+ const response = await getRecord({
1391
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1392
+ queryParams: { columns },
1393
+ ...fetchProps
1394
+ });
1395
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1396
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1397
+ } catch (e) {
1398
+ if (isObject(e) && e.status === 404) {
1399
+ return null;
1400
+ }
1401
+ throw e;
1144
1402
  }
1145
- throw e;
1146
1403
  }
1404
+ return null;
1147
1405
  }
1148
- async update(a, b) {
1406
+ async update(a, b, c) {
1149
1407
  if (Array.isArray(a)) {
1408
+ if (a.length === 0)
1409
+ return [];
1150
1410
  if (a.length > 100) {
1151
1411
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1152
1412
  }
1153
- return Promise.all(a.map((object) => this.update(object)));
1413
+ const columns = isStringArray(b) ? b : ["*"];
1414
+ return Promise.all(a.map((object) => this.update(object, columns)));
1154
1415
  }
1155
1416
  if (isString(a) && isObject(b)) {
1156
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1417
+ const columns = isStringArray(c) ? c : void 0;
1418
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1157
1419
  }
1158
1420
  if (isObject(a) && isString(a.id)) {
1159
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1421
+ const columns = isStringArray(b) ? b : void 0;
1422
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1160
1423
  }
1161
1424
  throw new Error("Invalid arguments for update method");
1162
1425
  }
1163
- async createOrUpdate(a, b) {
1426
+ async createOrUpdate(a, b, c) {
1164
1427
  if (Array.isArray(a)) {
1428
+ if (a.length === 0)
1429
+ return [];
1165
1430
  if (a.length > 100) {
1166
1431
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1167
1432
  }
1168
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1433
+ const columns = isStringArray(b) ? b : ["*"];
1434
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1169
1435
  }
1170
1436
  if (isString(a) && isObject(b)) {
1171
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1437
+ const columns = isStringArray(c) ? c : void 0;
1438
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1172
1439
  }
1173
1440
  if (isObject(a) && isString(a.id)) {
1174
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1441
+ const columns = isStringArray(c) ? c : void 0;
1442
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1175
1443
  }
1176
1444
  throw new Error("Invalid arguments for createOrUpdate method");
1177
1445
  }
1178
- async delete(recordId) {
1179
- if (Array.isArray(recordId)) {
1180
- if (recordId.length > 100) {
1446
+ async delete(a) {
1447
+ if (Array.isArray(a)) {
1448
+ if (a.length === 0)
1449
+ return;
1450
+ if (a.length > 100) {
1181
1451
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1182
1452
  }
1183
- await Promise.all(recordId.map((id) => this.delete(id)));
1453
+ await Promise.all(a.map((id) => this.delete(id)));
1184
1454
  return;
1185
1455
  }
1186
- if (isString(recordId)) {
1187
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId);
1456
+ if (isString(a)) {
1457
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1188
1458
  return;
1189
1459
  }
1190
- if (isObject(recordId) && isString(recordId.id)) {
1191
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId.id);
1460
+ if (isObject(a) && isString(a.id)) {
1461
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1192
1462
  return;
1193
1463
  }
1194
1464
  throw new Error("Invalid arguments for delete method");
1195
1465
  }
1196
1466
  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 },
1467
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1468
+ const { records } = await searchTable({
1469
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1470
+ body: {
1471
+ query,
1472
+ fuzziness: options.fuzziness,
1473
+ prefix: options.prefix,
1474
+ highlight: options.highlight,
1475
+ filter: options.filter,
1476
+ boosters: options.boosters
1477
+ },
1201
1478
  ...fetchProps
1202
1479
  });
1203
- return records.map((item) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), item));
1480
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1481
+ return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1204
1482
  }
1205
1483
  async query(query) {
1484
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1485
+ if (cacheQuery)
1486
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1206
1487
  const data = query.getQueryOptions();
1207
1488
  const body = {
1208
1489
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1209
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1210
- page: data.page,
1490
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1491
+ page: data.pagination,
1211
1492
  columns: data.columns
1212
1493
  };
1213
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1494
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1214
1495
  const { meta, records: objects } = await queryTable({
1215
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1496
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1216
1497
  body,
1217
1498
  ...fetchProps
1218
1499
  });
1219
- const records = objects.map((record) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), record));
1500
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1501
+ const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1502
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1220
1503
  return new Page(query, meta, records);
1221
1504
  }
1222
1505
  }
1223
1506
  _table = new WeakMap();
1224
- _links = new WeakMap();
1225
1507
  _getFetchProps = new WeakMap();
1508
+ _cache = new WeakMap();
1509
+ _schemaTables$2 = new WeakMap();
1226
1510
  _insertRecordWithoutId = new WeakSet();
1227
- insertRecordWithoutId_fn = async function(object) {
1228
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1511
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1512
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1229
1513
  const record = transformObjectLinks(object);
1230
1514
  const response = await insertRecord({
1231
1515
  pathParams: {
1232
1516
  workspace: "{workspaceId}",
1233
1517
  dbBranchName: "{dbBranch}",
1234
- tableName: __privateGet$2(this, _table)
1518
+ tableName: __privateGet$4(this, _table)
1235
1519
  },
1520
+ queryParams: { columns },
1236
1521
  body: record,
1237
1522
  ...fetchProps
1238
1523
  });
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;
1524
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1525
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1244
1526
  };
1245
1527
  _insertRecordWithId = new WeakSet();
1246
- insertRecordWithId_fn = async function(recordId, object) {
1247
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1528
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1529
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1248
1530
  const record = transformObjectLinks(object);
1249
1531
  const response = await insertRecordWithID({
1250
1532
  pathParams: {
1251
1533
  workspace: "{workspaceId}",
1252
1534
  dbBranchName: "{dbBranch}",
1253
- tableName: __privateGet$2(this, _table),
1535
+ tableName: __privateGet$4(this, _table),
1254
1536
  recordId
1255
1537
  },
1256
1538
  body: record,
1257
- queryParams: { createOnly: true },
1539
+ queryParams: { createOnly: true, columns },
1258
1540
  ...fetchProps
1259
1541
  });
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;
1542
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1543
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1265
1544
  };
1266
1545
  _bulkInsertTableRecords = new WeakSet();
1267
- bulkInsertTableRecords_fn = async function(objects) {
1268
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1546
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1547
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1269
1548
  const records = objects.map((object) => transformObjectLinks(object));
1270
1549
  const response = await bulkInsertTableRecords({
1271
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1550
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1551
+ queryParams: { columns },
1272
1552
  body: { records },
1273
1553
  ...fetchProps
1274
1554
  });
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");
1555
+ if (!isResponseWithRecords(response)) {
1556
+ throw new Error("Request included columns but server didn't include them");
1278
1557
  }
1279
- return finalObjects;
1558
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1559
+ return response.records?.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1280
1560
  };
1281
1561
  _updateRecordWithID = new WeakSet();
1282
- updateRecordWithID_fn = async function(recordId, object) {
1283
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1562
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1563
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1284
1564
  const record = transformObjectLinks(object);
1285
1565
  const response = await updateRecordWithID({
1286
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1566
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1567
+ queryParams: { columns },
1287
1568
  body: record,
1288
1569
  ...fetchProps
1289
1570
  });
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;
1571
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1572
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1294
1573
  };
1295
1574
  _upsertRecordWithID = new WeakSet();
1296
- upsertRecordWithID_fn = async function(recordId, object) {
1297
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1575
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1576
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1298
1577
  const response = await upsertRecordWithID({
1299
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1578
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1579
+ queryParams: { columns },
1300
1580
  body: object,
1301
1581
  ...fetchProps
1302
1582
  });
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;
1583
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1584
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1307
1585
  };
1308
1586
  _deleteRecord = new WeakSet();
1309
1587
  deleteRecord_fn = async function(recordId) {
1310
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1588
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1311
1589
  await deleteRecord({
1312
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1590
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1591
+ ...fetchProps
1592
+ });
1593
+ };
1594
+ _setCacheQuery = new WeakSet();
1595
+ setCacheQuery_fn = async function(query, meta, records) {
1596
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1597
+ };
1598
+ _getCacheQuery = new WeakSet();
1599
+ getCacheQuery_fn = async function(query) {
1600
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1601
+ const result = await __privateGet$4(this, _cache).get(key);
1602
+ if (!result)
1603
+ return null;
1604
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1605
+ if (ttl < 0)
1606
+ return null;
1607
+ const hasExpired = result.date.getTime() + ttl < Date.now();
1608
+ return hasExpired ? null : result;
1609
+ };
1610
+ _getSchemaTables$1 = new WeakSet();
1611
+ getSchemaTables_fn$1 = async function() {
1612
+ if (__privateGet$4(this, _schemaTables$2))
1613
+ return __privateGet$4(this, _schemaTables$2);
1614
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1615
+ const { schema } = await getBranchDetails({
1616
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1313
1617
  ...fetchProps
1314
1618
  });
1619
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1620
+ return schema.tables;
1315
1621
  };
1316
1622
  const transformObjectLinks = (object) => {
1317
1623
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1320,32 +1626,106 @@ const transformObjectLinks = (object) => {
1320
1626
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1321
1627
  }, {});
1322
1628
  };
1323
- const initObject = (db, links, table, object) => {
1629
+ const initObject = (db, schemaTables, table, object) => {
1324
1630
  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);
1631
+ const { xata, ...rest } = object ?? {};
1632
+ Object.assign(result, rest);
1633
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1634
+ if (!columns)
1635
+ console.error(`Table ${table} not found in schema`);
1636
+ for (const column of columns ?? []) {
1637
+ const value = result[column.name];
1638
+ switch (column.type) {
1639
+ case "datetime": {
1640
+ const date = value !== void 0 ? new Date(value) : void 0;
1641
+ if (date && isNaN(date.getTime())) {
1642
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1643
+ } else if (date) {
1644
+ result[column.name] = date;
1645
+ }
1646
+ break;
1647
+ }
1648
+ case "link": {
1649
+ const linkTable = column.link?.table;
1650
+ if (!linkTable) {
1651
+ console.error(`Failed to parse link for field ${column.name}`);
1652
+ } else if (isObject(value)) {
1653
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1654
+ }
1655
+ break;
1656
+ }
1332
1657
  }
1333
1658
  }
1334
- result.read = function() {
1335
- return db[table].read(result["id"]);
1659
+ result.read = function(columns2) {
1660
+ return db[table].read(result["id"], columns2);
1336
1661
  };
1337
- result.update = function(data) {
1338
- return db[table].update(result["id"], data);
1662
+ result.update = function(data, columns2) {
1663
+ return db[table].update(result["id"], data, columns2);
1339
1664
  };
1340
1665
  result.delete = function() {
1341
1666
  return db[table].delete(result["id"]);
1342
1667
  };
1343
- for (const prop of ["read", "update", "delete"]) {
1668
+ result.getMetadata = function() {
1669
+ return xata;
1670
+ };
1671
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1344
1672
  Object.defineProperty(result, prop, { enumerable: false });
1345
1673
  }
1346
1674
  Object.freeze(result);
1347
1675
  return result;
1348
1676
  };
1677
+ function isResponseWithRecords(value) {
1678
+ return isObject(value) && Array.isArray(value.records);
1679
+ }
1680
+
1681
+ var __accessCheck$3 = (obj, member, msg) => {
1682
+ if (!member.has(obj))
1683
+ throw TypeError("Cannot " + msg);
1684
+ };
1685
+ var __privateGet$3 = (obj, member, getter) => {
1686
+ __accessCheck$3(obj, member, "read from private field");
1687
+ return getter ? getter.call(obj) : member.get(obj);
1688
+ };
1689
+ var __privateAdd$3 = (obj, member, value) => {
1690
+ if (member.has(obj))
1691
+ throw TypeError("Cannot add the same private member more than once");
1692
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1693
+ };
1694
+ var __privateSet$3 = (obj, member, value, setter) => {
1695
+ __accessCheck$3(obj, member, "write to private field");
1696
+ setter ? setter.call(obj, value) : member.set(obj, value);
1697
+ return value;
1698
+ };
1699
+ var _map;
1700
+ class SimpleCache {
1701
+ constructor(options = {}) {
1702
+ __privateAdd$3(this, _map, void 0);
1703
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1704
+ this.capacity = options.max ?? 500;
1705
+ this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1706
+ }
1707
+ async getAll() {
1708
+ return Object.fromEntries(__privateGet$3(this, _map));
1709
+ }
1710
+ async get(key) {
1711
+ return __privateGet$3(this, _map).get(key) ?? null;
1712
+ }
1713
+ async set(key, value) {
1714
+ await this.delete(key);
1715
+ __privateGet$3(this, _map).set(key, value);
1716
+ if (__privateGet$3(this, _map).size > this.capacity) {
1717
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1718
+ await this.delete(leastRecentlyUsed);
1719
+ }
1720
+ }
1721
+ async delete(key) {
1722
+ __privateGet$3(this, _map).delete(key);
1723
+ }
1724
+ async clear() {
1725
+ return __privateGet$3(this, _map).clear();
1726
+ }
1727
+ }
1728
+ _map = new WeakMap();
1349
1729
 
1350
1730
  const gt = (value) => ({ $gt: value });
1351
1731
  const ge = (value) => ({ $ge: value });
@@ -1370,7 +1750,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1370
1750
  if (!member.has(obj))
1371
1751
  throw TypeError("Cannot " + msg);
1372
1752
  };
1373
- var __privateGet$1 = (obj, member, getter) => {
1753
+ var __privateGet$2 = (obj, member, getter) => {
1374
1754
  __accessCheck$2(obj, member, "read from private field");
1375
1755
  return getter ? getter.call(obj) : member.get(obj);
1376
1756
  };
@@ -1379,130 +1759,177 @@ var __privateAdd$2 = (obj, member, value) => {
1379
1759
  throw TypeError("Cannot add the same private member more than once");
1380
1760
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1381
1761
  };
1382
- var _tables;
1762
+ var __privateSet$2 = (obj, member, value, setter) => {
1763
+ __accessCheck$2(obj, member, "write to private field");
1764
+ setter ? setter.call(obj, value) : member.set(obj, value);
1765
+ return value;
1766
+ };
1767
+ var _tables, _schemaTables$1;
1383
1768
  class SchemaPlugin extends XataPlugin {
1384
- constructor(links, tableNames) {
1769
+ constructor(schemaTables) {
1385
1770
  super();
1386
- this.links = links;
1387
- this.tableNames = tableNames;
1388
1771
  __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];
1772
+ __privateAdd$2(this, _schemaTables$1, void 0);
1773
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1774
+ }
1775
+ build(pluginOptions) {
1776
+ const db = new Proxy(
1777
+ {},
1778
+ {
1779
+ get: (_target, table) => {
1780
+ if (!isString(table))
1781
+ throw new Error("Invalid table name");
1782
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1783
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1784
+ }
1785
+ return __privateGet$2(this, _tables)[table];
1786
+ }
1400
1787
  }
1401
- });
1402
- for (const table of this.tableNames ?? []) {
1403
- db[table] = new RestRepository({ db, getFetchProps, table, links });
1788
+ );
1789
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1790
+ for (const table of tableNames) {
1791
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1404
1792
  }
1405
1793
  return db;
1406
1794
  }
1407
1795
  }
1408
1796
  _tables = new WeakMap();
1797
+ _schemaTables$1 = new WeakMap();
1409
1798
 
1410
1799
  var __accessCheck$1 = (obj, member, msg) => {
1411
1800
  if (!member.has(obj))
1412
1801
  throw TypeError("Cannot " + msg);
1413
1802
  };
1803
+ var __privateGet$1 = (obj, member, getter) => {
1804
+ __accessCheck$1(obj, member, "read from private field");
1805
+ return getter ? getter.call(obj) : member.get(obj);
1806
+ };
1414
1807
  var __privateAdd$1 = (obj, member, value) => {
1415
1808
  if (member.has(obj))
1416
1809
  throw TypeError("Cannot add the same private member more than once");
1417
1810
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1418
1811
  };
1812
+ var __privateSet$1 = (obj, member, value, setter) => {
1813
+ __accessCheck$1(obj, member, "write to private field");
1814
+ setter ? setter.call(obj, value) : member.set(obj, value);
1815
+ return value;
1816
+ };
1419
1817
  var __privateMethod$1 = (obj, member, method) => {
1420
1818
  __accessCheck$1(obj, member, "access private method");
1421
1819
  return method;
1422
1820
  };
1423
- var _search, search_fn;
1821
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1424
1822
  class SearchPlugin extends XataPlugin {
1425
- constructor(db, links) {
1823
+ constructor(db, schemaTables) {
1426
1824
  super();
1427
1825
  this.db = db;
1428
- this.links = links;
1429
1826
  __privateAdd$1(this, _search);
1827
+ __privateAdd$1(this, _getSchemaTables);
1828
+ __privateAdd$1(this, _schemaTables, void 0);
1829
+ __privateSet$1(this, _schemaTables, schemaTables);
1430
1830
  }
1431
1831
  build({ getFetchProps }) {
1432
1832
  return {
1433
1833
  all: async (query, options = {}) => {
1434
1834
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1835
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1435
1836
  return records.map((record) => {
1436
1837
  const { table = "orphan" } = record.xata;
1437
- return { table, record: initObject(this.db, this.links, table, record) };
1838
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1438
1839
  });
1439
1840
  },
1440
1841
  byTable: async (query, options = {}) => {
1441
1842
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1843
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1442
1844
  return records.reduce((acc, record) => {
1443
1845
  const { table = "orphan" } = record.xata;
1444
1846
  const items = acc[table] ?? [];
1445
- const item = initObject(this.db, this.links, table, record);
1847
+ const item = initObject(this.db, schemaTables, table, record);
1446
1848
  return { ...acc, [table]: [...items, item] };
1447
1849
  }, {});
1448
1850
  }
1449
1851
  };
1450
1852
  }
1451
1853
  }
1854
+ _schemaTables = new WeakMap();
1452
1855
  _search = new WeakSet();
1453
1856
  search_fn = async function(query, options, getFetchProps) {
1454
1857
  const fetchProps = await getFetchProps();
1455
- const { tables, fuzziness } = options ?? {};
1858
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1456
1859
  const { records } = await searchBranch({
1457
1860
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1458
- body: { tables, query, fuzziness },
1861
+ body: { tables, query, fuzziness, prefix, highlight },
1459
1862
  ...fetchProps
1460
1863
  });
1461
1864
  return records;
1462
1865
  };
1866
+ _getSchemaTables = new WeakSet();
1867
+ getSchemaTables_fn = async function(getFetchProps) {
1868
+ if (__privateGet$1(this, _schemaTables))
1869
+ return __privateGet$1(this, _schemaTables);
1870
+ const fetchProps = await getFetchProps();
1871
+ const { schema } = await getBranchDetails({
1872
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1873
+ ...fetchProps
1874
+ });
1875
+ __privateSet$1(this, _schemaTables, schema.tables);
1876
+ return schema.tables;
1877
+ };
1463
1878
 
1464
1879
  const isBranchStrategyBuilder = (strategy) => {
1465
1880
  return typeof strategy === "function";
1466
1881
  };
1467
1882
 
1468
- const envBranchNames = [
1469
- "XATA_BRANCH",
1470
- "VERCEL_GIT_COMMIT_REF",
1471
- "CF_PAGES_BRANCH",
1472
- "BRANCH"
1473
- ];
1474
- const defaultBranch = "main";
1475
1883
  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;
1884
+ const { branch, envBranch } = getEnvironment();
1885
+ if (branch) {
1886
+ const details = await getDatabaseBranch(branch, options);
1887
+ if (details)
1888
+ return branch;
1889
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1890
+ }
1891
+ const gitBranch = envBranch || await getGitBranch();
1892
+ return resolveXataBranch(gitBranch, options);
1486
1893
  }
1487
1894
  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);
1895
+ const branch = await getCurrentBranchName(options);
1896
+ return getDatabaseBranch(branch, options);
1897
+ }
1898
+ async function resolveXataBranch(gitBranch, options) {
1899
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1900
+ const apiKey = options?.apiKey || getAPIKey();
1901
+ if (!databaseURL)
1902
+ throw new Error(
1903
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
1904
+ );
1905
+ if (!apiKey)
1906
+ throw new Error(
1907
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
1908
+ );
1909
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1910
+ const [workspace] = host.split(".");
1911
+ const { fallbackBranch } = getEnvironment();
1912
+ const { branch } = await resolveBranch({
1913
+ apiKey,
1914
+ apiUrl: databaseURL,
1915
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1916
+ workspacesApiUrl: `${protocol}//${host}`,
1917
+ pathParams: { dbName, workspace },
1918
+ queryParams: { gitBranch, fallbackBranch }
1919
+ });
1920
+ return branch;
1498
1921
  }
1499
1922
  async function getDatabaseBranch(branch, options) {
1500
1923
  const databaseURL = options?.databaseURL || getDatabaseURL();
1501
1924
  const apiKey = options?.apiKey || getAPIKey();
1502
1925
  if (!databaseURL)
1503
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1926
+ throw new Error(
1927
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
1928
+ );
1504
1929
  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");
1930
+ throw new Error(
1931
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
1932
+ );
1506
1933
  const [protocol, , host, , database] = databaseURL.split("/");
1507
1934
  const [workspace] = host.split(".");
1508
1935
  const dbBranchName = `${database}:${branch}`;
@@ -1512,10 +1939,7 @@ async function getDatabaseBranch(branch, options) {
1512
1939
  apiUrl: databaseURL,
1513
1940
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1514
1941
  workspacesApiUrl: `${protocol}//${host}`,
1515
- pathParams: {
1516
- dbBranchName,
1517
- workspace
1518
- }
1942
+ pathParams: { dbBranchName, workspace }
1519
1943
  });
1520
1944
  } catch (err) {
1521
1945
  if (isObject(err) && err.status === 404)
@@ -1523,21 +1947,10 @@ async function getDatabaseBranch(branch, options) {
1523
1947
  throw err;
1524
1948
  }
1525
1949
  }
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
1950
  function getDatabaseURL() {
1539
1951
  try {
1540
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1952
+ const { databaseURL } = getEnvironment();
1953
+ return databaseURL;
1541
1954
  } catch (err) {
1542
1955
  return void 0;
1543
1956
  }
@@ -1568,22 +1981,24 @@ var __privateMethod = (obj, member, method) => {
1568
1981
  const buildClient = (plugins) => {
1569
1982
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1570
1983
  return _a = class {
1571
- constructor(options = {}, links, tables) {
1984
+ constructor(options = {}, schemaTables) {
1572
1985
  __privateAdd(this, _parseOptions);
1573
1986
  __privateAdd(this, _getFetchProps);
1574
1987
  __privateAdd(this, _evaluateBranch);
1575
1988
  __privateAdd(this, _branch, void 0);
1576
1989
  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
- });
1990
+ const pluginOptions = {
1991
+ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1992
+ cache: safeOptions.cache
1993
+ };
1994
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
1995
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1581
1996
  this.db = db;
1582
1997
  this.search = search;
1583
1998
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1584
- if (!namespace)
1999
+ if (namespace === void 0)
1585
2000
  continue;
1586
- const result = namespace.build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
2001
+ const result = namespace.build(pluginOptions);
1587
2002
  if (result instanceof Promise) {
1588
2003
  void result.then((namespace2) => {
1589
2004
  this[key] = namespace2;
@@ -1597,11 +2012,12 @@ const buildClient = (plugins) => {
1597
2012
  const fetch = getFetchImplementation(options?.fetch);
1598
2013
  const databaseURL = options?.databaseURL || getDatabaseURL();
1599
2014
  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 });
2015
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2016
+ 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
2017
  if (!databaseURL || !apiKey) {
1602
2018
  throw new Error("Options databaseURL and apiKey are required");
1603
2019
  }
1604
- return { fetch, databaseURL, apiKey, branch };
2020
+ return { fetch, databaseURL, apiKey, branch, cache };
1605
2021
  }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1606
2022
  fetch,
1607
2023
  apiKey,
@@ -1624,7 +2040,7 @@ const buildClient = (plugins) => {
1624
2040
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1625
2041
  if (__privateGet(this, _branch))
1626
2042
  return __privateGet(this, _branch);
1627
- if (!param)
2043
+ if (param === void 0)
1628
2044
  return void 0;
1629
2045
  const strategies = Array.isArray(param) ? [...param] : [param];
1630
2046
  const evaluateBranch = async (strategy) => {
@@ -1649,5 +2065,5 @@ class XataError extends Error {
1649
2065
  }
1650
2066
  }
1651
2067
 
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 };
2068
+ 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, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
1653
2069
  //# sourceMappingURL=index.mjs.map