@xata.io/client 0.0.0-alpha.vfd071d9 → 0.0.0-alpha.vfd1a215

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,3 +1,25 @@
1
+ const defaultTrace = async (_name, fn, _options) => {
2
+ return await fn({
3
+ setAttributes: () => {
4
+ return;
5
+ }
6
+ });
7
+ };
8
+ const TraceAttributes = {
9
+ KIND: "xata.trace.kind",
10
+ VERSION: "xata.sdk.version",
11
+ TABLE: "xata.table",
12
+ HTTP_REQUEST_ID: "http.request_id",
13
+ HTTP_STATUS_CODE: "http.status_code",
14
+ HTTP_HOST: "http.host",
15
+ HTTP_SCHEME: "http.scheme",
16
+ HTTP_USER_AGENT: "http.user_agent",
17
+ HTTP_METHOD: "http.method",
18
+ HTTP_URL: "http.url",
19
+ HTTP_ROUTE: "http.route",
20
+ HTTP_TARGET: "http.target"
21
+ };
22
+
1
23
  function notEmpty(value) {
2
24
  return value !== null && value !== void 0;
3
25
  }
@@ -7,46 +29,101 @@ function compact(arr) {
7
29
  function isObject(value) {
8
30
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
31
  }
32
+ function isDefined(value) {
33
+ return value !== null && value !== void 0;
34
+ }
10
35
  function isString(value) {
11
- return value !== void 0 && value !== null && typeof value === "string";
36
+ return isDefined(value) && typeof value === "string";
37
+ }
38
+ function isStringArray(value) {
39
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
12
40
  }
13
41
  function toBase64(value) {
14
42
  try {
15
43
  return btoa(value);
16
44
  } catch (err) {
17
- return Buffer.from(value).toString("base64");
45
+ const buf = Buffer;
46
+ return buf.from(value).toString("base64");
18
47
  }
19
48
  }
20
49
 
21
- function getEnvVariable(name) {
50
+ function getEnvironment() {
22
51
  try {
23
- if (isObject(process) && isString(process?.env?.[name])) {
24
- return process.env[name];
52
+ if (isObject(process) && isObject(process.env)) {
53
+ return {
54
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
55
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
56
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
57
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
58
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
59
+ };
25
60
  }
26
61
  } catch (err) {
27
62
  }
28
63
  try {
29
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
30
- return Deno.env.get(name);
64
+ if (isObject(Deno) && isObject(Deno.env)) {
65
+ return {
66
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
67
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
68
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
69
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
70
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
71
+ };
31
72
  }
32
73
  } catch (err) {
33
74
  }
75
+ return {
76
+ apiKey: getGlobalApiKey(),
77
+ databaseURL: getGlobalDatabaseURL(),
78
+ branch: getGlobalBranch(),
79
+ envBranch: void 0,
80
+ fallbackBranch: getGlobalFallbackBranch()
81
+ };
82
+ }
83
+ function getGlobalApiKey() {
84
+ try {
85
+ return XATA_API_KEY;
86
+ } catch (err) {
87
+ return void 0;
88
+ }
89
+ }
90
+ function getGlobalDatabaseURL() {
91
+ try {
92
+ return XATA_DATABASE_URL;
93
+ } catch (err) {
94
+ return void 0;
95
+ }
96
+ }
97
+ function getGlobalBranch() {
98
+ try {
99
+ return XATA_BRANCH;
100
+ } catch (err) {
101
+ return void 0;
102
+ }
103
+ }
104
+ function getGlobalFallbackBranch() {
105
+ try {
106
+ return XATA_FALLBACK_BRANCH;
107
+ } catch (err) {
108
+ return void 0;
109
+ }
34
110
  }
35
111
  async function getGitBranch() {
112
+ const cmd = ["git", "branch", "--show-current"];
113
+ const fullCmd = cmd.join(" ");
114
+ const nodeModule = ["child", "process"].join("_");
115
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
36
116
  try {
37
117
  if (typeof require === "function") {
38
- const req = require;
39
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
118
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
40
119
  }
120
+ const { execSync } = await import(nodeModule);
121
+ return execSync(fullCmd, execOptions).toString().trim();
41
122
  } catch (err) {
42
123
  }
43
124
  try {
44
125
  if (isObject(Deno)) {
45
- const process2 = Deno.run({
46
- cmd: ["git", "branch", "--show-current"],
47
- stdout: "piped",
48
- stderr: "piped"
49
- });
126
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
50
127
  return new TextDecoder().decode(await process2.output()).trim();
51
128
  }
52
129
  } catch (err) {
@@ -55,7 +132,8 @@ async function getGitBranch() {
55
132
 
56
133
  function getAPIKey() {
57
134
  try {
58
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
135
+ const { apiKey } = getEnvironment();
136
+ return apiKey;
59
137
  } catch (err) {
60
138
  return void 0;
61
139
  }
@@ -65,21 +143,35 @@ function getFetchImplementation(userFetch) {
65
143
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
66
144
  const fetchImpl = userFetch ?? globalFetch;
67
145
  if (!fetchImpl) {
68
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
146
+ throw new Error(
147
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
148
+ );
69
149
  }
70
150
  return fetchImpl;
71
151
  }
72
152
 
73
- class FetcherError extends Error {
74
- constructor(status, data) {
153
+ const VERSION = "0.0.0-alpha.vfd1a215";
154
+
155
+ class ErrorWithCause extends Error {
156
+ constructor(message, options) {
157
+ super(message, options);
158
+ }
159
+ }
160
+ class FetcherError extends ErrorWithCause {
161
+ constructor(status, data, requestId) {
75
162
  super(getMessage(data));
76
163
  this.status = status;
77
164
  this.errors = isBulkError(data) ? data.errors : void 0;
165
+ this.requestId = requestId;
78
166
  if (data instanceof Error) {
79
167
  this.stack = data.stack;
80
168
  this.cause = data.cause;
81
169
  }
82
170
  }
171
+ toString() {
172
+ const error = super.toString();
173
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
174
+ }
83
175
  }
84
176
  function isBulkError(error) {
85
177
  return isObject(error) && Array.isArray(error.errors);
@@ -102,9 +194,17 @@ function getMessage(data) {
102
194
  }
103
195
 
104
196
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
105
- const query = new URLSearchParams(queryParams).toString();
197
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
198
+ if (value === void 0 || value === null)
199
+ return acc;
200
+ return { ...acc, [key]: value };
201
+ }, {});
202
+ const query = new URLSearchParams(cleanQueryParams).toString();
106
203
  const queryString = query.length > 0 ? `?${query}` : "";
107
- return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
204
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
205
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
206
+ }, {});
207
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
108
208
  };
109
209
  function buildBaseUrl({
110
210
  path,
@@ -112,10 +212,10 @@ function buildBaseUrl({
112
212
  apiUrl,
113
213
  pathParams
114
214
  }) {
115
- if (!pathParams?.workspace)
215
+ if (pathParams?.workspace === void 0)
116
216
  return `${apiUrl}${path}`;
117
217
  const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
118
- return url.replace("{workspaceId}", pathParams.workspace);
218
+ return url.replace("{workspaceId}", String(pathParams.workspace));
119
219
  }
120
220
  function hostHeader(url) {
121
221
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
@@ -132,32 +232,61 @@ async function fetch$1({
132
232
  fetchImpl,
133
233
  apiKey,
134
234
  apiUrl,
135
- workspacesApiUrl
235
+ workspacesApiUrl,
236
+ trace
136
237
  }) {
137
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
138
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
139
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
140
- const response = await fetchImpl(url, {
141
- method: method.toUpperCase(),
142
- body: body ? JSON.stringify(body) : void 0,
143
- headers: {
144
- "Content-Type": "application/json",
145
- ...headers,
146
- ...hostHeader(fullUrl),
147
- Authorization: `Bearer ${apiKey}`
148
- }
149
- });
150
- if (response.status === 204) {
151
- return {};
152
- }
238
+ return trace(
239
+ `${method.toUpperCase()} ${path}`,
240
+ async ({ setAttributes }) => {
241
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
242
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
243
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
244
+ setAttributes({
245
+ [TraceAttributes.HTTP_URL]: url,
246
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
247
+ });
248
+ const response = await fetchImpl(url, {
249
+ method: method.toUpperCase(),
250
+ body: body ? JSON.stringify(body) : void 0,
251
+ headers: {
252
+ "Content-Type": "application/json",
253
+ "User-Agent": `Xata client-ts/${VERSION}`,
254
+ ...headers,
255
+ ...hostHeader(fullUrl),
256
+ Authorization: `Bearer ${apiKey}`
257
+ }
258
+ });
259
+ if (response.status === 204) {
260
+ return {};
261
+ }
262
+ const { host, protocol } = parseUrl(response.url);
263
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
264
+ setAttributes({
265
+ [TraceAttributes.KIND]: "http",
266
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
267
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
268
+ [TraceAttributes.HTTP_HOST]: host,
269
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
270
+ });
271
+ try {
272
+ const jsonResponse = await response.json();
273
+ if (response.ok) {
274
+ return jsonResponse;
275
+ }
276
+ throw new FetcherError(response.status, jsonResponse, requestId);
277
+ } catch (error) {
278
+ throw new FetcherError(response.status, error, requestId);
279
+ }
280
+ },
281
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
282
+ );
283
+ }
284
+ function parseUrl(url) {
153
285
  try {
154
- const jsonResponse = await response.json();
155
- if (response.ok) {
156
- return jsonResponse;
157
- }
158
- throw new FetcherError(response.status, jsonResponse);
286
+ const { host, protocol } = new URL(url);
287
+ return { host, protocol };
159
288
  } catch (error) {
160
- throw new FetcherError(response.status, error);
289
+ return {};
161
290
  }
162
291
  }
163
292
 
@@ -216,6 +345,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
216
345
  ...variables
217
346
  });
218
347
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
348
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
219
349
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
220
350
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
221
351
  method: "delete",
@@ -251,6 +381,11 @@ const deleteDatabase = (variables) => fetch$1({
251
381
  method: "delete",
252
382
  ...variables
253
383
  });
384
+ const getDatabaseMetadata = (variables) => fetch$1({
385
+ url: "/dbs/{dbName}/metadata",
386
+ method: "get",
387
+ ...variables
388
+ });
254
389
  const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
255
390
  const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
256
391
  const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
@@ -259,16 +394,28 @@ const resolveBranch = (variables) => fetch$1({
259
394
  method: "get",
260
395
  ...variables
261
396
  });
262
- const getBranchDetails = (variables) => fetch$1({
263
- url: "/db/{dbBranchName}",
397
+ const listMigrationRequests = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/list", method: "post", ...variables });
398
+ const createMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations", method: "post", ...variables });
399
+ const getMigrationRequest = (variables) => fetch$1({
400
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
264
401
  method: "get",
265
402
  ...variables
266
403
  });
267
- const createBranch = (variables) => fetch$1({
404
+ const updateMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables });
405
+ const listMigrationRequestsCommits = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables });
406
+ const compareMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables });
407
+ const getMigrationRequestIsMerged = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables });
408
+ const mergeMigrationRequest = (variables) => fetch$1({
409
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
410
+ method: "post",
411
+ ...variables
412
+ });
413
+ const getBranchDetails = (variables) => fetch$1({
268
414
  url: "/db/{dbBranchName}",
269
- method: "put",
415
+ method: "get",
270
416
  ...variables
271
417
  });
418
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
272
419
  const deleteBranch = (variables) => fetch$1({
273
420
  url: "/db/{dbBranchName}",
274
421
  method: "delete",
@@ -287,6 +434,16 @@ const getBranchMetadata = (variables) => fetch$1({
287
434
  const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
288
435
  const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
289
436
  const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
437
+ const compareBranchWithUserSchema = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables });
438
+ const compareBranchSchemas = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables });
439
+ const updateBranchSchema = (variables) => fetch$1({
440
+ url: "/db/{dbBranchName}/schema/update",
441
+ method: "post",
442
+ ...variables
443
+ });
444
+ const previewBranchSchemaEdit = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables });
445
+ const applyBranchSchemaEdit = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables });
446
+ const getBranchSchemaHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables });
290
447
  const getBranchStats = (variables) => fetch$1({
291
448
  url: "/db/{dbBranchName}/stats",
292
449
  method: "get",
@@ -342,11 +499,7 @@ const updateColumn = (variables) => fetch$1({
342
499
  method: "patch",
343
500
  ...variables
344
501
  });
345
- const insertRecord = (variables) => fetch$1({
346
- url: "/db/{dbBranchName}/tables/{tableName}/data",
347
- method: "post",
348
- ...variables
349
- });
502
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
350
503
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
351
504
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
352
505
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -366,6 +519,11 @@ const queryTable = (variables) => fetch$1({
366
519
  method: "post",
367
520
  ...variables
368
521
  });
522
+ const searchTable = (variables) => fetch$1({
523
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
524
+ method: "post",
525
+ ...variables
526
+ });
369
527
  const searchBranch = (variables) => fetch$1({
370
528
  url: "/db/{dbBranchName}/search",
371
529
  method: "post",
@@ -383,6 +541,7 @@ const operationsByTag = {
383
541
  updateWorkspaceMemberRole,
384
542
  removeWorkspaceMember,
385
543
  inviteWorkspaceMember,
544
+ updateWorkspaceMemberInvite,
386
545
  cancelWorkspaceMemberInvite,
387
546
  resendWorkspaceMemberInvite,
388
547
  acceptWorkspaceMemberInvite
@@ -391,6 +550,7 @@ const operationsByTag = {
391
550
  getDatabaseList,
392
551
  createDatabase,
393
552
  deleteDatabase,
553
+ getDatabaseMetadata,
394
554
  getGitBranchesMapping,
395
555
  addGitBranchesEntry,
396
556
  removeGitBranchesEntry,
@@ -403,10 +563,28 @@ const operationsByTag = {
403
563
  deleteBranch,
404
564
  updateBranchMetadata,
405
565
  getBranchMetadata,
566
+ getBranchStats
567
+ },
568
+ migrationRequests: {
569
+ listMigrationRequests,
570
+ createMigrationRequest,
571
+ getMigrationRequest,
572
+ updateMigrationRequest,
573
+ listMigrationRequestsCommits,
574
+ compareMigrationRequest,
575
+ getMigrationRequestIsMerged,
576
+ mergeMigrationRequest
577
+ },
578
+ branchSchema: {
406
579
  getBranchMigrationHistory,
407
580
  executeBranchMigrationPlan,
408
581
  getBranchMigrationPlan,
409
- getBranchStats
582
+ compareBranchWithUserSchema,
583
+ compareBranchSchemas,
584
+ updateBranchSchema,
585
+ previewBranchSchemaEdit,
586
+ applyBranchSchemaEdit,
587
+ getBranchSchemaHistory
410
588
  },
411
589
  table: {
412
590
  createTable,
@@ -429,14 +607,15 @@ const operationsByTag = {
429
607
  getRecord,
430
608
  bulkInsertTableRecords,
431
609
  queryTable,
610
+ searchTable,
432
611
  searchBranch
433
612
  }
434
613
  };
435
614
 
436
615
  function getHostUrl(provider, type) {
437
- if (isValidAlias(provider)) {
616
+ if (isHostProviderAlias(provider)) {
438
617
  return providers[provider][type];
439
- } else if (isValidBuilder(provider)) {
618
+ } else if (isHostProviderBuilder(provider)) {
440
619
  return provider[type];
441
620
  }
442
621
  throw new Error("Invalid API provider");
@@ -451,10 +630,10 @@ const providers = {
451
630
  workspaces: "https://{workspaceId}.staging.xatabase.co"
452
631
  }
453
632
  };
454
- function isValidAlias(alias) {
633
+ function isHostProviderAlias(alias) {
455
634
  return isString(alias) && Object.keys(providers).includes(alias);
456
635
  }
457
- function isValidBuilder(builder) {
636
+ function isHostProviderBuilder(builder) {
458
637
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
459
638
  }
460
639
 
@@ -462,7 +641,7 @@ var __accessCheck$7 = (obj, member, msg) => {
462
641
  if (!member.has(obj))
463
642
  throw TypeError("Cannot " + msg);
464
643
  };
465
- var __privateGet$6 = (obj, member, getter) => {
644
+ var __privateGet$7 = (obj, member, getter) => {
466
645
  __accessCheck$7(obj, member, "read from private field");
467
646
  return getter ? getter.call(obj) : member.get(obj);
468
647
  };
@@ -471,7 +650,7 @@ var __privateAdd$7 = (obj, member, value) => {
471
650
  throw TypeError("Cannot add the same private member more than once");
472
651
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
473
652
  };
474
- var __privateSet$5 = (obj, member, value, setter) => {
653
+ var __privateSet$7 = (obj, member, value, setter) => {
475
654
  __accessCheck$7(obj, member, "write to private field");
476
655
  setter ? setter.call(obj, value) : member.set(obj, value);
477
656
  return value;
@@ -482,46 +661,58 @@ class XataApiClient {
482
661
  __privateAdd$7(this, _extraProps, void 0);
483
662
  __privateAdd$7(this, _namespaces, {});
484
663
  const provider = options.host ?? "production";
485
- const apiKey = options?.apiKey ?? getAPIKey();
664
+ const apiKey = options.apiKey ?? getAPIKey();
665
+ const trace = options.trace ?? defaultTrace;
486
666
  if (!apiKey) {
487
667
  throw new Error("Could not resolve a valid apiKey");
488
668
  }
489
- __privateSet$5(this, _extraProps, {
669
+ __privateSet$7(this, _extraProps, {
490
670
  apiUrl: getHostUrl(provider, "main"),
491
671
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
492
672
  fetchImpl: getFetchImplementation(options.fetch),
493
- apiKey
673
+ apiKey,
674
+ trace
494
675
  });
495
676
  }
496
677
  get user() {
497
- if (!__privateGet$6(this, _namespaces).user)
498
- __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
499
- return __privateGet$6(this, _namespaces).user;
678
+ if (!__privateGet$7(this, _namespaces).user)
679
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
680
+ return __privateGet$7(this, _namespaces).user;
500
681
  }
501
682
  get workspaces() {
502
- if (!__privateGet$6(this, _namespaces).workspaces)
503
- __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
504
- return __privateGet$6(this, _namespaces).workspaces;
683
+ if (!__privateGet$7(this, _namespaces).workspaces)
684
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
685
+ return __privateGet$7(this, _namespaces).workspaces;
505
686
  }
506
687
  get databases() {
507
- if (!__privateGet$6(this, _namespaces).databases)
508
- __privateGet$6(this, _namespaces).databases = new DatabaseApi(__privateGet$6(this, _extraProps));
509
- return __privateGet$6(this, _namespaces).databases;
688
+ if (!__privateGet$7(this, _namespaces).databases)
689
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
690
+ return __privateGet$7(this, _namespaces).databases;
510
691
  }
511
692
  get branches() {
512
- if (!__privateGet$6(this, _namespaces).branches)
513
- __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
514
- return __privateGet$6(this, _namespaces).branches;
693
+ if (!__privateGet$7(this, _namespaces).branches)
694
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
695
+ return __privateGet$7(this, _namespaces).branches;
515
696
  }
516
697
  get tables() {
517
- if (!__privateGet$6(this, _namespaces).tables)
518
- __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
519
- return __privateGet$6(this, _namespaces).tables;
698
+ if (!__privateGet$7(this, _namespaces).tables)
699
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
700
+ return __privateGet$7(this, _namespaces).tables;
520
701
  }
521
702
  get records() {
522
- if (!__privateGet$6(this, _namespaces).records)
523
- __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
524
- return __privateGet$6(this, _namespaces).records;
703
+ if (!__privateGet$7(this, _namespaces).records)
704
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
705
+ return __privateGet$7(this, _namespaces).records;
706
+ }
707
+ get migrationRequests() {
708
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
709
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
710
+ return __privateGet$7(this, _namespaces).migrationRequests;
711
+ }
712
+ get branchSchema() {
713
+ if (!__privateGet$7(this, _namespaces).branchSchema)
714
+ __privateGet$7(this, _namespaces).branchSchema = new BranchSchemaApi(__privateGet$7(this, _extraProps));
715
+ return __privateGet$7(this, _namespaces).branchSchema;
525
716
  }
526
717
  }
527
718
  _extraProps = new WeakMap();
@@ -613,6 +804,13 @@ class WorkspaceApi {
613
804
  ...this.extraProps
614
805
  });
615
806
  }
807
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
808
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
809
+ pathParams: { workspaceId, inviteId },
810
+ body: { role },
811
+ ...this.extraProps
812
+ });
813
+ }
616
814
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
617
815
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
618
816
  pathParams: { workspaceId, inviteId },
@@ -655,6 +853,12 @@ class DatabaseApi {
655
853
  ...this.extraProps
656
854
  });
657
855
  }
856
+ getDatabaseMetadata(workspace, dbName) {
857
+ return operationsByTag.database.getDatabaseMetadata({
858
+ pathParams: { workspace, dbName },
859
+ ...this.extraProps
860
+ });
861
+ }
658
862
  getGitBranchesMapping(workspace, dbName) {
659
863
  return operationsByTag.database.getGitBranchesMapping({
660
864
  pathParams: { workspace, dbName },
@@ -675,10 +879,10 @@ class DatabaseApi {
675
879
  ...this.extraProps
676
880
  });
677
881
  }
678
- resolveBranch(workspace, dbName, gitBranch) {
882
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
679
883
  return operationsByTag.database.resolveBranch({
680
884
  pathParams: { workspace, dbName },
681
- queryParams: { gitBranch },
885
+ queryParams: { gitBranch, fallbackBranch },
682
886
  ...this.extraProps
683
887
  });
684
888
  }
@@ -699,10 +903,10 @@ class BranchApi {
699
903
  ...this.extraProps
700
904
  });
701
905
  }
702
- createBranch(workspace, database, branch, from = "", options = {}) {
906
+ createBranch(workspace, database, branch, from, options = {}) {
703
907
  return operationsByTag.branch.createBranch({
704
908
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
705
- queryParams: { from },
909
+ queryParams: isString(from) ? { from } : void 0,
706
910
  body: options,
707
911
  ...this.extraProps
708
912
  });
@@ -726,27 +930,6 @@ class BranchApi {
726
930
  ...this.extraProps
727
931
  });
728
932
  }
729
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
730
- return operationsByTag.branch.getBranchMigrationHistory({
731
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
732
- body: options,
733
- ...this.extraProps
734
- });
735
- }
736
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
737
- return operationsByTag.branch.executeBranchMigrationPlan({
738
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
739
- body: migrationPlan,
740
- ...this.extraProps
741
- });
742
- }
743
- getBranchMigrationPlan(workspace, database, branch, schema) {
744
- return operationsByTag.branch.getBranchMigrationPlan({
745
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
746
- body: schema,
747
- ...this.extraProps
748
- });
749
- }
750
933
  getBranchStats(workspace, database, branch) {
751
934
  return operationsByTag.branch.getBranchStats({
752
935
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -827,9 +1010,10 @@ class RecordsApi {
827
1010
  constructor(extraProps) {
828
1011
  this.extraProps = extraProps;
829
1012
  }
830
- insertRecord(workspace, database, branch, tableName, record) {
1013
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
831
1014
  return operationsByTag.records.insertRecord({
832
1015
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1016
+ queryParams: options,
833
1017
  body: record,
834
1018
  ...this.extraProps
835
1019
  });
@@ -858,21 +1042,24 @@ class RecordsApi {
858
1042
  ...this.extraProps
859
1043
  });
860
1044
  }
861
- deleteRecord(workspace, database, branch, tableName, recordId) {
1045
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
862
1046
  return operationsByTag.records.deleteRecord({
863
1047
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1048
+ queryParams: options,
864
1049
  ...this.extraProps
865
1050
  });
866
1051
  }
867
1052
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
868
1053
  return operationsByTag.records.getRecord({
869
1054
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1055
+ queryParams: options,
870
1056
  ...this.extraProps
871
1057
  });
872
1058
  }
873
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1059
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
874
1060
  return operationsByTag.records.bulkInsertTableRecords({
875
1061
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1062
+ queryParams: options,
876
1063
  body: { records },
877
1064
  ...this.extraProps
878
1065
  });
@@ -884,6 +1071,13 @@ class RecordsApi {
884
1071
  ...this.extraProps
885
1072
  });
886
1073
  }
1074
+ searchTable(workspace, database, branch, tableName, query) {
1075
+ return operationsByTag.records.searchTable({
1076
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1077
+ body: query,
1078
+ ...this.extraProps
1079
+ });
1080
+ }
887
1081
  searchBranch(workspace, database, branch, query) {
888
1082
  return operationsByTag.records.searchBranch({
889
1083
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -892,6 +1086,131 @@ class RecordsApi {
892
1086
  });
893
1087
  }
894
1088
  }
1089
+ class MigrationRequestsApi {
1090
+ constructor(extraProps) {
1091
+ this.extraProps = extraProps;
1092
+ }
1093
+ listMigrationRequests(workspace, database, options = {}) {
1094
+ return operationsByTag.migrationRequests.listMigrationRequests({
1095
+ pathParams: { workspace, dbName: database },
1096
+ body: options,
1097
+ ...this.extraProps
1098
+ });
1099
+ }
1100
+ createMigrationRequest(workspace, database, options) {
1101
+ return operationsByTag.migrationRequests.createMigrationRequest({
1102
+ pathParams: { workspace, dbName: database },
1103
+ body: options,
1104
+ ...this.extraProps
1105
+ });
1106
+ }
1107
+ getMigrationRequest(workspace, database, migrationRequest) {
1108
+ return operationsByTag.migrationRequests.getMigrationRequest({
1109
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1110
+ ...this.extraProps
1111
+ });
1112
+ }
1113
+ updateMigrationRequest(workspace, database, migrationRequest, options) {
1114
+ return operationsByTag.migrationRequests.updateMigrationRequest({
1115
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1116
+ body: options,
1117
+ ...this.extraProps
1118
+ });
1119
+ }
1120
+ listMigrationRequestsCommits(workspace, database, migrationRequest, options = {}) {
1121
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1122
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1123
+ body: options,
1124
+ ...this.extraProps
1125
+ });
1126
+ }
1127
+ compareMigrationRequest(workspace, database, migrationRequest) {
1128
+ return operationsByTag.migrationRequests.compareMigrationRequest({
1129
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1130
+ ...this.extraProps
1131
+ });
1132
+ }
1133
+ getMigrationRequestIsMerged(workspace, database, migrationRequest) {
1134
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1135
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1136
+ ...this.extraProps
1137
+ });
1138
+ }
1139
+ mergeMigrationRequest(workspace, database, migrationRequest) {
1140
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
1141
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1142
+ ...this.extraProps
1143
+ });
1144
+ }
1145
+ }
1146
+ class BranchSchemaApi {
1147
+ constructor(extraProps) {
1148
+ this.extraProps = extraProps;
1149
+ }
1150
+ getBranchMigrationHistory(workspace, database, branch, options = {}) {
1151
+ return operationsByTag.branchSchema.getBranchMigrationHistory({
1152
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1153
+ body: options,
1154
+ ...this.extraProps
1155
+ });
1156
+ }
1157
+ executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
1158
+ return operationsByTag.branchSchema.executeBranchMigrationPlan({
1159
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1160
+ body: migrationPlan,
1161
+ ...this.extraProps
1162
+ });
1163
+ }
1164
+ getBranchMigrationPlan(workspace, database, branch, schema) {
1165
+ return operationsByTag.branchSchema.getBranchMigrationPlan({
1166
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1167
+ body: schema,
1168
+ ...this.extraProps
1169
+ });
1170
+ }
1171
+ compareBranchWithUserSchema(workspace, database, branch, schema) {
1172
+ return operationsByTag.branchSchema.compareBranchWithUserSchema({
1173
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1174
+ body: { schema },
1175
+ ...this.extraProps
1176
+ });
1177
+ }
1178
+ compareBranchSchemas(workspace, database, branch, branchName, schema) {
1179
+ return operationsByTag.branchSchema.compareBranchSchemas({
1180
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, branchName },
1181
+ body: { schema },
1182
+ ...this.extraProps
1183
+ });
1184
+ }
1185
+ updateBranchSchema(workspace, database, branch, migration) {
1186
+ return operationsByTag.branchSchema.updateBranchSchema({
1187
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1188
+ body: migration,
1189
+ ...this.extraProps
1190
+ });
1191
+ }
1192
+ previewBranchSchemaEdit(workspace, database, branch, migration) {
1193
+ return operationsByTag.branchSchema.previewBranchSchemaEdit({
1194
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1195
+ body: migration,
1196
+ ...this.extraProps
1197
+ });
1198
+ }
1199
+ applyBranchSchemaEdit(workspace, database, branch, edits) {
1200
+ return operationsByTag.branchSchema.applyBranchSchemaEdit({
1201
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1202
+ body: { edits },
1203
+ ...this.extraProps
1204
+ });
1205
+ }
1206
+ getBranchSchemaHistory(workspace, database, branch, options = {}) {
1207
+ return operationsByTag.branchSchema.getBranchSchemaHistory({
1208
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1209
+ body: options,
1210
+ ...this.extraProps
1211
+ });
1212
+ }
1213
+ }
895
1214
 
896
1215
  class XataApiPlugin {
897
1216
  async build(options) {
@@ -907,7 +1226,7 @@ var __accessCheck$6 = (obj, member, msg) => {
907
1226
  if (!member.has(obj))
908
1227
  throw TypeError("Cannot " + msg);
909
1228
  };
910
- var __privateGet$5 = (obj, member, getter) => {
1229
+ var __privateGet$6 = (obj, member, getter) => {
911
1230
  __accessCheck$6(obj, member, "read from private field");
912
1231
  return getter ? getter.call(obj) : member.get(obj);
913
1232
  };
@@ -916,30 +1235,30 @@ var __privateAdd$6 = (obj, member, value) => {
916
1235
  throw TypeError("Cannot add the same private member more than once");
917
1236
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
918
1237
  };
919
- var __privateSet$4 = (obj, member, value, setter) => {
1238
+ var __privateSet$6 = (obj, member, value, setter) => {
920
1239
  __accessCheck$6(obj, member, "write to private field");
921
1240
  setter ? setter.call(obj, value) : member.set(obj, value);
922
1241
  return value;
923
1242
  };
924
- var _query;
1243
+ var _query, _page;
925
1244
  class Page {
926
1245
  constructor(query, meta, records = []) {
927
1246
  __privateAdd$6(this, _query, void 0);
928
- __privateSet$4(this, _query, query);
1247
+ __privateSet$6(this, _query, query);
929
1248
  this.meta = meta;
930
- this.records = records;
1249
+ this.records = new RecordArray(this, records);
931
1250
  }
932
1251
  async nextPage(size, offset) {
933
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1252
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
934
1253
  }
935
1254
  async previousPage(size, offset) {
936
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1255
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
937
1256
  }
938
1257
  async firstPage(size, offset) {
939
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1258
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
940
1259
  }
941
1260
  async lastPage(size, offset) {
942
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1261
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
943
1262
  }
944
1263
  hasNextPage() {
945
1264
  return this.meta.page.more;
@@ -947,15 +1266,62 @@ class Page {
947
1266
  }
948
1267
  _query = new WeakMap();
949
1268
  const PAGINATION_MAX_SIZE = 200;
950
- const PAGINATION_DEFAULT_SIZE = 200;
1269
+ const PAGINATION_DEFAULT_SIZE = 20;
951
1270
  const PAGINATION_MAX_OFFSET = 800;
952
1271
  const PAGINATION_DEFAULT_OFFSET = 0;
1272
+ function isCursorPaginationOptions(options) {
1273
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1274
+ }
1275
+ const _RecordArray = class extends Array {
1276
+ constructor(...args) {
1277
+ super(..._RecordArray.parseConstructorParams(...args));
1278
+ __privateAdd$6(this, _page, void 0);
1279
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1280
+ }
1281
+ static parseConstructorParams(...args) {
1282
+ if (args.length === 1 && typeof args[0] === "number") {
1283
+ return new Array(args[0]);
1284
+ }
1285
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1286
+ const result = args[1] ?? args[0].records ?? [];
1287
+ return new Array(...result);
1288
+ }
1289
+ return new Array(...args);
1290
+ }
1291
+ toArray() {
1292
+ return new Array(...this);
1293
+ }
1294
+ map(callbackfn, thisArg) {
1295
+ return this.toArray().map(callbackfn, thisArg);
1296
+ }
1297
+ async nextPage(size, offset) {
1298
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1299
+ return new _RecordArray(newPage);
1300
+ }
1301
+ async previousPage(size, offset) {
1302
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1303
+ return new _RecordArray(newPage);
1304
+ }
1305
+ async firstPage(size, offset) {
1306
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1307
+ return new _RecordArray(newPage);
1308
+ }
1309
+ async lastPage(size, offset) {
1310
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1311
+ return new _RecordArray(newPage);
1312
+ }
1313
+ hasNextPage() {
1314
+ return __privateGet$6(this, _page).meta.page.more;
1315
+ }
1316
+ };
1317
+ let RecordArray = _RecordArray;
1318
+ _page = new WeakMap();
953
1319
 
954
1320
  var __accessCheck$5 = (obj, member, msg) => {
955
1321
  if (!member.has(obj))
956
1322
  throw TypeError("Cannot " + msg);
957
1323
  };
958
- var __privateGet$4 = (obj, member, getter) => {
1324
+ var __privateGet$5 = (obj, member, getter) => {
959
1325
  __accessCheck$5(obj, member, "read from private field");
960
1326
  return getter ? getter.call(obj) : member.get(obj);
961
1327
  };
@@ -964,34 +1330,35 @@ var __privateAdd$5 = (obj, member, value) => {
964
1330
  throw TypeError("Cannot add the same private member more than once");
965
1331
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
966
1332
  };
967
- var __privateSet$3 = (obj, member, value, setter) => {
1333
+ var __privateSet$5 = (obj, member, value, setter) => {
968
1334
  __accessCheck$5(obj, member, "write to private field");
969
1335
  setter ? setter.call(obj, value) : member.set(obj, value);
970
1336
  return value;
971
1337
  };
972
1338
  var _table$1, _repository, _data;
973
1339
  const _Query = class {
974
- constructor(repository, table, data, parent) {
1340
+ constructor(repository, table, data, rawParent) {
975
1341
  __privateAdd$5(this, _table$1, void 0);
976
1342
  __privateAdd$5(this, _repository, void 0);
977
1343
  __privateAdd$5(this, _data, { filter: {} });
978
1344
  this.meta = { page: { cursor: "start", more: true } };
979
- this.records = [];
980
- __privateSet$3(this, _table$1, table);
1345
+ this.records = new RecordArray(this, []);
1346
+ __privateSet$5(this, _table$1, table);
981
1347
  if (repository) {
982
- __privateSet$3(this, _repository, repository);
1348
+ __privateSet$5(this, _repository, repository);
983
1349
  } else {
984
- __privateSet$3(this, _repository, this);
1350
+ __privateSet$5(this, _repository, this);
985
1351
  }
986
- __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
987
- __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
988
- __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
989
- __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
990
- __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
991
- __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
992
- __privateGet$4(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
993
- __privateGet$4(this, _data).page = data.page ?? parent?.page;
994
- __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
1352
+ const parent = cleanParent(data, rawParent);
1353
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1354
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1355
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1356
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1357
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1358
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1359
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1360
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1361
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
995
1362
  this.any = this.any.bind(this);
996
1363
  this.all = this.all.bind(this);
997
1364
  this.not = this.not.bind(this);
@@ -1002,83 +1369,101 @@ const _Query = class {
1002
1369
  Object.defineProperty(this, "repository", { enumerable: false });
1003
1370
  }
1004
1371
  getQueryOptions() {
1005
- return __privateGet$4(this, _data);
1372
+ return __privateGet$5(this, _data);
1006
1373
  }
1007
1374
  key() {
1008
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$4(this, _data);
1009
- const key = JSON.stringify({ columns, filter, sort, page });
1375
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1376
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1010
1377
  return toBase64(key);
1011
1378
  }
1012
1379
  any(...queries) {
1013
1380
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1014
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
1381
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
1015
1382
  }
1016
1383
  all(...queries) {
1017
1384
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1018
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1385
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1019
1386
  }
1020
1387
  not(...queries) {
1021
1388
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1022
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
1389
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
1023
1390
  }
1024
1391
  none(...queries) {
1025
1392
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1026
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
1393
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
1027
1394
  }
1028
1395
  filter(a, b) {
1029
1396
  if (arguments.length === 1) {
1030
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1031
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
1032
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1397
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({ [column]: constraint }));
1398
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1399
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1033
1400
  } else {
1034
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1035
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1401
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: this.defaultFilter(a, b) }] : void 0;
1402
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1403
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1404
+ }
1405
+ }
1406
+ defaultFilter(column, value) {
1407
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
1408
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
1409
+ return { $includes: value };
1036
1410
  }
1411
+ return value;
1037
1412
  }
1038
- sort(column, direction) {
1039
- const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
1413
+ sort(column, direction = "asc") {
1414
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1040
1415
  const sort = [...originalSort, { column, direction }];
1041
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
1416
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1042
1417
  }
1043
1418
  select(columns) {
1044
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { columns }, __privateGet$4(this, _data));
1419
+ return new _Query(
1420
+ __privateGet$5(this, _repository),
1421
+ __privateGet$5(this, _table$1),
1422
+ { columns },
1423
+ __privateGet$5(this, _data)
1424
+ );
1045
1425
  }
1046
1426
  getPaginated(options = {}) {
1047
- const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
1048
- return __privateGet$4(this, _repository).query(query);
1427
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1428
+ return __privateGet$5(this, _repository).query(query);
1049
1429
  }
1050
1430
  async *[Symbol.asyncIterator]() {
1051
- for await (const [record] of this.getIterator(1)) {
1431
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1052
1432
  yield record;
1053
1433
  }
1054
1434
  }
1055
- async *getIterator(chunk, options = {}) {
1056
- let offset = 0;
1057
- let end = false;
1058
- while (!end) {
1059
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1060
- yield records;
1061
- offset += chunk;
1062
- end = !meta.page.more;
1435
+ async *getIterator(options = {}) {
1436
+ const { batchSize = 1 } = options;
1437
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1438
+ let more = page.hasNextPage();
1439
+ yield page.records;
1440
+ while (more) {
1441
+ page = await page.nextPage();
1442
+ more = page.hasNextPage();
1443
+ yield page.records;
1063
1444
  }
1064
1445
  }
1065
1446
  async getMany(options = {}) {
1066
- const { records } = await this.getPaginated(options);
1067
- return records;
1447
+ const page = await this.getPaginated(options);
1448
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1449
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1450
+ }
1451
+ return page.records;
1068
1452
  }
1069
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1453
+ async getAll(options = {}) {
1454
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1070
1455
  const results = [];
1071
- for await (const page of this.getIterator(chunk, options)) {
1456
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1072
1457
  results.push(...page);
1073
1458
  }
1074
1459
  return results;
1075
1460
  }
1076
1461
  async getFirst(options = {}) {
1077
- const records = await this.getMany({ ...options, page: { size: 1 } });
1078
- return records[0] || null;
1462
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1463
+ return records[0] ?? null;
1079
1464
  }
1080
1465
  cache(ttl) {
1081
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
1466
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1082
1467
  }
1083
1468
  nextPage(size, offset) {
1084
1469
  return this.firstPage(size, offset);
@@ -1087,10 +1472,10 @@ const _Query = class {
1087
1472
  return this.firstPage(size, offset);
1088
1473
  }
1089
1474
  firstPage(size, offset) {
1090
- return this.getPaginated({ page: { size, offset } });
1475
+ return this.getPaginated({ pagination: { size, offset } });
1091
1476
  }
1092
1477
  lastPage(size, offset) {
1093
- return this.getPaginated({ page: { size, offset, before: "end" } });
1478
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1094
1479
  }
1095
1480
  hasNextPage() {
1096
1481
  return this.meta.page.more;
@@ -1100,12 +1485,20 @@ let Query = _Query;
1100
1485
  _table$1 = new WeakMap();
1101
1486
  _repository = new WeakMap();
1102
1487
  _data = new WeakMap();
1488
+ function cleanParent(data, parent) {
1489
+ if (isCursorPaginationOptions(data.pagination)) {
1490
+ return { ...parent, sorting: void 0, filter: void 0 };
1491
+ }
1492
+ return parent;
1493
+ }
1103
1494
 
1104
1495
  function isIdentifiable(x) {
1105
1496
  return isObject(x) && isString(x?.id);
1106
1497
  }
1107
1498
  function isXataRecord(x) {
1108
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1499
+ const record = x;
1500
+ const metadata = record?.getMetadata();
1501
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1109
1502
  }
1110
1503
 
1111
1504
  function isSortFilterString(value) {
@@ -1135,7 +1528,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1135
1528
  if (!member.has(obj))
1136
1529
  throw TypeError("Cannot " + msg);
1137
1530
  };
1138
- var __privateGet$3 = (obj, member, getter) => {
1531
+ var __privateGet$4 = (obj, member, getter) => {
1139
1532
  __accessCheck$4(obj, member, "read from private field");
1140
1533
  return getter ? getter.call(obj) : member.get(obj);
1141
1534
  };
@@ -1144,7 +1537,7 @@ var __privateAdd$4 = (obj, member, value) => {
1144
1537
  throw TypeError("Cannot add the same private member more than once");
1145
1538
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1146
1539
  };
1147
- var __privateSet$2 = (obj, member, value, setter) => {
1540
+ var __privateSet$4 = (obj, member, value, setter) => {
1148
1541
  __accessCheck$4(obj, member, "write to private field");
1149
1542
  setter ? setter.call(obj, value) : member.set(obj, value);
1150
1543
  return value;
@@ -1153,304 +1546,355 @@ var __privateMethod$2 = (obj, member, method) => {
1153
1546
  __accessCheck$4(obj, member, "access private method");
1154
1547
  return method;
1155
1548
  };
1156
- var _table, _links, _getFetchProps, _cache, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn;
1549
+ 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;
1157
1550
  class Repository extends Query {
1158
1551
  }
1159
1552
  class RestRepository extends Query {
1160
1553
  constructor(options) {
1161
- super(null, options.table, {});
1554
+ super(
1555
+ null,
1556
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
1557
+ {}
1558
+ );
1162
1559
  __privateAdd$4(this, _insertRecordWithoutId);
1163
1560
  __privateAdd$4(this, _insertRecordWithId);
1164
1561
  __privateAdd$4(this, _bulkInsertTableRecords);
1165
1562
  __privateAdd$4(this, _updateRecordWithID);
1166
1563
  __privateAdd$4(this, _upsertRecordWithID);
1167
1564
  __privateAdd$4(this, _deleteRecord);
1168
- __privateAdd$4(this, _invalidateCache);
1169
- __privateAdd$4(this, _setCacheRecord);
1170
- __privateAdd$4(this, _getCacheRecord);
1171
1565
  __privateAdd$4(this, _setCacheQuery);
1172
1566
  __privateAdd$4(this, _getCacheQuery);
1567
+ __privateAdd$4(this, _getSchemaTables$1);
1173
1568
  __privateAdd$4(this, _table, void 0);
1174
- __privateAdd$4(this, _links, void 0);
1175
1569
  __privateAdd$4(this, _getFetchProps, void 0);
1570
+ __privateAdd$4(this, _db, void 0);
1176
1571
  __privateAdd$4(this, _cache, void 0);
1177
- __privateSet$2(this, _table, options.table);
1178
- __privateSet$2(this, _links, options.links ?? {});
1179
- __privateSet$2(this, _getFetchProps, options.pluginOptions.getFetchProps);
1180
- this.db = options.db;
1181
- __privateSet$2(this, _cache, options.pluginOptions.cache);
1182
- }
1183
- async create(a, b) {
1184
- if (Array.isArray(a)) {
1185
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1186
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1187
- return records;
1188
- }
1189
- if (isString(a) && isObject(b)) {
1190
- if (a === "")
1191
- throw new Error("The id can't be empty");
1192
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1193
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1194
- return record;
1195
- }
1196
- if (isObject(a) && isString(a.id)) {
1197
- if (a.id === "")
1198
- throw new Error("The id can't be empty");
1199
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1200
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1201
- return record;
1202
- }
1203
- if (isObject(a)) {
1204
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1205
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1206
- return record;
1207
- }
1208
- throw new Error("Invalid arguments for create method");
1209
- }
1210
- async read(recordId) {
1211
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1212
- if (cacheRecord)
1213
- return cacheRecord;
1214
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1215
- try {
1216
- const response = await getRecord({
1217
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1218
- ...fetchProps
1572
+ __privateAdd$4(this, _schemaTables$2, void 0);
1573
+ __privateAdd$4(this, _trace, void 0);
1574
+ __privateSet$4(this, _table, options.table);
1575
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1576
+ __privateSet$4(this, _db, options.db);
1577
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1578
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1579
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1580
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1581
+ return trace(name, fn, {
1582
+ ...options2,
1583
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1584
+ [TraceAttributes.KIND]: "sdk-operation",
1585
+ [TraceAttributes.VERSION]: VERSION
1219
1586
  });
1220
- return initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), response);
1221
- } catch (e) {
1222
- if (isObject(e) && e.status === 404) {
1223
- return null;
1587
+ });
1588
+ }
1589
+ async create(a, b, c) {
1590
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1591
+ if (Array.isArray(a)) {
1592
+ if (a.length === 0)
1593
+ return [];
1594
+ const columns = isStringArray(b) ? b : void 0;
1595
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1224
1596
  }
1225
- throw e;
1226
- }
1597
+ if (isString(a) && isObject(b)) {
1598
+ if (a === "")
1599
+ throw new Error("The id can't be empty");
1600
+ const columns = isStringArray(c) ? c : void 0;
1601
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1602
+ }
1603
+ if (isObject(a) && isString(a.id)) {
1604
+ if (a.id === "")
1605
+ throw new Error("The id can't be empty");
1606
+ const columns = isStringArray(b) ? b : void 0;
1607
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1608
+ }
1609
+ if (isObject(a)) {
1610
+ const columns = isStringArray(b) ? b : void 0;
1611
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1612
+ }
1613
+ throw new Error("Invalid arguments for create method");
1614
+ });
1227
1615
  }
1228
- async update(a, b) {
1229
- if (Array.isArray(a)) {
1230
- if (a.length > 100) {
1231
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1616
+ async read(a, b) {
1617
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1618
+ const columns = isStringArray(b) ? b : ["*"];
1619
+ if (Array.isArray(a)) {
1620
+ if (a.length === 0)
1621
+ return [];
1622
+ const ids = a.map((item) => extractId(item));
1623
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1624
+ const dictionary = finalObjects.reduce((acc, object) => {
1625
+ acc[object.id] = object;
1626
+ return acc;
1627
+ }, {});
1628
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1232
1629
  }
1233
- return Promise.all(a.map((object) => this.update(object)));
1234
- }
1235
- if (isString(a) && isObject(b)) {
1236
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1237
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1238
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1239
- return record;
1240
- }
1241
- if (isObject(a) && isString(a.id)) {
1242
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1243
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1244
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1245
- return record;
1246
- }
1247
- throw new Error("Invalid arguments for update method");
1630
+ const id = extractId(a);
1631
+ if (id) {
1632
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1633
+ try {
1634
+ const response = await getRecord({
1635
+ pathParams: {
1636
+ workspace: "{workspaceId}",
1637
+ dbBranchName: "{dbBranch}",
1638
+ tableName: __privateGet$4(this, _table),
1639
+ recordId: id
1640
+ },
1641
+ queryParams: { columns },
1642
+ ...fetchProps
1643
+ });
1644
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1645
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1646
+ } catch (e) {
1647
+ if (isObject(e) && e.status === 404) {
1648
+ return null;
1649
+ }
1650
+ throw e;
1651
+ }
1652
+ }
1653
+ return null;
1654
+ });
1248
1655
  }
1249
- async createOrUpdate(a, b) {
1250
- if (Array.isArray(a)) {
1251
- if (a.length > 100) {
1252
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1656
+ async update(a, b, c) {
1657
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1658
+ if (Array.isArray(a)) {
1659
+ if (a.length === 0)
1660
+ return [];
1661
+ if (a.length > 100) {
1662
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1663
+ }
1664
+ const columns = isStringArray(b) ? b : ["*"];
1665
+ return Promise.all(a.map((object) => this.update(object, columns)));
1253
1666
  }
1254
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1255
- }
1256
- if (isString(a) && isObject(b)) {
1257
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1258
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1259
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1260
- return record;
1261
- }
1262
- if (isObject(a) && isString(a.id)) {
1263
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1264
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1265
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1266
- return record;
1267
- }
1268
- throw new Error("Invalid arguments for createOrUpdate method");
1667
+ if (isString(a) && isObject(b)) {
1668
+ const columns = isStringArray(c) ? c : void 0;
1669
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1670
+ }
1671
+ if (isObject(a) && isString(a.id)) {
1672
+ const columns = isStringArray(b) ? b : void 0;
1673
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1674
+ }
1675
+ throw new Error("Invalid arguments for update method");
1676
+ });
1269
1677
  }
1270
- async delete(a) {
1271
- if (Array.isArray(a)) {
1272
- if (a.length > 100) {
1273
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1678
+ async createOrUpdate(a, b, c) {
1679
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1680
+ if (Array.isArray(a)) {
1681
+ if (a.length === 0)
1682
+ return [];
1683
+ if (a.length > 100) {
1684
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1685
+ }
1686
+ const columns = isStringArray(b) ? b : ["*"];
1687
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1274
1688
  }
1275
- await Promise.all(a.map((id) => this.delete(id)));
1276
- return;
1277
- }
1278
- if (isString(a)) {
1279
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1280
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1281
- return;
1282
- }
1283
- if (isObject(a) && isString(a.id)) {
1284
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1285
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1286
- return;
1287
- }
1288
- throw new Error("Invalid arguments for delete method");
1689
+ if (isString(a) && isObject(b)) {
1690
+ const columns = isStringArray(c) ? c : void 0;
1691
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1692
+ }
1693
+ if (isObject(a) && isString(a.id)) {
1694
+ const columns = isStringArray(c) ? c : void 0;
1695
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1696
+ }
1697
+ throw new Error("Invalid arguments for createOrUpdate method");
1698
+ });
1699
+ }
1700
+ async delete(a, b) {
1701
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1702
+ if (Array.isArray(a)) {
1703
+ if (a.length === 0)
1704
+ return [];
1705
+ if (a.length > 100) {
1706
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1707
+ }
1708
+ return Promise.all(a.map((id) => this.delete(id, b)));
1709
+ }
1710
+ if (isString(a)) {
1711
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1712
+ }
1713
+ if (isObject(a) && isString(a.id)) {
1714
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1715
+ }
1716
+ throw new Error("Invalid arguments for delete method");
1717
+ });
1289
1718
  }
1290
1719
  async search(query, options = {}) {
1291
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1292
- const { records } = await searchBranch({
1293
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1294
- body: { tables: [__privateGet$3(this, _table)], query, fuzziness: options.fuzziness },
1295
- ...fetchProps
1720
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1721
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1722
+ const { records } = await searchTable({
1723
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1724
+ body: {
1725
+ query,
1726
+ fuzziness: options.fuzziness,
1727
+ prefix: options.prefix,
1728
+ highlight: options.highlight,
1729
+ filter: options.filter,
1730
+ boosters: options.boosters
1731
+ },
1732
+ ...fetchProps
1733
+ });
1734
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1735
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1296
1736
  });
1297
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), item));
1298
1737
  }
1299
1738
  async query(query) {
1300
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1301
- if (cacheQuery)
1302
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1303
- const data = query.getQueryOptions();
1304
- const body = {
1305
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1306
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1307
- page: data.page,
1308
- columns: data.columns
1309
- };
1310
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1311
- const { meta, records: objects } = await queryTable({
1312
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1313
- body,
1314
- ...fetchProps
1739
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1740
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1741
+ if (cacheQuery)
1742
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1743
+ const data = query.getQueryOptions();
1744
+ const body = {
1745
+ filter: cleanFilter(data.filter),
1746
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1747
+ page: data.pagination,
1748
+ columns: data.columns
1749
+ };
1750
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1751
+ const { meta, records: objects } = await queryTable({
1752
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1753
+ body,
1754
+ ...fetchProps
1755
+ });
1756
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1757
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1758
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1759
+ return new Page(query, meta, records);
1315
1760
  });
1316
- const records = objects.map((record) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), record));
1317
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1318
- return new Page(query, meta, records);
1319
1761
  }
1320
1762
  }
1321
1763
  _table = new WeakMap();
1322
- _links = new WeakMap();
1323
1764
  _getFetchProps = new WeakMap();
1765
+ _db = new WeakMap();
1324
1766
  _cache = new WeakMap();
1767
+ _schemaTables$2 = new WeakMap();
1768
+ _trace = new WeakMap();
1325
1769
  _insertRecordWithoutId = new WeakSet();
1326
- insertRecordWithoutId_fn = async function(object) {
1327
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1770
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1771
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1328
1772
  const record = transformObjectLinks(object);
1329
1773
  const response = await insertRecord({
1330
1774
  pathParams: {
1331
1775
  workspace: "{workspaceId}",
1332
1776
  dbBranchName: "{dbBranch}",
1333
- tableName: __privateGet$3(this, _table)
1777
+ tableName: __privateGet$4(this, _table)
1334
1778
  },
1779
+ queryParams: { columns },
1335
1780
  body: record,
1336
1781
  ...fetchProps
1337
1782
  });
1338
- const finalObject = await this.read(response.id);
1339
- if (!finalObject) {
1340
- throw new Error("The server failed to save the record");
1341
- }
1342
- return finalObject;
1783
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1784
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1343
1785
  };
1344
1786
  _insertRecordWithId = new WeakSet();
1345
- insertRecordWithId_fn = async function(recordId, object) {
1346
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1787
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1788
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1347
1789
  const record = transformObjectLinks(object);
1348
1790
  const response = await insertRecordWithID({
1349
1791
  pathParams: {
1350
1792
  workspace: "{workspaceId}",
1351
1793
  dbBranchName: "{dbBranch}",
1352
- tableName: __privateGet$3(this, _table),
1794
+ tableName: __privateGet$4(this, _table),
1353
1795
  recordId
1354
1796
  },
1355
1797
  body: record,
1356
- queryParams: { createOnly: true },
1798
+ queryParams: { createOnly: true, columns },
1357
1799
  ...fetchProps
1358
1800
  });
1359
- const finalObject = await this.read(response.id);
1360
- if (!finalObject) {
1361
- throw new Error("The server failed to save the record");
1362
- }
1363
- return finalObject;
1801
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1802
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1364
1803
  };
1365
1804
  _bulkInsertTableRecords = new WeakSet();
1366
- bulkInsertTableRecords_fn = async function(objects) {
1367
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1805
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1806
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1368
1807
  const records = objects.map((object) => transformObjectLinks(object));
1369
1808
  const response = await bulkInsertTableRecords({
1370
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1809
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1810
+ queryParams: { columns },
1371
1811
  body: { records },
1372
1812
  ...fetchProps
1373
1813
  });
1374
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1375
- if (finalObjects.length !== objects.length) {
1376
- throw new Error("The server failed to save some records");
1814
+ if (!isResponseWithRecords(response)) {
1815
+ throw new Error("Request included columns but server didn't include them");
1377
1816
  }
1378
- return finalObjects;
1817
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1818
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1379
1819
  };
1380
1820
  _updateRecordWithID = new WeakSet();
1381
- updateRecordWithID_fn = async function(recordId, object) {
1382
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1821
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1822
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1383
1823
  const record = transformObjectLinks(object);
1384
- const response = await updateRecordWithID({
1385
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1386
- body: record,
1387
- ...fetchProps
1388
- });
1389
- const item = await this.read(response.id);
1390
- if (!item)
1391
- throw new Error("The server failed to save the record");
1392
- return item;
1824
+ try {
1825
+ const response = await updateRecordWithID({
1826
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1827
+ queryParams: { columns },
1828
+ body: record,
1829
+ ...fetchProps
1830
+ });
1831
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1832
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1833
+ } catch (e) {
1834
+ if (isObject(e) && e.status === 404) {
1835
+ return null;
1836
+ }
1837
+ throw e;
1838
+ }
1393
1839
  };
1394
1840
  _upsertRecordWithID = new WeakSet();
1395
- upsertRecordWithID_fn = async function(recordId, object) {
1396
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1841
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1842
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1397
1843
  const response = await upsertRecordWithID({
1398
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1844
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1845
+ queryParams: { columns },
1399
1846
  body: object,
1400
1847
  ...fetchProps
1401
1848
  });
1402
- const item = await this.read(response.id);
1403
- if (!item)
1404
- throw new Error("The server failed to save the record");
1405
- return item;
1849
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1850
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1406
1851
  };
1407
1852
  _deleteRecord = new WeakSet();
1408
- deleteRecord_fn = async function(recordId) {
1409
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1410
- await deleteRecord({
1411
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1412
- ...fetchProps
1413
- });
1414
- };
1415
- _invalidateCache = new WeakSet();
1416
- invalidateCache_fn = async function(recordId) {
1417
- await __privateGet$3(this, _cache).delete(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1418
- const cacheItems = await __privateGet$3(this, _cache).getAll();
1419
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1420
- for (const [key, value] of queries) {
1421
- const ids = getIds(value);
1422
- if (ids.includes(recordId))
1423
- await __privateGet$3(this, _cache).delete(key);
1853
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1854
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1855
+ try {
1856
+ const response = await deleteRecord({
1857
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1858
+ queryParams: { columns },
1859
+ ...fetchProps
1860
+ });
1861
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1862
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1863
+ } catch (e) {
1864
+ if (isObject(e) && e.status === 404) {
1865
+ return null;
1866
+ }
1867
+ throw e;
1424
1868
  }
1425
1869
  };
1426
- _setCacheRecord = new WeakSet();
1427
- setCacheRecord_fn = async function(record) {
1428
- if (!__privateGet$3(this, _cache).cacheRecords)
1429
- return;
1430
- await __privateGet$3(this, _cache).set(`rec_${__privateGet$3(this, _table)}:${record.id}`, record);
1431
- };
1432
- _getCacheRecord = new WeakSet();
1433
- getCacheRecord_fn = async function(recordId) {
1434
- if (!__privateGet$3(this, _cache).cacheRecords)
1435
- return null;
1436
- return __privateGet$3(this, _cache).get(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1437
- };
1438
1870
  _setCacheQuery = new WeakSet();
1439
1871
  setCacheQuery_fn = async function(query, meta, records) {
1440
- await __privateGet$3(this, _cache).set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1872
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1441
1873
  };
1442
1874
  _getCacheQuery = new WeakSet();
1443
1875
  getCacheQuery_fn = async function(query) {
1444
- const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
1445
- const result = await __privateGet$3(this, _cache).get(key);
1876
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1877
+ const result = await __privateGet$4(this, _cache).get(key);
1446
1878
  if (!result)
1447
1879
  return null;
1448
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1449
- if (!ttl || ttl < 0)
1450
- return result;
1880
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1881
+ if (ttl < 0)
1882
+ return null;
1451
1883
  const hasExpired = result.date.getTime() + ttl < Date.now();
1452
1884
  return hasExpired ? null : result;
1453
1885
  };
1886
+ _getSchemaTables$1 = new WeakSet();
1887
+ getSchemaTables_fn$1 = async function() {
1888
+ if (__privateGet$4(this, _schemaTables$2))
1889
+ return __privateGet$4(this, _schemaTables$2);
1890
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1891
+ const { schema } = await getBranchDetails({
1892
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1893
+ ...fetchProps
1894
+ });
1895
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1896
+ return schema.tables;
1897
+ };
1454
1898
  const transformObjectLinks = (object) => {
1455
1899
  return Object.entries(object).reduce((acc, [key, value]) => {
1456
1900
  if (key === "xata")
@@ -1458,47 +1902,76 @@ const transformObjectLinks = (object) => {
1458
1902
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1459
1903
  }, {});
1460
1904
  };
1461
- const initObject = (db, links, table, object) => {
1905
+ const initObject = (db, schemaTables, table, object) => {
1462
1906
  const result = {};
1463
- Object.assign(result, object);
1464
- const tableLinks = links[table] || [];
1465
- for (const link of tableLinks) {
1466
- const [field, linkTable] = link;
1467
- const value = result[field];
1468
- if (value && isObject(value)) {
1469
- result[field] = initObject(db, links, linkTable, value);
1907
+ const { xata, ...rest } = object ?? {};
1908
+ Object.assign(result, rest);
1909
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1910
+ if (!columns)
1911
+ console.error(`Table ${table} not found in schema`);
1912
+ for (const column of columns ?? []) {
1913
+ const value = result[column.name];
1914
+ switch (column.type) {
1915
+ case "datetime": {
1916
+ const date = value !== void 0 ? new Date(value) : void 0;
1917
+ if (date && isNaN(date.getTime())) {
1918
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1919
+ } else if (date) {
1920
+ result[column.name] = date;
1921
+ }
1922
+ break;
1923
+ }
1924
+ case "link": {
1925
+ const linkTable = column.link?.table;
1926
+ if (!linkTable) {
1927
+ console.error(`Failed to parse link for field ${column.name}`);
1928
+ } else if (isObject(value)) {
1929
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1930
+ }
1931
+ break;
1932
+ }
1470
1933
  }
1471
1934
  }
1472
- result.read = function() {
1473
- return db[table].read(result["id"]);
1935
+ result.read = function(columns2) {
1936
+ return db[table].read(result["id"], columns2);
1474
1937
  };
1475
- result.update = function(data) {
1476
- return db[table].update(result["id"], data);
1938
+ result.update = function(data, columns2) {
1939
+ return db[table].update(result["id"], data, columns2);
1477
1940
  };
1478
1941
  result.delete = function() {
1479
1942
  return db[table].delete(result["id"]);
1480
1943
  };
1481
- for (const prop of ["read", "update", "delete"]) {
1944
+ result.getMetadata = function() {
1945
+ return xata;
1946
+ };
1947
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1482
1948
  Object.defineProperty(result, prop, { enumerable: false });
1483
1949
  }
1484
1950
  Object.freeze(result);
1485
1951
  return result;
1486
1952
  };
1487
- function getIds(value) {
1488
- if (Array.isArray(value)) {
1489
- return value.map((item) => getIds(item)).flat();
1490
- }
1491
- if (!isObject(value))
1492
- return [];
1493
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1494
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1953
+ function isResponseWithRecords(value) {
1954
+ return isObject(value) && Array.isArray(value.records);
1955
+ }
1956
+ function extractId(value) {
1957
+ if (isString(value))
1958
+ return value;
1959
+ if (isObject(value) && isString(value.id))
1960
+ return value.id;
1961
+ return void 0;
1962
+ }
1963
+ function cleanFilter(filter) {
1964
+ if (!filter)
1965
+ return void 0;
1966
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1967
+ return values.length > 0 ? filter : void 0;
1495
1968
  }
1496
1969
 
1497
1970
  var __accessCheck$3 = (obj, member, msg) => {
1498
1971
  if (!member.has(obj))
1499
1972
  throw TypeError("Cannot " + msg);
1500
1973
  };
1501
- var __privateGet$2 = (obj, member, getter) => {
1974
+ var __privateGet$3 = (obj, member, getter) => {
1502
1975
  __accessCheck$3(obj, member, "read from private field");
1503
1976
  return getter ? getter.call(obj) : member.get(obj);
1504
1977
  };
@@ -1507,7 +1980,7 @@ var __privateAdd$3 = (obj, member, value) => {
1507
1980
  throw TypeError("Cannot add the same private member more than once");
1508
1981
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1509
1982
  };
1510
- var __privateSet$1 = (obj, member, value, setter) => {
1983
+ var __privateSet$3 = (obj, member, value, setter) => {
1511
1984
  __accessCheck$3(obj, member, "write to private field");
1512
1985
  setter ? setter.call(obj, value) : member.set(obj, value);
1513
1986
  return value;
@@ -1516,46 +1989,52 @@ var _map;
1516
1989
  class SimpleCache {
1517
1990
  constructor(options = {}) {
1518
1991
  __privateAdd$3(this, _map, void 0);
1519
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
1992
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1520
1993
  this.capacity = options.max ?? 500;
1521
- this.cacheRecords = options.cacheRecords ?? true;
1522
1994
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1523
1995
  }
1524
1996
  async getAll() {
1525
- return Object.fromEntries(__privateGet$2(this, _map));
1997
+ return Object.fromEntries(__privateGet$3(this, _map));
1526
1998
  }
1527
1999
  async get(key) {
1528
- return __privateGet$2(this, _map).get(key) ?? null;
2000
+ return __privateGet$3(this, _map).get(key) ?? null;
1529
2001
  }
1530
2002
  async set(key, value) {
1531
2003
  await this.delete(key);
1532
- __privateGet$2(this, _map).set(key, value);
1533
- if (__privateGet$2(this, _map).size > this.capacity) {
1534
- const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
2004
+ __privateGet$3(this, _map).set(key, value);
2005
+ if (__privateGet$3(this, _map).size > this.capacity) {
2006
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1535
2007
  await this.delete(leastRecentlyUsed);
1536
2008
  }
1537
2009
  }
1538
2010
  async delete(key) {
1539
- __privateGet$2(this, _map).delete(key);
2011
+ __privateGet$3(this, _map).delete(key);
1540
2012
  }
1541
2013
  async clear() {
1542
- return __privateGet$2(this, _map).clear();
2014
+ return __privateGet$3(this, _map).clear();
1543
2015
  }
1544
2016
  }
1545
2017
  _map = new WeakMap();
1546
2018
 
1547
- const gt = (value) => ({ $gt: value });
1548
- const ge = (value) => ({ $ge: value });
1549
- const gte = (value) => ({ $ge: value });
1550
- const lt = (value) => ({ $lt: value });
1551
- const lte = (value) => ({ $le: value });
1552
- const le = (value) => ({ $le: value });
2019
+ const greaterThan = (value) => ({ $gt: value });
2020
+ const gt = greaterThan;
2021
+ const greaterThanEquals = (value) => ({ $ge: value });
2022
+ const greaterEquals = greaterThanEquals;
2023
+ const gte = greaterThanEquals;
2024
+ const ge = greaterThanEquals;
2025
+ const lessThan = (value) => ({ $lt: value });
2026
+ const lt = lessThan;
2027
+ const lessThanEquals = (value) => ({ $le: value });
2028
+ const lessEquals = lessThanEquals;
2029
+ const lte = lessThanEquals;
2030
+ const le = lessThanEquals;
1553
2031
  const exists = (column) => ({ $exists: column });
1554
2032
  const notExists = (column) => ({ $notExists: column });
1555
2033
  const startsWith = (value) => ({ $startsWith: value });
1556
2034
  const endsWith = (value) => ({ $endsWith: value });
1557
2035
  const pattern = (value) => ({ $pattern: value });
1558
2036
  const is = (value) => ({ $is: value });
2037
+ const equals = is;
1559
2038
  const isNot = (value) => ({ $isNot: value });
1560
2039
  const contains = (value) => ({ $contains: value });
1561
2040
  const includes = (value) => ({ $includes: value });
@@ -1567,7 +2046,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1567
2046
  if (!member.has(obj))
1568
2047
  throw TypeError("Cannot " + msg);
1569
2048
  };
1570
- var __privateGet$1 = (obj, member, getter) => {
2049
+ var __privateGet$2 = (obj, member, getter) => {
1571
2050
  __accessCheck$2(obj, member, "read from private field");
1572
2051
  return getter ? getter.call(obj) : member.get(obj);
1573
2052
  };
@@ -1576,130 +2055,178 @@ var __privateAdd$2 = (obj, member, value) => {
1576
2055
  throw TypeError("Cannot add the same private member more than once");
1577
2056
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1578
2057
  };
1579
- var _tables;
2058
+ var __privateSet$2 = (obj, member, value, setter) => {
2059
+ __accessCheck$2(obj, member, "write to private field");
2060
+ setter ? setter.call(obj, value) : member.set(obj, value);
2061
+ return value;
2062
+ };
2063
+ var _tables, _schemaTables$1;
1580
2064
  class SchemaPlugin extends XataPlugin {
1581
- constructor(links, tableNames) {
2065
+ constructor(schemaTables) {
1582
2066
  super();
1583
- this.links = links;
1584
- this.tableNames = tableNames;
1585
2067
  __privateAdd$2(this, _tables, {});
2068
+ __privateAdd$2(this, _schemaTables$1, void 0);
2069
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1586
2070
  }
1587
2071
  build(pluginOptions) {
1588
- const links = this.links;
1589
- const db = new Proxy({}, {
1590
- get: (_target, table) => {
1591
- if (!isString(table))
1592
- throw new Error("Invalid table name");
1593
- if (!__privateGet$1(this, _tables)[table]) {
1594
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, links });
2072
+ const db = new Proxy(
2073
+ {},
2074
+ {
2075
+ get: (_target, table) => {
2076
+ if (!isString(table))
2077
+ throw new Error("Invalid table name");
2078
+ if (__privateGet$2(this, _tables)[table] === void 0) {
2079
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
2080
+ }
2081
+ return __privateGet$2(this, _tables)[table];
1595
2082
  }
1596
- return __privateGet$1(this, _tables)[table];
1597
2083
  }
1598
- });
1599
- for (const table of this.tableNames ?? []) {
1600
- db[table] = new RestRepository({ db, pluginOptions, table, links });
2084
+ );
2085
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
2086
+ for (const table of tableNames) {
2087
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1601
2088
  }
1602
2089
  return db;
1603
2090
  }
1604
2091
  }
1605
2092
  _tables = new WeakMap();
2093
+ _schemaTables$1 = new WeakMap();
1606
2094
 
1607
2095
  var __accessCheck$1 = (obj, member, msg) => {
1608
2096
  if (!member.has(obj))
1609
2097
  throw TypeError("Cannot " + msg);
1610
2098
  };
2099
+ var __privateGet$1 = (obj, member, getter) => {
2100
+ __accessCheck$1(obj, member, "read from private field");
2101
+ return getter ? getter.call(obj) : member.get(obj);
2102
+ };
1611
2103
  var __privateAdd$1 = (obj, member, value) => {
1612
2104
  if (member.has(obj))
1613
2105
  throw TypeError("Cannot add the same private member more than once");
1614
2106
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1615
2107
  };
2108
+ var __privateSet$1 = (obj, member, value, setter) => {
2109
+ __accessCheck$1(obj, member, "write to private field");
2110
+ setter ? setter.call(obj, value) : member.set(obj, value);
2111
+ return value;
2112
+ };
1616
2113
  var __privateMethod$1 = (obj, member, method) => {
1617
2114
  __accessCheck$1(obj, member, "access private method");
1618
2115
  return method;
1619
2116
  };
1620
- var _search, search_fn;
2117
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1621
2118
  class SearchPlugin extends XataPlugin {
1622
- constructor(db, links) {
2119
+ constructor(db, schemaTables) {
1623
2120
  super();
1624
2121
  this.db = db;
1625
- this.links = links;
1626
2122
  __privateAdd$1(this, _search);
2123
+ __privateAdd$1(this, _getSchemaTables);
2124
+ __privateAdd$1(this, _schemaTables, void 0);
2125
+ __privateSet$1(this, _schemaTables, schemaTables);
1627
2126
  }
1628
2127
  build({ getFetchProps }) {
1629
2128
  return {
1630
2129
  all: async (query, options = {}) => {
1631
2130
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2131
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1632
2132
  return records.map((record) => {
1633
2133
  const { table = "orphan" } = record.xata;
1634
- return { table, record: initObject(this.db, this.links, table, record) };
2134
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1635
2135
  });
1636
2136
  },
1637
2137
  byTable: async (query, options = {}) => {
1638
2138
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2139
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1639
2140
  return records.reduce((acc, record) => {
1640
2141
  const { table = "orphan" } = record.xata;
1641
2142
  const items = acc[table] ?? [];
1642
- const item = initObject(this.db, this.links, table, record);
2143
+ const item = initObject(this.db, schemaTables, table, record);
1643
2144
  return { ...acc, [table]: [...items, item] };
1644
2145
  }, {});
1645
2146
  }
1646
2147
  };
1647
2148
  }
1648
2149
  }
2150
+ _schemaTables = new WeakMap();
1649
2151
  _search = new WeakSet();
1650
2152
  search_fn = async function(query, options, getFetchProps) {
1651
2153
  const fetchProps = await getFetchProps();
1652
- const { tables, fuzziness } = options ?? {};
2154
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1653
2155
  const { records } = await searchBranch({
1654
2156
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1655
- body: { tables, query, fuzziness },
2157
+ body: { tables, query, fuzziness, prefix, highlight },
1656
2158
  ...fetchProps
1657
2159
  });
1658
2160
  return records;
1659
2161
  };
2162
+ _getSchemaTables = new WeakSet();
2163
+ getSchemaTables_fn = async function(getFetchProps) {
2164
+ if (__privateGet$1(this, _schemaTables))
2165
+ return __privateGet$1(this, _schemaTables);
2166
+ const fetchProps = await getFetchProps();
2167
+ const { schema } = await getBranchDetails({
2168
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2169
+ ...fetchProps
2170
+ });
2171
+ __privateSet$1(this, _schemaTables, schema.tables);
2172
+ return schema.tables;
2173
+ };
1660
2174
 
1661
2175
  const isBranchStrategyBuilder = (strategy) => {
1662
2176
  return typeof strategy === "function";
1663
2177
  };
1664
2178
 
1665
- const envBranchNames = [
1666
- "XATA_BRANCH",
1667
- "VERCEL_GIT_COMMIT_REF",
1668
- "CF_PAGES_BRANCH",
1669
- "BRANCH"
1670
- ];
1671
- const defaultBranch = "main";
1672
2179
  async function getCurrentBranchName(options) {
1673
- const env = await getBranchByEnvVariable();
1674
- if (env)
1675
- return env;
1676
- const branch = await getGitBranch();
1677
- if (!branch)
1678
- return defaultBranch;
1679
- const details = await getDatabaseBranch(branch, options);
1680
- if (details)
1681
- return branch;
1682
- return defaultBranch;
2180
+ const { branch, envBranch } = getEnvironment();
2181
+ if (branch) {
2182
+ const details = await getDatabaseBranch(branch, options);
2183
+ if (details)
2184
+ return branch;
2185
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2186
+ }
2187
+ const gitBranch = envBranch || await getGitBranch();
2188
+ return resolveXataBranch(gitBranch, options);
1683
2189
  }
1684
2190
  async function getCurrentBranchDetails(options) {
1685
- const env = await getBranchByEnvVariable();
1686
- if (env)
1687
- return getDatabaseBranch(env, options);
1688
- const branch = await getGitBranch();
1689
- if (!branch)
1690
- return getDatabaseBranch(defaultBranch, options);
1691
- const details = await getDatabaseBranch(branch, options);
1692
- if (details)
1693
- return details;
1694
- return getDatabaseBranch(defaultBranch, options);
2191
+ const branch = await getCurrentBranchName(options);
2192
+ return getDatabaseBranch(branch, options);
2193
+ }
2194
+ async function resolveXataBranch(gitBranch, options) {
2195
+ const databaseURL = options?.databaseURL || getDatabaseURL();
2196
+ const apiKey = options?.apiKey || getAPIKey();
2197
+ if (!databaseURL)
2198
+ throw new Error(
2199
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2200
+ );
2201
+ if (!apiKey)
2202
+ throw new Error(
2203
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2204
+ );
2205
+ const [protocol, , host, , dbName] = databaseURL.split("/");
2206
+ const [workspace] = host.split(".");
2207
+ const { fallbackBranch } = getEnvironment();
2208
+ const { branch } = await resolveBranch({
2209
+ apiKey,
2210
+ apiUrl: databaseURL,
2211
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
2212
+ workspacesApiUrl: `${protocol}//${host}`,
2213
+ pathParams: { dbName, workspace },
2214
+ queryParams: { gitBranch, fallbackBranch },
2215
+ trace: defaultTrace
2216
+ });
2217
+ return branch;
1695
2218
  }
1696
2219
  async function getDatabaseBranch(branch, options) {
1697
2220
  const databaseURL = options?.databaseURL || getDatabaseURL();
1698
2221
  const apiKey = options?.apiKey || getAPIKey();
1699
2222
  if (!databaseURL)
1700
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2223
+ throw new Error(
2224
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2225
+ );
1701
2226
  if (!apiKey)
1702
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2227
+ throw new Error(
2228
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2229
+ );
1703
2230
  const [protocol, , host, , database] = databaseURL.split("/");
1704
2231
  const [workspace] = host.split(".");
1705
2232
  const dbBranchName = `${database}:${branch}`;
@@ -1709,10 +2236,8 @@ async function getDatabaseBranch(branch, options) {
1709
2236
  apiUrl: databaseURL,
1710
2237
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1711
2238
  workspacesApiUrl: `${protocol}//${host}`,
1712
- pathParams: {
1713
- dbBranchName,
1714
- workspace
1715
- }
2239
+ pathParams: { dbBranchName, workspace },
2240
+ trace: defaultTrace
1716
2241
  });
1717
2242
  } catch (err) {
1718
2243
  if (isObject(err) && err.status === 404)
@@ -1720,21 +2245,10 @@ async function getDatabaseBranch(branch, options) {
1720
2245
  throw err;
1721
2246
  }
1722
2247
  }
1723
- function getBranchByEnvVariable() {
1724
- for (const name of envBranchNames) {
1725
- const value = getEnvVariable(name);
1726
- if (value) {
1727
- return value;
1728
- }
1729
- }
1730
- try {
1731
- return XATA_BRANCH;
1732
- } catch (err) {
1733
- }
1734
- }
1735
2248
  function getDatabaseURL() {
1736
2249
  try {
1737
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2250
+ const { databaseURL } = getEnvironment();
2251
+ return databaseURL;
1738
2252
  } catch (err) {
1739
2253
  return void 0;
1740
2254
  }
@@ -1763,24 +2277,27 @@ var __privateMethod = (obj, member, method) => {
1763
2277
  return method;
1764
2278
  };
1765
2279
  const buildClient = (plugins) => {
1766
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2280
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1767
2281
  return _a = class {
1768
- constructor(options = {}, links, tables) {
2282
+ constructor(options = {}, schemaTables) {
1769
2283
  __privateAdd(this, _parseOptions);
1770
2284
  __privateAdd(this, _getFetchProps);
1771
2285
  __privateAdd(this, _evaluateBranch);
1772
2286
  __privateAdd(this, _branch, void 0);
2287
+ __privateAdd(this, _options, void 0);
1773
2288
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2289
+ __privateSet(this, _options, safeOptions);
1774
2290
  const pluginOptions = {
1775
2291
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1776
- cache: safeOptions.cache
2292
+ cache: safeOptions.cache,
2293
+ trace: safeOptions.trace
1777
2294
  };
1778
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1779
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
2295
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2296
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1780
2297
  this.db = db;
1781
2298
  this.search = search;
1782
2299
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1783
- if (!namespace)
2300
+ if (namespace === void 0)
1784
2301
  continue;
1785
2302
  const result = namespace.build(pluginOptions);
1786
2303
  if (result instanceof Promise) {
@@ -1792,22 +2309,26 @@ const buildClient = (plugins) => {
1792
2309
  }
1793
2310
  }
1794
2311
  }
1795
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2312
+ async getConfig() {
2313
+ const databaseURL = __privateGet(this, _options).databaseURL;
2314
+ const branch = await __privateGet(this, _options).branch();
2315
+ return { databaseURL, branch };
2316
+ }
2317
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1796
2318
  const fetch = getFetchImplementation(options?.fetch);
1797
2319
  const databaseURL = options?.databaseURL || getDatabaseURL();
1798
2320
  const apiKey = options?.apiKey || getAPIKey();
1799
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1800
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1801
- if (!databaseURL || !apiKey) {
1802
- throw new Error("Options databaseURL and apiKey are required");
2321
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2322
+ const trace = options?.trace ?? defaultTrace;
2323
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2324
+ if (!apiKey) {
2325
+ throw new Error("Option apiKey is required");
1803
2326
  }
1804
- return { fetch, databaseURL, apiKey, branch, cache };
1805
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1806
- fetch,
1807
- apiKey,
1808
- databaseURL,
1809
- branch
1810
- }) {
2327
+ if (!databaseURL) {
2328
+ throw new Error("Option databaseURL is required");
2329
+ }
2330
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2331
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
1811
2332
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1812
2333
  if (!branchValue)
1813
2334
  throw new Error("Unable to resolve branch value");
@@ -1817,14 +2338,15 @@ const buildClient = (plugins) => {
1817
2338
  apiUrl: "",
1818
2339
  workspacesApiUrl: (path, params) => {
1819
2340
  const hasBranch = params.dbBranchName ?? params.branch;
1820
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
2341
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
1821
2342
  return databaseURL + newPath;
1822
- }
2343
+ },
2344
+ trace
1823
2345
  };
1824
2346
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1825
2347
  if (__privateGet(this, _branch))
1826
2348
  return __privateGet(this, _branch);
1827
- if (!param)
2349
+ if (param === void 0)
1828
2350
  return void 0;
1829
2351
  const strategies = Array.isArray(param) ? [...param] : [param];
1830
2352
  const evaluateBranch = async (strategy) => {
@@ -1842,6 +2364,88 @@ const buildClient = (plugins) => {
1842
2364
  class BaseClient extends buildClient() {
1843
2365
  }
1844
2366
 
2367
+ const META = "__";
2368
+ const VALUE = "___";
2369
+ class Serializer {
2370
+ constructor() {
2371
+ this.classes = {};
2372
+ }
2373
+ add(clazz) {
2374
+ this.classes[clazz.name] = clazz;
2375
+ }
2376
+ toJSON(data) {
2377
+ function visit(obj) {
2378
+ if (Array.isArray(obj))
2379
+ return obj.map(visit);
2380
+ const type = typeof obj;
2381
+ if (type === "undefined")
2382
+ return { [META]: "undefined" };
2383
+ if (type === "bigint")
2384
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2385
+ if (obj === null || type !== "object")
2386
+ return obj;
2387
+ const constructor = obj.constructor;
2388
+ const o = { [META]: constructor.name };
2389
+ for (const [key, value] of Object.entries(obj)) {
2390
+ o[key] = visit(value);
2391
+ }
2392
+ if (constructor === Date)
2393
+ o[VALUE] = obj.toISOString();
2394
+ if (constructor === Map)
2395
+ o[VALUE] = Object.fromEntries(obj);
2396
+ if (constructor === Set)
2397
+ o[VALUE] = [...obj];
2398
+ return o;
2399
+ }
2400
+ return JSON.stringify(visit(data));
2401
+ }
2402
+ fromJSON(json) {
2403
+ return JSON.parse(json, (key, value) => {
2404
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2405
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2406
+ const constructor = this.classes[clazz];
2407
+ if (constructor) {
2408
+ return Object.assign(Object.create(constructor.prototype), rest);
2409
+ }
2410
+ if (clazz === "Date")
2411
+ return new Date(val);
2412
+ if (clazz === "Set")
2413
+ return new Set(val);
2414
+ if (clazz === "Map")
2415
+ return new Map(Object.entries(val));
2416
+ if (clazz === "bigint")
2417
+ return BigInt(val);
2418
+ if (clazz === "undefined")
2419
+ return void 0;
2420
+ return rest;
2421
+ }
2422
+ return value;
2423
+ });
2424
+ }
2425
+ }
2426
+ const defaultSerializer = new Serializer();
2427
+ const serialize = (data) => {
2428
+ return defaultSerializer.toJSON(data);
2429
+ };
2430
+ const deserialize = (json) => {
2431
+ return defaultSerializer.fromJSON(json);
2432
+ };
2433
+
2434
+ function buildWorkerRunner(config) {
2435
+ return function xataWorker(name, _worker) {
2436
+ return async (...args) => {
2437
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2438
+ const result = await fetch(url, {
2439
+ method: "POST",
2440
+ headers: { "Content-Type": "application/json" },
2441
+ body: serialize({ args })
2442
+ });
2443
+ const text = await result.text();
2444
+ return deserialize(text);
2445
+ };
2446
+ };
2447
+ }
2448
+
1845
2449
  class XataError extends Error {
1846
2450
  constructor(message, status) {
1847
2451
  super(message);
@@ -1849,5 +2453,5 @@ class XataError extends Error {
1849
2453
  }
1850
2454
  }
1851
2455
 
1852
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2456
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, applyBranchSchemaEdit, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequests, listMigrationRequestsCommits, lt, lte, mergeMigrationRequest, notExists, operationsByTag, pattern, previewBranchSchemaEdit, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, updateBranchMetadata, updateBranchSchema, updateColumn, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
1853
2457
  //# sourceMappingURL=index.mjs.map