@xata.io/client 0.0.0-alpha.vf976907 → 0.0.0-alpha.vfae42b5

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
@@ -11,8 +11,11 @@ function compact(arr) {
11
11
  function isObject(value) {
12
12
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
13
13
  }
14
+ function isDefined(value) {
15
+ return value !== null && value !== void 0;
16
+ }
14
17
  function isString(value) {
15
- return value !== void 0 && value !== null && typeof value === "string";
18
+ return isDefined(value) && typeof value === "string";
16
19
  }
17
20
  function toBase64(value) {
18
21
  try {
@@ -74,7 +77,12 @@ function getFetchImplementation(userFetch) {
74
77
  return fetchImpl;
75
78
  }
76
79
 
77
- class FetcherError extends Error {
80
+ class ErrorWithCause extends Error {
81
+ constructor(message, options) {
82
+ super(message, options);
83
+ }
84
+ }
85
+ class FetcherError extends ErrorWithCause {
78
86
  constructor(status, data) {
79
87
  super(getMessage(data));
80
88
  this.status = status;
@@ -370,6 +378,11 @@ const queryTable = (variables) => fetch$1({
370
378
  method: "post",
371
379
  ...variables
372
380
  });
381
+ const searchTable = (variables) => fetch$1({
382
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
383
+ method: "post",
384
+ ...variables
385
+ });
373
386
  const searchBranch = (variables) => fetch$1({
374
387
  url: "/db/{dbBranchName}/search",
375
388
  method: "post",
@@ -433,6 +446,7 @@ const operationsByTag = {
433
446
  getRecord,
434
447
  bulkInsertTableRecords,
435
448
  queryTable,
449
+ searchTable,
436
450
  searchBranch
437
451
  }
438
452
  };
@@ -888,6 +902,13 @@ class RecordsApi {
888
902
  ...this.extraProps
889
903
  });
890
904
  }
905
+ searchTable(workspace, database, branch, tableName, query) {
906
+ return operationsByTag.records.searchTable({
907
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
908
+ body: query,
909
+ ...this.extraProps
910
+ });
911
+ }
891
912
  searchBranch(workspace, database, branch, query) {
892
913
  return operationsByTag.records.searchBranch({
893
914
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -954,6 +975,9 @@ const PAGINATION_MAX_SIZE = 200;
954
975
  const PAGINATION_DEFAULT_SIZE = 200;
955
976
  const PAGINATION_MAX_OFFSET = 800;
956
977
  const PAGINATION_DEFAULT_OFFSET = 0;
978
+ function isCursorPaginationOptions(options) {
979
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
980
+ }
957
981
 
958
982
  var __accessCheck$5 = (obj, member, msg) => {
959
983
  if (!member.has(obj))
@@ -975,7 +999,7 @@ var __privateSet$4 = (obj, member, value, setter) => {
975
999
  };
976
1000
  var _table$1, _repository, _data;
977
1001
  const _Query = class {
978
- constructor(repository, table, data, parent) {
1002
+ constructor(repository, table, data, rawParent) {
979
1003
  __privateAdd$5(this, _table$1, void 0);
980
1004
  __privateAdd$5(this, _repository, void 0);
981
1005
  __privateAdd$5(this, _data, { filter: {} });
@@ -987,6 +1011,7 @@ const _Query = class {
987
1011
  } else {
988
1012
  __privateSet$4(this, _repository, this);
989
1013
  }
1014
+ const parent = cleanParent(data, rawParent);
990
1015
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
991
1016
  __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
992
1017
  __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
@@ -1058,13 +1083,13 @@ const _Query = class {
1058
1083
  }
1059
1084
  async *getIterator(options = {}) {
1060
1085
  const { batchSize = 1 } = options;
1061
- let offset = 0;
1062
- let end = false;
1063
- while (!end) {
1064
- const { records, meta } = await this.getPaginated({ ...options, pagination: { size: batchSize, offset } });
1065
- yield records;
1066
- offset += batchSize;
1067
- end = !meta.page.more;
1086
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1087
+ let more = page.hasNextPage();
1088
+ yield page.records;
1089
+ while (more) {
1090
+ page = await page.nextPage();
1091
+ more = page.hasNextPage();
1092
+ yield page.records;
1068
1093
  }
1069
1094
  }
1070
1095
  async getMany(options = {}) {
@@ -1081,7 +1106,7 @@ const _Query = class {
1081
1106
  }
1082
1107
  async getFirst(options = {}) {
1083
1108
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1084
- return records[0] || null;
1109
+ return records[0] ?? null;
1085
1110
  }
1086
1111
  cache(ttl) {
1087
1112
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
@@ -1106,12 +1131,20 @@ let Query = _Query;
1106
1131
  _table$1 = new WeakMap();
1107
1132
  _repository = new WeakMap();
1108
1133
  _data = new WeakMap();
1134
+ function cleanParent(data, parent) {
1135
+ if (isCursorPaginationOptions(data.pagination)) {
1136
+ return { ...parent, sorting: void 0, filter: void 0 };
1137
+ }
1138
+ return parent;
1139
+ }
1109
1140
 
1110
1141
  function isIdentifiable(x) {
1111
1142
  return isObject(x) && isString(x?.id);
1112
1143
  }
1113
1144
  function isXataRecord(x) {
1114
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1145
+ const record = x;
1146
+ const metadata = record?.getMetadata();
1147
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1115
1148
  }
1116
1149
 
1117
1150
  function isSortFilterString(value) {
@@ -1188,6 +1221,8 @@ class RestRepository extends Query {
1188
1221
  }
1189
1222
  async create(a, b) {
1190
1223
  if (Array.isArray(a)) {
1224
+ if (a.length === 0)
1225
+ return [];
1191
1226
  const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1192
1227
  await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1193
1228
  return records;
@@ -1213,27 +1248,36 @@ class RestRepository extends Query {
1213
1248
  }
1214
1249
  throw new Error("Invalid arguments for create method");
1215
1250
  }
1216
- async read(recordId) {
1217
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1218
- if (cacheRecord)
1219
- return cacheRecord;
1220
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1221
- try {
1222
- const response = await getRecord({
1223
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1224
- ...fetchProps
1225
- });
1226
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1227
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1228
- } catch (e) {
1229
- if (isObject(e) && e.status === 404) {
1230
- return null;
1251
+ async read(a) {
1252
+ if (Array.isArray(a)) {
1253
+ if (a.length === 0)
1254
+ return [];
1255
+ return this.getAll({ filter: { id: { $any: a } } });
1256
+ }
1257
+ if (isString(a)) {
1258
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, a);
1259
+ if (cacheRecord)
1260
+ return cacheRecord;
1261
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1262
+ try {
1263
+ const response = await getRecord({
1264
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: a },
1265
+ ...fetchProps
1266
+ });
1267
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1268
+ return initObject(this.db, schema, __privateGet$4(this, _table), response);
1269
+ } catch (e) {
1270
+ if (isObject(e) && e.status === 404) {
1271
+ return null;
1272
+ }
1273
+ throw e;
1231
1274
  }
1232
- throw e;
1233
1275
  }
1234
1276
  }
1235
1277
  async update(a, b) {
1236
1278
  if (Array.isArray(a)) {
1279
+ if (a.length === 0)
1280
+ return [];
1237
1281
  if (a.length > 100) {
1238
1282
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1239
1283
  }
@@ -1255,6 +1299,8 @@ class RestRepository extends Query {
1255
1299
  }
1256
1300
  async createOrUpdate(a, b) {
1257
1301
  if (Array.isArray(a)) {
1302
+ if (a.length === 0)
1303
+ return [];
1258
1304
  if (a.length > 100) {
1259
1305
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1260
1306
  }
@@ -1276,6 +1322,8 @@ class RestRepository extends Query {
1276
1322
  }
1277
1323
  async delete(a) {
1278
1324
  if (Array.isArray(a)) {
1325
+ if (a.length === 0)
1326
+ return;
1279
1327
  if (a.length > 100) {
1280
1328
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1281
1329
  }
@@ -1296,9 +1344,14 @@ class RestRepository extends Query {
1296
1344
  }
1297
1345
  async search(query, options = {}) {
1298
1346
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1299
- const { records } = await searchBranch({
1300
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1301
- body: { tables: [__privateGet$4(this, _table)], query, fuzziness: options.fuzziness },
1347
+ const { records } = await searchTable({
1348
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1349
+ body: {
1350
+ query,
1351
+ fuzziness: options.fuzziness,
1352
+ highlight: options.highlight,
1353
+ filter: options.filter
1354
+ },
1302
1355
  ...fetchProps
1303
1356
  });
1304
1357
  const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
@@ -1311,7 +1364,7 @@ class RestRepository extends Query {
1311
1364
  const data = query.getQueryOptions();
1312
1365
  const body = {
1313
1366
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1314
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1367
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1315
1368
  page: data.pagination,
1316
1369
  columns: data.columns
1317
1370
  };
@@ -1481,7 +1534,8 @@ const transformObjectLinks = (object) => {
1481
1534
  };
1482
1535
  const initObject = (db, schema, table, object) => {
1483
1536
  const result = {};
1484
- Object.assign(result, object);
1537
+ const { xata, ...rest } = object ?? {};
1538
+ Object.assign(result, rest);
1485
1539
  const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1486
1540
  if (!columns)
1487
1541
  console.error(`Table ${table} not found in schema`);
@@ -1489,10 +1543,10 @@ const initObject = (db, schema, table, object) => {
1489
1543
  const value = result[column.name];
1490
1544
  switch (column.type) {
1491
1545
  case "datetime": {
1492
- const date = new Date(value);
1493
- if (isNaN(date.getTime())) {
1546
+ const date = value !== void 0 ? new Date(value) : void 0;
1547
+ if (date && isNaN(date.getTime())) {
1494
1548
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1495
- } else {
1549
+ } else if (date) {
1496
1550
  result[column.name] = date;
1497
1551
  }
1498
1552
  break;
@@ -1501,7 +1555,7 @@ const initObject = (db, schema, table, object) => {
1501
1555
  const linkTable = column.link?.table;
1502
1556
  if (!linkTable) {
1503
1557
  console.error(`Failed to parse link for field ${column.name}`);
1504
- } else if (value && isObject(value)) {
1558
+ } else if (isObject(value)) {
1505
1559
  result[column.name] = initObject(db, schema, linkTable, value);
1506
1560
  }
1507
1561
  break;
@@ -1517,7 +1571,10 @@ const initObject = (db, schema, table, object) => {
1517
1571
  result.delete = function() {
1518
1572
  return db[table].delete(result["id"]);
1519
1573
  };
1520
- for (const prop of ["read", "update", "delete"]) {
1574
+ result.getMetadata = function() {
1575
+ return xata;
1576
+ };
1577
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1521
1578
  Object.defineProperty(result, prop, { enumerable: false });
1522
1579
  }
1523
1580
  Object.freeze(result);
@@ -1627,7 +1684,7 @@ class SchemaPlugin extends XataPlugin {
1627
1684
  get: (_target, table) => {
1628
1685
  if (!isString(table))
1629
1686
  throw new Error("Invalid table name");
1630
- if (!__privateGet$2(this, _tables)[table]) {
1687
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1631
1688
  __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1632
1689
  }
1633
1690
  return __privateGet$2(this, _tables)[table];
@@ -1699,10 +1756,10 @@ _schema = new WeakMap();
1699
1756
  _search = new WeakSet();
1700
1757
  search_fn = async function(query, options, getFetchProps) {
1701
1758
  const fetchProps = await getFetchProps();
1702
- const { tables, fuzziness } = options ?? {};
1759
+ const { tables, fuzziness, highlight } = options ?? {};
1703
1760
  const { records } = await searchBranch({
1704
1761
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1705
- body: { tables, query, fuzziness },
1762
+ body: { tables, query, fuzziness, highlight },
1706
1763
  ...fetchProps
1707
1764
  });
1708
1765
  return records;
@@ -1730,30 +1787,39 @@ const envBranchNames = [
1730
1787
  "CF_PAGES_BRANCH",
1731
1788
  "BRANCH"
1732
1789
  ];
1733
- const defaultBranch = "main";
1734
1790
  async function getCurrentBranchName(options) {
1735
- const env = await getBranchByEnvVariable();
1736
- if (env)
1737
- return env;
1738
- const branch = await getGitBranch();
1739
- if (!branch)
1740
- return defaultBranch;
1741
- const details = await getDatabaseBranch(branch, options);
1742
- if (details)
1743
- return branch;
1744
- return defaultBranch;
1791
+ const env = getBranchByEnvVariable();
1792
+ if (env) {
1793
+ const details = await getDatabaseBranch(env, options);
1794
+ if (details)
1795
+ return env;
1796
+ console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1797
+ }
1798
+ const gitBranch = await getGitBranch();
1799
+ return resolveXataBranch(gitBranch, options);
1745
1800
  }
1746
1801
  async function getCurrentBranchDetails(options) {
1747
- const env = await getBranchByEnvVariable();
1748
- if (env)
1749
- return getDatabaseBranch(env, options);
1750
- const branch = await getGitBranch();
1751
- if (!branch)
1752
- return getDatabaseBranch(defaultBranch, options);
1753
- const details = await getDatabaseBranch(branch, options);
1754
- if (details)
1755
- return details;
1756
- return getDatabaseBranch(defaultBranch, options);
1802
+ const branch = await getCurrentBranchName(options);
1803
+ return getDatabaseBranch(branch, options);
1804
+ }
1805
+ async function resolveXataBranch(gitBranch, options) {
1806
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1807
+ const apiKey = options?.apiKey || getAPIKey();
1808
+ if (!databaseURL)
1809
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1810
+ if (!apiKey)
1811
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1812
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1813
+ const [workspace] = host.split(".");
1814
+ const { branch } = await resolveBranch({
1815
+ apiKey,
1816
+ apiUrl: databaseURL,
1817
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1818
+ workspacesApiUrl: `${protocol}//${host}`,
1819
+ pathParams: { dbName, workspace },
1820
+ queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
1821
+ });
1822
+ return branch;
1757
1823
  }
1758
1824
  async function getDatabaseBranch(branch, options) {
1759
1825
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1842,7 +1908,7 @@ const buildClient = (plugins) => {
1842
1908
  this.db = db;
1843
1909
  this.search = search;
1844
1910
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1845
- if (!namespace)
1911
+ if (namespace === void 0)
1846
1912
  continue;
1847
1913
  const result = namespace.build(pluginOptions);
1848
1914
  if (result instanceof Promise) {
@@ -1859,7 +1925,7 @@ const buildClient = (plugins) => {
1859
1925
  const databaseURL = options?.databaseURL || getDatabaseURL();
1860
1926
  const apiKey = options?.apiKey || getAPIKey();
1861
1927
  const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1862
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1928
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1863
1929
  if (!databaseURL || !apiKey) {
1864
1930
  throw new Error("Options databaseURL and apiKey are required");
1865
1931
  }
@@ -1886,7 +1952,7 @@ const buildClient = (plugins) => {
1886
1952
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1887
1953
  if (__privateGet(this, _branch))
1888
1954
  return __privateGet(this, _branch);
1889
- if (!param)
1955
+ if (param === void 0)
1890
1956
  return void 0;
1891
1957
  const strategies = Array.isArray(param) ? [...param] : [param];
1892
1958
  const evaluateBranch = async (strategy) => {
@@ -1983,6 +2049,7 @@ exports.insertRecord = insertRecord;
1983
2049
  exports.insertRecordWithID = insertRecordWithID;
1984
2050
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
1985
2051
  exports.is = is;
2052
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
1986
2053
  exports.isIdentifiable = isIdentifiable;
1987
2054
  exports.isNot = isNot;
1988
2055
  exports.isXataRecord = isXataRecord;
@@ -1998,6 +2065,7 @@ exports.removeWorkspaceMember = removeWorkspaceMember;
1998
2065
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
1999
2066
  exports.resolveBranch = resolveBranch;
2000
2067
  exports.searchBranch = searchBranch;
2068
+ exports.searchTable = searchTable;
2001
2069
  exports.setTableSchema = setTableSchema;
2002
2070
  exports.startsWith = startsWith;
2003
2071
  exports.updateBranchMetadata = updateBranchMetadata;