@xata.io/client 0.0.0-alpha.vecada6d → 0.0.0-alpha.vecd13ea

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,101 @@ 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);
12
40
  }
13
41
  function toBase64(value) {
14
42
  try {
15
43
  return btoa(value);
16
44
  } catch (err) {
17
- return Buffer.from(value).toString("base64");
45
+ const buf = Buffer;
46
+ return buf.from(value).toString("base64");
18
47
  }
19
48
  }
20
49
 
21
- function getEnvVariable(name) {
50
+ function getEnvironment() {
22
51
  try {
23
- if (isObject(process) && isString(process?.env?.[name])) {
24
- return process.env[name];
52
+ if (isObject(process) && isObject(process.env)) {
53
+ return {
54
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
55
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
56
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
57
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
58
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
59
+ };
25
60
  }
26
61
  } catch (err) {
27
62
  }
28
63
  try {
29
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
30
- return Deno.env.get(name);
64
+ if (isObject(Deno) && isObject(Deno.env)) {
65
+ return {
66
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
67
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
68
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
69
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
70
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
71
+ };
31
72
  }
32
73
  } catch (err) {
33
74
  }
75
+ return {
76
+ apiKey: getGlobalApiKey(),
77
+ databaseURL: getGlobalDatabaseURL(),
78
+ branch: getGlobalBranch(),
79
+ envBranch: void 0,
80
+ fallbackBranch: getGlobalFallbackBranch()
81
+ };
82
+ }
83
+ function getGlobalApiKey() {
84
+ try {
85
+ return XATA_API_KEY;
86
+ } catch (err) {
87
+ return void 0;
88
+ }
89
+ }
90
+ function getGlobalDatabaseURL() {
91
+ try {
92
+ return XATA_DATABASE_URL;
93
+ } catch (err) {
94
+ return void 0;
95
+ }
96
+ }
97
+ function getGlobalBranch() {
98
+ try {
99
+ return XATA_BRANCH;
100
+ } catch (err) {
101
+ return void 0;
102
+ }
103
+ }
104
+ function getGlobalFallbackBranch() {
105
+ try {
106
+ return XATA_FALLBACK_BRANCH;
107
+ } catch (err) {
108
+ return void 0;
109
+ }
34
110
  }
35
111
  async function getGitBranch() {
112
+ const cmd = ["git", "branch", "--show-current"];
113
+ const fullCmd = cmd.join(" ");
114
+ const nodeModule = ["child", "process"].join("_");
115
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
36
116
  try {
37
117
  if (typeof require === "function") {
38
- const req = require;
39
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
118
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
40
119
  }
120
+ const { execSync } = await import(nodeModule);
121
+ return execSync(fullCmd, execOptions).toString().trim();
41
122
  } catch (err) {
42
123
  }
43
124
  try {
44
125
  if (isObject(Deno)) {
45
- const process2 = Deno.run({
46
- cmd: ["git", "branch", "--show-current"],
47
- stdout: "piped",
48
- stderr: "piped"
49
- });
126
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
50
127
  return new TextDecoder().decode(await process2.output()).trim();
51
128
  }
52
129
  } catch (err) {
@@ -55,7 +132,8 @@ async function getGitBranch() {
55
132
 
56
133
  function getAPIKey() {
57
134
  try {
58
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
135
+ const { apiKey } = getEnvironment();
136
+ return apiKey;
59
137
  } catch (err) {
60
138
  return void 0;
61
139
  }
@@ -65,21 +143,35 @@ function getFetchImplementation(userFetch) {
65
143
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
66
144
  const fetchImpl = userFetch ?? globalFetch;
67
145
  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.`);
146
+ throw new Error(
147
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
148
+ );
69
149
  }
70
150
  return fetchImpl;
71
151
  }
72
152
 
73
- class FetcherError extends Error {
74
- constructor(status, data) {
153
+ const VERSION = "0.0.0-alpha.vecd13ea";
154
+
155
+ class ErrorWithCause extends Error {
156
+ constructor(message, options) {
157
+ super(message, options);
158
+ }
159
+ }
160
+ class FetcherError extends ErrorWithCause {
161
+ constructor(status, data, requestId) {
75
162
  super(getMessage(data));
76
163
  this.status = status;
77
164
  this.errors = isBulkError(data) ? data.errors : void 0;
165
+ this.requestId = requestId;
78
166
  if (data instanceof Error) {
79
167
  this.stack = data.stack;
80
168
  this.cause = data.cause;
81
169
  }
82
170
  }
171
+ toString() {
172
+ const error = super.toString();
173
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
174
+ }
83
175
  }
84
176
  function isBulkError(error) {
85
177
  return isObject(error) && Array.isArray(error.errors);
@@ -102,9 +194,17 @@ function getMessage(data) {
102
194
  }
103
195
 
104
196
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
105
- const query = new URLSearchParams(queryParams).toString();
197
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
198
+ if (value === void 0 || value === null)
199
+ return acc;
200
+ return { ...acc, [key]: value };
201
+ }, {});
202
+ const query = new URLSearchParams(cleanQueryParams).toString();
106
203
  const queryString = query.length > 0 ? `?${query}` : "";
107
- return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
204
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
205
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
206
+ }, {});
207
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
108
208
  };
109
209
  function buildBaseUrl({
110
210
  path,
@@ -112,10 +212,10 @@ function buildBaseUrl({
112
212
  apiUrl,
113
213
  pathParams
114
214
  }) {
115
- if (!pathParams?.workspace)
215
+ if (pathParams?.workspace === void 0)
116
216
  return `${apiUrl}${path}`;
117
217
  const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
118
- return url.replace("{workspaceId}", pathParams.workspace);
218
+ return url.replace("{workspaceId}", String(pathParams.workspace));
119
219
  }
120
220
  function hostHeader(url) {
121
221
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
@@ -132,249 +232,364 @@ async function fetch$1({
132
232
  fetchImpl,
133
233
  apiKey,
134
234
  apiUrl,
135
- workspacesApiUrl
235
+ workspacesApiUrl,
236
+ trace,
237
+ signal
136
238
  }) {
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
- }
239
+ return trace(
240
+ `${method.toUpperCase()} ${path}`,
241
+ async ({ setAttributes }) => {
242
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
243
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
244
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
245
+ setAttributes({
246
+ [TraceAttributes.HTTP_URL]: url,
247
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
248
+ });
249
+ const response = await fetchImpl(url, {
250
+ method: method.toUpperCase(),
251
+ body: body ? JSON.stringify(body) : void 0,
252
+ headers: {
253
+ "Content-Type": "application/json",
254
+ "User-Agent": `Xata client-ts/${VERSION}`,
255
+ ...headers,
256
+ ...hostHeader(fullUrl),
257
+ Authorization: `Bearer ${apiKey}`
258
+ },
259
+ signal
260
+ });
261
+ if (response.status === 204) {
262
+ return {};
263
+ }
264
+ const { host, protocol } = parseUrl(response.url);
265
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
266
+ setAttributes({
267
+ [TraceAttributes.KIND]: "http",
268
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
269
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
270
+ [TraceAttributes.HTTP_HOST]: host,
271
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
272
+ });
273
+ try {
274
+ const jsonResponse = await response.json();
275
+ if (response.ok) {
276
+ return jsonResponse;
277
+ }
278
+ throw new FetcherError(response.status, jsonResponse, requestId);
279
+ } catch (error) {
280
+ throw new FetcherError(response.status, error, requestId);
281
+ }
282
+ },
283
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
284
+ );
285
+ }
286
+ function parseUrl(url) {
153
287
  try {
154
- const jsonResponse = await response.json();
155
- if (response.ok) {
156
- return jsonResponse;
157
- }
158
- throw new FetcherError(response.status, jsonResponse);
288
+ const { host, protocol } = new URL(url);
289
+ return { host, protocol };
159
290
  } catch (error) {
160
- throw new FetcherError(response.status, error);
291
+ return {};
161
292
  }
162
293
  }
163
294
 
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({
295
+ const getUser = (variables, signal) => fetch$1({ url: "/user", method: "get", ...variables, signal });
296
+ const updateUser = (variables, signal) => fetch$1({
297
+ url: "/user",
298
+ method: "put",
299
+ ...variables,
300
+ signal
301
+ });
302
+ const deleteUser = (variables, signal) => fetch$1({ url: "/user", method: "delete", ...variables, signal });
303
+ const getUserAPIKeys = (variables, signal) => fetch$1({
168
304
  url: "/user/keys",
169
305
  method: "get",
170
- ...variables
306
+ ...variables,
307
+ signal
171
308
  });
172
- const createUserAPIKey = (variables) => fetch$1({
309
+ const createUserAPIKey = (variables, signal) => fetch$1({
173
310
  url: "/user/keys/{keyName}",
174
311
  method: "post",
175
- ...variables
312
+ ...variables,
313
+ signal
176
314
  });
177
- const deleteUserAPIKey = (variables) => fetch$1({
315
+ const deleteUserAPIKey = (variables, signal) => fetch$1({
178
316
  url: "/user/keys/{keyName}",
179
317
  method: "delete",
180
- ...variables
318
+ ...variables,
319
+ signal
181
320
  });
182
- const createWorkspace = (variables) => fetch$1({
321
+ const createWorkspace = (variables, signal) => fetch$1({
183
322
  url: "/workspaces",
184
323
  method: "post",
185
- ...variables
324
+ ...variables,
325
+ signal
186
326
  });
187
- const getWorkspacesList = (variables) => fetch$1({
327
+ const getWorkspacesList = (variables, signal) => fetch$1({
188
328
  url: "/workspaces",
189
329
  method: "get",
190
- ...variables
330
+ ...variables,
331
+ signal
191
332
  });
192
- const getWorkspace = (variables) => fetch$1({
333
+ const getWorkspace = (variables, signal) => fetch$1({
193
334
  url: "/workspaces/{workspaceId}",
194
335
  method: "get",
195
- ...variables
336
+ ...variables,
337
+ signal
196
338
  });
197
- const updateWorkspace = (variables) => fetch$1({
339
+ const updateWorkspace = (variables, signal) => fetch$1({
198
340
  url: "/workspaces/{workspaceId}",
199
341
  method: "put",
200
- ...variables
342
+ ...variables,
343
+ signal
201
344
  });
202
- const deleteWorkspace = (variables) => fetch$1({
345
+ const deleteWorkspace = (variables, signal) => fetch$1({
203
346
  url: "/workspaces/{workspaceId}",
204
347
  method: "delete",
205
- ...variables
348
+ ...variables,
349
+ signal
206
350
  });
207
- const getWorkspaceMembersList = (variables) => fetch$1({
351
+ const getWorkspaceMembersList = (variables, signal) => fetch$1({
208
352
  url: "/workspaces/{workspaceId}/members",
209
353
  method: "get",
210
- ...variables
354
+ ...variables,
355
+ signal
211
356
  });
212
- const updateWorkspaceMemberRole = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables });
213
- const removeWorkspaceMember = (variables) => fetch$1({
357
+ const updateWorkspaceMemberRole = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables, signal });
358
+ const removeWorkspaceMember = (variables, signal) => fetch$1({
214
359
  url: "/workspaces/{workspaceId}/members/{userId}",
215
360
  method: "delete",
216
- ...variables
361
+ ...variables,
362
+ signal
217
363
  });
218
- const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
219
- const cancelWorkspaceMemberInvite = (variables) => fetch$1({
364
+ const inviteWorkspaceMember = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables, signal });
365
+ const updateWorkspaceMemberInvite = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables, signal });
366
+ const cancelWorkspaceMemberInvite = (variables, signal) => fetch$1({
220
367
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
221
368
  method: "delete",
222
- ...variables
369
+ ...variables,
370
+ signal
223
371
  });
224
- const resendWorkspaceMemberInvite = (variables) => fetch$1({
372
+ const resendWorkspaceMemberInvite = (variables, signal) => fetch$1({
225
373
  url: "/workspaces/{workspaceId}/invites/{inviteId}/resend",
226
374
  method: "post",
227
- ...variables
375
+ ...variables,
376
+ signal
228
377
  });
229
- const acceptWorkspaceMemberInvite = (variables) => fetch$1({
378
+ const acceptWorkspaceMemberInvite = (variables, signal) => fetch$1({
230
379
  url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept",
231
380
  method: "post",
232
- ...variables
381
+ ...variables,
382
+ signal
233
383
  });
234
- const getDatabaseList = (variables) => fetch$1({
384
+ const getDatabaseList = (variables, signal) => fetch$1({
235
385
  url: "/dbs",
236
386
  method: "get",
237
- ...variables
387
+ ...variables,
388
+ signal
238
389
  });
239
- const getBranchList = (variables) => fetch$1({
390
+ const getBranchList = (variables, signal) => fetch$1({
240
391
  url: "/dbs/{dbName}",
241
392
  method: "get",
242
- ...variables
393
+ ...variables,
394
+ signal
243
395
  });
244
- const createDatabase = (variables) => fetch$1({
396
+ const createDatabase = (variables, signal) => fetch$1({
245
397
  url: "/dbs/{dbName}",
246
398
  method: "put",
247
- ...variables
399
+ ...variables,
400
+ signal
248
401
  });
249
- const deleteDatabase = (variables) => fetch$1({
402
+ const deleteDatabase = (variables, signal) => fetch$1({
250
403
  url: "/dbs/{dbName}",
251
404
  method: "delete",
252
- ...variables
405
+ ...variables,
406
+ signal
407
+ });
408
+ const getDatabaseMetadata = (variables, signal) => fetch$1({
409
+ url: "/dbs/{dbName}/metadata",
410
+ method: "get",
411
+ ...variables,
412
+ signal
253
413
  });
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({
414
+ const updateDatabaseMetadata = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
415
+ const getGitBranchesMapping = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables, signal });
416
+ const addGitBranchesEntry = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables, signal });
417
+ const removeGitBranchesEntry = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables, signal });
418
+ const resolveBranch = (variables, signal) => fetch$1({
258
419
  url: "/dbs/{dbName}/resolveBranch",
259
420
  method: "get",
260
- ...variables
421
+ ...variables,
422
+ signal
261
423
  });
262
- const getBranchDetails = (variables) => fetch$1({
263
- url: "/db/{dbBranchName}",
424
+ const queryMigrationRequests = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
425
+ const createMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
426
+ const getMigrationRequest = (variables, signal) => fetch$1({
427
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
264
428
  method: "get",
265
- ...variables
429
+ ...variables,
430
+ signal
431
+ });
432
+ const updateMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables, signal });
433
+ const listMigrationRequestsCommits = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables, signal });
434
+ const compareMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables, signal });
435
+ const getMigrationRequestIsMerged = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables, signal });
436
+ const mergeMigrationRequest = (variables, signal) => fetch$1({
437
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
438
+ method: "post",
439
+ ...variables,
440
+ signal
266
441
  });
267
- const createBranch = (variables) => fetch$1({
442
+ const getBranchDetails = (variables, signal) => fetch$1({
268
443
  url: "/db/{dbBranchName}",
269
- method: "put",
270
- ...variables
444
+ method: "get",
445
+ ...variables,
446
+ signal
271
447
  });
272
- const deleteBranch = (variables) => fetch$1({
448
+ const createBranch = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
449
+ const deleteBranch = (variables, signal) => fetch$1({
273
450
  url: "/db/{dbBranchName}",
274
451
  method: "delete",
275
- ...variables
452
+ ...variables,
453
+ signal
276
454
  });
277
- const updateBranchMetadata = (variables) => fetch$1({
455
+ const updateBranchMetadata = (variables, signal) => fetch$1({
278
456
  url: "/db/{dbBranchName}/metadata",
279
457
  method: "put",
280
- ...variables
458
+ ...variables,
459
+ signal
281
460
  });
282
- const getBranchMetadata = (variables) => fetch$1({
461
+ const getBranchMetadata = (variables, signal) => fetch$1({
283
462
  url: "/db/{dbBranchName}/metadata",
284
463
  method: "get",
285
- ...variables
464
+ ...variables,
465
+ signal
466
+ });
467
+ const getBranchMigrationHistory = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
468
+ const executeBranchMigrationPlan = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
469
+ const getBranchMigrationPlan = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
470
+ const compareBranchWithUserSchema = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables, signal });
471
+ const compareBranchSchemas = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables, signal });
472
+ const updateBranchSchema = (variables, signal) => fetch$1({
473
+ url: "/db/{dbBranchName}/schema/update",
474
+ method: "post",
475
+ ...variables,
476
+ signal
286
477
  });
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({
478
+ const previewBranchSchemaEdit = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
479
+ const applyBranchSchemaEdit = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
480
+ const getBranchSchemaHistory = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables, signal });
481
+ const getBranchStats = (variables, signal) => fetch$1({
291
482
  url: "/db/{dbBranchName}/stats",
292
483
  method: "get",
293
- ...variables
484
+ ...variables,
485
+ signal
294
486
  });
295
- const createTable = (variables) => fetch$1({
487
+ const createTable = (variables, signal) => fetch$1({
296
488
  url: "/db/{dbBranchName}/tables/{tableName}",
297
489
  method: "put",
298
- ...variables
490
+ ...variables,
491
+ signal
299
492
  });
300
- const deleteTable = (variables) => fetch$1({
493
+ const deleteTable = (variables, signal) => fetch$1({
301
494
  url: "/db/{dbBranchName}/tables/{tableName}",
302
495
  method: "delete",
303
- ...variables
496
+ ...variables,
497
+ signal
304
498
  });
305
- const updateTable = (variables) => fetch$1({
499
+ const updateTable = (variables, signal) => fetch$1({
306
500
  url: "/db/{dbBranchName}/tables/{tableName}",
307
501
  method: "patch",
308
- ...variables
502
+ ...variables,
503
+ signal
309
504
  });
310
- const getTableSchema = (variables) => fetch$1({
505
+ const getTableSchema = (variables, signal) => fetch$1({
311
506
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
312
507
  method: "get",
313
- ...variables
508
+ ...variables,
509
+ signal
314
510
  });
315
- const setTableSchema = (variables) => fetch$1({
511
+ const setTableSchema = (variables, signal) => fetch$1({
316
512
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
317
513
  method: "put",
318
- ...variables
514
+ ...variables,
515
+ signal
319
516
  });
320
- const getTableColumns = (variables) => fetch$1({
517
+ const getTableColumns = (variables, signal) => fetch$1({
321
518
  url: "/db/{dbBranchName}/tables/{tableName}/columns",
322
519
  method: "get",
323
- ...variables
520
+ ...variables,
521
+ signal
324
522
  });
325
- const addTableColumn = (variables) => fetch$1({
523
+ const addTableColumn = (variables, signal) => fetch$1({
326
524
  url: "/db/{dbBranchName}/tables/{tableName}/columns",
327
525
  method: "post",
328
- ...variables
526
+ ...variables,
527
+ signal
329
528
  });
330
- const getColumn = (variables) => fetch$1({
529
+ const getColumn = (variables, signal) => fetch$1({
331
530
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
332
531
  method: "get",
333
- ...variables
532
+ ...variables,
533
+ signal
334
534
  });
335
- const deleteColumn = (variables) => fetch$1({
535
+ const deleteColumn = (variables, signal) => fetch$1({
336
536
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
337
537
  method: "delete",
338
- ...variables
538
+ ...variables,
539
+ signal
339
540
  });
340
- const updateColumn = (variables) => fetch$1({
541
+ const updateColumn = (variables, signal) => fetch$1({
341
542
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
342
543
  method: "patch",
343
- ...variables
344
- });
345
- const insertRecord = (variables) => fetch$1({
346
- url: "/db/{dbBranchName}/tables/{tableName}/data",
347
- method: "post",
348
- ...variables
544
+ ...variables,
545
+ signal
349
546
  });
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({
547
+ const insertRecord = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
548
+ const insertRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables, signal });
549
+ const updateRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables, signal });
550
+ const upsertRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables, signal });
551
+ const deleteRecord = (variables, signal) => fetch$1({
354
552
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
355
553
  method: "delete",
356
- ...variables
554
+ ...variables,
555
+ signal
357
556
  });
358
- const getRecord = (variables) => fetch$1({
557
+ const getRecord = (variables, signal) => fetch$1({
359
558
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
360
559
  method: "get",
361
- ...variables
560
+ ...variables,
561
+ signal
362
562
  });
363
- const bulkInsertTableRecords = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables });
364
- const queryTable = (variables) => fetch$1({
563
+ const bulkInsertTableRecords = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables, signal });
564
+ const queryTable = (variables, signal) => fetch$1({
365
565
  url: "/db/{dbBranchName}/tables/{tableName}/query",
366
566
  method: "post",
367
- ...variables
567
+ ...variables,
568
+ signal
368
569
  });
369
- const searchTable = (variables) => fetch$1({
570
+ const searchTable = (variables, signal) => fetch$1({
370
571
  url: "/db/{dbBranchName}/tables/{tableName}/search",
371
572
  method: "post",
372
- ...variables
573
+ ...variables,
574
+ signal
373
575
  });
374
- const searchBranch = (variables) => fetch$1({
576
+ const searchBranch = (variables, signal) => fetch$1({
375
577
  url: "/db/{dbBranchName}/search",
376
578
  method: "post",
377
- ...variables
579
+ ...variables,
580
+ signal
581
+ });
582
+ const summarizeTable = (variables, signal) => fetch$1({
583
+ url: "/db/{dbBranchName}/tables/{tableName}/summarize",
584
+ method: "post",
585
+ ...variables,
586
+ signal
587
+ });
588
+ const aggregateTable = (variables, signal) => fetch$1({
589
+ url: "/db/{dbBranchName}/tables/{tableName}/aggregate",
590
+ method: "post",
591
+ ...variables,
592
+ signal
378
593
  });
379
594
  const operationsByTag = {
380
595
  users: { getUser, updateUser, deleteUser, getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
@@ -388,6 +603,7 @@ const operationsByTag = {
388
603
  updateWorkspaceMemberRole,
389
604
  removeWorkspaceMember,
390
605
  inviteWorkspaceMember,
606
+ updateWorkspaceMemberInvite,
391
607
  cancelWorkspaceMemberInvite,
392
608
  resendWorkspaceMemberInvite,
393
609
  acceptWorkspaceMemberInvite
@@ -396,6 +612,8 @@ const operationsByTag = {
396
612
  getDatabaseList,
397
613
  createDatabase,
398
614
  deleteDatabase,
615
+ getDatabaseMetadata,
616
+ updateDatabaseMetadata,
399
617
  getGitBranchesMapping,
400
618
  addGitBranchesEntry,
401
619
  removeGitBranchesEntry,
@@ -408,10 +626,28 @@ const operationsByTag = {
408
626
  deleteBranch,
409
627
  updateBranchMetadata,
410
628
  getBranchMetadata,
629
+ getBranchStats
630
+ },
631
+ migrationRequests: {
632
+ queryMigrationRequests,
633
+ createMigrationRequest,
634
+ getMigrationRequest,
635
+ updateMigrationRequest,
636
+ listMigrationRequestsCommits,
637
+ compareMigrationRequest,
638
+ getMigrationRequestIsMerged,
639
+ mergeMigrationRequest
640
+ },
641
+ branchSchema: {
411
642
  getBranchMigrationHistory,
412
643
  executeBranchMigrationPlan,
413
644
  getBranchMigrationPlan,
414
- getBranchStats
645
+ compareBranchWithUserSchema,
646
+ compareBranchSchemas,
647
+ updateBranchSchema,
648
+ previewBranchSchemaEdit,
649
+ applyBranchSchemaEdit,
650
+ getBranchSchemaHistory
415
651
  },
416
652
  table: {
417
653
  createTable,
@@ -435,14 +671,16 @@ const operationsByTag = {
435
671
  bulkInsertTableRecords,
436
672
  queryTable,
437
673
  searchTable,
438
- searchBranch
674
+ searchBranch,
675
+ summarizeTable,
676
+ aggregateTable
439
677
  }
440
678
  };
441
679
 
442
680
  function getHostUrl(provider, type) {
443
- if (isValidAlias(provider)) {
681
+ if (isHostProviderAlias(provider)) {
444
682
  return providers[provider][type];
445
- } else if (isValidBuilder(provider)) {
683
+ } else if (isHostProviderBuilder(provider)) {
446
684
  return provider[type];
447
685
  }
448
686
  throw new Error("Invalid API provider");
@@ -457,12 +695,21 @@ const providers = {
457
695
  workspaces: "https://{workspaceId}.staging.xatabase.co"
458
696
  }
459
697
  };
460
- function isValidAlias(alias) {
698
+ function isHostProviderAlias(alias) {
461
699
  return isString(alias) && Object.keys(providers).includes(alias);
462
700
  }
463
- function isValidBuilder(builder) {
701
+ function isHostProviderBuilder(builder) {
464
702
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
465
703
  }
704
+ function parseProviderString(provider = "production") {
705
+ if (isHostProviderAlias(provider)) {
706
+ return provider;
707
+ }
708
+ const [main, workspaces] = provider.split(",");
709
+ if (!main || !workspaces)
710
+ return null;
711
+ return { main, workspaces };
712
+ }
466
713
 
467
714
  var __accessCheck$7 = (obj, member, msg) => {
468
715
  if (!member.has(obj))
@@ -477,7 +724,7 @@ var __privateAdd$7 = (obj, member, value) => {
477
724
  throw TypeError("Cannot add the same private member more than once");
478
725
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
479
726
  };
480
- var __privateSet$6 = (obj, member, value, setter) => {
727
+ var __privateSet$7 = (obj, member, value, setter) => {
481
728
  __accessCheck$7(obj, member, "write to private field");
482
729
  setter ? setter.call(obj, value) : member.set(obj, value);
483
730
  return value;
@@ -488,15 +735,17 @@ class XataApiClient {
488
735
  __privateAdd$7(this, _extraProps, void 0);
489
736
  __privateAdd$7(this, _namespaces, {});
490
737
  const provider = options.host ?? "production";
491
- const apiKey = options?.apiKey ?? getAPIKey();
738
+ const apiKey = options.apiKey ?? getAPIKey();
739
+ const trace = options.trace ?? defaultTrace;
492
740
  if (!apiKey) {
493
741
  throw new Error("Could not resolve a valid apiKey");
494
742
  }
495
- __privateSet$6(this, _extraProps, {
743
+ __privateSet$7(this, _extraProps, {
496
744
  apiUrl: getHostUrl(provider, "main"),
497
745
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
498
746
  fetchImpl: getFetchImplementation(options.fetch),
499
- apiKey
747
+ apiKey,
748
+ trace
500
749
  });
501
750
  }
502
751
  get user() {
@@ -529,6 +778,16 @@ class XataApiClient {
529
778
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
530
779
  return __privateGet$7(this, _namespaces).records;
531
780
  }
781
+ get migrationRequests() {
782
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
783
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
784
+ return __privateGet$7(this, _namespaces).migrationRequests;
785
+ }
786
+ get branchSchema() {
787
+ if (!__privateGet$7(this, _namespaces).branchSchema)
788
+ __privateGet$7(this, _namespaces).branchSchema = new BranchSchemaApi(__privateGet$7(this, _extraProps));
789
+ return __privateGet$7(this, _namespaces).branchSchema;
790
+ }
532
791
  }
533
792
  _extraProps = new WeakMap();
534
793
  _namespaces = new WeakMap();
@@ -619,6 +878,13 @@ class WorkspaceApi {
619
878
  ...this.extraProps
620
879
  });
621
880
  }
881
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
882
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
883
+ pathParams: { workspaceId, inviteId },
884
+ body: { role },
885
+ ...this.extraProps
886
+ });
887
+ }
622
888
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
623
889
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
624
890
  pathParams: { workspaceId, inviteId },
@@ -661,6 +927,19 @@ class DatabaseApi {
661
927
  ...this.extraProps
662
928
  });
663
929
  }
930
+ getDatabaseMetadata(workspace, dbName) {
931
+ return operationsByTag.database.getDatabaseMetadata({
932
+ pathParams: { workspace, dbName },
933
+ ...this.extraProps
934
+ });
935
+ }
936
+ updateDatabaseMetadata(workspace, dbName, options = {}) {
937
+ return operationsByTag.database.updateDatabaseMetadata({
938
+ pathParams: { workspace, dbName },
939
+ body: options,
940
+ ...this.extraProps
941
+ });
942
+ }
664
943
  getGitBranchesMapping(workspace, dbName) {
665
944
  return operationsByTag.database.getGitBranchesMapping({
666
945
  pathParams: { workspace, dbName },
@@ -681,10 +960,10 @@ class DatabaseApi {
681
960
  ...this.extraProps
682
961
  });
683
962
  }
684
- resolveBranch(workspace, dbName, gitBranch) {
963
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
685
964
  return operationsByTag.database.resolveBranch({
686
965
  pathParams: { workspace, dbName },
687
- queryParams: { gitBranch },
966
+ queryParams: { gitBranch, fallbackBranch },
688
967
  ...this.extraProps
689
968
  });
690
969
  }
@@ -732,27 +1011,6 @@ class BranchApi {
732
1011
  ...this.extraProps
733
1012
  });
734
1013
  }
735
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
736
- return operationsByTag.branch.getBranchMigrationHistory({
737
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
738
- body: options,
739
- ...this.extraProps
740
- });
741
- }
742
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
743
- return operationsByTag.branch.executeBranchMigrationPlan({
744
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
745
- body: migrationPlan,
746
- ...this.extraProps
747
- });
748
- }
749
- getBranchMigrationPlan(workspace, database, branch, schema) {
750
- return operationsByTag.branch.getBranchMigrationPlan({
751
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
752
- body: schema,
753
- ...this.extraProps
754
- });
755
- }
756
1014
  getBranchStats(workspace, database, branch) {
757
1015
  return operationsByTag.branch.getBranchStats({
758
1016
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -833,9 +1091,10 @@ class RecordsApi {
833
1091
  constructor(extraProps) {
834
1092
  this.extraProps = extraProps;
835
1093
  }
836
- insertRecord(workspace, database, branch, tableName, record) {
1094
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
837
1095
  return operationsByTag.records.insertRecord({
838
1096
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1097
+ queryParams: options,
839
1098
  body: record,
840
1099
  ...this.extraProps
841
1100
  });
@@ -864,21 +1123,24 @@ class RecordsApi {
864
1123
  ...this.extraProps
865
1124
  });
866
1125
  }
867
- deleteRecord(workspace, database, branch, tableName, recordId) {
1126
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
868
1127
  return operationsByTag.records.deleteRecord({
869
1128
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1129
+ queryParams: options,
870
1130
  ...this.extraProps
871
1131
  });
872
1132
  }
873
1133
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
874
1134
  return operationsByTag.records.getRecord({
875
1135
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1136
+ queryParams: options,
876
1137
  ...this.extraProps
877
1138
  });
878
1139
  }
879
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1140
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
880
1141
  return operationsByTag.records.bulkInsertTableRecords({
881
1142
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1143
+ queryParams: options,
882
1144
  body: { records },
883
1145
  ...this.extraProps
884
1146
  });
@@ -904,6 +1166,145 @@ class RecordsApi {
904
1166
  ...this.extraProps
905
1167
  });
906
1168
  }
1169
+ summarizeTable(workspace, database, branch, tableName, query) {
1170
+ return operationsByTag.records.summarizeTable({
1171
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1172
+ body: query,
1173
+ ...this.extraProps
1174
+ });
1175
+ }
1176
+ aggregateTable(workspace, database, branch, tableName, query) {
1177
+ return operationsByTag.records.aggregateTable({
1178
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1179
+ body: query,
1180
+ ...this.extraProps
1181
+ });
1182
+ }
1183
+ }
1184
+ class MigrationRequestsApi {
1185
+ constructor(extraProps) {
1186
+ this.extraProps = extraProps;
1187
+ }
1188
+ queryMigrationRequests(workspace, database, options = {}) {
1189
+ return operationsByTag.migrationRequests.queryMigrationRequests({
1190
+ pathParams: { workspace, dbName: database },
1191
+ body: options,
1192
+ ...this.extraProps
1193
+ });
1194
+ }
1195
+ createMigrationRequest(workspace, database, options) {
1196
+ return operationsByTag.migrationRequests.createMigrationRequest({
1197
+ pathParams: { workspace, dbName: database },
1198
+ body: options,
1199
+ ...this.extraProps
1200
+ });
1201
+ }
1202
+ getMigrationRequest(workspace, database, migrationRequest) {
1203
+ return operationsByTag.migrationRequests.getMigrationRequest({
1204
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1205
+ ...this.extraProps
1206
+ });
1207
+ }
1208
+ updateMigrationRequest(workspace, database, migrationRequest, options) {
1209
+ return operationsByTag.migrationRequests.updateMigrationRequest({
1210
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1211
+ body: options,
1212
+ ...this.extraProps
1213
+ });
1214
+ }
1215
+ listMigrationRequestsCommits(workspace, database, migrationRequest, options = {}) {
1216
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1217
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1218
+ body: options,
1219
+ ...this.extraProps
1220
+ });
1221
+ }
1222
+ compareMigrationRequest(workspace, database, migrationRequest) {
1223
+ return operationsByTag.migrationRequests.compareMigrationRequest({
1224
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1225
+ ...this.extraProps
1226
+ });
1227
+ }
1228
+ getMigrationRequestIsMerged(workspace, database, migrationRequest) {
1229
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1230
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1231
+ ...this.extraProps
1232
+ });
1233
+ }
1234
+ mergeMigrationRequest(workspace, database, migrationRequest) {
1235
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
1236
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1237
+ ...this.extraProps
1238
+ });
1239
+ }
1240
+ }
1241
+ class BranchSchemaApi {
1242
+ constructor(extraProps) {
1243
+ this.extraProps = extraProps;
1244
+ }
1245
+ getBranchMigrationHistory(workspace, database, branch, options = {}) {
1246
+ return operationsByTag.branchSchema.getBranchMigrationHistory({
1247
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1248
+ body: options,
1249
+ ...this.extraProps
1250
+ });
1251
+ }
1252
+ executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
1253
+ return operationsByTag.branchSchema.executeBranchMigrationPlan({
1254
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1255
+ body: migrationPlan,
1256
+ ...this.extraProps
1257
+ });
1258
+ }
1259
+ getBranchMigrationPlan(workspace, database, branch, schema) {
1260
+ return operationsByTag.branchSchema.getBranchMigrationPlan({
1261
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1262
+ body: schema,
1263
+ ...this.extraProps
1264
+ });
1265
+ }
1266
+ compareBranchWithUserSchema(workspace, database, branch, schema) {
1267
+ return operationsByTag.branchSchema.compareBranchWithUserSchema({
1268
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1269
+ body: { schema },
1270
+ ...this.extraProps
1271
+ });
1272
+ }
1273
+ compareBranchSchemas(workspace, database, branch, branchName, schema) {
1274
+ return operationsByTag.branchSchema.compareBranchSchemas({
1275
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, branchName },
1276
+ body: { schema },
1277
+ ...this.extraProps
1278
+ });
1279
+ }
1280
+ updateBranchSchema(workspace, database, branch, migration) {
1281
+ return operationsByTag.branchSchema.updateBranchSchema({
1282
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1283
+ body: migration,
1284
+ ...this.extraProps
1285
+ });
1286
+ }
1287
+ previewBranchSchemaEdit(workspace, database, branch, migration) {
1288
+ return operationsByTag.branchSchema.previewBranchSchemaEdit({
1289
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1290
+ body: migration,
1291
+ ...this.extraProps
1292
+ });
1293
+ }
1294
+ applyBranchSchemaEdit(workspace, database, branch, edits) {
1295
+ return operationsByTag.branchSchema.applyBranchSchemaEdit({
1296
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1297
+ body: { edits },
1298
+ ...this.extraProps
1299
+ });
1300
+ }
1301
+ getBranchSchemaHistory(workspace, database, branch, options = {}) {
1302
+ return operationsByTag.branchSchema.getBranchSchemaHistory({
1303
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1304
+ body: options,
1305
+ ...this.extraProps
1306
+ });
1307
+ }
907
1308
  }
908
1309
 
909
1310
  class XataApiPlugin {
@@ -916,6 +1317,13 @@ class XataApiPlugin {
916
1317
  class XataPlugin {
917
1318
  }
918
1319
 
1320
+ function cleanFilter(filter) {
1321
+ if (!filter)
1322
+ return void 0;
1323
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1324
+ return values.length > 0 ? filter : void 0;
1325
+ }
1326
+
919
1327
  var __accessCheck$6 = (obj, member, msg) => {
920
1328
  if (!member.has(obj))
921
1329
  throw TypeError("Cannot " + msg);
@@ -929,18 +1337,18 @@ var __privateAdd$6 = (obj, member, value) => {
929
1337
  throw TypeError("Cannot add the same private member more than once");
930
1338
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
931
1339
  };
932
- var __privateSet$5 = (obj, member, value, setter) => {
1340
+ var __privateSet$6 = (obj, member, value, setter) => {
933
1341
  __accessCheck$6(obj, member, "write to private field");
934
1342
  setter ? setter.call(obj, value) : member.set(obj, value);
935
1343
  return value;
936
1344
  };
937
- var _query;
1345
+ var _query, _page;
938
1346
  class Page {
939
1347
  constructor(query, meta, records = []) {
940
1348
  __privateAdd$6(this, _query, void 0);
941
- __privateSet$5(this, _query, query);
1349
+ __privateSet$6(this, _query, query);
942
1350
  this.meta = meta;
943
- this.records = records;
1351
+ this.records = new RecordArray(this, records);
944
1352
  }
945
1353
  async nextPage(size, offset) {
946
1354
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
@@ -960,9 +1368,56 @@ class Page {
960
1368
  }
961
1369
  _query = new WeakMap();
962
1370
  const PAGINATION_MAX_SIZE = 200;
963
- const PAGINATION_DEFAULT_SIZE = 200;
1371
+ const PAGINATION_DEFAULT_SIZE = 20;
964
1372
  const PAGINATION_MAX_OFFSET = 800;
965
1373
  const PAGINATION_DEFAULT_OFFSET = 0;
1374
+ function isCursorPaginationOptions(options) {
1375
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1376
+ }
1377
+ const _RecordArray = class extends Array {
1378
+ constructor(...args) {
1379
+ super(..._RecordArray.parseConstructorParams(...args));
1380
+ __privateAdd$6(this, _page, void 0);
1381
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1382
+ }
1383
+ static parseConstructorParams(...args) {
1384
+ if (args.length === 1 && typeof args[0] === "number") {
1385
+ return new Array(args[0]);
1386
+ }
1387
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1388
+ const result = args[1] ?? args[0].records ?? [];
1389
+ return new Array(...result);
1390
+ }
1391
+ return new Array(...args);
1392
+ }
1393
+ toArray() {
1394
+ return new Array(...this);
1395
+ }
1396
+ map(callbackfn, thisArg) {
1397
+ return this.toArray().map(callbackfn, thisArg);
1398
+ }
1399
+ async nextPage(size, offset) {
1400
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1401
+ return new _RecordArray(newPage);
1402
+ }
1403
+ async previousPage(size, offset) {
1404
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1405
+ return new _RecordArray(newPage);
1406
+ }
1407
+ async firstPage(size, offset) {
1408
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1409
+ return new _RecordArray(newPage);
1410
+ }
1411
+ async lastPage(size, offset) {
1412
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1413
+ return new _RecordArray(newPage);
1414
+ }
1415
+ hasNextPage() {
1416
+ return __privateGet$6(this, _page).meta.page.more;
1417
+ }
1418
+ };
1419
+ let RecordArray = _RecordArray;
1420
+ _page = new WeakMap();
966
1421
 
967
1422
  var __accessCheck$5 = (obj, member, msg) => {
968
1423
  if (!member.has(obj))
@@ -977,32 +1432,38 @@ var __privateAdd$5 = (obj, member, value) => {
977
1432
  throw TypeError("Cannot add the same private member more than once");
978
1433
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
979
1434
  };
980
- var __privateSet$4 = (obj, member, value, setter) => {
1435
+ var __privateSet$5 = (obj, member, value, setter) => {
981
1436
  __accessCheck$5(obj, member, "write to private field");
982
1437
  setter ? setter.call(obj, value) : member.set(obj, value);
983
1438
  return value;
984
1439
  };
985
- var _table$1, _repository, _data;
1440
+ var __privateMethod$3 = (obj, member, method) => {
1441
+ __accessCheck$5(obj, member, "access private method");
1442
+ return method;
1443
+ };
1444
+ var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
986
1445
  const _Query = class {
987
- constructor(repository, table, data, parent) {
1446
+ constructor(repository, table, data, rawParent) {
1447
+ __privateAdd$5(this, _cleanFilterConstraint);
988
1448
  __privateAdd$5(this, _table$1, void 0);
989
1449
  __privateAdd$5(this, _repository, void 0);
990
1450
  __privateAdd$5(this, _data, { filter: {} });
991
1451
  this.meta = { page: { cursor: "start", more: true } };
992
- this.records = [];
993
- __privateSet$4(this, _table$1, table);
1452
+ this.records = new RecordArray(this, []);
1453
+ __privateSet$5(this, _table$1, table);
994
1454
  if (repository) {
995
- __privateSet$4(this, _repository, repository);
1455
+ __privateSet$5(this, _repository, repository);
996
1456
  } else {
997
- __privateSet$4(this, _repository, this);
1457
+ __privateSet$5(this, _repository, this);
998
1458
  }
1459
+ const parent = cleanParent(data, rawParent);
999
1460
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1000
1461
  __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1001
1462
  __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1002
1463
  __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1003
1464
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1004
1465
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1005
- __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1466
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
1006
1467
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1007
1468
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
1008
1469
  this.any = this.any.bind(this);
@@ -1040,21 +1501,29 @@ const _Query = class {
1040
1501
  }
1041
1502
  filter(a, b) {
1042
1503
  if (arguments.length === 1) {
1043
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1504
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
1505
+ [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
1506
+ }));
1044
1507
  const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1045
1508
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1046
1509
  } else {
1047
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1510
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
1511
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1048
1512
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1049
1513
  }
1050
1514
  }
1051
- sort(column, direction) {
1515
+ sort(column, direction = "asc") {
1052
1516
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1053
1517
  const sort = [...originalSort, { column, direction }];
1054
1518
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1055
1519
  }
1056
1520
  select(columns) {
1057
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1521
+ return new _Query(
1522
+ __privateGet$5(this, _repository),
1523
+ __privateGet$5(this, _table$1),
1524
+ { columns },
1525
+ __privateGet$5(this, _data)
1526
+ );
1058
1527
  }
1059
1528
  getPaginated(options = {}) {
1060
1529
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1067,18 +1536,30 @@ const _Query = class {
1067
1536
  }
1068
1537
  async *getIterator(options = {}) {
1069
1538
  const { batchSize = 1 } = options;
1070
- let offset = 0;
1071
- let end = false;
1072
- while (!end) {
1073
- const { records, meta } = await this.getPaginated({ ...options, pagination: { size: batchSize, offset } });
1074
- yield records;
1075
- offset += batchSize;
1076
- end = !meta.page.more;
1539
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1540
+ let more = page.hasNextPage();
1541
+ yield page.records;
1542
+ while (more) {
1543
+ page = await page.nextPage();
1544
+ more = page.hasNextPage();
1545
+ yield page.records;
1077
1546
  }
1078
1547
  }
1079
1548
  async getMany(options = {}) {
1080
- const { records } = await this.getPaginated(options);
1081
- return records;
1549
+ const { pagination = {}, ...rest } = options;
1550
+ const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
1551
+ const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
1552
+ let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
1553
+ const results = [...page.records];
1554
+ while (page.hasNextPage() && results.length < size) {
1555
+ page = await page.nextPage();
1556
+ results.push(...page.records);
1557
+ }
1558
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1559
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1560
+ }
1561
+ const array = new RecordArray(page, results.slice(0, size));
1562
+ return array;
1082
1563
  }
1083
1564
  async getAll(options = {}) {
1084
1565
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1092,6 +1573,22 @@ const _Query = class {
1092
1573
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1093
1574
  return records[0] ?? null;
1094
1575
  }
1576
+ async getFirstOrThrow(options = {}) {
1577
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1578
+ if (records[0] === void 0)
1579
+ throw new Error("No results found.");
1580
+ return records[0];
1581
+ }
1582
+ async summarize(params = {}) {
1583
+ const { summaries, summariesFilter, ...options } = params;
1584
+ const query = new _Query(
1585
+ __privateGet$5(this, _repository),
1586
+ __privateGet$5(this, _table$1),
1587
+ options,
1588
+ __privateGet$5(this, _data)
1589
+ );
1590
+ return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
1591
+ }
1095
1592
  cache(ttl) {
1096
1593
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1097
1594
  }
@@ -1115,12 +1612,31 @@ let Query = _Query;
1115
1612
  _table$1 = new WeakMap();
1116
1613
  _repository = new WeakMap();
1117
1614
  _data = new WeakMap();
1615
+ _cleanFilterConstraint = new WeakSet();
1616
+ cleanFilterConstraint_fn = function(column, value) {
1617
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
1618
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
1619
+ return { $includes: value };
1620
+ }
1621
+ if (columnType === "link" && isObject(value) && isString(value.id)) {
1622
+ return value.id;
1623
+ }
1624
+ return value;
1625
+ };
1626
+ function cleanParent(data, parent) {
1627
+ if (isCursorPaginationOptions(data.pagination)) {
1628
+ return { ...parent, sorting: void 0, filter: void 0 };
1629
+ }
1630
+ return parent;
1631
+ }
1118
1632
 
1119
1633
  function isIdentifiable(x) {
1120
1634
  return isObject(x) && isString(x?.id);
1121
1635
  }
1122
1636
  function isXataRecord(x) {
1123
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1637
+ const record = x;
1638
+ const metadata = record?.getMetadata();
1639
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1124
1640
  }
1125
1641
 
1126
1642
  function isSortFilterString(value) {
@@ -1159,7 +1675,7 @@ var __privateAdd$4 = (obj, member, value) => {
1159
1675
  throw TypeError("Cannot add the same private member more than once");
1160
1676
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1161
1677
  };
1162
- var __privateSet$3 = (obj, member, value, setter) => {
1678
+ var __privateSet$4 = (obj, member, value, setter) => {
1163
1679
  __accessCheck$4(obj, member, "write to private field");
1164
1680
  setter ? setter.call(obj, value) : member.set(obj, value);
1165
1681
  return value;
@@ -1168,184 +1684,314 @@ var __privateMethod$2 = (obj, member, method) => {
1168
1684
  __accessCheck$4(obj, member, "access private method");
1169
1685
  return method;
1170
1686
  };
1171
- var _table, _getFetchProps, _cache, _schema$1, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchema$1, getSchema_fn$1;
1687
+ 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;
1172
1688
  class Repository extends Query {
1173
1689
  }
1174
1690
  class RestRepository extends Query {
1175
1691
  constructor(options) {
1176
- super(null, options.table, {});
1692
+ super(
1693
+ null,
1694
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
1695
+ {}
1696
+ );
1177
1697
  __privateAdd$4(this, _insertRecordWithoutId);
1178
1698
  __privateAdd$4(this, _insertRecordWithId);
1179
1699
  __privateAdd$4(this, _bulkInsertTableRecords);
1180
1700
  __privateAdd$4(this, _updateRecordWithID);
1181
1701
  __privateAdd$4(this, _upsertRecordWithID);
1182
1702
  __privateAdd$4(this, _deleteRecord);
1183
- __privateAdd$4(this, _invalidateCache);
1184
- __privateAdd$4(this, _setCacheRecord);
1185
- __privateAdd$4(this, _getCacheRecord);
1186
1703
  __privateAdd$4(this, _setCacheQuery);
1187
1704
  __privateAdd$4(this, _getCacheQuery);
1188
- __privateAdd$4(this, _getSchema$1);
1705
+ __privateAdd$4(this, _getSchemaTables$1);
1189
1706
  __privateAdd$4(this, _table, void 0);
1190
1707
  __privateAdd$4(this, _getFetchProps, void 0);
1708
+ __privateAdd$4(this, _db, void 0);
1191
1709
  __privateAdd$4(this, _cache, void 0);
1192
- __privateAdd$4(this, _schema$1, void 0);
1193
- __privateSet$3(this, _table, options.table);
1194
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1195
- this.db = options.db;
1196
- __privateSet$3(this, _cache, options.pluginOptions.cache);
1197
- }
1198
- async create(a, b) {
1199
- if (Array.isArray(a)) {
1200
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1201
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1202
- return records;
1203
- }
1204
- if (isString(a) && isObject(b)) {
1205
- if (a === "")
1206
- throw new Error("The id can't be empty");
1207
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1208
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1209
- return record;
1210
- }
1211
- if (isObject(a) && isString(a.id)) {
1212
- if (a.id === "")
1213
- throw new Error("The id can't be empty");
1214
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1215
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1216
- return record;
1217
- }
1218
- if (isObject(a)) {
1219
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1220
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1221
- return record;
1222
- }
1223
- throw new Error("Invalid arguments for create method");
1224
- }
1225
- async read(recordId) {
1226
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1227
- if (cacheRecord)
1228
- return cacheRecord;
1229
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1230
- try {
1231
- const response = await getRecord({
1232
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1233
- ...fetchProps
1710
+ __privateAdd$4(this, _schemaTables$2, void 0);
1711
+ __privateAdd$4(this, _trace, void 0);
1712
+ __privateSet$4(this, _table, options.table);
1713
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1714
+ __privateSet$4(this, _db, options.db);
1715
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1716
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1717
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1718
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1719
+ return trace(name, fn, {
1720
+ ...options2,
1721
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1722
+ [TraceAttributes.KIND]: "sdk-operation",
1723
+ [TraceAttributes.VERSION]: VERSION
1234
1724
  });
1235
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1236
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1237
- } catch (e) {
1238
- if (isObject(e) && e.status === 404) {
1239
- return null;
1725
+ });
1726
+ }
1727
+ async create(a, b, c) {
1728
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1729
+ if (Array.isArray(a)) {
1730
+ if (a.length === 0)
1731
+ return [];
1732
+ const columns = isStringArray(b) ? b : void 0;
1733
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1240
1734
  }
1241
- throw e;
1242
- }
1735
+ if (isString(a) && isObject(b)) {
1736
+ if (a === "")
1737
+ throw new Error("The id can't be empty");
1738
+ const columns = isStringArray(c) ? c : void 0;
1739
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1740
+ }
1741
+ if (isObject(a) && isString(a.id)) {
1742
+ if (a.id === "")
1743
+ throw new Error("The id can't be empty");
1744
+ const columns = isStringArray(b) ? b : void 0;
1745
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1746
+ }
1747
+ if (isObject(a)) {
1748
+ const columns = isStringArray(b) ? b : void 0;
1749
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1750
+ }
1751
+ throw new Error("Invalid arguments for create method");
1752
+ });
1243
1753
  }
1244
- async update(a, b) {
1245
- if (Array.isArray(a)) {
1246
- if (a.length > 100) {
1247
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1754
+ async read(a, b) {
1755
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1756
+ const columns = isStringArray(b) ? b : ["*"];
1757
+ if (Array.isArray(a)) {
1758
+ if (a.length === 0)
1759
+ return [];
1760
+ const ids = a.map((item) => extractId(item));
1761
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1762
+ const dictionary = finalObjects.reduce((acc, object) => {
1763
+ acc[object.id] = object;
1764
+ return acc;
1765
+ }, {});
1766
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1248
1767
  }
1249
- return Promise.all(a.map((object) => this.update(object)));
1250
- }
1251
- if (isString(a) && isObject(b)) {
1252
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1253
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1254
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1255
- return record;
1256
- }
1257
- if (isObject(a) && isString(a.id)) {
1258
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1259
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1260
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1261
- return record;
1262
- }
1263
- throw new Error("Invalid arguments for update method");
1768
+ const id = extractId(a);
1769
+ if (id) {
1770
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1771
+ try {
1772
+ const response = await getRecord({
1773
+ pathParams: {
1774
+ workspace: "{workspaceId}",
1775
+ dbBranchName: "{dbBranch}",
1776
+ tableName: __privateGet$4(this, _table),
1777
+ recordId: id
1778
+ },
1779
+ queryParams: { columns },
1780
+ ...fetchProps
1781
+ });
1782
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1783
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1784
+ } catch (e) {
1785
+ if (isObject(e) && e.status === 404) {
1786
+ return null;
1787
+ }
1788
+ throw e;
1789
+ }
1790
+ }
1791
+ return null;
1792
+ });
1264
1793
  }
1265
- async createOrUpdate(a, b) {
1266
- if (Array.isArray(a)) {
1267
- if (a.length > 100) {
1268
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1794
+ async readOrThrow(a, b) {
1795
+ return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
1796
+ const result = await this.read(a, b);
1797
+ if (Array.isArray(result)) {
1798
+ const missingIds = compact(
1799
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1800
+ );
1801
+ if (missingIds.length > 0) {
1802
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1803
+ }
1804
+ return result;
1269
1805
  }
1270
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1271
- }
1272
- if (isString(a) && isObject(b)) {
1273
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1274
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1275
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1276
- return record;
1277
- }
1278
- if (isObject(a) && isString(a.id)) {
1279
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1280
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1281
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1282
- return record;
1283
- }
1284
- throw new Error("Invalid arguments for createOrUpdate method");
1806
+ if (result === null) {
1807
+ const id = extractId(a) ?? "unknown";
1808
+ throw new Error(`Record with id ${id} not found`);
1809
+ }
1810
+ return result;
1811
+ });
1285
1812
  }
1286
- async delete(a) {
1287
- if (Array.isArray(a)) {
1288
- if (a.length > 100) {
1289
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1813
+ async update(a, b, c) {
1814
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1815
+ if (Array.isArray(a)) {
1816
+ if (a.length === 0)
1817
+ return [];
1818
+ if (a.length > 100) {
1819
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1820
+ }
1821
+ const columns = isStringArray(b) ? b : ["*"];
1822
+ return Promise.all(a.map((object) => this.update(object, columns)));
1290
1823
  }
1291
- await Promise.all(a.map((id) => this.delete(id)));
1292
- return;
1293
- }
1294
- if (isString(a)) {
1295
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1296
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1297
- return;
1298
- }
1299
- if (isObject(a) && isString(a.id)) {
1300
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1301
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1302
- return;
1303
- }
1304
- throw new Error("Invalid arguments for delete method");
1824
+ if (isString(a) && isObject(b)) {
1825
+ const columns = isStringArray(c) ? c : void 0;
1826
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1827
+ }
1828
+ if (isObject(a) && isString(a.id)) {
1829
+ const columns = isStringArray(b) ? b : void 0;
1830
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1831
+ }
1832
+ throw new Error("Invalid arguments for update method");
1833
+ });
1834
+ }
1835
+ async updateOrThrow(a, b, c) {
1836
+ return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
1837
+ const result = await this.update(a, b, c);
1838
+ if (Array.isArray(result)) {
1839
+ const missingIds = compact(
1840
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1841
+ );
1842
+ if (missingIds.length > 0) {
1843
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1844
+ }
1845
+ return result;
1846
+ }
1847
+ if (result === null) {
1848
+ const id = extractId(a) ?? "unknown";
1849
+ throw new Error(`Record with id ${id} not found`);
1850
+ }
1851
+ return result;
1852
+ });
1853
+ }
1854
+ async createOrUpdate(a, b, c) {
1855
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1856
+ if (Array.isArray(a)) {
1857
+ if (a.length === 0)
1858
+ return [];
1859
+ if (a.length > 100) {
1860
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1861
+ }
1862
+ const columns = isStringArray(b) ? b : ["*"];
1863
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1864
+ }
1865
+ if (isString(a) && isObject(b)) {
1866
+ const columns = isStringArray(c) ? c : void 0;
1867
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1868
+ }
1869
+ if (isObject(a) && isString(a.id)) {
1870
+ const columns = isStringArray(c) ? c : void 0;
1871
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1872
+ }
1873
+ throw new Error("Invalid arguments for createOrUpdate method");
1874
+ });
1875
+ }
1876
+ async delete(a, b) {
1877
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1878
+ if (Array.isArray(a)) {
1879
+ if (a.length === 0)
1880
+ return [];
1881
+ if (a.length > 100) {
1882
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1883
+ }
1884
+ return Promise.all(a.map((id) => this.delete(id, b)));
1885
+ }
1886
+ if (isString(a)) {
1887
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1888
+ }
1889
+ if (isObject(a) && isString(a.id)) {
1890
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1891
+ }
1892
+ throw new Error("Invalid arguments for delete method");
1893
+ });
1894
+ }
1895
+ async deleteOrThrow(a, b) {
1896
+ return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
1897
+ const result = await this.delete(a, b);
1898
+ if (Array.isArray(result)) {
1899
+ const missingIds = compact(
1900
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1901
+ );
1902
+ if (missingIds.length > 0) {
1903
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1904
+ }
1905
+ return result;
1906
+ } else if (result === null) {
1907
+ const id = extractId(a) ?? "unknown";
1908
+ throw new Error(`Record with id ${id} not found`);
1909
+ }
1910
+ return result;
1911
+ });
1305
1912
  }
1306
1913
  async search(query, options = {}) {
1307
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1308
- const { records } = await searchTable({
1309
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1310
- body: {
1311
- query,
1312
- fuzziness: options.fuzziness,
1313
- filter: options.filter
1314
- },
1315
- ...fetchProps
1914
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1915
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1916
+ const { records } = await searchTable({
1917
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1918
+ body: {
1919
+ query,
1920
+ fuzziness: options.fuzziness,
1921
+ prefix: options.prefix,
1922
+ highlight: options.highlight,
1923
+ filter: options.filter,
1924
+ boosters: options.boosters
1925
+ },
1926
+ ...fetchProps
1927
+ });
1928
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1929
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
1930
+ });
1931
+ }
1932
+ async aggregate(aggs, filter) {
1933
+ return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
1934
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1935
+ const result = await aggregateTable({
1936
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1937
+ body: { aggs, filter },
1938
+ ...fetchProps
1939
+ });
1940
+ return result;
1316
1941
  });
1317
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1318
- return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1319
1942
  }
1320
1943
  async query(query) {
1321
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1322
- if (cacheQuery)
1323
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1324
- const data = query.getQueryOptions();
1325
- const body = {
1326
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1327
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1328
- page: data.pagination,
1329
- columns: data.columns
1330
- };
1331
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1332
- const { meta, records: objects } = await queryTable({
1333
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1334
- body,
1335
- ...fetchProps
1944
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1945
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1946
+ if (cacheQuery)
1947
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1948
+ const data = query.getQueryOptions();
1949
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1950
+ const { meta, records: objects } = await queryTable({
1951
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1952
+ body: {
1953
+ filter: cleanFilter(data.filter),
1954
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1955
+ page: data.pagination,
1956
+ columns: data.columns ?? ["*"]
1957
+ },
1958
+ ...fetchProps
1959
+ });
1960
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1961
+ const records = objects.map(
1962
+ (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
1963
+ );
1964
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1965
+ return new Page(query, meta, records);
1966
+ });
1967
+ }
1968
+ async summarizeTable(query, summaries, summariesFilter) {
1969
+ return __privateGet$4(this, _trace).call(this, "summarize", async () => {
1970
+ const data = query.getQueryOptions();
1971
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1972
+ const result = await summarizeTable({
1973
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1974
+ body: {
1975
+ filter: cleanFilter(data.filter),
1976
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1977
+ columns: data.columns,
1978
+ summaries,
1979
+ summariesFilter
1980
+ },
1981
+ ...fetchProps
1982
+ });
1983
+ return result;
1336
1984
  });
1337
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1338
- const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1339
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1340
- return new Page(query, meta, records);
1341
1985
  }
1342
1986
  }
1343
1987
  _table = new WeakMap();
1344
1988
  _getFetchProps = new WeakMap();
1989
+ _db = new WeakMap();
1345
1990
  _cache = new WeakMap();
1346
- _schema$1 = new WeakMap();
1991
+ _schemaTables$2 = new WeakMap();
1992
+ _trace = new WeakMap();
1347
1993
  _insertRecordWithoutId = new WeakSet();
1348
- insertRecordWithoutId_fn = async function(object) {
1994
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1349
1995
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1350
1996
  const record = transformObjectLinks(object);
1351
1997
  const response = await insertRecord({
@@ -1354,17 +2000,15 @@ insertRecordWithoutId_fn = async function(object) {
1354
2000
  dbBranchName: "{dbBranch}",
1355
2001
  tableName: __privateGet$4(this, _table)
1356
2002
  },
2003
+ queryParams: { columns },
1357
2004
  body: record,
1358
2005
  ...fetchProps
1359
2006
  });
1360
- const finalObject = await this.read(response.id);
1361
- if (!finalObject) {
1362
- throw new Error("The server failed to save the record");
1363
- }
1364
- return finalObject;
2007
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2008
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1365
2009
  };
1366
2010
  _insertRecordWithId = new WeakSet();
1367
- insertRecordWithId_fn = async function(recordId, object) {
2011
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1368
2012
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1369
2013
  const record = transformObjectLinks(object);
1370
2014
  const response = await insertRecordWithID({
@@ -1375,88 +2019,78 @@ insertRecordWithId_fn = async function(recordId, object) {
1375
2019
  recordId
1376
2020
  },
1377
2021
  body: record,
1378
- queryParams: { createOnly: true },
2022
+ queryParams: { createOnly: true, columns },
1379
2023
  ...fetchProps
1380
2024
  });
1381
- const finalObject = await this.read(response.id);
1382
- if (!finalObject) {
1383
- throw new Error("The server failed to save the record");
1384
- }
1385
- return finalObject;
2025
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2026
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1386
2027
  };
1387
2028
  _bulkInsertTableRecords = new WeakSet();
1388
- bulkInsertTableRecords_fn = async function(objects) {
2029
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1389
2030
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1390
2031
  const records = objects.map((object) => transformObjectLinks(object));
1391
2032
  const response = await bulkInsertTableRecords({
1392
2033
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
2034
+ queryParams: { columns },
1393
2035
  body: { records },
1394
2036
  ...fetchProps
1395
2037
  });
1396
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1397
- if (finalObjects.length !== objects.length) {
1398
- throw new Error("The server failed to save some records");
2038
+ if (!isResponseWithRecords(response)) {
2039
+ throw new Error("Request included columns but server didn't include them");
1399
2040
  }
1400
- return finalObjects;
2041
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2042
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
1401
2043
  };
1402
2044
  _updateRecordWithID = new WeakSet();
1403
- updateRecordWithID_fn = async function(recordId, object) {
2045
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1404
2046
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1405
2047
  const record = transformObjectLinks(object);
1406
- const response = await updateRecordWithID({
1407
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1408
- body: record,
1409
- ...fetchProps
1410
- });
1411
- const item = await this.read(response.id);
1412
- if (!item)
1413
- throw new Error("The server failed to save the record");
1414
- return item;
2048
+ try {
2049
+ const response = await updateRecordWithID({
2050
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2051
+ queryParams: { columns },
2052
+ body: record,
2053
+ ...fetchProps
2054
+ });
2055
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2056
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2057
+ } catch (e) {
2058
+ if (isObject(e) && e.status === 404) {
2059
+ return null;
2060
+ }
2061
+ throw e;
2062
+ }
1415
2063
  };
1416
2064
  _upsertRecordWithID = new WeakSet();
1417
- upsertRecordWithID_fn = async function(recordId, object) {
2065
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1418
2066
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1419
2067
  const response = await upsertRecordWithID({
1420
2068
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2069
+ queryParams: { columns },
1421
2070
  body: object,
1422
2071
  ...fetchProps
1423
2072
  });
1424
- const item = await this.read(response.id);
1425
- if (!item)
1426
- throw new Error("The server failed to save the record");
1427
- return item;
2073
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2074
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1428
2075
  };
1429
2076
  _deleteRecord = new WeakSet();
1430
- deleteRecord_fn = async function(recordId) {
2077
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1431
2078
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1432
- await deleteRecord({
1433
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1434
- ...fetchProps
1435
- });
1436
- };
1437
- _invalidateCache = new WeakSet();
1438
- invalidateCache_fn = async function(recordId) {
1439
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1440
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1441
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1442
- for (const [key, value] of queries) {
1443
- const ids = getIds(value);
1444
- if (ids.includes(recordId))
1445
- await __privateGet$4(this, _cache).delete(key);
2079
+ try {
2080
+ const response = await deleteRecord({
2081
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2082
+ queryParams: { columns },
2083
+ ...fetchProps
2084
+ });
2085
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2086
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2087
+ } catch (e) {
2088
+ if (isObject(e) && e.status === 404) {
2089
+ return null;
2090
+ }
2091
+ throw e;
1446
2092
  }
1447
2093
  };
1448
- _setCacheRecord = new WeakSet();
1449
- setCacheRecord_fn = async function(record) {
1450
- if (!__privateGet$4(this, _cache).cacheRecords)
1451
- return;
1452
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1453
- };
1454
- _getCacheRecord = new WeakSet();
1455
- getCacheRecord_fn = async function(recordId) {
1456
- if (!__privateGet$4(this, _cache).cacheRecords)
1457
- return null;
1458
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1459
- };
1460
2094
  _setCacheQuery = new WeakSet();
1461
2095
  setCacheQuery_fn = async function(query, meta, records) {
1462
2096
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -1473,17 +2107,17 @@ getCacheQuery_fn = async function(query) {
1473
2107
  const hasExpired = result.date.getTime() + ttl < Date.now();
1474
2108
  return hasExpired ? null : result;
1475
2109
  };
1476
- _getSchema$1 = new WeakSet();
1477
- getSchema_fn$1 = async function() {
1478
- if (__privateGet$4(this, _schema$1))
1479
- return __privateGet$4(this, _schema$1);
2110
+ _getSchemaTables$1 = new WeakSet();
2111
+ getSchemaTables_fn$1 = async function() {
2112
+ if (__privateGet$4(this, _schemaTables$2))
2113
+ return __privateGet$4(this, _schemaTables$2);
1480
2114
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1481
2115
  const { schema } = await getBranchDetails({
1482
2116
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1483
2117
  ...fetchProps
1484
2118
  });
1485
- __privateSet$3(this, _schema$1, schema);
1486
- return schema;
2119
+ __privateSet$4(this, _schemaTables$2, schema.tables);
2120
+ return schema.tables;
1487
2121
  };
1488
2122
  const transformObjectLinks = (object) => {
1489
2123
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1492,20 +2126,23 @@ const transformObjectLinks = (object) => {
1492
2126
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1493
2127
  }, {});
1494
2128
  };
1495
- const initObject = (db, schema, table, object) => {
2129
+ const initObject = (db, schemaTables, table, object, selectedColumns) => {
1496
2130
  const result = {};
1497
- Object.assign(result, object);
1498
- const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
2131
+ const { xata, ...rest } = object ?? {};
2132
+ Object.assign(result, rest);
2133
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1499
2134
  if (!columns)
1500
2135
  console.error(`Table ${table} not found in schema`);
1501
2136
  for (const column of columns ?? []) {
2137
+ if (!isValidColumn(selectedColumns, column))
2138
+ continue;
1502
2139
  const value = result[column.name];
1503
2140
  switch (column.type) {
1504
2141
  case "datetime": {
1505
- const date = new Date(value);
1506
- if (isNaN(date.getTime())) {
2142
+ const date = value !== void 0 ? new Date(value) : void 0;
2143
+ if (date && isNaN(date.getTime())) {
1507
2144
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1508
- } else {
2145
+ } else if (date) {
1509
2146
  result[column.name] = date;
1510
2147
  }
1511
2148
  break;
@@ -1515,35 +2152,66 @@ const initObject = (db, schema, table, object) => {
1515
2152
  if (!linkTable) {
1516
2153
  console.error(`Failed to parse link for field ${column.name}`);
1517
2154
  } else if (isObject(value)) {
1518
- result[column.name] = initObject(db, schema, linkTable, value);
2155
+ const selectedLinkColumns = selectedColumns.reduce((acc, item) => {
2156
+ if (item === column.name) {
2157
+ return [...acc, "*"];
2158
+ }
2159
+ if (item.startsWith(`${column.name}.`)) {
2160
+ const [, ...path] = item.split(".");
2161
+ return [...acc, path.join(".")];
2162
+ }
2163
+ return acc;
2164
+ }, []);
2165
+ result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2166
+ } else {
2167
+ result[column.name] = null;
1519
2168
  }
1520
2169
  break;
1521
2170
  }
2171
+ default:
2172
+ result[column.name] = value ?? null;
2173
+ if (column.notNull === true && value === null) {
2174
+ console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2175
+ }
2176
+ break;
1522
2177
  }
1523
2178
  }
1524
- result.read = function() {
1525
- return db[table].read(result["id"]);
2179
+ result.read = function(columns2) {
2180
+ return db[table].read(result["id"], columns2);
1526
2181
  };
1527
- result.update = function(data) {
1528
- return db[table].update(result["id"], data);
2182
+ result.update = function(data, columns2) {
2183
+ return db[table].update(result["id"], data, columns2);
1529
2184
  };
1530
2185
  result.delete = function() {
1531
2186
  return db[table].delete(result["id"]);
1532
2187
  };
1533
- for (const prop of ["read", "update", "delete"]) {
2188
+ result.getMetadata = function() {
2189
+ return xata;
2190
+ };
2191
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1534
2192
  Object.defineProperty(result, prop, { enumerable: false });
1535
2193
  }
1536
2194
  Object.freeze(result);
1537
2195
  return result;
1538
2196
  };
1539
- function getIds(value) {
1540
- if (Array.isArray(value)) {
1541
- return value.map((item) => getIds(item)).flat();
1542
- }
1543
- if (!isObject(value))
1544
- return [];
1545
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1546
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
2197
+ function isResponseWithRecords(value) {
2198
+ return isObject(value) && Array.isArray(value.records);
2199
+ }
2200
+ function extractId(value) {
2201
+ if (isString(value))
2202
+ return value;
2203
+ if (isObject(value) && isString(value.id))
2204
+ return value.id;
2205
+ return void 0;
2206
+ }
2207
+ function isValidColumn(columns, column) {
2208
+ if (columns.includes("*"))
2209
+ return true;
2210
+ if (column.type === "link") {
2211
+ const linkColumns = columns.filter((item) => item.startsWith(column.name));
2212
+ return linkColumns.length > 0;
2213
+ }
2214
+ return columns.includes(column.name);
1547
2215
  }
1548
2216
 
1549
2217
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1559,7 +2227,7 @@ var __privateAdd$3 = (obj, member, value) => {
1559
2227
  throw TypeError("Cannot add the same private member more than once");
1560
2228
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1561
2229
  };
1562
- var __privateSet$2 = (obj, member, value, setter) => {
2230
+ var __privateSet$3 = (obj, member, value, setter) => {
1563
2231
  __accessCheck$3(obj, member, "write to private field");
1564
2232
  setter ? setter.call(obj, value) : member.set(obj, value);
1565
2233
  return value;
@@ -1568,9 +2236,8 @@ var _map;
1568
2236
  class SimpleCache {
1569
2237
  constructor(options = {}) {
1570
2238
  __privateAdd$3(this, _map, void 0);
1571
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
2239
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1572
2240
  this.capacity = options.max ?? 500;
1573
- this.cacheRecords = options.cacheRecords ?? true;
1574
2241
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1575
2242
  }
1576
2243
  async getAll() {
@@ -1596,18 +2263,25 @@ class SimpleCache {
1596
2263
  }
1597
2264
  _map = new WeakMap();
1598
2265
 
1599
- const gt = (value) => ({ $gt: value });
1600
- const ge = (value) => ({ $ge: value });
1601
- const gte = (value) => ({ $ge: value });
1602
- const lt = (value) => ({ $lt: value });
1603
- const lte = (value) => ({ $le: value });
1604
- const le = (value) => ({ $le: value });
2266
+ const greaterThan = (value) => ({ $gt: value });
2267
+ const gt = greaterThan;
2268
+ const greaterThanEquals = (value) => ({ $ge: value });
2269
+ const greaterEquals = greaterThanEquals;
2270
+ const gte = greaterThanEquals;
2271
+ const ge = greaterThanEquals;
2272
+ const lessThan = (value) => ({ $lt: value });
2273
+ const lt = lessThan;
2274
+ const lessThanEquals = (value) => ({ $le: value });
2275
+ const lessEquals = lessThanEquals;
2276
+ const lte = lessThanEquals;
2277
+ const le = lessThanEquals;
1605
2278
  const exists = (column) => ({ $exists: column });
1606
2279
  const notExists = (column) => ({ $notExists: column });
1607
2280
  const startsWith = (value) => ({ $startsWith: value });
1608
2281
  const endsWith = (value) => ({ $endsWith: value });
1609
2282
  const pattern = (value) => ({ $pattern: value });
1610
2283
  const is = (value) => ({ $is: value });
2284
+ const equals = is;
1611
2285
  const isNot = (value) => ({ $isNot: value });
1612
2286
  const contains = (value) => ({ $contains: value });
1613
2287
  const includes = (value) => ({ $includes: value });
@@ -1628,31 +2302,42 @@ var __privateAdd$2 = (obj, member, value) => {
1628
2302
  throw TypeError("Cannot add the same private member more than once");
1629
2303
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1630
2304
  };
1631
- var _tables;
2305
+ var __privateSet$2 = (obj, member, value, setter) => {
2306
+ __accessCheck$2(obj, member, "write to private field");
2307
+ setter ? setter.call(obj, value) : member.set(obj, value);
2308
+ return value;
2309
+ };
2310
+ var _tables, _schemaTables$1;
1632
2311
  class SchemaPlugin extends XataPlugin {
1633
- constructor(tableNames) {
2312
+ constructor(schemaTables) {
1634
2313
  super();
1635
- this.tableNames = tableNames;
1636
2314
  __privateAdd$2(this, _tables, {});
2315
+ __privateAdd$2(this, _schemaTables$1, void 0);
2316
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1637
2317
  }
1638
2318
  build(pluginOptions) {
1639
- const db = new Proxy({}, {
1640
- get: (_target, table) => {
1641
- if (!isString(table))
1642
- throw new Error("Invalid table name");
1643
- if (__privateGet$2(this, _tables)[table] === void 0) {
1644
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
2319
+ const db = new Proxy(
2320
+ {},
2321
+ {
2322
+ get: (_target, table) => {
2323
+ if (!isString(table))
2324
+ throw new Error("Invalid table name");
2325
+ if (__privateGet$2(this, _tables)[table] === void 0) {
2326
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
2327
+ }
2328
+ return __privateGet$2(this, _tables)[table];
1645
2329
  }
1646
- return __privateGet$2(this, _tables)[table];
1647
2330
  }
1648
- });
1649
- for (const table of this.tableNames ?? []) {
1650
- db[table] = new RestRepository({ db, pluginOptions, table });
2331
+ );
2332
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
2333
+ for (const table of tableNames) {
2334
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1651
2335
  }
1652
2336
  return db;
1653
2337
  }
1654
2338
  }
1655
2339
  _tables = new WeakMap();
2340
+ _schemaTables$1 = new WeakMap();
1656
2341
 
1657
2342
  var __accessCheck$1 = (obj, member, msg) => {
1658
2343
  if (!member.has(obj))
@@ -1676,82 +2361,77 @@ var __privateMethod$1 = (obj, member, method) => {
1676
2361
  __accessCheck$1(obj, member, "access private method");
1677
2362
  return method;
1678
2363
  };
1679
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
2364
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1680
2365
  class SearchPlugin extends XataPlugin {
1681
- constructor(db) {
2366
+ constructor(db, schemaTables) {
1682
2367
  super();
1683
2368
  this.db = db;
1684
2369
  __privateAdd$1(this, _search);
1685
- __privateAdd$1(this, _getSchema);
1686
- __privateAdd$1(this, _schema, void 0);
2370
+ __privateAdd$1(this, _getSchemaTables);
2371
+ __privateAdd$1(this, _schemaTables, void 0);
2372
+ __privateSet$1(this, _schemaTables, schemaTables);
1687
2373
  }
1688
2374
  build({ getFetchProps }) {
1689
2375
  return {
1690
2376
  all: async (query, options = {}) => {
1691
2377
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1692
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
2378
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1693
2379
  return records.map((record) => {
1694
2380
  const { table = "orphan" } = record.xata;
1695
- return { table, record: initObject(this.db, schema, table, record) };
2381
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
1696
2382
  });
1697
2383
  },
1698
2384
  byTable: async (query, options = {}) => {
1699
2385
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1700
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
2386
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1701
2387
  return records.reduce((acc, record) => {
1702
2388
  const { table = "orphan" } = record.xata;
1703
2389
  const items = acc[table] ?? [];
1704
- const item = initObject(this.db, schema, table, record);
2390
+ const item = initObject(this.db, schemaTables, table, record, ["*"]);
1705
2391
  return { ...acc, [table]: [...items, item] };
1706
2392
  }, {});
1707
2393
  }
1708
2394
  };
1709
2395
  }
1710
2396
  }
1711
- _schema = new WeakMap();
2397
+ _schemaTables = new WeakMap();
1712
2398
  _search = new WeakSet();
1713
2399
  search_fn = async function(query, options, getFetchProps) {
1714
2400
  const fetchProps = await getFetchProps();
1715
- const { tables, fuzziness } = options ?? {};
2401
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1716
2402
  const { records } = await searchBranch({
1717
2403
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1718
- body: { tables, query, fuzziness },
2404
+ body: { tables, query, fuzziness, prefix, highlight },
1719
2405
  ...fetchProps
1720
2406
  });
1721
2407
  return records;
1722
2408
  };
1723
- _getSchema = new WeakSet();
1724
- getSchema_fn = async function(getFetchProps) {
1725
- if (__privateGet$1(this, _schema))
1726
- return __privateGet$1(this, _schema);
2409
+ _getSchemaTables = new WeakSet();
2410
+ getSchemaTables_fn = async function(getFetchProps) {
2411
+ if (__privateGet$1(this, _schemaTables))
2412
+ return __privateGet$1(this, _schemaTables);
1727
2413
  const fetchProps = await getFetchProps();
1728
2414
  const { schema } = await getBranchDetails({
1729
2415
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1730
2416
  ...fetchProps
1731
2417
  });
1732
- __privateSet$1(this, _schema, schema);
1733
- return schema;
2418
+ __privateSet$1(this, _schemaTables, schema.tables);
2419
+ return schema.tables;
1734
2420
  };
1735
2421
 
1736
2422
  const isBranchStrategyBuilder = (strategy) => {
1737
2423
  return typeof strategy === "function";
1738
2424
  };
1739
2425
 
1740
- const envBranchNames = [
1741
- "XATA_BRANCH",
1742
- "VERCEL_GIT_COMMIT_REF",
1743
- "CF_PAGES_BRANCH",
1744
- "BRANCH"
1745
- ];
1746
2426
  async function getCurrentBranchName(options) {
1747
- const env = getBranchByEnvVariable();
1748
- if (env) {
1749
- const details = await getDatabaseBranch(env, options);
2427
+ const { branch, envBranch } = getEnvironment();
2428
+ if (branch) {
2429
+ const details = await getDatabaseBranch(branch, options);
1750
2430
  if (details)
1751
- return env;
1752
- console.warn(`Branch ${env} not found in Xata. Ignoring...`);
2431
+ return branch;
2432
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1753
2433
  }
1754
- const gitBranch = await getGitBranch();
2434
+ const gitBranch = envBranch || await getGitBranch();
1755
2435
  return resolveXataBranch(gitBranch, options);
1756
2436
  }
1757
2437
  async function getCurrentBranchDetails(options) {
@@ -1762,18 +2442,24 @@ async function resolveXataBranch(gitBranch, options) {
1762
2442
  const databaseURL = options?.databaseURL || getDatabaseURL();
1763
2443
  const apiKey = options?.apiKey || getAPIKey();
1764
2444
  if (!databaseURL)
1765
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2445
+ throw new Error(
2446
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2447
+ );
1766
2448
  if (!apiKey)
1767
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2449
+ throw new Error(
2450
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2451
+ );
1768
2452
  const [protocol, , host, , dbName] = databaseURL.split("/");
1769
2453
  const [workspace] = host.split(".");
2454
+ const { fallbackBranch } = getEnvironment();
1770
2455
  const { branch } = await resolveBranch({
1771
2456
  apiKey,
1772
2457
  apiUrl: databaseURL,
1773
2458
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1774
2459
  workspacesApiUrl: `${protocol}//${host}`,
1775
2460
  pathParams: { dbName, workspace },
1776
- queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
2461
+ queryParams: { gitBranch, fallbackBranch },
2462
+ trace: defaultTrace
1777
2463
  });
1778
2464
  return branch;
1779
2465
  }
@@ -1781,9 +2467,13 @@ async function getDatabaseBranch(branch, options) {
1781
2467
  const databaseURL = options?.databaseURL || getDatabaseURL();
1782
2468
  const apiKey = options?.apiKey || getAPIKey();
1783
2469
  if (!databaseURL)
1784
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2470
+ throw new Error(
2471
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2472
+ );
1785
2473
  if (!apiKey)
1786
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2474
+ throw new Error(
2475
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2476
+ );
1787
2477
  const [protocol, , host, , database] = databaseURL.split("/");
1788
2478
  const [workspace] = host.split(".");
1789
2479
  const dbBranchName = `${database}:${branch}`;
@@ -1793,10 +2483,8 @@ async function getDatabaseBranch(branch, options) {
1793
2483
  apiUrl: databaseURL,
1794
2484
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1795
2485
  workspacesApiUrl: `${protocol}//${host}`,
1796
- pathParams: {
1797
- dbBranchName,
1798
- workspace
1799
- }
2486
+ pathParams: { dbBranchName, workspace },
2487
+ trace: defaultTrace
1800
2488
  });
1801
2489
  } catch (err) {
1802
2490
  if (isObject(err) && err.status === 404)
@@ -1804,21 +2492,10 @@ async function getDatabaseBranch(branch, options) {
1804
2492
  throw err;
1805
2493
  }
1806
2494
  }
1807
- function getBranchByEnvVariable() {
1808
- for (const name of envBranchNames) {
1809
- const value = getEnvVariable(name);
1810
- if (value) {
1811
- return value;
1812
- }
1813
- }
1814
- try {
1815
- return XATA_BRANCH;
1816
- } catch (err) {
1817
- }
1818
- }
1819
2495
  function getDatabaseURL() {
1820
2496
  try {
1821
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2497
+ const { databaseURL } = getEnvironment();
2498
+ return databaseURL;
1822
2499
  } catch (err) {
1823
2500
  return void 0;
1824
2501
  }
@@ -1847,20 +2524,23 @@ var __privateMethod = (obj, member, method) => {
1847
2524
  return method;
1848
2525
  };
1849
2526
  const buildClient = (plugins) => {
1850
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2527
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1851
2528
  return _a = class {
1852
- constructor(options = {}, tables) {
2529
+ constructor(options = {}, schemaTables) {
1853
2530
  __privateAdd(this, _parseOptions);
1854
2531
  __privateAdd(this, _getFetchProps);
1855
2532
  __privateAdd(this, _evaluateBranch);
1856
2533
  __privateAdd(this, _branch, void 0);
2534
+ __privateAdd(this, _options, void 0);
1857
2535
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2536
+ __privateSet(this, _options, safeOptions);
1858
2537
  const pluginOptions = {
1859
2538
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1860
- cache: safeOptions.cache
2539
+ cache: safeOptions.cache,
2540
+ trace: safeOptions.trace
1861
2541
  };
1862
- const db = new SchemaPlugin(tables).build(pluginOptions);
1863
- const search = new SearchPlugin(db).build(pluginOptions);
2542
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2543
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1864
2544
  this.db = db;
1865
2545
  this.search = search;
1866
2546
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
@@ -1876,22 +2556,26 @@ const buildClient = (plugins) => {
1876
2556
  }
1877
2557
  }
1878
2558
  }
1879
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2559
+ async getConfig() {
2560
+ const databaseURL = __privateGet(this, _options).databaseURL;
2561
+ const branch = await __privateGet(this, _options).branch();
2562
+ return { databaseURL, branch };
2563
+ }
2564
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1880
2565
  const fetch = getFetchImplementation(options?.fetch);
1881
2566
  const databaseURL = options?.databaseURL || getDatabaseURL();
1882
2567
  const apiKey = options?.apiKey || getAPIKey();
1883
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2568
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2569
+ const trace = options?.trace ?? defaultTrace;
1884
2570
  const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1885
- if (!databaseURL || !apiKey) {
1886
- throw new Error("Options databaseURL and apiKey are required");
2571
+ if (!apiKey) {
2572
+ throw new Error("Option apiKey is required");
1887
2573
  }
1888
- return { fetch, databaseURL, apiKey, branch, cache };
1889
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1890
- fetch,
1891
- apiKey,
1892
- databaseURL,
1893
- branch
1894
- }) {
2574
+ if (!databaseURL) {
2575
+ throw new Error("Option databaseURL is required");
2576
+ }
2577
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2578
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
1895
2579
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1896
2580
  if (!branchValue)
1897
2581
  throw new Error("Unable to resolve branch value");
@@ -1901,9 +2585,10 @@ const buildClient = (plugins) => {
1901
2585
  apiUrl: "",
1902
2586
  workspacesApiUrl: (path, params) => {
1903
2587
  const hasBranch = params.dbBranchName ?? params.branch;
1904
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
2588
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
1905
2589
  return databaseURL + newPath;
1906
- }
2590
+ },
2591
+ trace
1907
2592
  };
1908
2593
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1909
2594
  if (__privateGet(this, _branch))
@@ -1926,6 +2611,88 @@ const buildClient = (plugins) => {
1926
2611
  class BaseClient extends buildClient() {
1927
2612
  }
1928
2613
 
2614
+ const META = "__";
2615
+ const VALUE = "___";
2616
+ class Serializer {
2617
+ constructor() {
2618
+ this.classes = {};
2619
+ }
2620
+ add(clazz) {
2621
+ this.classes[clazz.name] = clazz;
2622
+ }
2623
+ toJSON(data) {
2624
+ function visit(obj) {
2625
+ if (Array.isArray(obj))
2626
+ return obj.map(visit);
2627
+ const type = typeof obj;
2628
+ if (type === "undefined")
2629
+ return { [META]: "undefined" };
2630
+ if (type === "bigint")
2631
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2632
+ if (obj === null || type !== "object")
2633
+ return obj;
2634
+ const constructor = obj.constructor;
2635
+ const o = { [META]: constructor.name };
2636
+ for (const [key, value] of Object.entries(obj)) {
2637
+ o[key] = visit(value);
2638
+ }
2639
+ if (constructor === Date)
2640
+ o[VALUE] = obj.toISOString();
2641
+ if (constructor === Map)
2642
+ o[VALUE] = Object.fromEntries(obj);
2643
+ if (constructor === Set)
2644
+ o[VALUE] = [...obj];
2645
+ return o;
2646
+ }
2647
+ return JSON.stringify(visit(data));
2648
+ }
2649
+ fromJSON(json) {
2650
+ return JSON.parse(json, (key, value) => {
2651
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2652
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2653
+ const constructor = this.classes[clazz];
2654
+ if (constructor) {
2655
+ return Object.assign(Object.create(constructor.prototype), rest);
2656
+ }
2657
+ if (clazz === "Date")
2658
+ return new Date(val);
2659
+ if (clazz === "Set")
2660
+ return new Set(val);
2661
+ if (clazz === "Map")
2662
+ return new Map(Object.entries(val));
2663
+ if (clazz === "bigint")
2664
+ return BigInt(val);
2665
+ if (clazz === "undefined")
2666
+ return void 0;
2667
+ return rest;
2668
+ }
2669
+ return value;
2670
+ });
2671
+ }
2672
+ }
2673
+ const defaultSerializer = new Serializer();
2674
+ const serialize = (data) => {
2675
+ return defaultSerializer.toJSON(data);
2676
+ };
2677
+ const deserialize = (json) => {
2678
+ return defaultSerializer.fromJSON(json);
2679
+ };
2680
+
2681
+ function buildWorkerRunner(config) {
2682
+ return function xataWorker(name, _worker) {
2683
+ return async (...args) => {
2684
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2685
+ const result = await fetch(url, {
2686
+ method: "POST",
2687
+ headers: { "Content-Type": "application/json" },
2688
+ body: serialize({ args })
2689
+ });
2690
+ const text = await result.text();
2691
+ return deserialize(text);
2692
+ };
2693
+ };
2694
+ }
2695
+
1929
2696
  class XataError extends Error {
1930
2697
  constructor(message, status) {
1931
2698
  super(message);
@@ -1933,5 +2700,5 @@ class XataError extends Error {
1933
2700
  }
1934
2701
  }
1935
2702
 
1936
- 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, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2703
+ 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, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, 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 };
1937
2704
  //# sourceMappingURL=index.mjs.map