@xata.io/client 0.0.0-alpha.vf0f8e71 → 0.0.0-alpha.vf0fa187

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,3 +1,26 @@
1
+ const defaultTrace = async (name, fn, _options) => {
2
+ return await fn({
3
+ name,
4
+ setAttributes: () => {
5
+ return;
6
+ }
7
+ });
8
+ };
9
+ const TraceAttributes = {
10
+ KIND: "xata.trace.kind",
11
+ VERSION: "xata.sdk.version",
12
+ TABLE: "xata.table",
13
+ HTTP_REQUEST_ID: "http.request_id",
14
+ HTTP_STATUS_CODE: "http.status_code",
15
+ HTTP_HOST: "http.host",
16
+ HTTP_SCHEME: "http.scheme",
17
+ HTTP_USER_AGENT: "http.user_agent",
18
+ HTTP_METHOD: "http.method",
19
+ HTTP_URL: "http.url",
20
+ HTTP_ROUTE: "http.route",
21
+ HTTP_TARGET: "http.target"
22
+ };
23
+
1
24
  function notEmpty(value) {
2
25
  return value !== null && value !== void 0;
3
26
  }
@@ -13,6 +36,24 @@ function isDefined(value) {
13
36
  function isString(value) {
14
37
  return isDefined(value) && typeof value === "string";
15
38
  }
39
+ function isStringArray(value) {
40
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
41
+ }
42
+ function isNumber(value) {
43
+ return isDefined(value) && typeof value === "number";
44
+ }
45
+ function parseNumber(value) {
46
+ if (isNumber(value)) {
47
+ return value;
48
+ }
49
+ if (isString(value)) {
50
+ const parsed = Number(value);
51
+ if (!Number.isNaN(parsed)) {
52
+ return parsed;
53
+ }
54
+ }
55
+ return void 0;
56
+ }
16
57
  function toBase64(value) {
17
58
  try {
18
59
  return btoa(value);
@@ -21,14 +62,36 @@ function toBase64(value) {
21
62
  return buf.from(value).toString("base64");
22
63
  }
23
64
  }
65
+ function deepMerge(a, b) {
66
+ const result = { ...a };
67
+ for (const [key, value] of Object.entries(b)) {
68
+ if (isObject(value) && isObject(result[key])) {
69
+ result[key] = deepMerge(result[key], value);
70
+ } else {
71
+ result[key] = value;
72
+ }
73
+ }
74
+ return result;
75
+ }
76
+ function chunk(array, chunkSize) {
77
+ const result = [];
78
+ for (let i = 0; i < array.length; i += chunkSize) {
79
+ result.push(array.slice(i, i + chunkSize));
80
+ }
81
+ return result;
82
+ }
83
+ async function timeout(ms) {
84
+ return new Promise((resolve) => setTimeout(resolve, ms));
85
+ }
24
86
 
25
87
  function getEnvironment() {
26
88
  try {
27
- if (isObject(process) && isObject(process.env)) {
89
+ if (isDefined(process) && isDefined(process.env)) {
28
90
  return {
29
91
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
30
92
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
31
- branch: process.env.XATA_BRANCH ?? process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH ?? getGlobalBranch(),
93
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
94
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
32
95
  fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
33
96
  };
34
97
  }
@@ -39,7 +102,8 @@ function getEnvironment() {
39
102
  return {
40
103
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
41
104
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
42
- branch: Deno.env.get("XATA_BRANCH") ?? Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH") ?? getGlobalBranch(),
105
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
106
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
43
107
  fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
44
108
  };
45
109
  }
@@ -49,9 +113,29 @@ function getEnvironment() {
49
113
  apiKey: getGlobalApiKey(),
50
114
  databaseURL: getGlobalDatabaseURL(),
51
115
  branch: getGlobalBranch(),
116
+ envBranch: void 0,
52
117
  fallbackBranch: getGlobalFallbackBranch()
53
118
  };
54
119
  }
120
+ function getEnableBrowserVariable() {
121
+ try {
122
+ if (isObject(process) && isObject(process.env) && process.env.XATA_ENABLE_BROWSER !== void 0) {
123
+ return process.env.XATA_ENABLE_BROWSER === "true";
124
+ }
125
+ } catch (err) {
126
+ }
127
+ try {
128
+ if (isObject(Deno) && isObject(Deno.env) && Deno.env.get("XATA_ENABLE_BROWSER") !== void 0) {
129
+ return Deno.env.get("XATA_ENABLE_BROWSER") === "true";
130
+ }
131
+ } catch (err) {
132
+ }
133
+ try {
134
+ return XATA_ENABLE_BROWSER === true || XATA_ENABLE_BROWSER === "true";
135
+ } catch (err) {
136
+ return void 0;
137
+ }
138
+ }
55
139
  function getGlobalApiKey() {
56
140
  try {
57
141
  return XATA_API_KEY;
@@ -81,20 +165,18 @@ function getGlobalFallbackBranch() {
81
165
  }
82
166
  }
83
167
  async function getGitBranch() {
168
+ const cmd = ["git", "branch", "--show-current"];
169
+ const fullCmd = cmd.join(" ");
170
+ const nodeModule = ["child", "process"].join("_");
171
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
84
172
  try {
85
- if (typeof require === "function") {
86
- const req = require;
87
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
88
- }
173
+ const { execSync } = await import(nodeModule);
174
+ return execSync(fullCmd, execOptions).toString().trim();
89
175
  } catch (err) {
90
176
  }
91
177
  try {
92
178
  if (isObject(Deno)) {
93
- const process2 = Deno.run({
94
- cmd: ["git", "branch", "--show-current"],
95
- stdout: "piped",
96
- stderr: "piped"
97
- });
179
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
98
180
  return new TextDecoder().decode(await process2.output()).trim();
99
181
  }
100
182
  } catch (err) {
@@ -110,16 +192,114 @@ function getAPIKey() {
110
192
  }
111
193
  }
112
194
 
195
+ var __accessCheck$8 = (obj, member, msg) => {
196
+ if (!member.has(obj))
197
+ throw TypeError("Cannot " + msg);
198
+ };
199
+ var __privateGet$8 = (obj, member, getter) => {
200
+ __accessCheck$8(obj, member, "read from private field");
201
+ return getter ? getter.call(obj) : member.get(obj);
202
+ };
203
+ var __privateAdd$8 = (obj, member, value) => {
204
+ if (member.has(obj))
205
+ throw TypeError("Cannot add the same private member more than once");
206
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
207
+ };
208
+ var __privateSet$8 = (obj, member, value, setter) => {
209
+ __accessCheck$8(obj, member, "write to private field");
210
+ setter ? setter.call(obj, value) : member.set(obj, value);
211
+ return value;
212
+ };
213
+ var __privateMethod$4 = (obj, member, method) => {
214
+ __accessCheck$8(obj, member, "access private method");
215
+ return method;
216
+ };
217
+ var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
113
218
  function getFetchImplementation(userFetch) {
114
219
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
115
220
  const fetchImpl = userFetch ?? globalFetch;
116
221
  if (!fetchImpl) {
117
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
222
+ throw new Error(
223
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
224
+ );
118
225
  }
119
226
  return fetchImpl;
120
227
  }
228
+ class ApiRequestPool {
229
+ constructor(concurrency = 10) {
230
+ __privateAdd$8(this, _enqueue);
231
+ __privateAdd$8(this, _fetch, void 0);
232
+ __privateAdd$8(this, _queue, void 0);
233
+ __privateAdd$8(this, _concurrency, void 0);
234
+ __privateSet$8(this, _queue, []);
235
+ __privateSet$8(this, _concurrency, concurrency);
236
+ this.running = 0;
237
+ this.started = 0;
238
+ }
239
+ setFetch(fetch2) {
240
+ __privateSet$8(this, _fetch, fetch2);
241
+ }
242
+ getFetch() {
243
+ if (!__privateGet$8(this, _fetch)) {
244
+ throw new Error("Fetch not set");
245
+ }
246
+ return __privateGet$8(this, _fetch);
247
+ }
248
+ request(url, options) {
249
+ const start = new Date();
250
+ const fetch2 = this.getFetch();
251
+ const runRequest = async (stalled = false) => {
252
+ const response = await fetch2(url, options);
253
+ if (response.status === 429) {
254
+ const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
255
+ await timeout(rateLimitReset * 1e3);
256
+ return await runRequest(true);
257
+ }
258
+ if (stalled) {
259
+ const stalledTime = new Date().getTime() - start.getTime();
260
+ console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
261
+ }
262
+ return response;
263
+ };
264
+ return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
265
+ return await runRequest();
266
+ });
267
+ }
268
+ }
269
+ _fetch = new WeakMap();
270
+ _queue = new WeakMap();
271
+ _concurrency = new WeakMap();
272
+ _enqueue = new WeakSet();
273
+ enqueue_fn = function(task) {
274
+ const promise = new Promise((resolve) => __privateGet$8(this, _queue).push(resolve)).finally(() => {
275
+ this.started--;
276
+ this.running++;
277
+ }).then(() => task()).finally(() => {
278
+ this.running--;
279
+ const next = __privateGet$8(this, _queue).shift();
280
+ if (next !== void 0) {
281
+ this.started++;
282
+ next();
283
+ }
284
+ });
285
+ if (this.running + this.started < __privateGet$8(this, _concurrency)) {
286
+ const next = __privateGet$8(this, _queue).shift();
287
+ if (next !== void 0) {
288
+ this.started++;
289
+ next();
290
+ }
291
+ }
292
+ return promise;
293
+ };
294
+
295
+ function generateUUID() {
296
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
297
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
298
+ return v.toString(16);
299
+ });
300
+ }
121
301
 
122
- const VERSION = "0.0.0-alpha.vf0f8e71";
302
+ const VERSION = "0.22.0";
123
303
 
124
304
  class ErrorWithCause extends Error {
125
305
  constructor(message, options) {
@@ -130,7 +310,7 @@ class FetcherError extends ErrorWithCause {
130
310
  constructor(status, data, requestId) {
131
311
  super(getMessage(data));
132
312
  this.status = status;
133
- this.errors = isBulkError(data) ? data.errors : void 0;
313
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
134
314
  this.requestId = requestId;
135
315
  if (data instanceof Error) {
136
316
  this.stack = data.stack;
@@ -162,6 +342,7 @@ function getMessage(data) {
162
342
  }
163
343
  }
164
344
 
345
+ const pool = new ApiRequestPool();
165
346
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
166
347
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
167
348
  if (value === void 0 || value === null)
@@ -170,305 +351,266 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
170
351
  }, {});
171
352
  const query = new URLSearchParams(cleanQueryParams).toString();
172
353
  const queryString = query.length > 0 ? `?${query}` : "";
173
- return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
354
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
355
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
356
+ }, {});
357
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
174
358
  };
175
359
  function buildBaseUrl({
360
+ endpoint,
176
361
  path,
177
362
  workspacesApiUrl,
178
363
  apiUrl,
179
- pathParams
364
+ pathParams = {}
180
365
  }) {
181
- if (!pathParams?.workspace)
182
- return `${apiUrl}${path}`;
183
- const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
184
- return url.replace("{workspaceId}", pathParams.workspace);
366
+ if (endpoint === "dataPlane") {
367
+ const url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
368
+ const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
369
+ return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
370
+ }
371
+ return `${apiUrl}${path}`;
185
372
  }
186
373
  function hostHeader(url) {
187
374
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
188
375
  const { groups } = pattern.exec(url) ?? {};
189
376
  return groups?.host ? { Host: groups.host } : {};
190
377
  }
378
+ const defaultClientID = generateUUID();
191
379
  async function fetch$1({
192
380
  url: path,
193
381
  method,
194
382
  body,
195
- headers,
383
+ headers: customHeaders,
196
384
  pathParams,
197
385
  queryParams,
198
386
  fetchImpl,
199
387
  apiKey,
388
+ endpoint,
200
389
  apiUrl,
201
- workspacesApiUrl
390
+ workspacesApiUrl,
391
+ trace,
392
+ signal,
393
+ clientID,
394
+ sessionID,
395
+ clientName,
396
+ fetchOptions = {}
202
397
  }) {
203
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
204
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
205
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
206
- const response = await fetchImpl(url, {
207
- method: method.toUpperCase(),
208
- body: body ? JSON.stringify(body) : void 0,
209
- headers: {
210
- "Content-Type": "application/json",
211
- "User-Agent": `Xata client-ts/${VERSION}`,
212
- ...headers,
213
- ...hostHeader(fullUrl),
214
- Authorization: `Bearer ${apiKey}`
215
- }
216
- });
217
- if (response.status === 204) {
218
- return {};
219
- }
220
- const requestId = response.headers?.get("x-request-id") ?? void 0;
398
+ pool.setFetch(fetchImpl);
399
+ return await trace(
400
+ `${method.toUpperCase()} ${path}`,
401
+ async ({ setAttributes }) => {
402
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
403
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
404
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
405
+ setAttributes({
406
+ [TraceAttributes.HTTP_URL]: url,
407
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
408
+ });
409
+ const xataAgent = compact([
410
+ ["client", "TS_SDK"],
411
+ ["version", VERSION],
412
+ isDefined(clientName) ? ["service", clientName] : void 0
413
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
414
+ const headers = {
415
+ "Accept-Encoding": "identity",
416
+ "Content-Type": "application/json",
417
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
418
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
419
+ "X-Xata-Agent": xataAgent,
420
+ ...customHeaders,
421
+ ...hostHeader(fullUrl),
422
+ Authorization: `Bearer ${apiKey}`
423
+ };
424
+ const response = await pool.request(url, {
425
+ ...fetchOptions,
426
+ method: method.toUpperCase(),
427
+ body: body ? JSON.stringify(body) : void 0,
428
+ headers,
429
+ signal
430
+ });
431
+ const { host, protocol } = parseUrl(response.url);
432
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
433
+ setAttributes({
434
+ [TraceAttributes.KIND]: "http",
435
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
436
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
437
+ [TraceAttributes.HTTP_HOST]: host,
438
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
439
+ });
440
+ if (response.status === 204) {
441
+ return {};
442
+ }
443
+ if (response.status === 429) {
444
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
445
+ }
446
+ try {
447
+ const jsonResponse = await response.json();
448
+ if (response.ok) {
449
+ return jsonResponse;
450
+ }
451
+ throw new FetcherError(response.status, jsonResponse, requestId);
452
+ } catch (error) {
453
+ throw new FetcherError(response.status, error, requestId);
454
+ }
455
+ },
456
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
457
+ );
458
+ }
459
+ function parseUrl(url) {
221
460
  try {
222
- const jsonResponse = await response.json();
223
- if (response.ok) {
224
- return jsonResponse;
225
- }
226
- throw new FetcherError(response.status, jsonResponse, requestId);
461
+ const { host, protocol } = new URL(url);
462
+ return { host, protocol };
227
463
  } catch (error) {
228
- throw new FetcherError(response.status, error, requestId);
464
+ return {};
229
465
  }
230
466
  }
231
467
 
232
- const getUser = (variables) => fetch$1({ url: "/user", method: "get", ...variables });
233
- const updateUser = (variables) => fetch$1({ url: "/user", method: "put", ...variables });
234
- const deleteUser = (variables) => fetch$1({ url: "/user", method: "delete", ...variables });
235
- const getUserAPIKeys = (variables) => fetch$1({
236
- url: "/user/keys",
237
- method: "get",
238
- ...variables
239
- });
240
- const createUserAPIKey = (variables) => fetch$1({
241
- url: "/user/keys/{keyName}",
242
- method: "post",
243
- ...variables
244
- });
245
- const deleteUserAPIKey = (variables) => fetch$1({
246
- url: "/user/keys/{keyName}",
247
- method: "delete",
248
- ...variables
249
- });
250
- const createWorkspace = (variables) => fetch$1({
251
- url: "/workspaces",
252
- method: "post",
253
- ...variables
254
- });
255
- const getWorkspacesList = (variables) => fetch$1({
256
- url: "/workspaces",
257
- method: "get",
258
- ...variables
259
- });
260
- const getWorkspace = (variables) => fetch$1({
261
- url: "/workspaces/{workspaceId}",
262
- method: "get",
263
- ...variables
264
- });
265
- const updateWorkspace = (variables) => fetch$1({
266
- url: "/workspaces/{workspaceId}",
267
- method: "put",
268
- ...variables
269
- });
270
- const deleteWorkspace = (variables) => fetch$1({
271
- url: "/workspaces/{workspaceId}",
272
- method: "delete",
273
- ...variables
274
- });
275
- const getWorkspaceMembersList = (variables) => fetch$1({
276
- url: "/workspaces/{workspaceId}/members",
277
- method: "get",
278
- ...variables
279
- });
280
- const updateWorkspaceMemberRole = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables });
281
- const removeWorkspaceMember = (variables) => fetch$1({
282
- url: "/workspaces/{workspaceId}/members/{userId}",
283
- method: "delete",
284
- ...variables
285
- });
286
- const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
287
- const cancelWorkspaceMemberInvite = (variables) => fetch$1({
288
- url: "/workspaces/{workspaceId}/invites/{inviteId}",
289
- method: "delete",
290
- ...variables
291
- });
292
- const resendWorkspaceMemberInvite = (variables) => fetch$1({
293
- url: "/workspaces/{workspaceId}/invites/{inviteId}/resend",
294
- method: "post",
295
- ...variables
296
- });
297
- const acceptWorkspaceMemberInvite = (variables) => fetch$1({
298
- url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept",
299
- method: "post",
300
- ...variables
301
- });
302
- const getDatabaseList = (variables) => fetch$1({
303
- url: "/dbs",
304
- method: "get",
305
- ...variables
306
- });
307
- const getBranchList = (variables) => fetch$1({
308
- url: "/dbs/{dbName}",
309
- method: "get",
310
- ...variables
311
- });
312
- const createDatabase = (variables) => fetch$1({
313
- url: "/dbs/{dbName}",
314
- method: "put",
315
- ...variables
316
- });
317
- const deleteDatabase = (variables) => fetch$1({
468
+ const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
469
+
470
+ const getBranchList = (variables, signal) => dataPlaneFetch({
318
471
  url: "/dbs/{dbName}",
319
- method: "delete",
320
- ...variables
321
- });
322
- const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
323
- const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
324
- const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
325
- const resolveBranch = (variables) => fetch$1({
326
- url: "/dbs/{dbName}/resolveBranch",
327
472
  method: "get",
328
- ...variables
473
+ ...variables,
474
+ signal
329
475
  });
330
- const getBranchDetails = (variables) => fetch$1({
476
+ const getBranchDetails = (variables, signal) => dataPlaneFetch({
331
477
  url: "/db/{dbBranchName}",
332
478
  method: "get",
333
- ...variables
479
+ ...variables,
480
+ signal
334
481
  });
335
- const createBranch = (variables) => fetch$1({
336
- url: "/db/{dbBranchName}",
337
- method: "put",
338
- ...variables
339
- });
340
- const deleteBranch = (variables) => fetch$1({
482
+ const createBranch = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
483
+ const deleteBranch = (variables, signal) => dataPlaneFetch({
341
484
  url: "/db/{dbBranchName}",
342
485
  method: "delete",
343
- ...variables
486
+ ...variables,
487
+ signal
344
488
  });
345
- const updateBranchMetadata = (variables) => fetch$1({
489
+ const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
346
490
  url: "/db/{dbBranchName}/metadata",
347
491
  method: "put",
348
- ...variables
492
+ ...variables,
493
+ signal
349
494
  });
350
- const getBranchMetadata = (variables) => fetch$1({
495
+ const getBranchMetadata = (variables, signal) => dataPlaneFetch({
351
496
  url: "/db/{dbBranchName}/metadata",
352
497
  method: "get",
353
- ...variables
498
+ ...variables,
499
+ signal
354
500
  });
355
- const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
356
- const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
357
- const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
358
- const getBranchStats = (variables) => fetch$1({
501
+ const getBranchStats = (variables, signal) => dataPlaneFetch({
359
502
  url: "/db/{dbBranchName}/stats",
360
503
  method: "get",
361
- ...variables
504
+ ...variables,
505
+ signal
506
+ });
507
+ const getGitBranchesMapping = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables, signal });
508
+ const addGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables, signal });
509
+ const removeGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables, signal });
510
+ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/resolveBranch", method: "get", ...variables, signal });
511
+ const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
512
+ const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
513
+ const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
514
+ const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
515
+ const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
516
+ const getMigrationRequest = (variables, signal) => dataPlaneFetch({
517
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
518
+ method: "get",
519
+ ...variables,
520
+ signal
521
+ });
522
+ const updateMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables, signal });
523
+ const listMigrationRequestsCommits = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables, signal });
524
+ const compareMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables, signal });
525
+ const getMigrationRequestIsMerged = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables, signal });
526
+ const mergeMigrationRequest = (variables, signal) => dataPlaneFetch({
527
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
528
+ method: "post",
529
+ ...variables,
530
+ signal
362
531
  });
363
- const createTable = (variables) => fetch$1({
532
+ const getBranchSchemaHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables, signal });
533
+ const compareBranchWithUserSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables, signal });
534
+ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables, signal });
535
+ const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
536
+ const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
537
+ const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
538
+ const createTable = (variables, signal) => dataPlaneFetch({
364
539
  url: "/db/{dbBranchName}/tables/{tableName}",
365
540
  method: "put",
366
- ...variables
541
+ ...variables,
542
+ signal
367
543
  });
368
- const deleteTable = (variables) => fetch$1({
544
+ const deleteTable = (variables, signal) => dataPlaneFetch({
369
545
  url: "/db/{dbBranchName}/tables/{tableName}",
370
546
  method: "delete",
371
- ...variables
547
+ ...variables,
548
+ signal
372
549
  });
373
- const updateTable = (variables) => fetch$1({
374
- url: "/db/{dbBranchName}/tables/{tableName}",
375
- method: "patch",
376
- ...variables
377
- });
378
- const getTableSchema = (variables) => fetch$1({
550
+ const updateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}", method: "patch", ...variables, signal });
551
+ const getTableSchema = (variables, signal) => dataPlaneFetch({
379
552
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
380
553
  method: "get",
381
- ...variables
554
+ ...variables,
555
+ signal
382
556
  });
383
- const setTableSchema = (variables) => fetch$1({
384
- url: "/db/{dbBranchName}/tables/{tableName}/schema",
385
- method: "put",
386
- ...variables
387
- });
388
- const getTableColumns = (variables) => fetch$1({
557
+ const setTableSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/schema", method: "put", ...variables, signal });
558
+ const getTableColumns = (variables, signal) => dataPlaneFetch({
389
559
  url: "/db/{dbBranchName}/tables/{tableName}/columns",
390
560
  method: "get",
391
- ...variables
392
- });
393
- const addTableColumn = (variables) => fetch$1({
394
- url: "/db/{dbBranchName}/tables/{tableName}/columns",
395
- method: "post",
396
- ...variables
561
+ ...variables,
562
+ signal
397
563
  });
398
- const getColumn = (variables) => fetch$1({
564
+ const addTableColumn = (variables, signal) => dataPlaneFetch(
565
+ { url: "/db/{dbBranchName}/tables/{tableName}/columns", method: "post", ...variables, signal }
566
+ );
567
+ const getColumn = (variables, signal) => dataPlaneFetch({
399
568
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
400
569
  method: "get",
401
- ...variables
402
- });
403
- const deleteColumn = (variables) => fetch$1({
404
- url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
405
- method: "delete",
406
- ...variables
570
+ ...variables,
571
+ signal
407
572
  });
408
- const updateColumn = (variables) => fetch$1({
573
+ const updateColumn = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}", method: "patch", ...variables, signal });
574
+ const deleteColumn = (variables, signal) => dataPlaneFetch({
409
575
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
410
- method: "patch",
411
- ...variables
412
- });
413
- const insertRecord = (variables) => fetch$1({
414
- url: "/db/{dbBranchName}/tables/{tableName}/data",
415
- method: "post",
416
- ...variables
417
- });
418
- const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
419
- const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
420
- const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
421
- const deleteRecord = (variables) => fetch$1({
422
- url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
423
576
  method: "delete",
424
- ...variables
577
+ ...variables,
578
+ signal
425
579
  });
426
- const getRecord = (variables) => fetch$1({
580
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
581
+ const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
582
+ const getRecord = (variables, signal) => dataPlaneFetch({
427
583
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
428
584
  method: "get",
429
- ...variables
585
+ ...variables,
586
+ signal
430
587
  });
431
- const bulkInsertTableRecords = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables });
432
- const queryTable = (variables) => fetch$1({
588
+ const insertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables, signal });
589
+ const updateRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables, signal });
590
+ const upsertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables, signal });
591
+ const deleteRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "delete", ...variables, signal });
592
+ const bulkInsertTableRecords = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables, signal });
593
+ const queryTable = (variables, signal) => dataPlaneFetch({
433
594
  url: "/db/{dbBranchName}/tables/{tableName}/query",
434
595
  method: "post",
435
- ...variables
596
+ ...variables,
597
+ signal
436
598
  });
437
- const searchTable = (variables) => fetch$1({
438
- url: "/db/{dbBranchName}/tables/{tableName}/search",
599
+ const searchBranch = (variables, signal) => dataPlaneFetch({
600
+ url: "/db/{dbBranchName}/search",
439
601
  method: "post",
440
- ...variables
602
+ ...variables,
603
+ signal
441
604
  });
442
- const searchBranch = (variables) => fetch$1({
443
- url: "/db/{dbBranchName}/search",
605
+ const searchTable = (variables, signal) => dataPlaneFetch({
606
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
444
607
  method: "post",
445
- ...variables
608
+ ...variables,
609
+ signal
446
610
  });
447
- const operationsByTag = {
448
- users: { getUser, updateUser, deleteUser, getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
449
- workspaces: {
450
- createWorkspace,
451
- getWorkspacesList,
452
- getWorkspace,
453
- updateWorkspace,
454
- deleteWorkspace,
455
- getWorkspaceMembersList,
456
- updateWorkspaceMemberRole,
457
- removeWorkspaceMember,
458
- inviteWorkspaceMember,
459
- cancelWorkspaceMemberInvite,
460
- resendWorkspaceMemberInvite,
461
- acceptWorkspaceMemberInvite
462
- },
463
- database: {
464
- getDatabaseList,
465
- createDatabase,
466
- deleteDatabase,
467
- getGitBranchesMapping,
468
- addGitBranchesEntry,
469
- removeGitBranchesEntry,
470
- resolveBranch
471
- },
611
+ const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
612
+ const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
613
+ const operationsByTag$2 = {
472
614
  branch: {
473
615
  getBranchList,
474
616
  getBranchDetails,
@@ -476,10 +618,32 @@ const operationsByTag = {
476
618
  deleteBranch,
477
619
  updateBranchMetadata,
478
620
  getBranchMetadata,
621
+ getBranchStats,
622
+ getGitBranchesMapping,
623
+ addGitBranchesEntry,
624
+ removeGitBranchesEntry,
625
+ resolveBranch
626
+ },
627
+ migrations: {
479
628
  getBranchMigrationHistory,
480
- executeBranchMigrationPlan,
481
629
  getBranchMigrationPlan,
482
- getBranchStats
630
+ executeBranchMigrationPlan,
631
+ getBranchSchemaHistory,
632
+ compareBranchWithUserSchema,
633
+ compareBranchSchemas,
634
+ updateBranchSchema,
635
+ previewBranchSchemaEdit,
636
+ applyBranchSchemaEdit
637
+ },
638
+ migrationRequests: {
639
+ queryMigrationRequests,
640
+ createMigrationRequest,
641
+ getMigrationRequest,
642
+ updateMigrationRequest,
643
+ listMigrationRequestsCommits,
644
+ compareMigrationRequest,
645
+ getMigrationRequestIsMerged,
646
+ mergeMigrationRequest
483
647
  },
484
648
  table: {
485
649
  createTable,
@@ -490,27 +654,166 @@ const operationsByTag = {
490
654
  getTableColumns,
491
655
  addTableColumn,
492
656
  getColumn,
493
- deleteColumn,
494
- updateColumn
657
+ updateColumn,
658
+ deleteColumn
495
659
  },
496
660
  records: {
661
+ branchTransaction,
497
662
  insertRecord,
663
+ getRecord,
498
664
  insertRecordWithID,
499
665
  updateRecordWithID,
500
666
  upsertRecordWithID,
501
667
  deleteRecord,
502
- getRecord,
503
- bulkInsertTableRecords,
504
- queryTable,
505
- searchTable,
506
- searchBranch
668
+ bulkInsertTableRecords
669
+ },
670
+ searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
671
+ };
672
+
673
+ const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
674
+
675
+ const getUser = (variables, signal) => controlPlaneFetch({
676
+ url: "/user",
677
+ method: "get",
678
+ ...variables,
679
+ signal
680
+ });
681
+ const updateUser = (variables, signal) => controlPlaneFetch({
682
+ url: "/user",
683
+ method: "put",
684
+ ...variables,
685
+ signal
686
+ });
687
+ const deleteUser = (variables, signal) => controlPlaneFetch({
688
+ url: "/user",
689
+ method: "delete",
690
+ ...variables,
691
+ signal
692
+ });
693
+ const getUserAPIKeys = (variables, signal) => controlPlaneFetch({
694
+ url: "/user/keys",
695
+ method: "get",
696
+ ...variables,
697
+ signal
698
+ });
699
+ const createUserAPIKey = (variables, signal) => controlPlaneFetch({
700
+ url: "/user/keys/{keyName}",
701
+ method: "post",
702
+ ...variables,
703
+ signal
704
+ });
705
+ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
706
+ url: "/user/keys/{keyName}",
707
+ method: "delete",
708
+ ...variables,
709
+ signal
710
+ });
711
+ const getWorkspacesList = (variables, signal) => controlPlaneFetch({
712
+ url: "/workspaces",
713
+ method: "get",
714
+ ...variables,
715
+ signal
716
+ });
717
+ const createWorkspace = (variables, signal) => controlPlaneFetch({
718
+ url: "/workspaces",
719
+ method: "post",
720
+ ...variables,
721
+ signal
722
+ });
723
+ const getWorkspace = (variables, signal) => controlPlaneFetch({
724
+ url: "/workspaces/{workspaceId}",
725
+ method: "get",
726
+ ...variables,
727
+ signal
728
+ });
729
+ const updateWorkspace = (variables, signal) => controlPlaneFetch({
730
+ url: "/workspaces/{workspaceId}",
731
+ method: "put",
732
+ ...variables,
733
+ signal
734
+ });
735
+ const deleteWorkspace = (variables, signal) => controlPlaneFetch({
736
+ url: "/workspaces/{workspaceId}",
737
+ method: "delete",
738
+ ...variables,
739
+ signal
740
+ });
741
+ const getWorkspaceMembersList = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/members", method: "get", ...variables, signal });
742
+ const updateWorkspaceMemberRole = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables, signal });
743
+ const removeWorkspaceMember = (variables, signal) => controlPlaneFetch({
744
+ url: "/workspaces/{workspaceId}/members/{userId}",
745
+ method: "delete",
746
+ ...variables,
747
+ signal
748
+ });
749
+ const inviteWorkspaceMember = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables, signal });
750
+ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables, signal });
751
+ const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
752
+ const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
753
+ const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
754
+ const getDatabaseList = (variables, signal) => controlPlaneFetch({
755
+ url: "/workspaces/{workspaceId}/dbs",
756
+ method: "get",
757
+ ...variables,
758
+ signal
759
+ });
760
+ const createDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables, signal });
761
+ const deleteDatabase = (variables, signal) => controlPlaneFetch({
762
+ url: "/workspaces/{workspaceId}/dbs/{dbName}",
763
+ method: "delete",
764
+ ...variables,
765
+ signal
766
+ });
767
+ const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
768
+ const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
769
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
770
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
771
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
772
+ const listRegions = (variables, signal) => controlPlaneFetch({
773
+ url: "/workspaces/{workspaceId}/regions",
774
+ method: "get",
775
+ ...variables,
776
+ signal
777
+ });
778
+ const operationsByTag$1 = {
779
+ users: { getUser, updateUser, deleteUser },
780
+ authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
781
+ workspaces: {
782
+ getWorkspacesList,
783
+ createWorkspace,
784
+ getWorkspace,
785
+ updateWorkspace,
786
+ deleteWorkspace,
787
+ getWorkspaceMembersList,
788
+ updateWorkspaceMemberRole,
789
+ removeWorkspaceMember
790
+ },
791
+ invites: {
792
+ inviteWorkspaceMember,
793
+ updateWorkspaceMemberInvite,
794
+ cancelWorkspaceMemberInvite,
795
+ acceptWorkspaceMemberInvite,
796
+ resendWorkspaceMemberInvite
797
+ },
798
+ databases: {
799
+ getDatabaseList,
800
+ createDatabase,
801
+ deleteDatabase,
802
+ getDatabaseMetadata,
803
+ updateDatabaseMetadata,
804
+ getDatabaseGithubSettings,
805
+ updateDatabaseGithubSettings,
806
+ deleteDatabaseGithubSettings,
807
+ listRegions
507
808
  }
508
809
  };
509
810
 
811
+ const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);
812
+
510
813
  function getHostUrl(provider, type) {
511
- if (isValidAlias(provider)) {
814
+ if (isHostProviderAlias(provider)) {
512
815
  return providers[provider][type];
513
- } else if (isValidBuilder(provider)) {
816
+ } else if (isHostProviderBuilder(provider)) {
514
817
  return provider[type];
515
818
  }
516
819
  throw new Error("Invalid API provider");
@@ -518,19 +821,39 @@ function getHostUrl(provider, type) {
518
821
  const providers = {
519
822
  production: {
520
823
  main: "https://api.xata.io",
521
- workspaces: "https://{workspaceId}.xata.sh"
824
+ workspaces: "https://{workspaceId}.{region}.xata.sh"
522
825
  },
523
826
  staging: {
524
827
  main: "https://staging.xatabase.co",
525
- workspaces: "https://{workspaceId}.staging.xatabase.co"
828
+ workspaces: "https://{workspaceId}.staging.{region}.xatabase.co"
526
829
  }
527
830
  };
528
- function isValidAlias(alias) {
831
+ function isHostProviderAlias(alias) {
529
832
  return isString(alias) && Object.keys(providers).includes(alias);
530
833
  }
531
- function isValidBuilder(builder) {
834
+ function isHostProviderBuilder(builder) {
532
835
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
533
836
  }
837
+ function parseProviderString(provider = "production") {
838
+ if (isHostProviderAlias(provider)) {
839
+ return provider;
840
+ }
841
+ const [main, workspaces] = provider.split(",");
842
+ if (!main || !workspaces)
843
+ return null;
844
+ return { main, workspaces };
845
+ }
846
+ function parseWorkspacesUrlParts(url) {
847
+ if (!isString(url))
848
+ return null;
849
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
850
+ const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
851
+ const regexDev = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xata\.tech.*/;
852
+ const match = url.match(regex) || url.match(regexStaging) || url.match(regexDev);
853
+ if (!match)
854
+ return null;
855
+ return { workspace: match[1], region: match[2] };
856
+ }
534
857
 
535
858
  var __accessCheck$7 = (obj, member, msg) => {
536
859
  if (!member.has(obj))
@@ -556,7 +879,9 @@ class XataApiClient {
556
879
  __privateAdd$7(this, _extraProps, void 0);
557
880
  __privateAdd$7(this, _namespaces, {});
558
881
  const provider = options.host ?? "production";
559
- const apiKey = options?.apiKey ?? getAPIKey();
882
+ const apiKey = options.apiKey ?? getAPIKey();
883
+ const trace = options.trace ?? defaultTrace;
884
+ const clientID = generateUUID();
560
885
  if (!apiKey) {
561
886
  throw new Error("Could not resolve a valid apiKey");
562
887
  }
@@ -564,7 +889,10 @@ class XataApiClient {
564
889
  apiUrl: getHostUrl(provider, "main"),
565
890
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
566
891
  fetchImpl: getFetchImplementation(options.fetch),
567
- apiKey
892
+ apiKey,
893
+ trace,
894
+ clientName: options.clientName,
895
+ clientID
568
896
  });
569
897
  }
570
898
  get user() {
@@ -572,21 +900,41 @@ class XataApiClient {
572
900
  __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
573
901
  return __privateGet$7(this, _namespaces).user;
574
902
  }
903
+ get authentication() {
904
+ if (!__privateGet$7(this, _namespaces).authentication)
905
+ __privateGet$7(this, _namespaces).authentication = new AuthenticationApi(__privateGet$7(this, _extraProps));
906
+ return __privateGet$7(this, _namespaces).authentication;
907
+ }
575
908
  get workspaces() {
576
909
  if (!__privateGet$7(this, _namespaces).workspaces)
577
910
  __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
578
911
  return __privateGet$7(this, _namespaces).workspaces;
579
912
  }
580
- get databases() {
581
- if (!__privateGet$7(this, _namespaces).databases)
582
- __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
583
- return __privateGet$7(this, _namespaces).databases;
913
+ get invites() {
914
+ if (!__privateGet$7(this, _namespaces).invites)
915
+ __privateGet$7(this, _namespaces).invites = new InvitesApi(__privateGet$7(this, _extraProps));
916
+ return __privateGet$7(this, _namespaces).invites;
917
+ }
918
+ get database() {
919
+ if (!__privateGet$7(this, _namespaces).database)
920
+ __privateGet$7(this, _namespaces).database = new DatabaseApi(__privateGet$7(this, _extraProps));
921
+ return __privateGet$7(this, _namespaces).database;
584
922
  }
585
923
  get branches() {
586
924
  if (!__privateGet$7(this, _namespaces).branches)
587
925
  __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
588
926
  return __privateGet$7(this, _namespaces).branches;
589
927
  }
928
+ get migrations() {
929
+ if (!__privateGet$7(this, _namespaces).migrations)
930
+ __privateGet$7(this, _namespaces).migrations = new MigrationsApi(__privateGet$7(this, _extraProps));
931
+ return __privateGet$7(this, _namespaces).migrations;
932
+ }
933
+ get migrationRequests() {
934
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
935
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
936
+ return __privateGet$7(this, _namespaces).migrationRequests;
937
+ }
590
938
  get tables() {
591
939
  if (!__privateGet$7(this, _namespaces).tables)
592
940
  __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
@@ -597,6 +945,11 @@ class XataApiClient {
597
945
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
598
946
  return __privateGet$7(this, _namespaces).records;
599
947
  }
948
+ get searchAndFilter() {
949
+ if (!__privateGet$7(this, _namespaces).searchAndFilter)
950
+ __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
951
+ return __privateGet$7(this, _namespaces).searchAndFilter;
952
+ }
600
953
  }
601
954
  _extraProps = new WeakMap();
602
955
  _namespaces = new WeakMap();
@@ -607,24 +960,29 @@ class UserApi {
607
960
  getUser() {
608
961
  return operationsByTag.users.getUser({ ...this.extraProps });
609
962
  }
610
- updateUser(user) {
963
+ updateUser({ user }) {
611
964
  return operationsByTag.users.updateUser({ body: user, ...this.extraProps });
612
965
  }
613
966
  deleteUser() {
614
967
  return operationsByTag.users.deleteUser({ ...this.extraProps });
615
968
  }
969
+ }
970
+ class AuthenticationApi {
971
+ constructor(extraProps) {
972
+ this.extraProps = extraProps;
973
+ }
616
974
  getUserAPIKeys() {
617
- return operationsByTag.users.getUserAPIKeys({ ...this.extraProps });
975
+ return operationsByTag.authentication.getUserAPIKeys({ ...this.extraProps });
618
976
  }
619
- createUserAPIKey(keyName) {
620
- return operationsByTag.users.createUserAPIKey({
621
- pathParams: { keyName },
977
+ createUserAPIKey({ name }) {
978
+ return operationsByTag.authentication.createUserAPIKey({
979
+ pathParams: { keyName: name },
622
980
  ...this.extraProps
623
981
  });
624
982
  }
625
- deleteUserAPIKey(keyName) {
626
- return operationsByTag.users.deleteUserAPIKey({
627
- pathParams: { keyName },
983
+ deleteUserAPIKey({ name }) {
984
+ return operationsByTag.authentication.deleteUserAPIKey({
985
+ pathParams: { keyName: name },
628
986
  ...this.extraProps
629
987
  });
630
988
  }
@@ -633,342 +991,926 @@ class WorkspaceApi {
633
991
  constructor(extraProps) {
634
992
  this.extraProps = extraProps;
635
993
  }
636
- createWorkspace(workspaceMeta) {
994
+ getWorkspacesList() {
995
+ return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
996
+ }
997
+ createWorkspace({ data }) {
637
998
  return operationsByTag.workspaces.createWorkspace({
638
- body: workspaceMeta,
999
+ body: data,
639
1000
  ...this.extraProps
640
1001
  });
641
1002
  }
642
- getWorkspacesList() {
643
- return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
644
- }
645
- getWorkspace(workspaceId) {
1003
+ getWorkspace({ workspace }) {
646
1004
  return operationsByTag.workspaces.getWorkspace({
647
- pathParams: { workspaceId },
1005
+ pathParams: { workspaceId: workspace },
648
1006
  ...this.extraProps
649
1007
  });
650
1008
  }
651
- updateWorkspace(workspaceId, workspaceMeta) {
1009
+ updateWorkspace({
1010
+ workspace,
1011
+ update
1012
+ }) {
652
1013
  return operationsByTag.workspaces.updateWorkspace({
653
- pathParams: { workspaceId },
654
- body: workspaceMeta,
1014
+ pathParams: { workspaceId: workspace },
1015
+ body: update,
655
1016
  ...this.extraProps
656
1017
  });
657
1018
  }
658
- deleteWorkspace(workspaceId) {
1019
+ deleteWorkspace({ workspace }) {
659
1020
  return operationsByTag.workspaces.deleteWorkspace({
660
- pathParams: { workspaceId },
1021
+ pathParams: { workspaceId: workspace },
661
1022
  ...this.extraProps
662
1023
  });
663
1024
  }
664
- getWorkspaceMembersList(workspaceId) {
1025
+ getWorkspaceMembersList({ workspace }) {
665
1026
  return operationsByTag.workspaces.getWorkspaceMembersList({
666
- pathParams: { workspaceId },
1027
+ pathParams: { workspaceId: workspace },
667
1028
  ...this.extraProps
668
1029
  });
669
1030
  }
670
- updateWorkspaceMemberRole(workspaceId, userId, role) {
1031
+ updateWorkspaceMemberRole({
1032
+ workspace,
1033
+ user,
1034
+ role
1035
+ }) {
671
1036
  return operationsByTag.workspaces.updateWorkspaceMemberRole({
672
- pathParams: { workspaceId, userId },
1037
+ pathParams: { workspaceId: workspace, userId: user },
673
1038
  body: { role },
674
1039
  ...this.extraProps
675
1040
  });
676
1041
  }
677
- removeWorkspaceMember(workspaceId, userId) {
1042
+ removeWorkspaceMember({
1043
+ workspace,
1044
+ user
1045
+ }) {
678
1046
  return operationsByTag.workspaces.removeWorkspaceMember({
679
- pathParams: { workspaceId, userId },
1047
+ pathParams: { workspaceId: workspace, userId: user },
680
1048
  ...this.extraProps
681
1049
  });
682
1050
  }
683
- inviteWorkspaceMember(workspaceId, email, role) {
684
- return operationsByTag.workspaces.inviteWorkspaceMember({
685
- pathParams: { workspaceId },
1051
+ }
1052
+ class InvitesApi {
1053
+ constructor(extraProps) {
1054
+ this.extraProps = extraProps;
1055
+ }
1056
+ inviteWorkspaceMember({
1057
+ workspace,
1058
+ email,
1059
+ role
1060
+ }) {
1061
+ return operationsByTag.invites.inviteWorkspaceMember({
1062
+ pathParams: { workspaceId: workspace },
686
1063
  body: { email, role },
687
1064
  ...this.extraProps
688
1065
  });
689
1066
  }
690
- cancelWorkspaceMemberInvite(workspaceId, inviteId) {
691
- return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
692
- pathParams: { workspaceId, inviteId },
1067
+ updateWorkspaceMemberInvite({
1068
+ workspace,
1069
+ invite,
1070
+ role
1071
+ }) {
1072
+ return operationsByTag.invites.updateWorkspaceMemberInvite({
1073
+ pathParams: { workspaceId: workspace, inviteId: invite },
1074
+ body: { role },
693
1075
  ...this.extraProps
694
1076
  });
695
1077
  }
696
- resendWorkspaceMemberInvite(workspaceId, inviteId) {
697
- return operationsByTag.workspaces.resendWorkspaceMemberInvite({
698
- pathParams: { workspaceId, inviteId },
1078
+ cancelWorkspaceMemberInvite({
1079
+ workspace,
1080
+ invite
1081
+ }) {
1082
+ return operationsByTag.invites.cancelWorkspaceMemberInvite({
1083
+ pathParams: { workspaceId: workspace, inviteId: invite },
1084
+ ...this.extraProps
1085
+ });
1086
+ }
1087
+ acceptWorkspaceMemberInvite({
1088
+ workspace,
1089
+ key
1090
+ }) {
1091
+ return operationsByTag.invites.acceptWorkspaceMemberInvite({
1092
+ pathParams: { workspaceId: workspace, inviteKey: key },
699
1093
  ...this.extraProps
700
1094
  });
701
1095
  }
702
- acceptWorkspaceMemberInvite(workspaceId, inviteKey) {
703
- return operationsByTag.workspaces.acceptWorkspaceMemberInvite({
704
- pathParams: { workspaceId, inviteKey },
1096
+ resendWorkspaceMemberInvite({
1097
+ workspace,
1098
+ invite
1099
+ }) {
1100
+ return operationsByTag.invites.resendWorkspaceMemberInvite({
1101
+ pathParams: { workspaceId: workspace, inviteId: invite },
705
1102
  ...this.extraProps
706
1103
  });
707
1104
  }
708
1105
  }
709
- class DatabaseApi {
1106
+ class BranchApi {
710
1107
  constructor(extraProps) {
711
1108
  this.extraProps = extraProps;
712
1109
  }
713
- getDatabaseList(workspace) {
714
- return operationsByTag.database.getDatabaseList({
715
- pathParams: { workspace },
1110
+ getBranchList({
1111
+ workspace,
1112
+ region,
1113
+ database
1114
+ }) {
1115
+ return operationsByTag.branch.getBranchList({
1116
+ pathParams: { workspace, region, dbName: database },
716
1117
  ...this.extraProps
717
1118
  });
718
1119
  }
719
- createDatabase(workspace, dbName, options = {}) {
720
- return operationsByTag.database.createDatabase({
721
- pathParams: { workspace, dbName },
722
- body: options,
1120
+ getBranchDetails({
1121
+ workspace,
1122
+ region,
1123
+ database,
1124
+ branch
1125
+ }) {
1126
+ return operationsByTag.branch.getBranchDetails({
1127
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
723
1128
  ...this.extraProps
724
1129
  });
725
1130
  }
726
- deleteDatabase(workspace, dbName) {
727
- return operationsByTag.database.deleteDatabase({
728
- pathParams: { workspace, dbName },
1131
+ createBranch({
1132
+ workspace,
1133
+ region,
1134
+ database,
1135
+ branch,
1136
+ from,
1137
+ metadata
1138
+ }) {
1139
+ return operationsByTag.branch.createBranch({
1140
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1141
+ body: { from, metadata },
729
1142
  ...this.extraProps
730
1143
  });
731
1144
  }
732
- getGitBranchesMapping(workspace, dbName) {
733
- return operationsByTag.database.getGitBranchesMapping({
734
- pathParams: { workspace, dbName },
1145
+ deleteBranch({
1146
+ workspace,
1147
+ region,
1148
+ database,
1149
+ branch
1150
+ }) {
1151
+ return operationsByTag.branch.deleteBranch({
1152
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
735
1153
  ...this.extraProps
736
1154
  });
737
1155
  }
738
- addGitBranchesEntry(workspace, dbName, body) {
739
- return operationsByTag.database.addGitBranchesEntry({
740
- pathParams: { workspace, dbName },
741
- body,
1156
+ updateBranchMetadata({
1157
+ workspace,
1158
+ region,
1159
+ database,
1160
+ branch,
1161
+ metadata
1162
+ }) {
1163
+ return operationsByTag.branch.updateBranchMetadata({
1164
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1165
+ body: metadata,
1166
+ ...this.extraProps
1167
+ });
1168
+ }
1169
+ getBranchMetadata({
1170
+ workspace,
1171
+ region,
1172
+ database,
1173
+ branch
1174
+ }) {
1175
+ return operationsByTag.branch.getBranchMetadata({
1176
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1177
+ ...this.extraProps
1178
+ });
1179
+ }
1180
+ getBranchStats({
1181
+ workspace,
1182
+ region,
1183
+ database,
1184
+ branch
1185
+ }) {
1186
+ return operationsByTag.branch.getBranchStats({
1187
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1188
+ ...this.extraProps
1189
+ });
1190
+ }
1191
+ getGitBranchesMapping({
1192
+ workspace,
1193
+ region,
1194
+ database
1195
+ }) {
1196
+ return operationsByTag.branch.getGitBranchesMapping({
1197
+ pathParams: { workspace, region, dbName: database },
1198
+ ...this.extraProps
1199
+ });
1200
+ }
1201
+ addGitBranchesEntry({
1202
+ workspace,
1203
+ region,
1204
+ database,
1205
+ gitBranch,
1206
+ xataBranch
1207
+ }) {
1208
+ return operationsByTag.branch.addGitBranchesEntry({
1209
+ pathParams: { workspace, region, dbName: database },
1210
+ body: { gitBranch, xataBranch },
742
1211
  ...this.extraProps
743
1212
  });
744
1213
  }
745
- removeGitBranchesEntry(workspace, dbName, gitBranch) {
746
- return operationsByTag.database.removeGitBranchesEntry({
747
- pathParams: { workspace, dbName },
1214
+ removeGitBranchesEntry({
1215
+ workspace,
1216
+ region,
1217
+ database,
1218
+ gitBranch
1219
+ }) {
1220
+ return operationsByTag.branch.removeGitBranchesEntry({
1221
+ pathParams: { workspace, region, dbName: database },
748
1222
  queryParams: { gitBranch },
749
1223
  ...this.extraProps
750
1224
  });
751
1225
  }
752
- resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
753
- return operationsByTag.database.resolveBranch({
754
- pathParams: { workspace, dbName },
1226
+ resolveBranch({
1227
+ workspace,
1228
+ region,
1229
+ database,
1230
+ gitBranch,
1231
+ fallbackBranch
1232
+ }) {
1233
+ return operationsByTag.branch.resolveBranch({
1234
+ pathParams: { workspace, region, dbName: database },
755
1235
  queryParams: { gitBranch, fallbackBranch },
756
1236
  ...this.extraProps
757
1237
  });
758
1238
  }
759
1239
  }
760
- class BranchApi {
1240
+ class TableApi {
761
1241
  constructor(extraProps) {
762
1242
  this.extraProps = extraProps;
763
1243
  }
764
- getBranchList(workspace, dbName) {
765
- return operationsByTag.branch.getBranchList({
766
- pathParams: { workspace, dbName },
1244
+ createTable({
1245
+ workspace,
1246
+ region,
1247
+ database,
1248
+ branch,
1249
+ table
1250
+ }) {
1251
+ return operationsByTag.table.createTable({
1252
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
767
1253
  ...this.extraProps
768
1254
  });
769
1255
  }
770
- getBranchDetails(workspace, database, branch) {
771
- return operationsByTag.branch.getBranchDetails({
772
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1256
+ deleteTable({
1257
+ workspace,
1258
+ region,
1259
+ database,
1260
+ branch,
1261
+ table
1262
+ }) {
1263
+ return operationsByTag.table.deleteTable({
1264
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
773
1265
  ...this.extraProps
774
1266
  });
775
1267
  }
776
- createBranch(workspace, database, branch, from, options = {}) {
777
- return operationsByTag.branch.createBranch({
778
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
779
- queryParams: isString(from) ? { from } : void 0,
780
- body: options,
1268
+ updateTable({
1269
+ workspace,
1270
+ region,
1271
+ database,
1272
+ branch,
1273
+ table,
1274
+ update
1275
+ }) {
1276
+ return operationsByTag.table.updateTable({
1277
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1278
+ body: update,
781
1279
  ...this.extraProps
782
1280
  });
783
1281
  }
784
- deleteBranch(workspace, database, branch) {
785
- return operationsByTag.branch.deleteBranch({
786
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1282
+ getTableSchema({
1283
+ workspace,
1284
+ region,
1285
+ database,
1286
+ branch,
1287
+ table
1288
+ }) {
1289
+ return operationsByTag.table.getTableSchema({
1290
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
787
1291
  ...this.extraProps
788
1292
  });
789
1293
  }
790
- updateBranchMetadata(workspace, database, branch, metadata = {}) {
791
- return operationsByTag.branch.updateBranchMetadata({
792
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
793
- body: metadata,
1294
+ setTableSchema({
1295
+ workspace,
1296
+ region,
1297
+ database,
1298
+ branch,
1299
+ table,
1300
+ schema
1301
+ }) {
1302
+ return operationsByTag.table.setTableSchema({
1303
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1304
+ body: schema,
794
1305
  ...this.extraProps
795
1306
  });
796
1307
  }
797
- getBranchMetadata(workspace, database, branch) {
798
- return operationsByTag.branch.getBranchMetadata({
799
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1308
+ getTableColumns({
1309
+ workspace,
1310
+ region,
1311
+ database,
1312
+ branch,
1313
+ table
1314
+ }) {
1315
+ return operationsByTag.table.getTableColumns({
1316
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
800
1317
  ...this.extraProps
801
1318
  });
802
1319
  }
803
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
804
- return operationsByTag.branch.getBranchMigrationHistory({
805
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
806
- body: options,
1320
+ addTableColumn({
1321
+ workspace,
1322
+ region,
1323
+ database,
1324
+ branch,
1325
+ table,
1326
+ column
1327
+ }) {
1328
+ return operationsByTag.table.addTableColumn({
1329
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1330
+ body: column,
807
1331
  ...this.extraProps
808
1332
  });
809
1333
  }
810
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
811
- return operationsByTag.branch.executeBranchMigrationPlan({
812
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
813
- body: migrationPlan,
1334
+ getColumn({
1335
+ workspace,
1336
+ region,
1337
+ database,
1338
+ branch,
1339
+ table,
1340
+ column
1341
+ }) {
1342
+ return operationsByTag.table.getColumn({
1343
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
814
1344
  ...this.extraProps
815
1345
  });
816
1346
  }
817
- getBranchMigrationPlan(workspace, database, branch, schema) {
818
- return operationsByTag.branch.getBranchMigrationPlan({
819
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
820
- body: schema,
1347
+ updateColumn({
1348
+ workspace,
1349
+ region,
1350
+ database,
1351
+ branch,
1352
+ table,
1353
+ column,
1354
+ update
1355
+ }) {
1356
+ return operationsByTag.table.updateColumn({
1357
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
1358
+ body: update,
1359
+ ...this.extraProps
1360
+ });
1361
+ }
1362
+ deleteColumn({
1363
+ workspace,
1364
+ region,
1365
+ database,
1366
+ branch,
1367
+ table,
1368
+ column
1369
+ }) {
1370
+ return operationsByTag.table.deleteColumn({
1371
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
1372
+ ...this.extraProps
1373
+ });
1374
+ }
1375
+ }
1376
+ class RecordsApi {
1377
+ constructor(extraProps) {
1378
+ this.extraProps = extraProps;
1379
+ }
1380
+ insertRecord({
1381
+ workspace,
1382
+ region,
1383
+ database,
1384
+ branch,
1385
+ table,
1386
+ record,
1387
+ columns
1388
+ }) {
1389
+ return operationsByTag.records.insertRecord({
1390
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1391
+ queryParams: { columns },
1392
+ body: record,
1393
+ ...this.extraProps
1394
+ });
1395
+ }
1396
+ getRecord({
1397
+ workspace,
1398
+ region,
1399
+ database,
1400
+ branch,
1401
+ table,
1402
+ id,
1403
+ columns
1404
+ }) {
1405
+ return operationsByTag.records.getRecord({
1406
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1407
+ queryParams: { columns },
1408
+ ...this.extraProps
1409
+ });
1410
+ }
1411
+ insertRecordWithID({
1412
+ workspace,
1413
+ region,
1414
+ database,
1415
+ branch,
1416
+ table,
1417
+ id,
1418
+ record,
1419
+ columns,
1420
+ createOnly,
1421
+ ifVersion
1422
+ }) {
1423
+ return operationsByTag.records.insertRecordWithID({
1424
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1425
+ queryParams: { columns, createOnly, ifVersion },
1426
+ body: record,
1427
+ ...this.extraProps
1428
+ });
1429
+ }
1430
+ updateRecordWithID({
1431
+ workspace,
1432
+ region,
1433
+ database,
1434
+ branch,
1435
+ table,
1436
+ id,
1437
+ record,
1438
+ columns,
1439
+ ifVersion
1440
+ }) {
1441
+ return operationsByTag.records.updateRecordWithID({
1442
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1443
+ queryParams: { columns, ifVersion },
1444
+ body: record,
1445
+ ...this.extraProps
1446
+ });
1447
+ }
1448
+ upsertRecordWithID({
1449
+ workspace,
1450
+ region,
1451
+ database,
1452
+ branch,
1453
+ table,
1454
+ id,
1455
+ record,
1456
+ columns,
1457
+ ifVersion
1458
+ }) {
1459
+ return operationsByTag.records.upsertRecordWithID({
1460
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1461
+ queryParams: { columns, ifVersion },
1462
+ body: record,
1463
+ ...this.extraProps
1464
+ });
1465
+ }
1466
+ deleteRecord({
1467
+ workspace,
1468
+ region,
1469
+ database,
1470
+ branch,
1471
+ table,
1472
+ id,
1473
+ columns
1474
+ }) {
1475
+ return operationsByTag.records.deleteRecord({
1476
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1477
+ queryParams: { columns },
1478
+ ...this.extraProps
1479
+ });
1480
+ }
1481
+ bulkInsertTableRecords({
1482
+ workspace,
1483
+ region,
1484
+ database,
1485
+ branch,
1486
+ table,
1487
+ records,
1488
+ columns
1489
+ }) {
1490
+ return operationsByTag.records.bulkInsertTableRecords({
1491
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1492
+ queryParams: { columns },
1493
+ body: { records },
1494
+ ...this.extraProps
1495
+ });
1496
+ }
1497
+ branchTransaction({
1498
+ workspace,
1499
+ region,
1500
+ database,
1501
+ branch,
1502
+ operations
1503
+ }) {
1504
+ return operationsByTag.records.branchTransaction({
1505
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1506
+ body: { operations },
1507
+ ...this.extraProps
1508
+ });
1509
+ }
1510
+ }
1511
+ class SearchAndFilterApi {
1512
+ constructor(extraProps) {
1513
+ this.extraProps = extraProps;
1514
+ }
1515
+ queryTable({
1516
+ workspace,
1517
+ region,
1518
+ database,
1519
+ branch,
1520
+ table,
1521
+ filter,
1522
+ sort,
1523
+ page,
1524
+ columns,
1525
+ consistency
1526
+ }) {
1527
+ return operationsByTag.searchAndFilter.queryTable({
1528
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1529
+ body: { filter, sort, page, columns, consistency },
1530
+ ...this.extraProps
1531
+ });
1532
+ }
1533
+ searchTable({
1534
+ workspace,
1535
+ region,
1536
+ database,
1537
+ branch,
1538
+ table,
1539
+ query,
1540
+ fuzziness,
1541
+ target,
1542
+ prefix,
1543
+ filter,
1544
+ highlight,
1545
+ boosters
1546
+ }) {
1547
+ return operationsByTag.searchAndFilter.searchTable({
1548
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1549
+ body: { query, fuzziness, target, prefix, filter, highlight, boosters },
1550
+ ...this.extraProps
1551
+ });
1552
+ }
1553
+ searchBranch({
1554
+ workspace,
1555
+ region,
1556
+ database,
1557
+ branch,
1558
+ tables,
1559
+ query,
1560
+ fuzziness,
1561
+ prefix,
1562
+ highlight
1563
+ }) {
1564
+ return operationsByTag.searchAndFilter.searchBranch({
1565
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1566
+ body: { tables, query, fuzziness, prefix, highlight },
1567
+ ...this.extraProps
1568
+ });
1569
+ }
1570
+ summarizeTable({
1571
+ workspace,
1572
+ region,
1573
+ database,
1574
+ branch,
1575
+ table,
1576
+ filter,
1577
+ columns,
1578
+ summaries,
1579
+ sort,
1580
+ summariesFilter,
1581
+ page,
1582
+ consistency
1583
+ }) {
1584
+ return operationsByTag.searchAndFilter.summarizeTable({
1585
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1586
+ body: { filter, columns, summaries, sort, summariesFilter, page, consistency },
1587
+ ...this.extraProps
1588
+ });
1589
+ }
1590
+ aggregateTable({
1591
+ workspace,
1592
+ region,
1593
+ database,
1594
+ branch,
1595
+ table,
1596
+ filter,
1597
+ aggs
1598
+ }) {
1599
+ return operationsByTag.searchAndFilter.aggregateTable({
1600
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1601
+ body: { filter, aggs },
1602
+ ...this.extraProps
1603
+ });
1604
+ }
1605
+ }
1606
+ class MigrationRequestsApi {
1607
+ constructor(extraProps) {
1608
+ this.extraProps = extraProps;
1609
+ }
1610
+ queryMigrationRequests({
1611
+ workspace,
1612
+ region,
1613
+ database,
1614
+ filter,
1615
+ sort,
1616
+ page,
1617
+ columns
1618
+ }) {
1619
+ return operationsByTag.migrationRequests.queryMigrationRequests({
1620
+ pathParams: { workspace, region, dbName: database },
1621
+ body: { filter, sort, page, columns },
1622
+ ...this.extraProps
1623
+ });
1624
+ }
1625
+ createMigrationRequest({
1626
+ workspace,
1627
+ region,
1628
+ database,
1629
+ migration
1630
+ }) {
1631
+ return operationsByTag.migrationRequests.createMigrationRequest({
1632
+ pathParams: { workspace, region, dbName: database },
1633
+ body: migration,
1634
+ ...this.extraProps
1635
+ });
1636
+ }
1637
+ getMigrationRequest({
1638
+ workspace,
1639
+ region,
1640
+ database,
1641
+ migrationRequest
1642
+ }) {
1643
+ return operationsByTag.migrationRequests.getMigrationRequest({
1644
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
1645
+ ...this.extraProps
1646
+ });
1647
+ }
1648
+ updateMigrationRequest({
1649
+ workspace,
1650
+ region,
1651
+ database,
1652
+ migrationRequest,
1653
+ update
1654
+ }) {
1655
+ return operationsByTag.migrationRequests.updateMigrationRequest({
1656
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
1657
+ body: update,
1658
+ ...this.extraProps
1659
+ });
1660
+ }
1661
+ listMigrationRequestsCommits({
1662
+ workspace,
1663
+ region,
1664
+ database,
1665
+ migrationRequest,
1666
+ page
1667
+ }) {
1668
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1669
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
1670
+ body: { page },
1671
+ ...this.extraProps
1672
+ });
1673
+ }
1674
+ compareMigrationRequest({
1675
+ workspace,
1676
+ region,
1677
+ database,
1678
+ migrationRequest
1679
+ }) {
1680
+ return operationsByTag.migrationRequests.compareMigrationRequest({
1681
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
1682
+ ...this.extraProps
1683
+ });
1684
+ }
1685
+ getMigrationRequestIsMerged({
1686
+ workspace,
1687
+ region,
1688
+ database,
1689
+ migrationRequest
1690
+ }) {
1691
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1692
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
821
1693
  ...this.extraProps
822
1694
  });
823
1695
  }
824
- getBranchStats(workspace, database, branch) {
825
- return operationsByTag.branch.getBranchStats({
826
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1696
+ mergeMigrationRequest({
1697
+ workspace,
1698
+ region,
1699
+ database,
1700
+ migrationRequest
1701
+ }) {
1702
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
1703
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
827
1704
  ...this.extraProps
828
1705
  });
829
1706
  }
830
1707
  }
831
- class TableApi {
1708
+ class MigrationsApi {
832
1709
  constructor(extraProps) {
833
1710
  this.extraProps = extraProps;
834
1711
  }
835
- createTable(workspace, database, branch, tableName) {
836
- return operationsByTag.table.createTable({
837
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
838
- ...this.extraProps
839
- });
840
- }
841
- deleteTable(workspace, database, branch, tableName) {
842
- return operationsByTag.table.deleteTable({
843
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1712
+ getBranchMigrationHistory({
1713
+ workspace,
1714
+ region,
1715
+ database,
1716
+ branch,
1717
+ limit,
1718
+ startFrom
1719
+ }) {
1720
+ return operationsByTag.migrations.getBranchMigrationHistory({
1721
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1722
+ body: { limit, startFrom },
844
1723
  ...this.extraProps
845
1724
  });
846
1725
  }
847
- updateTable(workspace, database, branch, tableName, options) {
848
- return operationsByTag.table.updateTable({
849
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
850
- body: options,
1726
+ getBranchMigrationPlan({
1727
+ workspace,
1728
+ region,
1729
+ database,
1730
+ branch,
1731
+ schema
1732
+ }) {
1733
+ return operationsByTag.migrations.getBranchMigrationPlan({
1734
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1735
+ body: schema,
851
1736
  ...this.extraProps
852
1737
  });
853
1738
  }
854
- getTableSchema(workspace, database, branch, tableName) {
855
- return operationsByTag.table.getTableSchema({
856
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1739
+ executeBranchMigrationPlan({
1740
+ workspace,
1741
+ region,
1742
+ database,
1743
+ branch,
1744
+ plan
1745
+ }) {
1746
+ return operationsByTag.migrations.executeBranchMigrationPlan({
1747
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1748
+ body: plan,
857
1749
  ...this.extraProps
858
1750
  });
859
1751
  }
860
- setTableSchema(workspace, database, branch, tableName, options) {
861
- return operationsByTag.table.setTableSchema({
862
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
863
- body: options,
1752
+ getBranchSchemaHistory({
1753
+ workspace,
1754
+ region,
1755
+ database,
1756
+ branch,
1757
+ page
1758
+ }) {
1759
+ return operationsByTag.migrations.getBranchSchemaHistory({
1760
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1761
+ body: { page },
864
1762
  ...this.extraProps
865
1763
  });
866
1764
  }
867
- getTableColumns(workspace, database, branch, tableName) {
868
- return operationsByTag.table.getTableColumns({
869
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1765
+ compareBranchWithUserSchema({
1766
+ workspace,
1767
+ region,
1768
+ database,
1769
+ branch,
1770
+ schema
1771
+ }) {
1772
+ return operationsByTag.migrations.compareBranchWithUserSchema({
1773
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1774
+ body: { schema },
870
1775
  ...this.extraProps
871
1776
  });
872
1777
  }
873
- addTableColumn(workspace, database, branch, tableName, column) {
874
- return operationsByTag.table.addTableColumn({
875
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
876
- body: column,
1778
+ compareBranchSchemas({
1779
+ workspace,
1780
+ region,
1781
+ database,
1782
+ branch,
1783
+ compare,
1784
+ schema
1785
+ }) {
1786
+ return operationsByTag.migrations.compareBranchSchemas({
1787
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1788
+ body: { schema },
877
1789
  ...this.extraProps
878
1790
  });
879
1791
  }
880
- getColumn(workspace, database, branch, tableName, columnName) {
881
- return operationsByTag.table.getColumn({
882
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
1792
+ updateBranchSchema({
1793
+ workspace,
1794
+ region,
1795
+ database,
1796
+ branch,
1797
+ migration
1798
+ }) {
1799
+ return operationsByTag.migrations.updateBranchSchema({
1800
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1801
+ body: migration,
883
1802
  ...this.extraProps
884
1803
  });
885
1804
  }
886
- deleteColumn(workspace, database, branch, tableName, columnName) {
887
- return operationsByTag.table.deleteColumn({
888
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
1805
+ previewBranchSchemaEdit({
1806
+ workspace,
1807
+ region,
1808
+ database,
1809
+ branch,
1810
+ data
1811
+ }) {
1812
+ return operationsByTag.migrations.previewBranchSchemaEdit({
1813
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1814
+ body: data,
889
1815
  ...this.extraProps
890
1816
  });
891
1817
  }
892
- updateColumn(workspace, database, branch, tableName, columnName, options) {
893
- return operationsByTag.table.updateColumn({
894
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
895
- body: options,
1818
+ applyBranchSchemaEdit({
1819
+ workspace,
1820
+ region,
1821
+ database,
1822
+ branch,
1823
+ edits
1824
+ }) {
1825
+ return operationsByTag.migrations.applyBranchSchemaEdit({
1826
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1827
+ body: { edits },
896
1828
  ...this.extraProps
897
1829
  });
898
1830
  }
899
1831
  }
900
- class RecordsApi {
1832
+ class DatabaseApi {
901
1833
  constructor(extraProps) {
902
1834
  this.extraProps = extraProps;
903
1835
  }
904
- insertRecord(workspace, database, branch, tableName, record) {
905
- return operationsByTag.records.insertRecord({
906
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
907
- body: record,
908
- ...this.extraProps
909
- });
910
- }
911
- insertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
912
- return operationsByTag.records.insertRecordWithID({
913
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
914
- queryParams: options,
915
- body: record,
1836
+ getDatabaseList({ workspace }) {
1837
+ return operationsByTag.databases.getDatabaseList({
1838
+ pathParams: { workspaceId: workspace },
916
1839
  ...this.extraProps
917
1840
  });
918
1841
  }
919
- updateRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
920
- return operationsByTag.records.updateRecordWithID({
921
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
922
- queryParams: options,
923
- body: record,
1842
+ createDatabase({
1843
+ workspace,
1844
+ database,
1845
+ data
1846
+ }) {
1847
+ return operationsByTag.databases.createDatabase({
1848
+ pathParams: { workspaceId: workspace, dbName: database },
1849
+ body: data,
924
1850
  ...this.extraProps
925
1851
  });
926
1852
  }
927
- upsertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
928
- return operationsByTag.records.upsertRecordWithID({
929
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
930
- queryParams: options,
931
- body: record,
1853
+ deleteDatabase({
1854
+ workspace,
1855
+ database
1856
+ }) {
1857
+ return operationsByTag.databases.deleteDatabase({
1858
+ pathParams: { workspaceId: workspace, dbName: database },
932
1859
  ...this.extraProps
933
1860
  });
934
1861
  }
935
- deleteRecord(workspace, database, branch, tableName, recordId) {
936
- return operationsByTag.records.deleteRecord({
937
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1862
+ getDatabaseMetadata({
1863
+ workspace,
1864
+ database
1865
+ }) {
1866
+ return operationsByTag.databases.getDatabaseMetadata({
1867
+ pathParams: { workspaceId: workspace, dbName: database },
938
1868
  ...this.extraProps
939
1869
  });
940
1870
  }
941
- getRecord(workspace, database, branch, tableName, recordId, options = {}) {
942
- return operationsByTag.records.getRecord({
943
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1871
+ updateDatabaseMetadata({
1872
+ workspace,
1873
+ database,
1874
+ metadata
1875
+ }) {
1876
+ return operationsByTag.databases.updateDatabaseMetadata({
1877
+ pathParams: { workspaceId: workspace, dbName: database },
1878
+ body: metadata,
944
1879
  ...this.extraProps
945
1880
  });
946
1881
  }
947
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
948
- return operationsByTag.records.bulkInsertTableRecords({
949
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
950
- body: { records },
1882
+ getDatabaseGithubSettings({
1883
+ workspace,
1884
+ database
1885
+ }) {
1886
+ return operationsByTag.databases.getDatabaseGithubSettings({
1887
+ pathParams: { workspaceId: workspace, dbName: database },
951
1888
  ...this.extraProps
952
1889
  });
953
1890
  }
954
- queryTable(workspace, database, branch, tableName, query) {
955
- return operationsByTag.records.queryTable({
956
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
957
- body: query,
1891
+ updateDatabaseGithubSettings({
1892
+ workspace,
1893
+ database,
1894
+ settings
1895
+ }) {
1896
+ return operationsByTag.databases.updateDatabaseGithubSettings({
1897
+ pathParams: { workspaceId: workspace, dbName: database },
1898
+ body: settings,
958
1899
  ...this.extraProps
959
1900
  });
960
1901
  }
961
- searchTable(workspace, database, branch, tableName, query) {
962
- return operationsByTag.records.searchTable({
963
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
964
- body: query,
1902
+ deleteDatabaseGithubSettings({
1903
+ workspace,
1904
+ database
1905
+ }) {
1906
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
1907
+ pathParams: { workspaceId: workspace, dbName: database },
965
1908
  ...this.extraProps
966
1909
  });
967
1910
  }
968
- searchBranch(workspace, database, branch, query) {
969
- return operationsByTag.records.searchBranch({
970
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
971
- body: query,
1911
+ listRegions({ workspace }) {
1912
+ return operationsByTag.databases.listRegions({
1913
+ pathParams: { workspaceId: workspace },
972
1914
  ...this.extraProps
973
1915
  });
974
1916
  }
@@ -984,6 +1926,13 @@ class XataApiPlugin {
984
1926
  class XataPlugin {
985
1927
  }
986
1928
 
1929
+ function cleanFilter(filter) {
1930
+ if (!filter)
1931
+ return void 0;
1932
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1933
+ return values.length > 0 ? filter : void 0;
1934
+ }
1935
+
987
1936
  var __accessCheck$6 = (obj, member, msg) => {
988
1937
  if (!member.has(obj))
989
1938
  throw TypeError("Cannot " + msg);
@@ -1016,11 +1965,11 @@ class Page {
1016
1965
  async previousPage(size, offset) {
1017
1966
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1018
1967
  }
1019
- async firstPage(size, offset) {
1020
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
1968
+ async startPage(size, offset) {
1969
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1021
1970
  }
1022
- async lastPage(size, offset) {
1023
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
1971
+ async endPage(size, offset) {
1972
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1024
1973
  }
1025
1974
  hasNextPage() {
1026
1975
  return this.meta.page.more;
@@ -1032,13 +1981,13 @@ const PAGINATION_DEFAULT_SIZE = 20;
1032
1981
  const PAGINATION_MAX_OFFSET = 800;
1033
1982
  const PAGINATION_DEFAULT_OFFSET = 0;
1034
1983
  function isCursorPaginationOptions(options) {
1035
- return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1984
+ return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1036
1985
  }
1037
1986
  const _RecordArray = class extends Array {
1038
- constructor(page, overrideRecords) {
1039
- super(..._RecordArray.parseConstructorParams(page, overrideRecords));
1987
+ constructor(...args) {
1988
+ super(..._RecordArray.parseConstructorParams(...args));
1040
1989
  __privateAdd$6(this, _page, void 0);
1041
- __privateSet$6(this, _page, page);
1990
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1042
1991
  }
1043
1992
  static parseConstructorParams(...args) {
1044
1993
  if (args.length === 1 && typeof args[0] === "number") {
@@ -1050,6 +1999,18 @@ const _RecordArray = class extends Array {
1050
1999
  }
1051
2000
  return new Array(...args);
1052
2001
  }
2002
+ toArray() {
2003
+ return new Array(...this);
2004
+ }
2005
+ toSerializable() {
2006
+ return JSON.parse(this.toString());
2007
+ }
2008
+ toString() {
2009
+ return JSON.stringify(this.toArray());
2010
+ }
2011
+ map(callbackfn, thisArg) {
2012
+ return this.toArray().map(callbackfn, thisArg);
2013
+ }
1053
2014
  async nextPage(size, offset) {
1054
2015
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1055
2016
  return new _RecordArray(newPage);
@@ -1058,12 +2019,12 @@ const _RecordArray = class extends Array {
1058
2019
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1059
2020
  return new _RecordArray(newPage);
1060
2021
  }
1061
- async firstPage(size, offset) {
1062
- const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
2022
+ async startPage(size, offset) {
2023
+ const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1063
2024
  return new _RecordArray(newPage);
1064
2025
  }
1065
- async lastPage(size, offset) {
1066
- const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
2026
+ async endPage(size, offset) {
2027
+ const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1067
2028
  return new _RecordArray(newPage);
1068
2029
  }
1069
2030
  hasNextPage() {
@@ -1091,9 +2052,14 @@ var __privateSet$5 = (obj, member, value, setter) => {
1091
2052
  setter ? setter.call(obj, value) : member.set(obj, value);
1092
2053
  return value;
1093
2054
  };
1094
- var _table$1, _repository, _data;
2055
+ var __privateMethod$3 = (obj, member, method) => {
2056
+ __accessCheck$5(obj, member, "access private method");
2057
+ return method;
2058
+ };
2059
+ var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
1095
2060
  const _Query = class {
1096
2061
  constructor(repository, table, data, rawParent) {
2062
+ __privateAdd$5(this, _cleanFilterConstraint);
1097
2063
  __privateAdd$5(this, _table$1, void 0);
1098
2064
  __privateAdd$5(this, _repository, void 0);
1099
2065
  __privateAdd$5(this, _data, { filter: {} });
@@ -1112,9 +2078,11 @@ const _Query = class {
1112
2078
  __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1113
2079
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1114
2080
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1115
- __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
2081
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
2082
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
1116
2083
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1117
2084
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
2085
+ __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
1118
2086
  this.any = this.any.bind(this);
1119
2087
  this.all = this.all.bind(this);
1120
2088
  this.not = this.not.bind(this);
@@ -1150,21 +2118,29 @@ const _Query = class {
1150
2118
  }
1151
2119
  filter(a, b) {
1152
2120
  if (arguments.length === 1) {
1153
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
2121
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
2122
+ [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
2123
+ }));
1154
2124
  const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1155
2125
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1156
2126
  } else {
1157
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
2127
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
2128
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1158
2129
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1159
2130
  }
1160
2131
  }
1161
- sort(column, direction) {
2132
+ sort(column, direction = "asc") {
1162
2133
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1163
2134
  const sort = [...originalSort, { column, direction }];
1164
2135
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1165
2136
  }
1166
2137
  select(columns) {
1167
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
2138
+ return new _Query(
2139
+ __privateGet$5(this, _repository),
2140
+ __privateGet$5(this, _table$1),
2141
+ { columns },
2142
+ __privateGet$5(this, _data)
2143
+ );
1168
2144
  }
1169
2145
  getPaginated(options = {}) {
1170
2146
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1187,11 +2163,20 @@ const _Query = class {
1187
2163
  }
1188
2164
  }
1189
2165
  async getMany(options = {}) {
1190
- const page = await this.getPaginated(options);
2166
+ const { pagination = {}, ...rest } = options;
2167
+ const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
2168
+ const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
2169
+ let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
2170
+ const results = [...page.records];
2171
+ while (page.hasNextPage() && results.length < size) {
2172
+ page = await page.nextPage();
2173
+ results.push(...page.records);
2174
+ }
1191
2175
  if (page.hasNextPage() && options.pagination?.size === void 0) {
1192
2176
  console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1193
2177
  }
1194
- return page.records;
2178
+ const array = new RecordArray(page, results.slice(0, size));
2179
+ return array;
1195
2180
  }
1196
2181
  async getAll(options = {}) {
1197
2182
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1205,19 +2190,35 @@ const _Query = class {
1205
2190
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1206
2191
  return records[0] ?? null;
1207
2192
  }
2193
+ async getFirstOrThrow(options = {}) {
2194
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
2195
+ if (records[0] === void 0)
2196
+ throw new Error("No results found.");
2197
+ return records[0];
2198
+ }
2199
+ async summarize(params = {}) {
2200
+ const { summaries, summariesFilter, ...options } = params;
2201
+ const query = new _Query(
2202
+ __privateGet$5(this, _repository),
2203
+ __privateGet$5(this, _table$1),
2204
+ options,
2205
+ __privateGet$5(this, _data)
2206
+ );
2207
+ return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2208
+ }
1208
2209
  cache(ttl) {
1209
2210
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1210
2211
  }
1211
2212
  nextPage(size, offset) {
1212
- return this.firstPage(size, offset);
2213
+ return this.startPage(size, offset);
1213
2214
  }
1214
2215
  previousPage(size, offset) {
1215
- return this.firstPage(size, offset);
2216
+ return this.startPage(size, offset);
1216
2217
  }
1217
- firstPage(size, offset) {
2218
+ startPage(size, offset) {
1218
2219
  return this.getPaginated({ pagination: { size, offset } });
1219
2220
  }
1220
- lastPage(size, offset) {
2221
+ endPage(size, offset) {
1221
2222
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
1222
2223
  }
1223
2224
  hasNextPage() {
@@ -1228,9 +2229,20 @@ let Query = _Query;
1228
2229
  _table$1 = new WeakMap();
1229
2230
  _repository = new WeakMap();
1230
2231
  _data = new WeakMap();
2232
+ _cleanFilterConstraint = new WeakSet();
2233
+ cleanFilterConstraint_fn = function(column, value) {
2234
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
2235
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
2236
+ return { $includes: value };
2237
+ }
2238
+ if (columnType === "link" && isObject(value) && isString(value.id)) {
2239
+ return value.id;
2240
+ }
2241
+ return value;
2242
+ };
1231
2243
  function cleanParent(data, parent) {
1232
2244
  if (isCursorPaginationOptions(data.pagination)) {
1233
- return { ...parent, sorting: void 0, filter: void 0 };
2245
+ return { ...parent, sort: void 0, filter: void 0 };
1234
2246
  }
1235
2247
  return parent;
1236
2248
  }
@@ -1289,317 +2301,574 @@ var __privateMethod$2 = (obj, member, method) => {
1289
2301
  __accessCheck$4(obj, member, "access private method");
1290
2302
  return method;
1291
2303
  };
1292
- var _table, _getFetchProps, _cache, _schemaTables$2, _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, _getSchemaTables$1, getSchemaTables_fn$1;
2304
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
2305
+ const BULK_OPERATION_MAX_SIZE = 1e3;
1293
2306
  class Repository extends Query {
1294
2307
  }
1295
2308
  class RestRepository extends Query {
1296
2309
  constructor(options) {
1297
- super(null, options.table, {});
2310
+ super(
2311
+ null,
2312
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
2313
+ {}
2314
+ );
1298
2315
  __privateAdd$4(this, _insertRecordWithoutId);
1299
2316
  __privateAdd$4(this, _insertRecordWithId);
1300
- __privateAdd$4(this, _bulkInsertTableRecords);
2317
+ __privateAdd$4(this, _insertRecords);
1301
2318
  __privateAdd$4(this, _updateRecordWithID);
2319
+ __privateAdd$4(this, _updateRecords);
1302
2320
  __privateAdd$4(this, _upsertRecordWithID);
1303
2321
  __privateAdd$4(this, _deleteRecord);
1304
- __privateAdd$4(this, _invalidateCache);
1305
- __privateAdd$4(this, _setCacheRecord);
1306
- __privateAdd$4(this, _getCacheRecord);
2322
+ __privateAdd$4(this, _deleteRecords);
1307
2323
  __privateAdd$4(this, _setCacheQuery);
1308
2324
  __privateAdd$4(this, _getCacheQuery);
1309
2325
  __privateAdd$4(this, _getSchemaTables$1);
1310
2326
  __privateAdd$4(this, _table, void 0);
1311
2327
  __privateAdd$4(this, _getFetchProps, void 0);
2328
+ __privateAdd$4(this, _db, void 0);
1312
2329
  __privateAdd$4(this, _cache, void 0);
1313
2330
  __privateAdd$4(this, _schemaTables$2, void 0);
2331
+ __privateAdd$4(this, _trace, void 0);
1314
2332
  __privateSet$4(this, _table, options.table);
1315
- __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1316
- this.db = options.db;
2333
+ __privateSet$4(this, _db, options.db);
1317
2334
  __privateSet$4(this, _cache, options.pluginOptions.cache);
1318
2335
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2336
+ __privateSet$4(this, _getFetchProps, async () => {
2337
+ const props = await options.pluginOptions.getFetchProps();
2338
+ return { ...props, sessionID: generateUUID() };
2339
+ });
2340
+ const trace = options.pluginOptions.trace ?? defaultTrace;
2341
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2342
+ return trace(name, fn, {
2343
+ ...options2,
2344
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
2345
+ [TraceAttributes.KIND]: "sdk-operation",
2346
+ [TraceAttributes.VERSION]: VERSION
2347
+ });
2348
+ });
1319
2349
  }
1320
- async create(a, b) {
1321
- if (Array.isArray(a)) {
1322
- if (a.length === 0)
1323
- return [];
1324
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1325
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1326
- return records;
1327
- }
1328
- if (isString(a) && isObject(b)) {
1329
- if (a === "")
1330
- throw new Error("The id can't be empty");
1331
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1332
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1333
- return record;
1334
- }
1335
- if (isObject(a) && isString(a.id)) {
1336
- if (a.id === "")
1337
- throw new Error("The id can't be empty");
1338
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1339
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1340
- return record;
1341
- }
1342
- if (isObject(a)) {
1343
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1344
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1345
- return record;
1346
- }
1347
- throw new Error("Invalid arguments for create method");
1348
- }
1349
- async read(a) {
1350
- if (Array.isArray(a)) {
1351
- if (a.length === 0)
1352
- return [];
1353
- const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1354
- return this.getAll({ filter: { id: { $any: ids } } });
1355
- }
1356
- const id = isString(a) ? a : a.id;
1357
- if (isString(id)) {
1358
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1359
- if (cacheRecord)
1360
- return cacheRecord;
1361
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1362
- try {
1363
- const response = await getRecord({
1364
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1365
- ...fetchProps
2350
+ async create(a, b, c, d) {
2351
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
2352
+ const ifVersion = parseIfVersion(b, c, d);
2353
+ if (Array.isArray(a)) {
2354
+ if (a.length === 0)
2355
+ return [];
2356
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2357
+ const columns = isStringArray(b) ? b : ["*"];
2358
+ const result = await this.read(ids, columns);
2359
+ return result;
2360
+ }
2361
+ if (isString(a) && isObject(b)) {
2362
+ if (a === "")
2363
+ throw new Error("The id can't be empty");
2364
+ const columns = isStringArray(c) ? c : void 0;
2365
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2366
+ }
2367
+ if (isObject(a) && isString(a.id)) {
2368
+ if (a.id === "")
2369
+ throw new Error("The id can't be empty");
2370
+ const columns = isStringArray(b) ? b : void 0;
2371
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2372
+ }
2373
+ if (isObject(a)) {
2374
+ const columns = isStringArray(b) ? b : void 0;
2375
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2376
+ }
2377
+ throw new Error("Invalid arguments for create method");
2378
+ });
2379
+ }
2380
+ async read(a, b) {
2381
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
2382
+ const columns = isStringArray(b) ? b : ["*"];
2383
+ if (Array.isArray(a)) {
2384
+ if (a.length === 0)
2385
+ return [];
2386
+ const ids = a.map((item) => extractId(item));
2387
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
2388
+ const dictionary = finalObjects.reduce((acc, object) => {
2389
+ acc[object.id] = object;
2390
+ return acc;
2391
+ }, {});
2392
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
2393
+ }
2394
+ const id = extractId(a);
2395
+ if (id) {
2396
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2397
+ try {
2398
+ const response = await getRecord({
2399
+ pathParams: {
2400
+ workspace: "{workspaceId}",
2401
+ dbBranchName: "{dbBranch}",
2402
+ region: "{region}",
2403
+ tableName: __privateGet$4(this, _table),
2404
+ recordId: id
2405
+ },
2406
+ queryParams: { columns },
2407
+ ...fetchProps
2408
+ });
2409
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2410
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2411
+ } catch (e) {
2412
+ if (isObject(e) && e.status === 404) {
2413
+ return null;
2414
+ }
2415
+ throw e;
2416
+ }
2417
+ }
2418
+ return null;
2419
+ });
2420
+ }
2421
+ async readOrThrow(a, b) {
2422
+ return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
2423
+ const result = await this.read(a, b);
2424
+ if (Array.isArray(result)) {
2425
+ const missingIds = compact(
2426
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
2427
+ );
2428
+ if (missingIds.length > 0) {
2429
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
2430
+ }
2431
+ return result;
2432
+ }
2433
+ if (result === null) {
2434
+ const id = extractId(a) ?? "unknown";
2435
+ throw new Error(`Record with id ${id} not found`);
2436
+ }
2437
+ return result;
2438
+ });
2439
+ }
2440
+ async update(a, b, c, d) {
2441
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
2442
+ const ifVersion = parseIfVersion(b, c, d);
2443
+ if (Array.isArray(a)) {
2444
+ if (a.length === 0)
2445
+ return [];
2446
+ const existing = await this.read(a, ["id"]);
2447
+ const updates = a.filter((_item, index) => existing[index] !== null);
2448
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
2449
+ ifVersion,
2450
+ upsert: false
1366
2451
  });
1367
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1368
- return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1369
- } catch (e) {
1370
- if (isObject(e) && e.status === 404) {
2452
+ const columns = isStringArray(b) ? b : ["*"];
2453
+ const result = await this.read(a, columns);
2454
+ return result;
2455
+ }
2456
+ try {
2457
+ if (isString(a) && isObject(b)) {
2458
+ const columns = isStringArray(c) ? c : void 0;
2459
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2460
+ }
2461
+ if (isObject(a) && isString(a.id)) {
2462
+ const columns = isStringArray(b) ? b : void 0;
2463
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2464
+ }
2465
+ } catch (error) {
2466
+ if (error.status === 422)
1371
2467
  return null;
2468
+ throw error;
2469
+ }
2470
+ throw new Error("Invalid arguments for update method");
2471
+ });
2472
+ }
2473
+ async updateOrThrow(a, b, c, d) {
2474
+ return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
2475
+ const result = await this.update(a, b, c, d);
2476
+ if (Array.isArray(result)) {
2477
+ const missingIds = compact(
2478
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
2479
+ );
2480
+ if (missingIds.length > 0) {
2481
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1372
2482
  }
1373
- throw e;
2483
+ return result;
1374
2484
  }
1375
- }
2485
+ if (result === null) {
2486
+ const id = extractId(a) ?? "unknown";
2487
+ throw new Error(`Record with id ${id} not found`);
2488
+ }
2489
+ return result;
2490
+ });
1376
2491
  }
1377
- async update(a, b) {
1378
- if (Array.isArray(a)) {
1379
- if (a.length === 0)
1380
- return [];
1381
- if (a.length > 100) {
1382
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2492
+ async createOrUpdate(a, b, c, d) {
2493
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
2494
+ const ifVersion = parseIfVersion(b, c, d);
2495
+ if (Array.isArray(a)) {
2496
+ if (a.length === 0)
2497
+ return [];
2498
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
2499
+ ifVersion,
2500
+ upsert: true
2501
+ });
2502
+ const columns = isStringArray(b) ? b : ["*"];
2503
+ const result = await this.read(a, columns);
2504
+ return result;
1383
2505
  }
1384
- return Promise.all(a.map((object) => this.update(object)));
1385
- }
1386
- if (isString(a) && isObject(b)) {
1387
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1388
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1389
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1390
- return record;
1391
- }
1392
- if (isObject(a) && isString(a.id)) {
1393
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1394
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1395
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1396
- return record;
1397
- }
1398
- throw new Error("Invalid arguments for update method");
1399
- }
1400
- async createOrUpdate(a, b) {
1401
- if (Array.isArray(a)) {
1402
- if (a.length === 0)
1403
- return [];
1404
- if (a.length > 100) {
1405
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2506
+ if (isString(a) && isObject(b)) {
2507
+ const columns = isStringArray(c) ? c : void 0;
2508
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
1406
2509
  }
1407
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1408
- }
1409
- if (isString(a) && isObject(b)) {
1410
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1411
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1412
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1413
- return record;
1414
- }
1415
- if (isObject(a) && isString(a.id)) {
1416
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1417
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1418
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1419
- return record;
1420
- }
1421
- throw new Error("Invalid arguments for createOrUpdate method");
1422
- }
1423
- async delete(a) {
1424
- if (Array.isArray(a)) {
1425
- if (a.length === 0)
1426
- return;
1427
- if (a.length > 100) {
1428
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
2510
+ if (isObject(a) && isString(a.id)) {
2511
+ const columns = isStringArray(c) ? c : void 0;
2512
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
1429
2513
  }
1430
- await Promise.all(a.map((id) => this.delete(id)));
1431
- return;
1432
- }
1433
- if (isString(a)) {
1434
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1435
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1436
- return;
1437
- }
1438
- if (isObject(a) && isString(a.id)) {
1439
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1440
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1441
- return;
1442
- }
1443
- throw new Error("Invalid arguments for delete method");
2514
+ throw new Error("Invalid arguments for createOrUpdate method");
2515
+ });
2516
+ }
2517
+ async createOrReplace(a, b, c, d) {
2518
+ return __privateGet$4(this, _trace).call(this, "createOrReplace", async () => {
2519
+ const ifVersion = parseIfVersion(b, c, d);
2520
+ if (Array.isArray(a)) {
2521
+ if (a.length === 0)
2522
+ return [];
2523
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2524
+ const columns = isStringArray(b) ? b : ["*"];
2525
+ const result = await this.read(ids, columns);
2526
+ return result;
2527
+ }
2528
+ if (isString(a) && isObject(b)) {
2529
+ const columns = isStringArray(c) ? c : void 0;
2530
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2531
+ }
2532
+ if (isObject(a) && isString(a.id)) {
2533
+ const columns = isStringArray(c) ? c : void 0;
2534
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
2535
+ }
2536
+ throw new Error("Invalid arguments for createOrReplace method");
2537
+ });
2538
+ }
2539
+ async delete(a, b) {
2540
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
2541
+ if (Array.isArray(a)) {
2542
+ if (a.length === 0)
2543
+ return [];
2544
+ const ids = a.map((o) => {
2545
+ if (isString(o))
2546
+ return o;
2547
+ if (isString(o.id))
2548
+ return o.id;
2549
+ throw new Error("Invalid arguments for delete method");
2550
+ });
2551
+ const columns = isStringArray(b) ? b : ["*"];
2552
+ const result = await this.read(a, columns);
2553
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2554
+ return result;
2555
+ }
2556
+ if (isString(a)) {
2557
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
2558
+ }
2559
+ if (isObject(a) && isString(a.id)) {
2560
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
2561
+ }
2562
+ throw new Error("Invalid arguments for delete method");
2563
+ });
2564
+ }
2565
+ async deleteOrThrow(a, b) {
2566
+ return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
2567
+ const result = await this.delete(a, b);
2568
+ if (Array.isArray(result)) {
2569
+ const missingIds = compact(
2570
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
2571
+ );
2572
+ if (missingIds.length > 0) {
2573
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
2574
+ }
2575
+ return result;
2576
+ } else if (result === null) {
2577
+ const id = extractId(a) ?? "unknown";
2578
+ throw new Error(`Record with id ${id} not found`);
2579
+ }
2580
+ return result;
2581
+ });
1444
2582
  }
1445
2583
  async search(query, options = {}) {
1446
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1447
- const { records } = await searchTable({
1448
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1449
- body: {
1450
- query,
1451
- fuzziness: options.fuzziness,
1452
- highlight: options.highlight,
1453
- filter: options.filter
1454
- },
1455
- ...fetchProps
2584
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
2585
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2586
+ const { records } = await searchTable({
2587
+ pathParams: {
2588
+ workspace: "{workspaceId}",
2589
+ dbBranchName: "{dbBranch}",
2590
+ region: "{region}",
2591
+ tableName: __privateGet$4(this, _table)
2592
+ },
2593
+ body: {
2594
+ query,
2595
+ fuzziness: options.fuzziness,
2596
+ prefix: options.prefix,
2597
+ highlight: options.highlight,
2598
+ filter: options.filter,
2599
+ boosters: options.boosters,
2600
+ page: options.page,
2601
+ target: options.target
2602
+ },
2603
+ ...fetchProps
2604
+ });
2605
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2606
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
2607
+ });
2608
+ }
2609
+ async aggregate(aggs, filter) {
2610
+ return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2611
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2612
+ const result = await aggregateTable({
2613
+ pathParams: {
2614
+ workspace: "{workspaceId}",
2615
+ dbBranchName: "{dbBranch}",
2616
+ region: "{region}",
2617
+ tableName: __privateGet$4(this, _table)
2618
+ },
2619
+ body: { aggs, filter },
2620
+ ...fetchProps
2621
+ });
2622
+ return result;
1456
2623
  });
1457
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1458
- return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1459
2624
  }
1460
2625
  async query(query) {
1461
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1462
- if (cacheQuery)
1463
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1464
- const data = query.getQueryOptions();
1465
- const body = {
1466
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1467
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1468
- page: data.pagination,
1469
- columns: data.columns
1470
- };
1471
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1472
- const { meta, records: objects } = await queryTable({
1473
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1474
- body,
1475
- ...fetchProps
2626
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
2627
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
2628
+ if (cacheQuery)
2629
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
2630
+ const data = query.getQueryOptions();
2631
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2632
+ const { meta, records: objects } = await queryTable({
2633
+ pathParams: {
2634
+ workspace: "{workspaceId}",
2635
+ dbBranchName: "{dbBranch}",
2636
+ region: "{region}",
2637
+ tableName: __privateGet$4(this, _table)
2638
+ },
2639
+ body: {
2640
+ filter: cleanFilter(data.filter),
2641
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2642
+ page: data.pagination,
2643
+ columns: data.columns ?? ["*"],
2644
+ consistency: data.consistency
2645
+ },
2646
+ fetchOptions: data.fetchOptions,
2647
+ ...fetchProps
2648
+ });
2649
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2650
+ const records = objects.map(
2651
+ (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
2652
+ );
2653
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
2654
+ return new Page(query, meta, records);
2655
+ });
2656
+ }
2657
+ async summarizeTable(query, summaries, summariesFilter) {
2658
+ return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2659
+ const data = query.getQueryOptions();
2660
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2661
+ const result = await summarizeTable({
2662
+ pathParams: {
2663
+ workspace: "{workspaceId}",
2664
+ dbBranchName: "{dbBranch}",
2665
+ region: "{region}",
2666
+ tableName: __privateGet$4(this, _table)
2667
+ },
2668
+ body: {
2669
+ filter: cleanFilter(data.filter),
2670
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2671
+ columns: data.columns,
2672
+ consistency: data.consistency,
2673
+ page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2674
+ summaries,
2675
+ summariesFilter
2676
+ },
2677
+ ...fetchProps
2678
+ });
2679
+ return result;
1476
2680
  });
1477
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1478
- const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1479
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1480
- return new Page(query, meta, records);
1481
2681
  }
1482
2682
  }
1483
2683
  _table = new WeakMap();
1484
2684
  _getFetchProps = new WeakMap();
2685
+ _db = new WeakMap();
1485
2686
  _cache = new WeakMap();
1486
2687
  _schemaTables$2 = new WeakMap();
2688
+ _trace = new WeakMap();
1487
2689
  _insertRecordWithoutId = new WeakSet();
1488
- insertRecordWithoutId_fn = async function(object) {
2690
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1489
2691
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1490
2692
  const record = transformObjectLinks(object);
1491
2693
  const response = await insertRecord({
1492
2694
  pathParams: {
1493
2695
  workspace: "{workspaceId}",
1494
2696
  dbBranchName: "{dbBranch}",
2697
+ region: "{region}",
1495
2698
  tableName: __privateGet$4(this, _table)
1496
2699
  },
2700
+ queryParams: { columns },
1497
2701
  body: record,
1498
2702
  ...fetchProps
1499
2703
  });
1500
- const finalObject = await this.read(response.id);
1501
- if (!finalObject) {
1502
- throw new Error("The server failed to save the record");
1503
- }
1504
- return finalObject;
2704
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2705
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1505
2706
  };
1506
2707
  _insertRecordWithId = new WeakSet();
1507
- insertRecordWithId_fn = async function(recordId, object) {
2708
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
1508
2709
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1509
2710
  const record = transformObjectLinks(object);
1510
2711
  const response = await insertRecordWithID({
1511
2712
  pathParams: {
1512
2713
  workspace: "{workspaceId}",
1513
2714
  dbBranchName: "{dbBranch}",
2715
+ region: "{region}",
1514
2716
  tableName: __privateGet$4(this, _table),
1515
2717
  recordId
1516
2718
  },
1517
2719
  body: record,
1518
- queryParams: { createOnly: true },
2720
+ queryParams: { createOnly, columns, ifVersion },
1519
2721
  ...fetchProps
1520
2722
  });
1521
- const finalObject = await this.read(response.id);
1522
- if (!finalObject) {
1523
- throw new Error("The server failed to save the record");
1524
- }
1525
- return finalObject;
2723
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2724
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1526
2725
  };
1527
- _bulkInsertTableRecords = new WeakSet();
1528
- bulkInsertTableRecords_fn = async function(objects) {
2726
+ _insertRecords = new WeakSet();
2727
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
1529
2728
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1530
- const records = objects.map((object) => transformObjectLinks(object));
1531
- const { recordIDs } = await bulkInsertTableRecords({
1532
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1533
- body: { records },
1534
- ...fetchProps
1535
- });
1536
- const finalObjects = await this.read(recordIDs);
1537
- if (finalObjects.length !== objects.length) {
1538
- throw new Error("The server failed to save some records");
2729
+ const chunkedOperations = chunk(
2730
+ objects.map((object) => ({
2731
+ insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2732
+ })),
2733
+ BULK_OPERATION_MAX_SIZE
2734
+ );
2735
+ const ids = [];
2736
+ for (const operations of chunkedOperations) {
2737
+ const { results } = await branchTransaction({
2738
+ pathParams: {
2739
+ workspace: "{workspaceId}",
2740
+ dbBranchName: "{dbBranch}",
2741
+ region: "{region}"
2742
+ },
2743
+ body: { operations },
2744
+ ...fetchProps
2745
+ });
2746
+ for (const result of results) {
2747
+ if (result.operation === "insert") {
2748
+ ids.push(result.id);
2749
+ } else {
2750
+ ids.push(null);
2751
+ }
2752
+ }
1539
2753
  }
1540
- const dictionary = finalObjects.reduce((acc, object) => {
1541
- acc[object.id] = object;
1542
- return acc;
1543
- }, {});
1544
- return recordIDs.map((id) => dictionary[id]);
2754
+ return ids;
1545
2755
  };
1546
2756
  _updateRecordWithID = new WeakSet();
1547
- updateRecordWithID_fn = async function(recordId, object) {
2757
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
1548
2758
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1549
- const record = transformObjectLinks(object);
1550
- const response = await updateRecordWithID({
1551
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1552
- body: record,
1553
- ...fetchProps
1554
- });
1555
- const item = await this.read(response.id);
1556
- if (!item)
1557
- throw new Error("The server failed to save the record");
1558
- return item;
2759
+ const { id: _id, ...record } = transformObjectLinks(object);
2760
+ try {
2761
+ const response = await updateRecordWithID({
2762
+ pathParams: {
2763
+ workspace: "{workspaceId}",
2764
+ dbBranchName: "{dbBranch}",
2765
+ region: "{region}",
2766
+ tableName: __privateGet$4(this, _table),
2767
+ recordId
2768
+ },
2769
+ queryParams: { columns, ifVersion },
2770
+ body: record,
2771
+ ...fetchProps
2772
+ });
2773
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2774
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2775
+ } catch (e) {
2776
+ if (isObject(e) && e.status === 404) {
2777
+ return null;
2778
+ }
2779
+ throw e;
2780
+ }
2781
+ };
2782
+ _updateRecords = new WeakSet();
2783
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2784
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2785
+ const chunkedOperations = chunk(
2786
+ objects.map(({ id, ...object }) => ({
2787
+ update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2788
+ })),
2789
+ BULK_OPERATION_MAX_SIZE
2790
+ );
2791
+ const ids = [];
2792
+ for (const operations of chunkedOperations) {
2793
+ const { results } = await branchTransaction({
2794
+ pathParams: {
2795
+ workspace: "{workspaceId}",
2796
+ dbBranchName: "{dbBranch}",
2797
+ region: "{region}"
2798
+ },
2799
+ body: { operations },
2800
+ ...fetchProps
2801
+ });
2802
+ for (const result of results) {
2803
+ if (result.operation === "update") {
2804
+ ids.push(result.id);
2805
+ } else {
2806
+ ids.push(null);
2807
+ }
2808
+ }
2809
+ }
2810
+ return ids;
1559
2811
  };
1560
2812
  _upsertRecordWithID = new WeakSet();
1561
- upsertRecordWithID_fn = async function(recordId, object) {
2813
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
1562
2814
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1563
2815
  const response = await upsertRecordWithID({
1564
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2816
+ pathParams: {
2817
+ workspace: "{workspaceId}",
2818
+ dbBranchName: "{dbBranch}",
2819
+ region: "{region}",
2820
+ tableName: __privateGet$4(this, _table),
2821
+ recordId
2822
+ },
2823
+ queryParams: { columns, ifVersion },
1565
2824
  body: object,
1566
2825
  ...fetchProps
1567
2826
  });
1568
- const item = await this.read(response.id);
1569
- if (!item)
1570
- throw new Error("The server failed to save the record");
1571
- return item;
2827
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2828
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1572
2829
  };
1573
2830
  _deleteRecord = new WeakSet();
1574
- deleteRecord_fn = async function(recordId) {
2831
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1575
2832
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1576
- await deleteRecord({
1577
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1578
- ...fetchProps
1579
- });
2833
+ try {
2834
+ const response = await deleteRecord({
2835
+ pathParams: {
2836
+ workspace: "{workspaceId}",
2837
+ dbBranchName: "{dbBranch}",
2838
+ region: "{region}",
2839
+ tableName: __privateGet$4(this, _table),
2840
+ recordId
2841
+ },
2842
+ queryParams: { columns },
2843
+ ...fetchProps
2844
+ });
2845
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2846
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2847
+ } catch (e) {
2848
+ if (isObject(e) && e.status === 404) {
2849
+ return null;
2850
+ }
2851
+ throw e;
2852
+ }
1580
2853
  };
1581
- _invalidateCache = new WeakSet();
1582
- invalidateCache_fn = async function(recordId) {
1583
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1584
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1585
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1586
- for (const [key, value] of queries) {
1587
- const ids = getIds(value);
1588
- if (ids.includes(recordId))
1589
- await __privateGet$4(this, _cache).delete(key);
1590
- }
1591
- };
1592
- _setCacheRecord = new WeakSet();
1593
- setCacheRecord_fn = async function(record) {
1594
- if (!__privateGet$4(this, _cache).cacheRecords)
1595
- return;
1596
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1597
- };
1598
- _getCacheRecord = new WeakSet();
1599
- getCacheRecord_fn = async function(recordId) {
1600
- if (!__privateGet$4(this, _cache).cacheRecords)
1601
- return null;
1602
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
2854
+ _deleteRecords = new WeakSet();
2855
+ deleteRecords_fn = async function(recordIds) {
2856
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2857
+ const chunkedOperations = chunk(
2858
+ recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2859
+ BULK_OPERATION_MAX_SIZE
2860
+ );
2861
+ for (const operations of chunkedOperations) {
2862
+ await branchTransaction({
2863
+ pathParams: {
2864
+ workspace: "{workspaceId}",
2865
+ dbBranchName: "{dbBranch}",
2866
+ region: "{region}"
2867
+ },
2868
+ body: { operations },
2869
+ ...fetchProps
2870
+ });
2871
+ }
1603
2872
  };
1604
2873
  _setCacheQuery = new WeakSet();
1605
2874
  setCacheQuery_fn = async function(query, meta, records) {
@@ -1623,7 +2892,7 @@ getSchemaTables_fn$1 = async function() {
1623
2892
  return __privateGet$4(this, _schemaTables$2);
1624
2893
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1625
2894
  const { schema } = await getBranchDetails({
1626
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2895
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
1627
2896
  ...fetchProps
1628
2897
  });
1629
2898
  __privateSet$4(this, _schemaTables$2, schema.tables);
@@ -1636,22 +2905,24 @@ const transformObjectLinks = (object) => {
1636
2905
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1637
2906
  }, {});
1638
2907
  };
1639
- const initObject = (db, schemaTables, table, object) => {
1640
- const result = {};
2908
+ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2909
+ const data = {};
1641
2910
  const { xata, ...rest } = object ?? {};
1642
- Object.assign(result, rest);
2911
+ Object.assign(data, rest);
1643
2912
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1644
2913
  if (!columns)
1645
2914
  console.error(`Table ${table} not found in schema`);
1646
2915
  for (const column of columns ?? []) {
1647
- const value = result[column.name];
2916
+ if (!isValidColumn(selectedColumns, column))
2917
+ continue;
2918
+ const value = data[column.name];
1648
2919
  switch (column.type) {
1649
2920
  case "datetime": {
1650
- const date = value !== void 0 ? new Date(value) : void 0;
1651
- if (date && isNaN(date.getTime())) {
2921
+ const date = value !== void 0 ? new Date(value) : null;
2922
+ if (date !== null && isNaN(date.getTime())) {
1652
2923
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1653
- } else if (date) {
1654
- result[column.name] = date;
2924
+ } else {
2925
+ data[column.name] = date;
1655
2926
  }
1656
2927
  break;
1657
2928
  }
@@ -1660,38 +2931,85 @@ const initObject = (db, schemaTables, table, object) => {
1660
2931
  if (!linkTable) {
1661
2932
  console.error(`Failed to parse link for field ${column.name}`);
1662
2933
  } else if (isObject(value)) {
1663
- result[column.name] = initObject(db, schemaTables, linkTable, value);
2934
+ const selectedLinkColumns = selectedColumns.reduce((acc, item) => {
2935
+ if (item === column.name) {
2936
+ return [...acc, "*"];
2937
+ }
2938
+ if (item.startsWith(`${column.name}.`)) {
2939
+ const [, ...path] = item.split(".");
2940
+ return [...acc, path.join(".")];
2941
+ }
2942
+ return acc;
2943
+ }, []);
2944
+ data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2945
+ } else {
2946
+ data[column.name] = null;
1664
2947
  }
1665
2948
  break;
1666
2949
  }
2950
+ default:
2951
+ data[column.name] = value ?? null;
2952
+ if (column.notNull === true && value === null) {
2953
+ console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2954
+ }
2955
+ break;
1667
2956
  }
1668
2957
  }
1669
- result.read = function() {
1670
- return db[table].read(result["id"]);
2958
+ const record = { ...data };
2959
+ record.read = function(columns2) {
2960
+ return db[table].read(record["id"], columns2);
2961
+ };
2962
+ record.update = function(data2, b, c) {
2963
+ const columns2 = isStringArray(b) ? b : ["*"];
2964
+ const ifVersion = parseIfVersion(b, c);
2965
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
1671
2966
  };
1672
- result.update = function(data) {
1673
- return db[table].update(result["id"], data);
2967
+ record.replace = function(data2, b, c) {
2968
+ const columns2 = isStringArray(b) ? b : ["*"];
2969
+ const ifVersion = parseIfVersion(b, c);
2970
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
1674
2971
  };
1675
- result.delete = function() {
1676
- return db[table].delete(result["id"]);
2972
+ record.delete = function() {
2973
+ return db[table].delete(record["id"]);
1677
2974
  };
1678
- result.getMetadata = function() {
2975
+ record.getMetadata = function() {
1679
2976
  return xata;
1680
2977
  };
1681
- for (const prop of ["read", "update", "delete", "getMetadata"]) {
1682
- Object.defineProperty(result, prop, { enumerable: false });
2978
+ record.toSerializable = function() {
2979
+ return JSON.parse(JSON.stringify(transformObjectLinks(data)));
2980
+ };
2981
+ record.toString = function() {
2982
+ return JSON.stringify(transformObjectLinks(data));
2983
+ };
2984
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
2985
+ Object.defineProperty(record, prop, { enumerable: false });
1683
2986
  }
1684
- Object.freeze(result);
1685
- return result;
2987
+ Object.freeze(record);
2988
+ return record;
1686
2989
  };
1687
- function getIds(value) {
1688
- if (Array.isArray(value)) {
1689
- return value.map((item) => getIds(item)).flat();
2990
+ function extractId(value) {
2991
+ if (isString(value))
2992
+ return value;
2993
+ if (isObject(value) && isString(value.id))
2994
+ return value.id;
2995
+ return void 0;
2996
+ }
2997
+ function isValidColumn(columns, column) {
2998
+ if (columns.includes("*"))
2999
+ return true;
3000
+ if (column.type === "link") {
3001
+ const linkColumns = columns.filter((item) => item.startsWith(column.name));
3002
+ return linkColumns.length > 0;
3003
+ }
3004
+ return columns.includes(column.name);
3005
+ }
3006
+ function parseIfVersion(...args) {
3007
+ for (const arg of args) {
3008
+ if (isObject(arg) && isNumber(arg.ifVersion)) {
3009
+ return arg.ifVersion;
3010
+ }
1690
3011
  }
1691
- if (!isObject(value))
1692
- return [];
1693
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1694
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
3012
+ return void 0;
1695
3013
  }
1696
3014
 
1697
3015
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1718,7 +3036,6 @@ class SimpleCache {
1718
3036
  __privateAdd$3(this, _map, void 0);
1719
3037
  __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1720
3038
  this.capacity = options.max ?? 500;
1721
- this.cacheRecords = options.cacheRecords ?? true;
1722
3039
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1723
3040
  }
1724
3041
  async getAll() {
@@ -1744,18 +3061,25 @@ class SimpleCache {
1744
3061
  }
1745
3062
  _map = new WeakMap();
1746
3063
 
1747
- const gt = (value) => ({ $gt: value });
1748
- const ge = (value) => ({ $ge: value });
1749
- const gte = (value) => ({ $ge: value });
1750
- const lt = (value) => ({ $lt: value });
1751
- const lte = (value) => ({ $le: value });
1752
- const le = (value) => ({ $le: value });
3064
+ const greaterThan = (value) => ({ $gt: value });
3065
+ const gt = greaterThan;
3066
+ const greaterThanEquals = (value) => ({ $ge: value });
3067
+ const greaterEquals = greaterThanEquals;
3068
+ const gte = greaterThanEquals;
3069
+ const ge = greaterThanEquals;
3070
+ const lessThan = (value) => ({ $lt: value });
3071
+ const lt = lessThan;
3072
+ const lessThanEquals = (value) => ({ $le: value });
3073
+ const lessEquals = lessThanEquals;
3074
+ const lte = lessThanEquals;
3075
+ const le = lessThanEquals;
1753
3076
  const exists = (column) => ({ $exists: column });
1754
3077
  const notExists = (column) => ({ $notExists: column });
1755
3078
  const startsWith = (value) => ({ $startsWith: value });
1756
3079
  const endsWith = (value) => ({ $endsWith: value });
1757
3080
  const pattern = (value) => ({ $pattern: value });
1758
3081
  const is = (value) => ({ $is: value });
3082
+ const equals = is;
1759
3083
  const isNot = (value) => ({ $isNot: value });
1760
3084
  const contains = (value) => ({ $contains: value });
1761
3085
  const includes = (value) => ({ $includes: value });
@@ -1790,16 +3114,19 @@ class SchemaPlugin extends XataPlugin {
1790
3114
  __privateSet$2(this, _schemaTables$1, schemaTables);
1791
3115
  }
1792
3116
  build(pluginOptions) {
1793
- const db = new Proxy({}, {
1794
- get: (_target, table) => {
1795
- if (!isString(table))
1796
- throw new Error("Invalid table name");
1797
- if (__privateGet$2(this, _tables)[table] === void 0) {
1798
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
3117
+ const db = new Proxy(
3118
+ {},
3119
+ {
3120
+ get: (_target, table) => {
3121
+ if (!isString(table))
3122
+ throw new Error("Invalid table name");
3123
+ if (__privateGet$2(this, _tables)[table] === void 0) {
3124
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
3125
+ }
3126
+ return __privateGet$2(this, _tables)[table];
1799
3127
  }
1800
- return __privateGet$2(this, _tables)[table];
1801
3128
  }
1802
- });
3129
+ );
1803
3130
  const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1804
3131
  for (const table of tableNames) {
1805
3132
  db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
@@ -1849,7 +3176,7 @@ class SearchPlugin extends XataPlugin {
1849
3176
  const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1850
3177
  return records.map((record) => {
1851
3178
  const { table = "orphan" } = record.xata;
1852
- return { table, record: initObject(this.db, schemaTables, table, record) };
3179
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
1853
3180
  });
1854
3181
  },
1855
3182
  byTable: async (query, options = {}) => {
@@ -1858,7 +3185,7 @@ class SearchPlugin extends XataPlugin {
1858
3185
  return records.reduce((acc, record) => {
1859
3186
  const { table = "orphan" } = record.xata;
1860
3187
  const items = acc[table] ?? [];
1861
- const item = initObject(this.db, schemaTables, table, record);
3188
+ const item = initObject(this.db, schemaTables, table, record, ["*"]);
1862
3189
  return { ...acc, [table]: [...items, item] };
1863
3190
  }, {});
1864
3191
  }
@@ -1869,10 +3196,10 @@ _schemaTables = new WeakMap();
1869
3196
  _search = new WeakSet();
1870
3197
  search_fn = async function(query, options, getFetchProps) {
1871
3198
  const fetchProps = await getFetchProps();
1872
- const { tables, fuzziness, highlight } = options ?? {};
3199
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
1873
3200
  const { records } = await searchBranch({
1874
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1875
- body: { tables, query, fuzziness, highlight },
3201
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3202
+ body: { tables, query, fuzziness, prefix, highlight, page },
1876
3203
  ...fetchProps
1877
3204
  });
1878
3205
  return records;
@@ -1883,26 +3210,38 @@ getSchemaTables_fn = async function(getFetchProps) {
1883
3210
  return __privateGet$1(this, _schemaTables);
1884
3211
  const fetchProps = await getFetchProps();
1885
3212
  const { schema } = await getBranchDetails({
1886
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
3213
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
1887
3214
  ...fetchProps
1888
3215
  });
1889
3216
  __privateSet$1(this, _schemaTables, schema.tables);
1890
3217
  return schema.tables;
1891
3218
  };
1892
3219
 
3220
+ class TransactionPlugin extends XataPlugin {
3221
+ build({ getFetchProps }) {
3222
+ return {
3223
+ run: async (operations) => {
3224
+ const fetchProps = await getFetchProps();
3225
+ const response = await branchTransaction({
3226
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3227
+ body: { operations },
3228
+ ...fetchProps
3229
+ });
3230
+ return response;
3231
+ }
3232
+ };
3233
+ }
3234
+ }
3235
+
1893
3236
  const isBranchStrategyBuilder = (strategy) => {
1894
3237
  return typeof strategy === "function";
1895
3238
  };
1896
3239
 
1897
3240
  async function getCurrentBranchName(options) {
1898
- const { branch } = getEnvironment();
1899
- if (branch) {
1900
- const details = await getDatabaseBranch(branch, options);
1901
- if (details)
1902
- return branch;
1903
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1904
- }
1905
- const gitBranch = await getGitBranch();
3241
+ const { branch, envBranch } = getEnvironment();
3242
+ if (branch)
3243
+ return branch;
3244
+ const gitBranch = envBranch || await getGitBranch();
1906
3245
  return resolveXataBranch(gitBranch, options);
1907
3246
  }
1908
3247
  async function getCurrentBranchDetails(options) {
@@ -1913,19 +3252,28 @@ async function resolveXataBranch(gitBranch, options) {
1913
3252
  const databaseURL = options?.databaseURL || getDatabaseURL();
1914
3253
  const apiKey = options?.apiKey || getAPIKey();
1915
3254
  if (!databaseURL)
1916
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
3255
+ throw new Error(
3256
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3257
+ );
1917
3258
  if (!apiKey)
1918
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
3259
+ throw new Error(
3260
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3261
+ );
1919
3262
  const [protocol, , host, , dbName] = databaseURL.split("/");
1920
- const [workspace] = host.split(".");
3263
+ const urlParts = parseWorkspacesUrlParts(host);
3264
+ if (!urlParts)
3265
+ throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3266
+ const { workspace, region } = urlParts;
1921
3267
  const { fallbackBranch } = getEnvironment();
1922
3268
  const { branch } = await resolveBranch({
1923
3269
  apiKey,
1924
3270
  apiUrl: databaseURL,
1925
3271
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1926
3272
  workspacesApiUrl: `${protocol}//${host}`,
1927
- pathParams: { dbName, workspace },
1928
- queryParams: { gitBranch, fallbackBranch }
3273
+ pathParams: { dbName, workspace, region },
3274
+ queryParams: { gitBranch, fallbackBranch },
3275
+ trace: defaultTrace,
3276
+ clientName: options?.clientName
1929
3277
  });
1930
3278
  return branch;
1931
3279
  }
@@ -1933,19 +3281,26 @@ async function getDatabaseBranch(branch, options) {
1933
3281
  const databaseURL = options?.databaseURL || getDatabaseURL();
1934
3282
  const apiKey = options?.apiKey || getAPIKey();
1935
3283
  if (!databaseURL)
1936
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
3284
+ throw new Error(
3285
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3286
+ );
1937
3287
  if (!apiKey)
1938
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
3288
+ throw new Error(
3289
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3290
+ );
1939
3291
  const [protocol, , host, , database] = databaseURL.split("/");
1940
- const [workspace] = host.split(".");
1941
- const dbBranchName = `${database}:${branch}`;
3292
+ const urlParts = parseWorkspacesUrlParts(host);
3293
+ if (!urlParts)
3294
+ throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3295
+ const { workspace, region } = urlParts;
1942
3296
  try {
1943
3297
  return await getBranchDetails({
1944
3298
  apiKey,
1945
3299
  apiUrl: databaseURL,
1946
3300
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1947
3301
  workspacesApiUrl: `${protocol}//${host}`,
1948
- pathParams: { dbBranchName, workspace }
3302
+ pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3303
+ trace: defaultTrace
1949
3304
  });
1950
3305
  } catch (err) {
1951
3306
  if (isObject(err) && err.status === 404)
@@ -1985,22 +3340,27 @@ var __privateMethod = (obj, member, method) => {
1985
3340
  return method;
1986
3341
  };
1987
3342
  const buildClient = (plugins) => {
1988
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
3343
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1989
3344
  return _a = class {
1990
3345
  constructor(options = {}, schemaTables) {
1991
3346
  __privateAdd(this, _parseOptions);
1992
3347
  __privateAdd(this, _getFetchProps);
1993
3348
  __privateAdd(this, _evaluateBranch);
1994
3349
  __privateAdd(this, _branch, void 0);
3350
+ __privateAdd(this, _options, void 0);
1995
3351
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3352
+ __privateSet(this, _options, safeOptions);
1996
3353
  const pluginOptions = {
1997
3354
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1998
- cache: safeOptions.cache
3355
+ cache: safeOptions.cache,
3356
+ trace: safeOptions.trace
1999
3357
  };
2000
3358
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2001
3359
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3360
+ const transactions = new TransactionPlugin().build(pluginOptions);
2002
3361
  this.db = db;
2003
3362
  this.search = search;
3363
+ this.transactions = transactions;
2004
3364
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
2005
3365
  if (namespace === void 0)
2006
3366
  continue;
@@ -2014,21 +3374,46 @@ const buildClient = (plugins) => {
2014
3374
  }
2015
3375
  }
2016
3376
  }
2017
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3377
+ async getConfig() {
3378
+ const databaseURL = __privateGet(this, _options).databaseURL;
3379
+ const branch = await __privateGet(this, _options).branch();
3380
+ return { databaseURL, branch };
3381
+ }
3382
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3383
+ const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3384
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3385
+ if (isBrowser && !enableBrowser) {
3386
+ throw new Error(
3387
+ "You are trying to use Xata from the browser, which is potentially a non-secure environment. If you understand the security concerns, such as leaking your credentials, pass `enableBrowser: true` to the client options to remove this error."
3388
+ );
3389
+ }
2018
3390
  const fetch = getFetchImplementation(options?.fetch);
2019
3391
  const databaseURL = options?.databaseURL || getDatabaseURL();
2020
3392
  const apiKey = options?.apiKey || getAPIKey();
2021
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2022
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2023
- if (!databaseURL || !apiKey) {
2024
- throw new Error("Options databaseURL and apiKey are required");
3393
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3394
+ const trace = options?.trace ?? defaultTrace;
3395
+ const clientName = options?.clientName;
3396
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({
3397
+ apiKey,
3398
+ databaseURL,
3399
+ fetchImpl: options?.fetch,
3400
+ clientName: options?.clientName
3401
+ });
3402
+ if (!apiKey) {
3403
+ throw new Error("Option apiKey is required");
3404
+ }
3405
+ if (!databaseURL) {
3406
+ throw new Error("Option databaseURL is required");
2025
3407
  }
2026
- return { fetch, databaseURL, apiKey, branch, cache };
3408
+ return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser, clientName };
2027
3409
  }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
2028
3410
  fetch,
2029
3411
  apiKey,
2030
3412
  databaseURL,
2031
- branch
3413
+ branch,
3414
+ trace,
3415
+ clientID,
3416
+ clientName
2032
3417
  }) {
2033
3418
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
2034
3419
  if (!branchValue)
@@ -2039,9 +3424,12 @@ const buildClient = (plugins) => {
2039
3424
  apiUrl: "",
2040
3425
  workspacesApiUrl: (path, params) => {
2041
3426
  const hasBranch = params.dbBranchName ?? params.branch;
2042
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
3427
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
2043
3428
  return databaseURL + newPath;
2044
- }
3429
+ },
3430
+ trace,
3431
+ clientID,
3432
+ clientName
2045
3433
  };
2046
3434
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
2047
3435
  if (__privateGet(this, _branch))
@@ -2064,6 +3452,88 @@ const buildClient = (plugins) => {
2064
3452
  class BaseClient extends buildClient() {
2065
3453
  }
2066
3454
 
3455
+ const META = "__";
3456
+ const VALUE = "___";
3457
+ class Serializer {
3458
+ constructor() {
3459
+ this.classes = {};
3460
+ }
3461
+ add(clazz) {
3462
+ this.classes[clazz.name] = clazz;
3463
+ }
3464
+ toJSON(data) {
3465
+ function visit(obj) {
3466
+ if (Array.isArray(obj))
3467
+ return obj.map(visit);
3468
+ const type = typeof obj;
3469
+ if (type === "undefined")
3470
+ return { [META]: "undefined" };
3471
+ if (type === "bigint")
3472
+ return { [META]: "bigint", [VALUE]: obj.toString() };
3473
+ if (obj === null || type !== "object")
3474
+ return obj;
3475
+ const constructor = obj.constructor;
3476
+ const o = { [META]: constructor.name };
3477
+ for (const [key, value] of Object.entries(obj)) {
3478
+ o[key] = visit(value);
3479
+ }
3480
+ if (constructor === Date)
3481
+ o[VALUE] = obj.toISOString();
3482
+ if (constructor === Map)
3483
+ o[VALUE] = Object.fromEntries(obj);
3484
+ if (constructor === Set)
3485
+ o[VALUE] = [...obj];
3486
+ return o;
3487
+ }
3488
+ return JSON.stringify(visit(data));
3489
+ }
3490
+ fromJSON(json) {
3491
+ return JSON.parse(json, (key, value) => {
3492
+ if (value && typeof value === "object" && !Array.isArray(value)) {
3493
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
3494
+ const constructor = this.classes[clazz];
3495
+ if (constructor) {
3496
+ return Object.assign(Object.create(constructor.prototype), rest);
3497
+ }
3498
+ if (clazz === "Date")
3499
+ return new Date(val);
3500
+ if (clazz === "Set")
3501
+ return new Set(val);
3502
+ if (clazz === "Map")
3503
+ return new Map(Object.entries(val));
3504
+ if (clazz === "bigint")
3505
+ return BigInt(val);
3506
+ if (clazz === "undefined")
3507
+ return void 0;
3508
+ return rest;
3509
+ }
3510
+ return value;
3511
+ });
3512
+ }
3513
+ }
3514
+ const defaultSerializer = new Serializer();
3515
+ const serialize = (data) => {
3516
+ return defaultSerializer.toJSON(data);
3517
+ };
3518
+ const deserialize = (json) => {
3519
+ return defaultSerializer.fromJSON(json);
3520
+ };
3521
+
3522
+ function buildWorkerRunner(config) {
3523
+ return function xataWorker(name, worker) {
3524
+ return async (...args) => {
3525
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3526
+ const result = await fetch(url, {
3527
+ method: "POST",
3528
+ headers: { "Content-Type": "application/json" },
3529
+ body: serialize({ args })
3530
+ });
3531
+ const text = await result.text();
3532
+ return deserialize(text);
3533
+ };
3534
+ };
3535
+ }
3536
+
2067
3537
  class XataError extends Error {
2068
3538
  constructor(message, status) {
2069
3539
  super(message);
@@ -2071,5 +3541,5 @@ class XataError extends Error {
2071
3541
  }
2072
3542
  }
2073
3543
 
2074
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
3544
+ export { BaseClient, FetcherError, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, branchTransaction, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
2075
3545
  //# sourceMappingURL=index.mjs.map