@xata.io/client 0.0.0-alpha.vfe07d64 → 0.0.0-alpha.vfe2d35daeb67fe5687ae597dfaeff7494139827f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -18,7 +18,8 @@ const TraceAttributes = {
18
18
  HTTP_METHOD: "http.method",
19
19
  HTTP_URL: "http.url",
20
20
  HTTP_ROUTE: "http.route",
21
- HTTP_TARGET: "http.target"
21
+ HTTP_TARGET: "http.target",
22
+ CLOUDFLARE_RAY_ID: "cf.ray"
22
23
  };
23
24
 
24
25
  function notEmpty(value) {
@@ -27,8 +28,18 @@ function notEmpty(value) {
27
28
  function compact(arr) {
28
29
  return arr.filter(notEmpty);
29
30
  }
31
+ function compactObject(obj) {
32
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
33
+ }
34
+ function isBlob(value) {
35
+ try {
36
+ return value instanceof Blob;
37
+ } catch (error) {
38
+ return false;
39
+ }
40
+ }
30
41
  function isObject(value) {
31
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
42
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
32
43
  }
33
44
  function isDefined(value) {
34
45
  return value !== null && value !== void 0;
@@ -83,6 +94,27 @@ function chunk(array, chunkSize) {
83
94
  async function timeout(ms) {
84
95
  return new Promise((resolve) => setTimeout(resolve, ms));
85
96
  }
97
+ function timeoutWithCancel(ms) {
98
+ let timeoutId;
99
+ const promise = new Promise((resolve) => {
100
+ timeoutId = setTimeout(() => {
101
+ resolve();
102
+ }, ms);
103
+ });
104
+ return {
105
+ cancel: () => clearTimeout(timeoutId),
106
+ promise
107
+ };
108
+ }
109
+ function promiseMap(inputValues, mapper) {
110
+ const reducer = (acc$, inputValue) => acc$.then(
111
+ (acc) => mapper(inputValue).then((result) => {
112
+ acc.push(result);
113
+ return acc;
114
+ })
115
+ );
116
+ return inputValues.reduce(reducer, Promise.resolve([]));
117
+ }
86
118
 
87
119
  function getEnvironment() {
88
120
  try {
@@ -91,8 +123,10 @@ function getEnvironment() {
91
123
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
92
124
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
93
125
  branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
94
- envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
95
- fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
126
+ deployPreview: process.env.XATA_PREVIEW,
127
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
128
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
129
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
96
130
  };
97
131
  }
98
132
  } catch (err) {
@@ -103,8 +137,10 @@ function getEnvironment() {
103
137
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
104
138
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
105
139
  branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
106
- envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
107
- fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
140
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
141
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
142
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
143
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
108
144
  };
109
145
  }
110
146
  } catch (err) {
@@ -113,8 +149,10 @@ function getEnvironment() {
113
149
  apiKey: getGlobalApiKey(),
114
150
  databaseURL: getGlobalDatabaseURL(),
115
151
  branch: getGlobalBranch(),
116
- envBranch: void 0,
117
- fallbackBranch: getGlobalFallbackBranch()
152
+ deployPreview: void 0,
153
+ deployPreviewBranch: void 0,
154
+ vercelGitCommitRef: void 0,
155
+ vercelGitRepoOwner: void 0
118
156
  };
119
157
  }
120
158
  function getEnableBrowserVariable() {
@@ -157,36 +195,48 @@ function getGlobalBranch() {
157
195
  return void 0;
158
196
  }
159
197
  }
160
- function getGlobalFallbackBranch() {
198
+ function getDatabaseURL() {
161
199
  try {
162
- return XATA_FALLBACK_BRANCH;
200
+ const { databaseURL } = getEnvironment();
201
+ return databaseURL;
163
202
  } catch (err) {
164
203
  return void 0;
165
204
  }
166
205
  }
167
- async function getGitBranch() {
168
- const cmd = ["git", "branch", "--show-current"];
169
- const fullCmd = cmd.join(" ");
170
- const nodeModule = ["child", "process"].join("_");
171
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
206
+ function getAPIKey() {
172
207
  try {
173
- const { execSync } = await import(nodeModule);
174
- return execSync(fullCmd, execOptions).toString().trim();
208
+ const { apiKey } = getEnvironment();
209
+ return apiKey;
175
210
  } catch (err) {
211
+ return void 0;
176
212
  }
213
+ }
214
+ function getBranch() {
177
215
  try {
178
- if (isObject(Deno)) {
179
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
180
- return new TextDecoder().decode(await process2.output()).trim();
181
- }
216
+ const { branch } = getEnvironment();
217
+ return branch;
182
218
  } catch (err) {
219
+ return void 0;
183
220
  }
184
221
  }
185
-
186
- function getAPIKey() {
222
+ function buildPreviewBranchName({ org, branch }) {
223
+ return `preview-${org}-${branch}`;
224
+ }
225
+ function getPreviewBranch() {
187
226
  try {
188
- const { apiKey } = getEnvironment();
189
- return apiKey;
227
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
228
+ if (deployPreviewBranch)
229
+ return deployPreviewBranch;
230
+ switch (deployPreview) {
231
+ case "vercel": {
232
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
233
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
234
+ return void 0;
235
+ }
236
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
237
+ }
238
+ }
239
+ return void 0;
190
240
  } catch (err) {
191
241
  return void 0;
192
242
  }
@@ -215,13 +265,13 @@ var __privateMethod$4 = (obj, member, method) => {
215
265
  return method;
216
266
  };
217
267
  var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
268
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
218
269
  function getFetchImplementation(userFetch) {
219
270
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
220
- const fetchImpl = userFetch ?? globalFetch;
271
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
272
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
221
273
  if (!fetchImpl) {
222
- throw new Error(
223
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
224
- );
274
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
225
275
  }
226
276
  return fetchImpl;
227
277
  }
@@ -246,18 +296,22 @@ class ApiRequestPool {
246
296
  return __privateGet$8(this, _fetch);
247
297
  }
248
298
  request(url, options) {
249
- const start = new Date();
250
- const fetch2 = this.getFetch();
299
+ const start = /* @__PURE__ */ new Date();
300
+ const fetchImpl = this.getFetch();
251
301
  const runRequest = async (stalled = false) => {
252
- const response = await fetch2(url, options);
302
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
303
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
304
+ if (!response) {
305
+ throw new Error("Request timed out");
306
+ }
253
307
  if (response.status === 429) {
254
308
  const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
255
309
  await timeout(rateLimitReset * 1e3);
256
310
  return await runRequest(true);
257
311
  }
258
312
  if (stalled) {
259
- const stalledTime = new Date().getTime() - start.getTime();
260
- console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
313
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
314
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
261
315
  }
262
316
  return response;
263
317
  };
@@ -299,7 +353,180 @@ function generateUUID() {
299
353
  });
300
354
  }
301
355
 
302
- const VERSION = "0.22.1";
356
+ async function getBytes(stream, onChunk) {
357
+ const reader = stream.getReader();
358
+ let result;
359
+ while (!(result = await reader.read()).done) {
360
+ onChunk(result.value);
361
+ }
362
+ }
363
+ function getLines(onLine) {
364
+ let buffer;
365
+ let position;
366
+ let fieldLength;
367
+ let discardTrailingNewline = false;
368
+ return function onChunk(arr) {
369
+ if (buffer === void 0) {
370
+ buffer = arr;
371
+ position = 0;
372
+ fieldLength = -1;
373
+ } else {
374
+ buffer = concat(buffer, arr);
375
+ }
376
+ const bufLength = buffer.length;
377
+ let lineStart = 0;
378
+ while (position < bufLength) {
379
+ if (discardTrailingNewline) {
380
+ if (buffer[position] === 10 /* NewLine */) {
381
+ lineStart = ++position;
382
+ }
383
+ discardTrailingNewline = false;
384
+ }
385
+ let lineEnd = -1;
386
+ for (; position < bufLength && lineEnd === -1; ++position) {
387
+ switch (buffer[position]) {
388
+ case 58 /* Colon */:
389
+ if (fieldLength === -1) {
390
+ fieldLength = position - lineStart;
391
+ }
392
+ break;
393
+ case 13 /* CarriageReturn */:
394
+ discardTrailingNewline = true;
395
+ case 10 /* NewLine */:
396
+ lineEnd = position;
397
+ break;
398
+ }
399
+ }
400
+ if (lineEnd === -1) {
401
+ break;
402
+ }
403
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
404
+ lineStart = position;
405
+ fieldLength = -1;
406
+ }
407
+ if (lineStart === bufLength) {
408
+ buffer = void 0;
409
+ } else if (lineStart !== 0) {
410
+ buffer = buffer.subarray(lineStart);
411
+ position -= lineStart;
412
+ }
413
+ };
414
+ }
415
+ function getMessages(onId, onRetry, onMessage) {
416
+ let message = newMessage();
417
+ const decoder = new TextDecoder();
418
+ return function onLine(line, fieldLength) {
419
+ if (line.length === 0) {
420
+ onMessage?.(message);
421
+ message = newMessage();
422
+ } else if (fieldLength > 0) {
423
+ const field = decoder.decode(line.subarray(0, fieldLength));
424
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
425
+ const value = decoder.decode(line.subarray(valueOffset));
426
+ switch (field) {
427
+ case "data":
428
+ message.data = message.data ? message.data + "\n" + value : value;
429
+ break;
430
+ case "event":
431
+ message.event = value;
432
+ break;
433
+ case "id":
434
+ onId(message.id = value);
435
+ break;
436
+ case "retry":
437
+ const retry = parseInt(value, 10);
438
+ if (!isNaN(retry)) {
439
+ onRetry(message.retry = retry);
440
+ }
441
+ break;
442
+ }
443
+ }
444
+ };
445
+ }
446
+ function concat(a, b) {
447
+ const res = new Uint8Array(a.length + b.length);
448
+ res.set(a);
449
+ res.set(b, a.length);
450
+ return res;
451
+ }
452
+ function newMessage() {
453
+ return {
454
+ data: "",
455
+ event: "",
456
+ id: "",
457
+ retry: void 0
458
+ };
459
+ }
460
+ const EventStreamContentType = "text/event-stream";
461
+ const LastEventId = "last-event-id";
462
+ function fetchEventSource(input, {
463
+ signal: inputSignal,
464
+ headers: inputHeaders,
465
+ onopen: inputOnOpen,
466
+ onmessage,
467
+ onclose,
468
+ onerror,
469
+ fetch: inputFetch,
470
+ ...rest
471
+ }) {
472
+ return new Promise((resolve, reject) => {
473
+ const headers = { ...inputHeaders };
474
+ if (!headers.accept) {
475
+ headers.accept = EventStreamContentType;
476
+ }
477
+ let curRequestController;
478
+ function dispose() {
479
+ curRequestController.abort();
480
+ }
481
+ inputSignal?.addEventListener("abort", () => {
482
+ dispose();
483
+ resolve();
484
+ });
485
+ const fetchImpl = inputFetch ?? fetch;
486
+ const onopen = inputOnOpen ?? defaultOnOpen;
487
+ async function create() {
488
+ curRequestController = new AbortController();
489
+ try {
490
+ const response = await fetchImpl(input, {
491
+ ...rest,
492
+ headers,
493
+ signal: curRequestController.signal
494
+ });
495
+ await onopen(response);
496
+ await getBytes(
497
+ response.body,
498
+ getLines(
499
+ getMessages(
500
+ (id) => {
501
+ if (id) {
502
+ headers[LastEventId] = id;
503
+ } else {
504
+ delete headers[LastEventId];
505
+ }
506
+ },
507
+ (_retry) => {
508
+ },
509
+ onmessage
510
+ )
511
+ )
512
+ );
513
+ onclose?.();
514
+ dispose();
515
+ resolve();
516
+ } catch (err) {
517
+ }
518
+ }
519
+ create();
520
+ });
521
+ }
522
+ function defaultOnOpen(response) {
523
+ const contentType = response.headers?.get("content-type");
524
+ if (!contentType?.startsWith(EventStreamContentType)) {
525
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
526
+ }
527
+ }
528
+
529
+ const VERSION = "0.28.3";
303
530
 
304
531
  class ErrorWithCause extends Error {
305
532
  constructor(message, options) {
@@ -342,6 +569,67 @@ function getMessage(data) {
342
569
  }
343
570
  }
344
571
 
572
+ function getHostUrl(provider, type) {
573
+ if (isHostProviderAlias(provider)) {
574
+ return providers[provider][type];
575
+ } else if (isHostProviderBuilder(provider)) {
576
+ return provider[type];
577
+ }
578
+ throw new Error("Invalid API provider");
579
+ }
580
+ const providers = {
581
+ production: {
582
+ main: "https://api.xata.io",
583
+ workspaces: "https://{workspaceId}.{region}.xata.sh"
584
+ },
585
+ staging: {
586
+ main: "https://api.staging-xata.dev",
587
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
588
+ },
589
+ dev: {
590
+ main: "https://api.dev-xata.dev",
591
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
592
+ },
593
+ local: {
594
+ main: "http://localhost:6001",
595
+ workspaces: "http://{workspaceId}.{region}.localhost:6001"
596
+ }
597
+ };
598
+ function isHostProviderAlias(alias) {
599
+ return isString(alias) && Object.keys(providers).includes(alias);
600
+ }
601
+ function isHostProviderBuilder(builder) {
602
+ return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
603
+ }
604
+ function parseProviderString(provider = "production") {
605
+ if (isHostProviderAlias(provider)) {
606
+ return provider;
607
+ }
608
+ const [main, workspaces] = provider.split(",");
609
+ if (!main || !workspaces)
610
+ return null;
611
+ return { main, workspaces };
612
+ }
613
+ function buildProviderString(provider) {
614
+ if (isHostProviderAlias(provider))
615
+ return provider;
616
+ return `${provider.main},${provider.workspaces}`;
617
+ }
618
+ function parseWorkspacesUrlParts(url) {
619
+ if (!isString(url))
620
+ return null;
621
+ const matches = {
622
+ production: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/),
623
+ staging: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/),
624
+ dev: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/),
625
+ local: url.match(/(?:https?:\/\/)?([^.]+)\.localhost:(\d+)/)
626
+ };
627
+ const [host, match] = Object.entries(matches).find(([, match2]) => match2 !== null) ?? [];
628
+ if (!isHostProviderAlias(host) || !match)
629
+ return null;
630
+ return { workspace: match[1], region: match[2], host };
631
+ }
632
+
345
633
  const pool = new ApiRequestPool();
346
634
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
347
635
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
@@ -357,6 +645,7 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
357
645
  return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
358
646
  };
359
647
  function buildBaseUrl({
648
+ method,
360
649
  endpoint,
361
650
  path,
362
651
  workspacesApiUrl,
@@ -364,7 +653,24 @@ function buildBaseUrl({
364
653
  pathParams = {}
365
654
  }) {
366
655
  if (endpoint === "dataPlane") {
367
- const url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
656
+ let url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
657
+ if (method.toUpperCase() === "PUT" && [
658
+ "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
659
+ "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}"
660
+ ].includes(path)) {
661
+ const { host } = parseWorkspacesUrlParts(url) ?? {};
662
+ switch (host) {
663
+ case "production":
664
+ url = url.replace("xata.sh", "upload.xata.sh");
665
+ break;
666
+ case "staging":
667
+ url = url.replace("staging-xata.dev", "upload.staging-xata.dev");
668
+ break;
669
+ case "dev":
670
+ url = url.replace("dev-xata.dev", "upload.dev-xata.dev");
671
+ break;
672
+ }
673
+ }
368
674
  const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
369
675
  return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
370
676
  }
@@ -375,6 +681,18 @@ function hostHeader(url) {
375
681
  const { groups } = pattern.exec(url) ?? {};
376
682
  return groups?.host ? { Host: groups.host } : {};
377
683
  }
684
+ async function parseBody(body, headers) {
685
+ if (!isDefined(body))
686
+ return void 0;
687
+ if (isBlob(body) || typeof body.text === "function") {
688
+ return body;
689
+ }
690
+ const { "Content-Type": contentType } = headers ?? {};
691
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
692
+ return JSON.stringify(body);
693
+ }
694
+ return body;
695
+ }
378
696
  const defaultClientID = generateUUID();
379
697
  async function fetch$1({
380
698
  url: path,
@@ -383,7 +701,7 @@ async function fetch$1({
383
701
  headers: customHeaders,
384
702
  pathParams,
385
703
  queryParams,
386
- fetchImpl,
704
+ fetch: fetch2,
387
705
  apiKey,
388
706
  endpoint,
389
707
  apiUrl,
@@ -394,13 +712,14 @@ async function fetch$1({
394
712
  sessionID,
395
713
  clientName,
396
714
  xataAgentExtra,
397
- fetchOptions = {}
715
+ fetchOptions = {},
716
+ rawResponse = false
398
717
  }) {
399
- pool.setFetch(fetchImpl);
718
+ pool.setFetch(fetch2);
400
719
  return await trace(
401
720
  `${method.toUpperCase()} ${path}`,
402
721
  async ({ setAttributes }) => {
403
- const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
722
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
404
723
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
405
724
  const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
406
725
  setAttributes({
@@ -413,7 +732,7 @@ async function fetch$1({
413
732
  isDefined(clientName) ? ["service", clientName] : void 0,
414
733
  ...Object.entries(xataAgentExtra ?? {})
415
734
  ]).map(([key, value]) => `${key}=${value}`).join("; ");
416
- const headers = {
735
+ const headers = compactObject({
417
736
  "Accept-Encoding": "identity",
418
737
  "Content-Type": "application/json",
419
738
  "X-Xata-Client-ID": clientID ?? defaultClientID,
@@ -422,11 +741,11 @@ async function fetch$1({
422
741
  ...customHeaders,
423
742
  ...hostHeader(fullUrl),
424
743
  Authorization: `Bearer ${apiKey}`
425
- };
744
+ });
426
745
  const response = await pool.request(url, {
427
746
  ...fetchOptions,
428
747
  method: method.toUpperCase(),
429
- body: body ? JSON.stringify(body) : void 0,
748
+ body: await parseBody(body, headers),
430
749
  headers,
431
750
  signal
432
751
  });
@@ -437,8 +756,12 @@ async function fetch$1({
437
756
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
438
757
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
439
758
  [TraceAttributes.HTTP_HOST]: host,
440
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
759
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
760
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
441
761
  });
762
+ const message = response.headers?.get("x-xata-message");
763
+ if (message)
764
+ console.warn(message);
442
765
  if (response.status === 204) {
443
766
  return {};
444
767
  }
@@ -446,7 +769,7 @@ async function fetch$1({
446
769
  throw new FetcherError(response.status, "Rate limit exceeded", requestId);
447
770
  }
448
771
  try {
449
- const jsonResponse = await response.json();
772
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
450
773
  if (response.ok) {
451
774
  return jsonResponse;
452
775
  }
@@ -458,6 +781,59 @@ async function fetch$1({
458
781
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
459
782
  );
460
783
  }
784
+ function fetchSSERequest({
785
+ url: path,
786
+ method,
787
+ body,
788
+ headers: customHeaders,
789
+ pathParams,
790
+ queryParams,
791
+ fetch: fetch2,
792
+ apiKey,
793
+ endpoint,
794
+ apiUrl,
795
+ workspacesApiUrl,
796
+ onMessage,
797
+ onError,
798
+ onClose,
799
+ signal,
800
+ clientID,
801
+ sessionID,
802
+ clientName,
803
+ xataAgentExtra
804
+ }) {
805
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
806
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
807
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
808
+ void fetchEventSource(url, {
809
+ method,
810
+ body: JSON.stringify(body),
811
+ fetch: fetch2,
812
+ signal,
813
+ headers: {
814
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
815
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
816
+ "X-Xata-Agent": compact([
817
+ ["client", "TS_SDK"],
818
+ ["version", VERSION],
819
+ isDefined(clientName) ? ["service", clientName] : void 0,
820
+ ...Object.entries(xataAgentExtra ?? {})
821
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
822
+ ...customHeaders,
823
+ Authorization: `Bearer ${apiKey}`,
824
+ "Content-Type": "application/json"
825
+ },
826
+ onmessage(ev) {
827
+ onMessage?.(JSON.parse(ev.data));
828
+ },
829
+ onerror(ev) {
830
+ onError?.(JSON.parse(ev.data));
831
+ },
832
+ onclose() {
833
+ onClose?.();
834
+ }
835
+ });
836
+ }
461
837
  function parseUrl(url) {
462
838
  try {
463
839
  const { host, protocol } = new URL(url);
@@ -469,6 +845,19 @@ function parseUrl(url) {
469
845
 
470
846
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
471
847
 
848
+ const applyMigration = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/pgroll/apply", method: "post", ...variables, signal });
849
+ const pgRollStatus = (variables, signal) => dataPlaneFetch({
850
+ url: "/db/{dbBranchName}/pgroll/status",
851
+ method: "get",
852
+ ...variables,
853
+ signal
854
+ });
855
+ const pgRollJobStatus = (variables, signal) => dataPlaneFetch({
856
+ url: "/db/{dbBranchName}/pgroll/jobs/{jobId}",
857
+ method: "get",
858
+ ...variables,
859
+ signal
860
+ });
472
861
  const getBranchList = (variables, signal) => dataPlaneFetch({
473
862
  url: "/dbs/{dbName}",
474
863
  method: "get",
@@ -488,6 +877,18 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
488
877
  ...variables,
489
878
  signal
490
879
  });
880
+ const getSchema = (variables, signal) => dataPlaneFetch({
881
+ url: "/db/{dbBranchName}/schema",
882
+ method: "get",
883
+ ...variables,
884
+ signal
885
+ });
886
+ const copyBranch = (variables, signal) => dataPlaneFetch({
887
+ url: "/db/{dbBranchName}/copy",
888
+ method: "post",
889
+ ...variables,
890
+ signal
891
+ });
491
892
  const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
492
893
  url: "/db/{dbBranchName}/metadata",
493
894
  method: "put",
@@ -537,6 +938,7 @@ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{
537
938
  const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
538
939
  const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
539
940
  const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
941
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
540
942
  const createTable = (variables, signal) => dataPlaneFetch({
541
943
  url: "/db/{dbBranchName}/tables/{tableName}",
542
944
  method: "put",
@@ -581,6 +983,42 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
581
983
  });
582
984
  const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
583
985
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
986
+ const getFileItem = (variables, signal) => dataPlaneFetch({
987
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
988
+ method: "get",
989
+ ...variables,
990
+ signal
991
+ });
992
+ const putFileItem = (variables, signal) => dataPlaneFetch({
993
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
994
+ method: "put",
995
+ ...variables,
996
+ signal
997
+ });
998
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
999
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
1000
+ method: "delete",
1001
+ ...variables,
1002
+ signal
1003
+ });
1004
+ const getFile = (variables, signal) => dataPlaneFetch({
1005
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1006
+ method: "get",
1007
+ ...variables,
1008
+ signal
1009
+ });
1010
+ const putFile = (variables, signal) => dataPlaneFetch({
1011
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1012
+ method: "put",
1013
+ ...variables,
1014
+ signal
1015
+ });
1016
+ const deleteFile = (variables, signal) => dataPlaneFetch({
1017
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1018
+ method: "delete",
1019
+ ...variables,
1020
+ signal
1021
+ });
584
1022
  const getRecord = (variables, signal) => dataPlaneFetch({
585
1023
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
586
1024
  method: "get",
@@ -610,14 +1048,44 @@ const searchTable = (variables, signal) => dataPlaneFetch({
610
1048
  ...variables,
611
1049
  signal
612
1050
  });
1051
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
1052
+ const askTable = (variables, signal) => dataPlaneFetch({
1053
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
1054
+ method: "post",
1055
+ ...variables,
1056
+ signal
1057
+ });
1058
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
613
1059
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
614
1060
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
1061
+ const fileAccess = (variables, signal) => dataPlaneFetch({
1062
+ url: "/file/{fileId}",
1063
+ method: "get",
1064
+ ...variables,
1065
+ signal
1066
+ });
1067
+ const fileUpload = (variables, signal) => dataPlaneFetch({
1068
+ url: "/file/{fileId}",
1069
+ method: "put",
1070
+ ...variables,
1071
+ signal
1072
+ });
1073
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
1074
+ url: "/db/{dbBranchName}/sql",
1075
+ method: "post",
1076
+ ...variables,
1077
+ signal
1078
+ });
615
1079
  const operationsByTag$2 = {
616
1080
  branch: {
1081
+ applyMigration,
1082
+ pgRollStatus,
1083
+ pgRollJobStatus,
617
1084
  getBranchList,
618
1085
  getBranchDetails,
619
1086
  createBranch,
620
1087
  deleteBranch,
1088
+ copyBranch,
621
1089
  updateBranchMetadata,
622
1090
  getBranchMetadata,
623
1091
  getBranchStats,
@@ -627,6 +1095,7 @@ const operationsByTag$2 = {
627
1095
  resolveBranch
628
1096
  },
629
1097
  migrations: {
1098
+ getSchema,
630
1099
  getBranchMigrationHistory,
631
1100
  getBranchMigrationPlan,
632
1101
  executeBranchMigrationPlan,
@@ -635,7 +1104,8 @@ const operationsByTag$2 = {
635
1104
  compareBranchSchemas,
636
1105
  updateBranchSchema,
637
1106
  previewBranchSchemaEdit,
638
- applyBranchSchemaEdit
1107
+ applyBranchSchemaEdit,
1108
+ pushBranchMigrations
639
1109
  },
640
1110
  migrationRequests: {
641
1111
  queryMigrationRequests,
@@ -669,11 +1139,24 @@ const operationsByTag$2 = {
669
1139
  deleteRecord,
670
1140
  bulkInsertTableRecords
671
1141
  },
672
- searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
1142
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess, fileUpload },
1143
+ searchAndFilter: {
1144
+ queryTable,
1145
+ searchBranch,
1146
+ searchTable,
1147
+ vectorSearchTable,
1148
+ askTable,
1149
+ askTableSession,
1150
+ summarizeTable,
1151
+ aggregateTable
1152
+ },
1153
+ sql: { sqlQuery }
673
1154
  };
674
1155
 
675
1156
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
676
1157
 
1158
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1159
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
677
1160
  const getUser = (variables, signal) => controlPlaneFetch({
678
1161
  url: "/user",
679
1162
  method: "get",
@@ -710,6 +1193,31 @@ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
710
1193
  ...variables,
711
1194
  signal
712
1195
  });
1196
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1197
+ url: "/user/oauth/clients",
1198
+ method: "get",
1199
+ ...variables,
1200
+ signal
1201
+ });
1202
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1203
+ url: "/user/oauth/clients/{clientId}",
1204
+ method: "delete",
1205
+ ...variables,
1206
+ signal
1207
+ });
1208
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1209
+ url: "/user/oauth/tokens",
1210
+ method: "get",
1211
+ ...variables,
1212
+ signal
1213
+ });
1214
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1215
+ url: "/user/oauth/tokens/{token}",
1216
+ method: "delete",
1217
+ ...variables,
1218
+ signal
1219
+ });
1220
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
713
1221
  const getWorkspacesList = (variables, signal) => controlPlaneFetch({
714
1222
  url: "/workspaces",
715
1223
  method: "get",
@@ -753,6 +1261,20 @@ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ u
753
1261
  const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
754
1262
  const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
755
1263
  const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1264
+ const listClusters = (variables, signal) => controlPlaneFetch({
1265
+ url: "/workspaces/{workspaceId}/clusters",
1266
+ method: "get",
1267
+ ...variables,
1268
+ signal
1269
+ });
1270
+ const createCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "post", ...variables, signal });
1271
+ const getCluster = (variables, signal) => controlPlaneFetch({
1272
+ url: "/workspaces/{workspaceId}/clusters/{clusterId}",
1273
+ method: "get",
1274
+ ...variables,
1275
+ signal
1276
+ });
1277
+ const updateCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters/{clusterId}", method: "patch", ...variables, signal });
756
1278
  const getDatabaseList = (variables, signal) => controlPlaneFetch({
757
1279
  url: "/workspaces/{workspaceId}/dbs",
758
1280
  method: "get",
@@ -768,6 +1290,7 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
768
1290
  });
769
1291
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
770
1292
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1293
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
771
1294
  const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
772
1295
  const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
773
1296
  const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
@@ -778,6 +1301,15 @@ const listRegions = (variables, signal) => controlPlaneFetch({
778
1301
  signal
779
1302
  });
780
1303
  const operationsByTag$1 = {
1304
+ oAuth: {
1305
+ getAuthorizationCode,
1306
+ grantAuthorizationCode,
1307
+ getUserOAuthClients,
1308
+ deleteUserOAuthClient,
1309
+ getUserOAuthAccessTokens,
1310
+ deleteOAuthAccessToken,
1311
+ updateOAuthAccessToken
1312
+ },
781
1313
  users: { getUser, updateUser, deleteUser },
782
1314
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
783
1315
  workspaces: {
@@ -797,12 +1329,14 @@ const operationsByTag$1 = {
797
1329
  acceptWorkspaceMemberInvite,
798
1330
  resendWorkspaceMemberInvite
799
1331
  },
1332
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
800
1333
  databases: {
801
1334
  getDatabaseList,
802
1335
  createDatabase,
803
1336
  deleteDatabase,
804
1337
  getDatabaseMetadata,
805
1338
  updateDatabaseMetadata,
1339
+ renameDatabase,
806
1340
  getDatabaseGithubSettings,
807
1341
  updateDatabaseGithubSettings,
808
1342
  deleteDatabaseGithubSettings,
@@ -812,51 +1346,6 @@ const operationsByTag$1 = {
812
1346
 
813
1347
  const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);
814
1348
 
815
- function getHostUrl(provider, type) {
816
- if (isHostProviderAlias(provider)) {
817
- return providers[provider][type];
818
- } else if (isHostProviderBuilder(provider)) {
819
- return provider[type];
820
- }
821
- throw new Error("Invalid API provider");
822
- }
823
- const providers = {
824
- production: {
825
- main: "https://api.xata.io",
826
- workspaces: "https://{workspaceId}.{region}.xata.sh"
827
- },
828
- staging: {
829
- main: "https://staging.xatabase.co",
830
- workspaces: "https://{workspaceId}.staging.{region}.xatabase.co"
831
- }
832
- };
833
- function isHostProviderAlias(alias) {
834
- return isString(alias) && Object.keys(providers).includes(alias);
835
- }
836
- function isHostProviderBuilder(builder) {
837
- return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
838
- }
839
- function parseProviderString(provider = "production") {
840
- if (isHostProviderAlias(provider)) {
841
- return provider;
842
- }
843
- const [main, workspaces] = provider.split(",");
844
- if (!main || !workspaces)
845
- return null;
846
- return { main, workspaces };
847
- }
848
- function parseWorkspacesUrlParts(url) {
849
- if (!isString(url))
850
- return null;
851
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
852
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
853
- const regexDev = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xata\.tech.*/;
854
- const match = url.match(regex) || url.match(regexStaging) || url.match(regexDev);
855
- if (!match)
856
- return null;
857
- return { workspace: match[1], region: match[2] };
858
- }
859
-
860
1349
  var __accessCheck$7 = (obj, member, msg) => {
861
1350
  if (!member.has(obj))
862
1351
  throw TypeError("Cannot " + msg);
@@ -890,7 +1379,7 @@ class XataApiClient {
890
1379
  __privateSet$7(this, _extraProps, {
891
1380
  apiUrl: getHostUrl(provider, "main"),
892
1381
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
893
- fetchImpl: getFetchImplementation(options.fetch),
1382
+ fetch: getFetchImplementation(options.fetch),
894
1383
  apiKey,
895
1384
  trace,
896
1385
  clientName: options.clientName,
@@ -948,6 +1437,11 @@ class XataApiClient {
948
1437
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
949
1438
  return __privateGet$7(this, _namespaces).records;
950
1439
  }
1440
+ get files() {
1441
+ if (!__privateGet$7(this, _namespaces).files)
1442
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1443
+ return __privateGet$7(this, _namespaces).files;
1444
+ }
951
1445
  get searchAndFilter() {
952
1446
  if (!__privateGet$7(this, _namespaces).searchAndFilter)
953
1447
  __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
@@ -1156,6 +1650,20 @@ class BranchApi {
1156
1650
  ...this.extraProps
1157
1651
  });
1158
1652
  }
1653
+ copyBranch({
1654
+ workspace,
1655
+ region,
1656
+ database,
1657
+ branch,
1658
+ destinationBranch,
1659
+ limit
1660
+ }) {
1661
+ return operationsByTag.branch.copyBranch({
1662
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1663
+ body: { destinationBranch, limit },
1664
+ ...this.extraProps
1665
+ });
1666
+ }
1159
1667
  updateBranchMetadata({
1160
1668
  workspace,
1161
1669
  region,
@@ -1511,6 +2019,164 @@ class RecordsApi {
1511
2019
  });
1512
2020
  }
1513
2021
  }
2022
+ class FilesApi {
2023
+ constructor(extraProps) {
2024
+ this.extraProps = extraProps;
2025
+ }
2026
+ getFileItem({
2027
+ workspace,
2028
+ region,
2029
+ database,
2030
+ branch,
2031
+ table,
2032
+ record,
2033
+ column,
2034
+ fileId
2035
+ }) {
2036
+ return operationsByTag.files.getFileItem({
2037
+ pathParams: {
2038
+ workspace,
2039
+ region,
2040
+ dbBranchName: `${database}:${branch}`,
2041
+ tableName: table,
2042
+ recordId: record,
2043
+ columnName: column,
2044
+ fileId
2045
+ },
2046
+ ...this.extraProps
2047
+ });
2048
+ }
2049
+ putFileItem({
2050
+ workspace,
2051
+ region,
2052
+ database,
2053
+ branch,
2054
+ table,
2055
+ record,
2056
+ column,
2057
+ fileId,
2058
+ file
2059
+ }) {
2060
+ return operationsByTag.files.putFileItem({
2061
+ pathParams: {
2062
+ workspace,
2063
+ region,
2064
+ dbBranchName: `${database}:${branch}`,
2065
+ tableName: table,
2066
+ recordId: record,
2067
+ columnName: column,
2068
+ fileId
2069
+ },
2070
+ // @ts-ignore
2071
+ body: file,
2072
+ ...this.extraProps
2073
+ });
2074
+ }
2075
+ deleteFileItem({
2076
+ workspace,
2077
+ region,
2078
+ database,
2079
+ branch,
2080
+ table,
2081
+ record,
2082
+ column,
2083
+ fileId
2084
+ }) {
2085
+ return operationsByTag.files.deleteFileItem({
2086
+ pathParams: {
2087
+ workspace,
2088
+ region,
2089
+ dbBranchName: `${database}:${branch}`,
2090
+ tableName: table,
2091
+ recordId: record,
2092
+ columnName: column,
2093
+ fileId
2094
+ },
2095
+ ...this.extraProps
2096
+ });
2097
+ }
2098
+ getFile({
2099
+ workspace,
2100
+ region,
2101
+ database,
2102
+ branch,
2103
+ table,
2104
+ record,
2105
+ column
2106
+ }) {
2107
+ return operationsByTag.files.getFile({
2108
+ pathParams: {
2109
+ workspace,
2110
+ region,
2111
+ dbBranchName: `${database}:${branch}`,
2112
+ tableName: table,
2113
+ recordId: record,
2114
+ columnName: column
2115
+ },
2116
+ ...this.extraProps
2117
+ });
2118
+ }
2119
+ putFile({
2120
+ workspace,
2121
+ region,
2122
+ database,
2123
+ branch,
2124
+ table,
2125
+ record,
2126
+ column,
2127
+ file
2128
+ }) {
2129
+ return operationsByTag.files.putFile({
2130
+ pathParams: {
2131
+ workspace,
2132
+ region,
2133
+ dbBranchName: `${database}:${branch}`,
2134
+ tableName: table,
2135
+ recordId: record,
2136
+ columnName: column
2137
+ },
2138
+ body: file,
2139
+ ...this.extraProps
2140
+ });
2141
+ }
2142
+ deleteFile({
2143
+ workspace,
2144
+ region,
2145
+ database,
2146
+ branch,
2147
+ table,
2148
+ record,
2149
+ column
2150
+ }) {
2151
+ return operationsByTag.files.deleteFile({
2152
+ pathParams: {
2153
+ workspace,
2154
+ region,
2155
+ dbBranchName: `${database}:${branch}`,
2156
+ tableName: table,
2157
+ recordId: record,
2158
+ columnName: column
2159
+ },
2160
+ ...this.extraProps
2161
+ });
2162
+ }
2163
+ fileAccess({
2164
+ workspace,
2165
+ region,
2166
+ fileId,
2167
+ verify
2168
+ }) {
2169
+ return operationsByTag.files.fileAccess({
2170
+ pathParams: {
2171
+ workspace,
2172
+ region,
2173
+ fileId
2174
+ },
2175
+ queryParams: { verify },
2176
+ ...this.extraProps
2177
+ });
2178
+ }
2179
+ }
1514
2180
  class SearchAndFilterApi {
1515
2181
  constructor(extraProps) {
1516
2182
  this.extraProps = extraProps;
@@ -1570,6 +2236,53 @@ class SearchAndFilterApi {
1570
2236
  ...this.extraProps
1571
2237
  });
1572
2238
  }
2239
+ vectorSearchTable({
2240
+ workspace,
2241
+ region,
2242
+ database,
2243
+ branch,
2244
+ table,
2245
+ queryVector,
2246
+ column,
2247
+ similarityFunction,
2248
+ size,
2249
+ filter
2250
+ }) {
2251
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2252
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2253
+ body: { queryVector, column, similarityFunction, size, filter },
2254
+ ...this.extraProps
2255
+ });
2256
+ }
2257
+ askTable({
2258
+ workspace,
2259
+ region,
2260
+ database,
2261
+ branch,
2262
+ table,
2263
+ options
2264
+ }) {
2265
+ return operationsByTag.searchAndFilter.askTable({
2266
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2267
+ body: { ...options },
2268
+ ...this.extraProps
2269
+ });
2270
+ }
2271
+ askTableSession({
2272
+ workspace,
2273
+ region,
2274
+ database,
2275
+ branch,
2276
+ table,
2277
+ sessionId,
2278
+ message
2279
+ }) {
2280
+ return operationsByTag.searchAndFilter.askTableSession({
2281
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2282
+ body: { message },
2283
+ ...this.extraProps
2284
+ });
2285
+ }
1573
2286
  summarizeTable({
1574
2287
  workspace,
1575
2288
  region,
@@ -1834,6 +2547,19 @@ class MigrationsApi {
1834
2547
  ...this.extraProps
1835
2548
  });
1836
2549
  }
2550
+ pushBranchMigrations({
2551
+ workspace,
2552
+ region,
2553
+ database,
2554
+ branch,
2555
+ migrations
2556
+ }) {
2557
+ return operationsByTag.migrations.pushBranchMigrations({
2558
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2559
+ body: { migrations },
2560
+ ...this.extraProps
2561
+ });
2562
+ }
1837
2563
  }
1838
2564
  class DatabaseApi {
1839
2565
  constructor(extraProps) {
@@ -1848,11 +2574,13 @@ class DatabaseApi {
1848
2574
  createDatabase({
1849
2575
  workspace,
1850
2576
  database,
1851
- data
2577
+ data,
2578
+ headers
1852
2579
  }) {
1853
2580
  return operationsByTag.databases.createDatabase({
1854
2581
  pathParams: { workspaceId: workspace, dbName: database },
1855
2582
  body: data,
2583
+ headers,
1856
2584
  ...this.extraProps
1857
2585
  });
1858
2586
  }
@@ -1874,14 +2602,25 @@ class DatabaseApi {
1874
2602
  ...this.extraProps
1875
2603
  });
1876
2604
  }
1877
- updateDatabaseMetadata({
2605
+ updateDatabaseMetadata({
2606
+ workspace,
2607
+ database,
2608
+ metadata
2609
+ }) {
2610
+ return operationsByTag.databases.updateDatabaseMetadata({
2611
+ pathParams: { workspaceId: workspace, dbName: database },
2612
+ body: metadata,
2613
+ ...this.extraProps
2614
+ });
2615
+ }
2616
+ renameDatabase({
1878
2617
  workspace,
1879
2618
  database,
1880
- metadata
2619
+ newName
1881
2620
  }) {
1882
- return operationsByTag.databases.updateDatabaseMetadata({
2621
+ return operationsByTag.databases.renameDatabase({
1883
2622
  pathParams: { workspaceId: workspace, dbName: database },
1884
- body: metadata,
2623
+ body: { newName },
1885
2624
  ...this.extraProps
1886
2625
  });
1887
2626
  }
@@ -1923,20 +2662,203 @@ class DatabaseApi {
1923
2662
  }
1924
2663
 
1925
2664
  class XataApiPlugin {
1926
- async build(options) {
1927
- const { fetchImpl, apiKey } = await options.getFetchProps();
1928
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2665
+ build(options) {
2666
+ return new XataApiClient(options);
1929
2667
  }
1930
2668
  }
1931
2669
 
1932
2670
  class XataPlugin {
1933
2671
  }
1934
2672
 
2673
+ function buildTransformString(transformations) {
2674
+ return transformations.flatMap(
2675
+ (t) => Object.entries(t).map(([key, value]) => {
2676
+ if (key === "trim") {
2677
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2678
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2679
+ }
2680
+ if (key === "gravity" && typeof value === "object") {
2681
+ const { x = 0.5, y = 0.5 } = value;
2682
+ return `${key}=${[x, y].join("x")}`;
2683
+ }
2684
+ return `${key}=${value}`;
2685
+ })
2686
+ ).join(",");
2687
+ }
2688
+ function transformImage(url, ...transformations) {
2689
+ if (!isDefined(url))
2690
+ return void 0;
2691
+ const newTransformations = buildTransformString(transformations);
2692
+ const { hostname, pathname, search } = new URL(url);
2693
+ const pathParts = pathname.split("/");
2694
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2695
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2696
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2697
+ const path = pathParts.join("/");
2698
+ return `https://${hostname}${transform}${path}${search}`;
2699
+ }
2700
+
2701
+ class XataFile {
2702
+ constructor(file) {
2703
+ this.id = file.id;
2704
+ this.name = file.name;
2705
+ this.mediaType = file.mediaType;
2706
+ this.base64Content = file.base64Content;
2707
+ this.enablePublicUrl = file.enablePublicUrl;
2708
+ this.signedUrlTimeout = file.signedUrlTimeout;
2709
+ this.uploadUrlTimeout = file.uploadUrlTimeout;
2710
+ this.size = file.size;
2711
+ this.version = file.version;
2712
+ this.url = file.url;
2713
+ this.signedUrl = file.signedUrl;
2714
+ this.uploadUrl = file.uploadUrl;
2715
+ this.attributes = file.attributes;
2716
+ }
2717
+ static fromBuffer(buffer, options = {}) {
2718
+ const base64Content = buffer.toString("base64");
2719
+ return new XataFile({ ...options, base64Content });
2720
+ }
2721
+ toBuffer() {
2722
+ if (!this.base64Content) {
2723
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2724
+ }
2725
+ return Buffer.from(this.base64Content, "base64");
2726
+ }
2727
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2728
+ const uint8Array = new Uint8Array(arrayBuffer);
2729
+ return this.fromUint8Array(uint8Array, options);
2730
+ }
2731
+ toArrayBuffer() {
2732
+ if (!this.base64Content) {
2733
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2734
+ }
2735
+ const binary = atob(this.base64Content);
2736
+ return new ArrayBuffer(binary.length);
2737
+ }
2738
+ static fromUint8Array(uint8Array, options = {}) {
2739
+ let binary = "";
2740
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2741
+ binary += String.fromCharCode(uint8Array[i]);
2742
+ }
2743
+ const base64Content = btoa(binary);
2744
+ return new XataFile({ ...options, base64Content });
2745
+ }
2746
+ toUint8Array() {
2747
+ if (!this.base64Content) {
2748
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2749
+ }
2750
+ const binary = atob(this.base64Content);
2751
+ const uint8Array = new Uint8Array(binary.length);
2752
+ for (let i = 0; i < binary.length; i++) {
2753
+ uint8Array[i] = binary.charCodeAt(i);
2754
+ }
2755
+ return uint8Array;
2756
+ }
2757
+ static async fromBlob(file, options = {}) {
2758
+ const name = options.name ?? file.name;
2759
+ const mediaType = file.type;
2760
+ const arrayBuffer = await file.arrayBuffer();
2761
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2762
+ }
2763
+ toBlob() {
2764
+ if (!this.base64Content) {
2765
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2766
+ }
2767
+ const binary = atob(this.base64Content);
2768
+ const uint8Array = new Uint8Array(binary.length);
2769
+ for (let i = 0; i < binary.length; i++) {
2770
+ uint8Array[i] = binary.charCodeAt(i);
2771
+ }
2772
+ return new Blob([uint8Array], { type: this.mediaType });
2773
+ }
2774
+ static fromString(string, options = {}) {
2775
+ const base64Content = btoa(string);
2776
+ return new XataFile({ ...options, base64Content });
2777
+ }
2778
+ toString() {
2779
+ if (!this.base64Content) {
2780
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2781
+ }
2782
+ return atob(this.base64Content);
2783
+ }
2784
+ static fromBase64(base64Content, options = {}) {
2785
+ return new XataFile({ ...options, base64Content });
2786
+ }
2787
+ toBase64() {
2788
+ if (!this.base64Content) {
2789
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2790
+ }
2791
+ return this.base64Content;
2792
+ }
2793
+ transform(...options) {
2794
+ return {
2795
+ url: transformImage(this.url, ...options),
2796
+ signedUrl: transformImage(this.signedUrl, ...options),
2797
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2798
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2799
+ };
2800
+ }
2801
+ }
2802
+ const parseInputFileEntry = async (entry) => {
2803
+ if (!isDefined(entry))
2804
+ return null;
2805
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout, uploadUrlTimeout } = await entry;
2806
+ return compactObject({
2807
+ id,
2808
+ // Name cannot be an empty string in our API
2809
+ name: name ? name : void 0,
2810
+ mediaType,
2811
+ base64Content,
2812
+ enablePublicUrl,
2813
+ signedUrlTimeout,
2814
+ uploadUrlTimeout
2815
+ });
2816
+ };
2817
+
1935
2818
  function cleanFilter(filter) {
1936
- if (!filter)
2819
+ if (!isDefined(filter))
1937
2820
  return void 0;
1938
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1939
- return values.length > 0 ? filter : void 0;
2821
+ if (!isObject(filter))
2822
+ return filter;
2823
+ const values = Object.fromEntries(
2824
+ Object.entries(filter).reduce((acc, [key, value]) => {
2825
+ if (!isDefined(value))
2826
+ return acc;
2827
+ if (Array.isArray(value)) {
2828
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2829
+ if (clean.length === 0)
2830
+ return acc;
2831
+ return [...acc, [key, clean]];
2832
+ }
2833
+ if (isObject(value)) {
2834
+ const clean = cleanFilter(value);
2835
+ if (!isDefined(clean))
2836
+ return acc;
2837
+ return [...acc, [key, clean]];
2838
+ }
2839
+ return [...acc, [key, value]];
2840
+ }, [])
2841
+ );
2842
+ return Object.keys(values).length > 0 ? values : void 0;
2843
+ }
2844
+
2845
+ function stringifyJson(value) {
2846
+ if (!isDefined(value))
2847
+ return value;
2848
+ if (isString(value))
2849
+ return value;
2850
+ try {
2851
+ return JSON.stringify(value);
2852
+ } catch (e) {
2853
+ return value;
2854
+ }
2855
+ }
2856
+ function parseJson(value) {
2857
+ try {
2858
+ return JSON.parse(value);
2859
+ } catch (e) {
2860
+ return value;
2861
+ }
1940
2862
  }
1941
2863
 
1942
2864
  var __accessCheck$6 = (obj, member, msg) => {
@@ -1965,31 +2887,59 @@ class Page {
1965
2887
  this.meta = meta;
1966
2888
  this.records = new RecordArray(this, records);
1967
2889
  }
2890
+ /**
2891
+ * Retrieves the next page of results.
2892
+ * @param size Maximum number of results to be retrieved.
2893
+ * @param offset Number of results to skip when retrieving the results.
2894
+ * @returns The next page or results.
2895
+ */
1968
2896
  async nextPage(size, offset) {
1969
2897
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
1970
2898
  }
2899
+ /**
2900
+ * Retrieves the previous page of results.
2901
+ * @param size Maximum number of results to be retrieved.
2902
+ * @param offset Number of results to skip when retrieving the results.
2903
+ * @returns The previous page or results.
2904
+ */
1971
2905
  async previousPage(size, offset) {
1972
2906
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1973
2907
  }
2908
+ /**
2909
+ * Retrieves the start page of results.
2910
+ * @param size Maximum number of results to be retrieved.
2911
+ * @param offset Number of results to skip when retrieving the results.
2912
+ * @returns The start page or results.
2913
+ */
1974
2914
  async startPage(size, offset) {
1975
2915
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1976
2916
  }
2917
+ /**
2918
+ * Retrieves the end page of results.
2919
+ * @param size Maximum number of results to be retrieved.
2920
+ * @param offset Number of results to skip when retrieving the results.
2921
+ * @returns The end page or results.
2922
+ */
1977
2923
  async endPage(size, offset) {
1978
2924
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1979
2925
  }
2926
+ /**
2927
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
2928
+ * @returns Whether or not there will be additional results in the next page of results.
2929
+ */
1980
2930
  hasNextPage() {
1981
2931
  return this.meta.page.more;
1982
2932
  }
1983
2933
  }
1984
2934
  _query = new WeakMap();
1985
- const PAGINATION_MAX_SIZE = 200;
2935
+ const PAGINATION_MAX_SIZE = 1e3;
1986
2936
  const PAGINATION_DEFAULT_SIZE = 20;
1987
- const PAGINATION_MAX_OFFSET = 800;
2937
+ const PAGINATION_MAX_OFFSET = 49e3;
1988
2938
  const PAGINATION_DEFAULT_OFFSET = 0;
1989
2939
  function isCursorPaginationOptions(options) {
1990
2940
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1991
2941
  }
1992
- const _RecordArray = class extends Array {
2942
+ const _RecordArray = class _RecordArray extends Array {
1993
2943
  constructor(...args) {
1994
2944
  super(..._RecordArray.parseConstructorParams(...args));
1995
2945
  __privateAdd$6(this, _page, void 0);
@@ -2017,28 +2967,51 @@ const _RecordArray = class extends Array {
2017
2967
  map(callbackfn, thisArg) {
2018
2968
  return this.toArray().map(callbackfn, thisArg);
2019
2969
  }
2970
+ /**
2971
+ * Retrieve next page of records
2972
+ *
2973
+ * @returns A new array of objects
2974
+ */
2020
2975
  async nextPage(size, offset) {
2021
2976
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
2022
2977
  return new _RecordArray(newPage);
2023
2978
  }
2979
+ /**
2980
+ * Retrieve previous page of records
2981
+ *
2982
+ * @returns A new array of objects
2983
+ */
2024
2984
  async previousPage(size, offset) {
2025
2985
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
2026
2986
  return new _RecordArray(newPage);
2027
2987
  }
2988
+ /**
2989
+ * Retrieve start page of records
2990
+ *
2991
+ * @returns A new array of objects
2992
+ */
2028
2993
  async startPage(size, offset) {
2029
2994
  const newPage = await __privateGet$6(this, _page).startPage(size, offset);
2030
2995
  return new _RecordArray(newPage);
2031
2996
  }
2997
+ /**
2998
+ * Retrieve end page of records
2999
+ *
3000
+ * @returns A new array of objects
3001
+ */
2032
3002
  async endPage(size, offset) {
2033
3003
  const newPage = await __privateGet$6(this, _page).endPage(size, offset);
2034
3004
  return new _RecordArray(newPage);
2035
3005
  }
3006
+ /**
3007
+ * @returns Boolean indicating if there is a next page
3008
+ */
2036
3009
  hasNextPage() {
2037
3010
  return __privateGet$6(this, _page).meta.page.more;
2038
3011
  }
2039
3012
  };
2040
- let RecordArray = _RecordArray;
2041
3013
  _page = new WeakMap();
3014
+ let RecordArray = _RecordArray;
2042
3015
 
2043
3016
  var __accessCheck$5 = (obj, member, msg) => {
2044
3017
  if (!member.has(obj))
@@ -2063,13 +3036,14 @@ var __privateMethod$3 = (obj, member, method) => {
2063
3036
  return method;
2064
3037
  };
2065
3038
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
2066
- const _Query = class {
3039
+ const _Query = class _Query {
2067
3040
  constructor(repository, table, data, rawParent) {
2068
3041
  __privateAdd$5(this, _cleanFilterConstraint);
2069
3042
  __privateAdd$5(this, _table$1, void 0);
2070
3043
  __privateAdd$5(this, _repository, void 0);
2071
3044
  __privateAdd$5(this, _data, { filter: {} });
2072
- this.meta = { page: { cursor: "start", more: true } };
3045
+ // Implements pagination
3046
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
2073
3047
  this.records = new RecordArray(this, []);
2074
3048
  __privateSet$5(this, _table$1, table);
2075
3049
  if (repository) {
@@ -2106,18 +3080,38 @@ const _Query = class {
2106
3080
  const key = JSON.stringify({ columns, filter, sort, pagination });
2107
3081
  return toBase64(key);
2108
3082
  }
3083
+ /**
3084
+ * Builds a new query object representing a logical OR between the given subqueries.
3085
+ * @param queries An array of subqueries.
3086
+ * @returns A new Query object.
3087
+ */
2109
3088
  any(...queries) {
2110
3089
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
2111
3090
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
2112
3091
  }
3092
+ /**
3093
+ * Builds a new query object representing a logical AND between the given subqueries.
3094
+ * @param queries An array of subqueries.
3095
+ * @returns A new Query object.
3096
+ */
2113
3097
  all(...queries) {
2114
3098
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
2115
3099
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
2116
3100
  }
3101
+ /**
3102
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3103
+ * @param queries An array of subqueries.
3104
+ * @returns A new Query object.
3105
+ */
2117
3106
  not(...queries) {
2118
3107
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
2119
3108
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
2120
3109
  }
3110
+ /**
3111
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3112
+ * @param queries An array of subqueries.
3113
+ * @returns A new Query object.
3114
+ */
2121
3115
  none(...queries) {
2122
3116
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
2123
3117
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
@@ -2140,6 +3134,11 @@ const _Query = class {
2140
3134
  const sort = [...originalSort, { column, direction }];
2141
3135
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
2142
3136
  }
3137
+ /**
3138
+ * Builds a new query specifying the set of columns to be returned in the query response.
3139
+ * @param columns Array of column names to be returned by the query.
3140
+ * @returns A new Query object.
3141
+ */
2143
3142
  select(columns) {
2144
3143
  return new _Query(
2145
3144
  __privateGet$5(this, _repository),
@@ -2152,6 +3151,12 @@ const _Query = class {
2152
3151
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
2153
3152
  return __privateGet$5(this, _repository).query(query);
2154
3153
  }
3154
+ /**
3155
+ * Get results in an iterator
3156
+ *
3157
+ * @async
3158
+ * @returns Async interable of results
3159
+ */
2155
3160
  async *[Symbol.asyncIterator]() {
2156
3161
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
2157
3162
  yield record;
@@ -2212,26 +3217,53 @@ const _Query = class {
2212
3217
  );
2213
3218
  return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2214
3219
  }
3220
+ /**
3221
+ * Builds a new query object adding a cache TTL in milliseconds.
3222
+ * @param ttl The cache TTL in milliseconds.
3223
+ * @returns A new Query object.
3224
+ */
2215
3225
  cache(ttl) {
2216
3226
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2217
3227
  }
3228
+ /**
3229
+ * Retrieve next page of records
3230
+ *
3231
+ * @returns A new page object.
3232
+ */
2218
3233
  nextPage(size, offset) {
2219
3234
  return this.startPage(size, offset);
2220
3235
  }
3236
+ /**
3237
+ * Retrieve previous page of records
3238
+ *
3239
+ * @returns A new page object
3240
+ */
2221
3241
  previousPage(size, offset) {
2222
3242
  return this.startPage(size, offset);
2223
3243
  }
3244
+ /**
3245
+ * Retrieve start page of records
3246
+ *
3247
+ * @returns A new page object
3248
+ */
2224
3249
  startPage(size, offset) {
2225
3250
  return this.getPaginated({ pagination: { size, offset } });
2226
3251
  }
3252
+ /**
3253
+ * Retrieve last page of records
3254
+ *
3255
+ * @returns A new page object
3256
+ */
2227
3257
  endPage(size, offset) {
2228
3258
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2229
3259
  }
3260
+ /**
3261
+ * @returns Boolean indicating if there is a next page
3262
+ */
2230
3263
  hasNextPage() {
2231
3264
  return this.meta.page.more;
2232
3265
  }
2233
3266
  };
2234
- let Query = _Query;
2235
3267
  _table$1 = new WeakMap();
2236
3268
  _repository = new WeakMap();
2237
3269
  _data = new WeakMap();
@@ -2246,6 +3278,7 @@ cleanFilterConstraint_fn = function(column, value) {
2246
3278
  }
2247
3279
  return value;
2248
3280
  };
3281
+ let Query = _Query;
2249
3282
  function cleanParent(data, parent) {
2250
3283
  if (isCursorPaginationOptions(data.pagination)) {
2251
3284
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2253,6 +3286,22 @@ function cleanParent(data, parent) {
2253
3286
  return parent;
2254
3287
  }
2255
3288
 
3289
+ const RecordColumnTypes = [
3290
+ "bool",
3291
+ "int",
3292
+ "float",
3293
+ "string",
3294
+ "text",
3295
+ "email",
3296
+ "multiple",
3297
+ "link",
3298
+ "object",
3299
+ "datetime",
3300
+ "vector",
3301
+ "file[]",
3302
+ "file",
3303
+ "json"
3304
+ ];
2256
3305
  function isIdentifiable(x) {
2257
3306
  return isObject(x) && isString(x?.id);
2258
3307
  }
@@ -2262,11 +3311,33 @@ function isXataRecord(x) {
2262
3311
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
2263
3312
  }
2264
3313
 
3314
+ function isValidExpandedColumn(column) {
3315
+ return isObject(column) && isString(column.name);
3316
+ }
3317
+ function isValidSelectableColumns(columns) {
3318
+ if (!Array.isArray(columns)) {
3319
+ return false;
3320
+ }
3321
+ return columns.every((column) => {
3322
+ if (typeof column === "string") {
3323
+ return true;
3324
+ }
3325
+ if (typeof column === "object") {
3326
+ return isValidExpandedColumn(column);
3327
+ }
3328
+ return false;
3329
+ });
3330
+ }
3331
+
2265
3332
  function isSortFilterString(value) {
2266
3333
  return isString(value);
2267
3334
  }
2268
3335
  function isSortFilterBase(filter) {
2269
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
3336
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
3337
+ if (key === "*")
3338
+ return value === "random";
3339
+ return value === "asc" || value === "desc";
3340
+ });
2270
3341
  }
2271
3342
  function isSortFilterObject(filter) {
2272
3343
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -2307,7 +3378,7 @@ var __privateMethod$2 = (obj, member, method) => {
2307
3378
  __accessCheck$4(obj, member, "access private method");
2308
3379
  return method;
2309
3380
  };
2310
- 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;
3381
+ 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;
2311
3382
  const BULK_OPERATION_MAX_SIZE = 1e3;
2312
3383
  class Repository extends Query {
2313
3384
  }
@@ -2329,6 +3400,7 @@ class RestRepository extends Query {
2329
3400
  __privateAdd$4(this, _setCacheQuery);
2330
3401
  __privateAdd$4(this, _getCacheQuery);
2331
3402
  __privateAdd$4(this, _getSchemaTables$1);
3403
+ __privateAdd$4(this, _transformObjectToApi);
2332
3404
  __privateAdd$4(this, _table, void 0);
2333
3405
  __privateAdd$4(this, _getFetchProps, void 0);
2334
3406
  __privateAdd$4(this, _db, void 0);
@@ -2339,10 +3411,7 @@ class RestRepository extends Query {
2339
3411
  __privateSet$4(this, _db, options.db);
2340
3412
  __privateSet$4(this, _cache, options.pluginOptions.cache);
2341
3413
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2342
- __privateSet$4(this, _getFetchProps, async () => {
2343
- const props = await options.pluginOptions.getFetchProps();
2344
- return { ...props, sessionID: generateUUID() };
2345
- });
3414
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2346
3415
  const trace = options.pluginOptions.trace ?? defaultTrace;
2347
3416
  __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2348
3417
  return trace(name, fn, {
@@ -2360,24 +3429,24 @@ class RestRepository extends Query {
2360
3429
  if (a.length === 0)
2361
3430
  return [];
2362
3431
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2363
- const columns = isStringArray(b) ? b : ["*"];
3432
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2364
3433
  const result = await this.read(ids, columns);
2365
3434
  return result;
2366
3435
  }
2367
3436
  if (isString(a) && isObject(b)) {
2368
3437
  if (a === "")
2369
3438
  throw new Error("The id can't be empty");
2370
- const columns = isStringArray(c) ? c : void 0;
3439
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2371
3440
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2372
3441
  }
2373
3442
  if (isObject(a) && isString(a.id)) {
2374
3443
  if (a.id === "")
2375
3444
  throw new Error("The id can't be empty");
2376
- const columns = isStringArray(b) ? b : void 0;
3445
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2377
3446
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2378
3447
  }
2379
3448
  if (isObject(a)) {
2380
- const columns = isStringArray(b) ? b : void 0;
3449
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2381
3450
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2382
3451
  }
2383
3452
  throw new Error("Invalid arguments for create method");
@@ -2385,7 +3454,7 @@ class RestRepository extends Query {
2385
3454
  }
2386
3455
  async read(a, b) {
2387
3456
  return __privateGet$4(this, _trace).call(this, "read", async () => {
2388
- const columns = isStringArray(b) ? b : ["*"];
3457
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2389
3458
  if (Array.isArray(a)) {
2390
3459
  if (a.length === 0)
2391
3460
  return [];
@@ -2399,7 +3468,6 @@ class RestRepository extends Query {
2399
3468
  }
2400
3469
  const id = extractId(a);
2401
3470
  if (id) {
2402
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2403
3471
  try {
2404
3472
  const response = await getRecord({
2405
3473
  pathParams: {
@@ -2410,10 +3478,16 @@ class RestRepository extends Query {
2410
3478
  recordId: id
2411
3479
  },
2412
3480
  queryParams: { columns },
2413
- ...fetchProps
3481
+ ...__privateGet$4(this, _getFetchProps).call(this)
2414
3482
  });
2415
3483
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2416
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3484
+ return initObject(
3485
+ __privateGet$4(this, _db),
3486
+ schemaTables,
3487
+ __privateGet$4(this, _table),
3488
+ response,
3489
+ columns
3490
+ );
2417
3491
  } catch (e) {
2418
3492
  if (isObject(e) && e.status === 404) {
2419
3493
  return null;
@@ -2455,17 +3529,17 @@ class RestRepository extends Query {
2455
3529
  ifVersion,
2456
3530
  upsert: false
2457
3531
  });
2458
- const columns = isStringArray(b) ? b : ["*"];
3532
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2459
3533
  const result = await this.read(a, columns);
2460
3534
  return result;
2461
3535
  }
2462
3536
  try {
2463
3537
  if (isString(a) && isObject(b)) {
2464
- const columns = isStringArray(c) ? c : void 0;
3538
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2465
3539
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2466
3540
  }
2467
3541
  if (isObject(a) && isString(a.id)) {
2468
- const columns = isStringArray(b) ? b : void 0;
3542
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2469
3543
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2470
3544
  }
2471
3545
  } catch (error) {
@@ -2505,17 +3579,27 @@ class RestRepository extends Query {
2505
3579
  ifVersion,
2506
3580
  upsert: true
2507
3581
  });
2508
- const columns = isStringArray(b) ? b : ["*"];
3582
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2509
3583
  const result = await this.read(a, columns);
2510
3584
  return result;
2511
3585
  }
2512
3586
  if (isString(a) && isObject(b)) {
2513
- const columns = isStringArray(c) ? c : void 0;
2514
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3587
+ if (a === "")
3588
+ throw new Error("The id can't be empty");
3589
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3590
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2515
3591
  }
2516
3592
  if (isObject(a) && isString(a.id)) {
2517
- const columns = isStringArray(c) ? c : void 0;
2518
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3593
+ if (a.id === "")
3594
+ throw new Error("The id can't be empty");
3595
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3596
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3597
+ }
3598
+ if (!isDefined(a) && isObject(b)) {
3599
+ return await this.create(b, c);
3600
+ }
3601
+ if (isObject(a) && !isDefined(a.id)) {
3602
+ return await this.create(a, b);
2519
3603
  }
2520
3604
  throw new Error("Invalid arguments for createOrUpdate method");
2521
3605
  });
@@ -2527,17 +3611,27 @@ class RestRepository extends Query {
2527
3611
  if (a.length === 0)
2528
3612
  return [];
2529
3613
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2530
- const columns = isStringArray(b) ? b : ["*"];
3614
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2531
3615
  const result = await this.read(ids, columns);
2532
3616
  return result;
2533
3617
  }
2534
3618
  if (isString(a) && isObject(b)) {
2535
- const columns = isStringArray(c) ? c : void 0;
2536
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3619
+ if (a === "")
3620
+ throw new Error("The id can't be empty");
3621
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3622
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2537
3623
  }
2538
3624
  if (isObject(a) && isString(a.id)) {
2539
- const columns = isStringArray(c) ? c : void 0;
2540
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3625
+ if (a.id === "")
3626
+ throw new Error("The id can't be empty");
3627
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3628
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3629
+ }
3630
+ if (!isDefined(a) && isObject(b)) {
3631
+ return await this.create(b, c);
3632
+ }
3633
+ if (isObject(a) && !isDefined(a.id)) {
3634
+ return await this.create(a, b);
2541
3635
  }
2542
3636
  throw new Error("Invalid arguments for createOrReplace method");
2543
3637
  });
@@ -2554,7 +3648,7 @@ class RestRepository extends Query {
2554
3648
  return o.id;
2555
3649
  throw new Error("Invalid arguments for delete method");
2556
3650
  });
2557
- const columns = isStringArray(b) ? b : ["*"];
3651
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2558
3652
  const result = await this.read(a, columns);
2559
3653
  await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2560
3654
  return result;
@@ -2588,8 +3682,7 @@ class RestRepository extends Query {
2588
3682
  }
2589
3683
  async search(query, options = {}) {
2590
3684
  return __privateGet$4(this, _trace).call(this, "search", async () => {
2591
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2592
- const { records } = await searchTable({
3685
+ const { records, totalCount } = await searchTable({
2593
3686
  pathParams: {
2594
3687
  workspace: "{workspaceId}",
2595
3688
  dbBranchName: "{dbBranch}",
@@ -2606,15 +3699,42 @@ class RestRepository extends Query {
2606
3699
  page: options.page,
2607
3700
  target: options.target
2608
3701
  },
2609
- ...fetchProps
3702
+ ...__privateGet$4(this, _getFetchProps).call(this)
3703
+ });
3704
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3705
+ return {
3706
+ records: records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"])),
3707
+ totalCount
3708
+ };
3709
+ });
3710
+ }
3711
+ async vectorSearch(column, query, options) {
3712
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3713
+ const { records, totalCount } = await vectorSearchTable({
3714
+ pathParams: {
3715
+ workspace: "{workspaceId}",
3716
+ dbBranchName: "{dbBranch}",
3717
+ region: "{region}",
3718
+ tableName: __privateGet$4(this, _table)
3719
+ },
3720
+ body: {
3721
+ column,
3722
+ queryVector: query,
3723
+ similarityFunction: options?.similarityFunction,
3724
+ size: options?.size,
3725
+ filter: options?.filter
3726
+ },
3727
+ ...__privateGet$4(this, _getFetchProps).call(this)
2610
3728
  });
2611
3729
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2612
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3730
+ return {
3731
+ records: records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"])),
3732
+ totalCount
3733
+ };
2613
3734
  });
2614
3735
  }
2615
3736
  async aggregate(aggs, filter) {
2616
3737
  return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2617
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2618
3738
  const result = await aggregateTable({
2619
3739
  pathParams: {
2620
3740
  workspace: "{workspaceId}",
@@ -2623,7 +3743,7 @@ class RestRepository extends Query {
2623
3743
  tableName: __privateGet$4(this, _table)
2624
3744
  },
2625
3745
  body: { aggs, filter },
2626
- ...fetchProps
3746
+ ...__privateGet$4(this, _getFetchProps).call(this)
2627
3747
  });
2628
3748
  return result;
2629
3749
  });
@@ -2634,7 +3754,6 @@ class RestRepository extends Query {
2634
3754
  if (cacheQuery)
2635
3755
  return new Page(query, cacheQuery.meta, cacheQuery.records);
2636
3756
  const data = query.getQueryOptions();
2637
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2638
3757
  const { meta, records: objects } = await queryTable({
2639
3758
  pathParams: {
2640
3759
  workspace: "{workspaceId}",
@@ -2650,11 +3769,17 @@ class RestRepository extends Query {
2650
3769
  consistency: data.consistency
2651
3770
  },
2652
3771
  fetchOptions: data.fetchOptions,
2653
- ...fetchProps
3772
+ ...__privateGet$4(this, _getFetchProps).call(this)
2654
3773
  });
2655
3774
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2656
3775
  const records = objects.map(
2657
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3776
+ (record) => initObject(
3777
+ __privateGet$4(this, _db),
3778
+ schemaTables,
3779
+ __privateGet$4(this, _table),
3780
+ record,
3781
+ data.columns ?? ["*"]
3782
+ )
2658
3783
  );
2659
3784
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
2660
3785
  return new Page(query, meta, records);
@@ -2663,7 +3788,6 @@ class RestRepository extends Query {
2663
3788
  async summarizeTable(query, summaries, summariesFilter) {
2664
3789
  return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2665
3790
  const data = query.getQueryOptions();
2666
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2667
3791
  const result = await summarizeTable({
2668
3792
  pathParams: {
2669
3793
  workspace: "{workspaceId}",
@@ -2680,11 +3804,50 @@ class RestRepository extends Query {
2680
3804
  summaries,
2681
3805
  summariesFilter
2682
3806
  },
2683
- ...fetchProps
3807
+ ...__privateGet$4(this, _getFetchProps).call(this)
2684
3808
  });
2685
- return result;
3809
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3810
+ return {
3811
+ ...result,
3812
+ summaries: result.summaries.map(
3813
+ (summary) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), summary, data.columns ?? [])
3814
+ )
3815
+ };
2686
3816
  });
2687
3817
  }
3818
+ ask(question, options) {
3819
+ const questionParam = options?.sessionId ? { message: question } : { question };
3820
+ const params = {
3821
+ pathParams: {
3822
+ workspace: "{workspaceId}",
3823
+ dbBranchName: "{dbBranch}",
3824
+ region: "{region}",
3825
+ tableName: __privateGet$4(this, _table),
3826
+ sessionId: options?.sessionId
3827
+ },
3828
+ body: {
3829
+ ...questionParam,
3830
+ rules: options?.rules,
3831
+ searchType: options?.searchType,
3832
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3833
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3834
+ },
3835
+ ...__privateGet$4(this, _getFetchProps).call(this)
3836
+ };
3837
+ if (options?.onMessage) {
3838
+ fetchSSERequest({
3839
+ endpoint: "dataPlane",
3840
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3841
+ method: "POST",
3842
+ onMessage: (message) => {
3843
+ options.onMessage?.({ answer: message.text, records: message.records });
3844
+ },
3845
+ ...params
3846
+ });
3847
+ } else {
3848
+ return askTableSession(params);
3849
+ }
3850
+ }
2688
3851
  }
2689
3852
  _table = new WeakMap();
2690
3853
  _getFetchProps = new WeakMap();
@@ -2694,8 +3857,7 @@ _schemaTables$2 = new WeakMap();
2694
3857
  _trace = new WeakMap();
2695
3858
  _insertRecordWithoutId = new WeakSet();
2696
3859
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2697
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2698
- const record = transformObjectLinks(object);
3860
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2699
3861
  const response = await insertRecord({
2700
3862
  pathParams: {
2701
3863
  workspace: "{workspaceId}",
@@ -2705,15 +3867,16 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2705
3867
  },
2706
3868
  queryParams: { columns },
2707
3869
  body: record,
2708
- ...fetchProps
3870
+ ...__privateGet$4(this, _getFetchProps).call(this)
2709
3871
  });
2710
3872
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2711
3873
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2712
3874
  };
2713
3875
  _insertRecordWithId = new WeakSet();
2714
3876
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2715
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2716
- const record = transformObjectLinks(object);
3877
+ if (!recordId)
3878
+ return null;
3879
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2717
3880
  const response = await insertRecordWithID({
2718
3881
  pathParams: {
2719
3882
  workspace: "{workspaceId}",
@@ -2724,30 +3887,28 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2724
3887
  },
2725
3888
  body: record,
2726
3889
  queryParams: { createOnly, columns, ifVersion },
2727
- ...fetchProps
3890
+ ...__privateGet$4(this, _getFetchProps).call(this)
2728
3891
  });
2729
3892
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2730
3893
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2731
3894
  };
2732
3895
  _insertRecords = new WeakSet();
2733
3896
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2734
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2735
- const chunkedOperations = chunk(
2736
- objects.map((object) => ({
2737
- insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2738
- })),
2739
- BULK_OPERATION_MAX_SIZE
2740
- );
3897
+ const operations = await promiseMap(objects, async (object) => {
3898
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3899
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
3900
+ });
3901
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2741
3902
  const ids = [];
2742
- for (const operations of chunkedOperations) {
3903
+ for (const operations2 of chunkedOperations) {
2743
3904
  const { results } = await branchTransaction({
2744
3905
  pathParams: {
2745
3906
  workspace: "{workspaceId}",
2746
3907
  dbBranchName: "{dbBranch}",
2747
3908
  region: "{region}"
2748
3909
  },
2749
- body: { operations },
2750
- ...fetchProps
3910
+ body: { operations: operations2 },
3911
+ ...__privateGet$4(this, _getFetchProps).call(this)
2751
3912
  });
2752
3913
  for (const result of results) {
2753
3914
  if (result.operation === "insert") {
@@ -2761,8 +3922,9 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2761
3922
  };
2762
3923
  _updateRecordWithID = new WeakSet();
2763
3924
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2764
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2765
- const { id: _id, ...record } = transformObjectLinks(object);
3925
+ if (!recordId)
3926
+ return null;
3927
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2766
3928
  try {
2767
3929
  const response = await updateRecordWithID({
2768
3930
  pathParams: {
@@ -2774,7 +3936,7 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2774
3936
  },
2775
3937
  queryParams: { columns, ifVersion },
2776
3938
  body: record,
2777
- ...fetchProps
3939
+ ...__privateGet$4(this, _getFetchProps).call(this)
2778
3940
  });
2779
3941
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2780
3942
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2787,23 +3949,21 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2787
3949
  };
2788
3950
  _updateRecords = new WeakSet();
2789
3951
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2790
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2791
- const chunkedOperations = chunk(
2792
- objects.map(({ id, ...object }) => ({
2793
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2794
- })),
2795
- BULK_OPERATION_MAX_SIZE
2796
- );
3952
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
3953
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3954
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
3955
+ });
3956
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2797
3957
  const ids = [];
2798
- for (const operations of chunkedOperations) {
3958
+ for (const operations2 of chunkedOperations) {
2799
3959
  const { results } = await branchTransaction({
2800
3960
  pathParams: {
2801
3961
  workspace: "{workspaceId}",
2802
3962
  dbBranchName: "{dbBranch}",
2803
3963
  region: "{region}"
2804
3964
  },
2805
- body: { operations },
2806
- ...fetchProps
3965
+ body: { operations: operations2 },
3966
+ ...__privateGet$4(this, _getFetchProps).call(this)
2807
3967
  });
2808
3968
  for (const result of results) {
2809
3969
  if (result.operation === "update") {
@@ -2817,7 +3977,8 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2817
3977
  };
2818
3978
  _upsertRecordWithID = new WeakSet();
2819
3979
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2820
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3980
+ if (!recordId)
3981
+ return null;
2821
3982
  const response = await upsertRecordWithID({
2822
3983
  pathParams: {
2823
3984
  workspace: "{workspaceId}",
@@ -2828,14 +3989,15 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2828
3989
  },
2829
3990
  queryParams: { columns, ifVersion },
2830
3991
  body: object,
2831
- ...fetchProps
3992
+ ...__privateGet$4(this, _getFetchProps).call(this)
2832
3993
  });
2833
3994
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2834
3995
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2835
3996
  };
2836
3997
  _deleteRecord = new WeakSet();
2837
3998
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
2838
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3999
+ if (!recordId)
4000
+ return null;
2839
4001
  try {
2840
4002
  const response = await deleteRecord({
2841
4003
  pathParams: {
@@ -2846,7 +4008,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2846
4008
  recordId
2847
4009
  },
2848
4010
  queryParams: { columns },
2849
- ...fetchProps
4011
+ ...__privateGet$4(this, _getFetchProps).call(this)
2850
4012
  });
2851
4013
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2852
4014
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2859,9 +4021,8 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2859
4021
  };
2860
4022
  _deleteRecords = new WeakSet();
2861
4023
  deleteRecords_fn = async function(recordIds) {
2862
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2863
4024
  const chunkedOperations = chunk(
2864
- recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
4025
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2865
4026
  BULK_OPERATION_MAX_SIZE
2866
4027
  );
2867
4028
  for (const operations of chunkedOperations) {
@@ -2872,21 +4033,22 @@ deleteRecords_fn = async function(recordIds) {
2872
4033
  region: "{region}"
2873
4034
  },
2874
4035
  body: { operations },
2875
- ...fetchProps
4036
+ ...__privateGet$4(this, _getFetchProps).call(this)
2876
4037
  });
2877
4038
  }
2878
4039
  };
2879
4040
  _setCacheQuery = new WeakSet();
2880
4041
  setCacheQuery_fn = async function(query, meta, records) {
2881
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
4042
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
2882
4043
  };
2883
4044
  _getCacheQuery = new WeakSet();
2884
4045
  getCacheQuery_fn = async function(query) {
2885
4046
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2886
- const result = await __privateGet$4(this, _cache).get(key);
4047
+ const result = await __privateGet$4(this, _cache)?.get(key);
2887
4048
  if (!result)
2888
4049
  return null;
2889
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
4050
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
4051
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2890
4052
  if (ttl < 0)
2891
4053
  return null;
2892
4054
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2896,20 +4058,47 @@ _getSchemaTables$1 = new WeakSet();
2896
4058
  getSchemaTables_fn$1 = async function() {
2897
4059
  if (__privateGet$4(this, _schemaTables$2))
2898
4060
  return __privateGet$4(this, _schemaTables$2);
2899
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2900
4061
  const { schema } = await getBranchDetails({
2901
4062
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2902
- ...fetchProps
4063
+ ...__privateGet$4(this, _getFetchProps).call(this)
2903
4064
  });
2904
4065
  __privateSet$4(this, _schemaTables$2, schema.tables);
2905
4066
  return schema.tables;
2906
4067
  };
2907
- const transformObjectLinks = (object) => {
2908
- return Object.entries(object).reduce((acc, [key, value]) => {
4068
+ _transformObjectToApi = new WeakSet();
4069
+ transformObjectToApi_fn = async function(object) {
4070
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4071
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
4072
+ if (!schema)
4073
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
4074
+ const result = {};
4075
+ for (const [key, value] of Object.entries(object)) {
2909
4076
  if (key === "xata")
2910
- return acc;
2911
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
2912
- }, {});
4077
+ continue;
4078
+ const type = schema.columns.find((column) => column.name === key)?.type;
4079
+ switch (type) {
4080
+ case "link": {
4081
+ result[key] = isIdentifiable(value) ? value.id : value;
4082
+ break;
4083
+ }
4084
+ case "datetime": {
4085
+ result[key] = value instanceof Date ? value.toISOString() : value;
4086
+ break;
4087
+ }
4088
+ case `file`:
4089
+ result[key] = await parseInputFileEntry(value);
4090
+ break;
4091
+ case "file[]":
4092
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4093
+ break;
4094
+ case "json":
4095
+ result[key] = stringifyJson(value);
4096
+ break;
4097
+ default:
4098
+ result[key] = value;
4099
+ }
4100
+ }
4101
+ return result;
2913
4102
  };
2914
4103
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2915
4104
  const data = {};
@@ -2941,18 +4130,33 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2941
4130
  if (item === column.name) {
2942
4131
  return [...acc, "*"];
2943
4132
  }
2944
- if (item.startsWith(`${column.name}.`)) {
4133
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
2945
4134
  const [, ...path] = item.split(".");
2946
4135
  return [...acc, path.join(".")];
2947
4136
  }
2948
4137
  return acc;
2949
4138
  }, []);
2950
- data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4139
+ data[column.name] = initObject(
4140
+ db,
4141
+ schemaTables,
4142
+ linkTable,
4143
+ value,
4144
+ selectedLinkColumns
4145
+ );
2951
4146
  } else {
2952
4147
  data[column.name] = null;
2953
4148
  }
2954
4149
  break;
2955
4150
  }
4151
+ case "file":
4152
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4153
+ break;
4154
+ case "file[]":
4155
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4156
+ break;
4157
+ case "json":
4158
+ data[column.name] = parseJson(value);
4159
+ break;
2956
4160
  default:
2957
4161
  data[column.name] = value ?? null;
2958
4162
  if (column.notNull === true && value === null) {
@@ -2962,30 +4166,34 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2962
4166
  }
2963
4167
  }
2964
4168
  const record = { ...data };
4169
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
2965
4170
  record.read = function(columns2) {
2966
4171
  return db[table].read(record["id"], columns2);
2967
4172
  };
2968
4173
  record.update = function(data2, b, c) {
2969
- const columns2 = isStringArray(b) ? b : ["*"];
4174
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2970
4175
  const ifVersion = parseIfVersion(b, c);
2971
4176
  return db[table].update(record["id"], data2, columns2, { ifVersion });
2972
4177
  };
2973
4178
  record.replace = function(data2, b, c) {
2974
- const columns2 = isStringArray(b) ? b : ["*"];
4179
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2975
4180
  const ifVersion = parseIfVersion(b, c);
2976
4181
  return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2977
4182
  };
2978
4183
  record.delete = function() {
2979
4184
  return db[table].delete(record["id"]);
2980
4185
  };
4186
+ if (metadata !== void 0) {
4187
+ record.xata = Object.freeze(metadata);
4188
+ }
2981
4189
  record.getMetadata = function() {
2982
- return xata;
4190
+ return record.xata;
2983
4191
  };
2984
4192
  record.toSerializable = function() {
2985
- return JSON.parse(JSON.stringify(transformObjectLinks(data)));
4193
+ return JSON.parse(JSON.stringify(record));
2986
4194
  };
2987
4195
  record.toString = function() {
2988
- return JSON.stringify(transformObjectLinks(data));
4196
+ return JSON.stringify(record);
2989
4197
  };
2990
4198
  for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
2991
4199
  Object.defineProperty(record, prop, { enumerable: false });
@@ -3003,11 +4211,7 @@ function extractId(value) {
3003
4211
  function isValidColumn(columns, column) {
3004
4212
  if (columns.includes("*"))
3005
4213
  return true;
3006
- if (column.type === "link") {
3007
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
3008
- return linkColumns.length > 0;
3009
- }
3010
- return columns.includes(column.name);
4214
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
3011
4215
  }
3012
4216
  function parseIfVersion(...args) {
3013
4217
  for (const arg of args) {
@@ -3084,10 +4288,12 @@ const notExists = (column) => ({ $notExists: column });
3084
4288
  const startsWith = (value) => ({ $startsWith: value });
3085
4289
  const endsWith = (value) => ({ $endsWith: value });
3086
4290
  const pattern = (value) => ({ $pattern: value });
4291
+ const iPattern = (value) => ({ $iPattern: value });
3087
4292
  const is = (value) => ({ $is: value });
3088
4293
  const equals = is;
3089
4294
  const isNot = (value) => ({ $isNot: value });
3090
4295
  const contains = (value) => ({ $contains: value });
4296
+ const iContains = (value) => ({ $iContains: value });
3091
4297
  const includes = (value) => ({ $includes: value });
3092
4298
  const includesAll = (value) => ({ $includesAll: value });
3093
4299
  const includesNone = (value) => ({ $includesNone: value });
@@ -3143,6 +4349,80 @@ class SchemaPlugin extends XataPlugin {
3143
4349
  _tables = new WeakMap();
3144
4350
  _schemaTables$1 = new WeakMap();
3145
4351
 
4352
+ class FilesPlugin extends XataPlugin {
4353
+ build(pluginOptions) {
4354
+ return {
4355
+ download: async (location) => {
4356
+ const { table, record, column, fileId = "" } = location ?? {};
4357
+ return await getFileItem({
4358
+ pathParams: {
4359
+ workspace: "{workspaceId}",
4360
+ dbBranchName: "{dbBranch}",
4361
+ region: "{region}",
4362
+ tableName: table ?? "",
4363
+ recordId: record ?? "",
4364
+ columnName: column ?? "",
4365
+ fileId
4366
+ },
4367
+ ...pluginOptions,
4368
+ rawResponse: true
4369
+ });
4370
+ },
4371
+ upload: async (location, file, options) => {
4372
+ const { table, record, column, fileId = "" } = location ?? {};
4373
+ const resolvedFile = await file;
4374
+ const contentType = options?.mediaType || getContentType(resolvedFile);
4375
+ const body = resolvedFile instanceof XataFile ? resolvedFile.toBlob() : resolvedFile;
4376
+ return await putFileItem({
4377
+ ...pluginOptions,
4378
+ pathParams: {
4379
+ workspace: "{workspaceId}",
4380
+ dbBranchName: "{dbBranch}",
4381
+ region: "{region}",
4382
+ tableName: table ?? "",
4383
+ recordId: record ?? "",
4384
+ columnName: column ?? "",
4385
+ fileId
4386
+ },
4387
+ body,
4388
+ headers: { "Content-Type": contentType }
4389
+ });
4390
+ },
4391
+ delete: async (location) => {
4392
+ const { table, record, column, fileId = "" } = location ?? {};
4393
+ return await deleteFileItem({
4394
+ pathParams: {
4395
+ workspace: "{workspaceId}",
4396
+ dbBranchName: "{dbBranch}",
4397
+ region: "{region}",
4398
+ tableName: table ?? "",
4399
+ recordId: record ?? "",
4400
+ columnName: column ?? "",
4401
+ fileId
4402
+ },
4403
+ ...pluginOptions
4404
+ });
4405
+ }
4406
+ };
4407
+ }
4408
+ }
4409
+ function getContentType(file) {
4410
+ if (typeof file === "string") {
4411
+ return "text/plain";
4412
+ }
4413
+ if ("mediaType" in file && file.mediaType !== void 0) {
4414
+ return file.mediaType;
4415
+ }
4416
+ if (isBlob(file)) {
4417
+ return file.type;
4418
+ }
4419
+ try {
4420
+ return file.type;
4421
+ } catch (e) {
4422
+ }
4423
+ return "application/octet-stream";
4424
+ }
4425
+
3146
4426
  var __accessCheck$1 = (obj, member, msg) => {
3147
4427
  if (!member.has(obj))
3148
4428
  throw TypeError("Cannot " + msg);
@@ -3175,63 +4455,137 @@ class SearchPlugin extends XataPlugin {
3175
4455
  __privateAdd$1(this, _schemaTables, void 0);
3176
4456
  __privateSet$1(this, _schemaTables, schemaTables);
3177
4457
  }
3178
- build({ getFetchProps }) {
4458
+ build(pluginOptions) {
3179
4459
  return {
3180
4460
  all: async (query, options = {}) => {
3181
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3182
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3183
- return records.map((record) => {
3184
- const { table = "orphan" } = record.xata;
3185
- return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
3186
- });
4461
+ const { records, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4462
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
4463
+ return {
4464
+ totalCount,
4465
+ records: records.map((record) => {
4466
+ const { table = "orphan" } = record.xata;
4467
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
4468
+ })
4469
+ };
3187
4470
  },
3188
4471
  byTable: async (query, options = {}) => {
3189
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3190
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3191
- return records.reduce((acc, record) => {
4472
+ const { records: rawRecords, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4473
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
4474
+ const records = rawRecords.reduce((acc, record) => {
3192
4475
  const { table = "orphan" } = record.xata;
3193
4476
  const items = acc[table] ?? [];
3194
4477
  const item = initObject(this.db, schemaTables, table, record, ["*"]);
3195
4478
  return { ...acc, [table]: [...items, item] };
3196
4479
  }, {});
4480
+ return { totalCount, records };
3197
4481
  }
3198
4482
  };
3199
4483
  }
3200
4484
  }
3201
4485
  _schemaTables = new WeakMap();
3202
4486
  _search = new WeakSet();
3203
- search_fn = async function(query, options, getFetchProps) {
3204
- const fetchProps = await getFetchProps();
4487
+ search_fn = async function(query, options, pluginOptions) {
3205
4488
  const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3206
- const { records } = await searchBranch({
4489
+ const { records, totalCount } = await searchBranch({
3207
4490
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4491
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
3208
4492
  body: { tables, query, fuzziness, prefix, highlight, page },
3209
- ...fetchProps
4493
+ ...pluginOptions
3210
4494
  });
3211
- return records;
4495
+ return { records, totalCount };
3212
4496
  };
3213
4497
  _getSchemaTables = new WeakSet();
3214
- getSchemaTables_fn = async function(getFetchProps) {
4498
+ getSchemaTables_fn = async function(pluginOptions) {
3215
4499
  if (__privateGet$1(this, _schemaTables))
3216
4500
  return __privateGet$1(this, _schemaTables);
3217
- const fetchProps = await getFetchProps();
3218
4501
  const { schema } = await getBranchDetails({
3219
4502
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3220
- ...fetchProps
4503
+ ...pluginOptions
3221
4504
  });
3222
4505
  __privateSet$1(this, _schemaTables, schema.tables);
3223
4506
  return schema.tables;
3224
4507
  };
3225
4508
 
4509
+ function escapeElement(elementRepresentation) {
4510
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4511
+ return '"' + escaped + '"';
4512
+ }
4513
+ function arrayString(val) {
4514
+ let result = "{";
4515
+ for (let i = 0; i < val.length; i++) {
4516
+ if (i > 0) {
4517
+ result = result + ",";
4518
+ }
4519
+ if (val[i] === null || typeof val[i] === "undefined") {
4520
+ result = result + "NULL";
4521
+ } else if (Array.isArray(val[i])) {
4522
+ result = result + arrayString(val[i]);
4523
+ } else if (val[i] instanceof Buffer) {
4524
+ result += "\\\\x" + val[i].toString("hex");
4525
+ } else {
4526
+ result += escapeElement(prepareValue(val[i]));
4527
+ }
4528
+ }
4529
+ result = result + "}";
4530
+ return result;
4531
+ }
4532
+ function prepareValue(value) {
4533
+ if (!isDefined(value))
4534
+ return null;
4535
+ if (value instanceof Date) {
4536
+ return value.toISOString();
4537
+ }
4538
+ if (Array.isArray(value)) {
4539
+ return arrayString(value);
4540
+ }
4541
+ if (isObject(value)) {
4542
+ return JSON.stringify(value);
4543
+ }
4544
+ try {
4545
+ return value.toString();
4546
+ } catch (e) {
4547
+ return value;
4548
+ }
4549
+ }
4550
+ function prepareParams(param1, param2) {
4551
+ if (isString(param1)) {
4552
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4553
+ }
4554
+ if (isStringArray(param1)) {
4555
+ const statement = param1.reduce((acc, curr, index) => {
4556
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4557
+ }, "");
4558
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4559
+ }
4560
+ if (isObject(param1)) {
4561
+ const { statement, params, consistency } = param1;
4562
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
4563
+ }
4564
+ throw new Error("Invalid query");
4565
+ }
4566
+
4567
+ class SQLPlugin extends XataPlugin {
4568
+ build(pluginOptions) {
4569
+ return async (param1, ...param2) => {
4570
+ const { statement, params, consistency } = prepareParams(param1, param2);
4571
+ const { records, warning } = await sqlQuery({
4572
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4573
+ body: { statement, params, consistency },
4574
+ ...pluginOptions
4575
+ });
4576
+ return { records, warning };
4577
+ };
4578
+ }
4579
+ }
4580
+
3226
4581
  class TransactionPlugin extends XataPlugin {
3227
- build({ getFetchProps }) {
4582
+ build(pluginOptions) {
3228
4583
  return {
3229
4584
  run: async (operations) => {
3230
- const fetchProps = await getFetchProps();
3231
4585
  const response = await branchTransaction({
3232
4586
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3233
4587
  body: { operations },
3234
- ...fetchProps
4588
+ ...pluginOptions
3235
4589
  });
3236
4590
  return response;
3237
4591
  }
@@ -3239,91 +4593,6 @@ class TransactionPlugin extends XataPlugin {
3239
4593
  }
3240
4594
  }
3241
4595
 
3242
- const isBranchStrategyBuilder = (strategy) => {
3243
- return typeof strategy === "function";
3244
- };
3245
-
3246
- async function getCurrentBranchName(options) {
3247
- const { branch, envBranch } = getEnvironment();
3248
- if (branch)
3249
- return branch;
3250
- const gitBranch = envBranch || await getGitBranch();
3251
- return resolveXataBranch(gitBranch, options);
3252
- }
3253
- async function getCurrentBranchDetails(options) {
3254
- const branch = await getCurrentBranchName(options);
3255
- return getDatabaseBranch(branch, options);
3256
- }
3257
- async function resolveXataBranch(gitBranch, options) {
3258
- const databaseURL = options?.databaseURL || getDatabaseURL();
3259
- const apiKey = options?.apiKey || getAPIKey();
3260
- if (!databaseURL)
3261
- throw new Error(
3262
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3263
- );
3264
- if (!apiKey)
3265
- throw new Error(
3266
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3267
- );
3268
- const [protocol, , host, , dbName] = databaseURL.split("/");
3269
- const urlParts = parseWorkspacesUrlParts(host);
3270
- if (!urlParts)
3271
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3272
- const { workspace, region } = urlParts;
3273
- const { fallbackBranch } = getEnvironment();
3274
- const { branch } = await resolveBranch({
3275
- apiKey,
3276
- apiUrl: databaseURL,
3277
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3278
- workspacesApiUrl: `${protocol}//${host}`,
3279
- pathParams: { dbName, workspace, region },
3280
- queryParams: { gitBranch, fallbackBranch },
3281
- trace: defaultTrace,
3282
- clientName: options?.clientName,
3283
- xataAgentExtra: options?.xataAgentExtra
3284
- });
3285
- return branch;
3286
- }
3287
- async function getDatabaseBranch(branch, options) {
3288
- const databaseURL = options?.databaseURL || getDatabaseURL();
3289
- const apiKey = options?.apiKey || getAPIKey();
3290
- if (!databaseURL)
3291
- throw new Error(
3292
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3293
- );
3294
- if (!apiKey)
3295
- throw new Error(
3296
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3297
- );
3298
- const [protocol, , host, , database] = databaseURL.split("/");
3299
- const urlParts = parseWorkspacesUrlParts(host);
3300
- if (!urlParts)
3301
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3302
- const { workspace, region } = urlParts;
3303
- try {
3304
- return await getBranchDetails({
3305
- apiKey,
3306
- apiUrl: databaseURL,
3307
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3308
- workspacesApiUrl: `${protocol}//${host}`,
3309
- pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3310
- trace: defaultTrace
3311
- });
3312
- } catch (err) {
3313
- if (isObject(err) && err.status === 404)
3314
- return null;
3315
- throw err;
3316
- }
3317
- }
3318
- function getDatabaseURL() {
3319
- try {
3320
- const { databaseURL } = getEnvironment();
3321
- return databaseURL;
3322
- } catch (err) {
3323
- return void 0;
3324
- }
3325
- }
3326
-
3327
4596
  var __accessCheck = (obj, member, msg) => {
3328
4597
  if (!member.has(obj))
3329
4598
  throw TypeError("Cannot " + msg);
@@ -3347,46 +4616,41 @@ var __privateMethod = (obj, member, method) => {
3347
4616
  return method;
3348
4617
  };
3349
4618
  const buildClient = (plugins) => {
3350
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
4619
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3351
4620
  return _a = class {
3352
4621
  constructor(options = {}, schemaTables) {
3353
4622
  __privateAdd(this, _parseOptions);
3354
4623
  __privateAdd(this, _getFetchProps);
3355
- __privateAdd(this, _evaluateBranch);
3356
- __privateAdd(this, _branch, void 0);
3357
4624
  __privateAdd(this, _options, void 0);
3358
4625
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3359
4626
  __privateSet(this, _options, safeOptions);
3360
4627
  const pluginOptions = {
3361
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
4628
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3362
4629
  cache: safeOptions.cache,
3363
- trace: safeOptions.trace
4630
+ host: safeOptions.host
3364
4631
  };
3365
4632
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3366
4633
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3367
4634
  const transactions = new TransactionPlugin().build(pluginOptions);
4635
+ const sql = new SQLPlugin().build(pluginOptions);
4636
+ const files = new FilesPlugin().build(pluginOptions);
3368
4637
  this.db = db;
3369
4638
  this.search = search;
3370
4639
  this.transactions = transactions;
4640
+ this.sql = sql;
4641
+ this.files = files;
3371
4642
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3372
4643
  if (namespace === void 0)
3373
4644
  continue;
3374
- const result = namespace.build(pluginOptions);
3375
- if (result instanceof Promise) {
3376
- void result.then((namespace2) => {
3377
- this[key] = namespace2;
3378
- });
3379
- } else {
3380
- this[key] = result;
3381
- }
4645
+ this[key] = namespace.build(pluginOptions);
3382
4646
  }
3383
4647
  }
3384
4648
  async getConfig() {
3385
4649
  const databaseURL = __privateGet(this, _options).databaseURL;
3386
- const branch = await __privateGet(this, _options).branch();
4650
+ const branch = __privateGet(this, _options).branch;
3387
4651
  return { databaseURL, branch };
3388
4652
  }
3389
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4653
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3390
4654
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3391
4655
  const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3392
4656
  if (isBrowser && !enableBrowser) {
@@ -3400,20 +4664,34 @@ const buildClient = (plugins) => {
3400
4664
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3401
4665
  const trace = options?.trace ?? defaultTrace;
3402
4666
  const clientName = options?.clientName;
4667
+ const host = options?.host ?? "production";
3403
4668
  const xataAgentExtra = options?.xataAgentExtra;
3404
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({
3405
- apiKey,
3406
- databaseURL,
3407
- fetchImpl: options?.fetch,
3408
- clientName,
3409
- xataAgentExtra
3410
- });
3411
4669
  if (!apiKey) {
3412
4670
  throw new Error("Option apiKey is required");
3413
4671
  }
3414
4672
  if (!databaseURL) {
3415
4673
  throw new Error("Option databaseURL is required");
3416
4674
  }
4675
+ const envBranch = getBranch();
4676
+ const previewBranch = getPreviewBranch();
4677
+ const branch = options?.branch || previewBranch || envBranch || "main";
4678
+ if (!!previewBranch && branch !== previewBranch) {
4679
+ console.warn(
4680
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4681
+ );
4682
+ } else if (!!envBranch && branch !== envBranch) {
4683
+ console.warn(
4684
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4685
+ );
4686
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4687
+ console.warn(
4688
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4689
+ );
4690
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4691
+ console.warn(
4692
+ `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.`
4693
+ );
4694
+ }
3417
4695
  return {
3418
4696
  fetch,
3419
4697
  databaseURL,
@@ -3421,12 +4699,13 @@ const buildClient = (plugins) => {
3421
4699
  branch,
3422
4700
  cache,
3423
4701
  trace,
4702
+ host,
3424
4703
  clientID: generateUUID(),
3425
4704
  enableBrowser,
3426
4705
  clientName,
3427
4706
  xataAgentExtra
3428
4707
  };
3429
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
4708
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
3430
4709
  fetch,
3431
4710
  apiKey,
3432
4711
  databaseURL,
@@ -3436,16 +4715,14 @@ const buildClient = (plugins) => {
3436
4715
  clientName,
3437
4716
  xataAgentExtra
3438
4717
  }) {
3439
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3440
- if (!branchValue)
3441
- throw new Error("Unable to resolve branch value");
3442
4718
  return {
3443
- fetchImpl: fetch,
4719
+ fetch,
3444
4720
  apiKey,
3445
4721
  apiUrl: "",
4722
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3446
4723
  workspacesApiUrl: (path, params) => {
3447
4724
  const hasBranch = params.dbBranchName ?? params.branch;
3448
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
4725
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
3449
4726
  return databaseURL + newPath;
3450
4727
  },
3451
4728
  trace,
@@ -3453,22 +4730,6 @@ const buildClient = (plugins) => {
3453
4730
  clientName,
3454
4731
  xataAgentExtra
3455
4732
  };
3456
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3457
- if (__privateGet(this, _branch))
3458
- return __privateGet(this, _branch);
3459
- if (param === void 0)
3460
- return void 0;
3461
- const strategies = Array.isArray(param) ? [...param] : [param];
3462
- const evaluateBranch = async (strategy) => {
3463
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
3464
- };
3465
- for await (const strategy of strategies) {
3466
- const branch = await evaluateBranch(strategy);
3467
- if (branch) {
3468
- __privateSet(this, _branch, branch);
3469
- return branch;
3470
- }
3471
- }
3472
4733
  }, _a;
3473
4734
  };
3474
4735
  class BaseClient extends buildClient() {
@@ -3541,21 +4802,6 @@ const deserialize = (json) => {
3541
4802
  return defaultSerializer.fromJSON(json);
3542
4803
  };
3543
4804
 
3544
- function buildWorkerRunner(config) {
3545
- return function xataWorker(name, worker) {
3546
- return async (...args) => {
3547
- const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3548
- const result = await fetch(url, {
3549
- method: "POST",
3550
- headers: { "Content-Type": "application/json" },
3551
- body: serialize({ args })
3552
- });
3553
- const text = await result.text();
3554
- return deserialize(text);
3555
- };
3556
- };
3557
- }
3558
-
3559
4805
  class XataError extends Error {
3560
4806
  constructor(message, status) {
3561
4807
  super(message);
@@ -3563,5 +4809,5 @@ class XataError extends Error {
3563
4809
  }
3564
4810
  }
3565
4811
 
3566
- export { BaseClient, FetcherError, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, branchTransaction, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
4812
+ export { BaseClient, FetcherError, FilesPlugin, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, RecordColumnTypes, Repository, RestRepository, SQLPlugin, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, TransactionPlugin, XataApiClient, XataApiPlugin, XataError, XataFile, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, applyMigration, askTable, askTableSession, branchTransaction, buildClient, buildPreviewBranchName, buildProviderString, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, copyBranch, createBranch, createCluster, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteFile, deleteFileItem, deleteOAuthAccessToken, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteUserOAuthClient, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, fileAccess, fileUpload, ge, getAPIKey, getAuthorizationCode, getBranch, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getCluster, getColumn, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getFile, getFileItem, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getPreviewBranch, getRecord, getSchema, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getUserOAuthAccessTokens, getUserOAuthClients, getWorkspace, getWorkspaceMembersList, getWorkspacesList, grantAuthorizationCode, greaterEquals, greaterThan, greaterThanEquals, gt, gte, iContains, iPattern, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isValidExpandedColumn, isValidSelectableColumns, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listClusters, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, pgRollJobStatus, pgRollStatus, previewBranchSchemaEdit, pushBranchMigrations, putFile, putFileItem, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, renameDatabase, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, sqlQuery, startsWith, summarizeTable, transformImage, updateBranchMetadata, updateBranchSchema, updateCluster, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateOAuthAccessToken, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID, vectorSearchTable };
3567
4813
  //# sourceMappingURL=index.mjs.map