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

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
@@ -29,8 +29,11 @@ function notEmpty(value) {
29
29
  function compact(arr) {
30
30
  return arr.filter(notEmpty);
31
31
  }
32
+ function compactObject(obj) {
33
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
34
+ }
32
35
  function isObject(value) {
33
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
36
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
34
37
  }
35
38
  function isDefined(value) {
36
39
  return value !== null && value !== void 0;
@@ -85,6 +88,27 @@ function chunk(array, chunkSize) {
85
88
  async function timeout(ms) {
86
89
  return new Promise((resolve) => setTimeout(resolve, ms));
87
90
  }
91
+ function timeoutWithCancel(ms) {
92
+ let timeoutId;
93
+ const promise = new Promise((resolve) => {
94
+ timeoutId = setTimeout(() => {
95
+ resolve();
96
+ }, ms);
97
+ });
98
+ return {
99
+ cancel: () => clearTimeout(timeoutId),
100
+ promise
101
+ };
102
+ }
103
+ function promiseMap(inputValues, mapper) {
104
+ const reducer = (acc$, inputValue) => acc$.then(
105
+ (acc) => mapper(inputValue).then((result) => {
106
+ acc.push(result);
107
+ return acc;
108
+ })
109
+ );
110
+ return inputValues.reduce(reducer, Promise.resolve([]));
111
+ }
88
112
 
89
113
  function getEnvironment() {
90
114
  try {
@@ -93,8 +117,10 @@ function getEnvironment() {
93
117
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
94
118
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
95
119
  branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
96
- envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
97
- fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
120
+ deployPreview: process.env.XATA_PREVIEW,
121
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
122
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
123
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
98
124
  };
99
125
  }
100
126
  } catch (err) {
@@ -105,8 +131,10 @@ function getEnvironment() {
105
131
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
106
132
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
107
133
  branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
108
- envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
109
- fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
134
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
135
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
136
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
137
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
110
138
  };
111
139
  }
112
140
  } catch (err) {
@@ -115,8 +143,10 @@ function getEnvironment() {
115
143
  apiKey: getGlobalApiKey(),
116
144
  databaseURL: getGlobalDatabaseURL(),
117
145
  branch: getGlobalBranch(),
118
- envBranch: void 0,
119
- fallbackBranch: getGlobalFallbackBranch()
146
+ deployPreview: void 0,
147
+ deployPreviewBranch: void 0,
148
+ vercelGitCommitRef: void 0,
149
+ vercelGitRepoOwner: void 0
120
150
  };
121
151
  }
122
152
  function getEnableBrowserVariable() {
@@ -159,45 +189,59 @@ function getGlobalBranch() {
159
189
  return void 0;
160
190
  }
161
191
  }
162
- function getGlobalFallbackBranch() {
192
+ function getDatabaseURL() {
163
193
  try {
164
- return XATA_FALLBACK_BRANCH;
194
+ const { databaseURL } = getEnvironment();
195
+ return databaseURL;
165
196
  } catch (err) {
166
197
  return void 0;
167
198
  }
168
199
  }
169
- async function getGitBranch() {
170
- const cmd = ["git", "branch", "--show-current"];
171
- const fullCmd = cmd.join(" ");
172
- const nodeModule = ["child", "process"].join("_");
173
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
200
+ function getAPIKey() {
174
201
  try {
175
- const req = eval("require");
176
- if (typeof req === "function") {
177
- return req(nodeModule).execSync(fullCmd, execOptions).trim();
178
- }
179
- const { execSync } = await import(nodeModule);
180
- return execSync(fullCmd, execOptions).toString().trim();
202
+ const { apiKey } = getEnvironment();
203
+ return apiKey;
181
204
  } catch (err) {
205
+ return void 0;
182
206
  }
207
+ }
208
+ function getBranch() {
183
209
  try {
184
- if (isObject(Deno)) {
185
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
186
- return new TextDecoder().decode(await process2.output()).trim();
187
- }
210
+ const { branch } = getEnvironment();
211
+ return branch;
188
212
  } catch (err) {
213
+ return void 0;
189
214
  }
190
215
  }
191
-
192
- function getAPIKey() {
216
+ function buildPreviewBranchName({ org, branch }) {
217
+ return `preview-${org}-${branch}`;
218
+ }
219
+ function getPreviewBranch() {
193
220
  try {
194
- const { apiKey } = getEnvironment();
195
- return apiKey;
221
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
222
+ if (deployPreviewBranch)
223
+ return deployPreviewBranch;
224
+ switch (deployPreview) {
225
+ case "vercel": {
226
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
227
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
228
+ return void 0;
229
+ }
230
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
231
+ }
232
+ }
233
+ return void 0;
196
234
  } catch (err) {
197
235
  return void 0;
198
236
  }
199
237
  }
200
238
 
239
+ var __defProp$8 = Object.defineProperty;
240
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
241
+ var __publicField$8 = (obj, key, value) => {
242
+ __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
243
+ return value;
244
+ };
201
245
  var __accessCheck$8 = (obj, member, msg) => {
202
246
  if (!member.has(obj))
203
247
  throw TypeError("Cannot " + msg);
@@ -221,6 +265,7 @@ var __privateMethod$4 = (obj, member, method) => {
221
265
  return method;
222
266
  };
223
267
  var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
268
+ const REQUEST_TIMEOUT = 3e4;
224
269
  function getFetchImplementation(userFetch) {
225
270
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
226
271
  const fetchImpl = userFetch ?? globalFetch;
@@ -237,6 +282,8 @@ class ApiRequestPool {
237
282
  __privateAdd$8(this, _fetch, void 0);
238
283
  __privateAdd$8(this, _queue, void 0);
239
284
  __privateAdd$8(this, _concurrency, void 0);
285
+ __publicField$8(this, "running");
286
+ __publicField$8(this, "started");
240
287
  __privateSet$8(this, _queue, []);
241
288
  __privateSet$8(this, _concurrency, concurrency);
242
289
  this.running = 0;
@@ -252,18 +299,22 @@ class ApiRequestPool {
252
299
  return __privateGet$8(this, _fetch);
253
300
  }
254
301
  request(url, options) {
255
- const start = new Date();
256
- const fetch2 = this.getFetch();
302
+ const start = /* @__PURE__ */ new Date();
303
+ const fetchImpl = this.getFetch();
257
304
  const runRequest = async (stalled = false) => {
258
- const response = await fetch2(url, options);
305
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
306
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
307
+ if (!response) {
308
+ throw new Error("Request timed out");
309
+ }
259
310
  if (response.status === 429) {
260
311
  const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
261
312
  await timeout(rateLimitReset * 1e3);
262
313
  return await runRequest(true);
263
314
  }
264
315
  if (stalled) {
265
- const stalledTime = new Date().getTime() - start.getTime();
266
- console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
316
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
317
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
267
318
  }
268
319
  return response;
269
320
  };
@@ -305,16 +356,199 @@ function generateUUID() {
305
356
  });
306
357
  }
307
358
 
308
- const VERSION = "0.0.0-alpha.vfafe7e2";
359
+ async function getBytes(stream, onChunk) {
360
+ const reader = stream.getReader();
361
+ let result;
362
+ while (!(result = await reader.read()).done) {
363
+ onChunk(result.value);
364
+ }
365
+ }
366
+ function getLines(onLine) {
367
+ let buffer;
368
+ let position;
369
+ let fieldLength;
370
+ let discardTrailingNewline = false;
371
+ return function onChunk(arr) {
372
+ if (buffer === void 0) {
373
+ buffer = arr;
374
+ position = 0;
375
+ fieldLength = -1;
376
+ } else {
377
+ buffer = concat(buffer, arr);
378
+ }
379
+ const bufLength = buffer.length;
380
+ let lineStart = 0;
381
+ while (position < bufLength) {
382
+ if (discardTrailingNewline) {
383
+ if (buffer[position] === 10 /* NewLine */) {
384
+ lineStart = ++position;
385
+ }
386
+ discardTrailingNewline = false;
387
+ }
388
+ let lineEnd = -1;
389
+ for (; position < bufLength && lineEnd === -1; ++position) {
390
+ switch (buffer[position]) {
391
+ case 58 /* Colon */:
392
+ if (fieldLength === -1) {
393
+ fieldLength = position - lineStart;
394
+ }
395
+ break;
396
+ case 13 /* CarriageReturn */:
397
+ discardTrailingNewline = true;
398
+ case 10 /* NewLine */:
399
+ lineEnd = position;
400
+ break;
401
+ }
402
+ }
403
+ if (lineEnd === -1) {
404
+ break;
405
+ }
406
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
407
+ lineStart = position;
408
+ fieldLength = -1;
409
+ }
410
+ if (lineStart === bufLength) {
411
+ buffer = void 0;
412
+ } else if (lineStart !== 0) {
413
+ buffer = buffer.subarray(lineStart);
414
+ position -= lineStart;
415
+ }
416
+ };
417
+ }
418
+ function getMessages(onId, onRetry, onMessage) {
419
+ let message = newMessage();
420
+ const decoder = new TextDecoder();
421
+ return function onLine(line, fieldLength) {
422
+ if (line.length === 0) {
423
+ onMessage?.(message);
424
+ message = newMessage();
425
+ } else if (fieldLength > 0) {
426
+ const field = decoder.decode(line.subarray(0, fieldLength));
427
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
428
+ const value = decoder.decode(line.subarray(valueOffset));
429
+ switch (field) {
430
+ case "data":
431
+ message.data = message.data ? message.data + "\n" + value : value;
432
+ break;
433
+ case "event":
434
+ message.event = value;
435
+ break;
436
+ case "id":
437
+ onId(message.id = value);
438
+ break;
439
+ case "retry":
440
+ const retry = parseInt(value, 10);
441
+ if (!isNaN(retry)) {
442
+ onRetry(message.retry = retry);
443
+ }
444
+ break;
445
+ }
446
+ }
447
+ };
448
+ }
449
+ function concat(a, b) {
450
+ const res = new Uint8Array(a.length + b.length);
451
+ res.set(a);
452
+ res.set(b, a.length);
453
+ return res;
454
+ }
455
+ function newMessage() {
456
+ return {
457
+ data: "",
458
+ event: "",
459
+ id: "",
460
+ retry: void 0
461
+ };
462
+ }
463
+ const EventStreamContentType = "text/event-stream";
464
+ const LastEventId = "last-event-id";
465
+ function fetchEventSource(input, {
466
+ signal: inputSignal,
467
+ headers: inputHeaders,
468
+ onopen: inputOnOpen,
469
+ onmessage,
470
+ onclose,
471
+ onerror,
472
+ fetch: inputFetch,
473
+ ...rest
474
+ }) {
475
+ return new Promise((resolve, reject) => {
476
+ const headers = { ...inputHeaders };
477
+ if (!headers.accept) {
478
+ headers.accept = EventStreamContentType;
479
+ }
480
+ let curRequestController;
481
+ function dispose() {
482
+ curRequestController.abort();
483
+ }
484
+ inputSignal?.addEventListener("abort", () => {
485
+ dispose();
486
+ resolve();
487
+ });
488
+ const fetchImpl = inputFetch ?? fetch;
489
+ const onopen = inputOnOpen ?? defaultOnOpen;
490
+ async function create() {
491
+ curRequestController = new AbortController();
492
+ try {
493
+ const response = await fetchImpl(input, {
494
+ ...rest,
495
+ headers,
496
+ signal: curRequestController.signal
497
+ });
498
+ await onopen(response);
499
+ await getBytes(
500
+ response.body,
501
+ getLines(
502
+ getMessages(
503
+ (id) => {
504
+ if (id) {
505
+ headers[LastEventId] = id;
506
+ } else {
507
+ delete headers[LastEventId];
508
+ }
509
+ },
510
+ (_retry) => {
511
+ },
512
+ onmessage
513
+ )
514
+ )
515
+ );
516
+ onclose?.();
517
+ dispose();
518
+ resolve();
519
+ } catch (err) {
520
+ }
521
+ }
522
+ create();
523
+ });
524
+ }
525
+ function defaultOnOpen(response) {
526
+ const contentType = response.headers?.get("content-type");
527
+ if (!contentType?.startsWith(EventStreamContentType)) {
528
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
529
+ }
530
+ }
309
531
 
532
+ const VERSION = "0.25.2";
533
+
534
+ var __defProp$7 = Object.defineProperty;
535
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
536
+ var __publicField$7 = (obj, key, value) => {
537
+ __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
538
+ return value;
539
+ };
310
540
  class ErrorWithCause extends Error {
311
541
  constructor(message, options) {
312
542
  super(message, options);
543
+ __publicField$7(this, "cause");
313
544
  }
314
545
  }
315
546
  class FetcherError extends ErrorWithCause {
316
547
  constructor(status, data, requestId) {
317
548
  super(getMessage(data));
549
+ __publicField$7(this, "status");
550
+ __publicField$7(this, "requestId");
551
+ __publicField$7(this, "errors");
318
552
  this.status = status;
319
553
  this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
320
554
  this.requestId = requestId;
@@ -381,6 +615,15 @@ function hostHeader(url) {
381
615
  const { groups } = pattern.exec(url) ?? {};
382
616
  return groups?.host ? { Host: groups.host } : {};
383
617
  }
618
+ function parseBody(body, headers) {
619
+ if (!isDefined(body))
620
+ return void 0;
621
+ const { "Content-Type": contentType } = headers ?? {};
622
+ if (String(contentType).toLowerCase() === "application/json") {
623
+ return JSON.stringify(body);
624
+ }
625
+ return body;
626
+ }
384
627
  const defaultClientID = generateUUID();
385
628
  async function fetch$1({
386
629
  url: path,
@@ -389,7 +632,7 @@ async function fetch$1({
389
632
  headers: customHeaders,
390
633
  pathParams,
391
634
  queryParams,
392
- fetchImpl,
635
+ fetch: fetch2,
393
636
  apiKey,
394
637
  endpoint,
395
638
  apiUrl,
@@ -399,12 +642,14 @@ async function fetch$1({
399
642
  clientID,
400
643
  sessionID,
401
644
  clientName,
402
- fetchOptions = {}
645
+ xataAgentExtra,
646
+ fetchOptions = {},
647
+ rawResponse = false
403
648
  }) {
404
- pool.setFetch(fetchImpl);
649
+ pool.setFetch(fetch2);
405
650
  return await trace(
406
651
  `${method.toUpperCase()} ${path}`,
407
- async ({ name, setAttributes }) => {
652
+ async ({ setAttributes }) => {
408
653
  const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
409
654
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
410
655
  const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
@@ -415,9 +660,10 @@ async function fetch$1({
415
660
  const xataAgent = compact([
416
661
  ["client", "TS_SDK"],
417
662
  ["version", VERSION],
418
- isDefined(clientName) ? ["service", clientName] : void 0
663
+ isDefined(clientName) ? ["service", clientName] : void 0,
664
+ ...Object.entries(xataAgentExtra ?? {})
419
665
  ]).map(([key, value]) => `${key}=${value}`).join("; ");
420
- const headers = {
666
+ const headers = compactObject({
421
667
  "Accept-Encoding": "identity",
422
668
  "Content-Type": "application/json",
423
669
  "X-Xata-Client-ID": clientID ?? defaultClientID,
@@ -426,11 +672,11 @@ async function fetch$1({
426
672
  ...customHeaders,
427
673
  ...hostHeader(fullUrl),
428
674
  Authorization: `Bearer ${apiKey}`
429
- };
675
+ });
430
676
  const response = await pool.request(url, {
431
677
  ...fetchOptions,
432
678
  method: method.toUpperCase(),
433
- body: body ? JSON.stringify(body) : void 0,
679
+ body: parseBody(body, headers),
434
680
  headers,
435
681
  signal
436
682
  });
@@ -443,6 +689,9 @@ async function fetch$1({
443
689
  [TraceAttributes.HTTP_HOST]: host,
444
690
  [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
445
691
  });
692
+ const message = response.headers?.get("x-xata-message");
693
+ if (message)
694
+ console.warn(message);
446
695
  if (response.status === 204) {
447
696
  return {};
448
697
  }
@@ -450,7 +699,7 @@ async function fetch$1({
450
699
  throw new FetcherError(response.status, "Rate limit exceeded", requestId);
451
700
  }
452
701
  try {
453
- const jsonResponse = await response.json();
702
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
454
703
  if (response.ok) {
455
704
  return jsonResponse;
456
705
  }
@@ -462,6 +711,59 @@ async function fetch$1({
462
711
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
463
712
  );
464
713
  }
714
+ function fetchSSERequest({
715
+ url: path,
716
+ method,
717
+ body,
718
+ headers: customHeaders,
719
+ pathParams,
720
+ queryParams,
721
+ fetch: fetch2,
722
+ apiKey,
723
+ endpoint,
724
+ apiUrl,
725
+ workspacesApiUrl,
726
+ onMessage,
727
+ onError,
728
+ onClose,
729
+ signal,
730
+ clientID,
731
+ sessionID,
732
+ clientName,
733
+ xataAgentExtra
734
+ }) {
735
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
736
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
737
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
738
+ void fetchEventSource(url, {
739
+ method,
740
+ body: JSON.stringify(body),
741
+ fetch: fetch2,
742
+ signal,
743
+ headers: {
744
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
745
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
746
+ "X-Xata-Agent": compact([
747
+ ["client", "TS_SDK"],
748
+ ["version", VERSION],
749
+ isDefined(clientName) ? ["service", clientName] : void 0,
750
+ ...Object.entries(xataAgentExtra ?? {})
751
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
752
+ ...customHeaders,
753
+ Authorization: `Bearer ${apiKey}`,
754
+ "Content-Type": "application/json"
755
+ },
756
+ onmessage(ev) {
757
+ onMessage?.(JSON.parse(ev.data));
758
+ },
759
+ onerror(ev) {
760
+ onError?.(JSON.parse(ev.data));
761
+ },
762
+ onclose() {
763
+ onClose?.();
764
+ }
765
+ });
766
+ }
465
767
  function parseUrl(url) {
466
768
  try {
467
769
  const { host, protocol } = new URL(url);
@@ -492,6 +794,12 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
492
794
  ...variables,
493
795
  signal
494
796
  });
797
+ const copyBranch = (variables, signal) => dataPlaneFetch({
798
+ url: "/db/{dbBranchName}/copy",
799
+ method: "post",
800
+ ...variables,
801
+ signal
802
+ });
495
803
  const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
496
804
  url: "/db/{dbBranchName}/metadata",
497
805
  method: "put",
@@ -517,7 +825,6 @@ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName
517
825
  const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
518
826
  const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
519
827
  const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
520
- const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
521
828
  const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
522
829
  const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
523
830
  const getMigrationRequest = (variables, signal) => dataPlaneFetch({
@@ -542,6 +849,7 @@ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{
542
849
  const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
543
850
  const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
544
851
  const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
852
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
545
853
  const createTable = (variables, signal) => dataPlaneFetch({
546
854
  url: "/db/{dbBranchName}/tables/{tableName}",
547
855
  method: "put",
@@ -584,7 +892,44 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
584
892
  ...variables,
585
893
  signal
586
894
  });
895
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
587
896
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
897
+ const getFileItem = (variables, signal) => dataPlaneFetch({
898
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
899
+ method: "get",
900
+ ...variables,
901
+ signal
902
+ });
903
+ const putFileItem = (variables, signal) => dataPlaneFetch({
904
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
905
+ method: "put",
906
+ ...variables,
907
+ signal
908
+ });
909
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
910
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
911
+ method: "delete",
912
+ ...variables,
913
+ signal
914
+ });
915
+ const getFile = (variables, signal) => dataPlaneFetch({
916
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
917
+ method: "get",
918
+ ...variables,
919
+ signal
920
+ });
921
+ const putFile = (variables, signal) => dataPlaneFetch({
922
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
923
+ method: "put",
924
+ ...variables,
925
+ signal
926
+ });
927
+ const deleteFile = (variables, signal) => dataPlaneFetch({
928
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
929
+ method: "delete",
930
+ ...variables,
931
+ signal
932
+ });
588
933
  const getRecord = (variables, signal) => dataPlaneFetch({
589
934
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
590
935
  method: "get",
@@ -614,14 +959,35 @@ const searchTable = (variables, signal) => dataPlaneFetch({
614
959
  ...variables,
615
960
  signal
616
961
  });
962
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
963
+ const askTable = (variables, signal) => dataPlaneFetch({
964
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
965
+ method: "post",
966
+ ...variables,
967
+ signal
968
+ });
969
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
617
970
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
618
971
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
972
+ const fileAccess = (variables, signal) => dataPlaneFetch({
973
+ url: "/file/{fileId}",
974
+ method: "get",
975
+ ...variables,
976
+ signal
977
+ });
978
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
979
+ url: "/db/{dbBranchName}/sql",
980
+ method: "post",
981
+ ...variables,
982
+ signal
983
+ });
619
984
  const operationsByTag$2 = {
620
985
  branch: {
621
986
  getBranchList,
622
987
  getBranchDetails,
623
988
  createBranch,
624
989
  deleteBranch,
990
+ copyBranch,
625
991
  updateBranchMetadata,
626
992
  getBranchMetadata,
627
993
  getBranchStats,
@@ -639,17 +1005,8 @@ const operationsByTag$2 = {
639
1005
  compareBranchSchemas,
640
1006
  updateBranchSchema,
641
1007
  previewBranchSchemaEdit,
642
- applyBranchSchemaEdit
643
- },
644
- records: {
645
- branchTransaction,
646
- insertRecord,
647
- getRecord,
648
- insertRecordWithID,
649
- updateRecordWithID,
650
- upsertRecordWithID,
651
- deleteRecord,
652
- bulkInsertTableRecords
1008
+ applyBranchSchemaEdit,
1009
+ pushBranchMigrations
653
1010
  },
654
1011
  migrationRequests: {
655
1012
  queryMigrationRequests,
@@ -673,11 +1030,34 @@ const operationsByTag$2 = {
673
1030
  updateColumn,
674
1031
  deleteColumn
675
1032
  },
676
- searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
1033
+ records: {
1034
+ branchTransaction,
1035
+ insertRecord,
1036
+ getRecord,
1037
+ insertRecordWithID,
1038
+ updateRecordWithID,
1039
+ upsertRecordWithID,
1040
+ deleteRecord,
1041
+ bulkInsertTableRecords
1042
+ },
1043
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess },
1044
+ searchAndFilter: {
1045
+ queryTable,
1046
+ searchBranch,
1047
+ searchTable,
1048
+ vectorSearchTable,
1049
+ askTable,
1050
+ askTableSession,
1051
+ summarizeTable,
1052
+ aggregateTable
1053
+ },
1054
+ sql: { sqlQuery }
677
1055
  };
678
1056
 
679
1057
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
680
1058
 
1059
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1060
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
681
1061
  const getUser = (variables, signal) => controlPlaneFetch({
682
1062
  url: "/user",
683
1063
  method: "get",
@@ -714,6 +1094,25 @@ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
714
1094
  ...variables,
715
1095
  signal
716
1096
  });
1097
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1098
+ url: "/user/oauth/clients",
1099
+ method: "get",
1100
+ ...variables,
1101
+ signal
1102
+ });
1103
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1104
+ url: "/user/oauth/tokens",
1105
+ method: "get",
1106
+ ...variables,
1107
+ signal
1108
+ });
1109
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1110
+ url: "/user/oauth/tokens/{token}",
1111
+ method: "delete",
1112
+ ...variables,
1113
+ signal
1114
+ });
1115
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
717
1116
  const getWorkspacesList = (variables, signal) => controlPlaneFetch({
718
1117
  url: "/workspaces",
719
1118
  method: "get",
@@ -772,6 +1171,10 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
772
1171
  });
773
1172
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
774
1173
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1174
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1175
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1176
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1177
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
775
1178
  const listRegions = (variables, signal) => controlPlaneFetch({
776
1179
  url: "/workspaces/{workspaceId}/regions",
777
1180
  method: "get",
@@ -779,8 +1182,9 @@ const listRegions = (variables, signal) => controlPlaneFetch({
779
1182
  signal
780
1183
  });
781
1184
  const operationsByTag$1 = {
1185
+ authOther: { getAuthorizationCode, grantAuthorizationCode, deleteOAuthAccessToken, updateOAuthAccessToken },
782
1186
  users: { getUser, updateUser, deleteUser },
783
- authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
1187
+ authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey, getUserOAuthClients, getUserOAuthAccessTokens },
784
1188
  workspaces: {
785
1189
  getWorkspacesList,
786
1190
  createWorkspace,
@@ -804,6 +1208,10 @@ const operationsByTag$1 = {
804
1208
  deleteDatabase,
805
1209
  getDatabaseMetadata,
806
1210
  updateDatabaseMetadata,
1211
+ renameDatabase,
1212
+ getDatabaseGithubSettings,
1213
+ updateDatabaseGithubSettings,
1214
+ deleteDatabaseGithubSettings,
807
1215
  listRegions
808
1216
  }
809
1217
  };
@@ -824,8 +1232,12 @@ const providers = {
824
1232
  workspaces: "https://{workspaceId}.{region}.xata.sh"
825
1233
  },
826
1234
  staging: {
827
- main: "https://staging.xatabase.co",
828
- workspaces: "https://{workspaceId}.staging.{region}.xatabase.co"
1235
+ main: "https://api.staging-xata.dev",
1236
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1237
+ },
1238
+ dev: {
1239
+ main: "https://api.dev-xata.dev",
1240
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
829
1241
  }
830
1242
  };
831
1243
  function isHostProviderAlias(alias) {
@@ -843,12 +1255,19 @@ function parseProviderString(provider = "production") {
843
1255
  return null;
844
1256
  return { main, workspaces };
845
1257
  }
1258
+ function buildProviderString(provider) {
1259
+ if (isHostProviderAlias(provider))
1260
+ return provider;
1261
+ return `${provider.main},${provider.workspaces}`;
1262
+ }
846
1263
  function parseWorkspacesUrlParts(url) {
847
1264
  if (!isString(url))
848
1265
  return null;
849
1266
  const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
850
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
851
- const match = url.match(regex) || url.match(regexStaging);
1267
+ const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1268
+ const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1269
+ const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1270
+ const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
852
1271
  if (!match)
853
1272
  return null;
854
1273
  return { workspace: match[1], region: match[2] };
@@ -887,10 +1306,11 @@ class XataApiClient {
887
1306
  __privateSet$7(this, _extraProps, {
888
1307
  apiUrl: getHostUrl(provider, "main"),
889
1308
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
890
- fetchImpl: getFetchImplementation(options.fetch),
1309
+ fetch: getFetchImplementation(options.fetch),
891
1310
  apiKey,
892
1311
  trace,
893
1312
  clientName: options.clientName,
1313
+ xataAgentExtra: options.xataAgentExtra,
894
1314
  clientID
895
1315
  });
896
1316
  }
@@ -944,6 +1364,11 @@ class XataApiClient {
944
1364
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
945
1365
  return __privateGet$7(this, _namespaces).records;
946
1366
  }
1367
+ get files() {
1368
+ if (!__privateGet$7(this, _namespaces).files)
1369
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1370
+ return __privateGet$7(this, _namespaces).files;
1371
+ }
947
1372
  get searchAndFilter() {
948
1373
  if (!__privateGet$7(this, _namespaces).searchAndFilter)
949
1374
  __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
@@ -1152,6 +1577,20 @@ class BranchApi {
1152
1577
  ...this.extraProps
1153
1578
  });
1154
1579
  }
1580
+ copyBranch({
1581
+ workspace,
1582
+ region,
1583
+ database,
1584
+ branch,
1585
+ destinationBranch,
1586
+ limit
1587
+ }) {
1588
+ return operationsByTag.branch.copyBranch({
1589
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1590
+ body: { destinationBranch, limit },
1591
+ ...this.extraProps
1592
+ });
1593
+ }
1155
1594
  updateBranchMetadata({
1156
1595
  workspace,
1157
1596
  region,
@@ -1507,6 +1946,164 @@ class RecordsApi {
1507
1946
  });
1508
1947
  }
1509
1948
  }
1949
+ class FilesApi {
1950
+ constructor(extraProps) {
1951
+ this.extraProps = extraProps;
1952
+ }
1953
+ getFileItem({
1954
+ workspace,
1955
+ region,
1956
+ database,
1957
+ branch,
1958
+ table,
1959
+ record,
1960
+ column,
1961
+ fileId
1962
+ }) {
1963
+ return operationsByTag.files.getFileItem({
1964
+ pathParams: {
1965
+ workspace,
1966
+ region,
1967
+ dbBranchName: `${database}:${branch}`,
1968
+ tableName: table,
1969
+ recordId: record,
1970
+ columnName: column,
1971
+ fileId
1972
+ },
1973
+ ...this.extraProps
1974
+ });
1975
+ }
1976
+ putFileItem({
1977
+ workspace,
1978
+ region,
1979
+ database,
1980
+ branch,
1981
+ table,
1982
+ record,
1983
+ column,
1984
+ fileId,
1985
+ file
1986
+ }) {
1987
+ return operationsByTag.files.putFileItem({
1988
+ pathParams: {
1989
+ workspace,
1990
+ region,
1991
+ dbBranchName: `${database}:${branch}`,
1992
+ tableName: table,
1993
+ recordId: record,
1994
+ columnName: column,
1995
+ fileId
1996
+ },
1997
+ // @ts-ignore
1998
+ body: file,
1999
+ ...this.extraProps
2000
+ });
2001
+ }
2002
+ deleteFileItem({
2003
+ workspace,
2004
+ region,
2005
+ database,
2006
+ branch,
2007
+ table,
2008
+ record,
2009
+ column,
2010
+ fileId
2011
+ }) {
2012
+ return operationsByTag.files.deleteFileItem({
2013
+ pathParams: {
2014
+ workspace,
2015
+ region,
2016
+ dbBranchName: `${database}:${branch}`,
2017
+ tableName: table,
2018
+ recordId: record,
2019
+ columnName: column,
2020
+ fileId
2021
+ },
2022
+ ...this.extraProps
2023
+ });
2024
+ }
2025
+ getFile({
2026
+ workspace,
2027
+ region,
2028
+ database,
2029
+ branch,
2030
+ table,
2031
+ record,
2032
+ column
2033
+ }) {
2034
+ return operationsByTag.files.getFile({
2035
+ pathParams: {
2036
+ workspace,
2037
+ region,
2038
+ dbBranchName: `${database}:${branch}`,
2039
+ tableName: table,
2040
+ recordId: record,
2041
+ columnName: column
2042
+ },
2043
+ ...this.extraProps
2044
+ });
2045
+ }
2046
+ putFile({
2047
+ workspace,
2048
+ region,
2049
+ database,
2050
+ branch,
2051
+ table,
2052
+ record,
2053
+ column,
2054
+ file
2055
+ }) {
2056
+ return operationsByTag.files.putFile({
2057
+ pathParams: {
2058
+ workspace,
2059
+ region,
2060
+ dbBranchName: `${database}:${branch}`,
2061
+ tableName: table,
2062
+ recordId: record,
2063
+ columnName: column
2064
+ },
2065
+ body: file,
2066
+ ...this.extraProps
2067
+ });
2068
+ }
2069
+ deleteFile({
2070
+ workspace,
2071
+ region,
2072
+ database,
2073
+ branch,
2074
+ table,
2075
+ record,
2076
+ column
2077
+ }) {
2078
+ return operationsByTag.files.deleteFile({
2079
+ pathParams: {
2080
+ workspace,
2081
+ region,
2082
+ dbBranchName: `${database}:${branch}`,
2083
+ tableName: table,
2084
+ recordId: record,
2085
+ columnName: column
2086
+ },
2087
+ ...this.extraProps
2088
+ });
2089
+ }
2090
+ fileAccess({
2091
+ workspace,
2092
+ region,
2093
+ fileId,
2094
+ verify
2095
+ }) {
2096
+ return operationsByTag.files.fileAccess({
2097
+ pathParams: {
2098
+ workspace,
2099
+ region,
2100
+ fileId
2101
+ },
2102
+ queryParams: { verify },
2103
+ ...this.extraProps
2104
+ });
2105
+ }
2106
+ }
1510
2107
  class SearchAndFilterApi {
1511
2108
  constructor(extraProps) {
1512
2109
  this.extraProps = extraProps;
@@ -1543,26 +2140,73 @@ class SearchAndFilterApi {
1543
2140
  highlight,
1544
2141
  boosters
1545
2142
  }) {
1546
- return operationsByTag.searchAndFilter.searchTable({
2143
+ return operationsByTag.searchAndFilter.searchTable({
2144
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2145
+ body: { query, fuzziness, target, prefix, filter, highlight, boosters },
2146
+ ...this.extraProps
2147
+ });
2148
+ }
2149
+ searchBranch({
2150
+ workspace,
2151
+ region,
2152
+ database,
2153
+ branch,
2154
+ tables,
2155
+ query,
2156
+ fuzziness,
2157
+ prefix,
2158
+ highlight
2159
+ }) {
2160
+ return operationsByTag.searchAndFilter.searchBranch({
2161
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2162
+ body: { tables, query, fuzziness, prefix, highlight },
2163
+ ...this.extraProps
2164
+ });
2165
+ }
2166
+ vectorSearchTable({
2167
+ workspace,
2168
+ region,
2169
+ database,
2170
+ branch,
2171
+ table,
2172
+ queryVector,
2173
+ column,
2174
+ similarityFunction,
2175
+ size,
2176
+ filter
2177
+ }) {
2178
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2179
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2180
+ body: { queryVector, column, similarityFunction, size, filter },
2181
+ ...this.extraProps
2182
+ });
2183
+ }
2184
+ askTable({
2185
+ workspace,
2186
+ region,
2187
+ database,
2188
+ branch,
2189
+ table,
2190
+ options
2191
+ }) {
2192
+ return operationsByTag.searchAndFilter.askTable({
1547
2193
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1548
- body: { query, fuzziness, target, prefix, filter, highlight, boosters },
2194
+ body: { ...options },
1549
2195
  ...this.extraProps
1550
2196
  });
1551
2197
  }
1552
- searchBranch({
2198
+ askTableSession({
1553
2199
  workspace,
1554
2200
  region,
1555
2201
  database,
1556
2202
  branch,
1557
- tables,
1558
- query,
1559
- fuzziness,
1560
- prefix,
1561
- highlight
2203
+ table,
2204
+ sessionId,
2205
+ message
1562
2206
  }) {
1563
- return operationsByTag.searchAndFilter.searchBranch({
1564
- pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1565
- body: { tables, query, fuzziness, prefix, highlight },
2207
+ return operationsByTag.searchAndFilter.askTableSession({
2208
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2209
+ body: { message },
1566
2210
  ...this.extraProps
1567
2211
  });
1568
2212
  }
@@ -1766,11 +2410,13 @@ class MigrationsApi {
1766
2410
  region,
1767
2411
  database,
1768
2412
  branch,
1769
- schema
2413
+ schema,
2414
+ schemaOperations,
2415
+ branchOperations
1770
2416
  }) {
1771
2417
  return operationsByTag.migrations.compareBranchWithUserSchema({
1772
2418
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1773
- body: { schema },
2419
+ body: { schema, schemaOperations, branchOperations },
1774
2420
  ...this.extraProps
1775
2421
  });
1776
2422
  }
@@ -1780,11 +2426,12 @@ class MigrationsApi {
1780
2426
  database,
1781
2427
  branch,
1782
2428
  compare,
1783
- schema
2429
+ sourceBranchOperations,
2430
+ targetBranchOperations
1784
2431
  }) {
1785
2432
  return operationsByTag.migrations.compareBranchSchemas({
1786
2433
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1787
- body: { schema },
2434
+ body: { sourceBranchOperations, targetBranchOperations },
1788
2435
  ...this.extraProps
1789
2436
  });
1790
2437
  }
@@ -1827,6 +2474,19 @@ class MigrationsApi {
1827
2474
  ...this.extraProps
1828
2475
  });
1829
2476
  }
2477
+ pushBranchMigrations({
2478
+ workspace,
2479
+ region,
2480
+ database,
2481
+ branch,
2482
+ migrations
2483
+ }) {
2484
+ return operationsByTag.migrations.pushBranchMigrations({
2485
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2486
+ body: { migrations },
2487
+ ...this.extraProps
2488
+ });
2489
+ }
1830
2490
  }
1831
2491
  class DatabaseApi {
1832
2492
  constructor(extraProps) {
@@ -1841,11 +2501,13 @@ class DatabaseApi {
1841
2501
  createDatabase({
1842
2502
  workspace,
1843
2503
  database,
1844
- data
2504
+ data,
2505
+ headers
1845
2506
  }) {
1846
2507
  return operationsByTag.databases.createDatabase({
1847
2508
  pathParams: { workspaceId: workspace, dbName: database },
1848
2509
  body: data,
2510
+ headers,
1849
2511
  ...this.extraProps
1850
2512
  });
1851
2513
  }
@@ -1878,6 +2540,46 @@ class DatabaseApi {
1878
2540
  ...this.extraProps
1879
2541
  });
1880
2542
  }
2543
+ renameDatabase({
2544
+ workspace,
2545
+ database,
2546
+ newName
2547
+ }) {
2548
+ return operationsByTag.databases.renameDatabase({
2549
+ pathParams: { workspaceId: workspace, dbName: database },
2550
+ body: { newName },
2551
+ ...this.extraProps
2552
+ });
2553
+ }
2554
+ getDatabaseGithubSettings({
2555
+ workspace,
2556
+ database
2557
+ }) {
2558
+ return operationsByTag.databases.getDatabaseGithubSettings({
2559
+ pathParams: { workspaceId: workspace, dbName: database },
2560
+ ...this.extraProps
2561
+ });
2562
+ }
2563
+ updateDatabaseGithubSettings({
2564
+ workspace,
2565
+ database,
2566
+ settings
2567
+ }) {
2568
+ return operationsByTag.databases.updateDatabaseGithubSettings({
2569
+ pathParams: { workspaceId: workspace, dbName: database },
2570
+ body: settings,
2571
+ ...this.extraProps
2572
+ });
2573
+ }
2574
+ deleteDatabaseGithubSettings({
2575
+ workspace,
2576
+ database
2577
+ }) {
2578
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
2579
+ pathParams: { workspaceId: workspace, dbName: database },
2580
+ ...this.extraProps
2581
+ });
2582
+ }
1881
2583
  listRegions({ workspace }) {
1882
2584
  return operationsByTag.databases.listRegions({
1883
2585
  pathParams: { workspaceId: workspace },
@@ -1887,22 +2589,269 @@ class DatabaseApi {
1887
2589
  }
1888
2590
 
1889
2591
  class XataApiPlugin {
1890
- async build(options) {
1891
- const { fetchImpl, apiKey } = await options.getFetchProps();
1892
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2592
+ build(options) {
2593
+ return new XataApiClient(options);
1893
2594
  }
1894
2595
  }
1895
2596
 
1896
2597
  class XataPlugin {
1897
2598
  }
1898
2599
 
2600
+ class FilesPlugin extends XataPlugin {
2601
+ build(pluginOptions) {
2602
+ return {
2603
+ download: async (location) => {
2604
+ const { table, record, column, fileId = "" } = location ?? {};
2605
+ return await getFileItem({
2606
+ pathParams: {
2607
+ workspace: "{workspaceId}",
2608
+ dbBranchName: "{dbBranch}",
2609
+ region: "{region}",
2610
+ tableName: table ?? "",
2611
+ recordId: record ?? "",
2612
+ columnName: column ?? "",
2613
+ fileId
2614
+ },
2615
+ ...pluginOptions,
2616
+ rawResponse: true
2617
+ });
2618
+ },
2619
+ upload: async (location, file) => {
2620
+ const { table, record, column, fileId = "" } = location ?? {};
2621
+ return await putFileItem({
2622
+ pathParams: {
2623
+ workspace: "{workspaceId}",
2624
+ dbBranchName: "{dbBranch}",
2625
+ region: "{region}",
2626
+ tableName: table ?? "",
2627
+ recordId: record ?? "",
2628
+ columnName: column ?? "",
2629
+ fileId
2630
+ },
2631
+ body: file,
2632
+ ...pluginOptions
2633
+ });
2634
+ },
2635
+ delete: async (location) => {
2636
+ const { table, record, column, fileId = "" } = location ?? {};
2637
+ return await deleteFileItem({
2638
+ pathParams: {
2639
+ workspace: "{workspaceId}",
2640
+ dbBranchName: "{dbBranch}",
2641
+ region: "{region}",
2642
+ tableName: table ?? "",
2643
+ recordId: record ?? "",
2644
+ columnName: column ?? "",
2645
+ fileId
2646
+ },
2647
+ ...pluginOptions
2648
+ });
2649
+ }
2650
+ };
2651
+ }
2652
+ }
2653
+
2654
+ function buildTransformString(transformations) {
2655
+ return transformations.flatMap(
2656
+ (t) => Object.entries(t).map(([key, value]) => {
2657
+ if (key === "trim") {
2658
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2659
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2660
+ }
2661
+ if (key === "gravity" && typeof value === "object") {
2662
+ const { x = 0.5, y = 0.5 } = value;
2663
+ return `${key}=${[x, y].join("x")}`;
2664
+ }
2665
+ return `${key}=${value}`;
2666
+ })
2667
+ ).join(",");
2668
+ }
2669
+ function transformImage(url, transformations) {
2670
+ if (!isDefined(url))
2671
+ return void 0;
2672
+ const transformationsString = buildTransformString(transformations);
2673
+ const { hostname, pathname, search } = new URL(url);
2674
+ return `https://${hostname}/transform/${transformationsString}${pathname}${search}`;
2675
+ }
2676
+
2677
+ var __defProp$6 = Object.defineProperty;
2678
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2679
+ var __publicField$6 = (obj, key, value) => {
2680
+ __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
2681
+ return value;
2682
+ };
2683
+ class XataFile {
2684
+ constructor(file) {
2685
+ /**
2686
+ * Name of this file.
2687
+ */
2688
+ __publicField$6(this, "name");
2689
+ /**
2690
+ * Media type of this file.
2691
+ */
2692
+ __publicField$6(this, "mediaType");
2693
+ /**
2694
+ * Base64 encoded content of this file.
2695
+ */
2696
+ __publicField$6(this, "base64Content");
2697
+ /**
2698
+ * Whether to enable public url for this file.
2699
+ */
2700
+ __publicField$6(this, "enablePublicUrl");
2701
+ /**
2702
+ * Timeout for the signed url.
2703
+ */
2704
+ __publicField$6(this, "signedUrlTimeout");
2705
+ /**
2706
+ * Size of this file.
2707
+ */
2708
+ __publicField$6(this, "size");
2709
+ /**
2710
+ * Version of this file.
2711
+ */
2712
+ __publicField$6(this, "version");
2713
+ /**
2714
+ * Url of this file.
2715
+ */
2716
+ __publicField$6(this, "url");
2717
+ /**
2718
+ * Signed url of this file.
2719
+ */
2720
+ __publicField$6(this, "signedUrl");
2721
+ /**
2722
+ * Attributes of this file.
2723
+ */
2724
+ __publicField$6(this, "attributes");
2725
+ this.name = file.name;
2726
+ this.mediaType = file.mediaType || "application/octet-stream";
2727
+ this.base64Content = file.base64Content;
2728
+ this.enablePublicUrl = file.enablePublicUrl;
2729
+ this.signedUrlTimeout = file.signedUrlTimeout;
2730
+ this.size = file.size;
2731
+ this.version = file.version;
2732
+ this.url = file.url;
2733
+ this.signedUrl = file.signedUrl;
2734
+ this.attributes = file.attributes;
2735
+ }
2736
+ static fromBuffer(buffer, options = {}) {
2737
+ const base64Content = buffer.toString("base64");
2738
+ return new XataFile({ ...options, base64Content });
2739
+ }
2740
+ toBuffer() {
2741
+ if (!this.base64Content) {
2742
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2743
+ }
2744
+ return Buffer.from(this.base64Content, "base64");
2745
+ }
2746
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2747
+ const uint8Array = new Uint8Array(arrayBuffer);
2748
+ return this.fromUint8Array(uint8Array, options);
2749
+ }
2750
+ toArrayBuffer() {
2751
+ if (!this.base64Content) {
2752
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2753
+ }
2754
+ const binary = atob(this.base64Content);
2755
+ return new ArrayBuffer(binary.length);
2756
+ }
2757
+ static fromUint8Array(uint8Array, options = {}) {
2758
+ let binary = "";
2759
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2760
+ binary += String.fromCharCode(uint8Array[i]);
2761
+ }
2762
+ const base64Content = btoa(binary);
2763
+ return new XataFile({ ...options, base64Content });
2764
+ }
2765
+ toUint8Array() {
2766
+ if (!this.base64Content) {
2767
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2768
+ }
2769
+ const binary = atob(this.base64Content);
2770
+ const uint8Array = new Uint8Array(binary.length);
2771
+ for (let i = 0; i < binary.length; i++) {
2772
+ uint8Array[i] = binary.charCodeAt(i);
2773
+ }
2774
+ return uint8Array;
2775
+ }
2776
+ static async fromBlob(file, options = {}) {
2777
+ const name = options.name ?? file.name;
2778
+ const mediaType = file.type;
2779
+ const arrayBuffer = await file.arrayBuffer();
2780
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2781
+ }
2782
+ toBlob() {
2783
+ if (!this.base64Content) {
2784
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2785
+ }
2786
+ const arrayBuffer = this.toArrayBuffer();
2787
+ return new Blob([arrayBuffer], { type: this.mediaType });
2788
+ }
2789
+ static fromString(string, options = {}) {
2790
+ const base64Content = btoa(string);
2791
+ return new XataFile({ ...options, base64Content });
2792
+ }
2793
+ toString() {
2794
+ if (!this.base64Content) {
2795
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2796
+ }
2797
+ return atob(this.base64Content);
2798
+ }
2799
+ static fromBase64(base64Content, options = {}) {
2800
+ return new XataFile({ ...options, base64Content });
2801
+ }
2802
+ toBase64() {
2803
+ if (!this.base64Content) {
2804
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2805
+ }
2806
+ return this.base64Content;
2807
+ }
2808
+ transform(...options) {
2809
+ return {
2810
+ url: transformImage(this.url, options),
2811
+ signedUrl: transformImage(this.signedUrl, options)
2812
+ };
2813
+ }
2814
+ }
2815
+ const parseInputFileEntry = async (entry) => {
2816
+ if (!isDefined(entry))
2817
+ return null;
2818
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout } = await entry;
2819
+ return compactObject({ id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout });
2820
+ };
2821
+
1899
2822
  function cleanFilter(filter) {
1900
- if (!filter)
2823
+ if (!isDefined(filter))
1901
2824
  return void 0;
1902
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1903
- return values.length > 0 ? filter : void 0;
2825
+ if (!isObject(filter))
2826
+ return filter;
2827
+ const values = Object.fromEntries(
2828
+ Object.entries(filter).reduce((acc, [key, value]) => {
2829
+ if (!isDefined(value))
2830
+ return acc;
2831
+ if (Array.isArray(value)) {
2832
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2833
+ if (clean.length === 0)
2834
+ return acc;
2835
+ return [...acc, [key, clean]];
2836
+ }
2837
+ if (isObject(value)) {
2838
+ const clean = cleanFilter(value);
2839
+ if (!isDefined(clean))
2840
+ return acc;
2841
+ return [...acc, [key, clean]];
2842
+ }
2843
+ return [...acc, [key, value]];
2844
+ }, [])
2845
+ );
2846
+ return Object.keys(values).length > 0 ? values : void 0;
1904
2847
  }
1905
2848
 
2849
+ var __defProp$5 = Object.defineProperty;
2850
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2851
+ var __publicField$5 = (obj, key, value) => {
2852
+ __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
2853
+ return value;
2854
+ };
1906
2855
  var __accessCheck$6 = (obj, member, msg) => {
1907
2856
  if (!member.has(obj))
1908
2857
  throw TypeError("Cannot " + msg);
@@ -1925,22 +2874,58 @@ var _query, _page;
1925
2874
  class Page {
1926
2875
  constructor(query, meta, records = []) {
1927
2876
  __privateAdd$6(this, _query, void 0);
2877
+ /**
2878
+ * Page metadata, required to retrieve additional records.
2879
+ */
2880
+ __publicField$5(this, "meta");
2881
+ /**
2882
+ * The set of results for this page.
2883
+ */
2884
+ __publicField$5(this, "records");
1928
2885
  __privateSet$6(this, _query, query);
1929
2886
  this.meta = meta;
1930
2887
  this.records = new RecordArray(this, records);
1931
2888
  }
2889
+ /**
2890
+ * Retrieves the next page of results.
2891
+ * @param size Maximum number of results to be retrieved.
2892
+ * @param offset Number of results to skip when retrieving the results.
2893
+ * @returns The next page or results.
2894
+ */
1932
2895
  async nextPage(size, offset) {
1933
2896
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
1934
2897
  }
2898
+ /**
2899
+ * Retrieves the previous page of results.
2900
+ * @param size Maximum number of results to be retrieved.
2901
+ * @param offset Number of results to skip when retrieving the results.
2902
+ * @returns The previous page or results.
2903
+ */
1935
2904
  async previousPage(size, offset) {
1936
2905
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1937
2906
  }
2907
+ /**
2908
+ * Retrieves the start page of results.
2909
+ * @param size Maximum number of results to be retrieved.
2910
+ * @param offset Number of results to skip when retrieving the results.
2911
+ * @returns The start page or results.
2912
+ */
1938
2913
  async startPage(size, offset) {
1939
2914
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1940
2915
  }
2916
+ /**
2917
+ * Retrieves the end page of results.
2918
+ * @param size Maximum number of results to be retrieved.
2919
+ * @param offset Number of results to skip when retrieving the results.
2920
+ * @returns The end page or results.
2921
+ */
1941
2922
  async endPage(size, offset) {
1942
2923
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1943
2924
  }
2925
+ /**
2926
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
2927
+ * @returns Whether or not there will be additional results in the next page of results.
2928
+ */
1944
2929
  hasNextPage() {
1945
2930
  return this.meta.page.more;
1946
2931
  }
@@ -1953,7 +2938,7 @@ const PAGINATION_DEFAULT_OFFSET = 0;
1953
2938
  function isCursorPaginationOptions(options) {
1954
2939
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1955
2940
  }
1956
- const _RecordArray = class extends Array {
2941
+ const _RecordArray = class _RecordArray extends Array {
1957
2942
  constructor(...args) {
1958
2943
  super(..._RecordArray.parseConstructorParams(...args));
1959
2944
  __privateAdd$6(this, _page, void 0);
@@ -1972,32 +2957,67 @@ const _RecordArray = class extends Array {
1972
2957
  toArray() {
1973
2958
  return new Array(...this);
1974
2959
  }
2960
+ toSerializable() {
2961
+ return JSON.parse(this.toString());
2962
+ }
2963
+ toString() {
2964
+ return JSON.stringify(this.toArray());
2965
+ }
1975
2966
  map(callbackfn, thisArg) {
1976
2967
  return this.toArray().map(callbackfn, thisArg);
1977
2968
  }
2969
+ /**
2970
+ * Retrieve next page of records
2971
+ *
2972
+ * @returns A new array of objects
2973
+ */
1978
2974
  async nextPage(size, offset) {
1979
2975
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1980
2976
  return new _RecordArray(newPage);
1981
2977
  }
2978
+ /**
2979
+ * Retrieve previous page of records
2980
+ *
2981
+ * @returns A new array of objects
2982
+ */
1982
2983
  async previousPage(size, offset) {
1983
2984
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1984
2985
  return new _RecordArray(newPage);
1985
2986
  }
2987
+ /**
2988
+ * Retrieve start page of records
2989
+ *
2990
+ * @returns A new array of objects
2991
+ */
1986
2992
  async startPage(size, offset) {
1987
2993
  const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1988
2994
  return new _RecordArray(newPage);
1989
2995
  }
2996
+ /**
2997
+ * Retrieve end page of records
2998
+ *
2999
+ * @returns A new array of objects
3000
+ */
1990
3001
  async endPage(size, offset) {
1991
3002
  const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1992
3003
  return new _RecordArray(newPage);
1993
3004
  }
3005
+ /**
3006
+ * @returns Boolean indicating if there is a next page
3007
+ */
1994
3008
  hasNextPage() {
1995
3009
  return __privateGet$6(this, _page).meta.page.more;
1996
3010
  }
1997
3011
  };
1998
- let RecordArray = _RecordArray;
1999
3012
  _page = new WeakMap();
3013
+ let RecordArray = _RecordArray;
2000
3014
 
3015
+ var __defProp$4 = Object.defineProperty;
3016
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3017
+ var __publicField$4 = (obj, key, value) => {
3018
+ __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
3019
+ return value;
3020
+ };
2001
3021
  var __accessCheck$5 = (obj, member, msg) => {
2002
3022
  if (!member.has(obj))
2003
3023
  throw TypeError("Cannot " + msg);
@@ -2021,14 +3041,15 @@ var __privateMethod$3 = (obj, member, method) => {
2021
3041
  return method;
2022
3042
  };
2023
3043
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
2024
- const _Query = class {
3044
+ const _Query = class _Query {
2025
3045
  constructor(repository, table, data, rawParent) {
2026
3046
  __privateAdd$5(this, _cleanFilterConstraint);
2027
3047
  __privateAdd$5(this, _table$1, void 0);
2028
3048
  __privateAdd$5(this, _repository, void 0);
2029
3049
  __privateAdd$5(this, _data, { filter: {} });
2030
- this.meta = { page: { cursor: "start", more: true } };
2031
- this.records = new RecordArray(this, []);
3050
+ // Implements pagination
3051
+ __publicField$4(this, "meta", { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } });
3052
+ __publicField$4(this, "records", new RecordArray(this, []));
2032
3053
  __privateSet$5(this, _table$1, table);
2033
3054
  if (repository) {
2034
3055
  __privateSet$5(this, _repository, repository);
@@ -2064,18 +3085,38 @@ const _Query = class {
2064
3085
  const key = JSON.stringify({ columns, filter, sort, pagination });
2065
3086
  return toBase64(key);
2066
3087
  }
3088
+ /**
3089
+ * Builds a new query object representing a logical OR between the given subqueries.
3090
+ * @param queries An array of subqueries.
3091
+ * @returns A new Query object.
3092
+ */
2067
3093
  any(...queries) {
2068
3094
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
2069
3095
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
2070
3096
  }
3097
+ /**
3098
+ * Builds a new query object representing a logical AND between the given subqueries.
3099
+ * @param queries An array of subqueries.
3100
+ * @returns A new Query object.
3101
+ */
2071
3102
  all(...queries) {
2072
3103
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
2073
3104
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
2074
3105
  }
3106
+ /**
3107
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3108
+ * @param queries An array of subqueries.
3109
+ * @returns A new Query object.
3110
+ */
2075
3111
  not(...queries) {
2076
3112
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
2077
3113
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
2078
3114
  }
3115
+ /**
3116
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3117
+ * @param queries An array of subqueries.
3118
+ * @returns A new Query object.
3119
+ */
2079
3120
  none(...queries) {
2080
3121
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
2081
3122
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
@@ -2098,6 +3139,11 @@ const _Query = class {
2098
3139
  const sort = [...originalSort, { column, direction }];
2099
3140
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
2100
3141
  }
3142
+ /**
3143
+ * Builds a new query specifying the set of columns to be returned in the query response.
3144
+ * @param columns Array of column names to be returned by the query.
3145
+ * @returns A new Query object.
3146
+ */
2101
3147
  select(columns) {
2102
3148
  return new _Query(
2103
3149
  __privateGet$5(this, _repository),
@@ -2110,6 +3156,12 @@ const _Query = class {
2110
3156
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
2111
3157
  return __privateGet$5(this, _repository).query(query);
2112
3158
  }
3159
+ /**
3160
+ * Get results in an iterator
3161
+ *
3162
+ * @async
3163
+ * @returns Async interable of results
3164
+ */
2113
3165
  async *[Symbol.asyncIterator]() {
2114
3166
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
2115
3167
  yield record;
@@ -2170,26 +3222,53 @@ const _Query = class {
2170
3222
  );
2171
3223
  return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2172
3224
  }
3225
+ /**
3226
+ * Builds a new query object adding a cache TTL in milliseconds.
3227
+ * @param ttl The cache TTL in milliseconds.
3228
+ * @returns A new Query object.
3229
+ */
2173
3230
  cache(ttl) {
2174
3231
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2175
3232
  }
3233
+ /**
3234
+ * Retrieve next page of records
3235
+ *
3236
+ * @returns A new page object.
3237
+ */
2176
3238
  nextPage(size, offset) {
2177
3239
  return this.startPage(size, offset);
2178
3240
  }
3241
+ /**
3242
+ * Retrieve previous page of records
3243
+ *
3244
+ * @returns A new page object
3245
+ */
2179
3246
  previousPage(size, offset) {
2180
3247
  return this.startPage(size, offset);
2181
3248
  }
3249
+ /**
3250
+ * Retrieve start page of records
3251
+ *
3252
+ * @returns A new page object
3253
+ */
2182
3254
  startPage(size, offset) {
2183
3255
  return this.getPaginated({ pagination: { size, offset } });
2184
3256
  }
3257
+ /**
3258
+ * Retrieve last page of records
3259
+ *
3260
+ * @returns A new page object
3261
+ */
2185
3262
  endPage(size, offset) {
2186
3263
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2187
3264
  }
3265
+ /**
3266
+ * @returns Boolean indicating if there is a next page
3267
+ */
2188
3268
  hasNextPage() {
2189
3269
  return this.meta.page.more;
2190
3270
  }
2191
3271
  };
2192
- let Query = _Query;
2193
3272
  _table$1 = new WeakMap();
2194
3273
  _repository = new WeakMap();
2195
3274
  _data = new WeakMap();
@@ -2204,6 +3283,7 @@ cleanFilterConstraint_fn = function(column, value) {
2204
3283
  }
2205
3284
  return value;
2206
3285
  };
3286
+ let Query = _Query;
2207
3287
  function cleanParent(data, parent) {
2208
3288
  if (isCursorPaginationOptions(data.pagination)) {
2209
3289
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2211,6 +3291,21 @@ function cleanParent(data, parent) {
2211
3291
  return parent;
2212
3292
  }
2213
3293
 
3294
+ const RecordColumnTypes = [
3295
+ "bool",
3296
+ "int",
3297
+ "float",
3298
+ "string",
3299
+ "text",
3300
+ "email",
3301
+ "multiple",
3302
+ "link",
3303
+ "object",
3304
+ "datetime",
3305
+ "vector",
3306
+ "file[]",
3307
+ "file"
3308
+ ];
2214
3309
  function isIdentifiable(x) {
2215
3310
  return isObject(x) && isString(x?.id);
2216
3311
  }
@@ -2224,7 +3319,11 @@ function isSortFilterString(value) {
2224
3319
  return isString(value);
2225
3320
  }
2226
3321
  function isSortFilterBase(filter) {
2227
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
3322
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
3323
+ if (key === "*")
3324
+ return value === "random";
3325
+ return value === "asc" || value === "desc";
3326
+ });
2228
3327
  }
2229
3328
  function isSortFilterObject(filter) {
2230
3329
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -2265,7 +3364,7 @@ var __privateMethod$2 = (obj, member, method) => {
2265
3364
  __accessCheck$4(obj, member, "access private method");
2266
3365
  return method;
2267
3366
  };
2268
- var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
3367
+ 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;
2269
3368
  const BULK_OPERATION_MAX_SIZE = 1e3;
2270
3369
  class Repository extends Query {
2271
3370
  }
@@ -2287,6 +3386,7 @@ class RestRepository extends Query {
2287
3386
  __privateAdd$4(this, _setCacheQuery);
2288
3387
  __privateAdd$4(this, _getCacheQuery);
2289
3388
  __privateAdd$4(this, _getSchemaTables$1);
3389
+ __privateAdd$4(this, _transformObjectToApi);
2290
3390
  __privateAdd$4(this, _table, void 0);
2291
3391
  __privateAdd$4(this, _getFetchProps, void 0);
2292
3392
  __privateAdd$4(this, _db, void 0);
@@ -2297,10 +3397,7 @@ class RestRepository extends Query {
2297
3397
  __privateSet$4(this, _db, options.db);
2298
3398
  __privateSet$4(this, _cache, options.pluginOptions.cache);
2299
3399
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2300
- __privateSet$4(this, _getFetchProps, async () => {
2301
- const props = await options.pluginOptions.getFetchProps();
2302
- return { ...props, sessionID: generateUUID() };
2303
- });
3400
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2304
3401
  const trace = options.pluginOptions.trace ?? defaultTrace;
2305
3402
  __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2306
3403
  return trace(name, fn, {
@@ -2357,7 +3454,6 @@ class RestRepository extends Query {
2357
3454
  }
2358
3455
  const id = extractId(a);
2359
3456
  if (id) {
2360
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2361
3457
  try {
2362
3458
  const response = await getRecord({
2363
3459
  pathParams: {
@@ -2368,7 +3464,7 @@ class RestRepository extends Query {
2368
3464
  recordId: id
2369
3465
  },
2370
3466
  queryParams: { columns },
2371
- ...fetchProps
3467
+ ...__privateGet$4(this, _getFetchProps).call(this)
2372
3468
  });
2373
3469
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2374
3470
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2468,12 +3564,22 @@ class RestRepository extends Query {
2468
3564
  return result;
2469
3565
  }
2470
3566
  if (isString(a) && isObject(b)) {
3567
+ if (a === "")
3568
+ throw new Error("The id can't be empty");
2471
3569
  const columns = isStringArray(c) ? c : void 0;
2472
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3570
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2473
3571
  }
2474
3572
  if (isObject(a) && isString(a.id)) {
3573
+ if (a.id === "")
3574
+ throw new Error("The id can't be empty");
2475
3575
  const columns = isStringArray(c) ? c : void 0;
2476
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3576
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3577
+ }
3578
+ if (!isDefined(a) && isObject(b)) {
3579
+ return await this.create(b, c);
3580
+ }
3581
+ if (isObject(a) && !isDefined(a.id)) {
3582
+ return await this.create(a, b);
2477
3583
  }
2478
3584
  throw new Error("Invalid arguments for createOrUpdate method");
2479
3585
  });
@@ -2490,12 +3596,22 @@ class RestRepository extends Query {
2490
3596
  return result;
2491
3597
  }
2492
3598
  if (isString(a) && isObject(b)) {
3599
+ if (a === "")
3600
+ throw new Error("The id can't be empty");
2493
3601
  const columns = isStringArray(c) ? c : void 0;
2494
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3602
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2495
3603
  }
2496
3604
  if (isObject(a) && isString(a.id)) {
3605
+ if (a.id === "")
3606
+ throw new Error("The id can't be empty");
2497
3607
  const columns = isStringArray(c) ? c : void 0;
2498
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3608
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3609
+ }
3610
+ if (!isDefined(a) && isObject(b)) {
3611
+ return await this.create(b, c);
3612
+ }
3613
+ if (isObject(a) && !isDefined(a.id)) {
3614
+ return await this.create(a, b);
2499
3615
  }
2500
3616
  throw new Error("Invalid arguments for createOrReplace method");
2501
3617
  });
@@ -2546,7 +3662,6 @@ class RestRepository extends Query {
2546
3662
  }
2547
3663
  async search(query, options = {}) {
2548
3664
  return __privateGet$4(this, _trace).call(this, "search", async () => {
2549
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2550
3665
  const { records } = await searchTable({
2551
3666
  pathParams: {
2552
3667
  workspace: "{workspaceId}",
@@ -2564,7 +3679,29 @@ class RestRepository extends Query {
2564
3679
  page: options.page,
2565
3680
  target: options.target
2566
3681
  },
2567
- ...fetchProps
3682
+ ...__privateGet$4(this, _getFetchProps).call(this)
3683
+ });
3684
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3685
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3686
+ });
3687
+ }
3688
+ async vectorSearch(column, query, options) {
3689
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3690
+ const { records } = await vectorSearchTable({
3691
+ pathParams: {
3692
+ workspace: "{workspaceId}",
3693
+ dbBranchName: "{dbBranch}",
3694
+ region: "{region}",
3695
+ tableName: __privateGet$4(this, _table)
3696
+ },
3697
+ body: {
3698
+ column,
3699
+ queryVector: query,
3700
+ similarityFunction: options?.similarityFunction,
3701
+ size: options?.size,
3702
+ filter: options?.filter
3703
+ },
3704
+ ...__privateGet$4(this, _getFetchProps).call(this)
2568
3705
  });
2569
3706
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2570
3707
  return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
@@ -2572,7 +3709,6 @@ class RestRepository extends Query {
2572
3709
  }
2573
3710
  async aggregate(aggs, filter) {
2574
3711
  return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2575
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2576
3712
  const result = await aggregateTable({
2577
3713
  pathParams: {
2578
3714
  workspace: "{workspaceId}",
@@ -2581,7 +3717,7 @@ class RestRepository extends Query {
2581
3717
  tableName: __privateGet$4(this, _table)
2582
3718
  },
2583
3719
  body: { aggs, filter },
2584
- ...fetchProps
3720
+ ...__privateGet$4(this, _getFetchProps).call(this)
2585
3721
  });
2586
3722
  return result;
2587
3723
  });
@@ -2592,7 +3728,6 @@ class RestRepository extends Query {
2592
3728
  if (cacheQuery)
2593
3729
  return new Page(query, cacheQuery.meta, cacheQuery.records);
2594
3730
  const data = query.getQueryOptions();
2595
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2596
3731
  const { meta, records: objects } = await queryTable({
2597
3732
  pathParams: {
2598
3733
  workspace: "{workspaceId}",
@@ -2608,7 +3743,7 @@ class RestRepository extends Query {
2608
3743
  consistency: data.consistency
2609
3744
  },
2610
3745
  fetchOptions: data.fetchOptions,
2611
- ...fetchProps
3746
+ ...__privateGet$4(this, _getFetchProps).call(this)
2612
3747
  });
2613
3748
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2614
3749
  const records = objects.map(
@@ -2621,7 +3756,6 @@ class RestRepository extends Query {
2621
3756
  async summarizeTable(query, summaries, summariesFilter) {
2622
3757
  return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2623
3758
  const data = query.getQueryOptions();
2624
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2625
3759
  const result = await summarizeTable({
2626
3760
  pathParams: {
2627
3761
  workspace: "{workspaceId}",
@@ -2638,11 +3772,44 @@ class RestRepository extends Query {
2638
3772
  summaries,
2639
3773
  summariesFilter
2640
3774
  },
2641
- ...fetchProps
3775
+ ...__privateGet$4(this, _getFetchProps).call(this)
2642
3776
  });
2643
3777
  return result;
2644
3778
  });
2645
3779
  }
3780
+ ask(question, options) {
3781
+ const questionParam = options?.sessionId ? { message: question } : { question };
3782
+ const params = {
3783
+ pathParams: {
3784
+ workspace: "{workspaceId}",
3785
+ dbBranchName: "{dbBranch}",
3786
+ region: "{region}",
3787
+ tableName: __privateGet$4(this, _table),
3788
+ sessionId: options?.sessionId
3789
+ },
3790
+ body: {
3791
+ ...questionParam,
3792
+ rules: options?.rules,
3793
+ searchType: options?.searchType,
3794
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3795
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3796
+ },
3797
+ ...__privateGet$4(this, _getFetchProps).call(this)
3798
+ };
3799
+ if (options?.onMessage) {
3800
+ fetchSSERequest({
3801
+ endpoint: "dataPlane",
3802
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3803
+ method: "POST",
3804
+ onMessage: (message) => {
3805
+ options.onMessage?.({ answer: message.text, records: message.records });
3806
+ },
3807
+ ...params
3808
+ });
3809
+ } else {
3810
+ return askTableSession(params);
3811
+ }
3812
+ }
2646
3813
  }
2647
3814
  _table = new WeakMap();
2648
3815
  _getFetchProps = new WeakMap();
@@ -2652,8 +3819,7 @@ _schemaTables$2 = new WeakMap();
2652
3819
  _trace = new WeakMap();
2653
3820
  _insertRecordWithoutId = new WeakSet();
2654
3821
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2655
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2656
- const record = transformObjectLinks(object);
3822
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2657
3823
  const response = await insertRecord({
2658
3824
  pathParams: {
2659
3825
  workspace: "{workspaceId}",
@@ -2663,15 +3829,16 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2663
3829
  },
2664
3830
  queryParams: { columns },
2665
3831
  body: record,
2666
- ...fetchProps
3832
+ ...__privateGet$4(this, _getFetchProps).call(this)
2667
3833
  });
2668
3834
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2669
3835
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2670
3836
  };
2671
3837
  _insertRecordWithId = new WeakSet();
2672
3838
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2673
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2674
- const record = transformObjectLinks(object);
3839
+ if (!recordId)
3840
+ return null;
3841
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2675
3842
  const response = await insertRecordWithID({
2676
3843
  pathParams: {
2677
3844
  workspace: "{workspaceId}",
@@ -2682,30 +3849,28 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2682
3849
  },
2683
3850
  body: record,
2684
3851
  queryParams: { createOnly, columns, ifVersion },
2685
- ...fetchProps
3852
+ ...__privateGet$4(this, _getFetchProps).call(this)
2686
3853
  });
2687
3854
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2688
3855
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2689
3856
  };
2690
3857
  _insertRecords = new WeakSet();
2691
3858
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2692
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2693
- const chunkedOperations = chunk(
2694
- objects.map((object) => ({
2695
- insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2696
- })),
2697
- BULK_OPERATION_MAX_SIZE
2698
- );
3859
+ const operations = await promiseMap(objects, async (object) => {
3860
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3861
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
3862
+ });
3863
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2699
3864
  const ids = [];
2700
- for (const operations of chunkedOperations) {
3865
+ for (const operations2 of chunkedOperations) {
2701
3866
  const { results } = await branchTransaction({
2702
3867
  pathParams: {
2703
3868
  workspace: "{workspaceId}",
2704
3869
  dbBranchName: "{dbBranch}",
2705
3870
  region: "{region}"
2706
3871
  },
2707
- body: { operations },
2708
- ...fetchProps
3872
+ body: { operations: operations2 },
3873
+ ...__privateGet$4(this, _getFetchProps).call(this)
2709
3874
  });
2710
3875
  for (const result of results) {
2711
3876
  if (result.operation === "insert") {
@@ -2719,8 +3884,9 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2719
3884
  };
2720
3885
  _updateRecordWithID = new WeakSet();
2721
3886
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2722
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2723
- const { id: _id, ...record } = transformObjectLinks(object);
3887
+ if (!recordId)
3888
+ return null;
3889
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2724
3890
  try {
2725
3891
  const response = await updateRecordWithID({
2726
3892
  pathParams: {
@@ -2732,7 +3898,7 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2732
3898
  },
2733
3899
  queryParams: { columns, ifVersion },
2734
3900
  body: record,
2735
- ...fetchProps
3901
+ ...__privateGet$4(this, _getFetchProps).call(this)
2736
3902
  });
2737
3903
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2738
3904
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2745,23 +3911,21 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2745
3911
  };
2746
3912
  _updateRecords = new WeakSet();
2747
3913
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2748
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2749
- const chunkedOperations = chunk(
2750
- objects.map(({ id, ...object }) => ({
2751
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2752
- })),
2753
- BULK_OPERATION_MAX_SIZE
2754
- );
3914
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
3915
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3916
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
3917
+ });
3918
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2755
3919
  const ids = [];
2756
- for (const operations of chunkedOperations) {
3920
+ for (const operations2 of chunkedOperations) {
2757
3921
  const { results } = await branchTransaction({
2758
3922
  pathParams: {
2759
3923
  workspace: "{workspaceId}",
2760
3924
  dbBranchName: "{dbBranch}",
2761
3925
  region: "{region}"
2762
3926
  },
2763
- body: { operations },
2764
- ...fetchProps
3927
+ body: { operations: operations2 },
3928
+ ...__privateGet$4(this, _getFetchProps).call(this)
2765
3929
  });
2766
3930
  for (const result of results) {
2767
3931
  if (result.operation === "update") {
@@ -2775,7 +3939,8 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2775
3939
  };
2776
3940
  _upsertRecordWithID = new WeakSet();
2777
3941
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2778
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3942
+ if (!recordId)
3943
+ return null;
2779
3944
  const response = await upsertRecordWithID({
2780
3945
  pathParams: {
2781
3946
  workspace: "{workspaceId}",
@@ -2786,14 +3951,15 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2786
3951
  },
2787
3952
  queryParams: { columns, ifVersion },
2788
3953
  body: object,
2789
- ...fetchProps
3954
+ ...__privateGet$4(this, _getFetchProps).call(this)
2790
3955
  });
2791
3956
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2792
3957
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2793
3958
  };
2794
3959
  _deleteRecord = new WeakSet();
2795
3960
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
2796
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3961
+ if (!recordId)
3962
+ return null;
2797
3963
  try {
2798
3964
  const response = await deleteRecord({
2799
3965
  pathParams: {
@@ -2804,7 +3970,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2804
3970
  recordId
2805
3971
  },
2806
3972
  queryParams: { columns },
2807
- ...fetchProps
3973
+ ...__privateGet$4(this, _getFetchProps).call(this)
2808
3974
  });
2809
3975
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2810
3976
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2817,9 +3983,8 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2817
3983
  };
2818
3984
  _deleteRecords = new WeakSet();
2819
3985
  deleteRecords_fn = async function(recordIds) {
2820
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2821
3986
  const chunkedOperations = chunk(
2822
- recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
3987
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2823
3988
  BULK_OPERATION_MAX_SIZE
2824
3989
  );
2825
3990
  for (const operations of chunkedOperations) {
@@ -2830,21 +3995,22 @@ deleteRecords_fn = async function(recordIds) {
2830
3995
  region: "{region}"
2831
3996
  },
2832
3997
  body: { operations },
2833
- ...fetchProps
3998
+ ...__privateGet$4(this, _getFetchProps).call(this)
2834
3999
  });
2835
4000
  }
2836
4001
  };
2837
4002
  _setCacheQuery = new WeakSet();
2838
4003
  setCacheQuery_fn = async function(query, meta, records) {
2839
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
4004
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
2840
4005
  };
2841
4006
  _getCacheQuery = new WeakSet();
2842
4007
  getCacheQuery_fn = async function(query) {
2843
4008
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2844
- const result = await __privateGet$4(this, _cache).get(key);
4009
+ const result = await __privateGet$4(this, _cache)?.get(key);
2845
4010
  if (!result)
2846
4011
  return null;
2847
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
4012
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
4013
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2848
4014
  if (ttl < 0)
2849
4015
  return null;
2850
4016
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2854,15 +4020,46 @@ _getSchemaTables$1 = new WeakSet();
2854
4020
  getSchemaTables_fn$1 = async function() {
2855
4021
  if (__privateGet$4(this, _schemaTables$2))
2856
4022
  return __privateGet$4(this, _schemaTables$2);
2857
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2858
4023
  const { schema } = await getBranchDetails({
2859
4024
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2860
- ...fetchProps
4025
+ ...__privateGet$4(this, _getFetchProps).call(this)
2861
4026
  });
2862
4027
  __privateSet$4(this, _schemaTables$2, schema.tables);
2863
4028
  return schema.tables;
2864
4029
  };
2865
- const transformObjectLinks = (object) => {
4030
+ _transformObjectToApi = new WeakSet();
4031
+ transformObjectToApi_fn = async function(object) {
4032
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4033
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
4034
+ if (!schema)
4035
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
4036
+ const result = {};
4037
+ for (const [key, value] of Object.entries(object)) {
4038
+ if (key === "xata")
4039
+ continue;
4040
+ const type = schema.columns.find((column) => column.name === key)?.type;
4041
+ switch (type) {
4042
+ case "link": {
4043
+ result[key] = isIdentifiable(value) ? value.id : value;
4044
+ break;
4045
+ }
4046
+ case "datetime": {
4047
+ result[key] = value instanceof Date ? value.toISOString() : value;
4048
+ break;
4049
+ }
4050
+ case `file`:
4051
+ result[key] = await parseInputFileEntry(value);
4052
+ break;
4053
+ case "file[]":
4054
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4055
+ break;
4056
+ default:
4057
+ result[key] = value;
4058
+ }
4059
+ }
4060
+ return result;
4061
+ };
4062
+ const removeLinksFromObject = (object) => {
2866
4063
  return Object.entries(object).reduce((acc, [key, value]) => {
2867
4064
  if (key === "xata")
2868
4065
  return acc;
@@ -2911,6 +4108,12 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2911
4108
  }
2912
4109
  break;
2913
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;
2914
4117
  default:
2915
4118
  data[column.name] = value ?? null;
2916
4119
  if (column.notNull === true && value === null) {
@@ -2920,6 +4123,8 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2920
4123
  }
2921
4124
  }
2922
4125
  const record = { ...data };
4126
+ const serializable = { xata, ...removeLinksFromObject(data) };
4127
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
2923
4128
  record.read = function(columns2) {
2924
4129
  return db[table].read(record["id"], columns2);
2925
4130
  };
@@ -2936,13 +4141,17 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2936
4141
  record.delete = function() {
2937
4142
  return db[table].delete(record["id"]);
2938
4143
  };
4144
+ record.xata = Object.freeze(metadata);
2939
4145
  record.getMetadata = function() {
2940
- return xata;
4146
+ return record.xata;
4147
+ };
4148
+ record.toSerializable = function() {
4149
+ return JSON.parse(JSON.stringify(serializable));
2941
4150
  };
2942
- record.toJSON = function() {
2943
- return JSON.parse(JSON.stringify(transformObjectLinks(data)));
4151
+ record.toString = function() {
4152
+ return JSON.stringify(serializable);
2944
4153
  };
2945
- for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
4154
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
2946
4155
  Object.defineProperty(record, prop, { enumerable: false });
2947
4156
  }
2948
4157
  Object.freeze(record);
@@ -2958,11 +4167,7 @@ function extractId(value) {
2958
4167
  function isValidColumn(columns, column) {
2959
4168
  if (columns.includes("*"))
2960
4169
  return true;
2961
- if (column.type === "link") {
2962
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
2963
- return linkColumns.length > 0;
2964
- }
2965
- return columns.includes(column.name);
4170
+ return columns.filter((item) => item.startsWith(column.name)).length > 0;
2966
4171
  }
2967
4172
  function parseIfVersion(...args) {
2968
4173
  for (const arg of args) {
@@ -2973,6 +4178,12 @@ function parseIfVersion(...args) {
2973
4178
  return void 0;
2974
4179
  }
2975
4180
 
4181
+ var __defProp$3 = Object.defineProperty;
4182
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4183
+ var __publicField$3 = (obj, key, value) => {
4184
+ __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
4185
+ return value;
4186
+ };
2976
4187
  var __accessCheck$3 = (obj, member, msg) => {
2977
4188
  if (!member.has(obj))
2978
4189
  throw TypeError("Cannot " + msg);
@@ -2995,6 +4206,8 @@ var _map;
2995
4206
  class SimpleCache {
2996
4207
  constructor(options = {}) {
2997
4208
  __privateAdd$3(this, _map, void 0);
4209
+ __publicField$3(this, "capacity");
4210
+ __publicField$3(this, "defaultQueryTTL");
2998
4211
  __privateSet$3(this, _map, /* @__PURE__ */ new Map());
2999
4212
  this.capacity = options.max ?? 500;
3000
4213
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
@@ -3130,19 +4343,19 @@ class SearchPlugin extends XataPlugin {
3130
4343
  __privateAdd$1(this, _schemaTables, void 0);
3131
4344
  __privateSet$1(this, _schemaTables, schemaTables);
3132
4345
  }
3133
- build({ getFetchProps }) {
4346
+ build(pluginOptions) {
3134
4347
  return {
3135
4348
  all: async (query, options = {}) => {
3136
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3137
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
4349
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4350
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3138
4351
  return records.map((record) => {
3139
4352
  const { table = "orphan" } = record.xata;
3140
4353
  return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
3141
4354
  });
3142
4355
  },
3143
4356
  byTable: async (query, options = {}) => {
3144
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3145
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
4357
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4358
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3146
4359
  return records.reduce((acc, record) => {
3147
4360
  const { table = "orphan" } = record.xata;
3148
4361
  const items = acc[table] ?? [];
@@ -3155,38 +4368,36 @@ class SearchPlugin extends XataPlugin {
3155
4368
  }
3156
4369
  _schemaTables = new WeakMap();
3157
4370
  _search = new WeakSet();
3158
- search_fn = async function(query, options, getFetchProps) {
3159
- const fetchProps = await getFetchProps();
4371
+ search_fn = async function(query, options, pluginOptions) {
3160
4372
  const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3161
4373
  const { records } = await searchBranch({
3162
4374
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4375
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
3163
4376
  body: { tables, query, fuzziness, prefix, highlight, page },
3164
- ...fetchProps
4377
+ ...pluginOptions
3165
4378
  });
3166
4379
  return records;
3167
4380
  };
3168
4381
  _getSchemaTables = new WeakSet();
3169
- getSchemaTables_fn = async function(getFetchProps) {
4382
+ getSchemaTables_fn = async function(pluginOptions) {
3170
4383
  if (__privateGet$1(this, _schemaTables))
3171
4384
  return __privateGet$1(this, _schemaTables);
3172
- const fetchProps = await getFetchProps();
3173
4385
  const { schema } = await getBranchDetails({
3174
4386
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3175
- ...fetchProps
4387
+ ...pluginOptions
3176
4388
  });
3177
4389
  __privateSet$1(this, _schemaTables, schema.tables);
3178
4390
  return schema.tables;
3179
4391
  };
3180
4392
 
3181
4393
  class TransactionPlugin extends XataPlugin {
3182
- build({ getFetchProps }) {
4394
+ build(pluginOptions) {
3183
4395
  return {
3184
4396
  run: async (operations) => {
3185
- const fetchProps = await getFetchProps();
3186
4397
  const response = await branchTransaction({
3187
4398
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3188
4399
  body: { operations },
3189
- ...fetchProps
4400
+ ...pluginOptions
3190
4401
  });
3191
4402
  return response;
3192
4403
  }
@@ -3194,90 +4405,12 @@ class TransactionPlugin extends XataPlugin {
3194
4405
  }
3195
4406
  }
3196
4407
 
3197
- const isBranchStrategyBuilder = (strategy) => {
3198
- return typeof strategy === "function";
4408
+ var __defProp$2 = Object.defineProperty;
4409
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4410
+ var __publicField$2 = (obj, key, value) => {
4411
+ __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
4412
+ return value;
3199
4413
  };
3200
-
3201
- async function getCurrentBranchName(options) {
3202
- const { branch, envBranch } = getEnvironment();
3203
- if (branch)
3204
- return branch;
3205
- const gitBranch = envBranch || await getGitBranch();
3206
- return resolveXataBranch(gitBranch, options);
3207
- }
3208
- async function getCurrentBranchDetails(options) {
3209
- const branch = await getCurrentBranchName(options);
3210
- return getDatabaseBranch(branch, options);
3211
- }
3212
- async function resolveXataBranch(gitBranch, options) {
3213
- const databaseURL = options?.databaseURL || getDatabaseURL();
3214
- const apiKey = options?.apiKey || getAPIKey();
3215
- if (!databaseURL)
3216
- throw new Error(
3217
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3218
- );
3219
- if (!apiKey)
3220
- throw new Error(
3221
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3222
- );
3223
- const [protocol, , host, , dbName] = databaseURL.split("/");
3224
- const urlParts = parseWorkspacesUrlParts(host);
3225
- if (!urlParts)
3226
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3227
- const { workspace, region } = urlParts;
3228
- const { fallbackBranch } = getEnvironment();
3229
- const { branch } = await resolveBranch({
3230
- apiKey,
3231
- apiUrl: databaseURL,
3232
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3233
- workspacesApiUrl: `${protocol}//${host}`,
3234
- pathParams: { dbName, workspace, region },
3235
- queryParams: { gitBranch, fallbackBranch },
3236
- trace: defaultTrace,
3237
- clientName: options?.clientName
3238
- });
3239
- return branch;
3240
- }
3241
- async function getDatabaseBranch(branch, options) {
3242
- const databaseURL = options?.databaseURL || getDatabaseURL();
3243
- const apiKey = options?.apiKey || getAPIKey();
3244
- if (!databaseURL)
3245
- throw new Error(
3246
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3247
- );
3248
- if (!apiKey)
3249
- throw new Error(
3250
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3251
- );
3252
- const [protocol, , host, , database] = databaseURL.split("/");
3253
- const urlParts = parseWorkspacesUrlParts(host);
3254
- if (!urlParts)
3255
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3256
- const { workspace, region } = urlParts;
3257
- try {
3258
- return await getBranchDetails({
3259
- apiKey,
3260
- apiUrl: databaseURL,
3261
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3262
- workspacesApiUrl: `${protocol}//${host}`,
3263
- pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3264
- trace: defaultTrace
3265
- });
3266
- } catch (err) {
3267
- if (isObject(err) && err.status === 404)
3268
- return null;
3269
- throw err;
3270
- }
3271
- }
3272
- function getDatabaseURL() {
3273
- try {
3274
- const { databaseURL } = getEnvironment();
3275
- return databaseURL;
3276
- } catch (err) {
3277
- return void 0;
3278
- }
3279
- }
3280
-
3281
4414
  var __accessCheck = (obj, member, msg) => {
3282
4415
  if (!member.has(obj))
3283
4416
  throw TypeError("Cannot " + msg);
@@ -3301,48 +4434,45 @@ var __privateMethod = (obj, member, method) => {
3301
4434
  return method;
3302
4435
  };
3303
4436
  const buildClient = (plugins) => {
3304
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
4437
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3305
4438
  return _a = class {
3306
4439
  constructor(options = {}, schemaTables) {
3307
4440
  __privateAdd(this, _parseOptions);
3308
4441
  __privateAdd(this, _getFetchProps);
3309
- __privateAdd(this, _evaluateBranch);
3310
- __privateAdd(this, _branch, void 0);
3311
4442
  __privateAdd(this, _options, void 0);
4443
+ __publicField$2(this, "db");
4444
+ __publicField$2(this, "search");
4445
+ __publicField$2(this, "transactions");
4446
+ __publicField$2(this, "files");
3312
4447
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3313
4448
  __privateSet(this, _options, safeOptions);
3314
4449
  const pluginOptions = {
3315
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
4450
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3316
4451
  cache: safeOptions.cache,
3317
- trace: safeOptions.trace
4452
+ host: safeOptions.host
3318
4453
  };
3319
4454
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3320
4455
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3321
4456
  const transactions = new TransactionPlugin().build(pluginOptions);
4457
+ const files = new FilesPlugin().build(pluginOptions);
3322
4458
  this.db = db;
3323
4459
  this.search = search;
3324
4460
  this.transactions = transactions;
4461
+ this.files = files;
3325
4462
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3326
4463
  if (namespace === void 0)
3327
4464
  continue;
3328
- const result = namespace.build(pluginOptions);
3329
- if (result instanceof Promise) {
3330
- void result.then((namespace2) => {
3331
- this[key] = namespace2;
3332
- });
3333
- } else {
3334
- this[key] = result;
3335
- }
4465
+ this[key] = namespace.build(pluginOptions);
3336
4466
  }
3337
4467
  }
3338
4468
  async getConfig() {
3339
4469
  const databaseURL = __privateGet(this, _options).databaseURL;
3340
- const branch = await __privateGet(this, _options).branch();
4470
+ const branch = __privateGet(this, _options).branch;
3341
4471
  return { databaseURL, branch };
3342
4472
  }
3343
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4473
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3344
4474
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3345
- const isBrowser = typeof window !== "undefined";
4475
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3346
4476
  if (isBrowser && !enableBrowser) {
3347
4477
  throw new Error(
3348
4478
  "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."
@@ -3354,70 +4484,88 @@ const buildClient = (plugins) => {
3354
4484
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3355
4485
  const trace = options?.trace ?? defaultTrace;
3356
4486
  const clientName = options?.clientName;
3357
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({
3358
- apiKey,
3359
- databaseURL,
3360
- fetchImpl: options?.fetch,
3361
- clientName: options?.clientName
3362
- });
4487
+ const host = options?.host ?? "production";
4488
+ const xataAgentExtra = options?.xataAgentExtra;
3363
4489
  if (!apiKey) {
3364
4490
  throw new Error("Option apiKey is required");
3365
4491
  }
3366
4492
  if (!databaseURL) {
3367
4493
  throw new Error("Option databaseURL is required");
3368
4494
  }
3369
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser, clientName };
3370
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
4495
+ const envBranch = getBranch();
4496
+ const previewBranch = getPreviewBranch();
4497
+ const branch = options?.branch || previewBranch || envBranch || "main";
4498
+ if (!!previewBranch && branch !== previewBranch) {
4499
+ console.warn(
4500
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4501
+ );
4502
+ } else if (!!envBranch && branch !== envBranch) {
4503
+ console.warn(
4504
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4505
+ );
4506
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4507
+ console.warn(
4508
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4509
+ );
4510
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4511
+ console.warn(
4512
+ `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.`
4513
+ );
4514
+ }
4515
+ return {
4516
+ fetch,
4517
+ databaseURL,
4518
+ apiKey,
4519
+ branch,
4520
+ cache,
4521
+ trace,
4522
+ host,
4523
+ clientID: generateUUID(),
4524
+ enableBrowser,
4525
+ clientName,
4526
+ xataAgentExtra
4527
+ };
4528
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
3371
4529
  fetch,
3372
4530
  apiKey,
3373
4531
  databaseURL,
3374
4532
  branch,
3375
4533
  trace,
3376
4534
  clientID,
3377
- clientName
4535
+ clientName,
4536
+ xataAgentExtra
3378
4537
  }) {
3379
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3380
- if (!branchValue)
3381
- throw new Error("Unable to resolve branch value");
3382
4538
  return {
3383
- fetchImpl: fetch,
4539
+ fetch,
3384
4540
  apiKey,
3385
4541
  apiUrl: "",
4542
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3386
4543
  workspacesApiUrl: (path, params) => {
3387
4544
  const hasBranch = params.dbBranchName ?? params.branch;
3388
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
4545
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
3389
4546
  return databaseURL + newPath;
3390
4547
  },
3391
4548
  trace,
3392
4549
  clientID,
3393
- clientName
3394
- };
3395
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3396
- if (__privateGet(this, _branch))
3397
- return __privateGet(this, _branch);
3398
- if (param === void 0)
3399
- return void 0;
3400
- const strategies = Array.isArray(param) ? [...param] : [param];
3401
- const evaluateBranch = async (strategy) => {
3402
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
4550
+ clientName,
4551
+ xataAgentExtra
3403
4552
  };
3404
- for await (const strategy of strategies) {
3405
- const branch = await evaluateBranch(strategy);
3406
- if (branch) {
3407
- __privateSet(this, _branch, branch);
3408
- return branch;
3409
- }
3410
- }
3411
4553
  }, _a;
3412
4554
  };
3413
4555
  class BaseClient extends buildClient() {
3414
4556
  }
3415
4557
 
4558
+ var __defProp$1 = Object.defineProperty;
4559
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4560
+ var __publicField$1 = (obj, key, value) => {
4561
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
4562
+ return value;
4563
+ };
3416
4564
  const META = "__";
3417
4565
  const VALUE = "___";
3418
4566
  class Serializer {
3419
4567
  constructor() {
3420
- this.classes = {};
4568
+ __publicField$1(this, "classes", {});
3421
4569
  }
3422
4570
  add(clazz) {
3423
4571
  this.classes[clazz.name] = clazz;
@@ -3495,15 +4643,23 @@ function buildWorkerRunner(config) {
3495
4643
  };
3496
4644
  }
3497
4645
 
4646
+ var __defProp = Object.defineProperty;
4647
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4648
+ var __publicField = (obj, key, value) => {
4649
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4650
+ return value;
4651
+ };
3498
4652
  class XataError extends Error {
3499
4653
  constructor(message, status) {
3500
4654
  super(message);
4655
+ __publicField(this, "status");
3501
4656
  this.status = status;
3502
4657
  }
3503
4658
  }
3504
4659
 
3505
4660
  exports.BaseClient = BaseClient;
3506
4661
  exports.FetcherError = FetcherError;
4662
+ exports.FilesPlugin = FilesPlugin;
3507
4663
  exports.Operations = operationsByTag;
3508
4664
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
3509
4665
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -3512,6 +4668,7 @@ exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
3512
4668
  exports.Page = Page;
3513
4669
  exports.Query = Query;
3514
4670
  exports.RecordArray = RecordArray;
4671
+ exports.RecordColumnTypes = RecordColumnTypes;
3515
4672
  exports.Repository = Repository;
3516
4673
  exports.RestRepository = RestRepository;
3517
4674
  exports.SchemaPlugin = SchemaPlugin;
@@ -3521,14 +4678,19 @@ exports.SimpleCache = SimpleCache;
3521
4678
  exports.XataApiClient = XataApiClient;
3522
4679
  exports.XataApiPlugin = XataApiPlugin;
3523
4680
  exports.XataError = XataError;
4681
+ exports.XataFile = XataFile;
3524
4682
  exports.XataPlugin = XataPlugin;
3525
4683
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
3526
4684
  exports.addGitBranchesEntry = addGitBranchesEntry;
3527
4685
  exports.addTableColumn = addTableColumn;
3528
4686
  exports.aggregateTable = aggregateTable;
3529
4687
  exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
4688
+ exports.askTable = askTable;
4689
+ exports.askTableSession = askTableSession;
3530
4690
  exports.branchTransaction = branchTransaction;
3531
4691
  exports.buildClient = buildClient;
4692
+ exports.buildPreviewBranchName = buildPreviewBranchName;
4693
+ exports.buildProviderString = buildProviderString;
3532
4694
  exports.buildWorkerRunner = buildWorkerRunner;
3533
4695
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
3534
4696
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
@@ -3536,6 +4698,7 @@ exports.compareBranchSchemas = compareBranchSchemas;
3536
4698
  exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
3537
4699
  exports.compareMigrationRequest = compareMigrationRequest;
3538
4700
  exports.contains = contains;
4701
+ exports.copyBranch = copyBranch;
3539
4702
  exports.createBranch = createBranch;
3540
4703
  exports.createDatabase = createDatabase;
3541
4704
  exports.createMigrationRequest = createMigrationRequest;
@@ -3545,6 +4708,10 @@ exports.createWorkspace = createWorkspace;
3545
4708
  exports.deleteBranch = deleteBranch;
3546
4709
  exports.deleteColumn = deleteColumn;
3547
4710
  exports.deleteDatabase = deleteDatabase;
4711
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
4712
+ exports.deleteFile = deleteFile;
4713
+ exports.deleteFileItem = deleteFileItem;
4714
+ exports.deleteOAuthAccessToken = deleteOAuthAccessToken;
3548
4715
  exports.deleteRecord = deleteRecord;
3549
4716
  exports.deleteTable = deleteTable;
3550
4717
  exports.deleteUser = deleteUser;
@@ -3555,8 +4722,11 @@ exports.endsWith = endsWith;
3555
4722
  exports.equals = equals;
3556
4723
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
3557
4724
  exports.exists = exists;
4725
+ exports.fileAccess = fileAccess;
3558
4726
  exports.ge = ge;
3559
4727
  exports.getAPIKey = getAPIKey;
4728
+ exports.getAuthorizationCode = getAuthorizationCode;
4729
+ exports.getBranch = getBranch;
3560
4730
  exports.getBranchDetails = getBranchDetails;
3561
4731
  exports.getBranchList = getBranchList;
3562
4732
  exports.getBranchMetadata = getBranchMetadata;
@@ -3565,23 +4735,28 @@ exports.getBranchMigrationPlan = getBranchMigrationPlan;
3565
4735
  exports.getBranchSchemaHistory = getBranchSchemaHistory;
3566
4736
  exports.getBranchStats = getBranchStats;
3567
4737
  exports.getColumn = getColumn;
3568
- exports.getCurrentBranchDetails = getCurrentBranchDetails;
3569
- exports.getCurrentBranchName = getCurrentBranchName;
4738
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
3570
4739
  exports.getDatabaseList = getDatabaseList;
3571
4740
  exports.getDatabaseMetadata = getDatabaseMetadata;
3572
4741
  exports.getDatabaseURL = getDatabaseURL;
4742
+ exports.getFile = getFile;
4743
+ exports.getFileItem = getFileItem;
3573
4744
  exports.getGitBranchesMapping = getGitBranchesMapping;
3574
4745
  exports.getHostUrl = getHostUrl;
3575
4746
  exports.getMigrationRequest = getMigrationRequest;
3576
4747
  exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
4748
+ exports.getPreviewBranch = getPreviewBranch;
3577
4749
  exports.getRecord = getRecord;
3578
4750
  exports.getTableColumns = getTableColumns;
3579
4751
  exports.getTableSchema = getTableSchema;
3580
4752
  exports.getUser = getUser;
3581
4753
  exports.getUserAPIKeys = getUserAPIKeys;
4754
+ exports.getUserOAuthAccessTokens = getUserOAuthAccessTokens;
4755
+ exports.getUserOAuthClients = getUserOAuthClients;
3582
4756
  exports.getWorkspace = getWorkspace;
3583
4757
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
3584
4758
  exports.getWorkspacesList = getWorkspacesList;
4759
+ exports.grantAuthorizationCode = grantAuthorizationCode;
3585
4760
  exports.greaterEquals = greaterEquals;
3586
4761
  exports.greaterThan = greaterThan;
3587
4762
  exports.greaterThanEquals = greaterThanEquals;
@@ -3616,23 +4791,31 @@ exports.parseProviderString = parseProviderString;
3616
4791
  exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
3617
4792
  exports.pattern = pattern;
3618
4793
  exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
4794
+ exports.pushBranchMigrations = pushBranchMigrations;
4795
+ exports.putFile = putFile;
4796
+ exports.putFileItem = putFileItem;
3619
4797
  exports.queryMigrationRequests = queryMigrationRequests;
3620
4798
  exports.queryTable = queryTable;
3621
4799
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
3622
4800
  exports.removeWorkspaceMember = removeWorkspaceMember;
4801
+ exports.renameDatabase = renameDatabase;
3623
4802
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
3624
4803
  exports.resolveBranch = resolveBranch;
3625
4804
  exports.searchBranch = searchBranch;
3626
4805
  exports.searchTable = searchTable;
3627
4806
  exports.serialize = serialize;
3628
4807
  exports.setTableSchema = setTableSchema;
4808
+ exports.sqlQuery = sqlQuery;
3629
4809
  exports.startsWith = startsWith;
3630
4810
  exports.summarizeTable = summarizeTable;
4811
+ exports.transformImage = transformImage;
3631
4812
  exports.updateBranchMetadata = updateBranchMetadata;
3632
4813
  exports.updateBranchSchema = updateBranchSchema;
3633
4814
  exports.updateColumn = updateColumn;
4815
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
3634
4816
  exports.updateDatabaseMetadata = updateDatabaseMetadata;
3635
4817
  exports.updateMigrationRequest = updateMigrationRequest;
4818
+ exports.updateOAuthAccessToken = updateOAuthAccessToken;
3636
4819
  exports.updateRecordWithID = updateRecordWithID;
3637
4820
  exports.updateTable = updateTable;
3638
4821
  exports.updateUser = updateUser;
@@ -3640,4 +4823,5 @@ exports.updateWorkspace = updateWorkspace;
3640
4823
  exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
3641
4824
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
3642
4825
  exports.upsertRecordWithID = upsertRecordWithID;
4826
+ exports.vectorSearchTable = vectorSearchTable;
3643
4827
  //# sourceMappingURL=index.cjs.map