@xata.io/client 0.0.0-beta.b4e03dd → 0.0.0-beta.b8f7b5b

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.
Files changed (53) hide show
  1. package/.eslintrc.cjs +13 -0
  2. package/CHANGELOG.md +57 -0
  3. package/dist/api/client.d.ts +2 -2
  4. package/dist/api/client.js +33 -17
  5. package/dist/api/components.d.ts +7 -6
  6. package/dist/api/components.js +7 -6
  7. package/dist/api/fetcher.d.ts +15 -0
  8. package/dist/api/fetcher.js +23 -22
  9. package/dist/api/providers.js +3 -2
  10. package/dist/api/responses.d.ts +6 -0
  11. package/dist/client.d.ts +39 -0
  12. package/dist/client.js +124 -0
  13. package/dist/index.d.ts +3 -0
  14. package/dist/index.js +3 -0
  15. package/dist/namespace.d.ts +7 -0
  16. package/dist/namespace.js +6 -0
  17. package/dist/schema/filters.d.ts +93 -17
  18. package/dist/schema/filters.js +0 -22
  19. package/dist/schema/filters.spec.d.ts +1 -0
  20. package/dist/schema/filters.spec.js +177 -0
  21. package/dist/schema/index.d.ts +17 -2
  22. package/dist/schema/index.js +29 -6
  23. package/dist/schema/operators.d.ts +26 -24
  24. package/dist/schema/operators.js +13 -11
  25. package/dist/schema/pagination.d.ts +13 -13
  26. package/dist/schema/pagination.js +0 -1
  27. package/dist/schema/query.d.ts +39 -50
  28. package/dist/schema/query.js +25 -37
  29. package/dist/schema/record.d.ts +25 -3
  30. package/dist/schema/record.js +11 -0
  31. package/dist/schema/repository.d.ts +94 -64
  32. package/dist/schema/repository.js +206 -202
  33. package/dist/schema/selection.d.ts +24 -11
  34. package/dist/schema/selection.spec.d.ts +1 -0
  35. package/dist/schema/selection.spec.js +204 -0
  36. package/dist/schema/sorting.d.ts +17 -0
  37. package/dist/schema/sorting.js +28 -0
  38. package/dist/schema/sorting.spec.d.ts +1 -0
  39. package/dist/schema/sorting.spec.js +11 -0
  40. package/dist/search/index.d.ts +20 -0
  41. package/dist/search/index.js +30 -0
  42. package/dist/util/branches.d.ts +5 -0
  43. package/dist/util/branches.js +7 -0
  44. package/dist/util/config.d.ts +11 -0
  45. package/dist/util/config.js +121 -0
  46. package/dist/util/environment.d.ts +5 -0
  47. package/dist/util/environment.js +68 -0
  48. package/dist/util/fetch.d.ts +2 -0
  49. package/dist/util/fetch.js +13 -0
  50. package/dist/util/lang.d.ts +3 -0
  51. package/dist/util/lang.js +13 -1
  52. package/dist/util/types.d.ts +23 -1
  53. package/package.json +5 -2
package/.eslintrc.cjs ADDED
@@ -0,0 +1,13 @@
1
+ module.exports = {
2
+ ignorePatterns: ["dist"],
3
+ parserOptions: {
4
+ ecmaVersion: 2020,
5
+ sourceType: 'module',
6
+ project: 'client/tsconfig.json'
7
+ },
8
+ rules: {
9
+ '@typescript-eslint/no-explicit-any': 'off',
10
+ '@typescript-eslint/ban-types': 'off',
11
+ '@typescript-eslint/no-floating-promises': 'error',
12
+ }
13
+ };
package/CHANGELOG.md CHANGED
@@ -1,5 +1,62 @@
1
1
  # @xata.io/client
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Patch Changes
6
+
7
+ - bde908e: Refactor client builder
8
+ - ea3eef8: Make records returned by the API readonly
9
+
10
+ ## 0.7.2
11
+
12
+ ### Patch Changes
13
+
14
+ - 4803b6f: Memoize ApiClient namespaces
15
+ - 1f268d7: Add search in XataClient
16
+ - d58c3d9: Hide private helper utilities
17
+ - f3b731b: Expose branch resolution API
18
+
19
+ ## 0.7.1
20
+
21
+ ### Patch Changes
22
+
23
+ - 01aef78: Fix bundle for browsers
24
+ - 56be1fd: Allow sending updates with link object
25
+ - fc51771: Add includes operator helper methods
26
+
27
+ ## 0.7.0
28
+
29
+ ### Minor Changes
30
+
31
+ - 6ce5512: Add bulk operations for all methods
32
+ - 2a1fa4f: Introduced automatic branch resolution mechanism
33
+
34
+ ### Patch Changes
35
+
36
+ - d033f3a: Improve column selection output type with non-nullable columns
37
+ - b1e92db: Include stack trace with errors
38
+ - deed570: Improve sorting with multiple properties
39
+ - 80b5417: Improve filtering types
40
+
41
+ ## 0.6.0
42
+
43
+ ### Minor Changes
44
+
45
+ - 084f5df: Add type inference for columns
46
+ - bb73c89: Unify create and insert in a single method overload
47
+
48
+ ### Patch Changes
49
+
50
+ - 716c487: Forward nullable types on links
51
+ - bb66bb2: Fix error handling with createMany
52
+ - 084f5df: Fix circular dependencies on selectable column
53
+
54
+ ## 0.5.1
55
+
56
+ ### Patch Changes
57
+
58
+ - 12729ab: Make API client fetch implementation optional
59
+
3
60
  ## 0.5.0
4
61
 
5
62
  ### Patch Changes
@@ -4,8 +4,8 @@ import { HostProvider } from './providers';
4
4
  import type * as Responses from './responses';
5
5
  import type * as Schemas from './schemas';
6
6
  export interface XataApiClientOptions {
7
- fetch: FetchImpl;
8
- apiKey: string;
7
+ fetch?: FetchImpl;
8
+ apiKey?: string;
9
9
  host?: HostProvider;
10
10
  }
11
11
  export declare class XataApiClient {
@@ -10,49 +10,63 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
12
  };
13
- var _XataApiClient_extraProps;
13
+ var _XataApiClient_extraProps, _XataApiClient_namespaces;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.XataApiClient = void 0;
16
+ const config_1 = require("../util/config");
17
+ const fetch_1 = require("../util/fetch");
16
18
  const components_1 = require("./components");
17
19
  const providers_1 = require("./providers");
18
20
  class XataApiClient {
19
21
  constructor(options) {
20
- var _a;
22
+ var _a, _b;
21
23
  _XataApiClient_extraProps.set(this, void 0);
22
- const fetchImpl = typeof fetch !== 'undefined' ? fetch : options.fetch;
23
- if (!fetchImpl) {
24
- /** @todo add a link after docs exist */
25
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
26
- }
24
+ _XataApiClient_namespaces.set(this, {});
27
25
  const provider = (_a = options.host) !== null && _a !== void 0 ? _a : 'production';
26
+ const apiKey = (_b = options === null || options === void 0 ? void 0 : options.apiKey) !== null && _b !== void 0 ? _b : (0, config_1.getAPIKey)();
27
+ if (!apiKey) {
28
+ throw new Error('Could not resolve a valid apiKey');
29
+ }
28
30
  __classPrivateFieldSet(this, _XataApiClient_extraProps, {
29
31
  apiUrl: (0, providers_1.getHostUrl)(provider, 'main'),
30
32
  workspacesApiUrl: (0, providers_1.getHostUrl)(provider, 'workspaces'),
31
- fetchImpl,
32
- apiKey: options.apiKey
33
+ fetchImpl: (0, fetch_1.getFetchImplementation)(options.fetch),
34
+ apiKey
33
35
  }, "f");
34
36
  }
35
37
  get user() {
36
- return new UserApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
38
+ if (!__classPrivateFieldGet(this, _XataApiClient_namespaces, "f").user)
39
+ __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").user = new UserApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
40
+ return __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").user;
37
41
  }
38
42
  get workspaces() {
39
- return new WorkspaceApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
43
+ if (!__classPrivateFieldGet(this, _XataApiClient_namespaces, "f").workspaces)
44
+ __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").workspaces = new WorkspaceApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
45
+ return __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").workspaces;
40
46
  }
41
47
  get databases() {
42
- return new DatabaseApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
48
+ if (!__classPrivateFieldGet(this, _XataApiClient_namespaces, "f").databases)
49
+ __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").databases = new DatabaseApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
50
+ return __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").databases;
43
51
  }
44
52
  get branches() {
45
- return new BranchApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
53
+ if (!__classPrivateFieldGet(this, _XataApiClient_namespaces, "f").branches)
54
+ __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").branches = new BranchApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
55
+ return __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").branches;
46
56
  }
47
57
  get tables() {
48
- return new TableApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
58
+ if (!__classPrivateFieldGet(this, _XataApiClient_namespaces, "f").tables)
59
+ __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").tables = new TableApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
60
+ return __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").tables;
49
61
  }
50
62
  get records() {
51
- return new RecordsApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
63
+ if (!__classPrivateFieldGet(this, _XataApiClient_namespaces, "f").records)
64
+ __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").records = new RecordsApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
65
+ return __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").records;
52
66
  }
53
67
  }
54
68
  exports.XataApiClient = XataApiClient;
55
- _XataApiClient_extraProps = new WeakMap();
69
+ _XataApiClient_extraProps = new WeakMap(), _XataApiClient_namespaces = new WeakMap();
56
70
  class UserApi {
57
71
  constructor(extraProps) {
58
72
  this.extraProps = extraProps;
@@ -220,7 +234,9 @@ class RecordsApi {
220
234
  deleteRecord(workspace, database, branch, tableName, recordId) {
221
235
  return components_1.operationsByTag.records.deleteRecord(Object.assign({ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId } }, this.extraProps));
222
236
  }
223
- getRecord(workspace, database, branch, tableName, recordId, options = {}) {
237
+ getRecord(workspace, database, branch, tableName, recordId,
238
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
239
+ options = {}) {
224
240
  return components_1.operationsByTag.records.getRecord(Object.assign({ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId } }, this.extraProps));
225
241
  }
226
242
  bulkInsertTableRecords(workspace, database, branch, tableName, records) {
@@ -990,8 +990,9 @@ export declare type QueryTableVariables = {
990
990
  * },
991
991
  * {
992
992
  * "name": "r2",
993
- * },
994
- * ],
993
+ * }
994
+ * ]
995
+ * }
995
996
  * }
996
997
  * ```
997
998
  *
@@ -1001,7 +1002,7 @@ export declare type QueryTableVariables = {
1001
1002
  * {
1002
1003
  * "filter": {
1003
1004
  * "$exists": "settings",
1004
- * },
1005
+ * }
1005
1006
  * }
1006
1007
  * ```
1007
1008
  *
@@ -1016,8 +1017,8 @@ export declare type QueryTableVariables = {
1016
1017
  * },
1017
1018
  * {
1018
1019
  * "$exists": "name",
1019
- * },
1020
- * ],
1020
+ * }
1021
+ * ]
1021
1022
  * }
1022
1023
  * }
1023
1024
  * ```
@@ -1028,7 +1029,7 @@ export declare type QueryTableVariables = {
1028
1029
  * {
1029
1030
  * "filter": {
1030
1031
  * "$notExists": "settings",
1031
- * },
1032
+ * }
1032
1033
  * }
1033
1034
  * ```
1034
1035
  *
@@ -573,8 +573,9 @@ exports.bulkInsertTableRecords = bulkInsertTableRecords;
573
573
  * },
574
574
  * {
575
575
  * "name": "r2",
576
- * },
577
- * ],
576
+ * }
577
+ * ]
578
+ * }
578
579
  * }
579
580
  * ```
580
581
  *
@@ -584,7 +585,7 @@ exports.bulkInsertTableRecords = bulkInsertTableRecords;
584
585
  * {
585
586
  * "filter": {
586
587
  * "$exists": "settings",
587
- * },
588
+ * }
588
589
  * }
589
590
  * ```
590
591
  *
@@ -599,8 +600,8 @@ exports.bulkInsertTableRecords = bulkInsertTableRecords;
599
600
  * },
600
601
  * {
601
602
  * "$exists": "name",
602
- * },
603
- * ],
603
+ * }
604
+ * ]
604
605
  * }
605
606
  * }
606
607
  * ```
@@ -611,7 +612,7 @@ exports.bulkInsertTableRecords = bulkInsertTableRecords;
611
612
  * {
612
613
  * "filter": {
613
614
  * "$notExists": "settings",
614
- * },
615
+ * }
615
616
  * }
616
617
  * ```
617
618
  *
@@ -23,3 +23,18 @@ export declare type FetcherOptions<TBody, THeaders, TQueryParams, TPathParams> =
23
23
  pathParams?: TPathParams;
24
24
  };
25
25
  export declare function fetch<TData, TBody extends Record<string, unknown> | undefined, THeaders extends Record<string, unknown>, TQueryParams extends Record<string, unknown>, TPathParams extends Record<string, string>>({ url: path, method, body, headers, pathParams, queryParams, fetchImpl, apiKey, apiUrl, workspacesApiUrl }: FetcherOptions<TBody, THeaders, TQueryParams, TPathParams> & FetcherExtraProps): Promise<TData>;
26
+ export declare class FetcherError extends Error {
27
+ status: number;
28
+ errors: Array<{
29
+ status: number;
30
+ message?: string;
31
+ }> | undefined;
32
+ constructor(data: {
33
+ message: string;
34
+ status: number;
35
+ errors?: Array<{
36
+ status: number;
37
+ message?: string;
38
+ }>;
39
+ }, parent?: Error);
40
+ }
@@ -9,13 +9,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.fetch = void 0;
12
+ exports.FetcherError = exports.fetch = void 0;
13
+ const lang_1 = require("../util/lang");
13
14
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
14
15
  const query = new URLSearchParams(queryParams).toString();
15
16
  const queryString = query.length > 0 ? `?${query}` : '';
16
17
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
17
18
  };
18
- const fallbackError = { message: 'Network response was not ok' };
19
19
  function buildBaseUrl({ path, workspacesApiUrl, apiUrl, pathParams }) {
20
20
  if (!(pathParams === null || pathParams === void 0 ? void 0 : pathParams.workspace))
21
21
  return `${apiUrl}${path}`;
@@ -51,28 +51,29 @@ function fetch({ url: path, method, body, headers, pathParams, queryParams, fetc
51
51
  if (response.ok) {
52
52
  return jsonResponse;
53
53
  }
54
- if (jsonResponse.message) {
55
- throw withStatus({ message: jsonResponse.message }, response.status);
56
- }
57
- else {
58
- throw withStatus(fallbackError, response.status);
59
- }
54
+ const { message = 'Unknown error', errors } = jsonResponse;
55
+ throw new FetcherError({ message, status: response.status, errors });
60
56
  }
61
- catch (e) {
62
- if (e instanceof Error) {
63
- const error = {
64
- message: e.message
65
- };
66
- throw withStatus(error, response.status);
67
- }
68
- else if (typeof e === 'object' && typeof e.message === 'string') {
69
- throw withStatus(e, response.status);
70
- }
71
- else {
72
- throw withStatus(fallbackError, response.status);
73
- }
57
+ catch (error) {
58
+ const message = hasMessage(error) ? error.message : 'Unknown network error';
59
+ const parent = error instanceof Error ? error : undefined;
60
+ throw new FetcherError({ message, status: response.status }, parent);
74
61
  }
75
62
  });
76
63
  }
77
64
  exports.fetch = fetch;
78
- const withStatus = (error, status) => (Object.assign(Object.assign({}, error), { status }));
65
+ const hasMessage = (error) => {
66
+ return (0, lang_1.isObject)(error) && (0, lang_1.isString)(error.message);
67
+ };
68
+ class FetcherError extends Error {
69
+ constructor(data, parent) {
70
+ super(data.message);
71
+ this.status = data.status;
72
+ this.errors = data.errors;
73
+ if (parent) {
74
+ this.stack = parent.stack;
75
+ this.cause = parent.cause;
76
+ }
77
+ }
78
+ }
79
+ exports.FetcherError = FetcherError;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getHostUrl = void 0;
4
+ const lang_1 = require("../util/lang");
4
5
  function getHostUrl(provider, type) {
5
6
  if (isValidAlias(provider)) {
6
7
  return providers[provider][type];
@@ -22,8 +23,8 @@ const providers = {
22
23
  }
23
24
  };
24
25
  function isValidAlias(alias) {
25
- return typeof alias === 'string' && Object.keys(providers).includes(alias);
26
+ return (0, lang_1.isString)(alias) && Object.keys(providers).includes(alias);
26
27
  }
27
28
  function isValidBuilder(builder) {
28
- return typeof builder === 'object' && typeof builder.main === 'string' && typeof builder.workspaces === 'string';
29
+ return (0, lang_1.isObject)(builder) && (0, lang_1.isString)(builder.main) && (0, lang_1.isString)(builder.workspaces);
29
30
  }
@@ -19,6 +19,12 @@ export declare type AuthError = {
19
19
  id?: string;
20
20
  message: string;
21
21
  };
22
+ export declare type BulkError = {
23
+ errors: {
24
+ message?: string;
25
+ status?: number;
26
+ }[];
27
+ };
22
28
  export declare type BranchMigrationPlan = {
23
29
  version: number;
24
30
  migration: Schemas.BranchMigration;
@@ -0,0 +1,39 @@
1
+ import { FetchImpl } from './api/fetcher';
2
+ import { Namespace } from './namespace';
3
+ import { SchemaNamespace } from './schema';
4
+ import { BaseData } from './schema/record';
5
+ import { LinkDictionary } from './schema/repository';
6
+ import { SearchNamespace } from './search';
7
+ import { BranchStrategyOption } from './util/branches';
8
+ import { StringKeys } from './util/types';
9
+ export declare type BaseClientOptions = {
10
+ fetch?: FetchImpl;
11
+ apiKey?: string;
12
+ databaseURL?: string;
13
+ branch?: BranchStrategyOption;
14
+ };
15
+ export declare const buildClientWithNamespaces: <ExternalNamespaces extends Record<string, Namespace>>(namespaces: ExternalNamespaces) => <Schemas extends Record<string, BaseData>>() => WrapperConstructor<Schemas, {
16
+ db: SchemaNamespace<Schemas>;
17
+ search: SearchNamespace<Schemas>;
18
+ }, ExternalNamespaces>;
19
+ export declare const buildClient: <Schemas extends Record<string, BaseData>, ExternalNamespaces extends Record<string, Namespace> = {}, Namespaces extends Record<string, Namespace> = {
20
+ db: SchemaNamespace<Schemas>;
21
+ search: SearchNamespace<Schemas>;
22
+ }>(external?: ExternalNamespaces | undefined) => WrapperConstructor<Schemas, Namespaces, ExternalNamespaces>;
23
+ export interface WrapperConstructor<Schemas extends Record<string, BaseData> = Record<string, any>, Namespaces extends Record<string, Namespace> = {
24
+ db: SchemaNamespace<Schemas>;
25
+ search: SearchNamespace<Schemas>;
26
+ }, ExternalNamespaces extends Record<string, Namespace> = Record<string, Namespace>> {
27
+ new (options?: Partial<BaseClientOptions>, links?: LinkDictionary): {
28
+ [Key in StringKeys<Namespaces>]: ReturnType<Namespaces[Key]['build']>;
29
+ } & {
30
+ [Key in StringKeys<NonNullable<ExternalNamespaces>>]: ReturnType<NonNullable<ExternalNamespaces>[Key]['build']>;
31
+ };
32
+ }
33
+ declare const BaseClient_base: WrapperConstructor<Record<string, any>, {
34
+ db: SchemaNamespace<Record<string, any>>;
35
+ search: SearchNamespace<Record<string, any>>;
36
+ }, {}>;
37
+ export declare class BaseClient extends BaseClient_base {
38
+ }
39
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
12
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
13
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
14
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
15
+ };
16
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
17
+ if (kind === "m") throw new TypeError("Private method is not writable");
18
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
19
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
20
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
21
+ };
22
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
23
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
24
+ var m = o[Symbol.asyncIterator], i;
25
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
26
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
27
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
28
+ };
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.BaseClient = exports.buildClient = exports.buildClientWithNamespaces = void 0;
31
+ const schema_1 = require("./schema");
32
+ const search_1 = require("./search");
33
+ const branches_1 = require("./util/branches");
34
+ const config_1 = require("./util/config");
35
+ const fetch_1 = require("./util/fetch");
36
+ const buildClientWithNamespaces = (namespaces) => () => (0, exports.buildClient)(namespaces);
37
+ exports.buildClientWithNamespaces = buildClientWithNamespaces;
38
+ const buildClient = (external) => {
39
+ var _instances, _branch, _parseOptions, _getFetchProps, _evaluateBranch, _a;
40
+ return _a = class {
41
+ constructor(options = {}, links) {
42
+ _instances.add(this);
43
+ _branch.set(this, void 0);
44
+ const safeOptions = __classPrivateFieldGet(this, _instances, "m", _parseOptions).call(this, options);
45
+ const namespaces = Object.assign({ db: new schema_1.SchemaNamespace(links), search: new search_1.SearchNamespace() }, external);
46
+ for (const [key, namespace] of Object.entries(namespaces)) {
47
+ if (!namespace)
48
+ continue;
49
+ // @ts-ignore
50
+ this[key] = namespace.build({ getFetchProps: () => __classPrivateFieldGet(this, _instances, "m", _getFetchProps).call(this, safeOptions) });
51
+ }
52
+ }
53
+ },
54
+ _branch = new WeakMap(),
55
+ _instances = new WeakSet(),
56
+ _parseOptions = function _parseOptions(options) {
57
+ const fetch = (0, fetch_1.getFetchImplementation)(options === null || options === void 0 ? void 0 : options.fetch);
58
+ const databaseURL = (options === null || options === void 0 ? void 0 : options.databaseURL) || (0, config_1.getDatabaseURL)();
59
+ const apiKey = (options === null || options === void 0 ? void 0 : options.apiKey) || (0, config_1.getAPIKey)();
60
+ const branch = () => __awaiter(this, void 0, void 0, function* () {
61
+ return (options === null || options === void 0 ? void 0 : options.branch)
62
+ ? yield __classPrivateFieldGet(this, _instances, "m", _evaluateBranch).call(this, options.branch)
63
+ : yield (0, config_1.getCurrentBranchName)({ apiKey, databaseURL, fetchImpl: options === null || options === void 0 ? void 0 : options.fetch });
64
+ });
65
+ if (!databaseURL || !apiKey) {
66
+ throw new Error('Options databaseURL and apiKey are required');
67
+ }
68
+ return { fetch, databaseURL, apiKey, branch };
69
+ },
70
+ _getFetchProps = function _getFetchProps({ fetch, apiKey, databaseURL, branch }) {
71
+ return __awaiter(this, void 0, void 0, function* () {
72
+ const branchValue = yield __classPrivateFieldGet(this, _instances, "m", _evaluateBranch).call(this, branch);
73
+ if (!branchValue)
74
+ throw new Error('Unable to resolve branch value');
75
+ return {
76
+ fetchImpl: fetch,
77
+ apiKey,
78
+ apiUrl: '',
79
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
80
+ workspacesApiUrl: (path, params) => {
81
+ var _a;
82
+ const hasBranch = (_a = params.dbBranchName) !== null && _a !== void 0 ? _a : params.branch;
83
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : '');
84
+ return databaseURL + newPath;
85
+ }
86
+ };
87
+ });
88
+ },
89
+ _evaluateBranch = function _evaluateBranch(param) {
90
+ var e_1, _a;
91
+ return __awaiter(this, void 0, void 0, function* () {
92
+ if (__classPrivateFieldGet(this, _branch, "f"))
93
+ return __classPrivateFieldGet(this, _branch, "f");
94
+ if (!param)
95
+ return undefined;
96
+ const strategies = Array.isArray(param) ? [...param] : [param];
97
+ const evaluateBranch = (strategy) => __awaiter(this, void 0, void 0, function* () {
98
+ return (0, branches_1.isBranchStrategyBuilder)(strategy) ? yield strategy() : strategy;
99
+ });
100
+ try {
101
+ for (var strategies_1 = __asyncValues(strategies), strategies_1_1; strategies_1_1 = yield strategies_1.next(), !strategies_1_1.done;) {
102
+ const strategy = strategies_1_1.value;
103
+ const branch = yield evaluateBranch(strategy);
104
+ if (branch) {
105
+ __classPrivateFieldSet(this, _branch, branch, "f");
106
+ return branch;
107
+ }
108
+ }
109
+ }
110
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
111
+ finally {
112
+ try {
113
+ if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) yield _a.call(strategies_1);
114
+ }
115
+ finally { if (e_1) throw e_1.error; }
116
+ }
117
+ });
118
+ },
119
+ _a;
120
+ };
121
+ exports.buildClient = buildClient;
122
+ class BaseClient extends (0, exports.buildClient)() {
123
+ }
124
+ exports.BaseClient = BaseClient;
package/dist/index.d.ts CHANGED
@@ -3,4 +3,7 @@ export declare class XataError extends Error {
3
3
  constructor(message: string, status: number);
4
4
  }
5
5
  export * from './api';
6
+ export * from './client';
6
7
  export * from './schema';
8
+ export * from './search';
9
+ export * from './util/config';
package/dist/index.js CHANGED
@@ -23,4 +23,7 @@ class XataError extends Error {
23
23
  }
24
24
  exports.XataError = XataError;
25
25
  __exportStar(require("./api"), exports);
26
+ __exportStar(require("./client"), exports);
26
27
  __exportStar(require("./schema"), exports);
28
+ __exportStar(require("./search"), exports);
29
+ __exportStar(require("./util/config"), exports);
@@ -0,0 +1,7 @@
1
+ import { FetcherExtraProps } from './api/fetcher';
2
+ export declare abstract class Namespace {
3
+ abstract build(options: NamespaceBuildOptions): unknown;
4
+ }
5
+ export declare type NamespaceBuildOptions = {
6
+ getFetchProps: () => Promise<FetcherExtraProps>;
7
+ };
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Namespace = void 0;
4
+ class Namespace {
5
+ }
6
+ exports.Namespace = Namespace;