@xata.io/client 0.0.0-alpha.ved669cc → 0.0.0-alpha.vede38ca

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2,6 +2,49 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ function _interopNamespace(e) {
6
+ if (e && e.__esModule) return e;
7
+ var n = Object.create(null);
8
+ if (e) {
9
+ Object.keys(e).forEach(function (k) {
10
+ if (k !== 'default') {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: true,
14
+ get: function () { return e[k]; }
15
+ });
16
+ }
17
+ });
18
+ }
19
+ n["default"] = e;
20
+ return Object.freeze(n);
21
+ }
22
+
23
+ const defaultTrace = async (_name, fn, _options) => {
24
+ return await fn({
25
+ setAttributes: () => {
26
+ return;
27
+ },
28
+ propagateTrace: () => {
29
+ return;
30
+ }
31
+ });
32
+ };
33
+ const TraceAttributes = {
34
+ KIND: "xata.trace.kind",
35
+ VERSION: "xata.sdk.version",
36
+ TABLE: "xata.table",
37
+ HTTP_REQUEST_ID: "http.request_id",
38
+ HTTP_STATUS_CODE: "http.status_code",
39
+ HTTP_HOST: "http.host",
40
+ HTTP_SCHEME: "http.scheme",
41
+ HTTP_USER_AGENT: "http.user_agent",
42
+ HTTP_METHOD: "http.method",
43
+ HTTP_URL: "http.url",
44
+ HTTP_ROUTE: "http.route",
45
+ HTTP_TARGET: "http.target"
46
+ };
47
+
5
48
  function notEmpty(value) {
6
49
  return value !== null && value !== void 0;
7
50
  }
@@ -17,6 +60,9 @@ function isDefined(value) {
17
60
  function isString(value) {
18
61
  return isDefined(value) && typeof value === "string";
19
62
  }
63
+ function isStringArray(value) {
64
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
65
+ }
20
66
  function toBase64(value) {
21
67
  try {
22
68
  return btoa(value);
@@ -32,7 +78,8 @@ function getEnvironment() {
32
78
  return {
33
79
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
34
80
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
35
- branch: process.env.XATA_BRANCH ?? process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH ?? getGlobalBranch(),
81
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
82
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
36
83
  fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
37
84
  };
38
85
  }
@@ -43,7 +90,8 @@ function getEnvironment() {
43
90
  return {
44
91
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
45
92
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
46
- branch: Deno.env.get("XATA_BRANCH") ?? Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH") ?? getGlobalBranch(),
93
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
94
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
47
95
  fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
48
96
  };
49
97
  }
@@ -53,6 +101,7 @@ function getEnvironment() {
53
101
  apiKey: getGlobalApiKey(),
54
102
  databaseURL: getGlobalDatabaseURL(),
55
103
  branch: getGlobalBranch(),
104
+ envBranch: void 0,
56
105
  fallbackBranch: getGlobalFallbackBranch()
57
106
  };
58
107
  }
@@ -85,20 +134,21 @@ function getGlobalFallbackBranch() {
85
134
  }
86
135
  }
87
136
  async function getGitBranch() {
137
+ const cmd = ["git", "branch", "--show-current"];
138
+ const fullCmd = cmd.join(" ");
139
+ const nodeModule = ["child", "process"].join("_");
140
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
88
141
  try {
89
142
  if (typeof require === "function") {
90
- const req = require;
91
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
143
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
92
144
  }
145
+ const { execSync } = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(nodeModule);
146
+ return execSync(fullCmd, execOptions).toString().trim();
93
147
  } catch (err) {
94
148
  }
95
149
  try {
96
150
  if (isObject(Deno)) {
97
- const process2 = Deno.run({
98
- cmd: ["git", "branch", "--show-current"],
99
- stdout: "piped",
100
- stderr: "piped"
101
- });
151
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
102
152
  return new TextDecoder().decode(await process2.output()).trim();
103
153
  }
104
154
  } catch (err) {
@@ -118,12 +168,14 @@ function getFetchImplementation(userFetch) {
118
168
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
119
169
  const fetchImpl = userFetch ?? globalFetch;
120
170
  if (!fetchImpl) {
121
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
171
+ throw new Error(
172
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
173
+ );
122
174
  }
123
175
  return fetchImpl;
124
176
  }
125
177
 
126
- const VERSION = "0.0.0-alpha.ved669cc";
178
+ const VERSION = "0.0.0-alpha.vede38ca";
127
179
 
128
180
  class ErrorWithCause extends Error {
129
181
  constructor(message, options) {
@@ -174,7 +226,10 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
174
226
  }, {});
175
227
  const query = new URLSearchParams(cleanQueryParams).toString();
176
228
  const queryString = query.length > 0 ? `?${query}` : "";
177
- return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
229
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
230
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
231
+ }, {});
232
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
178
233
  };
179
234
  function buildBaseUrl({
180
235
  path,
@@ -182,10 +237,10 @@ function buildBaseUrl({
182
237
  apiUrl,
183
238
  pathParams
184
239
  }) {
185
- if (!pathParams?.workspace)
240
+ if (pathParams?.workspace === void 0)
186
241
  return `${apiUrl}${path}`;
187
242
  const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
188
- return url.replace("{workspaceId}", pathParams.workspace);
243
+ return url.replace("{workspaceId}", String(pathParams.workspace));
189
244
  }
190
245
  function hostHeader(url) {
191
246
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
@@ -202,34 +257,63 @@ async function fetch$1({
202
257
  fetchImpl,
203
258
  apiKey,
204
259
  apiUrl,
205
- workspacesApiUrl
260
+ workspacesApiUrl,
261
+ trace
206
262
  }) {
207
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
208
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
209
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
210
- const response = await fetchImpl(url, {
211
- method: method.toUpperCase(),
212
- body: body ? JSON.stringify(body) : void 0,
213
- headers: {
214
- "Content-Type": "application/json",
215
- "User-Agent": `Xata client-ts/${VERSION}`,
216
- ...headers,
217
- ...hostHeader(fullUrl),
218
- Authorization: `Bearer ${apiKey}`
219
- }
220
- });
221
- if (response.status === 204) {
222
- return {};
223
- }
224
- const requestId = response.headers?.get("x-request-id") ?? void 0;
263
+ return trace(
264
+ `${method.toUpperCase()} ${path}`,
265
+ async ({ setAttributes, propagateTrace }) => {
266
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
267
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
268
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
269
+ setAttributes({
270
+ [TraceAttributes.HTTP_URL]: url,
271
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
272
+ });
273
+ const reqHeaders = {
274
+ "Content-Type": "application/json",
275
+ "User-Agent": `Xata client-ts/${VERSION}`,
276
+ ...headers,
277
+ ...hostHeader(fullUrl),
278
+ Authorization: `Bearer ${apiKey}`
279
+ };
280
+ propagateTrace(reqHeaders);
281
+ const response = await fetchImpl(url, {
282
+ method: method.toUpperCase(),
283
+ body: body ? JSON.stringify(body) : void 0,
284
+ headers: reqHeaders
285
+ });
286
+ if (response.status === 204) {
287
+ return {};
288
+ }
289
+ const { host, protocol } = parseUrl(response.url);
290
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
291
+ setAttributes({
292
+ [TraceAttributes.KIND]: "http",
293
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
294
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
295
+ [TraceAttributes.HTTP_HOST]: host,
296
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
297
+ });
298
+ try {
299
+ const jsonResponse = await response.json();
300
+ if (response.ok) {
301
+ return jsonResponse;
302
+ }
303
+ throw new FetcherError(response.status, jsonResponse, requestId);
304
+ } catch (error) {
305
+ throw new FetcherError(response.status, error, requestId);
306
+ }
307
+ },
308
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
309
+ );
310
+ }
311
+ function parseUrl(url) {
225
312
  try {
226
- const jsonResponse = await response.json();
227
- if (response.ok) {
228
- return jsonResponse;
229
- }
230
- throw new FetcherError(response.status, jsonResponse, requestId);
313
+ const { host, protocol } = new URL(url);
314
+ return { host, protocol };
231
315
  } catch (error) {
232
- throw new FetcherError(response.status, error, requestId);
316
+ return {};
233
317
  }
234
318
  }
235
319
 
@@ -288,6 +372,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
288
372
  ...variables
289
373
  });
290
374
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
375
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
291
376
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
292
377
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
293
378
  method: "delete",
@@ -323,6 +408,12 @@ const deleteDatabase = (variables) => fetch$1({
323
408
  method: "delete",
324
409
  ...variables
325
410
  });
411
+ const getDatabaseMetadata = (variables) => fetch$1({
412
+ url: "/dbs/{dbName}/metadata",
413
+ method: "get",
414
+ ...variables
415
+ });
416
+ const patchDatabaseMetadata = (variables) => fetch$1({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables });
326
417
  const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
327
418
  const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
328
419
  const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
@@ -331,16 +422,28 @@ const resolveBranch = (variables) => fetch$1({
331
422
  method: "get",
332
423
  ...variables
333
424
  });
334
- const getBranchDetails = (variables) => fetch$1({
335
- url: "/db/{dbBranchName}",
425
+ const listMigrationRequests = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/list", method: "post", ...variables });
426
+ const createMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations", method: "post", ...variables });
427
+ const getMigrationRequest = (variables) => fetch$1({
428
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
336
429
  method: "get",
337
430
  ...variables
338
431
  });
339
- const createBranch = (variables) => fetch$1({
432
+ const updateMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables });
433
+ const listMigrationRequestsCommits = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables });
434
+ const compareMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables });
435
+ const getMigrationRequestIsMerged = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables });
436
+ const mergeMigrationRequest = (variables) => fetch$1({
437
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
438
+ method: "post",
439
+ ...variables
440
+ });
441
+ const getBranchDetails = (variables) => fetch$1({
340
442
  url: "/db/{dbBranchName}",
341
- method: "put",
443
+ method: "get",
342
444
  ...variables
343
445
  });
446
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
344
447
  const deleteBranch = (variables) => fetch$1({
345
448
  url: "/db/{dbBranchName}",
346
449
  method: "delete",
@@ -359,6 +462,16 @@ const getBranchMetadata = (variables) => fetch$1({
359
462
  const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
360
463
  const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
361
464
  const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
465
+ const compareBranchWithUserSchema = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables });
466
+ const compareBranchSchemas = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables });
467
+ const updateBranchSchema = (variables) => fetch$1({
468
+ url: "/db/{dbBranchName}/schema/update",
469
+ method: "post",
470
+ ...variables
471
+ });
472
+ const previewBranchSchemaEdit = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables });
473
+ const applyBranchSchemaEdit = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables });
474
+ const getBranchSchemaHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables });
362
475
  const getBranchStats = (variables) => fetch$1({
363
476
  url: "/db/{dbBranchName}/stats",
364
477
  method: "get",
@@ -414,11 +527,7 @@ const updateColumn = (variables) => fetch$1({
414
527
  method: "patch",
415
528
  ...variables
416
529
  });
417
- const insertRecord = (variables) => fetch$1({
418
- url: "/db/{dbBranchName}/tables/{tableName}/data",
419
- method: "post",
420
- ...variables
421
- });
530
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
422
531
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
423
532
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
424
533
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -460,6 +569,7 @@ const operationsByTag = {
460
569
  updateWorkspaceMemberRole,
461
570
  removeWorkspaceMember,
462
571
  inviteWorkspaceMember,
572
+ updateWorkspaceMemberInvite,
463
573
  cancelWorkspaceMemberInvite,
464
574
  resendWorkspaceMemberInvite,
465
575
  acceptWorkspaceMemberInvite
@@ -468,6 +578,8 @@ const operationsByTag = {
468
578
  getDatabaseList,
469
579
  createDatabase,
470
580
  deleteDatabase,
581
+ getDatabaseMetadata,
582
+ patchDatabaseMetadata,
471
583
  getGitBranchesMapping,
472
584
  addGitBranchesEntry,
473
585
  removeGitBranchesEntry,
@@ -480,10 +592,28 @@ const operationsByTag = {
480
592
  deleteBranch,
481
593
  updateBranchMetadata,
482
594
  getBranchMetadata,
595
+ getBranchStats
596
+ },
597
+ migrationRequests: {
598
+ listMigrationRequests,
599
+ createMigrationRequest,
600
+ getMigrationRequest,
601
+ updateMigrationRequest,
602
+ listMigrationRequestsCommits,
603
+ compareMigrationRequest,
604
+ getMigrationRequestIsMerged,
605
+ mergeMigrationRequest
606
+ },
607
+ branchSchema: {
483
608
  getBranchMigrationHistory,
484
609
  executeBranchMigrationPlan,
485
610
  getBranchMigrationPlan,
486
- getBranchStats
611
+ compareBranchWithUserSchema,
612
+ compareBranchSchemas,
613
+ updateBranchSchema,
614
+ previewBranchSchemaEdit,
615
+ applyBranchSchemaEdit,
616
+ getBranchSchemaHistory
487
617
  },
488
618
  table: {
489
619
  createTable,
@@ -512,9 +642,9 @@ const operationsByTag = {
512
642
  };
513
643
 
514
644
  function getHostUrl(provider, type) {
515
- if (isValidAlias(provider)) {
645
+ if (isHostProviderAlias(provider)) {
516
646
  return providers[provider][type];
517
- } else if (isValidBuilder(provider)) {
647
+ } else if (isHostProviderBuilder(provider)) {
518
648
  return provider[type];
519
649
  }
520
650
  throw new Error("Invalid API provider");
@@ -529,10 +659,10 @@ const providers = {
529
659
  workspaces: "https://{workspaceId}.staging.xatabase.co"
530
660
  }
531
661
  };
532
- function isValidAlias(alias) {
662
+ function isHostProviderAlias(alias) {
533
663
  return isString(alias) && Object.keys(providers).includes(alias);
534
664
  }
535
- function isValidBuilder(builder) {
665
+ function isHostProviderBuilder(builder) {
536
666
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
537
667
  }
538
668
 
@@ -560,7 +690,8 @@ class XataApiClient {
560
690
  __privateAdd$7(this, _extraProps, void 0);
561
691
  __privateAdd$7(this, _namespaces, {});
562
692
  const provider = options.host ?? "production";
563
- const apiKey = options?.apiKey ?? getAPIKey();
693
+ const apiKey = options.apiKey ?? getAPIKey();
694
+ const trace = options.trace ?? defaultTrace;
564
695
  if (!apiKey) {
565
696
  throw new Error("Could not resolve a valid apiKey");
566
697
  }
@@ -568,7 +699,8 @@ class XataApiClient {
568
699
  apiUrl: getHostUrl(provider, "main"),
569
700
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
570
701
  fetchImpl: getFetchImplementation(options.fetch),
571
- apiKey
702
+ apiKey,
703
+ trace
572
704
  });
573
705
  }
574
706
  get user() {
@@ -601,6 +733,16 @@ class XataApiClient {
601
733
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
602
734
  return __privateGet$7(this, _namespaces).records;
603
735
  }
736
+ get migrationRequests() {
737
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
738
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
739
+ return __privateGet$7(this, _namespaces).migrationRequests;
740
+ }
741
+ get branchSchema() {
742
+ if (!__privateGet$7(this, _namespaces).branchSchema)
743
+ __privateGet$7(this, _namespaces).branchSchema = new BranchSchemaApi(__privateGet$7(this, _extraProps));
744
+ return __privateGet$7(this, _namespaces).branchSchema;
745
+ }
604
746
  }
605
747
  _extraProps = new WeakMap();
606
748
  _namespaces = new WeakMap();
@@ -691,6 +833,13 @@ class WorkspaceApi {
691
833
  ...this.extraProps
692
834
  });
693
835
  }
836
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
837
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
838
+ pathParams: { workspaceId, inviteId },
839
+ body: { role },
840
+ ...this.extraProps
841
+ });
842
+ }
694
843
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
695
844
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
696
845
  pathParams: { workspaceId, inviteId },
@@ -733,6 +882,19 @@ class DatabaseApi {
733
882
  ...this.extraProps
734
883
  });
735
884
  }
885
+ getDatabaseMetadata(workspace, dbName) {
886
+ return operationsByTag.database.getDatabaseMetadata({
887
+ pathParams: { workspace, dbName },
888
+ ...this.extraProps
889
+ });
890
+ }
891
+ patchDatabaseMetadata(workspace, dbName, options = {}) {
892
+ return operationsByTag.database.patchDatabaseMetadata({
893
+ pathParams: { workspace, dbName },
894
+ body: options,
895
+ ...this.extraProps
896
+ });
897
+ }
736
898
  getGitBranchesMapping(workspace, dbName) {
737
899
  return operationsByTag.database.getGitBranchesMapping({
738
900
  pathParams: { workspace, dbName },
@@ -804,27 +966,6 @@ class BranchApi {
804
966
  ...this.extraProps
805
967
  });
806
968
  }
807
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
808
- return operationsByTag.branch.getBranchMigrationHistory({
809
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
810
- body: options,
811
- ...this.extraProps
812
- });
813
- }
814
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
815
- return operationsByTag.branch.executeBranchMigrationPlan({
816
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
817
- body: migrationPlan,
818
- ...this.extraProps
819
- });
820
- }
821
- getBranchMigrationPlan(workspace, database, branch, schema) {
822
- return operationsByTag.branch.getBranchMigrationPlan({
823
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
824
- body: schema,
825
- ...this.extraProps
826
- });
827
- }
828
969
  getBranchStats(workspace, database, branch) {
829
970
  return operationsByTag.branch.getBranchStats({
830
971
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -905,9 +1046,10 @@ class RecordsApi {
905
1046
  constructor(extraProps) {
906
1047
  this.extraProps = extraProps;
907
1048
  }
908
- insertRecord(workspace, database, branch, tableName, record) {
1049
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
909
1050
  return operationsByTag.records.insertRecord({
910
1051
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1052
+ queryParams: options,
911
1053
  body: record,
912
1054
  ...this.extraProps
913
1055
  });
@@ -936,21 +1078,24 @@ class RecordsApi {
936
1078
  ...this.extraProps
937
1079
  });
938
1080
  }
939
- deleteRecord(workspace, database, branch, tableName, recordId) {
1081
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
940
1082
  return operationsByTag.records.deleteRecord({
941
1083
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1084
+ queryParams: options,
942
1085
  ...this.extraProps
943
1086
  });
944
1087
  }
945
1088
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
946
1089
  return operationsByTag.records.getRecord({
947
1090
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1091
+ queryParams: options,
948
1092
  ...this.extraProps
949
1093
  });
950
1094
  }
951
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1095
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
952
1096
  return operationsByTag.records.bulkInsertTableRecords({
953
1097
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1098
+ queryParams: options,
954
1099
  body: { records },
955
1100
  ...this.extraProps
956
1101
  });
@@ -977,6 +1122,131 @@ class RecordsApi {
977
1122
  });
978
1123
  }
979
1124
  }
1125
+ class MigrationRequestsApi {
1126
+ constructor(extraProps) {
1127
+ this.extraProps = extraProps;
1128
+ }
1129
+ listMigrationRequests(workspace, database, options = {}) {
1130
+ return operationsByTag.migrationRequests.listMigrationRequests({
1131
+ pathParams: { workspace, dbName: database },
1132
+ body: options,
1133
+ ...this.extraProps
1134
+ });
1135
+ }
1136
+ createMigrationRequest(workspace, database, options) {
1137
+ return operationsByTag.migrationRequests.createMigrationRequest({
1138
+ pathParams: { workspace, dbName: database },
1139
+ body: options,
1140
+ ...this.extraProps
1141
+ });
1142
+ }
1143
+ getMigrationRequest(workspace, database, migrationRequest) {
1144
+ return operationsByTag.migrationRequests.getMigrationRequest({
1145
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1146
+ ...this.extraProps
1147
+ });
1148
+ }
1149
+ updateMigrationRequest(workspace, database, migrationRequest, options) {
1150
+ return operationsByTag.migrationRequests.updateMigrationRequest({
1151
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1152
+ body: options,
1153
+ ...this.extraProps
1154
+ });
1155
+ }
1156
+ listMigrationRequestsCommits(workspace, database, migrationRequest, options = {}) {
1157
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1158
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1159
+ body: options,
1160
+ ...this.extraProps
1161
+ });
1162
+ }
1163
+ compareMigrationRequest(workspace, database, migrationRequest) {
1164
+ return operationsByTag.migrationRequests.compareMigrationRequest({
1165
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1166
+ ...this.extraProps
1167
+ });
1168
+ }
1169
+ getMigrationRequestIsMerged(workspace, database, migrationRequest) {
1170
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1171
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1172
+ ...this.extraProps
1173
+ });
1174
+ }
1175
+ mergeMigrationRequest(workspace, database, migrationRequest) {
1176
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
1177
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1178
+ ...this.extraProps
1179
+ });
1180
+ }
1181
+ }
1182
+ class BranchSchemaApi {
1183
+ constructor(extraProps) {
1184
+ this.extraProps = extraProps;
1185
+ }
1186
+ getBranchMigrationHistory(workspace, database, branch, options = {}) {
1187
+ return operationsByTag.branchSchema.getBranchMigrationHistory({
1188
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1189
+ body: options,
1190
+ ...this.extraProps
1191
+ });
1192
+ }
1193
+ executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
1194
+ return operationsByTag.branchSchema.executeBranchMigrationPlan({
1195
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1196
+ body: migrationPlan,
1197
+ ...this.extraProps
1198
+ });
1199
+ }
1200
+ getBranchMigrationPlan(workspace, database, branch, schema) {
1201
+ return operationsByTag.branchSchema.getBranchMigrationPlan({
1202
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1203
+ body: schema,
1204
+ ...this.extraProps
1205
+ });
1206
+ }
1207
+ compareBranchWithUserSchema(workspace, database, branch, schema) {
1208
+ return operationsByTag.branchSchema.compareBranchWithUserSchema({
1209
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1210
+ body: { schema },
1211
+ ...this.extraProps
1212
+ });
1213
+ }
1214
+ compareBranchSchemas(workspace, database, branch, branchName, schema) {
1215
+ return operationsByTag.branchSchema.compareBranchSchemas({
1216
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, branchName },
1217
+ body: { schema },
1218
+ ...this.extraProps
1219
+ });
1220
+ }
1221
+ updateBranchSchema(workspace, database, branch, migration) {
1222
+ return operationsByTag.branchSchema.updateBranchSchema({
1223
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1224
+ body: migration,
1225
+ ...this.extraProps
1226
+ });
1227
+ }
1228
+ previewBranchSchemaEdit(workspace, database, branch, migration) {
1229
+ return operationsByTag.branchSchema.previewBranchSchemaEdit({
1230
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1231
+ body: migration,
1232
+ ...this.extraProps
1233
+ });
1234
+ }
1235
+ applyBranchSchemaEdit(workspace, database, branch, edits) {
1236
+ return operationsByTag.branchSchema.applyBranchSchemaEdit({
1237
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1238
+ body: { edits },
1239
+ ...this.extraProps
1240
+ });
1241
+ }
1242
+ getBranchSchemaHistory(workspace, database, branch, options = {}) {
1243
+ return operationsByTag.branchSchema.getBranchSchemaHistory({
1244
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1245
+ body: options,
1246
+ ...this.extraProps
1247
+ });
1248
+ }
1249
+ }
980
1250
 
981
1251
  class XataApiPlugin {
982
1252
  async build(options) {
@@ -1039,10 +1309,10 @@ function isCursorPaginationOptions(options) {
1039
1309
  return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1040
1310
  }
1041
1311
  const _RecordArray = class extends Array {
1042
- constructor(page, overrideRecords) {
1043
- super(..._RecordArray.parseConstructorParams(page, overrideRecords));
1312
+ constructor(...args) {
1313
+ super(..._RecordArray.parseConstructorParams(...args));
1044
1314
  __privateAdd$6(this, _page, void 0);
1045
- __privateSet$6(this, _page, page);
1315
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1046
1316
  }
1047
1317
  static parseConstructorParams(...args) {
1048
1318
  if (args.length === 1 && typeof args[0] === "number") {
@@ -1054,6 +1324,12 @@ const _RecordArray = class extends Array {
1054
1324
  }
1055
1325
  return new Array(...args);
1056
1326
  }
1327
+ toArray() {
1328
+ return new Array(...this);
1329
+ }
1330
+ map(callbackfn, thisArg) {
1331
+ return this.toArray().map(callbackfn, thisArg);
1332
+ }
1057
1333
  async nextPage(size, offset) {
1058
1334
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1059
1335
  return new _RecordArray(newPage);
@@ -1154,21 +1430,34 @@ const _Query = class {
1154
1430
  }
1155
1431
  filter(a, b) {
1156
1432
  if (arguments.length === 1) {
1157
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1433
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({ [column]: constraint }));
1158
1434
  const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1159
1435
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1160
1436
  } else {
1161
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1437
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: this.defaultFilter(a, b) }] : void 0;
1438
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1162
1439
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1163
1440
  }
1164
1441
  }
1165
- sort(column, direction) {
1442
+ defaultFilter(column, value) {
1443
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
1444
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
1445
+ return { $includes: value };
1446
+ }
1447
+ return value;
1448
+ }
1449
+ sort(column, direction = "asc") {
1166
1450
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1167
1451
  const sort = [...originalSort, { column, direction }];
1168
1452
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1169
1453
  }
1170
1454
  select(columns) {
1171
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1455
+ return new _Query(
1456
+ __privateGet$5(this, _repository),
1457
+ __privateGet$5(this, _table$1),
1458
+ { columns },
1459
+ __privateGet$5(this, _data)
1460
+ );
1172
1461
  }
1173
1462
  getPaginated(options = {}) {
1174
1463
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1293,203 +1582,228 @@ var __privateMethod$2 = (obj, member, method) => {
1293
1582
  __accessCheck$4(obj, member, "access private method");
1294
1583
  return method;
1295
1584
  };
1296
- var _table, _getFetchProps, _cache, _schemaTables$2, _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, _getSchemaTables$1, getSchemaTables_fn$1;
1585
+ 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;
1297
1586
  class Repository extends Query {
1298
1587
  }
1299
1588
  class RestRepository extends Query {
1300
1589
  constructor(options) {
1301
- super(null, options.table, {});
1590
+ super(
1591
+ null,
1592
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
1593
+ {}
1594
+ );
1302
1595
  __privateAdd$4(this, _insertRecordWithoutId);
1303
1596
  __privateAdd$4(this, _insertRecordWithId);
1304
1597
  __privateAdd$4(this, _bulkInsertTableRecords);
1305
1598
  __privateAdd$4(this, _updateRecordWithID);
1306
1599
  __privateAdd$4(this, _upsertRecordWithID);
1307
1600
  __privateAdd$4(this, _deleteRecord);
1308
- __privateAdd$4(this, _invalidateCache);
1309
- __privateAdd$4(this, _setCacheRecord);
1310
- __privateAdd$4(this, _getCacheRecord);
1311
1601
  __privateAdd$4(this, _setCacheQuery);
1312
1602
  __privateAdd$4(this, _getCacheQuery);
1313
1603
  __privateAdd$4(this, _getSchemaTables$1);
1314
1604
  __privateAdd$4(this, _table, void 0);
1315
1605
  __privateAdd$4(this, _getFetchProps, void 0);
1606
+ __privateAdd$4(this, _db, void 0);
1316
1607
  __privateAdd$4(this, _cache, void 0);
1317
1608
  __privateAdd$4(this, _schemaTables$2, void 0);
1609
+ __privateAdd$4(this, _trace, void 0);
1318
1610
  __privateSet$4(this, _table, options.table);
1319
1611
  __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1320
- this.db = options.db;
1612
+ __privateSet$4(this, _db, options.db);
1321
1613
  __privateSet$4(this, _cache, options.pluginOptions.cache);
1322
1614
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
1615
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1616
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1617
+ return trace("sdk op: " + name, fn, {
1618
+ ...options2,
1619
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1620
+ [TraceAttributes.KIND]: "sdk-operation",
1621
+ [TraceAttributes.VERSION]: VERSION
1622
+ });
1623
+ });
1323
1624
  }
1324
- async create(a, b) {
1325
- if (Array.isArray(a)) {
1326
- if (a.length === 0)
1327
- return [];
1328
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1329
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1330
- return records;
1331
- }
1332
- if (isString(a) && isObject(b)) {
1333
- if (a === "")
1334
- throw new Error("The id can't be empty");
1335
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1336
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1337
- return record;
1338
- }
1339
- if (isObject(a) && isString(a.id)) {
1340
- if (a.id === "")
1341
- throw new Error("The id can't be empty");
1342
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1343
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1344
- return record;
1345
- }
1346
- if (isObject(a)) {
1347
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1348
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1349
- return record;
1350
- }
1351
- throw new Error("Invalid arguments for create method");
1352
- }
1353
- async read(a) {
1354
- if (Array.isArray(a)) {
1355
- if (a.length === 0)
1356
- return [];
1357
- const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1358
- return this.getAll({ filter: { id: { $any: ids } } });
1359
- }
1360
- const id = isString(a) ? a : a.id;
1361
- if (isString(id)) {
1362
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1363
- if (cacheRecord)
1364
- return cacheRecord;
1365
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1366
- try {
1367
- const response = await getRecord({
1368
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1369
- ...fetchProps
1370
- });
1371
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1372
- return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1373
- } catch (e) {
1374
- if (isObject(e) && e.status === 404) {
1375
- return null;
1625
+ async create(a, b, c) {
1626
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1627
+ if (Array.isArray(a)) {
1628
+ if (a.length === 0)
1629
+ return [];
1630
+ const columns = isStringArray(b) ? b : void 0;
1631
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1632
+ }
1633
+ if (isString(a) && isObject(b)) {
1634
+ if (a === "")
1635
+ throw new Error("The id can't be empty");
1636
+ const columns = isStringArray(c) ? c : void 0;
1637
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1638
+ }
1639
+ if (isObject(a) && isString(a.id)) {
1640
+ if (a.id === "")
1641
+ throw new Error("The id can't be empty");
1642
+ const columns = isStringArray(b) ? b : void 0;
1643
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1644
+ }
1645
+ if (isObject(a)) {
1646
+ const columns = isStringArray(b) ? b : void 0;
1647
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1648
+ }
1649
+ throw new Error("Invalid arguments for create method");
1650
+ });
1651
+ }
1652
+ async read(a, b) {
1653
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1654
+ const columns = isStringArray(b) ? b : ["*"];
1655
+ if (Array.isArray(a)) {
1656
+ if (a.length === 0)
1657
+ return [];
1658
+ const ids = a.map((item) => extractId(item));
1659
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1660
+ const dictionary = finalObjects.reduce((acc, object) => {
1661
+ acc[object.id] = object;
1662
+ return acc;
1663
+ }, {});
1664
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1665
+ }
1666
+ const id = extractId(a);
1667
+ if (id) {
1668
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1669
+ try {
1670
+ const response = await getRecord({
1671
+ pathParams: {
1672
+ workspace: "{workspaceId}",
1673
+ dbBranchName: "{dbBranch}",
1674
+ tableName: __privateGet$4(this, _table),
1675
+ recordId: id
1676
+ },
1677
+ queryParams: { columns },
1678
+ ...fetchProps
1679
+ });
1680
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1681
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1682
+ } catch (e) {
1683
+ if (isObject(e) && e.status === 404) {
1684
+ return null;
1685
+ }
1686
+ throw e;
1376
1687
  }
1377
- throw e;
1378
1688
  }
1379
- }
1689
+ return null;
1690
+ });
1380
1691
  }
1381
- async update(a, b) {
1382
- if (Array.isArray(a)) {
1383
- if (a.length === 0)
1384
- return [];
1385
- if (a.length > 100) {
1386
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1692
+ async update(a, b, c) {
1693
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1694
+ if (Array.isArray(a)) {
1695
+ if (a.length === 0)
1696
+ return [];
1697
+ if (a.length > 100) {
1698
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1699
+ }
1700
+ const columns = isStringArray(b) ? b : ["*"];
1701
+ return Promise.all(a.map((object) => this.update(object, columns)));
1387
1702
  }
1388
- return Promise.all(a.map((object) => this.update(object)));
1389
- }
1390
- if (isString(a) && isObject(b)) {
1391
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1392
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1393
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1394
- return record;
1395
- }
1396
- if (isObject(a) && isString(a.id)) {
1397
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1398
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1399
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1400
- return record;
1401
- }
1402
- throw new Error("Invalid arguments for update method");
1403
- }
1404
- async createOrUpdate(a, b) {
1405
- if (Array.isArray(a)) {
1406
- if (a.length === 0)
1407
- return [];
1408
- if (a.length > 100) {
1409
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1703
+ if (isString(a) && isObject(b)) {
1704
+ const columns = isStringArray(c) ? c : void 0;
1705
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1410
1706
  }
1411
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1412
- }
1413
- if (isString(a) && isObject(b)) {
1414
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1415
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1416
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1417
- return record;
1418
- }
1419
- if (isObject(a) && isString(a.id)) {
1420
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1421
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1422
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1423
- return record;
1424
- }
1425
- throw new Error("Invalid arguments for createOrUpdate method");
1426
- }
1427
- async delete(a) {
1428
- if (Array.isArray(a)) {
1429
- if (a.length === 0)
1430
- return;
1431
- if (a.length > 100) {
1432
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1707
+ if (isObject(a) && isString(a.id)) {
1708
+ const columns = isStringArray(b) ? b : void 0;
1709
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1433
1710
  }
1434
- await Promise.all(a.map((id) => this.delete(id)));
1435
- return;
1436
- }
1437
- if (isString(a)) {
1438
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1439
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1440
- return;
1441
- }
1442
- if (isObject(a) && isString(a.id)) {
1443
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1444
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1445
- return;
1446
- }
1447
- throw new Error("Invalid arguments for delete method");
1711
+ throw new Error("Invalid arguments for update method");
1712
+ });
1713
+ }
1714
+ async createOrUpdate(a, b, c) {
1715
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1716
+ if (Array.isArray(a)) {
1717
+ if (a.length === 0)
1718
+ return [];
1719
+ if (a.length > 100) {
1720
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1721
+ }
1722
+ const columns = isStringArray(b) ? b : ["*"];
1723
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1724
+ }
1725
+ if (isString(a) && isObject(b)) {
1726
+ const columns = isStringArray(c) ? c : void 0;
1727
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1728
+ }
1729
+ if (isObject(a) && isString(a.id)) {
1730
+ const columns = isStringArray(c) ? c : void 0;
1731
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1732
+ }
1733
+ throw new Error("Invalid arguments for createOrUpdate method");
1734
+ });
1735
+ }
1736
+ async delete(a, b) {
1737
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1738
+ if (Array.isArray(a)) {
1739
+ if (a.length === 0)
1740
+ return [];
1741
+ if (a.length > 100) {
1742
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1743
+ }
1744
+ return Promise.all(a.map((id) => this.delete(id, b)));
1745
+ }
1746
+ if (isString(a)) {
1747
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1748
+ }
1749
+ if (isObject(a) && isString(a.id)) {
1750
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1751
+ }
1752
+ throw new Error("Invalid arguments for delete method");
1753
+ });
1448
1754
  }
1449
1755
  async search(query, options = {}) {
1450
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1451
- const { records } = await searchTable({
1452
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1453
- body: {
1454
- query,
1455
- fuzziness: options.fuzziness,
1456
- highlight: options.highlight,
1457
- filter: options.filter
1458
- },
1459
- ...fetchProps
1756
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1757
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1758
+ const { records } = await searchTable({
1759
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1760
+ body: {
1761
+ query,
1762
+ fuzziness: options.fuzziness,
1763
+ prefix: options.prefix,
1764
+ highlight: options.highlight,
1765
+ filter: options.filter,
1766
+ boosters: options.boosters
1767
+ },
1768
+ ...fetchProps
1769
+ });
1770
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1771
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1460
1772
  });
1461
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1462
- return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1463
1773
  }
1464
1774
  async query(query) {
1465
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1466
- if (cacheQuery)
1467
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1468
- const data = query.getQueryOptions();
1469
- const body = {
1470
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1471
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1472
- page: data.pagination,
1473
- columns: data.columns
1474
- };
1475
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1476
- const { meta, records: objects } = await queryTable({
1477
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1478
- body,
1479
- ...fetchProps
1775
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1776
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1777
+ if (cacheQuery)
1778
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1779
+ const data = query.getQueryOptions();
1780
+ const body = {
1781
+ filter: cleanFilter(data.filter),
1782
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1783
+ page: data.pagination,
1784
+ columns: data.columns
1785
+ };
1786
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1787
+ const { meta, records: objects } = await queryTable({
1788
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1789
+ body,
1790
+ ...fetchProps
1791
+ });
1792
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1793
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1794
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1795
+ return new Page(query, meta, records);
1480
1796
  });
1481
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1482
- const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1483
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1484
- return new Page(query, meta, records);
1485
1797
  }
1486
1798
  }
1487
1799
  _table = new WeakMap();
1488
1800
  _getFetchProps = new WeakMap();
1801
+ _db = new WeakMap();
1489
1802
  _cache = new WeakMap();
1490
1803
  _schemaTables$2 = new WeakMap();
1804
+ _trace = new WeakMap();
1491
1805
  _insertRecordWithoutId = new WeakSet();
1492
- insertRecordWithoutId_fn = async function(object) {
1806
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1493
1807
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1494
1808
  const record = transformObjectLinks(object);
1495
1809
  const response = await insertRecord({
@@ -1498,17 +1812,15 @@ insertRecordWithoutId_fn = async function(object) {
1498
1812
  dbBranchName: "{dbBranch}",
1499
1813
  tableName: __privateGet$4(this, _table)
1500
1814
  },
1815
+ queryParams: { columns },
1501
1816
  body: record,
1502
1817
  ...fetchProps
1503
1818
  });
1504
- const finalObject = await this.read(response.id);
1505
- if (!finalObject) {
1506
- throw new Error("The server failed to save the record");
1507
- }
1508
- return finalObject;
1819
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1820
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1509
1821
  };
1510
1822
  _insertRecordWithId = new WeakSet();
1511
- insertRecordWithId_fn = async function(recordId, object) {
1823
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1512
1824
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1513
1825
  const record = transformObjectLinks(object);
1514
1826
  const response = await insertRecordWithID({
@@ -1519,92 +1831,78 @@ insertRecordWithId_fn = async function(recordId, object) {
1519
1831
  recordId
1520
1832
  },
1521
1833
  body: record,
1522
- queryParams: { createOnly: true },
1834
+ queryParams: { createOnly: true, columns },
1523
1835
  ...fetchProps
1524
1836
  });
1525
- const finalObject = await this.read(response.id);
1526
- if (!finalObject) {
1527
- throw new Error("The server failed to save the record");
1528
- }
1529
- return finalObject;
1837
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1838
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1530
1839
  };
1531
1840
  _bulkInsertTableRecords = new WeakSet();
1532
- bulkInsertTableRecords_fn = async function(objects) {
1841
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1533
1842
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1534
1843
  const records = objects.map((object) => transformObjectLinks(object));
1535
- const { recordIDs } = await bulkInsertTableRecords({
1844
+ const response = await bulkInsertTableRecords({
1536
1845
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1846
+ queryParams: { columns },
1537
1847
  body: { records },
1538
1848
  ...fetchProps
1539
1849
  });
1540
- const finalObjects = await this.read(recordIDs);
1541
- if (finalObjects.length !== objects.length) {
1542
- throw new Error("The server failed to save some records");
1850
+ if (!isResponseWithRecords(response)) {
1851
+ throw new Error("Request included columns but server didn't include them");
1543
1852
  }
1544
- const dictionary = finalObjects.reduce((acc, object) => {
1545
- acc[object.id] = object;
1546
- return acc;
1547
- }, {});
1548
- return recordIDs.map((id) => dictionary[id]);
1853
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1854
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1549
1855
  };
1550
1856
  _updateRecordWithID = new WeakSet();
1551
- updateRecordWithID_fn = async function(recordId, object) {
1857
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1552
1858
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1553
1859
  const record = transformObjectLinks(object);
1554
- const response = await updateRecordWithID({
1555
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1556
- body: record,
1557
- ...fetchProps
1558
- });
1559
- const item = await this.read(response.id);
1560
- if (!item)
1561
- throw new Error("The server failed to save the record");
1562
- return item;
1860
+ try {
1861
+ const response = await updateRecordWithID({
1862
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1863
+ queryParams: { columns },
1864
+ body: record,
1865
+ ...fetchProps
1866
+ });
1867
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1868
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1869
+ } catch (e) {
1870
+ if (isObject(e) && e.status === 404) {
1871
+ return null;
1872
+ }
1873
+ throw e;
1874
+ }
1563
1875
  };
1564
1876
  _upsertRecordWithID = new WeakSet();
1565
- upsertRecordWithID_fn = async function(recordId, object) {
1877
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1566
1878
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1567
1879
  const response = await upsertRecordWithID({
1568
1880
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1881
+ queryParams: { columns },
1569
1882
  body: object,
1570
1883
  ...fetchProps
1571
1884
  });
1572
- const item = await this.read(response.id);
1573
- if (!item)
1574
- throw new Error("The server failed to save the record");
1575
- return item;
1885
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1886
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1576
1887
  };
1577
1888
  _deleteRecord = new WeakSet();
1578
- deleteRecord_fn = async function(recordId) {
1889
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1579
1890
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1580
- await deleteRecord({
1581
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1582
- ...fetchProps
1583
- });
1584
- };
1585
- _invalidateCache = new WeakSet();
1586
- invalidateCache_fn = async function(recordId) {
1587
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1588
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1589
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1590
- for (const [key, value] of queries) {
1591
- const ids = getIds(value);
1592
- if (ids.includes(recordId))
1593
- await __privateGet$4(this, _cache).delete(key);
1891
+ try {
1892
+ const response = await deleteRecord({
1893
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1894
+ queryParams: { columns },
1895
+ ...fetchProps
1896
+ });
1897
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1898
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1899
+ } catch (e) {
1900
+ if (isObject(e) && e.status === 404) {
1901
+ return null;
1902
+ }
1903
+ throw e;
1594
1904
  }
1595
1905
  };
1596
- _setCacheRecord = new WeakSet();
1597
- setCacheRecord_fn = async function(record) {
1598
- if (!__privateGet$4(this, _cache).cacheRecords)
1599
- return;
1600
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1601
- };
1602
- _getCacheRecord = new WeakSet();
1603
- getCacheRecord_fn = async function(recordId) {
1604
- if (!__privateGet$4(this, _cache).cacheRecords)
1605
- return null;
1606
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1607
- };
1608
1906
  _setCacheQuery = new WeakSet();
1609
1907
  setCacheQuery_fn = async function(query, meta, records) {
1610
1908
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -1670,11 +1968,11 @@ const initObject = (db, schemaTables, table, object) => {
1670
1968
  }
1671
1969
  }
1672
1970
  }
1673
- result.read = function() {
1674
- return db[table].read(result["id"]);
1971
+ result.read = function(columns2) {
1972
+ return db[table].read(result["id"], columns2);
1675
1973
  };
1676
- result.update = function(data) {
1677
- return db[table].update(result["id"], data);
1974
+ result.update = function(data, columns2) {
1975
+ return db[table].update(result["id"], data, columns2);
1678
1976
  };
1679
1977
  result.delete = function() {
1680
1978
  return db[table].delete(result["id"]);
@@ -1688,14 +1986,21 @@ const initObject = (db, schemaTables, table, object) => {
1688
1986
  Object.freeze(result);
1689
1987
  return result;
1690
1988
  };
1691
- function getIds(value) {
1692
- if (Array.isArray(value)) {
1693
- return value.map((item) => getIds(item)).flat();
1694
- }
1695
- if (!isObject(value))
1696
- return [];
1697
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1698
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1989
+ function isResponseWithRecords(value) {
1990
+ return isObject(value) && Array.isArray(value.records);
1991
+ }
1992
+ function extractId(value) {
1993
+ if (isString(value))
1994
+ return value;
1995
+ if (isObject(value) && isString(value.id))
1996
+ return value.id;
1997
+ return void 0;
1998
+ }
1999
+ function cleanFilter(filter) {
2000
+ if (!filter)
2001
+ return void 0;
2002
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
2003
+ return values.length > 0 ? filter : void 0;
1699
2004
  }
1700
2005
 
1701
2006
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1722,7 +2027,6 @@ class SimpleCache {
1722
2027
  __privateAdd$3(this, _map, void 0);
1723
2028
  __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1724
2029
  this.capacity = options.max ?? 500;
1725
- this.cacheRecords = options.cacheRecords ?? true;
1726
2030
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1727
2031
  }
1728
2032
  async getAll() {
@@ -1748,18 +2052,25 @@ class SimpleCache {
1748
2052
  }
1749
2053
  _map = new WeakMap();
1750
2054
 
1751
- const gt = (value) => ({ $gt: value });
1752
- const ge = (value) => ({ $ge: value });
1753
- const gte = (value) => ({ $ge: value });
1754
- const lt = (value) => ({ $lt: value });
1755
- const lte = (value) => ({ $le: value });
1756
- const le = (value) => ({ $le: value });
2055
+ const greaterThan = (value) => ({ $gt: value });
2056
+ const gt = greaterThan;
2057
+ const greaterThanEquals = (value) => ({ $ge: value });
2058
+ const greaterEquals = greaterThanEquals;
2059
+ const gte = greaterThanEquals;
2060
+ const ge = greaterThanEquals;
2061
+ const lessThan = (value) => ({ $lt: value });
2062
+ const lt = lessThan;
2063
+ const lessThanEquals = (value) => ({ $le: value });
2064
+ const lessEquals = lessThanEquals;
2065
+ const lte = lessThanEquals;
2066
+ const le = lessThanEquals;
1757
2067
  const exists = (column) => ({ $exists: column });
1758
2068
  const notExists = (column) => ({ $notExists: column });
1759
2069
  const startsWith = (value) => ({ $startsWith: value });
1760
2070
  const endsWith = (value) => ({ $endsWith: value });
1761
2071
  const pattern = (value) => ({ $pattern: value });
1762
2072
  const is = (value) => ({ $is: value });
2073
+ const equals = is;
1763
2074
  const isNot = (value) => ({ $isNot: value });
1764
2075
  const contains = (value) => ({ $contains: value });
1765
2076
  const includes = (value) => ({ $includes: value });
@@ -1794,16 +2105,19 @@ class SchemaPlugin extends XataPlugin {
1794
2105
  __privateSet$2(this, _schemaTables$1, schemaTables);
1795
2106
  }
1796
2107
  build(pluginOptions) {
1797
- const db = new Proxy({}, {
1798
- get: (_target, table) => {
1799
- if (!isString(table))
1800
- throw new Error("Invalid table name");
1801
- if (__privateGet$2(this, _tables)[table] === void 0) {
1802
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
2108
+ const db = new Proxy(
2109
+ {},
2110
+ {
2111
+ get: (_target, table) => {
2112
+ if (!isString(table))
2113
+ throw new Error("Invalid table name");
2114
+ if (__privateGet$2(this, _tables)[table] === void 0) {
2115
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
2116
+ }
2117
+ return __privateGet$2(this, _tables)[table];
1803
2118
  }
1804
- return __privateGet$2(this, _tables)[table];
1805
2119
  }
1806
- });
2120
+ );
1807
2121
  const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1808
2122
  for (const table of tableNames) {
1809
2123
  db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
@@ -1873,10 +2187,10 @@ _schemaTables = new WeakMap();
1873
2187
  _search = new WeakSet();
1874
2188
  search_fn = async function(query, options, getFetchProps) {
1875
2189
  const fetchProps = await getFetchProps();
1876
- const { tables, fuzziness, highlight } = options ?? {};
2190
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1877
2191
  const { records } = await searchBranch({
1878
2192
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1879
- body: { tables, query, fuzziness, highlight },
2193
+ body: { tables, query, fuzziness, prefix, highlight },
1880
2194
  ...fetchProps
1881
2195
  });
1882
2196
  return records;
@@ -1899,14 +2213,14 @@ const isBranchStrategyBuilder = (strategy) => {
1899
2213
  };
1900
2214
 
1901
2215
  async function getCurrentBranchName(options) {
1902
- const { branch } = getEnvironment();
2216
+ const { branch, envBranch } = getEnvironment();
1903
2217
  if (branch) {
1904
2218
  const details = await getDatabaseBranch(branch, options);
1905
2219
  if (details)
1906
2220
  return branch;
1907
2221
  console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1908
2222
  }
1909
- const gitBranch = await getGitBranch();
2223
+ const gitBranch = envBranch || await getGitBranch();
1910
2224
  return resolveXataBranch(gitBranch, options);
1911
2225
  }
1912
2226
  async function getCurrentBranchDetails(options) {
@@ -1917,9 +2231,13 @@ async function resolveXataBranch(gitBranch, options) {
1917
2231
  const databaseURL = options?.databaseURL || getDatabaseURL();
1918
2232
  const apiKey = options?.apiKey || getAPIKey();
1919
2233
  if (!databaseURL)
1920
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2234
+ throw new Error(
2235
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2236
+ );
1921
2237
  if (!apiKey)
1922
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2238
+ throw new Error(
2239
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2240
+ );
1923
2241
  const [protocol, , host, , dbName] = databaseURL.split("/");
1924
2242
  const [workspace] = host.split(".");
1925
2243
  const { fallbackBranch } = getEnvironment();
@@ -1929,7 +2247,8 @@ async function resolveXataBranch(gitBranch, options) {
1929
2247
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1930
2248
  workspacesApiUrl: `${protocol}//${host}`,
1931
2249
  pathParams: { dbName, workspace },
1932
- queryParams: { gitBranch, fallbackBranch }
2250
+ queryParams: { gitBranch, fallbackBranch },
2251
+ trace: defaultTrace
1933
2252
  });
1934
2253
  return branch;
1935
2254
  }
@@ -1937,9 +2256,13 @@ async function getDatabaseBranch(branch, options) {
1937
2256
  const databaseURL = options?.databaseURL || getDatabaseURL();
1938
2257
  const apiKey = options?.apiKey || getAPIKey();
1939
2258
  if (!databaseURL)
1940
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2259
+ throw new Error(
2260
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2261
+ );
1941
2262
  if (!apiKey)
1942
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2263
+ throw new Error(
2264
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2265
+ );
1943
2266
  const [protocol, , host, , database] = databaseURL.split("/");
1944
2267
  const [workspace] = host.split(".");
1945
2268
  const dbBranchName = `${database}:${branch}`;
@@ -1949,7 +2272,8 @@ async function getDatabaseBranch(branch, options) {
1949
2272
  apiUrl: databaseURL,
1950
2273
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1951
2274
  workspacesApiUrl: `${protocol}//${host}`,
1952
- pathParams: { dbBranchName, workspace }
2275
+ pathParams: { dbBranchName, workspace },
2276
+ trace: defaultTrace
1953
2277
  });
1954
2278
  } catch (err) {
1955
2279
  if (isObject(err) && err.status === 404)
@@ -1989,17 +2313,20 @@ var __privateMethod = (obj, member, method) => {
1989
2313
  return method;
1990
2314
  };
1991
2315
  const buildClient = (plugins) => {
1992
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2316
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1993
2317
  return _a = class {
1994
2318
  constructor(options = {}, schemaTables) {
1995
2319
  __privateAdd(this, _parseOptions);
1996
2320
  __privateAdd(this, _getFetchProps);
1997
2321
  __privateAdd(this, _evaluateBranch);
1998
2322
  __privateAdd(this, _branch, void 0);
2323
+ __privateAdd(this, _options, void 0);
1999
2324
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2325
+ __privateSet(this, _options, safeOptions);
2000
2326
  const pluginOptions = {
2001
2327
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
2002
- cache: safeOptions.cache
2328
+ cache: safeOptions.cache,
2329
+ trace: safeOptions.trace
2003
2330
  };
2004
2331
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2005
2332
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
@@ -2018,22 +2345,26 @@ const buildClient = (plugins) => {
2018
2345
  }
2019
2346
  }
2020
2347
  }
2021
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2348
+ async getConfig() {
2349
+ const databaseURL = __privateGet(this, _options).databaseURL;
2350
+ const branch = await __privateGet(this, _options).branch();
2351
+ return { databaseURL, branch };
2352
+ }
2353
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2022
2354
  const fetch = getFetchImplementation(options?.fetch);
2023
2355
  const databaseURL = options?.databaseURL || getDatabaseURL();
2024
2356
  const apiKey = options?.apiKey || getAPIKey();
2025
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2357
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2358
+ const trace = options?.trace ?? defaultTrace;
2026
2359
  const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2027
- if (!databaseURL || !apiKey) {
2028
- throw new Error("Options databaseURL and apiKey are required");
2360
+ if (!apiKey) {
2361
+ throw new Error("Option apiKey is required");
2029
2362
  }
2030
- return { fetch, databaseURL, apiKey, branch, cache };
2031
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
2032
- fetch,
2033
- apiKey,
2034
- databaseURL,
2035
- branch
2036
- }) {
2363
+ if (!databaseURL) {
2364
+ throw new Error("Option databaseURL is required");
2365
+ }
2366
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2367
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
2037
2368
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
2038
2369
  if (!branchValue)
2039
2370
  throw new Error("Unable to resolve branch value");
@@ -2043,9 +2374,10 @@ const buildClient = (plugins) => {
2043
2374
  apiUrl: "",
2044
2375
  workspacesApiUrl: (path, params) => {
2045
2376
  const hasBranch = params.dbBranchName ?? params.branch;
2046
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
2377
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
2047
2378
  return databaseURL + newPath;
2048
- }
2379
+ },
2380
+ trace
2049
2381
  };
2050
2382
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
2051
2383
  if (__privateGet(this, _branch))
@@ -2068,6 +2400,88 @@ const buildClient = (plugins) => {
2068
2400
  class BaseClient extends buildClient() {
2069
2401
  }
2070
2402
 
2403
+ const META = "__";
2404
+ const VALUE = "___";
2405
+ class Serializer {
2406
+ constructor() {
2407
+ this.classes = {};
2408
+ }
2409
+ add(clazz) {
2410
+ this.classes[clazz.name] = clazz;
2411
+ }
2412
+ toJSON(data) {
2413
+ function visit(obj) {
2414
+ if (Array.isArray(obj))
2415
+ return obj.map(visit);
2416
+ const type = typeof obj;
2417
+ if (type === "undefined")
2418
+ return { [META]: "undefined" };
2419
+ if (type === "bigint")
2420
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2421
+ if (obj === null || type !== "object")
2422
+ return obj;
2423
+ const constructor = obj.constructor;
2424
+ const o = { [META]: constructor.name };
2425
+ for (const [key, value] of Object.entries(obj)) {
2426
+ o[key] = visit(value);
2427
+ }
2428
+ if (constructor === Date)
2429
+ o[VALUE] = obj.toISOString();
2430
+ if (constructor === Map)
2431
+ o[VALUE] = Object.fromEntries(obj);
2432
+ if (constructor === Set)
2433
+ o[VALUE] = [...obj];
2434
+ return o;
2435
+ }
2436
+ return JSON.stringify(visit(data));
2437
+ }
2438
+ fromJSON(json) {
2439
+ return JSON.parse(json, (key, value) => {
2440
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2441
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2442
+ const constructor = this.classes[clazz];
2443
+ if (constructor) {
2444
+ return Object.assign(Object.create(constructor.prototype), rest);
2445
+ }
2446
+ if (clazz === "Date")
2447
+ return new Date(val);
2448
+ if (clazz === "Set")
2449
+ return new Set(val);
2450
+ if (clazz === "Map")
2451
+ return new Map(Object.entries(val));
2452
+ if (clazz === "bigint")
2453
+ return BigInt(val);
2454
+ if (clazz === "undefined")
2455
+ return void 0;
2456
+ return rest;
2457
+ }
2458
+ return value;
2459
+ });
2460
+ }
2461
+ }
2462
+ const defaultSerializer = new Serializer();
2463
+ const serialize = (data) => {
2464
+ return defaultSerializer.toJSON(data);
2465
+ };
2466
+ const deserialize = (json) => {
2467
+ return defaultSerializer.fromJSON(json);
2468
+ };
2469
+
2470
+ function buildWorkerRunner(config) {
2471
+ return function xataWorker(name, _worker) {
2472
+ return async (...args) => {
2473
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2474
+ const result = await fetch(url, {
2475
+ method: "POST",
2476
+ headers: { "Content-Type": "application/json" },
2477
+ body: serialize({ args })
2478
+ });
2479
+ const text = await result.text();
2480
+ return deserialize(text);
2481
+ };
2482
+ };
2483
+ }
2484
+
2071
2485
  class XataError extends Error {
2072
2486
  constructor(message, status) {
2073
2487
  super(message);
@@ -2088,6 +2502,7 @@ exports.Repository = Repository;
2088
2502
  exports.RestRepository = RestRepository;
2089
2503
  exports.SchemaPlugin = SchemaPlugin;
2090
2504
  exports.SearchPlugin = SearchPlugin;
2505
+ exports.Serializer = Serializer;
2091
2506
  exports.SimpleCache = SimpleCache;
2092
2507
  exports.XataApiClient = XataApiClient;
2093
2508
  exports.XataApiPlugin = XataApiPlugin;
@@ -2096,12 +2511,18 @@ exports.XataPlugin = XataPlugin;
2096
2511
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
2097
2512
  exports.addGitBranchesEntry = addGitBranchesEntry;
2098
2513
  exports.addTableColumn = addTableColumn;
2514
+ exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
2099
2515
  exports.buildClient = buildClient;
2516
+ exports.buildWorkerRunner = buildWorkerRunner;
2100
2517
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
2101
2518
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
2519
+ exports.compareBranchSchemas = compareBranchSchemas;
2520
+ exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
2521
+ exports.compareMigrationRequest = compareMigrationRequest;
2102
2522
  exports.contains = contains;
2103
2523
  exports.createBranch = createBranch;
2104
2524
  exports.createDatabase = createDatabase;
2525
+ exports.createMigrationRequest = createMigrationRequest;
2105
2526
  exports.createTable = createTable;
2106
2527
  exports.createUserAPIKey = createUserAPIKey;
2107
2528
  exports.createWorkspace = createWorkspace;
@@ -2113,7 +2534,9 @@ exports.deleteTable = deleteTable;
2113
2534
  exports.deleteUser = deleteUser;
2114
2535
  exports.deleteUserAPIKey = deleteUserAPIKey;
2115
2536
  exports.deleteWorkspace = deleteWorkspace;
2537
+ exports.deserialize = deserialize;
2116
2538
  exports.endsWith = endsWith;
2539
+ exports.equals = equals;
2117
2540
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
2118
2541
  exports.exists = exists;
2119
2542
  exports.ge = ge;
@@ -2123,13 +2546,17 @@ exports.getBranchList = getBranchList;
2123
2546
  exports.getBranchMetadata = getBranchMetadata;
2124
2547
  exports.getBranchMigrationHistory = getBranchMigrationHistory;
2125
2548
  exports.getBranchMigrationPlan = getBranchMigrationPlan;
2549
+ exports.getBranchSchemaHistory = getBranchSchemaHistory;
2126
2550
  exports.getBranchStats = getBranchStats;
2127
2551
  exports.getColumn = getColumn;
2128
2552
  exports.getCurrentBranchDetails = getCurrentBranchDetails;
2129
2553
  exports.getCurrentBranchName = getCurrentBranchName;
2130
2554
  exports.getDatabaseList = getDatabaseList;
2555
+ exports.getDatabaseMetadata = getDatabaseMetadata;
2131
2556
  exports.getDatabaseURL = getDatabaseURL;
2132
2557
  exports.getGitBranchesMapping = getGitBranchesMapping;
2558
+ exports.getMigrationRequest = getMigrationRequest;
2559
+ exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
2133
2560
  exports.getRecord = getRecord;
2134
2561
  exports.getTableColumns = getTableColumns;
2135
2562
  exports.getTableSchema = getTableSchema;
@@ -2138,6 +2565,9 @@ exports.getUserAPIKeys = getUserAPIKeys;
2138
2565
  exports.getWorkspace = getWorkspace;
2139
2566
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
2140
2567
  exports.getWorkspacesList = getWorkspacesList;
2568
+ exports.greaterEquals = greaterEquals;
2569
+ exports.greaterThan = greaterThan;
2570
+ exports.greaterThanEquals = greaterThanEquals;
2141
2571
  exports.gt = gt;
2142
2572
  exports.gte = gte;
2143
2573
  exports.includes = includes;
@@ -2153,11 +2583,19 @@ exports.isIdentifiable = isIdentifiable;
2153
2583
  exports.isNot = isNot;
2154
2584
  exports.isXataRecord = isXataRecord;
2155
2585
  exports.le = le;
2586
+ exports.lessEquals = lessEquals;
2587
+ exports.lessThan = lessThan;
2588
+ exports.lessThanEquals = lessThanEquals;
2589
+ exports.listMigrationRequests = listMigrationRequests;
2590
+ exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
2156
2591
  exports.lt = lt;
2157
2592
  exports.lte = lte;
2593
+ exports.mergeMigrationRequest = mergeMigrationRequest;
2158
2594
  exports.notExists = notExists;
2159
2595
  exports.operationsByTag = operationsByTag;
2596
+ exports.patchDatabaseMetadata = patchDatabaseMetadata;
2160
2597
  exports.pattern = pattern;
2598
+ exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
2161
2599
  exports.queryTable = queryTable;
2162
2600
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
2163
2601
  exports.removeWorkspaceMember = removeWorkspaceMember;
@@ -2165,14 +2603,18 @@ exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
2165
2603
  exports.resolveBranch = resolveBranch;
2166
2604
  exports.searchBranch = searchBranch;
2167
2605
  exports.searchTable = searchTable;
2606
+ exports.serialize = serialize;
2168
2607
  exports.setTableSchema = setTableSchema;
2169
2608
  exports.startsWith = startsWith;
2170
2609
  exports.updateBranchMetadata = updateBranchMetadata;
2610
+ exports.updateBranchSchema = updateBranchSchema;
2171
2611
  exports.updateColumn = updateColumn;
2612
+ exports.updateMigrationRequest = updateMigrationRequest;
2172
2613
  exports.updateRecordWithID = updateRecordWithID;
2173
2614
  exports.updateTable = updateTable;
2174
2615
  exports.updateUser = updateUser;
2175
2616
  exports.updateWorkspace = updateWorkspace;
2617
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
2176
2618
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
2177
2619
  exports.upsertRecordWithID = upsertRecordWithID;
2178
2620
  //# sourceMappingURL=index.cjs.map