@xata.io/client 0.0.0-alpha.vf603f80 → 0.0.0-alpha.vf683143

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
@@ -20,6 +20,28 @@ function _interopNamespace(e) {
20
20
  return Object.freeze(n);
21
21
  }
22
22
 
23
+ const defaultTrace = async (_name, fn, _options) => {
24
+ return await fn({
25
+ setAttributes: () => {
26
+ return;
27
+ }
28
+ });
29
+ };
30
+ const TraceAttributes = {
31
+ KIND: "xata.trace.kind",
32
+ VERSION: "xata.sdk.version",
33
+ TABLE: "xata.table",
34
+ HTTP_REQUEST_ID: "http.request_id",
35
+ HTTP_STATUS_CODE: "http.status_code",
36
+ HTTP_HOST: "http.host",
37
+ HTTP_SCHEME: "http.scheme",
38
+ HTTP_USER_AGENT: "http.user_agent",
39
+ HTTP_METHOD: "http.method",
40
+ HTTP_URL: "http.url",
41
+ HTTP_ROUTE: "http.route",
42
+ HTTP_TARGET: "http.target"
43
+ };
44
+
23
45
  function notEmpty(value) {
24
46
  return value !== null && value !== void 0;
25
47
  }
@@ -35,6 +57,9 @@ function isDefined(value) {
35
57
  function isString(value) {
36
58
  return isDefined(value) && typeof value === "string";
37
59
  }
60
+ function isStringArray(value) {
61
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
62
+ }
38
63
  function toBase64(value) {
39
64
  try {
40
65
  return btoa(value);
@@ -140,12 +165,14 @@ function getFetchImplementation(userFetch) {
140
165
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
141
166
  const fetchImpl = userFetch ?? globalFetch;
142
167
  if (!fetchImpl) {
143
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
168
+ throw new Error(
169
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
170
+ );
144
171
  }
145
172
  return fetchImpl;
146
173
  }
147
174
 
148
- const VERSION = "0.0.0-alpha.vf603f80";
175
+ const VERSION = "0.0.0-alpha.vf683143";
149
176
 
150
177
  class ErrorWithCause extends Error {
151
178
  constructor(message, options) {
@@ -196,7 +223,10 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
196
223
  }, {});
197
224
  const query = new URLSearchParams(cleanQueryParams).toString();
198
225
  const queryString = query.length > 0 ? `?${query}` : "";
199
- return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
226
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
227
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
228
+ }, {});
229
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
200
230
  };
201
231
  function buildBaseUrl({
202
232
  path,
@@ -204,10 +234,10 @@ function buildBaseUrl({
204
234
  apiUrl,
205
235
  pathParams
206
236
  }) {
207
- if (!pathParams?.workspace)
237
+ if (pathParams?.workspace === void 0)
208
238
  return `${apiUrl}${path}`;
209
239
  const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
210
- return url.replace("{workspaceId}", pathParams.workspace);
240
+ return url.replace("{workspaceId}", String(pathParams.workspace));
211
241
  }
212
242
  function hostHeader(url) {
213
243
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
@@ -224,34 +254,61 @@ async function fetch$1({
224
254
  fetchImpl,
225
255
  apiKey,
226
256
  apiUrl,
227
- workspacesApiUrl
257
+ workspacesApiUrl,
258
+ trace
228
259
  }) {
229
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
230
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
231
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
232
- const response = await fetchImpl(url, {
233
- method: method.toUpperCase(),
234
- body: body ? JSON.stringify(body) : void 0,
235
- headers: {
236
- "Content-Type": "application/json",
237
- "User-Agent": `Xata client-ts/${VERSION}`,
238
- ...headers,
239
- ...hostHeader(fullUrl),
240
- Authorization: `Bearer ${apiKey}`
241
- }
242
- });
243
- if (response.status === 204) {
244
- return {};
245
- }
246
- const requestId = response.headers?.get("x-request-id") ?? void 0;
260
+ return trace(
261
+ `${method.toUpperCase()} ${path}`,
262
+ async ({ setAttributes }) => {
263
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
264
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
265
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
266
+ setAttributes({
267
+ [TraceAttributes.HTTP_URL]: url,
268
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
269
+ });
270
+ const response = await fetchImpl(url, {
271
+ method: method.toUpperCase(),
272
+ body: body ? JSON.stringify(body) : void 0,
273
+ headers: {
274
+ "Content-Type": "application/json",
275
+ "User-Agent": `Xata client-ts/${VERSION}`,
276
+ ...headers,
277
+ ...hostHeader(fullUrl),
278
+ Authorization: `Bearer ${apiKey}`
279
+ }
280
+ });
281
+ if (response.status === 204) {
282
+ return {};
283
+ }
284
+ const { host, protocol } = parseUrl(response.url);
285
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
286
+ setAttributes({
287
+ [TraceAttributes.KIND]: "http",
288
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
289
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
290
+ [TraceAttributes.HTTP_HOST]: host,
291
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
292
+ });
293
+ try {
294
+ const jsonResponse = await response.json();
295
+ if (response.ok) {
296
+ return jsonResponse;
297
+ }
298
+ throw new FetcherError(response.status, jsonResponse, requestId);
299
+ } catch (error) {
300
+ throw new FetcherError(response.status, error, requestId);
301
+ }
302
+ },
303
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
304
+ );
305
+ }
306
+ function parseUrl(url) {
247
307
  try {
248
- const jsonResponse = await response.json();
249
- if (response.ok) {
250
- return jsonResponse;
251
- }
252
- throw new FetcherError(response.status, jsonResponse, requestId);
308
+ const { host, protocol } = new URL(url);
309
+ return { host, protocol };
253
310
  } catch (error) {
254
- throw new FetcherError(response.status, error, requestId);
311
+ return {};
255
312
  }
256
313
  }
257
314
 
@@ -346,6 +403,12 @@ const deleteDatabase = (variables) => fetch$1({
346
403
  method: "delete",
347
404
  ...variables
348
405
  });
406
+ const getDatabaseMetadata = (variables) => fetch$1({
407
+ url: "/dbs/{dbName}/metadata",
408
+ method: "get",
409
+ ...variables
410
+ });
411
+ const updateDatabaseMetadata = (variables) => fetch$1({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables });
349
412
  const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
350
413
  const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
351
414
  const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
@@ -354,16 +417,28 @@ const resolveBranch = (variables) => fetch$1({
354
417
  method: "get",
355
418
  ...variables
356
419
  });
357
- const getBranchDetails = (variables) => fetch$1({
358
- url: "/db/{dbBranchName}",
420
+ const listMigrationRequests = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/list", method: "post", ...variables });
421
+ const createMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations", method: "post", ...variables });
422
+ const getMigrationRequest = (variables) => fetch$1({
423
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
359
424
  method: "get",
360
425
  ...variables
361
426
  });
362
- const createBranch = (variables) => fetch$1({
427
+ const updateMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables });
428
+ const listMigrationRequestsCommits = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables });
429
+ const compareMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables });
430
+ const getMigrationRequestIsMerged = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables });
431
+ const mergeMigrationRequest = (variables) => fetch$1({
432
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
433
+ method: "post",
434
+ ...variables
435
+ });
436
+ const getBranchDetails = (variables) => fetch$1({
363
437
  url: "/db/{dbBranchName}",
364
- method: "put",
438
+ method: "get",
365
439
  ...variables
366
440
  });
441
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
367
442
  const deleteBranch = (variables) => fetch$1({
368
443
  url: "/db/{dbBranchName}",
369
444
  method: "delete",
@@ -382,6 +457,16 @@ const getBranchMetadata = (variables) => fetch$1({
382
457
  const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
383
458
  const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
384
459
  const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
460
+ const compareBranchWithUserSchema = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables });
461
+ const compareBranchSchemas = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables });
462
+ const updateBranchSchema = (variables) => fetch$1({
463
+ url: "/db/{dbBranchName}/schema/update",
464
+ method: "post",
465
+ ...variables
466
+ });
467
+ const previewBranchSchemaEdit = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables });
468
+ const applyBranchSchemaEdit = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables });
469
+ const getBranchSchemaHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables });
385
470
  const getBranchStats = (variables) => fetch$1({
386
471
  url: "/db/{dbBranchName}/stats",
387
472
  method: "get",
@@ -437,11 +522,7 @@ const updateColumn = (variables) => fetch$1({
437
522
  method: "patch",
438
523
  ...variables
439
524
  });
440
- const insertRecord = (variables) => fetch$1({
441
- url: "/db/{dbBranchName}/tables/{tableName}/data",
442
- method: "post",
443
- ...variables
444
- });
525
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
445
526
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
446
527
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
447
528
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -471,6 +552,11 @@ const searchBranch = (variables) => fetch$1({
471
552
  method: "post",
472
553
  ...variables
473
554
  });
555
+ const summarizeTable = (variables) => fetch$1({
556
+ url: "/db/{dbBranchName}/tables/{tableName}/summarize",
557
+ method: "post",
558
+ ...variables
559
+ });
474
560
  const operationsByTag = {
475
561
  users: { getUser, updateUser, deleteUser, getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
476
562
  workspaces: {
@@ -492,6 +578,8 @@ const operationsByTag = {
492
578
  getDatabaseList,
493
579
  createDatabase,
494
580
  deleteDatabase,
581
+ getDatabaseMetadata,
582
+ updateDatabaseMetadata,
495
583
  getGitBranchesMapping,
496
584
  addGitBranchesEntry,
497
585
  removeGitBranchesEntry,
@@ -504,10 +592,28 @@ const operationsByTag = {
504
592
  deleteBranch,
505
593
  updateBranchMetadata,
506
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: {
507
608
  getBranchMigrationHistory,
508
609
  executeBranchMigrationPlan,
509
610
  getBranchMigrationPlan,
510
- getBranchStats
611
+ compareBranchWithUserSchema,
612
+ compareBranchSchemas,
613
+ updateBranchSchema,
614
+ previewBranchSchemaEdit,
615
+ applyBranchSchemaEdit,
616
+ getBranchSchemaHistory
511
617
  },
512
618
  table: {
513
619
  createTable,
@@ -531,14 +637,15 @@ const operationsByTag = {
531
637
  bulkInsertTableRecords,
532
638
  queryTable,
533
639
  searchTable,
534
- searchBranch
640
+ searchBranch,
641
+ summarizeTable
535
642
  }
536
643
  };
537
644
 
538
645
  function getHostUrl(provider, type) {
539
- if (isValidAlias(provider)) {
646
+ if (isHostProviderAlias(provider)) {
540
647
  return providers[provider][type];
541
- } else if (isValidBuilder(provider)) {
648
+ } else if (isHostProviderBuilder(provider)) {
542
649
  return provider[type];
543
650
  }
544
651
  throw new Error("Invalid API provider");
@@ -553,10 +660,10 @@ const providers = {
553
660
  workspaces: "https://{workspaceId}.staging.xatabase.co"
554
661
  }
555
662
  };
556
- function isValidAlias(alias) {
663
+ function isHostProviderAlias(alias) {
557
664
  return isString(alias) && Object.keys(providers).includes(alias);
558
665
  }
559
- function isValidBuilder(builder) {
666
+ function isHostProviderBuilder(builder) {
560
667
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
561
668
  }
562
669
 
@@ -584,7 +691,8 @@ class XataApiClient {
584
691
  __privateAdd$7(this, _extraProps, void 0);
585
692
  __privateAdd$7(this, _namespaces, {});
586
693
  const provider = options.host ?? "production";
587
- const apiKey = options?.apiKey ?? getAPIKey();
694
+ const apiKey = options.apiKey ?? getAPIKey();
695
+ const trace = options.trace ?? defaultTrace;
588
696
  if (!apiKey) {
589
697
  throw new Error("Could not resolve a valid apiKey");
590
698
  }
@@ -592,7 +700,8 @@ class XataApiClient {
592
700
  apiUrl: getHostUrl(provider, "main"),
593
701
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
594
702
  fetchImpl: getFetchImplementation(options.fetch),
595
- apiKey
703
+ apiKey,
704
+ trace
596
705
  });
597
706
  }
598
707
  get user() {
@@ -625,6 +734,16 @@ class XataApiClient {
625
734
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
626
735
  return __privateGet$7(this, _namespaces).records;
627
736
  }
737
+ get migrationRequests() {
738
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
739
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
740
+ return __privateGet$7(this, _namespaces).migrationRequests;
741
+ }
742
+ get branchSchema() {
743
+ if (!__privateGet$7(this, _namespaces).branchSchema)
744
+ __privateGet$7(this, _namespaces).branchSchema = new BranchSchemaApi(__privateGet$7(this, _extraProps));
745
+ return __privateGet$7(this, _namespaces).branchSchema;
746
+ }
628
747
  }
629
748
  _extraProps = new WeakMap();
630
749
  _namespaces = new WeakMap();
@@ -764,6 +883,19 @@ class DatabaseApi {
764
883
  ...this.extraProps
765
884
  });
766
885
  }
886
+ getDatabaseMetadata(workspace, dbName) {
887
+ return operationsByTag.database.getDatabaseMetadata({
888
+ pathParams: { workspace, dbName },
889
+ ...this.extraProps
890
+ });
891
+ }
892
+ updateDatabaseMetadata(workspace, dbName, options = {}) {
893
+ return operationsByTag.database.updateDatabaseMetadata({
894
+ pathParams: { workspace, dbName },
895
+ body: options,
896
+ ...this.extraProps
897
+ });
898
+ }
767
899
  getGitBranchesMapping(workspace, dbName) {
768
900
  return operationsByTag.database.getGitBranchesMapping({
769
901
  pathParams: { workspace, dbName },
@@ -835,27 +967,6 @@ class BranchApi {
835
967
  ...this.extraProps
836
968
  });
837
969
  }
838
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
839
- return operationsByTag.branch.getBranchMigrationHistory({
840
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
841
- body: options,
842
- ...this.extraProps
843
- });
844
- }
845
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
846
- return operationsByTag.branch.executeBranchMigrationPlan({
847
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
848
- body: migrationPlan,
849
- ...this.extraProps
850
- });
851
- }
852
- getBranchMigrationPlan(workspace, database, branch, schema) {
853
- return operationsByTag.branch.getBranchMigrationPlan({
854
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
855
- body: schema,
856
- ...this.extraProps
857
- });
858
- }
859
970
  getBranchStats(workspace, database, branch) {
860
971
  return operationsByTag.branch.getBranchStats({
861
972
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -936,9 +1047,10 @@ class RecordsApi {
936
1047
  constructor(extraProps) {
937
1048
  this.extraProps = extraProps;
938
1049
  }
939
- insertRecord(workspace, database, branch, tableName, record) {
1050
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
940
1051
  return operationsByTag.records.insertRecord({
941
1052
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1053
+ queryParams: options,
942
1054
  body: record,
943
1055
  ...this.extraProps
944
1056
  });
@@ -967,21 +1079,24 @@ class RecordsApi {
967
1079
  ...this.extraProps
968
1080
  });
969
1081
  }
970
- deleteRecord(workspace, database, branch, tableName, recordId) {
1082
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
971
1083
  return operationsByTag.records.deleteRecord({
972
1084
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1085
+ queryParams: options,
973
1086
  ...this.extraProps
974
1087
  });
975
1088
  }
976
1089
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
977
1090
  return operationsByTag.records.getRecord({
978
1091
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1092
+ queryParams: options,
979
1093
  ...this.extraProps
980
1094
  });
981
1095
  }
982
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1096
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
983
1097
  return operationsByTag.records.bulkInsertTableRecords({
984
1098
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1099
+ queryParams: options,
985
1100
  body: { records },
986
1101
  ...this.extraProps
987
1102
  });
@@ -1007,6 +1122,138 @@ class RecordsApi {
1007
1122
  ...this.extraProps
1008
1123
  });
1009
1124
  }
1125
+ summarizeTable(workspace, database, branch, tableName, query) {
1126
+ return operationsByTag.records.summarizeTable({
1127
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1128
+ body: query,
1129
+ ...this.extraProps
1130
+ });
1131
+ }
1132
+ }
1133
+ class MigrationRequestsApi {
1134
+ constructor(extraProps) {
1135
+ this.extraProps = extraProps;
1136
+ }
1137
+ listMigrationRequests(workspace, database, options = {}) {
1138
+ return operationsByTag.migrationRequests.listMigrationRequests({
1139
+ pathParams: { workspace, dbName: database },
1140
+ body: options,
1141
+ ...this.extraProps
1142
+ });
1143
+ }
1144
+ createMigrationRequest(workspace, database, options) {
1145
+ return operationsByTag.migrationRequests.createMigrationRequest({
1146
+ pathParams: { workspace, dbName: database },
1147
+ body: options,
1148
+ ...this.extraProps
1149
+ });
1150
+ }
1151
+ getMigrationRequest(workspace, database, migrationRequest) {
1152
+ return operationsByTag.migrationRequests.getMigrationRequest({
1153
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1154
+ ...this.extraProps
1155
+ });
1156
+ }
1157
+ updateMigrationRequest(workspace, database, migrationRequest, options) {
1158
+ return operationsByTag.migrationRequests.updateMigrationRequest({
1159
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1160
+ body: options,
1161
+ ...this.extraProps
1162
+ });
1163
+ }
1164
+ listMigrationRequestsCommits(workspace, database, migrationRequest, options = {}) {
1165
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1166
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1167
+ body: options,
1168
+ ...this.extraProps
1169
+ });
1170
+ }
1171
+ compareMigrationRequest(workspace, database, migrationRequest) {
1172
+ return operationsByTag.migrationRequests.compareMigrationRequest({
1173
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1174
+ ...this.extraProps
1175
+ });
1176
+ }
1177
+ getMigrationRequestIsMerged(workspace, database, migrationRequest) {
1178
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1179
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1180
+ ...this.extraProps
1181
+ });
1182
+ }
1183
+ mergeMigrationRequest(workspace, database, migrationRequest) {
1184
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
1185
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1186
+ ...this.extraProps
1187
+ });
1188
+ }
1189
+ }
1190
+ class BranchSchemaApi {
1191
+ constructor(extraProps) {
1192
+ this.extraProps = extraProps;
1193
+ }
1194
+ getBranchMigrationHistory(workspace, database, branch, options = {}) {
1195
+ return operationsByTag.branchSchema.getBranchMigrationHistory({
1196
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1197
+ body: options,
1198
+ ...this.extraProps
1199
+ });
1200
+ }
1201
+ executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
1202
+ return operationsByTag.branchSchema.executeBranchMigrationPlan({
1203
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1204
+ body: migrationPlan,
1205
+ ...this.extraProps
1206
+ });
1207
+ }
1208
+ getBranchMigrationPlan(workspace, database, branch, schema) {
1209
+ return operationsByTag.branchSchema.getBranchMigrationPlan({
1210
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1211
+ body: schema,
1212
+ ...this.extraProps
1213
+ });
1214
+ }
1215
+ compareBranchWithUserSchema(workspace, database, branch, schema) {
1216
+ return operationsByTag.branchSchema.compareBranchWithUserSchema({
1217
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1218
+ body: { schema },
1219
+ ...this.extraProps
1220
+ });
1221
+ }
1222
+ compareBranchSchemas(workspace, database, branch, branchName, schema) {
1223
+ return operationsByTag.branchSchema.compareBranchSchemas({
1224
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, branchName },
1225
+ body: { schema },
1226
+ ...this.extraProps
1227
+ });
1228
+ }
1229
+ updateBranchSchema(workspace, database, branch, migration) {
1230
+ return operationsByTag.branchSchema.updateBranchSchema({
1231
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1232
+ body: migration,
1233
+ ...this.extraProps
1234
+ });
1235
+ }
1236
+ previewBranchSchemaEdit(workspace, database, branch, migration) {
1237
+ return operationsByTag.branchSchema.previewBranchSchemaEdit({
1238
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1239
+ body: migration,
1240
+ ...this.extraProps
1241
+ });
1242
+ }
1243
+ applyBranchSchemaEdit(workspace, database, branch, edits) {
1244
+ return operationsByTag.branchSchema.applyBranchSchemaEdit({
1245
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1246
+ body: { edits },
1247
+ ...this.extraProps
1248
+ });
1249
+ }
1250
+ getBranchSchemaHistory(workspace, database, branch, options = {}) {
1251
+ return operationsByTag.branchSchema.getBranchSchemaHistory({
1252
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1253
+ body: options,
1254
+ ...this.extraProps
1255
+ });
1256
+ }
1010
1257
  }
1011
1258
 
1012
1259
  class XataApiPlugin {
@@ -1191,21 +1438,34 @@ const _Query = class {
1191
1438
  }
1192
1439
  filter(a, b) {
1193
1440
  if (arguments.length === 1) {
1194
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1441
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({ [column]: constraint }));
1195
1442
  const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1196
1443
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1197
1444
  } else {
1198
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1445
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: this.defaultFilter(a, b) }] : void 0;
1446
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1199
1447
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1200
1448
  }
1201
1449
  }
1202
- sort(column, direction) {
1450
+ defaultFilter(column, value) {
1451
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
1452
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
1453
+ return { $includes: value };
1454
+ }
1455
+ return value;
1456
+ }
1457
+ sort(column, direction = "asc") {
1203
1458
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1204
1459
  const sort = [...originalSort, { column, direction }];
1205
1460
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1206
1461
  }
1207
1462
  select(columns) {
1208
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1463
+ return new _Query(
1464
+ __privateGet$5(this, _repository),
1465
+ __privateGet$5(this, _table$1),
1466
+ { columns },
1467
+ __privateGet$5(this, _data)
1468
+ );
1209
1469
  }
1210
1470
  getPaginated(options = {}) {
1211
1471
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1228,11 +1488,20 @@ const _Query = class {
1228
1488
  }
1229
1489
  }
1230
1490
  async getMany(options = {}) {
1231
- const page = await this.getPaginated(options);
1491
+ const { pagination = {}, ...rest } = options;
1492
+ const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
1493
+ const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
1494
+ let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
1495
+ const results = [...page.records];
1496
+ while (page.hasNextPage() && results.length < size) {
1497
+ page = await page.nextPage();
1498
+ results.push(...page.records);
1499
+ }
1232
1500
  if (page.hasNextPage() && options.pagination?.size === void 0) {
1233
1501
  console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1234
1502
  }
1235
- return page.records;
1503
+ const array = new RecordArray(page, results.slice(0, size));
1504
+ return array;
1236
1505
  }
1237
1506
  async getAll(options = {}) {
1238
1507
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1246,6 +1515,12 @@ const _Query = class {
1246
1515
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1247
1516
  return records[0] ?? null;
1248
1517
  }
1518
+ async getFirstOrThrow(options = {}) {
1519
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1520
+ if (records[0] === void 0)
1521
+ throw new Error("No results found.");
1522
+ return records[0];
1523
+ }
1249
1524
  cache(ttl) {
1250
1525
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1251
1526
  }
@@ -1330,203 +1605,284 @@ var __privateMethod$2 = (obj, member, method) => {
1330
1605
  __accessCheck$4(obj, member, "access private method");
1331
1606
  return method;
1332
1607
  };
1333
- 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;
1608
+ 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;
1334
1609
  class Repository extends Query {
1335
1610
  }
1336
1611
  class RestRepository extends Query {
1337
1612
  constructor(options) {
1338
- super(null, options.table, {});
1613
+ super(
1614
+ null,
1615
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
1616
+ {}
1617
+ );
1339
1618
  __privateAdd$4(this, _insertRecordWithoutId);
1340
1619
  __privateAdd$4(this, _insertRecordWithId);
1341
1620
  __privateAdd$4(this, _bulkInsertTableRecords);
1342
1621
  __privateAdd$4(this, _updateRecordWithID);
1343
1622
  __privateAdd$4(this, _upsertRecordWithID);
1344
1623
  __privateAdd$4(this, _deleteRecord);
1345
- __privateAdd$4(this, _invalidateCache);
1346
- __privateAdd$4(this, _setCacheRecord);
1347
- __privateAdd$4(this, _getCacheRecord);
1348
1624
  __privateAdd$4(this, _setCacheQuery);
1349
1625
  __privateAdd$4(this, _getCacheQuery);
1350
1626
  __privateAdd$4(this, _getSchemaTables$1);
1351
1627
  __privateAdd$4(this, _table, void 0);
1352
1628
  __privateAdd$4(this, _getFetchProps, void 0);
1629
+ __privateAdd$4(this, _db, void 0);
1353
1630
  __privateAdd$4(this, _cache, void 0);
1354
1631
  __privateAdd$4(this, _schemaTables$2, void 0);
1632
+ __privateAdd$4(this, _trace, void 0);
1355
1633
  __privateSet$4(this, _table, options.table);
1356
1634
  __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1357
- this.db = options.db;
1635
+ __privateSet$4(this, _db, options.db);
1358
1636
  __privateSet$4(this, _cache, options.pluginOptions.cache);
1359
1637
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
1638
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1639
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1640
+ return trace(name, fn, {
1641
+ ...options2,
1642
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1643
+ [TraceAttributes.KIND]: "sdk-operation",
1644
+ [TraceAttributes.VERSION]: VERSION
1645
+ });
1646
+ });
1360
1647
  }
1361
- async create(a, b) {
1362
- if (Array.isArray(a)) {
1363
- if (a.length === 0)
1364
- return [];
1365
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1366
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1367
- return records;
1368
- }
1369
- if (isString(a) && isObject(b)) {
1370
- if (a === "")
1371
- throw new Error("The id can't be empty");
1372
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1373
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1374
- return record;
1375
- }
1376
- if (isObject(a) && isString(a.id)) {
1377
- if (a.id === "")
1378
- throw new Error("The id can't be empty");
1379
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1380
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1381
- return record;
1382
- }
1383
- if (isObject(a)) {
1384
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1385
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1386
- return record;
1387
- }
1388
- throw new Error("Invalid arguments for create method");
1389
- }
1390
- async read(a) {
1391
- if (Array.isArray(a)) {
1392
- if (a.length === 0)
1393
- return [];
1394
- const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1395
- return this.getAll({ filter: { id: { $any: ids } } });
1396
- }
1397
- const id = isString(a) ? a : a.id;
1398
- if (isString(id)) {
1399
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1400
- if (cacheRecord)
1401
- return cacheRecord;
1402
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1403
- try {
1404
- const response = await getRecord({
1405
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1406
- ...fetchProps
1407
- });
1408
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1409
- return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1410
- } catch (e) {
1411
- if (isObject(e) && e.status === 404) {
1412
- return null;
1648
+ async create(a, b, c) {
1649
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1650
+ if (Array.isArray(a)) {
1651
+ if (a.length === 0)
1652
+ return [];
1653
+ const columns = isStringArray(b) ? b : void 0;
1654
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1655
+ }
1656
+ if (isString(a) && isObject(b)) {
1657
+ if (a === "")
1658
+ throw new Error("The id can't be empty");
1659
+ const columns = isStringArray(c) ? c : void 0;
1660
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1661
+ }
1662
+ if (isObject(a) && isString(a.id)) {
1663
+ if (a.id === "")
1664
+ throw new Error("The id can't be empty");
1665
+ const columns = isStringArray(b) ? b : void 0;
1666
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1667
+ }
1668
+ if (isObject(a)) {
1669
+ const columns = isStringArray(b) ? b : void 0;
1670
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1671
+ }
1672
+ throw new Error("Invalid arguments for create method");
1673
+ });
1674
+ }
1675
+ async read(a, b) {
1676
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1677
+ const columns = isStringArray(b) ? b : ["*"];
1678
+ if (Array.isArray(a)) {
1679
+ if (a.length === 0)
1680
+ return [];
1681
+ const ids = a.map((item) => extractId(item));
1682
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1683
+ const dictionary = finalObjects.reduce((acc, object) => {
1684
+ acc[object.id] = object;
1685
+ return acc;
1686
+ }, {});
1687
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1688
+ }
1689
+ const id = extractId(a);
1690
+ if (id) {
1691
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1692
+ try {
1693
+ const response = await getRecord({
1694
+ pathParams: {
1695
+ workspace: "{workspaceId}",
1696
+ dbBranchName: "{dbBranch}",
1697
+ tableName: __privateGet$4(this, _table),
1698
+ recordId: id
1699
+ },
1700
+ queryParams: { columns },
1701
+ ...fetchProps
1702
+ });
1703
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1704
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1705
+ } catch (e) {
1706
+ if (isObject(e) && e.status === 404) {
1707
+ return null;
1708
+ }
1709
+ throw e;
1413
1710
  }
1414
- throw e;
1415
1711
  }
1416
- }
1712
+ return null;
1713
+ });
1417
1714
  }
1418
- async update(a, b) {
1419
- if (Array.isArray(a)) {
1420
- if (a.length === 0)
1421
- return [];
1422
- if (a.length > 100) {
1423
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1715
+ async readOrThrow(a, b) {
1716
+ return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
1717
+ const result = await this.read(a, b);
1718
+ if (Array.isArray(result)) {
1719
+ const missingIds = compact(
1720
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1721
+ );
1722
+ if (missingIds.length > 0) {
1723
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1724
+ }
1725
+ return result;
1424
1726
  }
1425
- return Promise.all(a.map((object) => this.update(object)));
1426
- }
1427
- if (isString(a) && isObject(b)) {
1428
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1429
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1430
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1431
- return record;
1432
- }
1433
- if (isObject(a) && isString(a.id)) {
1434
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1435
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1436
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1437
- return record;
1438
- }
1439
- throw new Error("Invalid arguments for update method");
1440
- }
1441
- async createOrUpdate(a, b) {
1442
- if (Array.isArray(a)) {
1443
- if (a.length === 0)
1444
- return [];
1445
- if (a.length > 100) {
1446
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1727
+ if (result === null) {
1728
+ const id = extractId(a) ?? "unknown";
1729
+ throw new Error(`Record with id ${id} not found`);
1447
1730
  }
1448
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1449
- }
1450
- if (isString(a) && isObject(b)) {
1451
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1452
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1453
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1454
- return record;
1455
- }
1456
- if (isObject(a) && isString(a.id)) {
1457
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1458
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1459
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1460
- return record;
1461
- }
1462
- throw new Error("Invalid arguments for createOrUpdate method");
1463
- }
1464
- async delete(a) {
1465
- if (Array.isArray(a)) {
1466
- if (a.length === 0)
1467
- return;
1468
- if (a.length > 100) {
1469
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1731
+ return result;
1732
+ });
1733
+ }
1734
+ async update(a, b, c) {
1735
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1736
+ if (Array.isArray(a)) {
1737
+ if (a.length === 0)
1738
+ return [];
1739
+ if (a.length > 100) {
1740
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1741
+ }
1742
+ const columns = isStringArray(b) ? b : ["*"];
1743
+ return Promise.all(a.map((object) => this.update(object, columns)));
1470
1744
  }
1471
- await Promise.all(a.map((id) => this.delete(id)));
1472
- return;
1473
- }
1474
- if (isString(a)) {
1475
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1476
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1477
- return;
1478
- }
1479
- if (isObject(a) && isString(a.id)) {
1480
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1481
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1482
- return;
1483
- }
1484
- throw new Error("Invalid arguments for delete method");
1745
+ if (isString(a) && isObject(b)) {
1746
+ const columns = isStringArray(c) ? c : void 0;
1747
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1748
+ }
1749
+ if (isObject(a) && isString(a.id)) {
1750
+ const columns = isStringArray(b) ? b : void 0;
1751
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1752
+ }
1753
+ throw new Error("Invalid arguments for update method");
1754
+ });
1755
+ }
1756
+ async updateOrThrow(a, b, c) {
1757
+ return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
1758
+ const result = await this.update(a, b, c);
1759
+ if (Array.isArray(result)) {
1760
+ const missingIds = compact(
1761
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1762
+ );
1763
+ if (missingIds.length > 0) {
1764
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1765
+ }
1766
+ return result;
1767
+ }
1768
+ if (result === null) {
1769
+ const id = extractId(a) ?? "unknown";
1770
+ throw new Error(`Record with id ${id} not found`);
1771
+ }
1772
+ return result;
1773
+ });
1774
+ }
1775
+ async createOrUpdate(a, b, c) {
1776
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1777
+ if (Array.isArray(a)) {
1778
+ if (a.length === 0)
1779
+ return [];
1780
+ if (a.length > 100) {
1781
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1782
+ }
1783
+ const columns = isStringArray(b) ? b : ["*"];
1784
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1785
+ }
1786
+ if (isString(a) && isObject(b)) {
1787
+ const columns = isStringArray(c) ? c : void 0;
1788
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1789
+ }
1790
+ if (isObject(a) && isString(a.id)) {
1791
+ const columns = isStringArray(c) ? c : void 0;
1792
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1793
+ }
1794
+ throw new Error("Invalid arguments for createOrUpdate method");
1795
+ });
1796
+ }
1797
+ async delete(a, b) {
1798
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1799
+ if (Array.isArray(a)) {
1800
+ if (a.length === 0)
1801
+ return [];
1802
+ if (a.length > 100) {
1803
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1804
+ }
1805
+ return Promise.all(a.map((id) => this.delete(id, b)));
1806
+ }
1807
+ if (isString(a)) {
1808
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1809
+ }
1810
+ if (isObject(a) && isString(a.id)) {
1811
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1812
+ }
1813
+ throw new Error("Invalid arguments for delete method");
1814
+ });
1815
+ }
1816
+ async deleteOrThrow(a, b) {
1817
+ return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
1818
+ const result = await this.delete(a, b);
1819
+ if (Array.isArray(result)) {
1820
+ const missingIds = compact(
1821
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1822
+ );
1823
+ if (missingIds.length > 0) {
1824
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1825
+ }
1826
+ return result;
1827
+ } else if (result === null) {
1828
+ const id = extractId(a) ?? "unknown";
1829
+ throw new Error(`Record with id ${id} not found`);
1830
+ }
1831
+ return result;
1832
+ });
1485
1833
  }
1486
1834
  async search(query, options = {}) {
1487
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1488
- const { records } = await searchTable({
1489
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1490
- body: {
1491
- query,
1492
- fuzziness: options.fuzziness,
1493
- highlight: options.highlight,
1494
- filter: options.filter
1495
- },
1496
- ...fetchProps
1835
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1836
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1837
+ const { records } = await searchTable({
1838
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1839
+ body: {
1840
+ query,
1841
+ fuzziness: options.fuzziness,
1842
+ prefix: options.prefix,
1843
+ highlight: options.highlight,
1844
+ filter: options.filter,
1845
+ boosters: options.boosters
1846
+ },
1847
+ ...fetchProps
1848
+ });
1849
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1850
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1497
1851
  });
1498
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1499
- return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1500
1852
  }
1501
1853
  async query(query) {
1502
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1503
- if (cacheQuery)
1504
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1505
- const data = query.getQueryOptions();
1506
- const body = {
1507
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1508
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1509
- page: data.pagination,
1510
- columns: data.columns
1511
- };
1512
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1513
- const { meta, records: objects } = await queryTable({
1514
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1515
- body,
1516
- ...fetchProps
1854
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1855
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1856
+ if (cacheQuery)
1857
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1858
+ const data = query.getQueryOptions();
1859
+ const body = {
1860
+ filter: cleanFilter(data.filter),
1861
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1862
+ page: data.pagination,
1863
+ columns: data.columns
1864
+ };
1865
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1866
+ const { meta, records: objects } = await queryTable({
1867
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1868
+ body,
1869
+ ...fetchProps
1870
+ });
1871
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1872
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1873
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1874
+ return new Page(query, meta, records);
1517
1875
  });
1518
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1519
- const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1520
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1521
- return new Page(query, meta, records);
1522
1876
  }
1523
1877
  }
1524
1878
  _table = new WeakMap();
1525
1879
  _getFetchProps = new WeakMap();
1880
+ _db = new WeakMap();
1526
1881
  _cache = new WeakMap();
1527
1882
  _schemaTables$2 = new WeakMap();
1883
+ _trace = new WeakMap();
1528
1884
  _insertRecordWithoutId = new WeakSet();
1529
- insertRecordWithoutId_fn = async function(object) {
1885
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1530
1886
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1531
1887
  const record = transformObjectLinks(object);
1532
1888
  const response = await insertRecord({
@@ -1535,17 +1891,15 @@ insertRecordWithoutId_fn = async function(object) {
1535
1891
  dbBranchName: "{dbBranch}",
1536
1892
  tableName: __privateGet$4(this, _table)
1537
1893
  },
1894
+ queryParams: { columns },
1538
1895
  body: record,
1539
1896
  ...fetchProps
1540
1897
  });
1541
- const finalObject = await this.read(response.id);
1542
- if (!finalObject) {
1543
- throw new Error("The server failed to save the record");
1544
- }
1545
- return finalObject;
1898
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1899
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1546
1900
  };
1547
1901
  _insertRecordWithId = new WeakSet();
1548
- insertRecordWithId_fn = async function(recordId, object) {
1902
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1549
1903
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1550
1904
  const record = transformObjectLinks(object);
1551
1905
  const response = await insertRecordWithID({
@@ -1556,92 +1910,78 @@ insertRecordWithId_fn = async function(recordId, object) {
1556
1910
  recordId
1557
1911
  },
1558
1912
  body: record,
1559
- queryParams: { createOnly: true },
1913
+ queryParams: { createOnly: true, columns },
1560
1914
  ...fetchProps
1561
1915
  });
1562
- const finalObject = await this.read(response.id);
1563
- if (!finalObject) {
1564
- throw new Error("The server failed to save the record");
1565
- }
1566
- return finalObject;
1916
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1917
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1567
1918
  };
1568
1919
  _bulkInsertTableRecords = new WeakSet();
1569
- bulkInsertTableRecords_fn = async function(objects) {
1920
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1570
1921
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1571
1922
  const records = objects.map((object) => transformObjectLinks(object));
1572
- const { recordIDs } = await bulkInsertTableRecords({
1923
+ const response = await bulkInsertTableRecords({
1573
1924
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1925
+ queryParams: { columns },
1574
1926
  body: { records },
1575
1927
  ...fetchProps
1576
1928
  });
1577
- const finalObjects = await this.read(recordIDs);
1578
- if (finalObjects.length !== objects.length) {
1579
- throw new Error("The server failed to save some records");
1929
+ if (!isResponseWithRecords(response)) {
1930
+ throw new Error("Request included columns but server didn't include them");
1580
1931
  }
1581
- const dictionary = finalObjects.reduce((acc, object) => {
1582
- acc[object.id] = object;
1583
- return acc;
1584
- }, {});
1585
- return recordIDs.map((id) => dictionary[id]);
1932
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1933
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1586
1934
  };
1587
1935
  _updateRecordWithID = new WeakSet();
1588
- updateRecordWithID_fn = async function(recordId, object) {
1936
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1589
1937
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1590
1938
  const record = transformObjectLinks(object);
1591
- const response = await updateRecordWithID({
1592
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1593
- body: record,
1594
- ...fetchProps
1595
- });
1596
- const item = await this.read(response.id);
1597
- if (!item)
1598
- throw new Error("The server failed to save the record");
1599
- return item;
1939
+ try {
1940
+ const response = await updateRecordWithID({
1941
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1942
+ queryParams: { columns },
1943
+ body: record,
1944
+ ...fetchProps
1945
+ });
1946
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1947
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1948
+ } catch (e) {
1949
+ if (isObject(e) && e.status === 404) {
1950
+ return null;
1951
+ }
1952
+ throw e;
1953
+ }
1600
1954
  };
1601
1955
  _upsertRecordWithID = new WeakSet();
1602
- upsertRecordWithID_fn = async function(recordId, object) {
1956
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1603
1957
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1604
1958
  const response = await upsertRecordWithID({
1605
1959
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1960
+ queryParams: { columns },
1606
1961
  body: object,
1607
1962
  ...fetchProps
1608
1963
  });
1609
- const item = await this.read(response.id);
1610
- if (!item)
1611
- throw new Error("The server failed to save the record");
1612
- return item;
1964
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1965
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1613
1966
  };
1614
1967
  _deleteRecord = new WeakSet();
1615
- deleteRecord_fn = async function(recordId) {
1968
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1616
1969
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1617
- await deleteRecord({
1618
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1619
- ...fetchProps
1620
- });
1621
- };
1622
- _invalidateCache = new WeakSet();
1623
- invalidateCache_fn = async function(recordId) {
1624
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1625
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1626
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1627
- for (const [key, value] of queries) {
1628
- const ids = getIds(value);
1629
- if (ids.includes(recordId))
1630
- await __privateGet$4(this, _cache).delete(key);
1970
+ try {
1971
+ const response = await deleteRecord({
1972
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1973
+ queryParams: { columns },
1974
+ ...fetchProps
1975
+ });
1976
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1977
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1978
+ } catch (e) {
1979
+ if (isObject(e) && e.status === 404) {
1980
+ return null;
1981
+ }
1982
+ throw e;
1631
1983
  }
1632
1984
  };
1633
- _setCacheRecord = new WeakSet();
1634
- setCacheRecord_fn = async function(record) {
1635
- if (!__privateGet$4(this, _cache).cacheRecords)
1636
- return;
1637
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1638
- };
1639
- _getCacheRecord = new WeakSet();
1640
- getCacheRecord_fn = async function(recordId) {
1641
- if (!__privateGet$4(this, _cache).cacheRecords)
1642
- return null;
1643
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1644
- };
1645
1985
  _setCacheQuery = new WeakSet();
1646
1986
  setCacheQuery_fn = async function(query, meta, records) {
1647
1987
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -1702,16 +2042,24 @@ const initObject = (db, schemaTables, table, object) => {
1702
2042
  console.error(`Failed to parse link for field ${column.name}`);
1703
2043
  } else if (isObject(value)) {
1704
2044
  result[column.name] = initObject(db, schemaTables, linkTable, value);
2045
+ } else {
2046
+ result[column.name] = null;
1705
2047
  }
1706
2048
  break;
1707
2049
  }
2050
+ default:
2051
+ result[column.name] = value ?? null;
2052
+ if (column.notNull === true && value === null) {
2053
+ console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2054
+ }
2055
+ break;
1708
2056
  }
1709
2057
  }
1710
- result.read = function() {
1711
- return db[table].read(result["id"]);
2058
+ result.read = function(columns2) {
2059
+ return db[table].read(result["id"], columns2);
1712
2060
  };
1713
- result.update = function(data) {
1714
- return db[table].update(result["id"], data);
2061
+ result.update = function(data, columns2) {
2062
+ return db[table].update(result["id"], data, columns2);
1715
2063
  };
1716
2064
  result.delete = function() {
1717
2065
  return db[table].delete(result["id"]);
@@ -1725,14 +2073,21 @@ const initObject = (db, schemaTables, table, object) => {
1725
2073
  Object.freeze(result);
1726
2074
  return result;
1727
2075
  };
1728
- function getIds(value) {
1729
- if (Array.isArray(value)) {
1730
- return value.map((item) => getIds(item)).flat();
1731
- }
1732
- if (!isObject(value))
1733
- return [];
1734
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1735
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
2076
+ function isResponseWithRecords(value) {
2077
+ return isObject(value) && Array.isArray(value.records);
2078
+ }
2079
+ function extractId(value) {
2080
+ if (isString(value))
2081
+ return value;
2082
+ if (isObject(value) && isString(value.id))
2083
+ return value.id;
2084
+ return void 0;
2085
+ }
2086
+ function cleanFilter(filter) {
2087
+ if (!filter)
2088
+ return void 0;
2089
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
2090
+ return values.length > 0 ? filter : void 0;
1736
2091
  }
1737
2092
 
1738
2093
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1759,7 +2114,6 @@ class SimpleCache {
1759
2114
  __privateAdd$3(this, _map, void 0);
1760
2115
  __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1761
2116
  this.capacity = options.max ?? 500;
1762
- this.cacheRecords = options.cacheRecords ?? true;
1763
2117
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1764
2118
  }
1765
2119
  async getAll() {
@@ -1785,18 +2139,25 @@ class SimpleCache {
1785
2139
  }
1786
2140
  _map = new WeakMap();
1787
2141
 
1788
- const gt = (value) => ({ $gt: value });
1789
- const ge = (value) => ({ $ge: value });
1790
- const gte = (value) => ({ $ge: value });
1791
- const lt = (value) => ({ $lt: value });
1792
- const lte = (value) => ({ $le: value });
1793
- const le = (value) => ({ $le: value });
2142
+ const greaterThan = (value) => ({ $gt: value });
2143
+ const gt = greaterThan;
2144
+ const greaterThanEquals = (value) => ({ $ge: value });
2145
+ const greaterEquals = greaterThanEquals;
2146
+ const gte = greaterThanEquals;
2147
+ const ge = greaterThanEquals;
2148
+ const lessThan = (value) => ({ $lt: value });
2149
+ const lt = lessThan;
2150
+ const lessThanEquals = (value) => ({ $le: value });
2151
+ const lessEquals = lessThanEquals;
2152
+ const lte = lessThanEquals;
2153
+ const le = lessThanEquals;
1794
2154
  const exists = (column) => ({ $exists: column });
1795
2155
  const notExists = (column) => ({ $notExists: column });
1796
2156
  const startsWith = (value) => ({ $startsWith: value });
1797
2157
  const endsWith = (value) => ({ $endsWith: value });
1798
2158
  const pattern = (value) => ({ $pattern: value });
1799
2159
  const is = (value) => ({ $is: value });
2160
+ const equals = is;
1800
2161
  const isNot = (value) => ({ $isNot: value });
1801
2162
  const contains = (value) => ({ $contains: value });
1802
2163
  const includes = (value) => ({ $includes: value });
@@ -1831,16 +2192,19 @@ class SchemaPlugin extends XataPlugin {
1831
2192
  __privateSet$2(this, _schemaTables$1, schemaTables);
1832
2193
  }
1833
2194
  build(pluginOptions) {
1834
- const db = new Proxy({}, {
1835
- get: (_target, table) => {
1836
- if (!isString(table))
1837
- throw new Error("Invalid table name");
1838
- if (__privateGet$2(this, _tables)[table] === void 0) {
1839
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
2195
+ const db = new Proxy(
2196
+ {},
2197
+ {
2198
+ get: (_target, table) => {
2199
+ if (!isString(table))
2200
+ throw new Error("Invalid table name");
2201
+ if (__privateGet$2(this, _tables)[table] === void 0) {
2202
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
2203
+ }
2204
+ return __privateGet$2(this, _tables)[table];
1840
2205
  }
1841
- return __privateGet$2(this, _tables)[table];
1842
2206
  }
1843
- });
2207
+ );
1844
2208
  const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1845
2209
  for (const table of tableNames) {
1846
2210
  db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
@@ -1910,10 +2274,10 @@ _schemaTables = new WeakMap();
1910
2274
  _search = new WeakSet();
1911
2275
  search_fn = async function(query, options, getFetchProps) {
1912
2276
  const fetchProps = await getFetchProps();
1913
- const { tables, fuzziness, highlight } = options ?? {};
2277
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1914
2278
  const { records } = await searchBranch({
1915
2279
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1916
- body: { tables, query, fuzziness, highlight },
2280
+ body: { tables, query, fuzziness, prefix, highlight },
1917
2281
  ...fetchProps
1918
2282
  });
1919
2283
  return records;
@@ -1954,9 +2318,13 @@ async function resolveXataBranch(gitBranch, options) {
1954
2318
  const databaseURL = options?.databaseURL || getDatabaseURL();
1955
2319
  const apiKey = options?.apiKey || getAPIKey();
1956
2320
  if (!databaseURL)
1957
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2321
+ throw new Error(
2322
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2323
+ );
1958
2324
  if (!apiKey)
1959
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2325
+ throw new Error(
2326
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2327
+ );
1960
2328
  const [protocol, , host, , dbName] = databaseURL.split("/");
1961
2329
  const [workspace] = host.split(".");
1962
2330
  const { fallbackBranch } = getEnvironment();
@@ -1966,7 +2334,8 @@ async function resolveXataBranch(gitBranch, options) {
1966
2334
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1967
2335
  workspacesApiUrl: `${protocol}//${host}`,
1968
2336
  pathParams: { dbName, workspace },
1969
- queryParams: { gitBranch, fallbackBranch }
2337
+ queryParams: { gitBranch, fallbackBranch },
2338
+ trace: defaultTrace
1970
2339
  });
1971
2340
  return branch;
1972
2341
  }
@@ -1974,9 +2343,13 @@ async function getDatabaseBranch(branch, options) {
1974
2343
  const databaseURL = options?.databaseURL || getDatabaseURL();
1975
2344
  const apiKey = options?.apiKey || getAPIKey();
1976
2345
  if (!databaseURL)
1977
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2346
+ throw new Error(
2347
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2348
+ );
1978
2349
  if (!apiKey)
1979
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2350
+ throw new Error(
2351
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2352
+ );
1980
2353
  const [protocol, , host, , database] = databaseURL.split("/");
1981
2354
  const [workspace] = host.split(".");
1982
2355
  const dbBranchName = `${database}:${branch}`;
@@ -1986,7 +2359,8 @@ async function getDatabaseBranch(branch, options) {
1986
2359
  apiUrl: databaseURL,
1987
2360
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1988
2361
  workspacesApiUrl: `${protocol}//${host}`,
1989
- pathParams: { dbBranchName, workspace }
2362
+ pathParams: { dbBranchName, workspace },
2363
+ trace: defaultTrace
1990
2364
  });
1991
2365
  } catch (err) {
1992
2366
  if (isObject(err) && err.status === 404)
@@ -2026,17 +2400,20 @@ var __privateMethod = (obj, member, method) => {
2026
2400
  return method;
2027
2401
  };
2028
2402
  const buildClient = (plugins) => {
2029
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2403
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2030
2404
  return _a = class {
2031
2405
  constructor(options = {}, schemaTables) {
2032
2406
  __privateAdd(this, _parseOptions);
2033
2407
  __privateAdd(this, _getFetchProps);
2034
2408
  __privateAdd(this, _evaluateBranch);
2035
2409
  __privateAdd(this, _branch, void 0);
2410
+ __privateAdd(this, _options, void 0);
2036
2411
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2412
+ __privateSet(this, _options, safeOptions);
2037
2413
  const pluginOptions = {
2038
2414
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
2039
- cache: safeOptions.cache
2415
+ cache: safeOptions.cache,
2416
+ trace: safeOptions.trace
2040
2417
  };
2041
2418
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2042
2419
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
@@ -2055,22 +2432,26 @@ const buildClient = (plugins) => {
2055
2432
  }
2056
2433
  }
2057
2434
  }
2058
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2435
+ async getConfig() {
2436
+ const databaseURL = __privateGet(this, _options).databaseURL;
2437
+ const branch = await __privateGet(this, _options).branch();
2438
+ return { databaseURL, branch };
2439
+ }
2440
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2059
2441
  const fetch = getFetchImplementation(options?.fetch);
2060
2442
  const databaseURL = options?.databaseURL || getDatabaseURL();
2061
2443
  const apiKey = options?.apiKey || getAPIKey();
2062
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2444
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2445
+ const trace = options?.trace ?? defaultTrace;
2063
2446
  const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2064
- if (!databaseURL || !apiKey) {
2065
- throw new Error("Options databaseURL and apiKey are required");
2447
+ if (!apiKey) {
2448
+ throw new Error("Option apiKey is required");
2066
2449
  }
2067
- return { fetch, databaseURL, apiKey, branch, cache };
2068
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
2069
- fetch,
2070
- apiKey,
2071
- databaseURL,
2072
- branch
2073
- }) {
2450
+ if (!databaseURL) {
2451
+ throw new Error("Option databaseURL is required");
2452
+ }
2453
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2454
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
2074
2455
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
2075
2456
  if (!branchValue)
2076
2457
  throw new Error("Unable to resolve branch value");
@@ -2080,9 +2461,10 @@ const buildClient = (plugins) => {
2080
2461
  apiUrl: "",
2081
2462
  workspacesApiUrl: (path, params) => {
2082
2463
  const hasBranch = params.dbBranchName ?? params.branch;
2083
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
2464
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
2084
2465
  return databaseURL + newPath;
2085
- }
2466
+ },
2467
+ trace
2086
2468
  };
2087
2469
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
2088
2470
  if (__privateGet(this, _branch))
@@ -2164,25 +2546,25 @@ class Serializer {
2164
2546
  });
2165
2547
  }
2166
2548
  }
2167
- const serialize = () => {
2168
- throw new Error("Not implemented");
2549
+ const defaultSerializer = new Serializer();
2550
+ const serialize = (data) => {
2551
+ return defaultSerializer.toJSON(data);
2169
2552
  };
2170
- const deserialize = () => {
2171
- throw new Error("Not implemented");
2553
+ const deserialize = (json) => {
2554
+ return defaultSerializer.fromJSON(json);
2172
2555
  };
2173
2556
 
2174
2557
  function buildWorkerRunner(config) {
2175
2558
  return function xataWorker(name, _worker) {
2176
2559
  return async (...args) => {
2177
- const result = await fetch("http://localhost:64749", {
2560
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2561
+ const result = await fetch(url, {
2178
2562
  method: "POST",
2179
2563
  headers: { "Content-Type": "application/json" },
2180
- body: JSON.stringify({
2181
- name,
2182
- payload: args
2183
- })
2564
+ body: serialize({ args })
2184
2565
  });
2185
- return result.json();
2566
+ const text = await result.text();
2567
+ return deserialize(text);
2186
2568
  };
2187
2569
  };
2188
2570
  }
@@ -2216,13 +2598,18 @@ exports.XataPlugin = XataPlugin;
2216
2598
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
2217
2599
  exports.addGitBranchesEntry = addGitBranchesEntry;
2218
2600
  exports.addTableColumn = addTableColumn;
2601
+ exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
2219
2602
  exports.buildClient = buildClient;
2220
2603
  exports.buildWorkerRunner = buildWorkerRunner;
2221
2604
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
2222
2605
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
2606
+ exports.compareBranchSchemas = compareBranchSchemas;
2607
+ exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
2608
+ exports.compareMigrationRequest = compareMigrationRequest;
2223
2609
  exports.contains = contains;
2224
2610
  exports.createBranch = createBranch;
2225
2611
  exports.createDatabase = createDatabase;
2612
+ exports.createMigrationRequest = createMigrationRequest;
2226
2613
  exports.createTable = createTable;
2227
2614
  exports.createUserAPIKey = createUserAPIKey;
2228
2615
  exports.createWorkspace = createWorkspace;
@@ -2236,6 +2623,7 @@ exports.deleteUserAPIKey = deleteUserAPIKey;
2236
2623
  exports.deleteWorkspace = deleteWorkspace;
2237
2624
  exports.deserialize = deserialize;
2238
2625
  exports.endsWith = endsWith;
2626
+ exports.equals = equals;
2239
2627
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
2240
2628
  exports.exists = exists;
2241
2629
  exports.ge = ge;
@@ -2245,13 +2633,17 @@ exports.getBranchList = getBranchList;
2245
2633
  exports.getBranchMetadata = getBranchMetadata;
2246
2634
  exports.getBranchMigrationHistory = getBranchMigrationHistory;
2247
2635
  exports.getBranchMigrationPlan = getBranchMigrationPlan;
2636
+ exports.getBranchSchemaHistory = getBranchSchemaHistory;
2248
2637
  exports.getBranchStats = getBranchStats;
2249
2638
  exports.getColumn = getColumn;
2250
2639
  exports.getCurrentBranchDetails = getCurrentBranchDetails;
2251
2640
  exports.getCurrentBranchName = getCurrentBranchName;
2252
2641
  exports.getDatabaseList = getDatabaseList;
2642
+ exports.getDatabaseMetadata = getDatabaseMetadata;
2253
2643
  exports.getDatabaseURL = getDatabaseURL;
2254
2644
  exports.getGitBranchesMapping = getGitBranchesMapping;
2645
+ exports.getMigrationRequest = getMigrationRequest;
2646
+ exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
2255
2647
  exports.getRecord = getRecord;
2256
2648
  exports.getTableColumns = getTableColumns;
2257
2649
  exports.getTableSchema = getTableSchema;
@@ -2260,6 +2652,9 @@ exports.getUserAPIKeys = getUserAPIKeys;
2260
2652
  exports.getWorkspace = getWorkspace;
2261
2653
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
2262
2654
  exports.getWorkspacesList = getWorkspacesList;
2655
+ exports.greaterEquals = greaterEquals;
2656
+ exports.greaterThan = greaterThan;
2657
+ exports.greaterThanEquals = greaterThanEquals;
2263
2658
  exports.gt = gt;
2264
2659
  exports.gte = gte;
2265
2660
  exports.includes = includes;
@@ -2275,11 +2670,18 @@ exports.isIdentifiable = isIdentifiable;
2275
2670
  exports.isNot = isNot;
2276
2671
  exports.isXataRecord = isXataRecord;
2277
2672
  exports.le = le;
2673
+ exports.lessEquals = lessEquals;
2674
+ exports.lessThan = lessThan;
2675
+ exports.lessThanEquals = lessThanEquals;
2676
+ exports.listMigrationRequests = listMigrationRequests;
2677
+ exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
2278
2678
  exports.lt = lt;
2279
2679
  exports.lte = lte;
2680
+ exports.mergeMigrationRequest = mergeMigrationRequest;
2280
2681
  exports.notExists = notExists;
2281
2682
  exports.operationsByTag = operationsByTag;
2282
2683
  exports.pattern = pattern;
2684
+ exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
2283
2685
  exports.queryTable = queryTable;
2284
2686
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
2285
2687
  exports.removeWorkspaceMember = removeWorkspaceMember;
@@ -2290,8 +2692,12 @@ exports.searchTable = searchTable;
2290
2692
  exports.serialize = serialize;
2291
2693
  exports.setTableSchema = setTableSchema;
2292
2694
  exports.startsWith = startsWith;
2695
+ exports.summarizeTable = summarizeTable;
2293
2696
  exports.updateBranchMetadata = updateBranchMetadata;
2697
+ exports.updateBranchSchema = updateBranchSchema;
2294
2698
  exports.updateColumn = updateColumn;
2699
+ exports.updateDatabaseMetadata = updateDatabaseMetadata;
2700
+ exports.updateMigrationRequest = updateMigrationRequest;
2295
2701
  exports.updateRecordWithID = updateRecordWithID;
2296
2702
  exports.updateTable = updateTable;
2297
2703
  exports.updateUser = updateUser;