@xata.io/client 0.0.0-alpha.vf59e81b → 0.0.0-alpha.vf5a2120

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
@@ -20,7 +20,8 @@ const TraceAttributes = {
20
20
  HTTP_METHOD: "http.method",
21
21
  HTTP_URL: "http.url",
22
22
  HTTP_ROUTE: "http.route",
23
- HTTP_TARGET: "http.target"
23
+ HTTP_TARGET: "http.target",
24
+ CLOUDFLARE_RAY_ID: "cf.ray"
24
25
  };
25
26
 
26
27
  function notEmpty(value) {
@@ -29,8 +30,18 @@ function notEmpty(value) {
29
30
  function compact(arr) {
30
31
  return arr.filter(notEmpty);
31
32
  }
33
+ function compactObject(obj) {
34
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
35
+ }
36
+ function isBlob(value) {
37
+ try {
38
+ return value instanceof Blob;
39
+ } catch (error) {
40
+ return false;
41
+ }
42
+ }
32
43
  function isObject(value) {
33
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
44
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
34
45
  }
35
46
  function isDefined(value) {
36
47
  return value !== null && value !== void 0;
@@ -85,6 +96,27 @@ function chunk(array, chunkSize) {
85
96
  async function timeout(ms) {
86
97
  return new Promise((resolve) => setTimeout(resolve, ms));
87
98
  }
99
+ function timeoutWithCancel(ms) {
100
+ let timeoutId;
101
+ const promise = new Promise((resolve) => {
102
+ timeoutId = setTimeout(() => {
103
+ resolve();
104
+ }, ms);
105
+ });
106
+ return {
107
+ cancel: () => clearTimeout(timeoutId),
108
+ promise
109
+ };
110
+ }
111
+ function promiseMap(inputValues, mapper) {
112
+ const reducer = (acc$, inputValue) => acc$.then(
113
+ (acc) => mapper(inputValue).then((result) => {
114
+ acc.push(result);
115
+ return acc;
116
+ })
117
+ );
118
+ return inputValues.reduce(reducer, Promise.resolve([]));
119
+ }
88
120
 
89
121
  function getEnvironment() {
90
122
  try {
@@ -93,8 +125,10 @@ function getEnvironment() {
93
125
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
94
126
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
95
127
  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()
128
+ deployPreview: process.env.XATA_PREVIEW,
129
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
130
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
131
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
98
132
  };
99
133
  }
100
134
  } catch (err) {
@@ -105,8 +139,10 @@ function getEnvironment() {
105
139
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
106
140
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
107
141
  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()
142
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
143
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
144
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
145
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
110
146
  };
111
147
  }
112
148
  } catch (err) {
@@ -115,8 +151,10 @@ function getEnvironment() {
115
151
  apiKey: getGlobalApiKey(),
116
152
  databaseURL: getGlobalDatabaseURL(),
117
153
  branch: getGlobalBranch(),
118
- envBranch: void 0,
119
- fallbackBranch: getGlobalFallbackBranch()
154
+ deployPreview: void 0,
155
+ deployPreviewBranch: void 0,
156
+ vercelGitCommitRef: void 0,
157
+ vercelGitRepoOwner: void 0
120
158
  };
121
159
  }
122
160
  function getEnableBrowserVariable() {
@@ -159,13 +197,6 @@ function getGlobalBranch() {
159
197
  return void 0;
160
198
  }
161
199
  }
162
- function getGlobalFallbackBranch() {
163
- try {
164
- return XATA_FALLBACK_BRANCH;
165
- } catch (err) {
166
- return void 0;
167
- }
168
- }
169
200
  function getDatabaseURL() {
170
201
  try {
171
202
  const { databaseURL } = getEnvironment();
@@ -182,7 +213,43 @@ function getAPIKey() {
182
213
  return void 0;
183
214
  }
184
215
  }
216
+ function getBranch() {
217
+ try {
218
+ const { branch } = getEnvironment();
219
+ return branch;
220
+ } catch (err) {
221
+ return void 0;
222
+ }
223
+ }
224
+ function buildPreviewBranchName({ org, branch }) {
225
+ return `preview-${org}-${branch}`;
226
+ }
227
+ function getPreviewBranch() {
228
+ try {
229
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
230
+ if (deployPreviewBranch)
231
+ return deployPreviewBranch;
232
+ switch (deployPreview) {
233
+ case "vercel": {
234
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
235
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
236
+ return void 0;
237
+ }
238
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
239
+ }
240
+ }
241
+ return void 0;
242
+ } catch (err) {
243
+ return void 0;
244
+ }
245
+ }
185
246
 
247
+ var __defProp$8 = Object.defineProperty;
248
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
249
+ var __publicField$8 = (obj, key, value) => {
250
+ __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
251
+ return value;
252
+ };
186
253
  var __accessCheck$8 = (obj, member, msg) => {
187
254
  if (!member.has(obj))
188
255
  throw TypeError("Cannot " + msg);
@@ -206,13 +273,13 @@ var __privateMethod$4 = (obj, member, method) => {
206
273
  return method;
207
274
  };
208
275
  var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
276
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
209
277
  function getFetchImplementation(userFetch) {
210
278
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
211
- const fetchImpl = userFetch ?? globalFetch;
279
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
280
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
212
281
  if (!fetchImpl) {
213
- throw new Error(
214
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
215
- );
282
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
216
283
  }
217
284
  return fetchImpl;
218
285
  }
@@ -222,6 +289,8 @@ class ApiRequestPool {
222
289
  __privateAdd$8(this, _fetch, void 0);
223
290
  __privateAdd$8(this, _queue, void 0);
224
291
  __privateAdd$8(this, _concurrency, void 0);
292
+ __publicField$8(this, "running");
293
+ __publicField$8(this, "started");
225
294
  __privateSet$8(this, _queue, []);
226
295
  __privateSet$8(this, _concurrency, concurrency);
227
296
  this.running = 0;
@@ -237,18 +306,22 @@ class ApiRequestPool {
237
306
  return __privateGet$8(this, _fetch);
238
307
  }
239
308
  request(url, options) {
240
- const start = new Date();
241
- const fetch2 = this.getFetch();
309
+ const start = /* @__PURE__ */ new Date();
310
+ const fetchImpl = this.getFetch();
242
311
  const runRequest = async (stalled = false) => {
243
- const response = await fetch2(url, options);
312
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
313
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
314
+ if (!response) {
315
+ throw new Error("Request timed out");
316
+ }
244
317
  if (response.status === 429) {
245
318
  const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
246
319
  await timeout(rateLimitReset * 1e3);
247
320
  return await runRequest(true);
248
321
  }
249
322
  if (stalled) {
250
- const stalledTime = new Date().getTime() - start.getTime();
251
- console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
323
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
324
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
252
325
  }
253
326
  return response;
254
327
  };
@@ -290,16 +363,199 @@ function generateUUID() {
290
363
  });
291
364
  }
292
365
 
293
- const VERSION = "0.21.6";
366
+ async function getBytes(stream, onChunk) {
367
+ const reader = stream.getReader();
368
+ let result;
369
+ while (!(result = await reader.read()).done) {
370
+ onChunk(result.value);
371
+ }
372
+ }
373
+ function getLines(onLine) {
374
+ let buffer;
375
+ let position;
376
+ let fieldLength;
377
+ let discardTrailingNewline = false;
378
+ return function onChunk(arr) {
379
+ if (buffer === void 0) {
380
+ buffer = arr;
381
+ position = 0;
382
+ fieldLength = -1;
383
+ } else {
384
+ buffer = concat(buffer, arr);
385
+ }
386
+ const bufLength = buffer.length;
387
+ let lineStart = 0;
388
+ while (position < bufLength) {
389
+ if (discardTrailingNewline) {
390
+ if (buffer[position] === 10 /* NewLine */) {
391
+ lineStart = ++position;
392
+ }
393
+ discardTrailingNewline = false;
394
+ }
395
+ let lineEnd = -1;
396
+ for (; position < bufLength && lineEnd === -1; ++position) {
397
+ switch (buffer[position]) {
398
+ case 58 /* Colon */:
399
+ if (fieldLength === -1) {
400
+ fieldLength = position - lineStart;
401
+ }
402
+ break;
403
+ case 13 /* CarriageReturn */:
404
+ discardTrailingNewline = true;
405
+ case 10 /* NewLine */:
406
+ lineEnd = position;
407
+ break;
408
+ }
409
+ }
410
+ if (lineEnd === -1) {
411
+ break;
412
+ }
413
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
414
+ lineStart = position;
415
+ fieldLength = -1;
416
+ }
417
+ if (lineStart === bufLength) {
418
+ buffer = void 0;
419
+ } else if (lineStart !== 0) {
420
+ buffer = buffer.subarray(lineStart);
421
+ position -= lineStart;
422
+ }
423
+ };
424
+ }
425
+ function getMessages(onId, onRetry, onMessage) {
426
+ let message = newMessage();
427
+ const decoder = new TextDecoder();
428
+ return function onLine(line, fieldLength) {
429
+ if (line.length === 0) {
430
+ onMessage?.(message);
431
+ message = newMessage();
432
+ } else if (fieldLength > 0) {
433
+ const field = decoder.decode(line.subarray(0, fieldLength));
434
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
435
+ const value = decoder.decode(line.subarray(valueOffset));
436
+ switch (field) {
437
+ case "data":
438
+ message.data = message.data ? message.data + "\n" + value : value;
439
+ break;
440
+ case "event":
441
+ message.event = value;
442
+ break;
443
+ case "id":
444
+ onId(message.id = value);
445
+ break;
446
+ case "retry":
447
+ const retry = parseInt(value, 10);
448
+ if (!isNaN(retry)) {
449
+ onRetry(message.retry = retry);
450
+ }
451
+ break;
452
+ }
453
+ }
454
+ };
455
+ }
456
+ function concat(a, b) {
457
+ const res = new Uint8Array(a.length + b.length);
458
+ res.set(a);
459
+ res.set(b, a.length);
460
+ return res;
461
+ }
462
+ function newMessage() {
463
+ return {
464
+ data: "",
465
+ event: "",
466
+ id: "",
467
+ retry: void 0
468
+ };
469
+ }
470
+ const EventStreamContentType = "text/event-stream";
471
+ const LastEventId = "last-event-id";
472
+ function fetchEventSource(input, {
473
+ signal: inputSignal,
474
+ headers: inputHeaders,
475
+ onopen: inputOnOpen,
476
+ onmessage,
477
+ onclose,
478
+ onerror,
479
+ fetch: inputFetch,
480
+ ...rest
481
+ }) {
482
+ return new Promise((resolve, reject) => {
483
+ const headers = { ...inputHeaders };
484
+ if (!headers.accept) {
485
+ headers.accept = EventStreamContentType;
486
+ }
487
+ let curRequestController;
488
+ function dispose() {
489
+ curRequestController.abort();
490
+ }
491
+ inputSignal?.addEventListener("abort", () => {
492
+ dispose();
493
+ resolve();
494
+ });
495
+ const fetchImpl = inputFetch ?? fetch;
496
+ const onopen = inputOnOpen ?? defaultOnOpen;
497
+ async function create() {
498
+ curRequestController = new AbortController();
499
+ try {
500
+ const response = await fetchImpl(input, {
501
+ ...rest,
502
+ headers,
503
+ signal: curRequestController.signal
504
+ });
505
+ await onopen(response);
506
+ await getBytes(
507
+ response.body,
508
+ getLines(
509
+ getMessages(
510
+ (id) => {
511
+ if (id) {
512
+ headers[LastEventId] = id;
513
+ } else {
514
+ delete headers[LastEventId];
515
+ }
516
+ },
517
+ (_retry) => {
518
+ },
519
+ onmessage
520
+ )
521
+ )
522
+ );
523
+ onclose?.();
524
+ dispose();
525
+ resolve();
526
+ } catch (err) {
527
+ }
528
+ }
529
+ create();
530
+ });
531
+ }
532
+ function defaultOnOpen(response) {
533
+ const contentType = response.headers?.get("content-type");
534
+ if (!contentType?.startsWith(EventStreamContentType)) {
535
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
536
+ }
537
+ }
538
+
539
+ const VERSION = "0.26.5";
294
540
 
541
+ var __defProp$7 = Object.defineProperty;
542
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
543
+ var __publicField$7 = (obj, key, value) => {
544
+ __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
545
+ return value;
546
+ };
295
547
  class ErrorWithCause extends Error {
296
548
  constructor(message, options) {
297
549
  super(message, options);
550
+ __publicField$7(this, "cause");
298
551
  }
299
552
  }
300
553
  class FetcherError extends ErrorWithCause {
301
554
  constructor(status, data, requestId) {
302
555
  super(getMessage(data));
556
+ __publicField$7(this, "status");
557
+ __publicField$7(this, "requestId");
558
+ __publicField$7(this, "errors");
303
559
  this.status = status;
304
560
  this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
305
561
  this.requestId = requestId;
@@ -366,6 +622,18 @@ function hostHeader(url) {
366
622
  const { groups } = pattern.exec(url) ?? {};
367
623
  return groups?.host ? { Host: groups.host } : {};
368
624
  }
625
+ async function parseBody(body, headers) {
626
+ if (!isDefined(body))
627
+ return void 0;
628
+ if (isBlob(body) || typeof body.text === "function") {
629
+ return body;
630
+ }
631
+ const { "Content-Type": contentType } = headers ?? {};
632
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
633
+ return JSON.stringify(body);
634
+ }
635
+ return body;
636
+ }
369
637
  const defaultClientID = generateUUID();
370
638
  async function fetch$1({
371
639
  url: path,
@@ -374,7 +642,7 @@ async function fetch$1({
374
642
  headers: customHeaders,
375
643
  pathParams,
376
644
  queryParams,
377
- fetchImpl,
645
+ fetch: fetch2,
378
646
  apiKey,
379
647
  endpoint,
380
648
  apiUrl,
@@ -384,9 +652,11 @@ async function fetch$1({
384
652
  clientID,
385
653
  sessionID,
386
654
  clientName,
387
- fetchOptions = {}
655
+ xataAgentExtra,
656
+ fetchOptions = {},
657
+ rawResponse = false
388
658
  }) {
389
- pool.setFetch(fetchImpl);
659
+ pool.setFetch(fetch2);
390
660
  return await trace(
391
661
  `${method.toUpperCase()} ${path}`,
392
662
  async ({ setAttributes }) => {
@@ -400,9 +670,10 @@ async function fetch$1({
400
670
  const xataAgent = compact([
401
671
  ["client", "TS_SDK"],
402
672
  ["version", VERSION],
403
- isDefined(clientName) ? ["service", clientName] : void 0
673
+ isDefined(clientName) ? ["service", clientName] : void 0,
674
+ ...Object.entries(xataAgentExtra ?? {})
404
675
  ]).map(([key, value]) => `${key}=${value}`).join("; ");
405
- const headers = {
676
+ const headers = compactObject({
406
677
  "Accept-Encoding": "identity",
407
678
  "Content-Type": "application/json",
408
679
  "X-Xata-Client-ID": clientID ?? defaultClientID,
@@ -411,11 +682,11 @@ async function fetch$1({
411
682
  ...customHeaders,
412
683
  ...hostHeader(fullUrl),
413
684
  Authorization: `Bearer ${apiKey}`
414
- };
685
+ });
415
686
  const response = await pool.request(url, {
416
687
  ...fetchOptions,
417
688
  method: method.toUpperCase(),
418
- body: body ? JSON.stringify(body) : void 0,
689
+ body: await parseBody(body, headers),
419
690
  headers,
420
691
  signal
421
692
  });
@@ -426,8 +697,12 @@ async function fetch$1({
426
697
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
427
698
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
428
699
  [TraceAttributes.HTTP_HOST]: host,
429
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
700
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
701
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
430
702
  });
703
+ const message = response.headers?.get("x-xata-message");
704
+ if (message)
705
+ console.warn(message);
431
706
  if (response.status === 204) {
432
707
  return {};
433
708
  }
@@ -435,7 +710,7 @@ async function fetch$1({
435
710
  throw new FetcherError(response.status, "Rate limit exceeded", requestId);
436
711
  }
437
712
  try {
438
- const jsonResponse = await response.json();
713
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
439
714
  if (response.ok) {
440
715
  return jsonResponse;
441
716
  }
@@ -447,6 +722,59 @@ async function fetch$1({
447
722
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
448
723
  );
449
724
  }
725
+ function fetchSSERequest({
726
+ url: path,
727
+ method,
728
+ body,
729
+ headers: customHeaders,
730
+ pathParams,
731
+ queryParams,
732
+ fetch: fetch2,
733
+ apiKey,
734
+ endpoint,
735
+ apiUrl,
736
+ workspacesApiUrl,
737
+ onMessage,
738
+ onError,
739
+ onClose,
740
+ signal,
741
+ clientID,
742
+ sessionID,
743
+ clientName,
744
+ xataAgentExtra
745
+ }) {
746
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
747
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
748
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
749
+ void fetchEventSource(url, {
750
+ method,
751
+ body: JSON.stringify(body),
752
+ fetch: fetch2,
753
+ signal,
754
+ headers: {
755
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
756
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
757
+ "X-Xata-Agent": compact([
758
+ ["client", "TS_SDK"],
759
+ ["version", VERSION],
760
+ isDefined(clientName) ? ["service", clientName] : void 0,
761
+ ...Object.entries(xataAgentExtra ?? {})
762
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
763
+ ...customHeaders,
764
+ Authorization: `Bearer ${apiKey}`,
765
+ "Content-Type": "application/json"
766
+ },
767
+ onmessage(ev) {
768
+ onMessage?.(JSON.parse(ev.data));
769
+ },
770
+ onerror(ev) {
771
+ onError?.(JSON.parse(ev.data));
772
+ },
773
+ onclose() {
774
+ onClose?.();
775
+ }
776
+ });
777
+ }
450
778
  function parseUrl(url) {
451
779
  try {
452
780
  const { host, protocol } = new URL(url);
@@ -477,6 +805,12 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
477
805
  ...variables,
478
806
  signal
479
807
  });
808
+ const copyBranch = (variables, signal) => dataPlaneFetch({
809
+ url: "/db/{dbBranchName}/copy",
810
+ method: "post",
811
+ ...variables,
812
+ signal
813
+ });
480
814
  const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
481
815
  url: "/db/{dbBranchName}/metadata",
482
816
  method: "put",
@@ -526,6 +860,7 @@ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{
526
860
  const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
527
861
  const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
528
862
  const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
863
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
529
864
  const createTable = (variables, signal) => dataPlaneFetch({
530
865
  url: "/db/{dbBranchName}/tables/{tableName}",
531
866
  method: "put",
@@ -570,6 +905,42 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
570
905
  });
571
906
  const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
572
907
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
908
+ const getFileItem = (variables, signal) => dataPlaneFetch({
909
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
910
+ method: "get",
911
+ ...variables,
912
+ signal
913
+ });
914
+ const putFileItem = (variables, signal) => dataPlaneFetch({
915
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
916
+ method: "put",
917
+ ...variables,
918
+ signal
919
+ });
920
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
921
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
922
+ method: "delete",
923
+ ...variables,
924
+ signal
925
+ });
926
+ const getFile = (variables, signal) => dataPlaneFetch({
927
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
928
+ method: "get",
929
+ ...variables,
930
+ signal
931
+ });
932
+ const putFile = (variables, signal) => dataPlaneFetch({
933
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
934
+ method: "put",
935
+ ...variables,
936
+ signal
937
+ });
938
+ const deleteFile = (variables, signal) => dataPlaneFetch({
939
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
940
+ method: "delete",
941
+ ...variables,
942
+ signal
943
+ });
573
944
  const getRecord = (variables, signal) => dataPlaneFetch({
574
945
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
575
946
  method: "get",
@@ -599,14 +970,35 @@ const searchTable = (variables, signal) => dataPlaneFetch({
599
970
  ...variables,
600
971
  signal
601
972
  });
973
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
974
+ const askTable = (variables, signal) => dataPlaneFetch({
975
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
976
+ method: "post",
977
+ ...variables,
978
+ signal
979
+ });
980
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
602
981
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
603
982
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
983
+ const fileAccess = (variables, signal) => dataPlaneFetch({
984
+ url: "/file/{fileId}",
985
+ method: "get",
986
+ ...variables,
987
+ signal
988
+ });
989
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
990
+ url: "/db/{dbBranchName}/sql",
991
+ method: "post",
992
+ ...variables,
993
+ signal
994
+ });
604
995
  const operationsByTag$2 = {
605
996
  branch: {
606
997
  getBranchList,
607
998
  getBranchDetails,
608
999
  createBranch,
609
1000
  deleteBranch,
1001
+ copyBranch,
610
1002
  updateBranchMetadata,
611
1003
  getBranchMetadata,
612
1004
  getBranchStats,
@@ -624,7 +1016,8 @@ const operationsByTag$2 = {
624
1016
  compareBranchSchemas,
625
1017
  updateBranchSchema,
626
1018
  previewBranchSchemaEdit,
627
- applyBranchSchemaEdit
1019
+ applyBranchSchemaEdit,
1020
+ pushBranchMigrations
628
1021
  },
629
1022
  migrationRequests: {
630
1023
  queryMigrationRequests,
@@ -658,11 +1051,24 @@ const operationsByTag$2 = {
658
1051
  deleteRecord,
659
1052
  bulkInsertTableRecords
660
1053
  },
661
- searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
1054
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess },
1055
+ searchAndFilter: {
1056
+ queryTable,
1057
+ searchBranch,
1058
+ searchTable,
1059
+ vectorSearchTable,
1060
+ askTable,
1061
+ askTableSession,
1062
+ summarizeTable,
1063
+ aggregateTable
1064
+ },
1065
+ sql: { sqlQuery }
662
1066
  };
663
1067
 
664
1068
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
665
1069
 
1070
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1071
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
666
1072
  const getUser = (variables, signal) => controlPlaneFetch({
667
1073
  url: "/user",
668
1074
  method: "get",
@@ -699,6 +1105,31 @@ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
699
1105
  ...variables,
700
1106
  signal
701
1107
  });
1108
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1109
+ url: "/user/oauth/clients",
1110
+ method: "get",
1111
+ ...variables,
1112
+ signal
1113
+ });
1114
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1115
+ url: "/user/oauth/clients/{clientId}",
1116
+ method: "delete",
1117
+ ...variables,
1118
+ signal
1119
+ });
1120
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1121
+ url: "/user/oauth/tokens",
1122
+ method: "get",
1123
+ ...variables,
1124
+ signal
1125
+ });
1126
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1127
+ url: "/user/oauth/tokens/{token}",
1128
+ method: "delete",
1129
+ ...variables,
1130
+ signal
1131
+ });
1132
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
702
1133
  const getWorkspacesList = (variables, signal) => controlPlaneFetch({
703
1134
  url: "/workspaces",
704
1135
  method: "get",
@@ -757,6 +1188,10 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
757
1188
  });
758
1189
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
759
1190
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1191
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1192
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1193
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1194
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
760
1195
  const listRegions = (variables, signal) => controlPlaneFetch({
761
1196
  url: "/workspaces/{workspaceId}/regions",
762
1197
  method: "get",
@@ -764,6 +1199,15 @@ const listRegions = (variables, signal) => controlPlaneFetch({
764
1199
  signal
765
1200
  });
766
1201
  const operationsByTag$1 = {
1202
+ oAuth: {
1203
+ getAuthorizationCode,
1204
+ grantAuthorizationCode,
1205
+ getUserOAuthClients,
1206
+ deleteUserOAuthClient,
1207
+ getUserOAuthAccessTokens,
1208
+ deleteOAuthAccessToken,
1209
+ updateOAuthAccessToken
1210
+ },
767
1211
  users: { getUser, updateUser, deleteUser },
768
1212
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
769
1213
  workspaces: {
@@ -789,6 +1233,10 @@ const operationsByTag$1 = {
789
1233
  deleteDatabase,
790
1234
  getDatabaseMetadata,
791
1235
  updateDatabaseMetadata,
1236
+ renameDatabase,
1237
+ getDatabaseGithubSettings,
1238
+ updateDatabaseGithubSettings,
1239
+ deleteDatabaseGithubSettings,
792
1240
  listRegions
793
1241
  }
794
1242
  };
@@ -809,8 +1257,12 @@ const providers = {
809
1257
  workspaces: "https://{workspaceId}.{region}.xata.sh"
810
1258
  },
811
1259
  staging: {
812
- main: "https://staging.xatabase.co",
813
- workspaces: "https://{workspaceId}.staging.{region}.xatabase.co"
1260
+ main: "https://api.staging-xata.dev",
1261
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1262
+ },
1263
+ dev: {
1264
+ main: "https://api.dev-xata.dev",
1265
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
814
1266
  }
815
1267
  };
816
1268
  function isHostProviderAlias(alias) {
@@ -828,12 +1280,19 @@ function parseProviderString(provider = "production") {
828
1280
  return null;
829
1281
  return { main, workspaces };
830
1282
  }
1283
+ function buildProviderString(provider) {
1284
+ if (isHostProviderAlias(provider))
1285
+ return provider;
1286
+ return `${provider.main},${provider.workspaces}`;
1287
+ }
831
1288
  function parseWorkspacesUrlParts(url) {
832
1289
  if (!isString(url))
833
1290
  return null;
834
1291
  const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
835
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
836
- const match = url.match(regex) || url.match(regexStaging);
1292
+ const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1293
+ const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1294
+ const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1295
+ const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
837
1296
  if (!match)
838
1297
  return null;
839
1298
  return { workspace: match[1], region: match[2] };
@@ -872,10 +1331,11 @@ class XataApiClient {
872
1331
  __privateSet$7(this, _extraProps, {
873
1332
  apiUrl: getHostUrl(provider, "main"),
874
1333
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
875
- fetchImpl: getFetchImplementation(options.fetch),
1334
+ fetch: getFetchImplementation(options.fetch),
876
1335
  apiKey,
877
1336
  trace,
878
1337
  clientName: options.clientName,
1338
+ xataAgentExtra: options.xataAgentExtra,
879
1339
  clientID
880
1340
  });
881
1341
  }
@@ -929,6 +1389,11 @@ class XataApiClient {
929
1389
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
930
1390
  return __privateGet$7(this, _namespaces).records;
931
1391
  }
1392
+ get files() {
1393
+ if (!__privateGet$7(this, _namespaces).files)
1394
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1395
+ return __privateGet$7(this, _namespaces).files;
1396
+ }
932
1397
  get searchAndFilter() {
933
1398
  if (!__privateGet$7(this, _namespaces).searchAndFilter)
934
1399
  __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
@@ -1137,6 +1602,20 @@ class BranchApi {
1137
1602
  ...this.extraProps
1138
1603
  });
1139
1604
  }
1605
+ copyBranch({
1606
+ workspace,
1607
+ region,
1608
+ database,
1609
+ branch,
1610
+ destinationBranch,
1611
+ limit
1612
+ }) {
1613
+ return operationsByTag.branch.copyBranch({
1614
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1615
+ body: { destinationBranch, limit },
1616
+ ...this.extraProps
1617
+ });
1618
+ }
1140
1619
  updateBranchMetadata({
1141
1620
  workspace,
1142
1621
  region,
@@ -1492,6 +1971,164 @@ class RecordsApi {
1492
1971
  });
1493
1972
  }
1494
1973
  }
1974
+ class FilesApi {
1975
+ constructor(extraProps) {
1976
+ this.extraProps = extraProps;
1977
+ }
1978
+ getFileItem({
1979
+ workspace,
1980
+ region,
1981
+ database,
1982
+ branch,
1983
+ table,
1984
+ record,
1985
+ column,
1986
+ fileId
1987
+ }) {
1988
+ return operationsByTag.files.getFileItem({
1989
+ pathParams: {
1990
+ workspace,
1991
+ region,
1992
+ dbBranchName: `${database}:${branch}`,
1993
+ tableName: table,
1994
+ recordId: record,
1995
+ columnName: column,
1996
+ fileId
1997
+ },
1998
+ ...this.extraProps
1999
+ });
2000
+ }
2001
+ putFileItem({
2002
+ workspace,
2003
+ region,
2004
+ database,
2005
+ branch,
2006
+ table,
2007
+ record,
2008
+ column,
2009
+ fileId,
2010
+ file
2011
+ }) {
2012
+ return operationsByTag.files.putFileItem({
2013
+ pathParams: {
2014
+ workspace,
2015
+ region,
2016
+ dbBranchName: `${database}:${branch}`,
2017
+ tableName: table,
2018
+ recordId: record,
2019
+ columnName: column,
2020
+ fileId
2021
+ },
2022
+ // @ts-ignore
2023
+ body: file,
2024
+ ...this.extraProps
2025
+ });
2026
+ }
2027
+ deleteFileItem({
2028
+ workspace,
2029
+ region,
2030
+ database,
2031
+ branch,
2032
+ table,
2033
+ record,
2034
+ column,
2035
+ fileId
2036
+ }) {
2037
+ return operationsByTag.files.deleteFileItem({
2038
+ pathParams: {
2039
+ workspace,
2040
+ region,
2041
+ dbBranchName: `${database}:${branch}`,
2042
+ tableName: table,
2043
+ recordId: record,
2044
+ columnName: column,
2045
+ fileId
2046
+ },
2047
+ ...this.extraProps
2048
+ });
2049
+ }
2050
+ getFile({
2051
+ workspace,
2052
+ region,
2053
+ database,
2054
+ branch,
2055
+ table,
2056
+ record,
2057
+ column
2058
+ }) {
2059
+ return operationsByTag.files.getFile({
2060
+ pathParams: {
2061
+ workspace,
2062
+ region,
2063
+ dbBranchName: `${database}:${branch}`,
2064
+ tableName: table,
2065
+ recordId: record,
2066
+ columnName: column
2067
+ },
2068
+ ...this.extraProps
2069
+ });
2070
+ }
2071
+ putFile({
2072
+ workspace,
2073
+ region,
2074
+ database,
2075
+ branch,
2076
+ table,
2077
+ record,
2078
+ column,
2079
+ file
2080
+ }) {
2081
+ return operationsByTag.files.putFile({
2082
+ pathParams: {
2083
+ workspace,
2084
+ region,
2085
+ dbBranchName: `${database}:${branch}`,
2086
+ tableName: table,
2087
+ recordId: record,
2088
+ columnName: column
2089
+ },
2090
+ body: file,
2091
+ ...this.extraProps
2092
+ });
2093
+ }
2094
+ deleteFile({
2095
+ workspace,
2096
+ region,
2097
+ database,
2098
+ branch,
2099
+ table,
2100
+ record,
2101
+ column
2102
+ }) {
2103
+ return operationsByTag.files.deleteFile({
2104
+ pathParams: {
2105
+ workspace,
2106
+ region,
2107
+ dbBranchName: `${database}:${branch}`,
2108
+ tableName: table,
2109
+ recordId: record,
2110
+ columnName: column
2111
+ },
2112
+ ...this.extraProps
2113
+ });
2114
+ }
2115
+ fileAccess({
2116
+ workspace,
2117
+ region,
2118
+ fileId,
2119
+ verify
2120
+ }) {
2121
+ return operationsByTag.files.fileAccess({
2122
+ pathParams: {
2123
+ workspace,
2124
+ region,
2125
+ fileId
2126
+ },
2127
+ queryParams: { verify },
2128
+ ...this.extraProps
2129
+ });
2130
+ }
2131
+ }
1495
2132
  class SearchAndFilterApi {
1496
2133
  constructor(extraProps) {
1497
2134
  this.extraProps = extraProps;
@@ -1551,6 +2188,53 @@ class SearchAndFilterApi {
1551
2188
  ...this.extraProps
1552
2189
  });
1553
2190
  }
2191
+ vectorSearchTable({
2192
+ workspace,
2193
+ region,
2194
+ database,
2195
+ branch,
2196
+ table,
2197
+ queryVector,
2198
+ column,
2199
+ similarityFunction,
2200
+ size,
2201
+ filter
2202
+ }) {
2203
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2204
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2205
+ body: { queryVector, column, similarityFunction, size, filter },
2206
+ ...this.extraProps
2207
+ });
2208
+ }
2209
+ askTable({
2210
+ workspace,
2211
+ region,
2212
+ database,
2213
+ branch,
2214
+ table,
2215
+ options
2216
+ }) {
2217
+ return operationsByTag.searchAndFilter.askTable({
2218
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2219
+ body: { ...options },
2220
+ ...this.extraProps
2221
+ });
2222
+ }
2223
+ askTableSession({
2224
+ workspace,
2225
+ region,
2226
+ database,
2227
+ branch,
2228
+ table,
2229
+ sessionId,
2230
+ message
2231
+ }) {
2232
+ return operationsByTag.searchAndFilter.askTableSession({
2233
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2234
+ body: { message },
2235
+ ...this.extraProps
2236
+ });
2237
+ }
1554
2238
  summarizeTable({
1555
2239
  workspace,
1556
2240
  region,
@@ -1751,11 +2435,13 @@ class MigrationsApi {
1751
2435
  region,
1752
2436
  database,
1753
2437
  branch,
1754
- schema
2438
+ schema,
2439
+ schemaOperations,
2440
+ branchOperations
1755
2441
  }) {
1756
2442
  return operationsByTag.migrations.compareBranchWithUserSchema({
1757
2443
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1758
- body: { schema },
2444
+ body: { schema, schemaOperations, branchOperations },
1759
2445
  ...this.extraProps
1760
2446
  });
1761
2447
  }
@@ -1765,11 +2451,12 @@ class MigrationsApi {
1765
2451
  database,
1766
2452
  branch,
1767
2453
  compare,
1768
- schema
2454
+ sourceBranchOperations,
2455
+ targetBranchOperations
1769
2456
  }) {
1770
2457
  return operationsByTag.migrations.compareBranchSchemas({
1771
2458
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1772
- body: { schema },
2459
+ body: { sourceBranchOperations, targetBranchOperations },
1773
2460
  ...this.extraProps
1774
2461
  });
1775
2462
  }
@@ -1812,6 +2499,19 @@ class MigrationsApi {
1812
2499
  ...this.extraProps
1813
2500
  });
1814
2501
  }
2502
+ pushBranchMigrations({
2503
+ workspace,
2504
+ region,
2505
+ database,
2506
+ branch,
2507
+ migrations
2508
+ }) {
2509
+ return operationsByTag.migrations.pushBranchMigrations({
2510
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2511
+ body: { migrations },
2512
+ ...this.extraProps
2513
+ });
2514
+ }
1815
2515
  }
1816
2516
  class DatabaseApi {
1817
2517
  constructor(extraProps) {
@@ -1826,11 +2526,13 @@ class DatabaseApi {
1826
2526
  createDatabase({
1827
2527
  workspace,
1828
2528
  database,
1829
- data
2529
+ data,
2530
+ headers
1830
2531
  }) {
1831
2532
  return operationsByTag.databases.createDatabase({
1832
2533
  pathParams: { workspaceId: workspace, dbName: database },
1833
2534
  body: data,
2535
+ headers,
1834
2536
  ...this.extraProps
1835
2537
  });
1836
2538
  }
@@ -1863,6 +2565,46 @@ class DatabaseApi {
1863
2565
  ...this.extraProps
1864
2566
  });
1865
2567
  }
2568
+ renameDatabase({
2569
+ workspace,
2570
+ database,
2571
+ newName
2572
+ }) {
2573
+ return operationsByTag.databases.renameDatabase({
2574
+ pathParams: { workspaceId: workspace, dbName: database },
2575
+ body: { newName },
2576
+ ...this.extraProps
2577
+ });
2578
+ }
2579
+ getDatabaseGithubSettings({
2580
+ workspace,
2581
+ database
2582
+ }) {
2583
+ return operationsByTag.databases.getDatabaseGithubSettings({
2584
+ pathParams: { workspaceId: workspace, dbName: database },
2585
+ ...this.extraProps
2586
+ });
2587
+ }
2588
+ updateDatabaseGithubSettings({
2589
+ workspace,
2590
+ database,
2591
+ settings
2592
+ }) {
2593
+ return operationsByTag.databases.updateDatabaseGithubSettings({
2594
+ pathParams: { workspaceId: workspace, dbName: database },
2595
+ body: settings,
2596
+ ...this.extraProps
2597
+ });
2598
+ }
2599
+ deleteDatabaseGithubSettings({
2600
+ workspace,
2601
+ database
2602
+ }) {
2603
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
2604
+ pathParams: { workspaceId: workspace, dbName: database },
2605
+ ...this.extraProps
2606
+ });
2607
+ }
1866
2608
  listRegions({ workspace }) {
1867
2609
  return operationsByTag.databases.listRegions({
1868
2610
  pathParams: { workspaceId: workspace },
@@ -1873,21 +2615,326 @@ class DatabaseApi {
1873
2615
 
1874
2616
  class XataApiPlugin {
1875
2617
  build(options) {
1876
- const { fetchImpl, apiKey } = options.getFetchProps();
1877
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2618
+ return new XataApiClient(options);
1878
2619
  }
1879
2620
  }
1880
2621
 
1881
2622
  class XataPlugin {
1882
2623
  }
1883
2624
 
2625
+ class FilesPlugin extends XataPlugin {
2626
+ build(pluginOptions) {
2627
+ return {
2628
+ download: async (location) => {
2629
+ const { table, record, column, fileId = "" } = location ?? {};
2630
+ return await getFileItem({
2631
+ pathParams: {
2632
+ workspace: "{workspaceId}",
2633
+ dbBranchName: "{dbBranch}",
2634
+ region: "{region}",
2635
+ tableName: table ?? "",
2636
+ recordId: record ?? "",
2637
+ columnName: column ?? "",
2638
+ fileId
2639
+ },
2640
+ ...pluginOptions,
2641
+ rawResponse: true
2642
+ });
2643
+ },
2644
+ upload: async (location, file) => {
2645
+ const { table, record, column, fileId = "" } = location ?? {};
2646
+ const contentType = getContentType(file);
2647
+ return await putFileItem({
2648
+ ...pluginOptions,
2649
+ pathParams: {
2650
+ workspace: "{workspaceId}",
2651
+ dbBranchName: "{dbBranch}",
2652
+ region: "{region}",
2653
+ tableName: table ?? "",
2654
+ recordId: record ?? "",
2655
+ columnName: column ?? "",
2656
+ fileId
2657
+ },
2658
+ body: file,
2659
+ headers: { "Content-Type": contentType }
2660
+ });
2661
+ },
2662
+ delete: async (location) => {
2663
+ const { table, record, column, fileId = "" } = location ?? {};
2664
+ return await deleteFileItem({
2665
+ pathParams: {
2666
+ workspace: "{workspaceId}",
2667
+ dbBranchName: "{dbBranch}",
2668
+ region: "{region}",
2669
+ tableName: table ?? "",
2670
+ recordId: record ?? "",
2671
+ columnName: column ?? "",
2672
+ fileId
2673
+ },
2674
+ ...pluginOptions
2675
+ });
2676
+ }
2677
+ };
2678
+ }
2679
+ }
2680
+ function getContentType(file) {
2681
+ if (typeof file === "string") {
2682
+ return "text/plain";
2683
+ }
2684
+ if (isBlob(file)) {
2685
+ return file.type;
2686
+ }
2687
+ try {
2688
+ return file.type;
2689
+ } catch (e) {
2690
+ }
2691
+ return "application/octet-stream";
2692
+ }
2693
+
2694
+ function buildTransformString(transformations) {
2695
+ return transformations.flatMap(
2696
+ (t) => Object.entries(t).map(([key, value]) => {
2697
+ if (key === "trim") {
2698
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2699
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2700
+ }
2701
+ if (key === "gravity" && typeof value === "object") {
2702
+ const { x = 0.5, y = 0.5 } = value;
2703
+ return `${key}=${[x, y].join("x")}`;
2704
+ }
2705
+ return `${key}=${value}`;
2706
+ })
2707
+ ).join(",");
2708
+ }
2709
+ function transformImage(url, ...transformations) {
2710
+ if (!isDefined(url))
2711
+ return void 0;
2712
+ const newTransformations = buildTransformString(transformations);
2713
+ const { hostname, pathname, search } = new URL(url);
2714
+ const pathParts = pathname.split("/");
2715
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2716
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2717
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2718
+ const path = pathParts.join("/");
2719
+ return `https://${hostname}${transform}${path}${search}`;
2720
+ }
2721
+
2722
+ var __defProp$6 = Object.defineProperty;
2723
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2724
+ var __publicField$6 = (obj, key, value) => {
2725
+ __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
2726
+ return value;
2727
+ };
2728
+ class XataFile {
2729
+ constructor(file) {
2730
+ /**
2731
+ * Identifier of the file.
2732
+ */
2733
+ __publicField$6(this, "id");
2734
+ /**
2735
+ * Name of the file.
2736
+ */
2737
+ __publicField$6(this, "name");
2738
+ /**
2739
+ * Media type of the file.
2740
+ */
2741
+ __publicField$6(this, "mediaType");
2742
+ /**
2743
+ * Base64 encoded content of the file.
2744
+ */
2745
+ __publicField$6(this, "base64Content");
2746
+ /**
2747
+ * Whether to enable public url for the file.
2748
+ */
2749
+ __publicField$6(this, "enablePublicUrl");
2750
+ /**
2751
+ * Timeout for the signed url.
2752
+ */
2753
+ __publicField$6(this, "signedUrlTimeout");
2754
+ /**
2755
+ * Size of the file.
2756
+ */
2757
+ __publicField$6(this, "size");
2758
+ /**
2759
+ * Version of the file.
2760
+ */
2761
+ __publicField$6(this, "version");
2762
+ /**
2763
+ * Url of the file.
2764
+ */
2765
+ __publicField$6(this, "url");
2766
+ /**
2767
+ * Signed url of the file.
2768
+ */
2769
+ __publicField$6(this, "signedUrl");
2770
+ /**
2771
+ * Attributes of the file.
2772
+ */
2773
+ __publicField$6(this, "attributes");
2774
+ this.id = file.id;
2775
+ this.name = file.name || "";
2776
+ this.mediaType = file.mediaType || "application/octet-stream";
2777
+ this.base64Content = file.base64Content;
2778
+ this.enablePublicUrl = file.enablePublicUrl ?? false;
2779
+ this.signedUrlTimeout = file.signedUrlTimeout ?? 300;
2780
+ this.size = file.size ?? 0;
2781
+ this.version = file.version ?? 1;
2782
+ this.url = file.url || "";
2783
+ this.signedUrl = file.signedUrl;
2784
+ this.attributes = file.attributes || {};
2785
+ }
2786
+ static fromBuffer(buffer, options = {}) {
2787
+ const base64Content = buffer.toString("base64");
2788
+ return new XataFile({ ...options, base64Content });
2789
+ }
2790
+ toBuffer() {
2791
+ if (!this.base64Content) {
2792
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2793
+ }
2794
+ return Buffer.from(this.base64Content, "base64");
2795
+ }
2796
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2797
+ const uint8Array = new Uint8Array(arrayBuffer);
2798
+ return this.fromUint8Array(uint8Array, options);
2799
+ }
2800
+ toArrayBuffer() {
2801
+ if (!this.base64Content) {
2802
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2803
+ }
2804
+ const binary = atob(this.base64Content);
2805
+ return new ArrayBuffer(binary.length);
2806
+ }
2807
+ static fromUint8Array(uint8Array, options = {}) {
2808
+ let binary = "";
2809
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2810
+ binary += String.fromCharCode(uint8Array[i]);
2811
+ }
2812
+ const base64Content = btoa(binary);
2813
+ return new XataFile({ ...options, base64Content });
2814
+ }
2815
+ toUint8Array() {
2816
+ if (!this.base64Content) {
2817
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2818
+ }
2819
+ const binary = atob(this.base64Content);
2820
+ const uint8Array = new Uint8Array(binary.length);
2821
+ for (let i = 0; i < binary.length; i++) {
2822
+ uint8Array[i] = binary.charCodeAt(i);
2823
+ }
2824
+ return uint8Array;
2825
+ }
2826
+ static async fromBlob(file, options = {}) {
2827
+ const name = options.name ?? file.name;
2828
+ const mediaType = file.type;
2829
+ const arrayBuffer = await file.arrayBuffer();
2830
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2831
+ }
2832
+ toBlob() {
2833
+ if (!this.base64Content) {
2834
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2835
+ }
2836
+ const binary = atob(this.base64Content);
2837
+ const uint8Array = new Uint8Array(binary.length);
2838
+ for (let i = 0; i < binary.length; i++) {
2839
+ uint8Array[i] = binary.charCodeAt(i);
2840
+ }
2841
+ return new Blob([uint8Array], { type: this.mediaType });
2842
+ }
2843
+ static fromString(string, options = {}) {
2844
+ const base64Content = btoa(string);
2845
+ return new XataFile({ ...options, base64Content });
2846
+ }
2847
+ toString() {
2848
+ if (!this.base64Content) {
2849
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2850
+ }
2851
+ return atob(this.base64Content);
2852
+ }
2853
+ static fromBase64(base64Content, options = {}) {
2854
+ return new XataFile({ ...options, base64Content });
2855
+ }
2856
+ toBase64() {
2857
+ if (!this.base64Content) {
2858
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2859
+ }
2860
+ return this.base64Content;
2861
+ }
2862
+ transform(...options) {
2863
+ return {
2864
+ url: transformImage(this.url, ...options),
2865
+ signedUrl: transformImage(this.signedUrl, ...options),
2866
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2867
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2868
+ };
2869
+ }
2870
+ }
2871
+ const parseInputFileEntry = async (entry) => {
2872
+ if (!isDefined(entry))
2873
+ return null;
2874
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout } = await entry;
2875
+ return compactObject({
2876
+ id,
2877
+ // Name cannot be an empty string in our API
2878
+ name: name ? name : void 0,
2879
+ mediaType,
2880
+ base64Content,
2881
+ enablePublicUrl,
2882
+ signedUrlTimeout
2883
+ });
2884
+ };
2885
+
1884
2886
  function cleanFilter(filter) {
1885
- if (!filter)
2887
+ if (!isDefined(filter))
1886
2888
  return void 0;
1887
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1888
- return values.length > 0 ? filter : void 0;
2889
+ if (!isObject(filter))
2890
+ return filter;
2891
+ const values = Object.fromEntries(
2892
+ Object.entries(filter).reduce((acc, [key, value]) => {
2893
+ if (!isDefined(value))
2894
+ return acc;
2895
+ if (Array.isArray(value)) {
2896
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2897
+ if (clean.length === 0)
2898
+ return acc;
2899
+ return [...acc, [key, clean]];
2900
+ }
2901
+ if (isObject(value)) {
2902
+ const clean = cleanFilter(value);
2903
+ if (!isDefined(clean))
2904
+ return acc;
2905
+ return [...acc, [key, clean]];
2906
+ }
2907
+ return [...acc, [key, value]];
2908
+ }, [])
2909
+ );
2910
+ return Object.keys(values).length > 0 ? values : void 0;
2911
+ }
2912
+
2913
+ function stringifyJson(value) {
2914
+ if (!isDefined(value))
2915
+ return value;
2916
+ if (isString(value))
2917
+ return value;
2918
+ try {
2919
+ return JSON.stringify(value);
2920
+ } catch (e) {
2921
+ return value;
2922
+ }
2923
+ }
2924
+ function parseJson(value) {
2925
+ try {
2926
+ return JSON.parse(value);
2927
+ } catch (e) {
2928
+ return value;
2929
+ }
1889
2930
  }
1890
2931
 
2932
+ var __defProp$5 = Object.defineProperty;
2933
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2934
+ var __publicField$5 = (obj, key, value) => {
2935
+ __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
2936
+ return value;
2937
+ };
1891
2938
  var __accessCheck$6 = (obj, member, msg) => {
1892
2939
  if (!member.has(obj))
1893
2940
  throw TypeError("Cannot " + msg);
@@ -1910,22 +2957,58 @@ var _query, _page;
1910
2957
  class Page {
1911
2958
  constructor(query, meta, records = []) {
1912
2959
  __privateAdd$6(this, _query, void 0);
2960
+ /**
2961
+ * Page metadata, required to retrieve additional records.
2962
+ */
2963
+ __publicField$5(this, "meta");
2964
+ /**
2965
+ * The set of results for this page.
2966
+ */
2967
+ __publicField$5(this, "records");
1913
2968
  __privateSet$6(this, _query, query);
1914
2969
  this.meta = meta;
1915
2970
  this.records = new RecordArray(this, records);
1916
2971
  }
2972
+ /**
2973
+ * Retrieves the next page of results.
2974
+ * @param size Maximum number of results to be retrieved.
2975
+ * @param offset Number of results to skip when retrieving the results.
2976
+ * @returns The next page or results.
2977
+ */
1917
2978
  async nextPage(size, offset) {
1918
2979
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
1919
2980
  }
2981
+ /**
2982
+ * Retrieves the previous page of results.
2983
+ * @param size Maximum number of results to be retrieved.
2984
+ * @param offset Number of results to skip when retrieving the results.
2985
+ * @returns The previous page or results.
2986
+ */
1920
2987
  async previousPage(size, offset) {
1921
2988
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1922
2989
  }
2990
+ /**
2991
+ * Retrieves the start page of results.
2992
+ * @param size Maximum number of results to be retrieved.
2993
+ * @param offset Number of results to skip when retrieving the results.
2994
+ * @returns The start page or results.
2995
+ */
1923
2996
  async startPage(size, offset) {
1924
2997
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1925
2998
  }
2999
+ /**
3000
+ * Retrieves the end page of results.
3001
+ * @param size Maximum number of results to be retrieved.
3002
+ * @param offset Number of results to skip when retrieving the results.
3003
+ * @returns The end page or results.
3004
+ */
1926
3005
  async endPage(size, offset) {
1927
3006
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1928
3007
  }
3008
+ /**
3009
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
3010
+ * @returns Whether or not there will be additional results in the next page of results.
3011
+ */
1929
3012
  hasNextPage() {
1930
3013
  return this.meta.page.more;
1931
3014
  }
@@ -1938,7 +3021,7 @@ const PAGINATION_DEFAULT_OFFSET = 0;
1938
3021
  function isCursorPaginationOptions(options) {
1939
3022
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1940
3023
  }
1941
- const _RecordArray = class extends Array {
3024
+ const _RecordArray = class _RecordArray extends Array {
1942
3025
  constructor(...args) {
1943
3026
  super(..._RecordArray.parseConstructorParams(...args));
1944
3027
  __privateAdd$6(this, _page, void 0);
@@ -1966,29 +3049,58 @@ const _RecordArray = class extends Array {
1966
3049
  map(callbackfn, thisArg) {
1967
3050
  return this.toArray().map(callbackfn, thisArg);
1968
3051
  }
3052
+ /**
3053
+ * Retrieve next page of records
3054
+ *
3055
+ * @returns A new array of objects
3056
+ */
1969
3057
  async nextPage(size, offset) {
1970
3058
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1971
3059
  return new _RecordArray(newPage);
1972
3060
  }
3061
+ /**
3062
+ * Retrieve previous page of records
3063
+ *
3064
+ * @returns A new array of objects
3065
+ */
1973
3066
  async previousPage(size, offset) {
1974
3067
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1975
3068
  return new _RecordArray(newPage);
1976
3069
  }
3070
+ /**
3071
+ * Retrieve start page of records
3072
+ *
3073
+ * @returns A new array of objects
3074
+ */
1977
3075
  async startPage(size, offset) {
1978
3076
  const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1979
3077
  return new _RecordArray(newPage);
1980
3078
  }
3079
+ /**
3080
+ * Retrieve end page of records
3081
+ *
3082
+ * @returns A new array of objects
3083
+ */
1981
3084
  async endPage(size, offset) {
1982
3085
  const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1983
3086
  return new _RecordArray(newPage);
1984
3087
  }
3088
+ /**
3089
+ * @returns Boolean indicating if there is a next page
3090
+ */
1985
3091
  hasNextPage() {
1986
3092
  return __privateGet$6(this, _page).meta.page.more;
1987
3093
  }
1988
3094
  };
1989
- let RecordArray = _RecordArray;
1990
3095
  _page = new WeakMap();
3096
+ let RecordArray = _RecordArray;
1991
3097
 
3098
+ var __defProp$4 = Object.defineProperty;
3099
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3100
+ var __publicField$4 = (obj, key, value) => {
3101
+ __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
3102
+ return value;
3103
+ };
1992
3104
  var __accessCheck$5 = (obj, member, msg) => {
1993
3105
  if (!member.has(obj))
1994
3106
  throw TypeError("Cannot " + msg);
@@ -2012,14 +3124,15 @@ var __privateMethod$3 = (obj, member, method) => {
2012
3124
  return method;
2013
3125
  };
2014
3126
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
2015
- const _Query = class {
3127
+ const _Query = class _Query {
2016
3128
  constructor(repository, table, data, rawParent) {
2017
3129
  __privateAdd$5(this, _cleanFilterConstraint);
2018
3130
  __privateAdd$5(this, _table$1, void 0);
2019
3131
  __privateAdd$5(this, _repository, void 0);
2020
3132
  __privateAdd$5(this, _data, { filter: {} });
2021
- this.meta = { page: { cursor: "start", more: true } };
2022
- this.records = new RecordArray(this, []);
3133
+ // Implements pagination
3134
+ __publicField$4(this, "meta", { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } });
3135
+ __publicField$4(this, "records", new RecordArray(this, []));
2023
3136
  __privateSet$5(this, _table$1, table);
2024
3137
  if (repository) {
2025
3138
  __privateSet$5(this, _repository, repository);
@@ -2055,18 +3168,38 @@ const _Query = class {
2055
3168
  const key = JSON.stringify({ columns, filter, sort, pagination });
2056
3169
  return toBase64(key);
2057
3170
  }
3171
+ /**
3172
+ * Builds a new query object representing a logical OR between the given subqueries.
3173
+ * @param queries An array of subqueries.
3174
+ * @returns A new Query object.
3175
+ */
2058
3176
  any(...queries) {
2059
3177
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
2060
3178
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
2061
3179
  }
3180
+ /**
3181
+ * Builds a new query object representing a logical AND between the given subqueries.
3182
+ * @param queries An array of subqueries.
3183
+ * @returns A new Query object.
3184
+ */
2062
3185
  all(...queries) {
2063
3186
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
2064
3187
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
2065
3188
  }
3189
+ /**
3190
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3191
+ * @param queries An array of subqueries.
3192
+ * @returns A new Query object.
3193
+ */
2066
3194
  not(...queries) {
2067
3195
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
2068
3196
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
2069
3197
  }
3198
+ /**
3199
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3200
+ * @param queries An array of subqueries.
3201
+ * @returns A new Query object.
3202
+ */
2070
3203
  none(...queries) {
2071
3204
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
2072
3205
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
@@ -2089,6 +3222,11 @@ const _Query = class {
2089
3222
  const sort = [...originalSort, { column, direction }];
2090
3223
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
2091
3224
  }
3225
+ /**
3226
+ * Builds a new query specifying the set of columns to be returned in the query response.
3227
+ * @param columns Array of column names to be returned by the query.
3228
+ * @returns A new Query object.
3229
+ */
2092
3230
  select(columns) {
2093
3231
  return new _Query(
2094
3232
  __privateGet$5(this, _repository),
@@ -2101,6 +3239,12 @@ const _Query = class {
2101
3239
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
2102
3240
  return __privateGet$5(this, _repository).query(query);
2103
3241
  }
3242
+ /**
3243
+ * Get results in an iterator
3244
+ *
3245
+ * @async
3246
+ * @returns Async interable of results
3247
+ */
2104
3248
  async *[Symbol.asyncIterator]() {
2105
3249
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
2106
3250
  yield record;
@@ -2161,26 +3305,53 @@ const _Query = class {
2161
3305
  );
2162
3306
  return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2163
3307
  }
3308
+ /**
3309
+ * Builds a new query object adding a cache TTL in milliseconds.
3310
+ * @param ttl The cache TTL in milliseconds.
3311
+ * @returns A new Query object.
3312
+ */
2164
3313
  cache(ttl) {
2165
3314
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2166
3315
  }
3316
+ /**
3317
+ * Retrieve next page of records
3318
+ *
3319
+ * @returns A new page object.
3320
+ */
2167
3321
  nextPage(size, offset) {
2168
3322
  return this.startPage(size, offset);
2169
3323
  }
3324
+ /**
3325
+ * Retrieve previous page of records
3326
+ *
3327
+ * @returns A new page object
3328
+ */
2170
3329
  previousPage(size, offset) {
2171
3330
  return this.startPage(size, offset);
2172
3331
  }
3332
+ /**
3333
+ * Retrieve start page of records
3334
+ *
3335
+ * @returns A new page object
3336
+ */
2173
3337
  startPage(size, offset) {
2174
3338
  return this.getPaginated({ pagination: { size, offset } });
2175
3339
  }
3340
+ /**
3341
+ * Retrieve last page of records
3342
+ *
3343
+ * @returns A new page object
3344
+ */
2176
3345
  endPage(size, offset) {
2177
3346
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2178
3347
  }
3348
+ /**
3349
+ * @returns Boolean indicating if there is a next page
3350
+ */
2179
3351
  hasNextPage() {
2180
3352
  return this.meta.page.more;
2181
3353
  }
2182
3354
  };
2183
- let Query = _Query;
2184
3355
  _table$1 = new WeakMap();
2185
3356
  _repository = new WeakMap();
2186
3357
  _data = new WeakMap();
@@ -2195,6 +3366,7 @@ cleanFilterConstraint_fn = function(column, value) {
2195
3366
  }
2196
3367
  return value;
2197
3368
  };
3369
+ let Query = _Query;
2198
3370
  function cleanParent(data, parent) {
2199
3371
  if (isCursorPaginationOptions(data.pagination)) {
2200
3372
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2202,6 +3374,22 @@ function cleanParent(data, parent) {
2202
3374
  return parent;
2203
3375
  }
2204
3376
 
3377
+ const RecordColumnTypes = [
3378
+ "bool",
3379
+ "int",
3380
+ "float",
3381
+ "string",
3382
+ "text",
3383
+ "email",
3384
+ "multiple",
3385
+ "link",
3386
+ "object",
3387
+ "datetime",
3388
+ "vector",
3389
+ "file[]",
3390
+ "file",
3391
+ "json"
3392
+ ];
2205
3393
  function isIdentifiable(x) {
2206
3394
  return isObject(x) && isString(x?.id);
2207
3395
  }
@@ -2211,11 +3399,33 @@ function isXataRecord(x) {
2211
3399
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
2212
3400
  }
2213
3401
 
3402
+ function isValidExpandedColumn(column) {
3403
+ return isObject(column) && isString(column.name);
3404
+ }
3405
+ function isValidSelectableColumns(columns) {
3406
+ if (!Array.isArray(columns)) {
3407
+ return false;
3408
+ }
3409
+ return columns.every((column) => {
3410
+ if (typeof column === "string") {
3411
+ return true;
3412
+ }
3413
+ if (typeof column === "object") {
3414
+ return isValidExpandedColumn(column);
3415
+ }
3416
+ return false;
3417
+ });
3418
+ }
3419
+
2214
3420
  function isSortFilterString(value) {
2215
3421
  return isString(value);
2216
3422
  }
2217
3423
  function isSortFilterBase(filter) {
2218
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
3424
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
3425
+ if (key === "*")
3426
+ return value === "random";
3427
+ return value === "asc" || value === "desc";
3428
+ });
2219
3429
  }
2220
3430
  function isSortFilterObject(filter) {
2221
3431
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -2256,7 +3466,7 @@ var __privateMethod$2 = (obj, member, method) => {
2256
3466
  __accessCheck$4(obj, member, "access private method");
2257
3467
  return method;
2258
3468
  };
2259
- 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;
3469
+ 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;
2260
3470
  const BULK_OPERATION_MAX_SIZE = 1e3;
2261
3471
  class Repository extends Query {
2262
3472
  }
@@ -2278,6 +3488,7 @@ class RestRepository extends Query {
2278
3488
  __privateAdd$4(this, _setCacheQuery);
2279
3489
  __privateAdd$4(this, _getCacheQuery);
2280
3490
  __privateAdd$4(this, _getSchemaTables$1);
3491
+ __privateAdd$4(this, _transformObjectToApi);
2281
3492
  __privateAdd$4(this, _table, void 0);
2282
3493
  __privateAdd$4(this, _getFetchProps, void 0);
2283
3494
  __privateAdd$4(this, _db, void 0);
@@ -2288,10 +3499,7 @@ class RestRepository extends Query {
2288
3499
  __privateSet$4(this, _db, options.db);
2289
3500
  __privateSet$4(this, _cache, options.pluginOptions.cache);
2290
3501
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2291
- __privateSet$4(this, _getFetchProps, async () => {
2292
- const props = await options.pluginOptions.getFetchProps();
2293
- return { ...props, sessionID: generateUUID() };
2294
- });
3502
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2295
3503
  const trace = options.pluginOptions.trace ?? defaultTrace;
2296
3504
  __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2297
3505
  return trace(name, fn, {
@@ -2309,24 +3517,24 @@ class RestRepository extends Query {
2309
3517
  if (a.length === 0)
2310
3518
  return [];
2311
3519
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2312
- const columns = isStringArray(b) ? b : ["*"];
3520
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2313
3521
  const result = await this.read(ids, columns);
2314
3522
  return result;
2315
3523
  }
2316
3524
  if (isString(a) && isObject(b)) {
2317
3525
  if (a === "")
2318
3526
  throw new Error("The id can't be empty");
2319
- const columns = isStringArray(c) ? c : void 0;
3527
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2320
3528
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2321
3529
  }
2322
3530
  if (isObject(a) && isString(a.id)) {
2323
3531
  if (a.id === "")
2324
3532
  throw new Error("The id can't be empty");
2325
- const columns = isStringArray(b) ? b : void 0;
3533
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2326
3534
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2327
3535
  }
2328
3536
  if (isObject(a)) {
2329
- const columns = isStringArray(b) ? b : void 0;
3537
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2330
3538
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2331
3539
  }
2332
3540
  throw new Error("Invalid arguments for create method");
@@ -2334,7 +3542,7 @@ class RestRepository extends Query {
2334
3542
  }
2335
3543
  async read(a, b) {
2336
3544
  return __privateGet$4(this, _trace).call(this, "read", async () => {
2337
- const columns = isStringArray(b) ? b : ["*"];
3545
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2338
3546
  if (Array.isArray(a)) {
2339
3547
  if (a.length === 0)
2340
3548
  return [];
@@ -2348,7 +3556,6 @@ class RestRepository extends Query {
2348
3556
  }
2349
3557
  const id = extractId(a);
2350
3558
  if (id) {
2351
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2352
3559
  try {
2353
3560
  const response = await getRecord({
2354
3561
  pathParams: {
@@ -2359,10 +3566,16 @@ class RestRepository extends Query {
2359
3566
  recordId: id
2360
3567
  },
2361
3568
  queryParams: { columns },
2362
- ...fetchProps
3569
+ ...__privateGet$4(this, _getFetchProps).call(this)
2363
3570
  });
2364
3571
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2365
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3572
+ return initObject(
3573
+ __privateGet$4(this, _db),
3574
+ schemaTables,
3575
+ __privateGet$4(this, _table),
3576
+ response,
3577
+ columns
3578
+ );
2366
3579
  } catch (e) {
2367
3580
  if (isObject(e) && e.status === 404) {
2368
3581
  return null;
@@ -2404,17 +3617,17 @@ class RestRepository extends Query {
2404
3617
  ifVersion,
2405
3618
  upsert: false
2406
3619
  });
2407
- const columns = isStringArray(b) ? b : ["*"];
3620
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2408
3621
  const result = await this.read(a, columns);
2409
3622
  return result;
2410
3623
  }
2411
3624
  try {
2412
3625
  if (isString(a) && isObject(b)) {
2413
- const columns = isStringArray(c) ? c : void 0;
3626
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2414
3627
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2415
3628
  }
2416
3629
  if (isObject(a) && isString(a.id)) {
2417
- const columns = isStringArray(b) ? b : void 0;
3630
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2418
3631
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2419
3632
  }
2420
3633
  } catch (error) {
@@ -2454,17 +3667,27 @@ class RestRepository extends Query {
2454
3667
  ifVersion,
2455
3668
  upsert: true
2456
3669
  });
2457
- const columns = isStringArray(b) ? b : ["*"];
3670
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2458
3671
  const result = await this.read(a, columns);
2459
3672
  return result;
2460
3673
  }
2461
3674
  if (isString(a) && isObject(b)) {
2462
- const columns = isStringArray(c) ? c : void 0;
2463
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3675
+ if (a === "")
3676
+ throw new Error("The id can't be empty");
3677
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3678
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2464
3679
  }
2465
3680
  if (isObject(a) && isString(a.id)) {
2466
- const columns = isStringArray(c) ? c : void 0;
2467
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3681
+ if (a.id === "")
3682
+ throw new Error("The id can't be empty");
3683
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3684
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3685
+ }
3686
+ if (!isDefined(a) && isObject(b)) {
3687
+ return await this.create(b, c);
3688
+ }
3689
+ if (isObject(a) && !isDefined(a.id)) {
3690
+ return await this.create(a, b);
2468
3691
  }
2469
3692
  throw new Error("Invalid arguments for createOrUpdate method");
2470
3693
  });
@@ -2476,17 +3699,27 @@ class RestRepository extends Query {
2476
3699
  if (a.length === 0)
2477
3700
  return [];
2478
3701
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2479
- const columns = isStringArray(b) ? b : ["*"];
3702
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2480
3703
  const result = await this.read(ids, columns);
2481
3704
  return result;
2482
3705
  }
2483
3706
  if (isString(a) && isObject(b)) {
2484
- const columns = isStringArray(c) ? c : void 0;
2485
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3707
+ if (a === "")
3708
+ throw new Error("The id can't be empty");
3709
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3710
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2486
3711
  }
2487
3712
  if (isObject(a) && isString(a.id)) {
2488
- const columns = isStringArray(c) ? c : void 0;
2489
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3713
+ if (a.id === "")
3714
+ throw new Error("The id can't be empty");
3715
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3716
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3717
+ }
3718
+ if (!isDefined(a) && isObject(b)) {
3719
+ return await this.create(b, c);
3720
+ }
3721
+ if (isObject(a) && !isDefined(a.id)) {
3722
+ return await this.create(a, b);
2490
3723
  }
2491
3724
  throw new Error("Invalid arguments for createOrReplace method");
2492
3725
  });
@@ -2503,7 +3736,7 @@ class RestRepository extends Query {
2503
3736
  return o.id;
2504
3737
  throw new Error("Invalid arguments for delete method");
2505
3738
  });
2506
- const columns = isStringArray(b) ? b : ["*"];
3739
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2507
3740
  const result = await this.read(a, columns);
2508
3741
  await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2509
3742
  return result;
@@ -2537,7 +3770,6 @@ class RestRepository extends Query {
2537
3770
  }
2538
3771
  async search(query, options = {}) {
2539
3772
  return __privateGet$4(this, _trace).call(this, "search", async () => {
2540
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2541
3773
  const { records } = await searchTable({
2542
3774
  pathParams: {
2543
3775
  workspace: "{workspaceId}",
@@ -2555,7 +3787,29 @@ class RestRepository extends Query {
2555
3787
  page: options.page,
2556
3788
  target: options.target
2557
3789
  },
2558
- ...fetchProps
3790
+ ...__privateGet$4(this, _getFetchProps).call(this)
3791
+ });
3792
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3793
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3794
+ });
3795
+ }
3796
+ async vectorSearch(column, query, options) {
3797
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3798
+ const { records } = await vectorSearchTable({
3799
+ pathParams: {
3800
+ workspace: "{workspaceId}",
3801
+ dbBranchName: "{dbBranch}",
3802
+ region: "{region}",
3803
+ tableName: __privateGet$4(this, _table)
3804
+ },
3805
+ body: {
3806
+ column,
3807
+ queryVector: query,
3808
+ similarityFunction: options?.similarityFunction,
3809
+ size: options?.size,
3810
+ filter: options?.filter
3811
+ },
3812
+ ...__privateGet$4(this, _getFetchProps).call(this)
2559
3813
  });
2560
3814
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2561
3815
  return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
@@ -2563,7 +3817,6 @@ class RestRepository extends Query {
2563
3817
  }
2564
3818
  async aggregate(aggs, filter) {
2565
3819
  return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2566
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2567
3820
  const result = await aggregateTable({
2568
3821
  pathParams: {
2569
3822
  workspace: "{workspaceId}",
@@ -2572,7 +3825,7 @@ class RestRepository extends Query {
2572
3825
  tableName: __privateGet$4(this, _table)
2573
3826
  },
2574
3827
  body: { aggs, filter },
2575
- ...fetchProps
3828
+ ...__privateGet$4(this, _getFetchProps).call(this)
2576
3829
  });
2577
3830
  return result;
2578
3831
  });
@@ -2583,7 +3836,6 @@ class RestRepository extends Query {
2583
3836
  if (cacheQuery)
2584
3837
  return new Page(query, cacheQuery.meta, cacheQuery.records);
2585
3838
  const data = query.getQueryOptions();
2586
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2587
3839
  const { meta, records: objects } = await queryTable({
2588
3840
  pathParams: {
2589
3841
  workspace: "{workspaceId}",
@@ -2599,11 +3851,17 @@ class RestRepository extends Query {
2599
3851
  consistency: data.consistency
2600
3852
  },
2601
3853
  fetchOptions: data.fetchOptions,
2602
- ...fetchProps
3854
+ ...__privateGet$4(this, _getFetchProps).call(this)
2603
3855
  });
2604
3856
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2605
3857
  const records = objects.map(
2606
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3858
+ (record) => initObject(
3859
+ __privateGet$4(this, _db),
3860
+ schemaTables,
3861
+ __privateGet$4(this, _table),
3862
+ record,
3863
+ data.columns ?? ["*"]
3864
+ )
2607
3865
  );
2608
3866
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
2609
3867
  return new Page(query, meta, records);
@@ -2612,7 +3870,6 @@ class RestRepository extends Query {
2612
3870
  async summarizeTable(query, summaries, summariesFilter) {
2613
3871
  return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2614
3872
  const data = query.getQueryOptions();
2615
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2616
3873
  const result = await summarizeTable({
2617
3874
  pathParams: {
2618
3875
  workspace: "{workspaceId}",
@@ -2629,11 +3886,44 @@ class RestRepository extends Query {
2629
3886
  summaries,
2630
3887
  summariesFilter
2631
3888
  },
2632
- ...fetchProps
3889
+ ...__privateGet$4(this, _getFetchProps).call(this)
2633
3890
  });
2634
3891
  return result;
2635
3892
  });
2636
3893
  }
3894
+ ask(question, options) {
3895
+ const questionParam = options?.sessionId ? { message: question } : { question };
3896
+ const params = {
3897
+ pathParams: {
3898
+ workspace: "{workspaceId}",
3899
+ dbBranchName: "{dbBranch}",
3900
+ region: "{region}",
3901
+ tableName: __privateGet$4(this, _table),
3902
+ sessionId: options?.sessionId
3903
+ },
3904
+ body: {
3905
+ ...questionParam,
3906
+ rules: options?.rules,
3907
+ searchType: options?.searchType,
3908
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3909
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3910
+ },
3911
+ ...__privateGet$4(this, _getFetchProps).call(this)
3912
+ };
3913
+ if (options?.onMessage) {
3914
+ fetchSSERequest({
3915
+ endpoint: "dataPlane",
3916
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3917
+ method: "POST",
3918
+ onMessage: (message) => {
3919
+ options.onMessage?.({ answer: message.text, records: message.records });
3920
+ },
3921
+ ...params
3922
+ });
3923
+ } else {
3924
+ return askTableSession(params);
3925
+ }
3926
+ }
2637
3927
  }
2638
3928
  _table = new WeakMap();
2639
3929
  _getFetchProps = new WeakMap();
@@ -2643,8 +3933,7 @@ _schemaTables$2 = new WeakMap();
2643
3933
  _trace = new WeakMap();
2644
3934
  _insertRecordWithoutId = new WeakSet();
2645
3935
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2646
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2647
- const record = transformObjectLinks(object);
3936
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2648
3937
  const response = await insertRecord({
2649
3938
  pathParams: {
2650
3939
  workspace: "{workspaceId}",
@@ -2654,15 +3943,16 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2654
3943
  },
2655
3944
  queryParams: { columns },
2656
3945
  body: record,
2657
- ...fetchProps
3946
+ ...__privateGet$4(this, _getFetchProps).call(this)
2658
3947
  });
2659
3948
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2660
3949
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2661
3950
  };
2662
3951
  _insertRecordWithId = new WeakSet();
2663
3952
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2664
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2665
- const record = transformObjectLinks(object);
3953
+ if (!recordId)
3954
+ return null;
3955
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2666
3956
  const response = await insertRecordWithID({
2667
3957
  pathParams: {
2668
3958
  workspace: "{workspaceId}",
@@ -2673,30 +3963,28 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2673
3963
  },
2674
3964
  body: record,
2675
3965
  queryParams: { createOnly, columns, ifVersion },
2676
- ...fetchProps
3966
+ ...__privateGet$4(this, _getFetchProps).call(this)
2677
3967
  });
2678
3968
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2679
3969
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2680
3970
  };
2681
3971
  _insertRecords = new WeakSet();
2682
3972
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2683
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2684
- const chunkedOperations = chunk(
2685
- objects.map((object) => ({
2686
- insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2687
- })),
2688
- BULK_OPERATION_MAX_SIZE
2689
- );
3973
+ const operations = await promiseMap(objects, async (object) => {
3974
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3975
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
3976
+ });
3977
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2690
3978
  const ids = [];
2691
- for (const operations of chunkedOperations) {
3979
+ for (const operations2 of chunkedOperations) {
2692
3980
  const { results } = await branchTransaction({
2693
3981
  pathParams: {
2694
3982
  workspace: "{workspaceId}",
2695
3983
  dbBranchName: "{dbBranch}",
2696
3984
  region: "{region}"
2697
3985
  },
2698
- body: { operations },
2699
- ...fetchProps
3986
+ body: { operations: operations2 },
3987
+ ...__privateGet$4(this, _getFetchProps).call(this)
2700
3988
  });
2701
3989
  for (const result of results) {
2702
3990
  if (result.operation === "insert") {
@@ -2710,8 +3998,9 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2710
3998
  };
2711
3999
  _updateRecordWithID = new WeakSet();
2712
4000
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2713
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2714
- const { id: _id, ...record } = transformObjectLinks(object);
4001
+ if (!recordId)
4002
+ return null;
4003
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2715
4004
  try {
2716
4005
  const response = await updateRecordWithID({
2717
4006
  pathParams: {
@@ -2723,7 +4012,7 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2723
4012
  },
2724
4013
  queryParams: { columns, ifVersion },
2725
4014
  body: record,
2726
- ...fetchProps
4015
+ ...__privateGet$4(this, _getFetchProps).call(this)
2727
4016
  });
2728
4017
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2729
4018
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2736,23 +4025,21 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2736
4025
  };
2737
4026
  _updateRecords = new WeakSet();
2738
4027
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2739
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2740
- const chunkedOperations = chunk(
2741
- objects.map(({ id, ...object }) => ({
2742
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2743
- })),
2744
- BULK_OPERATION_MAX_SIZE
2745
- );
4028
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
4029
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
4030
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
4031
+ });
4032
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2746
4033
  const ids = [];
2747
- for (const operations of chunkedOperations) {
4034
+ for (const operations2 of chunkedOperations) {
2748
4035
  const { results } = await branchTransaction({
2749
4036
  pathParams: {
2750
4037
  workspace: "{workspaceId}",
2751
4038
  dbBranchName: "{dbBranch}",
2752
4039
  region: "{region}"
2753
4040
  },
2754
- body: { operations },
2755
- ...fetchProps
4041
+ body: { operations: operations2 },
4042
+ ...__privateGet$4(this, _getFetchProps).call(this)
2756
4043
  });
2757
4044
  for (const result of results) {
2758
4045
  if (result.operation === "update") {
@@ -2766,7 +4053,8 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2766
4053
  };
2767
4054
  _upsertRecordWithID = new WeakSet();
2768
4055
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2769
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
4056
+ if (!recordId)
4057
+ return null;
2770
4058
  const response = await upsertRecordWithID({
2771
4059
  pathParams: {
2772
4060
  workspace: "{workspaceId}",
@@ -2777,14 +4065,15 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2777
4065
  },
2778
4066
  queryParams: { columns, ifVersion },
2779
4067
  body: object,
2780
- ...fetchProps
4068
+ ...__privateGet$4(this, _getFetchProps).call(this)
2781
4069
  });
2782
4070
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2783
4071
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2784
4072
  };
2785
4073
  _deleteRecord = new WeakSet();
2786
4074
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
2787
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
4075
+ if (!recordId)
4076
+ return null;
2788
4077
  try {
2789
4078
  const response = await deleteRecord({
2790
4079
  pathParams: {
@@ -2795,7 +4084,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2795
4084
  recordId
2796
4085
  },
2797
4086
  queryParams: { columns },
2798
- ...fetchProps
4087
+ ...__privateGet$4(this, _getFetchProps).call(this)
2799
4088
  });
2800
4089
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2801
4090
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2808,9 +4097,8 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2808
4097
  };
2809
4098
  _deleteRecords = new WeakSet();
2810
4099
  deleteRecords_fn = async function(recordIds) {
2811
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2812
4100
  const chunkedOperations = chunk(
2813
- recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
4101
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2814
4102
  BULK_OPERATION_MAX_SIZE
2815
4103
  );
2816
4104
  for (const operations of chunkedOperations) {
@@ -2821,13 +4109,13 @@ deleteRecords_fn = async function(recordIds) {
2821
4109
  region: "{region}"
2822
4110
  },
2823
4111
  body: { operations },
2824
- ...fetchProps
4112
+ ...__privateGet$4(this, _getFetchProps).call(this)
2825
4113
  });
2826
4114
  }
2827
4115
  };
2828
4116
  _setCacheQuery = new WeakSet();
2829
4117
  setCacheQuery_fn = async function(query, meta, records) {
2830
- await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
4118
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
2831
4119
  };
2832
4120
  _getCacheQuery = new WeakSet();
2833
4121
  getCacheQuery_fn = async function(query) {
@@ -2846,15 +4134,49 @@ _getSchemaTables$1 = new WeakSet();
2846
4134
  getSchemaTables_fn$1 = async function() {
2847
4135
  if (__privateGet$4(this, _schemaTables$2))
2848
4136
  return __privateGet$4(this, _schemaTables$2);
2849
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2850
4137
  const { schema } = await getBranchDetails({
2851
4138
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2852
- ...fetchProps
4139
+ ...__privateGet$4(this, _getFetchProps).call(this)
2853
4140
  });
2854
4141
  __privateSet$4(this, _schemaTables$2, schema.tables);
2855
4142
  return schema.tables;
2856
4143
  };
2857
- const transformObjectLinks = (object) => {
4144
+ _transformObjectToApi = new WeakSet();
4145
+ transformObjectToApi_fn = async function(object) {
4146
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4147
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
4148
+ if (!schema)
4149
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
4150
+ const result = {};
4151
+ for (const [key, value] of Object.entries(object)) {
4152
+ if (key === "xata")
4153
+ continue;
4154
+ const type = schema.columns.find((column) => column.name === key)?.type;
4155
+ switch (type) {
4156
+ case "link": {
4157
+ result[key] = isIdentifiable(value) ? value.id : value;
4158
+ break;
4159
+ }
4160
+ case "datetime": {
4161
+ result[key] = value instanceof Date ? value.toISOString() : value;
4162
+ break;
4163
+ }
4164
+ case `file`:
4165
+ result[key] = await parseInputFileEntry(value);
4166
+ break;
4167
+ case "file[]":
4168
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4169
+ break;
4170
+ case "json":
4171
+ result[key] = stringifyJson(value);
4172
+ break;
4173
+ default:
4174
+ result[key] = value;
4175
+ }
4176
+ }
4177
+ return result;
4178
+ };
4179
+ const removeLinksFromObject = (object) => {
2858
4180
  return Object.entries(object).reduce((acc, [key, value]) => {
2859
4181
  if (key === "xata")
2860
4182
  return acc;
@@ -2891,18 +4213,33 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2891
4213
  if (item === column.name) {
2892
4214
  return [...acc, "*"];
2893
4215
  }
2894
- if (item.startsWith(`${column.name}.`)) {
4216
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
2895
4217
  const [, ...path] = item.split(".");
2896
4218
  return [...acc, path.join(".")];
2897
4219
  }
2898
4220
  return acc;
2899
4221
  }, []);
2900
- data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4222
+ data[column.name] = initObject(
4223
+ db,
4224
+ schemaTables,
4225
+ linkTable,
4226
+ value,
4227
+ selectedLinkColumns
4228
+ );
2901
4229
  } else {
2902
4230
  data[column.name] = null;
2903
4231
  }
2904
4232
  break;
2905
4233
  }
4234
+ case "file":
4235
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4236
+ break;
4237
+ case "file[]":
4238
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4239
+ break;
4240
+ case "json":
4241
+ data[column.name] = parseJson(value);
4242
+ break;
2906
4243
  default:
2907
4244
  data[column.name] = value ?? null;
2908
4245
  if (column.notNull === true && value === null) {
@@ -2912,30 +4249,33 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2912
4249
  }
2913
4250
  }
2914
4251
  const record = { ...data };
4252
+ const serializable = { xata, ...removeLinksFromObject(data) };
4253
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
2915
4254
  record.read = function(columns2) {
2916
4255
  return db[table].read(record["id"], columns2);
2917
4256
  };
2918
4257
  record.update = function(data2, b, c) {
2919
- const columns2 = isStringArray(b) ? b : ["*"];
4258
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2920
4259
  const ifVersion = parseIfVersion(b, c);
2921
4260
  return db[table].update(record["id"], data2, columns2, { ifVersion });
2922
4261
  };
2923
4262
  record.replace = function(data2, b, c) {
2924
- const columns2 = isStringArray(b) ? b : ["*"];
4263
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2925
4264
  const ifVersion = parseIfVersion(b, c);
2926
4265
  return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2927
4266
  };
2928
4267
  record.delete = function() {
2929
4268
  return db[table].delete(record["id"]);
2930
4269
  };
4270
+ record.xata = Object.freeze(metadata);
2931
4271
  record.getMetadata = function() {
2932
- return xata;
4272
+ return record.xata;
2933
4273
  };
2934
4274
  record.toSerializable = function() {
2935
- return JSON.parse(JSON.stringify(transformObjectLinks(data)));
4275
+ return JSON.parse(JSON.stringify(serializable));
2936
4276
  };
2937
4277
  record.toString = function() {
2938
- return JSON.stringify(transformObjectLinks(data));
4278
+ return JSON.stringify(serializable);
2939
4279
  };
2940
4280
  for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
2941
4281
  Object.defineProperty(record, prop, { enumerable: false });
@@ -2953,11 +4293,7 @@ function extractId(value) {
2953
4293
  function isValidColumn(columns, column) {
2954
4294
  if (columns.includes("*"))
2955
4295
  return true;
2956
- if (column.type === "link") {
2957
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
2958
- return linkColumns.length > 0;
2959
- }
2960
- return columns.includes(column.name);
4296
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
2961
4297
  }
2962
4298
  function parseIfVersion(...args) {
2963
4299
  for (const arg of args) {
@@ -2968,6 +4304,12 @@ function parseIfVersion(...args) {
2968
4304
  return void 0;
2969
4305
  }
2970
4306
 
4307
+ var __defProp$3 = Object.defineProperty;
4308
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4309
+ var __publicField$3 = (obj, key, value) => {
4310
+ __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
4311
+ return value;
4312
+ };
2971
4313
  var __accessCheck$3 = (obj, member, msg) => {
2972
4314
  if (!member.has(obj))
2973
4315
  throw TypeError("Cannot " + msg);
@@ -2990,6 +4332,8 @@ var _map;
2990
4332
  class SimpleCache {
2991
4333
  constructor(options = {}) {
2992
4334
  __privateAdd$3(this, _map, void 0);
4335
+ __publicField$3(this, "capacity");
4336
+ __publicField$3(this, "defaultQueryTTL");
2993
4337
  __privateSet$3(this, _map, /* @__PURE__ */ new Map());
2994
4338
  this.capacity = options.max ?? 500;
2995
4339
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
@@ -3125,19 +4469,19 @@ class SearchPlugin extends XataPlugin {
3125
4469
  __privateAdd$1(this, _schemaTables, void 0);
3126
4470
  __privateSet$1(this, _schemaTables, schemaTables);
3127
4471
  }
3128
- build({ getFetchProps }) {
4472
+ build(pluginOptions) {
3129
4473
  return {
3130
4474
  all: async (query, options = {}) => {
3131
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3132
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
4475
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4476
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3133
4477
  return records.map((record) => {
3134
4478
  const { table = "orphan" } = record.xata;
3135
4479
  return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
3136
4480
  });
3137
4481
  },
3138
4482
  byTable: async (query, options = {}) => {
3139
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3140
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
4483
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4484
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3141
4485
  return records.reduce((acc, record) => {
3142
4486
  const { table = "orphan" } = record.xata;
3143
4487
  const items = acc[table] ?? [];
@@ -3150,38 +4494,108 @@ class SearchPlugin extends XataPlugin {
3150
4494
  }
3151
4495
  _schemaTables = new WeakMap();
3152
4496
  _search = new WeakSet();
3153
- search_fn = async function(query, options, getFetchProps) {
3154
- const fetchProps = await getFetchProps();
4497
+ search_fn = async function(query, options, pluginOptions) {
3155
4498
  const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3156
4499
  const { records } = await searchBranch({
3157
4500
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4501
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
3158
4502
  body: { tables, query, fuzziness, prefix, highlight, page },
3159
- ...fetchProps
4503
+ ...pluginOptions
3160
4504
  });
3161
4505
  return records;
3162
4506
  };
3163
4507
  _getSchemaTables = new WeakSet();
3164
- getSchemaTables_fn = async function(getFetchProps) {
4508
+ getSchemaTables_fn = async function(pluginOptions) {
3165
4509
  if (__privateGet$1(this, _schemaTables))
3166
4510
  return __privateGet$1(this, _schemaTables);
3167
- const fetchProps = await getFetchProps();
3168
4511
  const { schema } = await getBranchDetails({
3169
4512
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3170
- ...fetchProps
4513
+ ...pluginOptions
3171
4514
  });
3172
4515
  __privateSet$1(this, _schemaTables, schema.tables);
3173
4516
  return schema.tables;
3174
4517
  };
3175
4518
 
4519
+ function escapeElement(elementRepresentation) {
4520
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4521
+ return '"' + escaped + '"';
4522
+ }
4523
+ function arrayString(val) {
4524
+ let result = "{";
4525
+ for (let i = 0; i < val.length; i++) {
4526
+ if (i > 0) {
4527
+ result = result + ",";
4528
+ }
4529
+ if (val[i] === null || typeof val[i] === "undefined") {
4530
+ result = result + "NULL";
4531
+ } else if (Array.isArray(val[i])) {
4532
+ result = result + arrayString(val[i]);
4533
+ } else if (val[i] instanceof Buffer) {
4534
+ result += "\\\\x" + val[i].toString("hex");
4535
+ } else {
4536
+ result += escapeElement(prepareValue(val[i]));
4537
+ }
4538
+ }
4539
+ result = result + "}";
4540
+ return result;
4541
+ }
4542
+ function prepareValue(value) {
4543
+ if (!isDefined(value))
4544
+ return null;
4545
+ if (value instanceof Date) {
4546
+ return value.toISOString();
4547
+ }
4548
+ if (Array.isArray(value)) {
4549
+ return arrayString(value);
4550
+ }
4551
+ if (isObject(value)) {
4552
+ return JSON.stringify(value);
4553
+ }
4554
+ try {
4555
+ return value.toString();
4556
+ } catch (e) {
4557
+ return value;
4558
+ }
4559
+ }
4560
+ function prepareParams(param1, param2) {
4561
+ if (isString(param1)) {
4562
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4563
+ }
4564
+ if (isStringArray(param1)) {
4565
+ const statement = param1.reduce((acc, curr, index) => {
4566
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4567
+ }, "");
4568
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4569
+ }
4570
+ if (isObject(param1)) {
4571
+ const { statement, params, consistency } = param1;
4572
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
4573
+ }
4574
+ throw new Error("Invalid query");
4575
+ }
4576
+
4577
+ class SQLPlugin extends XataPlugin {
4578
+ build(pluginOptions) {
4579
+ return async (param1, ...param2) => {
4580
+ const { statement, params, consistency } = prepareParams(param1, param2);
4581
+ const { records, warning } = await sqlQuery({
4582
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4583
+ body: { statement, params, consistency },
4584
+ ...pluginOptions
4585
+ });
4586
+ return { records, warning };
4587
+ };
4588
+ }
4589
+ }
4590
+
3176
4591
  class TransactionPlugin extends XataPlugin {
3177
- build({ getFetchProps }) {
4592
+ build(pluginOptions) {
3178
4593
  return {
3179
4594
  run: async (operations) => {
3180
- const fetchProps = await getFetchProps();
3181
4595
  const response = await branchTransaction({
3182
4596
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3183
4597
  body: { operations },
3184
- ...fetchProps
4598
+ ...pluginOptions
3185
4599
  });
3186
4600
  return response;
3187
4601
  }
@@ -3189,10 +4603,12 @@ class TransactionPlugin extends XataPlugin {
3189
4603
  }
3190
4604
  }
3191
4605
 
3192
- const isBranchStrategyBuilder = (strategy) => {
3193
- return typeof strategy === "function";
4606
+ var __defProp$2 = Object.defineProperty;
4607
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4608
+ var __publicField$2 = (obj, key, value) => {
4609
+ __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
4610
+ return value;
3194
4611
  };
3195
-
3196
4612
  var __accessCheck = (obj, member, msg) => {
3197
4613
  if (!member.has(obj))
3198
4614
  throw TypeError("Cannot " + msg);
@@ -3216,27 +4632,34 @@ var __privateMethod = (obj, member, method) => {
3216
4632
  return method;
3217
4633
  };
3218
4634
  const buildClient = (plugins) => {
3219
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
4635
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3220
4636
  return _a = class {
3221
4637
  constructor(options = {}, schemaTables) {
3222
4638
  __privateAdd(this, _parseOptions);
3223
4639
  __privateAdd(this, _getFetchProps);
3224
- __privateAdd(this, _evaluateBranch);
3225
- __privateAdd(this, _branch, void 0);
3226
4640
  __privateAdd(this, _options, void 0);
4641
+ __publicField$2(this, "db");
4642
+ __publicField$2(this, "search");
4643
+ __publicField$2(this, "transactions");
4644
+ __publicField$2(this, "sql");
4645
+ __publicField$2(this, "files");
3227
4646
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3228
4647
  __privateSet(this, _options, safeOptions);
3229
4648
  const pluginOptions = {
3230
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
4649
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3231
4650
  cache: safeOptions.cache,
3232
- trace: safeOptions.trace
4651
+ host: safeOptions.host
3233
4652
  };
3234
4653
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3235
4654
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3236
4655
  const transactions = new TransactionPlugin().build(pluginOptions);
4656
+ const sql = new SQLPlugin().build(pluginOptions);
4657
+ const files = new FilesPlugin().build(pluginOptions);
3237
4658
  this.db = db;
3238
4659
  this.search = search;
3239
4660
  this.transactions = transactions;
4661
+ this.sql = sql;
4662
+ this.files = files;
3240
4663
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3241
4664
  if (namespace === void 0)
3242
4665
  continue;
@@ -3248,7 +4671,7 @@ const buildClient = (plugins) => {
3248
4671
  const branch = __privateGet(this, _options).branch;
3249
4672
  return { databaseURL, branch };
3250
4673
  }
3251
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4674
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3252
4675
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3253
4676
  const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3254
4677
  if (isBrowser && !enableBrowser) {
@@ -3263,13 +4686,33 @@ const buildClient = (plugins) => {
3263
4686
  const trace = options?.trace ?? defaultTrace;
3264
4687
  const clientName = options?.clientName;
3265
4688
  const host = options?.host ?? "production";
3266
- const branch = options?.branch !== void 0 ? __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : "main";
4689
+ const xataAgentExtra = options?.xataAgentExtra;
3267
4690
  if (!apiKey) {
3268
4691
  throw new Error("Option apiKey is required");
3269
4692
  }
3270
4693
  if (!databaseURL) {
3271
4694
  throw new Error("Option databaseURL is required");
3272
4695
  }
4696
+ const envBranch = getBranch();
4697
+ const previewBranch = getPreviewBranch();
4698
+ const branch = options?.branch || previewBranch || envBranch || "main";
4699
+ if (!!previewBranch && branch !== previewBranch) {
4700
+ console.warn(
4701
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4702
+ );
4703
+ } else if (!!envBranch && branch !== envBranch) {
4704
+ console.warn(
4705
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4706
+ );
4707
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4708
+ console.warn(
4709
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4710
+ );
4711
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4712
+ console.warn(
4713
+ `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.`
4714
+ );
4715
+ }
3273
4716
  return {
3274
4717
  fetch,
3275
4718
  databaseURL,
@@ -3280,51 +4723,50 @@ const buildClient = (plugins) => {
3280
4723
  host,
3281
4724
  clientID: generateUUID(),
3282
4725
  enableBrowser,
3283
- clientName
4726
+ clientName,
4727
+ xataAgentExtra
3284
4728
  };
3285
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({ fetch, apiKey, databaseURL, branch, trace, clientID, clientName }) {
3286
- const branchValue = __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3287
- if (!branchValue)
3288
- throw new Error("Unable to resolve branch value");
4729
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
4730
+ fetch,
4731
+ apiKey,
4732
+ databaseURL,
4733
+ branch,
4734
+ trace,
4735
+ clientID,
4736
+ clientName,
4737
+ xataAgentExtra
4738
+ }) {
3289
4739
  return {
3290
- fetchImpl: fetch,
4740
+ fetch,
3291
4741
  apiKey,
3292
4742
  apiUrl: "",
4743
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3293
4744
  workspacesApiUrl: (path, params) => {
3294
4745
  const hasBranch = params.dbBranchName ?? params.branch;
3295
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
4746
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
3296
4747
  return databaseURL + newPath;
3297
4748
  },
3298
4749
  trace,
3299
4750
  clientID,
3300
- clientName
3301
- };
3302
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = function(param) {
3303
- if (__privateGet(this, _branch))
3304
- return __privateGet(this, _branch);
3305
- if (param === void 0)
3306
- return void 0;
3307
- const strategies = Array.isArray(param) ? [...param] : [param];
3308
- const evaluateBranch = (strategy) => {
3309
- return isBranchStrategyBuilder(strategy) ? strategy() : strategy;
4751
+ clientName,
4752
+ xataAgentExtra
3310
4753
  };
3311
- for (const strategy of strategies) {
3312
- const branch = evaluateBranch(strategy);
3313
- if (branch) {
3314
- __privateSet(this, _branch, branch);
3315
- return branch;
3316
- }
3317
- }
3318
4754
  }, _a;
3319
4755
  };
3320
4756
  class BaseClient extends buildClient() {
3321
4757
  }
3322
4758
 
4759
+ var __defProp$1 = Object.defineProperty;
4760
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4761
+ var __publicField$1 = (obj, key, value) => {
4762
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
4763
+ return value;
4764
+ };
3323
4765
  const META = "__";
3324
4766
  const VALUE = "___";
3325
4767
  class Serializer {
3326
4768
  constructor() {
3327
- this.classes = {};
4769
+ __publicField$1(this, "classes", {});
3328
4770
  }
3329
4771
  add(clazz) {
3330
4772
  this.classes[clazz.name] = clazz;
@@ -3402,15 +4844,23 @@ function buildWorkerRunner(config) {
3402
4844
  };
3403
4845
  }
3404
4846
 
4847
+ var __defProp = Object.defineProperty;
4848
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4849
+ var __publicField = (obj, key, value) => {
4850
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4851
+ return value;
4852
+ };
3405
4853
  class XataError extends Error {
3406
4854
  constructor(message, status) {
3407
4855
  super(message);
4856
+ __publicField(this, "status");
3408
4857
  this.status = status;
3409
4858
  }
3410
4859
  }
3411
4860
 
3412
4861
  exports.BaseClient = BaseClient;
3413
4862
  exports.FetcherError = FetcherError;
4863
+ exports.FilesPlugin = FilesPlugin;
3414
4864
  exports.Operations = operationsByTag;
3415
4865
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
3416
4866
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -3419,8 +4869,10 @@ exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
3419
4869
  exports.Page = Page;
3420
4870
  exports.Query = Query;
3421
4871
  exports.RecordArray = RecordArray;
4872
+ exports.RecordColumnTypes = RecordColumnTypes;
3422
4873
  exports.Repository = Repository;
3423
4874
  exports.RestRepository = RestRepository;
4875
+ exports.SQLPlugin = SQLPlugin;
3424
4876
  exports.SchemaPlugin = SchemaPlugin;
3425
4877
  exports.SearchPlugin = SearchPlugin;
3426
4878
  exports.Serializer = Serializer;
@@ -3428,14 +4880,19 @@ exports.SimpleCache = SimpleCache;
3428
4880
  exports.XataApiClient = XataApiClient;
3429
4881
  exports.XataApiPlugin = XataApiPlugin;
3430
4882
  exports.XataError = XataError;
4883
+ exports.XataFile = XataFile;
3431
4884
  exports.XataPlugin = XataPlugin;
3432
4885
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
3433
4886
  exports.addGitBranchesEntry = addGitBranchesEntry;
3434
4887
  exports.addTableColumn = addTableColumn;
3435
4888
  exports.aggregateTable = aggregateTable;
3436
4889
  exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
4890
+ exports.askTable = askTable;
4891
+ exports.askTableSession = askTableSession;
3437
4892
  exports.branchTransaction = branchTransaction;
3438
4893
  exports.buildClient = buildClient;
4894
+ exports.buildPreviewBranchName = buildPreviewBranchName;
4895
+ exports.buildProviderString = buildProviderString;
3439
4896
  exports.buildWorkerRunner = buildWorkerRunner;
3440
4897
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
3441
4898
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
@@ -3443,6 +4900,7 @@ exports.compareBranchSchemas = compareBranchSchemas;
3443
4900
  exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
3444
4901
  exports.compareMigrationRequest = compareMigrationRequest;
3445
4902
  exports.contains = contains;
4903
+ exports.copyBranch = copyBranch;
3446
4904
  exports.createBranch = createBranch;
3447
4905
  exports.createDatabase = createDatabase;
3448
4906
  exports.createMigrationRequest = createMigrationRequest;
@@ -3452,18 +4910,26 @@ exports.createWorkspace = createWorkspace;
3452
4910
  exports.deleteBranch = deleteBranch;
3453
4911
  exports.deleteColumn = deleteColumn;
3454
4912
  exports.deleteDatabase = deleteDatabase;
4913
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
4914
+ exports.deleteFile = deleteFile;
4915
+ exports.deleteFileItem = deleteFileItem;
4916
+ exports.deleteOAuthAccessToken = deleteOAuthAccessToken;
3455
4917
  exports.deleteRecord = deleteRecord;
3456
4918
  exports.deleteTable = deleteTable;
3457
4919
  exports.deleteUser = deleteUser;
3458
4920
  exports.deleteUserAPIKey = deleteUserAPIKey;
4921
+ exports.deleteUserOAuthClient = deleteUserOAuthClient;
3459
4922
  exports.deleteWorkspace = deleteWorkspace;
3460
4923
  exports.deserialize = deserialize;
3461
4924
  exports.endsWith = endsWith;
3462
4925
  exports.equals = equals;
3463
4926
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
3464
4927
  exports.exists = exists;
4928
+ exports.fileAccess = fileAccess;
3465
4929
  exports.ge = ge;
3466
4930
  exports.getAPIKey = getAPIKey;
4931
+ exports.getAuthorizationCode = getAuthorizationCode;
4932
+ exports.getBranch = getBranch;
3467
4933
  exports.getBranchDetails = getBranchDetails;
3468
4934
  exports.getBranchList = getBranchList;
3469
4935
  exports.getBranchMetadata = getBranchMetadata;
@@ -3472,21 +4938,28 @@ exports.getBranchMigrationPlan = getBranchMigrationPlan;
3472
4938
  exports.getBranchSchemaHistory = getBranchSchemaHistory;
3473
4939
  exports.getBranchStats = getBranchStats;
3474
4940
  exports.getColumn = getColumn;
4941
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
3475
4942
  exports.getDatabaseList = getDatabaseList;
3476
4943
  exports.getDatabaseMetadata = getDatabaseMetadata;
3477
4944
  exports.getDatabaseURL = getDatabaseURL;
4945
+ exports.getFile = getFile;
4946
+ exports.getFileItem = getFileItem;
3478
4947
  exports.getGitBranchesMapping = getGitBranchesMapping;
3479
4948
  exports.getHostUrl = getHostUrl;
3480
4949
  exports.getMigrationRequest = getMigrationRequest;
3481
4950
  exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
4951
+ exports.getPreviewBranch = getPreviewBranch;
3482
4952
  exports.getRecord = getRecord;
3483
4953
  exports.getTableColumns = getTableColumns;
3484
4954
  exports.getTableSchema = getTableSchema;
3485
4955
  exports.getUser = getUser;
3486
4956
  exports.getUserAPIKeys = getUserAPIKeys;
4957
+ exports.getUserOAuthAccessTokens = getUserOAuthAccessTokens;
4958
+ exports.getUserOAuthClients = getUserOAuthClients;
3487
4959
  exports.getWorkspace = getWorkspace;
3488
4960
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
3489
4961
  exports.getWorkspacesList = getWorkspacesList;
4962
+ exports.grantAuthorizationCode = grantAuthorizationCode;
3490
4963
  exports.greaterEquals = greaterEquals;
3491
4964
  exports.greaterThan = greaterThan;
3492
4965
  exports.greaterThanEquals = greaterThanEquals;
@@ -3505,6 +4978,8 @@ exports.isHostProviderAlias = isHostProviderAlias;
3505
4978
  exports.isHostProviderBuilder = isHostProviderBuilder;
3506
4979
  exports.isIdentifiable = isIdentifiable;
3507
4980
  exports.isNot = isNot;
4981
+ exports.isValidExpandedColumn = isValidExpandedColumn;
4982
+ exports.isValidSelectableColumns = isValidSelectableColumns;
3508
4983
  exports.isXataRecord = isXataRecord;
3509
4984
  exports.le = le;
3510
4985
  exports.lessEquals = lessEquals;
@@ -3521,23 +4996,31 @@ exports.parseProviderString = parseProviderString;
3521
4996
  exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
3522
4997
  exports.pattern = pattern;
3523
4998
  exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
4999
+ exports.pushBranchMigrations = pushBranchMigrations;
5000
+ exports.putFile = putFile;
5001
+ exports.putFileItem = putFileItem;
3524
5002
  exports.queryMigrationRequests = queryMigrationRequests;
3525
5003
  exports.queryTable = queryTable;
3526
5004
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
3527
5005
  exports.removeWorkspaceMember = removeWorkspaceMember;
5006
+ exports.renameDatabase = renameDatabase;
3528
5007
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
3529
5008
  exports.resolveBranch = resolveBranch;
3530
5009
  exports.searchBranch = searchBranch;
3531
5010
  exports.searchTable = searchTable;
3532
5011
  exports.serialize = serialize;
3533
5012
  exports.setTableSchema = setTableSchema;
5013
+ exports.sqlQuery = sqlQuery;
3534
5014
  exports.startsWith = startsWith;
3535
5015
  exports.summarizeTable = summarizeTable;
5016
+ exports.transformImage = transformImage;
3536
5017
  exports.updateBranchMetadata = updateBranchMetadata;
3537
5018
  exports.updateBranchSchema = updateBranchSchema;
3538
5019
  exports.updateColumn = updateColumn;
5020
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
3539
5021
  exports.updateDatabaseMetadata = updateDatabaseMetadata;
3540
5022
  exports.updateMigrationRequest = updateMigrationRequest;
5023
+ exports.updateOAuthAccessToken = updateOAuthAccessToken;
3541
5024
  exports.updateRecordWithID = updateRecordWithID;
3542
5025
  exports.updateTable = updateTable;
3543
5026
  exports.updateUser = updateUser;
@@ -3545,4 +5028,5 @@ exports.updateWorkspace = updateWorkspace;
3545
5028
  exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
3546
5029
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
3547
5030
  exports.upsertRecordWithID = upsertRecordWithID;
5031
+ exports.vectorSearchTable = vectorSearchTable;
3548
5032
  //# sourceMappingURL=index.cjs.map