@xata.io/client 0.0.0-alpha.vecada6d → 0.0.0-alpha.vecd13ea

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