@xata.io/client 0.0.0-alpha.vfaf51aa → 0.0.0-alpha.vfafe7e2

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