@xata.io/client 0.0.0-alpha.vf7b5320 → 0.0.0-alpha.vf8b33c9

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,3 +1,25 @@
1
+ const defaultTrace = async (_name, fn, _options) => {
2
+ return await fn({
3
+ setAttributes: () => {
4
+ return;
5
+ }
6
+ });
7
+ };
8
+ const TraceAttributes = {
9
+ KIND: "xata.trace.kind",
10
+ VERSION: "xata.sdk.version",
11
+ TABLE: "xata.table",
12
+ HTTP_REQUEST_ID: "http.request_id",
13
+ HTTP_STATUS_CODE: "http.status_code",
14
+ HTTP_HOST: "http.host",
15
+ HTTP_SCHEME: "http.scheme",
16
+ HTTP_USER_AGENT: "http.user_agent",
17
+ HTTP_METHOD: "http.method",
18
+ HTTP_URL: "http.url",
19
+ HTTP_ROUTE: "http.route",
20
+ HTTP_TARGET: "http.target"
21
+ };
22
+
1
23
  function notEmpty(value) {
2
24
  return value !== null && value !== void 0;
3
25
  }
@@ -7,46 +29,101 @@ function compact(arr) {
7
29
  function isObject(value) {
8
30
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
31
  }
32
+ function isDefined(value) {
33
+ return value !== null && value !== void 0;
34
+ }
10
35
  function isString(value) {
11
- return value !== void 0 && value !== null && typeof value === "string";
36
+ return isDefined(value) && typeof value === "string";
37
+ }
38
+ function isStringArray(value) {
39
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
12
40
  }
13
41
  function toBase64(value) {
14
42
  try {
15
43
  return btoa(value);
16
44
  } catch (err) {
17
- return Buffer.from(value).toString("base64");
45
+ const buf = Buffer;
46
+ return buf.from(value).toString("base64");
18
47
  }
19
48
  }
20
49
 
21
- function getEnvVariable(name) {
50
+ function getEnvironment() {
22
51
  try {
23
- if (isObject(process) && isString(process?.env?.[name])) {
24
- return process.env[name];
52
+ if (isObject(process) && isObject(process.env)) {
53
+ return {
54
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
55
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
56
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
57
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
58
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
59
+ };
25
60
  }
26
61
  } catch (err) {
27
62
  }
28
63
  try {
29
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
30
- return Deno.env.get(name);
64
+ if (isObject(Deno) && isObject(Deno.env)) {
65
+ return {
66
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
67
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
68
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
69
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
70
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
71
+ };
31
72
  }
32
73
  } catch (err) {
33
74
  }
75
+ return {
76
+ apiKey: getGlobalApiKey(),
77
+ databaseURL: getGlobalDatabaseURL(),
78
+ branch: getGlobalBranch(),
79
+ envBranch: void 0,
80
+ fallbackBranch: getGlobalFallbackBranch()
81
+ };
82
+ }
83
+ function getGlobalApiKey() {
84
+ try {
85
+ return XATA_API_KEY;
86
+ } catch (err) {
87
+ return void 0;
88
+ }
89
+ }
90
+ function getGlobalDatabaseURL() {
91
+ try {
92
+ return XATA_DATABASE_URL;
93
+ } catch (err) {
94
+ return void 0;
95
+ }
96
+ }
97
+ function getGlobalBranch() {
98
+ try {
99
+ return XATA_BRANCH;
100
+ } catch (err) {
101
+ return void 0;
102
+ }
103
+ }
104
+ function getGlobalFallbackBranch() {
105
+ try {
106
+ return XATA_FALLBACK_BRANCH;
107
+ } catch (err) {
108
+ return void 0;
109
+ }
34
110
  }
35
111
  async function getGitBranch() {
112
+ const cmd = ["git", "branch", "--show-current"];
113
+ const fullCmd = cmd.join(" ");
114
+ const nodeModule = ["child", "process"].join("_");
115
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
36
116
  try {
37
117
  if (typeof require === "function") {
38
- const req = require;
39
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
118
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
40
119
  }
120
+ const { execSync } = await import(nodeModule);
121
+ return execSync(fullCmd, execOptions).toString().trim();
41
122
  } catch (err) {
42
123
  }
43
124
  try {
44
125
  if (isObject(Deno)) {
45
- const process2 = Deno.run({
46
- cmd: ["git", "branch", "--show-current"],
47
- stdout: "piped",
48
- stderr: "piped"
49
- });
126
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
50
127
  return new TextDecoder().decode(await process2.output()).trim();
51
128
  }
52
129
  } catch (err) {
@@ -55,7 +132,8 @@ async function getGitBranch() {
55
132
 
56
133
  function getAPIKey() {
57
134
  try {
58
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
135
+ const { apiKey } = getEnvironment();
136
+ return apiKey;
59
137
  } catch (err) {
60
138
  return void 0;
61
139
  }
@@ -65,21 +143,35 @@ function getFetchImplementation(userFetch) {
65
143
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
66
144
  const fetchImpl = userFetch ?? globalFetch;
67
145
  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.`);
146
+ throw new Error(
147
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
148
+ );
69
149
  }
70
150
  return fetchImpl;
71
151
  }
72
152
 
73
- class FetcherError extends Error {
74
- constructor(status, data) {
153
+ const VERSION = "0.0.0-alpha.vf8b33c9";
154
+
155
+ class ErrorWithCause extends Error {
156
+ constructor(message, options) {
157
+ super(message, options);
158
+ }
159
+ }
160
+ class FetcherError extends ErrorWithCause {
161
+ constructor(status, data, requestId) {
75
162
  super(getMessage(data));
76
163
  this.status = status;
77
164
  this.errors = isBulkError(data) ? data.errors : void 0;
165
+ this.requestId = requestId;
78
166
  if (data instanceof Error) {
79
167
  this.stack = data.stack;
80
168
  this.cause = data.cause;
81
169
  }
82
170
  }
171
+ toString() {
172
+ const error = super.toString();
173
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
174
+ }
83
175
  }
84
176
  function isBulkError(error) {
85
177
  return isObject(error) && Array.isArray(error.errors);
@@ -102,9 +194,17 @@ function getMessage(data) {
102
194
  }
103
195
 
104
196
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
105
- const query = new URLSearchParams(queryParams).toString();
197
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
198
+ if (value === void 0 || value === null)
199
+ return acc;
200
+ return { ...acc, [key]: value };
201
+ }, {});
202
+ const query = new URLSearchParams(cleanQueryParams).toString();
106
203
  const queryString = query.length > 0 ? `?${query}` : "";
107
- return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
204
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
205
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
206
+ }, {});
207
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
108
208
  };
109
209
  function buildBaseUrl({
110
210
  path,
@@ -112,10 +212,10 @@ function buildBaseUrl({
112
212
  apiUrl,
113
213
  pathParams
114
214
  }) {
115
- if (!pathParams?.workspace)
215
+ if (pathParams?.workspace === void 0)
116
216
  return `${apiUrl}${path}`;
117
217
  const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
118
- return url.replace("{workspaceId}", pathParams.workspace);
218
+ return url.replace("{workspaceId}", String(pathParams.workspace));
119
219
  }
120
220
  function hostHeader(url) {
121
221
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
@@ -132,32 +232,61 @@ async function fetch$1({
132
232
  fetchImpl,
133
233
  apiKey,
134
234
  apiUrl,
135
- workspacesApiUrl
235
+ workspacesApiUrl,
236
+ trace
136
237
  }) {
137
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
138
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
139
- 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,
143
- headers: {
144
- "Content-Type": "application/json",
145
- ...headers,
146
- ...hostHeader(fullUrl),
147
- Authorization: `Bearer ${apiKey}`
148
- }
149
- });
150
- if (response.status === 204) {
151
- return {};
152
- }
238
+ return trace(
239
+ `${method.toUpperCase()} ${path}`,
240
+ async ({ setAttributes }) => {
241
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
242
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
243
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
244
+ setAttributes({
245
+ [TraceAttributes.HTTP_URL]: url,
246
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
247
+ });
248
+ const response = await fetchImpl(url, {
249
+ method: method.toUpperCase(),
250
+ body: body ? JSON.stringify(body) : void 0,
251
+ headers: {
252
+ "Content-Type": "application/json",
253
+ "User-Agent": `Xata client-ts/${VERSION}`,
254
+ ...headers,
255
+ ...hostHeader(fullUrl),
256
+ Authorization: `Bearer ${apiKey}`
257
+ }
258
+ });
259
+ if (response.status === 204) {
260
+ return {};
261
+ }
262
+ const { host, protocol } = parseUrl(response.url);
263
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
264
+ setAttributes({
265
+ [TraceAttributes.KIND]: "http",
266
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
267
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
268
+ [TraceAttributes.HTTP_HOST]: host,
269
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
270
+ });
271
+ try {
272
+ const jsonResponse = await response.json();
273
+ if (response.ok) {
274
+ return jsonResponse;
275
+ }
276
+ throw new FetcherError(response.status, jsonResponse, requestId);
277
+ } catch (error) {
278
+ throw new FetcherError(response.status, error, requestId);
279
+ }
280
+ },
281
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
282
+ );
283
+ }
284
+ function parseUrl(url) {
153
285
  try {
154
- const jsonResponse = await response.json();
155
- if (response.ok) {
156
- return jsonResponse;
157
- }
158
- throw new FetcherError(response.status, jsonResponse);
286
+ const { host, protocol } = new URL(url);
287
+ return { host, protocol };
159
288
  } catch (error) {
160
- throw new FetcherError(response.status, error);
289
+ return {};
161
290
  }
162
291
  }
163
292
 
@@ -216,6 +345,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
216
345
  ...variables
217
346
  });
218
347
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
348
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
219
349
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
220
350
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
221
351
  method: "delete",
@@ -251,6 +381,12 @@ const deleteDatabase = (variables) => fetch$1({
251
381
  method: "delete",
252
382
  ...variables
253
383
  });
384
+ const getDatabaseMetadata = (variables) => fetch$1({
385
+ url: "/dbs/{dbName}/metadata",
386
+ method: "get",
387
+ ...variables
388
+ });
389
+ const updateDatabaseMetadata = (variables) => fetch$1({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables });
254
390
  const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
255
391
  const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
256
392
  const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
@@ -259,16 +395,28 @@ const resolveBranch = (variables) => fetch$1({
259
395
  method: "get",
260
396
  ...variables
261
397
  });
262
- const getBranchDetails = (variables) => fetch$1({
263
- url: "/db/{dbBranchName}",
398
+ const listMigrationRequests = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/list", method: "post", ...variables });
399
+ const createMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations", method: "post", ...variables });
400
+ const getMigrationRequest = (variables) => fetch$1({
401
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
264
402
  method: "get",
265
403
  ...variables
266
404
  });
267
- const createBranch = (variables) => fetch$1({
405
+ const updateMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables });
406
+ const listMigrationRequestsCommits = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables });
407
+ const compareMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables });
408
+ const getMigrationRequestIsMerged = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables });
409
+ const mergeMigrationRequest = (variables) => fetch$1({
410
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
411
+ method: "post",
412
+ ...variables
413
+ });
414
+ const getBranchDetails = (variables) => fetch$1({
268
415
  url: "/db/{dbBranchName}",
269
- method: "put",
416
+ method: "get",
270
417
  ...variables
271
418
  });
419
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
272
420
  const deleteBranch = (variables) => fetch$1({
273
421
  url: "/db/{dbBranchName}",
274
422
  method: "delete",
@@ -287,6 +435,16 @@ const getBranchMetadata = (variables) => fetch$1({
287
435
  const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
288
436
  const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
289
437
  const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
438
+ const compareBranchWithUserSchema = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables });
439
+ const compareBranchSchemas = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables });
440
+ const updateBranchSchema = (variables) => fetch$1({
441
+ url: "/db/{dbBranchName}/schema/update",
442
+ method: "post",
443
+ ...variables
444
+ });
445
+ const previewBranchSchemaEdit = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables });
446
+ const applyBranchSchemaEdit = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables });
447
+ const getBranchSchemaHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables });
290
448
  const getBranchStats = (variables) => fetch$1({
291
449
  url: "/db/{dbBranchName}/stats",
292
450
  method: "get",
@@ -342,11 +500,7 @@ const updateColumn = (variables) => fetch$1({
342
500
  method: "patch",
343
501
  ...variables
344
502
  });
345
- const insertRecord = (variables) => fetch$1({
346
- url: "/db/{dbBranchName}/tables/{tableName}/data",
347
- method: "post",
348
- ...variables
349
- });
503
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
350
504
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
351
505
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
352
506
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -366,6 +520,11 @@ const queryTable = (variables) => fetch$1({
366
520
  method: "post",
367
521
  ...variables
368
522
  });
523
+ const searchTable = (variables) => fetch$1({
524
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
525
+ method: "post",
526
+ ...variables
527
+ });
369
528
  const searchBranch = (variables) => fetch$1({
370
529
  url: "/db/{dbBranchName}/search",
371
530
  method: "post",
@@ -383,6 +542,7 @@ const operationsByTag = {
383
542
  updateWorkspaceMemberRole,
384
543
  removeWorkspaceMember,
385
544
  inviteWorkspaceMember,
545
+ updateWorkspaceMemberInvite,
386
546
  cancelWorkspaceMemberInvite,
387
547
  resendWorkspaceMemberInvite,
388
548
  acceptWorkspaceMemberInvite
@@ -391,6 +551,8 @@ const operationsByTag = {
391
551
  getDatabaseList,
392
552
  createDatabase,
393
553
  deleteDatabase,
554
+ getDatabaseMetadata,
555
+ updateDatabaseMetadata,
394
556
  getGitBranchesMapping,
395
557
  addGitBranchesEntry,
396
558
  removeGitBranchesEntry,
@@ -403,10 +565,28 @@ const operationsByTag = {
403
565
  deleteBranch,
404
566
  updateBranchMetadata,
405
567
  getBranchMetadata,
568
+ getBranchStats
569
+ },
570
+ migrationRequests: {
571
+ listMigrationRequests,
572
+ createMigrationRequest,
573
+ getMigrationRequest,
574
+ updateMigrationRequest,
575
+ listMigrationRequestsCommits,
576
+ compareMigrationRequest,
577
+ getMigrationRequestIsMerged,
578
+ mergeMigrationRequest
579
+ },
580
+ branchSchema: {
406
581
  getBranchMigrationHistory,
407
582
  executeBranchMigrationPlan,
408
583
  getBranchMigrationPlan,
409
- getBranchStats
584
+ compareBranchWithUserSchema,
585
+ compareBranchSchemas,
586
+ updateBranchSchema,
587
+ previewBranchSchemaEdit,
588
+ applyBranchSchemaEdit,
589
+ getBranchSchemaHistory
410
590
  },
411
591
  table: {
412
592
  createTable,
@@ -429,14 +609,15 @@ const operationsByTag = {
429
609
  getRecord,
430
610
  bulkInsertTableRecords,
431
611
  queryTable,
612
+ searchTable,
432
613
  searchBranch
433
614
  }
434
615
  };
435
616
 
436
617
  function getHostUrl(provider, type) {
437
- if (isValidAlias(provider)) {
618
+ if (isHostProviderAlias(provider)) {
438
619
  return providers[provider][type];
439
- } else if (isValidBuilder(provider)) {
620
+ } else if (isHostProviderBuilder(provider)) {
440
621
  return provider[type];
441
622
  }
442
623
  throw new Error("Invalid API provider");
@@ -451,10 +632,10 @@ const providers = {
451
632
  workspaces: "https://{workspaceId}.staging.xatabase.co"
452
633
  }
453
634
  };
454
- function isValidAlias(alias) {
635
+ function isHostProviderAlias(alias) {
455
636
  return isString(alias) && Object.keys(providers).includes(alias);
456
637
  }
457
- function isValidBuilder(builder) {
638
+ function isHostProviderBuilder(builder) {
458
639
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
459
640
  }
460
641
 
@@ -471,7 +652,7 @@ var __privateAdd$7 = (obj, member, value) => {
471
652
  throw TypeError("Cannot add the same private member more than once");
472
653
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
473
654
  };
474
- var __privateSet$6 = (obj, member, value, setter) => {
655
+ var __privateSet$7 = (obj, member, value, setter) => {
475
656
  __accessCheck$7(obj, member, "write to private field");
476
657
  setter ? setter.call(obj, value) : member.set(obj, value);
477
658
  return value;
@@ -482,15 +663,17 @@ class XataApiClient {
482
663
  __privateAdd$7(this, _extraProps, void 0);
483
664
  __privateAdd$7(this, _namespaces, {});
484
665
  const provider = options.host ?? "production";
485
- const apiKey = options?.apiKey ?? getAPIKey();
666
+ const apiKey = options.apiKey ?? getAPIKey();
667
+ const trace = options.trace ?? defaultTrace;
486
668
  if (!apiKey) {
487
669
  throw new Error("Could not resolve a valid apiKey");
488
670
  }
489
- __privateSet$6(this, _extraProps, {
671
+ __privateSet$7(this, _extraProps, {
490
672
  apiUrl: getHostUrl(provider, "main"),
491
673
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
492
674
  fetchImpl: getFetchImplementation(options.fetch),
493
- apiKey
675
+ apiKey,
676
+ trace
494
677
  });
495
678
  }
496
679
  get user() {
@@ -523,6 +706,16 @@ class XataApiClient {
523
706
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
524
707
  return __privateGet$7(this, _namespaces).records;
525
708
  }
709
+ get migrationRequests() {
710
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
711
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
712
+ return __privateGet$7(this, _namespaces).migrationRequests;
713
+ }
714
+ get branchSchema() {
715
+ if (!__privateGet$7(this, _namespaces).branchSchema)
716
+ __privateGet$7(this, _namespaces).branchSchema = new BranchSchemaApi(__privateGet$7(this, _extraProps));
717
+ return __privateGet$7(this, _namespaces).branchSchema;
718
+ }
526
719
  }
527
720
  _extraProps = new WeakMap();
528
721
  _namespaces = new WeakMap();
@@ -613,6 +806,13 @@ class WorkspaceApi {
613
806
  ...this.extraProps
614
807
  });
615
808
  }
809
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
810
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
811
+ pathParams: { workspaceId, inviteId },
812
+ body: { role },
813
+ ...this.extraProps
814
+ });
815
+ }
616
816
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
617
817
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
618
818
  pathParams: { workspaceId, inviteId },
@@ -655,6 +855,19 @@ class DatabaseApi {
655
855
  ...this.extraProps
656
856
  });
657
857
  }
858
+ getDatabaseMetadata(workspace, dbName) {
859
+ return operationsByTag.database.getDatabaseMetadata({
860
+ pathParams: { workspace, dbName },
861
+ ...this.extraProps
862
+ });
863
+ }
864
+ updateDatabaseMetadata(workspace, dbName, options = {}) {
865
+ return operationsByTag.database.updateDatabaseMetadata({
866
+ pathParams: { workspace, dbName },
867
+ body: options,
868
+ ...this.extraProps
869
+ });
870
+ }
658
871
  getGitBranchesMapping(workspace, dbName) {
659
872
  return operationsByTag.database.getGitBranchesMapping({
660
873
  pathParams: { workspace, dbName },
@@ -675,10 +888,10 @@ class DatabaseApi {
675
888
  ...this.extraProps
676
889
  });
677
890
  }
678
- resolveBranch(workspace, dbName, gitBranch) {
891
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
679
892
  return operationsByTag.database.resolveBranch({
680
893
  pathParams: { workspace, dbName },
681
- queryParams: { gitBranch },
894
+ queryParams: { gitBranch, fallbackBranch },
682
895
  ...this.extraProps
683
896
  });
684
897
  }
@@ -699,10 +912,10 @@ class BranchApi {
699
912
  ...this.extraProps
700
913
  });
701
914
  }
702
- createBranch(workspace, database, branch, from = "", options = {}) {
915
+ createBranch(workspace, database, branch, from, options = {}) {
703
916
  return operationsByTag.branch.createBranch({
704
917
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
705
- queryParams: { from },
918
+ queryParams: isString(from) ? { from } : void 0,
706
919
  body: options,
707
920
  ...this.extraProps
708
921
  });
@@ -726,27 +939,6 @@ class BranchApi {
726
939
  ...this.extraProps
727
940
  });
728
941
  }
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
942
  getBranchStats(workspace, database, branch) {
751
943
  return operationsByTag.branch.getBranchStats({
752
944
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -827,9 +1019,10 @@ class RecordsApi {
827
1019
  constructor(extraProps) {
828
1020
  this.extraProps = extraProps;
829
1021
  }
830
- insertRecord(workspace, database, branch, tableName, record) {
1022
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
831
1023
  return operationsByTag.records.insertRecord({
832
1024
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1025
+ queryParams: options,
833
1026
  body: record,
834
1027
  ...this.extraProps
835
1028
  });
@@ -858,21 +1051,24 @@ class RecordsApi {
858
1051
  ...this.extraProps
859
1052
  });
860
1053
  }
861
- deleteRecord(workspace, database, branch, tableName, recordId) {
1054
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
862
1055
  return operationsByTag.records.deleteRecord({
863
1056
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1057
+ queryParams: options,
864
1058
  ...this.extraProps
865
1059
  });
866
1060
  }
867
1061
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
868
1062
  return operationsByTag.records.getRecord({
869
1063
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1064
+ queryParams: options,
870
1065
  ...this.extraProps
871
1066
  });
872
1067
  }
873
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1068
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
874
1069
  return operationsByTag.records.bulkInsertTableRecords({
875
1070
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1071
+ queryParams: options,
876
1072
  body: { records },
877
1073
  ...this.extraProps
878
1074
  });
@@ -884,6 +1080,13 @@ class RecordsApi {
884
1080
  ...this.extraProps
885
1081
  });
886
1082
  }
1083
+ searchTable(workspace, database, branch, tableName, query) {
1084
+ return operationsByTag.records.searchTable({
1085
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1086
+ body: query,
1087
+ ...this.extraProps
1088
+ });
1089
+ }
887
1090
  searchBranch(workspace, database, branch, query) {
888
1091
  return operationsByTag.records.searchBranch({
889
1092
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -892,6 +1095,131 @@ class RecordsApi {
892
1095
  });
893
1096
  }
894
1097
  }
1098
+ class MigrationRequestsApi {
1099
+ constructor(extraProps) {
1100
+ this.extraProps = extraProps;
1101
+ }
1102
+ listMigrationRequests(workspace, database, options = {}) {
1103
+ return operationsByTag.migrationRequests.listMigrationRequests({
1104
+ pathParams: { workspace, dbName: database },
1105
+ body: options,
1106
+ ...this.extraProps
1107
+ });
1108
+ }
1109
+ createMigrationRequest(workspace, database, options) {
1110
+ return operationsByTag.migrationRequests.createMigrationRequest({
1111
+ pathParams: { workspace, dbName: database },
1112
+ body: options,
1113
+ ...this.extraProps
1114
+ });
1115
+ }
1116
+ getMigrationRequest(workspace, database, migrationRequest) {
1117
+ return operationsByTag.migrationRequests.getMigrationRequest({
1118
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1119
+ ...this.extraProps
1120
+ });
1121
+ }
1122
+ updateMigrationRequest(workspace, database, migrationRequest, options) {
1123
+ return operationsByTag.migrationRequests.updateMigrationRequest({
1124
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1125
+ body: options,
1126
+ ...this.extraProps
1127
+ });
1128
+ }
1129
+ listMigrationRequestsCommits(workspace, database, migrationRequest, options = {}) {
1130
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1131
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1132
+ body: options,
1133
+ ...this.extraProps
1134
+ });
1135
+ }
1136
+ compareMigrationRequest(workspace, database, migrationRequest) {
1137
+ return operationsByTag.migrationRequests.compareMigrationRequest({
1138
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1139
+ ...this.extraProps
1140
+ });
1141
+ }
1142
+ getMigrationRequestIsMerged(workspace, database, migrationRequest) {
1143
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1144
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1145
+ ...this.extraProps
1146
+ });
1147
+ }
1148
+ mergeMigrationRequest(workspace, database, migrationRequest) {
1149
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
1150
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1151
+ ...this.extraProps
1152
+ });
1153
+ }
1154
+ }
1155
+ class BranchSchemaApi {
1156
+ constructor(extraProps) {
1157
+ this.extraProps = extraProps;
1158
+ }
1159
+ getBranchMigrationHistory(workspace, database, branch, options = {}) {
1160
+ return operationsByTag.branchSchema.getBranchMigrationHistory({
1161
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1162
+ body: options,
1163
+ ...this.extraProps
1164
+ });
1165
+ }
1166
+ executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
1167
+ return operationsByTag.branchSchema.executeBranchMigrationPlan({
1168
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1169
+ body: migrationPlan,
1170
+ ...this.extraProps
1171
+ });
1172
+ }
1173
+ getBranchMigrationPlan(workspace, database, branch, schema) {
1174
+ return operationsByTag.branchSchema.getBranchMigrationPlan({
1175
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1176
+ body: schema,
1177
+ ...this.extraProps
1178
+ });
1179
+ }
1180
+ compareBranchWithUserSchema(workspace, database, branch, schema) {
1181
+ return operationsByTag.branchSchema.compareBranchWithUserSchema({
1182
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1183
+ body: { schema },
1184
+ ...this.extraProps
1185
+ });
1186
+ }
1187
+ compareBranchSchemas(workspace, database, branch, branchName, schema) {
1188
+ return operationsByTag.branchSchema.compareBranchSchemas({
1189
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, branchName },
1190
+ body: { schema },
1191
+ ...this.extraProps
1192
+ });
1193
+ }
1194
+ updateBranchSchema(workspace, database, branch, migration) {
1195
+ return operationsByTag.branchSchema.updateBranchSchema({
1196
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1197
+ body: migration,
1198
+ ...this.extraProps
1199
+ });
1200
+ }
1201
+ previewBranchSchemaEdit(workspace, database, branch, migration) {
1202
+ return operationsByTag.branchSchema.previewBranchSchemaEdit({
1203
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1204
+ body: migration,
1205
+ ...this.extraProps
1206
+ });
1207
+ }
1208
+ applyBranchSchemaEdit(workspace, database, branch, edits) {
1209
+ return operationsByTag.branchSchema.applyBranchSchemaEdit({
1210
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1211
+ body: { edits },
1212
+ ...this.extraProps
1213
+ });
1214
+ }
1215
+ getBranchSchemaHistory(workspace, database, branch, options = {}) {
1216
+ return operationsByTag.branchSchema.getBranchSchemaHistory({
1217
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1218
+ body: options,
1219
+ ...this.extraProps
1220
+ });
1221
+ }
1222
+ }
895
1223
 
896
1224
  class XataApiPlugin {
897
1225
  async build(options) {
@@ -916,18 +1244,18 @@ var __privateAdd$6 = (obj, member, value) => {
916
1244
  throw TypeError("Cannot add the same private member more than once");
917
1245
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
918
1246
  };
919
- var __privateSet$5 = (obj, member, value, setter) => {
1247
+ var __privateSet$6 = (obj, member, value, setter) => {
920
1248
  __accessCheck$6(obj, member, "write to private field");
921
1249
  setter ? setter.call(obj, value) : member.set(obj, value);
922
1250
  return value;
923
1251
  };
924
- var _query;
1252
+ var _query, _page;
925
1253
  class Page {
926
1254
  constructor(query, meta, records = []) {
927
1255
  __privateAdd$6(this, _query, void 0);
928
- __privateSet$5(this, _query, query);
1256
+ __privateSet$6(this, _query, query);
929
1257
  this.meta = meta;
930
- this.records = records;
1258
+ this.records = new RecordArray(this, records);
931
1259
  }
932
1260
  async nextPage(size, offset) {
933
1261
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
@@ -947,9 +1275,56 @@ class Page {
947
1275
  }
948
1276
  _query = new WeakMap();
949
1277
  const PAGINATION_MAX_SIZE = 200;
950
- const PAGINATION_DEFAULT_SIZE = 200;
1278
+ const PAGINATION_DEFAULT_SIZE = 20;
951
1279
  const PAGINATION_MAX_OFFSET = 800;
952
1280
  const PAGINATION_DEFAULT_OFFSET = 0;
1281
+ function isCursorPaginationOptions(options) {
1282
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1283
+ }
1284
+ const _RecordArray = class extends Array {
1285
+ constructor(...args) {
1286
+ super(..._RecordArray.parseConstructorParams(...args));
1287
+ __privateAdd$6(this, _page, void 0);
1288
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1289
+ }
1290
+ static parseConstructorParams(...args) {
1291
+ if (args.length === 1 && typeof args[0] === "number") {
1292
+ return new Array(args[0]);
1293
+ }
1294
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1295
+ const result = args[1] ?? args[0].records ?? [];
1296
+ return new Array(...result);
1297
+ }
1298
+ return new Array(...args);
1299
+ }
1300
+ toArray() {
1301
+ return new Array(...this);
1302
+ }
1303
+ map(callbackfn, thisArg) {
1304
+ return this.toArray().map(callbackfn, thisArg);
1305
+ }
1306
+ async nextPage(size, offset) {
1307
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1308
+ return new _RecordArray(newPage);
1309
+ }
1310
+ async previousPage(size, offset) {
1311
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1312
+ return new _RecordArray(newPage);
1313
+ }
1314
+ async firstPage(size, offset) {
1315
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1316
+ return new _RecordArray(newPage);
1317
+ }
1318
+ async lastPage(size, offset) {
1319
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1320
+ return new _RecordArray(newPage);
1321
+ }
1322
+ hasNextPage() {
1323
+ return __privateGet$6(this, _page).meta.page.more;
1324
+ }
1325
+ };
1326
+ let RecordArray = _RecordArray;
1327
+ _page = new WeakMap();
953
1328
 
954
1329
  var __accessCheck$5 = (obj, member, msg) => {
955
1330
  if (!member.has(obj))
@@ -964,25 +1339,26 @@ var __privateAdd$5 = (obj, member, value) => {
964
1339
  throw TypeError("Cannot add the same private member more than once");
965
1340
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
966
1341
  };
967
- var __privateSet$4 = (obj, member, value, setter) => {
1342
+ var __privateSet$5 = (obj, member, value, setter) => {
968
1343
  __accessCheck$5(obj, member, "write to private field");
969
1344
  setter ? setter.call(obj, value) : member.set(obj, value);
970
1345
  return value;
971
1346
  };
972
1347
  var _table$1, _repository, _data;
973
1348
  const _Query = class {
974
- constructor(repository, table, data, parent) {
1349
+ constructor(repository, table, data, rawParent) {
975
1350
  __privateAdd$5(this, _table$1, void 0);
976
1351
  __privateAdd$5(this, _repository, void 0);
977
1352
  __privateAdd$5(this, _data, { filter: {} });
978
1353
  this.meta = { page: { cursor: "start", more: true } };
979
- this.records = [];
980
- __privateSet$4(this, _table$1, table);
1354
+ this.records = new RecordArray(this, []);
1355
+ __privateSet$5(this, _table$1, table);
981
1356
  if (repository) {
982
- __privateSet$4(this, _repository, repository);
1357
+ __privateSet$5(this, _repository, repository);
983
1358
  } else {
984
- __privateSet$4(this, _repository, this);
1359
+ __privateSet$5(this, _repository, this);
985
1360
  }
1361
+ const parent = cleanParent(data, rawParent);
986
1362
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
987
1363
  __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
988
1364
  __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
@@ -1027,55 +1403,88 @@ const _Query = class {
1027
1403
  }
1028
1404
  filter(a, b) {
1029
1405
  if (arguments.length === 1) {
1030
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1406
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({ [column]: constraint }));
1031
1407
  const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1032
1408
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1033
1409
  } else {
1034
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1410
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: this.defaultFilter(a, b) }] : void 0;
1411
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1035
1412
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1036
1413
  }
1037
1414
  }
1038
- sort(column, direction) {
1415
+ defaultFilter(column, value) {
1416
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
1417
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
1418
+ return { $includes: value };
1419
+ }
1420
+ return value;
1421
+ }
1422
+ sort(column, direction = "asc") {
1039
1423
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1040
1424
  const sort = [...originalSort, { column, direction }];
1041
1425
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1042
1426
  }
1043
1427
  select(columns) {
1044
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1428
+ return new _Query(
1429
+ __privateGet$5(this, _repository),
1430
+ __privateGet$5(this, _table$1),
1431
+ { columns },
1432
+ __privateGet$5(this, _data)
1433
+ );
1045
1434
  }
1046
1435
  getPaginated(options = {}) {
1047
1436
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1048
1437
  return __privateGet$5(this, _repository).query(query);
1049
1438
  }
1050
1439
  async *[Symbol.asyncIterator]() {
1051
- for await (const [record] of this.getIterator(1)) {
1440
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1052
1441
  yield record;
1053
1442
  }
1054
1443
  }
1055
- async *getIterator(chunk, options = {}) {
1056
- let offset = 0;
1057
- let end = false;
1058
- while (!end) {
1059
- const { records, meta } = await this.getPaginated({ ...options, pagination: { size: chunk, offset } });
1060
- yield records;
1061
- offset += chunk;
1062
- end = !meta.page.more;
1444
+ async *getIterator(options = {}) {
1445
+ const { batchSize = 1 } = options;
1446
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1447
+ let more = page.hasNextPage();
1448
+ yield page.records;
1449
+ while (more) {
1450
+ page = await page.nextPage();
1451
+ more = page.hasNextPage();
1452
+ yield page.records;
1063
1453
  }
1064
1454
  }
1065
1455
  async getMany(options = {}) {
1066
- const { records } = await this.getPaginated(options);
1067
- return records;
1456
+ const { pagination = {}, ...rest } = options;
1457
+ const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
1458
+ const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
1459
+ let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
1460
+ const results = [...page.records];
1461
+ while (page.hasNextPage() && results.length < size) {
1462
+ page = await page.nextPage();
1463
+ results.push(...page.records);
1464
+ }
1465
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1466
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1467
+ }
1468
+ const array = new RecordArray(page, results.slice(0, size));
1469
+ return array;
1068
1470
  }
1069
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1471
+ async getAll(options = {}) {
1472
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1070
1473
  const results = [];
1071
- for await (const page of this.getIterator(chunk, options)) {
1474
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1072
1475
  results.push(...page);
1073
1476
  }
1074
1477
  return results;
1075
1478
  }
1076
1479
  async getFirst(options = {}) {
1077
1480
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1078
- return records[0] || null;
1481
+ return records[0] ?? null;
1482
+ }
1483
+ async getFirstOrThrow(options = {}) {
1484
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1485
+ if (records[0] === void 0)
1486
+ throw new Error("No results found.");
1487
+ return records[0];
1079
1488
  }
1080
1489
  cache(ttl) {
1081
1490
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
@@ -1100,12 +1509,20 @@ let Query = _Query;
1100
1509
  _table$1 = new WeakMap();
1101
1510
  _repository = new WeakMap();
1102
1511
  _data = new WeakMap();
1512
+ function cleanParent(data, parent) {
1513
+ if (isCursorPaginationOptions(data.pagination)) {
1514
+ return { ...parent, sorting: void 0, filter: void 0 };
1515
+ }
1516
+ return parent;
1517
+ }
1103
1518
 
1104
1519
  function isIdentifiable(x) {
1105
1520
  return isObject(x) && isString(x?.id);
1106
1521
  }
1107
1522
  function isXataRecord(x) {
1108
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1523
+ const record = x;
1524
+ const metadata = record?.getMetadata();
1525
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1109
1526
  }
1110
1527
 
1111
1528
  function isSortFilterString(value) {
@@ -1144,7 +1561,7 @@ var __privateAdd$4 = (obj, member, value) => {
1144
1561
  throw TypeError("Cannot add the same private member more than once");
1145
1562
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1146
1563
  };
1147
- var __privateSet$3 = (obj, member, value, setter) => {
1564
+ var __privateSet$4 = (obj, member, value, setter) => {
1148
1565
  __accessCheck$4(obj, member, "write to private field");
1149
1566
  setter ? setter.call(obj, value) : member.set(obj, value);
1150
1567
  return value;
@@ -1153,180 +1570,284 @@ var __privateMethod$2 = (obj, member, method) => {
1153
1570
  __accessCheck$4(obj, member, "access private method");
1154
1571
  return method;
1155
1572
  };
1156
- var _table, _getFetchProps, _cache, _schema$1, _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, _getSchema$1, getSchema_fn$1;
1573
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
1157
1574
  class Repository extends Query {
1158
1575
  }
1159
1576
  class RestRepository extends Query {
1160
1577
  constructor(options) {
1161
- super(null, options.table, {});
1578
+ super(
1579
+ null,
1580
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
1581
+ {}
1582
+ );
1162
1583
  __privateAdd$4(this, _insertRecordWithoutId);
1163
1584
  __privateAdd$4(this, _insertRecordWithId);
1164
1585
  __privateAdd$4(this, _bulkInsertTableRecords);
1165
1586
  __privateAdd$4(this, _updateRecordWithID);
1166
1587
  __privateAdd$4(this, _upsertRecordWithID);
1167
1588
  __privateAdd$4(this, _deleteRecord);
1168
- __privateAdd$4(this, _invalidateCache);
1169
- __privateAdd$4(this, _setCacheRecord);
1170
- __privateAdd$4(this, _getCacheRecord);
1171
1589
  __privateAdd$4(this, _setCacheQuery);
1172
1590
  __privateAdd$4(this, _getCacheQuery);
1173
- __privateAdd$4(this, _getSchema$1);
1591
+ __privateAdd$4(this, _getSchemaTables$1);
1174
1592
  __privateAdd$4(this, _table, void 0);
1175
1593
  __privateAdd$4(this, _getFetchProps, void 0);
1594
+ __privateAdd$4(this, _db, void 0);
1176
1595
  __privateAdd$4(this, _cache, void 0);
1177
- __privateAdd$4(this, _schema$1, void 0);
1178
- __privateSet$3(this, _table, options.table);
1179
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1180
- this.db = options.db;
1181
- __privateSet$3(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$4(this, _getFetchProps).call(this);
1215
- try {
1216
- const response = await getRecord({
1217
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1218
- ...fetchProps
1596
+ __privateAdd$4(this, _schemaTables$2, void 0);
1597
+ __privateAdd$4(this, _trace, void 0);
1598
+ __privateSet$4(this, _table, options.table);
1599
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1600
+ __privateSet$4(this, _db, options.db);
1601
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1602
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1603
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1604
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1605
+ return trace(name, fn, {
1606
+ ...options2,
1607
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1608
+ [TraceAttributes.KIND]: "sdk-operation",
1609
+ [TraceAttributes.VERSION]: VERSION
1219
1610
  });
1220
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1221
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1222
- } catch (e) {
1223
- if (isObject(e) && e.status === 404) {
1224
- return null;
1611
+ });
1612
+ }
1613
+ async create(a, b, c) {
1614
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1615
+ if (Array.isArray(a)) {
1616
+ if (a.length === 0)
1617
+ return [];
1618
+ const columns = isStringArray(b) ? b : void 0;
1619
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1225
1620
  }
1226
- throw e;
1227
- }
1621
+ if (isString(a) && isObject(b)) {
1622
+ if (a === "")
1623
+ throw new Error("The id can't be empty");
1624
+ const columns = isStringArray(c) ? c : void 0;
1625
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1626
+ }
1627
+ if (isObject(a) && isString(a.id)) {
1628
+ if (a.id === "")
1629
+ throw new Error("The id can't be empty");
1630
+ const columns = isStringArray(b) ? b : void 0;
1631
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1632
+ }
1633
+ if (isObject(a)) {
1634
+ const columns = isStringArray(b) ? b : void 0;
1635
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1636
+ }
1637
+ throw new Error("Invalid arguments for create method");
1638
+ });
1228
1639
  }
1229
- async update(a, b) {
1230
- if (Array.isArray(a)) {
1231
- if (a.length > 100) {
1232
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1640
+ async read(a, b) {
1641
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1642
+ const columns = isStringArray(b) ? b : ["*"];
1643
+ if (Array.isArray(a)) {
1644
+ if (a.length === 0)
1645
+ return [];
1646
+ const ids = a.map((item) => extractId(item));
1647
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1648
+ const dictionary = finalObjects.reduce((acc, object) => {
1649
+ acc[object.id] = object;
1650
+ return acc;
1651
+ }, {});
1652
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1233
1653
  }
1234
- return Promise.all(a.map((object) => this.update(object)));
1235
- }
1236
- if (isString(a) && isObject(b)) {
1237
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1238
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1239
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1240
- return record;
1241
- }
1242
- if (isObject(a) && isString(a.id)) {
1243
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1244
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1245
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1246
- return record;
1247
- }
1248
- throw new Error("Invalid arguments for update method");
1654
+ const id = extractId(a);
1655
+ if (id) {
1656
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1657
+ try {
1658
+ const response = await getRecord({
1659
+ pathParams: {
1660
+ workspace: "{workspaceId}",
1661
+ dbBranchName: "{dbBranch}",
1662
+ tableName: __privateGet$4(this, _table),
1663
+ recordId: id
1664
+ },
1665
+ queryParams: { columns },
1666
+ ...fetchProps
1667
+ });
1668
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1669
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1670
+ } catch (e) {
1671
+ if (isObject(e) && e.status === 404) {
1672
+ return null;
1673
+ }
1674
+ throw e;
1675
+ }
1676
+ }
1677
+ return null;
1678
+ });
1249
1679
  }
1250
- async createOrUpdate(a, b) {
1251
- if (Array.isArray(a)) {
1252
- if (a.length > 100) {
1253
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1680
+ async readOrThrow(a, b) {
1681
+ return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
1682
+ const result = await this.read(a, b);
1683
+ if (Array.isArray(result)) {
1684
+ const missingIds = compact(
1685
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1686
+ );
1687
+ if (missingIds.length > 0) {
1688
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1689
+ }
1690
+ return result;
1254
1691
  }
1255
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1256
- }
1257
- if (isString(a) && isObject(b)) {
1258
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1259
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1260
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1261
- return record;
1262
- }
1263
- if (isObject(a) && isString(a.id)) {
1264
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1265
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1266
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1267
- return record;
1268
- }
1269
- throw new Error("Invalid arguments for createOrUpdate method");
1692
+ if (result === null) {
1693
+ const id = extractId(a) ?? "unknown";
1694
+ throw new Error(`Record with id ${id} not found`);
1695
+ }
1696
+ return result;
1697
+ });
1698
+ }
1699
+ async update(a, b, c) {
1700
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1701
+ if (Array.isArray(a)) {
1702
+ if (a.length === 0)
1703
+ return [];
1704
+ if (a.length > 100) {
1705
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1706
+ }
1707
+ const columns = isStringArray(b) ? b : ["*"];
1708
+ return Promise.all(a.map((object) => this.update(object, columns)));
1709
+ }
1710
+ if (isString(a) && isObject(b)) {
1711
+ const columns = isStringArray(c) ? c : void 0;
1712
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1713
+ }
1714
+ if (isObject(a) && isString(a.id)) {
1715
+ const columns = isStringArray(b) ? b : void 0;
1716
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1717
+ }
1718
+ throw new Error("Invalid arguments for update method");
1719
+ });
1270
1720
  }
1271
- async delete(a) {
1272
- if (Array.isArray(a)) {
1273
- if (a.length > 100) {
1274
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1721
+ async updateOrThrow(a, b, c) {
1722
+ return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
1723
+ const result = await this.update(a, b, c);
1724
+ if (Array.isArray(result)) {
1725
+ const missingIds = compact(
1726
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1727
+ );
1728
+ if (missingIds.length > 0) {
1729
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1730
+ }
1731
+ return result;
1275
1732
  }
1276
- await Promise.all(a.map((id) => this.delete(id)));
1277
- return;
1278
- }
1279
- if (isString(a)) {
1280
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1281
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1282
- return;
1283
- }
1284
- if (isObject(a) && isString(a.id)) {
1285
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1286
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1287
- return;
1288
- }
1289
- throw new Error("Invalid arguments for delete method");
1733
+ if (result === null) {
1734
+ const id = extractId(a) ?? "unknown";
1735
+ throw new Error(`Record with id ${id} not found`);
1736
+ }
1737
+ return result;
1738
+ });
1739
+ }
1740
+ async createOrUpdate(a, b, c) {
1741
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1742
+ if (Array.isArray(a)) {
1743
+ if (a.length === 0)
1744
+ return [];
1745
+ if (a.length > 100) {
1746
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1747
+ }
1748
+ const columns = isStringArray(b) ? b : ["*"];
1749
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1750
+ }
1751
+ if (isString(a) && isObject(b)) {
1752
+ const columns = isStringArray(c) ? c : void 0;
1753
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1754
+ }
1755
+ if (isObject(a) && isString(a.id)) {
1756
+ const columns = isStringArray(c) ? c : void 0;
1757
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1758
+ }
1759
+ throw new Error("Invalid arguments for createOrUpdate method");
1760
+ });
1761
+ }
1762
+ async delete(a, b) {
1763
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1764
+ if (Array.isArray(a)) {
1765
+ if (a.length === 0)
1766
+ return [];
1767
+ if (a.length > 100) {
1768
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1769
+ }
1770
+ return Promise.all(a.map((id) => this.delete(id, b)));
1771
+ }
1772
+ if (isString(a)) {
1773
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1774
+ }
1775
+ if (isObject(a) && isString(a.id)) {
1776
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1777
+ }
1778
+ throw new Error("Invalid arguments for delete method");
1779
+ });
1780
+ }
1781
+ async deleteOrThrow(a, b) {
1782
+ return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
1783
+ const result = await this.delete(a, b);
1784
+ if (Array.isArray(result)) {
1785
+ const missingIds = compact(
1786
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1787
+ );
1788
+ if (missingIds.length > 0) {
1789
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1790
+ }
1791
+ return result;
1792
+ } else if (result === null) {
1793
+ const id = extractId(a) ?? "unknown";
1794
+ throw new Error(`Record with id ${id} not found`);
1795
+ }
1796
+ return result;
1797
+ });
1290
1798
  }
1291
1799
  async search(query, options = {}) {
1292
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1293
- const { records } = await searchBranch({
1294
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1295
- body: { tables: [__privateGet$4(this, _table)], query, fuzziness: options.fuzziness },
1296
- ...fetchProps
1800
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1801
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1802
+ const { records } = await searchTable({
1803
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1804
+ body: {
1805
+ query,
1806
+ fuzziness: options.fuzziness,
1807
+ prefix: options.prefix,
1808
+ highlight: options.highlight,
1809
+ filter: options.filter,
1810
+ boosters: options.boosters
1811
+ },
1812
+ ...fetchProps
1813
+ });
1814
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1815
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1297
1816
  });
1298
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1299
- return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1300
1817
  }
1301
1818
  async query(query) {
1302
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1303
- if (cacheQuery)
1304
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1305
- const data = query.getQueryOptions();
1306
- const body = {
1307
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1308
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1309
- page: data.pagination,
1310
- columns: data.columns
1311
- };
1312
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1313
- const { meta, records: objects } = await queryTable({
1314
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1315
- body,
1316
- ...fetchProps
1819
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1820
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1821
+ if (cacheQuery)
1822
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1823
+ const data = query.getQueryOptions();
1824
+ const body = {
1825
+ filter: cleanFilter(data.filter),
1826
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1827
+ page: data.pagination,
1828
+ columns: data.columns
1829
+ };
1830
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1831
+ const { meta, records: objects } = await queryTable({
1832
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1833
+ body,
1834
+ ...fetchProps
1835
+ });
1836
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1837
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1838
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1839
+ return new Page(query, meta, records);
1317
1840
  });
1318
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1319
- const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1320
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1321
- return new Page(query, meta, records);
1322
1841
  }
1323
1842
  }
1324
1843
  _table = new WeakMap();
1325
1844
  _getFetchProps = new WeakMap();
1845
+ _db = new WeakMap();
1326
1846
  _cache = new WeakMap();
1327
- _schema$1 = new WeakMap();
1847
+ _schemaTables$2 = new WeakMap();
1848
+ _trace = new WeakMap();
1328
1849
  _insertRecordWithoutId = new WeakSet();
1329
- insertRecordWithoutId_fn = async function(object) {
1850
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1330
1851
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1331
1852
  const record = transformObjectLinks(object);
1332
1853
  const response = await insertRecord({
@@ -1335,17 +1856,15 @@ insertRecordWithoutId_fn = async function(object) {
1335
1856
  dbBranchName: "{dbBranch}",
1336
1857
  tableName: __privateGet$4(this, _table)
1337
1858
  },
1859
+ queryParams: { columns },
1338
1860
  body: record,
1339
1861
  ...fetchProps
1340
1862
  });
1341
- const finalObject = await this.read(response.id);
1342
- if (!finalObject) {
1343
- throw new Error("The server failed to save the record");
1344
- }
1345
- return finalObject;
1863
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1864
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1346
1865
  };
1347
1866
  _insertRecordWithId = new WeakSet();
1348
- insertRecordWithId_fn = async function(recordId, object) {
1867
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1349
1868
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1350
1869
  const record = transformObjectLinks(object);
1351
1870
  const response = await insertRecordWithID({
@@ -1356,88 +1875,78 @@ insertRecordWithId_fn = async function(recordId, object) {
1356
1875
  recordId
1357
1876
  },
1358
1877
  body: record,
1359
- queryParams: { createOnly: true },
1878
+ queryParams: { createOnly: true, columns },
1360
1879
  ...fetchProps
1361
1880
  });
1362
- const finalObject = await this.read(response.id);
1363
- if (!finalObject) {
1364
- throw new Error("The server failed to save the record");
1365
- }
1366
- return finalObject;
1881
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1882
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1367
1883
  };
1368
1884
  _bulkInsertTableRecords = new WeakSet();
1369
- bulkInsertTableRecords_fn = async function(objects) {
1885
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1370
1886
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1371
1887
  const records = objects.map((object) => transformObjectLinks(object));
1372
1888
  const response = await bulkInsertTableRecords({
1373
1889
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1890
+ queryParams: { columns },
1374
1891
  body: { records },
1375
1892
  ...fetchProps
1376
1893
  });
1377
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1378
- if (finalObjects.length !== objects.length) {
1379
- throw new Error("The server failed to save some records");
1894
+ if (!isResponseWithRecords(response)) {
1895
+ throw new Error("Request included columns but server didn't include them");
1380
1896
  }
1381
- return finalObjects;
1897
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1898
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1382
1899
  };
1383
1900
  _updateRecordWithID = new WeakSet();
1384
- updateRecordWithID_fn = async function(recordId, object) {
1901
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1385
1902
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1386
1903
  const record = transformObjectLinks(object);
1387
- const response = await updateRecordWithID({
1388
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1389
- body: record,
1390
- ...fetchProps
1391
- });
1392
- const item = await this.read(response.id);
1393
- if (!item)
1394
- throw new Error("The server failed to save the record");
1395
- return item;
1904
+ try {
1905
+ const response = await updateRecordWithID({
1906
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1907
+ queryParams: { columns },
1908
+ body: record,
1909
+ ...fetchProps
1910
+ });
1911
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1912
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1913
+ } catch (e) {
1914
+ if (isObject(e) && e.status === 404) {
1915
+ return null;
1916
+ }
1917
+ throw e;
1918
+ }
1396
1919
  };
1397
1920
  _upsertRecordWithID = new WeakSet();
1398
- upsertRecordWithID_fn = async function(recordId, object) {
1921
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1399
1922
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1400
1923
  const response = await upsertRecordWithID({
1401
1924
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1925
+ queryParams: { columns },
1402
1926
  body: object,
1403
1927
  ...fetchProps
1404
1928
  });
1405
- const item = await this.read(response.id);
1406
- if (!item)
1407
- throw new Error("The server failed to save the record");
1408
- return item;
1929
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1930
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1409
1931
  };
1410
1932
  _deleteRecord = new WeakSet();
1411
- deleteRecord_fn = async function(recordId) {
1933
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1412
1934
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1413
- await deleteRecord({
1414
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1415
- ...fetchProps
1416
- });
1417
- };
1418
- _invalidateCache = new WeakSet();
1419
- invalidateCache_fn = async function(recordId) {
1420
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1421
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1422
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1423
- for (const [key, value] of queries) {
1424
- const ids = getIds(value);
1425
- if (ids.includes(recordId))
1426
- await __privateGet$4(this, _cache).delete(key);
1935
+ try {
1936
+ const response = await deleteRecord({
1937
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1938
+ queryParams: { columns },
1939
+ ...fetchProps
1940
+ });
1941
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1942
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1943
+ } catch (e) {
1944
+ if (isObject(e) && e.status === 404) {
1945
+ return null;
1946
+ }
1947
+ throw e;
1427
1948
  }
1428
1949
  };
1429
- _setCacheRecord = new WeakSet();
1430
- setCacheRecord_fn = async function(record) {
1431
- if (!__privateGet$4(this, _cache).cacheRecords)
1432
- return;
1433
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1434
- };
1435
- _getCacheRecord = new WeakSet();
1436
- getCacheRecord_fn = async function(recordId) {
1437
- if (!__privateGet$4(this, _cache).cacheRecords)
1438
- return null;
1439
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1440
- };
1441
1950
  _setCacheQuery = new WeakSet();
1442
1951
  setCacheQuery_fn = async function(query, meta, records) {
1443
1952
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -1449,22 +1958,22 @@ getCacheQuery_fn = async function(query) {
1449
1958
  if (!result)
1450
1959
  return null;
1451
1960
  const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1452
- if (!ttl || ttl < 0)
1453
- return result;
1961
+ if (ttl < 0)
1962
+ return null;
1454
1963
  const hasExpired = result.date.getTime() + ttl < Date.now();
1455
1964
  return hasExpired ? null : result;
1456
1965
  };
1457
- _getSchema$1 = new WeakSet();
1458
- getSchema_fn$1 = async function() {
1459
- if (__privateGet$4(this, _schema$1))
1460
- return __privateGet$4(this, _schema$1);
1966
+ _getSchemaTables$1 = new WeakSet();
1967
+ getSchemaTables_fn$1 = async function() {
1968
+ if (__privateGet$4(this, _schemaTables$2))
1969
+ return __privateGet$4(this, _schemaTables$2);
1461
1970
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1462
1971
  const { schema } = await getBranchDetails({
1463
1972
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1464
1973
  ...fetchProps
1465
1974
  });
1466
- __privateSet$3(this, _schema$1, schema);
1467
- return schema;
1975
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1976
+ return schema.tables;
1468
1977
  };
1469
1978
  const transformObjectLinks = (object) => {
1470
1979
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1473,20 +1982,21 @@ const transformObjectLinks = (object) => {
1473
1982
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1474
1983
  }, {});
1475
1984
  };
1476
- const initObject = (db, schema, table, object) => {
1985
+ const initObject = (db, schemaTables, table, object) => {
1477
1986
  const result = {};
1478
- Object.assign(result, object);
1479
- const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1987
+ const { xata, ...rest } = object ?? {};
1988
+ Object.assign(result, rest);
1989
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1480
1990
  if (!columns)
1481
1991
  console.error(`Table ${table} not found in schema`);
1482
1992
  for (const column of columns ?? []) {
1483
1993
  const value = result[column.name];
1484
1994
  switch (column.type) {
1485
1995
  case "datetime": {
1486
- const date = new Date(value);
1487
- if (isNaN(date.getTime())) {
1996
+ const date = value !== void 0 ? new Date(value) : void 0;
1997
+ if (date && isNaN(date.getTime())) {
1488
1998
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1489
- } else {
1999
+ } else if (date) {
1490
2000
  result[column.name] = date;
1491
2001
  }
1492
2002
  break;
@@ -1495,36 +2005,54 @@ const initObject = (db, schema, table, object) => {
1495
2005
  const linkTable = column.link?.table;
1496
2006
  if (!linkTable) {
1497
2007
  console.error(`Failed to parse link for field ${column.name}`);
1498
- } else if (value && isObject(value)) {
1499
- result[column.name] = initObject(db, schema, linkTable, value);
2008
+ } else if (isObject(value)) {
2009
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
2010
+ } else {
2011
+ result[column.name] = null;
1500
2012
  }
1501
2013
  break;
1502
2014
  }
2015
+ default:
2016
+ result[column.name] = value ?? null;
2017
+ if (column.notNull === true && value === null) {
2018
+ console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2019
+ }
2020
+ break;
1503
2021
  }
1504
2022
  }
1505
- result.read = function() {
1506
- return db[table].read(result["id"]);
2023
+ result.read = function(columns2) {
2024
+ return db[table].read(result["id"], columns2);
1507
2025
  };
1508
- result.update = function(data) {
1509
- return db[table].update(result["id"], data);
2026
+ result.update = function(data, columns2) {
2027
+ return db[table].update(result["id"], data, columns2);
1510
2028
  };
1511
2029
  result.delete = function() {
1512
2030
  return db[table].delete(result["id"]);
1513
2031
  };
1514
- for (const prop of ["read", "update", "delete"]) {
2032
+ result.getMetadata = function() {
2033
+ return xata;
2034
+ };
2035
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1515
2036
  Object.defineProperty(result, prop, { enumerable: false });
1516
2037
  }
1517
2038
  Object.freeze(result);
1518
2039
  return result;
1519
2040
  };
1520
- function getIds(value) {
1521
- if (Array.isArray(value)) {
1522
- return value.map((item) => getIds(item)).flat();
1523
- }
1524
- if (!isObject(value))
1525
- return [];
1526
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1527
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
2041
+ function isResponseWithRecords(value) {
2042
+ return isObject(value) && Array.isArray(value.records);
2043
+ }
2044
+ function extractId(value) {
2045
+ if (isString(value))
2046
+ return value;
2047
+ if (isObject(value) && isString(value.id))
2048
+ return value.id;
2049
+ return void 0;
2050
+ }
2051
+ function cleanFilter(filter) {
2052
+ if (!filter)
2053
+ return void 0;
2054
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
2055
+ return values.length > 0 ? filter : void 0;
1528
2056
  }
1529
2057
 
1530
2058
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1540,7 +2068,7 @@ var __privateAdd$3 = (obj, member, value) => {
1540
2068
  throw TypeError("Cannot add the same private member more than once");
1541
2069
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1542
2070
  };
1543
- var __privateSet$2 = (obj, member, value, setter) => {
2071
+ var __privateSet$3 = (obj, member, value, setter) => {
1544
2072
  __accessCheck$3(obj, member, "write to private field");
1545
2073
  setter ? setter.call(obj, value) : member.set(obj, value);
1546
2074
  return value;
@@ -1549,9 +2077,8 @@ var _map;
1549
2077
  class SimpleCache {
1550
2078
  constructor(options = {}) {
1551
2079
  __privateAdd$3(this, _map, void 0);
1552
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
2080
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1553
2081
  this.capacity = options.max ?? 500;
1554
- this.cacheRecords = options.cacheRecords ?? true;
1555
2082
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1556
2083
  }
1557
2084
  async getAll() {
@@ -1577,18 +2104,25 @@ class SimpleCache {
1577
2104
  }
1578
2105
  _map = new WeakMap();
1579
2106
 
1580
- const gt = (value) => ({ $gt: value });
1581
- const ge = (value) => ({ $ge: value });
1582
- const gte = (value) => ({ $ge: value });
1583
- const lt = (value) => ({ $lt: value });
1584
- const lte = (value) => ({ $le: value });
1585
- const le = (value) => ({ $le: value });
2107
+ const greaterThan = (value) => ({ $gt: value });
2108
+ const gt = greaterThan;
2109
+ const greaterThanEquals = (value) => ({ $ge: value });
2110
+ const greaterEquals = greaterThanEquals;
2111
+ const gte = greaterThanEquals;
2112
+ const ge = greaterThanEquals;
2113
+ const lessThan = (value) => ({ $lt: value });
2114
+ const lt = lessThan;
2115
+ const lessThanEquals = (value) => ({ $le: value });
2116
+ const lessEquals = lessThanEquals;
2117
+ const lte = lessThanEquals;
2118
+ const le = lessThanEquals;
1586
2119
  const exists = (column) => ({ $exists: column });
1587
2120
  const notExists = (column) => ({ $notExists: column });
1588
2121
  const startsWith = (value) => ({ $startsWith: value });
1589
2122
  const endsWith = (value) => ({ $endsWith: value });
1590
2123
  const pattern = (value) => ({ $pattern: value });
1591
2124
  const is = (value) => ({ $is: value });
2125
+ const equals = is;
1592
2126
  const isNot = (value) => ({ $isNot: value });
1593
2127
  const contains = (value) => ({ $contains: value });
1594
2128
  const includes = (value) => ({ $includes: value });
@@ -1609,31 +2143,42 @@ var __privateAdd$2 = (obj, member, value) => {
1609
2143
  throw TypeError("Cannot add the same private member more than once");
1610
2144
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1611
2145
  };
1612
- var _tables;
2146
+ var __privateSet$2 = (obj, member, value, setter) => {
2147
+ __accessCheck$2(obj, member, "write to private field");
2148
+ setter ? setter.call(obj, value) : member.set(obj, value);
2149
+ return value;
2150
+ };
2151
+ var _tables, _schemaTables$1;
1613
2152
  class SchemaPlugin extends XataPlugin {
1614
- constructor(tableNames) {
2153
+ constructor(schemaTables) {
1615
2154
  super();
1616
- this.tableNames = tableNames;
1617
2155
  __privateAdd$2(this, _tables, {});
2156
+ __privateAdd$2(this, _schemaTables$1, void 0);
2157
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1618
2158
  }
1619
2159
  build(pluginOptions) {
1620
- const db = new Proxy({}, {
1621
- get: (_target, table) => {
1622
- if (!isString(table))
1623
- throw new Error("Invalid table name");
1624
- if (!__privateGet$2(this, _tables)[table]) {
1625
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
2160
+ const db = new Proxy(
2161
+ {},
2162
+ {
2163
+ get: (_target, table) => {
2164
+ if (!isString(table))
2165
+ throw new Error("Invalid table name");
2166
+ if (__privateGet$2(this, _tables)[table] === void 0) {
2167
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
2168
+ }
2169
+ return __privateGet$2(this, _tables)[table];
1626
2170
  }
1627
- return __privateGet$2(this, _tables)[table];
1628
2171
  }
1629
- });
1630
- for (const table of this.tableNames ?? []) {
1631
- db[table] = new RestRepository({ db, pluginOptions, table });
2172
+ );
2173
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
2174
+ for (const table of tableNames) {
2175
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1632
2176
  }
1633
2177
  return db;
1634
2178
  }
1635
2179
  }
1636
2180
  _tables = new WeakMap();
2181
+ _schemaTables$1 = new WeakMap();
1637
2182
 
1638
2183
  var __accessCheck$1 = (obj, member, msg) => {
1639
2184
  if (!member.has(obj))
@@ -1657,105 +2202,119 @@ var __privateMethod$1 = (obj, member, method) => {
1657
2202
  __accessCheck$1(obj, member, "access private method");
1658
2203
  return method;
1659
2204
  };
1660
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
2205
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1661
2206
  class SearchPlugin extends XataPlugin {
1662
- constructor(db) {
2207
+ constructor(db, schemaTables) {
1663
2208
  super();
1664
2209
  this.db = db;
1665
2210
  __privateAdd$1(this, _search);
1666
- __privateAdd$1(this, _getSchema);
1667
- __privateAdd$1(this, _schema, void 0);
2211
+ __privateAdd$1(this, _getSchemaTables);
2212
+ __privateAdd$1(this, _schemaTables, void 0);
2213
+ __privateSet$1(this, _schemaTables, schemaTables);
1668
2214
  }
1669
2215
  build({ getFetchProps }) {
1670
2216
  return {
1671
2217
  all: async (query, options = {}) => {
1672
2218
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1673
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
2219
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1674
2220
  return records.map((record) => {
1675
2221
  const { table = "orphan" } = record.xata;
1676
- return { table, record: initObject(this.db, schema, table, record) };
2222
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1677
2223
  });
1678
2224
  },
1679
2225
  byTable: async (query, options = {}) => {
1680
2226
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1681
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
2227
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1682
2228
  return records.reduce((acc, record) => {
1683
2229
  const { table = "orphan" } = record.xata;
1684
2230
  const items = acc[table] ?? [];
1685
- const item = initObject(this.db, schema, table, record);
2231
+ const item = initObject(this.db, schemaTables, table, record);
1686
2232
  return { ...acc, [table]: [...items, item] };
1687
2233
  }, {});
1688
2234
  }
1689
2235
  };
1690
2236
  }
1691
2237
  }
1692
- _schema = new WeakMap();
2238
+ _schemaTables = new WeakMap();
1693
2239
  _search = new WeakSet();
1694
2240
  search_fn = async function(query, options, getFetchProps) {
1695
2241
  const fetchProps = await getFetchProps();
1696
- const { tables, fuzziness } = options ?? {};
2242
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1697
2243
  const { records } = await searchBranch({
1698
2244
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1699
- body: { tables, query, fuzziness },
2245
+ body: { tables, query, fuzziness, prefix, highlight },
1700
2246
  ...fetchProps
1701
2247
  });
1702
2248
  return records;
1703
2249
  };
1704
- _getSchema = new WeakSet();
1705
- getSchema_fn = async function(getFetchProps) {
1706
- if (__privateGet$1(this, _schema))
1707
- return __privateGet$1(this, _schema);
2250
+ _getSchemaTables = new WeakSet();
2251
+ getSchemaTables_fn = async function(getFetchProps) {
2252
+ if (__privateGet$1(this, _schemaTables))
2253
+ return __privateGet$1(this, _schemaTables);
1708
2254
  const fetchProps = await getFetchProps();
1709
2255
  const { schema } = await getBranchDetails({
1710
2256
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1711
2257
  ...fetchProps
1712
2258
  });
1713
- __privateSet$1(this, _schema, schema);
1714
- return schema;
2259
+ __privateSet$1(this, _schemaTables, schema.tables);
2260
+ return schema.tables;
1715
2261
  };
1716
2262
 
1717
2263
  const isBranchStrategyBuilder = (strategy) => {
1718
2264
  return typeof strategy === "function";
1719
2265
  };
1720
2266
 
1721
- const envBranchNames = [
1722
- "XATA_BRANCH",
1723
- "VERCEL_GIT_COMMIT_REF",
1724
- "CF_PAGES_BRANCH",
1725
- "BRANCH"
1726
- ];
1727
- const defaultBranch = "main";
1728
2267
  async function getCurrentBranchName(options) {
1729
- const env = await getBranchByEnvVariable();
1730
- if (env)
1731
- return env;
1732
- const branch = await getGitBranch();
1733
- if (!branch)
1734
- return defaultBranch;
1735
- const details = await getDatabaseBranch(branch, options);
1736
- if (details)
1737
- return branch;
1738
- return defaultBranch;
2268
+ const { branch, envBranch } = getEnvironment();
2269
+ if (branch) {
2270
+ const details = await getDatabaseBranch(branch, options);
2271
+ if (details)
2272
+ return branch;
2273
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2274
+ }
2275
+ const gitBranch = envBranch || await getGitBranch();
2276
+ return resolveXataBranch(gitBranch, options);
1739
2277
  }
1740
2278
  async function getCurrentBranchDetails(options) {
1741
- const env = await getBranchByEnvVariable();
1742
- if (env)
1743
- return getDatabaseBranch(env, options);
1744
- const branch = await getGitBranch();
1745
- if (!branch)
1746
- return getDatabaseBranch(defaultBranch, options);
1747
- const details = await getDatabaseBranch(branch, options);
1748
- if (details)
1749
- return details;
1750
- return getDatabaseBranch(defaultBranch, options);
2279
+ const branch = await getCurrentBranchName(options);
2280
+ return getDatabaseBranch(branch, options);
2281
+ }
2282
+ async function resolveXataBranch(gitBranch, options) {
2283
+ const databaseURL = options?.databaseURL || getDatabaseURL();
2284
+ const apiKey = options?.apiKey || getAPIKey();
2285
+ if (!databaseURL)
2286
+ throw new Error(
2287
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2288
+ );
2289
+ if (!apiKey)
2290
+ throw new Error(
2291
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2292
+ );
2293
+ const [protocol, , host, , dbName] = databaseURL.split("/");
2294
+ const [workspace] = host.split(".");
2295
+ const { fallbackBranch } = getEnvironment();
2296
+ const { branch } = await resolveBranch({
2297
+ apiKey,
2298
+ apiUrl: databaseURL,
2299
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
2300
+ workspacesApiUrl: `${protocol}//${host}`,
2301
+ pathParams: { dbName, workspace },
2302
+ queryParams: { gitBranch, fallbackBranch },
2303
+ trace: defaultTrace
2304
+ });
2305
+ return branch;
1751
2306
  }
1752
2307
  async function getDatabaseBranch(branch, options) {
1753
2308
  const databaseURL = options?.databaseURL || getDatabaseURL();
1754
2309
  const apiKey = options?.apiKey || getAPIKey();
1755
2310
  if (!databaseURL)
1756
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2311
+ throw new Error(
2312
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2313
+ );
1757
2314
  if (!apiKey)
1758
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2315
+ throw new Error(
2316
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2317
+ );
1759
2318
  const [protocol, , host, , database] = databaseURL.split("/");
1760
2319
  const [workspace] = host.split(".");
1761
2320
  const dbBranchName = `${database}:${branch}`;
@@ -1765,10 +2324,8 @@ async function getDatabaseBranch(branch, options) {
1765
2324
  apiUrl: databaseURL,
1766
2325
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1767
2326
  workspacesApiUrl: `${protocol}//${host}`,
1768
- pathParams: {
1769
- dbBranchName,
1770
- workspace
1771
- }
2327
+ pathParams: { dbBranchName, workspace },
2328
+ trace: defaultTrace
1772
2329
  });
1773
2330
  } catch (err) {
1774
2331
  if (isObject(err) && err.status === 404)
@@ -1776,21 +2333,10 @@ async function getDatabaseBranch(branch, options) {
1776
2333
  throw err;
1777
2334
  }
1778
2335
  }
1779
- function getBranchByEnvVariable() {
1780
- for (const name of envBranchNames) {
1781
- const value = getEnvVariable(name);
1782
- if (value) {
1783
- return value;
1784
- }
1785
- }
1786
- try {
1787
- return XATA_BRANCH;
1788
- } catch (err) {
1789
- }
1790
- }
1791
2336
  function getDatabaseURL() {
1792
2337
  try {
1793
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2338
+ const { databaseURL } = getEnvironment();
2339
+ return databaseURL;
1794
2340
  } catch (err) {
1795
2341
  return void 0;
1796
2342
  }
@@ -1819,24 +2365,27 @@ var __privateMethod = (obj, member, method) => {
1819
2365
  return method;
1820
2366
  };
1821
2367
  const buildClient = (plugins) => {
1822
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2368
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1823
2369
  return _a = class {
1824
- constructor(options = {}, tables) {
2370
+ constructor(options = {}, schemaTables) {
1825
2371
  __privateAdd(this, _parseOptions);
1826
2372
  __privateAdd(this, _getFetchProps);
1827
2373
  __privateAdd(this, _evaluateBranch);
1828
2374
  __privateAdd(this, _branch, void 0);
2375
+ __privateAdd(this, _options, void 0);
1829
2376
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2377
+ __privateSet(this, _options, safeOptions);
1830
2378
  const pluginOptions = {
1831
2379
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1832
- cache: safeOptions.cache
2380
+ cache: safeOptions.cache,
2381
+ trace: safeOptions.trace
1833
2382
  };
1834
- const db = new SchemaPlugin(tables).build(pluginOptions);
1835
- const search = new SearchPlugin(db).build(pluginOptions);
2383
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2384
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1836
2385
  this.db = db;
1837
2386
  this.search = search;
1838
2387
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1839
- if (!namespace)
2388
+ if (namespace === void 0)
1840
2389
  continue;
1841
2390
  const result = namespace.build(pluginOptions);
1842
2391
  if (result instanceof Promise) {
@@ -1848,22 +2397,26 @@ const buildClient = (plugins) => {
1848
2397
  }
1849
2398
  }
1850
2399
  }
1851
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2400
+ async getConfig() {
2401
+ const databaseURL = __privateGet(this, _options).databaseURL;
2402
+ const branch = await __privateGet(this, _options).branch();
2403
+ return { databaseURL, branch };
2404
+ }
2405
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1852
2406
  const fetch = getFetchImplementation(options?.fetch);
1853
2407
  const databaseURL = options?.databaseURL || getDatabaseURL();
1854
2408
  const apiKey = options?.apiKey || getAPIKey();
1855
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1856
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1857
- if (!databaseURL || !apiKey) {
1858
- throw new Error("Options databaseURL and apiKey are required");
2409
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2410
+ const trace = options?.trace ?? defaultTrace;
2411
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2412
+ if (!apiKey) {
2413
+ throw new Error("Option apiKey is required");
1859
2414
  }
1860
- return { fetch, databaseURL, apiKey, branch, cache };
1861
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1862
- fetch,
1863
- apiKey,
1864
- databaseURL,
1865
- branch
1866
- }) {
2415
+ if (!databaseURL) {
2416
+ throw new Error("Option databaseURL is required");
2417
+ }
2418
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2419
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
1867
2420
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1868
2421
  if (!branchValue)
1869
2422
  throw new Error("Unable to resolve branch value");
@@ -1873,14 +2426,15 @@ const buildClient = (plugins) => {
1873
2426
  apiUrl: "",
1874
2427
  workspacesApiUrl: (path, params) => {
1875
2428
  const hasBranch = params.dbBranchName ?? params.branch;
1876
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
2429
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
1877
2430
  return databaseURL + newPath;
1878
- }
2431
+ },
2432
+ trace
1879
2433
  };
1880
2434
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1881
2435
  if (__privateGet(this, _branch))
1882
2436
  return __privateGet(this, _branch);
1883
- if (!param)
2437
+ if (param === void 0)
1884
2438
  return void 0;
1885
2439
  const strategies = Array.isArray(param) ? [...param] : [param];
1886
2440
  const evaluateBranch = async (strategy) => {
@@ -1898,6 +2452,88 @@ const buildClient = (plugins) => {
1898
2452
  class BaseClient extends buildClient() {
1899
2453
  }
1900
2454
 
2455
+ const META = "__";
2456
+ const VALUE = "___";
2457
+ class Serializer {
2458
+ constructor() {
2459
+ this.classes = {};
2460
+ }
2461
+ add(clazz) {
2462
+ this.classes[clazz.name] = clazz;
2463
+ }
2464
+ toJSON(data) {
2465
+ function visit(obj) {
2466
+ if (Array.isArray(obj))
2467
+ return obj.map(visit);
2468
+ const type = typeof obj;
2469
+ if (type === "undefined")
2470
+ return { [META]: "undefined" };
2471
+ if (type === "bigint")
2472
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2473
+ if (obj === null || type !== "object")
2474
+ return obj;
2475
+ const constructor = obj.constructor;
2476
+ const o = { [META]: constructor.name };
2477
+ for (const [key, value] of Object.entries(obj)) {
2478
+ o[key] = visit(value);
2479
+ }
2480
+ if (constructor === Date)
2481
+ o[VALUE] = obj.toISOString();
2482
+ if (constructor === Map)
2483
+ o[VALUE] = Object.fromEntries(obj);
2484
+ if (constructor === Set)
2485
+ o[VALUE] = [...obj];
2486
+ return o;
2487
+ }
2488
+ return JSON.stringify(visit(data));
2489
+ }
2490
+ fromJSON(json) {
2491
+ return JSON.parse(json, (key, value) => {
2492
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2493
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2494
+ const constructor = this.classes[clazz];
2495
+ if (constructor) {
2496
+ return Object.assign(Object.create(constructor.prototype), rest);
2497
+ }
2498
+ if (clazz === "Date")
2499
+ return new Date(val);
2500
+ if (clazz === "Set")
2501
+ return new Set(val);
2502
+ if (clazz === "Map")
2503
+ return new Map(Object.entries(val));
2504
+ if (clazz === "bigint")
2505
+ return BigInt(val);
2506
+ if (clazz === "undefined")
2507
+ return void 0;
2508
+ return rest;
2509
+ }
2510
+ return value;
2511
+ });
2512
+ }
2513
+ }
2514
+ const defaultSerializer = new Serializer();
2515
+ const serialize = (data) => {
2516
+ return defaultSerializer.toJSON(data);
2517
+ };
2518
+ const deserialize = (json) => {
2519
+ return defaultSerializer.fromJSON(json);
2520
+ };
2521
+
2522
+ function buildWorkerRunner(config) {
2523
+ return function xataWorker(name, _worker) {
2524
+ return async (...args) => {
2525
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2526
+ const result = await fetch(url, {
2527
+ method: "POST",
2528
+ headers: { "Content-Type": "application/json" },
2529
+ body: serialize({ args })
2530
+ });
2531
+ const text = await result.text();
2532
+ return deserialize(text);
2533
+ };
2534
+ };
2535
+ }
2536
+
1901
2537
  class XataError extends Error {
1902
2538
  constructor(message, status) {
1903
2539
  super(message);
@@ -1905,5 +2541,5 @@ class XataError extends Error {
1905
2541
  }
1906
2542
  }
1907
2543
 
1908
- 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 };
2544
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, applyBranchSchemaEdit, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequests, listMigrationRequestsCommits, lt, lte, mergeMigrationRequest, notExists, operationsByTag, pattern, previewBranchSchemaEdit, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
1909
2545
  //# sourceMappingURL=index.mjs.map