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

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