@xata.io/client 0.0.0-alpha.vf170c2c → 0.0.0-alpha.vf181bf6b5770b15d42125b2728f3bf80a87e6333

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