@xata.io/client 0.0.0-alpha.vfd071d9 → 0.0.0-alpha.vfd68d20

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