@xata.io/client 0.0.0-alpha.vf71bb14 → 0.0.0-alpha.vf726cd76bbb4ca962ba9b7cd65a295354fbb999c

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.
Files changed (71) hide show
  1. package/.turbo/turbo-add-version.log +4 -0
  2. package/.turbo/turbo-build.log +13 -0
  3. package/CHANGELOG.md +745 -0
  4. package/README.md +7 -1
  5. package/dist/index.cjs +5082 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.ts +10504 -7
  8. package/dist/index.mjs +4892 -0
  9. package/dist/index.mjs.map +1 -0
  10. package/package.json +20 -10
  11. package/.eslintrc.cjs +0 -13
  12. package/dist/api/client.d.ts +0 -95
  13. package/dist/api/client.js +0 -251
  14. package/dist/api/components.d.ts +0 -1437
  15. package/dist/api/components.js +0 -998
  16. package/dist/api/fetcher.d.ts +0 -40
  17. package/dist/api/fetcher.js +0 -79
  18. package/dist/api/index.d.ts +0 -13
  19. package/dist/api/index.js +0 -40
  20. package/dist/api/parameters.d.ts +0 -16
  21. package/dist/api/parameters.js +0 -2
  22. package/dist/api/providers.d.ts +0 -8
  23. package/dist/api/providers.js +0 -30
  24. package/dist/api/responses.d.ts +0 -50
  25. package/dist/api/responses.js +0 -2
  26. package/dist/api/schemas.d.ts +0 -311
  27. package/dist/api/schemas.js +0 -2
  28. package/dist/client.d.ts +0 -27
  29. package/dist/client.js +0 -131
  30. package/dist/index.js +0 -30
  31. package/dist/plugins.d.ts +0 -7
  32. package/dist/plugins.js +0 -6
  33. package/dist/schema/filters.d.ts +0 -96
  34. package/dist/schema/filters.js +0 -2
  35. package/dist/schema/filters.spec.d.ts +0 -1
  36. package/dist/schema/filters.spec.js +0 -177
  37. package/dist/schema/index.d.ts +0 -24
  38. package/dist/schema/index.js +0 -60
  39. package/dist/schema/operators.d.ts +0 -74
  40. package/dist/schema/operators.js +0 -93
  41. package/dist/schema/pagination.d.ts +0 -83
  42. package/dist/schema/pagination.js +0 -93
  43. package/dist/schema/query.d.ts +0 -118
  44. package/dist/schema/query.js +0 -242
  45. package/dist/schema/record.d.ts +0 -66
  46. package/dist/schema/record.js +0 -13
  47. package/dist/schema/repository.d.ts +0 -135
  48. package/dist/schema/repository.js +0 -283
  49. package/dist/schema/selection.d.ts +0 -25
  50. package/dist/schema/selection.js +0 -2
  51. package/dist/schema/selection.spec.d.ts +0 -1
  52. package/dist/schema/selection.spec.js +0 -204
  53. package/dist/schema/sorting.d.ts +0 -22
  54. package/dist/schema/sorting.js +0 -35
  55. package/dist/schema/sorting.spec.d.ts +0 -1
  56. package/dist/schema/sorting.spec.js +0 -11
  57. package/dist/search/index.d.ts +0 -34
  58. package/dist/search/index.js +0 -55
  59. package/dist/util/branches.d.ts +0 -5
  60. package/dist/util/branches.js +0 -7
  61. package/dist/util/config.d.ts +0 -11
  62. package/dist/util/config.js +0 -121
  63. package/dist/util/environment.d.ts +0 -5
  64. package/dist/util/environment.js +0 -68
  65. package/dist/util/fetch.d.ts +0 -2
  66. package/dist/util/fetch.js +0 -13
  67. package/dist/util/lang.d.ts +0 -5
  68. package/dist/util/lang.js +0 -22
  69. package/dist/util/types.d.ts +0 -25
  70. package/dist/util/types.js +0 -2
  71. package/tsconfig.json +0 -21
package/dist/index.mjs ADDED
@@ -0,0 +1,4892 @@
1
+ const defaultTrace = async (name, fn, _options) => {
2
+ return await fn({
3
+ name,
4
+ setAttributes: () => {
5
+ return;
6
+ }
7
+ });
8
+ };
9
+ const TraceAttributes = {
10
+ KIND: "xata.trace.kind",
11
+ VERSION: "xata.sdk.version",
12
+ TABLE: "xata.table",
13
+ HTTP_REQUEST_ID: "http.request_id",
14
+ HTTP_STATUS_CODE: "http.status_code",
15
+ HTTP_HOST: "http.host",
16
+ HTTP_SCHEME: "http.scheme",
17
+ HTTP_USER_AGENT: "http.user_agent",
18
+ HTTP_METHOD: "http.method",
19
+ HTTP_URL: "http.url",
20
+ HTTP_ROUTE: "http.route",
21
+ HTTP_TARGET: "http.target",
22
+ CLOUDFLARE_RAY_ID: "cf.ray"
23
+ };
24
+
25
+ function notEmpty(value) {
26
+ return value !== null && value !== void 0;
27
+ }
28
+ function compact(arr) {
29
+ return arr.filter(notEmpty);
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
+ }
41
+ function isObject(value) {
42
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
43
+ }
44
+ function isDefined(value) {
45
+ return value !== null && value !== void 0;
46
+ }
47
+ function isString(value) {
48
+ return isDefined(value) && typeof value === "string";
49
+ }
50
+ function isStringArray(value) {
51
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
52
+ }
53
+ function isNumber(value) {
54
+ return isDefined(value) && typeof value === "number";
55
+ }
56
+ function parseNumber(value) {
57
+ if (isNumber(value)) {
58
+ return value;
59
+ }
60
+ if (isString(value)) {
61
+ const parsed = Number(value);
62
+ if (!Number.isNaN(parsed)) {
63
+ return parsed;
64
+ }
65
+ }
66
+ return void 0;
67
+ }
68
+ function toBase64(value) {
69
+ try {
70
+ return btoa(value);
71
+ } catch (err) {
72
+ const buf = Buffer;
73
+ return buf.from(value).toString("base64");
74
+ }
75
+ }
76
+ function deepMerge(a, b) {
77
+ const result = { ...a };
78
+ for (const [key, value] of Object.entries(b)) {
79
+ if (isObject(value) && isObject(result[key])) {
80
+ result[key] = deepMerge(result[key], value);
81
+ } else {
82
+ result[key] = value;
83
+ }
84
+ }
85
+ return result;
86
+ }
87
+ function chunk(array, chunkSize) {
88
+ const result = [];
89
+ for (let i = 0; i < array.length; i += chunkSize) {
90
+ result.push(array.slice(i, i + chunkSize));
91
+ }
92
+ return result;
93
+ }
94
+ async function timeout(ms) {
95
+ return new Promise((resolve) => setTimeout(resolve, ms));
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
+ }
118
+
119
+ function getEnvironment() {
120
+ try {
121
+ if (isDefined(process) && isDefined(process.env)) {
122
+ return {
123
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
124
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
125
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
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
130
+ };
131
+ }
132
+ } catch (err) {
133
+ }
134
+ try {
135
+ if (isObject(Deno) && isObject(Deno.env)) {
136
+ return {
137
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
138
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
139
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
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")
144
+ };
145
+ }
146
+ } catch (err) {
147
+ }
148
+ return {
149
+ apiKey: getGlobalApiKey(),
150
+ databaseURL: getGlobalDatabaseURL(),
151
+ branch: getGlobalBranch(),
152
+ deployPreview: void 0,
153
+ deployPreviewBranch: void 0,
154
+ vercelGitCommitRef: void 0,
155
+ vercelGitRepoOwner: void 0
156
+ };
157
+ }
158
+ function getEnableBrowserVariable() {
159
+ try {
160
+ if (isObject(process) && isObject(process.env) && process.env.XATA_ENABLE_BROWSER !== void 0) {
161
+ return process.env.XATA_ENABLE_BROWSER === "true";
162
+ }
163
+ } catch (err) {
164
+ }
165
+ try {
166
+ if (isObject(Deno) && isObject(Deno.env) && Deno.env.get("XATA_ENABLE_BROWSER") !== void 0) {
167
+ return Deno.env.get("XATA_ENABLE_BROWSER") === "true";
168
+ }
169
+ } catch (err) {
170
+ }
171
+ try {
172
+ return XATA_ENABLE_BROWSER === true || XATA_ENABLE_BROWSER === "true";
173
+ } catch (err) {
174
+ return void 0;
175
+ }
176
+ }
177
+ function getGlobalApiKey() {
178
+ try {
179
+ return XATA_API_KEY;
180
+ } catch (err) {
181
+ return void 0;
182
+ }
183
+ }
184
+ function getGlobalDatabaseURL() {
185
+ try {
186
+ return XATA_DATABASE_URL;
187
+ } catch (err) {
188
+ return void 0;
189
+ }
190
+ }
191
+ function getGlobalBranch() {
192
+ try {
193
+ return XATA_BRANCH;
194
+ } catch (err) {
195
+ return void 0;
196
+ }
197
+ }
198
+ function getDatabaseURL() {
199
+ try {
200
+ const { databaseURL } = getEnvironment();
201
+ return databaseURL;
202
+ } catch (err) {
203
+ return void 0;
204
+ }
205
+ }
206
+ function getAPIKey() {
207
+ try {
208
+ const { apiKey } = getEnvironment();
209
+ return apiKey;
210
+ } catch (err) {
211
+ return void 0;
212
+ }
213
+ }
214
+ function getBranch() {
215
+ try {
216
+ const { branch } = getEnvironment();
217
+ return branch;
218
+ } catch (err) {
219
+ return void 0;
220
+ }
221
+ }
222
+ function buildPreviewBranchName({ org, branch }) {
223
+ return `preview-${org}-${branch}`;
224
+ }
225
+ function getPreviewBranch() {
226
+ try {
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;
240
+ } catch (err) {
241
+ return void 0;
242
+ }
243
+ }
244
+
245
+ var __accessCheck$8 = (obj, member, msg) => {
246
+ if (!member.has(obj))
247
+ throw TypeError("Cannot " + msg);
248
+ };
249
+ var __privateGet$7 = (obj, member, getter) => {
250
+ __accessCheck$8(obj, member, "read from private field");
251
+ return getter ? getter.call(obj) : member.get(obj);
252
+ };
253
+ var __privateAdd$8 = (obj, member, value) => {
254
+ if (member.has(obj))
255
+ throw TypeError("Cannot add the same private member more than once");
256
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
257
+ };
258
+ var __privateSet$6 = (obj, member, value, setter) => {
259
+ __accessCheck$8(obj, member, "write to private field");
260
+ setter ? setter.call(obj, value) : member.set(obj, value);
261
+ return value;
262
+ };
263
+ var __privateMethod$4 = (obj, member, method) => {
264
+ __accessCheck$8(obj, member, "access private method");
265
+ return method;
266
+ };
267
+ var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
268
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
269
+ function getFetchImplementation(userFetch) {
270
+ const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
271
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
272
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
273
+ if (!fetchImpl) {
274
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
275
+ }
276
+ return fetchImpl;
277
+ }
278
+ class ApiRequestPool {
279
+ constructor(concurrency = 10) {
280
+ __privateAdd$8(this, _enqueue);
281
+ __privateAdd$8(this, _fetch, void 0);
282
+ __privateAdd$8(this, _queue, void 0);
283
+ __privateAdd$8(this, _concurrency, void 0);
284
+ __privateSet$6(this, _queue, []);
285
+ __privateSet$6(this, _concurrency, concurrency);
286
+ this.running = 0;
287
+ this.started = 0;
288
+ }
289
+ setFetch(fetch2) {
290
+ __privateSet$6(this, _fetch, fetch2);
291
+ }
292
+ getFetch() {
293
+ if (!__privateGet$7(this, _fetch)) {
294
+ throw new Error("Fetch not set");
295
+ }
296
+ return __privateGet$7(this, _fetch);
297
+ }
298
+ request(url, options) {
299
+ const start = /* @__PURE__ */ new Date();
300
+ const fetchImpl = this.getFetch();
301
+ const runRequest = async (stalled = false) => {
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
+ }
307
+ if (response.status === 429) {
308
+ const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
309
+ await timeout(rateLimitReset * 1e3);
310
+ return await runRequest(true);
311
+ }
312
+ if (stalled) {
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`);
315
+ }
316
+ return response;
317
+ };
318
+ return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
319
+ return await runRequest();
320
+ });
321
+ }
322
+ }
323
+ _fetch = new WeakMap();
324
+ _queue = new WeakMap();
325
+ _concurrency = new WeakMap();
326
+ _enqueue = new WeakSet();
327
+ enqueue_fn = function(task) {
328
+ const promise = new Promise((resolve) => __privateGet$7(this, _queue).push(resolve)).finally(() => {
329
+ this.started--;
330
+ this.running++;
331
+ }).then(() => task()).finally(() => {
332
+ this.running--;
333
+ const next = __privateGet$7(this, _queue).shift();
334
+ if (next !== void 0) {
335
+ this.started++;
336
+ next();
337
+ }
338
+ });
339
+ if (this.running + this.started < __privateGet$7(this, _concurrency)) {
340
+ const next = __privateGet$7(this, _queue).shift();
341
+ if (next !== void 0) {
342
+ this.started++;
343
+ next();
344
+ }
345
+ }
346
+ return promise;
347
+ };
348
+
349
+ function generateUUID() {
350
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
351
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
352
+ return v.toString(16);
353
+ });
354
+ }
355
+
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.29.3";
530
+
531
+ class ErrorWithCause extends Error {
532
+ constructor(message, options) {
533
+ super(message, options);
534
+ }
535
+ }
536
+ class FetcherError extends ErrorWithCause {
537
+ constructor(status, data, requestId) {
538
+ super(getMessage(data));
539
+ this.status = status;
540
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
541
+ this.requestId = requestId;
542
+ if (data instanceof Error) {
543
+ this.stack = data.stack;
544
+ this.cause = data.cause;
545
+ }
546
+ }
547
+ toString() {
548
+ const error = super.toString();
549
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
550
+ }
551
+ }
552
+ function isBulkError(error) {
553
+ return isObject(error) && Array.isArray(error.errors);
554
+ }
555
+ function isErrorWithMessage(error) {
556
+ return isObject(error) && isString(error.message);
557
+ }
558
+ function getMessage(data) {
559
+ if (data instanceof Error) {
560
+ return data.message;
561
+ } else if (isString(data)) {
562
+ return data;
563
+ } else if (isErrorWithMessage(data)) {
564
+ return data.message;
565
+ } else if (isBulkError(data)) {
566
+ return "Bulk operation failed";
567
+ } else {
568
+ return "Unexpected error";
569
+ }
570
+ }
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\/db\/([^:]+):?(.*)?/),
623
+ staging: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev\/db\/([^:]+):?(.*)?/),
624
+ dev: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev\/db\/([^:]+):?(.*)?/),
625
+ local: url.match(/(?:https?:\/\/)?([^.]+)(?:\.([^.]+))\.localhost:([^:]+):?(.*)?/)
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], database: match[3], branch: match[4], host };
631
+ }
632
+
633
+ const pool = new ApiRequestPool();
634
+ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
635
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
636
+ if (value === void 0 || value === null)
637
+ return acc;
638
+ return { ...acc, [key]: value };
639
+ }, {});
640
+ const query = new URLSearchParams(cleanQueryParams).toString();
641
+ const queryString = query.length > 0 ? `?${query}` : "";
642
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
643
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
644
+ }, {});
645
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
646
+ };
647
+ function buildBaseUrl({
648
+ method,
649
+ endpoint,
650
+ path,
651
+ workspacesApiUrl,
652
+ apiUrl,
653
+ pathParams = {}
654
+ }) {
655
+ if (endpoint === "dataPlane") {
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
+ }
674
+ const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
675
+ return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
676
+ }
677
+ return `${apiUrl}${path}`;
678
+ }
679
+ function hostHeader(url) {
680
+ const pattern = /.*:\/\/(?<host>[^/]+).*/;
681
+ const { groups } = pattern.exec(url) ?? {};
682
+ return groups?.host ? { Host: groups.host } : {};
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
+ }
696
+ const defaultClientID = generateUUID();
697
+ async function fetch$1({
698
+ url: path,
699
+ method,
700
+ body,
701
+ headers: customHeaders,
702
+ pathParams,
703
+ queryParams,
704
+ fetch: fetch2,
705
+ apiKey,
706
+ endpoint,
707
+ apiUrl,
708
+ workspacesApiUrl,
709
+ trace,
710
+ signal,
711
+ clientID,
712
+ sessionID,
713
+ clientName,
714
+ xataAgentExtra,
715
+ fetchOptions = {},
716
+ rawResponse = false
717
+ }) {
718
+ pool.setFetch(fetch2);
719
+ return await trace(
720
+ `${method.toUpperCase()} ${path}`,
721
+ async ({ setAttributes }) => {
722
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
723
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
724
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\.[^.]+\./, "http://") : fullUrl;
725
+ setAttributes({
726
+ [TraceAttributes.HTTP_URL]: url,
727
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
728
+ });
729
+ const xataAgent = compact([
730
+ ["client", "TS_SDK"],
731
+ ["version", VERSION],
732
+ isDefined(clientName) ? ["service", clientName] : void 0,
733
+ ...Object.entries(xataAgentExtra ?? {})
734
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
735
+ const headers = compactObject({
736
+ "Accept-Encoding": "identity",
737
+ "Content-Type": "application/json",
738
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
739
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
740
+ "X-Xata-Agent": xataAgent,
741
+ ...customHeaders,
742
+ ...hostHeader(fullUrl),
743
+ Authorization: `Bearer ${apiKey}`
744
+ });
745
+ const response = await pool.request(url, {
746
+ ...fetchOptions,
747
+ method: method.toUpperCase(),
748
+ body: await parseBody(body, headers),
749
+ headers,
750
+ signal
751
+ });
752
+ const { host, protocol } = parseUrl(response.url);
753
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
754
+ setAttributes({
755
+ [TraceAttributes.KIND]: "http",
756
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
757
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
758
+ [TraceAttributes.HTTP_HOST]: host,
759
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
760
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
761
+ });
762
+ const message = response.headers?.get("x-xata-message");
763
+ if (message)
764
+ console.warn(message);
765
+ if (response.status === 204) {
766
+ return {};
767
+ }
768
+ if (response.status === 429) {
769
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
770
+ }
771
+ try {
772
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
773
+ if (response.ok) {
774
+ return jsonResponse;
775
+ }
776
+ throw new FetcherError(response.status, jsonResponse, requestId);
777
+ } catch (error) {
778
+ throw new FetcherError(response.status, error, requestId);
779
+ }
780
+ },
781
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
782
+ );
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
+ }
837
+ function parseUrl(url) {
838
+ try {
839
+ const { host, protocol } = new URL(url);
840
+ return { host, protocol };
841
+ } catch (error) {
842
+ return {};
843
+ }
844
+ }
845
+
846
+ const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
847
+
848
+ const applyMigration = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/apply", method: "post", ...variables, signal });
849
+ const adaptTable = (variables, signal) => dataPlaneFetch({
850
+ url: "/db/{dbBranchName}/migrations/adapt/{tableName}",
851
+ method: "post",
852
+ ...variables,
853
+ signal
854
+ });
855
+ const getBranchMigrationJobStatus = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/status", method: "get", ...variables, signal });
856
+ const getMigrationJobStatus = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/jobs/{jobId}", method: "get", ...variables, signal });
857
+ const getMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/history", method: "get", ...variables, signal });
858
+ const getBranchList = (variables, signal) => dataPlaneFetch({
859
+ url: "/dbs/{dbName}",
860
+ method: "get",
861
+ ...variables,
862
+ signal
863
+ });
864
+ const getDatabaseSettings = (variables, signal) => dataPlaneFetch({
865
+ url: "/dbs/{dbName}/settings",
866
+ method: "get",
867
+ ...variables,
868
+ signal
869
+ });
870
+ const updateDatabaseSettings = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/settings", method: "patch", ...variables, signal });
871
+ const getBranchDetails = (variables, signal) => dataPlaneFetch({
872
+ url: "/db/{dbBranchName}",
873
+ method: "get",
874
+ ...variables,
875
+ signal
876
+ });
877
+ const createBranch = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
878
+ const deleteBranch = (variables, signal) => dataPlaneFetch({
879
+ url: "/db/{dbBranchName}",
880
+ method: "delete",
881
+ ...variables,
882
+ signal
883
+ });
884
+ const getSchema = (variables, signal) => dataPlaneFetch({
885
+ url: "/db/{dbBranchName}/schema",
886
+ method: "get",
887
+ ...variables,
888
+ signal
889
+ });
890
+ const copyBranch = (variables, signal) => dataPlaneFetch({
891
+ url: "/db/{dbBranchName}/copy",
892
+ method: "post",
893
+ ...variables,
894
+ signal
895
+ });
896
+ const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
897
+ url: "/db/{dbBranchName}/metadata",
898
+ method: "put",
899
+ ...variables,
900
+ signal
901
+ });
902
+ const getBranchMetadata = (variables, signal) => dataPlaneFetch({
903
+ url: "/db/{dbBranchName}/metadata",
904
+ method: "get",
905
+ ...variables,
906
+ signal
907
+ });
908
+ const getBranchStats = (variables, signal) => dataPlaneFetch({
909
+ url: "/db/{dbBranchName}/stats",
910
+ method: "get",
911
+ ...variables,
912
+ signal
913
+ });
914
+ const getGitBranchesMapping = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables, signal });
915
+ const addGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables, signal });
916
+ const removeGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables, signal });
917
+ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/resolveBranch", method: "get", ...variables, signal });
918
+ const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
919
+ const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
920
+ const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
921
+ const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
922
+ const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
923
+ const getMigrationRequest = (variables, signal) => dataPlaneFetch({
924
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
925
+ method: "get",
926
+ ...variables,
927
+ signal
928
+ });
929
+ const updateMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables, signal });
930
+ const listMigrationRequestsCommits = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables, signal });
931
+ const compareMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables, signal });
932
+ const getMigrationRequestIsMerged = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables, signal });
933
+ const mergeMigrationRequest = (variables, signal) => dataPlaneFetch({
934
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
935
+ method: "post",
936
+ ...variables,
937
+ signal
938
+ });
939
+ const getBranchSchemaHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables, signal });
940
+ const compareBranchWithUserSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables, signal });
941
+ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables, signal });
942
+ const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
943
+ const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
944
+ const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
945
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
946
+ const createTable = (variables, signal) => dataPlaneFetch({
947
+ url: "/db/{dbBranchName}/tables/{tableName}",
948
+ method: "put",
949
+ ...variables,
950
+ signal
951
+ });
952
+ const deleteTable = (variables, signal) => dataPlaneFetch({
953
+ url: "/db/{dbBranchName}/tables/{tableName}",
954
+ method: "delete",
955
+ ...variables,
956
+ signal
957
+ });
958
+ const updateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}", method: "patch", ...variables, signal });
959
+ const getTableSchema = (variables, signal) => dataPlaneFetch({
960
+ url: "/db/{dbBranchName}/tables/{tableName}/schema",
961
+ method: "get",
962
+ ...variables,
963
+ signal
964
+ });
965
+ const setTableSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/schema", method: "put", ...variables, signal });
966
+ const getTableColumns = (variables, signal) => dataPlaneFetch({
967
+ url: "/db/{dbBranchName}/tables/{tableName}/columns",
968
+ method: "get",
969
+ ...variables,
970
+ signal
971
+ });
972
+ const addTableColumn = (variables, signal) => dataPlaneFetch(
973
+ { url: "/db/{dbBranchName}/tables/{tableName}/columns", method: "post", ...variables, signal }
974
+ );
975
+ const getColumn = (variables, signal) => dataPlaneFetch({
976
+ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
977
+ method: "get",
978
+ ...variables,
979
+ signal
980
+ });
981
+ const updateColumn = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}", method: "patch", ...variables, signal });
982
+ const deleteColumn = (variables, signal) => dataPlaneFetch({
983
+ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
984
+ method: "delete",
985
+ ...variables,
986
+ signal
987
+ });
988
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
989
+ const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
990
+ const getFileItem = (variables, signal) => dataPlaneFetch({
991
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
992
+ method: "get",
993
+ ...variables,
994
+ signal
995
+ });
996
+ const putFileItem = (variables, signal) => dataPlaneFetch({
997
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
998
+ method: "put",
999
+ ...variables,
1000
+ signal
1001
+ });
1002
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
1003
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
1004
+ method: "delete",
1005
+ ...variables,
1006
+ signal
1007
+ });
1008
+ const getFile = (variables, signal) => dataPlaneFetch({
1009
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1010
+ method: "get",
1011
+ ...variables,
1012
+ signal
1013
+ });
1014
+ const putFile = (variables, signal) => dataPlaneFetch({
1015
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1016
+ method: "put",
1017
+ ...variables,
1018
+ signal
1019
+ });
1020
+ const deleteFile = (variables, signal) => dataPlaneFetch({
1021
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1022
+ method: "delete",
1023
+ ...variables,
1024
+ signal
1025
+ });
1026
+ const getRecord = (variables, signal) => dataPlaneFetch({
1027
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
1028
+ method: "get",
1029
+ ...variables,
1030
+ signal
1031
+ });
1032
+ const insertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables, signal });
1033
+ const updateRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables, signal });
1034
+ const upsertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables, signal });
1035
+ const deleteRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "delete", ...variables, signal });
1036
+ const bulkInsertTableRecords = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables, signal });
1037
+ const queryTable = (variables, signal) => dataPlaneFetch({
1038
+ url: "/db/{dbBranchName}/tables/{tableName}/query",
1039
+ method: "post",
1040
+ ...variables,
1041
+ signal
1042
+ });
1043
+ const searchBranch = (variables, signal) => dataPlaneFetch({
1044
+ url: "/db/{dbBranchName}/search",
1045
+ method: "post",
1046
+ ...variables,
1047
+ signal
1048
+ });
1049
+ const searchTable = (variables, signal) => dataPlaneFetch({
1050
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
1051
+ method: "post",
1052
+ ...variables,
1053
+ signal
1054
+ });
1055
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
1056
+ const askTable = (variables, signal) => dataPlaneFetch({
1057
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
1058
+ method: "post",
1059
+ ...variables,
1060
+ signal
1061
+ });
1062
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
1063
+ const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
1064
+ const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
1065
+ const fileAccess = (variables, signal) => dataPlaneFetch({
1066
+ url: "/file/{fileId}",
1067
+ method: "get",
1068
+ ...variables,
1069
+ signal
1070
+ });
1071
+ const fileUpload = (variables, signal) => dataPlaneFetch({
1072
+ url: "/file/{fileId}",
1073
+ method: "put",
1074
+ ...variables,
1075
+ signal
1076
+ });
1077
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
1078
+ url: "/db/{dbBranchName}/sql",
1079
+ method: "post",
1080
+ ...variables,
1081
+ signal
1082
+ });
1083
+ const operationsByTag$2 = {
1084
+ migrations: {
1085
+ applyMigration,
1086
+ adaptTable,
1087
+ getBranchMigrationJobStatus,
1088
+ getMigrationJobStatus,
1089
+ getMigrationHistory,
1090
+ getSchema,
1091
+ getBranchMigrationHistory,
1092
+ getBranchMigrationPlan,
1093
+ executeBranchMigrationPlan,
1094
+ getBranchSchemaHistory,
1095
+ compareBranchWithUserSchema,
1096
+ compareBranchSchemas,
1097
+ updateBranchSchema,
1098
+ previewBranchSchemaEdit,
1099
+ applyBranchSchemaEdit,
1100
+ pushBranchMigrations
1101
+ },
1102
+ branch: {
1103
+ getBranchList,
1104
+ getBranchDetails,
1105
+ createBranch,
1106
+ deleteBranch,
1107
+ copyBranch,
1108
+ updateBranchMetadata,
1109
+ getBranchMetadata,
1110
+ getBranchStats,
1111
+ getGitBranchesMapping,
1112
+ addGitBranchesEntry,
1113
+ removeGitBranchesEntry,
1114
+ resolveBranch
1115
+ },
1116
+ database: { getDatabaseSettings, updateDatabaseSettings },
1117
+ migrationRequests: {
1118
+ queryMigrationRequests,
1119
+ createMigrationRequest,
1120
+ getMigrationRequest,
1121
+ updateMigrationRequest,
1122
+ listMigrationRequestsCommits,
1123
+ compareMigrationRequest,
1124
+ getMigrationRequestIsMerged,
1125
+ mergeMigrationRequest
1126
+ },
1127
+ table: {
1128
+ createTable,
1129
+ deleteTable,
1130
+ updateTable,
1131
+ getTableSchema,
1132
+ setTableSchema,
1133
+ getTableColumns,
1134
+ addTableColumn,
1135
+ getColumn,
1136
+ updateColumn,
1137
+ deleteColumn
1138
+ },
1139
+ records: {
1140
+ branchTransaction,
1141
+ insertRecord,
1142
+ getRecord,
1143
+ insertRecordWithID,
1144
+ updateRecordWithID,
1145
+ upsertRecordWithID,
1146
+ deleteRecord,
1147
+ bulkInsertTableRecords
1148
+ },
1149
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess, fileUpload },
1150
+ searchAndFilter: {
1151
+ queryTable,
1152
+ searchBranch,
1153
+ searchTable,
1154
+ vectorSearchTable,
1155
+ askTable,
1156
+ askTableSession,
1157
+ summarizeTable,
1158
+ aggregateTable
1159
+ },
1160
+ sql: { sqlQuery }
1161
+ };
1162
+
1163
+ const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
1164
+
1165
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1166
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
1167
+ const getUser = (variables, signal) => controlPlaneFetch({
1168
+ url: "/user",
1169
+ method: "get",
1170
+ ...variables,
1171
+ signal
1172
+ });
1173
+ const updateUser = (variables, signal) => controlPlaneFetch({
1174
+ url: "/user",
1175
+ method: "put",
1176
+ ...variables,
1177
+ signal
1178
+ });
1179
+ const deleteUser = (variables, signal) => controlPlaneFetch({
1180
+ url: "/user",
1181
+ method: "delete",
1182
+ ...variables,
1183
+ signal
1184
+ });
1185
+ const getUserAPIKeys = (variables, signal) => controlPlaneFetch({
1186
+ url: "/user/keys",
1187
+ method: "get",
1188
+ ...variables,
1189
+ signal
1190
+ });
1191
+ const createUserAPIKey = (variables, signal) => controlPlaneFetch({
1192
+ url: "/user/keys/{keyName}",
1193
+ method: "post",
1194
+ ...variables,
1195
+ signal
1196
+ });
1197
+ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
1198
+ url: "/user/keys/{keyName}",
1199
+ method: "delete",
1200
+ ...variables,
1201
+ signal
1202
+ });
1203
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1204
+ url: "/user/oauth/clients",
1205
+ method: "get",
1206
+ ...variables,
1207
+ signal
1208
+ });
1209
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1210
+ url: "/user/oauth/clients/{clientId}",
1211
+ method: "delete",
1212
+ ...variables,
1213
+ signal
1214
+ });
1215
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1216
+ url: "/user/oauth/tokens",
1217
+ method: "get",
1218
+ ...variables,
1219
+ signal
1220
+ });
1221
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1222
+ url: "/user/oauth/tokens/{token}",
1223
+ method: "delete",
1224
+ ...variables,
1225
+ signal
1226
+ });
1227
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
1228
+ const getWorkspacesList = (variables, signal) => controlPlaneFetch({
1229
+ url: "/workspaces",
1230
+ method: "get",
1231
+ ...variables,
1232
+ signal
1233
+ });
1234
+ const createWorkspace = (variables, signal) => controlPlaneFetch({
1235
+ url: "/workspaces",
1236
+ method: "post",
1237
+ ...variables,
1238
+ signal
1239
+ });
1240
+ const getWorkspace = (variables, signal) => controlPlaneFetch({
1241
+ url: "/workspaces/{workspaceId}",
1242
+ method: "get",
1243
+ ...variables,
1244
+ signal
1245
+ });
1246
+ const updateWorkspace = (variables, signal) => controlPlaneFetch({
1247
+ url: "/workspaces/{workspaceId}",
1248
+ method: "put",
1249
+ ...variables,
1250
+ signal
1251
+ });
1252
+ const deleteWorkspace = (variables, signal) => controlPlaneFetch({
1253
+ url: "/workspaces/{workspaceId}",
1254
+ method: "delete",
1255
+ ...variables,
1256
+ signal
1257
+ });
1258
+ const getWorkspaceSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/settings", method: "get", ...variables, signal });
1259
+ const updateWorkspaceSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/settings", method: "patch", ...variables, signal });
1260
+ const getWorkspaceMembersList = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/members", method: "get", ...variables, signal });
1261
+ const updateWorkspaceMemberRole = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables, signal });
1262
+ const removeWorkspaceMember = (variables, signal) => controlPlaneFetch({
1263
+ url: "/workspaces/{workspaceId}/members/{userId}",
1264
+ method: "delete",
1265
+ ...variables,
1266
+ signal
1267
+ });
1268
+ const inviteWorkspaceMember = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables, signal });
1269
+ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables, signal });
1270
+ const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
1271
+ const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
1272
+ const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1273
+ const listClusters = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "get", ...variables, signal });
1274
+ const createCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "post", ...variables, signal });
1275
+ const getCluster = (variables, signal) => controlPlaneFetch({
1276
+ url: "/workspaces/{workspaceId}/clusters/{clusterId}",
1277
+ method: "get",
1278
+ ...variables,
1279
+ signal
1280
+ });
1281
+ const updateCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters/{clusterId}", method: "patch", ...variables, signal });
1282
+ const getDatabaseList = (variables, signal) => controlPlaneFetch({
1283
+ url: "/workspaces/{workspaceId}/dbs",
1284
+ method: "get",
1285
+ ...variables,
1286
+ signal
1287
+ });
1288
+ const createDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables, signal });
1289
+ const deleteDatabase = (variables, signal) => controlPlaneFetch({
1290
+ url: "/workspaces/{workspaceId}/dbs/{dbName}",
1291
+ method: "delete",
1292
+ ...variables,
1293
+ signal
1294
+ });
1295
+ const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
1296
+ const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1297
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1298
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1299
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1300
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
1301
+ const listRegions = (variables, signal) => controlPlaneFetch({
1302
+ url: "/workspaces/{workspaceId}/regions",
1303
+ method: "get",
1304
+ ...variables,
1305
+ signal
1306
+ });
1307
+ const operationsByTag$1 = {
1308
+ oAuth: {
1309
+ getAuthorizationCode,
1310
+ grantAuthorizationCode,
1311
+ getUserOAuthClients,
1312
+ deleteUserOAuthClient,
1313
+ getUserOAuthAccessTokens,
1314
+ deleteOAuthAccessToken,
1315
+ updateOAuthAccessToken
1316
+ },
1317
+ users: { getUser, updateUser, deleteUser },
1318
+ authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
1319
+ workspaces: {
1320
+ getWorkspacesList,
1321
+ createWorkspace,
1322
+ getWorkspace,
1323
+ updateWorkspace,
1324
+ deleteWorkspace,
1325
+ getWorkspaceSettings,
1326
+ updateWorkspaceSettings,
1327
+ getWorkspaceMembersList,
1328
+ updateWorkspaceMemberRole,
1329
+ removeWorkspaceMember
1330
+ },
1331
+ invites: {
1332
+ inviteWorkspaceMember,
1333
+ updateWorkspaceMemberInvite,
1334
+ cancelWorkspaceMemberInvite,
1335
+ acceptWorkspaceMemberInvite,
1336
+ resendWorkspaceMemberInvite
1337
+ },
1338
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
1339
+ databases: {
1340
+ getDatabaseList,
1341
+ createDatabase,
1342
+ deleteDatabase,
1343
+ getDatabaseMetadata,
1344
+ updateDatabaseMetadata,
1345
+ renameDatabase,
1346
+ getDatabaseGithubSettings,
1347
+ updateDatabaseGithubSettings,
1348
+ deleteDatabaseGithubSettings,
1349
+ listRegions
1350
+ }
1351
+ };
1352
+
1353
+ const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);
1354
+
1355
+ var __accessCheck$7 = (obj, member, msg) => {
1356
+ if (!member.has(obj))
1357
+ throw TypeError("Cannot " + msg);
1358
+ };
1359
+ var __privateGet$6 = (obj, member, getter) => {
1360
+ __accessCheck$7(obj, member, "read from private field");
1361
+ return getter ? getter.call(obj) : member.get(obj);
1362
+ };
1363
+ var __privateAdd$7 = (obj, member, value) => {
1364
+ if (member.has(obj))
1365
+ throw TypeError("Cannot add the same private member more than once");
1366
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1367
+ };
1368
+ var __privateSet$5 = (obj, member, value, setter) => {
1369
+ __accessCheck$7(obj, member, "write to private field");
1370
+ setter ? setter.call(obj, value) : member.set(obj, value);
1371
+ return value;
1372
+ };
1373
+ var _extraProps, _namespaces;
1374
+ class XataApiClient {
1375
+ constructor(options = {}) {
1376
+ __privateAdd$7(this, _extraProps, void 0);
1377
+ __privateAdd$7(this, _namespaces, {});
1378
+ const provider = options.host ?? "production";
1379
+ const apiKey = options.apiKey ?? getAPIKey();
1380
+ const trace = options.trace ?? defaultTrace;
1381
+ const clientID = generateUUID();
1382
+ if (!apiKey) {
1383
+ throw new Error("Could not resolve a valid apiKey");
1384
+ }
1385
+ __privateSet$5(this, _extraProps, {
1386
+ apiUrl: getHostUrl(provider, "main"),
1387
+ workspacesApiUrl: getHostUrl(provider, "workspaces"),
1388
+ fetch: getFetchImplementation(options.fetch),
1389
+ apiKey,
1390
+ trace,
1391
+ clientName: options.clientName,
1392
+ xataAgentExtra: options.xataAgentExtra,
1393
+ clientID
1394
+ });
1395
+ }
1396
+ get user() {
1397
+ if (!__privateGet$6(this, _namespaces).user)
1398
+ __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
1399
+ return __privateGet$6(this, _namespaces).user;
1400
+ }
1401
+ get authentication() {
1402
+ if (!__privateGet$6(this, _namespaces).authentication)
1403
+ __privateGet$6(this, _namespaces).authentication = new AuthenticationApi(__privateGet$6(this, _extraProps));
1404
+ return __privateGet$6(this, _namespaces).authentication;
1405
+ }
1406
+ get workspaces() {
1407
+ if (!__privateGet$6(this, _namespaces).workspaces)
1408
+ __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
1409
+ return __privateGet$6(this, _namespaces).workspaces;
1410
+ }
1411
+ get invites() {
1412
+ if (!__privateGet$6(this, _namespaces).invites)
1413
+ __privateGet$6(this, _namespaces).invites = new InvitesApi(__privateGet$6(this, _extraProps));
1414
+ return __privateGet$6(this, _namespaces).invites;
1415
+ }
1416
+ get database() {
1417
+ if (!__privateGet$6(this, _namespaces).database)
1418
+ __privateGet$6(this, _namespaces).database = new DatabaseApi(__privateGet$6(this, _extraProps));
1419
+ return __privateGet$6(this, _namespaces).database;
1420
+ }
1421
+ get branches() {
1422
+ if (!__privateGet$6(this, _namespaces).branches)
1423
+ __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
1424
+ return __privateGet$6(this, _namespaces).branches;
1425
+ }
1426
+ get migrations() {
1427
+ if (!__privateGet$6(this, _namespaces).migrations)
1428
+ __privateGet$6(this, _namespaces).migrations = new MigrationsApi(__privateGet$6(this, _extraProps));
1429
+ return __privateGet$6(this, _namespaces).migrations;
1430
+ }
1431
+ get migrationRequests() {
1432
+ if (!__privateGet$6(this, _namespaces).migrationRequests)
1433
+ __privateGet$6(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$6(this, _extraProps));
1434
+ return __privateGet$6(this, _namespaces).migrationRequests;
1435
+ }
1436
+ get tables() {
1437
+ if (!__privateGet$6(this, _namespaces).tables)
1438
+ __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
1439
+ return __privateGet$6(this, _namespaces).tables;
1440
+ }
1441
+ get records() {
1442
+ if (!__privateGet$6(this, _namespaces).records)
1443
+ __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
1444
+ return __privateGet$6(this, _namespaces).records;
1445
+ }
1446
+ get files() {
1447
+ if (!__privateGet$6(this, _namespaces).files)
1448
+ __privateGet$6(this, _namespaces).files = new FilesApi(__privateGet$6(this, _extraProps));
1449
+ return __privateGet$6(this, _namespaces).files;
1450
+ }
1451
+ get searchAndFilter() {
1452
+ if (!__privateGet$6(this, _namespaces).searchAndFilter)
1453
+ __privateGet$6(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$6(this, _extraProps));
1454
+ return __privateGet$6(this, _namespaces).searchAndFilter;
1455
+ }
1456
+ }
1457
+ _extraProps = new WeakMap();
1458
+ _namespaces = new WeakMap();
1459
+ class UserApi {
1460
+ constructor(extraProps) {
1461
+ this.extraProps = extraProps;
1462
+ }
1463
+ getUser() {
1464
+ return operationsByTag.users.getUser({ ...this.extraProps });
1465
+ }
1466
+ updateUser({ user }) {
1467
+ return operationsByTag.users.updateUser({ body: user, ...this.extraProps });
1468
+ }
1469
+ deleteUser() {
1470
+ return operationsByTag.users.deleteUser({ ...this.extraProps });
1471
+ }
1472
+ }
1473
+ class AuthenticationApi {
1474
+ constructor(extraProps) {
1475
+ this.extraProps = extraProps;
1476
+ }
1477
+ getUserAPIKeys() {
1478
+ return operationsByTag.authentication.getUserAPIKeys({ ...this.extraProps });
1479
+ }
1480
+ createUserAPIKey({ name }) {
1481
+ return operationsByTag.authentication.createUserAPIKey({
1482
+ pathParams: { keyName: name },
1483
+ ...this.extraProps
1484
+ });
1485
+ }
1486
+ deleteUserAPIKey({ name }) {
1487
+ return operationsByTag.authentication.deleteUserAPIKey({
1488
+ pathParams: { keyName: name },
1489
+ ...this.extraProps
1490
+ });
1491
+ }
1492
+ }
1493
+ class WorkspaceApi {
1494
+ constructor(extraProps) {
1495
+ this.extraProps = extraProps;
1496
+ }
1497
+ getWorkspacesList() {
1498
+ return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
1499
+ }
1500
+ createWorkspace({ data }) {
1501
+ return operationsByTag.workspaces.createWorkspace({
1502
+ body: data,
1503
+ ...this.extraProps
1504
+ });
1505
+ }
1506
+ getWorkspace({ workspace }) {
1507
+ return operationsByTag.workspaces.getWorkspace({
1508
+ pathParams: { workspaceId: workspace },
1509
+ ...this.extraProps
1510
+ });
1511
+ }
1512
+ updateWorkspace({
1513
+ workspace,
1514
+ update
1515
+ }) {
1516
+ return operationsByTag.workspaces.updateWorkspace({
1517
+ pathParams: { workspaceId: workspace },
1518
+ body: update,
1519
+ ...this.extraProps
1520
+ });
1521
+ }
1522
+ deleteWorkspace({ workspace }) {
1523
+ return operationsByTag.workspaces.deleteWorkspace({
1524
+ pathParams: { workspaceId: workspace },
1525
+ ...this.extraProps
1526
+ });
1527
+ }
1528
+ getWorkspaceMembersList({ workspace }) {
1529
+ return operationsByTag.workspaces.getWorkspaceMembersList({
1530
+ pathParams: { workspaceId: workspace },
1531
+ ...this.extraProps
1532
+ });
1533
+ }
1534
+ updateWorkspaceMemberRole({
1535
+ workspace,
1536
+ user,
1537
+ role
1538
+ }) {
1539
+ return operationsByTag.workspaces.updateWorkspaceMemberRole({
1540
+ pathParams: { workspaceId: workspace, userId: user },
1541
+ body: { role },
1542
+ ...this.extraProps
1543
+ });
1544
+ }
1545
+ removeWorkspaceMember({
1546
+ workspace,
1547
+ user
1548
+ }) {
1549
+ return operationsByTag.workspaces.removeWorkspaceMember({
1550
+ pathParams: { workspaceId: workspace, userId: user },
1551
+ ...this.extraProps
1552
+ });
1553
+ }
1554
+ }
1555
+ class InvitesApi {
1556
+ constructor(extraProps) {
1557
+ this.extraProps = extraProps;
1558
+ }
1559
+ inviteWorkspaceMember({
1560
+ workspace,
1561
+ email,
1562
+ role
1563
+ }) {
1564
+ return operationsByTag.invites.inviteWorkspaceMember({
1565
+ pathParams: { workspaceId: workspace },
1566
+ body: { email, role },
1567
+ ...this.extraProps
1568
+ });
1569
+ }
1570
+ updateWorkspaceMemberInvite({
1571
+ workspace,
1572
+ invite,
1573
+ role
1574
+ }) {
1575
+ return operationsByTag.invites.updateWorkspaceMemberInvite({
1576
+ pathParams: { workspaceId: workspace, inviteId: invite },
1577
+ body: { role },
1578
+ ...this.extraProps
1579
+ });
1580
+ }
1581
+ cancelWorkspaceMemberInvite({
1582
+ workspace,
1583
+ invite
1584
+ }) {
1585
+ return operationsByTag.invites.cancelWorkspaceMemberInvite({
1586
+ pathParams: { workspaceId: workspace, inviteId: invite },
1587
+ ...this.extraProps
1588
+ });
1589
+ }
1590
+ acceptWorkspaceMemberInvite({
1591
+ workspace,
1592
+ key
1593
+ }) {
1594
+ return operationsByTag.invites.acceptWorkspaceMemberInvite({
1595
+ pathParams: { workspaceId: workspace, inviteKey: key },
1596
+ ...this.extraProps
1597
+ });
1598
+ }
1599
+ resendWorkspaceMemberInvite({
1600
+ workspace,
1601
+ invite
1602
+ }) {
1603
+ return operationsByTag.invites.resendWorkspaceMemberInvite({
1604
+ pathParams: { workspaceId: workspace, inviteId: invite },
1605
+ ...this.extraProps
1606
+ });
1607
+ }
1608
+ }
1609
+ class BranchApi {
1610
+ constructor(extraProps) {
1611
+ this.extraProps = extraProps;
1612
+ }
1613
+ getBranchList({
1614
+ workspace,
1615
+ region,
1616
+ database
1617
+ }) {
1618
+ return operationsByTag.branch.getBranchList({
1619
+ pathParams: { workspace, region, dbName: database },
1620
+ ...this.extraProps
1621
+ });
1622
+ }
1623
+ getBranchDetails({
1624
+ workspace,
1625
+ region,
1626
+ database,
1627
+ branch
1628
+ }) {
1629
+ return operationsByTag.branch.getBranchDetails({
1630
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1631
+ ...this.extraProps
1632
+ });
1633
+ }
1634
+ createBranch({
1635
+ workspace,
1636
+ region,
1637
+ database,
1638
+ branch,
1639
+ from,
1640
+ metadata
1641
+ }) {
1642
+ return operationsByTag.branch.createBranch({
1643
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1644
+ body: { from, metadata },
1645
+ ...this.extraProps
1646
+ });
1647
+ }
1648
+ deleteBranch({
1649
+ workspace,
1650
+ region,
1651
+ database,
1652
+ branch
1653
+ }) {
1654
+ return operationsByTag.branch.deleteBranch({
1655
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1656
+ ...this.extraProps
1657
+ });
1658
+ }
1659
+ copyBranch({
1660
+ workspace,
1661
+ region,
1662
+ database,
1663
+ branch,
1664
+ destinationBranch,
1665
+ limit
1666
+ }) {
1667
+ return operationsByTag.branch.copyBranch({
1668
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1669
+ body: { destinationBranch, limit },
1670
+ ...this.extraProps
1671
+ });
1672
+ }
1673
+ updateBranchMetadata({
1674
+ workspace,
1675
+ region,
1676
+ database,
1677
+ branch,
1678
+ metadata
1679
+ }) {
1680
+ return operationsByTag.branch.updateBranchMetadata({
1681
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1682
+ body: metadata,
1683
+ ...this.extraProps
1684
+ });
1685
+ }
1686
+ getBranchMetadata({
1687
+ workspace,
1688
+ region,
1689
+ database,
1690
+ branch
1691
+ }) {
1692
+ return operationsByTag.branch.getBranchMetadata({
1693
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1694
+ ...this.extraProps
1695
+ });
1696
+ }
1697
+ getBranchStats({
1698
+ workspace,
1699
+ region,
1700
+ database,
1701
+ branch
1702
+ }) {
1703
+ return operationsByTag.branch.getBranchStats({
1704
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1705
+ ...this.extraProps
1706
+ });
1707
+ }
1708
+ getGitBranchesMapping({
1709
+ workspace,
1710
+ region,
1711
+ database
1712
+ }) {
1713
+ return operationsByTag.branch.getGitBranchesMapping({
1714
+ pathParams: { workspace, region, dbName: database },
1715
+ ...this.extraProps
1716
+ });
1717
+ }
1718
+ addGitBranchesEntry({
1719
+ workspace,
1720
+ region,
1721
+ database,
1722
+ gitBranch,
1723
+ xataBranch
1724
+ }) {
1725
+ return operationsByTag.branch.addGitBranchesEntry({
1726
+ pathParams: { workspace, region, dbName: database },
1727
+ body: { gitBranch, xataBranch },
1728
+ ...this.extraProps
1729
+ });
1730
+ }
1731
+ removeGitBranchesEntry({
1732
+ workspace,
1733
+ region,
1734
+ database,
1735
+ gitBranch
1736
+ }) {
1737
+ return operationsByTag.branch.removeGitBranchesEntry({
1738
+ pathParams: { workspace, region, dbName: database },
1739
+ queryParams: { gitBranch },
1740
+ ...this.extraProps
1741
+ });
1742
+ }
1743
+ resolveBranch({
1744
+ workspace,
1745
+ region,
1746
+ database,
1747
+ gitBranch,
1748
+ fallbackBranch
1749
+ }) {
1750
+ return operationsByTag.branch.resolveBranch({
1751
+ pathParams: { workspace, region, dbName: database },
1752
+ queryParams: { gitBranch, fallbackBranch },
1753
+ ...this.extraProps
1754
+ });
1755
+ }
1756
+ pgRollMigrationHistory({
1757
+ workspace,
1758
+ region,
1759
+ database,
1760
+ branch
1761
+ }) {
1762
+ return operationsByTag.migrations.getMigrationHistory({
1763
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1764
+ ...this.extraProps
1765
+ });
1766
+ }
1767
+ applyMigration({
1768
+ workspace,
1769
+ region,
1770
+ database,
1771
+ branch,
1772
+ migration
1773
+ }) {
1774
+ return operationsByTag.migrations.applyMigration({
1775
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1776
+ body: migration,
1777
+ ...this.extraProps
1778
+ });
1779
+ }
1780
+ }
1781
+ class TableApi {
1782
+ constructor(extraProps) {
1783
+ this.extraProps = extraProps;
1784
+ }
1785
+ createTable({
1786
+ workspace,
1787
+ region,
1788
+ database,
1789
+ branch,
1790
+ table
1791
+ }) {
1792
+ return operationsByTag.table.createTable({
1793
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1794
+ ...this.extraProps
1795
+ });
1796
+ }
1797
+ deleteTable({
1798
+ workspace,
1799
+ region,
1800
+ database,
1801
+ branch,
1802
+ table
1803
+ }) {
1804
+ return operationsByTag.table.deleteTable({
1805
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1806
+ ...this.extraProps
1807
+ });
1808
+ }
1809
+ updateTable({
1810
+ workspace,
1811
+ region,
1812
+ database,
1813
+ branch,
1814
+ table,
1815
+ update
1816
+ }) {
1817
+ return operationsByTag.table.updateTable({
1818
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1819
+ body: update,
1820
+ ...this.extraProps
1821
+ });
1822
+ }
1823
+ getTableSchema({
1824
+ workspace,
1825
+ region,
1826
+ database,
1827
+ branch,
1828
+ table
1829
+ }) {
1830
+ return operationsByTag.table.getTableSchema({
1831
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1832
+ ...this.extraProps
1833
+ });
1834
+ }
1835
+ setTableSchema({
1836
+ workspace,
1837
+ region,
1838
+ database,
1839
+ branch,
1840
+ table,
1841
+ schema
1842
+ }) {
1843
+ return operationsByTag.table.setTableSchema({
1844
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1845
+ body: schema,
1846
+ ...this.extraProps
1847
+ });
1848
+ }
1849
+ getTableColumns({
1850
+ workspace,
1851
+ region,
1852
+ database,
1853
+ branch,
1854
+ table
1855
+ }) {
1856
+ return operationsByTag.table.getTableColumns({
1857
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1858
+ ...this.extraProps
1859
+ });
1860
+ }
1861
+ addTableColumn({
1862
+ workspace,
1863
+ region,
1864
+ database,
1865
+ branch,
1866
+ table,
1867
+ column
1868
+ }) {
1869
+ return operationsByTag.table.addTableColumn({
1870
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1871
+ body: column,
1872
+ ...this.extraProps
1873
+ });
1874
+ }
1875
+ getColumn({
1876
+ workspace,
1877
+ region,
1878
+ database,
1879
+ branch,
1880
+ table,
1881
+ column
1882
+ }) {
1883
+ return operationsByTag.table.getColumn({
1884
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
1885
+ ...this.extraProps
1886
+ });
1887
+ }
1888
+ updateColumn({
1889
+ workspace,
1890
+ region,
1891
+ database,
1892
+ branch,
1893
+ table,
1894
+ column,
1895
+ update
1896
+ }) {
1897
+ return operationsByTag.table.updateColumn({
1898
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
1899
+ body: update,
1900
+ ...this.extraProps
1901
+ });
1902
+ }
1903
+ deleteColumn({
1904
+ workspace,
1905
+ region,
1906
+ database,
1907
+ branch,
1908
+ table,
1909
+ column
1910
+ }) {
1911
+ return operationsByTag.table.deleteColumn({
1912
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
1913
+ ...this.extraProps
1914
+ });
1915
+ }
1916
+ }
1917
+ class RecordsApi {
1918
+ constructor(extraProps) {
1919
+ this.extraProps = extraProps;
1920
+ }
1921
+ insertRecord({
1922
+ workspace,
1923
+ region,
1924
+ database,
1925
+ branch,
1926
+ table,
1927
+ record,
1928
+ columns
1929
+ }) {
1930
+ return operationsByTag.records.insertRecord({
1931
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1932
+ queryParams: { columns },
1933
+ body: record,
1934
+ ...this.extraProps
1935
+ });
1936
+ }
1937
+ getRecord({
1938
+ workspace,
1939
+ region,
1940
+ database,
1941
+ branch,
1942
+ table,
1943
+ id,
1944
+ columns
1945
+ }) {
1946
+ return operationsByTag.records.getRecord({
1947
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1948
+ queryParams: { columns },
1949
+ ...this.extraProps
1950
+ });
1951
+ }
1952
+ insertRecordWithID({
1953
+ workspace,
1954
+ region,
1955
+ database,
1956
+ branch,
1957
+ table,
1958
+ id,
1959
+ record,
1960
+ columns,
1961
+ createOnly,
1962
+ ifVersion
1963
+ }) {
1964
+ return operationsByTag.records.insertRecordWithID({
1965
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1966
+ queryParams: { columns, createOnly, ifVersion },
1967
+ body: record,
1968
+ ...this.extraProps
1969
+ });
1970
+ }
1971
+ updateRecordWithID({
1972
+ workspace,
1973
+ region,
1974
+ database,
1975
+ branch,
1976
+ table,
1977
+ id,
1978
+ record,
1979
+ columns,
1980
+ ifVersion
1981
+ }) {
1982
+ return operationsByTag.records.updateRecordWithID({
1983
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1984
+ queryParams: { columns, ifVersion },
1985
+ body: record,
1986
+ ...this.extraProps
1987
+ });
1988
+ }
1989
+ upsertRecordWithID({
1990
+ workspace,
1991
+ region,
1992
+ database,
1993
+ branch,
1994
+ table,
1995
+ id,
1996
+ record,
1997
+ columns,
1998
+ ifVersion
1999
+ }) {
2000
+ return operationsByTag.records.upsertRecordWithID({
2001
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
2002
+ queryParams: { columns, ifVersion },
2003
+ body: record,
2004
+ ...this.extraProps
2005
+ });
2006
+ }
2007
+ deleteRecord({
2008
+ workspace,
2009
+ region,
2010
+ database,
2011
+ branch,
2012
+ table,
2013
+ id,
2014
+ columns
2015
+ }) {
2016
+ return operationsByTag.records.deleteRecord({
2017
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
2018
+ queryParams: { columns },
2019
+ ...this.extraProps
2020
+ });
2021
+ }
2022
+ bulkInsertTableRecords({
2023
+ workspace,
2024
+ region,
2025
+ database,
2026
+ branch,
2027
+ table,
2028
+ records,
2029
+ columns
2030
+ }) {
2031
+ return operationsByTag.records.bulkInsertTableRecords({
2032
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2033
+ queryParams: { columns },
2034
+ body: { records },
2035
+ ...this.extraProps
2036
+ });
2037
+ }
2038
+ branchTransaction({
2039
+ workspace,
2040
+ region,
2041
+ database,
2042
+ branch,
2043
+ operations
2044
+ }) {
2045
+ return operationsByTag.records.branchTransaction({
2046
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2047
+ body: { operations },
2048
+ ...this.extraProps
2049
+ });
2050
+ }
2051
+ }
2052
+ class FilesApi {
2053
+ constructor(extraProps) {
2054
+ this.extraProps = extraProps;
2055
+ }
2056
+ getFileItem({
2057
+ workspace,
2058
+ region,
2059
+ database,
2060
+ branch,
2061
+ table,
2062
+ record,
2063
+ column,
2064
+ fileId
2065
+ }) {
2066
+ return operationsByTag.files.getFileItem({
2067
+ pathParams: {
2068
+ workspace,
2069
+ region,
2070
+ dbBranchName: `${database}:${branch}`,
2071
+ tableName: table,
2072
+ recordId: record,
2073
+ columnName: column,
2074
+ fileId
2075
+ },
2076
+ ...this.extraProps
2077
+ });
2078
+ }
2079
+ putFileItem({
2080
+ workspace,
2081
+ region,
2082
+ database,
2083
+ branch,
2084
+ table,
2085
+ record,
2086
+ column,
2087
+ fileId,
2088
+ file
2089
+ }) {
2090
+ return operationsByTag.files.putFileItem({
2091
+ pathParams: {
2092
+ workspace,
2093
+ region,
2094
+ dbBranchName: `${database}:${branch}`,
2095
+ tableName: table,
2096
+ recordId: record,
2097
+ columnName: column,
2098
+ fileId
2099
+ },
2100
+ // @ts-ignore
2101
+ body: file,
2102
+ ...this.extraProps
2103
+ });
2104
+ }
2105
+ deleteFileItem({
2106
+ workspace,
2107
+ region,
2108
+ database,
2109
+ branch,
2110
+ table,
2111
+ record,
2112
+ column,
2113
+ fileId
2114
+ }) {
2115
+ return operationsByTag.files.deleteFileItem({
2116
+ pathParams: {
2117
+ workspace,
2118
+ region,
2119
+ dbBranchName: `${database}:${branch}`,
2120
+ tableName: table,
2121
+ recordId: record,
2122
+ columnName: column,
2123
+ fileId
2124
+ },
2125
+ ...this.extraProps
2126
+ });
2127
+ }
2128
+ getFile({
2129
+ workspace,
2130
+ region,
2131
+ database,
2132
+ branch,
2133
+ table,
2134
+ record,
2135
+ column
2136
+ }) {
2137
+ return operationsByTag.files.getFile({
2138
+ pathParams: {
2139
+ workspace,
2140
+ region,
2141
+ dbBranchName: `${database}:${branch}`,
2142
+ tableName: table,
2143
+ recordId: record,
2144
+ columnName: column
2145
+ },
2146
+ ...this.extraProps
2147
+ });
2148
+ }
2149
+ putFile({
2150
+ workspace,
2151
+ region,
2152
+ database,
2153
+ branch,
2154
+ table,
2155
+ record,
2156
+ column,
2157
+ file
2158
+ }) {
2159
+ return operationsByTag.files.putFile({
2160
+ pathParams: {
2161
+ workspace,
2162
+ region,
2163
+ dbBranchName: `${database}:${branch}`,
2164
+ tableName: table,
2165
+ recordId: record,
2166
+ columnName: column
2167
+ },
2168
+ body: file,
2169
+ ...this.extraProps
2170
+ });
2171
+ }
2172
+ deleteFile({
2173
+ workspace,
2174
+ region,
2175
+ database,
2176
+ branch,
2177
+ table,
2178
+ record,
2179
+ column
2180
+ }) {
2181
+ return operationsByTag.files.deleteFile({
2182
+ pathParams: {
2183
+ workspace,
2184
+ region,
2185
+ dbBranchName: `${database}:${branch}`,
2186
+ tableName: table,
2187
+ recordId: record,
2188
+ columnName: column
2189
+ },
2190
+ ...this.extraProps
2191
+ });
2192
+ }
2193
+ fileAccess({
2194
+ workspace,
2195
+ region,
2196
+ fileId,
2197
+ verify
2198
+ }) {
2199
+ return operationsByTag.files.fileAccess({
2200
+ pathParams: {
2201
+ workspace,
2202
+ region,
2203
+ fileId
2204
+ },
2205
+ queryParams: { verify },
2206
+ ...this.extraProps
2207
+ });
2208
+ }
2209
+ }
2210
+ class SearchAndFilterApi {
2211
+ constructor(extraProps) {
2212
+ this.extraProps = extraProps;
2213
+ }
2214
+ queryTable({
2215
+ workspace,
2216
+ region,
2217
+ database,
2218
+ branch,
2219
+ table,
2220
+ filter,
2221
+ sort,
2222
+ page,
2223
+ columns,
2224
+ consistency
2225
+ }) {
2226
+ return operationsByTag.searchAndFilter.queryTable({
2227
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2228
+ body: { filter, sort, page, columns, consistency },
2229
+ ...this.extraProps
2230
+ });
2231
+ }
2232
+ searchTable({
2233
+ workspace,
2234
+ region,
2235
+ database,
2236
+ branch,
2237
+ table,
2238
+ query,
2239
+ fuzziness,
2240
+ target,
2241
+ prefix,
2242
+ filter,
2243
+ highlight,
2244
+ boosters
2245
+ }) {
2246
+ return operationsByTag.searchAndFilter.searchTable({
2247
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2248
+ body: { query, fuzziness, target, prefix, filter, highlight, boosters },
2249
+ ...this.extraProps
2250
+ });
2251
+ }
2252
+ searchBranch({
2253
+ workspace,
2254
+ region,
2255
+ database,
2256
+ branch,
2257
+ tables,
2258
+ query,
2259
+ fuzziness,
2260
+ prefix,
2261
+ highlight
2262
+ }) {
2263
+ return operationsByTag.searchAndFilter.searchBranch({
2264
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2265
+ body: { tables, query, fuzziness, prefix, highlight },
2266
+ ...this.extraProps
2267
+ });
2268
+ }
2269
+ vectorSearchTable({
2270
+ workspace,
2271
+ region,
2272
+ database,
2273
+ branch,
2274
+ table,
2275
+ queryVector,
2276
+ column,
2277
+ similarityFunction,
2278
+ size,
2279
+ filter
2280
+ }) {
2281
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2282
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2283
+ body: { queryVector, column, similarityFunction, size, filter },
2284
+ ...this.extraProps
2285
+ });
2286
+ }
2287
+ askTable({
2288
+ workspace,
2289
+ region,
2290
+ database,
2291
+ branch,
2292
+ table,
2293
+ options
2294
+ }) {
2295
+ return operationsByTag.searchAndFilter.askTable({
2296
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2297
+ body: { ...options },
2298
+ ...this.extraProps
2299
+ });
2300
+ }
2301
+ askTableSession({
2302
+ workspace,
2303
+ region,
2304
+ database,
2305
+ branch,
2306
+ table,
2307
+ sessionId,
2308
+ message
2309
+ }) {
2310
+ return operationsByTag.searchAndFilter.askTableSession({
2311
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2312
+ body: { message },
2313
+ ...this.extraProps
2314
+ });
2315
+ }
2316
+ summarizeTable({
2317
+ workspace,
2318
+ region,
2319
+ database,
2320
+ branch,
2321
+ table,
2322
+ filter,
2323
+ columns,
2324
+ summaries,
2325
+ sort,
2326
+ summariesFilter,
2327
+ page,
2328
+ consistency
2329
+ }) {
2330
+ return operationsByTag.searchAndFilter.summarizeTable({
2331
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2332
+ body: { filter, columns, summaries, sort, summariesFilter, page, consistency },
2333
+ ...this.extraProps
2334
+ });
2335
+ }
2336
+ aggregateTable({
2337
+ workspace,
2338
+ region,
2339
+ database,
2340
+ branch,
2341
+ table,
2342
+ filter,
2343
+ aggs
2344
+ }) {
2345
+ return operationsByTag.searchAndFilter.aggregateTable({
2346
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2347
+ body: { filter, aggs },
2348
+ ...this.extraProps
2349
+ });
2350
+ }
2351
+ }
2352
+ class MigrationRequestsApi {
2353
+ constructor(extraProps) {
2354
+ this.extraProps = extraProps;
2355
+ }
2356
+ queryMigrationRequests({
2357
+ workspace,
2358
+ region,
2359
+ database,
2360
+ filter,
2361
+ sort,
2362
+ page,
2363
+ columns
2364
+ }) {
2365
+ return operationsByTag.migrationRequests.queryMigrationRequests({
2366
+ pathParams: { workspace, region, dbName: database },
2367
+ body: { filter, sort, page, columns },
2368
+ ...this.extraProps
2369
+ });
2370
+ }
2371
+ createMigrationRequest({
2372
+ workspace,
2373
+ region,
2374
+ database,
2375
+ migration
2376
+ }) {
2377
+ return operationsByTag.migrationRequests.createMigrationRequest({
2378
+ pathParams: { workspace, region, dbName: database },
2379
+ body: migration,
2380
+ ...this.extraProps
2381
+ });
2382
+ }
2383
+ getMigrationRequest({
2384
+ workspace,
2385
+ region,
2386
+ database,
2387
+ migrationRequest
2388
+ }) {
2389
+ return operationsByTag.migrationRequests.getMigrationRequest({
2390
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2391
+ ...this.extraProps
2392
+ });
2393
+ }
2394
+ updateMigrationRequest({
2395
+ workspace,
2396
+ region,
2397
+ database,
2398
+ migrationRequest,
2399
+ update
2400
+ }) {
2401
+ return operationsByTag.migrationRequests.updateMigrationRequest({
2402
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2403
+ body: update,
2404
+ ...this.extraProps
2405
+ });
2406
+ }
2407
+ listMigrationRequestsCommits({
2408
+ workspace,
2409
+ region,
2410
+ database,
2411
+ migrationRequest,
2412
+ page
2413
+ }) {
2414
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
2415
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2416
+ body: { page },
2417
+ ...this.extraProps
2418
+ });
2419
+ }
2420
+ compareMigrationRequest({
2421
+ workspace,
2422
+ region,
2423
+ database,
2424
+ migrationRequest
2425
+ }) {
2426
+ return operationsByTag.migrationRequests.compareMigrationRequest({
2427
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2428
+ ...this.extraProps
2429
+ });
2430
+ }
2431
+ getMigrationRequestIsMerged({
2432
+ workspace,
2433
+ region,
2434
+ database,
2435
+ migrationRequest
2436
+ }) {
2437
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
2438
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2439
+ ...this.extraProps
2440
+ });
2441
+ }
2442
+ mergeMigrationRequest({
2443
+ workspace,
2444
+ region,
2445
+ database,
2446
+ migrationRequest
2447
+ }) {
2448
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
2449
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2450
+ ...this.extraProps
2451
+ });
2452
+ }
2453
+ }
2454
+ class MigrationsApi {
2455
+ constructor(extraProps) {
2456
+ this.extraProps = extraProps;
2457
+ }
2458
+ getBranchMigrationHistory({
2459
+ workspace,
2460
+ region,
2461
+ database,
2462
+ branch,
2463
+ limit,
2464
+ startFrom
2465
+ }) {
2466
+ return operationsByTag.migrations.getBranchMigrationHistory({
2467
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2468
+ body: { limit, startFrom },
2469
+ ...this.extraProps
2470
+ });
2471
+ }
2472
+ getBranchMigrationPlan({
2473
+ workspace,
2474
+ region,
2475
+ database,
2476
+ branch,
2477
+ schema
2478
+ }) {
2479
+ return operationsByTag.migrations.getBranchMigrationPlan({
2480
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2481
+ body: schema,
2482
+ ...this.extraProps
2483
+ });
2484
+ }
2485
+ executeBranchMigrationPlan({
2486
+ workspace,
2487
+ region,
2488
+ database,
2489
+ branch,
2490
+ plan
2491
+ }) {
2492
+ return operationsByTag.migrations.executeBranchMigrationPlan({
2493
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2494
+ body: plan,
2495
+ ...this.extraProps
2496
+ });
2497
+ }
2498
+ getBranchSchemaHistory({
2499
+ workspace,
2500
+ region,
2501
+ database,
2502
+ branch,
2503
+ page
2504
+ }) {
2505
+ return operationsByTag.migrations.getBranchSchemaHistory({
2506
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2507
+ body: { page },
2508
+ ...this.extraProps
2509
+ });
2510
+ }
2511
+ compareBranchWithUserSchema({
2512
+ workspace,
2513
+ region,
2514
+ database,
2515
+ branch,
2516
+ schema,
2517
+ schemaOperations,
2518
+ branchOperations
2519
+ }) {
2520
+ return operationsByTag.migrations.compareBranchWithUserSchema({
2521
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2522
+ body: { schema, schemaOperations, branchOperations },
2523
+ ...this.extraProps
2524
+ });
2525
+ }
2526
+ compareBranchSchemas({
2527
+ workspace,
2528
+ region,
2529
+ database,
2530
+ branch,
2531
+ compare,
2532
+ sourceBranchOperations,
2533
+ targetBranchOperations
2534
+ }) {
2535
+ return operationsByTag.migrations.compareBranchSchemas({
2536
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
2537
+ body: { sourceBranchOperations, targetBranchOperations },
2538
+ ...this.extraProps
2539
+ });
2540
+ }
2541
+ updateBranchSchema({
2542
+ workspace,
2543
+ region,
2544
+ database,
2545
+ branch,
2546
+ migration
2547
+ }) {
2548
+ return operationsByTag.migrations.updateBranchSchema({
2549
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2550
+ body: migration,
2551
+ ...this.extraProps
2552
+ });
2553
+ }
2554
+ previewBranchSchemaEdit({
2555
+ workspace,
2556
+ region,
2557
+ database,
2558
+ branch,
2559
+ data
2560
+ }) {
2561
+ return operationsByTag.migrations.previewBranchSchemaEdit({
2562
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2563
+ body: data,
2564
+ ...this.extraProps
2565
+ });
2566
+ }
2567
+ applyBranchSchemaEdit({
2568
+ workspace,
2569
+ region,
2570
+ database,
2571
+ branch,
2572
+ edits
2573
+ }) {
2574
+ return operationsByTag.migrations.applyBranchSchemaEdit({
2575
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2576
+ body: { edits },
2577
+ ...this.extraProps
2578
+ });
2579
+ }
2580
+ pushBranchMigrations({
2581
+ workspace,
2582
+ region,
2583
+ database,
2584
+ branch,
2585
+ migrations
2586
+ }) {
2587
+ return operationsByTag.migrations.pushBranchMigrations({
2588
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2589
+ body: { migrations },
2590
+ ...this.extraProps
2591
+ });
2592
+ }
2593
+ getSchema({
2594
+ workspace,
2595
+ region,
2596
+ database,
2597
+ branch
2598
+ }) {
2599
+ return operationsByTag.migrations.getSchema({
2600
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2601
+ ...this.extraProps
2602
+ });
2603
+ }
2604
+ }
2605
+ class DatabaseApi {
2606
+ constructor(extraProps) {
2607
+ this.extraProps = extraProps;
2608
+ }
2609
+ getDatabaseList({ workspace }) {
2610
+ return operationsByTag.databases.getDatabaseList({
2611
+ pathParams: { workspaceId: workspace },
2612
+ ...this.extraProps
2613
+ });
2614
+ }
2615
+ createDatabase({
2616
+ workspace,
2617
+ database,
2618
+ data,
2619
+ headers
2620
+ }) {
2621
+ return operationsByTag.databases.createDatabase({
2622
+ pathParams: { workspaceId: workspace, dbName: database },
2623
+ body: data,
2624
+ headers,
2625
+ ...this.extraProps
2626
+ });
2627
+ }
2628
+ deleteDatabase({
2629
+ workspace,
2630
+ database
2631
+ }) {
2632
+ return operationsByTag.databases.deleteDatabase({
2633
+ pathParams: { workspaceId: workspace, dbName: database },
2634
+ ...this.extraProps
2635
+ });
2636
+ }
2637
+ getDatabaseMetadata({
2638
+ workspace,
2639
+ database
2640
+ }) {
2641
+ return operationsByTag.databases.getDatabaseMetadata({
2642
+ pathParams: { workspaceId: workspace, dbName: database },
2643
+ ...this.extraProps
2644
+ });
2645
+ }
2646
+ updateDatabaseMetadata({
2647
+ workspace,
2648
+ database,
2649
+ metadata
2650
+ }) {
2651
+ return operationsByTag.databases.updateDatabaseMetadata({
2652
+ pathParams: { workspaceId: workspace, dbName: database },
2653
+ body: metadata,
2654
+ ...this.extraProps
2655
+ });
2656
+ }
2657
+ renameDatabase({
2658
+ workspace,
2659
+ database,
2660
+ newName
2661
+ }) {
2662
+ return operationsByTag.databases.renameDatabase({
2663
+ pathParams: { workspaceId: workspace, dbName: database },
2664
+ body: { newName },
2665
+ ...this.extraProps
2666
+ });
2667
+ }
2668
+ getDatabaseGithubSettings({
2669
+ workspace,
2670
+ database
2671
+ }) {
2672
+ return operationsByTag.databases.getDatabaseGithubSettings({
2673
+ pathParams: { workspaceId: workspace, dbName: database },
2674
+ ...this.extraProps
2675
+ });
2676
+ }
2677
+ updateDatabaseGithubSettings({
2678
+ workspace,
2679
+ database,
2680
+ settings
2681
+ }) {
2682
+ return operationsByTag.databases.updateDatabaseGithubSettings({
2683
+ pathParams: { workspaceId: workspace, dbName: database },
2684
+ body: settings,
2685
+ ...this.extraProps
2686
+ });
2687
+ }
2688
+ deleteDatabaseGithubSettings({
2689
+ workspace,
2690
+ database
2691
+ }) {
2692
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
2693
+ pathParams: { workspaceId: workspace, dbName: database },
2694
+ ...this.extraProps
2695
+ });
2696
+ }
2697
+ listRegions({ workspace }) {
2698
+ return operationsByTag.databases.listRegions({
2699
+ pathParams: { workspaceId: workspace },
2700
+ ...this.extraProps
2701
+ });
2702
+ }
2703
+ }
2704
+
2705
+ class XataApiPlugin {
2706
+ build(options) {
2707
+ return new XataApiClient(options);
2708
+ }
2709
+ }
2710
+
2711
+ class XataPlugin {
2712
+ }
2713
+
2714
+ function buildTransformString(transformations) {
2715
+ return transformations.flatMap(
2716
+ (t) => Object.entries(t).map(([key, value]) => {
2717
+ if (key === "trim") {
2718
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2719
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2720
+ }
2721
+ if (key === "gravity" && typeof value === "object") {
2722
+ const { x = 0.5, y = 0.5 } = value;
2723
+ return `${key}=${[x, y].join("x")}`;
2724
+ }
2725
+ return `${key}=${value}`;
2726
+ })
2727
+ ).join(",");
2728
+ }
2729
+ function transformImage(url, ...transformations) {
2730
+ if (!isDefined(url))
2731
+ return void 0;
2732
+ const newTransformations = buildTransformString(transformations);
2733
+ const { hostname, pathname, search } = new URL(url);
2734
+ const pathParts = pathname.split("/");
2735
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2736
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2737
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2738
+ const path = pathParts.join("/");
2739
+ return `https://${hostname}${transform}${path}${search}`;
2740
+ }
2741
+
2742
+ class XataFile {
2743
+ constructor(file) {
2744
+ this.id = file.id;
2745
+ this.name = file.name;
2746
+ this.mediaType = file.mediaType;
2747
+ this.base64Content = file.base64Content;
2748
+ this.enablePublicUrl = file.enablePublicUrl;
2749
+ this.signedUrlTimeout = file.signedUrlTimeout;
2750
+ this.uploadUrlTimeout = file.uploadUrlTimeout;
2751
+ this.size = file.size;
2752
+ this.version = file.version;
2753
+ this.url = file.url;
2754
+ this.signedUrl = file.signedUrl;
2755
+ this.uploadUrl = file.uploadUrl;
2756
+ this.attributes = file.attributes;
2757
+ }
2758
+ static fromBuffer(buffer, options = {}) {
2759
+ const base64Content = buffer.toString("base64");
2760
+ return new XataFile({ ...options, base64Content });
2761
+ }
2762
+ toBuffer() {
2763
+ if (!this.base64Content) {
2764
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2765
+ }
2766
+ return Buffer.from(this.base64Content, "base64");
2767
+ }
2768
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2769
+ const uint8Array = new Uint8Array(arrayBuffer);
2770
+ return this.fromUint8Array(uint8Array, options);
2771
+ }
2772
+ toArrayBuffer() {
2773
+ if (!this.base64Content) {
2774
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2775
+ }
2776
+ const binary = atob(this.base64Content);
2777
+ return new ArrayBuffer(binary.length);
2778
+ }
2779
+ static fromUint8Array(uint8Array, options = {}) {
2780
+ let binary = "";
2781
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2782
+ binary += String.fromCharCode(uint8Array[i]);
2783
+ }
2784
+ const base64Content = btoa(binary);
2785
+ return new XataFile({ ...options, base64Content });
2786
+ }
2787
+ toUint8Array() {
2788
+ if (!this.base64Content) {
2789
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2790
+ }
2791
+ const binary = atob(this.base64Content);
2792
+ const uint8Array = new Uint8Array(binary.length);
2793
+ for (let i = 0; i < binary.length; i++) {
2794
+ uint8Array[i] = binary.charCodeAt(i);
2795
+ }
2796
+ return uint8Array;
2797
+ }
2798
+ static async fromBlob(file, options = {}) {
2799
+ const name = options.name ?? file.name;
2800
+ const mediaType = file.type;
2801
+ const arrayBuffer = await file.arrayBuffer();
2802
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2803
+ }
2804
+ toBlob() {
2805
+ if (!this.base64Content) {
2806
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2807
+ }
2808
+ const binary = atob(this.base64Content);
2809
+ const uint8Array = new Uint8Array(binary.length);
2810
+ for (let i = 0; i < binary.length; i++) {
2811
+ uint8Array[i] = binary.charCodeAt(i);
2812
+ }
2813
+ return new Blob([uint8Array], { type: this.mediaType });
2814
+ }
2815
+ static fromString(string, options = {}) {
2816
+ const base64Content = btoa(string);
2817
+ return new XataFile({ ...options, base64Content });
2818
+ }
2819
+ toString() {
2820
+ if (!this.base64Content) {
2821
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2822
+ }
2823
+ return atob(this.base64Content);
2824
+ }
2825
+ static fromBase64(base64Content, options = {}) {
2826
+ return new XataFile({ ...options, base64Content });
2827
+ }
2828
+ toBase64() {
2829
+ if (!this.base64Content) {
2830
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2831
+ }
2832
+ return this.base64Content;
2833
+ }
2834
+ transform(...options) {
2835
+ return {
2836
+ url: transformImage(this.url, ...options),
2837
+ signedUrl: transformImage(this.signedUrl, ...options),
2838
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2839
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2840
+ };
2841
+ }
2842
+ }
2843
+ const parseInputFileEntry = async (entry) => {
2844
+ if (!isDefined(entry))
2845
+ return null;
2846
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout, uploadUrlTimeout } = await entry;
2847
+ return compactObject({
2848
+ id,
2849
+ // Name cannot be an empty string in our API
2850
+ name: name ? name : void 0,
2851
+ mediaType,
2852
+ base64Content,
2853
+ enablePublicUrl,
2854
+ signedUrlTimeout,
2855
+ uploadUrlTimeout
2856
+ });
2857
+ };
2858
+
2859
+ function cleanFilter(filter) {
2860
+ if (!isDefined(filter))
2861
+ return void 0;
2862
+ if (!isObject(filter))
2863
+ return filter;
2864
+ const values = Object.fromEntries(
2865
+ Object.entries(filter).reduce((acc, [key, value]) => {
2866
+ if (!isDefined(value))
2867
+ return acc;
2868
+ if (Array.isArray(value)) {
2869
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2870
+ if (clean.length === 0)
2871
+ return acc;
2872
+ return [...acc, [key, clean]];
2873
+ }
2874
+ if (isObject(value)) {
2875
+ const clean = cleanFilter(value);
2876
+ if (!isDefined(clean))
2877
+ return acc;
2878
+ return [...acc, [key, clean]];
2879
+ }
2880
+ return [...acc, [key, value]];
2881
+ }, [])
2882
+ );
2883
+ return Object.keys(values).length > 0 ? values : void 0;
2884
+ }
2885
+
2886
+ function stringifyJson(value) {
2887
+ if (!isDefined(value))
2888
+ return value;
2889
+ if (isString(value))
2890
+ return value;
2891
+ try {
2892
+ return JSON.stringify(value);
2893
+ } catch (e) {
2894
+ return value;
2895
+ }
2896
+ }
2897
+ function parseJson(value) {
2898
+ try {
2899
+ return JSON.parse(value);
2900
+ } catch (e) {
2901
+ return value;
2902
+ }
2903
+ }
2904
+
2905
+ var __accessCheck$6 = (obj, member, msg) => {
2906
+ if (!member.has(obj))
2907
+ throw TypeError("Cannot " + msg);
2908
+ };
2909
+ var __privateGet$5 = (obj, member, getter) => {
2910
+ __accessCheck$6(obj, member, "read from private field");
2911
+ return getter ? getter.call(obj) : member.get(obj);
2912
+ };
2913
+ var __privateAdd$6 = (obj, member, value) => {
2914
+ if (member.has(obj))
2915
+ throw TypeError("Cannot add the same private member more than once");
2916
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2917
+ };
2918
+ var __privateSet$4 = (obj, member, value, setter) => {
2919
+ __accessCheck$6(obj, member, "write to private field");
2920
+ setter ? setter.call(obj, value) : member.set(obj, value);
2921
+ return value;
2922
+ };
2923
+ var _query, _page;
2924
+ class Page {
2925
+ constructor(query, meta, records = []) {
2926
+ __privateAdd$6(this, _query, void 0);
2927
+ __privateSet$4(this, _query, query);
2928
+ this.meta = meta;
2929
+ this.records = new PageRecordArray(this, records);
2930
+ }
2931
+ /**
2932
+ * Retrieves the next page of results.
2933
+ * @param size Maximum number of results to be retrieved.
2934
+ * @param offset Number of results to skip when retrieving the results.
2935
+ * @returns The next page or results.
2936
+ */
2937
+ async nextPage(size, offset) {
2938
+ return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
2939
+ }
2940
+ /**
2941
+ * Retrieves the previous page of results.
2942
+ * @param size Maximum number of results to be retrieved.
2943
+ * @param offset Number of results to skip when retrieving the results.
2944
+ * @returns The previous page or results.
2945
+ */
2946
+ async previousPage(size, offset) {
2947
+ return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
2948
+ }
2949
+ /**
2950
+ * Retrieves the start page of results.
2951
+ * @param size Maximum number of results to be retrieved.
2952
+ * @param offset Number of results to skip when retrieving the results.
2953
+ * @returns The start page or results.
2954
+ */
2955
+ async startPage(size, offset) {
2956
+ return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
2957
+ }
2958
+ /**
2959
+ * Retrieves the end page of results.
2960
+ * @param size Maximum number of results to be retrieved.
2961
+ * @param offset Number of results to skip when retrieving the results.
2962
+ * @returns The end page or results.
2963
+ */
2964
+ async endPage(size, offset) {
2965
+ return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
2966
+ }
2967
+ /**
2968
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
2969
+ * @returns Whether or not there will be additional results in the next page of results.
2970
+ */
2971
+ hasNextPage() {
2972
+ return this.meta.page.more;
2973
+ }
2974
+ }
2975
+ _query = new WeakMap();
2976
+ const PAGINATION_MAX_SIZE = 1e3;
2977
+ const PAGINATION_DEFAULT_SIZE = 20;
2978
+ const PAGINATION_MAX_OFFSET = 49e3;
2979
+ const PAGINATION_DEFAULT_OFFSET = 0;
2980
+ function isCursorPaginationOptions(options) {
2981
+ return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
2982
+ }
2983
+ class RecordArray extends Array {
2984
+ constructor(...args) {
2985
+ super(...RecordArray.parseConstructorParams(...args));
2986
+ }
2987
+ static parseConstructorParams(...args) {
2988
+ if (args.length === 1 && typeof args[0] === "number") {
2989
+ return new Array(args[0]);
2990
+ }
2991
+ if (args.length <= 1 && Array.isArray(args[0] ?? [])) {
2992
+ const result = args[0] ?? [];
2993
+ return new Array(...result);
2994
+ }
2995
+ return new Array(...args);
2996
+ }
2997
+ toArray() {
2998
+ return new Array(...this);
2999
+ }
3000
+ toSerializable() {
3001
+ return JSON.parse(this.toString());
3002
+ }
3003
+ toString() {
3004
+ return JSON.stringify(this.toArray());
3005
+ }
3006
+ map(callbackfn, thisArg) {
3007
+ return this.toArray().map(callbackfn, thisArg);
3008
+ }
3009
+ }
3010
+ const _PageRecordArray = class _PageRecordArray extends Array {
3011
+ constructor(...args) {
3012
+ super(..._PageRecordArray.parseConstructorParams(...args));
3013
+ __privateAdd$6(this, _page, void 0);
3014
+ __privateSet$4(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
3015
+ }
3016
+ static parseConstructorParams(...args) {
3017
+ if (args.length === 1 && typeof args[0] === "number") {
3018
+ return new Array(args[0]);
3019
+ }
3020
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
3021
+ const result = args[1] ?? args[0].records ?? [];
3022
+ return new Array(...result);
3023
+ }
3024
+ return new Array(...args);
3025
+ }
3026
+ toArray() {
3027
+ return new Array(...this);
3028
+ }
3029
+ toSerializable() {
3030
+ return JSON.parse(this.toString());
3031
+ }
3032
+ toString() {
3033
+ return JSON.stringify(this.toArray());
3034
+ }
3035
+ map(callbackfn, thisArg) {
3036
+ return this.toArray().map(callbackfn, thisArg);
3037
+ }
3038
+ /**
3039
+ * Retrieve next page of records
3040
+ *
3041
+ * @returns A new array of objects
3042
+ */
3043
+ async nextPage(size, offset) {
3044
+ const newPage = await __privateGet$5(this, _page).nextPage(size, offset);
3045
+ return new _PageRecordArray(newPage);
3046
+ }
3047
+ /**
3048
+ * Retrieve previous page of records
3049
+ *
3050
+ * @returns A new array of objects
3051
+ */
3052
+ async previousPage(size, offset) {
3053
+ const newPage = await __privateGet$5(this, _page).previousPage(size, offset);
3054
+ return new _PageRecordArray(newPage);
3055
+ }
3056
+ /**
3057
+ * Retrieve start page of records
3058
+ *
3059
+ * @returns A new array of objects
3060
+ */
3061
+ async startPage(size, offset) {
3062
+ const newPage = await __privateGet$5(this, _page).startPage(size, offset);
3063
+ return new _PageRecordArray(newPage);
3064
+ }
3065
+ /**
3066
+ * Retrieve end page of records
3067
+ *
3068
+ * @returns A new array of objects
3069
+ */
3070
+ async endPage(size, offset) {
3071
+ const newPage = await __privateGet$5(this, _page).endPage(size, offset);
3072
+ return new _PageRecordArray(newPage);
3073
+ }
3074
+ /**
3075
+ * @returns Boolean indicating if there is a next page
3076
+ */
3077
+ hasNextPage() {
3078
+ return __privateGet$5(this, _page).meta.page.more;
3079
+ }
3080
+ };
3081
+ _page = new WeakMap();
3082
+ let PageRecordArray = _PageRecordArray;
3083
+
3084
+ var __accessCheck$5 = (obj, member, msg) => {
3085
+ if (!member.has(obj))
3086
+ throw TypeError("Cannot " + msg);
3087
+ };
3088
+ var __privateGet$4 = (obj, member, getter) => {
3089
+ __accessCheck$5(obj, member, "read from private field");
3090
+ return getter ? getter.call(obj) : member.get(obj);
3091
+ };
3092
+ var __privateAdd$5 = (obj, member, value) => {
3093
+ if (member.has(obj))
3094
+ throw TypeError("Cannot add the same private member more than once");
3095
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3096
+ };
3097
+ var __privateSet$3 = (obj, member, value, setter) => {
3098
+ __accessCheck$5(obj, member, "write to private field");
3099
+ setter ? setter.call(obj, value) : member.set(obj, value);
3100
+ return value;
3101
+ };
3102
+ var __privateMethod$3 = (obj, member, method) => {
3103
+ __accessCheck$5(obj, member, "access private method");
3104
+ return method;
3105
+ };
3106
+ var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
3107
+ const _Query = class _Query {
3108
+ constructor(repository, table, data, rawParent) {
3109
+ __privateAdd$5(this, _cleanFilterConstraint);
3110
+ __privateAdd$5(this, _table$1, void 0);
3111
+ __privateAdd$5(this, _repository, void 0);
3112
+ __privateAdd$5(this, _data, { filter: {} });
3113
+ // Implements pagination
3114
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
3115
+ this.records = new PageRecordArray(this, []);
3116
+ __privateSet$3(this, _table$1, table);
3117
+ if (repository) {
3118
+ __privateSet$3(this, _repository, repository);
3119
+ } else {
3120
+ __privateSet$3(this, _repository, this);
3121
+ }
3122
+ const parent = cleanParent(data, rawParent);
3123
+ __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
3124
+ __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
3125
+ __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
3126
+ __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
3127
+ __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
3128
+ __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
3129
+ __privateGet$4(this, _data).columns = data.columns ?? parent?.columns;
3130
+ __privateGet$4(this, _data).consistency = data.consistency ?? parent?.consistency;
3131
+ __privateGet$4(this, _data).pagination = data.pagination ?? parent?.pagination;
3132
+ __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
3133
+ __privateGet$4(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
3134
+ this.any = this.any.bind(this);
3135
+ this.all = this.all.bind(this);
3136
+ this.not = this.not.bind(this);
3137
+ this.filter = this.filter.bind(this);
3138
+ this.sort = this.sort.bind(this);
3139
+ this.none = this.none.bind(this);
3140
+ Object.defineProperty(this, "table", { enumerable: false });
3141
+ Object.defineProperty(this, "repository", { enumerable: false });
3142
+ }
3143
+ getQueryOptions() {
3144
+ return __privateGet$4(this, _data);
3145
+ }
3146
+ key() {
3147
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$4(this, _data);
3148
+ const key = JSON.stringify({ columns, filter, sort, pagination });
3149
+ return toBase64(key);
3150
+ }
3151
+ /**
3152
+ * Builds a new query object representing a logical OR between the given subqueries.
3153
+ * @param queries An array of subqueries.
3154
+ * @returns A new Query object.
3155
+ */
3156
+ any(...queries) {
3157
+ const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
3158
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
3159
+ }
3160
+ /**
3161
+ * Builds a new query object representing a logical AND between the given subqueries.
3162
+ * @param queries An array of subqueries.
3163
+ * @returns A new Query object.
3164
+ */
3165
+ all(...queries) {
3166
+ const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
3167
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
3168
+ }
3169
+ /**
3170
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3171
+ * @param queries An array of subqueries.
3172
+ * @returns A new Query object.
3173
+ */
3174
+ not(...queries) {
3175
+ const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
3176
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
3177
+ }
3178
+ /**
3179
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3180
+ * @param queries An array of subqueries.
3181
+ * @returns A new Query object.
3182
+ */
3183
+ none(...queries) {
3184
+ const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
3185
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
3186
+ }
3187
+ filter(a, b) {
3188
+ if (arguments.length === 1) {
3189
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
3190
+ [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
3191
+ }));
3192
+ const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
3193
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
3194
+ } else {
3195
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
3196
+ const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
3197
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
3198
+ }
3199
+ }
3200
+ sort(column, direction = "asc") {
3201
+ const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
3202
+ const sort = [...originalSort, { column, direction }];
3203
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
3204
+ }
3205
+ /**
3206
+ * Builds a new query specifying the set of columns to be returned in the query response.
3207
+ * @param columns Array of column names to be returned by the query.
3208
+ * @returns A new Query object.
3209
+ */
3210
+ select(columns) {
3211
+ return new _Query(
3212
+ __privateGet$4(this, _repository),
3213
+ __privateGet$4(this, _table$1),
3214
+ { columns },
3215
+ __privateGet$4(this, _data)
3216
+ );
3217
+ }
3218
+ getPaginated(options = {}) {
3219
+ const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
3220
+ return __privateGet$4(this, _repository).query(query);
3221
+ }
3222
+ /**
3223
+ * Get results in an iterator
3224
+ *
3225
+ * @async
3226
+ * @returns Async interable of results
3227
+ */
3228
+ async *[Symbol.asyncIterator]() {
3229
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
3230
+ yield record;
3231
+ }
3232
+ }
3233
+ async *getIterator(options = {}) {
3234
+ const { batchSize = 1 } = options;
3235
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
3236
+ let more = page.hasNextPage();
3237
+ yield page.records;
3238
+ while (more) {
3239
+ page = await page.nextPage();
3240
+ more = page.hasNextPage();
3241
+ yield page.records;
3242
+ }
3243
+ }
3244
+ async getMany(options = {}) {
3245
+ const { pagination = {}, ...rest } = options;
3246
+ const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
3247
+ const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
3248
+ let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
3249
+ const results = [...page.records];
3250
+ while (page.hasNextPage() && results.length < size) {
3251
+ page = await page.nextPage();
3252
+ results.push(...page.records);
3253
+ }
3254
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
3255
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
3256
+ }
3257
+ const array = new PageRecordArray(page, results.slice(0, size));
3258
+ return array;
3259
+ }
3260
+ async getAll(options = {}) {
3261
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
3262
+ const results = [];
3263
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
3264
+ results.push(...page);
3265
+ }
3266
+ return new RecordArray(results);
3267
+ }
3268
+ async getFirst(options = {}) {
3269
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
3270
+ return records[0] ?? null;
3271
+ }
3272
+ async getFirstOrThrow(options = {}) {
3273
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
3274
+ if (records[0] === void 0)
3275
+ throw new Error("No results found.");
3276
+ return records[0];
3277
+ }
3278
+ async summarize(params = {}) {
3279
+ const { summaries, summariesFilter, ...options } = params;
3280
+ const query = new _Query(
3281
+ __privateGet$4(this, _repository),
3282
+ __privateGet$4(this, _table$1),
3283
+ options,
3284
+ __privateGet$4(this, _data)
3285
+ );
3286
+ return __privateGet$4(this, _repository).summarizeTable(query, summaries, summariesFilter);
3287
+ }
3288
+ /**
3289
+ * Builds a new query object adding a cache TTL in milliseconds.
3290
+ * @param ttl The cache TTL in milliseconds.
3291
+ * @returns A new Query object.
3292
+ */
3293
+ cache(ttl) {
3294
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
3295
+ }
3296
+ /**
3297
+ * Retrieve next page of records
3298
+ *
3299
+ * @returns A new page object.
3300
+ */
3301
+ nextPage(size, offset) {
3302
+ return this.startPage(size, offset);
3303
+ }
3304
+ /**
3305
+ * Retrieve previous page of records
3306
+ *
3307
+ * @returns A new page object
3308
+ */
3309
+ previousPage(size, offset) {
3310
+ return this.startPage(size, offset);
3311
+ }
3312
+ /**
3313
+ * Retrieve start page of records
3314
+ *
3315
+ * @returns A new page object
3316
+ */
3317
+ startPage(size, offset) {
3318
+ return this.getPaginated({ pagination: { size, offset } });
3319
+ }
3320
+ /**
3321
+ * Retrieve last page of records
3322
+ *
3323
+ * @returns A new page object
3324
+ */
3325
+ endPage(size, offset) {
3326
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
3327
+ }
3328
+ /**
3329
+ * @returns Boolean indicating if there is a next page
3330
+ */
3331
+ hasNextPage() {
3332
+ return this.meta.page.more;
3333
+ }
3334
+ };
3335
+ _table$1 = new WeakMap();
3336
+ _repository = new WeakMap();
3337
+ _data = new WeakMap();
3338
+ _cleanFilterConstraint = new WeakSet();
3339
+ cleanFilterConstraint_fn = function(column, value) {
3340
+ const columnType = __privateGet$4(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
3341
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
3342
+ return { $includes: value };
3343
+ }
3344
+ if (columnType === "link" && isObject(value) && isString(value.id)) {
3345
+ return value.id;
3346
+ }
3347
+ return value;
3348
+ };
3349
+ let Query = _Query;
3350
+ function cleanParent(data, parent) {
3351
+ if (isCursorPaginationOptions(data.pagination)) {
3352
+ return { ...parent, sort: void 0, filter: void 0 };
3353
+ }
3354
+ return parent;
3355
+ }
3356
+
3357
+ const RecordColumnTypes = [
3358
+ "bool",
3359
+ "int",
3360
+ "float",
3361
+ "string",
3362
+ "text",
3363
+ "email",
3364
+ "multiple",
3365
+ "link",
3366
+ "datetime",
3367
+ "vector",
3368
+ "file[]",
3369
+ "file",
3370
+ "json"
3371
+ ];
3372
+ function isIdentifiable(x) {
3373
+ return isObject(x) && isString(x?.id);
3374
+ }
3375
+ function isXataRecord(x) {
3376
+ const record = x;
3377
+ const metadata = record?.getMetadata();
3378
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
3379
+ }
3380
+
3381
+ function isValidExpandedColumn(column) {
3382
+ return isObject(column) && isString(column.name);
3383
+ }
3384
+ function isValidSelectableColumns(columns) {
3385
+ if (!Array.isArray(columns)) {
3386
+ return false;
3387
+ }
3388
+ return columns.every((column) => {
3389
+ if (typeof column === "string") {
3390
+ return true;
3391
+ }
3392
+ if (typeof column === "object") {
3393
+ return isValidExpandedColumn(column);
3394
+ }
3395
+ return false;
3396
+ });
3397
+ }
3398
+
3399
+ function isSortFilterString(value) {
3400
+ return isString(value);
3401
+ }
3402
+ function isSortFilterBase(filter) {
3403
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
3404
+ if (key === "*")
3405
+ return value === "random";
3406
+ return value === "asc" || value === "desc";
3407
+ });
3408
+ }
3409
+ function isSortFilterObject(filter) {
3410
+ return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
3411
+ }
3412
+ function buildSortFilter(filter) {
3413
+ if (isSortFilterString(filter)) {
3414
+ return { [filter]: "asc" };
3415
+ } else if (Array.isArray(filter)) {
3416
+ return filter.map((item) => buildSortFilter(item));
3417
+ } else if (isSortFilterBase(filter)) {
3418
+ return filter;
3419
+ } else if (isSortFilterObject(filter)) {
3420
+ return { [filter.column]: filter.direction ?? "asc" };
3421
+ } else {
3422
+ throw new Error(`Invalid sort filter: ${filter}`);
3423
+ }
3424
+ }
3425
+
3426
+ var __accessCheck$4 = (obj, member, msg) => {
3427
+ if (!member.has(obj))
3428
+ throw TypeError("Cannot " + msg);
3429
+ };
3430
+ var __privateGet$3 = (obj, member, getter) => {
3431
+ __accessCheck$4(obj, member, "read from private field");
3432
+ return getter ? getter.call(obj) : member.get(obj);
3433
+ };
3434
+ var __privateAdd$4 = (obj, member, value) => {
3435
+ if (member.has(obj))
3436
+ throw TypeError("Cannot add the same private member more than once");
3437
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3438
+ };
3439
+ var __privateSet$2 = (obj, member, value, setter) => {
3440
+ __accessCheck$4(obj, member, "write to private field");
3441
+ setter ? setter.call(obj, value) : member.set(obj, value);
3442
+ return value;
3443
+ };
3444
+ var __privateMethod$2 = (obj, member, method) => {
3445
+ __accessCheck$4(obj, member, "access private method");
3446
+ return method;
3447
+ };
3448
+ var _table, _getFetchProps, _db, _cache, _schemaTables, _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, getSchemaTables_fn, _transformObjectToApi, transformObjectToApi_fn;
3449
+ const BULK_OPERATION_MAX_SIZE = 1e3;
3450
+ class Repository extends Query {
3451
+ }
3452
+ class RestRepository extends Query {
3453
+ constructor(options) {
3454
+ super(
3455
+ null,
3456
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
3457
+ {}
3458
+ );
3459
+ __privateAdd$4(this, _insertRecordWithoutId);
3460
+ __privateAdd$4(this, _insertRecordWithId);
3461
+ __privateAdd$4(this, _insertRecords);
3462
+ __privateAdd$4(this, _updateRecordWithID);
3463
+ __privateAdd$4(this, _updateRecords);
3464
+ __privateAdd$4(this, _upsertRecordWithID);
3465
+ __privateAdd$4(this, _deleteRecord);
3466
+ __privateAdd$4(this, _deleteRecords);
3467
+ __privateAdd$4(this, _setCacheQuery);
3468
+ __privateAdd$4(this, _getCacheQuery);
3469
+ __privateAdd$4(this, _getSchemaTables);
3470
+ __privateAdd$4(this, _transformObjectToApi);
3471
+ __privateAdd$4(this, _table, void 0);
3472
+ __privateAdd$4(this, _getFetchProps, void 0);
3473
+ __privateAdd$4(this, _db, void 0);
3474
+ __privateAdd$4(this, _cache, void 0);
3475
+ __privateAdd$4(this, _schemaTables, void 0);
3476
+ __privateAdd$4(this, _trace, void 0);
3477
+ __privateSet$2(this, _table, options.table);
3478
+ __privateSet$2(this, _db, options.db);
3479
+ __privateSet$2(this, _cache, options.pluginOptions.cache);
3480
+ __privateSet$2(this, _schemaTables, options.schemaTables);
3481
+ __privateSet$2(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
3482
+ const trace = options.pluginOptions.trace ?? defaultTrace;
3483
+ __privateSet$2(this, _trace, async (name, fn, options2 = {}) => {
3484
+ return trace(name, fn, {
3485
+ ...options2,
3486
+ [TraceAttributes.TABLE]: __privateGet$3(this, _table),
3487
+ [TraceAttributes.KIND]: "sdk-operation",
3488
+ [TraceAttributes.VERSION]: VERSION
3489
+ });
3490
+ });
3491
+ }
3492
+ async create(a, b, c, d) {
3493
+ return __privateGet$3(this, _trace).call(this, "create", async () => {
3494
+ const ifVersion = parseIfVersion(b, c, d);
3495
+ if (Array.isArray(a)) {
3496
+ if (a.length === 0)
3497
+ return [];
3498
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
3499
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3500
+ const result = await this.read(ids, columns);
3501
+ return result;
3502
+ }
3503
+ if (isString(a) && isObject(b)) {
3504
+ if (a === "")
3505
+ throw new Error("The id can't be empty");
3506
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3507
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
3508
+ }
3509
+ if (isObject(a) && isString(a.id)) {
3510
+ if (a.id === "")
3511
+ throw new Error("The id can't be empty");
3512
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3513
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
3514
+ }
3515
+ if (isObject(a)) {
3516
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3517
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
3518
+ }
3519
+ throw new Error("Invalid arguments for create method");
3520
+ });
3521
+ }
3522
+ async read(a, b) {
3523
+ return __privateGet$3(this, _trace).call(this, "read", async () => {
3524
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3525
+ if (Array.isArray(a)) {
3526
+ if (a.length === 0)
3527
+ return [];
3528
+ const ids = a.map((item) => extractId(item));
3529
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
3530
+ const dictionary = finalObjects.reduce((acc, object) => {
3531
+ acc[object.id] = object;
3532
+ return acc;
3533
+ }, {});
3534
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
3535
+ }
3536
+ const id = extractId(a);
3537
+ if (id) {
3538
+ try {
3539
+ const response = await getRecord({
3540
+ pathParams: {
3541
+ workspace: "{workspaceId}",
3542
+ dbBranchName: "{dbBranch}",
3543
+ region: "{region}",
3544
+ tableName: __privateGet$3(this, _table),
3545
+ recordId: id
3546
+ },
3547
+ queryParams: { columns },
3548
+ ...__privateGet$3(this, _getFetchProps).call(this)
3549
+ });
3550
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3551
+ return initObject(
3552
+ __privateGet$3(this, _db),
3553
+ schemaTables,
3554
+ __privateGet$3(this, _table),
3555
+ response,
3556
+ columns
3557
+ );
3558
+ } catch (e) {
3559
+ if (isObject(e) && e.status === 404) {
3560
+ return null;
3561
+ }
3562
+ throw e;
3563
+ }
3564
+ }
3565
+ return null;
3566
+ });
3567
+ }
3568
+ async readOrThrow(a, b) {
3569
+ return __privateGet$3(this, _trace).call(this, "readOrThrow", async () => {
3570
+ const result = await this.read(a, b);
3571
+ if (Array.isArray(result)) {
3572
+ const missingIds = compact(
3573
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
3574
+ );
3575
+ if (missingIds.length > 0) {
3576
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
3577
+ }
3578
+ return result;
3579
+ }
3580
+ if (result === null) {
3581
+ const id = extractId(a) ?? "unknown";
3582
+ throw new Error(`Record with id ${id} not found`);
3583
+ }
3584
+ return result;
3585
+ });
3586
+ }
3587
+ async update(a, b, c, d) {
3588
+ return __privateGet$3(this, _trace).call(this, "update", async () => {
3589
+ const ifVersion = parseIfVersion(b, c, d);
3590
+ if (Array.isArray(a)) {
3591
+ if (a.length === 0)
3592
+ return [];
3593
+ const existing = await this.read(a, ["id"]);
3594
+ const updates = a.filter((_item, index) => existing[index] !== null);
3595
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
3596
+ ifVersion,
3597
+ upsert: false
3598
+ });
3599
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3600
+ const result = await this.read(a, columns);
3601
+ return result;
3602
+ }
3603
+ try {
3604
+ if (isString(a) && isObject(b)) {
3605
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3606
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3607
+ }
3608
+ if (isObject(a) && isString(a.id)) {
3609
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3610
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3611
+ }
3612
+ } catch (error) {
3613
+ if (error.status === 422)
3614
+ return null;
3615
+ throw error;
3616
+ }
3617
+ throw new Error("Invalid arguments for update method");
3618
+ });
3619
+ }
3620
+ async updateOrThrow(a, b, c, d) {
3621
+ return __privateGet$3(this, _trace).call(this, "updateOrThrow", async () => {
3622
+ const result = await this.update(a, b, c, d);
3623
+ if (Array.isArray(result)) {
3624
+ const missingIds = compact(
3625
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
3626
+ );
3627
+ if (missingIds.length > 0) {
3628
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
3629
+ }
3630
+ return result;
3631
+ }
3632
+ if (result === null) {
3633
+ const id = extractId(a) ?? "unknown";
3634
+ throw new Error(`Record with id ${id} not found`);
3635
+ }
3636
+ return result;
3637
+ });
3638
+ }
3639
+ async createOrUpdate(a, b, c, d) {
3640
+ return __privateGet$3(this, _trace).call(this, "createOrUpdate", async () => {
3641
+ const ifVersion = parseIfVersion(b, c, d);
3642
+ if (Array.isArray(a)) {
3643
+ if (a.length === 0)
3644
+ return [];
3645
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
3646
+ ifVersion,
3647
+ upsert: true
3648
+ });
3649
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3650
+ const result = await this.read(a, columns);
3651
+ return result;
3652
+ }
3653
+ if (isString(a) && isObject(b)) {
3654
+ if (a === "")
3655
+ throw new Error("The id can't be empty");
3656
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3657
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3658
+ }
3659
+ if (isObject(a) && isString(a.id)) {
3660
+ if (a.id === "")
3661
+ throw new Error("The id can't be empty");
3662
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3663
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3664
+ }
3665
+ if (!isDefined(a) && isObject(b)) {
3666
+ return await this.create(b, c);
3667
+ }
3668
+ if (isObject(a) && !isDefined(a.id)) {
3669
+ return await this.create(a, b);
3670
+ }
3671
+ throw new Error("Invalid arguments for createOrUpdate method");
3672
+ });
3673
+ }
3674
+ async createOrReplace(a, b, c, d) {
3675
+ return __privateGet$3(this, _trace).call(this, "createOrReplace", async () => {
3676
+ const ifVersion = parseIfVersion(b, c, d);
3677
+ if (Array.isArray(a)) {
3678
+ if (a.length === 0)
3679
+ return [];
3680
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
3681
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3682
+ const result = await this.read(ids, columns);
3683
+ return result;
3684
+ }
3685
+ if (isString(a) && isObject(b)) {
3686
+ if (a === "")
3687
+ throw new Error("The id can't be empty");
3688
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3689
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3690
+ }
3691
+ if (isObject(a) && isString(a.id)) {
3692
+ if (a.id === "")
3693
+ throw new Error("The id can't be empty");
3694
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3695
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3696
+ }
3697
+ if (!isDefined(a) && isObject(b)) {
3698
+ return await this.create(b, c);
3699
+ }
3700
+ if (isObject(a) && !isDefined(a.id)) {
3701
+ return await this.create(a, b);
3702
+ }
3703
+ throw new Error("Invalid arguments for createOrReplace method");
3704
+ });
3705
+ }
3706
+ async delete(a, b) {
3707
+ return __privateGet$3(this, _trace).call(this, "delete", async () => {
3708
+ if (Array.isArray(a)) {
3709
+ if (a.length === 0)
3710
+ return [];
3711
+ const ids = a.map((o) => {
3712
+ if (isString(o))
3713
+ return o;
3714
+ if (isString(o.id))
3715
+ return o.id;
3716
+ throw new Error("Invalid arguments for delete method");
3717
+ });
3718
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3719
+ const result = await this.read(a, columns);
3720
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
3721
+ return result;
3722
+ }
3723
+ if (isString(a)) {
3724
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
3725
+ }
3726
+ if (isObject(a) && isString(a.id)) {
3727
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
3728
+ }
3729
+ throw new Error("Invalid arguments for delete method");
3730
+ });
3731
+ }
3732
+ async deleteOrThrow(a, b) {
3733
+ return __privateGet$3(this, _trace).call(this, "deleteOrThrow", async () => {
3734
+ const result = await this.delete(a, b);
3735
+ if (Array.isArray(result)) {
3736
+ const missingIds = compact(
3737
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
3738
+ );
3739
+ if (missingIds.length > 0) {
3740
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
3741
+ }
3742
+ return result;
3743
+ } else if (result === null) {
3744
+ const id = extractId(a) ?? "unknown";
3745
+ throw new Error(`Record with id ${id} not found`);
3746
+ }
3747
+ return result;
3748
+ });
3749
+ }
3750
+ async search(query, options = {}) {
3751
+ return __privateGet$3(this, _trace).call(this, "search", async () => {
3752
+ const { records, totalCount } = await searchTable({
3753
+ pathParams: {
3754
+ workspace: "{workspaceId}",
3755
+ dbBranchName: "{dbBranch}",
3756
+ region: "{region}",
3757
+ tableName: __privateGet$3(this, _table)
3758
+ },
3759
+ body: {
3760
+ query,
3761
+ fuzziness: options.fuzziness,
3762
+ prefix: options.prefix,
3763
+ highlight: options.highlight,
3764
+ filter: options.filter,
3765
+ boosters: options.boosters,
3766
+ page: options.page,
3767
+ target: options.target
3768
+ },
3769
+ ...__privateGet$3(this, _getFetchProps).call(this)
3770
+ });
3771
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3772
+ return {
3773
+ records: records.map((item) => initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), item, ["*"])),
3774
+ totalCount
3775
+ };
3776
+ });
3777
+ }
3778
+ async vectorSearch(column, query, options) {
3779
+ return __privateGet$3(this, _trace).call(this, "vectorSearch", async () => {
3780
+ const { records, totalCount } = await vectorSearchTable({
3781
+ pathParams: {
3782
+ workspace: "{workspaceId}",
3783
+ dbBranchName: "{dbBranch}",
3784
+ region: "{region}",
3785
+ tableName: __privateGet$3(this, _table)
3786
+ },
3787
+ body: {
3788
+ column,
3789
+ queryVector: query,
3790
+ similarityFunction: options?.similarityFunction,
3791
+ size: options?.size,
3792
+ filter: options?.filter
3793
+ },
3794
+ ...__privateGet$3(this, _getFetchProps).call(this)
3795
+ });
3796
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3797
+ return {
3798
+ records: records.map((item) => initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), item, ["*"])),
3799
+ totalCount
3800
+ };
3801
+ });
3802
+ }
3803
+ async aggregate(aggs, filter) {
3804
+ return __privateGet$3(this, _trace).call(this, "aggregate", async () => {
3805
+ const result = await aggregateTable({
3806
+ pathParams: {
3807
+ workspace: "{workspaceId}",
3808
+ dbBranchName: "{dbBranch}",
3809
+ region: "{region}",
3810
+ tableName: __privateGet$3(this, _table)
3811
+ },
3812
+ body: { aggs, filter },
3813
+ ...__privateGet$3(this, _getFetchProps).call(this)
3814
+ });
3815
+ return result;
3816
+ });
3817
+ }
3818
+ async query(query) {
3819
+ return __privateGet$3(this, _trace).call(this, "query", async () => {
3820
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
3821
+ if (cacheQuery)
3822
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
3823
+ const data = query.getQueryOptions();
3824
+ const { meta, records: objects } = await queryTable({
3825
+ pathParams: {
3826
+ workspace: "{workspaceId}",
3827
+ dbBranchName: "{dbBranch}",
3828
+ region: "{region}",
3829
+ tableName: __privateGet$3(this, _table)
3830
+ },
3831
+ body: {
3832
+ filter: cleanFilter(data.filter),
3833
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
3834
+ page: data.pagination,
3835
+ columns: data.columns ?? ["*"],
3836
+ consistency: data.consistency
3837
+ },
3838
+ fetchOptions: data.fetchOptions,
3839
+ ...__privateGet$3(this, _getFetchProps).call(this)
3840
+ });
3841
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3842
+ const records = objects.map(
3843
+ (record) => initObject(
3844
+ __privateGet$3(this, _db),
3845
+ schemaTables,
3846
+ __privateGet$3(this, _table),
3847
+ record,
3848
+ data.columns ?? ["*"]
3849
+ )
3850
+ );
3851
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
3852
+ return new Page(query, meta, records);
3853
+ });
3854
+ }
3855
+ async summarizeTable(query, summaries, summariesFilter) {
3856
+ return __privateGet$3(this, _trace).call(this, "summarize", async () => {
3857
+ const data = query.getQueryOptions();
3858
+ const result = await summarizeTable({
3859
+ pathParams: {
3860
+ workspace: "{workspaceId}",
3861
+ dbBranchName: "{dbBranch}",
3862
+ region: "{region}",
3863
+ tableName: __privateGet$3(this, _table)
3864
+ },
3865
+ body: {
3866
+ filter: cleanFilter(data.filter),
3867
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
3868
+ columns: data.columns,
3869
+ consistency: data.consistency,
3870
+ page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
3871
+ summaries,
3872
+ summariesFilter
3873
+ },
3874
+ ...__privateGet$3(this, _getFetchProps).call(this)
3875
+ });
3876
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3877
+ return {
3878
+ ...result,
3879
+ summaries: result.summaries.map(
3880
+ (summary) => initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), summary, data.columns ?? [])
3881
+ )
3882
+ };
3883
+ });
3884
+ }
3885
+ ask(question, options) {
3886
+ const questionParam = options?.sessionId ? { message: question } : { question };
3887
+ const params = {
3888
+ pathParams: {
3889
+ workspace: "{workspaceId}",
3890
+ dbBranchName: "{dbBranch}",
3891
+ region: "{region}",
3892
+ tableName: __privateGet$3(this, _table),
3893
+ sessionId: options?.sessionId
3894
+ },
3895
+ body: {
3896
+ ...questionParam,
3897
+ rules: options?.rules,
3898
+ searchType: options?.searchType,
3899
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3900
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3901
+ },
3902
+ ...__privateGet$3(this, _getFetchProps).call(this)
3903
+ };
3904
+ if (options?.onMessage) {
3905
+ fetchSSERequest({
3906
+ endpoint: "dataPlane",
3907
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3908
+ method: "POST",
3909
+ onMessage: (message) => {
3910
+ options.onMessage?.({ answer: message.text, records: message.records });
3911
+ },
3912
+ ...params
3913
+ });
3914
+ } else {
3915
+ return askTableSession(params);
3916
+ }
3917
+ }
3918
+ }
3919
+ _table = new WeakMap();
3920
+ _getFetchProps = new WeakMap();
3921
+ _db = new WeakMap();
3922
+ _cache = new WeakMap();
3923
+ _schemaTables = new WeakMap();
3924
+ _trace = new WeakMap();
3925
+ _insertRecordWithoutId = new WeakSet();
3926
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
3927
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3928
+ const response = await insertRecord({
3929
+ pathParams: {
3930
+ workspace: "{workspaceId}",
3931
+ dbBranchName: "{dbBranch}",
3932
+ region: "{region}",
3933
+ tableName: __privateGet$3(this, _table)
3934
+ },
3935
+ queryParams: { columns },
3936
+ body: record,
3937
+ ...__privateGet$3(this, _getFetchProps).call(this)
3938
+ });
3939
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3940
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
3941
+ };
3942
+ _insertRecordWithId = new WeakSet();
3943
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
3944
+ if (!recordId)
3945
+ return null;
3946
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3947
+ const response = await insertRecordWithID({
3948
+ pathParams: {
3949
+ workspace: "{workspaceId}",
3950
+ dbBranchName: "{dbBranch}",
3951
+ region: "{region}",
3952
+ tableName: __privateGet$3(this, _table),
3953
+ recordId
3954
+ },
3955
+ body: record,
3956
+ queryParams: { createOnly, columns, ifVersion },
3957
+ ...__privateGet$3(this, _getFetchProps).call(this)
3958
+ });
3959
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3960
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
3961
+ };
3962
+ _insertRecords = new WeakSet();
3963
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
3964
+ const operations = await promiseMap(objects, async (object) => {
3965
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3966
+ return { insert: { table: __privateGet$3(this, _table), record, createOnly, ifVersion } };
3967
+ });
3968
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
3969
+ const ids = [];
3970
+ for (const operations2 of chunkedOperations) {
3971
+ const { results } = await branchTransaction({
3972
+ pathParams: {
3973
+ workspace: "{workspaceId}",
3974
+ dbBranchName: "{dbBranch}",
3975
+ region: "{region}"
3976
+ },
3977
+ body: { operations: operations2 },
3978
+ ...__privateGet$3(this, _getFetchProps).call(this)
3979
+ });
3980
+ for (const result of results) {
3981
+ if (result.operation === "insert") {
3982
+ ids.push(result.id);
3983
+ } else {
3984
+ ids.push(null);
3985
+ }
3986
+ }
3987
+ }
3988
+ return ids;
3989
+ };
3990
+ _updateRecordWithID = new WeakSet();
3991
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
3992
+ if (!recordId)
3993
+ return null;
3994
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3995
+ try {
3996
+ const response = await updateRecordWithID({
3997
+ pathParams: {
3998
+ workspace: "{workspaceId}",
3999
+ dbBranchName: "{dbBranch}",
4000
+ region: "{region}",
4001
+ tableName: __privateGet$3(this, _table),
4002
+ recordId
4003
+ },
4004
+ queryParams: { columns, ifVersion },
4005
+ body: record,
4006
+ ...__privateGet$3(this, _getFetchProps).call(this)
4007
+ });
4008
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
4009
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
4010
+ } catch (e) {
4011
+ if (isObject(e) && e.status === 404) {
4012
+ return null;
4013
+ }
4014
+ throw e;
4015
+ }
4016
+ };
4017
+ _updateRecords = new WeakSet();
4018
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
4019
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
4020
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
4021
+ return { update: { table: __privateGet$3(this, _table), id, ifVersion, upsert, fields } };
4022
+ });
4023
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
4024
+ const ids = [];
4025
+ for (const operations2 of chunkedOperations) {
4026
+ const { results } = await branchTransaction({
4027
+ pathParams: {
4028
+ workspace: "{workspaceId}",
4029
+ dbBranchName: "{dbBranch}",
4030
+ region: "{region}"
4031
+ },
4032
+ body: { operations: operations2 },
4033
+ ...__privateGet$3(this, _getFetchProps).call(this)
4034
+ });
4035
+ for (const result of results) {
4036
+ if (result.operation === "update") {
4037
+ ids.push(result.id);
4038
+ } else {
4039
+ ids.push(null);
4040
+ }
4041
+ }
4042
+ }
4043
+ return ids;
4044
+ };
4045
+ _upsertRecordWithID = new WeakSet();
4046
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
4047
+ if (!recordId)
4048
+ return null;
4049
+ const response = await upsertRecordWithID({
4050
+ pathParams: {
4051
+ workspace: "{workspaceId}",
4052
+ dbBranchName: "{dbBranch}",
4053
+ region: "{region}",
4054
+ tableName: __privateGet$3(this, _table),
4055
+ recordId
4056
+ },
4057
+ queryParams: { columns, ifVersion },
4058
+ body: object,
4059
+ ...__privateGet$3(this, _getFetchProps).call(this)
4060
+ });
4061
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
4062
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
4063
+ };
4064
+ _deleteRecord = new WeakSet();
4065
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
4066
+ if (!recordId)
4067
+ return null;
4068
+ try {
4069
+ const response = await deleteRecord({
4070
+ pathParams: {
4071
+ workspace: "{workspaceId}",
4072
+ dbBranchName: "{dbBranch}",
4073
+ region: "{region}",
4074
+ tableName: __privateGet$3(this, _table),
4075
+ recordId
4076
+ },
4077
+ queryParams: { columns },
4078
+ ...__privateGet$3(this, _getFetchProps).call(this)
4079
+ });
4080
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
4081
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
4082
+ } catch (e) {
4083
+ if (isObject(e) && e.status === 404) {
4084
+ return null;
4085
+ }
4086
+ throw e;
4087
+ }
4088
+ };
4089
+ _deleteRecords = new WeakSet();
4090
+ deleteRecords_fn = async function(recordIds) {
4091
+ const chunkedOperations = chunk(
4092
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$3(this, _table), id } })),
4093
+ BULK_OPERATION_MAX_SIZE
4094
+ );
4095
+ for (const operations of chunkedOperations) {
4096
+ await branchTransaction({
4097
+ pathParams: {
4098
+ workspace: "{workspaceId}",
4099
+ dbBranchName: "{dbBranch}",
4100
+ region: "{region}"
4101
+ },
4102
+ body: { operations },
4103
+ ...__privateGet$3(this, _getFetchProps).call(this)
4104
+ });
4105
+ }
4106
+ };
4107
+ _setCacheQuery = new WeakSet();
4108
+ setCacheQuery_fn = async function(query, meta, records) {
4109
+ await __privateGet$3(this, _cache)?.set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
4110
+ };
4111
+ _getCacheQuery = new WeakSet();
4112
+ getCacheQuery_fn = async function(query) {
4113
+ const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
4114
+ const result = await __privateGet$3(this, _cache)?.get(key);
4115
+ if (!result)
4116
+ return null;
4117
+ const defaultTTL = __privateGet$3(this, _cache)?.defaultQueryTTL ?? -1;
4118
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
4119
+ if (ttl < 0)
4120
+ return null;
4121
+ const hasExpired = result.date.getTime() + ttl < Date.now();
4122
+ return hasExpired ? null : result;
4123
+ };
4124
+ _getSchemaTables = new WeakSet();
4125
+ getSchemaTables_fn = async function() {
4126
+ if (__privateGet$3(this, _schemaTables))
4127
+ return __privateGet$3(this, _schemaTables);
4128
+ const { schema } = await getBranchDetails({
4129
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4130
+ ...__privateGet$3(this, _getFetchProps).call(this)
4131
+ });
4132
+ __privateSet$2(this, _schemaTables, schema.tables);
4133
+ return schema.tables;
4134
+ };
4135
+ _transformObjectToApi = new WeakSet();
4136
+ transformObjectToApi_fn = async function(object) {
4137
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
4138
+ const schema = schemaTables.find((table) => table.name === __privateGet$3(this, _table));
4139
+ if (!schema)
4140
+ throw new Error(`Table ${__privateGet$3(this, _table)} not found in schema`);
4141
+ const result = {};
4142
+ for (const [key, value] of Object.entries(object)) {
4143
+ if (key === "xata")
4144
+ continue;
4145
+ const type = schema.columns.find((column) => column.name === key)?.type;
4146
+ switch (type) {
4147
+ case "link": {
4148
+ result[key] = isIdentifiable(value) ? value.id : value;
4149
+ break;
4150
+ }
4151
+ case "datetime": {
4152
+ result[key] = value instanceof Date ? value.toISOString() : value;
4153
+ break;
4154
+ }
4155
+ case `file`:
4156
+ result[key] = await parseInputFileEntry(value);
4157
+ break;
4158
+ case "file[]":
4159
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4160
+ break;
4161
+ case "json":
4162
+ result[key] = stringifyJson(value);
4163
+ break;
4164
+ default:
4165
+ result[key] = value;
4166
+ }
4167
+ }
4168
+ return result;
4169
+ };
4170
+ const initObject = (db, schemaTables, table, object, selectedColumns) => {
4171
+ const data = {};
4172
+ const { xata, ...rest } = object ?? {};
4173
+ Object.assign(data, rest);
4174
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
4175
+ if (!columns)
4176
+ console.error(`Table ${table} not found in schema`);
4177
+ for (const column of columns ?? []) {
4178
+ if (!isValidColumn(selectedColumns, column))
4179
+ continue;
4180
+ const value = data[column.name];
4181
+ switch (column.type) {
4182
+ case "datetime": {
4183
+ const date = value !== void 0 ? new Date(value) : null;
4184
+ if (date !== null && isNaN(date.getTime())) {
4185
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
4186
+ } else {
4187
+ data[column.name] = date;
4188
+ }
4189
+ break;
4190
+ }
4191
+ case "link": {
4192
+ const linkTable = column.link?.table;
4193
+ if (!linkTable) {
4194
+ console.error(`Failed to parse link for field ${column.name}`);
4195
+ } else if (isObject(value)) {
4196
+ const selectedLinkColumns = selectedColumns.reduce((acc, item) => {
4197
+ if (item === column.name) {
4198
+ return [...acc, "*"];
4199
+ }
4200
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
4201
+ const [, ...path] = item.split(".");
4202
+ return [...acc, path.join(".")];
4203
+ }
4204
+ return acc;
4205
+ }, []);
4206
+ data[column.name] = initObject(
4207
+ db,
4208
+ schemaTables,
4209
+ linkTable,
4210
+ value,
4211
+ selectedLinkColumns
4212
+ );
4213
+ } else {
4214
+ data[column.name] = null;
4215
+ }
4216
+ break;
4217
+ }
4218
+ case "file":
4219
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4220
+ break;
4221
+ case "file[]":
4222
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4223
+ break;
4224
+ case "json":
4225
+ data[column.name] = parseJson(value);
4226
+ break;
4227
+ default:
4228
+ data[column.name] = value ?? null;
4229
+ if (column.notNull === true && value === null) {
4230
+ console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
4231
+ }
4232
+ break;
4233
+ }
4234
+ }
4235
+ const record = { ...data };
4236
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
4237
+ record.read = function(columns2) {
4238
+ return db[table].read(record["id"], columns2);
4239
+ };
4240
+ record.update = function(data2, b, c) {
4241
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
4242
+ const ifVersion = parseIfVersion(b, c);
4243
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
4244
+ };
4245
+ record.replace = function(data2, b, c) {
4246
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
4247
+ const ifVersion = parseIfVersion(b, c);
4248
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
4249
+ };
4250
+ record.delete = function() {
4251
+ return db[table].delete(record["id"]);
4252
+ };
4253
+ if (metadata !== void 0) {
4254
+ record.xata = Object.freeze(metadata);
4255
+ }
4256
+ record.getMetadata = function() {
4257
+ return record.xata;
4258
+ };
4259
+ record.toSerializable = function() {
4260
+ return JSON.parse(JSON.stringify(record));
4261
+ };
4262
+ record.toString = function() {
4263
+ return JSON.stringify(record);
4264
+ };
4265
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
4266
+ Object.defineProperty(record, prop, { enumerable: false });
4267
+ }
4268
+ Object.freeze(record);
4269
+ return record;
4270
+ };
4271
+ function extractId(value) {
4272
+ if (isString(value))
4273
+ return value;
4274
+ if (isObject(value) && isString(value.id))
4275
+ return value.id;
4276
+ return void 0;
4277
+ }
4278
+ function isValidColumn(columns, column) {
4279
+ if (columns.includes("*"))
4280
+ return true;
4281
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
4282
+ }
4283
+ function parseIfVersion(...args) {
4284
+ for (const arg of args) {
4285
+ if (isObject(arg) && isNumber(arg.ifVersion)) {
4286
+ return arg.ifVersion;
4287
+ }
4288
+ }
4289
+ return void 0;
4290
+ }
4291
+
4292
+ var __accessCheck$3 = (obj, member, msg) => {
4293
+ if (!member.has(obj))
4294
+ throw TypeError("Cannot " + msg);
4295
+ };
4296
+ var __privateGet$2 = (obj, member, getter) => {
4297
+ __accessCheck$3(obj, member, "read from private field");
4298
+ return getter ? getter.call(obj) : member.get(obj);
4299
+ };
4300
+ var __privateAdd$3 = (obj, member, value) => {
4301
+ if (member.has(obj))
4302
+ throw TypeError("Cannot add the same private member more than once");
4303
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
4304
+ };
4305
+ var __privateSet$1 = (obj, member, value, setter) => {
4306
+ __accessCheck$3(obj, member, "write to private field");
4307
+ setter ? setter.call(obj, value) : member.set(obj, value);
4308
+ return value;
4309
+ };
4310
+ var _map;
4311
+ class SimpleCache {
4312
+ constructor(options = {}) {
4313
+ __privateAdd$3(this, _map, void 0);
4314
+ __privateSet$1(this, _map, /* @__PURE__ */ new Map());
4315
+ this.capacity = options.max ?? 500;
4316
+ this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
4317
+ }
4318
+ async getAll() {
4319
+ return Object.fromEntries(__privateGet$2(this, _map));
4320
+ }
4321
+ async get(key) {
4322
+ return __privateGet$2(this, _map).get(key) ?? null;
4323
+ }
4324
+ async set(key, value) {
4325
+ await this.delete(key);
4326
+ __privateGet$2(this, _map).set(key, value);
4327
+ if (__privateGet$2(this, _map).size > this.capacity) {
4328
+ const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
4329
+ await this.delete(leastRecentlyUsed);
4330
+ }
4331
+ }
4332
+ async delete(key) {
4333
+ __privateGet$2(this, _map).delete(key);
4334
+ }
4335
+ async clear() {
4336
+ return __privateGet$2(this, _map).clear();
4337
+ }
4338
+ }
4339
+ _map = new WeakMap();
4340
+
4341
+ const greaterThan = (value) => ({ $gt: value });
4342
+ const gt = greaterThan;
4343
+ const greaterThanEquals = (value) => ({ $ge: value });
4344
+ const greaterEquals = greaterThanEquals;
4345
+ const gte = greaterThanEquals;
4346
+ const ge = greaterThanEquals;
4347
+ const lessThan = (value) => ({ $lt: value });
4348
+ const lt = lessThan;
4349
+ const lessThanEquals = (value) => ({ $le: value });
4350
+ const lessEquals = lessThanEquals;
4351
+ const lte = lessThanEquals;
4352
+ const le = lessThanEquals;
4353
+ const exists = (column) => ({ $exists: column });
4354
+ const notExists = (column) => ({ $notExists: column });
4355
+ const startsWith = (value) => ({ $startsWith: value });
4356
+ const endsWith = (value) => ({ $endsWith: value });
4357
+ const pattern = (value) => ({ $pattern: value });
4358
+ const iPattern = (value) => ({ $iPattern: value });
4359
+ const is = (value) => ({ $is: value });
4360
+ const equals = is;
4361
+ const isNot = (value) => ({ $isNot: value });
4362
+ const contains = (value) => ({ $contains: value });
4363
+ const iContains = (value) => ({ $iContains: value });
4364
+ const includes = (value) => ({ $includes: value });
4365
+ const includesAll = (value) => ({ $includesAll: value });
4366
+ const includesNone = (value) => ({ $includesNone: value });
4367
+ const includesAny = (value) => ({ $includesAny: value });
4368
+
4369
+ var __accessCheck$2 = (obj, member, msg) => {
4370
+ if (!member.has(obj))
4371
+ throw TypeError("Cannot " + msg);
4372
+ };
4373
+ var __privateGet$1 = (obj, member, getter) => {
4374
+ __accessCheck$2(obj, member, "read from private field");
4375
+ return getter ? getter.call(obj) : member.get(obj);
4376
+ };
4377
+ var __privateAdd$2 = (obj, member, value) => {
4378
+ if (member.has(obj))
4379
+ throw TypeError("Cannot add the same private member more than once");
4380
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
4381
+ };
4382
+ var _tables;
4383
+ class SchemaPlugin extends XataPlugin {
4384
+ constructor() {
4385
+ super();
4386
+ __privateAdd$2(this, _tables, {});
4387
+ }
4388
+ build(pluginOptions) {
4389
+ const db = new Proxy(
4390
+ {},
4391
+ {
4392
+ get: (_target, table) => {
4393
+ if (!isString(table))
4394
+ throw new Error("Invalid table name");
4395
+ if (__privateGet$1(this, _tables)[table] === void 0) {
4396
+ __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: pluginOptions.tables });
4397
+ }
4398
+ return __privateGet$1(this, _tables)[table];
4399
+ }
4400
+ }
4401
+ );
4402
+ const tableNames = pluginOptions.tables?.map(({ name }) => name) ?? [];
4403
+ for (const table of tableNames) {
4404
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: pluginOptions.tables });
4405
+ }
4406
+ return db;
4407
+ }
4408
+ }
4409
+ _tables = new WeakMap();
4410
+
4411
+ class FilesPlugin extends XataPlugin {
4412
+ build(pluginOptions) {
4413
+ return {
4414
+ download: async (location) => {
4415
+ const { table, record, column, fileId = "" } = location ?? {};
4416
+ return await getFileItem({
4417
+ pathParams: {
4418
+ workspace: "{workspaceId}",
4419
+ dbBranchName: "{dbBranch}",
4420
+ region: "{region}",
4421
+ tableName: table ?? "",
4422
+ recordId: record ?? "",
4423
+ columnName: column ?? "",
4424
+ fileId
4425
+ },
4426
+ ...pluginOptions,
4427
+ rawResponse: true
4428
+ });
4429
+ },
4430
+ upload: async (location, file, options) => {
4431
+ const { table, record, column, fileId = "" } = location ?? {};
4432
+ const resolvedFile = await file;
4433
+ const contentType = options?.mediaType || getContentType(resolvedFile);
4434
+ const body = resolvedFile instanceof XataFile ? resolvedFile.toBlob() : resolvedFile;
4435
+ return await putFileItem({
4436
+ ...pluginOptions,
4437
+ pathParams: {
4438
+ workspace: "{workspaceId}",
4439
+ dbBranchName: "{dbBranch}",
4440
+ region: "{region}",
4441
+ tableName: table ?? "",
4442
+ recordId: record ?? "",
4443
+ columnName: column ?? "",
4444
+ fileId
4445
+ },
4446
+ body,
4447
+ headers: { "Content-Type": contentType }
4448
+ });
4449
+ },
4450
+ delete: async (location) => {
4451
+ const { table, record, column, fileId = "" } = location ?? {};
4452
+ return await deleteFileItem({
4453
+ pathParams: {
4454
+ workspace: "{workspaceId}",
4455
+ dbBranchName: "{dbBranch}",
4456
+ region: "{region}",
4457
+ tableName: table ?? "",
4458
+ recordId: record ?? "",
4459
+ columnName: column ?? "",
4460
+ fileId
4461
+ },
4462
+ ...pluginOptions
4463
+ });
4464
+ }
4465
+ };
4466
+ }
4467
+ }
4468
+ function getContentType(file) {
4469
+ if (typeof file === "string") {
4470
+ return "text/plain";
4471
+ }
4472
+ if ("mediaType" in file && file.mediaType !== void 0) {
4473
+ return file.mediaType;
4474
+ }
4475
+ if (isBlob(file)) {
4476
+ return file.type;
4477
+ }
4478
+ try {
4479
+ return file.type;
4480
+ } catch (e) {
4481
+ }
4482
+ return "application/octet-stream";
4483
+ }
4484
+
4485
+ var __accessCheck$1 = (obj, member, msg) => {
4486
+ if (!member.has(obj))
4487
+ throw TypeError("Cannot " + msg);
4488
+ };
4489
+ var __privateAdd$1 = (obj, member, value) => {
4490
+ if (member.has(obj))
4491
+ throw TypeError("Cannot add the same private member more than once");
4492
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
4493
+ };
4494
+ var __privateMethod$1 = (obj, member, method) => {
4495
+ __accessCheck$1(obj, member, "access private method");
4496
+ return method;
4497
+ };
4498
+ var _search, search_fn;
4499
+ class SearchPlugin extends XataPlugin {
4500
+ constructor(db) {
4501
+ super();
4502
+ this.db = db;
4503
+ __privateAdd$1(this, _search);
4504
+ }
4505
+ build(pluginOptions) {
4506
+ return {
4507
+ all: async (query, options = {}) => {
4508
+ const { records, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4509
+ return {
4510
+ totalCount,
4511
+ records: records.map((record) => {
4512
+ const { table = "orphan" } = record.xata;
4513
+ return { table, record: initObject(this.db, pluginOptions.tables, table, record, ["*"]) };
4514
+ })
4515
+ };
4516
+ },
4517
+ byTable: async (query, options = {}) => {
4518
+ const { records: rawRecords, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4519
+ const records = rawRecords.reduce((acc, record) => {
4520
+ const { table = "orphan" } = record.xata;
4521
+ const items = acc[table] ?? [];
4522
+ const item = initObject(this.db, pluginOptions.tables, table, record, ["*"]);
4523
+ return { ...acc, [table]: [...items, item] };
4524
+ }, {});
4525
+ return { totalCount, records };
4526
+ }
4527
+ };
4528
+ }
4529
+ }
4530
+ _search = new WeakSet();
4531
+ search_fn = async function(query, options, pluginOptions) {
4532
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
4533
+ const { records, totalCount } = await searchBranch({
4534
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4535
+ // @ts-expect-error Filter properties do not match inferred type
4536
+ body: { tables, query, fuzziness, prefix, highlight, page },
4537
+ ...pluginOptions
4538
+ });
4539
+ return { records, totalCount };
4540
+ };
4541
+
4542
+ function escapeElement(elementRepresentation) {
4543
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4544
+ return '"' + escaped + '"';
4545
+ }
4546
+ function arrayString(val) {
4547
+ let result = "{";
4548
+ for (let i = 0; i < val.length; i++) {
4549
+ if (i > 0) {
4550
+ result = result + ",";
4551
+ }
4552
+ if (val[i] === null || typeof val[i] === "undefined") {
4553
+ result = result + "NULL";
4554
+ } else if (Array.isArray(val[i])) {
4555
+ result = result + arrayString(val[i]);
4556
+ } else if (val[i] instanceof Buffer) {
4557
+ result += "\\\\x" + val[i].toString("hex");
4558
+ } else {
4559
+ result += escapeElement(prepareValue(val[i]));
4560
+ }
4561
+ }
4562
+ result = result + "}";
4563
+ return result;
4564
+ }
4565
+ function prepareValue(value) {
4566
+ if (!isDefined(value))
4567
+ return null;
4568
+ if (value instanceof Date) {
4569
+ return value.toISOString();
4570
+ }
4571
+ if (Array.isArray(value)) {
4572
+ return arrayString(value);
4573
+ }
4574
+ if (isObject(value)) {
4575
+ return JSON.stringify(value);
4576
+ }
4577
+ try {
4578
+ return value.toString();
4579
+ } catch (e) {
4580
+ return value;
4581
+ }
4582
+ }
4583
+ function prepareParams(param1, param2) {
4584
+ if (isString(param1)) {
4585
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4586
+ }
4587
+ if (isStringArray(param1)) {
4588
+ const statement = param1.reduce((acc, curr, index) => {
4589
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4590
+ }, "");
4591
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4592
+ }
4593
+ if (isObject(param1)) {
4594
+ const { statement, params, consistency, responseType } = param1;
4595
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency, responseType };
4596
+ }
4597
+ throw new Error("Invalid query");
4598
+ }
4599
+
4600
+ class SQLPlugin extends XataPlugin {
4601
+ build(pluginOptions) {
4602
+ const sqlFunction = async (query, ...parameters) => {
4603
+ if (!isParamsObject(query) && (!isTemplateStringsArray(query) || !Array.isArray(parameters))) {
4604
+ throw new Error("Invalid usage of `xata.sql`. Please use it as a tagged template or with an object.");
4605
+ }
4606
+ const { statement, params, consistency, responseType } = prepareParams(query, parameters);
4607
+ const {
4608
+ records,
4609
+ rows,
4610
+ warning,
4611
+ columns = []
4612
+ } = await sqlQuery({
4613
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4614
+ body: { statement, params, consistency, responseType },
4615
+ ...pluginOptions
4616
+ });
4617
+ return { records, rows, warning, columns };
4618
+ };
4619
+ sqlFunction.connectionString = buildConnectionString(pluginOptions);
4620
+ return sqlFunction;
4621
+ }
4622
+ }
4623
+ function isTemplateStringsArray(strings) {
4624
+ return Array.isArray(strings) && "raw" in strings && Array.isArray(strings.raw);
4625
+ }
4626
+ function isParamsObject(params) {
4627
+ return isObject(params) && "statement" in params;
4628
+ }
4629
+ function buildDomain(host, region) {
4630
+ switch (host) {
4631
+ case "production":
4632
+ return `${region}.sql.xata.sh`;
4633
+ case "staging":
4634
+ return `${region}.sql.staging-xata.dev`;
4635
+ case "dev":
4636
+ return `${region}.sql.dev-xata.dev`;
4637
+ case "local":
4638
+ return "localhost:7654";
4639
+ default:
4640
+ throw new Error("Invalid host provider");
4641
+ }
4642
+ }
4643
+ function buildConnectionString({ apiKey, workspacesApiUrl, branch }) {
4644
+ const url = isString(workspacesApiUrl) ? workspacesApiUrl : workspacesApiUrl("", {});
4645
+ const parts = parseWorkspacesUrlParts(url);
4646
+ if (!parts)
4647
+ throw new Error("Invalid workspaces URL");
4648
+ const { workspace: workspaceSlug, region, database, host } = parts;
4649
+ const domain = buildDomain(host, region);
4650
+ const workspace = workspaceSlug.split("-").pop();
4651
+ if (!workspace || !region || !database || !apiKey || !branch) {
4652
+ throw new Error("Unable to build xata connection string");
4653
+ }
4654
+ return `postgresql://${workspace}:${apiKey}@${domain}/${database}:${branch}?sslmode=require`;
4655
+ }
4656
+
4657
+ class TransactionPlugin extends XataPlugin {
4658
+ build(pluginOptions) {
4659
+ return {
4660
+ run: async (operations) => {
4661
+ const response = await branchTransaction({
4662
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4663
+ body: { operations },
4664
+ ...pluginOptions
4665
+ });
4666
+ return response;
4667
+ }
4668
+ };
4669
+ }
4670
+ }
4671
+
4672
+ var __accessCheck = (obj, member, msg) => {
4673
+ if (!member.has(obj))
4674
+ throw TypeError("Cannot " + msg);
4675
+ };
4676
+ var __privateGet = (obj, member, getter) => {
4677
+ __accessCheck(obj, member, "read from private field");
4678
+ return getter ? getter.call(obj) : member.get(obj);
4679
+ };
4680
+ var __privateAdd = (obj, member, value) => {
4681
+ if (member.has(obj))
4682
+ throw TypeError("Cannot add the same private member more than once");
4683
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
4684
+ };
4685
+ var __privateSet = (obj, member, value, setter) => {
4686
+ __accessCheck(obj, member, "write to private field");
4687
+ setter ? setter.call(obj, value) : member.set(obj, value);
4688
+ return value;
4689
+ };
4690
+ var __privateMethod = (obj, member, method) => {
4691
+ __accessCheck(obj, member, "access private method");
4692
+ return method;
4693
+ };
4694
+ const buildClient = (plugins) => {
4695
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
4696
+ return _a = class {
4697
+ constructor(options = {}, tables) {
4698
+ __privateAdd(this, _parseOptions);
4699
+ __privateAdd(this, _getFetchProps);
4700
+ __privateAdd(this, _options, void 0);
4701
+ const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
4702
+ __privateSet(this, _options, safeOptions);
4703
+ const pluginOptions = {
4704
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
4705
+ cache: safeOptions.cache,
4706
+ host: safeOptions.host,
4707
+ tables,
4708
+ branch: safeOptions.branch
4709
+ };
4710
+ const db = new SchemaPlugin().build(pluginOptions);
4711
+ const search = new SearchPlugin(db).build(pluginOptions);
4712
+ const transactions = new TransactionPlugin().build(pluginOptions);
4713
+ const sql = new SQLPlugin().build(pluginOptions);
4714
+ const files = new FilesPlugin().build(pluginOptions);
4715
+ this.schema = { tables };
4716
+ this.db = db;
4717
+ this.search = search;
4718
+ this.transactions = transactions;
4719
+ this.sql = sql;
4720
+ this.files = files;
4721
+ for (const [key, namespace] of Object.entries(plugins ?? {})) {
4722
+ if (namespace === void 0)
4723
+ continue;
4724
+ this[key] = namespace.build(pluginOptions);
4725
+ }
4726
+ }
4727
+ async getConfig() {
4728
+ const databaseURL = __privateGet(this, _options).databaseURL;
4729
+ const branch = __privateGet(this, _options).branch;
4730
+ return { databaseURL, branch };
4731
+ }
4732
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4733
+ const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
4734
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
4735
+ if (isBrowser && !enableBrowser) {
4736
+ throw new Error(
4737
+ "You are trying to use Xata from the browser, which is potentially a non-secure environment. How to fix: https://xata.io/docs/messages/api-key-browser-error"
4738
+ );
4739
+ }
4740
+ const fetch = getFetchImplementation(options?.fetch);
4741
+ const databaseURL = options?.databaseURL || getDatabaseURL();
4742
+ const apiKey = options?.apiKey || getAPIKey();
4743
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
4744
+ const trace = options?.trace ?? defaultTrace;
4745
+ const clientName = options?.clientName;
4746
+ const host = options?.host ?? "production";
4747
+ const xataAgentExtra = options?.xataAgentExtra;
4748
+ if (!apiKey) {
4749
+ throw new Error("Option apiKey is required");
4750
+ }
4751
+ if (!databaseURL) {
4752
+ throw new Error("Option databaseURL is required");
4753
+ }
4754
+ const envBranch = getBranch();
4755
+ const previewBranch = getPreviewBranch();
4756
+ const branch = options?.branch || previewBranch || envBranch || "main";
4757
+ if (!!previewBranch && branch !== previewBranch) {
4758
+ console.warn(
4759
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4760
+ );
4761
+ } else if (!!envBranch && branch !== envBranch) {
4762
+ console.warn(
4763
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4764
+ );
4765
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4766
+ console.warn(
4767
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4768
+ );
4769
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4770
+ console.warn(
4771
+ `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.`
4772
+ );
4773
+ }
4774
+ return {
4775
+ fetch,
4776
+ databaseURL,
4777
+ apiKey,
4778
+ branch,
4779
+ cache,
4780
+ trace,
4781
+ host,
4782
+ clientID: generateUUID(),
4783
+ enableBrowser,
4784
+ clientName,
4785
+ xataAgentExtra
4786
+ };
4787
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
4788
+ fetch,
4789
+ apiKey,
4790
+ databaseURL,
4791
+ branch,
4792
+ trace,
4793
+ clientID,
4794
+ clientName,
4795
+ xataAgentExtra
4796
+ }) {
4797
+ return {
4798
+ fetch,
4799
+ apiKey,
4800
+ apiUrl: "",
4801
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
4802
+ workspacesApiUrl: (path, params) => {
4803
+ const hasBranch = params.dbBranchName ?? params.branch;
4804
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
4805
+ return databaseURL + newPath;
4806
+ },
4807
+ trace,
4808
+ clientID,
4809
+ clientName,
4810
+ xataAgentExtra
4811
+ };
4812
+ }, _a;
4813
+ };
4814
+ class BaseClient extends buildClient() {
4815
+ }
4816
+
4817
+ const META = "__";
4818
+ const VALUE = "___";
4819
+ class Serializer {
4820
+ constructor() {
4821
+ this.classes = {};
4822
+ }
4823
+ add(clazz) {
4824
+ this.classes[clazz.name] = clazz;
4825
+ }
4826
+ toJSON(data) {
4827
+ function visit(obj) {
4828
+ if (Array.isArray(obj))
4829
+ return obj.map(visit);
4830
+ const type = typeof obj;
4831
+ if (type === "undefined")
4832
+ return { [META]: "undefined" };
4833
+ if (type === "bigint")
4834
+ return { [META]: "bigint", [VALUE]: obj.toString() };
4835
+ if (obj === null || type !== "object")
4836
+ return obj;
4837
+ const constructor = obj.constructor;
4838
+ const o = { [META]: constructor.name };
4839
+ for (const [key, value] of Object.entries(obj)) {
4840
+ o[key] = visit(value);
4841
+ }
4842
+ if (constructor === Date)
4843
+ o[VALUE] = obj.toISOString();
4844
+ if (constructor === Map)
4845
+ o[VALUE] = Object.fromEntries(obj);
4846
+ if (constructor === Set)
4847
+ o[VALUE] = [...obj];
4848
+ return o;
4849
+ }
4850
+ return JSON.stringify(visit(data));
4851
+ }
4852
+ fromJSON(json) {
4853
+ return JSON.parse(json, (key, value) => {
4854
+ if (value && typeof value === "object" && !Array.isArray(value)) {
4855
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
4856
+ const constructor = this.classes[clazz];
4857
+ if (constructor) {
4858
+ return Object.assign(Object.create(constructor.prototype), rest);
4859
+ }
4860
+ if (clazz === "Date")
4861
+ return new Date(val);
4862
+ if (clazz === "Set")
4863
+ return new Set(val);
4864
+ if (clazz === "Map")
4865
+ return new Map(Object.entries(val));
4866
+ if (clazz === "bigint")
4867
+ return BigInt(val);
4868
+ if (clazz === "undefined")
4869
+ return void 0;
4870
+ return rest;
4871
+ }
4872
+ return value;
4873
+ });
4874
+ }
4875
+ }
4876
+ const defaultSerializer = new Serializer();
4877
+ const serialize = (data) => {
4878
+ return defaultSerializer.toJSON(data);
4879
+ };
4880
+ const deserialize = (json) => {
4881
+ return defaultSerializer.fromJSON(json);
4882
+ };
4883
+
4884
+ class XataError extends Error {
4885
+ constructor(message, status) {
4886
+ super(message);
4887
+ this.status = status;
4888
+ }
4889
+ }
4890
+
4891
+ export { BaseClient, FetcherError, FilesPlugin, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, PageRecordArray, Query, RecordArray, RecordColumnTypes, Repository, RestRepository, SQLPlugin, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, TransactionPlugin, XataApiClient, XataApiPlugin, XataError, XataFile, XataPlugin, acceptWorkspaceMemberInvite, adaptTable, 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, getBranchMigrationJobStatus, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getCluster, getColumn, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseSettings, getDatabaseURL, getFile, getFileItem, getGitBranchesMapping, getHostUrl, getMigrationHistory, getMigrationJobStatus, getMigrationRequest, getMigrationRequestIsMerged, getPreviewBranch, getRecord, getSchema, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getUserOAuthAccessTokens, getUserOAuthClients, getWorkspace, getWorkspaceMembersList, getWorkspaceSettings, 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, 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, updateDatabaseSettings, updateMigrationRequest, updateOAuthAccessToken, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, updateWorkspaceSettings, upsertRecordWithID, vectorSearchTable };
4892
+ //# sourceMappingURL=index.mjs.map