@xata.io/client 0.0.0-alpha.vf9d4e41 → 0.0.0-alpha.vfa22996

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