@xata.io/client 0.0.0-alpha.vf170c2c → 0.0.0-alpha.vf1de7db

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2,6 +2,46 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ function _interopNamespace(e) {
6
+ if (e && e.__esModule) return e;
7
+ var n = Object.create(null);
8
+ if (e) {
9
+ Object.keys(e).forEach(function (k) {
10
+ if (k !== 'default') {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: true,
14
+ get: function () { return e[k]; }
15
+ });
16
+ }
17
+ });
18
+ }
19
+ n["default"] = e;
20
+ return Object.freeze(n);
21
+ }
22
+
23
+ const defaultTrace = async (_name, fn, _options) => {
24
+ return await fn({
25
+ setAttributes: () => {
26
+ return;
27
+ }
28
+ });
29
+ };
30
+ const TraceAttributes = {
31
+ KIND: "xata.trace.kind",
32
+ VERSION: "xata.sdk.version",
33
+ TABLE: "xata.table",
34
+ HTTP_REQUEST_ID: "http.request_id",
35
+ HTTP_STATUS_CODE: "http.status_code",
36
+ HTTP_HOST: "http.host",
37
+ HTTP_SCHEME: "http.scheme",
38
+ HTTP_USER_AGENT: "http.user_agent",
39
+ HTTP_METHOD: "http.method",
40
+ HTTP_URL: "http.url",
41
+ HTTP_ROUTE: "http.route",
42
+ HTTP_TARGET: "http.target"
43
+ };
44
+
5
45
  function notEmpty(value) {
6
46
  return value !== null && value !== void 0;
7
47
  }
@@ -11,36 +51,101 @@ function compact(arr) {
11
51
  function isObject(value) {
12
52
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
13
53
  }
54
+ function isDefined(value) {
55
+ return value !== null && value !== void 0;
56
+ }
14
57
  function isString(value) {
15
- return value !== void 0 && value !== null && typeof value === "string";
58
+ return isDefined(value) && typeof value === "string";
59
+ }
60
+ function isStringArray(value) {
61
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
62
+ }
63
+ function toBase64(value) {
64
+ try {
65
+ return btoa(value);
66
+ } catch (err) {
67
+ const buf = Buffer;
68
+ return buf.from(value).toString("base64");
69
+ }
16
70
  }
17
71
 
18
- function getEnvVariable(name) {
72
+ function getEnvironment() {
19
73
  try {
20
- if (isObject(process) && isString(process?.env?.[name])) {
21
- return process.env[name];
74
+ if (isObject(process) && isObject(process.env)) {
75
+ return {
76
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
77
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
78
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
79
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
80
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
81
+ };
22
82
  }
23
83
  } catch (err) {
24
84
  }
25
85
  try {
26
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
27
- return Deno.env.get(name);
86
+ if (isObject(Deno) && isObject(Deno.env)) {
87
+ return {
88
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
89
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
90
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
91
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
92
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
93
+ };
28
94
  }
29
95
  } catch (err) {
30
96
  }
97
+ return {
98
+ apiKey: getGlobalApiKey(),
99
+ databaseURL: getGlobalDatabaseURL(),
100
+ branch: getGlobalBranch(),
101
+ envBranch: void 0,
102
+ fallbackBranch: getGlobalFallbackBranch()
103
+ };
104
+ }
105
+ function getGlobalApiKey() {
106
+ try {
107
+ return XATA_API_KEY;
108
+ } catch (err) {
109
+ return void 0;
110
+ }
111
+ }
112
+ function getGlobalDatabaseURL() {
113
+ try {
114
+ return XATA_DATABASE_URL;
115
+ } catch (err) {
116
+ return void 0;
117
+ }
118
+ }
119
+ function getGlobalBranch() {
120
+ try {
121
+ return XATA_BRANCH;
122
+ } catch (err) {
123
+ return void 0;
124
+ }
125
+ }
126
+ function getGlobalFallbackBranch() {
127
+ try {
128
+ return XATA_FALLBACK_BRANCH;
129
+ } catch (err) {
130
+ return void 0;
131
+ }
31
132
  }
32
133
  async function getGitBranch() {
134
+ const cmd = ["git", "branch", "--show-current"];
135
+ const fullCmd = cmd.join(" ");
136
+ const nodeModule = ["child", "process"].join("_");
137
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
33
138
  try {
34
- return require("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
139
+ if (typeof require === "function") {
140
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
141
+ }
142
+ const { execSync } = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(nodeModule);
143
+ return execSync(fullCmd, execOptions).toString().trim();
35
144
  } catch (err) {
36
145
  }
37
146
  try {
38
147
  if (isObject(Deno)) {
39
- const process2 = Deno.run({
40
- cmd: ["git", "branch", "--show-current"],
41
- stdout: "piped",
42
- stderr: "piped"
43
- });
148
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
44
149
  return new TextDecoder().decode(await process2.output()).trim();
45
150
  }
46
151
  } catch (err) {
@@ -49,7 +154,8 @@ async function getGitBranch() {
49
154
 
50
155
  function getAPIKey() {
51
156
  try {
52
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
157
+ const { apiKey } = getEnvironment();
158
+ return apiKey;
53
159
  } catch (err) {
54
160
  return void 0;
55
161
  }
@@ -59,21 +165,35 @@ function getFetchImplementation(userFetch) {
59
165
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
60
166
  const fetchImpl = userFetch ?? globalFetch;
61
167
  if (!fetchImpl) {
62
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
168
+ throw new Error(
169
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
170
+ );
63
171
  }
64
172
  return fetchImpl;
65
173
  }
66
174
 
67
- class FetcherError extends Error {
68
- constructor(status, data) {
175
+ const VERSION = "0.0.0-alpha.vf1de7db";
176
+
177
+ class ErrorWithCause extends Error {
178
+ constructor(message, options) {
179
+ super(message, options);
180
+ }
181
+ }
182
+ class FetcherError extends ErrorWithCause {
183
+ constructor(status, data, requestId) {
69
184
  super(getMessage(data));
70
185
  this.status = status;
71
186
  this.errors = isBulkError(data) ? data.errors : void 0;
187
+ this.requestId = requestId;
72
188
  if (data instanceof Error) {
73
189
  this.stack = data.stack;
74
190
  this.cause = data.cause;
75
191
  }
76
192
  }
193
+ toString() {
194
+ const error = super.toString();
195
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
196
+ }
77
197
  }
78
198
  function isBulkError(error) {
79
199
  return isObject(error) && Array.isArray(error.errors);
@@ -96,9 +216,17 @@ function getMessage(data) {
96
216
  }
97
217
 
98
218
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
99
- const query = new URLSearchParams(queryParams).toString();
219
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
220
+ if (value === void 0 || value === null)
221
+ return acc;
222
+ return { ...acc, [key]: value };
223
+ }, {});
224
+ const query = new URLSearchParams(cleanQueryParams).toString();
100
225
  const queryString = query.length > 0 ? `?${query}` : "";
101
- return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
226
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
227
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
228
+ }, {});
229
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
102
230
  };
103
231
  function buildBaseUrl({
104
232
  path,
@@ -106,10 +234,10 @@ function buildBaseUrl({
106
234
  apiUrl,
107
235
  pathParams
108
236
  }) {
109
- if (!pathParams?.workspace)
237
+ if (pathParams?.workspace === void 0)
110
238
  return `${apiUrl}${path}`;
111
239
  const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
112
- return url.replace("{workspaceId}", pathParams.workspace);
240
+ return url.replace("{workspaceId}", String(pathParams.workspace));
113
241
  }
114
242
  function hostHeader(url) {
115
243
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
@@ -126,32 +254,61 @@ async function fetch$1({
126
254
  fetchImpl,
127
255
  apiKey,
128
256
  apiUrl,
129
- workspacesApiUrl
257
+ workspacesApiUrl,
258
+ trace
130
259
  }) {
131
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
132
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
133
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
134
- const response = await fetchImpl(url, {
135
- method: method.toUpperCase(),
136
- body: body ? JSON.stringify(body) : void 0,
137
- headers: {
138
- "Content-Type": "application/json",
139
- ...headers,
140
- ...hostHeader(fullUrl),
141
- Authorization: `Bearer ${apiKey}`
142
- }
143
- });
144
- if (response.status === 204) {
145
- return {};
146
- }
260
+ return trace(
261
+ `${method.toUpperCase()} ${path}`,
262
+ async ({ setAttributes }) => {
263
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
264
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
265
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
266
+ setAttributes({
267
+ [TraceAttributes.HTTP_URL]: url,
268
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
269
+ });
270
+ const response = await fetchImpl(url, {
271
+ method: method.toUpperCase(),
272
+ body: body ? JSON.stringify(body) : void 0,
273
+ headers: {
274
+ "Content-Type": "application/json",
275
+ "User-Agent": `Xata client-ts/${VERSION}`,
276
+ ...headers,
277
+ ...hostHeader(fullUrl),
278
+ Authorization: `Bearer ${apiKey}`
279
+ }
280
+ });
281
+ if (response.status === 204) {
282
+ return {};
283
+ }
284
+ const { host, protocol } = parseUrl(response.url);
285
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
286
+ setAttributes({
287
+ [TraceAttributes.KIND]: "http",
288
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
289
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
290
+ [TraceAttributes.HTTP_HOST]: host,
291
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
292
+ });
293
+ try {
294
+ const jsonResponse = await response.json();
295
+ if (response.ok) {
296
+ return jsonResponse;
297
+ }
298
+ throw new FetcherError(response.status, jsonResponse, requestId);
299
+ } catch (error) {
300
+ throw new FetcherError(response.status, error, requestId);
301
+ }
302
+ },
303
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
304
+ );
305
+ }
306
+ function parseUrl(url) {
147
307
  try {
148
- const jsonResponse = await response.json();
149
- if (response.ok) {
150
- return jsonResponse;
151
- }
152
- throw new FetcherError(response.status, jsonResponse);
308
+ const { host, protocol } = new URL(url);
309
+ return { host, protocol };
153
310
  } catch (error) {
154
- throw new FetcherError(response.status, error);
311
+ return {};
155
312
  }
156
313
  }
157
314
 
@@ -210,6 +367,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
210
367
  ...variables
211
368
  });
212
369
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
370
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
213
371
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
214
372
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
215
373
  method: "delete",
@@ -245,16 +403,42 @@ const deleteDatabase = (variables) => fetch$1({
245
403
  method: "delete",
246
404
  ...variables
247
405
  });
248
- const getBranchDetails = (variables) => fetch$1({
249
- url: "/db/{dbBranchName}",
406
+ const getDatabaseMetadata = (variables) => fetch$1({
407
+ url: "/dbs/{dbName}/metadata",
408
+ method: "get",
409
+ ...variables
410
+ });
411
+ const updateDatabaseMetadata = (variables) => fetch$1({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables });
412
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
413
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
414
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
415
+ const resolveBranch = (variables) => fetch$1({
416
+ url: "/dbs/{dbName}/resolveBranch",
417
+ method: "get",
418
+ ...variables
419
+ });
420
+ const queryMigrationRequests = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables });
421
+ const createMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations", method: "post", ...variables });
422
+ const getMigrationRequest = (variables) => fetch$1({
423
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
250
424
  method: "get",
251
425
  ...variables
252
426
  });
253
- const createBranch = (variables) => fetch$1({
427
+ const updateMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables });
428
+ const listMigrationRequestsCommits = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables });
429
+ const compareMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables });
430
+ const getMigrationRequestIsMerged = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables });
431
+ const mergeMigrationRequest = (variables) => fetch$1({
432
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
433
+ method: "post",
434
+ ...variables
435
+ });
436
+ const getBranchDetails = (variables) => fetch$1({
254
437
  url: "/db/{dbBranchName}",
255
- method: "put",
438
+ method: "get",
256
439
  ...variables
257
440
  });
441
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
258
442
  const deleteBranch = (variables) => fetch$1({
259
443
  url: "/db/{dbBranchName}",
260
444
  method: "delete",
@@ -273,6 +457,16 @@ const getBranchMetadata = (variables) => fetch$1({
273
457
  const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
274
458
  const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
275
459
  const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
460
+ const compareBranchWithUserSchema = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables });
461
+ const compareBranchSchemas = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables });
462
+ const updateBranchSchema = (variables) => fetch$1({
463
+ url: "/db/{dbBranchName}/schema/update",
464
+ method: "post",
465
+ ...variables
466
+ });
467
+ const previewBranchSchemaEdit = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables });
468
+ const applyBranchSchemaEdit = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables });
469
+ const getBranchSchemaHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables });
276
470
  const getBranchStats = (variables) => fetch$1({
277
471
  url: "/db/{dbBranchName}/stats",
278
472
  method: "get",
@@ -328,11 +522,7 @@ const updateColumn = (variables) => fetch$1({
328
522
  method: "patch",
329
523
  ...variables
330
524
  });
331
- const insertRecord = (variables) => fetch$1({
332
- url: "/db/{dbBranchName}/tables/{tableName}/data",
333
- method: "post",
334
- ...variables
335
- });
525
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
336
526
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
337
527
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
338
528
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -352,11 +542,36 @@ const queryTable = (variables) => fetch$1({
352
542
  method: "post",
353
543
  ...variables
354
544
  });
545
+ const searchTable = (variables) => fetch$1({
546
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
547
+ method: "post",
548
+ ...variables
549
+ });
355
550
  const searchBranch = (variables) => fetch$1({
356
551
  url: "/db/{dbBranchName}/search",
357
552
  method: "post",
358
553
  ...variables
359
554
  });
555
+ const summarizeTable = (variables) => fetch$1({
556
+ url: "/db/{dbBranchName}/tables/{tableName}/summarize",
557
+ method: "post",
558
+ ...variables
559
+ });
560
+ const cPgetDatabaseList = (variables) => fetch$1({
561
+ url: "/workspaces/{workspaceId}/dbs",
562
+ method: "get",
563
+ ...variables
564
+ });
565
+ const cPcreateDatabase = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables });
566
+ const cPdeleteDatabase = (variables) => fetch$1({
567
+ url: "/workspaces/{workspaceId}/dbs/{dbName}",
568
+ method: "delete",
569
+ ...variables
570
+ });
571
+ const cPgetCPDatabaseMetadata = (variables) => fetch$1(
572
+ { url: "/workspaces/{workspaceId}/dbs/{dbName}/metadata", method: "get", ...variables }
573
+ );
574
+ const cPupdateCPDatabaseMetadata = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/dbs/{dbName}/metadata", method: "patch", ...variables });
360
575
  const operationsByTag = {
361
576
  users: { getUser, updateUser, deleteUser, getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
362
577
  workspaces: {
@@ -369,11 +584,22 @@ const operationsByTag = {
369
584
  updateWorkspaceMemberRole,
370
585
  removeWorkspaceMember,
371
586
  inviteWorkspaceMember,
587
+ updateWorkspaceMemberInvite,
372
588
  cancelWorkspaceMemberInvite,
373
589
  resendWorkspaceMemberInvite,
374
590
  acceptWorkspaceMemberInvite
375
591
  },
376
- database: { getDatabaseList, createDatabase, deleteDatabase },
592
+ database: {
593
+ getDatabaseList,
594
+ createDatabase,
595
+ deleteDatabase,
596
+ getDatabaseMetadata,
597
+ updateDatabaseMetadata,
598
+ getGitBranchesMapping,
599
+ addGitBranchesEntry,
600
+ removeGitBranchesEntry,
601
+ resolveBranch
602
+ },
377
603
  branch: {
378
604
  getBranchList,
379
605
  getBranchDetails,
@@ -381,10 +607,28 @@ const operationsByTag = {
381
607
  deleteBranch,
382
608
  updateBranchMetadata,
383
609
  getBranchMetadata,
610
+ getBranchStats
611
+ },
612
+ migrationRequests: {
613
+ queryMigrationRequests,
614
+ createMigrationRequest,
615
+ getMigrationRequest,
616
+ updateMigrationRequest,
617
+ listMigrationRequestsCommits,
618
+ compareMigrationRequest,
619
+ getMigrationRequestIsMerged,
620
+ mergeMigrationRequest
621
+ },
622
+ branchSchema: {
384
623
  getBranchMigrationHistory,
385
624
  executeBranchMigrationPlan,
386
625
  getBranchMigrationPlan,
387
- getBranchStats
626
+ compareBranchWithUserSchema,
627
+ compareBranchSchemas,
628
+ updateBranchSchema,
629
+ previewBranchSchemaEdit,
630
+ applyBranchSchemaEdit,
631
+ getBranchSchemaHistory
388
632
  },
389
633
  table: {
390
634
  createTable,
@@ -407,14 +651,23 @@ const operationsByTag = {
407
651
  getRecord,
408
652
  bulkInsertTableRecords,
409
653
  queryTable,
410
- searchBranch
654
+ searchTable,
655
+ searchBranch,
656
+ summarizeTable
657
+ },
658
+ databases: {
659
+ cPgetDatabaseList,
660
+ cPcreateDatabase,
661
+ cPdeleteDatabase,
662
+ cPgetCPDatabaseMetadata,
663
+ cPupdateCPDatabaseMetadata
411
664
  }
412
665
  };
413
666
 
414
667
  function getHostUrl(provider, type) {
415
- if (isValidAlias(provider)) {
668
+ if (isHostProviderAlias(provider)) {
416
669
  return providers[provider][type];
417
- } else if (isValidBuilder(provider)) {
670
+ } else if (isHostProviderBuilder(provider)) {
418
671
  return provider[type];
419
672
  }
420
673
  throw new Error("Invalid API provider");
@@ -429,77 +682,89 @@ const providers = {
429
682
  workspaces: "https://{workspaceId}.staging.xatabase.co"
430
683
  }
431
684
  };
432
- function isValidAlias(alias) {
685
+ function isHostProviderAlias(alias) {
433
686
  return isString(alias) && Object.keys(providers).includes(alias);
434
687
  }
435
- function isValidBuilder(builder) {
688
+ function isHostProviderBuilder(builder) {
436
689
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
437
690
  }
438
691
 
439
- var __accessCheck$6 = (obj, member, msg) => {
692
+ var __accessCheck$7 = (obj, member, msg) => {
440
693
  if (!member.has(obj))
441
694
  throw TypeError("Cannot " + msg);
442
695
  };
443
- var __privateGet$5 = (obj, member, getter) => {
444
- __accessCheck$6(obj, member, "read from private field");
696
+ var __privateGet$7 = (obj, member, getter) => {
697
+ __accessCheck$7(obj, member, "read from private field");
445
698
  return getter ? getter.call(obj) : member.get(obj);
446
699
  };
447
- var __privateAdd$6 = (obj, member, value) => {
700
+ var __privateAdd$7 = (obj, member, value) => {
448
701
  if (member.has(obj))
449
702
  throw TypeError("Cannot add the same private member more than once");
450
703
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
451
704
  };
452
- var __privateSet$4 = (obj, member, value, setter) => {
453
- __accessCheck$6(obj, member, "write to private field");
705
+ var __privateSet$7 = (obj, member, value, setter) => {
706
+ __accessCheck$7(obj, member, "write to private field");
454
707
  setter ? setter.call(obj, value) : member.set(obj, value);
455
708
  return value;
456
709
  };
457
710
  var _extraProps, _namespaces;
458
711
  class XataApiClient {
459
712
  constructor(options = {}) {
460
- __privateAdd$6(this, _extraProps, void 0);
461
- __privateAdd$6(this, _namespaces, {});
713
+ __privateAdd$7(this, _extraProps, void 0);
714
+ __privateAdd$7(this, _namespaces, {});
462
715
  const provider = options.host ?? "production";
463
- const apiKey = options?.apiKey ?? getAPIKey();
716
+ const apiKey = options.apiKey ?? getAPIKey();
717
+ const trace = options.trace ?? defaultTrace;
464
718
  if (!apiKey) {
465
719
  throw new Error("Could not resolve a valid apiKey");
466
720
  }
467
- __privateSet$4(this, _extraProps, {
721
+ __privateSet$7(this, _extraProps, {
468
722
  apiUrl: getHostUrl(provider, "main"),
469
723
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
470
724
  fetchImpl: getFetchImplementation(options.fetch),
471
- apiKey
725
+ apiKey,
726
+ trace
472
727
  });
473
728
  }
474
729
  get user() {
475
- if (!__privateGet$5(this, _namespaces).user)
476
- __privateGet$5(this, _namespaces).user = new UserApi(__privateGet$5(this, _extraProps));
477
- return __privateGet$5(this, _namespaces).user;
730
+ if (!__privateGet$7(this, _namespaces).user)
731
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
732
+ return __privateGet$7(this, _namespaces).user;
478
733
  }
479
734
  get workspaces() {
480
- if (!__privateGet$5(this, _namespaces).workspaces)
481
- __privateGet$5(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$5(this, _extraProps));
482
- return __privateGet$5(this, _namespaces).workspaces;
735
+ if (!__privateGet$7(this, _namespaces).workspaces)
736
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
737
+ return __privateGet$7(this, _namespaces).workspaces;
483
738
  }
484
739
  get databases() {
485
- if (!__privateGet$5(this, _namespaces).databases)
486
- __privateGet$5(this, _namespaces).databases = new DatabaseApi(__privateGet$5(this, _extraProps));
487
- return __privateGet$5(this, _namespaces).databases;
740
+ if (!__privateGet$7(this, _namespaces).databases)
741
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
742
+ return __privateGet$7(this, _namespaces).databases;
488
743
  }
489
744
  get branches() {
490
- if (!__privateGet$5(this, _namespaces).branches)
491
- __privateGet$5(this, _namespaces).branches = new BranchApi(__privateGet$5(this, _extraProps));
492
- return __privateGet$5(this, _namespaces).branches;
745
+ if (!__privateGet$7(this, _namespaces).branches)
746
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
747
+ return __privateGet$7(this, _namespaces).branches;
493
748
  }
494
749
  get tables() {
495
- if (!__privateGet$5(this, _namespaces).tables)
496
- __privateGet$5(this, _namespaces).tables = new TableApi(__privateGet$5(this, _extraProps));
497
- return __privateGet$5(this, _namespaces).tables;
750
+ if (!__privateGet$7(this, _namespaces).tables)
751
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
752
+ return __privateGet$7(this, _namespaces).tables;
498
753
  }
499
754
  get records() {
500
- if (!__privateGet$5(this, _namespaces).records)
501
- __privateGet$5(this, _namespaces).records = new RecordsApi(__privateGet$5(this, _extraProps));
502
- return __privateGet$5(this, _namespaces).records;
755
+ if (!__privateGet$7(this, _namespaces).records)
756
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
757
+ return __privateGet$7(this, _namespaces).records;
758
+ }
759
+ get migrationRequests() {
760
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
761
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
762
+ return __privateGet$7(this, _namespaces).migrationRequests;
763
+ }
764
+ get branchSchema() {
765
+ if (!__privateGet$7(this, _namespaces).branchSchema)
766
+ __privateGet$7(this, _namespaces).branchSchema = new BranchSchemaApi(__privateGet$7(this, _extraProps));
767
+ return __privateGet$7(this, _namespaces).branchSchema;
503
768
  }
504
769
  }
505
770
  _extraProps = new WeakMap();
@@ -591,6 +856,13 @@ class WorkspaceApi {
591
856
  ...this.extraProps
592
857
  });
593
858
  }
859
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
860
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
861
+ pathParams: { workspaceId, inviteId },
862
+ body: { role },
863
+ ...this.extraProps
864
+ });
865
+ }
594
866
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
595
867
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
596
868
  pathParams: { workspaceId, inviteId },
@@ -633,6 +905,46 @@ class DatabaseApi {
633
905
  ...this.extraProps
634
906
  });
635
907
  }
908
+ getDatabaseMetadata(workspace, dbName) {
909
+ return operationsByTag.database.getDatabaseMetadata({
910
+ pathParams: { workspace, dbName },
911
+ ...this.extraProps
912
+ });
913
+ }
914
+ updateDatabaseMetadata(workspace, dbName, options = {}) {
915
+ return operationsByTag.database.updateDatabaseMetadata({
916
+ pathParams: { workspace, dbName },
917
+ body: options,
918
+ ...this.extraProps
919
+ });
920
+ }
921
+ getGitBranchesMapping(workspace, dbName) {
922
+ return operationsByTag.database.getGitBranchesMapping({
923
+ pathParams: { workspace, dbName },
924
+ ...this.extraProps
925
+ });
926
+ }
927
+ addGitBranchesEntry(workspace, dbName, body) {
928
+ return operationsByTag.database.addGitBranchesEntry({
929
+ pathParams: { workspace, dbName },
930
+ body,
931
+ ...this.extraProps
932
+ });
933
+ }
934
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
935
+ return operationsByTag.database.removeGitBranchesEntry({
936
+ pathParams: { workspace, dbName },
937
+ queryParams: { gitBranch },
938
+ ...this.extraProps
939
+ });
940
+ }
941
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
942
+ return operationsByTag.database.resolveBranch({
943
+ pathParams: { workspace, dbName },
944
+ queryParams: { gitBranch, fallbackBranch },
945
+ ...this.extraProps
946
+ });
947
+ }
636
948
  }
637
949
  class BranchApi {
638
950
  constructor(extraProps) {
@@ -650,10 +962,10 @@ class BranchApi {
650
962
  ...this.extraProps
651
963
  });
652
964
  }
653
- createBranch(workspace, database, branch, from = "", options = {}) {
965
+ createBranch(workspace, database, branch, from, options = {}) {
654
966
  return operationsByTag.branch.createBranch({
655
967
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
656
- queryParams: { from },
968
+ queryParams: isString(from) ? { from } : void 0,
657
969
  body: options,
658
970
  ...this.extraProps
659
971
  });
@@ -677,27 +989,6 @@ class BranchApi {
677
989
  ...this.extraProps
678
990
  });
679
991
  }
680
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
681
- return operationsByTag.branch.getBranchMigrationHistory({
682
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
683
- body: options,
684
- ...this.extraProps
685
- });
686
- }
687
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
688
- return operationsByTag.branch.executeBranchMigrationPlan({
689
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
690
- body: migrationPlan,
691
- ...this.extraProps
692
- });
693
- }
694
- getBranchMigrationPlan(workspace, database, branch, schema) {
695
- return operationsByTag.branch.getBranchMigrationPlan({
696
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
697
- body: schema,
698
- ...this.extraProps
699
- });
700
- }
701
992
  getBranchStats(workspace, database, branch) {
702
993
  return operationsByTag.branch.getBranchStats({
703
994
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -778,9 +1069,10 @@ class RecordsApi {
778
1069
  constructor(extraProps) {
779
1070
  this.extraProps = extraProps;
780
1071
  }
781
- insertRecord(workspace, database, branch, tableName, record) {
1072
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
782
1073
  return operationsByTag.records.insertRecord({
783
1074
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1075
+ queryParams: options,
784
1076
  body: record,
785
1077
  ...this.extraProps
786
1078
  });
@@ -809,21 +1101,24 @@ class RecordsApi {
809
1101
  ...this.extraProps
810
1102
  });
811
1103
  }
812
- deleteRecord(workspace, database, branch, tableName, recordId) {
1104
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
813
1105
  return operationsByTag.records.deleteRecord({
814
1106
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1107
+ queryParams: options,
815
1108
  ...this.extraProps
816
1109
  });
817
1110
  }
818
1111
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
819
1112
  return operationsByTag.records.getRecord({
820
1113
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1114
+ queryParams: options,
821
1115
  ...this.extraProps
822
1116
  });
823
1117
  }
824
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1118
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
825
1119
  return operationsByTag.records.bulkInsertTableRecords({
826
1120
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1121
+ queryParams: options,
827
1122
  body: { records },
828
1123
  ...this.extraProps
829
1124
  });
@@ -835,6 +1130,13 @@ class RecordsApi {
835
1130
  ...this.extraProps
836
1131
  });
837
1132
  }
1133
+ searchTable(workspace, database, branch, tableName, query) {
1134
+ return operationsByTag.records.searchTable({
1135
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1136
+ body: query,
1137
+ ...this.extraProps
1138
+ });
1139
+ }
838
1140
  searchBranch(workspace, database, branch, query) {
839
1141
  return operationsByTag.records.searchBranch({
840
1142
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -842,6 +1144,138 @@ class RecordsApi {
842
1144
  ...this.extraProps
843
1145
  });
844
1146
  }
1147
+ summarizeTable(workspace, database, branch, tableName, query) {
1148
+ return operationsByTag.records.summarizeTable({
1149
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1150
+ body: query,
1151
+ ...this.extraProps
1152
+ });
1153
+ }
1154
+ }
1155
+ class MigrationRequestsApi {
1156
+ constructor(extraProps) {
1157
+ this.extraProps = extraProps;
1158
+ }
1159
+ queryMigrationRequests(workspace, database, options = {}) {
1160
+ return operationsByTag.migrationRequests.queryMigrationRequests({
1161
+ pathParams: { workspace, dbName: database },
1162
+ body: options,
1163
+ ...this.extraProps
1164
+ });
1165
+ }
1166
+ createMigrationRequest(workspace, database, options) {
1167
+ return operationsByTag.migrationRequests.createMigrationRequest({
1168
+ pathParams: { workspace, dbName: database },
1169
+ body: options,
1170
+ ...this.extraProps
1171
+ });
1172
+ }
1173
+ getMigrationRequest(workspace, database, migrationRequest) {
1174
+ return operationsByTag.migrationRequests.getMigrationRequest({
1175
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1176
+ ...this.extraProps
1177
+ });
1178
+ }
1179
+ updateMigrationRequest(workspace, database, migrationRequest, options) {
1180
+ return operationsByTag.migrationRequests.updateMigrationRequest({
1181
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1182
+ body: options,
1183
+ ...this.extraProps
1184
+ });
1185
+ }
1186
+ listMigrationRequestsCommits(workspace, database, migrationRequest, options = {}) {
1187
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1188
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1189
+ body: options,
1190
+ ...this.extraProps
1191
+ });
1192
+ }
1193
+ compareMigrationRequest(workspace, database, migrationRequest) {
1194
+ return operationsByTag.migrationRequests.compareMigrationRequest({
1195
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1196
+ ...this.extraProps
1197
+ });
1198
+ }
1199
+ getMigrationRequestIsMerged(workspace, database, migrationRequest) {
1200
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1201
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1202
+ ...this.extraProps
1203
+ });
1204
+ }
1205
+ mergeMigrationRequest(workspace, database, migrationRequest) {
1206
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
1207
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1208
+ ...this.extraProps
1209
+ });
1210
+ }
1211
+ }
1212
+ class BranchSchemaApi {
1213
+ constructor(extraProps) {
1214
+ this.extraProps = extraProps;
1215
+ }
1216
+ getBranchMigrationHistory(workspace, database, branch, options = {}) {
1217
+ return operationsByTag.branchSchema.getBranchMigrationHistory({
1218
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1219
+ body: options,
1220
+ ...this.extraProps
1221
+ });
1222
+ }
1223
+ executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
1224
+ return operationsByTag.branchSchema.executeBranchMigrationPlan({
1225
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1226
+ body: migrationPlan,
1227
+ ...this.extraProps
1228
+ });
1229
+ }
1230
+ getBranchMigrationPlan(workspace, database, branch, schema) {
1231
+ return operationsByTag.branchSchema.getBranchMigrationPlan({
1232
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1233
+ body: schema,
1234
+ ...this.extraProps
1235
+ });
1236
+ }
1237
+ compareBranchWithUserSchema(workspace, database, branch, schema) {
1238
+ return operationsByTag.branchSchema.compareBranchWithUserSchema({
1239
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1240
+ body: { schema },
1241
+ ...this.extraProps
1242
+ });
1243
+ }
1244
+ compareBranchSchemas(workspace, database, branch, branchName, schema) {
1245
+ return operationsByTag.branchSchema.compareBranchSchemas({
1246
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, branchName },
1247
+ body: { schema },
1248
+ ...this.extraProps
1249
+ });
1250
+ }
1251
+ updateBranchSchema(workspace, database, branch, migration) {
1252
+ return operationsByTag.branchSchema.updateBranchSchema({
1253
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1254
+ body: migration,
1255
+ ...this.extraProps
1256
+ });
1257
+ }
1258
+ previewBranchSchemaEdit(workspace, database, branch, migration) {
1259
+ return operationsByTag.branchSchema.previewBranchSchemaEdit({
1260
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1261
+ body: migration,
1262
+ ...this.extraProps
1263
+ });
1264
+ }
1265
+ applyBranchSchemaEdit(workspace, database, branch, edits) {
1266
+ return operationsByTag.branchSchema.applyBranchSchemaEdit({
1267
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1268
+ body: { edits },
1269
+ ...this.extraProps
1270
+ });
1271
+ }
1272
+ getBranchSchemaHistory(workspace, database, branch, options = {}) {
1273
+ return operationsByTag.branchSchema.getBranchSchemaHistory({
1274
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1275
+ body: options,
1276
+ ...this.extraProps
1277
+ });
1278
+ }
845
1279
  }
846
1280
 
847
1281
  class XataApiPlugin {
@@ -854,43 +1288,43 @@ class XataApiPlugin {
854
1288
  class XataPlugin {
855
1289
  }
856
1290
 
857
- var __accessCheck$5 = (obj, member, msg) => {
1291
+ var __accessCheck$6 = (obj, member, msg) => {
858
1292
  if (!member.has(obj))
859
1293
  throw TypeError("Cannot " + msg);
860
1294
  };
861
- var __privateGet$4 = (obj, member, getter) => {
862
- __accessCheck$5(obj, member, "read from private field");
1295
+ var __privateGet$6 = (obj, member, getter) => {
1296
+ __accessCheck$6(obj, member, "read from private field");
863
1297
  return getter ? getter.call(obj) : member.get(obj);
864
1298
  };
865
- var __privateAdd$5 = (obj, member, value) => {
1299
+ var __privateAdd$6 = (obj, member, value) => {
866
1300
  if (member.has(obj))
867
1301
  throw TypeError("Cannot add the same private member more than once");
868
1302
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
869
1303
  };
870
- var __privateSet$3 = (obj, member, value, setter) => {
871
- __accessCheck$5(obj, member, "write to private field");
1304
+ var __privateSet$6 = (obj, member, value, setter) => {
1305
+ __accessCheck$6(obj, member, "write to private field");
872
1306
  setter ? setter.call(obj, value) : member.set(obj, value);
873
1307
  return value;
874
1308
  };
875
- var _query;
1309
+ var _query, _page;
876
1310
  class Page {
877
1311
  constructor(query, meta, records = []) {
878
- __privateAdd$5(this, _query, void 0);
879
- __privateSet$3(this, _query, query);
1312
+ __privateAdd$6(this, _query, void 0);
1313
+ __privateSet$6(this, _query, query);
880
1314
  this.meta = meta;
881
- this.records = records;
1315
+ this.records = new RecordArray(this, records);
882
1316
  }
883
1317
  async nextPage(size, offset) {
884
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1318
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
885
1319
  }
886
1320
  async previousPage(size, offset) {
887
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1321
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
888
1322
  }
889
1323
  async firstPage(size, offset) {
890
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1324
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
891
1325
  }
892
1326
  async lastPage(size, offset) {
893
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1327
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
894
1328
  }
895
1329
  hasNextPage() {
896
1330
  return this.meta.page.more;
@@ -898,50 +1332,104 @@ class Page {
898
1332
  }
899
1333
  _query = new WeakMap();
900
1334
  const PAGINATION_MAX_SIZE = 200;
901
- const PAGINATION_DEFAULT_SIZE = 200;
1335
+ const PAGINATION_DEFAULT_SIZE = 20;
902
1336
  const PAGINATION_MAX_OFFSET = 800;
903
1337
  const PAGINATION_DEFAULT_OFFSET = 0;
1338
+ function isCursorPaginationOptions(options) {
1339
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1340
+ }
1341
+ const _RecordArray = class extends Array {
1342
+ constructor(...args) {
1343
+ super(..._RecordArray.parseConstructorParams(...args));
1344
+ __privateAdd$6(this, _page, void 0);
1345
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1346
+ }
1347
+ static parseConstructorParams(...args) {
1348
+ if (args.length === 1 && typeof args[0] === "number") {
1349
+ return new Array(args[0]);
1350
+ }
1351
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1352
+ const result = args[1] ?? args[0].records ?? [];
1353
+ return new Array(...result);
1354
+ }
1355
+ return new Array(...args);
1356
+ }
1357
+ toArray() {
1358
+ return new Array(...this);
1359
+ }
1360
+ map(callbackfn, thisArg) {
1361
+ return this.toArray().map(callbackfn, thisArg);
1362
+ }
1363
+ async nextPage(size, offset) {
1364
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1365
+ return new _RecordArray(newPage);
1366
+ }
1367
+ async previousPage(size, offset) {
1368
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1369
+ return new _RecordArray(newPage);
1370
+ }
1371
+ async firstPage(size, offset) {
1372
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1373
+ return new _RecordArray(newPage);
1374
+ }
1375
+ async lastPage(size, offset) {
1376
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1377
+ return new _RecordArray(newPage);
1378
+ }
1379
+ hasNextPage() {
1380
+ return __privateGet$6(this, _page).meta.page.more;
1381
+ }
1382
+ };
1383
+ let RecordArray = _RecordArray;
1384
+ _page = new WeakMap();
904
1385
 
905
- var __accessCheck$4 = (obj, member, msg) => {
1386
+ var __accessCheck$5 = (obj, member, msg) => {
906
1387
  if (!member.has(obj))
907
1388
  throw TypeError("Cannot " + msg);
908
1389
  };
909
- var __privateGet$3 = (obj, member, getter) => {
910
- __accessCheck$4(obj, member, "read from private field");
1390
+ var __privateGet$5 = (obj, member, getter) => {
1391
+ __accessCheck$5(obj, member, "read from private field");
911
1392
  return getter ? getter.call(obj) : member.get(obj);
912
1393
  };
913
- var __privateAdd$4 = (obj, member, value) => {
1394
+ var __privateAdd$5 = (obj, member, value) => {
914
1395
  if (member.has(obj))
915
1396
  throw TypeError("Cannot add the same private member more than once");
916
1397
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
917
1398
  };
918
- var __privateSet$2 = (obj, member, value, setter) => {
919
- __accessCheck$4(obj, member, "write to private field");
1399
+ var __privateSet$5 = (obj, member, value, setter) => {
1400
+ __accessCheck$5(obj, member, "write to private field");
920
1401
  setter ? setter.call(obj, value) : member.set(obj, value);
921
1402
  return value;
922
1403
  };
923
- var _table$1, _repository, _data;
1404
+ var __privateMethod$3 = (obj, member, method) => {
1405
+ __accessCheck$5(obj, member, "access private method");
1406
+ return method;
1407
+ };
1408
+ var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
924
1409
  const _Query = class {
925
- constructor(repository, table, data, parent) {
926
- __privateAdd$4(this, _table$1, void 0);
927
- __privateAdd$4(this, _repository, void 0);
928
- __privateAdd$4(this, _data, { filter: {} });
1410
+ constructor(repository, table, data, rawParent) {
1411
+ __privateAdd$5(this, _cleanFilterConstraint);
1412
+ __privateAdd$5(this, _table$1, void 0);
1413
+ __privateAdd$5(this, _repository, void 0);
1414
+ __privateAdd$5(this, _data, { filter: {} });
929
1415
  this.meta = { page: { cursor: "start", more: true } };
930
- this.records = [];
931
- __privateSet$2(this, _table$1, table);
1416
+ this.records = new RecordArray(this, []);
1417
+ __privateSet$5(this, _table$1, table);
932
1418
  if (repository) {
933
- __privateSet$2(this, _repository, repository);
1419
+ __privateSet$5(this, _repository, repository);
934
1420
  } else {
935
- __privateSet$2(this, _repository, this);
1421
+ __privateSet$5(this, _repository, this);
936
1422
  }
937
- __privateGet$3(this, _data).filter = data.filter ?? parent?.filter ?? {};
938
- __privateGet$3(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
939
- __privateGet$3(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
940
- __privateGet$3(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
941
- __privateGet$3(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
942
- __privateGet$3(this, _data).sort = data.sort ?? parent?.sort;
943
- __privateGet$3(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
944
- __privateGet$3(this, _data).page = data.page ?? parent?.page;
1423
+ const parent = cleanParent(data, rawParent);
1424
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1425
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1426
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1427
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1428
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1429
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1430
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1431
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1432
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
945
1433
  this.any = this.any.bind(this);
946
1434
  this.all = this.all.bind(this);
947
1435
  this.not = this.not.bind(this);
@@ -952,75 +1440,111 @@ const _Query = class {
952
1440
  Object.defineProperty(this, "repository", { enumerable: false });
953
1441
  }
954
1442
  getQueryOptions() {
955
- return __privateGet$3(this, _data);
1443
+ return __privateGet$5(this, _data);
1444
+ }
1445
+ key() {
1446
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1447
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1448
+ return toBase64(key);
956
1449
  }
957
1450
  any(...queries) {
958
1451
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
959
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $any } }, __privateGet$3(this, _data));
1452
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
960
1453
  }
961
1454
  all(...queries) {
962
1455
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
963
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1456
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
964
1457
  }
965
1458
  not(...queries) {
966
1459
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
967
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $not } }, __privateGet$3(this, _data));
1460
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
968
1461
  }
969
1462
  none(...queries) {
970
1463
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
971
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $none } }, __privateGet$3(this, _data));
1464
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
972
1465
  }
973
1466
  filter(a, b) {
974
1467
  if (arguments.length === 1) {
975
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
976
- const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat(constraints));
977
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1468
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
1469
+ [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
1470
+ }));
1471
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1472
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
978
1473
  } else {
979
- const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
980
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1474
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
1475
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1476
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
981
1477
  }
982
1478
  }
983
- sort(column, direction) {
984
- const originalSort = [__privateGet$3(this, _data).sort ?? []].flat();
1479
+ sort(column, direction = "asc") {
1480
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
985
1481
  const sort = [...originalSort, { column, direction }];
986
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { sort }, __privateGet$3(this, _data));
1482
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
987
1483
  }
988
1484
  select(columns) {
989
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { columns }, __privateGet$3(this, _data));
1485
+ return new _Query(
1486
+ __privateGet$5(this, _repository),
1487
+ __privateGet$5(this, _table$1),
1488
+ { columns },
1489
+ __privateGet$5(this, _data)
1490
+ );
990
1491
  }
991
1492
  getPaginated(options = {}) {
992
- const query = new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), options, __privateGet$3(this, _data));
993
- return __privateGet$3(this, _repository).query(query);
1493
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1494
+ return __privateGet$5(this, _repository).query(query);
994
1495
  }
995
1496
  async *[Symbol.asyncIterator]() {
996
- for await (const [record] of this.getIterator(1)) {
1497
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
997
1498
  yield record;
998
1499
  }
999
1500
  }
1000
- async *getIterator(chunk, options = {}) {
1001
- let offset = 0;
1002
- let end = false;
1003
- while (!end) {
1004
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1005
- yield records;
1006
- offset += chunk;
1007
- end = !meta.page.more;
1501
+ async *getIterator(options = {}) {
1502
+ const { batchSize = 1 } = options;
1503
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1504
+ let more = page.hasNextPage();
1505
+ yield page.records;
1506
+ while (more) {
1507
+ page = await page.nextPage();
1508
+ more = page.hasNextPage();
1509
+ yield page.records;
1008
1510
  }
1009
1511
  }
1010
1512
  async getMany(options = {}) {
1011
- const { records } = await this.getPaginated(options);
1012
- return records;
1513
+ const { pagination = {}, ...rest } = options;
1514
+ const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
1515
+ const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
1516
+ let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
1517
+ const results = [...page.records];
1518
+ while (page.hasNextPage() && results.length < size) {
1519
+ page = await page.nextPage();
1520
+ results.push(...page.records);
1521
+ }
1522
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1523
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1524
+ }
1525
+ const array = new RecordArray(page, results.slice(0, size));
1526
+ return array;
1013
1527
  }
1014
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1528
+ async getAll(options = {}) {
1529
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1015
1530
  const results = [];
1016
- for await (const page of this.getIterator(chunk, options)) {
1531
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1017
1532
  results.push(...page);
1018
1533
  }
1019
1534
  return results;
1020
1535
  }
1021
- async getOne(options = {}) {
1022
- const records = await this.getMany({ ...options, page: { size: 1 } });
1023
- return records[0] || null;
1536
+ async getFirst(options = {}) {
1537
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1538
+ return records[0] ?? null;
1539
+ }
1540
+ async getFirstOrThrow(options = {}) {
1541
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1542
+ if (records[0] === void 0)
1543
+ throw new Error("No results found.");
1544
+ return records[0];
1545
+ }
1546
+ cache(ttl) {
1547
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1024
1548
  }
1025
1549
  nextPage(size, offset) {
1026
1550
  return this.firstPage(size, offset);
@@ -1029,10 +1553,10 @@ const _Query = class {
1029
1553
  return this.firstPage(size, offset);
1030
1554
  }
1031
1555
  firstPage(size, offset) {
1032
- return this.getPaginated({ page: { size, offset } });
1556
+ return this.getPaginated({ pagination: { size, offset } });
1033
1557
  }
1034
1558
  lastPage(size, offset) {
1035
- return this.getPaginated({ page: { size, offset, before: "end" } });
1559
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1036
1560
  }
1037
1561
  hasNextPage() {
1038
1562
  return this.meta.page.more;
@@ -1042,12 +1566,31 @@ let Query = _Query;
1042
1566
  _table$1 = new WeakMap();
1043
1567
  _repository = new WeakMap();
1044
1568
  _data = new WeakMap();
1569
+ _cleanFilterConstraint = new WeakSet();
1570
+ cleanFilterConstraint_fn = function(column, value) {
1571
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
1572
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
1573
+ return { $includes: value };
1574
+ }
1575
+ if (columnType === "link" && isObject(value) && isString(value.id)) {
1576
+ return value.id;
1577
+ }
1578
+ return value;
1579
+ };
1580
+ function cleanParent(data, parent) {
1581
+ if (isCursorPaginationOptions(data.pagination)) {
1582
+ return { ...parent, sorting: void 0, filter: void 0 };
1583
+ }
1584
+ return parent;
1585
+ }
1045
1586
 
1046
1587
  function isIdentifiable(x) {
1047
1588
  return isObject(x) && isString(x?.id);
1048
1589
  }
1049
1590
  function isXataRecord(x) {
1050
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1591
+ const record = x;
1592
+ const metadata = record?.getMetadata();
1593
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1051
1594
  }
1052
1595
 
1053
1596
  function isSortFilterString(value) {
@@ -1073,249 +1616,434 @@ function buildSortFilter(filter) {
1073
1616
  }
1074
1617
  }
1075
1618
 
1076
- var __accessCheck$3 = (obj, member, msg) => {
1619
+ var __accessCheck$4 = (obj, member, msg) => {
1077
1620
  if (!member.has(obj))
1078
1621
  throw TypeError("Cannot " + msg);
1079
1622
  };
1080
- var __privateGet$2 = (obj, member, getter) => {
1081
- __accessCheck$3(obj, member, "read from private field");
1623
+ var __privateGet$4 = (obj, member, getter) => {
1624
+ __accessCheck$4(obj, member, "read from private field");
1082
1625
  return getter ? getter.call(obj) : member.get(obj);
1083
1626
  };
1084
- var __privateAdd$3 = (obj, member, value) => {
1627
+ var __privateAdd$4 = (obj, member, value) => {
1085
1628
  if (member.has(obj))
1086
1629
  throw TypeError("Cannot add the same private member more than once");
1087
1630
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1088
1631
  };
1089
- var __privateSet$1 = (obj, member, value, setter) => {
1090
- __accessCheck$3(obj, member, "write to private field");
1632
+ var __privateSet$4 = (obj, member, value, setter) => {
1633
+ __accessCheck$4(obj, member, "write to private field");
1091
1634
  setter ? setter.call(obj, value) : member.set(obj, value);
1092
1635
  return value;
1093
1636
  };
1094
1637
  var __privateMethod$2 = (obj, member, method) => {
1095
- __accessCheck$3(obj, member, "access private method");
1638
+ __accessCheck$4(obj, member, "access private method");
1096
1639
  return method;
1097
1640
  };
1098
- var _table, _links, _getFetchProps, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn;
1641
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
1099
1642
  class Repository extends Query {
1100
1643
  }
1101
1644
  class RestRepository extends Query {
1102
1645
  constructor(options) {
1103
- super(null, options.table, {});
1104
- __privateAdd$3(this, _insertRecordWithoutId);
1105
- __privateAdd$3(this, _insertRecordWithId);
1106
- __privateAdd$3(this, _bulkInsertTableRecords);
1107
- __privateAdd$3(this, _updateRecordWithID);
1108
- __privateAdd$3(this, _upsertRecordWithID);
1109
- __privateAdd$3(this, _deleteRecord);
1110
- __privateAdd$3(this, _table, void 0);
1111
- __privateAdd$3(this, _links, void 0);
1112
- __privateAdd$3(this, _getFetchProps, void 0);
1113
- __privateSet$1(this, _table, options.table);
1114
- __privateSet$1(this, _links, options.links ?? {});
1115
- __privateSet$1(this, _getFetchProps, options.getFetchProps);
1116
- this.db = options.db;
1117
- }
1118
- async create(a, b) {
1119
- if (Array.isArray(a)) {
1120
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1121
- }
1122
- if (isString(a) && isObject(b)) {
1123
- if (a === "")
1124
- throw new Error("The id can't be empty");
1125
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1126
- }
1127
- if (isObject(a) && isString(a.id)) {
1128
- if (a.id === "")
1129
- throw new Error("The id can't be empty");
1130
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1131
- }
1132
- if (isObject(a)) {
1133
- return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1134
- }
1135
- throw new Error("Invalid arguments for create method");
1136
- }
1137
- async read(recordId) {
1138
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1139
- try {
1140
- const response = await getRecord({
1141
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1142
- ...fetchProps
1646
+ super(
1647
+ null,
1648
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
1649
+ {}
1650
+ );
1651
+ __privateAdd$4(this, _insertRecordWithoutId);
1652
+ __privateAdd$4(this, _insertRecordWithId);
1653
+ __privateAdd$4(this, _bulkInsertTableRecords);
1654
+ __privateAdd$4(this, _updateRecordWithID);
1655
+ __privateAdd$4(this, _upsertRecordWithID);
1656
+ __privateAdd$4(this, _deleteRecord);
1657
+ __privateAdd$4(this, _setCacheQuery);
1658
+ __privateAdd$4(this, _getCacheQuery);
1659
+ __privateAdd$4(this, _getSchemaTables$1);
1660
+ __privateAdd$4(this, _table, void 0);
1661
+ __privateAdd$4(this, _getFetchProps, void 0);
1662
+ __privateAdd$4(this, _db, void 0);
1663
+ __privateAdd$4(this, _cache, void 0);
1664
+ __privateAdd$4(this, _schemaTables$2, void 0);
1665
+ __privateAdd$4(this, _trace, void 0);
1666
+ __privateSet$4(this, _table, options.table);
1667
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1668
+ __privateSet$4(this, _db, options.db);
1669
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1670
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1671
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1672
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1673
+ return trace(name, fn, {
1674
+ ...options2,
1675
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1676
+ [TraceAttributes.KIND]: "sdk-operation",
1677
+ [TraceAttributes.VERSION]: VERSION
1143
1678
  });
1144
- return initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), response);
1145
- } catch (e) {
1146
- if (isObject(e) && e.status === 404) {
1147
- return null;
1679
+ });
1680
+ }
1681
+ async create(a, b, c) {
1682
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1683
+ if (Array.isArray(a)) {
1684
+ if (a.length === 0)
1685
+ return [];
1686
+ const columns = isStringArray(b) ? b : void 0;
1687
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1148
1688
  }
1149
- throw e;
1150
- }
1689
+ if (isString(a) && isObject(b)) {
1690
+ if (a === "")
1691
+ throw new Error("The id can't be empty");
1692
+ const columns = isStringArray(c) ? c : void 0;
1693
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1694
+ }
1695
+ if (isObject(a) && isString(a.id)) {
1696
+ if (a.id === "")
1697
+ throw new Error("The id can't be empty");
1698
+ const columns = isStringArray(b) ? b : void 0;
1699
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1700
+ }
1701
+ if (isObject(a)) {
1702
+ const columns = isStringArray(b) ? b : void 0;
1703
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1704
+ }
1705
+ throw new Error("Invalid arguments for create method");
1706
+ });
1151
1707
  }
1152
- async update(a, b) {
1153
- if (Array.isArray(a)) {
1154
- if (a.length > 100) {
1155
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1708
+ async read(a, b) {
1709
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1710
+ const columns = isStringArray(b) ? b : ["*"];
1711
+ if (Array.isArray(a)) {
1712
+ if (a.length === 0)
1713
+ return [];
1714
+ const ids = a.map((item) => extractId(item));
1715
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1716
+ const dictionary = finalObjects.reduce((acc, object) => {
1717
+ acc[object.id] = object;
1718
+ return acc;
1719
+ }, {});
1720
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1156
1721
  }
1157
- return Promise.all(a.map((object) => this.update(object)));
1158
- }
1159
- if (isString(a) && isObject(b)) {
1160
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1161
- }
1162
- if (isObject(a) && isString(a.id)) {
1163
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1164
- }
1165
- throw new Error("Invalid arguments for update method");
1722
+ const id = extractId(a);
1723
+ if (id) {
1724
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1725
+ try {
1726
+ const response = await getRecord({
1727
+ pathParams: {
1728
+ workspace: "{workspaceId}",
1729
+ dbBranchName: "{dbBranch}",
1730
+ tableName: __privateGet$4(this, _table),
1731
+ recordId: id
1732
+ },
1733
+ queryParams: { columns },
1734
+ ...fetchProps
1735
+ });
1736
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1737
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1738
+ } catch (e) {
1739
+ if (isObject(e) && e.status === 404) {
1740
+ return null;
1741
+ }
1742
+ throw e;
1743
+ }
1744
+ }
1745
+ return null;
1746
+ });
1166
1747
  }
1167
- async createOrUpdate(a, b) {
1168
- if (Array.isArray(a)) {
1169
- if (a.length > 100) {
1170
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1748
+ async readOrThrow(a, b) {
1749
+ return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
1750
+ const result = await this.read(a, b);
1751
+ if (Array.isArray(result)) {
1752
+ const missingIds = compact(
1753
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1754
+ );
1755
+ if (missingIds.length > 0) {
1756
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1757
+ }
1758
+ return result;
1171
1759
  }
1172
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1173
- }
1174
- if (isString(a) && isObject(b)) {
1175
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1176
- }
1177
- if (isObject(a) && isString(a.id)) {
1178
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1179
- }
1180
- throw new Error("Invalid arguments for createOrUpdate method");
1760
+ if (result === null) {
1761
+ const id = extractId(a) ?? "unknown";
1762
+ throw new Error(`Record with id ${id} not found`);
1763
+ }
1764
+ return result;
1765
+ });
1181
1766
  }
1182
- async delete(recordId) {
1183
- if (Array.isArray(recordId)) {
1184
- if (recordId.length > 100) {
1185
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1767
+ async update(a, b, c) {
1768
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1769
+ if (Array.isArray(a)) {
1770
+ if (a.length === 0)
1771
+ return [];
1772
+ if (a.length > 100) {
1773
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1774
+ }
1775
+ const columns = isStringArray(b) ? b : ["*"];
1776
+ return Promise.all(a.map((object) => this.update(object, columns)));
1186
1777
  }
1187
- await Promise.all(recordId.map((id) => this.delete(id)));
1188
- return;
1189
- }
1190
- if (isString(recordId)) {
1191
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId);
1192
- return;
1193
- }
1194
- if (isObject(recordId) && isString(recordId.id)) {
1195
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId.id);
1196
- return;
1197
- }
1198
- throw new Error("Invalid arguments for delete method");
1778
+ if (isString(a) && isObject(b)) {
1779
+ const columns = isStringArray(c) ? c : void 0;
1780
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1781
+ }
1782
+ if (isObject(a) && isString(a.id)) {
1783
+ const columns = isStringArray(b) ? b : void 0;
1784
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1785
+ }
1786
+ throw new Error("Invalid arguments for update method");
1787
+ });
1788
+ }
1789
+ async updateOrThrow(a, b, c) {
1790
+ return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
1791
+ const result = await this.update(a, b, c);
1792
+ if (Array.isArray(result)) {
1793
+ const missingIds = compact(
1794
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1795
+ );
1796
+ if (missingIds.length > 0) {
1797
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1798
+ }
1799
+ return result;
1800
+ }
1801
+ if (result === null) {
1802
+ const id = extractId(a) ?? "unknown";
1803
+ throw new Error(`Record with id ${id} not found`);
1804
+ }
1805
+ return result;
1806
+ });
1807
+ }
1808
+ async createOrUpdate(a, b, c) {
1809
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1810
+ if (Array.isArray(a)) {
1811
+ if (a.length === 0)
1812
+ return [];
1813
+ if (a.length > 100) {
1814
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1815
+ }
1816
+ const columns = isStringArray(b) ? b : ["*"];
1817
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1818
+ }
1819
+ if (isString(a) && isObject(b)) {
1820
+ const columns = isStringArray(c) ? c : void 0;
1821
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1822
+ }
1823
+ if (isObject(a) && isString(a.id)) {
1824
+ const columns = isStringArray(c) ? c : void 0;
1825
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1826
+ }
1827
+ throw new Error("Invalid arguments for createOrUpdate method");
1828
+ });
1829
+ }
1830
+ async delete(a, b) {
1831
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1832
+ if (Array.isArray(a)) {
1833
+ if (a.length === 0)
1834
+ return [];
1835
+ if (a.length > 100) {
1836
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1837
+ }
1838
+ return Promise.all(a.map((id) => this.delete(id, b)));
1839
+ }
1840
+ if (isString(a)) {
1841
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1842
+ }
1843
+ if (isObject(a) && isString(a.id)) {
1844
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1845
+ }
1846
+ throw new Error("Invalid arguments for delete method");
1847
+ });
1848
+ }
1849
+ async deleteOrThrow(a, b) {
1850
+ return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
1851
+ const result = await this.delete(a, b);
1852
+ if (Array.isArray(result)) {
1853
+ const missingIds = compact(
1854
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1855
+ );
1856
+ if (missingIds.length > 0) {
1857
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1858
+ }
1859
+ return result;
1860
+ } else if (result === null) {
1861
+ const id = extractId(a) ?? "unknown";
1862
+ throw new Error(`Record with id ${id} not found`);
1863
+ }
1864
+ return result;
1865
+ });
1199
1866
  }
1200
1867
  async search(query, options = {}) {
1201
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1202
- const { records } = await searchBranch({
1203
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1204
- body: { tables: [__privateGet$2(this, _table)], query, fuzziness: options.fuzziness },
1205
- ...fetchProps
1868
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1869
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1870
+ const { records } = await searchTable({
1871
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1872
+ body: {
1873
+ query,
1874
+ fuzziness: options.fuzziness,
1875
+ prefix: options.prefix,
1876
+ highlight: options.highlight,
1877
+ filter: options.filter,
1878
+ boosters: options.boosters
1879
+ },
1880
+ ...fetchProps
1881
+ });
1882
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1883
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
1206
1884
  });
1207
- return records.map((item) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), item));
1208
1885
  }
1209
1886
  async query(query) {
1210
- const data = query.getQueryOptions();
1211
- const body = {
1212
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1213
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1214
- page: data.page,
1215
- columns: data.columns
1216
- };
1217
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1218
- const { meta, records: objects } = await queryTable({
1219
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1220
- body,
1221
- ...fetchProps
1887
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1888
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1889
+ if (cacheQuery)
1890
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1891
+ const data = query.getQueryOptions();
1892
+ const body = {
1893
+ filter: cleanFilter(data.filter),
1894
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1895
+ page: data.pagination,
1896
+ columns: data.columns
1897
+ };
1898
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1899
+ const { meta, records: objects } = await queryTable({
1900
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1901
+ body,
1902
+ ...fetchProps
1903
+ });
1904
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1905
+ const records = objects.map(
1906
+ (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
1907
+ );
1908
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1909
+ return new Page(query, meta, records);
1222
1910
  });
1223
- const records = objects.map((record) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), record));
1224
- return new Page(query, meta, records);
1225
1911
  }
1226
1912
  }
1227
1913
  _table = new WeakMap();
1228
- _links = new WeakMap();
1229
1914
  _getFetchProps = new WeakMap();
1915
+ _db = new WeakMap();
1916
+ _cache = new WeakMap();
1917
+ _schemaTables$2 = new WeakMap();
1918
+ _trace = new WeakMap();
1230
1919
  _insertRecordWithoutId = new WeakSet();
1231
- insertRecordWithoutId_fn = async function(object) {
1232
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1920
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1921
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1233
1922
  const record = transformObjectLinks(object);
1234
1923
  const response = await insertRecord({
1235
1924
  pathParams: {
1236
1925
  workspace: "{workspaceId}",
1237
1926
  dbBranchName: "{dbBranch}",
1238
- tableName: __privateGet$2(this, _table)
1927
+ tableName: __privateGet$4(this, _table)
1239
1928
  },
1929
+ queryParams: { columns },
1240
1930
  body: record,
1241
1931
  ...fetchProps
1242
1932
  });
1243
- const finalObject = await this.read(response.id);
1244
- if (!finalObject) {
1245
- throw new Error("The server failed to save the record");
1246
- }
1247
- return finalObject;
1933
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1934
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1248
1935
  };
1249
1936
  _insertRecordWithId = new WeakSet();
1250
- insertRecordWithId_fn = async function(recordId, object) {
1251
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1937
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1938
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1252
1939
  const record = transformObjectLinks(object);
1253
1940
  const response = await insertRecordWithID({
1254
1941
  pathParams: {
1255
1942
  workspace: "{workspaceId}",
1256
1943
  dbBranchName: "{dbBranch}",
1257
- tableName: __privateGet$2(this, _table),
1944
+ tableName: __privateGet$4(this, _table),
1258
1945
  recordId
1259
1946
  },
1260
1947
  body: record,
1261
- queryParams: { createOnly: true },
1948
+ queryParams: { createOnly: true, columns },
1262
1949
  ...fetchProps
1263
1950
  });
1264
- const finalObject = await this.read(response.id);
1265
- if (!finalObject) {
1266
- throw new Error("The server failed to save the record");
1267
- }
1268
- return finalObject;
1951
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1952
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1269
1953
  };
1270
1954
  _bulkInsertTableRecords = new WeakSet();
1271
- bulkInsertTableRecords_fn = async function(objects) {
1272
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1955
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1956
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1273
1957
  const records = objects.map((object) => transformObjectLinks(object));
1274
1958
  const response = await bulkInsertTableRecords({
1275
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1959
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1960
+ queryParams: { columns },
1276
1961
  body: { records },
1277
1962
  ...fetchProps
1278
1963
  });
1279
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1280
- if (finalObjects.length !== objects.length) {
1281
- throw new Error("The server failed to save some records");
1964
+ if (!isResponseWithRecords(response)) {
1965
+ throw new Error("Request included columns but server didn't include them");
1282
1966
  }
1283
- return finalObjects;
1967
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1968
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
1284
1969
  };
1285
1970
  _updateRecordWithID = new WeakSet();
1286
- updateRecordWithID_fn = async function(recordId, object) {
1287
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1971
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1972
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1288
1973
  const record = transformObjectLinks(object);
1289
- const response = await updateRecordWithID({
1290
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1291
- body: record,
1292
- ...fetchProps
1293
- });
1294
- const item = await this.read(response.id);
1295
- if (!item)
1296
- throw new Error("The server failed to save the record");
1297
- return item;
1974
+ try {
1975
+ const response = await updateRecordWithID({
1976
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1977
+ queryParams: { columns },
1978
+ body: record,
1979
+ ...fetchProps
1980
+ });
1981
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1982
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1983
+ } catch (e) {
1984
+ if (isObject(e) && e.status === 404) {
1985
+ return null;
1986
+ }
1987
+ throw e;
1988
+ }
1298
1989
  };
1299
1990
  _upsertRecordWithID = new WeakSet();
1300
- upsertRecordWithID_fn = async function(recordId, object) {
1301
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1991
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1992
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1302
1993
  const response = await upsertRecordWithID({
1303
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1994
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1995
+ queryParams: { columns },
1304
1996
  body: object,
1305
1997
  ...fetchProps
1306
1998
  });
1307
- const item = await this.read(response.id);
1308
- if (!item)
1309
- throw new Error("The server failed to save the record");
1310
- return item;
1999
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2000
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1311
2001
  };
1312
2002
  _deleteRecord = new WeakSet();
1313
- deleteRecord_fn = async function(recordId) {
1314
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1315
- await deleteRecord({
1316
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
2003
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2004
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2005
+ try {
2006
+ const response = await deleteRecord({
2007
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2008
+ queryParams: { columns },
2009
+ ...fetchProps
2010
+ });
2011
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2012
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2013
+ } catch (e) {
2014
+ if (isObject(e) && e.status === 404) {
2015
+ return null;
2016
+ }
2017
+ throw e;
2018
+ }
2019
+ };
2020
+ _setCacheQuery = new WeakSet();
2021
+ setCacheQuery_fn = async function(query, meta, records) {
2022
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
2023
+ };
2024
+ _getCacheQuery = new WeakSet();
2025
+ getCacheQuery_fn = async function(query) {
2026
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2027
+ const result = await __privateGet$4(this, _cache).get(key);
2028
+ if (!result)
2029
+ return null;
2030
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
2031
+ if (ttl < 0)
2032
+ return null;
2033
+ const hasExpired = result.date.getTime() + ttl < Date.now();
2034
+ return hasExpired ? null : result;
2035
+ };
2036
+ _getSchemaTables$1 = new WeakSet();
2037
+ getSchemaTables_fn$1 = async function() {
2038
+ if (__privateGet$4(this, _schemaTables$2))
2039
+ return __privateGet$4(this, _schemaTables$2);
2040
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2041
+ const { schema } = await getBranchDetails({
2042
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1317
2043
  ...fetchProps
1318
2044
  });
2045
+ __privateSet$4(this, _schemaTables$2, schema.tables);
2046
+ return schema.tables;
1319
2047
  };
1320
2048
  const transformObjectLinks = (object) => {
1321
2049
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1324,45 +2052,168 @@ const transformObjectLinks = (object) => {
1324
2052
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1325
2053
  }, {});
1326
2054
  };
1327
- const initObject = (db, links, table, object) => {
2055
+ const initObject = (db, schemaTables, table, object, selectedColumns) => {
1328
2056
  const result = {};
1329
- Object.assign(result, object);
1330
- const tableLinks = links[table] || [];
1331
- for (const link of tableLinks) {
1332
- const [field, linkTable] = link;
1333
- const value = result[field];
1334
- if (value && isObject(value)) {
1335
- result[field] = initObject(db, links, linkTable, value);
2057
+ const { xata, ...rest } = object ?? {};
2058
+ Object.assign(result, rest);
2059
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2060
+ if (!columns)
2061
+ console.error(`Table ${table} not found in schema`);
2062
+ for (const column of columns ?? []) {
2063
+ if (!isValidColumn(selectedColumns, column))
2064
+ continue;
2065
+ const value = result[column.name];
2066
+ switch (column.type) {
2067
+ case "datetime": {
2068
+ const date = value !== void 0 ? new Date(value) : void 0;
2069
+ if (date && isNaN(date.getTime())) {
2070
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
2071
+ } else if (date) {
2072
+ result[column.name] = date;
2073
+ }
2074
+ break;
2075
+ }
2076
+ case "link": {
2077
+ const linkTable = column.link?.table;
2078
+ if (!linkTable) {
2079
+ console.error(`Failed to parse link for field ${column.name}`);
2080
+ } else if (isObject(value)) {
2081
+ const selectedLinkColumns = selectedColumns.reduce((acc, item) => {
2082
+ if (item === column.name) {
2083
+ return [...acc, "*"];
2084
+ }
2085
+ if (item.startsWith(`${column.name}.`)) {
2086
+ const [, ...path] = item.split(".");
2087
+ return [...acc, path.join(".")];
2088
+ }
2089
+ return acc;
2090
+ }, []);
2091
+ result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2092
+ } else {
2093
+ result[column.name] = null;
2094
+ }
2095
+ break;
2096
+ }
2097
+ default:
2098
+ result[column.name] = value ?? null;
2099
+ if (column.notNull === true && value === null) {
2100
+ console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2101
+ }
2102
+ break;
1336
2103
  }
1337
2104
  }
1338
- result.read = function() {
1339
- return db[table].read(result["id"]);
2105
+ result.read = function(columns2) {
2106
+ return db[table].read(result["id"], columns2);
1340
2107
  };
1341
- result.update = function(data) {
1342
- return db[table].update(result["id"], data);
2108
+ result.update = function(data, columns2) {
2109
+ return db[table].update(result["id"], data, columns2);
1343
2110
  };
1344
2111
  result.delete = function() {
1345
2112
  return db[table].delete(result["id"]);
1346
2113
  };
1347
- for (const prop of ["read", "update", "delete"]) {
2114
+ result.getMetadata = function() {
2115
+ return xata;
2116
+ };
2117
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1348
2118
  Object.defineProperty(result, prop, { enumerable: false });
1349
2119
  }
1350
2120
  Object.freeze(result);
1351
2121
  return result;
1352
2122
  };
2123
+ function isResponseWithRecords(value) {
2124
+ return isObject(value) && Array.isArray(value.records);
2125
+ }
2126
+ function extractId(value) {
2127
+ if (isString(value))
2128
+ return value;
2129
+ if (isObject(value) && isString(value.id))
2130
+ return value.id;
2131
+ return void 0;
2132
+ }
2133
+ function cleanFilter(filter) {
2134
+ if (!filter)
2135
+ return void 0;
2136
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
2137
+ return values.length > 0 ? filter : void 0;
2138
+ }
2139
+ function isValidColumn(columns, column) {
2140
+ if (columns.includes("*"))
2141
+ return true;
2142
+ if (column.type === "link") {
2143
+ const linkColumns = columns.filter((item) => item.startsWith(column.name));
2144
+ return linkColumns.length > 0;
2145
+ }
2146
+ return columns.includes(column.name);
2147
+ }
2148
+
2149
+ var __accessCheck$3 = (obj, member, msg) => {
2150
+ if (!member.has(obj))
2151
+ throw TypeError("Cannot " + msg);
2152
+ };
2153
+ var __privateGet$3 = (obj, member, getter) => {
2154
+ __accessCheck$3(obj, member, "read from private field");
2155
+ return getter ? getter.call(obj) : member.get(obj);
2156
+ };
2157
+ var __privateAdd$3 = (obj, member, value) => {
2158
+ if (member.has(obj))
2159
+ throw TypeError("Cannot add the same private member more than once");
2160
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2161
+ };
2162
+ var __privateSet$3 = (obj, member, value, setter) => {
2163
+ __accessCheck$3(obj, member, "write to private field");
2164
+ setter ? setter.call(obj, value) : member.set(obj, value);
2165
+ return value;
2166
+ };
2167
+ var _map;
2168
+ class SimpleCache {
2169
+ constructor(options = {}) {
2170
+ __privateAdd$3(this, _map, void 0);
2171
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
2172
+ this.capacity = options.max ?? 500;
2173
+ this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
2174
+ }
2175
+ async getAll() {
2176
+ return Object.fromEntries(__privateGet$3(this, _map));
2177
+ }
2178
+ async get(key) {
2179
+ return __privateGet$3(this, _map).get(key) ?? null;
2180
+ }
2181
+ async set(key, value) {
2182
+ await this.delete(key);
2183
+ __privateGet$3(this, _map).set(key, value);
2184
+ if (__privateGet$3(this, _map).size > this.capacity) {
2185
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
2186
+ await this.delete(leastRecentlyUsed);
2187
+ }
2188
+ }
2189
+ async delete(key) {
2190
+ __privateGet$3(this, _map).delete(key);
2191
+ }
2192
+ async clear() {
2193
+ return __privateGet$3(this, _map).clear();
2194
+ }
2195
+ }
2196
+ _map = new WeakMap();
1353
2197
 
1354
- const gt = (value) => ({ $gt: value });
1355
- const ge = (value) => ({ $ge: value });
1356
- const gte = (value) => ({ $ge: value });
1357
- const lt = (value) => ({ $lt: value });
1358
- const lte = (value) => ({ $le: value });
1359
- const le = (value) => ({ $le: value });
2198
+ const greaterThan = (value) => ({ $gt: value });
2199
+ const gt = greaterThan;
2200
+ const greaterThanEquals = (value) => ({ $ge: value });
2201
+ const greaterEquals = greaterThanEquals;
2202
+ const gte = greaterThanEquals;
2203
+ const ge = greaterThanEquals;
2204
+ const lessThan = (value) => ({ $lt: value });
2205
+ const lt = lessThan;
2206
+ const lessThanEquals = (value) => ({ $le: value });
2207
+ const lessEquals = lessThanEquals;
2208
+ const lte = lessThanEquals;
2209
+ const le = lessThanEquals;
1360
2210
  const exists = (column) => ({ $exists: column });
1361
2211
  const notExists = (column) => ({ $notExists: column });
1362
2212
  const startsWith = (value) => ({ $startsWith: value });
1363
2213
  const endsWith = (value) => ({ $endsWith: value });
1364
2214
  const pattern = (value) => ({ $pattern: value });
1365
2215
  const is = (value) => ({ $is: value });
2216
+ const equals = is;
1366
2217
  const isNot = (value) => ({ $isNot: value });
1367
2218
  const contains = (value) => ({ $contains: value });
1368
2219
  const includes = (value) => ({ $includes: value });
@@ -1374,7 +2225,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1374
2225
  if (!member.has(obj))
1375
2226
  throw TypeError("Cannot " + msg);
1376
2227
  };
1377
- var __privateGet$1 = (obj, member, getter) => {
2228
+ var __privateGet$2 = (obj, member, getter) => {
1378
2229
  __accessCheck$2(obj, member, "read from private field");
1379
2230
  return getter ? getter.call(obj) : member.get(obj);
1380
2231
  };
@@ -1383,126 +2234,178 @@ var __privateAdd$2 = (obj, member, value) => {
1383
2234
  throw TypeError("Cannot add the same private member more than once");
1384
2235
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1385
2236
  };
1386
- var _tables;
2237
+ var __privateSet$2 = (obj, member, value, setter) => {
2238
+ __accessCheck$2(obj, member, "write to private field");
2239
+ setter ? setter.call(obj, value) : member.set(obj, value);
2240
+ return value;
2241
+ };
2242
+ var _tables, _schemaTables$1;
1387
2243
  class SchemaPlugin extends XataPlugin {
1388
- constructor(links) {
2244
+ constructor(schemaTables) {
1389
2245
  super();
1390
- this.links = links;
1391
2246
  __privateAdd$2(this, _tables, {});
1392
- }
1393
- build(options) {
1394
- const { getFetchProps } = options;
1395
- const links = this.links;
1396
- const db = new Proxy({}, {
1397
- get: (_target, table) => {
1398
- if (!isString(table))
1399
- throw new Error("Invalid table name");
1400
- if (!__privateGet$1(this, _tables)[table])
1401
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, getFetchProps, table, links });
1402
- return __privateGet$1(this, _tables)[table];
2247
+ __privateAdd$2(this, _schemaTables$1, void 0);
2248
+ __privateSet$2(this, _schemaTables$1, schemaTables);
2249
+ }
2250
+ build(pluginOptions) {
2251
+ const db = new Proxy(
2252
+ {},
2253
+ {
2254
+ get: (_target, table) => {
2255
+ if (!isString(table))
2256
+ throw new Error("Invalid table name");
2257
+ if (__privateGet$2(this, _tables)[table] === void 0) {
2258
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
2259
+ }
2260
+ return __privateGet$2(this, _tables)[table];
2261
+ }
1403
2262
  }
1404
- });
2263
+ );
2264
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
2265
+ for (const table of tableNames) {
2266
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
2267
+ }
1405
2268
  return db;
1406
2269
  }
1407
2270
  }
1408
2271
  _tables = new WeakMap();
2272
+ _schemaTables$1 = new WeakMap();
1409
2273
 
1410
2274
  var __accessCheck$1 = (obj, member, msg) => {
1411
2275
  if (!member.has(obj))
1412
2276
  throw TypeError("Cannot " + msg);
1413
2277
  };
2278
+ var __privateGet$1 = (obj, member, getter) => {
2279
+ __accessCheck$1(obj, member, "read from private field");
2280
+ return getter ? getter.call(obj) : member.get(obj);
2281
+ };
1414
2282
  var __privateAdd$1 = (obj, member, value) => {
1415
2283
  if (member.has(obj))
1416
2284
  throw TypeError("Cannot add the same private member more than once");
1417
2285
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1418
2286
  };
2287
+ var __privateSet$1 = (obj, member, value, setter) => {
2288
+ __accessCheck$1(obj, member, "write to private field");
2289
+ setter ? setter.call(obj, value) : member.set(obj, value);
2290
+ return value;
2291
+ };
1419
2292
  var __privateMethod$1 = (obj, member, method) => {
1420
2293
  __accessCheck$1(obj, member, "access private method");
1421
2294
  return method;
1422
2295
  };
1423
- var _search, search_fn;
2296
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1424
2297
  class SearchPlugin extends XataPlugin {
1425
- constructor(db, links) {
2298
+ constructor(db, schemaTables) {
1426
2299
  super();
1427
2300
  this.db = db;
1428
- this.links = links;
1429
2301
  __privateAdd$1(this, _search);
2302
+ __privateAdd$1(this, _getSchemaTables);
2303
+ __privateAdd$1(this, _schemaTables, void 0);
2304
+ __privateSet$1(this, _schemaTables, schemaTables);
1430
2305
  }
1431
2306
  build({ getFetchProps }) {
1432
2307
  return {
1433
2308
  all: async (query, options = {}) => {
1434
2309
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2310
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1435
2311
  return records.map((record) => {
1436
2312
  const { table = "orphan" } = record.xata;
1437
- return { table, record: initObject(this.db, this.links, table, record) };
2313
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
1438
2314
  });
1439
2315
  },
1440
2316
  byTable: async (query, options = {}) => {
1441
2317
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2318
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1442
2319
  return records.reduce((acc, record) => {
1443
2320
  const { table = "orphan" } = record.xata;
1444
2321
  const items = acc[table] ?? [];
1445
- const item = initObject(this.db, this.links, table, record);
2322
+ const item = initObject(this.db, schemaTables, table, record, ["*"]);
1446
2323
  return { ...acc, [table]: [...items, item] };
1447
2324
  }, {});
1448
2325
  }
1449
2326
  };
1450
2327
  }
1451
2328
  }
2329
+ _schemaTables = new WeakMap();
1452
2330
  _search = new WeakSet();
1453
2331
  search_fn = async function(query, options, getFetchProps) {
1454
2332
  const fetchProps = await getFetchProps();
1455
- const { tables, fuzziness } = options ?? {};
2333
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1456
2334
  const { records } = await searchBranch({
1457
2335
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1458
- body: { tables, query, fuzziness },
2336
+ body: { tables, query, fuzziness, prefix, highlight },
1459
2337
  ...fetchProps
1460
2338
  });
1461
2339
  return records;
1462
2340
  };
2341
+ _getSchemaTables = new WeakSet();
2342
+ getSchemaTables_fn = async function(getFetchProps) {
2343
+ if (__privateGet$1(this, _schemaTables))
2344
+ return __privateGet$1(this, _schemaTables);
2345
+ const fetchProps = await getFetchProps();
2346
+ const { schema } = await getBranchDetails({
2347
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2348
+ ...fetchProps
2349
+ });
2350
+ __privateSet$1(this, _schemaTables, schema.tables);
2351
+ return schema.tables;
2352
+ };
1463
2353
 
1464
2354
  const isBranchStrategyBuilder = (strategy) => {
1465
2355
  return typeof strategy === "function";
1466
2356
  };
1467
2357
 
1468
- const envBranchNames = [
1469
- "XATA_BRANCH",
1470
- "VERCEL_GIT_COMMIT_REF",
1471
- "CF_PAGES_BRANCH",
1472
- "BRANCH"
1473
- ];
1474
- const defaultBranch = "main";
1475
2358
  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;
2359
+ const { branch, envBranch } = getEnvironment();
2360
+ if (branch) {
2361
+ const details = await getDatabaseBranch(branch, options);
2362
+ if (details)
2363
+ return branch;
2364
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2365
+ }
2366
+ const gitBranch = envBranch || await getGitBranch();
2367
+ return resolveXataBranch(gitBranch, options);
1486
2368
  }
1487
2369
  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);
2370
+ const branch = await getCurrentBranchName(options);
2371
+ return getDatabaseBranch(branch, options);
2372
+ }
2373
+ async function resolveXataBranch(gitBranch, options) {
2374
+ const databaseURL = options?.databaseURL || getDatabaseURL();
2375
+ const apiKey = options?.apiKey || getAPIKey();
2376
+ if (!databaseURL)
2377
+ throw new Error(
2378
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2379
+ );
2380
+ if (!apiKey)
2381
+ throw new Error(
2382
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2383
+ );
2384
+ const [protocol, , host, , dbName] = databaseURL.split("/");
2385
+ const [workspace] = host.split(".");
2386
+ const { fallbackBranch } = getEnvironment();
2387
+ const { branch } = await resolveBranch({
2388
+ apiKey,
2389
+ apiUrl: databaseURL,
2390
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
2391
+ workspacesApiUrl: `${protocol}//${host}`,
2392
+ pathParams: { dbName, workspace },
2393
+ queryParams: { gitBranch, fallbackBranch },
2394
+ trace: defaultTrace
2395
+ });
2396
+ return branch;
1498
2397
  }
1499
2398
  async function getDatabaseBranch(branch, options) {
1500
2399
  const databaseURL = options?.databaseURL || getDatabaseURL();
1501
2400
  const apiKey = options?.apiKey || getAPIKey();
1502
2401
  if (!databaseURL)
1503
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2402
+ throw new Error(
2403
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2404
+ );
1504
2405
  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");
2406
+ throw new Error(
2407
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2408
+ );
1506
2409
  const [protocol, , host, , database] = databaseURL.split("/");
1507
2410
  const [workspace] = host.split(".");
1508
2411
  const dbBranchName = `${database}:${branch}`;
@@ -1512,10 +2415,8 @@ async function getDatabaseBranch(branch, options) {
1512
2415
  apiUrl: databaseURL,
1513
2416
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1514
2417
  workspacesApiUrl: `${protocol}//${host}`,
1515
- pathParams: {
1516
- dbBranchName,
1517
- workspace
1518
- }
2418
+ pathParams: { dbBranchName, workspace },
2419
+ trace: defaultTrace
1519
2420
  });
1520
2421
  } catch (err) {
1521
2422
  if (isObject(err) && err.status === 404)
@@ -1523,21 +2424,10 @@ async function getDatabaseBranch(branch, options) {
1523
2424
  throw err;
1524
2425
  }
1525
2426
  }
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
2427
  function getDatabaseURL() {
1539
2428
  try {
1540
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2429
+ const { databaseURL } = getEnvironment();
2430
+ return databaseURL;
1541
2431
  } catch (err) {
1542
2432
  return void 0;
1543
2433
  }
@@ -1566,24 +2456,29 @@ var __privateMethod = (obj, member, method) => {
1566
2456
  return method;
1567
2457
  };
1568
2458
  const buildClient = (plugins) => {
1569
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2459
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1570
2460
  return _a = class {
1571
- constructor(options = {}, links) {
2461
+ constructor(options = {}, schemaTables) {
1572
2462
  __privateAdd(this, _parseOptions);
1573
2463
  __privateAdd(this, _getFetchProps);
1574
2464
  __privateAdd(this, _evaluateBranch);
1575
2465
  __privateAdd(this, _branch, void 0);
2466
+ __privateAdd(this, _options, void 0);
1576
2467
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
1577
- const db = new SchemaPlugin(links).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
- });
2468
+ __privateSet(this, _options, safeOptions);
2469
+ const pluginOptions = {
2470
+ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
2471
+ cache: safeOptions.cache,
2472
+ trace: safeOptions.trace
2473
+ };
2474
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2475
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1581
2476
  this.db = db;
1582
2477
  this.search = search;
1583
2478
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1584
- if (!namespace)
2479
+ if (namespace === void 0)
1585
2480
  continue;
1586
- const result = namespace.build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
2481
+ const result = namespace.build(pluginOptions);
1587
2482
  if (result instanceof Promise) {
1588
2483
  void result.then((namespace2) => {
1589
2484
  this[key] = namespace2;
@@ -1593,21 +2488,26 @@ const buildClient = (plugins) => {
1593
2488
  }
1594
2489
  }
1595
2490
  }
1596
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2491
+ async getConfig() {
2492
+ const databaseURL = __privateGet(this, _options).databaseURL;
2493
+ const branch = await __privateGet(this, _options).branch();
2494
+ return { databaseURL, branch };
2495
+ }
2496
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1597
2497
  const fetch = getFetchImplementation(options?.fetch);
1598
2498
  const databaseURL = options?.databaseURL || getDatabaseURL();
1599
2499
  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 });
1601
- if (!databaseURL || !apiKey) {
1602
- throw new Error("Options databaseURL and apiKey are required");
2500
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2501
+ const trace = options?.trace ?? defaultTrace;
2502
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2503
+ if (!apiKey) {
2504
+ throw new Error("Option apiKey is required");
1603
2505
  }
1604
- return { fetch, databaseURL, apiKey, branch };
1605
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1606
- fetch,
1607
- apiKey,
1608
- databaseURL,
1609
- branch
1610
- }) {
2506
+ if (!databaseURL) {
2507
+ throw new Error("Option databaseURL is required");
2508
+ }
2509
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2510
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
1611
2511
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1612
2512
  if (!branchValue)
1613
2513
  throw new Error("Unable to resolve branch value");
@@ -1617,14 +2517,15 @@ const buildClient = (plugins) => {
1617
2517
  apiUrl: "",
1618
2518
  workspacesApiUrl: (path, params) => {
1619
2519
  const hasBranch = params.dbBranchName ?? params.branch;
1620
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
2520
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
1621
2521
  return databaseURL + newPath;
1622
- }
2522
+ },
2523
+ trace
1623
2524
  };
1624
2525
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1625
2526
  if (__privateGet(this, _branch))
1626
2527
  return __privateGet(this, _branch);
1627
- if (!param)
2528
+ if (param === void 0)
1628
2529
  return void 0;
1629
2530
  const strategies = Array.isArray(param) ? [...param] : [param];
1630
2531
  const evaluateBranch = async (strategy) => {
@@ -1642,6 +2543,88 @@ const buildClient = (plugins) => {
1642
2543
  class BaseClient extends buildClient() {
1643
2544
  }
1644
2545
 
2546
+ const META = "__";
2547
+ const VALUE = "___";
2548
+ class Serializer {
2549
+ constructor() {
2550
+ this.classes = {};
2551
+ }
2552
+ add(clazz) {
2553
+ this.classes[clazz.name] = clazz;
2554
+ }
2555
+ toJSON(data) {
2556
+ function visit(obj) {
2557
+ if (Array.isArray(obj))
2558
+ return obj.map(visit);
2559
+ const type = typeof obj;
2560
+ if (type === "undefined")
2561
+ return { [META]: "undefined" };
2562
+ if (type === "bigint")
2563
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2564
+ if (obj === null || type !== "object")
2565
+ return obj;
2566
+ const constructor = obj.constructor;
2567
+ const o = { [META]: constructor.name };
2568
+ for (const [key, value] of Object.entries(obj)) {
2569
+ o[key] = visit(value);
2570
+ }
2571
+ if (constructor === Date)
2572
+ o[VALUE] = obj.toISOString();
2573
+ if (constructor === Map)
2574
+ o[VALUE] = Object.fromEntries(obj);
2575
+ if (constructor === Set)
2576
+ o[VALUE] = [...obj];
2577
+ return o;
2578
+ }
2579
+ return JSON.stringify(visit(data));
2580
+ }
2581
+ fromJSON(json) {
2582
+ return JSON.parse(json, (key, value) => {
2583
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2584
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2585
+ const constructor = this.classes[clazz];
2586
+ if (constructor) {
2587
+ return Object.assign(Object.create(constructor.prototype), rest);
2588
+ }
2589
+ if (clazz === "Date")
2590
+ return new Date(val);
2591
+ if (clazz === "Set")
2592
+ return new Set(val);
2593
+ if (clazz === "Map")
2594
+ return new Map(Object.entries(val));
2595
+ if (clazz === "bigint")
2596
+ return BigInt(val);
2597
+ if (clazz === "undefined")
2598
+ return void 0;
2599
+ return rest;
2600
+ }
2601
+ return value;
2602
+ });
2603
+ }
2604
+ }
2605
+ const defaultSerializer = new Serializer();
2606
+ const serialize = (data) => {
2607
+ return defaultSerializer.toJSON(data);
2608
+ };
2609
+ const deserialize = (json) => {
2610
+ return defaultSerializer.fromJSON(json);
2611
+ };
2612
+
2613
+ function buildWorkerRunner(config) {
2614
+ return function xataWorker(name, _worker) {
2615
+ return async (...args) => {
2616
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2617
+ const result = await fetch(url, {
2618
+ method: "POST",
2619
+ headers: { "Content-Type": "application/json" },
2620
+ body: serialize({ args })
2621
+ });
2622
+ const text = await result.text();
2623
+ return deserialize(text);
2624
+ };
2625
+ };
2626
+ }
2627
+
1645
2628
  class XataError extends Error {
1646
2629
  constructor(message, status) {
1647
2630
  super(message);
@@ -1657,22 +2640,37 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1657
2640
  exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1658
2641
  exports.Page = Page;
1659
2642
  exports.Query = Query;
2643
+ exports.RecordArray = RecordArray;
1660
2644
  exports.Repository = Repository;
1661
2645
  exports.RestRepository = RestRepository;
1662
2646
  exports.SchemaPlugin = SchemaPlugin;
1663
2647
  exports.SearchPlugin = SearchPlugin;
2648
+ exports.Serializer = Serializer;
2649
+ exports.SimpleCache = SimpleCache;
1664
2650
  exports.XataApiClient = XataApiClient;
1665
2651
  exports.XataApiPlugin = XataApiPlugin;
1666
2652
  exports.XataError = XataError;
1667
2653
  exports.XataPlugin = XataPlugin;
1668
2654
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
2655
+ exports.addGitBranchesEntry = addGitBranchesEntry;
1669
2656
  exports.addTableColumn = addTableColumn;
2657
+ exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
1670
2658
  exports.buildClient = buildClient;
2659
+ exports.buildWorkerRunner = buildWorkerRunner;
1671
2660
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
2661
+ exports.cPcreateDatabase = cPcreateDatabase;
2662
+ exports.cPdeleteDatabase = cPdeleteDatabase;
2663
+ exports.cPgetCPDatabaseMetadata = cPgetCPDatabaseMetadata;
2664
+ exports.cPgetDatabaseList = cPgetDatabaseList;
2665
+ exports.cPupdateCPDatabaseMetadata = cPupdateCPDatabaseMetadata;
1672
2666
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
2667
+ exports.compareBranchSchemas = compareBranchSchemas;
2668
+ exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
2669
+ exports.compareMigrationRequest = compareMigrationRequest;
1673
2670
  exports.contains = contains;
1674
2671
  exports.createBranch = createBranch;
1675
2672
  exports.createDatabase = createDatabase;
2673
+ exports.createMigrationRequest = createMigrationRequest;
1676
2674
  exports.createTable = createTable;
1677
2675
  exports.createUserAPIKey = createUserAPIKey;
1678
2676
  exports.createWorkspace = createWorkspace;
@@ -1684,7 +2682,9 @@ exports.deleteTable = deleteTable;
1684
2682
  exports.deleteUser = deleteUser;
1685
2683
  exports.deleteUserAPIKey = deleteUserAPIKey;
1686
2684
  exports.deleteWorkspace = deleteWorkspace;
2685
+ exports.deserialize = deserialize;
1687
2686
  exports.endsWith = endsWith;
2687
+ exports.equals = equals;
1688
2688
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
1689
2689
  exports.exists = exists;
1690
2690
  exports.ge = ge;
@@ -1694,12 +2694,17 @@ exports.getBranchList = getBranchList;
1694
2694
  exports.getBranchMetadata = getBranchMetadata;
1695
2695
  exports.getBranchMigrationHistory = getBranchMigrationHistory;
1696
2696
  exports.getBranchMigrationPlan = getBranchMigrationPlan;
2697
+ exports.getBranchSchemaHistory = getBranchSchemaHistory;
1697
2698
  exports.getBranchStats = getBranchStats;
1698
2699
  exports.getColumn = getColumn;
1699
2700
  exports.getCurrentBranchDetails = getCurrentBranchDetails;
1700
2701
  exports.getCurrentBranchName = getCurrentBranchName;
1701
2702
  exports.getDatabaseList = getDatabaseList;
2703
+ exports.getDatabaseMetadata = getDatabaseMetadata;
1702
2704
  exports.getDatabaseURL = getDatabaseURL;
2705
+ exports.getGitBranchesMapping = getGitBranchesMapping;
2706
+ exports.getMigrationRequest = getMigrationRequest;
2707
+ exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
1703
2708
  exports.getRecord = getRecord;
1704
2709
  exports.getTableColumns = getTableColumns;
1705
2710
  exports.getTableSchema = getTableSchema;
@@ -1708,6 +2713,9 @@ exports.getUserAPIKeys = getUserAPIKeys;
1708
2713
  exports.getWorkspace = getWorkspace;
1709
2714
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
1710
2715
  exports.getWorkspacesList = getWorkspacesList;
2716
+ exports.greaterEquals = greaterEquals;
2717
+ exports.greaterThan = greaterThan;
2718
+ exports.greaterThanEquals = greaterThanEquals;
1711
2719
  exports.gt = gt;
1712
2720
  exports.gte = gte;
1713
2721
  exports.includes = includes;
@@ -1718,27 +2726,44 @@ exports.insertRecord = insertRecord;
1718
2726
  exports.insertRecordWithID = insertRecordWithID;
1719
2727
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
1720
2728
  exports.is = is;
2729
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
1721
2730
  exports.isIdentifiable = isIdentifiable;
1722
2731
  exports.isNot = isNot;
1723
2732
  exports.isXataRecord = isXataRecord;
1724
2733
  exports.le = le;
2734
+ exports.lessEquals = lessEquals;
2735
+ exports.lessThan = lessThan;
2736
+ exports.lessThanEquals = lessThanEquals;
2737
+ exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
1725
2738
  exports.lt = lt;
1726
2739
  exports.lte = lte;
2740
+ exports.mergeMigrationRequest = mergeMigrationRequest;
1727
2741
  exports.notExists = notExists;
1728
2742
  exports.operationsByTag = operationsByTag;
1729
2743
  exports.pattern = pattern;
2744
+ exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
2745
+ exports.queryMigrationRequests = queryMigrationRequests;
1730
2746
  exports.queryTable = queryTable;
2747
+ exports.removeGitBranchesEntry = removeGitBranchesEntry;
1731
2748
  exports.removeWorkspaceMember = removeWorkspaceMember;
1732
2749
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
2750
+ exports.resolveBranch = resolveBranch;
1733
2751
  exports.searchBranch = searchBranch;
2752
+ exports.searchTable = searchTable;
2753
+ exports.serialize = serialize;
1734
2754
  exports.setTableSchema = setTableSchema;
1735
2755
  exports.startsWith = startsWith;
2756
+ exports.summarizeTable = summarizeTable;
1736
2757
  exports.updateBranchMetadata = updateBranchMetadata;
2758
+ exports.updateBranchSchema = updateBranchSchema;
1737
2759
  exports.updateColumn = updateColumn;
2760
+ exports.updateDatabaseMetadata = updateDatabaseMetadata;
2761
+ exports.updateMigrationRequest = updateMigrationRequest;
1738
2762
  exports.updateRecordWithID = updateRecordWithID;
1739
2763
  exports.updateTable = updateTable;
1740
2764
  exports.updateUser = updateUser;
1741
2765
  exports.updateWorkspace = updateWorkspace;
2766
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
1742
2767
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
1743
2768
  exports.upsertRecordWithID = upsertRecordWithID;
1744
2769
  //# sourceMappingURL=index.cjs.map