@xata.io/client 0.0.0-alpha.vff9649a → 0.0.0-alpha.vffe924c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -93,8 +93,10 @@ function getEnvironment() {
93
93
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
94
94
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
95
95
  branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
96
- envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
97
- fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
96
+ deployPreview: process.env.XATA_PREVIEW,
97
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
98
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
99
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
98
100
  };
99
101
  }
100
102
  } catch (err) {
@@ -105,8 +107,10 @@ function getEnvironment() {
105
107
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
106
108
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
107
109
  branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
108
- envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
109
- fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
110
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
111
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
112
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
113
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
110
114
  };
111
115
  }
112
116
  } catch (err) {
@@ -115,8 +119,10 @@ function getEnvironment() {
115
119
  apiKey: getGlobalApiKey(),
116
120
  databaseURL: getGlobalDatabaseURL(),
117
121
  branch: getGlobalBranch(),
118
- envBranch: void 0,
119
- fallbackBranch: getGlobalFallbackBranch()
122
+ deployPreview: void 0,
123
+ deployPreviewBranch: void 0,
124
+ vercelGitCommitRef: void 0,
125
+ vercelGitRepoOwner: void 0
120
126
  };
121
127
  }
122
128
  function getEnableBrowserVariable() {
@@ -159,37 +165,48 @@ function getGlobalBranch() {
159
165
  return void 0;
160
166
  }
161
167
  }
162
- function getGlobalFallbackBranch() {
168
+ function getDatabaseURL() {
163
169
  try {
164
- return XATA_FALLBACK_BRANCH;
170
+ const { databaseURL } = getEnvironment();
171
+ return databaseURL;
165
172
  } catch (err) {
166
173
  return void 0;
167
174
  }
168
175
  }
169
- async function getGitBranch() {
170
- const cmd = ["git", "branch", "--show-current"];
171
- const fullCmd = cmd.join(" ");
172
- const nodeModule = ["child", "process"].join("_");
173
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
176
+ function getAPIKey() {
174
177
  try {
175
- if (typeof require === "function") {
176
- return require(nodeModule).execSync(fullCmd, execOptions).trim();
177
- }
178
+ const { apiKey } = getEnvironment();
179
+ return apiKey;
178
180
  } catch (err) {
181
+ return void 0;
179
182
  }
183
+ }
184
+ function getBranch() {
180
185
  try {
181
- if (isObject(Deno)) {
182
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
183
- return new TextDecoder().decode(await process2.output()).trim();
184
- }
186
+ const { branch } = getEnvironment();
187
+ return branch ?? "main";
185
188
  } catch (err) {
189
+ return void 0;
186
190
  }
187
191
  }
188
-
189
- function getAPIKey() {
192
+ function buildPreviewBranchName({ org, branch }) {
193
+ return `preview-${org}-${branch}`;
194
+ }
195
+ function getPreviewBranch() {
190
196
  try {
191
- const { apiKey } = getEnvironment();
192
- return apiKey;
197
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
198
+ if (deployPreviewBranch)
199
+ return deployPreviewBranch;
200
+ switch (deployPreview) {
201
+ case "vercel": {
202
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
203
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
204
+ return void 0;
205
+ }
206
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
207
+ }
208
+ }
209
+ return void 0;
193
210
  } catch (err) {
194
211
  return void 0;
195
212
  }
@@ -249,7 +266,7 @@ class ApiRequestPool {
249
266
  return __privateGet$8(this, _fetch);
250
267
  }
251
268
  request(url, options) {
252
- const start = new Date();
269
+ const start = /* @__PURE__ */ new Date();
253
270
  const fetch2 = this.getFetch();
254
271
  const runRequest = async (stalled = false) => {
255
272
  const response = await fetch2(url, options);
@@ -259,7 +276,7 @@ class ApiRequestPool {
259
276
  return await runRequest(true);
260
277
  }
261
278
  if (stalled) {
262
- const stalledTime = new Date().getTime() - start.getTime();
279
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
263
280
  console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
264
281
  }
265
282
  return response;
@@ -302,7 +319,180 @@ function generateUUID() {
302
319
  });
303
320
  }
304
321
 
305
- const VERSION = "0.21.6";
322
+ async function getBytes(stream, onChunk) {
323
+ const reader = stream.getReader();
324
+ let result;
325
+ while (!(result = await reader.read()).done) {
326
+ onChunk(result.value);
327
+ }
328
+ }
329
+ function getLines(onLine) {
330
+ let buffer;
331
+ let position;
332
+ let fieldLength;
333
+ let discardTrailingNewline = false;
334
+ return function onChunk(arr) {
335
+ if (buffer === void 0) {
336
+ buffer = arr;
337
+ position = 0;
338
+ fieldLength = -1;
339
+ } else {
340
+ buffer = concat(buffer, arr);
341
+ }
342
+ const bufLength = buffer.length;
343
+ let lineStart = 0;
344
+ while (position < bufLength) {
345
+ if (discardTrailingNewline) {
346
+ if (buffer[position] === 10 /* NewLine */) {
347
+ lineStart = ++position;
348
+ }
349
+ discardTrailingNewline = false;
350
+ }
351
+ let lineEnd = -1;
352
+ for (; position < bufLength && lineEnd === -1; ++position) {
353
+ switch (buffer[position]) {
354
+ case 58 /* Colon */:
355
+ if (fieldLength === -1) {
356
+ fieldLength = position - lineStart;
357
+ }
358
+ break;
359
+ case 13 /* CarriageReturn */:
360
+ discardTrailingNewline = true;
361
+ case 10 /* NewLine */:
362
+ lineEnd = position;
363
+ break;
364
+ }
365
+ }
366
+ if (lineEnd === -1) {
367
+ break;
368
+ }
369
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
370
+ lineStart = position;
371
+ fieldLength = -1;
372
+ }
373
+ if (lineStart === bufLength) {
374
+ buffer = void 0;
375
+ } else if (lineStart !== 0) {
376
+ buffer = buffer.subarray(lineStart);
377
+ position -= lineStart;
378
+ }
379
+ };
380
+ }
381
+ function getMessages(onId, onRetry, onMessage) {
382
+ let message = newMessage();
383
+ const decoder = new TextDecoder();
384
+ return function onLine(line, fieldLength) {
385
+ if (line.length === 0) {
386
+ onMessage?.(message);
387
+ message = newMessage();
388
+ } else if (fieldLength > 0) {
389
+ const field = decoder.decode(line.subarray(0, fieldLength));
390
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
391
+ const value = decoder.decode(line.subarray(valueOffset));
392
+ switch (field) {
393
+ case "data":
394
+ message.data = message.data ? message.data + "\n" + value : value;
395
+ break;
396
+ case "event":
397
+ message.event = value;
398
+ break;
399
+ case "id":
400
+ onId(message.id = value);
401
+ break;
402
+ case "retry":
403
+ const retry = parseInt(value, 10);
404
+ if (!isNaN(retry)) {
405
+ onRetry(message.retry = retry);
406
+ }
407
+ break;
408
+ }
409
+ }
410
+ };
411
+ }
412
+ function concat(a, b) {
413
+ const res = new Uint8Array(a.length + b.length);
414
+ res.set(a);
415
+ res.set(b, a.length);
416
+ return res;
417
+ }
418
+ function newMessage() {
419
+ return {
420
+ data: "",
421
+ event: "",
422
+ id: "",
423
+ retry: void 0
424
+ };
425
+ }
426
+ const EventStreamContentType = "text/event-stream";
427
+ const LastEventId = "last-event-id";
428
+ function fetchEventSource(input, {
429
+ signal: inputSignal,
430
+ headers: inputHeaders,
431
+ onopen: inputOnOpen,
432
+ onmessage,
433
+ onclose,
434
+ onerror,
435
+ fetch: inputFetch,
436
+ ...rest
437
+ }) {
438
+ return new Promise((resolve, reject) => {
439
+ const headers = { ...inputHeaders };
440
+ if (!headers.accept) {
441
+ headers.accept = EventStreamContentType;
442
+ }
443
+ let curRequestController;
444
+ function dispose() {
445
+ curRequestController.abort();
446
+ }
447
+ inputSignal?.addEventListener("abort", () => {
448
+ dispose();
449
+ resolve();
450
+ });
451
+ const fetchImpl = inputFetch ?? fetch;
452
+ const onopen = inputOnOpen ?? defaultOnOpen;
453
+ async function create() {
454
+ curRequestController = new AbortController();
455
+ try {
456
+ const response = await fetchImpl(input, {
457
+ ...rest,
458
+ headers,
459
+ signal: curRequestController.signal
460
+ });
461
+ await onopen(response);
462
+ await getBytes(
463
+ response.body,
464
+ getLines(
465
+ getMessages(
466
+ (id) => {
467
+ if (id) {
468
+ headers[LastEventId] = id;
469
+ } else {
470
+ delete headers[LastEventId];
471
+ }
472
+ },
473
+ (_retry) => {
474
+ },
475
+ onmessage
476
+ )
477
+ )
478
+ );
479
+ onclose?.();
480
+ dispose();
481
+ resolve();
482
+ } catch (err) {
483
+ }
484
+ }
485
+ create();
486
+ });
487
+ }
488
+ function defaultOnOpen(response) {
489
+ const contentType = response.headers?.get("content-type");
490
+ if (!contentType?.startsWith(EventStreamContentType)) {
491
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
492
+ }
493
+ }
494
+
495
+ const VERSION = "0.24.2";
306
496
 
307
497
  class ErrorWithCause extends Error {
308
498
  constructor(message, options) {
@@ -386,7 +576,7 @@ async function fetch$1({
386
576
  headers: customHeaders,
387
577
  pathParams,
388
578
  queryParams,
389
- fetchImpl,
579
+ fetch: fetch2,
390
580
  apiKey,
391
581
  endpoint,
392
582
  apiUrl,
@@ -396,9 +586,10 @@ async function fetch$1({
396
586
  clientID,
397
587
  sessionID,
398
588
  clientName,
589
+ xataAgentExtra,
399
590
  fetchOptions = {}
400
591
  }) {
401
- pool.setFetch(fetchImpl);
592
+ pool.setFetch(fetch2);
402
593
  return await trace(
403
594
  `${method.toUpperCase()} ${path}`,
404
595
  async ({ setAttributes }) => {
@@ -412,7 +603,8 @@ async function fetch$1({
412
603
  const xataAgent = compact([
413
604
  ["client", "TS_SDK"],
414
605
  ["version", VERSION],
415
- isDefined(clientName) ? ["service", clientName] : void 0
606
+ isDefined(clientName) ? ["service", clientName] : void 0,
607
+ ...Object.entries(xataAgentExtra ?? {})
416
608
  ]).map(([key, value]) => `${key}=${value}`).join("; ");
417
609
  const headers = {
418
610
  "Accept-Encoding": "identity",
@@ -459,6 +651,59 @@ async function fetch$1({
459
651
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
460
652
  );
461
653
  }
654
+ function fetchSSERequest({
655
+ url: path,
656
+ method,
657
+ body,
658
+ headers: customHeaders,
659
+ pathParams,
660
+ queryParams,
661
+ fetch: fetch2,
662
+ apiKey,
663
+ endpoint,
664
+ apiUrl,
665
+ workspacesApiUrl,
666
+ onMessage,
667
+ onError,
668
+ onClose,
669
+ signal,
670
+ clientID,
671
+ sessionID,
672
+ clientName,
673
+ xataAgentExtra
674
+ }) {
675
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
676
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
677
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
678
+ void fetchEventSource(url, {
679
+ method,
680
+ body: JSON.stringify(body),
681
+ fetch: fetch2,
682
+ signal,
683
+ headers: {
684
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
685
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
686
+ "X-Xata-Agent": compact([
687
+ ["client", "TS_SDK"],
688
+ ["version", VERSION],
689
+ isDefined(clientName) ? ["service", clientName] : void 0,
690
+ ...Object.entries(xataAgentExtra ?? {})
691
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
692
+ ...customHeaders,
693
+ Authorization: `Bearer ${apiKey}`,
694
+ "Content-Type": "application/json"
695
+ },
696
+ onmessage(ev) {
697
+ onMessage?.(JSON.parse(ev.data));
698
+ },
699
+ onerror(ev) {
700
+ onError?.(JSON.parse(ev.data));
701
+ },
702
+ onclose() {
703
+ onClose?.();
704
+ }
705
+ });
706
+ }
462
707
  function parseUrl(url) {
463
708
  try {
464
709
  const { host, protocol } = new URL(url);
@@ -489,6 +734,12 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
489
734
  ...variables,
490
735
  signal
491
736
  });
737
+ const copyBranch = (variables, signal) => dataPlaneFetch({
738
+ url: "/db/{dbBranchName}/copy",
739
+ method: "post",
740
+ ...variables,
741
+ signal
742
+ });
492
743
  const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
493
744
  url: "/db/{dbBranchName}/metadata",
494
745
  method: "put",
@@ -514,7 +765,6 @@ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName
514
765
  const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
515
766
  const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
516
767
  const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
517
- const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
518
768
  const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
519
769
  const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
520
770
  const getMigrationRequest = (variables, signal) => dataPlaneFetch({
@@ -539,6 +789,7 @@ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{
539
789
  const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
540
790
  const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
541
791
  const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
792
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
542
793
  const createTable = (variables, signal) => dataPlaneFetch({
543
794
  url: "/db/{dbBranchName}/tables/{tableName}",
544
795
  method: "put",
@@ -581,7 +832,44 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
581
832
  ...variables,
582
833
  signal
583
834
  });
835
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
584
836
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
837
+ const getFileItem = (variables, signal) => dataPlaneFetch({
838
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
839
+ method: "get",
840
+ ...variables,
841
+ signal
842
+ });
843
+ const putFileItem = (variables, signal) => dataPlaneFetch({
844
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
845
+ method: "put",
846
+ ...variables,
847
+ signal
848
+ });
849
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
850
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
851
+ method: "delete",
852
+ ...variables,
853
+ signal
854
+ });
855
+ const getFile = (variables, signal) => dataPlaneFetch({
856
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
857
+ method: "get",
858
+ ...variables,
859
+ signal
860
+ });
861
+ const putFile = (variables, signal) => dataPlaneFetch({
862
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
863
+ method: "put",
864
+ ...variables,
865
+ signal
866
+ });
867
+ const deleteFile = (variables, signal) => dataPlaneFetch({
868
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
869
+ method: "delete",
870
+ ...variables,
871
+ signal
872
+ });
585
873
  const getRecord = (variables, signal) => dataPlaneFetch({
586
874
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
587
875
  method: "get",
@@ -611,14 +899,34 @@ const searchTable = (variables, signal) => dataPlaneFetch({
611
899
  ...variables,
612
900
  signal
613
901
  });
902
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
903
+ url: "/db/{dbBranchName}/sql",
904
+ method: "post",
905
+ ...variables,
906
+ signal
907
+ });
908
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
909
+ const askTable = (variables, signal) => dataPlaneFetch({
910
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
911
+ method: "post",
912
+ ...variables,
913
+ signal
914
+ });
614
915
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
615
916
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
917
+ const fileAccess = (variables, signal) => dataPlaneFetch({
918
+ url: "/file/{fileId}",
919
+ method: "get",
920
+ ...variables,
921
+ signal
922
+ });
616
923
  const operationsByTag$2 = {
617
924
  branch: {
618
925
  getBranchList,
619
926
  getBranchDetails,
620
927
  createBranch,
621
928
  deleteBranch,
929
+ copyBranch,
622
930
  updateBranchMetadata,
623
931
  getBranchMetadata,
624
932
  getBranchStats,
@@ -636,17 +944,8 @@ const operationsByTag$2 = {
636
944
  compareBranchSchemas,
637
945
  updateBranchSchema,
638
946
  previewBranchSchemaEdit,
639
- applyBranchSchemaEdit
640
- },
641
- records: {
642
- branchTransaction,
643
- insertRecord,
644
- getRecord,
645
- insertRecordWithID,
646
- updateRecordWithID,
647
- upsertRecordWithID,
648
- deleteRecord,
649
- bulkInsertTableRecords
947
+ applyBranchSchemaEdit,
948
+ pushBranchMigrations
650
949
  },
651
950
  migrationRequests: {
652
951
  queryMigrationRequests,
@@ -670,7 +969,27 @@ const operationsByTag$2 = {
670
969
  updateColumn,
671
970
  deleteColumn
672
971
  },
673
- searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
972
+ records: {
973
+ branchTransaction,
974
+ insertRecord,
975
+ getRecord,
976
+ insertRecordWithID,
977
+ updateRecordWithID,
978
+ upsertRecordWithID,
979
+ deleteRecord,
980
+ bulkInsertTableRecords
981
+ },
982
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess },
983
+ searchAndFilter: {
984
+ queryTable,
985
+ searchBranch,
986
+ searchTable,
987
+ sqlQuery,
988
+ vectorSearchTable,
989
+ askTable,
990
+ summarizeTable,
991
+ aggregateTable
992
+ }
674
993
  };
675
994
 
676
995
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
@@ -769,6 +1088,10 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
769
1088
  });
770
1089
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
771
1090
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1091
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1092
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1093
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1094
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
772
1095
  const listRegions = (variables, signal) => controlPlaneFetch({
773
1096
  url: "/workspaces/{workspaceId}/regions",
774
1097
  method: "get",
@@ -801,6 +1124,10 @@ const operationsByTag$1 = {
801
1124
  deleteDatabase,
802
1125
  getDatabaseMetadata,
803
1126
  updateDatabaseMetadata,
1127
+ renameDatabase,
1128
+ getDatabaseGithubSettings,
1129
+ updateDatabaseGithubSettings,
1130
+ deleteDatabaseGithubSettings,
804
1131
  listRegions
805
1132
  }
806
1133
  };
@@ -821,8 +1148,12 @@ const providers = {
821
1148
  workspaces: "https://{workspaceId}.{region}.xata.sh"
822
1149
  },
823
1150
  staging: {
824
- main: "https://staging.xatabase.co",
825
- workspaces: "https://{workspaceId}.staging.{region}.xatabase.co"
1151
+ main: "https://api.staging-xata.dev",
1152
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1153
+ },
1154
+ dev: {
1155
+ main: "https://api.dev-xata.dev",
1156
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
826
1157
  }
827
1158
  };
828
1159
  function isHostProviderAlias(alias) {
@@ -840,12 +1171,19 @@ function parseProviderString(provider = "production") {
840
1171
  return null;
841
1172
  return { main, workspaces };
842
1173
  }
1174
+ function buildProviderString(provider) {
1175
+ if (isHostProviderAlias(provider))
1176
+ return provider;
1177
+ return `${provider.main},${provider.workspaces}`;
1178
+ }
843
1179
  function parseWorkspacesUrlParts(url) {
844
1180
  if (!isString(url))
845
1181
  return null;
846
1182
  const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
847
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
848
- const match = url.match(regex) || url.match(regexStaging);
1183
+ const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1184
+ const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1185
+ const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1186
+ const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
849
1187
  if (!match)
850
1188
  return null;
851
1189
  return { workspace: match[1], region: match[2] };
@@ -884,10 +1222,11 @@ class XataApiClient {
884
1222
  __privateSet$7(this, _extraProps, {
885
1223
  apiUrl: getHostUrl(provider, "main"),
886
1224
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
887
- fetchImpl: getFetchImplementation(options.fetch),
1225
+ fetch: getFetchImplementation(options.fetch),
888
1226
  apiKey,
889
1227
  trace,
890
1228
  clientName: options.clientName,
1229
+ xataAgentExtra: options.xataAgentExtra,
891
1230
  clientID
892
1231
  });
893
1232
  }
@@ -941,6 +1280,11 @@ class XataApiClient {
941
1280
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
942
1281
  return __privateGet$7(this, _namespaces).records;
943
1282
  }
1283
+ get files() {
1284
+ if (!__privateGet$7(this, _namespaces).files)
1285
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1286
+ return __privateGet$7(this, _namespaces).files;
1287
+ }
944
1288
  get searchAndFilter() {
945
1289
  if (!__privateGet$7(this, _namespaces).searchAndFilter)
946
1290
  __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
@@ -1149,6 +1493,20 @@ class BranchApi {
1149
1493
  ...this.extraProps
1150
1494
  });
1151
1495
  }
1496
+ copyBranch({
1497
+ workspace,
1498
+ region,
1499
+ database,
1500
+ branch,
1501
+ destinationBranch,
1502
+ limit
1503
+ }) {
1504
+ return operationsByTag.branch.copyBranch({
1505
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1506
+ body: { destinationBranch, limit },
1507
+ ...this.extraProps
1508
+ });
1509
+ }
1152
1510
  updateBranchMetadata({
1153
1511
  workspace,
1154
1512
  region,
@@ -1504,6 +1862,164 @@ class RecordsApi {
1504
1862
  });
1505
1863
  }
1506
1864
  }
1865
+ class FilesApi {
1866
+ constructor(extraProps) {
1867
+ this.extraProps = extraProps;
1868
+ }
1869
+ getFileItem({
1870
+ workspace,
1871
+ region,
1872
+ database,
1873
+ branch,
1874
+ table,
1875
+ record,
1876
+ column,
1877
+ fileId
1878
+ }) {
1879
+ return operationsByTag.files.getFileItem({
1880
+ pathParams: {
1881
+ workspace,
1882
+ region,
1883
+ dbBranchName: `${database}:${branch}`,
1884
+ tableName: table,
1885
+ recordId: record,
1886
+ columnName: column,
1887
+ fileId
1888
+ },
1889
+ ...this.extraProps
1890
+ });
1891
+ }
1892
+ putFileItem({
1893
+ workspace,
1894
+ region,
1895
+ database,
1896
+ branch,
1897
+ table,
1898
+ record,
1899
+ column,
1900
+ fileId,
1901
+ file
1902
+ }) {
1903
+ return operationsByTag.files.putFileItem({
1904
+ pathParams: {
1905
+ workspace,
1906
+ region,
1907
+ dbBranchName: `${database}:${branch}`,
1908
+ tableName: table,
1909
+ recordId: record,
1910
+ columnName: column,
1911
+ fileId
1912
+ },
1913
+ // @ts-ignore
1914
+ body: file,
1915
+ ...this.extraProps
1916
+ });
1917
+ }
1918
+ deleteFileItem({
1919
+ workspace,
1920
+ region,
1921
+ database,
1922
+ branch,
1923
+ table,
1924
+ record,
1925
+ column,
1926
+ fileId
1927
+ }) {
1928
+ return operationsByTag.files.deleteFileItem({
1929
+ pathParams: {
1930
+ workspace,
1931
+ region,
1932
+ dbBranchName: `${database}:${branch}`,
1933
+ tableName: table,
1934
+ recordId: record,
1935
+ columnName: column,
1936
+ fileId
1937
+ },
1938
+ ...this.extraProps
1939
+ });
1940
+ }
1941
+ getFile({
1942
+ workspace,
1943
+ region,
1944
+ database,
1945
+ branch,
1946
+ table,
1947
+ record,
1948
+ column
1949
+ }) {
1950
+ return operationsByTag.files.getFile({
1951
+ pathParams: {
1952
+ workspace,
1953
+ region,
1954
+ dbBranchName: `${database}:${branch}`,
1955
+ tableName: table,
1956
+ recordId: record,
1957
+ columnName: column
1958
+ },
1959
+ ...this.extraProps
1960
+ });
1961
+ }
1962
+ putFile({
1963
+ workspace,
1964
+ region,
1965
+ database,
1966
+ branch,
1967
+ table,
1968
+ record,
1969
+ column,
1970
+ file
1971
+ }) {
1972
+ return operationsByTag.files.putFile({
1973
+ pathParams: {
1974
+ workspace,
1975
+ region,
1976
+ dbBranchName: `${database}:${branch}`,
1977
+ tableName: table,
1978
+ recordId: record,
1979
+ columnName: column
1980
+ },
1981
+ body: file,
1982
+ ...this.extraProps
1983
+ });
1984
+ }
1985
+ deleteFile({
1986
+ workspace,
1987
+ region,
1988
+ database,
1989
+ branch,
1990
+ table,
1991
+ record,
1992
+ column
1993
+ }) {
1994
+ return operationsByTag.files.deleteFile({
1995
+ pathParams: {
1996
+ workspace,
1997
+ region,
1998
+ dbBranchName: `${database}:${branch}`,
1999
+ tableName: table,
2000
+ recordId: record,
2001
+ columnName: column
2002
+ },
2003
+ ...this.extraProps
2004
+ });
2005
+ }
2006
+ fileAccess({
2007
+ workspace,
2008
+ region,
2009
+ fileId,
2010
+ verify
2011
+ }) {
2012
+ return operationsByTag.files.fileAccess({
2013
+ pathParams: {
2014
+ workspace,
2015
+ region,
2016
+ fileId
2017
+ },
2018
+ queryParams: { verify },
2019
+ ...this.extraProps
2020
+ });
2021
+ }
2022
+ }
1507
2023
  class SearchAndFilterApi {
1508
2024
  constructor(extraProps) {
1509
2025
  this.extraProps = extraProps;
@@ -1563,6 +2079,38 @@ class SearchAndFilterApi {
1563
2079
  ...this.extraProps
1564
2080
  });
1565
2081
  }
2082
+ vectorSearchTable({
2083
+ workspace,
2084
+ region,
2085
+ database,
2086
+ branch,
2087
+ table,
2088
+ queryVector,
2089
+ column,
2090
+ similarityFunction,
2091
+ size,
2092
+ filter
2093
+ }) {
2094
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2095
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2096
+ body: { queryVector, column, similarityFunction, size, filter },
2097
+ ...this.extraProps
2098
+ });
2099
+ }
2100
+ askTable({
2101
+ workspace,
2102
+ region,
2103
+ database,
2104
+ branch,
2105
+ table,
2106
+ options
2107
+ }) {
2108
+ return operationsByTag.searchAndFilter.askTable({
2109
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2110
+ body: { ...options },
2111
+ ...this.extraProps
2112
+ });
2113
+ }
1566
2114
  summarizeTable({
1567
2115
  workspace,
1568
2116
  region,
@@ -1763,11 +2311,13 @@ class MigrationsApi {
1763
2311
  region,
1764
2312
  database,
1765
2313
  branch,
1766
- schema
2314
+ schema,
2315
+ schemaOperations,
2316
+ branchOperations
1767
2317
  }) {
1768
2318
  return operationsByTag.migrations.compareBranchWithUserSchema({
1769
2319
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1770
- body: { schema },
2320
+ body: { schema, schemaOperations, branchOperations },
1771
2321
  ...this.extraProps
1772
2322
  });
1773
2323
  }
@@ -1777,11 +2327,12 @@ class MigrationsApi {
1777
2327
  database,
1778
2328
  branch,
1779
2329
  compare,
1780
- schema
2330
+ sourceBranchOperations,
2331
+ targetBranchOperations
1781
2332
  }) {
1782
2333
  return operationsByTag.migrations.compareBranchSchemas({
1783
2334
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1784
- body: { schema },
2335
+ body: { sourceBranchOperations, targetBranchOperations },
1785
2336
  ...this.extraProps
1786
2337
  });
1787
2338
  }
@@ -1824,6 +2375,19 @@ class MigrationsApi {
1824
2375
  ...this.extraProps
1825
2376
  });
1826
2377
  }
2378
+ pushBranchMigrations({
2379
+ workspace,
2380
+ region,
2381
+ database,
2382
+ branch,
2383
+ migrations
2384
+ }) {
2385
+ return operationsByTag.migrations.pushBranchMigrations({
2386
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2387
+ body: { migrations },
2388
+ ...this.extraProps
2389
+ });
2390
+ }
1827
2391
  }
1828
2392
  class DatabaseApi {
1829
2393
  constructor(extraProps) {
@@ -1875,6 +2439,46 @@ class DatabaseApi {
1875
2439
  ...this.extraProps
1876
2440
  });
1877
2441
  }
2442
+ renameDatabase({
2443
+ workspace,
2444
+ database,
2445
+ newName
2446
+ }) {
2447
+ return operationsByTag.databases.renameDatabase({
2448
+ pathParams: { workspaceId: workspace, dbName: database },
2449
+ body: { newName },
2450
+ ...this.extraProps
2451
+ });
2452
+ }
2453
+ getDatabaseGithubSettings({
2454
+ workspace,
2455
+ database
2456
+ }) {
2457
+ return operationsByTag.databases.getDatabaseGithubSettings({
2458
+ pathParams: { workspaceId: workspace, dbName: database },
2459
+ ...this.extraProps
2460
+ });
2461
+ }
2462
+ updateDatabaseGithubSettings({
2463
+ workspace,
2464
+ database,
2465
+ settings
2466
+ }) {
2467
+ return operationsByTag.databases.updateDatabaseGithubSettings({
2468
+ pathParams: { workspaceId: workspace, dbName: database },
2469
+ body: settings,
2470
+ ...this.extraProps
2471
+ });
2472
+ }
2473
+ deleteDatabaseGithubSettings({
2474
+ workspace,
2475
+ database
2476
+ }) {
2477
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
2478
+ pathParams: { workspaceId: workspace, dbName: database },
2479
+ ...this.extraProps
2480
+ });
2481
+ }
1878
2482
  listRegions({ workspace }) {
1879
2483
  return operationsByTag.databases.listRegions({
1880
2484
  pathParams: { workspaceId: workspace },
@@ -1884,9 +2488,8 @@ class DatabaseApi {
1884
2488
  }
1885
2489
 
1886
2490
  class XataApiPlugin {
1887
- async build(options) {
1888
- const { fetchImpl, apiKey } = await options.getFetchProps();
1889
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2491
+ build(options) {
2492
+ return new XataApiClient(options);
1890
2493
  }
1891
2494
  }
1892
2495
 
@@ -1926,18 +2529,46 @@ class Page {
1926
2529
  this.meta = meta;
1927
2530
  this.records = new RecordArray(this, records);
1928
2531
  }
2532
+ /**
2533
+ * Retrieves the next page of results.
2534
+ * @param size Maximum number of results to be retrieved.
2535
+ * @param offset Number of results to skip when retrieving the results.
2536
+ * @returns The next page or results.
2537
+ */
1929
2538
  async nextPage(size, offset) {
1930
2539
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
1931
2540
  }
2541
+ /**
2542
+ * Retrieves the previous page of results.
2543
+ * @param size Maximum number of results to be retrieved.
2544
+ * @param offset Number of results to skip when retrieving the results.
2545
+ * @returns The previous page or results.
2546
+ */
1932
2547
  async previousPage(size, offset) {
1933
2548
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1934
2549
  }
2550
+ /**
2551
+ * Retrieves the start page of results.
2552
+ * @param size Maximum number of results to be retrieved.
2553
+ * @param offset Number of results to skip when retrieving the results.
2554
+ * @returns The start page or results.
2555
+ */
1935
2556
  async startPage(size, offset) {
1936
2557
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1937
2558
  }
2559
+ /**
2560
+ * Retrieves the end page of results.
2561
+ * @param size Maximum number of results to be retrieved.
2562
+ * @param offset Number of results to skip when retrieving the results.
2563
+ * @returns The end page or results.
2564
+ */
1938
2565
  async endPage(size, offset) {
1939
2566
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1940
2567
  }
2568
+ /**
2569
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
2570
+ * @returns Whether or not there will be additional results in the next page of results.
2571
+ */
1941
2572
  hasNextPage() {
1942
2573
  return this.meta.page.more;
1943
2574
  }
@@ -1969,25 +2600,54 @@ const _RecordArray = class extends Array {
1969
2600
  toArray() {
1970
2601
  return new Array(...this);
1971
2602
  }
2603
+ toSerializable() {
2604
+ return JSON.parse(this.toString());
2605
+ }
2606
+ toString() {
2607
+ return JSON.stringify(this.toArray());
2608
+ }
1972
2609
  map(callbackfn, thisArg) {
1973
2610
  return this.toArray().map(callbackfn, thisArg);
1974
2611
  }
2612
+ /**
2613
+ * Retrieve next page of records
2614
+ *
2615
+ * @returns A new array of objects
2616
+ */
1975
2617
  async nextPage(size, offset) {
1976
2618
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1977
2619
  return new _RecordArray(newPage);
1978
2620
  }
2621
+ /**
2622
+ * Retrieve previous page of records
2623
+ *
2624
+ * @returns A new array of objects
2625
+ */
1979
2626
  async previousPage(size, offset) {
1980
2627
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1981
2628
  return new _RecordArray(newPage);
1982
2629
  }
2630
+ /**
2631
+ * Retrieve start page of records
2632
+ *
2633
+ * @returns A new array of objects
2634
+ */
1983
2635
  async startPage(size, offset) {
1984
2636
  const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1985
2637
  return new _RecordArray(newPage);
1986
2638
  }
2639
+ /**
2640
+ * Retrieve end page of records
2641
+ *
2642
+ * @returns A new array of objects
2643
+ */
1987
2644
  async endPage(size, offset) {
1988
2645
  const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1989
2646
  return new _RecordArray(newPage);
1990
2647
  }
2648
+ /**
2649
+ * @returns Boolean indicating if there is a next page
2650
+ */
1991
2651
  hasNextPage() {
1992
2652
  return __privateGet$6(this, _page).meta.page.more;
1993
2653
  }
@@ -2024,7 +2684,8 @@ const _Query = class {
2024
2684
  __privateAdd$5(this, _table$1, void 0);
2025
2685
  __privateAdd$5(this, _repository, void 0);
2026
2686
  __privateAdd$5(this, _data, { filter: {} });
2027
- this.meta = { page: { cursor: "start", more: true } };
2687
+ // Implements pagination
2688
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
2028
2689
  this.records = new RecordArray(this, []);
2029
2690
  __privateSet$5(this, _table$1, table);
2030
2691
  if (repository) {
@@ -2061,18 +2722,38 @@ const _Query = class {
2061
2722
  const key = JSON.stringify({ columns, filter, sort, pagination });
2062
2723
  return toBase64(key);
2063
2724
  }
2725
+ /**
2726
+ * Builds a new query object representing a logical OR between the given subqueries.
2727
+ * @param queries An array of subqueries.
2728
+ * @returns A new Query object.
2729
+ */
2064
2730
  any(...queries) {
2065
2731
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
2066
2732
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
2067
2733
  }
2734
+ /**
2735
+ * Builds a new query object representing a logical AND between the given subqueries.
2736
+ * @param queries An array of subqueries.
2737
+ * @returns A new Query object.
2738
+ */
2068
2739
  all(...queries) {
2069
2740
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
2070
2741
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
2071
2742
  }
2743
+ /**
2744
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
2745
+ * @param queries An array of subqueries.
2746
+ * @returns A new Query object.
2747
+ */
2072
2748
  not(...queries) {
2073
2749
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
2074
2750
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
2075
2751
  }
2752
+ /**
2753
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
2754
+ * @param queries An array of subqueries.
2755
+ * @returns A new Query object.
2756
+ */
2076
2757
  none(...queries) {
2077
2758
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
2078
2759
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
@@ -2095,6 +2776,11 @@ const _Query = class {
2095
2776
  const sort = [...originalSort, { column, direction }];
2096
2777
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
2097
2778
  }
2779
+ /**
2780
+ * Builds a new query specifying the set of columns to be returned in the query response.
2781
+ * @param columns Array of column names to be returned by the query.
2782
+ * @returns A new Query object.
2783
+ */
2098
2784
  select(columns) {
2099
2785
  return new _Query(
2100
2786
  __privateGet$5(this, _repository),
@@ -2107,6 +2793,12 @@ const _Query = class {
2107
2793
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
2108
2794
  return __privateGet$5(this, _repository).query(query);
2109
2795
  }
2796
+ /**
2797
+ * Get results in an iterator
2798
+ *
2799
+ * @async
2800
+ * @returns Async interable of results
2801
+ */
2110
2802
  async *[Symbol.asyncIterator]() {
2111
2803
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
2112
2804
  yield record;
@@ -2167,21 +2859,49 @@ const _Query = class {
2167
2859
  );
2168
2860
  return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2169
2861
  }
2862
+ /**
2863
+ * Builds a new query object adding a cache TTL in milliseconds.
2864
+ * @param ttl The cache TTL in milliseconds.
2865
+ * @returns A new Query object.
2866
+ */
2170
2867
  cache(ttl) {
2171
2868
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2172
2869
  }
2870
+ /**
2871
+ * Retrieve next page of records
2872
+ *
2873
+ * @returns A new page object.
2874
+ */
2173
2875
  nextPage(size, offset) {
2174
2876
  return this.startPage(size, offset);
2175
2877
  }
2878
+ /**
2879
+ * Retrieve previous page of records
2880
+ *
2881
+ * @returns A new page object
2882
+ */
2176
2883
  previousPage(size, offset) {
2177
2884
  return this.startPage(size, offset);
2178
2885
  }
2886
+ /**
2887
+ * Retrieve start page of records
2888
+ *
2889
+ * @returns A new page object
2890
+ */
2179
2891
  startPage(size, offset) {
2180
2892
  return this.getPaginated({ pagination: { size, offset } });
2181
2893
  }
2894
+ /**
2895
+ * Retrieve last page of records
2896
+ *
2897
+ * @returns A new page object
2898
+ */
2182
2899
  endPage(size, offset) {
2183
2900
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2184
2901
  }
2902
+ /**
2903
+ * @returns Boolean indicating if there is a next page
2904
+ */
2185
2905
  hasNextPage() {
2186
2906
  return this.meta.page.more;
2187
2907
  }
@@ -2221,7 +2941,11 @@ function isSortFilterString(value) {
2221
2941
  return isString(value);
2222
2942
  }
2223
2943
  function isSortFilterBase(filter) {
2224
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
2944
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
2945
+ if (key === "*")
2946
+ return value === "random";
2947
+ return value === "asc" || value === "desc";
2948
+ });
2225
2949
  }
2226
2950
  function isSortFilterObject(filter) {
2227
2951
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -2294,10 +3018,7 @@ class RestRepository extends Query {
2294
3018
  __privateSet$4(this, _db, options.db);
2295
3019
  __privateSet$4(this, _cache, options.pluginOptions.cache);
2296
3020
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2297
- __privateSet$4(this, _getFetchProps, async () => {
2298
- const props = await options.pluginOptions.getFetchProps();
2299
- return { ...props, sessionID: generateUUID() };
2300
- });
3021
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2301
3022
  const trace = options.pluginOptions.trace ?? defaultTrace;
2302
3023
  __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2303
3024
  return trace(name, fn, {
@@ -2354,7 +3075,6 @@ class RestRepository extends Query {
2354
3075
  }
2355
3076
  const id = extractId(a);
2356
3077
  if (id) {
2357
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2358
3078
  try {
2359
3079
  const response = await getRecord({
2360
3080
  pathParams: {
@@ -2365,7 +3085,7 @@ class RestRepository extends Query {
2365
3085
  recordId: id
2366
3086
  },
2367
3087
  queryParams: { columns },
2368
- ...fetchProps
3088
+ ...__privateGet$4(this, _getFetchProps).call(this)
2369
3089
  });
2370
3090
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2371
3091
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2465,12 +3185,22 @@ class RestRepository extends Query {
2465
3185
  return result;
2466
3186
  }
2467
3187
  if (isString(a) && isObject(b)) {
3188
+ if (a === "")
3189
+ throw new Error("The id can't be empty");
2468
3190
  const columns = isStringArray(c) ? c : void 0;
2469
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3191
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2470
3192
  }
2471
3193
  if (isObject(a) && isString(a.id)) {
3194
+ if (a.id === "")
3195
+ throw new Error("The id can't be empty");
2472
3196
  const columns = isStringArray(c) ? c : void 0;
2473
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3197
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3198
+ }
3199
+ if (!isDefined(a) && isObject(b)) {
3200
+ return await this.create(b, c);
3201
+ }
3202
+ if (isObject(a) && !isDefined(a.id)) {
3203
+ return await this.create(a, b);
2474
3204
  }
2475
3205
  throw new Error("Invalid arguments for createOrUpdate method");
2476
3206
  });
@@ -2487,12 +3217,22 @@ class RestRepository extends Query {
2487
3217
  return result;
2488
3218
  }
2489
3219
  if (isString(a) && isObject(b)) {
3220
+ if (a === "")
3221
+ throw new Error("The id can't be empty");
2490
3222
  const columns = isStringArray(c) ? c : void 0;
2491
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3223
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2492
3224
  }
2493
3225
  if (isObject(a) && isString(a.id)) {
3226
+ if (a.id === "")
3227
+ throw new Error("The id can't be empty");
2494
3228
  const columns = isStringArray(c) ? c : void 0;
2495
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3229
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3230
+ }
3231
+ if (!isDefined(a) && isObject(b)) {
3232
+ return await this.create(b, c);
3233
+ }
3234
+ if (isObject(a) && !isDefined(a.id)) {
3235
+ return await this.create(a, b);
2496
3236
  }
2497
3237
  throw new Error("Invalid arguments for createOrReplace method");
2498
3238
  });
@@ -2543,7 +3283,6 @@ class RestRepository extends Query {
2543
3283
  }
2544
3284
  async search(query, options = {}) {
2545
3285
  return __privateGet$4(this, _trace).call(this, "search", async () => {
2546
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2547
3286
  const { records } = await searchTable({
2548
3287
  pathParams: {
2549
3288
  workspace: "{workspaceId}",
@@ -2561,7 +3300,29 @@ class RestRepository extends Query {
2561
3300
  page: options.page,
2562
3301
  target: options.target
2563
3302
  },
2564
- ...fetchProps
3303
+ ...__privateGet$4(this, _getFetchProps).call(this)
3304
+ });
3305
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3306
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3307
+ });
3308
+ }
3309
+ async vectorSearch(column, query, options) {
3310
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3311
+ const { records } = await vectorSearchTable({
3312
+ pathParams: {
3313
+ workspace: "{workspaceId}",
3314
+ dbBranchName: "{dbBranch}",
3315
+ region: "{region}",
3316
+ tableName: __privateGet$4(this, _table)
3317
+ },
3318
+ body: {
3319
+ column,
3320
+ queryVector: query,
3321
+ similarityFunction: options?.similarityFunction,
3322
+ size: options?.size,
3323
+ filter: options?.filter
3324
+ },
3325
+ ...__privateGet$4(this, _getFetchProps).call(this)
2565
3326
  });
2566
3327
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2567
3328
  return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
@@ -2569,7 +3330,6 @@ class RestRepository extends Query {
2569
3330
  }
2570
3331
  async aggregate(aggs, filter) {
2571
3332
  return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2572
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2573
3333
  const result = await aggregateTable({
2574
3334
  pathParams: {
2575
3335
  workspace: "{workspaceId}",
@@ -2578,7 +3338,7 @@ class RestRepository extends Query {
2578
3338
  tableName: __privateGet$4(this, _table)
2579
3339
  },
2580
3340
  body: { aggs, filter },
2581
- ...fetchProps
3341
+ ...__privateGet$4(this, _getFetchProps).call(this)
2582
3342
  });
2583
3343
  return result;
2584
3344
  });
@@ -2589,7 +3349,6 @@ class RestRepository extends Query {
2589
3349
  if (cacheQuery)
2590
3350
  return new Page(query, cacheQuery.meta, cacheQuery.records);
2591
3351
  const data = query.getQueryOptions();
2592
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2593
3352
  const { meta, records: objects } = await queryTable({
2594
3353
  pathParams: {
2595
3354
  workspace: "{workspaceId}",
@@ -2605,7 +3364,7 @@ class RestRepository extends Query {
2605
3364
  consistency: data.consistency
2606
3365
  },
2607
3366
  fetchOptions: data.fetchOptions,
2608
- ...fetchProps
3367
+ ...__privateGet$4(this, _getFetchProps).call(this)
2609
3368
  });
2610
3369
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2611
3370
  const records = objects.map(
@@ -2618,7 +3377,6 @@ class RestRepository extends Query {
2618
3377
  async summarizeTable(query, summaries, summariesFilter) {
2619
3378
  return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2620
3379
  const data = query.getQueryOptions();
2621
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2622
3380
  const result = await summarizeTable({
2623
3381
  pathParams: {
2624
3382
  workspace: "{workspaceId}",
@@ -2635,11 +3393,39 @@ class RestRepository extends Query {
2635
3393
  summaries,
2636
3394
  summariesFilter
2637
3395
  },
2638
- ...fetchProps
3396
+ ...__privateGet$4(this, _getFetchProps).call(this)
2639
3397
  });
2640
3398
  return result;
2641
3399
  });
2642
3400
  }
3401
+ ask(question, options) {
3402
+ const params = {
3403
+ pathParams: {
3404
+ workspace: "{workspaceId}",
3405
+ dbBranchName: "{dbBranch}",
3406
+ region: "{region}",
3407
+ tableName: __privateGet$4(this, _table)
3408
+ },
3409
+ body: {
3410
+ question,
3411
+ ...options
3412
+ },
3413
+ ...__privateGet$4(this, _getFetchProps).call(this)
3414
+ };
3415
+ if (options?.onMessage) {
3416
+ fetchSSERequest({
3417
+ endpoint: "dataPlane",
3418
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
3419
+ method: "POST",
3420
+ onMessage: (message) => {
3421
+ options.onMessage?.({ answer: message.text, records: message.records });
3422
+ },
3423
+ ...params
3424
+ });
3425
+ } else {
3426
+ return askTable(params);
3427
+ }
3428
+ }
2643
3429
  }
2644
3430
  _table = new WeakMap();
2645
3431
  _getFetchProps = new WeakMap();
@@ -2649,7 +3435,6 @@ _schemaTables$2 = new WeakMap();
2649
3435
  _trace = new WeakMap();
2650
3436
  _insertRecordWithoutId = new WeakSet();
2651
3437
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2652
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2653
3438
  const record = transformObjectLinks(object);
2654
3439
  const response = await insertRecord({
2655
3440
  pathParams: {
@@ -2660,14 +3445,15 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2660
3445
  },
2661
3446
  queryParams: { columns },
2662
3447
  body: record,
2663
- ...fetchProps
3448
+ ...__privateGet$4(this, _getFetchProps).call(this)
2664
3449
  });
2665
3450
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2666
3451
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2667
3452
  };
2668
3453
  _insertRecordWithId = new WeakSet();
2669
3454
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2670
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3455
+ if (!recordId)
3456
+ return null;
2671
3457
  const record = transformObjectLinks(object);
2672
3458
  const response = await insertRecordWithID({
2673
3459
  pathParams: {
@@ -2679,14 +3465,13 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2679
3465
  },
2680
3466
  body: record,
2681
3467
  queryParams: { createOnly, columns, ifVersion },
2682
- ...fetchProps
3468
+ ...__privateGet$4(this, _getFetchProps).call(this)
2683
3469
  });
2684
3470
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2685
3471
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2686
3472
  };
2687
3473
  _insertRecords = new WeakSet();
2688
3474
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2689
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2690
3475
  const chunkedOperations = chunk(
2691
3476
  objects.map((object) => ({
2692
3477
  insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
@@ -2702,7 +3487,7 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2702
3487
  region: "{region}"
2703
3488
  },
2704
3489
  body: { operations },
2705
- ...fetchProps
3490
+ ...__privateGet$4(this, _getFetchProps).call(this)
2706
3491
  });
2707
3492
  for (const result of results) {
2708
3493
  if (result.operation === "insert") {
@@ -2716,7 +3501,8 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2716
3501
  };
2717
3502
  _updateRecordWithID = new WeakSet();
2718
3503
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2719
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3504
+ if (!recordId)
3505
+ return null;
2720
3506
  const { id: _id, ...record } = transformObjectLinks(object);
2721
3507
  try {
2722
3508
  const response = await updateRecordWithID({
@@ -2729,7 +3515,7 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2729
3515
  },
2730
3516
  queryParams: { columns, ifVersion },
2731
3517
  body: record,
2732
- ...fetchProps
3518
+ ...__privateGet$4(this, _getFetchProps).call(this)
2733
3519
  });
2734
3520
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2735
3521
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2742,7 +3528,6 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2742
3528
  };
2743
3529
  _updateRecords = new WeakSet();
2744
3530
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2745
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2746
3531
  const chunkedOperations = chunk(
2747
3532
  objects.map(({ id, ...object }) => ({
2748
3533
  update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
@@ -2758,7 +3543,7 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2758
3543
  region: "{region}"
2759
3544
  },
2760
3545
  body: { operations },
2761
- ...fetchProps
3546
+ ...__privateGet$4(this, _getFetchProps).call(this)
2762
3547
  });
2763
3548
  for (const result of results) {
2764
3549
  if (result.operation === "update") {
@@ -2772,7 +3557,8 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2772
3557
  };
2773
3558
  _upsertRecordWithID = new WeakSet();
2774
3559
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2775
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3560
+ if (!recordId)
3561
+ return null;
2776
3562
  const response = await upsertRecordWithID({
2777
3563
  pathParams: {
2778
3564
  workspace: "{workspaceId}",
@@ -2783,14 +3569,15 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2783
3569
  },
2784
3570
  queryParams: { columns, ifVersion },
2785
3571
  body: object,
2786
- ...fetchProps
3572
+ ...__privateGet$4(this, _getFetchProps).call(this)
2787
3573
  });
2788
3574
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2789
3575
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2790
3576
  };
2791
3577
  _deleteRecord = new WeakSet();
2792
3578
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
2793
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3579
+ if (!recordId)
3580
+ return null;
2794
3581
  try {
2795
3582
  const response = await deleteRecord({
2796
3583
  pathParams: {
@@ -2801,7 +3588,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2801
3588
  recordId
2802
3589
  },
2803
3590
  queryParams: { columns },
2804
- ...fetchProps
3591
+ ...__privateGet$4(this, _getFetchProps).call(this)
2805
3592
  });
2806
3593
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2807
3594
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2814,9 +3601,8 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2814
3601
  };
2815
3602
  _deleteRecords = new WeakSet();
2816
3603
  deleteRecords_fn = async function(recordIds) {
2817
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2818
3604
  const chunkedOperations = chunk(
2819
- recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
3605
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2820
3606
  BULK_OPERATION_MAX_SIZE
2821
3607
  );
2822
3608
  for (const operations of chunkedOperations) {
@@ -2827,21 +3613,22 @@ deleteRecords_fn = async function(recordIds) {
2827
3613
  region: "{region}"
2828
3614
  },
2829
3615
  body: { operations },
2830
- ...fetchProps
3616
+ ...__privateGet$4(this, _getFetchProps).call(this)
2831
3617
  });
2832
3618
  }
2833
3619
  };
2834
3620
  _setCacheQuery = new WeakSet();
2835
3621
  setCacheQuery_fn = async function(query, meta, records) {
2836
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
3622
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
2837
3623
  };
2838
3624
  _getCacheQuery = new WeakSet();
2839
3625
  getCacheQuery_fn = async function(query) {
2840
3626
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2841
- const result = await __privateGet$4(this, _cache).get(key);
3627
+ const result = await __privateGet$4(this, _cache)?.get(key);
2842
3628
  if (!result)
2843
3629
  return null;
2844
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
3630
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
3631
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2845
3632
  if (ttl < 0)
2846
3633
  return null;
2847
3634
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2851,10 +3638,9 @@ _getSchemaTables$1 = new WeakSet();
2851
3638
  getSchemaTables_fn$1 = async function() {
2852
3639
  if (__privateGet$4(this, _schemaTables$2))
2853
3640
  return __privateGet$4(this, _schemaTables$2);
2854
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2855
3641
  const { schema } = await getBranchDetails({
2856
3642
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2857
- ...fetchProps
3643
+ ...__privateGet$4(this, _getFetchProps).call(this)
2858
3644
  });
2859
3645
  __privateSet$4(this, _schemaTables$2, schema.tables);
2860
3646
  return schema.tables;
@@ -2917,6 +3703,8 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2917
3703
  }
2918
3704
  }
2919
3705
  const record = { ...data };
3706
+ const serializable = { xata, ...transformObjectLinks(data) };
3707
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
2920
3708
  record.read = function(columns2) {
2921
3709
  return db[table].read(record["id"], columns2);
2922
3710
  };
@@ -2933,10 +3721,17 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2933
3721
  record.delete = function() {
2934
3722
  return db[table].delete(record["id"]);
2935
3723
  };
3724
+ record.xata = Object.freeze(metadata);
2936
3725
  record.getMetadata = function() {
2937
- return xata;
3726
+ return record.xata;
3727
+ };
3728
+ record.toSerializable = function() {
3729
+ return JSON.parse(JSON.stringify(serializable));
3730
+ };
3731
+ record.toString = function() {
3732
+ return JSON.stringify(transformObjectLinks(serializable));
2938
3733
  };
2939
- for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
3734
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
2940
3735
  Object.defineProperty(record, prop, { enumerable: false });
2941
3736
  }
2942
3737
  Object.freeze(record);
@@ -3124,19 +3919,19 @@ class SearchPlugin extends XataPlugin {
3124
3919
  __privateAdd$1(this, _schemaTables, void 0);
3125
3920
  __privateSet$1(this, _schemaTables, schemaTables);
3126
3921
  }
3127
- build({ getFetchProps }) {
3922
+ build(pluginOptions) {
3128
3923
  return {
3129
3924
  all: async (query, options = {}) => {
3130
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3131
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3925
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3926
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3132
3927
  return records.map((record) => {
3133
3928
  const { table = "orphan" } = record.xata;
3134
3929
  return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
3135
3930
  });
3136
3931
  },
3137
3932
  byTable: async (query, options = {}) => {
3138
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3139
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3933
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3934
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3140
3935
  return records.reduce((acc, record) => {
3141
3936
  const { table = "orphan" } = record.xata;
3142
3937
  const items = acc[table] ?? [];
@@ -3149,38 +3944,36 @@ class SearchPlugin extends XataPlugin {
3149
3944
  }
3150
3945
  _schemaTables = new WeakMap();
3151
3946
  _search = new WeakSet();
3152
- search_fn = async function(query, options, getFetchProps) {
3153
- const fetchProps = await getFetchProps();
3947
+ search_fn = async function(query, options, pluginOptions) {
3154
3948
  const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3155
3949
  const { records } = await searchBranch({
3156
3950
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3951
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
3157
3952
  body: { tables, query, fuzziness, prefix, highlight, page },
3158
- ...fetchProps
3953
+ ...pluginOptions
3159
3954
  });
3160
3955
  return records;
3161
3956
  };
3162
3957
  _getSchemaTables = new WeakSet();
3163
- getSchemaTables_fn = async function(getFetchProps) {
3958
+ getSchemaTables_fn = async function(pluginOptions) {
3164
3959
  if (__privateGet$1(this, _schemaTables))
3165
3960
  return __privateGet$1(this, _schemaTables);
3166
- const fetchProps = await getFetchProps();
3167
3961
  const { schema } = await getBranchDetails({
3168
3962
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3169
- ...fetchProps
3963
+ ...pluginOptions
3170
3964
  });
3171
3965
  __privateSet$1(this, _schemaTables, schema.tables);
3172
3966
  return schema.tables;
3173
3967
  };
3174
3968
 
3175
3969
  class TransactionPlugin extends XataPlugin {
3176
- build({ getFetchProps }) {
3970
+ build(pluginOptions) {
3177
3971
  return {
3178
3972
  run: async (operations) => {
3179
- const fetchProps = await getFetchProps();
3180
3973
  const response = await branchTransaction({
3181
3974
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3182
3975
  body: { operations },
3183
- ...fetchProps
3976
+ ...pluginOptions
3184
3977
  });
3185
3978
  return response;
3186
3979
  }
@@ -3188,90 +3981,6 @@ class TransactionPlugin extends XataPlugin {
3188
3981
  }
3189
3982
  }
3190
3983
 
3191
- const isBranchStrategyBuilder = (strategy) => {
3192
- return typeof strategy === "function";
3193
- };
3194
-
3195
- async function getCurrentBranchName(options) {
3196
- const { branch, envBranch } = getEnvironment();
3197
- if (branch)
3198
- return branch;
3199
- const gitBranch = envBranch || await getGitBranch();
3200
- return resolveXataBranch(gitBranch, options);
3201
- }
3202
- async function getCurrentBranchDetails(options) {
3203
- const branch = await getCurrentBranchName(options);
3204
- return getDatabaseBranch(branch, options);
3205
- }
3206
- async function resolveXataBranch(gitBranch, options) {
3207
- const databaseURL = options?.databaseURL || getDatabaseURL();
3208
- const apiKey = options?.apiKey || getAPIKey();
3209
- if (!databaseURL)
3210
- throw new Error(
3211
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3212
- );
3213
- if (!apiKey)
3214
- throw new Error(
3215
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3216
- );
3217
- const [protocol, , host, , dbName] = databaseURL.split("/");
3218
- const urlParts = parseWorkspacesUrlParts(host);
3219
- if (!urlParts)
3220
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3221
- const { workspace, region } = urlParts;
3222
- const { fallbackBranch } = getEnvironment();
3223
- const { branch } = await resolveBranch({
3224
- apiKey,
3225
- apiUrl: databaseURL,
3226
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3227
- workspacesApiUrl: `${protocol}//${host}`,
3228
- pathParams: { dbName, workspace, region },
3229
- queryParams: { gitBranch, fallbackBranch },
3230
- trace: defaultTrace,
3231
- clientName: options?.clientName
3232
- });
3233
- return branch;
3234
- }
3235
- async function getDatabaseBranch(branch, options) {
3236
- const databaseURL = options?.databaseURL || getDatabaseURL();
3237
- const apiKey = options?.apiKey || getAPIKey();
3238
- if (!databaseURL)
3239
- throw new Error(
3240
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3241
- );
3242
- if (!apiKey)
3243
- throw new Error(
3244
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3245
- );
3246
- const [protocol, , host, , database] = databaseURL.split("/");
3247
- const urlParts = parseWorkspacesUrlParts(host);
3248
- if (!urlParts)
3249
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3250
- const { workspace, region } = urlParts;
3251
- try {
3252
- return await getBranchDetails({
3253
- apiKey,
3254
- apiUrl: databaseURL,
3255
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3256
- workspacesApiUrl: `${protocol}//${host}`,
3257
- pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3258
- trace: defaultTrace
3259
- });
3260
- } catch (err) {
3261
- if (isObject(err) && err.status === 404)
3262
- return null;
3263
- throw err;
3264
- }
3265
- }
3266
- function getDatabaseURL() {
3267
- try {
3268
- const { databaseURL } = getEnvironment();
3269
- return databaseURL;
3270
- } catch (err) {
3271
- return void 0;
3272
- }
3273
- }
3274
-
3275
3984
  var __accessCheck = (obj, member, msg) => {
3276
3985
  if (!member.has(obj))
3277
3986
  throw TypeError("Cannot " + msg);
@@ -3295,20 +4004,18 @@ var __privateMethod = (obj, member, method) => {
3295
4004
  return method;
3296
4005
  };
3297
4006
  const buildClient = (plugins) => {
3298
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
4007
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3299
4008
  return _a = class {
3300
4009
  constructor(options = {}, schemaTables) {
3301
4010
  __privateAdd(this, _parseOptions);
3302
4011
  __privateAdd(this, _getFetchProps);
3303
- __privateAdd(this, _evaluateBranch);
3304
- __privateAdd(this, _branch, void 0);
3305
4012
  __privateAdd(this, _options, void 0);
3306
4013
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3307
4014
  __privateSet(this, _options, safeOptions);
3308
4015
  const pluginOptions = {
3309
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
4016
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3310
4017
  cache: safeOptions.cache,
3311
- trace: safeOptions.trace
4018
+ host: safeOptions.host
3312
4019
  };
3313
4020
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3314
4021
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
@@ -3319,22 +4026,15 @@ const buildClient = (plugins) => {
3319
4026
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3320
4027
  if (namespace === void 0)
3321
4028
  continue;
3322
- const result = namespace.build(pluginOptions);
3323
- if (result instanceof Promise) {
3324
- void result.then((namespace2) => {
3325
- this[key] = namespace2;
3326
- });
3327
- } else {
3328
- this[key] = result;
3329
- }
4029
+ this[key] = namespace.build(pluginOptions);
3330
4030
  }
3331
4031
  }
3332
4032
  async getConfig() {
3333
4033
  const databaseURL = __privateGet(this, _options).databaseURL;
3334
- const branch = await __privateGet(this, _options).branch();
4034
+ const branch = __privateGet(this, _options).branch;
3335
4035
  return { databaseURL, branch };
3336
4036
  }
3337
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4037
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3338
4038
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3339
4039
  const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3340
4040
  if (isBrowser && !enableBrowser) {
@@ -3348,60 +4048,72 @@ const buildClient = (plugins) => {
3348
4048
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3349
4049
  const trace = options?.trace ?? defaultTrace;
3350
4050
  const clientName = options?.clientName;
3351
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({
3352
- apiKey,
3353
- databaseURL,
3354
- fetchImpl: options?.fetch,
3355
- clientName: options?.clientName
3356
- });
4051
+ const host = options?.host ?? "production";
4052
+ const xataAgentExtra = options?.xataAgentExtra;
3357
4053
  if (!apiKey) {
3358
4054
  throw new Error("Option apiKey is required");
3359
4055
  }
3360
4056
  if (!databaseURL) {
3361
4057
  throw new Error("Option databaseURL is required");
3362
4058
  }
3363
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser, clientName };
3364
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
4059
+ const envBranch = getBranch();
4060
+ const previewBranch = getPreviewBranch();
4061
+ const branch = options?.branch || previewBranch || envBranch || "main";
4062
+ if (!!previewBranch && branch !== previewBranch) {
4063
+ console.warn(
4064
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4065
+ );
4066
+ } else if (!!envBranch && branch !== envBranch) {
4067
+ console.warn(
4068
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4069
+ );
4070
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4071
+ console.warn(
4072
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4073
+ );
4074
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4075
+ console.warn(
4076
+ `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.`
4077
+ );
4078
+ }
4079
+ return {
4080
+ fetch,
4081
+ databaseURL,
4082
+ apiKey,
4083
+ branch,
4084
+ cache,
4085
+ trace,
4086
+ host,
4087
+ clientID: generateUUID(),
4088
+ enableBrowser,
4089
+ clientName,
4090
+ xataAgentExtra
4091
+ };
4092
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
3365
4093
  fetch,
3366
4094
  apiKey,
3367
4095
  databaseURL,
3368
4096
  branch,
3369
4097
  trace,
3370
4098
  clientID,
3371
- clientName
4099
+ clientName,
4100
+ xataAgentExtra
3372
4101
  }) {
3373
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3374
- if (!branchValue)
3375
- throw new Error("Unable to resolve branch value");
3376
4102
  return {
3377
- fetchImpl: fetch,
4103
+ fetch,
3378
4104
  apiKey,
3379
4105
  apiUrl: "",
4106
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3380
4107
  workspacesApiUrl: (path, params) => {
3381
4108
  const hasBranch = params.dbBranchName ?? params.branch;
3382
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
4109
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
3383
4110
  return databaseURL + newPath;
3384
4111
  },
3385
4112
  trace,
3386
4113
  clientID,
3387
- clientName
4114
+ clientName,
4115
+ xataAgentExtra
3388
4116
  };
3389
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3390
- if (__privateGet(this, _branch))
3391
- return __privateGet(this, _branch);
3392
- if (param === void 0)
3393
- return void 0;
3394
- const strategies = Array.isArray(param) ? [...param] : [param];
3395
- const evaluateBranch = async (strategy) => {
3396
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
3397
- };
3398
- for await (const strategy of strategies) {
3399
- const branch = await evaluateBranch(strategy);
3400
- if (branch) {
3401
- __privateSet(this, _branch, branch);
3402
- return branch;
3403
- }
3404
- }
3405
4117
  }, _a;
3406
4118
  };
3407
4119
  class BaseClient extends buildClient() {
@@ -3521,8 +4233,11 @@ exports.addGitBranchesEntry = addGitBranchesEntry;
3521
4233
  exports.addTableColumn = addTableColumn;
3522
4234
  exports.aggregateTable = aggregateTable;
3523
4235
  exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
4236
+ exports.askTable = askTable;
3524
4237
  exports.branchTransaction = branchTransaction;
3525
4238
  exports.buildClient = buildClient;
4239
+ exports.buildPreviewBranchName = buildPreviewBranchName;
4240
+ exports.buildProviderString = buildProviderString;
3526
4241
  exports.buildWorkerRunner = buildWorkerRunner;
3527
4242
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
3528
4243
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
@@ -3530,6 +4245,7 @@ exports.compareBranchSchemas = compareBranchSchemas;
3530
4245
  exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
3531
4246
  exports.compareMigrationRequest = compareMigrationRequest;
3532
4247
  exports.contains = contains;
4248
+ exports.copyBranch = copyBranch;
3533
4249
  exports.createBranch = createBranch;
3534
4250
  exports.createDatabase = createDatabase;
3535
4251
  exports.createMigrationRequest = createMigrationRequest;
@@ -3539,6 +4255,9 @@ exports.createWorkspace = createWorkspace;
3539
4255
  exports.deleteBranch = deleteBranch;
3540
4256
  exports.deleteColumn = deleteColumn;
3541
4257
  exports.deleteDatabase = deleteDatabase;
4258
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
4259
+ exports.deleteFile = deleteFile;
4260
+ exports.deleteFileItem = deleteFileItem;
3542
4261
  exports.deleteRecord = deleteRecord;
3543
4262
  exports.deleteTable = deleteTable;
3544
4263
  exports.deleteUser = deleteUser;
@@ -3549,8 +4268,10 @@ exports.endsWith = endsWith;
3549
4268
  exports.equals = equals;
3550
4269
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
3551
4270
  exports.exists = exists;
4271
+ exports.fileAccess = fileAccess;
3552
4272
  exports.ge = ge;
3553
4273
  exports.getAPIKey = getAPIKey;
4274
+ exports.getBranch = getBranch;
3554
4275
  exports.getBranchDetails = getBranchDetails;
3555
4276
  exports.getBranchList = getBranchList;
3556
4277
  exports.getBranchMetadata = getBranchMetadata;
@@ -3559,15 +4280,17 @@ exports.getBranchMigrationPlan = getBranchMigrationPlan;
3559
4280
  exports.getBranchSchemaHistory = getBranchSchemaHistory;
3560
4281
  exports.getBranchStats = getBranchStats;
3561
4282
  exports.getColumn = getColumn;
3562
- exports.getCurrentBranchDetails = getCurrentBranchDetails;
3563
- exports.getCurrentBranchName = getCurrentBranchName;
4283
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
3564
4284
  exports.getDatabaseList = getDatabaseList;
3565
4285
  exports.getDatabaseMetadata = getDatabaseMetadata;
3566
4286
  exports.getDatabaseURL = getDatabaseURL;
4287
+ exports.getFile = getFile;
4288
+ exports.getFileItem = getFileItem;
3567
4289
  exports.getGitBranchesMapping = getGitBranchesMapping;
3568
4290
  exports.getHostUrl = getHostUrl;
3569
4291
  exports.getMigrationRequest = getMigrationRequest;
3570
4292
  exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
4293
+ exports.getPreviewBranch = getPreviewBranch;
3571
4294
  exports.getRecord = getRecord;
3572
4295
  exports.getTableColumns = getTableColumns;
3573
4296
  exports.getTableSchema = getTableSchema;
@@ -3610,21 +4333,27 @@ exports.parseProviderString = parseProviderString;
3610
4333
  exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
3611
4334
  exports.pattern = pattern;
3612
4335
  exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
4336
+ exports.pushBranchMigrations = pushBranchMigrations;
4337
+ exports.putFile = putFile;
4338
+ exports.putFileItem = putFileItem;
3613
4339
  exports.queryMigrationRequests = queryMigrationRequests;
3614
4340
  exports.queryTable = queryTable;
3615
4341
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
3616
4342
  exports.removeWorkspaceMember = removeWorkspaceMember;
4343
+ exports.renameDatabase = renameDatabase;
3617
4344
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
3618
4345
  exports.resolveBranch = resolveBranch;
3619
4346
  exports.searchBranch = searchBranch;
3620
4347
  exports.searchTable = searchTable;
3621
4348
  exports.serialize = serialize;
3622
4349
  exports.setTableSchema = setTableSchema;
4350
+ exports.sqlQuery = sqlQuery;
3623
4351
  exports.startsWith = startsWith;
3624
4352
  exports.summarizeTable = summarizeTable;
3625
4353
  exports.updateBranchMetadata = updateBranchMetadata;
3626
4354
  exports.updateBranchSchema = updateBranchSchema;
3627
4355
  exports.updateColumn = updateColumn;
4356
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
3628
4357
  exports.updateDatabaseMetadata = updateDatabaseMetadata;
3629
4358
  exports.updateMigrationRequest = updateMigrationRequest;
3630
4359
  exports.updateRecordWithID = updateRecordWithID;
@@ -3634,4 +4363,5 @@ exports.updateWorkspace = updateWorkspace;
3634
4363
  exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
3635
4364
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
3636
4365
  exports.upsertRecordWithID = upsertRecordWithID;
4366
+ exports.vectorSearchTable = vectorSearchTable;
3637
4367
  //# sourceMappingURL=index.cjs.map