@xata.io/client 0.0.0-alpha.vf4e6746 → 0.0.0-alpha.vf59e81b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
- const defaultTrace = async (_name, fn, _options) => {
1
+ const defaultTrace = async (name, fn, _options) => {
2
2
  return await fn({
3
+ name,
3
4
  setAttributes: () => {
4
5
  return;
5
6
  }
@@ -163,28 +164,14 @@ function getGlobalFallbackBranch() {
163
164
  return void 0;
164
165
  }
165
166
  }
166
- async function getGitBranch() {
167
- const cmd = ["git", "branch", "--show-current"];
168
- const fullCmd = cmd.join(" ");
169
- const nodeModule = ["child", "process"].join("_");
170
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
171
- try {
172
- if (typeof require === "function") {
173
- return require(nodeModule).execSync(fullCmd, execOptions).trim();
174
- }
175
- const { execSync } = await import(nodeModule);
176
- return execSync(fullCmd, execOptions).toString().trim();
177
- } catch (err) {
178
- }
167
+ function getDatabaseURL() {
179
168
  try {
180
- if (isObject(Deno)) {
181
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
182
- return new TextDecoder().decode(await process2.output()).trim();
183
- }
169
+ const { databaseURL } = getEnvironment();
170
+ return databaseURL;
184
171
  } catch (err) {
172
+ return void 0;
185
173
  }
186
174
  }
187
-
188
175
  function getAPIKey() {
189
176
  try {
190
177
  const { apiKey } = getEnvironment();
@@ -294,7 +281,14 @@ enqueue_fn = function(task) {
294
281
  return promise;
295
282
  };
296
283
 
297
- const VERSION = "0.0.0-alpha.vf4e6746";
284
+ function generateUUID() {
285
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
286
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
287
+ return v.toString(16);
288
+ });
289
+ }
290
+
291
+ const VERSION = "0.21.6";
298
292
 
299
293
  class ErrorWithCause extends Error {
300
294
  constructor(message, options) {
@@ -305,7 +299,7 @@ class FetcherError extends ErrorWithCause {
305
299
  constructor(status, data, requestId) {
306
300
  super(getMessage(data));
307
301
  this.status = status;
308
- this.errors = isBulkError(data) ? data.errors : void 0;
302
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
309
303
  this.requestId = requestId;
310
304
  if (data instanceof Error) {
311
305
  this.stack = data.stack;
@@ -370,11 +364,12 @@ function hostHeader(url) {
370
364
  const { groups } = pattern.exec(url) ?? {};
371
365
  return groups?.host ? { Host: groups.host } : {};
372
366
  }
367
+ const defaultClientID = generateUUID();
373
368
  async function fetch$1({
374
369
  url: path,
375
370
  method,
376
371
  body,
377
- headers,
372
+ headers: customHeaders,
378
373
  pathParams,
379
374
  queryParams,
380
375
  fetchImpl,
@@ -386,6 +381,7 @@ async function fetch$1({
386
381
  signal,
387
382
  clientID,
388
383
  sessionID,
384
+ clientName,
389
385
  fetchOptions = {}
390
386
  }) {
391
387
  pool.setFetch(fetchImpl);
@@ -399,19 +395,26 @@ async function fetch$1({
399
395
  [TraceAttributes.HTTP_URL]: url,
400
396
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
401
397
  });
398
+ const xataAgent = compact([
399
+ ["client", "TS_SDK"],
400
+ ["version", VERSION],
401
+ isDefined(clientName) ? ["service", clientName] : void 0
402
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
403
+ const headers = {
404
+ "Accept-Encoding": "identity",
405
+ "Content-Type": "application/json",
406
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
407
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
408
+ "X-Xata-Agent": xataAgent,
409
+ ...customHeaders,
410
+ ...hostHeader(fullUrl),
411
+ Authorization: `Bearer ${apiKey}`
412
+ };
402
413
  const response = await pool.request(url, {
403
414
  ...fetchOptions,
404
415
  method: method.toUpperCase(),
405
416
  body: body ? JSON.stringify(body) : void 0,
406
- headers: {
407
- "Content-Type": "application/json",
408
- "User-Agent": `Xata client-ts/${VERSION}`,
409
- "X-Xata-Client-ID": clientID ?? "",
410
- "X-Xata-Session-ID": sessionID ?? "",
411
- ...headers,
412
- ...hostHeader(fullUrl),
413
- Authorization: `Bearer ${apiKey}`
414
- },
417
+ headers,
415
418
  signal
416
419
  });
417
420
  const { host, protocol } = parseUrl(response.url);
@@ -453,17 +456,12 @@ function parseUrl(url) {
453
456
 
454
457
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
455
458
 
456
- const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
457
459
  const getBranchList = (variables, signal) => dataPlaneFetch({
458
460
  url: "/dbs/{dbName}",
459
461
  method: "get",
460
462
  ...variables,
461
463
  signal
462
464
  });
463
- const dEPRECATEDcreateDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
464
- const dEPRECATEDdeleteDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "delete", ...variables, signal });
465
- const dEPRECATEDgetDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "get", ...variables, signal });
466
- const dEPRECATEDupdateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
467
465
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
468
466
  url: "/db/{dbBranchName}",
469
467
  method: "get",
@@ -502,7 +500,6 @@ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName
502
500
  const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
503
501
  const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
504
502
  const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
505
- const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
506
503
  const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
507
504
  const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
508
505
  const getMigrationRequest = (variables, signal) => dataPlaneFetch({
@@ -569,6 +566,7 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
569
566
  ...variables,
570
567
  signal
571
568
  });
569
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
572
570
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
573
571
  const getRecord = (variables, signal) => dataPlaneFetch({
574
572
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
@@ -602,13 +600,6 @@ const searchTable = (variables, signal) => dataPlaneFetch({
602
600
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
603
601
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
604
602
  const operationsByTag$2 = {
605
- database: {
606
- dEPRECATEDgetDatabaseList,
607
- dEPRECATEDcreateDatabase,
608
- dEPRECATEDdeleteDatabase,
609
- dEPRECATEDgetDatabaseMetadata,
610
- dEPRECATEDupdateDatabaseMetadata
611
- },
612
603
  branch: {
613
604
  getBranchList,
614
605
  getBranchDetails,
@@ -633,16 +624,6 @@ const operationsByTag$2 = {
633
624
  previewBranchSchemaEdit,
634
625
  applyBranchSchemaEdit
635
626
  },
636
- records: {
637
- branchTransaction,
638
- insertRecord,
639
- getRecord,
640
- insertRecordWithID,
641
- updateRecordWithID,
642
- upsertRecordWithID,
643
- deleteRecord,
644
- bulkInsertTableRecords
645
- },
646
627
  migrationRequests: {
647
628
  queryMigrationRequests,
648
629
  createMigrationRequest,
@@ -665,6 +646,16 @@ const operationsByTag$2 = {
665
646
  updateColumn,
666
647
  deleteColumn
667
648
  },
649
+ records: {
650
+ branchTransaction,
651
+ insertRecord,
652
+ getRecord,
653
+ insertRecordWithID,
654
+ updateRecordWithID,
655
+ upsertRecordWithID,
656
+ deleteRecord,
657
+ bulkInsertTableRecords
658
+ },
668
659
  searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
669
660
  };
670
661
 
@@ -838,12 +829,12 @@ function parseProviderString(provider = "production") {
838
829
  function parseWorkspacesUrlParts(url) {
839
830
  if (!isString(url))
840
831
  return null;
841
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
842
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
832
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
833
+ const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
843
834
  const match = url.match(regex) || url.match(regexStaging);
844
835
  if (!match)
845
836
  return null;
846
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
837
+ return { workspace: match[1], region: match[2] };
847
838
  }
848
839
 
849
840
  var __accessCheck$7 = (obj, member, msg) => {
@@ -872,6 +863,7 @@ class XataApiClient {
872
863
  const provider = options.host ?? "production";
873
864
  const apiKey = options.apiKey ?? getAPIKey();
874
865
  const trace = options.trace ?? defaultTrace;
866
+ const clientID = generateUUID();
875
867
  if (!apiKey) {
876
868
  throw new Error("Could not resolve a valid apiKey");
877
869
  }
@@ -880,7 +872,9 @@ class XataApiClient {
880
872
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
881
873
  fetchImpl: getFetchImplementation(options.fetch),
882
874
  apiKey,
883
- trace
875
+ trace,
876
+ clientName: options.clientName,
877
+ clientID
884
878
  });
885
879
  }
886
880
  get user() {
@@ -1876,8 +1870,8 @@ class DatabaseApi {
1876
1870
  }
1877
1871
 
1878
1872
  class XataApiPlugin {
1879
- async build(options) {
1880
- const { fetchImpl, apiKey } = await options.getFetchProps();
1873
+ build(options) {
1874
+ const { fetchImpl, apiKey } = options.getFetchProps();
1881
1875
  return new XataApiClient({ fetch: fetchImpl, apiKey });
1882
1876
  }
1883
1877
  }
@@ -1885,13 +1879,6 @@ class XataApiPlugin {
1885
1879
  class XataPlugin {
1886
1880
  }
1887
1881
 
1888
- function generateUUID() {
1889
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1890
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1891
- return v.toString(16);
1892
- });
1893
- }
1894
-
1895
1882
  function cleanFilter(filter) {
1896
1883
  if (!filter)
1897
1884
  return void 0;
@@ -1968,6 +1955,12 @@ const _RecordArray = class extends Array {
1968
1955
  toArray() {
1969
1956
  return new Array(...this);
1970
1957
  }
1958
+ toSerializable() {
1959
+ return JSON.parse(this.toString());
1960
+ }
1961
+ toString() {
1962
+ return JSON.stringify(this.toArray());
1963
+ }
1971
1964
  map(callbackfn, thisArg) {
1972
1965
  return this.toArray().map(callbackfn, thisArg);
1973
1966
  }
@@ -2039,6 +2032,7 @@ const _Query = class {
2039
2032
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
2040
2033
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
2041
2034
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
2035
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
2042
2036
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
2043
2037
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
2044
2038
  __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
@@ -2412,13 +2406,19 @@ class RestRepository extends Query {
2412
2406
  const result = await this.read(a, columns);
2413
2407
  return result;
2414
2408
  }
2415
- if (isString(a) && isObject(b)) {
2416
- const columns = isStringArray(c) ? c : void 0;
2417
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2418
- }
2419
- if (isObject(a) && isString(a.id)) {
2420
- const columns = isStringArray(b) ? b : void 0;
2421
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2409
+ try {
2410
+ if (isString(a) && isObject(b)) {
2411
+ const columns = isStringArray(c) ? c : void 0;
2412
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2413
+ }
2414
+ if (isObject(a) && isString(a.id)) {
2415
+ const columns = isStringArray(b) ? b : void 0;
2416
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2417
+ }
2418
+ } catch (error) {
2419
+ if (error.status === 422)
2420
+ return null;
2421
+ throw error;
2422
2422
  }
2423
2423
  throw new Error("Invalid arguments for update method");
2424
2424
  });
@@ -2549,7 +2549,9 @@ class RestRepository extends Query {
2549
2549
  prefix: options.prefix,
2550
2550
  highlight: options.highlight,
2551
2551
  filter: options.filter,
2552
- boosters: options.boosters
2552
+ boosters: options.boosters,
2553
+ page: options.page,
2554
+ target: options.target
2553
2555
  },
2554
2556
  ...fetchProps
2555
2557
  });
@@ -2591,7 +2593,8 @@ class RestRepository extends Query {
2591
2593
  filter: cleanFilter(data.filter),
2592
2594
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2593
2595
  page: data.pagination,
2594
- columns: data.columns ?? ["*"]
2596
+ columns: data.columns ?? ["*"],
2597
+ consistency: data.consistency
2595
2598
  },
2596
2599
  fetchOptions: data.fetchOptions,
2597
2600
  ...fetchProps
@@ -2619,6 +2622,7 @@ class RestRepository extends Query {
2619
2622
  filter: cleanFilter(data.filter),
2620
2623
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2621
2624
  columns: data.columns,
2625
+ consistency: data.consistency,
2622
2626
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2623
2627
  summaries,
2624
2628
  summariesFilter
@@ -2821,15 +2825,16 @@ deleteRecords_fn = async function(recordIds) {
2821
2825
  };
2822
2826
  _setCacheQuery = new WeakSet();
2823
2827
  setCacheQuery_fn = async function(query, meta, records) {
2824
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
2828
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
2825
2829
  };
2826
2830
  _getCacheQuery = new WeakSet();
2827
2831
  getCacheQuery_fn = async function(query) {
2828
2832
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2829
- const result = await __privateGet$4(this, _cache).get(key);
2833
+ const result = await __privateGet$4(this, _cache)?.get(key);
2830
2834
  if (!result)
2831
2835
  return null;
2832
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
2836
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
2837
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2833
2838
  if (ttl < 0)
2834
2839
  return null;
2835
2840
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2855,23 +2860,23 @@ const transformObjectLinks = (object) => {
2855
2860
  }, {});
2856
2861
  };
2857
2862
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2858
- const result = {};
2863
+ const data = {};
2859
2864
  const { xata, ...rest } = object ?? {};
2860
- Object.assign(result, rest);
2865
+ Object.assign(data, rest);
2861
2866
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2862
2867
  if (!columns)
2863
2868
  console.error(`Table ${table} not found in schema`);
2864
2869
  for (const column of columns ?? []) {
2865
2870
  if (!isValidColumn(selectedColumns, column))
2866
2871
  continue;
2867
- const value = result[column.name];
2872
+ const value = data[column.name];
2868
2873
  switch (column.type) {
2869
2874
  case "datetime": {
2870
2875
  const date = value !== void 0 ? new Date(value) : null;
2871
2876
  if (date !== null && isNaN(date.getTime())) {
2872
2877
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2873
2878
  } else {
2874
- result[column.name] = date;
2879
+ data[column.name] = date;
2875
2880
  }
2876
2881
  break;
2877
2882
  }
@@ -2890,44 +2895,51 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2890
2895
  }
2891
2896
  return acc;
2892
2897
  }, []);
2893
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2898
+ data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2894
2899
  } else {
2895
- result[column.name] = null;
2900
+ data[column.name] = null;
2896
2901
  }
2897
2902
  break;
2898
2903
  }
2899
2904
  default:
2900
- result[column.name] = value ?? null;
2905
+ data[column.name] = value ?? null;
2901
2906
  if (column.notNull === true && value === null) {
2902
2907
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2903
2908
  }
2904
2909
  break;
2905
2910
  }
2906
2911
  }
2907
- result.read = function(columns2) {
2908
- return db[table].read(result["id"], columns2);
2912
+ const record = { ...data };
2913
+ record.read = function(columns2) {
2914
+ return db[table].read(record["id"], columns2);
2909
2915
  };
2910
- result.update = function(data, b, c) {
2916
+ record.update = function(data2, b, c) {
2911
2917
  const columns2 = isStringArray(b) ? b : ["*"];
2912
2918
  const ifVersion = parseIfVersion(b, c);
2913
- return db[table].update(result["id"], data, columns2, { ifVersion });
2919
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2914
2920
  };
2915
- result.replace = function(data, b, c) {
2921
+ record.replace = function(data2, b, c) {
2916
2922
  const columns2 = isStringArray(b) ? b : ["*"];
2917
2923
  const ifVersion = parseIfVersion(b, c);
2918
- return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
2924
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2919
2925
  };
2920
- result.delete = function() {
2921
- return db[table].delete(result["id"]);
2926
+ record.delete = function() {
2927
+ return db[table].delete(record["id"]);
2922
2928
  };
2923
- result.getMetadata = function() {
2929
+ record.getMetadata = function() {
2924
2930
  return xata;
2925
2931
  };
2926
- for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
2927
- Object.defineProperty(result, prop, { enumerable: false });
2932
+ record.toSerializable = function() {
2933
+ return JSON.parse(JSON.stringify(transformObjectLinks(data)));
2934
+ };
2935
+ record.toString = function() {
2936
+ return JSON.stringify(transformObjectLinks(data));
2937
+ };
2938
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
2939
+ Object.defineProperty(record, prop, { enumerable: false });
2928
2940
  }
2929
- Object.freeze(result);
2930
- return result;
2941
+ Object.freeze(record);
2942
+ return record;
2931
2943
  };
2932
2944
  function extractId(value) {
2933
2945
  if (isString(value))
@@ -3138,10 +3150,10 @@ _schemaTables = new WeakMap();
3138
3150
  _search = new WeakSet();
3139
3151
  search_fn = async function(query, options, getFetchProps) {
3140
3152
  const fetchProps = await getFetchProps();
3141
- const { tables, fuzziness, highlight, prefix } = options ?? {};
3153
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3142
3154
  const { records } = await searchBranch({
3143
3155
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3144
- body: { tables, query, fuzziness, prefix, highlight },
3156
+ body: { tables, query, fuzziness, prefix, highlight, page },
3145
3157
  ...fetchProps
3146
3158
  });
3147
3159
  return records;
@@ -3179,89 +3191,6 @@ const isBranchStrategyBuilder = (strategy) => {
3179
3191
  return typeof strategy === "function";
3180
3192
  };
3181
3193
 
3182
- async function getCurrentBranchName(options) {
3183
- const { branch, envBranch } = getEnvironment();
3184
- if (branch) {
3185
- const details = await getDatabaseBranch(branch, options);
3186
- if (details)
3187
- return branch;
3188
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
3189
- }
3190
- const gitBranch = envBranch || await getGitBranch();
3191
- return resolveXataBranch(gitBranch, options);
3192
- }
3193
- async function getCurrentBranchDetails(options) {
3194
- const branch = await getCurrentBranchName(options);
3195
- return getDatabaseBranch(branch, options);
3196
- }
3197
- async function resolveXataBranch(gitBranch, options) {
3198
- const databaseURL = options?.databaseURL || getDatabaseURL();
3199
- const apiKey = options?.apiKey || getAPIKey();
3200
- if (!databaseURL)
3201
- throw new Error(
3202
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3203
- );
3204
- if (!apiKey)
3205
- throw new Error(
3206
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3207
- );
3208
- const [protocol, , host, , dbName] = databaseURL.split("/");
3209
- const urlParts = parseWorkspacesUrlParts(host);
3210
- if (!urlParts)
3211
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3212
- const { workspace, region } = urlParts;
3213
- const { fallbackBranch } = getEnvironment();
3214
- const { branch } = await resolveBranch({
3215
- apiKey,
3216
- apiUrl: databaseURL,
3217
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3218
- workspacesApiUrl: `${protocol}//${host}`,
3219
- pathParams: { dbName, workspace, region },
3220
- queryParams: { gitBranch, fallbackBranch },
3221
- trace: defaultTrace
3222
- });
3223
- return branch;
3224
- }
3225
- async function getDatabaseBranch(branch, options) {
3226
- const databaseURL = options?.databaseURL || getDatabaseURL();
3227
- const apiKey = options?.apiKey || getAPIKey();
3228
- if (!databaseURL)
3229
- throw new Error(
3230
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3231
- );
3232
- if (!apiKey)
3233
- throw new Error(
3234
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3235
- );
3236
- const [protocol, , host, , database] = databaseURL.split("/");
3237
- const urlParts = parseWorkspacesUrlParts(host);
3238
- if (!urlParts)
3239
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3240
- const { workspace, region } = urlParts;
3241
- try {
3242
- return await getBranchDetails({
3243
- apiKey,
3244
- apiUrl: databaseURL,
3245
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3246
- workspacesApiUrl: `${protocol}//${host}`,
3247
- pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3248
- trace: defaultTrace
3249
- });
3250
- } catch (err) {
3251
- if (isObject(err) && err.status === 404)
3252
- return null;
3253
- throw err;
3254
- }
3255
- }
3256
- function getDatabaseURL() {
3257
- try {
3258
- const { databaseURL } = getEnvironment();
3259
- return databaseURL;
3260
- } catch (err) {
3261
- return void 0;
3262
- }
3263
- }
3264
-
3265
3194
  var __accessCheck = (obj, member, msg) => {
3266
3195
  if (!member.has(obj))
3267
3196
  throw TypeError("Cannot " + msg);
@@ -3309,24 +3238,17 @@ const buildClient = (plugins) => {
3309
3238
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3310
3239
  if (namespace === void 0)
3311
3240
  continue;
3312
- const result = namespace.build(pluginOptions);
3313
- if (result instanceof Promise) {
3314
- void result.then((namespace2) => {
3315
- this[key] = namespace2;
3316
- });
3317
- } else {
3318
- this[key] = result;
3319
- }
3241
+ this[key] = namespace.build(pluginOptions);
3320
3242
  }
3321
3243
  }
3322
3244
  async getConfig() {
3323
3245
  const databaseURL = __privateGet(this, _options).databaseURL;
3324
- const branch = await __privateGet(this, _options).branch();
3246
+ const branch = __privateGet(this, _options).branch;
3325
3247
  return { databaseURL, branch };
3326
3248
  }
3327
3249
  }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3328
3250
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3329
- const isBrowser = typeof window !== "undefined";
3251
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3330
3252
  if (isBrowser && !enableBrowser) {
3331
3253
  throw new Error(
3332
3254
  "You are trying to use Xata from the browser, which is potentially a non-secure environment. If you understand the security concerns, such as leaking your credentials, pass `enableBrowser: true` to the client options to remove this error."
@@ -3337,16 +3259,29 @@ const buildClient = (plugins) => {
3337
3259
  const apiKey = options?.apiKey || getAPIKey();
3338
3260
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3339
3261
  const trace = options?.trace ?? defaultTrace;
3340
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
3262
+ const clientName = options?.clientName;
3263
+ const host = options?.host ?? "production";
3264
+ const branch = options?.branch !== void 0 ? __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : "main";
3341
3265
  if (!apiKey) {
3342
3266
  throw new Error("Option apiKey is required");
3343
3267
  }
3344
3268
  if (!databaseURL) {
3345
3269
  throw new Error("Option databaseURL is required");
3346
3270
  }
3347
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser };
3348
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3349
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3271
+ return {
3272
+ fetch,
3273
+ databaseURL,
3274
+ apiKey,
3275
+ branch,
3276
+ cache,
3277
+ trace,
3278
+ host,
3279
+ clientID: generateUUID(),
3280
+ enableBrowser,
3281
+ clientName
3282
+ };
3283
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({ fetch, apiKey, databaseURL, branch, trace, clientID, clientName }) {
3284
+ const branchValue = __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3350
3285
  if (!branchValue)
3351
3286
  throw new Error("Unable to resolve branch value");
3352
3287
  return {
@@ -3359,19 +3294,20 @@ const buildClient = (plugins) => {
3359
3294
  return databaseURL + newPath;
3360
3295
  },
3361
3296
  trace,
3362
- clientID
3297
+ clientID,
3298
+ clientName
3363
3299
  };
3364
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3300
+ }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = function(param) {
3365
3301
  if (__privateGet(this, _branch))
3366
3302
  return __privateGet(this, _branch);
3367
3303
  if (param === void 0)
3368
3304
  return void 0;
3369
3305
  const strategies = Array.isArray(param) ? [...param] : [param];
3370
- const evaluateBranch = async (strategy) => {
3371
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
3306
+ const evaluateBranch = (strategy) => {
3307
+ return isBranchStrategyBuilder(strategy) ? strategy() : strategy;
3372
3308
  };
3373
- for await (const strategy of strategies) {
3374
- const branch = await evaluateBranch(strategy);
3309
+ for (const strategy of strategies) {
3310
+ const branch = evaluateBranch(strategy);
3375
3311
  if (branch) {
3376
3312
  __privateSet(this, _branch, branch);
3377
3313
  return branch;
@@ -3450,7 +3386,7 @@ const deserialize = (json) => {
3450
3386
  };
3451
3387
 
3452
3388
  function buildWorkerRunner(config) {
3453
- return function xataWorker(name, _worker) {
3389
+ return function xataWorker(name, worker) {
3454
3390
  return async (...args) => {
3455
3391
  const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3456
3392
  const result = await fetch(url, {
@@ -3471,5 +3407,5 @@ class XataError extends Error {
3471
3407
  }
3472
3408
  }
3473
3409
 
3474
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, branchTransaction, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, dEPRECATEDcreateDatabase, dEPRECATEDdeleteDatabase, dEPRECATEDgetDatabaseList, dEPRECATEDgetDatabaseMetadata, dEPRECATEDupdateDatabaseMetadata, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
3410
+ export { BaseClient, FetcherError, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, branchTransaction, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
3475
3411
  //# sourceMappingURL=index.mjs.map