@xata.io/client 0.0.0-alpha.vf76843f → 0.0.0-alpha.vf7a5219a6da9afdecee2e8995fcc249036ff88a1

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,5 +1,6 @@
1
- const defaultTrace = async (_name, fn, _options) => {
1
+ const defaultTrace = async (name, fn, _options) => {
2
2
  return await fn({
3
+ name,
3
4
  setAttributes: () => {
4
5
  return;
5
6
  }
@@ -17,7 +18,8 @@ const TraceAttributes = {
17
18
  HTTP_METHOD: "http.method",
18
19
  HTTP_URL: "http.url",
19
20
  HTTP_ROUTE: "http.route",
20
- HTTP_TARGET: "http.target"
21
+ HTTP_TARGET: "http.target",
22
+ CLOUDFLARE_RAY_ID: "cf.ray"
21
23
  };
22
24
 
23
25
  function notEmpty(value) {
@@ -26,8 +28,18 @@ function notEmpty(value) {
26
28
  function compact(arr) {
27
29
  return arr.filter(notEmpty);
28
30
  }
31
+ function compactObject(obj) {
32
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
33
+ }
34
+ function isBlob(value) {
35
+ try {
36
+ return value instanceof Blob;
37
+ } catch (error) {
38
+ return false;
39
+ }
40
+ }
29
41
  function isObject(value) {
30
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
42
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
31
43
  }
32
44
  function isDefined(value) {
33
45
  return value !== null && value !== void 0;
@@ -41,6 +53,18 @@ function isStringArray(value) {
41
53
  function isNumber(value) {
42
54
  return isDefined(value) && typeof value === "number";
43
55
  }
56
+ function parseNumber(value) {
57
+ if (isNumber(value)) {
58
+ return value;
59
+ }
60
+ if (isString(value)) {
61
+ const parsed = Number(value);
62
+ if (!Number.isNaN(parsed)) {
63
+ return parsed;
64
+ }
65
+ }
66
+ return void 0;
67
+ }
44
68
  function toBase64(value) {
45
69
  try {
46
70
  return btoa(value);
@@ -67,16 +91,42 @@ function chunk(array, chunkSize) {
67
91
  }
68
92
  return result;
69
93
  }
94
+ async function timeout(ms) {
95
+ return new Promise((resolve) => setTimeout(resolve, ms));
96
+ }
97
+ function timeoutWithCancel(ms) {
98
+ let timeoutId;
99
+ const promise = new Promise((resolve) => {
100
+ timeoutId = setTimeout(() => {
101
+ resolve();
102
+ }, ms);
103
+ });
104
+ return {
105
+ cancel: () => clearTimeout(timeoutId),
106
+ promise
107
+ };
108
+ }
109
+ function promiseMap(inputValues, mapper) {
110
+ const reducer = (acc$, inputValue) => acc$.then(
111
+ (acc) => mapper(inputValue).then((result) => {
112
+ acc.push(result);
113
+ return acc;
114
+ })
115
+ );
116
+ return inputValues.reduce(reducer, Promise.resolve([]));
117
+ }
70
118
 
71
119
  function getEnvironment() {
72
120
  try {
73
- if (isObject(process) && isObject(process.env)) {
121
+ if (isDefined(process) && isDefined(process.env)) {
74
122
  return {
75
123
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
76
124
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
77
125
  branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
78
- envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
79
- fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
126
+ deployPreview: process.env.XATA_PREVIEW,
127
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
128
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
129
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
80
130
  };
81
131
  }
82
132
  } catch (err) {
@@ -87,8 +137,10 @@ function getEnvironment() {
87
137
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
88
138
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
89
139
  branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
90
- envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
91
- fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
140
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
141
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
142
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
143
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
92
144
  };
93
145
  }
94
146
  } catch (err) {
@@ -97,8 +149,10 @@ function getEnvironment() {
97
149
  apiKey: getGlobalApiKey(),
98
150
  databaseURL: getGlobalDatabaseURL(),
99
151
  branch: getGlobalBranch(),
100
- envBranch: void 0,
101
- fallbackBranch: getGlobalFallbackBranch()
152
+ deployPreview: void 0,
153
+ deployPreviewBranch: void 0,
154
+ vercelGitCommitRef: void 0,
155
+ vercelGitRepoOwner: void 0
102
156
  };
103
157
  }
104
158
  function getEnableBrowserVariable() {
@@ -141,56 +195,338 @@ function getGlobalBranch() {
141
195
  return void 0;
142
196
  }
143
197
  }
144
- function getGlobalFallbackBranch() {
198
+ function getDatabaseURL() {
145
199
  try {
146
- return XATA_FALLBACK_BRANCH;
200
+ const { databaseURL } = getEnvironment();
201
+ return databaseURL;
147
202
  } catch (err) {
148
203
  return void 0;
149
204
  }
150
205
  }
151
- async function getGitBranch() {
152
- const cmd = ["git", "branch", "--show-current"];
153
- const fullCmd = cmd.join(" ");
154
- const nodeModule = ["child", "process"].join("_");
155
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
206
+ function getAPIKey() {
156
207
  try {
157
- if (typeof require === "function") {
158
- return require(nodeModule).execSync(fullCmd, execOptions).trim();
159
- }
160
- const { execSync } = await import(nodeModule);
161
- return execSync(fullCmd, execOptions).toString().trim();
208
+ const { apiKey } = getEnvironment();
209
+ return apiKey;
162
210
  } catch (err) {
211
+ return void 0;
163
212
  }
213
+ }
214
+ function getBranch() {
164
215
  try {
165
- if (isObject(Deno)) {
166
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
167
- return new TextDecoder().decode(await process2.output()).trim();
168
- }
216
+ const { branch } = getEnvironment();
217
+ return branch;
169
218
  } catch (err) {
219
+ return void 0;
170
220
  }
171
221
  }
172
-
173
- function getAPIKey() {
222
+ function buildPreviewBranchName({ org, branch }) {
223
+ return `preview-${org}-${branch}`;
224
+ }
225
+ function getPreviewBranch() {
174
226
  try {
175
- const { apiKey } = getEnvironment();
176
- return apiKey;
227
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
228
+ if (deployPreviewBranch)
229
+ return deployPreviewBranch;
230
+ switch (deployPreview) {
231
+ case "vercel": {
232
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
233
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
234
+ return void 0;
235
+ }
236
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
237
+ }
238
+ }
239
+ return void 0;
177
240
  } catch (err) {
178
241
  return void 0;
179
242
  }
180
243
  }
181
244
 
245
+ var __accessCheck$8 = (obj, member, msg) => {
246
+ if (!member.has(obj))
247
+ throw TypeError("Cannot " + msg);
248
+ };
249
+ var __privateGet$8 = (obj, member, getter) => {
250
+ __accessCheck$8(obj, member, "read from private field");
251
+ return getter ? getter.call(obj) : member.get(obj);
252
+ };
253
+ var __privateAdd$8 = (obj, member, value) => {
254
+ if (member.has(obj))
255
+ throw TypeError("Cannot add the same private member more than once");
256
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
257
+ };
258
+ var __privateSet$8 = (obj, member, value, setter) => {
259
+ __accessCheck$8(obj, member, "write to private field");
260
+ setter ? setter.call(obj, value) : member.set(obj, value);
261
+ return value;
262
+ };
263
+ var __privateMethod$4 = (obj, member, method) => {
264
+ __accessCheck$8(obj, member, "access private method");
265
+ return method;
266
+ };
267
+ var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
268
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
182
269
  function getFetchImplementation(userFetch) {
183
270
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
184
- const fetchImpl = userFetch ?? globalFetch;
271
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
272
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
185
273
  if (!fetchImpl) {
186
- throw new Error(
187
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
188
- );
274
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
189
275
  }
190
276
  return fetchImpl;
191
277
  }
278
+ class ApiRequestPool {
279
+ constructor(concurrency = 10) {
280
+ __privateAdd$8(this, _enqueue);
281
+ __privateAdd$8(this, _fetch, void 0);
282
+ __privateAdd$8(this, _queue, void 0);
283
+ __privateAdd$8(this, _concurrency, void 0);
284
+ __privateSet$8(this, _queue, []);
285
+ __privateSet$8(this, _concurrency, concurrency);
286
+ this.running = 0;
287
+ this.started = 0;
288
+ }
289
+ setFetch(fetch2) {
290
+ __privateSet$8(this, _fetch, fetch2);
291
+ }
292
+ getFetch() {
293
+ if (!__privateGet$8(this, _fetch)) {
294
+ throw new Error("Fetch not set");
295
+ }
296
+ return __privateGet$8(this, _fetch);
297
+ }
298
+ request(url, options) {
299
+ const start = /* @__PURE__ */ new Date();
300
+ const fetchImpl = this.getFetch();
301
+ const runRequest = async (stalled = false) => {
302
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
303
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
304
+ if (!response) {
305
+ throw new Error("Request timed out");
306
+ }
307
+ if (response.status === 429) {
308
+ const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
309
+ await timeout(rateLimitReset * 1e3);
310
+ return await runRequest(true);
311
+ }
312
+ if (stalled) {
313
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
314
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
315
+ }
316
+ return response;
317
+ };
318
+ return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
319
+ return await runRequest();
320
+ });
321
+ }
322
+ }
323
+ _fetch = new WeakMap();
324
+ _queue = new WeakMap();
325
+ _concurrency = new WeakMap();
326
+ _enqueue = new WeakSet();
327
+ enqueue_fn = function(task) {
328
+ const promise = new Promise((resolve) => __privateGet$8(this, _queue).push(resolve)).finally(() => {
329
+ this.started--;
330
+ this.running++;
331
+ }).then(() => task()).finally(() => {
332
+ this.running--;
333
+ const next = __privateGet$8(this, _queue).shift();
334
+ if (next !== void 0) {
335
+ this.started++;
336
+ next();
337
+ }
338
+ });
339
+ if (this.running + this.started < __privateGet$8(this, _concurrency)) {
340
+ const next = __privateGet$8(this, _queue).shift();
341
+ if (next !== void 0) {
342
+ this.started++;
343
+ next();
344
+ }
345
+ }
346
+ return promise;
347
+ };
348
+
349
+ function generateUUID() {
350
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
351
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
352
+ return v.toString(16);
353
+ });
354
+ }
355
+
356
+ async function getBytes(stream, onChunk) {
357
+ const reader = stream.getReader();
358
+ let result;
359
+ while (!(result = await reader.read()).done) {
360
+ onChunk(result.value);
361
+ }
362
+ }
363
+ function getLines(onLine) {
364
+ let buffer;
365
+ let position;
366
+ let fieldLength;
367
+ let discardTrailingNewline = false;
368
+ return function onChunk(arr) {
369
+ if (buffer === void 0) {
370
+ buffer = arr;
371
+ position = 0;
372
+ fieldLength = -1;
373
+ } else {
374
+ buffer = concat(buffer, arr);
375
+ }
376
+ const bufLength = buffer.length;
377
+ let lineStart = 0;
378
+ while (position < bufLength) {
379
+ if (discardTrailingNewline) {
380
+ if (buffer[position] === 10 /* NewLine */) {
381
+ lineStart = ++position;
382
+ }
383
+ discardTrailingNewline = false;
384
+ }
385
+ let lineEnd = -1;
386
+ for (; position < bufLength && lineEnd === -1; ++position) {
387
+ switch (buffer[position]) {
388
+ case 58 /* Colon */:
389
+ if (fieldLength === -1) {
390
+ fieldLength = position - lineStart;
391
+ }
392
+ break;
393
+ case 13 /* CarriageReturn */:
394
+ discardTrailingNewline = true;
395
+ case 10 /* NewLine */:
396
+ lineEnd = position;
397
+ break;
398
+ }
399
+ }
400
+ if (lineEnd === -1) {
401
+ break;
402
+ }
403
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
404
+ lineStart = position;
405
+ fieldLength = -1;
406
+ }
407
+ if (lineStart === bufLength) {
408
+ buffer = void 0;
409
+ } else if (lineStart !== 0) {
410
+ buffer = buffer.subarray(lineStart);
411
+ position -= lineStart;
412
+ }
413
+ };
414
+ }
415
+ function getMessages(onId, onRetry, onMessage) {
416
+ let message = newMessage();
417
+ const decoder = new TextDecoder();
418
+ return function onLine(line, fieldLength) {
419
+ if (line.length === 0) {
420
+ onMessage?.(message);
421
+ message = newMessage();
422
+ } else if (fieldLength > 0) {
423
+ const field = decoder.decode(line.subarray(0, fieldLength));
424
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
425
+ const value = decoder.decode(line.subarray(valueOffset));
426
+ switch (field) {
427
+ case "data":
428
+ message.data = message.data ? message.data + "\n" + value : value;
429
+ break;
430
+ case "event":
431
+ message.event = value;
432
+ break;
433
+ case "id":
434
+ onId(message.id = value);
435
+ break;
436
+ case "retry":
437
+ const retry = parseInt(value, 10);
438
+ if (!isNaN(retry)) {
439
+ onRetry(message.retry = retry);
440
+ }
441
+ break;
442
+ }
443
+ }
444
+ };
445
+ }
446
+ function concat(a, b) {
447
+ const res = new Uint8Array(a.length + b.length);
448
+ res.set(a);
449
+ res.set(b, a.length);
450
+ return res;
451
+ }
452
+ function newMessage() {
453
+ return {
454
+ data: "",
455
+ event: "",
456
+ id: "",
457
+ retry: void 0
458
+ };
459
+ }
460
+ const EventStreamContentType = "text/event-stream";
461
+ const LastEventId = "last-event-id";
462
+ function fetchEventSource(input, {
463
+ signal: inputSignal,
464
+ headers: inputHeaders,
465
+ onopen: inputOnOpen,
466
+ onmessage,
467
+ onclose,
468
+ onerror,
469
+ fetch: inputFetch,
470
+ ...rest
471
+ }) {
472
+ return new Promise((resolve, reject) => {
473
+ const headers = { ...inputHeaders };
474
+ if (!headers.accept) {
475
+ headers.accept = EventStreamContentType;
476
+ }
477
+ let curRequestController;
478
+ function dispose() {
479
+ curRequestController.abort();
480
+ }
481
+ inputSignal?.addEventListener("abort", () => {
482
+ dispose();
483
+ resolve();
484
+ });
485
+ const fetchImpl = inputFetch ?? fetch;
486
+ const onopen = inputOnOpen ?? defaultOnOpen;
487
+ async function create() {
488
+ curRequestController = new AbortController();
489
+ try {
490
+ const response = await fetchImpl(input, {
491
+ ...rest,
492
+ headers,
493
+ signal: curRequestController.signal
494
+ });
495
+ await onopen(response);
496
+ await getBytes(
497
+ response.body,
498
+ getLines(
499
+ getMessages(
500
+ (id) => {
501
+ if (id) {
502
+ headers[LastEventId] = id;
503
+ } else {
504
+ delete headers[LastEventId];
505
+ }
506
+ },
507
+ (_retry) => {
508
+ },
509
+ onmessage
510
+ )
511
+ )
512
+ );
513
+ onclose?.();
514
+ dispose();
515
+ resolve();
516
+ } catch (err) {
517
+ }
518
+ }
519
+ create();
520
+ });
521
+ }
522
+ function defaultOnOpen(response) {
523
+ const contentType = response.headers?.get("content-type");
524
+ if (!contentType?.startsWith(EventStreamContentType)) {
525
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
526
+ }
527
+ }
192
528
 
193
- const VERSION = "0.0.0-alpha.vf76843f";
529
+ const VERSION = "0.28.3";
194
530
 
195
531
  class ErrorWithCause extends Error {
196
532
  constructor(message, options) {
@@ -201,7 +537,7 @@ class FetcherError extends ErrorWithCause {
201
537
  constructor(status, data, requestId) {
202
538
  super(getMessage(data));
203
539
  this.status = status;
204
- this.errors = isBulkError(data) ? data.errors : void 0;
540
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
205
541
  this.requestId = requestId;
206
542
  if (data instanceof Error) {
207
543
  this.stack = data.stack;
@@ -233,6 +569,68 @@ function getMessage(data) {
233
569
  }
234
570
  }
235
571
 
572
+ function getHostUrl(provider, type) {
573
+ if (isHostProviderAlias(provider)) {
574
+ return providers[provider][type];
575
+ } else if (isHostProviderBuilder(provider)) {
576
+ return provider[type];
577
+ }
578
+ throw new Error("Invalid API provider");
579
+ }
580
+ const providers = {
581
+ production: {
582
+ main: "https://api.xata.io",
583
+ workspaces: "https://{workspaceId}.{region}.xata.sh"
584
+ },
585
+ staging: {
586
+ main: "https://api.staging-xata.dev",
587
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
588
+ },
589
+ dev: {
590
+ main: "https://api.dev-xata.dev",
591
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
592
+ },
593
+ local: {
594
+ main: "http://localhost:6001",
595
+ workspaces: "http://{workspaceId}.{region}.localhost:6001"
596
+ }
597
+ };
598
+ function isHostProviderAlias(alias) {
599
+ return isString(alias) && Object.keys(providers).includes(alias);
600
+ }
601
+ function isHostProviderBuilder(builder) {
602
+ return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
603
+ }
604
+ function parseProviderString(provider = "production") {
605
+ if (isHostProviderAlias(provider)) {
606
+ return provider;
607
+ }
608
+ const [main, workspaces] = provider.split(",");
609
+ if (!main || !workspaces)
610
+ return null;
611
+ return { main, workspaces };
612
+ }
613
+ function buildProviderString(provider) {
614
+ if (isHostProviderAlias(provider))
615
+ return provider;
616
+ return `${provider.main},${provider.workspaces}`;
617
+ }
618
+ function parseWorkspacesUrlParts(url) {
619
+ if (!isString(url))
620
+ return null;
621
+ const matches = {
622
+ production: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/),
623
+ staging: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/),
624
+ dev: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/),
625
+ local: url.match(/(?:https?:\/\/)?([^.]+)(?:\.([^.]+))\.localhost:(\d+)/)
626
+ };
627
+ const [host, match] = Object.entries(matches).find(([, match2]) => match2 !== null) ?? [];
628
+ if (!isHostProviderAlias(host) || !match)
629
+ return null;
630
+ return { workspace: match[1], region: match[2], host };
631
+ }
632
+
633
+ const pool = new ApiRequestPool();
236
634
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
237
635
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
238
636
  if (value === void 0 || value === null)
@@ -247,6 +645,7 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
247
645
  return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
248
646
  };
249
647
  function buildBaseUrl({
648
+ method,
250
649
  endpoint,
251
650
  path,
252
651
  workspacesApiUrl,
@@ -254,7 +653,24 @@ function buildBaseUrl({
254
653
  pathParams = {}
255
654
  }) {
256
655
  if (endpoint === "dataPlane") {
257
- const url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
656
+ let url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
657
+ if (method.toUpperCase() === "PUT" && [
658
+ "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
659
+ "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}"
660
+ ].includes(path)) {
661
+ const { host } = parseWorkspacesUrlParts(url) ?? {};
662
+ switch (host) {
663
+ case "production":
664
+ url = url.replace("xata.sh", "upload.xata.sh");
665
+ break;
666
+ case "staging":
667
+ url = url.replace("staging-xata.dev", "upload.staging-xata.dev");
668
+ break;
669
+ case "dev":
670
+ url = url.replace("dev-xata.dev", "upload.dev-xata.dev");
671
+ break;
672
+ }
673
+ }
258
674
  const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
259
675
  return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
260
676
  }
@@ -265,14 +681,27 @@ function hostHeader(url) {
265
681
  const { groups } = pattern.exec(url) ?? {};
266
682
  return groups?.host ? { Host: groups.host } : {};
267
683
  }
684
+ async function parseBody(body, headers) {
685
+ if (!isDefined(body))
686
+ return void 0;
687
+ if (isBlob(body) || typeof body.text === "function") {
688
+ return body;
689
+ }
690
+ const { "Content-Type": contentType } = headers ?? {};
691
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
692
+ return JSON.stringify(body);
693
+ }
694
+ return body;
695
+ }
696
+ const defaultClientID = generateUUID();
268
697
  async function fetch$1({
269
698
  url: path,
270
699
  method,
271
700
  body,
272
- headers,
701
+ headers: customHeaders,
273
702
  pathParams,
274
703
  queryParams,
275
- fetchImpl,
704
+ fetch: fetch2,
276
705
  apiKey,
277
706
  endpoint,
278
707
  apiUrl,
@@ -281,36 +710,45 @@ async function fetch$1({
281
710
  signal,
282
711
  clientID,
283
712
  sessionID,
284
- fetchOptions = {}
713
+ clientName,
714
+ xataAgentExtra,
715
+ fetchOptions = {},
716
+ rawResponse = false
285
717
  }) {
286
- return trace(
718
+ pool.setFetch(fetch2);
719
+ return await trace(
287
720
  `${method.toUpperCase()} ${path}`,
288
721
  async ({ setAttributes }) => {
289
- const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
722
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
290
723
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
291
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
724
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\.[^.]+\./, "http://") : fullUrl;
292
725
  setAttributes({
293
726
  [TraceAttributes.HTTP_URL]: url,
294
727
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
295
728
  });
296
- const response = await fetchImpl(url, {
729
+ const xataAgent = compact([
730
+ ["client", "TS_SDK"],
731
+ ["version", VERSION],
732
+ isDefined(clientName) ? ["service", clientName] : void 0,
733
+ ...Object.entries(xataAgentExtra ?? {})
734
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
735
+ const headers = compactObject({
736
+ "Accept-Encoding": "identity",
737
+ "Content-Type": "application/json",
738
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
739
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
740
+ "X-Xata-Agent": xataAgent,
741
+ ...customHeaders,
742
+ ...hostHeader(fullUrl),
743
+ Authorization: `Bearer ${apiKey}`
744
+ });
745
+ const response = await pool.request(url, {
297
746
  ...fetchOptions,
298
747
  method: method.toUpperCase(),
299
- body: body ? JSON.stringify(body) : void 0,
300
- headers: {
301
- "Content-Type": "application/json",
302
- "User-Agent": `Xata client-ts/${VERSION}`,
303
- "X-Xata-Client-ID": clientID ?? "",
304
- "X-Xata-Session-ID": sessionID ?? "",
305
- ...headers,
306
- ...hostHeader(fullUrl),
307
- Authorization: `Bearer ${apiKey}`
308
- },
748
+ body: await parseBody(body, headers),
749
+ headers,
309
750
  signal
310
751
  });
311
- if (response.status === 204) {
312
- return {};
313
- }
314
752
  const { host, protocol } = parseUrl(response.url);
315
753
  const requestId = response.headers?.get("x-request-id") ?? void 0;
316
754
  setAttributes({
@@ -318,10 +756,20 @@ async function fetch$1({
318
756
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
319
757
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
320
758
  [TraceAttributes.HTTP_HOST]: host,
321
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
759
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
760
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
322
761
  });
762
+ const message = response.headers?.get("x-xata-message");
763
+ if (message)
764
+ console.warn(message);
765
+ if (response.status === 204) {
766
+ return {};
767
+ }
768
+ if (response.status === 429) {
769
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
770
+ }
323
771
  try {
324
- const jsonResponse = await response.json();
772
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
325
773
  if (response.ok) {
326
774
  return jsonResponse;
327
775
  }
@@ -333,6 +781,59 @@ async function fetch$1({
333
781
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
334
782
  );
335
783
  }
784
+ function fetchSSERequest({
785
+ url: path,
786
+ method,
787
+ body,
788
+ headers: customHeaders,
789
+ pathParams,
790
+ queryParams,
791
+ fetch: fetch2,
792
+ apiKey,
793
+ endpoint,
794
+ apiUrl,
795
+ workspacesApiUrl,
796
+ onMessage,
797
+ onError,
798
+ onClose,
799
+ signal,
800
+ clientID,
801
+ sessionID,
802
+ clientName,
803
+ xataAgentExtra
804
+ }) {
805
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
806
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
807
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
808
+ void fetchEventSource(url, {
809
+ method,
810
+ body: JSON.stringify(body),
811
+ fetch: fetch2,
812
+ signal,
813
+ headers: {
814
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
815
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
816
+ "X-Xata-Agent": compact([
817
+ ["client", "TS_SDK"],
818
+ ["version", VERSION],
819
+ isDefined(clientName) ? ["service", clientName] : void 0,
820
+ ...Object.entries(xataAgentExtra ?? {})
821
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
822
+ ...customHeaders,
823
+ Authorization: `Bearer ${apiKey}`,
824
+ "Content-Type": "application/json"
825
+ },
826
+ onmessage(ev) {
827
+ onMessage?.(JSON.parse(ev.data));
828
+ },
829
+ onerror(ev) {
830
+ onError?.(JSON.parse(ev.data));
831
+ },
832
+ onclose() {
833
+ onClose?.();
834
+ }
835
+ });
836
+ }
336
837
  function parseUrl(url) {
337
838
  try {
338
839
  const { host, protocol } = new URL(url);
@@ -344,17 +845,26 @@ function parseUrl(url) {
344
845
 
345
846
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
346
847
 
347
- const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
848
+ const applyMigration = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/pgroll/apply", method: "post", ...variables, signal });
849
+ const pgRollStatus = (variables, signal) => dataPlaneFetch({
850
+ url: "/db/{dbBranchName}/pgroll/status",
851
+ method: "get",
852
+ ...variables,
853
+ signal
854
+ });
855
+ const pgRollJobStatus = (variables, signal) => dataPlaneFetch({
856
+ url: "/db/{dbBranchName}/pgroll/jobs/{jobId}",
857
+ method: "get",
858
+ ...variables,
859
+ signal
860
+ });
861
+ const pgRollMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/pgroll/migrations", method: "get", ...variables, signal });
348
862
  const getBranchList = (variables, signal) => dataPlaneFetch({
349
863
  url: "/dbs/{dbName}",
350
864
  method: "get",
351
865
  ...variables,
352
866
  signal
353
867
  });
354
- const dEPRECATEDcreateDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
355
- const dEPRECATEDdeleteDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "delete", ...variables, signal });
356
- const dEPRECATEDgetDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "get", ...variables, signal });
357
- const dEPRECATEDupdateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
358
868
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
359
869
  url: "/db/{dbBranchName}",
360
870
  method: "get",
@@ -368,6 +878,18 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
368
878
  ...variables,
369
879
  signal
370
880
  });
881
+ const getSchema = (variables, signal) => dataPlaneFetch({
882
+ url: "/db/{dbBranchName}/schema",
883
+ method: "get",
884
+ ...variables,
885
+ signal
886
+ });
887
+ const copyBranch = (variables, signal) => dataPlaneFetch({
888
+ url: "/db/{dbBranchName}/copy",
889
+ method: "post",
890
+ ...variables,
891
+ signal
892
+ });
371
893
  const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
372
894
  url: "/db/{dbBranchName}/metadata",
373
895
  method: "put",
@@ -393,7 +915,6 @@ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName
393
915
  const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
394
916
  const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
395
917
  const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
396
- const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
397
918
  const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
398
919
  const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
399
920
  const getMigrationRequest = (variables, signal) => dataPlaneFetch({
@@ -418,6 +939,7 @@ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{
418
939
  const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
419
940
  const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
420
941
  const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
942
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
421
943
  const createTable = (variables, signal) => dataPlaneFetch({
422
944
  url: "/db/{dbBranchName}/tables/{tableName}",
423
945
  method: "put",
@@ -460,7 +982,44 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
460
982
  ...variables,
461
983
  signal
462
984
  });
985
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
463
986
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
987
+ const getFileItem = (variables, signal) => dataPlaneFetch({
988
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
989
+ method: "get",
990
+ ...variables,
991
+ signal
992
+ });
993
+ const putFileItem = (variables, signal) => dataPlaneFetch({
994
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
995
+ method: "put",
996
+ ...variables,
997
+ signal
998
+ });
999
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
1000
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
1001
+ method: "delete",
1002
+ ...variables,
1003
+ signal
1004
+ });
1005
+ const getFile = (variables, signal) => dataPlaneFetch({
1006
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1007
+ method: "get",
1008
+ ...variables,
1009
+ signal
1010
+ });
1011
+ const putFile = (variables, signal) => dataPlaneFetch({
1012
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1013
+ method: "put",
1014
+ ...variables,
1015
+ signal
1016
+ });
1017
+ const deleteFile = (variables, signal) => dataPlaneFetch({
1018
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1019
+ method: "delete",
1020
+ ...variables,
1021
+ signal
1022
+ });
464
1023
  const getRecord = (variables, signal) => dataPlaneFetch({
465
1024
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
466
1025
  method: "get",
@@ -490,21 +1049,45 @@ const searchTable = (variables, signal) => dataPlaneFetch({
490
1049
  ...variables,
491
1050
  signal
492
1051
  });
1052
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
1053
+ const askTable = (variables, signal) => dataPlaneFetch({
1054
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
1055
+ method: "post",
1056
+ ...variables,
1057
+ signal
1058
+ });
1059
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
493
1060
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
494
1061
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
1062
+ const fileAccess = (variables, signal) => dataPlaneFetch({
1063
+ url: "/file/{fileId}",
1064
+ method: "get",
1065
+ ...variables,
1066
+ signal
1067
+ });
1068
+ const fileUpload = (variables, signal) => dataPlaneFetch({
1069
+ url: "/file/{fileId}",
1070
+ method: "put",
1071
+ ...variables,
1072
+ signal
1073
+ });
1074
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
1075
+ url: "/db/{dbBranchName}/sql",
1076
+ method: "post",
1077
+ ...variables,
1078
+ signal
1079
+ });
495
1080
  const operationsByTag$2 = {
496
- database: {
497
- dEPRECATEDgetDatabaseList,
498
- dEPRECATEDcreateDatabase,
499
- dEPRECATEDdeleteDatabase,
500
- dEPRECATEDgetDatabaseMetadata,
501
- dEPRECATEDupdateDatabaseMetadata
502
- },
503
1081
  branch: {
1082
+ applyMigration,
1083
+ pgRollStatus,
1084
+ pgRollJobStatus,
1085
+ pgRollMigrationHistory,
504
1086
  getBranchList,
505
1087
  getBranchDetails,
506
1088
  createBranch,
507
1089
  deleteBranch,
1090
+ copyBranch,
508
1091
  updateBranchMetadata,
509
1092
  getBranchMetadata,
510
1093
  getBranchStats,
@@ -514,6 +1097,7 @@ const operationsByTag$2 = {
514
1097
  resolveBranch
515
1098
  },
516
1099
  migrations: {
1100
+ getSchema,
517
1101
  getBranchMigrationHistory,
518
1102
  getBranchMigrationPlan,
519
1103
  executeBranchMigrationPlan,
@@ -522,17 +1106,8 @@ const operationsByTag$2 = {
522
1106
  compareBranchSchemas,
523
1107
  updateBranchSchema,
524
1108
  previewBranchSchemaEdit,
525
- applyBranchSchemaEdit
526
- },
527
- records: {
528
- branchTransaction,
529
- insertRecord,
530
- getRecord,
531
- insertRecordWithID,
532
- updateRecordWithID,
533
- upsertRecordWithID,
534
- deleteRecord,
535
- bulkInsertTableRecords
1109
+ applyBranchSchemaEdit,
1110
+ pushBranchMigrations
536
1111
  },
537
1112
  migrationRequests: {
538
1113
  queryMigrationRequests,
@@ -556,11 +1131,34 @@ const operationsByTag$2 = {
556
1131
  updateColumn,
557
1132
  deleteColumn
558
1133
  },
559
- searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
1134
+ records: {
1135
+ branchTransaction,
1136
+ insertRecord,
1137
+ getRecord,
1138
+ insertRecordWithID,
1139
+ updateRecordWithID,
1140
+ upsertRecordWithID,
1141
+ deleteRecord,
1142
+ bulkInsertTableRecords
1143
+ },
1144
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess, fileUpload },
1145
+ searchAndFilter: {
1146
+ queryTable,
1147
+ searchBranch,
1148
+ searchTable,
1149
+ vectorSearchTable,
1150
+ askTable,
1151
+ askTableSession,
1152
+ summarizeTable,
1153
+ aggregateTable
1154
+ },
1155
+ sql: { sqlQuery }
560
1156
  };
561
1157
 
562
1158
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
563
1159
 
1160
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1161
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
564
1162
  const getUser = (variables, signal) => controlPlaneFetch({
565
1163
  url: "/user",
566
1164
  method: "get",
@@ -585,18 +1183,43 @@ const getUserAPIKeys = (variables, signal) => controlPlaneFetch({
585
1183
  ...variables,
586
1184
  signal
587
1185
  });
588
- const createUserAPIKey = (variables, signal) => controlPlaneFetch({
589
- url: "/user/keys/{keyName}",
590
- method: "post",
1186
+ const createUserAPIKey = (variables, signal) => controlPlaneFetch({
1187
+ url: "/user/keys/{keyName}",
1188
+ method: "post",
1189
+ ...variables,
1190
+ signal
1191
+ });
1192
+ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
1193
+ url: "/user/keys/{keyName}",
1194
+ method: "delete",
1195
+ ...variables,
1196
+ signal
1197
+ });
1198
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1199
+ url: "/user/oauth/clients",
1200
+ method: "get",
1201
+ ...variables,
1202
+ signal
1203
+ });
1204
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1205
+ url: "/user/oauth/clients/{clientId}",
1206
+ method: "delete",
1207
+ ...variables,
1208
+ signal
1209
+ });
1210
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1211
+ url: "/user/oauth/tokens",
1212
+ method: "get",
591
1213
  ...variables,
592
1214
  signal
593
1215
  });
594
- const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
595
- url: "/user/keys/{keyName}",
1216
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1217
+ url: "/user/oauth/tokens/{token}",
596
1218
  method: "delete",
597
1219
  ...variables,
598
1220
  signal
599
1221
  });
1222
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
600
1223
  const getWorkspacesList = (variables, signal) => controlPlaneFetch({
601
1224
  url: "/workspaces",
602
1225
  method: "get",
@@ -640,6 +1263,15 @@ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ u
640
1263
  const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
641
1264
  const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
642
1265
  const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1266
+ const listClusters = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "get", ...variables, signal });
1267
+ const createCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "post", ...variables, signal });
1268
+ const getCluster = (variables, signal) => controlPlaneFetch({
1269
+ url: "/workspaces/{workspaceId}/clusters/{clusterId}",
1270
+ method: "get",
1271
+ ...variables,
1272
+ signal
1273
+ });
1274
+ const updateCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters/{clusterId}", method: "patch", ...variables, signal });
643
1275
  const getDatabaseList = (variables, signal) => controlPlaneFetch({
644
1276
  url: "/workspaces/{workspaceId}/dbs",
645
1277
  method: "get",
@@ -655,6 +1287,10 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
655
1287
  });
656
1288
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
657
1289
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1290
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1291
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1292
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1293
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
658
1294
  const listRegions = (variables, signal) => controlPlaneFetch({
659
1295
  url: "/workspaces/{workspaceId}/regions",
660
1296
  method: "get",
@@ -662,6 +1298,15 @@ const listRegions = (variables, signal) => controlPlaneFetch({
662
1298
  signal
663
1299
  });
664
1300
  const operationsByTag$1 = {
1301
+ oAuth: {
1302
+ getAuthorizationCode,
1303
+ grantAuthorizationCode,
1304
+ getUserOAuthClients,
1305
+ deleteUserOAuthClient,
1306
+ getUserOAuthAccessTokens,
1307
+ deleteOAuthAccessToken,
1308
+ updateOAuthAccessToken
1309
+ },
665
1310
  users: { getUser, updateUser, deleteUser },
666
1311
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
667
1312
  workspaces: {
@@ -681,62 +1326,23 @@ const operationsByTag$1 = {
681
1326
  acceptWorkspaceMemberInvite,
682
1327
  resendWorkspaceMemberInvite
683
1328
  },
1329
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
684
1330
  databases: {
685
1331
  getDatabaseList,
686
1332
  createDatabase,
687
1333
  deleteDatabase,
688
1334
  getDatabaseMetadata,
689
1335
  updateDatabaseMetadata,
1336
+ renameDatabase,
1337
+ getDatabaseGithubSettings,
1338
+ updateDatabaseGithubSettings,
1339
+ deleteDatabaseGithubSettings,
690
1340
  listRegions
691
1341
  }
692
1342
  };
693
1343
 
694
1344
  const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);
695
1345
 
696
- function getHostUrl(provider, type) {
697
- if (isHostProviderAlias(provider)) {
698
- return providers[provider][type];
699
- } else if (isHostProviderBuilder(provider)) {
700
- return provider[type];
701
- }
702
- throw new Error("Invalid API provider");
703
- }
704
- const providers = {
705
- production: {
706
- main: "https://api.xata.io",
707
- workspaces: "https://{workspaceId}.{region}.xata.sh"
708
- },
709
- staging: {
710
- main: "https://staging.xatabase.co",
711
- workspaces: "https://{workspaceId}.staging.{region}.xatabase.co"
712
- }
713
- };
714
- function isHostProviderAlias(alias) {
715
- return isString(alias) && Object.keys(providers).includes(alias);
716
- }
717
- function isHostProviderBuilder(builder) {
718
- return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
719
- }
720
- function parseProviderString(provider = "production") {
721
- if (isHostProviderAlias(provider)) {
722
- return provider;
723
- }
724
- const [main, workspaces] = provider.split(",");
725
- if (!main || !workspaces)
726
- return null;
727
- return { main, workspaces };
728
- }
729
- function parseWorkspacesUrlParts(url) {
730
- if (!isString(url))
731
- return null;
732
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
733
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
734
- const match = url.match(regex) || url.match(regexStaging);
735
- if (!match)
736
- return null;
737
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
738
- }
739
-
740
1346
  var __accessCheck$7 = (obj, member, msg) => {
741
1347
  if (!member.has(obj))
742
1348
  throw TypeError("Cannot " + msg);
@@ -763,15 +1369,19 @@ class XataApiClient {
763
1369
  const provider = options.host ?? "production";
764
1370
  const apiKey = options.apiKey ?? getAPIKey();
765
1371
  const trace = options.trace ?? defaultTrace;
1372
+ const clientID = generateUUID();
766
1373
  if (!apiKey) {
767
1374
  throw new Error("Could not resolve a valid apiKey");
768
1375
  }
769
1376
  __privateSet$7(this, _extraProps, {
770
1377
  apiUrl: getHostUrl(provider, "main"),
771
1378
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
772
- fetchImpl: getFetchImplementation(options.fetch),
1379
+ fetch: getFetchImplementation(options.fetch),
773
1380
  apiKey,
774
- trace
1381
+ trace,
1382
+ clientName: options.clientName,
1383
+ xataAgentExtra: options.xataAgentExtra,
1384
+ clientID
775
1385
  });
776
1386
  }
777
1387
  get user() {
@@ -824,6 +1434,11 @@ class XataApiClient {
824
1434
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
825
1435
  return __privateGet$7(this, _namespaces).records;
826
1436
  }
1437
+ get files() {
1438
+ if (!__privateGet$7(this, _namespaces).files)
1439
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1440
+ return __privateGet$7(this, _namespaces).files;
1441
+ }
827
1442
  get searchAndFilter() {
828
1443
  if (!__privateGet$7(this, _namespaces).searchAndFilter)
829
1444
  __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
@@ -1032,6 +1647,20 @@ class BranchApi {
1032
1647
  ...this.extraProps
1033
1648
  });
1034
1649
  }
1650
+ copyBranch({
1651
+ workspace,
1652
+ region,
1653
+ database,
1654
+ branch,
1655
+ destinationBranch,
1656
+ limit
1657
+ }) {
1658
+ return operationsByTag.branch.copyBranch({
1659
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1660
+ body: { destinationBranch, limit },
1661
+ ...this.extraProps
1662
+ });
1663
+ }
1035
1664
  updateBranchMetadata({
1036
1665
  workspace,
1037
1666
  region,
@@ -1387,6 +2016,164 @@ class RecordsApi {
1387
2016
  });
1388
2017
  }
1389
2018
  }
2019
+ class FilesApi {
2020
+ constructor(extraProps) {
2021
+ this.extraProps = extraProps;
2022
+ }
2023
+ getFileItem({
2024
+ workspace,
2025
+ region,
2026
+ database,
2027
+ branch,
2028
+ table,
2029
+ record,
2030
+ column,
2031
+ fileId
2032
+ }) {
2033
+ return operationsByTag.files.getFileItem({
2034
+ pathParams: {
2035
+ workspace,
2036
+ region,
2037
+ dbBranchName: `${database}:${branch}`,
2038
+ tableName: table,
2039
+ recordId: record,
2040
+ columnName: column,
2041
+ fileId
2042
+ },
2043
+ ...this.extraProps
2044
+ });
2045
+ }
2046
+ putFileItem({
2047
+ workspace,
2048
+ region,
2049
+ database,
2050
+ branch,
2051
+ table,
2052
+ record,
2053
+ column,
2054
+ fileId,
2055
+ file
2056
+ }) {
2057
+ return operationsByTag.files.putFileItem({
2058
+ pathParams: {
2059
+ workspace,
2060
+ region,
2061
+ dbBranchName: `${database}:${branch}`,
2062
+ tableName: table,
2063
+ recordId: record,
2064
+ columnName: column,
2065
+ fileId
2066
+ },
2067
+ // @ts-ignore
2068
+ body: file,
2069
+ ...this.extraProps
2070
+ });
2071
+ }
2072
+ deleteFileItem({
2073
+ workspace,
2074
+ region,
2075
+ database,
2076
+ branch,
2077
+ table,
2078
+ record,
2079
+ column,
2080
+ fileId
2081
+ }) {
2082
+ return operationsByTag.files.deleteFileItem({
2083
+ pathParams: {
2084
+ workspace,
2085
+ region,
2086
+ dbBranchName: `${database}:${branch}`,
2087
+ tableName: table,
2088
+ recordId: record,
2089
+ columnName: column,
2090
+ fileId
2091
+ },
2092
+ ...this.extraProps
2093
+ });
2094
+ }
2095
+ getFile({
2096
+ workspace,
2097
+ region,
2098
+ database,
2099
+ branch,
2100
+ table,
2101
+ record,
2102
+ column
2103
+ }) {
2104
+ return operationsByTag.files.getFile({
2105
+ pathParams: {
2106
+ workspace,
2107
+ region,
2108
+ dbBranchName: `${database}:${branch}`,
2109
+ tableName: table,
2110
+ recordId: record,
2111
+ columnName: column
2112
+ },
2113
+ ...this.extraProps
2114
+ });
2115
+ }
2116
+ putFile({
2117
+ workspace,
2118
+ region,
2119
+ database,
2120
+ branch,
2121
+ table,
2122
+ record,
2123
+ column,
2124
+ file
2125
+ }) {
2126
+ return operationsByTag.files.putFile({
2127
+ pathParams: {
2128
+ workspace,
2129
+ region,
2130
+ dbBranchName: `${database}:${branch}`,
2131
+ tableName: table,
2132
+ recordId: record,
2133
+ columnName: column
2134
+ },
2135
+ body: file,
2136
+ ...this.extraProps
2137
+ });
2138
+ }
2139
+ deleteFile({
2140
+ workspace,
2141
+ region,
2142
+ database,
2143
+ branch,
2144
+ table,
2145
+ record,
2146
+ column
2147
+ }) {
2148
+ return operationsByTag.files.deleteFile({
2149
+ pathParams: {
2150
+ workspace,
2151
+ region,
2152
+ dbBranchName: `${database}:${branch}`,
2153
+ tableName: table,
2154
+ recordId: record,
2155
+ columnName: column
2156
+ },
2157
+ ...this.extraProps
2158
+ });
2159
+ }
2160
+ fileAccess({
2161
+ workspace,
2162
+ region,
2163
+ fileId,
2164
+ verify
2165
+ }) {
2166
+ return operationsByTag.files.fileAccess({
2167
+ pathParams: {
2168
+ workspace,
2169
+ region,
2170
+ fileId
2171
+ },
2172
+ queryParams: { verify },
2173
+ ...this.extraProps
2174
+ });
2175
+ }
2176
+ }
1390
2177
  class SearchAndFilterApi {
1391
2178
  constructor(extraProps) {
1392
2179
  this.extraProps = extraProps;
@@ -1446,6 +2233,53 @@ class SearchAndFilterApi {
1446
2233
  ...this.extraProps
1447
2234
  });
1448
2235
  }
2236
+ vectorSearchTable({
2237
+ workspace,
2238
+ region,
2239
+ database,
2240
+ branch,
2241
+ table,
2242
+ queryVector,
2243
+ column,
2244
+ similarityFunction,
2245
+ size,
2246
+ filter
2247
+ }) {
2248
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2249
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2250
+ body: { queryVector, column, similarityFunction, size, filter },
2251
+ ...this.extraProps
2252
+ });
2253
+ }
2254
+ askTable({
2255
+ workspace,
2256
+ region,
2257
+ database,
2258
+ branch,
2259
+ table,
2260
+ options
2261
+ }) {
2262
+ return operationsByTag.searchAndFilter.askTable({
2263
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2264
+ body: { ...options },
2265
+ ...this.extraProps
2266
+ });
2267
+ }
2268
+ askTableSession({
2269
+ workspace,
2270
+ region,
2271
+ database,
2272
+ branch,
2273
+ table,
2274
+ sessionId,
2275
+ message
2276
+ }) {
2277
+ return operationsByTag.searchAndFilter.askTableSession({
2278
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2279
+ body: { message },
2280
+ ...this.extraProps
2281
+ });
2282
+ }
1449
2283
  summarizeTable({
1450
2284
  workspace,
1451
2285
  region,
@@ -1646,11 +2480,13 @@ class MigrationsApi {
1646
2480
  region,
1647
2481
  database,
1648
2482
  branch,
1649
- schema
2483
+ schema,
2484
+ schemaOperations,
2485
+ branchOperations
1650
2486
  }) {
1651
2487
  return operationsByTag.migrations.compareBranchWithUserSchema({
1652
2488
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1653
- body: { schema },
2489
+ body: { schema, schemaOperations, branchOperations },
1654
2490
  ...this.extraProps
1655
2491
  });
1656
2492
  }
@@ -1660,11 +2496,12 @@ class MigrationsApi {
1660
2496
  database,
1661
2497
  branch,
1662
2498
  compare,
1663
- schema
2499
+ sourceBranchOperations,
2500
+ targetBranchOperations
1664
2501
  }) {
1665
2502
  return operationsByTag.migrations.compareBranchSchemas({
1666
2503
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1667
- body: { schema },
2504
+ body: { sourceBranchOperations, targetBranchOperations },
1668
2505
  ...this.extraProps
1669
2506
  });
1670
2507
  }
@@ -1707,6 +2544,19 @@ class MigrationsApi {
1707
2544
  ...this.extraProps
1708
2545
  });
1709
2546
  }
2547
+ pushBranchMigrations({
2548
+ workspace,
2549
+ region,
2550
+ database,
2551
+ branch,
2552
+ migrations
2553
+ }) {
2554
+ return operationsByTag.migrations.pushBranchMigrations({
2555
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2556
+ body: { migrations },
2557
+ ...this.extraProps
2558
+ });
2559
+ }
1710
2560
  }
1711
2561
  class DatabaseApi {
1712
2562
  constructor(extraProps) {
@@ -1721,11 +2571,13 @@ class DatabaseApi {
1721
2571
  createDatabase({
1722
2572
  workspace,
1723
2573
  database,
1724
- data
2574
+ data,
2575
+ headers
1725
2576
  }) {
1726
2577
  return operationsByTag.databases.createDatabase({
1727
2578
  pathParams: { workspaceId: workspace, dbName: database },
1728
2579
  body: data,
2580
+ headers,
1729
2581
  ...this.extraProps
1730
2582
  });
1731
2583
  }
@@ -1758,36 +2610,252 @@ class DatabaseApi {
1758
2610
  ...this.extraProps
1759
2611
  });
1760
2612
  }
1761
- listRegions({ workspace }) {
1762
- return operationsByTag.databases.listRegions({
1763
- pathParams: { workspaceId: workspace },
1764
- ...this.extraProps
1765
- });
2613
+ renameDatabase({
2614
+ workspace,
2615
+ database,
2616
+ newName
2617
+ }) {
2618
+ return operationsByTag.databases.renameDatabase({
2619
+ pathParams: { workspaceId: workspace, dbName: database },
2620
+ body: { newName },
2621
+ ...this.extraProps
2622
+ });
2623
+ }
2624
+ getDatabaseGithubSettings({
2625
+ workspace,
2626
+ database
2627
+ }) {
2628
+ return operationsByTag.databases.getDatabaseGithubSettings({
2629
+ pathParams: { workspaceId: workspace, dbName: database },
2630
+ ...this.extraProps
2631
+ });
2632
+ }
2633
+ updateDatabaseGithubSettings({
2634
+ workspace,
2635
+ database,
2636
+ settings
2637
+ }) {
2638
+ return operationsByTag.databases.updateDatabaseGithubSettings({
2639
+ pathParams: { workspaceId: workspace, dbName: database },
2640
+ body: settings,
2641
+ ...this.extraProps
2642
+ });
2643
+ }
2644
+ deleteDatabaseGithubSettings({
2645
+ workspace,
2646
+ database
2647
+ }) {
2648
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
2649
+ pathParams: { workspaceId: workspace, dbName: database },
2650
+ ...this.extraProps
2651
+ });
2652
+ }
2653
+ listRegions({ workspace }) {
2654
+ return operationsByTag.databases.listRegions({
2655
+ pathParams: { workspaceId: workspace },
2656
+ ...this.extraProps
2657
+ });
2658
+ }
2659
+ }
2660
+
2661
+ class XataApiPlugin {
2662
+ build(options) {
2663
+ return new XataApiClient(options);
2664
+ }
2665
+ }
2666
+
2667
+ class XataPlugin {
2668
+ }
2669
+
2670
+ function buildTransformString(transformations) {
2671
+ return transformations.flatMap(
2672
+ (t) => Object.entries(t).map(([key, value]) => {
2673
+ if (key === "trim") {
2674
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2675
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2676
+ }
2677
+ if (key === "gravity" && typeof value === "object") {
2678
+ const { x = 0.5, y = 0.5 } = value;
2679
+ return `${key}=${[x, y].join("x")}`;
2680
+ }
2681
+ return `${key}=${value}`;
2682
+ })
2683
+ ).join(",");
2684
+ }
2685
+ function transformImage(url, ...transformations) {
2686
+ if (!isDefined(url))
2687
+ return void 0;
2688
+ const newTransformations = buildTransformString(transformations);
2689
+ const { hostname, pathname, search } = new URL(url);
2690
+ const pathParts = pathname.split("/");
2691
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2692
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2693
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2694
+ const path = pathParts.join("/");
2695
+ return `https://${hostname}${transform}${path}${search}`;
2696
+ }
2697
+
2698
+ class XataFile {
2699
+ constructor(file) {
2700
+ this.id = file.id;
2701
+ this.name = file.name;
2702
+ this.mediaType = file.mediaType;
2703
+ this.base64Content = file.base64Content;
2704
+ this.enablePublicUrl = file.enablePublicUrl;
2705
+ this.signedUrlTimeout = file.signedUrlTimeout;
2706
+ this.uploadUrlTimeout = file.uploadUrlTimeout;
2707
+ this.size = file.size;
2708
+ this.version = file.version;
2709
+ this.url = file.url;
2710
+ this.signedUrl = file.signedUrl;
2711
+ this.uploadUrl = file.uploadUrl;
2712
+ this.attributes = file.attributes;
2713
+ }
2714
+ static fromBuffer(buffer, options = {}) {
2715
+ const base64Content = buffer.toString("base64");
2716
+ return new XataFile({ ...options, base64Content });
2717
+ }
2718
+ toBuffer() {
2719
+ if (!this.base64Content) {
2720
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2721
+ }
2722
+ return Buffer.from(this.base64Content, "base64");
2723
+ }
2724
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2725
+ const uint8Array = new Uint8Array(arrayBuffer);
2726
+ return this.fromUint8Array(uint8Array, options);
2727
+ }
2728
+ toArrayBuffer() {
2729
+ if (!this.base64Content) {
2730
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2731
+ }
2732
+ const binary = atob(this.base64Content);
2733
+ return new ArrayBuffer(binary.length);
2734
+ }
2735
+ static fromUint8Array(uint8Array, options = {}) {
2736
+ let binary = "";
2737
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2738
+ binary += String.fromCharCode(uint8Array[i]);
2739
+ }
2740
+ const base64Content = btoa(binary);
2741
+ return new XataFile({ ...options, base64Content });
2742
+ }
2743
+ toUint8Array() {
2744
+ if (!this.base64Content) {
2745
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2746
+ }
2747
+ const binary = atob(this.base64Content);
2748
+ const uint8Array = new Uint8Array(binary.length);
2749
+ for (let i = 0; i < binary.length; i++) {
2750
+ uint8Array[i] = binary.charCodeAt(i);
2751
+ }
2752
+ return uint8Array;
2753
+ }
2754
+ static async fromBlob(file, options = {}) {
2755
+ const name = options.name ?? file.name;
2756
+ const mediaType = file.type;
2757
+ const arrayBuffer = await file.arrayBuffer();
2758
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2759
+ }
2760
+ toBlob() {
2761
+ if (!this.base64Content) {
2762
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2763
+ }
2764
+ const binary = atob(this.base64Content);
2765
+ const uint8Array = new Uint8Array(binary.length);
2766
+ for (let i = 0; i < binary.length; i++) {
2767
+ uint8Array[i] = binary.charCodeAt(i);
2768
+ }
2769
+ return new Blob([uint8Array], { type: this.mediaType });
2770
+ }
2771
+ static fromString(string, options = {}) {
2772
+ const base64Content = btoa(string);
2773
+ return new XataFile({ ...options, base64Content });
1766
2774
  }
1767
- }
1768
-
1769
- class XataApiPlugin {
1770
- async build(options) {
1771
- const { fetchImpl, apiKey } = await options.getFetchProps();
1772
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2775
+ toString() {
2776
+ if (!this.base64Content) {
2777
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2778
+ }
2779
+ return atob(this.base64Content);
2780
+ }
2781
+ static fromBase64(base64Content, options = {}) {
2782
+ return new XataFile({ ...options, base64Content });
2783
+ }
2784
+ toBase64() {
2785
+ if (!this.base64Content) {
2786
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2787
+ }
2788
+ return this.base64Content;
2789
+ }
2790
+ transform(...options) {
2791
+ return {
2792
+ url: transformImage(this.url, ...options),
2793
+ signedUrl: transformImage(this.signedUrl, ...options),
2794
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2795
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2796
+ };
1773
2797
  }
1774
2798
  }
1775
-
1776
- class XataPlugin {
1777
- }
1778
-
1779
- function generateUUID() {
1780
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1781
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1782
- return v.toString(16);
2799
+ const parseInputFileEntry = async (entry) => {
2800
+ if (!isDefined(entry))
2801
+ return null;
2802
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout, uploadUrlTimeout } = await entry;
2803
+ return compactObject({
2804
+ id,
2805
+ // Name cannot be an empty string in our API
2806
+ name: name ? name : void 0,
2807
+ mediaType,
2808
+ base64Content,
2809
+ enablePublicUrl,
2810
+ signedUrlTimeout,
2811
+ uploadUrlTimeout
1783
2812
  });
1784
- }
2813
+ };
1785
2814
 
1786
2815
  function cleanFilter(filter) {
1787
- if (!filter)
2816
+ if (!isDefined(filter))
1788
2817
  return void 0;
1789
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1790
- return values.length > 0 ? filter : void 0;
2818
+ if (!isObject(filter))
2819
+ return filter;
2820
+ const values = Object.fromEntries(
2821
+ Object.entries(filter).reduce((acc, [key, value]) => {
2822
+ if (!isDefined(value))
2823
+ return acc;
2824
+ if (Array.isArray(value)) {
2825
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2826
+ if (clean.length === 0)
2827
+ return acc;
2828
+ return [...acc, [key, clean]];
2829
+ }
2830
+ if (isObject(value)) {
2831
+ const clean = cleanFilter(value);
2832
+ if (!isDefined(clean))
2833
+ return acc;
2834
+ return [...acc, [key, clean]];
2835
+ }
2836
+ return [...acc, [key, value]];
2837
+ }, [])
2838
+ );
2839
+ return Object.keys(values).length > 0 ? values : void 0;
2840
+ }
2841
+
2842
+ function stringifyJson(value) {
2843
+ if (!isDefined(value))
2844
+ return value;
2845
+ if (isString(value))
2846
+ return value;
2847
+ try {
2848
+ return JSON.stringify(value);
2849
+ } catch (e) {
2850
+ return value;
2851
+ }
2852
+ }
2853
+ function parseJson(value) {
2854
+ try {
2855
+ return JSON.parse(value);
2856
+ } catch (e) {
2857
+ return value;
2858
+ }
1791
2859
  }
1792
2860
 
1793
2861
  var __accessCheck$6 = (obj, member, msg) => {
@@ -1816,31 +2884,59 @@ class Page {
1816
2884
  this.meta = meta;
1817
2885
  this.records = new RecordArray(this, records);
1818
2886
  }
2887
+ /**
2888
+ * Retrieves the next page of results.
2889
+ * @param size Maximum number of results to be retrieved.
2890
+ * @param offset Number of results to skip when retrieving the results.
2891
+ * @returns The next page or results.
2892
+ */
1819
2893
  async nextPage(size, offset) {
1820
2894
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
1821
2895
  }
2896
+ /**
2897
+ * Retrieves the previous page of results.
2898
+ * @param size Maximum number of results to be retrieved.
2899
+ * @param offset Number of results to skip when retrieving the results.
2900
+ * @returns The previous page or results.
2901
+ */
1822
2902
  async previousPage(size, offset) {
1823
2903
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1824
2904
  }
2905
+ /**
2906
+ * Retrieves the start page of results.
2907
+ * @param size Maximum number of results to be retrieved.
2908
+ * @param offset Number of results to skip when retrieving the results.
2909
+ * @returns The start page or results.
2910
+ */
1825
2911
  async startPage(size, offset) {
1826
2912
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1827
2913
  }
2914
+ /**
2915
+ * Retrieves the end page of results.
2916
+ * @param size Maximum number of results to be retrieved.
2917
+ * @param offset Number of results to skip when retrieving the results.
2918
+ * @returns The end page or results.
2919
+ */
1828
2920
  async endPage(size, offset) {
1829
2921
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1830
2922
  }
2923
+ /**
2924
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
2925
+ * @returns Whether or not there will be additional results in the next page of results.
2926
+ */
1831
2927
  hasNextPage() {
1832
2928
  return this.meta.page.more;
1833
2929
  }
1834
2930
  }
1835
2931
  _query = new WeakMap();
1836
- const PAGINATION_MAX_SIZE = 200;
2932
+ const PAGINATION_MAX_SIZE = 1e3;
1837
2933
  const PAGINATION_DEFAULT_SIZE = 20;
1838
- const PAGINATION_MAX_OFFSET = 800;
2934
+ const PAGINATION_MAX_OFFSET = 49e3;
1839
2935
  const PAGINATION_DEFAULT_OFFSET = 0;
1840
2936
  function isCursorPaginationOptions(options) {
1841
2937
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1842
2938
  }
1843
- const _RecordArray = class extends Array {
2939
+ const _RecordArray = class _RecordArray extends Array {
1844
2940
  constructor(...args) {
1845
2941
  super(..._RecordArray.parseConstructorParams(...args));
1846
2942
  __privateAdd$6(this, _page, void 0);
@@ -1859,31 +2955,60 @@ const _RecordArray = class extends Array {
1859
2955
  toArray() {
1860
2956
  return new Array(...this);
1861
2957
  }
2958
+ toSerializable() {
2959
+ return JSON.parse(this.toString());
2960
+ }
2961
+ toString() {
2962
+ return JSON.stringify(this.toArray());
2963
+ }
1862
2964
  map(callbackfn, thisArg) {
1863
2965
  return this.toArray().map(callbackfn, thisArg);
1864
2966
  }
2967
+ /**
2968
+ * Retrieve next page of records
2969
+ *
2970
+ * @returns A new array of objects
2971
+ */
1865
2972
  async nextPage(size, offset) {
1866
2973
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1867
2974
  return new _RecordArray(newPage);
1868
2975
  }
2976
+ /**
2977
+ * Retrieve previous page of records
2978
+ *
2979
+ * @returns A new array of objects
2980
+ */
1869
2981
  async previousPage(size, offset) {
1870
2982
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1871
2983
  return new _RecordArray(newPage);
1872
2984
  }
2985
+ /**
2986
+ * Retrieve start page of records
2987
+ *
2988
+ * @returns A new array of objects
2989
+ */
1873
2990
  async startPage(size, offset) {
1874
2991
  const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1875
2992
  return new _RecordArray(newPage);
1876
2993
  }
2994
+ /**
2995
+ * Retrieve end page of records
2996
+ *
2997
+ * @returns A new array of objects
2998
+ */
1877
2999
  async endPage(size, offset) {
1878
3000
  const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1879
3001
  return new _RecordArray(newPage);
1880
3002
  }
3003
+ /**
3004
+ * @returns Boolean indicating if there is a next page
3005
+ */
1881
3006
  hasNextPage() {
1882
3007
  return __privateGet$6(this, _page).meta.page.more;
1883
3008
  }
1884
3009
  };
1885
- let RecordArray = _RecordArray;
1886
3010
  _page = new WeakMap();
3011
+ let RecordArray = _RecordArray;
1887
3012
 
1888
3013
  var __accessCheck$5 = (obj, member, msg) => {
1889
3014
  if (!member.has(obj))
@@ -1908,13 +3033,14 @@ var __privateMethod$3 = (obj, member, method) => {
1908
3033
  return method;
1909
3034
  };
1910
3035
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
1911
- const _Query = class {
3036
+ const _Query = class _Query {
1912
3037
  constructor(repository, table, data, rawParent) {
1913
3038
  __privateAdd$5(this, _cleanFilterConstraint);
1914
3039
  __privateAdd$5(this, _table$1, void 0);
1915
3040
  __privateAdd$5(this, _repository, void 0);
1916
3041
  __privateAdd$5(this, _data, { filter: {} });
1917
- this.meta = { page: { cursor: "start", more: true } };
3042
+ // Implements pagination
3043
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
1918
3044
  this.records = new RecordArray(this, []);
1919
3045
  __privateSet$5(this, _table$1, table);
1920
3046
  if (repository) {
@@ -1930,6 +3056,7 @@ const _Query = class {
1930
3056
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1931
3057
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1932
3058
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
3059
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
1933
3060
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1934
3061
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
1935
3062
  __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
@@ -1950,18 +3077,38 @@ const _Query = class {
1950
3077
  const key = JSON.stringify({ columns, filter, sort, pagination });
1951
3078
  return toBase64(key);
1952
3079
  }
3080
+ /**
3081
+ * Builds a new query object representing a logical OR between the given subqueries.
3082
+ * @param queries An array of subqueries.
3083
+ * @returns A new Query object.
3084
+ */
1953
3085
  any(...queries) {
1954
3086
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1955
3087
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
1956
3088
  }
3089
+ /**
3090
+ * Builds a new query object representing a logical AND between the given subqueries.
3091
+ * @param queries An array of subqueries.
3092
+ * @returns A new Query object.
3093
+ */
1957
3094
  all(...queries) {
1958
3095
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1959
3096
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1960
3097
  }
3098
+ /**
3099
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3100
+ * @param queries An array of subqueries.
3101
+ * @returns A new Query object.
3102
+ */
1961
3103
  not(...queries) {
1962
3104
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1963
3105
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
1964
3106
  }
3107
+ /**
3108
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3109
+ * @param queries An array of subqueries.
3110
+ * @returns A new Query object.
3111
+ */
1965
3112
  none(...queries) {
1966
3113
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1967
3114
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
@@ -1984,6 +3131,11 @@ const _Query = class {
1984
3131
  const sort = [...originalSort, { column, direction }];
1985
3132
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1986
3133
  }
3134
+ /**
3135
+ * Builds a new query specifying the set of columns to be returned in the query response.
3136
+ * @param columns Array of column names to be returned by the query.
3137
+ * @returns A new Query object.
3138
+ */
1987
3139
  select(columns) {
1988
3140
  return new _Query(
1989
3141
  __privateGet$5(this, _repository),
@@ -1996,6 +3148,12 @@ const _Query = class {
1996
3148
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1997
3149
  return __privateGet$5(this, _repository).query(query);
1998
3150
  }
3151
+ /**
3152
+ * Get results in an iterator
3153
+ *
3154
+ * @async
3155
+ * @returns Async interable of results
3156
+ */
1999
3157
  async *[Symbol.asyncIterator]() {
2000
3158
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
2001
3159
  yield record;
@@ -2056,26 +3214,53 @@ const _Query = class {
2056
3214
  );
2057
3215
  return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2058
3216
  }
3217
+ /**
3218
+ * Builds a new query object adding a cache TTL in milliseconds.
3219
+ * @param ttl The cache TTL in milliseconds.
3220
+ * @returns A new Query object.
3221
+ */
2059
3222
  cache(ttl) {
2060
3223
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2061
3224
  }
3225
+ /**
3226
+ * Retrieve next page of records
3227
+ *
3228
+ * @returns A new page object.
3229
+ */
2062
3230
  nextPage(size, offset) {
2063
3231
  return this.startPage(size, offset);
2064
3232
  }
3233
+ /**
3234
+ * Retrieve previous page of records
3235
+ *
3236
+ * @returns A new page object
3237
+ */
2065
3238
  previousPage(size, offset) {
2066
3239
  return this.startPage(size, offset);
2067
3240
  }
3241
+ /**
3242
+ * Retrieve start page of records
3243
+ *
3244
+ * @returns A new page object
3245
+ */
2068
3246
  startPage(size, offset) {
2069
3247
  return this.getPaginated({ pagination: { size, offset } });
2070
3248
  }
3249
+ /**
3250
+ * Retrieve last page of records
3251
+ *
3252
+ * @returns A new page object
3253
+ */
2071
3254
  endPage(size, offset) {
2072
3255
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2073
3256
  }
3257
+ /**
3258
+ * @returns Boolean indicating if there is a next page
3259
+ */
2074
3260
  hasNextPage() {
2075
3261
  return this.meta.page.more;
2076
3262
  }
2077
3263
  };
2078
- let Query = _Query;
2079
3264
  _table$1 = new WeakMap();
2080
3265
  _repository = new WeakMap();
2081
3266
  _data = new WeakMap();
@@ -2090,6 +3275,7 @@ cleanFilterConstraint_fn = function(column, value) {
2090
3275
  }
2091
3276
  return value;
2092
3277
  };
3278
+ let Query = _Query;
2093
3279
  function cleanParent(data, parent) {
2094
3280
  if (isCursorPaginationOptions(data.pagination)) {
2095
3281
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2097,6 +3283,21 @@ function cleanParent(data, parent) {
2097
3283
  return parent;
2098
3284
  }
2099
3285
 
3286
+ const RecordColumnTypes = [
3287
+ "bool",
3288
+ "int",
3289
+ "float",
3290
+ "string",
3291
+ "text",
3292
+ "email",
3293
+ "multiple",
3294
+ "link",
3295
+ "datetime",
3296
+ "vector",
3297
+ "file[]",
3298
+ "file",
3299
+ "json"
3300
+ ];
2100
3301
  function isIdentifiable(x) {
2101
3302
  return isObject(x) && isString(x?.id);
2102
3303
  }
@@ -2106,11 +3307,33 @@ function isXataRecord(x) {
2106
3307
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
2107
3308
  }
2108
3309
 
3310
+ function isValidExpandedColumn(column) {
3311
+ return isObject(column) && isString(column.name);
3312
+ }
3313
+ function isValidSelectableColumns(columns) {
3314
+ if (!Array.isArray(columns)) {
3315
+ return false;
3316
+ }
3317
+ return columns.every((column) => {
3318
+ if (typeof column === "string") {
3319
+ return true;
3320
+ }
3321
+ if (typeof column === "object") {
3322
+ return isValidExpandedColumn(column);
3323
+ }
3324
+ return false;
3325
+ });
3326
+ }
3327
+
2109
3328
  function isSortFilterString(value) {
2110
3329
  return isString(value);
2111
3330
  }
2112
3331
  function isSortFilterBase(filter) {
2113
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
3332
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
3333
+ if (key === "*")
3334
+ return value === "random";
3335
+ return value === "asc" || value === "desc";
3336
+ });
2114
3337
  }
2115
3338
  function isSortFilterObject(filter) {
2116
3339
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -2151,7 +3374,7 @@ var __privateMethod$2 = (obj, member, method) => {
2151
3374
  __accessCheck$4(obj, member, "access private method");
2152
3375
  return method;
2153
3376
  };
2154
- var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
3377
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1, _transformObjectToApi, transformObjectToApi_fn;
2155
3378
  const BULK_OPERATION_MAX_SIZE = 1e3;
2156
3379
  class Repository extends Query {
2157
3380
  }
@@ -2173,6 +3396,7 @@ class RestRepository extends Query {
2173
3396
  __privateAdd$4(this, _setCacheQuery);
2174
3397
  __privateAdd$4(this, _getCacheQuery);
2175
3398
  __privateAdd$4(this, _getSchemaTables$1);
3399
+ __privateAdd$4(this, _transformObjectToApi);
2176
3400
  __privateAdd$4(this, _table, void 0);
2177
3401
  __privateAdd$4(this, _getFetchProps, void 0);
2178
3402
  __privateAdd$4(this, _db, void 0);
@@ -2183,10 +3407,7 @@ class RestRepository extends Query {
2183
3407
  __privateSet$4(this, _db, options.db);
2184
3408
  __privateSet$4(this, _cache, options.pluginOptions.cache);
2185
3409
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2186
- __privateSet$4(this, _getFetchProps, async () => {
2187
- const props = await options.pluginOptions.getFetchProps();
2188
- return { ...props, sessionID: generateUUID() };
2189
- });
3410
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2190
3411
  const trace = options.pluginOptions.trace ?? defaultTrace;
2191
3412
  __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2192
3413
  return trace(name, fn, {
@@ -2204,24 +3425,24 @@ class RestRepository extends Query {
2204
3425
  if (a.length === 0)
2205
3426
  return [];
2206
3427
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2207
- const columns = isStringArray(b) ? b : ["*"];
3428
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2208
3429
  const result = await this.read(ids, columns);
2209
3430
  return result;
2210
3431
  }
2211
3432
  if (isString(a) && isObject(b)) {
2212
3433
  if (a === "")
2213
3434
  throw new Error("The id can't be empty");
2214
- const columns = isStringArray(c) ? c : void 0;
3435
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2215
3436
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2216
3437
  }
2217
3438
  if (isObject(a) && isString(a.id)) {
2218
3439
  if (a.id === "")
2219
3440
  throw new Error("The id can't be empty");
2220
- const columns = isStringArray(b) ? b : void 0;
3441
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2221
3442
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2222
3443
  }
2223
3444
  if (isObject(a)) {
2224
- const columns = isStringArray(b) ? b : void 0;
3445
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2225
3446
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2226
3447
  }
2227
3448
  throw new Error("Invalid arguments for create method");
@@ -2229,7 +3450,7 @@ class RestRepository extends Query {
2229
3450
  }
2230
3451
  async read(a, b) {
2231
3452
  return __privateGet$4(this, _trace).call(this, "read", async () => {
2232
- const columns = isStringArray(b) ? b : ["*"];
3453
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2233
3454
  if (Array.isArray(a)) {
2234
3455
  if (a.length === 0)
2235
3456
  return [];
@@ -2243,7 +3464,6 @@ class RestRepository extends Query {
2243
3464
  }
2244
3465
  const id = extractId(a);
2245
3466
  if (id) {
2246
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2247
3467
  try {
2248
3468
  const response = await getRecord({
2249
3469
  pathParams: {
@@ -2254,10 +3474,16 @@ class RestRepository extends Query {
2254
3474
  recordId: id
2255
3475
  },
2256
3476
  queryParams: { columns },
2257
- ...fetchProps
3477
+ ...__privateGet$4(this, _getFetchProps).call(this)
2258
3478
  });
2259
3479
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2260
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3480
+ return initObject(
3481
+ __privateGet$4(this, _db),
3482
+ schemaTables,
3483
+ __privateGet$4(this, _table),
3484
+ response,
3485
+ columns
3486
+ );
2261
3487
  } catch (e) {
2262
3488
  if (isObject(e) && e.status === 404) {
2263
3489
  return null;
@@ -2299,17 +3525,23 @@ class RestRepository extends Query {
2299
3525
  ifVersion,
2300
3526
  upsert: false
2301
3527
  });
2302
- const columns = isStringArray(b) ? b : ["*"];
3528
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2303
3529
  const result = await this.read(a, columns);
2304
3530
  return result;
2305
3531
  }
2306
- if (isString(a) && isObject(b)) {
2307
- const columns = isStringArray(c) ? c : void 0;
2308
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2309
- }
2310
- if (isObject(a) && isString(a.id)) {
2311
- const columns = isStringArray(b) ? b : void 0;
2312
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3532
+ try {
3533
+ if (isString(a) && isObject(b)) {
3534
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3535
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3536
+ }
3537
+ if (isObject(a) && isString(a.id)) {
3538
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3539
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3540
+ }
3541
+ } catch (error) {
3542
+ if (error.status === 422)
3543
+ return null;
3544
+ throw error;
2313
3545
  }
2314
3546
  throw new Error("Invalid arguments for update method");
2315
3547
  });
@@ -2343,17 +3575,27 @@ class RestRepository extends Query {
2343
3575
  ifVersion,
2344
3576
  upsert: true
2345
3577
  });
2346
- const columns = isStringArray(b) ? b : ["*"];
3578
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2347
3579
  const result = await this.read(a, columns);
2348
3580
  return result;
2349
3581
  }
2350
3582
  if (isString(a) && isObject(b)) {
2351
- const columns = isStringArray(c) ? c : void 0;
2352
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3583
+ if (a === "")
3584
+ throw new Error("The id can't be empty");
3585
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3586
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2353
3587
  }
2354
3588
  if (isObject(a) && isString(a.id)) {
2355
- const columns = isStringArray(c) ? c : void 0;
2356
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3589
+ if (a.id === "")
3590
+ throw new Error("The id can't be empty");
3591
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3592
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3593
+ }
3594
+ if (!isDefined(a) && isObject(b)) {
3595
+ return await this.create(b, c);
3596
+ }
3597
+ if (isObject(a) && !isDefined(a.id)) {
3598
+ return await this.create(a, b);
2357
3599
  }
2358
3600
  throw new Error("Invalid arguments for createOrUpdate method");
2359
3601
  });
@@ -2365,17 +3607,27 @@ class RestRepository extends Query {
2365
3607
  if (a.length === 0)
2366
3608
  return [];
2367
3609
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2368
- const columns = isStringArray(b) ? b : ["*"];
3610
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2369
3611
  const result = await this.read(ids, columns);
2370
3612
  return result;
2371
3613
  }
2372
3614
  if (isString(a) && isObject(b)) {
2373
- const columns = isStringArray(c) ? c : void 0;
2374
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3615
+ if (a === "")
3616
+ throw new Error("The id can't be empty");
3617
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3618
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2375
3619
  }
2376
3620
  if (isObject(a) && isString(a.id)) {
2377
- const columns = isStringArray(c) ? c : void 0;
2378
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3621
+ if (a.id === "")
3622
+ throw new Error("The id can't be empty");
3623
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3624
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3625
+ }
3626
+ if (!isDefined(a) && isObject(b)) {
3627
+ return await this.create(b, c);
3628
+ }
3629
+ if (isObject(a) && !isDefined(a.id)) {
3630
+ return await this.create(a, b);
2379
3631
  }
2380
3632
  throw new Error("Invalid arguments for createOrReplace method");
2381
3633
  });
@@ -2392,7 +3644,7 @@ class RestRepository extends Query {
2392
3644
  return o.id;
2393
3645
  throw new Error("Invalid arguments for delete method");
2394
3646
  });
2395
- const columns = isStringArray(b) ? b : ["*"];
3647
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2396
3648
  const result = await this.read(a, columns);
2397
3649
  await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2398
3650
  return result;
@@ -2426,8 +3678,7 @@ class RestRepository extends Query {
2426
3678
  }
2427
3679
  async search(query, options = {}) {
2428
3680
  return __privateGet$4(this, _trace).call(this, "search", async () => {
2429
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2430
- const { records } = await searchTable({
3681
+ const { records, totalCount } = await searchTable({
2431
3682
  pathParams: {
2432
3683
  workspace: "{workspaceId}",
2433
3684
  dbBranchName: "{dbBranch}",
@@ -2440,17 +3691,46 @@ class RestRepository extends Query {
2440
3691
  prefix: options.prefix,
2441
3692
  highlight: options.highlight,
2442
3693
  filter: options.filter,
2443
- boosters: options.boosters
3694
+ boosters: options.boosters,
3695
+ page: options.page,
3696
+ target: options.target
3697
+ },
3698
+ ...__privateGet$4(this, _getFetchProps).call(this)
3699
+ });
3700
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3701
+ return {
3702
+ records: records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"])),
3703
+ totalCount
3704
+ };
3705
+ });
3706
+ }
3707
+ async vectorSearch(column, query, options) {
3708
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3709
+ const { records, totalCount } = await vectorSearchTable({
3710
+ pathParams: {
3711
+ workspace: "{workspaceId}",
3712
+ dbBranchName: "{dbBranch}",
3713
+ region: "{region}",
3714
+ tableName: __privateGet$4(this, _table)
2444
3715
  },
2445
- ...fetchProps
3716
+ body: {
3717
+ column,
3718
+ queryVector: query,
3719
+ similarityFunction: options?.similarityFunction,
3720
+ size: options?.size,
3721
+ filter: options?.filter
3722
+ },
3723
+ ...__privateGet$4(this, _getFetchProps).call(this)
2446
3724
  });
2447
3725
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2448
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3726
+ return {
3727
+ records: records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"])),
3728
+ totalCount
3729
+ };
2449
3730
  });
2450
3731
  }
2451
3732
  async aggregate(aggs, filter) {
2452
3733
  return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2453
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2454
3734
  const result = await aggregateTable({
2455
3735
  pathParams: {
2456
3736
  workspace: "{workspaceId}",
@@ -2459,7 +3739,7 @@ class RestRepository extends Query {
2459
3739
  tableName: __privateGet$4(this, _table)
2460
3740
  },
2461
3741
  body: { aggs, filter },
2462
- ...fetchProps
3742
+ ...__privateGet$4(this, _getFetchProps).call(this)
2463
3743
  });
2464
3744
  return result;
2465
3745
  });
@@ -2470,7 +3750,6 @@ class RestRepository extends Query {
2470
3750
  if (cacheQuery)
2471
3751
  return new Page(query, cacheQuery.meta, cacheQuery.records);
2472
3752
  const data = query.getQueryOptions();
2473
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2474
3753
  const { meta, records: objects } = await queryTable({
2475
3754
  pathParams: {
2476
3755
  workspace: "{workspaceId}",
@@ -2482,14 +3761,21 @@ class RestRepository extends Query {
2482
3761
  filter: cleanFilter(data.filter),
2483
3762
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2484
3763
  page: data.pagination,
2485
- columns: data.columns ?? ["*"]
3764
+ columns: data.columns ?? ["*"],
3765
+ consistency: data.consistency
2486
3766
  },
2487
3767
  fetchOptions: data.fetchOptions,
2488
- ...fetchProps
3768
+ ...__privateGet$4(this, _getFetchProps).call(this)
2489
3769
  });
2490
3770
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2491
3771
  const records = objects.map(
2492
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3772
+ (record) => initObject(
3773
+ __privateGet$4(this, _db),
3774
+ schemaTables,
3775
+ __privateGet$4(this, _table),
3776
+ record,
3777
+ data.columns ?? ["*"]
3778
+ )
2493
3779
  );
2494
3780
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
2495
3781
  return new Page(query, meta, records);
@@ -2498,7 +3784,6 @@ class RestRepository extends Query {
2498
3784
  async summarizeTable(query, summaries, summariesFilter) {
2499
3785
  return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2500
3786
  const data = query.getQueryOptions();
2501
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2502
3787
  const result = await summarizeTable({
2503
3788
  pathParams: {
2504
3789
  workspace: "{workspaceId}",
@@ -2510,15 +3795,55 @@ class RestRepository extends Query {
2510
3795
  filter: cleanFilter(data.filter),
2511
3796
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2512
3797
  columns: data.columns,
3798
+ consistency: data.consistency,
2513
3799
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2514
3800
  summaries,
2515
3801
  summariesFilter
2516
3802
  },
2517
- ...fetchProps
3803
+ ...__privateGet$4(this, _getFetchProps).call(this)
2518
3804
  });
2519
- return result;
3805
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3806
+ return {
3807
+ ...result,
3808
+ summaries: result.summaries.map(
3809
+ (summary) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), summary, data.columns ?? [])
3810
+ )
3811
+ };
2520
3812
  });
2521
3813
  }
3814
+ ask(question, options) {
3815
+ const questionParam = options?.sessionId ? { message: question } : { question };
3816
+ const params = {
3817
+ pathParams: {
3818
+ workspace: "{workspaceId}",
3819
+ dbBranchName: "{dbBranch}",
3820
+ region: "{region}",
3821
+ tableName: __privateGet$4(this, _table),
3822
+ sessionId: options?.sessionId
3823
+ },
3824
+ body: {
3825
+ ...questionParam,
3826
+ rules: options?.rules,
3827
+ searchType: options?.searchType,
3828
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3829
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3830
+ },
3831
+ ...__privateGet$4(this, _getFetchProps).call(this)
3832
+ };
3833
+ if (options?.onMessage) {
3834
+ fetchSSERequest({
3835
+ endpoint: "dataPlane",
3836
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3837
+ method: "POST",
3838
+ onMessage: (message) => {
3839
+ options.onMessage?.({ answer: message.text, records: message.records });
3840
+ },
3841
+ ...params
3842
+ });
3843
+ } else {
3844
+ return askTableSession(params);
3845
+ }
3846
+ }
2522
3847
  }
2523
3848
  _table = new WeakMap();
2524
3849
  _getFetchProps = new WeakMap();
@@ -2528,8 +3853,7 @@ _schemaTables$2 = new WeakMap();
2528
3853
  _trace = new WeakMap();
2529
3854
  _insertRecordWithoutId = new WeakSet();
2530
3855
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2531
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2532
- const record = transformObjectLinks(object);
3856
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2533
3857
  const response = await insertRecord({
2534
3858
  pathParams: {
2535
3859
  workspace: "{workspaceId}",
@@ -2539,15 +3863,16 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2539
3863
  },
2540
3864
  queryParams: { columns },
2541
3865
  body: record,
2542
- ...fetchProps
3866
+ ...__privateGet$4(this, _getFetchProps).call(this)
2543
3867
  });
2544
3868
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2545
3869
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2546
3870
  };
2547
3871
  _insertRecordWithId = new WeakSet();
2548
3872
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2549
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2550
- const record = transformObjectLinks(object);
3873
+ if (!recordId)
3874
+ return null;
3875
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2551
3876
  const response = await insertRecordWithID({
2552
3877
  pathParams: {
2553
3878
  workspace: "{workspaceId}",
@@ -2558,30 +3883,28 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2558
3883
  },
2559
3884
  body: record,
2560
3885
  queryParams: { createOnly, columns, ifVersion },
2561
- ...fetchProps
3886
+ ...__privateGet$4(this, _getFetchProps).call(this)
2562
3887
  });
2563
3888
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2564
3889
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2565
3890
  };
2566
3891
  _insertRecords = new WeakSet();
2567
3892
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2568
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2569
- const chunkedOperations = chunk(
2570
- objects.map((object) => ({
2571
- insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2572
- })),
2573
- BULK_OPERATION_MAX_SIZE
2574
- );
3893
+ const operations = await promiseMap(objects, async (object) => {
3894
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3895
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
3896
+ });
3897
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2575
3898
  const ids = [];
2576
- for (const operations of chunkedOperations) {
3899
+ for (const operations2 of chunkedOperations) {
2577
3900
  const { results } = await branchTransaction({
2578
3901
  pathParams: {
2579
3902
  workspace: "{workspaceId}",
2580
3903
  dbBranchName: "{dbBranch}",
2581
3904
  region: "{region}"
2582
3905
  },
2583
- body: { operations },
2584
- ...fetchProps
3906
+ body: { operations: operations2 },
3907
+ ...__privateGet$4(this, _getFetchProps).call(this)
2585
3908
  });
2586
3909
  for (const result of results) {
2587
3910
  if (result.operation === "insert") {
@@ -2595,8 +3918,9 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2595
3918
  };
2596
3919
  _updateRecordWithID = new WeakSet();
2597
3920
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2598
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2599
- const { id: _id, ...record } = transformObjectLinks(object);
3921
+ if (!recordId)
3922
+ return null;
3923
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2600
3924
  try {
2601
3925
  const response = await updateRecordWithID({
2602
3926
  pathParams: {
@@ -2608,7 +3932,7 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2608
3932
  },
2609
3933
  queryParams: { columns, ifVersion },
2610
3934
  body: record,
2611
- ...fetchProps
3935
+ ...__privateGet$4(this, _getFetchProps).call(this)
2612
3936
  });
2613
3937
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2614
3938
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2621,23 +3945,21 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2621
3945
  };
2622
3946
  _updateRecords = new WeakSet();
2623
3947
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2624
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2625
- const chunkedOperations = chunk(
2626
- objects.map(({ id, ...object }) => ({
2627
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2628
- })),
2629
- BULK_OPERATION_MAX_SIZE
2630
- );
3948
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
3949
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3950
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
3951
+ });
3952
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2631
3953
  const ids = [];
2632
- for (const operations of chunkedOperations) {
3954
+ for (const operations2 of chunkedOperations) {
2633
3955
  const { results } = await branchTransaction({
2634
3956
  pathParams: {
2635
3957
  workspace: "{workspaceId}",
2636
3958
  dbBranchName: "{dbBranch}",
2637
3959
  region: "{region}"
2638
3960
  },
2639
- body: { operations },
2640
- ...fetchProps
3961
+ body: { operations: operations2 },
3962
+ ...__privateGet$4(this, _getFetchProps).call(this)
2641
3963
  });
2642
3964
  for (const result of results) {
2643
3965
  if (result.operation === "update") {
@@ -2651,7 +3973,8 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2651
3973
  };
2652
3974
  _upsertRecordWithID = new WeakSet();
2653
3975
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2654
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3976
+ if (!recordId)
3977
+ return null;
2655
3978
  const response = await upsertRecordWithID({
2656
3979
  pathParams: {
2657
3980
  workspace: "{workspaceId}",
@@ -2662,14 +3985,15 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2662
3985
  },
2663
3986
  queryParams: { columns, ifVersion },
2664
3987
  body: object,
2665
- ...fetchProps
3988
+ ...__privateGet$4(this, _getFetchProps).call(this)
2666
3989
  });
2667
3990
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2668
3991
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2669
3992
  };
2670
3993
  _deleteRecord = new WeakSet();
2671
3994
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
2672
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3995
+ if (!recordId)
3996
+ return null;
2673
3997
  try {
2674
3998
  const response = await deleteRecord({
2675
3999
  pathParams: {
@@ -2680,7 +4004,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2680
4004
  recordId
2681
4005
  },
2682
4006
  queryParams: { columns },
2683
- ...fetchProps
4007
+ ...__privateGet$4(this, _getFetchProps).call(this)
2684
4008
  });
2685
4009
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2686
4010
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2693,9 +4017,8 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2693
4017
  };
2694
4018
  _deleteRecords = new WeakSet();
2695
4019
  deleteRecords_fn = async function(recordIds) {
2696
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2697
4020
  const chunkedOperations = chunk(
2698
- recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
4021
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2699
4022
  BULK_OPERATION_MAX_SIZE
2700
4023
  );
2701
4024
  for (const operations of chunkedOperations) {
@@ -2706,21 +4029,22 @@ deleteRecords_fn = async function(recordIds) {
2706
4029
  region: "{region}"
2707
4030
  },
2708
4031
  body: { operations },
2709
- ...fetchProps
4032
+ ...__privateGet$4(this, _getFetchProps).call(this)
2710
4033
  });
2711
4034
  }
2712
4035
  };
2713
4036
  _setCacheQuery = new WeakSet();
2714
4037
  setCacheQuery_fn = async function(query, meta, records) {
2715
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
4038
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
2716
4039
  };
2717
4040
  _getCacheQuery = new WeakSet();
2718
4041
  getCacheQuery_fn = async function(query) {
2719
4042
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2720
- const result = await __privateGet$4(this, _cache).get(key);
4043
+ const result = await __privateGet$4(this, _cache)?.get(key);
2721
4044
  if (!result)
2722
4045
  return null;
2723
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
4046
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
4047
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2724
4048
  if (ttl < 0)
2725
4049
  return null;
2726
4050
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2730,39 +4054,66 @@ _getSchemaTables$1 = new WeakSet();
2730
4054
  getSchemaTables_fn$1 = async function() {
2731
4055
  if (__privateGet$4(this, _schemaTables$2))
2732
4056
  return __privateGet$4(this, _schemaTables$2);
2733
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2734
4057
  const { schema } = await getBranchDetails({
2735
4058
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2736
- ...fetchProps
4059
+ ...__privateGet$4(this, _getFetchProps).call(this)
2737
4060
  });
2738
4061
  __privateSet$4(this, _schemaTables$2, schema.tables);
2739
4062
  return schema.tables;
2740
4063
  };
2741
- const transformObjectLinks = (object) => {
2742
- return Object.entries(object).reduce((acc, [key, value]) => {
4064
+ _transformObjectToApi = new WeakSet();
4065
+ transformObjectToApi_fn = async function(object) {
4066
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4067
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
4068
+ if (!schema)
4069
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
4070
+ const result = {};
4071
+ for (const [key, value] of Object.entries(object)) {
2743
4072
  if (key === "xata")
2744
- return acc;
2745
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
2746
- }, {});
4073
+ continue;
4074
+ const type = schema.columns.find((column) => column.name === key)?.type;
4075
+ switch (type) {
4076
+ case "link": {
4077
+ result[key] = isIdentifiable(value) ? value.id : value;
4078
+ break;
4079
+ }
4080
+ case "datetime": {
4081
+ result[key] = value instanceof Date ? value.toISOString() : value;
4082
+ break;
4083
+ }
4084
+ case `file`:
4085
+ result[key] = await parseInputFileEntry(value);
4086
+ break;
4087
+ case "file[]":
4088
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4089
+ break;
4090
+ case "json":
4091
+ result[key] = stringifyJson(value);
4092
+ break;
4093
+ default:
4094
+ result[key] = value;
4095
+ }
4096
+ }
4097
+ return result;
2747
4098
  };
2748
4099
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2749
- const result = {};
4100
+ const data = {};
2750
4101
  const { xata, ...rest } = object ?? {};
2751
- Object.assign(result, rest);
4102
+ Object.assign(data, rest);
2752
4103
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2753
4104
  if (!columns)
2754
4105
  console.error(`Table ${table} not found in schema`);
2755
4106
  for (const column of columns ?? []) {
2756
4107
  if (!isValidColumn(selectedColumns, column))
2757
4108
  continue;
2758
- const value = result[column.name];
4109
+ const value = data[column.name];
2759
4110
  switch (column.type) {
2760
4111
  case "datetime": {
2761
- const date = value !== void 0 ? new Date(value) : void 0;
2762
- if (date && isNaN(date.getTime())) {
4112
+ const date = value !== void 0 ? new Date(value) : null;
4113
+ if (date !== null && isNaN(date.getTime())) {
2763
4114
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2764
- } else if (date) {
2765
- result[column.name] = date;
4115
+ } else {
4116
+ data[column.name] = date;
2766
4117
  }
2767
4118
  break;
2768
4119
  }
@@ -2775,50 +4126,76 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2775
4126
  if (item === column.name) {
2776
4127
  return [...acc, "*"];
2777
4128
  }
2778
- if (item.startsWith(`${column.name}.`)) {
4129
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
2779
4130
  const [, ...path] = item.split(".");
2780
4131
  return [...acc, path.join(".")];
2781
4132
  }
2782
4133
  return acc;
2783
4134
  }, []);
2784
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4135
+ data[column.name] = initObject(
4136
+ db,
4137
+ schemaTables,
4138
+ linkTable,
4139
+ value,
4140
+ selectedLinkColumns
4141
+ );
2785
4142
  } else {
2786
- result[column.name] = null;
4143
+ data[column.name] = null;
2787
4144
  }
2788
4145
  break;
2789
4146
  }
4147
+ case "file":
4148
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4149
+ break;
4150
+ case "file[]":
4151
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4152
+ break;
4153
+ case "json":
4154
+ data[column.name] = parseJson(value);
4155
+ break;
2790
4156
  default:
2791
- result[column.name] = value ?? null;
4157
+ data[column.name] = value ?? null;
2792
4158
  if (column.notNull === true && value === null) {
2793
4159
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2794
4160
  }
2795
4161
  break;
2796
4162
  }
2797
4163
  }
2798
- result.read = function(columns2) {
2799
- return db[table].read(result["id"], columns2);
4164
+ const record = { ...data };
4165
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
4166
+ record.read = function(columns2) {
4167
+ return db[table].read(record["id"], columns2);
2800
4168
  };
2801
- result.update = function(data, b, c) {
2802
- const columns2 = isStringArray(b) ? b : ["*"];
4169
+ record.update = function(data2, b, c) {
4170
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2803
4171
  const ifVersion = parseIfVersion(b, c);
2804
- return db[table].update(result["id"], data, columns2, { ifVersion });
4172
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2805
4173
  };
2806
- result.replace = function(data, b, c) {
2807
- const columns2 = isStringArray(b) ? b : ["*"];
4174
+ record.replace = function(data2, b, c) {
4175
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2808
4176
  const ifVersion = parseIfVersion(b, c);
2809
- return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
4177
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
4178
+ };
4179
+ record.delete = function() {
4180
+ return db[table].delete(record["id"]);
4181
+ };
4182
+ if (metadata !== void 0) {
4183
+ record.xata = Object.freeze(metadata);
4184
+ }
4185
+ record.getMetadata = function() {
4186
+ return record.xata;
2810
4187
  };
2811
- result.delete = function() {
2812
- return db[table].delete(result["id"]);
4188
+ record.toSerializable = function() {
4189
+ return JSON.parse(JSON.stringify(record));
2813
4190
  };
2814
- result.getMetadata = function() {
2815
- return xata;
4191
+ record.toString = function() {
4192
+ return JSON.stringify(record);
2816
4193
  };
2817
- for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
2818
- Object.defineProperty(result, prop, { enumerable: false });
4194
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
4195
+ Object.defineProperty(record, prop, { enumerable: false });
2819
4196
  }
2820
- Object.freeze(result);
2821
- return result;
4197
+ Object.freeze(record);
4198
+ return record;
2822
4199
  };
2823
4200
  function extractId(value) {
2824
4201
  if (isString(value))
@@ -2830,11 +4207,7 @@ function extractId(value) {
2830
4207
  function isValidColumn(columns, column) {
2831
4208
  if (columns.includes("*"))
2832
4209
  return true;
2833
- if (column.type === "link") {
2834
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
2835
- return linkColumns.length > 0;
2836
- }
2837
- return columns.includes(column.name);
4210
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
2838
4211
  }
2839
4212
  function parseIfVersion(...args) {
2840
4213
  for (const arg of args) {
@@ -2911,10 +4284,12 @@ const notExists = (column) => ({ $notExists: column });
2911
4284
  const startsWith = (value) => ({ $startsWith: value });
2912
4285
  const endsWith = (value) => ({ $endsWith: value });
2913
4286
  const pattern = (value) => ({ $pattern: value });
4287
+ const iPattern = (value) => ({ $iPattern: value });
2914
4288
  const is = (value) => ({ $is: value });
2915
4289
  const equals = is;
2916
4290
  const isNot = (value) => ({ $isNot: value });
2917
4291
  const contains = (value) => ({ $contains: value });
4292
+ const iContains = (value) => ({ $iContains: value });
2918
4293
  const includes = (value) => ({ $includes: value });
2919
4294
  const includesAll = (value) => ({ $includesAll: value });
2920
4295
  const includesNone = (value) => ({ $includesNone: value });
@@ -2970,6 +4345,80 @@ class SchemaPlugin extends XataPlugin {
2970
4345
  _tables = new WeakMap();
2971
4346
  _schemaTables$1 = new WeakMap();
2972
4347
 
4348
+ class FilesPlugin extends XataPlugin {
4349
+ build(pluginOptions) {
4350
+ return {
4351
+ download: async (location) => {
4352
+ const { table, record, column, fileId = "" } = location ?? {};
4353
+ return await getFileItem({
4354
+ pathParams: {
4355
+ workspace: "{workspaceId}",
4356
+ dbBranchName: "{dbBranch}",
4357
+ region: "{region}",
4358
+ tableName: table ?? "",
4359
+ recordId: record ?? "",
4360
+ columnName: column ?? "",
4361
+ fileId
4362
+ },
4363
+ ...pluginOptions,
4364
+ rawResponse: true
4365
+ });
4366
+ },
4367
+ upload: async (location, file, options) => {
4368
+ const { table, record, column, fileId = "" } = location ?? {};
4369
+ const resolvedFile = await file;
4370
+ const contentType = options?.mediaType || getContentType(resolvedFile);
4371
+ const body = resolvedFile instanceof XataFile ? resolvedFile.toBlob() : resolvedFile;
4372
+ return await putFileItem({
4373
+ ...pluginOptions,
4374
+ pathParams: {
4375
+ workspace: "{workspaceId}",
4376
+ dbBranchName: "{dbBranch}",
4377
+ region: "{region}",
4378
+ tableName: table ?? "",
4379
+ recordId: record ?? "",
4380
+ columnName: column ?? "",
4381
+ fileId
4382
+ },
4383
+ body,
4384
+ headers: { "Content-Type": contentType }
4385
+ });
4386
+ },
4387
+ delete: async (location) => {
4388
+ const { table, record, column, fileId = "" } = location ?? {};
4389
+ return await deleteFileItem({
4390
+ pathParams: {
4391
+ workspace: "{workspaceId}",
4392
+ dbBranchName: "{dbBranch}",
4393
+ region: "{region}",
4394
+ tableName: table ?? "",
4395
+ recordId: record ?? "",
4396
+ columnName: column ?? "",
4397
+ fileId
4398
+ },
4399
+ ...pluginOptions
4400
+ });
4401
+ }
4402
+ };
4403
+ }
4404
+ }
4405
+ function getContentType(file) {
4406
+ if (typeof file === "string") {
4407
+ return "text/plain";
4408
+ }
4409
+ if ("mediaType" in file && file.mediaType !== void 0) {
4410
+ return file.mediaType;
4411
+ }
4412
+ if (isBlob(file)) {
4413
+ return file.type;
4414
+ }
4415
+ try {
4416
+ return file.type;
4417
+ } catch (e) {
4418
+ }
4419
+ return "application/octet-stream";
4420
+ }
4421
+
2973
4422
  var __accessCheck$1 = (obj, member, msg) => {
2974
4423
  if (!member.has(obj))
2975
4424
  throw TypeError("Cannot " + msg);
@@ -3002,138 +4451,141 @@ class SearchPlugin extends XataPlugin {
3002
4451
  __privateAdd$1(this, _schemaTables, void 0);
3003
4452
  __privateSet$1(this, _schemaTables, schemaTables);
3004
4453
  }
3005
- build({ getFetchProps }) {
4454
+ build(pluginOptions) {
3006
4455
  return {
3007
4456
  all: async (query, options = {}) => {
3008
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3009
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3010
- return records.map((record) => {
3011
- const { table = "orphan" } = record.xata;
3012
- return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
3013
- });
4457
+ const { records, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4458
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
4459
+ return {
4460
+ totalCount,
4461
+ records: records.map((record) => {
4462
+ const { table = "orphan" } = record.xata;
4463
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
4464
+ })
4465
+ };
3014
4466
  },
3015
4467
  byTable: async (query, options = {}) => {
3016
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3017
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3018
- return records.reduce((acc, record) => {
4468
+ const { records: rawRecords, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4469
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
4470
+ const records = rawRecords.reduce((acc, record) => {
3019
4471
  const { table = "orphan" } = record.xata;
3020
4472
  const items = acc[table] ?? [];
3021
4473
  const item = initObject(this.db, schemaTables, table, record, ["*"]);
3022
4474
  return { ...acc, [table]: [...items, item] };
3023
4475
  }, {});
4476
+ return { totalCount, records };
3024
4477
  }
3025
4478
  };
3026
4479
  }
3027
4480
  }
3028
4481
  _schemaTables = new WeakMap();
3029
4482
  _search = new WeakSet();
3030
- search_fn = async function(query, options, getFetchProps) {
3031
- const fetchProps = await getFetchProps();
3032
- const { tables, fuzziness, highlight, prefix } = options ?? {};
3033
- const { records } = await searchBranch({
4483
+ search_fn = async function(query, options, pluginOptions) {
4484
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
4485
+ const { records, totalCount } = await searchBranch({
3034
4486
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3035
- body: { tables, query, fuzziness, prefix, highlight },
3036
- ...fetchProps
4487
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
4488
+ body: { tables, query, fuzziness, prefix, highlight, page },
4489
+ ...pluginOptions
3037
4490
  });
3038
- return records;
4491
+ return { records, totalCount };
3039
4492
  };
3040
4493
  _getSchemaTables = new WeakSet();
3041
- getSchemaTables_fn = async function(getFetchProps) {
4494
+ getSchemaTables_fn = async function(pluginOptions) {
3042
4495
  if (__privateGet$1(this, _schemaTables))
3043
4496
  return __privateGet$1(this, _schemaTables);
3044
- const fetchProps = await getFetchProps();
3045
4497
  const { schema } = await getBranchDetails({
3046
4498
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3047
- ...fetchProps
4499
+ ...pluginOptions
3048
4500
  });
3049
4501
  __privateSet$1(this, _schemaTables, schema.tables);
3050
4502
  return schema.tables;
3051
4503
  };
3052
4504
 
3053
- const isBranchStrategyBuilder = (strategy) => {
3054
- return typeof strategy === "function";
3055
- };
3056
-
3057
- async function getCurrentBranchName(options) {
3058
- const { branch, envBranch } = getEnvironment();
3059
- if (branch) {
3060
- const details = await getDatabaseBranch(branch, options);
3061
- if (details)
3062
- return branch;
3063
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
3064
- }
3065
- const gitBranch = envBranch || await getGitBranch();
3066
- return resolveXataBranch(gitBranch, options);
3067
- }
3068
- async function getCurrentBranchDetails(options) {
3069
- const branch = await getCurrentBranchName(options);
3070
- return getDatabaseBranch(branch, options);
3071
- }
3072
- async function resolveXataBranch(gitBranch, options) {
3073
- const databaseURL = options?.databaseURL || getDatabaseURL();
3074
- const apiKey = options?.apiKey || getAPIKey();
3075
- if (!databaseURL)
3076
- throw new Error(
3077
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3078
- );
3079
- if (!apiKey)
3080
- throw new Error(
3081
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3082
- );
3083
- const [protocol, , host, , dbName] = databaseURL.split("/");
3084
- const urlParts = parseWorkspacesUrlParts(host);
3085
- if (!urlParts)
3086
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3087
- const { workspace, region } = urlParts;
3088
- const { fallbackBranch } = getEnvironment();
3089
- const { branch } = await resolveBranch({
3090
- apiKey,
3091
- apiUrl: databaseURL,
3092
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3093
- workspacesApiUrl: `${protocol}//${host}`,
3094
- pathParams: { dbName, workspace, region },
3095
- queryParams: { gitBranch, fallbackBranch },
3096
- trace: defaultTrace
3097
- });
3098
- return branch;
3099
- }
3100
- async function getDatabaseBranch(branch, options) {
3101
- const databaseURL = options?.databaseURL || getDatabaseURL();
3102
- const apiKey = options?.apiKey || getAPIKey();
3103
- if (!databaseURL)
3104
- throw new Error(
3105
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3106
- );
3107
- if (!apiKey)
3108
- throw new Error(
3109
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3110
- );
3111
- const [protocol, , host, , database] = databaseURL.split("/");
3112
- const urlParts = parseWorkspacesUrlParts(host);
3113
- if (!urlParts)
3114
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3115
- const { workspace, region } = urlParts;
3116
- try {
3117
- return await getBranchDetails({
3118
- apiKey,
3119
- apiUrl: databaseURL,
3120
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3121
- workspacesApiUrl: `${protocol}//${host}`,
3122
- pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3123
- trace: defaultTrace
3124
- });
3125
- } catch (err) {
3126
- if (isObject(err) && err.status === 404)
3127
- return null;
3128
- throw err;
4505
+ function escapeElement(elementRepresentation) {
4506
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4507
+ return '"' + escaped + '"';
4508
+ }
4509
+ function arrayString(val) {
4510
+ let result = "{";
4511
+ for (let i = 0; i < val.length; i++) {
4512
+ if (i > 0) {
4513
+ result = result + ",";
4514
+ }
4515
+ if (val[i] === null || typeof val[i] === "undefined") {
4516
+ result = result + "NULL";
4517
+ } else if (Array.isArray(val[i])) {
4518
+ result = result + arrayString(val[i]);
4519
+ } else if (val[i] instanceof Buffer) {
4520
+ result += "\\\\x" + val[i].toString("hex");
4521
+ } else {
4522
+ result += escapeElement(prepareValue(val[i]));
4523
+ }
3129
4524
  }
4525
+ result = result + "}";
4526
+ return result;
3130
4527
  }
3131
- function getDatabaseURL() {
4528
+ function prepareValue(value) {
4529
+ if (!isDefined(value))
4530
+ return null;
4531
+ if (value instanceof Date) {
4532
+ return value.toISOString();
4533
+ }
4534
+ if (Array.isArray(value)) {
4535
+ return arrayString(value);
4536
+ }
4537
+ if (isObject(value)) {
4538
+ return JSON.stringify(value);
4539
+ }
3132
4540
  try {
3133
- const { databaseURL } = getEnvironment();
3134
- return databaseURL;
3135
- } catch (err) {
3136
- return void 0;
4541
+ return value.toString();
4542
+ } catch (e) {
4543
+ return value;
4544
+ }
4545
+ }
4546
+ function prepareParams(param1, param2) {
4547
+ if (isString(param1)) {
4548
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4549
+ }
4550
+ if (isStringArray(param1)) {
4551
+ const statement = param1.reduce((acc, curr, index) => {
4552
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4553
+ }, "");
4554
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4555
+ }
4556
+ if (isObject(param1)) {
4557
+ const { statement, params, consistency } = param1;
4558
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
4559
+ }
4560
+ throw new Error("Invalid query");
4561
+ }
4562
+
4563
+ class SQLPlugin extends XataPlugin {
4564
+ build(pluginOptions) {
4565
+ return async (param1, ...param2) => {
4566
+ const { statement, params, consistency } = prepareParams(param1, param2);
4567
+ const { records, warning } = await sqlQuery({
4568
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4569
+ body: { statement, params, consistency },
4570
+ ...pluginOptions
4571
+ });
4572
+ return { records, warning };
4573
+ };
4574
+ }
4575
+ }
4576
+
4577
+ class TransactionPlugin extends XataPlugin {
4578
+ build(pluginOptions) {
4579
+ return {
4580
+ run: async (operations) => {
4581
+ const response = await branchTransaction({
4582
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4583
+ body: { operations },
4584
+ ...pluginOptions
4585
+ });
4586
+ return response;
4587
+ }
4588
+ };
3137
4589
  }
3138
4590
  }
3139
4591
 
@@ -3160,46 +4612,43 @@ var __privateMethod = (obj, member, method) => {
3160
4612
  return method;
3161
4613
  };
3162
4614
  const buildClient = (plugins) => {
3163
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
4615
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3164
4616
  return _a = class {
3165
4617
  constructor(options = {}, schemaTables) {
3166
4618
  __privateAdd(this, _parseOptions);
3167
4619
  __privateAdd(this, _getFetchProps);
3168
- __privateAdd(this, _evaluateBranch);
3169
- __privateAdd(this, _branch, void 0);
3170
4620
  __privateAdd(this, _options, void 0);
3171
4621
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3172
4622
  __privateSet(this, _options, safeOptions);
3173
4623
  const pluginOptions = {
3174
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
4624
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3175
4625
  cache: safeOptions.cache,
3176
- trace: safeOptions.trace
4626
+ host: safeOptions.host
3177
4627
  };
3178
4628
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3179
4629
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
4630
+ const transactions = new TransactionPlugin().build(pluginOptions);
4631
+ const sql = new SQLPlugin().build(pluginOptions);
4632
+ const files = new FilesPlugin().build(pluginOptions);
3180
4633
  this.db = db;
3181
4634
  this.search = search;
4635
+ this.transactions = transactions;
4636
+ this.sql = sql;
4637
+ this.files = files;
3182
4638
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3183
4639
  if (namespace === void 0)
3184
4640
  continue;
3185
- const result = namespace.build(pluginOptions);
3186
- if (result instanceof Promise) {
3187
- void result.then((namespace2) => {
3188
- this[key] = namespace2;
3189
- });
3190
- } else {
3191
- this[key] = result;
3192
- }
4641
+ this[key] = namespace.build(pluginOptions);
3193
4642
  }
3194
4643
  }
3195
4644
  async getConfig() {
3196
4645
  const databaseURL = __privateGet(this, _options).databaseURL;
3197
- const branch = await __privateGet(this, _options).branch();
4646
+ const branch = __privateGet(this, _options).branch;
3198
4647
  return { databaseURL, branch };
3199
4648
  }
3200
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4649
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3201
4650
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3202
- const isBrowser = typeof window !== "undefined";
4651
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3203
4652
  if (isBrowser && !enableBrowser) {
3204
4653
  throw new Error(
3205
4654
  "You are trying to use Xata from the browser, which is potentially a non-secure environment. If you understand the security concerns, such as leaking your credentials, pass `enableBrowser: true` to the client options to remove this error."
@@ -3210,46 +4659,73 @@ const buildClient = (plugins) => {
3210
4659
  const apiKey = options?.apiKey || getAPIKey();
3211
4660
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3212
4661
  const trace = options?.trace ?? defaultTrace;
3213
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
4662
+ const clientName = options?.clientName;
4663
+ const host = options?.host ?? "production";
4664
+ const xataAgentExtra = options?.xataAgentExtra;
3214
4665
  if (!apiKey) {
3215
4666
  throw new Error("Option apiKey is required");
3216
4667
  }
3217
4668
  if (!databaseURL) {
3218
4669
  throw new Error("Option databaseURL is required");
3219
4670
  }
3220
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser };
3221
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3222
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3223
- if (!branchValue)
3224
- throw new Error("Unable to resolve branch value");
4671
+ const envBranch = getBranch();
4672
+ const previewBranch = getPreviewBranch();
4673
+ const branch = options?.branch || previewBranch || envBranch || "main";
4674
+ if (!!previewBranch && branch !== previewBranch) {
4675
+ console.warn(
4676
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4677
+ );
4678
+ } else if (!!envBranch && branch !== envBranch) {
4679
+ console.warn(
4680
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4681
+ );
4682
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4683
+ console.warn(
4684
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4685
+ );
4686
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4687
+ console.warn(
4688
+ `No branch was passed to the client constructor. Using default branch ${branch}. You can set the branch with the environment variable XATA_BRANCH or by passing the branch option to the client constructor.`
4689
+ );
4690
+ }
4691
+ return {
4692
+ fetch,
4693
+ databaseURL,
4694
+ apiKey,
4695
+ branch,
4696
+ cache,
4697
+ trace,
4698
+ host,
4699
+ clientID: generateUUID(),
4700
+ enableBrowser,
4701
+ clientName,
4702
+ xataAgentExtra
4703
+ };
4704
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
4705
+ fetch,
4706
+ apiKey,
4707
+ databaseURL,
4708
+ branch,
4709
+ trace,
4710
+ clientID,
4711
+ clientName,
4712
+ xataAgentExtra
4713
+ }) {
3225
4714
  return {
3226
- fetchImpl: fetch,
4715
+ fetch,
3227
4716
  apiKey,
3228
4717
  apiUrl: "",
4718
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3229
4719
  workspacesApiUrl: (path, params) => {
3230
4720
  const hasBranch = params.dbBranchName ?? params.branch;
3231
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
4721
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
3232
4722
  return databaseURL + newPath;
3233
4723
  },
3234
4724
  trace,
3235
- clientID
3236
- };
3237
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3238
- if (__privateGet(this, _branch))
3239
- return __privateGet(this, _branch);
3240
- if (param === void 0)
3241
- return void 0;
3242
- const strategies = Array.isArray(param) ? [...param] : [param];
3243
- const evaluateBranch = async (strategy) => {
3244
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
4725
+ clientID,
4726
+ clientName,
4727
+ xataAgentExtra
3245
4728
  };
3246
- for await (const strategy of strategies) {
3247
- const branch = await evaluateBranch(strategy);
3248
- if (branch) {
3249
- __privateSet(this, _branch, branch);
3250
- return branch;
3251
- }
3252
- }
3253
4729
  }, _a;
3254
4730
  };
3255
4731
  class BaseClient extends buildClient() {
@@ -3322,21 +4798,6 @@ const deserialize = (json) => {
3322
4798
  return defaultSerializer.fromJSON(json);
3323
4799
  };
3324
4800
 
3325
- function buildWorkerRunner(config) {
3326
- return function xataWorker(name, _worker) {
3327
- return async (...args) => {
3328
- const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3329
- const result = await fetch(url, {
3330
- method: "POST",
3331
- headers: { "Content-Type": "application/json" },
3332
- body: serialize({ args })
3333
- });
3334
- const text = await result.text();
3335
- return deserialize(text);
3336
- };
3337
- };
3338
- }
3339
-
3340
4801
  class XataError extends Error {
3341
4802
  constructor(message, status) {
3342
4803
  super(message);
@@ -3344,5 +4805,5 @@ class XataError extends Error {
3344
4805
  }
3345
4806
  }
3346
4807
 
3347
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, branchTransaction, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, dEPRECATEDcreateDatabase, dEPRECATEDdeleteDatabase, dEPRECATEDgetDatabaseList, dEPRECATEDgetDatabaseMetadata, dEPRECATEDupdateDatabaseMetadata, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
4808
+ export { BaseClient, FetcherError, FilesPlugin, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, RecordColumnTypes, Repository, RestRepository, SQLPlugin, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, TransactionPlugin, XataApiClient, XataApiPlugin, XataError, XataFile, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, applyMigration, askTable, askTableSession, branchTransaction, buildClient, buildPreviewBranchName, buildProviderString, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, copyBranch, createBranch, createCluster, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteFile, deleteFileItem, deleteOAuthAccessToken, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteUserOAuthClient, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, fileAccess, fileUpload, ge, getAPIKey, getAuthorizationCode, getBranch, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getCluster, getColumn, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getFile, getFileItem, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getPreviewBranch, getRecord, getSchema, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getUserOAuthAccessTokens, getUserOAuthClients, getWorkspace, getWorkspaceMembersList, getWorkspacesList, grantAuthorizationCode, greaterEquals, greaterThan, greaterThanEquals, gt, gte, iContains, iPattern, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isValidExpandedColumn, isValidSelectableColumns, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listClusters, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, pgRollJobStatus, pgRollMigrationHistory, pgRollStatus, previewBranchSchemaEdit, pushBranchMigrations, putFile, putFileItem, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, renameDatabase, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, sqlQuery, startsWith, summarizeTable, transformImage, updateBranchMetadata, updateBranchSchema, updateCluster, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateOAuthAccessToken, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID, vectorSearchTable };
3348
4809
  //# sourceMappingURL=index.mjs.map