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

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