@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.cjs CHANGED
@@ -1,7 +1,8 @@
1
1
  'use strict';
2
2
 
3
- const defaultTrace = async (_name, fn, _options) => {
3
+ const defaultTrace = async (name, fn, _options) => {
4
4
  return await fn({
5
+ name,
5
6
  setAttributes: () => {
6
7
  return;
7
8
  }
@@ -165,28 +166,14 @@ function getGlobalFallbackBranch() {
165
166
  return void 0;
166
167
  }
167
168
  }
168
- async function getGitBranch() {
169
- const cmd = ["git", "branch", "--show-current"];
170
- const fullCmd = cmd.join(" ");
171
- const nodeModule = ["child", "process"].join("_");
172
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
173
- try {
174
- if (typeof require === "function") {
175
- return require(nodeModule).execSync(fullCmd, execOptions).trim();
176
- }
177
- const { execSync } = await import(nodeModule);
178
- return execSync(fullCmd, execOptions).toString().trim();
179
- } catch (err) {
180
- }
169
+ function getDatabaseURL() {
181
170
  try {
182
- if (isObject(Deno)) {
183
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
184
- return new TextDecoder().decode(await process2.output()).trim();
185
- }
171
+ const { databaseURL } = getEnvironment();
172
+ return databaseURL;
186
173
  } catch (err) {
174
+ return void 0;
187
175
  }
188
176
  }
189
-
190
177
  function getAPIKey() {
191
178
  try {
192
179
  const { apiKey } = getEnvironment();
@@ -296,7 +283,14 @@ enqueue_fn = function(task) {
296
283
  return promise;
297
284
  };
298
285
 
299
- const VERSION = "0.0.0-alpha.vf4e6746";
286
+ function generateUUID() {
287
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
288
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
289
+ return v.toString(16);
290
+ });
291
+ }
292
+
293
+ const VERSION = "0.21.6";
300
294
 
301
295
  class ErrorWithCause extends Error {
302
296
  constructor(message, options) {
@@ -307,7 +301,7 @@ class FetcherError extends ErrorWithCause {
307
301
  constructor(status, data, requestId) {
308
302
  super(getMessage(data));
309
303
  this.status = status;
310
- this.errors = isBulkError(data) ? data.errors : void 0;
304
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
311
305
  this.requestId = requestId;
312
306
  if (data instanceof Error) {
313
307
  this.stack = data.stack;
@@ -372,11 +366,12 @@ function hostHeader(url) {
372
366
  const { groups } = pattern.exec(url) ?? {};
373
367
  return groups?.host ? { Host: groups.host } : {};
374
368
  }
369
+ const defaultClientID = generateUUID();
375
370
  async function fetch$1({
376
371
  url: path,
377
372
  method,
378
373
  body,
379
- headers,
374
+ headers: customHeaders,
380
375
  pathParams,
381
376
  queryParams,
382
377
  fetchImpl,
@@ -388,6 +383,7 @@ async function fetch$1({
388
383
  signal,
389
384
  clientID,
390
385
  sessionID,
386
+ clientName,
391
387
  fetchOptions = {}
392
388
  }) {
393
389
  pool.setFetch(fetchImpl);
@@ -401,19 +397,26 @@ async function fetch$1({
401
397
  [TraceAttributes.HTTP_URL]: url,
402
398
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
403
399
  });
400
+ const xataAgent = compact([
401
+ ["client", "TS_SDK"],
402
+ ["version", VERSION],
403
+ isDefined(clientName) ? ["service", clientName] : void 0
404
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
405
+ const headers = {
406
+ "Accept-Encoding": "identity",
407
+ "Content-Type": "application/json",
408
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
409
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
410
+ "X-Xata-Agent": xataAgent,
411
+ ...customHeaders,
412
+ ...hostHeader(fullUrl),
413
+ Authorization: `Bearer ${apiKey}`
414
+ };
404
415
  const response = await pool.request(url, {
405
416
  ...fetchOptions,
406
417
  method: method.toUpperCase(),
407
418
  body: body ? JSON.stringify(body) : void 0,
408
- headers: {
409
- "Content-Type": "application/json",
410
- "User-Agent": `Xata client-ts/${VERSION}`,
411
- "X-Xata-Client-ID": clientID ?? "",
412
- "X-Xata-Session-ID": sessionID ?? "",
413
- ...headers,
414
- ...hostHeader(fullUrl),
415
- Authorization: `Bearer ${apiKey}`
416
- },
419
+ headers,
417
420
  signal
418
421
  });
419
422
  const { host, protocol } = parseUrl(response.url);
@@ -455,17 +458,12 @@ function parseUrl(url) {
455
458
 
456
459
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
457
460
 
458
- const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
459
461
  const getBranchList = (variables, signal) => dataPlaneFetch({
460
462
  url: "/dbs/{dbName}",
461
463
  method: "get",
462
464
  ...variables,
463
465
  signal
464
466
  });
465
- const dEPRECATEDcreateDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
466
- const dEPRECATEDdeleteDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "delete", ...variables, signal });
467
- const dEPRECATEDgetDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "get", ...variables, signal });
468
- const dEPRECATEDupdateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
469
467
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
470
468
  url: "/db/{dbBranchName}",
471
469
  method: "get",
@@ -504,7 +502,6 @@ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName
504
502
  const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
505
503
  const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
506
504
  const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
507
- const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
508
505
  const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
509
506
  const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
510
507
  const getMigrationRequest = (variables, signal) => dataPlaneFetch({
@@ -571,6 +568,7 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
571
568
  ...variables,
572
569
  signal
573
570
  });
571
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
574
572
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
575
573
  const getRecord = (variables, signal) => dataPlaneFetch({
576
574
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
@@ -604,13 +602,6 @@ const searchTable = (variables, signal) => dataPlaneFetch({
604
602
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
605
603
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
606
604
  const operationsByTag$2 = {
607
- database: {
608
- dEPRECATEDgetDatabaseList,
609
- dEPRECATEDcreateDatabase,
610
- dEPRECATEDdeleteDatabase,
611
- dEPRECATEDgetDatabaseMetadata,
612
- dEPRECATEDupdateDatabaseMetadata
613
- },
614
605
  branch: {
615
606
  getBranchList,
616
607
  getBranchDetails,
@@ -635,16 +626,6 @@ const operationsByTag$2 = {
635
626
  previewBranchSchemaEdit,
636
627
  applyBranchSchemaEdit
637
628
  },
638
- records: {
639
- branchTransaction,
640
- insertRecord,
641
- getRecord,
642
- insertRecordWithID,
643
- updateRecordWithID,
644
- upsertRecordWithID,
645
- deleteRecord,
646
- bulkInsertTableRecords
647
- },
648
629
  migrationRequests: {
649
630
  queryMigrationRequests,
650
631
  createMigrationRequest,
@@ -667,6 +648,16 @@ const operationsByTag$2 = {
667
648
  updateColumn,
668
649
  deleteColumn
669
650
  },
651
+ records: {
652
+ branchTransaction,
653
+ insertRecord,
654
+ getRecord,
655
+ insertRecordWithID,
656
+ updateRecordWithID,
657
+ upsertRecordWithID,
658
+ deleteRecord,
659
+ bulkInsertTableRecords
660
+ },
670
661
  searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
671
662
  };
672
663
 
@@ -840,12 +831,12 @@ function parseProviderString(provider = "production") {
840
831
  function parseWorkspacesUrlParts(url) {
841
832
  if (!isString(url))
842
833
  return null;
843
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
844
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
834
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
835
+ const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
845
836
  const match = url.match(regex) || url.match(regexStaging);
846
837
  if (!match)
847
838
  return null;
848
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
839
+ return { workspace: match[1], region: match[2] };
849
840
  }
850
841
 
851
842
  var __accessCheck$7 = (obj, member, msg) => {
@@ -874,6 +865,7 @@ class XataApiClient {
874
865
  const provider = options.host ?? "production";
875
866
  const apiKey = options.apiKey ?? getAPIKey();
876
867
  const trace = options.trace ?? defaultTrace;
868
+ const clientID = generateUUID();
877
869
  if (!apiKey) {
878
870
  throw new Error("Could not resolve a valid apiKey");
879
871
  }
@@ -882,7 +874,9 @@ class XataApiClient {
882
874
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
883
875
  fetchImpl: getFetchImplementation(options.fetch),
884
876
  apiKey,
885
- trace
877
+ trace,
878
+ clientName: options.clientName,
879
+ clientID
886
880
  });
887
881
  }
888
882
  get user() {
@@ -1878,8 +1872,8 @@ class DatabaseApi {
1878
1872
  }
1879
1873
 
1880
1874
  class XataApiPlugin {
1881
- async build(options) {
1882
- const { fetchImpl, apiKey } = await options.getFetchProps();
1875
+ build(options) {
1876
+ const { fetchImpl, apiKey } = options.getFetchProps();
1883
1877
  return new XataApiClient({ fetch: fetchImpl, apiKey });
1884
1878
  }
1885
1879
  }
@@ -1887,13 +1881,6 @@ class XataApiPlugin {
1887
1881
  class XataPlugin {
1888
1882
  }
1889
1883
 
1890
- function generateUUID() {
1891
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1892
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1893
- return v.toString(16);
1894
- });
1895
- }
1896
-
1897
1884
  function cleanFilter(filter) {
1898
1885
  if (!filter)
1899
1886
  return void 0;
@@ -1970,6 +1957,12 @@ const _RecordArray = class extends Array {
1970
1957
  toArray() {
1971
1958
  return new Array(...this);
1972
1959
  }
1960
+ toSerializable() {
1961
+ return JSON.parse(this.toString());
1962
+ }
1963
+ toString() {
1964
+ return JSON.stringify(this.toArray());
1965
+ }
1973
1966
  map(callbackfn, thisArg) {
1974
1967
  return this.toArray().map(callbackfn, thisArg);
1975
1968
  }
@@ -2041,6 +2034,7 @@ const _Query = class {
2041
2034
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
2042
2035
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
2043
2036
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
2037
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
2044
2038
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
2045
2039
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
2046
2040
  __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
@@ -2414,13 +2408,19 @@ class RestRepository extends Query {
2414
2408
  const result = await this.read(a, columns);
2415
2409
  return result;
2416
2410
  }
2417
- if (isString(a) && isObject(b)) {
2418
- const columns = isStringArray(c) ? c : void 0;
2419
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2420
- }
2421
- if (isObject(a) && isString(a.id)) {
2422
- const columns = isStringArray(b) ? b : void 0;
2423
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2411
+ try {
2412
+ if (isString(a) && isObject(b)) {
2413
+ const columns = isStringArray(c) ? c : void 0;
2414
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2415
+ }
2416
+ if (isObject(a) && isString(a.id)) {
2417
+ const columns = isStringArray(b) ? b : void 0;
2418
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2419
+ }
2420
+ } catch (error) {
2421
+ if (error.status === 422)
2422
+ return null;
2423
+ throw error;
2424
2424
  }
2425
2425
  throw new Error("Invalid arguments for update method");
2426
2426
  });
@@ -2551,7 +2551,9 @@ class RestRepository extends Query {
2551
2551
  prefix: options.prefix,
2552
2552
  highlight: options.highlight,
2553
2553
  filter: options.filter,
2554
- boosters: options.boosters
2554
+ boosters: options.boosters,
2555
+ page: options.page,
2556
+ target: options.target
2555
2557
  },
2556
2558
  ...fetchProps
2557
2559
  });
@@ -2593,7 +2595,8 @@ class RestRepository extends Query {
2593
2595
  filter: cleanFilter(data.filter),
2594
2596
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2595
2597
  page: data.pagination,
2596
- columns: data.columns ?? ["*"]
2598
+ columns: data.columns ?? ["*"],
2599
+ consistency: data.consistency
2597
2600
  },
2598
2601
  fetchOptions: data.fetchOptions,
2599
2602
  ...fetchProps
@@ -2621,6 +2624,7 @@ class RestRepository extends Query {
2621
2624
  filter: cleanFilter(data.filter),
2622
2625
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2623
2626
  columns: data.columns,
2627
+ consistency: data.consistency,
2624
2628
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2625
2629
  summaries,
2626
2630
  summariesFilter
@@ -2823,15 +2827,16 @@ deleteRecords_fn = async function(recordIds) {
2823
2827
  };
2824
2828
  _setCacheQuery = new WeakSet();
2825
2829
  setCacheQuery_fn = async function(query, meta, records) {
2826
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
2830
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
2827
2831
  };
2828
2832
  _getCacheQuery = new WeakSet();
2829
2833
  getCacheQuery_fn = async function(query) {
2830
2834
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2831
- const result = await __privateGet$4(this, _cache).get(key);
2835
+ const result = await __privateGet$4(this, _cache)?.get(key);
2832
2836
  if (!result)
2833
2837
  return null;
2834
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
2838
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
2839
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2835
2840
  if (ttl < 0)
2836
2841
  return null;
2837
2842
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2857,23 +2862,23 @@ const transformObjectLinks = (object) => {
2857
2862
  }, {});
2858
2863
  };
2859
2864
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2860
- const result = {};
2865
+ const data = {};
2861
2866
  const { xata, ...rest } = object ?? {};
2862
- Object.assign(result, rest);
2867
+ Object.assign(data, rest);
2863
2868
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2864
2869
  if (!columns)
2865
2870
  console.error(`Table ${table} not found in schema`);
2866
2871
  for (const column of columns ?? []) {
2867
2872
  if (!isValidColumn(selectedColumns, column))
2868
2873
  continue;
2869
- const value = result[column.name];
2874
+ const value = data[column.name];
2870
2875
  switch (column.type) {
2871
2876
  case "datetime": {
2872
2877
  const date = value !== void 0 ? new Date(value) : null;
2873
2878
  if (date !== null && isNaN(date.getTime())) {
2874
2879
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2875
2880
  } else {
2876
- result[column.name] = date;
2881
+ data[column.name] = date;
2877
2882
  }
2878
2883
  break;
2879
2884
  }
@@ -2892,44 +2897,51 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2892
2897
  }
2893
2898
  return acc;
2894
2899
  }, []);
2895
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2900
+ data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2896
2901
  } else {
2897
- result[column.name] = null;
2902
+ data[column.name] = null;
2898
2903
  }
2899
2904
  break;
2900
2905
  }
2901
2906
  default:
2902
- result[column.name] = value ?? null;
2907
+ data[column.name] = value ?? null;
2903
2908
  if (column.notNull === true && value === null) {
2904
2909
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2905
2910
  }
2906
2911
  break;
2907
2912
  }
2908
2913
  }
2909
- result.read = function(columns2) {
2910
- return db[table].read(result["id"], columns2);
2914
+ const record = { ...data };
2915
+ record.read = function(columns2) {
2916
+ return db[table].read(record["id"], columns2);
2911
2917
  };
2912
- result.update = function(data, b, c) {
2918
+ record.update = function(data2, b, c) {
2913
2919
  const columns2 = isStringArray(b) ? b : ["*"];
2914
2920
  const ifVersion = parseIfVersion(b, c);
2915
- return db[table].update(result["id"], data, columns2, { ifVersion });
2921
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2916
2922
  };
2917
- result.replace = function(data, b, c) {
2923
+ record.replace = function(data2, b, c) {
2918
2924
  const columns2 = isStringArray(b) ? b : ["*"];
2919
2925
  const ifVersion = parseIfVersion(b, c);
2920
- return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
2926
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2921
2927
  };
2922
- result.delete = function() {
2923
- return db[table].delete(result["id"]);
2928
+ record.delete = function() {
2929
+ return db[table].delete(record["id"]);
2924
2930
  };
2925
- result.getMetadata = function() {
2931
+ record.getMetadata = function() {
2926
2932
  return xata;
2927
2933
  };
2928
- for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
2929
- Object.defineProperty(result, prop, { enumerable: false });
2934
+ record.toSerializable = function() {
2935
+ return JSON.parse(JSON.stringify(transformObjectLinks(data)));
2936
+ };
2937
+ record.toString = function() {
2938
+ return JSON.stringify(transformObjectLinks(data));
2939
+ };
2940
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
2941
+ Object.defineProperty(record, prop, { enumerable: false });
2930
2942
  }
2931
- Object.freeze(result);
2932
- return result;
2943
+ Object.freeze(record);
2944
+ return record;
2933
2945
  };
2934
2946
  function extractId(value) {
2935
2947
  if (isString(value))
@@ -3140,10 +3152,10 @@ _schemaTables = new WeakMap();
3140
3152
  _search = new WeakSet();
3141
3153
  search_fn = async function(query, options, getFetchProps) {
3142
3154
  const fetchProps = await getFetchProps();
3143
- const { tables, fuzziness, highlight, prefix } = options ?? {};
3155
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3144
3156
  const { records } = await searchBranch({
3145
3157
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3146
- body: { tables, query, fuzziness, prefix, highlight },
3158
+ body: { tables, query, fuzziness, prefix, highlight, page },
3147
3159
  ...fetchProps
3148
3160
  });
3149
3161
  return records;
@@ -3181,89 +3193,6 @@ const isBranchStrategyBuilder = (strategy) => {
3181
3193
  return typeof strategy === "function";
3182
3194
  };
3183
3195
 
3184
- async function getCurrentBranchName(options) {
3185
- const { branch, envBranch } = getEnvironment();
3186
- if (branch) {
3187
- const details = await getDatabaseBranch(branch, options);
3188
- if (details)
3189
- return branch;
3190
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
3191
- }
3192
- const gitBranch = envBranch || await getGitBranch();
3193
- return resolveXataBranch(gitBranch, options);
3194
- }
3195
- async function getCurrentBranchDetails(options) {
3196
- const branch = await getCurrentBranchName(options);
3197
- return getDatabaseBranch(branch, options);
3198
- }
3199
- async function resolveXataBranch(gitBranch, options) {
3200
- const databaseURL = options?.databaseURL || getDatabaseURL();
3201
- const apiKey = options?.apiKey || getAPIKey();
3202
- if (!databaseURL)
3203
- throw new Error(
3204
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3205
- );
3206
- if (!apiKey)
3207
- throw new Error(
3208
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3209
- );
3210
- const [protocol, , host, , dbName] = databaseURL.split("/");
3211
- const urlParts = parseWorkspacesUrlParts(host);
3212
- if (!urlParts)
3213
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3214
- const { workspace, region } = urlParts;
3215
- const { fallbackBranch } = getEnvironment();
3216
- const { branch } = await resolveBranch({
3217
- apiKey,
3218
- apiUrl: databaseURL,
3219
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3220
- workspacesApiUrl: `${protocol}//${host}`,
3221
- pathParams: { dbName, workspace, region },
3222
- queryParams: { gitBranch, fallbackBranch },
3223
- trace: defaultTrace
3224
- });
3225
- return branch;
3226
- }
3227
- async function getDatabaseBranch(branch, options) {
3228
- const databaseURL = options?.databaseURL || getDatabaseURL();
3229
- const apiKey = options?.apiKey || getAPIKey();
3230
- if (!databaseURL)
3231
- throw new Error(
3232
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3233
- );
3234
- if (!apiKey)
3235
- throw new Error(
3236
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3237
- );
3238
- const [protocol, , host, , database] = databaseURL.split("/");
3239
- const urlParts = parseWorkspacesUrlParts(host);
3240
- if (!urlParts)
3241
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3242
- const { workspace, region } = urlParts;
3243
- try {
3244
- return await getBranchDetails({
3245
- apiKey,
3246
- apiUrl: databaseURL,
3247
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3248
- workspacesApiUrl: `${protocol}//${host}`,
3249
- pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3250
- trace: defaultTrace
3251
- });
3252
- } catch (err) {
3253
- if (isObject(err) && err.status === 404)
3254
- return null;
3255
- throw err;
3256
- }
3257
- }
3258
- function getDatabaseURL() {
3259
- try {
3260
- const { databaseURL } = getEnvironment();
3261
- return databaseURL;
3262
- } catch (err) {
3263
- return void 0;
3264
- }
3265
- }
3266
-
3267
3196
  var __accessCheck = (obj, member, msg) => {
3268
3197
  if (!member.has(obj))
3269
3198
  throw TypeError("Cannot " + msg);
@@ -3311,24 +3240,17 @@ const buildClient = (plugins) => {
3311
3240
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3312
3241
  if (namespace === void 0)
3313
3242
  continue;
3314
- const result = namespace.build(pluginOptions);
3315
- if (result instanceof Promise) {
3316
- void result.then((namespace2) => {
3317
- this[key] = namespace2;
3318
- });
3319
- } else {
3320
- this[key] = result;
3321
- }
3243
+ this[key] = namespace.build(pluginOptions);
3322
3244
  }
3323
3245
  }
3324
3246
  async getConfig() {
3325
3247
  const databaseURL = __privateGet(this, _options).databaseURL;
3326
- const branch = await __privateGet(this, _options).branch();
3248
+ const branch = __privateGet(this, _options).branch;
3327
3249
  return { databaseURL, branch };
3328
3250
  }
3329
3251
  }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3330
3252
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3331
- const isBrowser = typeof window !== "undefined";
3253
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3332
3254
  if (isBrowser && !enableBrowser) {
3333
3255
  throw new Error(
3334
3256
  "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."
@@ -3339,16 +3261,29 @@ const buildClient = (plugins) => {
3339
3261
  const apiKey = options?.apiKey || getAPIKey();
3340
3262
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3341
3263
  const trace = options?.trace ?? defaultTrace;
3342
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
3264
+ const clientName = options?.clientName;
3265
+ const host = options?.host ?? "production";
3266
+ const branch = options?.branch !== void 0 ? __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : "main";
3343
3267
  if (!apiKey) {
3344
3268
  throw new Error("Option apiKey is required");
3345
3269
  }
3346
3270
  if (!databaseURL) {
3347
3271
  throw new Error("Option databaseURL is required");
3348
3272
  }
3349
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser };
3350
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3351
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3273
+ return {
3274
+ fetch,
3275
+ databaseURL,
3276
+ apiKey,
3277
+ branch,
3278
+ cache,
3279
+ trace,
3280
+ host,
3281
+ clientID: generateUUID(),
3282
+ enableBrowser,
3283
+ clientName
3284
+ };
3285
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({ fetch, apiKey, databaseURL, branch, trace, clientID, clientName }) {
3286
+ const branchValue = __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3352
3287
  if (!branchValue)
3353
3288
  throw new Error("Unable to resolve branch value");
3354
3289
  return {
@@ -3361,19 +3296,20 @@ const buildClient = (plugins) => {
3361
3296
  return databaseURL + newPath;
3362
3297
  },
3363
3298
  trace,
3364
- clientID
3299
+ clientID,
3300
+ clientName
3365
3301
  };
3366
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3302
+ }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = function(param) {
3367
3303
  if (__privateGet(this, _branch))
3368
3304
  return __privateGet(this, _branch);
3369
3305
  if (param === void 0)
3370
3306
  return void 0;
3371
3307
  const strategies = Array.isArray(param) ? [...param] : [param];
3372
- const evaluateBranch = async (strategy) => {
3373
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
3308
+ const evaluateBranch = (strategy) => {
3309
+ return isBranchStrategyBuilder(strategy) ? strategy() : strategy;
3374
3310
  };
3375
- for await (const strategy of strategies) {
3376
- const branch = await evaluateBranch(strategy);
3311
+ for (const strategy of strategies) {
3312
+ const branch = evaluateBranch(strategy);
3377
3313
  if (branch) {
3378
3314
  __privateSet(this, _branch, branch);
3379
3315
  return branch;
@@ -3452,7 +3388,7 @@ const deserialize = (json) => {
3452
3388
  };
3453
3389
 
3454
3390
  function buildWorkerRunner(config) {
3455
- return function xataWorker(name, _worker) {
3391
+ return function xataWorker(name, worker) {
3456
3392
  return async (...args) => {
3457
3393
  const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3458
3394
  const result = await fetch(url, {
@@ -3474,6 +3410,7 @@ class XataError extends Error {
3474
3410
  }
3475
3411
 
3476
3412
  exports.BaseClient = BaseClient;
3413
+ exports.FetcherError = FetcherError;
3477
3414
  exports.Operations = operationsByTag;
3478
3415
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
3479
3416
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -3512,11 +3449,6 @@ exports.createMigrationRequest = createMigrationRequest;
3512
3449
  exports.createTable = createTable;
3513
3450
  exports.createUserAPIKey = createUserAPIKey;
3514
3451
  exports.createWorkspace = createWorkspace;
3515
- exports.dEPRECATEDcreateDatabase = dEPRECATEDcreateDatabase;
3516
- exports.dEPRECATEDdeleteDatabase = dEPRECATEDdeleteDatabase;
3517
- exports.dEPRECATEDgetDatabaseList = dEPRECATEDgetDatabaseList;
3518
- exports.dEPRECATEDgetDatabaseMetadata = dEPRECATEDgetDatabaseMetadata;
3519
- exports.dEPRECATEDupdateDatabaseMetadata = dEPRECATEDupdateDatabaseMetadata;
3520
3452
  exports.deleteBranch = deleteBranch;
3521
3453
  exports.deleteColumn = deleteColumn;
3522
3454
  exports.deleteDatabase = deleteDatabase;
@@ -3540,8 +3472,6 @@ exports.getBranchMigrationPlan = getBranchMigrationPlan;
3540
3472
  exports.getBranchSchemaHistory = getBranchSchemaHistory;
3541
3473
  exports.getBranchStats = getBranchStats;
3542
3474
  exports.getColumn = getColumn;
3543
- exports.getCurrentBranchDetails = getCurrentBranchDetails;
3544
- exports.getCurrentBranchName = getCurrentBranchName;
3545
3475
  exports.getDatabaseList = getDatabaseList;
3546
3476
  exports.getDatabaseMetadata = getDatabaseMetadata;
3547
3477
  exports.getDatabaseURL = getDatabaseURL;