@xata.io/client 0.0.0-alpha.vf8f3b02 → 0.0.0-alpha.vf90263d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,8 @@
1
1
  'use strict';
2
2
 
3
- const defaultTrace = async (_name, fn, _options) => {
3
+ const defaultTrace = async (name, fn, _options) => {
4
4
  return await fn({
5
+ name,
5
6
  setAttributes: () => {
6
7
  return;
7
8
  }
@@ -19,7 +20,8 @@ const TraceAttributes = {
19
20
  HTTP_METHOD: "http.method",
20
21
  HTTP_URL: "http.url",
21
22
  HTTP_ROUTE: "http.route",
22
- HTTP_TARGET: "http.target"
23
+ HTTP_TARGET: "http.target",
24
+ CLOUDFLARE_RAY_ID: "cf.ray"
23
25
  };
24
26
 
25
27
  function notEmpty(value) {
@@ -28,8 +30,18 @@ function notEmpty(value) {
28
30
  function compact(arr) {
29
31
  return arr.filter(notEmpty);
30
32
  }
33
+ function compactObject(obj) {
34
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
35
+ }
36
+ function isBlob(value) {
37
+ try {
38
+ return value instanceof Blob;
39
+ } catch (error) {
40
+ return false;
41
+ }
42
+ }
31
43
  function isObject(value) {
32
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
44
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
33
45
  }
34
46
  function isDefined(value) {
35
47
  return value !== null && value !== void 0;
@@ -43,6 +55,18 @@ function isStringArray(value) {
43
55
  function isNumber(value) {
44
56
  return isDefined(value) && typeof value === "number";
45
57
  }
58
+ function parseNumber(value) {
59
+ if (isNumber(value)) {
60
+ return value;
61
+ }
62
+ if (isString(value)) {
63
+ const parsed = Number(value);
64
+ if (!Number.isNaN(parsed)) {
65
+ return parsed;
66
+ }
67
+ }
68
+ return void 0;
69
+ }
46
70
  function toBase64(value) {
47
71
  try {
48
72
  return btoa(value);
@@ -62,16 +86,49 @@ function deepMerge(a, b) {
62
86
  }
63
87
  return result;
64
88
  }
89
+ function chunk(array, chunkSize) {
90
+ const result = [];
91
+ for (let i = 0; i < array.length; i += chunkSize) {
92
+ result.push(array.slice(i, i + chunkSize));
93
+ }
94
+ return result;
95
+ }
96
+ async function timeout(ms) {
97
+ return new Promise((resolve) => setTimeout(resolve, ms));
98
+ }
99
+ function timeoutWithCancel(ms) {
100
+ let timeoutId;
101
+ const promise = new Promise((resolve) => {
102
+ timeoutId = setTimeout(() => {
103
+ resolve();
104
+ }, ms);
105
+ });
106
+ return {
107
+ cancel: () => clearTimeout(timeoutId),
108
+ promise
109
+ };
110
+ }
111
+ function promiseMap(inputValues, mapper) {
112
+ const reducer = (acc$, inputValue) => acc$.then(
113
+ (acc) => mapper(inputValue).then((result) => {
114
+ acc.push(result);
115
+ return acc;
116
+ })
117
+ );
118
+ return inputValues.reduce(reducer, Promise.resolve([]));
119
+ }
65
120
 
66
121
  function getEnvironment() {
67
122
  try {
68
- if (isObject(process) && isObject(process.env)) {
123
+ if (isDefined(process) && isDefined(process.env)) {
69
124
  return {
70
125
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
71
126
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
72
127
  branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
73
- envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
74
- fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
128
+ deployPreview: process.env.XATA_PREVIEW,
129
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
130
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
131
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
75
132
  };
76
133
  }
77
134
  } catch (err) {
@@ -82,8 +139,10 @@ function getEnvironment() {
82
139
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
83
140
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
84
141
  branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
85
- envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
86
- fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
142
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
143
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
144
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
145
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
87
146
  };
88
147
  }
89
148
  } catch (err) {
@@ -92,8 +151,10 @@ function getEnvironment() {
92
151
  apiKey: getGlobalApiKey(),
93
152
  databaseURL: getGlobalDatabaseURL(),
94
153
  branch: getGlobalBranch(),
95
- envBranch: void 0,
96
- fallbackBranch: getGlobalFallbackBranch()
154
+ deployPreview: void 0,
155
+ deployPreviewBranch: void 0,
156
+ vercelGitCommitRef: void 0,
157
+ vercelGitRepoOwner: void 0
97
158
  };
98
159
  }
99
160
  function getEnableBrowserVariable() {
@@ -136,56 +197,338 @@ function getGlobalBranch() {
136
197
  return void 0;
137
198
  }
138
199
  }
139
- function getGlobalFallbackBranch() {
200
+ function getDatabaseURL() {
140
201
  try {
141
- return XATA_FALLBACK_BRANCH;
202
+ const { databaseURL } = getEnvironment();
203
+ return databaseURL;
142
204
  } catch (err) {
143
205
  return void 0;
144
206
  }
145
207
  }
146
- async function getGitBranch() {
147
- const cmd = ["git", "branch", "--show-current"];
148
- const fullCmd = cmd.join(" ");
149
- const nodeModule = ["child", "process"].join("_");
150
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
208
+ function getAPIKey() {
151
209
  try {
152
- if (typeof require === "function") {
153
- return require(nodeModule).execSync(fullCmd, execOptions).trim();
154
- }
155
- const { execSync } = await import(nodeModule);
156
- return execSync(fullCmd, execOptions).toString().trim();
210
+ const { apiKey } = getEnvironment();
211
+ return apiKey;
157
212
  } catch (err) {
213
+ return void 0;
158
214
  }
215
+ }
216
+ function getBranch() {
159
217
  try {
160
- if (isObject(Deno)) {
161
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
162
- return new TextDecoder().decode(await process2.output()).trim();
163
- }
218
+ const { branch } = getEnvironment();
219
+ return branch;
164
220
  } catch (err) {
221
+ return void 0;
165
222
  }
166
223
  }
167
-
168
- function getAPIKey() {
224
+ function buildPreviewBranchName({ org, branch }) {
225
+ return `preview-${org}-${branch}`;
226
+ }
227
+ function getPreviewBranch() {
169
228
  try {
170
- const { apiKey } = getEnvironment();
171
- return apiKey;
229
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
230
+ if (deployPreviewBranch)
231
+ return deployPreviewBranch;
232
+ switch (deployPreview) {
233
+ case "vercel": {
234
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
235
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
236
+ return void 0;
237
+ }
238
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
239
+ }
240
+ }
241
+ return void 0;
172
242
  } catch (err) {
173
243
  return void 0;
174
244
  }
175
245
  }
176
246
 
247
+ var __accessCheck$8 = (obj, member, msg) => {
248
+ if (!member.has(obj))
249
+ throw TypeError("Cannot " + msg);
250
+ };
251
+ var __privateGet$8 = (obj, member, getter) => {
252
+ __accessCheck$8(obj, member, "read from private field");
253
+ return getter ? getter.call(obj) : member.get(obj);
254
+ };
255
+ var __privateAdd$8 = (obj, member, value) => {
256
+ if (member.has(obj))
257
+ throw TypeError("Cannot add the same private member more than once");
258
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
259
+ };
260
+ var __privateSet$8 = (obj, member, value, setter) => {
261
+ __accessCheck$8(obj, member, "write to private field");
262
+ setter ? setter.call(obj, value) : member.set(obj, value);
263
+ return value;
264
+ };
265
+ var __privateMethod$4 = (obj, member, method) => {
266
+ __accessCheck$8(obj, member, "access private method");
267
+ return method;
268
+ };
269
+ var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
270
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
177
271
  function getFetchImplementation(userFetch) {
178
272
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
179
- const fetchImpl = userFetch ?? globalFetch;
273
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
274
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
180
275
  if (!fetchImpl) {
181
- throw new Error(
182
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
183
- );
276
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
184
277
  }
185
278
  return fetchImpl;
186
279
  }
280
+ class ApiRequestPool {
281
+ constructor(concurrency = 10) {
282
+ __privateAdd$8(this, _enqueue);
283
+ __privateAdd$8(this, _fetch, void 0);
284
+ __privateAdd$8(this, _queue, void 0);
285
+ __privateAdd$8(this, _concurrency, void 0);
286
+ __privateSet$8(this, _queue, []);
287
+ __privateSet$8(this, _concurrency, concurrency);
288
+ this.running = 0;
289
+ this.started = 0;
290
+ }
291
+ setFetch(fetch2) {
292
+ __privateSet$8(this, _fetch, fetch2);
293
+ }
294
+ getFetch() {
295
+ if (!__privateGet$8(this, _fetch)) {
296
+ throw new Error("Fetch not set");
297
+ }
298
+ return __privateGet$8(this, _fetch);
299
+ }
300
+ request(url, options) {
301
+ const start = /* @__PURE__ */ new Date();
302
+ const fetchImpl = this.getFetch();
303
+ const runRequest = async (stalled = false) => {
304
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
305
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
306
+ if (!response) {
307
+ throw new Error("Request timed out");
308
+ }
309
+ if (response.status === 429) {
310
+ const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
311
+ await timeout(rateLimitReset * 1e3);
312
+ return await runRequest(true);
313
+ }
314
+ if (stalled) {
315
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
316
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
317
+ }
318
+ return response;
319
+ };
320
+ return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
321
+ return await runRequest();
322
+ });
323
+ }
324
+ }
325
+ _fetch = new WeakMap();
326
+ _queue = new WeakMap();
327
+ _concurrency = new WeakMap();
328
+ _enqueue = new WeakSet();
329
+ enqueue_fn = function(task) {
330
+ const promise = new Promise((resolve) => __privateGet$8(this, _queue).push(resolve)).finally(() => {
331
+ this.started--;
332
+ this.running++;
333
+ }).then(() => task()).finally(() => {
334
+ this.running--;
335
+ const next = __privateGet$8(this, _queue).shift();
336
+ if (next !== void 0) {
337
+ this.started++;
338
+ next();
339
+ }
340
+ });
341
+ if (this.running + this.started < __privateGet$8(this, _concurrency)) {
342
+ const next = __privateGet$8(this, _queue).shift();
343
+ if (next !== void 0) {
344
+ this.started++;
345
+ next();
346
+ }
347
+ }
348
+ return promise;
349
+ };
350
+
351
+ function generateUUID() {
352
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
353
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
354
+ return v.toString(16);
355
+ });
356
+ }
357
+
358
+ async function getBytes(stream, onChunk) {
359
+ const reader = stream.getReader();
360
+ let result;
361
+ while (!(result = await reader.read()).done) {
362
+ onChunk(result.value);
363
+ }
364
+ }
365
+ function getLines(onLine) {
366
+ let buffer;
367
+ let position;
368
+ let fieldLength;
369
+ let discardTrailingNewline = false;
370
+ return function onChunk(arr) {
371
+ if (buffer === void 0) {
372
+ buffer = arr;
373
+ position = 0;
374
+ fieldLength = -1;
375
+ } else {
376
+ buffer = concat(buffer, arr);
377
+ }
378
+ const bufLength = buffer.length;
379
+ let lineStart = 0;
380
+ while (position < bufLength) {
381
+ if (discardTrailingNewline) {
382
+ if (buffer[position] === 10 /* NewLine */) {
383
+ lineStart = ++position;
384
+ }
385
+ discardTrailingNewline = false;
386
+ }
387
+ let lineEnd = -1;
388
+ for (; position < bufLength && lineEnd === -1; ++position) {
389
+ switch (buffer[position]) {
390
+ case 58 /* Colon */:
391
+ if (fieldLength === -1) {
392
+ fieldLength = position - lineStart;
393
+ }
394
+ break;
395
+ case 13 /* CarriageReturn */:
396
+ discardTrailingNewline = true;
397
+ case 10 /* NewLine */:
398
+ lineEnd = position;
399
+ break;
400
+ }
401
+ }
402
+ if (lineEnd === -1) {
403
+ break;
404
+ }
405
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
406
+ lineStart = position;
407
+ fieldLength = -1;
408
+ }
409
+ if (lineStart === bufLength) {
410
+ buffer = void 0;
411
+ } else if (lineStart !== 0) {
412
+ buffer = buffer.subarray(lineStart);
413
+ position -= lineStart;
414
+ }
415
+ };
416
+ }
417
+ function getMessages(onId, onRetry, onMessage) {
418
+ let message = newMessage();
419
+ const decoder = new TextDecoder();
420
+ return function onLine(line, fieldLength) {
421
+ if (line.length === 0) {
422
+ onMessage?.(message);
423
+ message = newMessage();
424
+ } else if (fieldLength > 0) {
425
+ const field = decoder.decode(line.subarray(0, fieldLength));
426
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
427
+ const value = decoder.decode(line.subarray(valueOffset));
428
+ switch (field) {
429
+ case "data":
430
+ message.data = message.data ? message.data + "\n" + value : value;
431
+ break;
432
+ case "event":
433
+ message.event = value;
434
+ break;
435
+ case "id":
436
+ onId(message.id = value);
437
+ break;
438
+ case "retry":
439
+ const retry = parseInt(value, 10);
440
+ if (!isNaN(retry)) {
441
+ onRetry(message.retry = retry);
442
+ }
443
+ break;
444
+ }
445
+ }
446
+ };
447
+ }
448
+ function concat(a, b) {
449
+ const res = new Uint8Array(a.length + b.length);
450
+ res.set(a);
451
+ res.set(b, a.length);
452
+ return res;
453
+ }
454
+ function newMessage() {
455
+ return {
456
+ data: "",
457
+ event: "",
458
+ id: "",
459
+ retry: void 0
460
+ };
461
+ }
462
+ const EventStreamContentType = "text/event-stream";
463
+ const LastEventId = "last-event-id";
464
+ function fetchEventSource(input, {
465
+ signal: inputSignal,
466
+ headers: inputHeaders,
467
+ onopen: inputOnOpen,
468
+ onmessage,
469
+ onclose,
470
+ onerror,
471
+ fetch: inputFetch,
472
+ ...rest
473
+ }) {
474
+ return new Promise((resolve, reject) => {
475
+ const headers = { ...inputHeaders };
476
+ if (!headers.accept) {
477
+ headers.accept = EventStreamContentType;
478
+ }
479
+ let curRequestController;
480
+ function dispose() {
481
+ curRequestController.abort();
482
+ }
483
+ inputSignal?.addEventListener("abort", () => {
484
+ dispose();
485
+ resolve();
486
+ });
487
+ const fetchImpl = inputFetch ?? fetch;
488
+ const onopen = inputOnOpen ?? defaultOnOpen;
489
+ async function create() {
490
+ curRequestController = new AbortController();
491
+ try {
492
+ const response = await fetchImpl(input, {
493
+ ...rest,
494
+ headers,
495
+ signal: curRequestController.signal
496
+ });
497
+ await onopen(response);
498
+ await getBytes(
499
+ response.body,
500
+ getLines(
501
+ getMessages(
502
+ (id) => {
503
+ if (id) {
504
+ headers[LastEventId] = id;
505
+ } else {
506
+ delete headers[LastEventId];
507
+ }
508
+ },
509
+ (_retry) => {
510
+ },
511
+ onmessage
512
+ )
513
+ )
514
+ );
515
+ onclose?.();
516
+ dispose();
517
+ resolve();
518
+ } catch (err) {
519
+ }
520
+ }
521
+ create();
522
+ });
523
+ }
524
+ function defaultOnOpen(response) {
525
+ const contentType = response.headers?.get("content-type");
526
+ if (!contentType?.startsWith(EventStreamContentType)) {
527
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
528
+ }
529
+ }
187
530
 
188
- const VERSION = "0.0.0-alpha.vf8f3b02";
531
+ const VERSION = "0.27.0";
189
532
 
190
533
  class ErrorWithCause extends Error {
191
534
  constructor(message, options) {
@@ -196,7 +539,7 @@ class FetcherError extends ErrorWithCause {
196
539
  constructor(status, data, requestId) {
197
540
  super(getMessage(data));
198
541
  this.status = status;
199
- this.errors = isBulkError(data) ? data.errors : void 0;
542
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
200
543
  this.requestId = requestId;
201
544
  if (data instanceof Error) {
202
545
  this.stack = data.stack;
@@ -228,6 +571,7 @@ function getMessage(data) {
228
571
  }
229
572
  }
230
573
 
574
+ const pool = new ApiRequestPool();
231
575
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
232
576
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
233
577
  if (value === void 0 || value === null)
@@ -260,14 +604,27 @@ function hostHeader(url) {
260
604
  const { groups } = pattern.exec(url) ?? {};
261
605
  return groups?.host ? { Host: groups.host } : {};
262
606
  }
607
+ async function parseBody(body, headers) {
608
+ if (!isDefined(body))
609
+ return void 0;
610
+ if (isBlob(body) || typeof body.text === "function") {
611
+ return body;
612
+ }
613
+ const { "Content-Type": contentType } = headers ?? {};
614
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
615
+ return JSON.stringify(body);
616
+ }
617
+ return body;
618
+ }
619
+ const defaultClientID = generateUUID();
263
620
  async function fetch$1({
264
621
  url: path,
265
622
  method,
266
623
  body,
267
- headers,
624
+ headers: customHeaders,
268
625
  pathParams,
269
626
  queryParams,
270
- fetchImpl,
627
+ fetch: fetch2,
271
628
  apiKey,
272
629
  endpoint,
273
630
  apiUrl,
@@ -276,9 +633,13 @@ async function fetch$1({
276
633
  signal,
277
634
  clientID,
278
635
  sessionID,
279
- fetchOptions = {}
636
+ clientName,
637
+ xataAgentExtra,
638
+ fetchOptions = {},
639
+ rawResponse = false
280
640
  }) {
281
- return trace(
641
+ pool.setFetch(fetch2);
642
+ return await trace(
282
643
  `${method.toUpperCase()} ${path}`,
283
644
  async ({ setAttributes }) => {
284
645
  const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
@@ -288,24 +649,29 @@ async function fetch$1({
288
649
  [TraceAttributes.HTTP_URL]: url,
289
650
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
290
651
  });
291
- const response = await fetchImpl(url, {
652
+ const xataAgent = compact([
653
+ ["client", "TS_SDK"],
654
+ ["version", VERSION],
655
+ isDefined(clientName) ? ["service", clientName] : void 0,
656
+ ...Object.entries(xataAgentExtra ?? {})
657
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
658
+ const headers = compactObject({
659
+ "Accept-Encoding": "identity",
660
+ "Content-Type": "application/json",
661
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
662
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
663
+ "X-Xata-Agent": xataAgent,
664
+ ...customHeaders,
665
+ ...hostHeader(fullUrl),
666
+ Authorization: `Bearer ${apiKey}`
667
+ });
668
+ const response = await pool.request(url, {
292
669
  ...fetchOptions,
293
670
  method: method.toUpperCase(),
294
- body: body ? JSON.stringify(body) : void 0,
295
- headers: {
296
- "Content-Type": "application/json",
297
- "User-Agent": `Xata client-ts/${VERSION}`,
298
- "X-Xata-Client-ID": clientID ?? "",
299
- "X-Xata-Session-ID": sessionID ?? "",
300
- ...headers,
301
- ...hostHeader(fullUrl),
302
- Authorization: `Bearer ${apiKey}`
303
- },
671
+ body: await parseBody(body, headers),
672
+ headers,
304
673
  signal
305
674
  });
306
- if (response.status === 204) {
307
- return {};
308
- }
309
675
  const { host, protocol } = parseUrl(response.url);
310
676
  const requestId = response.headers?.get("x-request-id") ?? void 0;
311
677
  setAttributes({
@@ -313,10 +679,20 @@ async function fetch$1({
313
679
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
314
680
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
315
681
  [TraceAttributes.HTTP_HOST]: host,
316
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
682
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
683
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
317
684
  });
685
+ const message = response.headers?.get("x-xata-message");
686
+ if (message)
687
+ console.warn(message);
688
+ if (response.status === 204) {
689
+ return {};
690
+ }
691
+ if (response.status === 429) {
692
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
693
+ }
318
694
  try {
319
- const jsonResponse = await response.json();
695
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
320
696
  if (response.ok) {
321
697
  return jsonResponse;
322
698
  }
@@ -328,6 +704,59 @@ async function fetch$1({
328
704
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
329
705
  );
330
706
  }
707
+ function fetchSSERequest({
708
+ url: path,
709
+ method,
710
+ body,
711
+ headers: customHeaders,
712
+ pathParams,
713
+ queryParams,
714
+ fetch: fetch2,
715
+ apiKey,
716
+ endpoint,
717
+ apiUrl,
718
+ workspacesApiUrl,
719
+ onMessage,
720
+ onError,
721
+ onClose,
722
+ signal,
723
+ clientID,
724
+ sessionID,
725
+ clientName,
726
+ xataAgentExtra
727
+ }) {
728
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
729
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
730
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
731
+ void fetchEventSource(url, {
732
+ method,
733
+ body: JSON.stringify(body),
734
+ fetch: fetch2,
735
+ signal,
736
+ headers: {
737
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
738
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
739
+ "X-Xata-Agent": compact([
740
+ ["client", "TS_SDK"],
741
+ ["version", VERSION],
742
+ isDefined(clientName) ? ["service", clientName] : void 0,
743
+ ...Object.entries(xataAgentExtra ?? {})
744
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
745
+ ...customHeaders,
746
+ Authorization: `Bearer ${apiKey}`,
747
+ "Content-Type": "application/json"
748
+ },
749
+ onmessage(ev) {
750
+ onMessage?.(JSON.parse(ev.data));
751
+ },
752
+ onerror(ev) {
753
+ onError?.(JSON.parse(ev.data));
754
+ },
755
+ onclose() {
756
+ onClose?.();
757
+ }
758
+ });
759
+ }
331
760
  function parseUrl(url) {
332
761
  try {
333
762
  const { host, protocol } = new URL(url);
@@ -339,17 +768,18 @@ function parseUrl(url) {
339
768
 
340
769
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
341
770
 
342
- const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
771
+ const applyMigration = (variables, signal) => dataPlaneFetch({
772
+ url: "/db/{dbBranchName}/pgroll/apply",
773
+ method: "post",
774
+ ...variables,
775
+ signal
776
+ });
343
777
  const getBranchList = (variables, signal) => dataPlaneFetch({
344
778
  url: "/dbs/{dbName}",
345
779
  method: "get",
346
780
  ...variables,
347
781
  signal
348
782
  });
349
- const dEPRECATEDcreateDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
350
- const dEPRECATEDdeleteDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "delete", ...variables, signal });
351
- const dEPRECATEDgetDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "get", ...variables, signal });
352
- const dEPRECATEDupdateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
353
783
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
354
784
  url: "/db/{dbBranchName}",
355
785
  method: "get",
@@ -363,6 +793,18 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
363
793
  ...variables,
364
794
  signal
365
795
  });
796
+ const getSchema = (variables, signal) => dataPlaneFetch({
797
+ url: "/db/{dbBranchName}/schema",
798
+ method: "get",
799
+ ...variables,
800
+ signal
801
+ });
802
+ const copyBranch = (variables, signal) => dataPlaneFetch({
803
+ url: "/db/{dbBranchName}/copy",
804
+ method: "post",
805
+ ...variables,
806
+ signal
807
+ });
366
808
  const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
367
809
  url: "/db/{dbBranchName}/metadata",
368
810
  method: "put",
@@ -388,7 +830,6 @@ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName
388
830
  const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
389
831
  const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
390
832
  const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
391
- const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
392
833
  const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
393
834
  const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
394
835
  const getMigrationRequest = (variables, signal) => dataPlaneFetch({
@@ -413,6 +854,7 @@ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{
413
854
  const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
414
855
  const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
415
856
  const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
857
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
416
858
  const createTable = (variables, signal) => dataPlaneFetch({
417
859
  url: "/db/{dbBranchName}/tables/{tableName}",
418
860
  method: "put",
@@ -455,7 +897,44 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
455
897
  ...variables,
456
898
  signal
457
899
  });
900
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
458
901
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
902
+ const getFileItem = (variables, signal) => dataPlaneFetch({
903
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
904
+ method: "get",
905
+ ...variables,
906
+ signal
907
+ });
908
+ const putFileItem = (variables, signal) => dataPlaneFetch({
909
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
910
+ method: "put",
911
+ ...variables,
912
+ signal
913
+ });
914
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
915
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
916
+ method: "delete",
917
+ ...variables,
918
+ signal
919
+ });
920
+ const getFile = (variables, signal) => dataPlaneFetch({
921
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
922
+ method: "get",
923
+ ...variables,
924
+ signal
925
+ });
926
+ const putFile = (variables, signal) => dataPlaneFetch({
927
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
928
+ method: "put",
929
+ ...variables,
930
+ signal
931
+ });
932
+ const deleteFile = (variables, signal) => dataPlaneFetch({
933
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
934
+ method: "delete",
935
+ ...variables,
936
+ signal
937
+ });
459
938
  const getRecord = (variables, signal) => dataPlaneFetch({
460
939
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
461
940
  method: "get",
@@ -485,21 +964,36 @@ const searchTable = (variables, signal) => dataPlaneFetch({
485
964
  ...variables,
486
965
  signal
487
966
  });
967
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
968
+ const askTable = (variables, signal) => dataPlaneFetch({
969
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
970
+ method: "post",
971
+ ...variables,
972
+ signal
973
+ });
974
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
488
975
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
489
976
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
977
+ const fileAccess = (variables, signal) => dataPlaneFetch({
978
+ url: "/file/{fileId}",
979
+ method: "get",
980
+ ...variables,
981
+ signal
982
+ });
983
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
984
+ url: "/db/{dbBranchName}/sql",
985
+ method: "post",
986
+ ...variables,
987
+ signal
988
+ });
490
989
  const operationsByTag$2 = {
491
- database: {
492
- dEPRECATEDgetDatabaseList,
493
- dEPRECATEDcreateDatabase,
494
- dEPRECATEDdeleteDatabase,
495
- dEPRECATEDgetDatabaseMetadata,
496
- dEPRECATEDupdateDatabaseMetadata
497
- },
498
990
  branch: {
991
+ applyMigration,
499
992
  getBranchList,
500
993
  getBranchDetails,
501
994
  createBranch,
502
995
  deleteBranch,
996
+ copyBranch,
503
997
  updateBranchMetadata,
504
998
  getBranchMetadata,
505
999
  getBranchStats,
@@ -509,6 +1003,7 @@ const operationsByTag$2 = {
509
1003
  resolveBranch
510
1004
  },
511
1005
  migrations: {
1006
+ getSchema,
512
1007
  getBranchMigrationHistory,
513
1008
  getBranchMigrationPlan,
514
1009
  executeBranchMigrationPlan,
@@ -517,17 +1012,8 @@ const operationsByTag$2 = {
517
1012
  compareBranchSchemas,
518
1013
  updateBranchSchema,
519
1014
  previewBranchSchemaEdit,
520
- applyBranchSchemaEdit
521
- },
522
- records: {
523
- branchTransaction,
524
- insertRecord,
525
- getRecord,
526
- insertRecordWithID,
527
- updateRecordWithID,
528
- upsertRecordWithID,
529
- deleteRecord,
530
- bulkInsertTableRecords
1015
+ applyBranchSchemaEdit,
1016
+ pushBranchMigrations
531
1017
  },
532
1018
  migrationRequests: {
533
1019
  queryMigrationRequests,
@@ -551,11 +1037,34 @@ const operationsByTag$2 = {
551
1037
  updateColumn,
552
1038
  deleteColumn
553
1039
  },
554
- searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
1040
+ records: {
1041
+ branchTransaction,
1042
+ insertRecord,
1043
+ getRecord,
1044
+ insertRecordWithID,
1045
+ updateRecordWithID,
1046
+ upsertRecordWithID,
1047
+ deleteRecord,
1048
+ bulkInsertTableRecords
1049
+ },
1050
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess },
1051
+ searchAndFilter: {
1052
+ queryTable,
1053
+ searchBranch,
1054
+ searchTable,
1055
+ vectorSearchTable,
1056
+ askTable,
1057
+ askTableSession,
1058
+ summarizeTable,
1059
+ aggregateTable
1060
+ },
1061
+ sql: { sqlQuery }
555
1062
  };
556
1063
 
557
1064
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
558
1065
 
1066
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1067
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
559
1068
  const getUser = (variables, signal) => controlPlaneFetch({
560
1069
  url: "/user",
561
1070
  method: "get",
@@ -592,6 +1101,31 @@ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
592
1101
  ...variables,
593
1102
  signal
594
1103
  });
1104
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1105
+ url: "/user/oauth/clients",
1106
+ method: "get",
1107
+ ...variables,
1108
+ signal
1109
+ });
1110
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1111
+ url: "/user/oauth/clients/{clientId}",
1112
+ method: "delete",
1113
+ ...variables,
1114
+ signal
1115
+ });
1116
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1117
+ url: "/user/oauth/tokens",
1118
+ method: "get",
1119
+ ...variables,
1120
+ signal
1121
+ });
1122
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1123
+ url: "/user/oauth/tokens/{token}",
1124
+ method: "delete",
1125
+ ...variables,
1126
+ signal
1127
+ });
1128
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
595
1129
  const getWorkspacesList = (variables, signal) => controlPlaneFetch({
596
1130
  url: "/workspaces",
597
1131
  method: "get",
@@ -635,6 +1169,20 @@ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ u
635
1169
  const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
636
1170
  const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
637
1171
  const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1172
+ const listClusters = (variables, signal) => controlPlaneFetch({
1173
+ url: "/workspaces/{workspaceId}/clusters",
1174
+ method: "get",
1175
+ ...variables,
1176
+ signal
1177
+ });
1178
+ const createCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "post", ...variables, signal });
1179
+ const getCluster = (variables, signal) => controlPlaneFetch({
1180
+ url: "/workspaces/{workspaceId}/clusters/{clusterId}",
1181
+ method: "get",
1182
+ ...variables,
1183
+ signal
1184
+ });
1185
+ const updateCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters/{clusterId}", method: "patch", ...variables, signal });
638
1186
  const getDatabaseList = (variables, signal) => controlPlaneFetch({
639
1187
  url: "/workspaces/{workspaceId}/dbs",
640
1188
  method: "get",
@@ -650,6 +1198,10 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
650
1198
  });
651
1199
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
652
1200
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1201
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1202
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1203
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1204
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
653
1205
  const listRegions = (variables, signal) => controlPlaneFetch({
654
1206
  url: "/workspaces/{workspaceId}/regions",
655
1207
  method: "get",
@@ -657,6 +1209,15 @@ const listRegions = (variables, signal) => controlPlaneFetch({
657
1209
  signal
658
1210
  });
659
1211
  const operationsByTag$1 = {
1212
+ oAuth: {
1213
+ getAuthorizationCode,
1214
+ grantAuthorizationCode,
1215
+ getUserOAuthClients,
1216
+ deleteUserOAuthClient,
1217
+ getUserOAuthAccessTokens,
1218
+ deleteOAuthAccessToken,
1219
+ updateOAuthAccessToken
1220
+ },
660
1221
  users: { getUser, updateUser, deleteUser },
661
1222
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
662
1223
  workspaces: {
@@ -676,12 +1237,17 @@ const operationsByTag$1 = {
676
1237
  acceptWorkspaceMemberInvite,
677
1238
  resendWorkspaceMemberInvite
678
1239
  },
1240
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
679
1241
  databases: {
680
1242
  getDatabaseList,
681
1243
  createDatabase,
682
1244
  deleteDatabase,
683
1245
  getDatabaseMetadata,
684
1246
  updateDatabaseMetadata,
1247
+ renameDatabase,
1248
+ getDatabaseGithubSettings,
1249
+ updateDatabaseGithubSettings,
1250
+ deleteDatabaseGithubSettings,
685
1251
  listRegions
686
1252
  }
687
1253
  };
@@ -702,8 +1268,12 @@ const providers = {
702
1268
  workspaces: "https://{workspaceId}.{region}.xata.sh"
703
1269
  },
704
1270
  staging: {
705
- main: "https://staging.xatabase.co",
706
- workspaces: "https://{workspaceId}.staging.{region}.xatabase.co"
1271
+ main: "https://api.staging-xata.dev",
1272
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1273
+ },
1274
+ dev: {
1275
+ main: "https://api.dev-xata.dev",
1276
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
707
1277
  }
708
1278
  };
709
1279
  function isHostProviderAlias(alias) {
@@ -721,15 +1291,22 @@ function parseProviderString(provider = "production") {
721
1291
  return null;
722
1292
  return { main, workspaces };
723
1293
  }
1294
+ function buildProviderString(provider) {
1295
+ if (isHostProviderAlias(provider))
1296
+ return provider;
1297
+ return `${provider.main},${provider.workspaces}`;
1298
+ }
724
1299
  function parseWorkspacesUrlParts(url) {
725
1300
  if (!isString(url))
726
1301
  return null;
727
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
728
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
729
- const match = url.match(regex) || url.match(regexStaging);
1302
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
1303
+ const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1304
+ const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1305
+ const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1306
+ const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
730
1307
  if (!match)
731
1308
  return null;
732
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
1309
+ return { workspace: match[1], region: match[2] };
733
1310
  }
734
1311
 
735
1312
  var __accessCheck$7 = (obj, member, msg) => {
@@ -758,15 +1335,19 @@ class XataApiClient {
758
1335
  const provider = options.host ?? "production";
759
1336
  const apiKey = options.apiKey ?? getAPIKey();
760
1337
  const trace = options.trace ?? defaultTrace;
1338
+ const clientID = generateUUID();
761
1339
  if (!apiKey) {
762
1340
  throw new Error("Could not resolve a valid apiKey");
763
1341
  }
764
1342
  __privateSet$7(this, _extraProps, {
765
1343
  apiUrl: getHostUrl(provider, "main"),
766
1344
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
767
- fetchImpl: getFetchImplementation(options.fetch),
1345
+ fetch: getFetchImplementation(options.fetch),
768
1346
  apiKey,
769
- trace
1347
+ trace,
1348
+ clientName: options.clientName,
1349
+ xataAgentExtra: options.xataAgentExtra,
1350
+ clientID
770
1351
  });
771
1352
  }
772
1353
  get user() {
@@ -819,6 +1400,11 @@ class XataApiClient {
819
1400
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
820
1401
  return __privateGet$7(this, _namespaces).records;
821
1402
  }
1403
+ get files() {
1404
+ if (!__privateGet$7(this, _namespaces).files)
1405
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1406
+ return __privateGet$7(this, _namespaces).files;
1407
+ }
822
1408
  get searchAndFilter() {
823
1409
  if (!__privateGet$7(this, _namespaces).searchAndFilter)
824
1410
  __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
@@ -1027,6 +1613,20 @@ class BranchApi {
1027
1613
  ...this.extraProps
1028
1614
  });
1029
1615
  }
1616
+ copyBranch({
1617
+ workspace,
1618
+ region,
1619
+ database,
1620
+ branch,
1621
+ destinationBranch,
1622
+ limit
1623
+ }) {
1624
+ return operationsByTag.branch.copyBranch({
1625
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1626
+ body: { destinationBranch, limit },
1627
+ ...this.extraProps
1628
+ });
1629
+ }
1030
1630
  updateBranchMetadata({
1031
1631
  workspace,
1032
1632
  region,
@@ -1368,6 +1968,177 @@ class RecordsApi {
1368
1968
  ...this.extraProps
1369
1969
  });
1370
1970
  }
1971
+ branchTransaction({
1972
+ workspace,
1973
+ region,
1974
+ database,
1975
+ branch,
1976
+ operations
1977
+ }) {
1978
+ return operationsByTag.records.branchTransaction({
1979
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1980
+ body: { operations },
1981
+ ...this.extraProps
1982
+ });
1983
+ }
1984
+ }
1985
+ class FilesApi {
1986
+ constructor(extraProps) {
1987
+ this.extraProps = extraProps;
1988
+ }
1989
+ getFileItem({
1990
+ workspace,
1991
+ region,
1992
+ database,
1993
+ branch,
1994
+ table,
1995
+ record,
1996
+ column,
1997
+ fileId
1998
+ }) {
1999
+ return operationsByTag.files.getFileItem({
2000
+ pathParams: {
2001
+ workspace,
2002
+ region,
2003
+ dbBranchName: `${database}:${branch}`,
2004
+ tableName: table,
2005
+ recordId: record,
2006
+ columnName: column,
2007
+ fileId
2008
+ },
2009
+ ...this.extraProps
2010
+ });
2011
+ }
2012
+ putFileItem({
2013
+ workspace,
2014
+ region,
2015
+ database,
2016
+ branch,
2017
+ table,
2018
+ record,
2019
+ column,
2020
+ fileId,
2021
+ file
2022
+ }) {
2023
+ return operationsByTag.files.putFileItem({
2024
+ pathParams: {
2025
+ workspace,
2026
+ region,
2027
+ dbBranchName: `${database}:${branch}`,
2028
+ tableName: table,
2029
+ recordId: record,
2030
+ columnName: column,
2031
+ fileId
2032
+ },
2033
+ // @ts-ignore
2034
+ body: file,
2035
+ ...this.extraProps
2036
+ });
2037
+ }
2038
+ deleteFileItem({
2039
+ workspace,
2040
+ region,
2041
+ database,
2042
+ branch,
2043
+ table,
2044
+ record,
2045
+ column,
2046
+ fileId
2047
+ }) {
2048
+ return operationsByTag.files.deleteFileItem({
2049
+ pathParams: {
2050
+ workspace,
2051
+ region,
2052
+ dbBranchName: `${database}:${branch}`,
2053
+ tableName: table,
2054
+ recordId: record,
2055
+ columnName: column,
2056
+ fileId
2057
+ },
2058
+ ...this.extraProps
2059
+ });
2060
+ }
2061
+ getFile({
2062
+ workspace,
2063
+ region,
2064
+ database,
2065
+ branch,
2066
+ table,
2067
+ record,
2068
+ column
2069
+ }) {
2070
+ return operationsByTag.files.getFile({
2071
+ pathParams: {
2072
+ workspace,
2073
+ region,
2074
+ dbBranchName: `${database}:${branch}`,
2075
+ tableName: table,
2076
+ recordId: record,
2077
+ columnName: column
2078
+ },
2079
+ ...this.extraProps
2080
+ });
2081
+ }
2082
+ putFile({
2083
+ workspace,
2084
+ region,
2085
+ database,
2086
+ branch,
2087
+ table,
2088
+ record,
2089
+ column,
2090
+ file
2091
+ }) {
2092
+ return operationsByTag.files.putFile({
2093
+ pathParams: {
2094
+ workspace,
2095
+ region,
2096
+ dbBranchName: `${database}:${branch}`,
2097
+ tableName: table,
2098
+ recordId: record,
2099
+ columnName: column
2100
+ },
2101
+ body: file,
2102
+ ...this.extraProps
2103
+ });
2104
+ }
2105
+ deleteFile({
2106
+ workspace,
2107
+ region,
2108
+ database,
2109
+ branch,
2110
+ table,
2111
+ record,
2112
+ column
2113
+ }) {
2114
+ return operationsByTag.files.deleteFile({
2115
+ pathParams: {
2116
+ workspace,
2117
+ region,
2118
+ dbBranchName: `${database}:${branch}`,
2119
+ tableName: table,
2120
+ recordId: record,
2121
+ columnName: column
2122
+ },
2123
+ ...this.extraProps
2124
+ });
2125
+ }
2126
+ fileAccess({
2127
+ workspace,
2128
+ region,
2129
+ fileId,
2130
+ verify
2131
+ }) {
2132
+ return operationsByTag.files.fileAccess({
2133
+ pathParams: {
2134
+ workspace,
2135
+ region,
2136
+ fileId
2137
+ },
2138
+ queryParams: { verify },
2139
+ ...this.extraProps
2140
+ });
2141
+ }
1371
2142
  }
1372
2143
  class SearchAndFilterApi {
1373
2144
  constructor(extraProps) {
@@ -1428,6 +2199,53 @@ class SearchAndFilterApi {
1428
2199
  ...this.extraProps
1429
2200
  });
1430
2201
  }
2202
+ vectorSearchTable({
2203
+ workspace,
2204
+ region,
2205
+ database,
2206
+ branch,
2207
+ table,
2208
+ queryVector,
2209
+ column,
2210
+ similarityFunction,
2211
+ size,
2212
+ filter
2213
+ }) {
2214
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2215
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2216
+ body: { queryVector, column, similarityFunction, size, filter },
2217
+ ...this.extraProps
2218
+ });
2219
+ }
2220
+ askTable({
2221
+ workspace,
2222
+ region,
2223
+ database,
2224
+ branch,
2225
+ table,
2226
+ options
2227
+ }) {
2228
+ return operationsByTag.searchAndFilter.askTable({
2229
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2230
+ body: { ...options },
2231
+ ...this.extraProps
2232
+ });
2233
+ }
2234
+ askTableSession({
2235
+ workspace,
2236
+ region,
2237
+ database,
2238
+ branch,
2239
+ table,
2240
+ sessionId,
2241
+ message
2242
+ }) {
2243
+ return operationsByTag.searchAndFilter.askTableSession({
2244
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2245
+ body: { message },
2246
+ ...this.extraProps
2247
+ });
2248
+ }
1431
2249
  summarizeTable({
1432
2250
  workspace,
1433
2251
  region,
@@ -1628,11 +2446,13 @@ class MigrationsApi {
1628
2446
  region,
1629
2447
  database,
1630
2448
  branch,
1631
- schema
2449
+ schema,
2450
+ schemaOperations,
2451
+ branchOperations
1632
2452
  }) {
1633
2453
  return operationsByTag.migrations.compareBranchWithUserSchema({
1634
2454
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1635
- body: { schema },
2455
+ body: { schema, schemaOperations, branchOperations },
1636
2456
  ...this.extraProps
1637
2457
  });
1638
2458
  }
@@ -1642,11 +2462,12 @@ class MigrationsApi {
1642
2462
  database,
1643
2463
  branch,
1644
2464
  compare,
1645
- schema
2465
+ sourceBranchOperations,
2466
+ targetBranchOperations
1646
2467
  }) {
1647
2468
  return operationsByTag.migrations.compareBranchSchemas({
1648
2469
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1649
- body: { schema },
2470
+ body: { sourceBranchOperations, targetBranchOperations },
1650
2471
  ...this.extraProps
1651
2472
  });
1652
2473
  }
@@ -1689,6 +2510,19 @@ class MigrationsApi {
1689
2510
  ...this.extraProps
1690
2511
  });
1691
2512
  }
2513
+ pushBranchMigrations({
2514
+ workspace,
2515
+ region,
2516
+ database,
2517
+ branch,
2518
+ migrations
2519
+ }) {
2520
+ return operationsByTag.migrations.pushBranchMigrations({
2521
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2522
+ body: { migrations },
2523
+ ...this.extraProps
2524
+ });
2525
+ }
1692
2526
  }
1693
2527
  class DatabaseApi {
1694
2528
  constructor(extraProps) {
@@ -1703,11 +2537,13 @@ class DatabaseApi {
1703
2537
  createDatabase({
1704
2538
  workspace,
1705
2539
  database,
1706
- data
2540
+ data,
2541
+ headers
1707
2542
  }) {
1708
2543
  return operationsByTag.databases.createDatabase({
1709
2544
  pathParams: { workspaceId: workspace, dbName: database },
1710
2545
  body: data,
2546
+ headers,
1711
2547
  ...this.extraProps
1712
2548
  });
1713
2549
  }
@@ -1740,6 +2576,46 @@ class DatabaseApi {
1740
2576
  ...this.extraProps
1741
2577
  });
1742
2578
  }
2579
+ renameDatabase({
2580
+ workspace,
2581
+ database,
2582
+ newName
2583
+ }) {
2584
+ return operationsByTag.databases.renameDatabase({
2585
+ pathParams: { workspaceId: workspace, dbName: database },
2586
+ body: { newName },
2587
+ ...this.extraProps
2588
+ });
2589
+ }
2590
+ getDatabaseGithubSettings({
2591
+ workspace,
2592
+ database
2593
+ }) {
2594
+ return operationsByTag.databases.getDatabaseGithubSettings({
2595
+ pathParams: { workspaceId: workspace, dbName: database },
2596
+ ...this.extraProps
2597
+ });
2598
+ }
2599
+ updateDatabaseGithubSettings({
2600
+ workspace,
2601
+ database,
2602
+ settings
2603
+ }) {
2604
+ return operationsByTag.databases.updateDatabaseGithubSettings({
2605
+ pathParams: { workspaceId: workspace, dbName: database },
2606
+ body: settings,
2607
+ ...this.extraProps
2608
+ });
2609
+ }
2610
+ deleteDatabaseGithubSettings({
2611
+ workspace,
2612
+ database
2613
+ }) {
2614
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
2615
+ pathParams: { workspaceId: workspace, dbName: database },
2616
+ ...this.extraProps
2617
+ });
2618
+ }
1743
2619
  listRegions({ workspace }) {
1744
2620
  return operationsByTag.databases.listRegions({
1745
2621
  pathParams: { workspaceId: workspace },
@@ -1749,27 +2625,200 @@ class DatabaseApi {
1749
2625
  }
1750
2626
 
1751
2627
  class XataApiPlugin {
1752
- async build(options) {
1753
- const { fetchImpl, apiKey } = await options.getFetchProps();
1754
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2628
+ build(options) {
2629
+ return new XataApiClient(options);
1755
2630
  }
1756
2631
  }
1757
2632
 
1758
2633
  class XataPlugin {
1759
2634
  }
1760
2635
 
1761
- function generateUUID() {
1762
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1763
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1764
- return v.toString(16);
2636
+ function buildTransformString(transformations) {
2637
+ return transformations.flatMap(
2638
+ (t) => Object.entries(t).map(([key, value]) => {
2639
+ if (key === "trim") {
2640
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2641
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2642
+ }
2643
+ if (key === "gravity" && typeof value === "object") {
2644
+ const { x = 0.5, y = 0.5 } = value;
2645
+ return `${key}=${[x, y].join("x")}`;
2646
+ }
2647
+ return `${key}=${value}`;
2648
+ })
2649
+ ).join(",");
2650
+ }
2651
+ function transformImage(url, ...transformations) {
2652
+ if (!isDefined(url))
2653
+ return void 0;
2654
+ const newTransformations = buildTransformString(transformations);
2655
+ const { hostname, pathname, search } = new URL(url);
2656
+ const pathParts = pathname.split("/");
2657
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2658
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2659
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2660
+ const path = pathParts.join("/");
2661
+ return `https://${hostname}${transform}${path}${search}`;
2662
+ }
2663
+
2664
+ class XataFile {
2665
+ constructor(file) {
2666
+ this.id = file.id;
2667
+ this.name = file.name || "";
2668
+ this.mediaType = file.mediaType || "application/octet-stream";
2669
+ this.base64Content = file.base64Content;
2670
+ this.enablePublicUrl = file.enablePublicUrl ?? false;
2671
+ this.signedUrlTimeout = file.signedUrlTimeout ?? 300;
2672
+ this.size = file.size ?? 0;
2673
+ this.version = file.version ?? 1;
2674
+ this.url = file.url || "";
2675
+ this.signedUrl = file.signedUrl;
2676
+ this.attributes = file.attributes || {};
2677
+ }
2678
+ static fromBuffer(buffer, options = {}) {
2679
+ const base64Content = buffer.toString("base64");
2680
+ return new XataFile({ ...options, base64Content });
2681
+ }
2682
+ toBuffer() {
2683
+ if (!this.base64Content) {
2684
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2685
+ }
2686
+ return Buffer.from(this.base64Content, "base64");
2687
+ }
2688
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2689
+ const uint8Array = new Uint8Array(arrayBuffer);
2690
+ return this.fromUint8Array(uint8Array, options);
2691
+ }
2692
+ toArrayBuffer() {
2693
+ if (!this.base64Content) {
2694
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2695
+ }
2696
+ const binary = atob(this.base64Content);
2697
+ return new ArrayBuffer(binary.length);
2698
+ }
2699
+ static fromUint8Array(uint8Array, options = {}) {
2700
+ let binary = "";
2701
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2702
+ binary += String.fromCharCode(uint8Array[i]);
2703
+ }
2704
+ const base64Content = btoa(binary);
2705
+ return new XataFile({ ...options, base64Content });
2706
+ }
2707
+ toUint8Array() {
2708
+ if (!this.base64Content) {
2709
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2710
+ }
2711
+ const binary = atob(this.base64Content);
2712
+ const uint8Array = new Uint8Array(binary.length);
2713
+ for (let i = 0; i < binary.length; i++) {
2714
+ uint8Array[i] = binary.charCodeAt(i);
2715
+ }
2716
+ return uint8Array;
2717
+ }
2718
+ static async fromBlob(file, options = {}) {
2719
+ const name = options.name ?? file.name;
2720
+ const mediaType = file.type;
2721
+ const arrayBuffer = await file.arrayBuffer();
2722
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2723
+ }
2724
+ toBlob() {
2725
+ if (!this.base64Content) {
2726
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2727
+ }
2728
+ const binary = atob(this.base64Content);
2729
+ const uint8Array = new Uint8Array(binary.length);
2730
+ for (let i = 0; i < binary.length; i++) {
2731
+ uint8Array[i] = binary.charCodeAt(i);
2732
+ }
2733
+ return new Blob([uint8Array], { type: this.mediaType });
2734
+ }
2735
+ static fromString(string, options = {}) {
2736
+ const base64Content = btoa(string);
2737
+ return new XataFile({ ...options, base64Content });
2738
+ }
2739
+ toString() {
2740
+ if (!this.base64Content) {
2741
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2742
+ }
2743
+ return atob(this.base64Content);
2744
+ }
2745
+ static fromBase64(base64Content, options = {}) {
2746
+ return new XataFile({ ...options, base64Content });
2747
+ }
2748
+ toBase64() {
2749
+ if (!this.base64Content) {
2750
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2751
+ }
2752
+ return this.base64Content;
2753
+ }
2754
+ transform(...options) {
2755
+ return {
2756
+ url: transformImage(this.url, ...options),
2757
+ signedUrl: transformImage(this.signedUrl, ...options),
2758
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2759
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2760
+ };
2761
+ }
2762
+ }
2763
+ const parseInputFileEntry = async (entry) => {
2764
+ if (!isDefined(entry))
2765
+ return null;
2766
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout } = await entry;
2767
+ return compactObject({
2768
+ id,
2769
+ // Name cannot be an empty string in our API
2770
+ name: name ? name : void 0,
2771
+ mediaType,
2772
+ base64Content,
2773
+ enablePublicUrl,
2774
+ signedUrlTimeout
1765
2775
  });
1766
- }
2776
+ };
1767
2777
 
1768
2778
  function cleanFilter(filter) {
1769
- if (!filter)
2779
+ if (!isDefined(filter))
1770
2780
  return void 0;
1771
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1772
- return values.length > 0 ? filter : void 0;
2781
+ if (!isObject(filter))
2782
+ return filter;
2783
+ const values = Object.fromEntries(
2784
+ Object.entries(filter).reduce((acc, [key, value]) => {
2785
+ if (!isDefined(value))
2786
+ return acc;
2787
+ if (Array.isArray(value)) {
2788
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2789
+ if (clean.length === 0)
2790
+ return acc;
2791
+ return [...acc, [key, clean]];
2792
+ }
2793
+ if (isObject(value)) {
2794
+ const clean = cleanFilter(value);
2795
+ if (!isDefined(clean))
2796
+ return acc;
2797
+ return [...acc, [key, clean]];
2798
+ }
2799
+ return [...acc, [key, value]];
2800
+ }, [])
2801
+ );
2802
+ return Object.keys(values).length > 0 ? values : void 0;
2803
+ }
2804
+
2805
+ function stringifyJson(value) {
2806
+ if (!isDefined(value))
2807
+ return value;
2808
+ if (isString(value))
2809
+ return value;
2810
+ try {
2811
+ return JSON.stringify(value);
2812
+ } catch (e) {
2813
+ return value;
2814
+ }
2815
+ }
2816
+ function parseJson(value) {
2817
+ try {
2818
+ return JSON.parse(value);
2819
+ } catch (e) {
2820
+ return value;
2821
+ }
1773
2822
  }
1774
2823
 
1775
2824
  var __accessCheck$6 = (obj, member, msg) => {
@@ -1798,31 +2847,59 @@ class Page {
1798
2847
  this.meta = meta;
1799
2848
  this.records = new RecordArray(this, records);
1800
2849
  }
2850
+ /**
2851
+ * Retrieves the next page of results.
2852
+ * @param size Maximum number of results to be retrieved.
2853
+ * @param offset Number of results to skip when retrieving the results.
2854
+ * @returns The next page or results.
2855
+ */
1801
2856
  async nextPage(size, offset) {
1802
2857
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
1803
2858
  }
2859
+ /**
2860
+ * Retrieves the previous page of results.
2861
+ * @param size Maximum number of results to be retrieved.
2862
+ * @param offset Number of results to skip when retrieving the results.
2863
+ * @returns The previous page or results.
2864
+ */
1804
2865
  async previousPage(size, offset) {
1805
2866
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1806
2867
  }
2868
+ /**
2869
+ * Retrieves the start page of results.
2870
+ * @param size Maximum number of results to be retrieved.
2871
+ * @param offset Number of results to skip when retrieving the results.
2872
+ * @returns The start page or results.
2873
+ */
1807
2874
  async startPage(size, offset) {
1808
2875
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1809
2876
  }
2877
+ /**
2878
+ * Retrieves the end page of results.
2879
+ * @param size Maximum number of results to be retrieved.
2880
+ * @param offset Number of results to skip when retrieving the results.
2881
+ * @returns The end page or results.
2882
+ */
1810
2883
  async endPage(size, offset) {
1811
2884
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1812
2885
  }
2886
+ /**
2887
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
2888
+ * @returns Whether or not there will be additional results in the next page of results.
2889
+ */
1813
2890
  hasNextPage() {
1814
2891
  return this.meta.page.more;
1815
2892
  }
1816
2893
  }
1817
2894
  _query = new WeakMap();
1818
- const PAGINATION_MAX_SIZE = 200;
2895
+ const PAGINATION_MAX_SIZE = 1e3;
1819
2896
  const PAGINATION_DEFAULT_SIZE = 20;
1820
- const PAGINATION_MAX_OFFSET = 800;
2897
+ const PAGINATION_MAX_OFFSET = 49e3;
1821
2898
  const PAGINATION_DEFAULT_OFFSET = 0;
1822
2899
  function isCursorPaginationOptions(options) {
1823
2900
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1824
2901
  }
1825
- const _RecordArray = class extends Array {
2902
+ const _RecordArray = class _RecordArray extends Array {
1826
2903
  constructor(...args) {
1827
2904
  super(..._RecordArray.parseConstructorParams(...args));
1828
2905
  __privateAdd$6(this, _page, void 0);
@@ -1841,31 +2918,60 @@ const _RecordArray = class extends Array {
1841
2918
  toArray() {
1842
2919
  return new Array(...this);
1843
2920
  }
2921
+ toSerializable() {
2922
+ return JSON.parse(this.toString());
2923
+ }
2924
+ toString() {
2925
+ return JSON.stringify(this.toArray());
2926
+ }
1844
2927
  map(callbackfn, thisArg) {
1845
2928
  return this.toArray().map(callbackfn, thisArg);
1846
2929
  }
2930
+ /**
2931
+ * Retrieve next page of records
2932
+ *
2933
+ * @returns A new array of objects
2934
+ */
1847
2935
  async nextPage(size, offset) {
1848
2936
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1849
2937
  return new _RecordArray(newPage);
1850
2938
  }
2939
+ /**
2940
+ * Retrieve previous page of records
2941
+ *
2942
+ * @returns A new array of objects
2943
+ */
1851
2944
  async previousPage(size, offset) {
1852
2945
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1853
2946
  return new _RecordArray(newPage);
1854
2947
  }
2948
+ /**
2949
+ * Retrieve start page of records
2950
+ *
2951
+ * @returns A new array of objects
2952
+ */
1855
2953
  async startPage(size, offset) {
1856
2954
  const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1857
2955
  return new _RecordArray(newPage);
1858
2956
  }
2957
+ /**
2958
+ * Retrieve end page of records
2959
+ *
2960
+ * @returns A new array of objects
2961
+ */
1859
2962
  async endPage(size, offset) {
1860
2963
  const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1861
2964
  return new _RecordArray(newPage);
1862
2965
  }
2966
+ /**
2967
+ * @returns Boolean indicating if there is a next page
2968
+ */
1863
2969
  hasNextPage() {
1864
2970
  return __privateGet$6(this, _page).meta.page.more;
1865
2971
  }
1866
2972
  };
1867
- let RecordArray = _RecordArray;
1868
2973
  _page = new WeakMap();
2974
+ let RecordArray = _RecordArray;
1869
2975
 
1870
2976
  var __accessCheck$5 = (obj, member, msg) => {
1871
2977
  if (!member.has(obj))
@@ -1890,13 +2996,14 @@ var __privateMethod$3 = (obj, member, method) => {
1890
2996
  return method;
1891
2997
  };
1892
2998
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
1893
- const _Query = class {
2999
+ const _Query = class _Query {
1894
3000
  constructor(repository, table, data, rawParent) {
1895
3001
  __privateAdd$5(this, _cleanFilterConstraint);
1896
3002
  __privateAdd$5(this, _table$1, void 0);
1897
3003
  __privateAdd$5(this, _repository, void 0);
1898
3004
  __privateAdd$5(this, _data, { filter: {} });
1899
- this.meta = { page: { cursor: "start", more: true } };
3005
+ // Implements pagination
3006
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
1900
3007
  this.records = new RecordArray(this, []);
1901
3008
  __privateSet$5(this, _table$1, table);
1902
3009
  if (repository) {
@@ -1912,6 +3019,7 @@ const _Query = class {
1912
3019
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1913
3020
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1914
3021
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
3022
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
1915
3023
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1916
3024
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
1917
3025
  __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
@@ -1932,18 +3040,38 @@ const _Query = class {
1932
3040
  const key = JSON.stringify({ columns, filter, sort, pagination });
1933
3041
  return toBase64(key);
1934
3042
  }
3043
+ /**
3044
+ * Builds a new query object representing a logical OR between the given subqueries.
3045
+ * @param queries An array of subqueries.
3046
+ * @returns A new Query object.
3047
+ */
1935
3048
  any(...queries) {
1936
3049
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1937
3050
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
1938
3051
  }
3052
+ /**
3053
+ * Builds a new query object representing a logical AND between the given subqueries.
3054
+ * @param queries An array of subqueries.
3055
+ * @returns A new Query object.
3056
+ */
1939
3057
  all(...queries) {
1940
3058
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1941
3059
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1942
3060
  }
3061
+ /**
3062
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3063
+ * @param queries An array of subqueries.
3064
+ * @returns A new Query object.
3065
+ */
1943
3066
  not(...queries) {
1944
3067
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1945
3068
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
1946
3069
  }
3070
+ /**
3071
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3072
+ * @param queries An array of subqueries.
3073
+ * @returns A new Query object.
3074
+ */
1947
3075
  none(...queries) {
1948
3076
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1949
3077
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
@@ -1966,6 +3094,11 @@ const _Query = class {
1966
3094
  const sort = [...originalSort, { column, direction }];
1967
3095
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1968
3096
  }
3097
+ /**
3098
+ * Builds a new query specifying the set of columns to be returned in the query response.
3099
+ * @param columns Array of column names to be returned by the query.
3100
+ * @returns A new Query object.
3101
+ */
1969
3102
  select(columns) {
1970
3103
  return new _Query(
1971
3104
  __privateGet$5(this, _repository),
@@ -1978,6 +3111,12 @@ const _Query = class {
1978
3111
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1979
3112
  return __privateGet$5(this, _repository).query(query);
1980
3113
  }
3114
+ /**
3115
+ * Get results in an iterator
3116
+ *
3117
+ * @async
3118
+ * @returns Async interable of results
3119
+ */
1981
3120
  async *[Symbol.asyncIterator]() {
1982
3121
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
1983
3122
  yield record;
@@ -2038,26 +3177,53 @@ const _Query = class {
2038
3177
  );
2039
3178
  return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2040
3179
  }
3180
+ /**
3181
+ * Builds a new query object adding a cache TTL in milliseconds.
3182
+ * @param ttl The cache TTL in milliseconds.
3183
+ * @returns A new Query object.
3184
+ */
2041
3185
  cache(ttl) {
2042
3186
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2043
3187
  }
3188
+ /**
3189
+ * Retrieve next page of records
3190
+ *
3191
+ * @returns A new page object.
3192
+ */
2044
3193
  nextPage(size, offset) {
2045
3194
  return this.startPage(size, offset);
2046
3195
  }
3196
+ /**
3197
+ * Retrieve previous page of records
3198
+ *
3199
+ * @returns A new page object
3200
+ */
2047
3201
  previousPage(size, offset) {
2048
3202
  return this.startPage(size, offset);
2049
3203
  }
3204
+ /**
3205
+ * Retrieve start page of records
3206
+ *
3207
+ * @returns A new page object
3208
+ */
2050
3209
  startPage(size, offset) {
2051
3210
  return this.getPaginated({ pagination: { size, offset } });
2052
3211
  }
3212
+ /**
3213
+ * Retrieve last page of records
3214
+ *
3215
+ * @returns A new page object
3216
+ */
2053
3217
  endPage(size, offset) {
2054
3218
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2055
3219
  }
3220
+ /**
3221
+ * @returns Boolean indicating if there is a next page
3222
+ */
2056
3223
  hasNextPage() {
2057
3224
  return this.meta.page.more;
2058
3225
  }
2059
3226
  };
2060
- let Query = _Query;
2061
3227
  _table$1 = new WeakMap();
2062
3228
  _repository = new WeakMap();
2063
3229
  _data = new WeakMap();
@@ -2072,6 +3238,7 @@ cleanFilterConstraint_fn = function(column, value) {
2072
3238
  }
2073
3239
  return value;
2074
3240
  };
3241
+ let Query = _Query;
2075
3242
  function cleanParent(data, parent) {
2076
3243
  if (isCursorPaginationOptions(data.pagination)) {
2077
3244
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2079,6 +3246,22 @@ function cleanParent(data, parent) {
2079
3246
  return parent;
2080
3247
  }
2081
3248
 
3249
+ const RecordColumnTypes = [
3250
+ "bool",
3251
+ "int",
3252
+ "float",
3253
+ "string",
3254
+ "text",
3255
+ "email",
3256
+ "multiple",
3257
+ "link",
3258
+ "object",
3259
+ "datetime",
3260
+ "vector",
3261
+ "file[]",
3262
+ "file",
3263
+ "json"
3264
+ ];
2082
3265
  function isIdentifiable(x) {
2083
3266
  return isObject(x) && isString(x?.id);
2084
3267
  }
@@ -2088,11 +3271,33 @@ function isXataRecord(x) {
2088
3271
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
2089
3272
  }
2090
3273
 
3274
+ function isValidExpandedColumn(column) {
3275
+ return isObject(column) && isString(column.name);
3276
+ }
3277
+ function isValidSelectableColumns(columns) {
3278
+ if (!Array.isArray(columns)) {
3279
+ return false;
3280
+ }
3281
+ return columns.every((column) => {
3282
+ if (typeof column === "string") {
3283
+ return true;
3284
+ }
3285
+ if (typeof column === "object") {
3286
+ return isValidExpandedColumn(column);
3287
+ }
3288
+ return false;
3289
+ });
3290
+ }
3291
+
2091
3292
  function isSortFilterString(value) {
2092
3293
  return isString(value);
2093
3294
  }
2094
3295
  function isSortFilterBase(filter) {
2095
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
3296
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
3297
+ if (key === "*")
3298
+ return value === "random";
3299
+ return value === "asc" || value === "desc";
3300
+ });
2096
3301
  }
2097
3302
  function isSortFilterObject(filter) {
2098
3303
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -2133,7 +3338,8 @@ var __privateMethod$2 = (obj, member, method) => {
2133
3338
  __accessCheck$4(obj, member, "access private method");
2134
3339
  return method;
2135
3340
  };
2136
- var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
3341
+ 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;
3342
+ const BULK_OPERATION_MAX_SIZE = 1e3;
2137
3343
  class Repository extends Query {
2138
3344
  }
2139
3345
  class RestRepository extends Query {
@@ -2145,13 +3351,16 @@ class RestRepository extends Query {
2145
3351
  );
2146
3352
  __privateAdd$4(this, _insertRecordWithoutId);
2147
3353
  __privateAdd$4(this, _insertRecordWithId);
2148
- __privateAdd$4(this, _bulkInsertTableRecords);
3354
+ __privateAdd$4(this, _insertRecords);
2149
3355
  __privateAdd$4(this, _updateRecordWithID);
3356
+ __privateAdd$4(this, _updateRecords);
2150
3357
  __privateAdd$4(this, _upsertRecordWithID);
2151
3358
  __privateAdd$4(this, _deleteRecord);
3359
+ __privateAdd$4(this, _deleteRecords);
2152
3360
  __privateAdd$4(this, _setCacheQuery);
2153
3361
  __privateAdd$4(this, _getCacheQuery);
2154
3362
  __privateAdd$4(this, _getSchemaTables$1);
3363
+ __privateAdd$4(this, _transformObjectToApi);
2155
3364
  __privateAdd$4(this, _table, void 0);
2156
3365
  __privateAdd$4(this, _getFetchProps, void 0);
2157
3366
  __privateAdd$4(this, _db, void 0);
@@ -2162,10 +3371,7 @@ class RestRepository extends Query {
2162
3371
  __privateSet$4(this, _db, options.db);
2163
3372
  __privateSet$4(this, _cache, options.pluginOptions.cache);
2164
3373
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2165
- __privateSet$4(this, _getFetchProps, async () => {
2166
- const props = await options.pluginOptions.getFetchProps();
2167
- return { ...props, sessionID: generateUUID() };
2168
- });
3374
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2169
3375
  const trace = options.pluginOptions.trace ?? defaultTrace;
2170
3376
  __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2171
3377
  return trace(name, fn, {
@@ -2182,23 +3388,25 @@ class RestRepository extends Query {
2182
3388
  if (Array.isArray(a)) {
2183
3389
  if (a.length === 0)
2184
3390
  return [];
2185
- const columns = isStringArray(b) ? b : void 0;
2186
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
3391
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
3392
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3393
+ const result = await this.read(ids, columns);
3394
+ return result;
2187
3395
  }
2188
3396
  if (isString(a) && isObject(b)) {
2189
3397
  if (a === "")
2190
3398
  throw new Error("The id can't be empty");
2191
- const columns = isStringArray(c) ? c : void 0;
2192
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
3399
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3400
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2193
3401
  }
2194
3402
  if (isObject(a) && isString(a.id)) {
2195
3403
  if (a.id === "")
2196
3404
  throw new Error("The id can't be empty");
2197
- const columns = isStringArray(b) ? b : void 0;
2198
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
3405
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3406
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2199
3407
  }
2200
3408
  if (isObject(a)) {
2201
- const columns = isStringArray(b) ? b : void 0;
3409
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2202
3410
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2203
3411
  }
2204
3412
  throw new Error("Invalid arguments for create method");
@@ -2206,7 +3414,7 @@ class RestRepository extends Query {
2206
3414
  }
2207
3415
  async read(a, b) {
2208
3416
  return __privateGet$4(this, _trace).call(this, "read", async () => {
2209
- const columns = isStringArray(b) ? b : ["*"];
3417
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2210
3418
  if (Array.isArray(a)) {
2211
3419
  if (a.length === 0)
2212
3420
  return [];
@@ -2220,7 +3428,6 @@ class RestRepository extends Query {
2220
3428
  }
2221
3429
  const id = extractId(a);
2222
3430
  if (id) {
2223
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2224
3431
  try {
2225
3432
  const response = await getRecord({
2226
3433
  pathParams: {
@@ -2231,10 +3438,16 @@ class RestRepository extends Query {
2231
3438
  recordId: id
2232
3439
  },
2233
3440
  queryParams: { columns },
2234
- ...fetchProps
3441
+ ...__privateGet$4(this, _getFetchProps).call(this)
2235
3442
  });
2236
3443
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2237
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3444
+ return initObject(
3445
+ __privateGet$4(this, _db),
3446
+ schemaTables,
3447
+ __privateGet$4(this, _table),
3448
+ response,
3449
+ columns
3450
+ );
2238
3451
  } catch (e) {
2239
3452
  if (isObject(e) && e.status === 404) {
2240
3453
  return null;
@@ -2270,19 +3483,29 @@ class RestRepository extends Query {
2270
3483
  if (Array.isArray(a)) {
2271
3484
  if (a.length === 0)
2272
3485
  return [];
2273
- if (a.length > 100) {
2274
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2275
- }
2276
- const columns = isStringArray(b) ? b : ["*"];
2277
- return Promise.all(a.map((object) => this.update(object, columns)));
2278
- }
2279
- if (isString(a) && isObject(b)) {
2280
- const columns = isStringArray(c) ? c : void 0;
2281
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3486
+ const existing = await this.read(a, ["id"]);
3487
+ const updates = a.filter((_item, index) => existing[index] !== null);
3488
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
3489
+ ifVersion,
3490
+ upsert: false
3491
+ });
3492
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3493
+ const result = await this.read(a, columns);
3494
+ return result;
2282
3495
  }
2283
- if (isObject(a) && isString(a.id)) {
2284
- const columns = isStringArray(b) ? b : void 0;
2285
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3496
+ try {
3497
+ if (isString(a) && isObject(b)) {
3498
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3499
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3500
+ }
3501
+ if (isObject(a) && isString(a.id)) {
3502
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3503
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3504
+ }
3505
+ } catch (error) {
3506
+ if (error.status === 422)
3507
+ return null;
3508
+ throw error;
2286
3509
  }
2287
3510
  throw new Error("Invalid arguments for update method");
2288
3511
  });
@@ -2312,19 +3535,31 @@ class RestRepository extends Query {
2312
3535
  if (Array.isArray(a)) {
2313
3536
  if (a.length === 0)
2314
3537
  return [];
2315
- if (a.length > 100) {
2316
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2317
- }
2318
- const columns = isStringArray(b) ? b : ["*"];
2319
- return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
3538
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
3539
+ ifVersion,
3540
+ upsert: true
3541
+ });
3542
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3543
+ const result = await this.read(a, columns);
3544
+ return result;
2320
3545
  }
2321
3546
  if (isString(a) && isObject(b)) {
2322
- const columns = isStringArray(c) ? c : void 0;
2323
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3547
+ if (a === "")
3548
+ throw new Error("The id can't be empty");
3549
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3550
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2324
3551
  }
2325
3552
  if (isObject(a) && isString(a.id)) {
2326
- const columns = isStringArray(c) ? c : void 0;
2327
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3553
+ if (a.id === "")
3554
+ throw new Error("The id can't be empty");
3555
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3556
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3557
+ }
3558
+ if (!isDefined(a) && isObject(b)) {
3559
+ return await this.create(b, c);
3560
+ }
3561
+ if (isObject(a) && !isDefined(a.id)) {
3562
+ return await this.create(a, b);
2328
3563
  }
2329
3564
  throw new Error("Invalid arguments for createOrUpdate method");
2330
3565
  });
@@ -2335,16 +3570,28 @@ class RestRepository extends Query {
2335
3570
  if (Array.isArray(a)) {
2336
3571
  if (a.length === 0)
2337
3572
  return [];
2338
- const columns = isStringArray(b) ? b : ["*"];
2339
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
3573
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
3574
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3575
+ const result = await this.read(ids, columns);
3576
+ return result;
2340
3577
  }
2341
3578
  if (isString(a) && isObject(b)) {
2342
- const columns = isStringArray(c) ? c : void 0;
2343
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3579
+ if (a === "")
3580
+ throw new Error("The id can't be empty");
3581
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3582
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2344
3583
  }
2345
3584
  if (isObject(a) && isString(a.id)) {
2346
- const columns = isStringArray(c) ? c : void 0;
2347
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3585
+ if (a.id === "")
3586
+ throw new Error("The id can't be empty");
3587
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3588
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3589
+ }
3590
+ if (!isDefined(a) && isObject(b)) {
3591
+ return await this.create(b, c);
3592
+ }
3593
+ if (isObject(a) && !isDefined(a.id)) {
3594
+ return await this.create(a, b);
2348
3595
  }
2349
3596
  throw new Error("Invalid arguments for createOrReplace method");
2350
3597
  });
@@ -2354,10 +3601,17 @@ class RestRepository extends Query {
2354
3601
  if (Array.isArray(a)) {
2355
3602
  if (a.length === 0)
2356
3603
  return [];
2357
- if (a.length > 100) {
2358
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
2359
- }
2360
- return Promise.all(a.map((id) => this.delete(id, b)));
3604
+ const ids = a.map((o) => {
3605
+ if (isString(o))
3606
+ return o;
3607
+ if (isString(o.id))
3608
+ return o.id;
3609
+ throw new Error("Invalid arguments for delete method");
3610
+ });
3611
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3612
+ const result = await this.read(a, columns);
3613
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
3614
+ return result;
2361
3615
  }
2362
3616
  if (isString(a)) {
2363
3617
  return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
@@ -2388,8 +3642,7 @@ class RestRepository extends Query {
2388
3642
  }
2389
3643
  async search(query, options = {}) {
2390
3644
  return __privateGet$4(this, _trace).call(this, "search", async () => {
2391
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2392
- const { records } = await searchTable({
3645
+ const { records, totalCount } = await searchTable({
2393
3646
  pathParams: {
2394
3647
  workspace: "{workspaceId}",
2395
3648
  dbBranchName: "{dbBranch}",
@@ -2402,17 +3655,46 @@ class RestRepository extends Query {
2402
3655
  prefix: options.prefix,
2403
3656
  highlight: options.highlight,
2404
3657
  filter: options.filter,
2405
- boosters: options.boosters
3658
+ boosters: options.boosters,
3659
+ page: options.page,
3660
+ target: options.target
3661
+ },
3662
+ ...__privateGet$4(this, _getFetchProps).call(this)
3663
+ });
3664
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3665
+ return {
3666
+ records: records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"])),
3667
+ totalCount
3668
+ };
3669
+ });
3670
+ }
3671
+ async vectorSearch(column, query, options) {
3672
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3673
+ const { records, totalCount } = await vectorSearchTable({
3674
+ pathParams: {
3675
+ workspace: "{workspaceId}",
3676
+ dbBranchName: "{dbBranch}",
3677
+ region: "{region}",
3678
+ tableName: __privateGet$4(this, _table)
2406
3679
  },
2407
- ...fetchProps
3680
+ body: {
3681
+ column,
3682
+ queryVector: query,
3683
+ similarityFunction: options?.similarityFunction,
3684
+ size: options?.size,
3685
+ filter: options?.filter
3686
+ },
3687
+ ...__privateGet$4(this, _getFetchProps).call(this)
2408
3688
  });
2409
3689
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2410
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3690
+ return {
3691
+ records: records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"])),
3692
+ totalCount
3693
+ };
2411
3694
  });
2412
3695
  }
2413
3696
  async aggregate(aggs, filter) {
2414
3697
  return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2415
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2416
3698
  const result = await aggregateTable({
2417
3699
  pathParams: {
2418
3700
  workspace: "{workspaceId}",
@@ -2421,7 +3703,7 @@ class RestRepository extends Query {
2421
3703
  tableName: __privateGet$4(this, _table)
2422
3704
  },
2423
3705
  body: { aggs, filter },
2424
- ...fetchProps
3706
+ ...__privateGet$4(this, _getFetchProps).call(this)
2425
3707
  });
2426
3708
  return result;
2427
3709
  });
@@ -2432,7 +3714,6 @@ class RestRepository extends Query {
2432
3714
  if (cacheQuery)
2433
3715
  return new Page(query, cacheQuery.meta, cacheQuery.records);
2434
3716
  const data = query.getQueryOptions();
2435
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2436
3717
  const { meta, records: objects } = await queryTable({
2437
3718
  pathParams: {
2438
3719
  workspace: "{workspaceId}",
@@ -2444,14 +3725,21 @@ class RestRepository extends Query {
2444
3725
  filter: cleanFilter(data.filter),
2445
3726
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2446
3727
  page: data.pagination,
2447
- columns: data.columns ?? ["*"]
3728
+ columns: data.columns ?? ["*"],
3729
+ consistency: data.consistency
2448
3730
  },
2449
3731
  fetchOptions: data.fetchOptions,
2450
- ...fetchProps
3732
+ ...__privateGet$4(this, _getFetchProps).call(this)
2451
3733
  });
2452
3734
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2453
3735
  const records = objects.map(
2454
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3736
+ (record) => initObject(
3737
+ __privateGet$4(this, _db),
3738
+ schemaTables,
3739
+ __privateGet$4(this, _table),
3740
+ record,
3741
+ data.columns ?? ["*"]
3742
+ )
2455
3743
  );
2456
3744
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
2457
3745
  return new Page(query, meta, records);
@@ -2460,7 +3748,6 @@ class RestRepository extends Query {
2460
3748
  async summarizeTable(query, summaries, summariesFilter) {
2461
3749
  return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2462
3750
  const data = query.getQueryOptions();
2463
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2464
3751
  const result = await summarizeTable({
2465
3752
  pathParams: {
2466
3753
  workspace: "{workspaceId}",
@@ -2472,15 +3759,55 @@ class RestRepository extends Query {
2472
3759
  filter: cleanFilter(data.filter),
2473
3760
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2474
3761
  columns: data.columns,
3762
+ consistency: data.consistency,
2475
3763
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2476
3764
  summaries,
2477
3765
  summariesFilter
2478
3766
  },
2479
- ...fetchProps
3767
+ ...__privateGet$4(this, _getFetchProps).call(this)
2480
3768
  });
2481
- return result;
3769
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3770
+ return {
3771
+ ...result,
3772
+ summaries: result.summaries.map(
3773
+ (summary) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), summary, data.columns ?? [])
3774
+ )
3775
+ };
2482
3776
  });
2483
3777
  }
3778
+ ask(question, options) {
3779
+ const questionParam = options?.sessionId ? { message: question } : { question };
3780
+ const params = {
3781
+ pathParams: {
3782
+ workspace: "{workspaceId}",
3783
+ dbBranchName: "{dbBranch}",
3784
+ region: "{region}",
3785
+ tableName: __privateGet$4(this, _table),
3786
+ sessionId: options?.sessionId
3787
+ },
3788
+ body: {
3789
+ ...questionParam,
3790
+ rules: options?.rules,
3791
+ searchType: options?.searchType,
3792
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3793
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3794
+ },
3795
+ ...__privateGet$4(this, _getFetchProps).call(this)
3796
+ };
3797
+ if (options?.onMessage) {
3798
+ fetchSSERequest({
3799
+ endpoint: "dataPlane",
3800
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3801
+ method: "POST",
3802
+ onMessage: (message) => {
3803
+ options.onMessage?.({ answer: message.text, records: message.records });
3804
+ },
3805
+ ...params
3806
+ });
3807
+ } else {
3808
+ return askTableSession(params);
3809
+ }
3810
+ }
2484
3811
  }
2485
3812
  _table = new WeakMap();
2486
3813
  _getFetchProps = new WeakMap();
@@ -2490,8 +3817,7 @@ _schemaTables$2 = new WeakMap();
2490
3817
  _trace = new WeakMap();
2491
3818
  _insertRecordWithoutId = new WeakSet();
2492
3819
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2493
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2494
- const record = transformObjectLinks(object);
3820
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2495
3821
  const response = await insertRecord({
2496
3822
  pathParams: {
2497
3823
  workspace: "{workspaceId}",
@@ -2501,15 +3827,16 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2501
3827
  },
2502
3828
  queryParams: { columns },
2503
3829
  body: record,
2504
- ...fetchProps
3830
+ ...__privateGet$4(this, _getFetchProps).call(this)
2505
3831
  });
2506
3832
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2507
3833
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2508
3834
  };
2509
3835
  _insertRecordWithId = new WeakSet();
2510
3836
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2511
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2512
- const record = transformObjectLinks(object);
3837
+ if (!recordId)
3838
+ return null;
3839
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2513
3840
  const response = await insertRecordWithID({
2514
3841
  pathParams: {
2515
3842
  workspace: "{workspaceId}",
@@ -2520,36 +3847,44 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2520
3847
  },
2521
3848
  body: record,
2522
3849
  queryParams: { createOnly, columns, ifVersion },
2523
- ...fetchProps
3850
+ ...__privateGet$4(this, _getFetchProps).call(this)
2524
3851
  });
2525
3852
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2526
3853
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2527
3854
  };
2528
- _bulkInsertTableRecords = new WeakSet();
2529
- bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
2530
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2531
- const records = objects.map((object) => transformObjectLinks(object));
2532
- const response = await bulkInsertTableRecords({
2533
- pathParams: {
2534
- workspace: "{workspaceId}",
2535
- dbBranchName: "{dbBranch}",
2536
- region: "{region}",
2537
- tableName: __privateGet$4(this, _table)
2538
- },
2539
- queryParams: { columns },
2540
- body: { records },
2541
- ...fetchProps
3855
+ _insertRecords = new WeakSet();
3856
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
3857
+ const operations = await promiseMap(objects, async (object) => {
3858
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3859
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
2542
3860
  });
2543
- if (!isResponseWithRecords(response)) {
2544
- throw new Error("Request included columns but server didn't include them");
3861
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
3862
+ const ids = [];
3863
+ for (const operations2 of chunkedOperations) {
3864
+ const { results } = await branchTransaction({
3865
+ pathParams: {
3866
+ workspace: "{workspaceId}",
3867
+ dbBranchName: "{dbBranch}",
3868
+ region: "{region}"
3869
+ },
3870
+ body: { operations: operations2 },
3871
+ ...__privateGet$4(this, _getFetchProps).call(this)
3872
+ });
3873
+ for (const result of results) {
3874
+ if (result.operation === "insert") {
3875
+ ids.push(result.id);
3876
+ } else {
3877
+ ids.push(null);
3878
+ }
3879
+ }
2545
3880
  }
2546
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2547
- return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
3881
+ return ids;
2548
3882
  };
2549
3883
  _updateRecordWithID = new WeakSet();
2550
3884
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2551
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2552
- const record = transformObjectLinks(object);
3885
+ if (!recordId)
3886
+ return null;
3887
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2553
3888
  try {
2554
3889
  const response = await updateRecordWithID({
2555
3890
  pathParams: {
@@ -2561,7 +3896,7 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2561
3896
  },
2562
3897
  queryParams: { columns, ifVersion },
2563
3898
  body: record,
2564
- ...fetchProps
3899
+ ...__privateGet$4(this, _getFetchProps).call(this)
2565
3900
  });
2566
3901
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2567
3902
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2572,9 +3907,38 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2572
3907
  throw e;
2573
3908
  }
2574
3909
  };
3910
+ _updateRecords = new WeakSet();
3911
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
3912
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
3913
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3914
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
3915
+ });
3916
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
3917
+ const ids = [];
3918
+ for (const operations2 of chunkedOperations) {
3919
+ const { results } = await branchTransaction({
3920
+ pathParams: {
3921
+ workspace: "{workspaceId}",
3922
+ dbBranchName: "{dbBranch}",
3923
+ region: "{region}"
3924
+ },
3925
+ body: { operations: operations2 },
3926
+ ...__privateGet$4(this, _getFetchProps).call(this)
3927
+ });
3928
+ for (const result of results) {
3929
+ if (result.operation === "update") {
3930
+ ids.push(result.id);
3931
+ } else {
3932
+ ids.push(null);
3933
+ }
3934
+ }
3935
+ }
3936
+ return ids;
3937
+ };
2575
3938
  _upsertRecordWithID = new WeakSet();
2576
3939
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2577
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3940
+ if (!recordId)
3941
+ return null;
2578
3942
  const response = await upsertRecordWithID({
2579
3943
  pathParams: {
2580
3944
  workspace: "{workspaceId}",
@@ -2585,14 +3949,15 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2585
3949
  },
2586
3950
  queryParams: { columns, ifVersion },
2587
3951
  body: object,
2588
- ...fetchProps
3952
+ ...__privateGet$4(this, _getFetchProps).call(this)
2589
3953
  });
2590
3954
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2591
3955
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2592
3956
  };
2593
3957
  _deleteRecord = new WeakSet();
2594
3958
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
2595
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3959
+ if (!recordId)
3960
+ return null;
2596
3961
  try {
2597
3962
  const response = await deleteRecord({
2598
3963
  pathParams: {
@@ -2603,7 +3968,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2603
3968
  recordId
2604
3969
  },
2605
3970
  queryParams: { columns },
2606
- ...fetchProps
3971
+ ...__privateGet$4(this, _getFetchProps).call(this)
2607
3972
  });
2608
3973
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2609
3974
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2614,17 +3979,36 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2614
3979
  throw e;
2615
3980
  }
2616
3981
  };
3982
+ _deleteRecords = new WeakSet();
3983
+ deleteRecords_fn = async function(recordIds) {
3984
+ const chunkedOperations = chunk(
3985
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
3986
+ BULK_OPERATION_MAX_SIZE
3987
+ );
3988
+ for (const operations of chunkedOperations) {
3989
+ await branchTransaction({
3990
+ pathParams: {
3991
+ workspace: "{workspaceId}",
3992
+ dbBranchName: "{dbBranch}",
3993
+ region: "{region}"
3994
+ },
3995
+ body: { operations },
3996
+ ...__privateGet$4(this, _getFetchProps).call(this)
3997
+ });
3998
+ }
3999
+ };
2617
4000
  _setCacheQuery = new WeakSet();
2618
4001
  setCacheQuery_fn = async function(query, meta, records) {
2619
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
4002
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
2620
4003
  };
2621
4004
  _getCacheQuery = new WeakSet();
2622
4005
  getCacheQuery_fn = async function(query) {
2623
4006
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2624
- const result = await __privateGet$4(this, _cache).get(key);
4007
+ const result = await __privateGet$4(this, _cache)?.get(key);
2625
4008
  if (!result)
2626
4009
  return null;
2627
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
4010
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
4011
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2628
4012
  if (ttl < 0)
2629
4013
  return null;
2630
4014
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2634,39 +4018,66 @@ _getSchemaTables$1 = new WeakSet();
2634
4018
  getSchemaTables_fn$1 = async function() {
2635
4019
  if (__privateGet$4(this, _schemaTables$2))
2636
4020
  return __privateGet$4(this, _schemaTables$2);
2637
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2638
4021
  const { schema } = await getBranchDetails({
2639
4022
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2640
- ...fetchProps
4023
+ ...__privateGet$4(this, _getFetchProps).call(this)
2641
4024
  });
2642
4025
  __privateSet$4(this, _schemaTables$2, schema.tables);
2643
4026
  return schema.tables;
2644
4027
  };
2645
- const transformObjectLinks = (object) => {
2646
- return Object.entries(object).reduce((acc, [key, value]) => {
4028
+ _transformObjectToApi = new WeakSet();
4029
+ transformObjectToApi_fn = async function(object) {
4030
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4031
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
4032
+ if (!schema)
4033
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
4034
+ const result = {};
4035
+ for (const [key, value] of Object.entries(object)) {
2647
4036
  if (key === "xata")
2648
- return acc;
2649
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
2650
- }, {});
4037
+ continue;
4038
+ const type = schema.columns.find((column) => column.name === key)?.type;
4039
+ switch (type) {
4040
+ case "link": {
4041
+ result[key] = isIdentifiable(value) ? value.id : value;
4042
+ break;
4043
+ }
4044
+ case "datetime": {
4045
+ result[key] = value instanceof Date ? value.toISOString() : value;
4046
+ break;
4047
+ }
4048
+ case `file`:
4049
+ result[key] = await parseInputFileEntry(value);
4050
+ break;
4051
+ case "file[]":
4052
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4053
+ break;
4054
+ case "json":
4055
+ result[key] = stringifyJson(value);
4056
+ break;
4057
+ default:
4058
+ result[key] = value;
4059
+ }
4060
+ }
4061
+ return result;
2651
4062
  };
2652
4063
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2653
- const result = {};
4064
+ const data = {};
2654
4065
  const { xata, ...rest } = object ?? {};
2655
- Object.assign(result, rest);
4066
+ Object.assign(data, rest);
2656
4067
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2657
4068
  if (!columns)
2658
4069
  console.error(`Table ${table} not found in schema`);
2659
4070
  for (const column of columns ?? []) {
2660
4071
  if (!isValidColumn(selectedColumns, column))
2661
4072
  continue;
2662
- const value = result[column.name];
4073
+ const value = data[column.name];
2663
4074
  switch (column.type) {
2664
4075
  case "datetime": {
2665
- const date = value !== void 0 ? new Date(value) : void 0;
2666
- if (date && isNaN(date.getTime())) {
4076
+ const date = value !== void 0 ? new Date(value) : null;
4077
+ if (date !== null && isNaN(date.getTime())) {
2667
4078
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2668
- } else if (date) {
2669
- result[column.name] = date;
4079
+ } else {
4080
+ data[column.name] = date;
2670
4081
  }
2671
4082
  break;
2672
4083
  }
@@ -2679,54 +4090,77 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2679
4090
  if (item === column.name) {
2680
4091
  return [...acc, "*"];
2681
4092
  }
2682
- if (item.startsWith(`${column.name}.`)) {
4093
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
2683
4094
  const [, ...path] = item.split(".");
2684
4095
  return [...acc, path.join(".")];
2685
4096
  }
2686
4097
  return acc;
2687
4098
  }, []);
2688
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4099
+ data[column.name] = initObject(
4100
+ db,
4101
+ schemaTables,
4102
+ linkTable,
4103
+ value,
4104
+ selectedLinkColumns
4105
+ );
2689
4106
  } else {
2690
- result[column.name] = null;
4107
+ data[column.name] = null;
2691
4108
  }
2692
4109
  break;
2693
4110
  }
4111
+ case "file":
4112
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4113
+ break;
4114
+ case "file[]":
4115
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4116
+ break;
4117
+ case "json":
4118
+ data[column.name] = parseJson(value);
4119
+ break;
2694
4120
  default:
2695
- result[column.name] = value ?? null;
4121
+ data[column.name] = value ?? null;
2696
4122
  if (column.notNull === true && value === null) {
2697
4123
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2698
4124
  }
2699
4125
  break;
2700
4126
  }
2701
4127
  }
2702
- result.read = function(columns2) {
2703
- return db[table].read(result["id"], columns2);
4128
+ const record = { ...data };
4129
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
4130
+ record.read = function(columns2) {
4131
+ return db[table].read(record["id"], columns2);
2704
4132
  };
2705
- result.update = function(data, b, c) {
2706
- const columns2 = isStringArray(b) ? b : ["*"];
4133
+ record.update = function(data2, b, c) {
4134
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2707
4135
  const ifVersion = parseIfVersion(b, c);
2708
- return db[table].update(result["id"], data, columns2, { ifVersion });
4136
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2709
4137
  };
2710
- result.replace = function(data, b, c) {
2711
- const columns2 = isStringArray(b) ? b : ["*"];
4138
+ record.replace = function(data2, b, c) {
4139
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2712
4140
  const ifVersion = parseIfVersion(b, c);
2713
- return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
4141
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
4142
+ };
4143
+ record.delete = function() {
4144
+ return db[table].delete(record["id"]);
4145
+ };
4146
+ if (metadata !== void 0) {
4147
+ record.xata = Object.freeze(metadata);
4148
+ }
4149
+ record.getMetadata = function() {
4150
+ return record.xata;
2714
4151
  };
2715
- result.delete = function() {
2716
- return db[table].delete(result["id"]);
4152
+ record.toSerializable = function() {
4153
+ return JSON.parse(JSON.stringify(record));
2717
4154
  };
2718
- result.getMetadata = function() {
2719
- return xata;
4155
+ record.toString = function() {
4156
+ return JSON.stringify(record);
2720
4157
  };
2721
- for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
2722
- Object.defineProperty(result, prop, { enumerable: false });
4158
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
4159
+ Object.defineProperty(record, prop, { enumerable: false });
2723
4160
  }
2724
- Object.freeze(result);
2725
- return result;
4161
+ Object.freeze(record);
4162
+ return record;
2726
4163
  };
2727
- function isResponseWithRecords(value) {
2728
- return isObject(value) && Array.isArray(value.records);
2729
- }
2730
4164
  function extractId(value) {
2731
4165
  if (isString(value))
2732
4166
  return value;
@@ -2737,11 +4171,7 @@ function extractId(value) {
2737
4171
  function isValidColumn(columns, column) {
2738
4172
  if (columns.includes("*"))
2739
4173
  return true;
2740
- if (column.type === "link") {
2741
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
2742
- return linkColumns.length > 0;
2743
- }
2744
- return columns.includes(column.name);
4174
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
2745
4175
  }
2746
4176
  function parseIfVersion(...args) {
2747
4177
  for (const arg of args) {
@@ -2818,10 +4248,12 @@ const notExists = (column) => ({ $notExists: column });
2818
4248
  const startsWith = (value) => ({ $startsWith: value });
2819
4249
  const endsWith = (value) => ({ $endsWith: value });
2820
4250
  const pattern = (value) => ({ $pattern: value });
4251
+ const iPattern = (value) => ({ $iPattern: value });
2821
4252
  const is = (value) => ({ $is: value });
2822
4253
  const equals = is;
2823
4254
  const isNot = (value) => ({ $isNot: value });
2824
4255
  const contains = (value) => ({ $contains: value });
4256
+ const iContains = (value) => ({ $iContains: value });
2825
4257
  const includes = (value) => ({ $includes: value });
2826
4258
  const includesAll = (value) => ({ $includesAll: value });
2827
4259
  const includesNone = (value) => ({ $includesNone: value });
@@ -2877,6 +4309,80 @@ class SchemaPlugin extends XataPlugin {
2877
4309
  _tables = new WeakMap();
2878
4310
  _schemaTables$1 = new WeakMap();
2879
4311
 
4312
+ class FilesPlugin extends XataPlugin {
4313
+ build(pluginOptions) {
4314
+ return {
4315
+ download: async (location) => {
4316
+ const { table, record, column, fileId = "" } = location ?? {};
4317
+ return await getFileItem({
4318
+ pathParams: {
4319
+ workspace: "{workspaceId}",
4320
+ dbBranchName: "{dbBranch}",
4321
+ region: "{region}",
4322
+ tableName: table ?? "",
4323
+ recordId: record ?? "",
4324
+ columnName: column ?? "",
4325
+ fileId
4326
+ },
4327
+ ...pluginOptions,
4328
+ rawResponse: true
4329
+ });
4330
+ },
4331
+ upload: async (location, file, options) => {
4332
+ const { table, record, column, fileId = "" } = location ?? {};
4333
+ const resolvedFile = await file;
4334
+ const contentType = options?.mediaType || getContentType(resolvedFile);
4335
+ const body = resolvedFile instanceof XataFile ? resolvedFile.toBlob() : resolvedFile;
4336
+ return await putFileItem({
4337
+ ...pluginOptions,
4338
+ pathParams: {
4339
+ workspace: "{workspaceId}",
4340
+ dbBranchName: "{dbBranch}",
4341
+ region: "{region}",
4342
+ tableName: table ?? "",
4343
+ recordId: record ?? "",
4344
+ columnName: column ?? "",
4345
+ fileId
4346
+ },
4347
+ body,
4348
+ headers: { "Content-Type": contentType }
4349
+ });
4350
+ },
4351
+ delete: async (location) => {
4352
+ const { table, record, column, fileId = "" } = location ?? {};
4353
+ return await deleteFileItem({
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
+ });
4365
+ }
4366
+ };
4367
+ }
4368
+ }
4369
+ function getContentType(file) {
4370
+ if (typeof file === "string") {
4371
+ return "text/plain";
4372
+ }
4373
+ if ("mediaType" in file) {
4374
+ return file.mediaType;
4375
+ }
4376
+ if (isBlob(file)) {
4377
+ return file.type;
4378
+ }
4379
+ try {
4380
+ return file.type;
4381
+ } catch (e) {
4382
+ }
4383
+ return "application/octet-stream";
4384
+ }
4385
+
2880
4386
  var __accessCheck$1 = (obj, member, msg) => {
2881
4387
  if (!member.has(obj))
2882
4388
  throw TypeError("Cannot " + msg);
@@ -2909,138 +4415,141 @@ class SearchPlugin extends XataPlugin {
2909
4415
  __privateAdd$1(this, _schemaTables, void 0);
2910
4416
  __privateSet$1(this, _schemaTables, schemaTables);
2911
4417
  }
2912
- build({ getFetchProps }) {
4418
+ build(pluginOptions) {
2913
4419
  return {
2914
4420
  all: async (query, options = {}) => {
2915
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2916
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
2917
- return records.map((record) => {
2918
- const { table = "orphan" } = record.xata;
2919
- return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
2920
- });
4421
+ const { records, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4422
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
4423
+ return {
4424
+ totalCount,
4425
+ records: records.map((record) => {
4426
+ const { table = "orphan" } = record.xata;
4427
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
4428
+ })
4429
+ };
2921
4430
  },
2922
4431
  byTable: async (query, options = {}) => {
2923
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2924
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
2925
- return records.reduce((acc, record) => {
4432
+ const { records: rawRecords, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4433
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
4434
+ const records = rawRecords.reduce((acc, record) => {
2926
4435
  const { table = "orphan" } = record.xata;
2927
4436
  const items = acc[table] ?? [];
2928
4437
  const item = initObject(this.db, schemaTables, table, record, ["*"]);
2929
4438
  return { ...acc, [table]: [...items, item] };
2930
4439
  }, {});
4440
+ return { totalCount, records };
2931
4441
  }
2932
4442
  };
2933
4443
  }
2934
4444
  }
2935
4445
  _schemaTables = new WeakMap();
2936
4446
  _search = new WeakSet();
2937
- search_fn = async function(query, options, getFetchProps) {
2938
- const fetchProps = await getFetchProps();
2939
- const { tables, fuzziness, highlight, prefix } = options ?? {};
2940
- const { records } = await searchBranch({
4447
+ search_fn = async function(query, options, pluginOptions) {
4448
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
4449
+ const { records, totalCount } = await searchBranch({
2941
4450
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2942
- body: { tables, query, fuzziness, prefix, highlight },
2943
- ...fetchProps
4451
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
4452
+ body: { tables, query, fuzziness, prefix, highlight, page },
4453
+ ...pluginOptions
2944
4454
  });
2945
- return records;
4455
+ return { records, totalCount };
2946
4456
  };
2947
4457
  _getSchemaTables = new WeakSet();
2948
- getSchemaTables_fn = async function(getFetchProps) {
4458
+ getSchemaTables_fn = async function(pluginOptions) {
2949
4459
  if (__privateGet$1(this, _schemaTables))
2950
4460
  return __privateGet$1(this, _schemaTables);
2951
- const fetchProps = await getFetchProps();
2952
4461
  const { schema } = await getBranchDetails({
2953
4462
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2954
- ...fetchProps
4463
+ ...pluginOptions
2955
4464
  });
2956
4465
  __privateSet$1(this, _schemaTables, schema.tables);
2957
4466
  return schema.tables;
2958
4467
  };
2959
4468
 
2960
- const isBranchStrategyBuilder = (strategy) => {
2961
- return typeof strategy === "function";
2962
- };
2963
-
2964
- async function getCurrentBranchName(options) {
2965
- const { branch, envBranch } = getEnvironment();
2966
- if (branch) {
2967
- const details = await getDatabaseBranch(branch, options);
2968
- if (details)
2969
- return branch;
2970
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2971
- }
2972
- const gitBranch = envBranch || await getGitBranch();
2973
- return resolveXataBranch(gitBranch, options);
2974
- }
2975
- async function getCurrentBranchDetails(options) {
2976
- const branch = await getCurrentBranchName(options);
2977
- return getDatabaseBranch(branch, options);
2978
- }
2979
- async function resolveXataBranch(gitBranch, options) {
2980
- const databaseURL = options?.databaseURL || getDatabaseURL();
2981
- const apiKey = options?.apiKey || getAPIKey();
2982
- if (!databaseURL)
2983
- throw new Error(
2984
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2985
- );
2986
- if (!apiKey)
2987
- throw new Error(
2988
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2989
- );
2990
- const [protocol, , host, , dbName] = databaseURL.split("/");
2991
- const urlParts = parseWorkspacesUrlParts(host);
2992
- if (!urlParts)
2993
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
2994
- const { workspace, region } = urlParts;
2995
- const { fallbackBranch } = getEnvironment();
2996
- const { branch } = await resolveBranch({
2997
- apiKey,
2998
- apiUrl: databaseURL,
2999
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3000
- workspacesApiUrl: `${protocol}//${host}`,
3001
- pathParams: { dbName, workspace, region },
3002
- queryParams: { gitBranch, fallbackBranch },
3003
- trace: defaultTrace
3004
- });
3005
- return branch;
3006
- }
3007
- async function getDatabaseBranch(branch, options) {
3008
- const databaseURL = options?.databaseURL || getDatabaseURL();
3009
- const apiKey = options?.apiKey || getAPIKey();
3010
- if (!databaseURL)
3011
- throw new Error(
3012
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3013
- );
3014
- if (!apiKey)
3015
- throw new Error(
3016
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3017
- );
3018
- const [protocol, , host, , database] = databaseURL.split("/");
3019
- const urlParts = parseWorkspacesUrlParts(host);
3020
- if (!urlParts)
3021
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3022
- const { workspace, region } = urlParts;
3023
- try {
3024
- return await getBranchDetails({
3025
- apiKey,
3026
- apiUrl: databaseURL,
3027
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3028
- workspacesApiUrl: `${protocol}//${host}`,
3029
- pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3030
- trace: defaultTrace
3031
- });
3032
- } catch (err) {
3033
- if (isObject(err) && err.status === 404)
3034
- return null;
3035
- throw err;
4469
+ function escapeElement(elementRepresentation) {
4470
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4471
+ return '"' + escaped + '"';
4472
+ }
4473
+ function arrayString(val) {
4474
+ let result = "{";
4475
+ for (let i = 0; i < val.length; i++) {
4476
+ if (i > 0) {
4477
+ result = result + ",";
4478
+ }
4479
+ if (val[i] === null || typeof val[i] === "undefined") {
4480
+ result = result + "NULL";
4481
+ } else if (Array.isArray(val[i])) {
4482
+ result = result + arrayString(val[i]);
4483
+ } else if (val[i] instanceof Buffer) {
4484
+ result += "\\\\x" + val[i].toString("hex");
4485
+ } else {
4486
+ result += escapeElement(prepareValue(val[i]));
4487
+ }
3036
4488
  }
4489
+ result = result + "}";
4490
+ return result;
3037
4491
  }
3038
- function getDatabaseURL() {
4492
+ function prepareValue(value) {
4493
+ if (!isDefined(value))
4494
+ return null;
4495
+ if (value instanceof Date) {
4496
+ return value.toISOString();
4497
+ }
4498
+ if (Array.isArray(value)) {
4499
+ return arrayString(value);
4500
+ }
4501
+ if (isObject(value)) {
4502
+ return JSON.stringify(value);
4503
+ }
3039
4504
  try {
3040
- const { databaseURL } = getEnvironment();
3041
- return databaseURL;
3042
- } catch (err) {
3043
- return void 0;
4505
+ return value.toString();
4506
+ } catch (e) {
4507
+ return value;
4508
+ }
4509
+ }
4510
+ function prepareParams(param1, param2) {
4511
+ if (isString(param1)) {
4512
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4513
+ }
4514
+ if (isStringArray(param1)) {
4515
+ const statement = param1.reduce((acc, curr, index) => {
4516
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4517
+ }, "");
4518
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4519
+ }
4520
+ if (isObject(param1)) {
4521
+ const { statement, params, consistency } = param1;
4522
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
4523
+ }
4524
+ throw new Error("Invalid query");
4525
+ }
4526
+
4527
+ class SQLPlugin extends XataPlugin {
4528
+ build(pluginOptions) {
4529
+ return async (param1, ...param2) => {
4530
+ const { statement, params, consistency } = prepareParams(param1, param2);
4531
+ const { records, warning } = await sqlQuery({
4532
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4533
+ body: { statement, params, consistency },
4534
+ ...pluginOptions
4535
+ });
4536
+ return { records, warning };
4537
+ };
4538
+ }
4539
+ }
4540
+
4541
+ class TransactionPlugin extends XataPlugin {
4542
+ build(pluginOptions) {
4543
+ return {
4544
+ run: async (operations) => {
4545
+ const response = await branchTransaction({
4546
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4547
+ body: { operations },
4548
+ ...pluginOptions
4549
+ });
4550
+ return response;
4551
+ }
4552
+ };
3044
4553
  }
3045
4554
  }
3046
4555
 
@@ -3067,46 +4576,43 @@ var __privateMethod = (obj, member, method) => {
3067
4576
  return method;
3068
4577
  };
3069
4578
  const buildClient = (plugins) => {
3070
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
4579
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3071
4580
  return _a = class {
3072
4581
  constructor(options = {}, schemaTables) {
3073
4582
  __privateAdd(this, _parseOptions);
3074
4583
  __privateAdd(this, _getFetchProps);
3075
- __privateAdd(this, _evaluateBranch);
3076
- __privateAdd(this, _branch, void 0);
3077
4584
  __privateAdd(this, _options, void 0);
3078
4585
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3079
4586
  __privateSet(this, _options, safeOptions);
3080
4587
  const pluginOptions = {
3081
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
4588
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3082
4589
  cache: safeOptions.cache,
3083
- trace: safeOptions.trace
4590
+ host: safeOptions.host
3084
4591
  };
3085
4592
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3086
4593
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
4594
+ const transactions = new TransactionPlugin().build(pluginOptions);
4595
+ const sql = new SQLPlugin().build(pluginOptions);
4596
+ const files = new FilesPlugin().build(pluginOptions);
3087
4597
  this.db = db;
3088
4598
  this.search = search;
4599
+ this.transactions = transactions;
4600
+ this.sql = sql;
4601
+ this.files = files;
3089
4602
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3090
4603
  if (namespace === void 0)
3091
4604
  continue;
3092
- const result = namespace.build(pluginOptions);
3093
- if (result instanceof Promise) {
3094
- void result.then((namespace2) => {
3095
- this[key] = namespace2;
3096
- });
3097
- } else {
3098
- this[key] = result;
3099
- }
4605
+ this[key] = namespace.build(pluginOptions);
3100
4606
  }
3101
4607
  }
3102
4608
  async getConfig() {
3103
4609
  const databaseURL = __privateGet(this, _options).databaseURL;
3104
- const branch = await __privateGet(this, _options).branch();
4610
+ const branch = __privateGet(this, _options).branch;
3105
4611
  return { databaseURL, branch };
3106
4612
  }
3107
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4613
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3108
4614
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3109
- const isBrowser = typeof window !== "undefined";
4615
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3110
4616
  if (isBrowser && !enableBrowser) {
3111
4617
  throw new Error(
3112
4618
  "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."
@@ -3117,46 +4623,73 @@ const buildClient = (plugins) => {
3117
4623
  const apiKey = options?.apiKey || getAPIKey();
3118
4624
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3119
4625
  const trace = options?.trace ?? defaultTrace;
3120
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
4626
+ const clientName = options?.clientName;
4627
+ const host = options?.host ?? "production";
4628
+ const xataAgentExtra = options?.xataAgentExtra;
3121
4629
  if (!apiKey) {
3122
4630
  throw new Error("Option apiKey is required");
3123
4631
  }
3124
4632
  if (!databaseURL) {
3125
4633
  throw new Error("Option databaseURL is required");
3126
4634
  }
3127
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser };
3128
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3129
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3130
- if (!branchValue)
3131
- throw new Error("Unable to resolve branch value");
4635
+ const envBranch = getBranch();
4636
+ const previewBranch = getPreviewBranch();
4637
+ const branch = options?.branch || previewBranch || envBranch || "main";
4638
+ if (!!previewBranch && branch !== previewBranch) {
4639
+ console.warn(
4640
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4641
+ );
4642
+ } else if (!!envBranch && branch !== envBranch) {
4643
+ console.warn(
4644
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4645
+ );
4646
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4647
+ console.warn(
4648
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4649
+ );
4650
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4651
+ console.warn(
4652
+ `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.`
4653
+ );
4654
+ }
4655
+ return {
4656
+ fetch,
4657
+ databaseURL,
4658
+ apiKey,
4659
+ branch,
4660
+ cache,
4661
+ trace,
4662
+ host,
4663
+ clientID: generateUUID(),
4664
+ enableBrowser,
4665
+ clientName,
4666
+ xataAgentExtra
4667
+ };
4668
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
4669
+ fetch,
4670
+ apiKey,
4671
+ databaseURL,
4672
+ branch,
4673
+ trace,
4674
+ clientID,
4675
+ clientName,
4676
+ xataAgentExtra
4677
+ }) {
3132
4678
  return {
3133
- fetchImpl: fetch,
4679
+ fetch,
3134
4680
  apiKey,
3135
4681
  apiUrl: "",
4682
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3136
4683
  workspacesApiUrl: (path, params) => {
3137
4684
  const hasBranch = params.dbBranchName ?? params.branch;
3138
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
4685
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
3139
4686
  return databaseURL + newPath;
3140
4687
  },
3141
4688
  trace,
3142
- clientID
3143
- };
3144
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3145
- if (__privateGet(this, _branch))
3146
- return __privateGet(this, _branch);
3147
- if (param === void 0)
3148
- return void 0;
3149
- const strategies = Array.isArray(param) ? [...param] : [param];
3150
- const evaluateBranch = async (strategy) => {
3151
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
4689
+ clientID,
4690
+ clientName,
4691
+ xataAgentExtra
3152
4692
  };
3153
- for await (const strategy of strategies) {
3154
- const branch = await evaluateBranch(strategy);
3155
- if (branch) {
3156
- __privateSet(this, _branch, branch);
3157
- return branch;
3158
- }
3159
- }
3160
4693
  }, _a;
3161
4694
  };
3162
4695
  class BaseClient extends buildClient() {
@@ -3230,7 +4763,7 @@ const deserialize = (json) => {
3230
4763
  };
3231
4764
 
3232
4765
  function buildWorkerRunner(config) {
3233
- return function xataWorker(name, _worker) {
4766
+ return function xataWorker(name, worker) {
3234
4767
  return async (...args) => {
3235
4768
  const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3236
4769
  const result = await fetch(url, {
@@ -3252,6 +4785,8 @@ class XataError extends Error {
3252
4785
  }
3253
4786
 
3254
4787
  exports.BaseClient = BaseClient;
4788
+ exports.FetcherError = FetcherError;
4789
+ exports.FilesPlugin = FilesPlugin;
3255
4790
  exports.Operations = operationsByTag;
3256
4791
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
3257
4792
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -3260,23 +4795,32 @@ exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
3260
4795
  exports.Page = Page;
3261
4796
  exports.Query = Query;
3262
4797
  exports.RecordArray = RecordArray;
4798
+ exports.RecordColumnTypes = RecordColumnTypes;
3263
4799
  exports.Repository = Repository;
3264
4800
  exports.RestRepository = RestRepository;
4801
+ exports.SQLPlugin = SQLPlugin;
3265
4802
  exports.SchemaPlugin = SchemaPlugin;
3266
4803
  exports.SearchPlugin = SearchPlugin;
3267
4804
  exports.Serializer = Serializer;
3268
4805
  exports.SimpleCache = SimpleCache;
4806
+ exports.TransactionPlugin = TransactionPlugin;
3269
4807
  exports.XataApiClient = XataApiClient;
3270
4808
  exports.XataApiPlugin = XataApiPlugin;
3271
4809
  exports.XataError = XataError;
4810
+ exports.XataFile = XataFile;
3272
4811
  exports.XataPlugin = XataPlugin;
3273
4812
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
3274
4813
  exports.addGitBranchesEntry = addGitBranchesEntry;
3275
4814
  exports.addTableColumn = addTableColumn;
3276
4815
  exports.aggregateTable = aggregateTable;
3277
4816
  exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
4817
+ exports.applyMigration = applyMigration;
4818
+ exports.askTable = askTable;
4819
+ exports.askTableSession = askTableSession;
3278
4820
  exports.branchTransaction = branchTransaction;
3279
4821
  exports.buildClient = buildClient;
4822
+ exports.buildPreviewBranchName = buildPreviewBranchName;
4823
+ exports.buildProviderString = buildProviderString;
3280
4824
  exports.buildWorkerRunner = buildWorkerRunner;
3281
4825
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
3282
4826
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
@@ -3284,32 +4828,37 @@ exports.compareBranchSchemas = compareBranchSchemas;
3284
4828
  exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
3285
4829
  exports.compareMigrationRequest = compareMigrationRequest;
3286
4830
  exports.contains = contains;
4831
+ exports.copyBranch = copyBranch;
3287
4832
  exports.createBranch = createBranch;
4833
+ exports.createCluster = createCluster;
3288
4834
  exports.createDatabase = createDatabase;
3289
4835
  exports.createMigrationRequest = createMigrationRequest;
3290
4836
  exports.createTable = createTable;
3291
4837
  exports.createUserAPIKey = createUserAPIKey;
3292
4838
  exports.createWorkspace = createWorkspace;
3293
- exports.dEPRECATEDcreateDatabase = dEPRECATEDcreateDatabase;
3294
- exports.dEPRECATEDdeleteDatabase = dEPRECATEDdeleteDatabase;
3295
- exports.dEPRECATEDgetDatabaseList = dEPRECATEDgetDatabaseList;
3296
- exports.dEPRECATEDgetDatabaseMetadata = dEPRECATEDgetDatabaseMetadata;
3297
- exports.dEPRECATEDupdateDatabaseMetadata = dEPRECATEDupdateDatabaseMetadata;
3298
4839
  exports.deleteBranch = deleteBranch;
3299
4840
  exports.deleteColumn = deleteColumn;
3300
4841
  exports.deleteDatabase = deleteDatabase;
4842
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
4843
+ exports.deleteFile = deleteFile;
4844
+ exports.deleteFileItem = deleteFileItem;
4845
+ exports.deleteOAuthAccessToken = deleteOAuthAccessToken;
3301
4846
  exports.deleteRecord = deleteRecord;
3302
4847
  exports.deleteTable = deleteTable;
3303
4848
  exports.deleteUser = deleteUser;
3304
4849
  exports.deleteUserAPIKey = deleteUserAPIKey;
4850
+ exports.deleteUserOAuthClient = deleteUserOAuthClient;
3305
4851
  exports.deleteWorkspace = deleteWorkspace;
3306
4852
  exports.deserialize = deserialize;
3307
4853
  exports.endsWith = endsWith;
3308
4854
  exports.equals = equals;
3309
4855
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
3310
4856
  exports.exists = exists;
4857
+ exports.fileAccess = fileAccess;
3311
4858
  exports.ge = ge;
3312
4859
  exports.getAPIKey = getAPIKey;
4860
+ exports.getAuthorizationCode = getAuthorizationCode;
4861
+ exports.getBranch = getBranch;
3313
4862
  exports.getBranchDetails = getBranchDetails;
3314
4863
  exports.getBranchList = getBranchList;
3315
4864
  exports.getBranchMetadata = getBranchMetadata;
@@ -3317,29 +4866,38 @@ exports.getBranchMigrationHistory = getBranchMigrationHistory;
3317
4866
  exports.getBranchMigrationPlan = getBranchMigrationPlan;
3318
4867
  exports.getBranchSchemaHistory = getBranchSchemaHistory;
3319
4868
  exports.getBranchStats = getBranchStats;
4869
+ exports.getCluster = getCluster;
3320
4870
  exports.getColumn = getColumn;
3321
- exports.getCurrentBranchDetails = getCurrentBranchDetails;
3322
- exports.getCurrentBranchName = getCurrentBranchName;
4871
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
3323
4872
  exports.getDatabaseList = getDatabaseList;
3324
4873
  exports.getDatabaseMetadata = getDatabaseMetadata;
3325
4874
  exports.getDatabaseURL = getDatabaseURL;
4875
+ exports.getFile = getFile;
4876
+ exports.getFileItem = getFileItem;
3326
4877
  exports.getGitBranchesMapping = getGitBranchesMapping;
3327
4878
  exports.getHostUrl = getHostUrl;
3328
4879
  exports.getMigrationRequest = getMigrationRequest;
3329
4880
  exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
4881
+ exports.getPreviewBranch = getPreviewBranch;
3330
4882
  exports.getRecord = getRecord;
4883
+ exports.getSchema = getSchema;
3331
4884
  exports.getTableColumns = getTableColumns;
3332
4885
  exports.getTableSchema = getTableSchema;
3333
4886
  exports.getUser = getUser;
3334
4887
  exports.getUserAPIKeys = getUserAPIKeys;
4888
+ exports.getUserOAuthAccessTokens = getUserOAuthAccessTokens;
4889
+ exports.getUserOAuthClients = getUserOAuthClients;
3335
4890
  exports.getWorkspace = getWorkspace;
3336
4891
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
3337
4892
  exports.getWorkspacesList = getWorkspacesList;
4893
+ exports.grantAuthorizationCode = grantAuthorizationCode;
3338
4894
  exports.greaterEquals = greaterEquals;
3339
4895
  exports.greaterThan = greaterThan;
3340
4896
  exports.greaterThanEquals = greaterThanEquals;
3341
4897
  exports.gt = gt;
3342
4898
  exports.gte = gte;
4899
+ exports.iContains = iContains;
4900
+ exports.iPattern = iPattern;
3343
4901
  exports.includes = includes;
3344
4902
  exports.includesAll = includesAll;
3345
4903
  exports.includesAny = includesAny;
@@ -3353,11 +4911,14 @@ exports.isHostProviderAlias = isHostProviderAlias;
3353
4911
  exports.isHostProviderBuilder = isHostProviderBuilder;
3354
4912
  exports.isIdentifiable = isIdentifiable;
3355
4913
  exports.isNot = isNot;
4914
+ exports.isValidExpandedColumn = isValidExpandedColumn;
4915
+ exports.isValidSelectableColumns = isValidSelectableColumns;
3356
4916
  exports.isXataRecord = isXataRecord;
3357
4917
  exports.le = le;
3358
4918
  exports.lessEquals = lessEquals;
3359
4919
  exports.lessThan = lessThan;
3360
4920
  exports.lessThanEquals = lessThanEquals;
4921
+ exports.listClusters = listClusters;
3361
4922
  exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
3362
4923
  exports.listRegions = listRegions;
3363
4924
  exports.lt = lt;
@@ -3369,23 +4930,32 @@ exports.parseProviderString = parseProviderString;
3369
4930
  exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
3370
4931
  exports.pattern = pattern;
3371
4932
  exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
4933
+ exports.pushBranchMigrations = pushBranchMigrations;
4934
+ exports.putFile = putFile;
4935
+ exports.putFileItem = putFileItem;
3372
4936
  exports.queryMigrationRequests = queryMigrationRequests;
3373
4937
  exports.queryTable = queryTable;
3374
4938
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
3375
4939
  exports.removeWorkspaceMember = removeWorkspaceMember;
4940
+ exports.renameDatabase = renameDatabase;
3376
4941
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
3377
4942
  exports.resolveBranch = resolveBranch;
3378
4943
  exports.searchBranch = searchBranch;
3379
4944
  exports.searchTable = searchTable;
3380
4945
  exports.serialize = serialize;
3381
4946
  exports.setTableSchema = setTableSchema;
4947
+ exports.sqlQuery = sqlQuery;
3382
4948
  exports.startsWith = startsWith;
3383
4949
  exports.summarizeTable = summarizeTable;
4950
+ exports.transformImage = transformImage;
3384
4951
  exports.updateBranchMetadata = updateBranchMetadata;
3385
4952
  exports.updateBranchSchema = updateBranchSchema;
4953
+ exports.updateCluster = updateCluster;
3386
4954
  exports.updateColumn = updateColumn;
4955
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
3387
4956
  exports.updateDatabaseMetadata = updateDatabaseMetadata;
3388
4957
  exports.updateMigrationRequest = updateMigrationRequest;
4958
+ exports.updateOAuthAccessToken = updateOAuthAccessToken;
3389
4959
  exports.updateRecordWithID = updateRecordWithID;
3390
4960
  exports.updateTable = updateTable;
3391
4961
  exports.updateUser = updateUser;
@@ -3393,4 +4963,5 @@ exports.updateWorkspace = updateWorkspace;
3393
4963
  exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
3394
4964
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
3395
4965
  exports.upsertRecordWithID = upsertRecordWithID;
4966
+ exports.vectorSearchTable = vectorSearchTable;
3396
4967
  //# sourceMappingURL=index.cjs.map