@xata.io/client 0.0.0-alpha.vfd071d9 → 0.0.0-alpha.vfd609764793466374d6519edeb1be8debc9a83d5

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