@xata.io/client 0.0.0-beta.fddf861 → 0.0.0-next.v43b83f3e3d703ba85a9c6790259cc93a43f69e98

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 (48) hide show
  1. package/.turbo/turbo-add-version.log +4 -0
  2. package/.turbo/turbo-build.log +13 -0
  3. package/CHANGELOG.md +811 -0
  4. package/README.md +7 -1
  5. package/dist/index.cjs +3653 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.ts +9685 -3
  8. package/dist/index.mjs +3466 -0
  9. package/dist/index.mjs.map +1 -0
  10. package/package.json +23 -10
  11. package/dist/api/client.d.ts +0 -95
  12. package/dist/api/client.js +0 -235
  13. package/dist/api/components.d.ts +0 -1440
  14. package/dist/api/components.js +0 -1001
  15. package/dist/api/fetcher.d.ts +0 -25
  16. package/dist/api/fetcher.js +0 -78
  17. package/dist/api/index.d.ts +0 -7
  18. package/dist/api/index.js +0 -21
  19. package/dist/api/parameters.d.ts +0 -16
  20. package/dist/api/parameters.js +0 -2
  21. package/dist/api/providers.d.ts +0 -8
  22. package/dist/api/providers.js +0 -29
  23. package/dist/api/responses.d.ts +0 -44
  24. package/dist/api/responses.js +0 -2
  25. package/dist/api/schemas.d.ts +0 -311
  26. package/dist/api/schemas.js +0 -2
  27. package/dist/index.js +0 -26
  28. package/dist/schema/filters.d.ts +0 -20
  29. package/dist/schema/filters.js +0 -24
  30. package/dist/schema/index.d.ts +0 -6
  31. package/dist/schema/index.js +0 -26
  32. package/dist/schema/operators.d.ts +0 -72
  33. package/dist/schema/operators.js +0 -91
  34. package/dist/schema/pagination.d.ts +0 -83
  35. package/dist/schema/pagination.js +0 -94
  36. package/dist/schema/query.d.ts +0 -129
  37. package/dist/schema/query.js +0 -254
  38. package/dist/schema/record.d.ts +0 -44
  39. package/dist/schema/record.js +0 -2
  40. package/dist/schema/repository.d.ts +0 -104
  41. package/dist/schema/repository.js +0 -280
  42. package/dist/schema/selection.d.ts +0 -12
  43. package/dist/schema/selection.js +0 -2
  44. package/dist/util/lang.d.ts +0 -2
  45. package/dist/util/lang.js +0 -10
  46. package/dist/util/types.d.ts +0 -3
  47. package/dist/util/types.js +0 -2
  48. package/tsconfig.json +0 -21
package/dist/index.cjs ADDED
@@ -0,0 +1,3653 @@
1
+ 'use strict';
2
+
3
+ const defaultTrace = async (name, fn, _options) => {
4
+ return await fn({
5
+ name,
6
+ setAttributes: () => {
7
+ return;
8
+ }
9
+ });
10
+ };
11
+ const TraceAttributes = {
12
+ KIND: "xata.trace.kind",
13
+ VERSION: "xata.sdk.version",
14
+ TABLE: "xata.table",
15
+ HTTP_REQUEST_ID: "http.request_id",
16
+ HTTP_STATUS_CODE: "http.status_code",
17
+ HTTP_HOST: "http.host",
18
+ HTTP_SCHEME: "http.scheme",
19
+ HTTP_USER_AGENT: "http.user_agent",
20
+ HTTP_METHOD: "http.method",
21
+ HTTP_URL: "http.url",
22
+ HTTP_ROUTE: "http.route",
23
+ HTTP_TARGET: "http.target",
24
+ CLOUDFLARE_RAY_ID: "cf.ray"
25
+ };
26
+
27
+ function notEmpty(value) {
28
+ return value !== null && value !== void 0;
29
+ }
30
+ function compact(arr) {
31
+ return arr.filter(notEmpty);
32
+ }
33
+ function compactObject(obj) {
34
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
35
+ }
36
+ function isBlob(value) {
37
+ try {
38
+ return value instanceof Blob;
39
+ } catch (error) {
40
+ return false;
41
+ }
42
+ }
43
+ function isObject(value) {
44
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
45
+ }
46
+ function isDefined(value) {
47
+ return value !== null && value !== void 0;
48
+ }
49
+ function isString(value) {
50
+ return isDefined(value) && typeof value === "string";
51
+ }
52
+ function isStringArray(value) {
53
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
54
+ }
55
+ function isNumber(value) {
56
+ return isDefined(value) && typeof value === "number";
57
+ }
58
+ function parseNumber(value) {
59
+ if (isNumber(value)) {
60
+ return value;
61
+ }
62
+ if (isString(value)) {
63
+ const parsed = Number(value);
64
+ if (!Number.isNaN(parsed)) {
65
+ return parsed;
66
+ }
67
+ }
68
+ return void 0;
69
+ }
70
+ function toBase64(value) {
71
+ try {
72
+ return btoa(value);
73
+ } catch (err) {
74
+ const buf = Buffer;
75
+ return buf.from(value).toString("base64");
76
+ }
77
+ }
78
+ function deepMerge(a, b) {
79
+ const result = { ...a };
80
+ for (const [key, value] of Object.entries(b)) {
81
+ if (isObject(value) && isObject(result[key])) {
82
+ result[key] = deepMerge(result[key], value);
83
+ } else {
84
+ result[key] = value;
85
+ }
86
+ }
87
+ return result;
88
+ }
89
+ function chunk(array, chunkSize) {
90
+ const result = [];
91
+ for (let i = 0; i < array.length; i += chunkSize) {
92
+ result.push(array.slice(i, i + chunkSize));
93
+ }
94
+ return result;
95
+ }
96
+ async function timeout(ms) {
97
+ return new Promise((resolve) => setTimeout(resolve, ms));
98
+ }
99
+ function timeoutWithCancel(ms) {
100
+ let timeoutId;
101
+ const promise = new Promise((resolve) => {
102
+ timeoutId = setTimeout(() => {
103
+ resolve();
104
+ }, ms);
105
+ });
106
+ return {
107
+ cancel: () => clearTimeout(timeoutId),
108
+ promise
109
+ };
110
+ }
111
+ function promiseMap(inputValues, mapper) {
112
+ const reducer = (acc$, inputValue) => acc$.then(
113
+ (acc) => mapper(inputValue).then((result) => {
114
+ acc.push(result);
115
+ return acc;
116
+ })
117
+ );
118
+ return inputValues.reduce(reducer, Promise.resolve([]));
119
+ }
120
+
121
+ function getEnvironment() {
122
+ try {
123
+ if (isDefined(process) && isDefined(process.env)) {
124
+ return {
125
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
126
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
127
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
128
+ deployPreview: process.env.XATA_PREVIEW,
129
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
130
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
131
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
132
+ };
133
+ }
134
+ } catch (err) {
135
+ }
136
+ try {
137
+ if (isObject(Deno) && isObject(Deno.env)) {
138
+ return {
139
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
140
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
141
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
142
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
143
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
144
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
145
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
146
+ };
147
+ }
148
+ } catch (err) {
149
+ }
150
+ return {
151
+ apiKey: getGlobalApiKey(),
152
+ databaseURL: getGlobalDatabaseURL(),
153
+ branch: getGlobalBranch(),
154
+ deployPreview: void 0,
155
+ deployPreviewBranch: void 0,
156
+ vercelGitCommitRef: void 0,
157
+ vercelGitRepoOwner: void 0
158
+ };
159
+ }
160
+ function getEnableBrowserVariable() {
161
+ try {
162
+ if (isObject(process) && isObject(process.env) && process.env.XATA_ENABLE_BROWSER !== void 0) {
163
+ return process.env.XATA_ENABLE_BROWSER === "true";
164
+ }
165
+ } catch (err) {
166
+ }
167
+ try {
168
+ if (isObject(Deno) && isObject(Deno.env) && Deno.env.get("XATA_ENABLE_BROWSER") !== void 0) {
169
+ return Deno.env.get("XATA_ENABLE_BROWSER") === "true";
170
+ }
171
+ } catch (err) {
172
+ }
173
+ try {
174
+ return XATA_ENABLE_BROWSER === true || XATA_ENABLE_BROWSER === "true";
175
+ } catch (err) {
176
+ return void 0;
177
+ }
178
+ }
179
+ function getGlobalApiKey() {
180
+ try {
181
+ return XATA_API_KEY;
182
+ } catch (err) {
183
+ return void 0;
184
+ }
185
+ }
186
+ function getGlobalDatabaseURL() {
187
+ try {
188
+ return XATA_DATABASE_URL;
189
+ } catch (err) {
190
+ return void 0;
191
+ }
192
+ }
193
+ function getGlobalBranch() {
194
+ try {
195
+ return XATA_BRANCH;
196
+ } catch (err) {
197
+ return void 0;
198
+ }
199
+ }
200
+ function getDatabaseURL() {
201
+ try {
202
+ const { databaseURL } = getEnvironment();
203
+ return databaseURL;
204
+ } catch (err) {
205
+ return void 0;
206
+ }
207
+ }
208
+ function getAPIKey() {
209
+ try {
210
+ const { apiKey } = getEnvironment();
211
+ return apiKey;
212
+ } catch (err) {
213
+ return void 0;
214
+ }
215
+ }
216
+ function getBranch() {
217
+ try {
218
+ const { branch } = getEnvironment();
219
+ return branch;
220
+ } catch (err) {
221
+ return void 0;
222
+ }
223
+ }
224
+ function buildPreviewBranchName({ org, branch }) {
225
+ return `preview-${org}-${branch}`;
226
+ }
227
+ function getPreviewBranch() {
228
+ try {
229
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
230
+ if (deployPreviewBranch)
231
+ return deployPreviewBranch;
232
+ switch (deployPreview) {
233
+ case "vercel": {
234
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
235
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
236
+ return void 0;
237
+ }
238
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
239
+ }
240
+ }
241
+ return void 0;
242
+ } catch (err) {
243
+ return void 0;
244
+ }
245
+ }
246
+
247
+ var __accessCheck$6 = (obj, member, msg) => {
248
+ if (!member.has(obj))
249
+ throw TypeError("Cannot " + msg);
250
+ };
251
+ var __privateGet$5 = (obj, member, getter) => {
252
+ __accessCheck$6(obj, member, "read from private field");
253
+ return getter ? getter.call(obj) : member.get(obj);
254
+ };
255
+ var __privateAdd$6 = (obj, member, value) => {
256
+ if (member.has(obj))
257
+ throw TypeError("Cannot add the same private member more than once");
258
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
259
+ };
260
+ var __privateSet$4 = (obj, member, value, setter) => {
261
+ __accessCheck$6(obj, member, "write to private field");
262
+ setter ? setter.call(obj, value) : member.set(obj, value);
263
+ return value;
264
+ };
265
+ var __privateMethod$4 = (obj, member, method) => {
266
+ __accessCheck$6(obj, member, "access private method");
267
+ return method;
268
+ };
269
+ var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
270
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
271
+ function getFetchImplementation(userFetch) {
272
+ const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
273
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
274
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
275
+ if (!fetchImpl) {
276
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
277
+ }
278
+ return fetchImpl;
279
+ }
280
+ class ApiRequestPool {
281
+ constructor(concurrency = 10) {
282
+ __privateAdd$6(this, _enqueue);
283
+ __privateAdd$6(this, _fetch, void 0);
284
+ __privateAdd$6(this, _queue, void 0);
285
+ __privateAdd$6(this, _concurrency, void 0);
286
+ __privateSet$4(this, _queue, []);
287
+ __privateSet$4(this, _concurrency, concurrency);
288
+ this.running = 0;
289
+ this.started = 0;
290
+ }
291
+ setFetch(fetch2) {
292
+ __privateSet$4(this, _fetch, fetch2);
293
+ }
294
+ getFetch() {
295
+ if (!__privateGet$5(this, _fetch)) {
296
+ throw new Error("Fetch not set");
297
+ }
298
+ return __privateGet$5(this, _fetch);
299
+ }
300
+ request(url, options) {
301
+ const start = /* @__PURE__ */ new Date();
302
+ const fetchImpl = this.getFetch();
303
+ const runRequest = async (stalled = false) => {
304
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
305
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
306
+ if (!response) {
307
+ throw new Error("Request timed out");
308
+ }
309
+ if (response.status === 429) {
310
+ const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
311
+ await timeout(rateLimitReset * 1e3);
312
+ return await runRequest(true);
313
+ }
314
+ if (stalled) {
315
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
316
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
317
+ }
318
+ return response;
319
+ };
320
+ return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
321
+ return await runRequest();
322
+ });
323
+ }
324
+ }
325
+ _fetch = new WeakMap();
326
+ _queue = new WeakMap();
327
+ _concurrency = new WeakMap();
328
+ _enqueue = new WeakSet();
329
+ enqueue_fn = function(task) {
330
+ const promise = new Promise((resolve) => __privateGet$5(this, _queue).push(resolve)).finally(() => {
331
+ this.started--;
332
+ this.running++;
333
+ }).then(() => task()).finally(() => {
334
+ this.running--;
335
+ const next = __privateGet$5(this, _queue).shift();
336
+ if (next !== void 0) {
337
+ this.started++;
338
+ next();
339
+ }
340
+ });
341
+ if (this.running + this.started < __privateGet$5(this, _concurrency)) {
342
+ const next = __privateGet$5(this, _queue).shift();
343
+ if (next !== void 0) {
344
+ this.started++;
345
+ next();
346
+ }
347
+ }
348
+ return promise;
349
+ };
350
+
351
+ function generateUUID() {
352
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
353
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
354
+ return v.toString(16);
355
+ });
356
+ }
357
+
358
+ async function getBytes(stream, onChunk) {
359
+ const reader = stream.getReader();
360
+ let result;
361
+ while (!(result = await reader.read()).done) {
362
+ onChunk(result.value);
363
+ }
364
+ }
365
+ function getLines(onLine) {
366
+ let buffer;
367
+ let position;
368
+ let fieldLength;
369
+ let discardTrailingNewline = false;
370
+ return function onChunk(arr) {
371
+ if (buffer === void 0) {
372
+ buffer = arr;
373
+ position = 0;
374
+ fieldLength = -1;
375
+ } else {
376
+ buffer = concat(buffer, arr);
377
+ }
378
+ const bufLength = buffer.length;
379
+ let lineStart = 0;
380
+ while (position < bufLength) {
381
+ if (discardTrailingNewline) {
382
+ if (buffer[position] === 10 /* NewLine */) {
383
+ lineStart = ++position;
384
+ }
385
+ discardTrailingNewline = false;
386
+ }
387
+ let lineEnd = -1;
388
+ for (; position < bufLength && lineEnd === -1; ++position) {
389
+ switch (buffer[position]) {
390
+ case 58 /* Colon */:
391
+ if (fieldLength === -1) {
392
+ fieldLength = position - lineStart;
393
+ }
394
+ break;
395
+ case 13 /* CarriageReturn */:
396
+ discardTrailingNewline = true;
397
+ case 10 /* NewLine */:
398
+ lineEnd = position;
399
+ break;
400
+ }
401
+ }
402
+ if (lineEnd === -1) {
403
+ break;
404
+ }
405
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
406
+ lineStart = position;
407
+ fieldLength = -1;
408
+ }
409
+ if (lineStart === bufLength) {
410
+ buffer = void 0;
411
+ } else if (lineStart !== 0) {
412
+ buffer = buffer.subarray(lineStart);
413
+ position -= lineStart;
414
+ }
415
+ };
416
+ }
417
+ function getMessages(onId, onRetry, onMessage) {
418
+ let message = newMessage();
419
+ const decoder = new TextDecoder();
420
+ return function onLine(line, fieldLength) {
421
+ if (line.length === 0) {
422
+ onMessage?.(message);
423
+ message = newMessage();
424
+ } else if (fieldLength > 0) {
425
+ const field = decoder.decode(line.subarray(0, fieldLength));
426
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
427
+ const value = decoder.decode(line.subarray(valueOffset));
428
+ switch (field) {
429
+ case "data":
430
+ message.data = message.data ? message.data + "\n" + value : value;
431
+ break;
432
+ case "event":
433
+ message.event = value;
434
+ break;
435
+ case "id":
436
+ onId(message.id = value);
437
+ break;
438
+ case "retry":
439
+ const retry = parseInt(value, 10);
440
+ if (!isNaN(retry)) {
441
+ onRetry(message.retry = retry);
442
+ }
443
+ break;
444
+ }
445
+ }
446
+ };
447
+ }
448
+ function concat(a, b) {
449
+ const res = new Uint8Array(a.length + b.length);
450
+ res.set(a);
451
+ res.set(b, a.length);
452
+ return res;
453
+ }
454
+ function newMessage() {
455
+ return {
456
+ data: "",
457
+ event: "",
458
+ id: "",
459
+ retry: void 0
460
+ };
461
+ }
462
+ const EventStreamContentType = "text/event-stream";
463
+ const LastEventId = "last-event-id";
464
+ function fetchEventSource(input, {
465
+ signal: inputSignal,
466
+ headers: inputHeaders,
467
+ onopen: inputOnOpen,
468
+ onmessage,
469
+ onclose,
470
+ onerror,
471
+ fetch: inputFetch,
472
+ ...rest
473
+ }) {
474
+ return new Promise((resolve, reject) => {
475
+ const headers = { ...inputHeaders };
476
+ if (!headers.accept) {
477
+ headers.accept = EventStreamContentType;
478
+ }
479
+ let curRequestController;
480
+ function dispose() {
481
+ curRequestController.abort();
482
+ }
483
+ inputSignal?.addEventListener("abort", () => {
484
+ dispose();
485
+ resolve();
486
+ });
487
+ const fetchImpl = inputFetch ?? fetch;
488
+ const onopen = inputOnOpen ?? defaultOnOpen;
489
+ async function create() {
490
+ curRequestController = new AbortController();
491
+ try {
492
+ const response = await fetchImpl(input, {
493
+ ...rest,
494
+ headers,
495
+ signal: curRequestController.signal
496
+ });
497
+ await onopen(response);
498
+ await getBytes(
499
+ response.body,
500
+ getLines(
501
+ getMessages(
502
+ (id) => {
503
+ if (id) {
504
+ headers[LastEventId] = id;
505
+ } else {
506
+ delete headers[LastEventId];
507
+ }
508
+ },
509
+ (_retry) => {
510
+ },
511
+ onmessage
512
+ )
513
+ )
514
+ );
515
+ onclose?.();
516
+ dispose();
517
+ resolve();
518
+ } catch (err) {
519
+ }
520
+ }
521
+ create();
522
+ });
523
+ }
524
+ function defaultOnOpen(response) {
525
+ const contentType = response.headers?.get("content-type");
526
+ if (!contentType?.startsWith(EventStreamContentType)) {
527
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
528
+ }
529
+ }
530
+
531
+ const VERSION = "0.29.2";
532
+
533
+ class ErrorWithCause extends Error {
534
+ constructor(message, options) {
535
+ super(message, options);
536
+ }
537
+ }
538
+ class FetcherError extends ErrorWithCause {
539
+ constructor(status, data, requestId) {
540
+ super(getMessage(data));
541
+ this.status = status;
542
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
543
+ this.requestId = requestId;
544
+ if (data instanceof Error) {
545
+ this.stack = data.stack;
546
+ this.cause = data.cause;
547
+ }
548
+ }
549
+ toString() {
550
+ const error = super.toString();
551
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
552
+ }
553
+ }
554
+ function isBulkError(error) {
555
+ return isObject(error) && Array.isArray(error.errors);
556
+ }
557
+ function isErrorWithMessage(error) {
558
+ return isObject(error) && isString(error.message);
559
+ }
560
+ function getMessage(data) {
561
+ if (data instanceof Error) {
562
+ return data.message;
563
+ } else if (isString(data)) {
564
+ return data;
565
+ } else if (isErrorWithMessage(data)) {
566
+ return data.message;
567
+ } else if (isBulkError(data)) {
568
+ return "Bulk operation failed";
569
+ } else {
570
+ return "Unexpected error";
571
+ }
572
+ }
573
+
574
+ function getHostUrl(provider, type) {
575
+ if (isHostProviderAlias(provider)) {
576
+ return providers[provider][type];
577
+ } else if (isHostProviderBuilder(provider)) {
578
+ return provider[type];
579
+ }
580
+ throw new Error("Invalid API provider");
581
+ }
582
+ const providers = {
583
+ production: {
584
+ main: "https://api.xata.io",
585
+ workspaces: "https://{workspaceId}.{region}.xata.sh"
586
+ },
587
+ staging: {
588
+ main: "https://api.staging-xata.dev",
589
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
590
+ },
591
+ dev: {
592
+ main: "https://api.dev-xata.dev",
593
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
594
+ },
595
+ local: {
596
+ main: "http://localhost:6001",
597
+ workspaces: "http://{workspaceId}.{region}.localhost:6001"
598
+ }
599
+ };
600
+ function isHostProviderAlias(alias) {
601
+ return isString(alias) && Object.keys(providers).includes(alias);
602
+ }
603
+ function isHostProviderBuilder(builder) {
604
+ return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
605
+ }
606
+ function parseProviderString(provider = "production") {
607
+ if (isHostProviderAlias(provider)) {
608
+ return provider;
609
+ }
610
+ const [main, workspaces] = provider.split(",");
611
+ if (!main || !workspaces)
612
+ return null;
613
+ return { main, workspaces };
614
+ }
615
+ function buildProviderString(provider) {
616
+ if (isHostProviderAlias(provider))
617
+ return provider;
618
+ return `${provider.main},${provider.workspaces}`;
619
+ }
620
+ function parseWorkspacesUrlParts(url) {
621
+ if (!isString(url))
622
+ return null;
623
+ const matches = {
624
+ production: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/),
625
+ staging: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/),
626
+ dev: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/),
627
+ local: url.match(/(?:https?:\/\/)?([^.]+)(?:\.([^.]+))\.localhost:(\d+)/)
628
+ };
629
+ const [host, match] = Object.entries(matches).find(([, match2]) => match2 !== null) ?? [];
630
+ if (!isHostProviderAlias(host) || !match)
631
+ return null;
632
+ return { workspace: match[1], region: match[2], host };
633
+ }
634
+
635
+ const pool = new ApiRequestPool();
636
+ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
637
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
638
+ if (value === void 0 || value === null)
639
+ return acc;
640
+ return { ...acc, [key]: value };
641
+ }, {});
642
+ const query = new URLSearchParams(cleanQueryParams).toString();
643
+ const queryString = query.length > 0 ? `?${query}` : "";
644
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
645
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
646
+ }, {});
647
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
648
+ };
649
+ function buildBaseUrl({
650
+ method,
651
+ endpoint,
652
+ path,
653
+ workspacesApiUrl,
654
+ apiUrl,
655
+ pathParams = {}
656
+ }) {
657
+ if (endpoint === "dataPlane") {
658
+ let url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
659
+ if (method.toUpperCase() === "PUT" && [
660
+ "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
661
+ "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}"
662
+ ].includes(path)) {
663
+ const { host } = parseWorkspacesUrlParts(url) ?? {};
664
+ switch (host) {
665
+ case "production":
666
+ url = url.replace("xata.sh", "upload.xata.sh");
667
+ break;
668
+ case "staging":
669
+ url = url.replace("staging-xata.dev", "upload.staging-xata.dev");
670
+ break;
671
+ case "dev":
672
+ url = url.replace("dev-xata.dev", "upload.dev-xata.dev");
673
+ break;
674
+ }
675
+ }
676
+ const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
677
+ return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
678
+ }
679
+ return `${apiUrl}${path}`;
680
+ }
681
+ function hostHeader(url) {
682
+ const pattern = /.*:\/\/(?<host>[^/]+).*/;
683
+ const { groups } = pattern.exec(url) ?? {};
684
+ return groups?.host ? { Host: groups.host } : {};
685
+ }
686
+ async function parseBody(body, headers) {
687
+ if (!isDefined(body))
688
+ return void 0;
689
+ if (isBlob(body) || typeof body.text === "function") {
690
+ return body;
691
+ }
692
+ const { "Content-Type": contentType } = headers ?? {};
693
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
694
+ return JSON.stringify(body);
695
+ }
696
+ return body;
697
+ }
698
+ const defaultClientID = generateUUID();
699
+ async function fetch$1({
700
+ url: path,
701
+ method,
702
+ body,
703
+ headers: customHeaders,
704
+ pathParams,
705
+ queryParams,
706
+ fetch: fetch2,
707
+ apiKey,
708
+ endpoint,
709
+ apiUrl,
710
+ workspacesApiUrl,
711
+ trace,
712
+ signal,
713
+ clientID,
714
+ sessionID,
715
+ clientName,
716
+ xataAgentExtra,
717
+ fetchOptions = {},
718
+ rawResponse = false
719
+ }) {
720
+ pool.setFetch(fetch2);
721
+ return await trace(
722
+ `${method.toUpperCase()} ${path}`,
723
+ async ({ setAttributes }) => {
724
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
725
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
726
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\.[^.]+\./, "http://") : fullUrl;
727
+ setAttributes({
728
+ [TraceAttributes.HTTP_URL]: url,
729
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
730
+ });
731
+ const xataAgent = compact([
732
+ ["client", "TS_SDK"],
733
+ ["version", VERSION],
734
+ isDefined(clientName) ? ["service", clientName] : void 0,
735
+ ...Object.entries(xataAgentExtra ?? {})
736
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
737
+ const headers = compactObject({
738
+ "Accept-Encoding": "identity",
739
+ "Content-Type": "application/json",
740
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
741
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
742
+ "X-Xata-Agent": xataAgent,
743
+ ...customHeaders,
744
+ ...hostHeader(fullUrl),
745
+ Authorization: `Bearer ${apiKey}`
746
+ });
747
+ const response = await pool.request(url, {
748
+ ...fetchOptions,
749
+ method: method.toUpperCase(),
750
+ body: await parseBody(body, headers),
751
+ headers,
752
+ signal
753
+ });
754
+ const { host, protocol } = parseUrl(response.url);
755
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
756
+ setAttributes({
757
+ [TraceAttributes.KIND]: "http",
758
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
759
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
760
+ [TraceAttributes.HTTP_HOST]: host,
761
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
762
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
763
+ });
764
+ const message = response.headers?.get("x-xata-message");
765
+ if (message)
766
+ console.warn(message);
767
+ if (response.status === 204) {
768
+ return {};
769
+ }
770
+ if (response.status === 429) {
771
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
772
+ }
773
+ try {
774
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
775
+ if (response.ok) {
776
+ return jsonResponse;
777
+ }
778
+ throw new FetcherError(response.status, jsonResponse, requestId);
779
+ } catch (error) {
780
+ throw new FetcherError(response.status, error, requestId);
781
+ }
782
+ },
783
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
784
+ );
785
+ }
786
+ function fetchSSERequest({
787
+ url: path,
788
+ method,
789
+ body,
790
+ headers: customHeaders,
791
+ pathParams,
792
+ queryParams,
793
+ fetch: fetch2,
794
+ apiKey,
795
+ endpoint,
796
+ apiUrl,
797
+ workspacesApiUrl,
798
+ onMessage,
799
+ onError,
800
+ onClose,
801
+ signal,
802
+ clientID,
803
+ sessionID,
804
+ clientName,
805
+ xataAgentExtra
806
+ }) {
807
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
808
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
809
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
810
+ void fetchEventSource(url, {
811
+ method,
812
+ body: JSON.stringify(body),
813
+ fetch: fetch2,
814
+ signal,
815
+ headers: {
816
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
817
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
818
+ "X-Xata-Agent": compact([
819
+ ["client", "TS_SDK"],
820
+ ["version", VERSION],
821
+ isDefined(clientName) ? ["service", clientName] : void 0,
822
+ ...Object.entries(xataAgentExtra ?? {})
823
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
824
+ ...customHeaders,
825
+ Authorization: `Bearer ${apiKey}`,
826
+ "Content-Type": "application/json"
827
+ },
828
+ onmessage(ev) {
829
+ onMessage?.(JSON.parse(ev.data));
830
+ },
831
+ onerror(ev) {
832
+ onError?.(JSON.parse(ev.data));
833
+ },
834
+ onclose() {
835
+ onClose?.();
836
+ }
837
+ });
838
+ }
839
+ function parseUrl(url) {
840
+ try {
841
+ const { host, protocol } = new URL(url);
842
+ return { host, protocol };
843
+ } catch (error) {
844
+ return {};
845
+ }
846
+ }
847
+
848
+ const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
849
+
850
+ const applyMigration = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/apply", method: "post", ...variables, signal });
851
+ const adaptTable = (variables, signal) => dataPlaneFetch({
852
+ url: "/db/{dbBranchName}/migrations/adapt/{tableName}",
853
+ method: "post",
854
+ ...variables,
855
+ signal
856
+ });
857
+ const getBranchMigrationJobStatus = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/status", method: "get", ...variables, signal });
858
+ const getMigrationJobStatus = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/jobs/{jobId}", method: "get", ...variables, signal });
859
+ const getMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/history", method: "get", ...variables, signal });
860
+ const getBranchList = (variables, signal) => dataPlaneFetch({
861
+ url: "/dbs/{dbName}",
862
+ method: "get",
863
+ ...variables,
864
+ signal
865
+ });
866
+ const getDatabaseSettings = (variables, signal) => dataPlaneFetch({
867
+ url: "/dbs/{dbName}/settings",
868
+ method: "get",
869
+ ...variables,
870
+ signal
871
+ });
872
+ const updateDatabaseSettings = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/settings", method: "patch", ...variables, signal });
873
+ const getBranchDetails = (variables, signal) => dataPlaneFetch({
874
+ url: "/db/{dbBranchName}",
875
+ method: "get",
876
+ ...variables,
877
+ signal
878
+ });
879
+ const createBranch = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
880
+ const deleteBranch = (variables, signal) => dataPlaneFetch({
881
+ url: "/db/{dbBranchName}",
882
+ method: "delete",
883
+ ...variables,
884
+ signal
885
+ });
886
+ const getSchema = (variables, signal) => dataPlaneFetch({
887
+ url: "/db/{dbBranchName}/schema",
888
+ method: "get",
889
+ ...variables,
890
+ signal
891
+ });
892
+ const copyBranch = (variables, signal) => dataPlaneFetch({
893
+ url: "/db/{dbBranchName}/copy",
894
+ method: "post",
895
+ ...variables,
896
+ signal
897
+ });
898
+ const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
899
+ url: "/db/{dbBranchName}/metadata",
900
+ method: "put",
901
+ ...variables,
902
+ signal
903
+ });
904
+ const getBranchMetadata = (variables, signal) => dataPlaneFetch({
905
+ url: "/db/{dbBranchName}/metadata",
906
+ method: "get",
907
+ ...variables,
908
+ signal
909
+ });
910
+ const getBranchStats = (variables, signal) => dataPlaneFetch({
911
+ url: "/db/{dbBranchName}/stats",
912
+ method: "get",
913
+ ...variables,
914
+ signal
915
+ });
916
+ const getGitBranchesMapping = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables, signal });
917
+ const addGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables, signal });
918
+ const removeGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables, signal });
919
+ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/resolveBranch", method: "get", ...variables, signal });
920
+ const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
921
+ const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
922
+ const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
923
+ const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
924
+ const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
925
+ const getMigrationRequest = (variables, signal) => dataPlaneFetch({
926
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
927
+ method: "get",
928
+ ...variables,
929
+ signal
930
+ });
931
+ const updateMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables, signal });
932
+ const listMigrationRequestsCommits = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables, signal });
933
+ const compareMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables, signal });
934
+ const getMigrationRequestIsMerged = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables, signal });
935
+ const mergeMigrationRequest = (variables, signal) => dataPlaneFetch({
936
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
937
+ method: "post",
938
+ ...variables,
939
+ signal
940
+ });
941
+ const getBranchSchemaHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables, signal });
942
+ const compareBranchWithUserSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables, signal });
943
+ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables, signal });
944
+ const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
945
+ const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
946
+ const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
947
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
948
+ const createTable = (variables, signal) => dataPlaneFetch({
949
+ url: "/db/{dbBranchName}/tables/{tableName}",
950
+ method: "put",
951
+ ...variables,
952
+ signal
953
+ });
954
+ const deleteTable = (variables, signal) => dataPlaneFetch({
955
+ url: "/db/{dbBranchName}/tables/{tableName}",
956
+ method: "delete",
957
+ ...variables,
958
+ signal
959
+ });
960
+ const updateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}", method: "patch", ...variables, signal });
961
+ const getTableSchema = (variables, signal) => dataPlaneFetch({
962
+ url: "/db/{dbBranchName}/tables/{tableName}/schema",
963
+ method: "get",
964
+ ...variables,
965
+ signal
966
+ });
967
+ const setTableSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/schema", method: "put", ...variables, signal });
968
+ const getTableColumns = (variables, signal) => dataPlaneFetch({
969
+ url: "/db/{dbBranchName}/tables/{tableName}/columns",
970
+ method: "get",
971
+ ...variables,
972
+ signal
973
+ });
974
+ const addTableColumn = (variables, signal) => dataPlaneFetch(
975
+ { url: "/db/{dbBranchName}/tables/{tableName}/columns", method: "post", ...variables, signal }
976
+ );
977
+ const getColumn = (variables, signal) => dataPlaneFetch({
978
+ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
979
+ method: "get",
980
+ ...variables,
981
+ signal
982
+ });
983
+ const updateColumn = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}", method: "patch", ...variables, signal });
984
+ const deleteColumn = (variables, signal) => dataPlaneFetch({
985
+ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
986
+ method: "delete",
987
+ ...variables,
988
+ signal
989
+ });
990
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
991
+ const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
992
+ const getFileItem = (variables, signal) => dataPlaneFetch({
993
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
994
+ method: "get",
995
+ ...variables,
996
+ signal
997
+ });
998
+ const putFileItem = (variables, signal) => dataPlaneFetch({
999
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
1000
+ method: "put",
1001
+ ...variables,
1002
+ signal
1003
+ });
1004
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
1005
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
1006
+ method: "delete",
1007
+ ...variables,
1008
+ signal
1009
+ });
1010
+ const getFile = (variables, signal) => dataPlaneFetch({
1011
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1012
+ method: "get",
1013
+ ...variables,
1014
+ signal
1015
+ });
1016
+ const putFile = (variables, signal) => dataPlaneFetch({
1017
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1018
+ method: "put",
1019
+ ...variables,
1020
+ signal
1021
+ });
1022
+ const deleteFile = (variables, signal) => dataPlaneFetch({
1023
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1024
+ method: "delete",
1025
+ ...variables,
1026
+ signal
1027
+ });
1028
+ const getRecord = (variables, signal) => dataPlaneFetch({
1029
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
1030
+ method: "get",
1031
+ ...variables,
1032
+ signal
1033
+ });
1034
+ const insertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables, signal });
1035
+ const updateRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables, signal });
1036
+ const upsertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables, signal });
1037
+ const deleteRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "delete", ...variables, signal });
1038
+ const bulkInsertTableRecords = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables, signal });
1039
+ const queryTable = (variables, signal) => dataPlaneFetch({
1040
+ url: "/db/{dbBranchName}/tables/{tableName}/query",
1041
+ method: "post",
1042
+ ...variables,
1043
+ signal
1044
+ });
1045
+ const searchBranch = (variables, signal) => dataPlaneFetch({
1046
+ url: "/db/{dbBranchName}/search",
1047
+ method: "post",
1048
+ ...variables,
1049
+ signal
1050
+ });
1051
+ const searchTable = (variables, signal) => dataPlaneFetch({
1052
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
1053
+ method: "post",
1054
+ ...variables,
1055
+ signal
1056
+ });
1057
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
1058
+ const askTable = (variables, signal) => dataPlaneFetch({
1059
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
1060
+ method: "post",
1061
+ ...variables,
1062
+ signal
1063
+ });
1064
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
1065
+ const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
1066
+ const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
1067
+ const fileAccess = (variables, signal) => dataPlaneFetch({
1068
+ url: "/file/{fileId}",
1069
+ method: "get",
1070
+ ...variables,
1071
+ signal
1072
+ });
1073
+ const fileUpload = (variables, signal) => dataPlaneFetch({
1074
+ url: "/file/{fileId}",
1075
+ method: "put",
1076
+ ...variables,
1077
+ signal
1078
+ });
1079
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
1080
+ url: "/db/{dbBranchName}/sql",
1081
+ method: "post",
1082
+ ...variables,
1083
+ signal
1084
+ });
1085
+ const operationsByTag$2 = {
1086
+ migrations: {
1087
+ applyMigration,
1088
+ adaptTable,
1089
+ getBranchMigrationJobStatus,
1090
+ getMigrationJobStatus,
1091
+ getMigrationHistory,
1092
+ getSchema,
1093
+ getBranchMigrationHistory,
1094
+ getBranchMigrationPlan,
1095
+ executeBranchMigrationPlan,
1096
+ getBranchSchemaHistory,
1097
+ compareBranchWithUserSchema,
1098
+ compareBranchSchemas,
1099
+ updateBranchSchema,
1100
+ previewBranchSchemaEdit,
1101
+ applyBranchSchemaEdit,
1102
+ pushBranchMigrations
1103
+ },
1104
+ branch: {
1105
+ getBranchList,
1106
+ getBranchDetails,
1107
+ createBranch,
1108
+ deleteBranch,
1109
+ copyBranch,
1110
+ updateBranchMetadata,
1111
+ getBranchMetadata,
1112
+ getBranchStats,
1113
+ getGitBranchesMapping,
1114
+ addGitBranchesEntry,
1115
+ removeGitBranchesEntry,
1116
+ resolveBranch
1117
+ },
1118
+ database: { getDatabaseSettings, updateDatabaseSettings },
1119
+ migrationRequests: {
1120
+ queryMigrationRequests,
1121
+ createMigrationRequest,
1122
+ getMigrationRequest,
1123
+ updateMigrationRequest,
1124
+ listMigrationRequestsCommits,
1125
+ compareMigrationRequest,
1126
+ getMigrationRequestIsMerged,
1127
+ mergeMigrationRequest
1128
+ },
1129
+ table: {
1130
+ createTable,
1131
+ deleteTable,
1132
+ updateTable,
1133
+ getTableSchema,
1134
+ setTableSchema,
1135
+ getTableColumns,
1136
+ addTableColumn,
1137
+ getColumn,
1138
+ updateColumn,
1139
+ deleteColumn
1140
+ },
1141
+ records: {
1142
+ branchTransaction,
1143
+ insertRecord,
1144
+ getRecord,
1145
+ insertRecordWithID,
1146
+ updateRecordWithID,
1147
+ upsertRecordWithID,
1148
+ deleteRecord,
1149
+ bulkInsertTableRecords
1150
+ },
1151
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess, fileUpload },
1152
+ searchAndFilter: {
1153
+ queryTable,
1154
+ searchBranch,
1155
+ searchTable,
1156
+ vectorSearchTable,
1157
+ askTable,
1158
+ askTableSession,
1159
+ summarizeTable,
1160
+ aggregateTable
1161
+ },
1162
+ sql: { sqlQuery }
1163
+ };
1164
+
1165
+ const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
1166
+
1167
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1168
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
1169
+ const getUser = (variables, signal) => controlPlaneFetch({
1170
+ url: "/user",
1171
+ method: "get",
1172
+ ...variables,
1173
+ signal
1174
+ });
1175
+ const updateUser = (variables, signal) => controlPlaneFetch({
1176
+ url: "/user",
1177
+ method: "put",
1178
+ ...variables,
1179
+ signal
1180
+ });
1181
+ const deleteUser = (variables, signal) => controlPlaneFetch({
1182
+ url: "/user",
1183
+ method: "delete",
1184
+ ...variables,
1185
+ signal
1186
+ });
1187
+ const getUserAPIKeys = (variables, signal) => controlPlaneFetch({
1188
+ url: "/user/keys",
1189
+ method: "get",
1190
+ ...variables,
1191
+ signal
1192
+ });
1193
+ const createUserAPIKey = (variables, signal) => controlPlaneFetch({
1194
+ url: "/user/keys/{keyName}",
1195
+ method: "post",
1196
+ ...variables,
1197
+ signal
1198
+ });
1199
+ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
1200
+ url: "/user/keys/{keyName}",
1201
+ method: "delete",
1202
+ ...variables,
1203
+ signal
1204
+ });
1205
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1206
+ url: "/user/oauth/clients",
1207
+ method: "get",
1208
+ ...variables,
1209
+ signal
1210
+ });
1211
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1212
+ url: "/user/oauth/clients/{clientId}",
1213
+ method: "delete",
1214
+ ...variables,
1215
+ signal
1216
+ });
1217
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1218
+ url: "/user/oauth/tokens",
1219
+ method: "get",
1220
+ ...variables,
1221
+ signal
1222
+ });
1223
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1224
+ url: "/user/oauth/tokens/{token}",
1225
+ method: "delete",
1226
+ ...variables,
1227
+ signal
1228
+ });
1229
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
1230
+ const getWorkspacesList = (variables, signal) => controlPlaneFetch({
1231
+ url: "/workspaces",
1232
+ method: "get",
1233
+ ...variables,
1234
+ signal
1235
+ });
1236
+ const createWorkspace = (variables, signal) => controlPlaneFetch({
1237
+ url: "/workspaces",
1238
+ method: "post",
1239
+ ...variables,
1240
+ signal
1241
+ });
1242
+ const getWorkspace = (variables, signal) => controlPlaneFetch({
1243
+ url: "/workspaces/{workspaceId}",
1244
+ method: "get",
1245
+ ...variables,
1246
+ signal
1247
+ });
1248
+ const updateWorkspace = (variables, signal) => controlPlaneFetch({
1249
+ url: "/workspaces/{workspaceId}",
1250
+ method: "put",
1251
+ ...variables,
1252
+ signal
1253
+ });
1254
+ const deleteWorkspace = (variables, signal) => controlPlaneFetch({
1255
+ url: "/workspaces/{workspaceId}",
1256
+ method: "delete",
1257
+ ...variables,
1258
+ signal
1259
+ });
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
+ getWorkspaceMembersList,
1326
+ updateWorkspaceMemberRole,
1327
+ removeWorkspaceMember
1328
+ },
1329
+ invites: {
1330
+ inviteWorkspaceMember,
1331
+ updateWorkspaceMemberInvite,
1332
+ cancelWorkspaceMemberInvite,
1333
+ acceptWorkspaceMemberInvite,
1334
+ resendWorkspaceMemberInvite
1335
+ },
1336
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
1337
+ databases: {
1338
+ getDatabaseList,
1339
+ createDatabase,
1340
+ deleteDatabase,
1341
+ getDatabaseMetadata,
1342
+ updateDatabaseMetadata,
1343
+ renameDatabase,
1344
+ getDatabaseGithubSettings,
1345
+ updateDatabaseGithubSettings,
1346
+ deleteDatabaseGithubSettings,
1347
+ listRegions
1348
+ }
1349
+ };
1350
+
1351
+ const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);
1352
+
1353
+ const buildApiClient = () => class {
1354
+ constructor(options = {}) {
1355
+ const provider = options.host ?? "production";
1356
+ const apiKey = options.apiKey ?? getAPIKey();
1357
+ const trace = options.trace ?? defaultTrace;
1358
+ const clientID = generateUUID();
1359
+ if (!apiKey) {
1360
+ throw new Error("Could not resolve a valid apiKey");
1361
+ }
1362
+ const extraProps = {
1363
+ apiUrl: getHostUrl(provider, "main"),
1364
+ workspacesApiUrl: getHostUrl(provider, "workspaces"),
1365
+ fetch: getFetchImplementation(options.fetch),
1366
+ apiKey,
1367
+ trace,
1368
+ clientName: options.clientName,
1369
+ xataAgentExtra: options.xataAgentExtra,
1370
+ clientID
1371
+ };
1372
+ return new Proxy(this, {
1373
+ get: (_target, namespace) => {
1374
+ if (operationsByTag[namespace] === void 0) {
1375
+ return void 0;
1376
+ }
1377
+ return new Proxy(
1378
+ {},
1379
+ {
1380
+ get: (_target2, operation) => {
1381
+ if (operationsByTag[namespace][operation] === void 0) {
1382
+ return void 0;
1383
+ }
1384
+ const method = operationsByTag[namespace][operation];
1385
+ return async (params) => {
1386
+ return await method({ ...params, ...extraProps });
1387
+ };
1388
+ }
1389
+ }
1390
+ );
1391
+ }
1392
+ });
1393
+ }
1394
+ };
1395
+ class XataApiClient extends buildApiClient() {
1396
+ }
1397
+
1398
+ class XataApiPlugin {
1399
+ build(options) {
1400
+ return new XataApiClient(options);
1401
+ }
1402
+ }
1403
+
1404
+ class XataPlugin {
1405
+ }
1406
+
1407
+ function buildTransformString(transformations) {
1408
+ return transformations.flatMap(
1409
+ (t) => Object.entries(t).map(([key, value]) => {
1410
+ if (key === "trim") {
1411
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
1412
+ return `${key}=${[top, right, bottom, left].join(";")}`;
1413
+ }
1414
+ if (key === "gravity" && typeof value === "object") {
1415
+ const { x = 0.5, y = 0.5 } = value;
1416
+ return `${key}=${[x, y].join("x")}`;
1417
+ }
1418
+ return `${key}=${value}`;
1419
+ })
1420
+ ).join(",");
1421
+ }
1422
+ function transformImage(url, ...transformations) {
1423
+ if (!isDefined(url))
1424
+ return void 0;
1425
+ const newTransformations = buildTransformString(transformations);
1426
+ const { hostname, pathname, search } = new URL(url);
1427
+ const pathParts = pathname.split("/");
1428
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
1429
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
1430
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
1431
+ const path = pathParts.join("/");
1432
+ return `https://${hostname}${transform}${path}${search}`;
1433
+ }
1434
+
1435
+ class XataFile {
1436
+ constructor(file) {
1437
+ this.id = file.id;
1438
+ this.name = file.name;
1439
+ this.mediaType = file.mediaType;
1440
+ this.base64Content = file.base64Content;
1441
+ this.enablePublicUrl = file.enablePublicUrl;
1442
+ this.signedUrlTimeout = file.signedUrlTimeout;
1443
+ this.uploadUrlTimeout = file.uploadUrlTimeout;
1444
+ this.size = file.size;
1445
+ this.version = file.version;
1446
+ this.url = file.url;
1447
+ this.signedUrl = file.signedUrl;
1448
+ this.uploadUrl = file.uploadUrl;
1449
+ this.attributes = file.attributes;
1450
+ }
1451
+ static fromBuffer(buffer, options = {}) {
1452
+ const base64Content = buffer.toString("base64");
1453
+ return new XataFile({ ...options, base64Content });
1454
+ }
1455
+ toBuffer() {
1456
+ if (!this.base64Content) {
1457
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
1458
+ }
1459
+ return Buffer.from(this.base64Content, "base64");
1460
+ }
1461
+ static fromArrayBuffer(arrayBuffer, options = {}) {
1462
+ const uint8Array = new Uint8Array(arrayBuffer);
1463
+ return this.fromUint8Array(uint8Array, options);
1464
+ }
1465
+ toArrayBuffer() {
1466
+ if (!this.base64Content) {
1467
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
1468
+ }
1469
+ const binary = atob(this.base64Content);
1470
+ return new ArrayBuffer(binary.length);
1471
+ }
1472
+ static fromUint8Array(uint8Array, options = {}) {
1473
+ let binary = "";
1474
+ for (let i = 0; i < uint8Array.byteLength; i++) {
1475
+ binary += String.fromCharCode(uint8Array[i]);
1476
+ }
1477
+ const base64Content = btoa(binary);
1478
+ return new XataFile({ ...options, base64Content });
1479
+ }
1480
+ toUint8Array() {
1481
+ if (!this.base64Content) {
1482
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
1483
+ }
1484
+ const binary = atob(this.base64Content);
1485
+ const uint8Array = new Uint8Array(binary.length);
1486
+ for (let i = 0; i < binary.length; i++) {
1487
+ uint8Array[i] = binary.charCodeAt(i);
1488
+ }
1489
+ return uint8Array;
1490
+ }
1491
+ static async fromBlob(file, options = {}) {
1492
+ const name = options.name ?? file.name;
1493
+ const mediaType = file.type;
1494
+ const arrayBuffer = await file.arrayBuffer();
1495
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
1496
+ }
1497
+ toBlob() {
1498
+ if (!this.base64Content) {
1499
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
1500
+ }
1501
+ const binary = atob(this.base64Content);
1502
+ const uint8Array = new Uint8Array(binary.length);
1503
+ for (let i = 0; i < binary.length; i++) {
1504
+ uint8Array[i] = binary.charCodeAt(i);
1505
+ }
1506
+ return new Blob([uint8Array], { type: this.mediaType });
1507
+ }
1508
+ static fromString(string, options = {}) {
1509
+ const base64Content = btoa(string);
1510
+ return new XataFile({ ...options, base64Content });
1511
+ }
1512
+ toString() {
1513
+ if (!this.base64Content) {
1514
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
1515
+ }
1516
+ return atob(this.base64Content);
1517
+ }
1518
+ static fromBase64(base64Content, options = {}) {
1519
+ return new XataFile({ ...options, base64Content });
1520
+ }
1521
+ toBase64() {
1522
+ if (!this.base64Content) {
1523
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
1524
+ }
1525
+ return this.base64Content;
1526
+ }
1527
+ transform(...options) {
1528
+ return {
1529
+ url: transformImage(this.url, ...options),
1530
+ signedUrl: transformImage(this.signedUrl, ...options),
1531
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
1532
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
1533
+ };
1534
+ }
1535
+ }
1536
+ const parseInputFileEntry = async (entry) => {
1537
+ if (!isDefined(entry))
1538
+ return null;
1539
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout, uploadUrlTimeout } = await entry;
1540
+ return compactObject({
1541
+ id,
1542
+ // Name cannot be an empty string in our API
1543
+ name: name ? name : void 0,
1544
+ mediaType,
1545
+ base64Content,
1546
+ enablePublicUrl,
1547
+ signedUrlTimeout,
1548
+ uploadUrlTimeout
1549
+ });
1550
+ };
1551
+
1552
+ function cleanFilter(filter) {
1553
+ if (!isDefined(filter))
1554
+ return void 0;
1555
+ if (!isObject(filter))
1556
+ return filter;
1557
+ const values = Object.fromEntries(
1558
+ Object.entries(filter).reduce((acc, [key, value]) => {
1559
+ if (!isDefined(value))
1560
+ return acc;
1561
+ if (Array.isArray(value)) {
1562
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
1563
+ if (clean.length === 0)
1564
+ return acc;
1565
+ return [...acc, [key, clean]];
1566
+ }
1567
+ if (isObject(value)) {
1568
+ const clean = cleanFilter(value);
1569
+ if (!isDefined(clean))
1570
+ return acc;
1571
+ return [...acc, [key, clean]];
1572
+ }
1573
+ return [...acc, [key, value]];
1574
+ }, [])
1575
+ );
1576
+ return Object.keys(values).length > 0 ? values : void 0;
1577
+ }
1578
+
1579
+ function stringifyJson(value) {
1580
+ if (!isDefined(value))
1581
+ return value;
1582
+ if (isString(value))
1583
+ return value;
1584
+ try {
1585
+ return JSON.stringify(value);
1586
+ } catch (e) {
1587
+ return value;
1588
+ }
1589
+ }
1590
+ function parseJson(value) {
1591
+ try {
1592
+ return JSON.parse(value);
1593
+ } catch (e) {
1594
+ return value;
1595
+ }
1596
+ }
1597
+
1598
+ var __accessCheck$5 = (obj, member, msg) => {
1599
+ if (!member.has(obj))
1600
+ throw TypeError("Cannot " + msg);
1601
+ };
1602
+ var __privateGet$4 = (obj, member, getter) => {
1603
+ __accessCheck$5(obj, member, "read from private field");
1604
+ return getter ? getter.call(obj) : member.get(obj);
1605
+ };
1606
+ var __privateAdd$5 = (obj, member, value) => {
1607
+ if (member.has(obj))
1608
+ throw TypeError("Cannot add the same private member more than once");
1609
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1610
+ };
1611
+ var __privateSet$3 = (obj, member, value, setter) => {
1612
+ __accessCheck$5(obj, member, "write to private field");
1613
+ setter ? setter.call(obj, value) : member.set(obj, value);
1614
+ return value;
1615
+ };
1616
+ var _query, _page;
1617
+ class Page {
1618
+ constructor(query, meta, records = []) {
1619
+ __privateAdd$5(this, _query, void 0);
1620
+ __privateSet$3(this, _query, query);
1621
+ this.meta = meta;
1622
+ this.records = new PageRecordArray(this, records);
1623
+ }
1624
+ /**
1625
+ * Retrieves the next page of results.
1626
+ * @param size Maximum number of results to be retrieved.
1627
+ * @param offset Number of results to skip when retrieving the results.
1628
+ * @returns The next page or results.
1629
+ */
1630
+ async nextPage(size, offset) {
1631
+ return __privateGet$4(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
1632
+ }
1633
+ /**
1634
+ * Retrieves the previous page of results.
1635
+ * @param size Maximum number of results to be retrieved.
1636
+ * @param offset Number of results to skip when retrieving the results.
1637
+ * @returns The previous page or results.
1638
+ */
1639
+ async previousPage(size, offset) {
1640
+ return __privateGet$4(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1641
+ }
1642
+ /**
1643
+ * Retrieves the start page of results.
1644
+ * @param size Maximum number of results to be retrieved.
1645
+ * @param offset Number of results to skip when retrieving the results.
1646
+ * @returns The start page or results.
1647
+ */
1648
+ async startPage(size, offset) {
1649
+ return __privateGet$4(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1650
+ }
1651
+ /**
1652
+ * Retrieves the end page of results.
1653
+ * @param size Maximum number of results to be retrieved.
1654
+ * @param offset Number of results to skip when retrieving the results.
1655
+ * @returns The end page or results.
1656
+ */
1657
+ async endPage(size, offset) {
1658
+ return __privateGet$4(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1659
+ }
1660
+ /**
1661
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
1662
+ * @returns Whether or not there will be additional results in the next page of results.
1663
+ */
1664
+ hasNextPage() {
1665
+ return this.meta.page.more;
1666
+ }
1667
+ }
1668
+ _query = new WeakMap();
1669
+ const PAGINATION_MAX_SIZE = 1e3;
1670
+ const PAGINATION_DEFAULT_SIZE = 20;
1671
+ const PAGINATION_MAX_OFFSET = 49e3;
1672
+ const PAGINATION_DEFAULT_OFFSET = 0;
1673
+ function isCursorPaginationOptions(options) {
1674
+ return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1675
+ }
1676
+ class RecordArray extends Array {
1677
+ constructor(...args) {
1678
+ super(...RecordArray.parseConstructorParams(...args));
1679
+ }
1680
+ static parseConstructorParams(...args) {
1681
+ if (args.length === 1 && typeof args[0] === "number") {
1682
+ return new Array(args[0]);
1683
+ }
1684
+ if (args.length <= 1 && Array.isArray(args[0] ?? [])) {
1685
+ const result = args[0] ?? [];
1686
+ return new Array(...result);
1687
+ }
1688
+ return new Array(...args);
1689
+ }
1690
+ toArray() {
1691
+ return new Array(...this);
1692
+ }
1693
+ toSerializable() {
1694
+ return JSON.parse(this.toString());
1695
+ }
1696
+ toString() {
1697
+ return JSON.stringify(this.toArray());
1698
+ }
1699
+ map(callbackfn, thisArg) {
1700
+ return this.toArray().map(callbackfn, thisArg);
1701
+ }
1702
+ }
1703
+ const _PageRecordArray = class _PageRecordArray extends Array {
1704
+ constructor(...args) {
1705
+ super(..._PageRecordArray.parseConstructorParams(...args));
1706
+ __privateAdd$5(this, _page, void 0);
1707
+ __privateSet$3(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1708
+ }
1709
+ static parseConstructorParams(...args) {
1710
+ if (args.length === 1 && typeof args[0] === "number") {
1711
+ return new Array(args[0]);
1712
+ }
1713
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1714
+ const result = args[1] ?? args[0].records ?? [];
1715
+ return new Array(...result);
1716
+ }
1717
+ return new Array(...args);
1718
+ }
1719
+ toArray() {
1720
+ return new Array(...this);
1721
+ }
1722
+ toSerializable() {
1723
+ return JSON.parse(this.toString());
1724
+ }
1725
+ toString() {
1726
+ return JSON.stringify(this.toArray());
1727
+ }
1728
+ map(callbackfn, thisArg) {
1729
+ return this.toArray().map(callbackfn, thisArg);
1730
+ }
1731
+ /**
1732
+ * Retrieve next page of records
1733
+ *
1734
+ * @returns A new array of objects
1735
+ */
1736
+ async nextPage(size, offset) {
1737
+ const newPage = await __privateGet$4(this, _page).nextPage(size, offset);
1738
+ return new _PageRecordArray(newPage);
1739
+ }
1740
+ /**
1741
+ * Retrieve previous page of records
1742
+ *
1743
+ * @returns A new array of objects
1744
+ */
1745
+ async previousPage(size, offset) {
1746
+ const newPage = await __privateGet$4(this, _page).previousPage(size, offset);
1747
+ return new _PageRecordArray(newPage);
1748
+ }
1749
+ /**
1750
+ * Retrieve start page of records
1751
+ *
1752
+ * @returns A new array of objects
1753
+ */
1754
+ async startPage(size, offset) {
1755
+ const newPage = await __privateGet$4(this, _page).startPage(size, offset);
1756
+ return new _PageRecordArray(newPage);
1757
+ }
1758
+ /**
1759
+ * Retrieve end page of records
1760
+ *
1761
+ * @returns A new array of objects
1762
+ */
1763
+ async endPage(size, offset) {
1764
+ const newPage = await __privateGet$4(this, _page).endPage(size, offset);
1765
+ return new _PageRecordArray(newPage);
1766
+ }
1767
+ /**
1768
+ * @returns Boolean indicating if there is a next page
1769
+ */
1770
+ hasNextPage() {
1771
+ return __privateGet$4(this, _page).meta.page.more;
1772
+ }
1773
+ };
1774
+ _page = new WeakMap();
1775
+ let PageRecordArray = _PageRecordArray;
1776
+
1777
+ var __accessCheck$4 = (obj, member, msg) => {
1778
+ if (!member.has(obj))
1779
+ throw TypeError("Cannot " + msg);
1780
+ };
1781
+ var __privateGet$3 = (obj, member, getter) => {
1782
+ __accessCheck$4(obj, member, "read from private field");
1783
+ return getter ? getter.call(obj) : member.get(obj);
1784
+ };
1785
+ var __privateAdd$4 = (obj, member, value) => {
1786
+ if (member.has(obj))
1787
+ throw TypeError("Cannot add the same private member more than once");
1788
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1789
+ };
1790
+ var __privateSet$2 = (obj, member, value, setter) => {
1791
+ __accessCheck$4(obj, member, "write to private field");
1792
+ setter ? setter.call(obj, value) : member.set(obj, value);
1793
+ return value;
1794
+ };
1795
+ var __privateMethod$3 = (obj, member, method) => {
1796
+ __accessCheck$4(obj, member, "access private method");
1797
+ return method;
1798
+ };
1799
+ var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
1800
+ const _Query = class _Query {
1801
+ constructor(repository, table, data, rawParent) {
1802
+ __privateAdd$4(this, _cleanFilterConstraint);
1803
+ __privateAdd$4(this, _table$1, void 0);
1804
+ __privateAdd$4(this, _repository, void 0);
1805
+ __privateAdd$4(this, _data, { filter: {} });
1806
+ // Implements pagination
1807
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
1808
+ this.records = new PageRecordArray(this, []);
1809
+ __privateSet$2(this, _table$1, table);
1810
+ if (repository) {
1811
+ __privateSet$2(this, _repository, repository);
1812
+ } else {
1813
+ __privateSet$2(this, _repository, this);
1814
+ }
1815
+ const parent = cleanParent(data, rawParent);
1816
+ __privateGet$3(this, _data).filter = data.filter ?? parent?.filter ?? {};
1817
+ __privateGet$3(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1818
+ __privateGet$3(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1819
+ __privateGet$3(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1820
+ __privateGet$3(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1821
+ __privateGet$3(this, _data).sort = data.sort ?? parent?.sort;
1822
+ __privateGet$3(this, _data).columns = data.columns ?? parent?.columns;
1823
+ __privateGet$3(this, _data).consistency = data.consistency ?? parent?.consistency;
1824
+ __privateGet$3(this, _data).pagination = data.pagination ?? parent?.pagination;
1825
+ __privateGet$3(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
1826
+ this.any = this.any.bind(this);
1827
+ this.all = this.all.bind(this);
1828
+ this.not = this.not.bind(this);
1829
+ this.filter = this.filter.bind(this);
1830
+ this.sort = this.sort.bind(this);
1831
+ this.none = this.none.bind(this);
1832
+ Object.defineProperty(this, "table", { enumerable: false });
1833
+ Object.defineProperty(this, "repository", { enumerable: false });
1834
+ }
1835
+ getQueryOptions() {
1836
+ return __privateGet$3(this, _data);
1837
+ }
1838
+ key() {
1839
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$3(this, _data);
1840
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1841
+ return toBase64(key);
1842
+ }
1843
+ /**
1844
+ * Builds a new query object representing a logical OR between the given subqueries.
1845
+ * @param queries An array of subqueries.
1846
+ * @returns A new Query object.
1847
+ */
1848
+ any(...queries) {
1849
+ const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1850
+ return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $any } }, __privateGet$3(this, _data));
1851
+ }
1852
+ /**
1853
+ * Builds a new query object representing a logical AND between the given subqueries.
1854
+ * @param queries An array of subqueries.
1855
+ * @returns A new Query object.
1856
+ */
1857
+ all(...queries) {
1858
+ const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1859
+ return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1860
+ }
1861
+ /**
1862
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
1863
+ * @param queries An array of subqueries.
1864
+ * @returns A new Query object.
1865
+ */
1866
+ not(...queries) {
1867
+ const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1868
+ return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $not } }, __privateGet$3(this, _data));
1869
+ }
1870
+ /**
1871
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
1872
+ * @param queries An array of subqueries.
1873
+ * @returns A new Query object.
1874
+ */
1875
+ none(...queries) {
1876
+ const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1877
+ return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $none } }, __privateGet$3(this, _data));
1878
+ }
1879
+ filter(a, b) {
1880
+ if (arguments.length === 1) {
1881
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
1882
+ [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
1883
+ }));
1884
+ const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat(constraints));
1885
+ return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1886
+ } else {
1887
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
1888
+ const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat(constraints));
1889
+ return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1890
+ }
1891
+ }
1892
+ sort(column, direction = "asc") {
1893
+ const originalSort = [__privateGet$3(this, _data).sort ?? []].flat();
1894
+ const sort = [...originalSort, { column, direction }];
1895
+ return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { sort }, __privateGet$3(this, _data));
1896
+ }
1897
+ /**
1898
+ * Builds a new query specifying the set of columns to be returned in the query response.
1899
+ * @param columns Array of column names to be returned by the query.
1900
+ * @returns A new Query object.
1901
+ */
1902
+ select(columns) {
1903
+ return new _Query(
1904
+ __privateGet$3(this, _repository),
1905
+ __privateGet$3(this, _table$1),
1906
+ { columns },
1907
+ __privateGet$3(this, _data)
1908
+ );
1909
+ }
1910
+ getPaginated(options = {}) {
1911
+ const query = new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), options, __privateGet$3(this, _data));
1912
+ return __privateGet$3(this, _repository).query(query);
1913
+ }
1914
+ /**
1915
+ * Get results in an iterator
1916
+ *
1917
+ * @async
1918
+ * @returns Async interable of results
1919
+ */
1920
+ async *[Symbol.asyncIterator]() {
1921
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1922
+ yield record;
1923
+ }
1924
+ }
1925
+ async *getIterator(options = {}) {
1926
+ const { batchSize = 1 } = options;
1927
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1928
+ let more = page.hasNextPage();
1929
+ yield page.records;
1930
+ while (more) {
1931
+ page = await page.nextPage();
1932
+ more = page.hasNextPage();
1933
+ yield page.records;
1934
+ }
1935
+ }
1936
+ async getMany(options = {}) {
1937
+ const { pagination = {}, ...rest } = options;
1938
+ const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
1939
+ const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
1940
+ let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
1941
+ const results = [...page.records];
1942
+ while (page.hasNextPage() && results.length < size) {
1943
+ page = await page.nextPage();
1944
+ results.push(...page.records);
1945
+ }
1946
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1947
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1948
+ }
1949
+ const array = new PageRecordArray(page, results.slice(0, size));
1950
+ return array;
1951
+ }
1952
+ async getAll(options = {}) {
1953
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1954
+ const results = [];
1955
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1956
+ results.push(...page);
1957
+ }
1958
+ return new RecordArray(results);
1959
+ }
1960
+ async getFirst(options = {}) {
1961
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1962
+ return records[0] ?? null;
1963
+ }
1964
+ async getFirstOrThrow(options = {}) {
1965
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1966
+ if (records[0] === void 0)
1967
+ throw new Error("No results found.");
1968
+ return records[0];
1969
+ }
1970
+ async summarize(params = {}) {
1971
+ const { summaries, summariesFilter, ...options } = params;
1972
+ const query = new _Query(
1973
+ __privateGet$3(this, _repository),
1974
+ __privateGet$3(this, _table$1),
1975
+ options,
1976
+ __privateGet$3(this, _data)
1977
+ );
1978
+ return __privateGet$3(this, _repository).summarizeTable(query, summaries, summariesFilter);
1979
+ }
1980
+ /**
1981
+ * Retrieve next page of records
1982
+ *
1983
+ * @returns A new page object.
1984
+ */
1985
+ nextPage(size, offset) {
1986
+ return this.startPage(size, offset);
1987
+ }
1988
+ /**
1989
+ * Retrieve previous page of records
1990
+ *
1991
+ * @returns A new page object
1992
+ */
1993
+ previousPage(size, offset) {
1994
+ return this.startPage(size, offset);
1995
+ }
1996
+ /**
1997
+ * Retrieve start page of records
1998
+ *
1999
+ * @returns A new page object
2000
+ */
2001
+ startPage(size, offset) {
2002
+ return this.getPaginated({ pagination: { size, offset } });
2003
+ }
2004
+ /**
2005
+ * Retrieve last page of records
2006
+ *
2007
+ * @returns A new page object
2008
+ */
2009
+ endPage(size, offset) {
2010
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
2011
+ }
2012
+ /**
2013
+ * @returns Boolean indicating if there is a next page
2014
+ */
2015
+ hasNextPage() {
2016
+ return this.meta.page.more;
2017
+ }
2018
+ };
2019
+ _table$1 = new WeakMap();
2020
+ _repository = new WeakMap();
2021
+ _data = new WeakMap();
2022
+ _cleanFilterConstraint = new WeakSet();
2023
+ cleanFilterConstraint_fn = function(column, value) {
2024
+ const columnType = __privateGet$3(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
2025
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
2026
+ return { $includes: value };
2027
+ }
2028
+ if (columnType === "link" && isObject(value) && isString(value.id)) {
2029
+ return value.id;
2030
+ }
2031
+ return value;
2032
+ };
2033
+ let Query = _Query;
2034
+ function cleanParent(data, parent) {
2035
+ if (isCursorPaginationOptions(data.pagination)) {
2036
+ return { ...parent, sort: void 0, filter: void 0 };
2037
+ }
2038
+ return parent;
2039
+ }
2040
+
2041
+ const RecordColumnTypes = [
2042
+ "bool",
2043
+ "int",
2044
+ "float",
2045
+ "string",
2046
+ "text",
2047
+ "email",
2048
+ "multiple",
2049
+ "link",
2050
+ "datetime",
2051
+ "vector",
2052
+ "file[]",
2053
+ "file",
2054
+ "json"
2055
+ ];
2056
+ function isIdentifiable(x) {
2057
+ return isObject(x) && isString(x?.id);
2058
+ }
2059
+ function isXataRecord(x) {
2060
+ const record = x;
2061
+ const metadata = record?.getMetadata();
2062
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
2063
+ }
2064
+
2065
+ function isValidExpandedColumn(column) {
2066
+ return isObject(column) && isString(column.name);
2067
+ }
2068
+ function isValidSelectableColumns(columns) {
2069
+ if (!Array.isArray(columns)) {
2070
+ return false;
2071
+ }
2072
+ return columns.every((column) => {
2073
+ if (typeof column === "string") {
2074
+ return true;
2075
+ }
2076
+ if (typeof column === "object") {
2077
+ return isValidExpandedColumn(column);
2078
+ }
2079
+ return false;
2080
+ });
2081
+ }
2082
+
2083
+ function isSortFilterString(value) {
2084
+ return isString(value);
2085
+ }
2086
+ function isSortFilterBase(filter) {
2087
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
2088
+ if (key === "*")
2089
+ return value === "random";
2090
+ return value === "asc" || value === "desc";
2091
+ });
2092
+ }
2093
+ function isSortFilterObject(filter) {
2094
+ return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
2095
+ }
2096
+ function buildSortFilter(filter) {
2097
+ if (isSortFilterString(filter)) {
2098
+ return { [filter]: "asc" };
2099
+ } else if (Array.isArray(filter)) {
2100
+ return filter.map((item) => buildSortFilter(item));
2101
+ } else if (isSortFilterBase(filter)) {
2102
+ return filter;
2103
+ } else if (isSortFilterObject(filter)) {
2104
+ return { [filter.column]: filter.direction ?? "asc" };
2105
+ } else {
2106
+ throw new Error(`Invalid sort filter: ${filter}`);
2107
+ }
2108
+ }
2109
+
2110
+ var __accessCheck$3 = (obj, member, msg) => {
2111
+ if (!member.has(obj))
2112
+ throw TypeError("Cannot " + msg);
2113
+ };
2114
+ var __privateGet$2 = (obj, member, getter) => {
2115
+ __accessCheck$3(obj, member, "read from private field");
2116
+ return getter ? getter.call(obj) : member.get(obj);
2117
+ };
2118
+ var __privateAdd$3 = (obj, member, value) => {
2119
+ if (member.has(obj))
2120
+ throw TypeError("Cannot add the same private member more than once");
2121
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2122
+ };
2123
+ var __privateSet$1 = (obj, member, value, setter) => {
2124
+ __accessCheck$3(obj, member, "write to private field");
2125
+ setter ? setter.call(obj, value) : member.set(obj, value);
2126
+ return value;
2127
+ };
2128
+ var __privateMethod$2 = (obj, member, method) => {
2129
+ __accessCheck$3(obj, member, "access private method");
2130
+ return method;
2131
+ };
2132
+ var _table, _getFetchProps, _db, _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, _getSchemaTables, getSchemaTables_fn, _transformObjectToApi, transformObjectToApi_fn;
2133
+ const BULK_OPERATION_MAX_SIZE = 1e3;
2134
+ class Repository extends Query {
2135
+ }
2136
+ class RestRepository extends Query {
2137
+ constructor(options) {
2138
+ super(
2139
+ null,
2140
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
2141
+ {}
2142
+ );
2143
+ __privateAdd$3(this, _insertRecordWithoutId);
2144
+ __privateAdd$3(this, _insertRecordWithId);
2145
+ __privateAdd$3(this, _insertRecords);
2146
+ __privateAdd$3(this, _updateRecordWithID);
2147
+ __privateAdd$3(this, _updateRecords);
2148
+ __privateAdd$3(this, _upsertRecordWithID);
2149
+ __privateAdd$3(this, _deleteRecord);
2150
+ __privateAdd$3(this, _deleteRecords);
2151
+ __privateAdd$3(this, _getSchemaTables);
2152
+ __privateAdd$3(this, _transformObjectToApi);
2153
+ __privateAdd$3(this, _table, void 0);
2154
+ __privateAdd$3(this, _getFetchProps, void 0);
2155
+ __privateAdd$3(this, _db, void 0);
2156
+ __privateAdd$3(this, _schemaTables, void 0);
2157
+ __privateAdd$3(this, _trace, void 0);
2158
+ __privateSet$1(this, _table, options.table);
2159
+ __privateSet$1(this, _db, options.db);
2160
+ __privateSet$1(this, _schemaTables, options.schemaTables);
2161
+ __privateSet$1(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2162
+ const trace = options.pluginOptions.trace ?? defaultTrace;
2163
+ __privateSet$1(this, _trace, async (name, fn, options2 = {}) => {
2164
+ return trace(name, fn, {
2165
+ ...options2,
2166
+ [TraceAttributes.TABLE]: __privateGet$2(this, _table),
2167
+ [TraceAttributes.KIND]: "sdk-operation",
2168
+ [TraceAttributes.VERSION]: VERSION
2169
+ });
2170
+ });
2171
+ }
2172
+ async create(a, b, c, d) {
2173
+ return __privateGet$2(this, _trace).call(this, "create", async () => {
2174
+ const ifVersion = parseIfVersion(b, c, d);
2175
+ if (Array.isArray(a)) {
2176
+ if (a.length === 0)
2177
+ return [];
2178
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2179
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2180
+ const result = await this.read(ids, columns);
2181
+ return result;
2182
+ }
2183
+ if (isString(a) && isObject(b)) {
2184
+ if (a === "")
2185
+ throw new Error("The id can't be empty");
2186
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2187
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2188
+ }
2189
+ if (isObject(a) && isString(a.id)) {
2190
+ if (a.id === "")
2191
+ throw new Error("The id can't be empty");
2192
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2193
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2194
+ }
2195
+ if (isObject(a)) {
2196
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2197
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2198
+ }
2199
+ throw new Error("Invalid arguments for create method");
2200
+ });
2201
+ }
2202
+ async read(a, b) {
2203
+ return __privateGet$2(this, _trace).call(this, "read", async () => {
2204
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2205
+ if (Array.isArray(a)) {
2206
+ if (a.length === 0)
2207
+ return [];
2208
+ const ids = a.map((item) => extractId(item));
2209
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
2210
+ const dictionary = finalObjects.reduce((acc, object) => {
2211
+ acc[object.id] = object;
2212
+ return acc;
2213
+ }, {});
2214
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
2215
+ }
2216
+ const id = extractId(a);
2217
+ if (id) {
2218
+ try {
2219
+ const response = await getRecord({
2220
+ pathParams: {
2221
+ workspace: "{workspaceId}",
2222
+ dbBranchName: "{dbBranch}",
2223
+ region: "{region}",
2224
+ tableName: __privateGet$2(this, _table),
2225
+ recordId: id
2226
+ },
2227
+ queryParams: { columns },
2228
+ ...__privateGet$2(this, _getFetchProps).call(this)
2229
+ });
2230
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
2231
+ return initObject(
2232
+ __privateGet$2(this, _db),
2233
+ schemaTables,
2234
+ __privateGet$2(this, _table),
2235
+ response,
2236
+ columns
2237
+ );
2238
+ } catch (e) {
2239
+ if (isObject(e) && e.status === 404) {
2240
+ return null;
2241
+ }
2242
+ throw e;
2243
+ }
2244
+ }
2245
+ return null;
2246
+ });
2247
+ }
2248
+ async readOrThrow(a, b) {
2249
+ return __privateGet$2(this, _trace).call(this, "readOrThrow", async () => {
2250
+ const result = await this.read(a, b);
2251
+ if (Array.isArray(result)) {
2252
+ const missingIds = compact(
2253
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
2254
+ );
2255
+ if (missingIds.length > 0) {
2256
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
2257
+ }
2258
+ return result;
2259
+ }
2260
+ if (result === null) {
2261
+ const id = extractId(a) ?? "unknown";
2262
+ throw new Error(`Record with id ${id} not found`);
2263
+ }
2264
+ return result;
2265
+ });
2266
+ }
2267
+ async update(a, b, c, d) {
2268
+ return __privateGet$2(this, _trace).call(this, "update", async () => {
2269
+ const ifVersion = parseIfVersion(b, c, d);
2270
+ if (Array.isArray(a)) {
2271
+ if (a.length === 0)
2272
+ return [];
2273
+ const existing = await this.read(a, ["id"]);
2274
+ const updates = a.filter((_item, index) => existing[index] !== null);
2275
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
2276
+ ifVersion,
2277
+ upsert: false
2278
+ });
2279
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2280
+ const result = await this.read(a, columns);
2281
+ return result;
2282
+ }
2283
+ try {
2284
+ if (isString(a) && isObject(b)) {
2285
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2286
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2287
+ }
2288
+ if (isObject(a) && isString(a.id)) {
2289
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2290
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2291
+ }
2292
+ } catch (error) {
2293
+ if (error.status === 422)
2294
+ return null;
2295
+ throw error;
2296
+ }
2297
+ throw new Error("Invalid arguments for update method");
2298
+ });
2299
+ }
2300
+ async updateOrThrow(a, b, c, d) {
2301
+ return __privateGet$2(this, _trace).call(this, "updateOrThrow", async () => {
2302
+ const result = await this.update(a, b, c, d);
2303
+ if (Array.isArray(result)) {
2304
+ const missingIds = compact(
2305
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
2306
+ );
2307
+ if (missingIds.length > 0) {
2308
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
2309
+ }
2310
+ return result;
2311
+ }
2312
+ if (result === null) {
2313
+ const id = extractId(a) ?? "unknown";
2314
+ throw new Error(`Record with id ${id} not found`);
2315
+ }
2316
+ return result;
2317
+ });
2318
+ }
2319
+ async createOrUpdate(a, b, c, d) {
2320
+ return __privateGet$2(this, _trace).call(this, "createOrUpdate", async () => {
2321
+ const ifVersion = parseIfVersion(b, c, d);
2322
+ if (Array.isArray(a)) {
2323
+ if (a.length === 0)
2324
+ return [];
2325
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
2326
+ ifVersion,
2327
+ upsert: true
2328
+ });
2329
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2330
+ const result = await this.read(a, columns);
2331
+ return result;
2332
+ }
2333
+ if (isString(a) && isObject(b)) {
2334
+ if (a === "")
2335
+ throw new Error("The id can't be empty");
2336
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2337
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2338
+ }
2339
+ if (isObject(a) && isString(a.id)) {
2340
+ if (a.id === "")
2341
+ throw new Error("The id can't be empty");
2342
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2343
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2344
+ }
2345
+ if (!isDefined(a) && isObject(b)) {
2346
+ return await this.create(b, c);
2347
+ }
2348
+ if (isObject(a) && !isDefined(a.id)) {
2349
+ return await this.create(a, b);
2350
+ }
2351
+ throw new Error("Invalid arguments for createOrUpdate method");
2352
+ });
2353
+ }
2354
+ async createOrReplace(a, b, c, d) {
2355
+ return __privateGet$2(this, _trace).call(this, "createOrReplace", async () => {
2356
+ const ifVersion = parseIfVersion(b, c, d);
2357
+ if (Array.isArray(a)) {
2358
+ if (a.length === 0)
2359
+ return [];
2360
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2361
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2362
+ const result = await this.read(ids, columns);
2363
+ return result;
2364
+ }
2365
+ if (isString(a) && isObject(b)) {
2366
+ if (a === "")
2367
+ throw new Error("The id can't be empty");
2368
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2369
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2370
+ }
2371
+ if (isObject(a) && isString(a.id)) {
2372
+ if (a.id === "")
2373
+ throw new Error("The id can't be empty");
2374
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2375
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
2376
+ }
2377
+ if (!isDefined(a) && isObject(b)) {
2378
+ return await this.create(b, c);
2379
+ }
2380
+ if (isObject(a) && !isDefined(a.id)) {
2381
+ return await this.create(a, b);
2382
+ }
2383
+ throw new Error("Invalid arguments for createOrReplace method");
2384
+ });
2385
+ }
2386
+ async delete(a, b) {
2387
+ return __privateGet$2(this, _trace).call(this, "delete", async () => {
2388
+ if (Array.isArray(a)) {
2389
+ if (a.length === 0)
2390
+ return [];
2391
+ const ids = a.map((o) => {
2392
+ if (isString(o))
2393
+ return o;
2394
+ if (isString(o.id))
2395
+ return o.id;
2396
+ throw new Error("Invalid arguments for delete method");
2397
+ });
2398
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2399
+ const result = await this.read(a, columns);
2400
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2401
+ return result;
2402
+ }
2403
+ if (isString(a)) {
2404
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
2405
+ }
2406
+ if (isObject(a) && isString(a.id)) {
2407
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
2408
+ }
2409
+ throw new Error("Invalid arguments for delete method");
2410
+ });
2411
+ }
2412
+ async deleteOrThrow(a, b) {
2413
+ return __privateGet$2(this, _trace).call(this, "deleteOrThrow", async () => {
2414
+ const result = await this.delete(a, b);
2415
+ if (Array.isArray(result)) {
2416
+ const missingIds = compact(
2417
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
2418
+ );
2419
+ if (missingIds.length > 0) {
2420
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
2421
+ }
2422
+ return result;
2423
+ } else if (result === null) {
2424
+ const id = extractId(a) ?? "unknown";
2425
+ throw new Error(`Record with id ${id} not found`);
2426
+ }
2427
+ return result;
2428
+ });
2429
+ }
2430
+ async search(query, options = {}) {
2431
+ return __privateGet$2(this, _trace).call(this, "search", async () => {
2432
+ const { records, totalCount } = await searchTable({
2433
+ pathParams: {
2434
+ workspace: "{workspaceId}",
2435
+ dbBranchName: "{dbBranch}",
2436
+ region: "{region}",
2437
+ tableName: __privateGet$2(this, _table)
2438
+ },
2439
+ body: {
2440
+ query,
2441
+ fuzziness: options.fuzziness,
2442
+ prefix: options.prefix,
2443
+ highlight: options.highlight,
2444
+ filter: options.filter,
2445
+ boosters: options.boosters,
2446
+ page: options.page,
2447
+ target: options.target
2448
+ },
2449
+ ...__privateGet$2(this, _getFetchProps).call(this)
2450
+ });
2451
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
2452
+ return {
2453
+ records: records.map((item) => initObject(__privateGet$2(this, _db), schemaTables, __privateGet$2(this, _table), item, ["*"])),
2454
+ totalCount
2455
+ };
2456
+ });
2457
+ }
2458
+ async vectorSearch(column, query, options) {
2459
+ return __privateGet$2(this, _trace).call(this, "vectorSearch", async () => {
2460
+ const { records, totalCount } = await vectorSearchTable({
2461
+ pathParams: {
2462
+ workspace: "{workspaceId}",
2463
+ dbBranchName: "{dbBranch}",
2464
+ region: "{region}",
2465
+ tableName: __privateGet$2(this, _table)
2466
+ },
2467
+ body: {
2468
+ column,
2469
+ queryVector: query,
2470
+ similarityFunction: options?.similarityFunction,
2471
+ size: options?.size,
2472
+ filter: options?.filter
2473
+ },
2474
+ ...__privateGet$2(this, _getFetchProps).call(this)
2475
+ });
2476
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
2477
+ return {
2478
+ records: records.map((item) => initObject(__privateGet$2(this, _db), schemaTables, __privateGet$2(this, _table), item, ["*"])),
2479
+ totalCount
2480
+ };
2481
+ });
2482
+ }
2483
+ async aggregate(aggs, filter) {
2484
+ return __privateGet$2(this, _trace).call(this, "aggregate", async () => {
2485
+ const result = await aggregateTable({
2486
+ pathParams: {
2487
+ workspace: "{workspaceId}",
2488
+ dbBranchName: "{dbBranch}",
2489
+ region: "{region}",
2490
+ tableName: __privateGet$2(this, _table)
2491
+ },
2492
+ body: { aggs, filter },
2493
+ ...__privateGet$2(this, _getFetchProps).call(this)
2494
+ });
2495
+ return result;
2496
+ });
2497
+ }
2498
+ async query(query) {
2499
+ return __privateGet$2(this, _trace).call(this, "query", async () => {
2500
+ const data = query.getQueryOptions();
2501
+ const { meta, records: objects } = await queryTable({
2502
+ pathParams: {
2503
+ workspace: "{workspaceId}",
2504
+ dbBranchName: "{dbBranch}",
2505
+ region: "{region}",
2506
+ tableName: __privateGet$2(this, _table)
2507
+ },
2508
+ body: {
2509
+ filter: cleanFilter(data.filter),
2510
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2511
+ page: data.pagination,
2512
+ columns: data.columns ?? ["*"],
2513
+ consistency: data.consistency
2514
+ },
2515
+ fetchOptions: data.fetchOptions,
2516
+ ...__privateGet$2(this, _getFetchProps).call(this)
2517
+ });
2518
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
2519
+ const records = objects.map(
2520
+ (record) => initObject(
2521
+ __privateGet$2(this, _db),
2522
+ schemaTables,
2523
+ __privateGet$2(this, _table),
2524
+ record,
2525
+ data.columns ?? ["*"]
2526
+ )
2527
+ );
2528
+ return new Page(query, meta, records);
2529
+ });
2530
+ }
2531
+ async summarizeTable(query, summaries, summariesFilter) {
2532
+ return __privateGet$2(this, _trace).call(this, "summarize", async () => {
2533
+ const data = query.getQueryOptions();
2534
+ const result = await summarizeTable({
2535
+ pathParams: {
2536
+ workspace: "{workspaceId}",
2537
+ dbBranchName: "{dbBranch}",
2538
+ region: "{region}",
2539
+ tableName: __privateGet$2(this, _table)
2540
+ },
2541
+ body: {
2542
+ filter: cleanFilter(data.filter),
2543
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2544
+ columns: data.columns,
2545
+ consistency: data.consistency,
2546
+ page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2547
+ summaries,
2548
+ summariesFilter
2549
+ },
2550
+ ...__privateGet$2(this, _getFetchProps).call(this)
2551
+ });
2552
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
2553
+ return {
2554
+ ...result,
2555
+ summaries: result.summaries.map(
2556
+ (summary) => initObject(__privateGet$2(this, _db), schemaTables, __privateGet$2(this, _table), summary, data.columns ?? [])
2557
+ )
2558
+ };
2559
+ });
2560
+ }
2561
+ ask(question, options) {
2562
+ const questionParam = options?.sessionId ? { message: question } : { question };
2563
+ const params = {
2564
+ pathParams: {
2565
+ workspace: "{workspaceId}",
2566
+ dbBranchName: "{dbBranch}",
2567
+ region: "{region}",
2568
+ tableName: __privateGet$2(this, _table),
2569
+ sessionId: options?.sessionId
2570
+ },
2571
+ body: {
2572
+ ...questionParam,
2573
+ rules: options?.rules,
2574
+ searchType: options?.searchType,
2575
+ search: options?.searchType === "keyword" ? options?.search : void 0,
2576
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
2577
+ },
2578
+ ...__privateGet$2(this, _getFetchProps).call(this)
2579
+ };
2580
+ if (options?.onMessage) {
2581
+ fetchSSERequest({
2582
+ endpoint: "dataPlane",
2583
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
2584
+ method: "POST",
2585
+ onMessage: (message) => {
2586
+ options.onMessage?.({ answer: message.text, records: message.records });
2587
+ },
2588
+ ...params
2589
+ });
2590
+ } else {
2591
+ return askTableSession(params);
2592
+ }
2593
+ }
2594
+ }
2595
+ _table = new WeakMap();
2596
+ _getFetchProps = new WeakMap();
2597
+ _db = new WeakMap();
2598
+ _schemaTables = new WeakMap();
2599
+ _trace = new WeakMap();
2600
+ _insertRecordWithoutId = new WeakSet();
2601
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2602
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2603
+ const response = await insertRecord({
2604
+ pathParams: {
2605
+ workspace: "{workspaceId}",
2606
+ dbBranchName: "{dbBranch}",
2607
+ region: "{region}",
2608
+ tableName: __privateGet$2(this, _table)
2609
+ },
2610
+ queryParams: { columns },
2611
+ body: record,
2612
+ ...__privateGet$2(this, _getFetchProps).call(this)
2613
+ });
2614
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
2615
+ return initObject(__privateGet$2(this, _db), schemaTables, __privateGet$2(this, _table), response, columns);
2616
+ };
2617
+ _insertRecordWithId = new WeakSet();
2618
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2619
+ if (!recordId)
2620
+ return null;
2621
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2622
+ const response = await insertRecordWithID({
2623
+ pathParams: {
2624
+ workspace: "{workspaceId}",
2625
+ dbBranchName: "{dbBranch}",
2626
+ region: "{region}",
2627
+ tableName: __privateGet$2(this, _table),
2628
+ recordId
2629
+ },
2630
+ body: record,
2631
+ queryParams: { createOnly, columns, ifVersion },
2632
+ ...__privateGet$2(this, _getFetchProps).call(this)
2633
+ });
2634
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
2635
+ return initObject(__privateGet$2(this, _db), schemaTables, __privateGet$2(this, _table), response, columns);
2636
+ };
2637
+ _insertRecords = new WeakSet();
2638
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2639
+ const operations = await promiseMap(objects, async (object) => {
2640
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2641
+ return { insert: { table: __privateGet$2(this, _table), record, createOnly, ifVersion } };
2642
+ });
2643
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2644
+ const ids = [];
2645
+ for (const operations2 of chunkedOperations) {
2646
+ const { results } = await branchTransaction({
2647
+ pathParams: {
2648
+ workspace: "{workspaceId}",
2649
+ dbBranchName: "{dbBranch}",
2650
+ region: "{region}"
2651
+ },
2652
+ body: { operations: operations2 },
2653
+ ...__privateGet$2(this, _getFetchProps).call(this)
2654
+ });
2655
+ for (const result of results) {
2656
+ if (result.operation === "insert") {
2657
+ ids.push(result.id);
2658
+ } else {
2659
+ ids.push(null);
2660
+ }
2661
+ }
2662
+ }
2663
+ return ids;
2664
+ };
2665
+ _updateRecordWithID = new WeakSet();
2666
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2667
+ if (!recordId)
2668
+ return null;
2669
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2670
+ try {
2671
+ const response = await updateRecordWithID({
2672
+ pathParams: {
2673
+ workspace: "{workspaceId}",
2674
+ dbBranchName: "{dbBranch}",
2675
+ region: "{region}",
2676
+ tableName: __privateGet$2(this, _table),
2677
+ recordId
2678
+ },
2679
+ queryParams: { columns, ifVersion },
2680
+ body: record,
2681
+ ...__privateGet$2(this, _getFetchProps).call(this)
2682
+ });
2683
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
2684
+ return initObject(__privateGet$2(this, _db), schemaTables, __privateGet$2(this, _table), response, columns);
2685
+ } catch (e) {
2686
+ if (isObject(e) && e.status === 404) {
2687
+ return null;
2688
+ }
2689
+ throw e;
2690
+ }
2691
+ };
2692
+ _updateRecords = new WeakSet();
2693
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2694
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
2695
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2696
+ return { update: { table: __privateGet$2(this, _table), id, ifVersion, upsert, fields } };
2697
+ });
2698
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2699
+ const ids = [];
2700
+ for (const operations2 of chunkedOperations) {
2701
+ const { results } = await branchTransaction({
2702
+ pathParams: {
2703
+ workspace: "{workspaceId}",
2704
+ dbBranchName: "{dbBranch}",
2705
+ region: "{region}"
2706
+ },
2707
+ body: { operations: operations2 },
2708
+ ...__privateGet$2(this, _getFetchProps).call(this)
2709
+ });
2710
+ for (const result of results) {
2711
+ if (result.operation === "update") {
2712
+ ids.push(result.id);
2713
+ } else {
2714
+ ids.push(null);
2715
+ }
2716
+ }
2717
+ }
2718
+ return ids;
2719
+ };
2720
+ _upsertRecordWithID = new WeakSet();
2721
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2722
+ if (!recordId)
2723
+ return null;
2724
+ const response = await upsertRecordWithID({
2725
+ pathParams: {
2726
+ workspace: "{workspaceId}",
2727
+ dbBranchName: "{dbBranch}",
2728
+ region: "{region}",
2729
+ tableName: __privateGet$2(this, _table),
2730
+ recordId
2731
+ },
2732
+ queryParams: { columns, ifVersion },
2733
+ body: object,
2734
+ ...__privateGet$2(this, _getFetchProps).call(this)
2735
+ });
2736
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
2737
+ return initObject(__privateGet$2(this, _db), schemaTables, __privateGet$2(this, _table), response, columns);
2738
+ };
2739
+ _deleteRecord = new WeakSet();
2740
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2741
+ if (!recordId)
2742
+ return null;
2743
+ try {
2744
+ const response = await deleteRecord({
2745
+ pathParams: {
2746
+ workspace: "{workspaceId}",
2747
+ dbBranchName: "{dbBranch}",
2748
+ region: "{region}",
2749
+ tableName: __privateGet$2(this, _table),
2750
+ recordId
2751
+ },
2752
+ queryParams: { columns },
2753
+ ...__privateGet$2(this, _getFetchProps).call(this)
2754
+ });
2755
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
2756
+ return initObject(__privateGet$2(this, _db), schemaTables, __privateGet$2(this, _table), response, columns);
2757
+ } catch (e) {
2758
+ if (isObject(e) && e.status === 404) {
2759
+ return null;
2760
+ }
2761
+ throw e;
2762
+ }
2763
+ };
2764
+ _deleteRecords = new WeakSet();
2765
+ deleteRecords_fn = async function(recordIds) {
2766
+ const chunkedOperations = chunk(
2767
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$2(this, _table), id } })),
2768
+ BULK_OPERATION_MAX_SIZE
2769
+ );
2770
+ for (const operations of chunkedOperations) {
2771
+ await branchTransaction({
2772
+ pathParams: {
2773
+ workspace: "{workspaceId}",
2774
+ dbBranchName: "{dbBranch}",
2775
+ region: "{region}"
2776
+ },
2777
+ body: { operations },
2778
+ ...__privateGet$2(this, _getFetchProps).call(this)
2779
+ });
2780
+ }
2781
+ };
2782
+ _getSchemaTables = new WeakSet();
2783
+ getSchemaTables_fn = async function() {
2784
+ if (__privateGet$2(this, _schemaTables))
2785
+ return __privateGet$2(this, _schemaTables);
2786
+ const { schema } = await getBranchDetails({
2787
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2788
+ ...__privateGet$2(this, _getFetchProps).call(this)
2789
+ });
2790
+ __privateSet$1(this, _schemaTables, schema.tables);
2791
+ return schema.tables;
2792
+ };
2793
+ _transformObjectToApi = new WeakSet();
2794
+ transformObjectToApi_fn = async function(object) {
2795
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
2796
+ const schema = schemaTables.find((table) => table.name === __privateGet$2(this, _table));
2797
+ if (!schema)
2798
+ throw new Error(`Table ${__privateGet$2(this, _table)} not found in schema`);
2799
+ const result = {};
2800
+ for (const [key, value] of Object.entries(object)) {
2801
+ if (key === "xata")
2802
+ continue;
2803
+ const type = schema.columns.find((column) => column.name === key)?.type;
2804
+ switch (type) {
2805
+ case "link": {
2806
+ result[key] = isIdentifiable(value) ? value.id : value;
2807
+ break;
2808
+ }
2809
+ case "datetime": {
2810
+ result[key] = value instanceof Date ? value.toISOString() : value;
2811
+ break;
2812
+ }
2813
+ case `file`:
2814
+ result[key] = await parseInputFileEntry(value);
2815
+ break;
2816
+ case "file[]":
2817
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
2818
+ break;
2819
+ case "json":
2820
+ result[key] = stringifyJson(value);
2821
+ break;
2822
+ default:
2823
+ result[key] = value;
2824
+ }
2825
+ }
2826
+ return result;
2827
+ };
2828
+ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2829
+ const data = {};
2830
+ const { xata, ...rest } = object ?? {};
2831
+ Object.assign(data, rest);
2832
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2833
+ if (!columns)
2834
+ console.error(`Table ${table} not found in schema`);
2835
+ for (const column of columns ?? []) {
2836
+ if (!isValidColumn(selectedColumns, column))
2837
+ continue;
2838
+ const value = data[column.name];
2839
+ switch (column.type) {
2840
+ case "datetime": {
2841
+ const date = value !== void 0 ? new Date(value) : null;
2842
+ if (date !== null && isNaN(date.getTime())) {
2843
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
2844
+ } else {
2845
+ data[column.name] = date;
2846
+ }
2847
+ break;
2848
+ }
2849
+ case "link": {
2850
+ const linkTable = column.link?.table;
2851
+ if (!linkTable) {
2852
+ console.error(`Failed to parse link for field ${column.name}`);
2853
+ } else if (isObject(value)) {
2854
+ const selectedLinkColumns = selectedColumns.reduce((acc, item) => {
2855
+ if (item === column.name) {
2856
+ return [...acc, "*"];
2857
+ }
2858
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
2859
+ const [, ...path] = item.split(".");
2860
+ return [...acc, path.join(".")];
2861
+ }
2862
+ return acc;
2863
+ }, []);
2864
+ data[column.name] = initObject(
2865
+ db,
2866
+ schemaTables,
2867
+ linkTable,
2868
+ value,
2869
+ selectedLinkColumns
2870
+ );
2871
+ } else {
2872
+ data[column.name] = null;
2873
+ }
2874
+ break;
2875
+ }
2876
+ case "file":
2877
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
2878
+ break;
2879
+ case "file[]":
2880
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
2881
+ break;
2882
+ case "json":
2883
+ data[column.name] = parseJson(value);
2884
+ break;
2885
+ default:
2886
+ data[column.name] = value ?? null;
2887
+ if (column.notNull === true && value === null) {
2888
+ console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2889
+ }
2890
+ break;
2891
+ }
2892
+ }
2893
+ const record = { ...data };
2894
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
2895
+ record.read = function(columns2) {
2896
+ return db[table].read(record["id"], columns2);
2897
+ };
2898
+ record.update = function(data2, b, c) {
2899
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2900
+ const ifVersion = parseIfVersion(b, c);
2901
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2902
+ };
2903
+ record.replace = function(data2, b, c) {
2904
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2905
+ const ifVersion = parseIfVersion(b, c);
2906
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2907
+ };
2908
+ record.delete = function() {
2909
+ return db[table].delete(record["id"]);
2910
+ };
2911
+ if (metadata !== void 0) {
2912
+ record.xata = Object.freeze(metadata);
2913
+ }
2914
+ record.getMetadata = function() {
2915
+ return record.xata;
2916
+ };
2917
+ record.toSerializable = function() {
2918
+ return JSON.parse(JSON.stringify(record));
2919
+ };
2920
+ record.toString = function() {
2921
+ return JSON.stringify(record);
2922
+ };
2923
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
2924
+ Object.defineProperty(record, prop, { enumerable: false });
2925
+ }
2926
+ Object.freeze(record);
2927
+ return record;
2928
+ };
2929
+ function extractId(value) {
2930
+ if (isString(value))
2931
+ return value;
2932
+ if (isObject(value) && isString(value.id))
2933
+ return value.id;
2934
+ return void 0;
2935
+ }
2936
+ function isValidColumn(columns, column) {
2937
+ if (columns.includes("*"))
2938
+ return true;
2939
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
2940
+ }
2941
+ function parseIfVersion(...args) {
2942
+ for (const arg of args) {
2943
+ if (isObject(arg) && isNumber(arg.ifVersion)) {
2944
+ return arg.ifVersion;
2945
+ }
2946
+ }
2947
+ return void 0;
2948
+ }
2949
+
2950
+ const greaterThan = (value) => ({ $gt: value });
2951
+ const gt = greaterThan;
2952
+ const greaterThanEquals = (value) => ({ $ge: value });
2953
+ const greaterEquals = greaterThanEquals;
2954
+ const gte = greaterThanEquals;
2955
+ const ge = greaterThanEquals;
2956
+ const lessThan = (value) => ({ $lt: value });
2957
+ const lt = lessThan;
2958
+ const lessThanEquals = (value) => ({ $le: value });
2959
+ const lessEquals = lessThanEquals;
2960
+ const lte = lessThanEquals;
2961
+ const le = lessThanEquals;
2962
+ const exists = (column) => ({ $exists: column });
2963
+ const notExists = (column) => ({ $notExists: column });
2964
+ const startsWith = (value) => ({ $startsWith: value });
2965
+ const endsWith = (value) => ({ $endsWith: value });
2966
+ const pattern = (value) => ({ $pattern: value });
2967
+ const iPattern = (value) => ({ $iPattern: value });
2968
+ const is = (value) => ({ $is: value });
2969
+ const equals = is;
2970
+ const isNot = (value) => ({ $isNot: value });
2971
+ const contains = (value) => ({ $contains: value });
2972
+ const iContains = (value) => ({ $iContains: value });
2973
+ const includes = (value) => ({ $includes: value });
2974
+ const includesAll = (value) => ({ $includesAll: value });
2975
+ const includesNone = (value) => ({ $includesNone: value });
2976
+ const includesAny = (value) => ({ $includesAny: value });
2977
+
2978
+ var __accessCheck$2 = (obj, member, msg) => {
2979
+ if (!member.has(obj))
2980
+ throw TypeError("Cannot " + msg);
2981
+ };
2982
+ var __privateGet$1 = (obj, member, getter) => {
2983
+ __accessCheck$2(obj, member, "read from private field");
2984
+ return getter ? getter.call(obj) : member.get(obj);
2985
+ };
2986
+ var __privateAdd$2 = (obj, member, value) => {
2987
+ if (member.has(obj))
2988
+ throw TypeError("Cannot add the same private member more than once");
2989
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2990
+ };
2991
+ var _tables;
2992
+ class SchemaPlugin extends XataPlugin {
2993
+ constructor() {
2994
+ super();
2995
+ __privateAdd$2(this, _tables, {});
2996
+ }
2997
+ build(pluginOptions) {
2998
+ const db = new Proxy(
2999
+ {},
3000
+ {
3001
+ get: (_target, table) => {
3002
+ if (!isString(table))
3003
+ throw new Error("Invalid table name");
3004
+ if (__privateGet$1(this, _tables)[table] === void 0) {
3005
+ __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: pluginOptions.tables });
3006
+ }
3007
+ return __privateGet$1(this, _tables)[table];
3008
+ }
3009
+ }
3010
+ );
3011
+ const tableNames = pluginOptions.tables?.map(({ name }) => name) ?? [];
3012
+ for (const table of tableNames) {
3013
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: pluginOptions.tables });
3014
+ }
3015
+ return db;
3016
+ }
3017
+ }
3018
+ _tables = new WeakMap();
3019
+
3020
+ class FilesPlugin extends XataPlugin {
3021
+ build(pluginOptions) {
3022
+ return {
3023
+ download: async (location) => {
3024
+ const { table, record, column, fileId = "" } = location ?? {};
3025
+ return await getFileItem({
3026
+ pathParams: {
3027
+ workspace: "{workspaceId}",
3028
+ dbBranchName: "{dbBranch}",
3029
+ region: "{region}",
3030
+ tableName: table ?? "",
3031
+ recordId: record ?? "",
3032
+ columnName: column ?? "",
3033
+ fileId
3034
+ },
3035
+ ...pluginOptions,
3036
+ rawResponse: true
3037
+ });
3038
+ },
3039
+ upload: async (location, file, options) => {
3040
+ const { table, record, column, fileId = "" } = location ?? {};
3041
+ const resolvedFile = await file;
3042
+ const contentType = options?.mediaType || getContentType(resolvedFile);
3043
+ const body = resolvedFile instanceof XataFile ? resolvedFile.toBlob() : resolvedFile;
3044
+ return await putFileItem({
3045
+ ...pluginOptions,
3046
+ pathParams: {
3047
+ workspace: "{workspaceId}",
3048
+ dbBranchName: "{dbBranch}",
3049
+ region: "{region}",
3050
+ tableName: table ?? "",
3051
+ recordId: record ?? "",
3052
+ columnName: column ?? "",
3053
+ fileId
3054
+ },
3055
+ body,
3056
+ headers: { "Content-Type": contentType }
3057
+ });
3058
+ },
3059
+ delete: async (location) => {
3060
+ const { table, record, column, fileId = "" } = location ?? {};
3061
+ return await deleteFileItem({
3062
+ pathParams: {
3063
+ workspace: "{workspaceId}",
3064
+ dbBranchName: "{dbBranch}",
3065
+ region: "{region}",
3066
+ tableName: table ?? "",
3067
+ recordId: record ?? "",
3068
+ columnName: column ?? "",
3069
+ fileId
3070
+ },
3071
+ ...pluginOptions
3072
+ });
3073
+ }
3074
+ };
3075
+ }
3076
+ }
3077
+ function getContentType(file) {
3078
+ if (typeof file === "string") {
3079
+ return "text/plain";
3080
+ }
3081
+ if ("mediaType" in file && file.mediaType !== void 0) {
3082
+ return file.mediaType;
3083
+ }
3084
+ if (isBlob(file)) {
3085
+ return file.type;
3086
+ }
3087
+ try {
3088
+ return file.type;
3089
+ } catch (e) {
3090
+ }
3091
+ return "application/octet-stream";
3092
+ }
3093
+
3094
+ var __accessCheck$1 = (obj, member, msg) => {
3095
+ if (!member.has(obj))
3096
+ throw TypeError("Cannot " + msg);
3097
+ };
3098
+ var __privateAdd$1 = (obj, member, value) => {
3099
+ if (member.has(obj))
3100
+ throw TypeError("Cannot add the same private member more than once");
3101
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3102
+ };
3103
+ var __privateMethod$1 = (obj, member, method) => {
3104
+ __accessCheck$1(obj, member, "access private method");
3105
+ return method;
3106
+ };
3107
+ var _search, search_fn;
3108
+ class SearchPlugin extends XataPlugin {
3109
+ constructor(db) {
3110
+ super();
3111
+ this.db = db;
3112
+ __privateAdd$1(this, _search);
3113
+ }
3114
+ build(pluginOptions) {
3115
+ return {
3116
+ all: async (query, options = {}) => {
3117
+ const { records, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3118
+ return {
3119
+ totalCount,
3120
+ records: records.map((record) => {
3121
+ const { table = "orphan" } = record.xata;
3122
+ return { table, record: initObject(this.db, pluginOptions.tables, table, record, ["*"]) };
3123
+ })
3124
+ };
3125
+ },
3126
+ byTable: async (query, options = {}) => {
3127
+ const { records: rawRecords, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3128
+ const records = rawRecords.reduce((acc, record) => {
3129
+ const { table = "orphan" } = record.xata;
3130
+ const items = acc[table] ?? [];
3131
+ const item = initObject(this.db, pluginOptions.tables, table, record, ["*"]);
3132
+ return { ...acc, [table]: [...items, item] };
3133
+ }, {});
3134
+ return { totalCount, records };
3135
+ }
3136
+ };
3137
+ }
3138
+ }
3139
+ _search = new WeakSet();
3140
+ search_fn = async function(query, options, pluginOptions) {
3141
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3142
+ const { records, totalCount } = await searchBranch({
3143
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3144
+ // @ts-expect-error Filter properties do not match inferred type
3145
+ body: { tables, query, fuzziness, prefix, highlight, page },
3146
+ ...pluginOptions
3147
+ });
3148
+ return { records, totalCount };
3149
+ };
3150
+
3151
+ function escapeElement(elementRepresentation) {
3152
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
3153
+ return '"' + escaped + '"';
3154
+ }
3155
+ function arrayString(val) {
3156
+ let result = "{";
3157
+ for (let i = 0; i < val.length; i++) {
3158
+ if (i > 0) {
3159
+ result = result + ",";
3160
+ }
3161
+ if (val[i] === null || typeof val[i] === "undefined") {
3162
+ result = result + "NULL";
3163
+ } else if (Array.isArray(val[i])) {
3164
+ result = result + arrayString(val[i]);
3165
+ } else if (val[i] instanceof Buffer) {
3166
+ result += "\\\\x" + val[i].toString("hex");
3167
+ } else {
3168
+ result += escapeElement(prepareValue(val[i]));
3169
+ }
3170
+ }
3171
+ result = result + "}";
3172
+ return result;
3173
+ }
3174
+ function prepareValue(value) {
3175
+ if (!isDefined(value))
3176
+ return null;
3177
+ if (value instanceof Date) {
3178
+ return value.toISOString();
3179
+ }
3180
+ if (Array.isArray(value)) {
3181
+ return arrayString(value);
3182
+ }
3183
+ if (isObject(value)) {
3184
+ return JSON.stringify(value);
3185
+ }
3186
+ try {
3187
+ return value.toString();
3188
+ } catch (e) {
3189
+ return value;
3190
+ }
3191
+ }
3192
+ function prepareParams(param1, param2) {
3193
+ if (isString(param1)) {
3194
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
3195
+ }
3196
+ if (isStringArray(param1)) {
3197
+ const statement = param1.reduce((acc, curr, index) => {
3198
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
3199
+ }, "");
3200
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
3201
+ }
3202
+ if (isObject(param1)) {
3203
+ const { statement, params, consistency } = param1;
3204
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
3205
+ }
3206
+ throw new Error("Invalid query");
3207
+ }
3208
+
3209
+ class SQLPlugin extends XataPlugin {
3210
+ build(pluginOptions) {
3211
+ return async (query, ...parameters) => {
3212
+ if (!isParamsObject(query) && (!isTemplateStringsArray(query) || !Array.isArray(parameters))) {
3213
+ throw new Error("Invalid usage of `xata.sql`. Please use it as a tagged template or with an object.");
3214
+ }
3215
+ const { statement, params, consistency } = prepareParams(query, parameters);
3216
+ const {
3217
+ records,
3218
+ rows,
3219
+ warning,
3220
+ columns = []
3221
+ } = await sqlQuery({
3222
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3223
+ body: { statement, params, consistency },
3224
+ ...pluginOptions
3225
+ });
3226
+ return { records, rows, warning, columns };
3227
+ };
3228
+ }
3229
+ }
3230
+ function isTemplateStringsArray(strings) {
3231
+ return Array.isArray(strings) && "raw" in strings && Array.isArray(strings.raw);
3232
+ }
3233
+ function isParamsObject(params) {
3234
+ return isObject(params) && "statement" in params;
3235
+ }
3236
+
3237
+ class TransactionPlugin extends XataPlugin {
3238
+ build(pluginOptions) {
3239
+ return {
3240
+ run: async (operations) => {
3241
+ const response = await branchTransaction({
3242
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3243
+ body: { operations },
3244
+ ...pluginOptions
3245
+ });
3246
+ return response;
3247
+ }
3248
+ };
3249
+ }
3250
+ }
3251
+
3252
+ var __accessCheck = (obj, member, msg) => {
3253
+ if (!member.has(obj))
3254
+ throw TypeError("Cannot " + msg);
3255
+ };
3256
+ var __privateGet = (obj, member, getter) => {
3257
+ __accessCheck(obj, member, "read from private field");
3258
+ return getter ? getter.call(obj) : member.get(obj);
3259
+ };
3260
+ var __privateAdd = (obj, member, value) => {
3261
+ if (member.has(obj))
3262
+ throw TypeError("Cannot add the same private member more than once");
3263
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3264
+ };
3265
+ var __privateSet = (obj, member, value, setter) => {
3266
+ __accessCheck(obj, member, "write to private field");
3267
+ setter ? setter.call(obj, value) : member.set(obj, value);
3268
+ return value;
3269
+ };
3270
+ var __privateMethod = (obj, member, method) => {
3271
+ __accessCheck(obj, member, "access private method");
3272
+ return method;
3273
+ };
3274
+ const buildClient = (plugins) => {
3275
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3276
+ return _a = class {
3277
+ constructor(options = {}, tables) {
3278
+ __privateAdd(this, _parseOptions);
3279
+ __privateAdd(this, _getFetchProps);
3280
+ __privateAdd(this, _options, void 0);
3281
+ const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3282
+ __privateSet(this, _options, safeOptions);
3283
+ const pluginOptions = {
3284
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3285
+ host: safeOptions.host,
3286
+ tables
3287
+ };
3288
+ const db = new SchemaPlugin().build(pluginOptions);
3289
+ const search = new SearchPlugin(db).build(pluginOptions);
3290
+ const transactions = new TransactionPlugin().build(pluginOptions);
3291
+ const sql = new SQLPlugin().build(pluginOptions);
3292
+ const files = new FilesPlugin().build(pluginOptions);
3293
+ this.schema = { tables };
3294
+ this.db = db;
3295
+ this.search = search;
3296
+ this.transactions = transactions;
3297
+ this.sql = sql;
3298
+ this.files = files;
3299
+ for (const [key, namespace] of Object.entries(plugins ?? {})) {
3300
+ if (namespace === void 0)
3301
+ continue;
3302
+ this[key] = namespace.build(pluginOptions);
3303
+ }
3304
+ }
3305
+ async getConfig() {
3306
+ const databaseURL = __privateGet(this, _options).databaseURL;
3307
+ const branch = __privateGet(this, _options).branch;
3308
+ return { databaseURL, branch };
3309
+ }
3310
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3311
+ const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3312
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3313
+ if (isBrowser && !enableBrowser) {
3314
+ throw new Error(
3315
+ "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"
3316
+ );
3317
+ }
3318
+ const fetch = getFetchImplementation(options?.fetch);
3319
+ const databaseURL = options?.databaseURL || getDatabaseURL();
3320
+ const apiKey = options?.apiKey || getAPIKey();
3321
+ const trace = options?.trace ?? defaultTrace;
3322
+ const clientName = options?.clientName;
3323
+ const host = options?.host ?? "production";
3324
+ const xataAgentExtra = options?.xataAgentExtra;
3325
+ if (!apiKey) {
3326
+ throw new Error("Option apiKey is required");
3327
+ }
3328
+ if (!databaseURL) {
3329
+ throw new Error("Option databaseURL is required");
3330
+ }
3331
+ const envBranch = getBranch();
3332
+ const previewBranch = getPreviewBranch();
3333
+ const branch = options?.branch || previewBranch || envBranch || "main";
3334
+ if (!!previewBranch && branch !== previewBranch) {
3335
+ console.warn(
3336
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
3337
+ );
3338
+ } else if (!!envBranch && branch !== envBranch) {
3339
+ console.warn(
3340
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
3341
+ );
3342
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
3343
+ console.warn(
3344
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
3345
+ );
3346
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
3347
+ console.warn(
3348
+ `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.`
3349
+ );
3350
+ }
3351
+ return {
3352
+ fetch,
3353
+ databaseURL,
3354
+ apiKey,
3355
+ branch,
3356
+ trace,
3357
+ host,
3358
+ clientID: generateUUID(),
3359
+ enableBrowser,
3360
+ clientName,
3361
+ xataAgentExtra
3362
+ };
3363
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
3364
+ fetch,
3365
+ apiKey,
3366
+ databaseURL,
3367
+ branch,
3368
+ trace,
3369
+ clientID,
3370
+ clientName,
3371
+ xataAgentExtra
3372
+ }) {
3373
+ return {
3374
+ fetch,
3375
+ apiKey,
3376
+ apiUrl: "",
3377
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3378
+ workspacesApiUrl: (path, params) => {
3379
+ const hasBranch = params.dbBranchName ?? params.branch;
3380
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
3381
+ return databaseURL + newPath;
3382
+ },
3383
+ trace,
3384
+ clientID,
3385
+ clientName,
3386
+ xataAgentExtra
3387
+ };
3388
+ }, _a;
3389
+ };
3390
+ class BaseClient extends buildClient() {
3391
+ }
3392
+
3393
+ const META = "__";
3394
+ const VALUE = "___";
3395
+ class Serializer {
3396
+ constructor() {
3397
+ this.classes = {};
3398
+ }
3399
+ add(clazz) {
3400
+ this.classes[clazz.name] = clazz;
3401
+ }
3402
+ toJSON(data) {
3403
+ function visit(obj) {
3404
+ if (Array.isArray(obj))
3405
+ return obj.map(visit);
3406
+ const type = typeof obj;
3407
+ if (type === "undefined")
3408
+ return { [META]: "undefined" };
3409
+ if (type === "bigint")
3410
+ return { [META]: "bigint", [VALUE]: obj.toString() };
3411
+ if (obj === null || type !== "object")
3412
+ return obj;
3413
+ const constructor = obj.constructor;
3414
+ const o = { [META]: constructor.name };
3415
+ for (const [key, value] of Object.entries(obj)) {
3416
+ o[key] = visit(value);
3417
+ }
3418
+ if (constructor === Date)
3419
+ o[VALUE] = obj.toISOString();
3420
+ if (constructor === Map)
3421
+ o[VALUE] = Object.fromEntries(obj);
3422
+ if (constructor === Set)
3423
+ o[VALUE] = [...obj];
3424
+ return o;
3425
+ }
3426
+ return JSON.stringify(visit(data));
3427
+ }
3428
+ fromJSON(json) {
3429
+ return JSON.parse(json, (key, value) => {
3430
+ if (value && typeof value === "object" && !Array.isArray(value)) {
3431
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
3432
+ const constructor = this.classes[clazz];
3433
+ if (constructor) {
3434
+ return Object.assign(Object.create(constructor.prototype), rest);
3435
+ }
3436
+ if (clazz === "Date")
3437
+ return new Date(val);
3438
+ if (clazz === "Set")
3439
+ return new Set(val);
3440
+ if (clazz === "Map")
3441
+ return new Map(Object.entries(val));
3442
+ if (clazz === "bigint")
3443
+ return BigInt(val);
3444
+ if (clazz === "undefined")
3445
+ return void 0;
3446
+ return rest;
3447
+ }
3448
+ return value;
3449
+ });
3450
+ }
3451
+ }
3452
+ const defaultSerializer = new Serializer();
3453
+ const serialize = (data) => {
3454
+ return defaultSerializer.toJSON(data);
3455
+ };
3456
+ const deserialize = (json) => {
3457
+ return defaultSerializer.fromJSON(json);
3458
+ };
3459
+
3460
+ class XataError extends Error {
3461
+ constructor(message, status) {
3462
+ super(message);
3463
+ this.status = status;
3464
+ }
3465
+ }
3466
+
3467
+ exports.BaseClient = BaseClient;
3468
+ exports.FetcherError = FetcherError;
3469
+ exports.FilesPlugin = FilesPlugin;
3470
+ exports.Operations = operationsByTag;
3471
+ exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
3472
+ exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
3473
+ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
3474
+ exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
3475
+ exports.Page = Page;
3476
+ exports.PageRecordArray = PageRecordArray;
3477
+ exports.Query = Query;
3478
+ exports.RecordArray = RecordArray;
3479
+ exports.RecordColumnTypes = RecordColumnTypes;
3480
+ exports.Repository = Repository;
3481
+ exports.RestRepository = RestRepository;
3482
+ exports.SQLPlugin = SQLPlugin;
3483
+ exports.SchemaPlugin = SchemaPlugin;
3484
+ exports.SearchPlugin = SearchPlugin;
3485
+ exports.Serializer = Serializer;
3486
+ exports.TransactionPlugin = TransactionPlugin;
3487
+ exports.XataApiClient = XataApiClient;
3488
+ exports.XataApiPlugin = XataApiPlugin;
3489
+ exports.XataError = XataError;
3490
+ exports.XataFile = XataFile;
3491
+ exports.XataPlugin = XataPlugin;
3492
+ exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
3493
+ exports.adaptTable = adaptTable;
3494
+ exports.addGitBranchesEntry = addGitBranchesEntry;
3495
+ exports.addTableColumn = addTableColumn;
3496
+ exports.aggregateTable = aggregateTable;
3497
+ exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
3498
+ exports.applyMigration = applyMigration;
3499
+ exports.askTable = askTable;
3500
+ exports.askTableSession = askTableSession;
3501
+ exports.branchTransaction = branchTransaction;
3502
+ exports.buildClient = buildClient;
3503
+ exports.buildPreviewBranchName = buildPreviewBranchName;
3504
+ exports.buildProviderString = buildProviderString;
3505
+ exports.bulkInsertTableRecords = bulkInsertTableRecords;
3506
+ exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
3507
+ exports.compareBranchSchemas = compareBranchSchemas;
3508
+ exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
3509
+ exports.compareMigrationRequest = compareMigrationRequest;
3510
+ exports.contains = contains;
3511
+ exports.copyBranch = copyBranch;
3512
+ exports.createBranch = createBranch;
3513
+ exports.createCluster = createCluster;
3514
+ exports.createDatabase = createDatabase;
3515
+ exports.createMigrationRequest = createMigrationRequest;
3516
+ exports.createTable = createTable;
3517
+ exports.createUserAPIKey = createUserAPIKey;
3518
+ exports.createWorkspace = createWorkspace;
3519
+ exports.deleteBranch = deleteBranch;
3520
+ exports.deleteColumn = deleteColumn;
3521
+ exports.deleteDatabase = deleteDatabase;
3522
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
3523
+ exports.deleteFile = deleteFile;
3524
+ exports.deleteFileItem = deleteFileItem;
3525
+ exports.deleteOAuthAccessToken = deleteOAuthAccessToken;
3526
+ exports.deleteRecord = deleteRecord;
3527
+ exports.deleteTable = deleteTable;
3528
+ exports.deleteUser = deleteUser;
3529
+ exports.deleteUserAPIKey = deleteUserAPIKey;
3530
+ exports.deleteUserOAuthClient = deleteUserOAuthClient;
3531
+ exports.deleteWorkspace = deleteWorkspace;
3532
+ exports.deserialize = deserialize;
3533
+ exports.endsWith = endsWith;
3534
+ exports.equals = equals;
3535
+ exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
3536
+ exports.exists = exists;
3537
+ exports.fileAccess = fileAccess;
3538
+ exports.fileUpload = fileUpload;
3539
+ exports.ge = ge;
3540
+ exports.getAPIKey = getAPIKey;
3541
+ exports.getAuthorizationCode = getAuthorizationCode;
3542
+ exports.getBranch = getBranch;
3543
+ exports.getBranchDetails = getBranchDetails;
3544
+ exports.getBranchList = getBranchList;
3545
+ exports.getBranchMetadata = getBranchMetadata;
3546
+ exports.getBranchMigrationHistory = getBranchMigrationHistory;
3547
+ exports.getBranchMigrationJobStatus = getBranchMigrationJobStatus;
3548
+ exports.getBranchMigrationPlan = getBranchMigrationPlan;
3549
+ exports.getBranchSchemaHistory = getBranchSchemaHistory;
3550
+ exports.getBranchStats = getBranchStats;
3551
+ exports.getCluster = getCluster;
3552
+ exports.getColumn = getColumn;
3553
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
3554
+ exports.getDatabaseList = getDatabaseList;
3555
+ exports.getDatabaseMetadata = getDatabaseMetadata;
3556
+ exports.getDatabaseSettings = getDatabaseSettings;
3557
+ exports.getDatabaseURL = getDatabaseURL;
3558
+ exports.getFile = getFile;
3559
+ exports.getFileItem = getFileItem;
3560
+ exports.getGitBranchesMapping = getGitBranchesMapping;
3561
+ exports.getHostUrl = getHostUrl;
3562
+ exports.getMigrationHistory = getMigrationHistory;
3563
+ exports.getMigrationJobStatus = getMigrationJobStatus;
3564
+ exports.getMigrationRequest = getMigrationRequest;
3565
+ exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
3566
+ exports.getPreviewBranch = getPreviewBranch;
3567
+ exports.getRecord = getRecord;
3568
+ exports.getSchema = getSchema;
3569
+ exports.getTableColumns = getTableColumns;
3570
+ exports.getTableSchema = getTableSchema;
3571
+ exports.getUser = getUser;
3572
+ exports.getUserAPIKeys = getUserAPIKeys;
3573
+ exports.getUserOAuthAccessTokens = getUserOAuthAccessTokens;
3574
+ exports.getUserOAuthClients = getUserOAuthClients;
3575
+ exports.getWorkspace = getWorkspace;
3576
+ exports.getWorkspaceMembersList = getWorkspaceMembersList;
3577
+ exports.getWorkspacesList = getWorkspacesList;
3578
+ exports.grantAuthorizationCode = grantAuthorizationCode;
3579
+ exports.greaterEquals = greaterEquals;
3580
+ exports.greaterThan = greaterThan;
3581
+ exports.greaterThanEquals = greaterThanEquals;
3582
+ exports.gt = gt;
3583
+ exports.gte = gte;
3584
+ exports.iContains = iContains;
3585
+ exports.iPattern = iPattern;
3586
+ exports.includes = includes;
3587
+ exports.includesAll = includesAll;
3588
+ exports.includesAny = includesAny;
3589
+ exports.includesNone = includesNone;
3590
+ exports.insertRecord = insertRecord;
3591
+ exports.insertRecordWithID = insertRecordWithID;
3592
+ exports.inviteWorkspaceMember = inviteWorkspaceMember;
3593
+ exports.is = is;
3594
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
3595
+ exports.isHostProviderAlias = isHostProviderAlias;
3596
+ exports.isHostProviderBuilder = isHostProviderBuilder;
3597
+ exports.isIdentifiable = isIdentifiable;
3598
+ exports.isNot = isNot;
3599
+ exports.isValidExpandedColumn = isValidExpandedColumn;
3600
+ exports.isValidSelectableColumns = isValidSelectableColumns;
3601
+ exports.isXataRecord = isXataRecord;
3602
+ exports.le = le;
3603
+ exports.lessEquals = lessEquals;
3604
+ exports.lessThan = lessThan;
3605
+ exports.lessThanEquals = lessThanEquals;
3606
+ exports.listClusters = listClusters;
3607
+ exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
3608
+ exports.listRegions = listRegions;
3609
+ exports.lt = lt;
3610
+ exports.lte = lte;
3611
+ exports.mergeMigrationRequest = mergeMigrationRequest;
3612
+ exports.notExists = notExists;
3613
+ exports.operationsByTag = operationsByTag;
3614
+ exports.parseProviderString = parseProviderString;
3615
+ exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
3616
+ exports.pattern = pattern;
3617
+ exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
3618
+ exports.pushBranchMigrations = pushBranchMigrations;
3619
+ exports.putFile = putFile;
3620
+ exports.putFileItem = putFileItem;
3621
+ exports.queryMigrationRequests = queryMigrationRequests;
3622
+ exports.queryTable = queryTable;
3623
+ exports.removeGitBranchesEntry = removeGitBranchesEntry;
3624
+ exports.removeWorkspaceMember = removeWorkspaceMember;
3625
+ exports.renameDatabase = renameDatabase;
3626
+ exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
3627
+ exports.resolveBranch = resolveBranch;
3628
+ exports.searchBranch = searchBranch;
3629
+ exports.searchTable = searchTable;
3630
+ exports.serialize = serialize;
3631
+ exports.setTableSchema = setTableSchema;
3632
+ exports.sqlQuery = sqlQuery;
3633
+ exports.startsWith = startsWith;
3634
+ exports.summarizeTable = summarizeTable;
3635
+ exports.transformImage = transformImage;
3636
+ exports.updateBranchMetadata = updateBranchMetadata;
3637
+ exports.updateBranchSchema = updateBranchSchema;
3638
+ exports.updateCluster = updateCluster;
3639
+ exports.updateColumn = updateColumn;
3640
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
3641
+ exports.updateDatabaseMetadata = updateDatabaseMetadata;
3642
+ exports.updateDatabaseSettings = updateDatabaseSettings;
3643
+ exports.updateMigrationRequest = updateMigrationRequest;
3644
+ exports.updateOAuthAccessToken = updateOAuthAccessToken;
3645
+ exports.updateRecordWithID = updateRecordWithID;
3646
+ exports.updateTable = updateTable;
3647
+ exports.updateUser = updateUser;
3648
+ exports.updateWorkspace = updateWorkspace;
3649
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
3650
+ exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
3651
+ exports.upsertRecordWithID = upsertRecordWithID;
3652
+ exports.vectorSearchTable = vectorSearchTable;
3653
+ //# sourceMappingURL=index.cjs.map