@webex/byods 0.0.0-next.1

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 (36) hide show
  1. package/README.md +66 -0
  2. package/dist/Errors/catalog/ExtendedError.js +24 -0
  3. package/dist/Errors/types.js +32 -0
  4. package/dist/Logger/index.js +202 -0
  5. package/dist/Logger/types.js +31 -0
  6. package/dist/base-client/index.js +182 -0
  7. package/dist/byods/index.js +127 -0
  8. package/dist/constants.js +25 -0
  9. package/dist/data-source-client/constants.js +7 -0
  10. package/dist/data-source-client/index.js +205 -0
  11. package/dist/data-source-client/types.js +5 -0
  12. package/dist/http-client/types.js +5 -0
  13. package/dist/http-utils/index.js +140 -0
  14. package/dist/index.js +48 -0
  15. package/dist/token-manager/index.js +232 -0
  16. package/dist/token-storage-adapter/index.js +80 -0
  17. package/dist/token-storage-adapter/types.js +5 -0
  18. package/dist/types/Errors/catalog/ExtendedError.d.ts +14 -0
  19. package/dist/types/Errors/types.d.ts +32 -0
  20. package/dist/types/Logger/index.d.ts +71 -0
  21. package/dist/types/Logger/types.d.ts +27 -0
  22. package/dist/types/base-client/index.d.ts +91 -0
  23. package/dist/types/byods/index.d.ts +43 -0
  24. package/dist/types/constants.d.ts +17 -0
  25. package/dist/types/data-source-client/constants.d.ts +1 -0
  26. package/dist/types/data-source-client/index.d.ts +87 -0
  27. package/dist/types/data-source-client/types.d.ts +108 -0
  28. package/dist/types/http-client/types.d.ts +53 -0
  29. package/dist/types/http-utils/index.d.ts +70 -0
  30. package/dist/types/index.d.ts +8 -0
  31. package/dist/types/token-manager/index.d.ts +101 -0
  32. package/dist/types/token-storage-adapter/index.d.ts +54 -0
  33. package/dist/types/token-storage-adapter/types.d.ts +46 -0
  34. package/dist/types/types.d.ts +112 -0
  35. package/dist/types.js +5 -0
  36. package/package.json +121 -0
package/README.md ADDED
@@ -0,0 +1,66 @@
1
+ ### Bring Your Own Data Source (BYoDS) Node.JS SDK
2
+
3
+ ### Table of Contents
4
+
5
+ - [Getting Started](#getting-started)
6
+ - [Developing](#developing)
7
+ - [Building](#building)
8
+ - [Testing](#testing)
9
+ - [Samples](#samples)
10
+ - [Consuming SDK](#consuming-sdk)
11
+ - [NPM](#npm)
12
+
13
+ ---
14
+
15
+ ## Getting Started
16
+
17
+ The BYoDS Node.js SDK makes it easy for developers to register their data sources to the BYoDS system. It allows developers to build data sources without needing to manage the complexities of integration. With features like customizable storage, service app token management, and auto refresh of JWS tokens. The BYoDS SDK provides a solid foundation for creating secure and reliable data sources.
18
+
19
+ ## Developing
20
+
21
+ ```bash
22
+ git clone https://github.com/\<your-fork\>/webex-js-sdk.git
23
+ cd web-js-sdk/
24
+ yarn install
25
+ ```
26
+
27
+ ## Building
28
+
29
+ If your project needs some additional steps for the developer to build the
30
+ project after some code changes, state them here:
31
+
32
+ ```bash
33
+ yarn workspace @webex/byods run build:src
34
+ ```
35
+
36
+ ## Testing
37
+
38
+ ```bash
39
+ yarn workspace @webex/byods run test:unit
40
+ ```
41
+
42
+ ## Samples
43
+
44
+ ```bash
45
+ yarn workspace @webex/byods-demo-server dev:hot
46
+ ```
47
+
48
+ ## Consuming SDK
49
+
50
+ To consume the latest stable version of the BYoDS SDK, you can use NPM.
51
+
52
+ # NPM
53
+
54
+ ```javascript
55
+ npm install @webex/byods
56
+ ```
57
+
58
+ (or)
59
+
60
+ ```javascript
61
+ yarn add @webex/byods
62
+ ```
63
+
64
+ ```javascript
65
+ import BYoDS from '@webex/byods';
66
+ ```
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _types = require("../types");
8
+ /**
9
+ *
10
+ */
11
+ class ExtendedError extends Error {
12
+ /**
13
+ * Constructs an ExtendedError instance.
14
+ *
15
+ * @param msg - The error message.
16
+ * @param type - The type of the error.
17
+ */
18
+ constructor(msg, type = _types.ERROR_TYPE.DEFAULT) {
19
+ super(msg);
20
+ this.type = type;
21
+ Object.setPrototypeOf(this, ExtendedError.prototype);
22
+ }
23
+ }
24
+ exports.default = ExtendedError;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.ERROR_TYPE = exports.ERROR_CODE = void 0;
7
+ let ERROR_TYPE = exports.ERROR_TYPE = /*#__PURE__*/function (ERROR_TYPE) {
8
+ ERROR_TYPE["DEFAULT"] = "default_error";
9
+ ERROR_TYPE["FORBIDDEN_ERROR"] = "forbidden";
10
+ ERROR_TYPE["NOT_FOUND"] = "not_found";
11
+ ERROR_TYPE["REGISTRATION_ERROR"] = "registration_error";
12
+ ERROR_TYPE["SERVICE_UNAVAILABLE"] = "service_unavailable";
13
+ ERROR_TYPE["TIMEOUT"] = "timeout";
14
+ ERROR_TYPE["TOKEN_ERROR"] = "token_error";
15
+ ERROR_TYPE["SERVER_ERROR"] = "server_error";
16
+ ERROR_TYPE["SCHEDULE_JWS_TOKEN_REFRESH_ERROR"] = "schedule_jws_token_refresh_error";
17
+ ERROR_TYPE["START_AUTO_REFRESH_ERROR"] = "start_auto_refresh_error";
18
+ return ERROR_TYPE;
19
+ }({});
20
+ let ERROR_CODE = exports.ERROR_CODE = /*#__PURE__*/function (ERROR_CODE) {
21
+ ERROR_CODE[ERROR_CODE["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
22
+ ERROR_CODE[ERROR_CODE["FORBIDDEN"] = 403] = "FORBIDDEN";
23
+ ERROR_CODE[ERROR_CODE["DEVICE_NOT_FOUND"] = 404] = "DEVICE_NOT_FOUND";
24
+ ERROR_CODE[ERROR_CODE["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
25
+ ERROR_CODE[ERROR_CODE["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED";
26
+ ERROR_CODE[ERROR_CODE["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
27
+ ERROR_CODE[ERROR_CODE["BAD_REQUEST"] = 400] = "BAD_REQUEST";
28
+ ERROR_CODE[ERROR_CODE["REQUEST_TIMEOUT"] = 408] = "REQUEST_TIMEOUT";
29
+ ERROR_CODE[ERROR_CODE["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS";
30
+ return ERROR_CODE;
31
+ }({}); // Disable ESLint for empty interface as it may be extended in the future
32
+ // eslint-disable-next-line @typescript-eslint/no-empty-interface
@@ -0,0 +1,202 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _constants = require("../constants");
8
+ var _types = require("./types");
9
+ /* eslint-disable valid-jsdoc */
10
+
11
+ class Logger {
12
+ currentLogLevel = _types.LOGGING_LEVEL.error;
13
+
14
+ /**
15
+ * A wrapper around console which prints
16
+ * based on the level defined.
17
+ *
18
+ * @param message - Log Message to print.
19
+ * @param level - Log level.
20
+ */
21
+ writeToConsole(message, level) {
22
+ switch (level) {
23
+ case _types.LOGGER.INFO:
24
+ case _types.LOGGER.LOG:
25
+ {
26
+ // eslint-disable-next-line no-console
27
+ console.log(message);
28
+ break;
29
+ }
30
+ case _types.LOGGER.WARN:
31
+ {
32
+ console.warn(message);
33
+ break;
34
+ }
35
+ case _types.LOGGER.ERROR:
36
+ {
37
+ console.error(message);
38
+ break;
39
+ }
40
+ case _types.LOGGER.TRACE:
41
+ {
42
+ // eslint-disable-next-line no-console
43
+ console.trace(message);
44
+ break;
45
+ }
46
+ default:
47
+ {
48
+ // Since this is internal , we shouldn't reach here
49
+ }
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Format the Log message as 'timestamp BYODS SDK - [level]: file:example.ts - method:methodName - Actual log message'.
55
+ *
56
+ * @param context - File and method.
57
+ * @param level - Log level.
58
+ * @returns - Formatted string.
59
+ */
60
+ format(context, level) {
61
+ const timestamp = new Date().toUTCString();
62
+ return `${_constants.BYODS_PACKAGE_NAME}: ${timestamp}: ${level}: ${_types.LOG_PREFIX.FILE}:${context.file} - ${_types.LOG_PREFIX.METHOD}:${context.method}`;
63
+ }
64
+
65
+ /**
66
+ * Used to initialize the logger module
67
+ * with a certain level.
68
+ *
69
+ * @param level - Log Level.
70
+ */
71
+ setLogger(level, module) {
72
+ switch (level) {
73
+ case _types.LOGGER.WARN:
74
+ {
75
+ this.currentLogLevel = _types.LOGGING_LEVEL.warn;
76
+ break;
77
+ }
78
+ case _types.LOGGER.LOG:
79
+ {
80
+ this.currentLogLevel = _types.LOGGING_LEVEL.log;
81
+ break;
82
+ }
83
+ case _types.LOGGER.INFO:
84
+ {
85
+ this.currentLogLevel = _types.LOGGING_LEVEL.info;
86
+ break;
87
+ }
88
+ case _types.LOGGER.TRACE:
89
+ {
90
+ this.currentLogLevel = _types.LOGGING_LEVEL.trace;
91
+ break;
92
+ }
93
+ default:
94
+ {
95
+ this.currentLogLevel = _types.LOGGING_LEVEL.error;
96
+ }
97
+ }
98
+ const message = `Logger initialized for module: ${module} with level: ${this.currentLogLevel}`;
99
+ this.writeToConsole(`${this.format({
100
+ file: 'logger.ts',
101
+ method: 'setLogger'
102
+ }, '')} - ${_types.LOG_PREFIX.MESSAGE}:${message}`, _types.LOGGER.INFO);
103
+ }
104
+
105
+ /**
106
+ * To retrieve the current log level.
107
+ *
108
+ * @returns - Log level.
109
+ */
110
+ getLogLevel() {
111
+ let level;
112
+ switch (this.currentLogLevel) {
113
+ case _types.LOGGING_LEVEL.warn:
114
+ {
115
+ level = _types.LOGGER.WARN;
116
+ break;
117
+ }
118
+ case _types.LOGGING_LEVEL.log:
119
+ {
120
+ level = _types.LOGGER.LOG;
121
+ break;
122
+ }
123
+ case _types.LOGGING_LEVEL.info:
124
+ {
125
+ level = _types.LOGGER.INFO;
126
+ break;
127
+ }
128
+ case _types.LOGGING_LEVEL.trace:
129
+ {
130
+ level = _types.LOGGER.TRACE;
131
+ break;
132
+ }
133
+ default:
134
+ {
135
+ level = _types.LOGGER.ERROR;
136
+ }
137
+ }
138
+ return level;
139
+ }
140
+
141
+ /**
142
+ * Can be used to print only useful information.
143
+ *
144
+ * @param message - Caller emitted string.
145
+ * @param context - File and method which called.
146
+ */
147
+ log(message, context) {
148
+ if (this.currentLogLevel >= _types.LOGGING_LEVEL.log) {
149
+ this.writeToConsole(`${this.format(context, '[LOG]')} - ${_types.LOG_PREFIX.MESSAGE}:${message}`, _types.LOGGER.LOG);
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Can be used to print informational messages.
155
+ *
156
+ * @param message - Caller emitted string.
157
+ * @param context - File and method which called.
158
+ */
159
+ info(message, context) {
160
+ if (this.currentLogLevel >= _types.LOGGING_LEVEL.info) {
161
+ this.writeToConsole(`${this.format(context, '[INFO]')} - ${_types.LOG_PREFIX.MESSAGE}:${message}`, _types.LOGGER.INFO);
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Can be used to print warning messages.
167
+ *
168
+ * @param message - Caller emitted string.
169
+ * @param context - File and method which called.
170
+ */
171
+ warn(message, context) {
172
+ if (this.currentLogLevel >= _types.LOGGING_LEVEL.warn) {
173
+ this.writeToConsole(`${this.format(context, '[WARN]')} - ${_types.LOG_PREFIX.MESSAGE}:${message}`, _types.LOGGER.WARN);
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Can be used to print the stack trace of the entire call path.
179
+ *
180
+ * @param message - Caller emitted string.
181
+ * @param context - File and method which called.
182
+ */
183
+ trace(message, context) {
184
+ if (this.currentLogLevel >= _types.LOGGING_LEVEL.trace) {
185
+ this.writeToConsole(`${this.format(context, '[TRACE]')} - ${_types.LOG_PREFIX.MESSAGE}:${message}`, _types.LOGGER.TRACE);
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Can be used to print only errors.
191
+ *
192
+ * @param error - Error string .
193
+ * @param context - File and method which called.
194
+ */
195
+ error(error, context) {
196
+ if (this.currentLogLevel >= _types.LOGGING_LEVEL.error) {
197
+ this.writeToConsole(`${this.format(context, '[ERROR]')} - !${_types.LOG_PREFIX.ERROR}!${_types.LOG_PREFIX.MESSAGE}:${error.message}`, _types.LOGGER.ERROR);
198
+ }
199
+ }
200
+ }
201
+ const log = new Logger();
202
+ var _default = exports.default = log;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.LOG_PREFIX = exports.LOGGING_LEVEL = exports.LOGGER = void 0;
7
+ let LOG_PREFIX = exports.LOG_PREFIX = /*#__PURE__*/function (LOG_PREFIX) {
8
+ LOG_PREFIX["MAIN"] = "BYODOS_SDK";
9
+ LOG_PREFIX["FILE"] = "file";
10
+ LOG_PREFIX["METHOD"] = "method";
11
+ LOG_PREFIX["EVENT"] = "event";
12
+ LOG_PREFIX["MESSAGE"] = "message";
13
+ LOG_PREFIX["ERROR"] = "error";
14
+ return LOG_PREFIX;
15
+ }({});
16
+ let LOGGING_LEVEL = exports.LOGGING_LEVEL = /*#__PURE__*/function (LOGGING_LEVEL) {
17
+ LOGGING_LEVEL[LOGGING_LEVEL["error"] = 1] = "error";
18
+ LOGGING_LEVEL[LOGGING_LEVEL["warn"] = 2] = "warn";
19
+ LOGGING_LEVEL[LOGGING_LEVEL["log"] = 3] = "log";
20
+ LOGGING_LEVEL[LOGGING_LEVEL["info"] = 4] = "info";
21
+ LOGGING_LEVEL[LOGGING_LEVEL["trace"] = 5] = "trace";
22
+ return LOGGING_LEVEL;
23
+ }({});
24
+ let LOGGER = exports.LOGGER = /*#__PURE__*/function (LOGGER) {
25
+ LOGGER["ERROR"] = "error";
26
+ LOGGER["WARN"] = "warn";
27
+ LOGGER["INFO"] = "info";
28
+ LOGGER["LOG"] = "log";
29
+ LOGGER["TRACE"] = "trace";
30
+ return LOGGER;
31
+ }({});
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _dataSourceClient = _interopRequireDefault(require("../data-source-client"));
8
+ var _httpUtils = require("../http-utils");
9
+ var _constants = require("../constants");
10
+ var _Logger = _interopRequireDefault(require("../Logger"));
11
+ var _ExtendedError = _interopRequireDefault(require("../Errors/catalog/ExtendedError"));
12
+ var _types = require("../Errors/types");
13
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
+ class BaseClient {
15
+ /**
16
+ * Creates an instance of BaseClient.
17
+ * @param {string} baseUrl - The base URL for the API.
18
+ * @param {Record<string, string>} headers - The additional headers to be used in requests.
19
+ * @param {TokenManager} tokenManager - The token manager instance.
20
+ * @param {string} orgId - The organization ID.
21
+ * @example
22
+ * const client = new BaseClient('https://webexapis.com/v1', { 'Your-Custom-Header': 'some value' }, tokenManager, 'org123');
23
+ */
24
+ constructor(baseUrl, headers, tokenManager, orgId, loggerConfig = _constants.DEFAULT_LOGGER_CONFIG) {
25
+ this.baseUrl = baseUrl;
26
+ this.headers = headers;
27
+ this.tokenManager = tokenManager;
28
+ this.orgId = orgId;
29
+ this.dataSource = new _dataSourceClient.default(this.getHttpClientForOrg());
30
+ this.loggerConfig = loggerConfig;
31
+ _Logger.default.setLogger(this.loggerConfig.level, _constants.BYODS_BASE_CLIENT_MODULE);
32
+ }
33
+
34
+ /**
35
+ * Makes an HTTP request.
36
+ * @param {string} endpoint - The API endpoint.
37
+ * @param {HttpRequestInit} [options={}] - The request options.
38
+ * @returns {Promise<ApiResponse<T>>} - The API response.
39
+ * @template T
40
+ * @example
41
+ * const response = await client.request('/endpoint', { method: 'GET', headers: {} });
42
+ */
43
+ async request(endpoint, options = {}) {
44
+ const url = `${this.baseUrl}${endpoint}`;
45
+ const token = await this.getToken();
46
+ return _httpUtils.httpUtils.request(url, {
47
+ ...options,
48
+ headers: {
49
+ ...this.headers,
50
+ ...options.headers,
51
+ Authorization: `Bearer ${token}`
52
+ }
53
+ });
54
+ }
55
+
56
+ /**
57
+ * Makes a POST request.
58
+ * @param {string} endpoint - The API endpoint.
59
+ * @param {Record<string, any>} body - The request body.
60
+ * @param {Record<string, string>} [headers={}] - The request headers.
61
+ * @returns {Promise<ApiResponse<T>>} - The API response.
62
+ * @template T
63
+ * @example
64
+ * const response = await client.post('/endpoint', { key: 'value' });
65
+ */
66
+ async post(endpoint, body, headers = {}) {
67
+ return this.request(endpoint, {
68
+ method: 'POST',
69
+ body: JSON.stringify(body),
70
+ headers: {
71
+ 'Content-Type': 'application/json',
72
+ ...headers
73
+ }
74
+ });
75
+ }
76
+
77
+ /**
78
+ * Makes a PUT request.
79
+ * @param {string} endpoint - The API endpoint.
80
+ * @param {Record<string, any>} body - The request body.
81
+ * @returns {Promise<ApiResponse<T>>} - The API response.
82
+ * @template T
83
+ * @example
84
+ * const response = await client.put('/endpoint', { key: 'value' });
85
+ */
86
+ async put(endpoint, body, headers = {}) {
87
+ return this.request(endpoint, {
88
+ method: 'PUT',
89
+ body: JSON.stringify(body),
90
+ headers: {
91
+ 'Content-Type': 'application/json',
92
+ ...headers
93
+ }
94
+ });
95
+ }
96
+
97
+ /**
98
+ * Makes a PATCH request.
99
+ * @param {string} endpoint - The API endpoint.
100
+ * @param {Record<string, any>} body - The request body.
101
+ * @returns {Promise<ApiResponse<T>>} - The API response.
102
+ * @template T
103
+ * @example
104
+ * const response = await client.patch('/endpoint', { key: 'value' });
105
+ */
106
+ async patch(endpoint, body, headers = {}) {
107
+ return this.request(endpoint, {
108
+ method: 'PATCH',
109
+ body: JSON.stringify(body),
110
+ headers: {
111
+ 'Content-Type': 'application/json',
112
+ ...headers
113
+ }
114
+ });
115
+ }
116
+
117
+ /**
118
+ * Makes a GET request.
119
+ * @param {string} endpoint - The API endpoint.
120
+ * @returns {Promise<ApiResponse<T>>} - The API response.
121
+ * @template T
122
+ * @example
123
+ * const response = await client.get('/endpoint');
124
+ */
125
+ async get(endpoint, headers = {}) {
126
+ return this.request(endpoint, {
127
+ method: 'GET',
128
+ headers
129
+ });
130
+ }
131
+
132
+ /**
133
+ * Makes a DELETE request.
134
+ * @param {string} endpoint - The API endpoint.
135
+ * @returns {Promise<ApiResponse<T>>} - The API response.
136
+ * @template T
137
+ * @example
138
+ * const response = await client.delete('/endpoint');
139
+ */
140
+ async delete(endpoint, headers = {}) {
141
+ return this.request(endpoint, {
142
+ method: 'DELETE',
143
+ headers
144
+ });
145
+ }
146
+
147
+ /**
148
+ * Get an HTTP client for a specific organization.
149
+ * @returns {HttpClient} - An object containing methods for making HTTP requests.
150
+ * @example
151
+ * const httpClient = client.getHttpClientForOrg();
152
+ * const response = await httpClient.get('/endpoint');
153
+ */
154
+ getHttpClientForOrg() {
155
+ return {
156
+ get: endpoint => this.get(endpoint),
157
+ delete: endpoint => this.delete(endpoint),
158
+ post: (endpoint, body) => this.post(endpoint, body),
159
+ put: (endpoint, body) => this.put(endpoint, body),
160
+ patch: (endpoint, body) => this.patch(endpoint, body)
161
+ };
162
+ }
163
+ async getToken() {
164
+ try {
165
+ const serviceAppAuthorization = await this.tokenManager.getOrgServiceAppAuthorization(this.orgId);
166
+ let token = serviceAppAuthorization.serviceAppToken.accessToken;
167
+ if (new Date() >= new Date(serviceAppAuthorization.serviceAppToken.expiresAt)) {
168
+ await this.tokenManager.refreshServiceAppAccessToken(this.orgId, this.headers);
169
+ const refreshedAuthorization = await this.tokenManager.getOrgServiceAppAuthorization(this.orgId);
170
+ token = refreshedAuthorization.serviceAppToken.accessToken;
171
+ }
172
+ return token;
173
+ } catch (error) {
174
+ _Logger.default.error(new _ExtendedError.default('Error obtaining token', _types.ERROR_TYPE.TOKEN_ERROR), {
175
+ file: _constants.BYODS_BASE_CLIENT_MODULE,
176
+ method: 'getToken'
177
+ });
178
+ throw new Error('Failed to obtain token');
179
+ }
180
+ }
181
+ }
182
+ exports.default = BaseClient;
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _jose = require("jose");
8
+ var _baseClient = _interopRequireDefault(require("../base-client"));
9
+ var _constants = require("../constants");
10
+ var _tokenManager = _interopRequireDefault(require("../token-manager"));
11
+ var _Logger = _interopRequireDefault(require("../Logger"));
12
+ var _types = require("../Logger/types");
13
+ var _types2 = require("../Errors/types");
14
+ var _ExtendedError = _interopRequireDefault(require("../Errors/catalog/ExtendedError"));
15
+ var _tokenStorageAdapter = require("../token-storage-adapter");
16
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
+ /**
18
+ * The BYoDS SDK.
19
+ */
20
+ class BYODS {
21
+ headers = {
22
+ 'User-Agent': _constants.USER_AGENT
23
+ };
24
+ jwksCache = {};
25
+ // No defined interface for return type of createRemoteJWKSet
26
+
27
+ /**
28
+ * The token manager for the SDK.
29
+ */
30
+
31
+ /**
32
+ * Constructs a new instance of the BYODS SDK.
33
+ *
34
+ * @param {SDKConfig} config - The configuration object containing clientId and clientSecret.
35
+ * @example
36
+ * const sdk = new BYODS({ clientId: 'your-client-id', clientSecret: 'your-client-secret' });
37
+ */
38
+ constructor({
39
+ clientId,
40
+ clientSecret,
41
+ tokenStorageAdapter = new _tokenStorageAdapter.InMemoryTokenStorageAdapter(),
42
+ logger = _constants.DEFAULT_LOGGER_CONFIG
43
+ }) {
44
+ this.config = {
45
+ clientId,
46
+ clientSecret,
47
+ tokenStorageAdapter,
48
+ logger
49
+ };
50
+ _Logger.default.setLogger(this.config.logger?.level || _types.LOGGER.INFO, _constants.BYODS_MODULE);
51
+
52
+ /**
53
+ * The environment variable `process.env.BYODS_ENVIRONMENT` determines the environment in which the SDK operates.
54
+ * It can be set to either 'production' or 'integration'. If not set, it defaults to 'production'.
55
+ */
56
+ const parsedEnv = process.env.BYODS_ENVIRONMENT || 'production';
57
+ let jwksUrl = _constants.PRODUCTION_JWKS_URL;
58
+ switch (parsedEnv) {
59
+ case 'production':
60
+ this.env = 'production';
61
+ this.baseUrl = _constants.PRODUCTION_BASE_URL;
62
+ jwksUrl = _constants.PRODUCTION_JWKS_URL;
63
+ break;
64
+ case 'integration':
65
+ this.env = 'integration';
66
+ this.baseUrl = _constants.INTEGRATION_BASE_URL;
67
+ jwksUrl = _constants.INTEGRATION_JWKS_URL;
68
+ break;
69
+ default:
70
+ this.env = 'production';
71
+ this.baseUrl = _constants.PRODUCTION_BASE_URL;
72
+ jwksUrl = _constants.PRODUCTION_JWKS_URL;
73
+ }
74
+
75
+ // Create token manager
76
+ this.tokenManager = new _tokenManager.default(clientId, clientSecret, this.baseUrl, tokenStorageAdapter, this.config.logger);
77
+
78
+ // Create a remote JWK Set
79
+ this.jwks = (0, _jose.createRemoteJWKSet)(new URL(jwksUrl), {
80
+ [_jose.jwksCache]: this.jwksCache,
81
+ cacheMaxAge: 600000,
82
+ // 10 minutes
83
+ cooldownDuration: 30000 // 30 seconds
84
+ });
85
+ }
86
+
87
+ /**
88
+ * Verifies a JWS token using the public key.
89
+ * @param {string} jws - The JWS token to verify.
90
+ * @returns {Promise<JWSTokenVerificationResult>} A promise that resolves to an object containing the result of the verification.
91
+ * @example
92
+ * const result = await sdk.verifyJWSToken('jws-token');
93
+ */
94
+ async verifyJWSToken(jws) {
95
+ const result = {
96
+ isValid: false
97
+ };
98
+ try {
99
+ await (0, _jose.jwtVerify)(jws, this.jwks);
100
+ result.isValid = true;
101
+ } catch (error) {
102
+ _Logger.default.error(new _ExtendedError.default('Error verifying JWS token', _types2.ERROR_TYPE.TOKEN_ERROR), {
103
+ file: _constants.BYODS_MODULE,
104
+ method: 'verifyJWSToken'
105
+ });
106
+ result.isValid = false;
107
+ result.error = error.message || 'Unknown error';
108
+ }
109
+ return result;
110
+ }
111
+
112
+ /**
113
+ * Retrieves a client instance for a specific organization.
114
+ *
115
+ * @param {string} orgId - The unique identifier of the organization.
116
+ * @returns {BaseClient} A new instance of BaseClient configured for the specified organization.
117
+ * @example
118
+ * const client = sdk.getClientForOrg('org-id');
119
+ */
120
+ getClientForOrg(orgId) {
121
+ if (!orgId) {
122
+ throw new Error(`orgId is required`);
123
+ }
124
+ return new _baseClient.default(this.baseUrl, this.headers, this.tokenManager, orgId);
125
+ }
126
+ }
127
+ exports.default = BYODS;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.USER_AGENT = exports.PRODUCTION_JWKS_URL = exports.PRODUCTION_BASE_URL = exports.INTEGRATION_JWKS_URL = exports.INTEGRATION_BASE_URL = exports.DEFAULT_LOGGER_CONFIG = exports.BYODS_TOKEN_MANAGER_MODULE = exports.BYODS_SDK_VERSION = exports.BYODS_PACKAGE_NAME = exports.BYODS_MODULE = exports.BYODS_FILE = exports.BYODS_DATA_SOURCE_CLIENT_MODULE = exports.BYODS_BASE_CLIENT_MODULE = exports.APPLICATION_ID_PREFIX = void 0;
7
+ var _os = _interopRequireDefault(require("os"));
8
+ var _types = require("./Logger/types");
9
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
10
+ const BYODS_FILE = exports.BYODS_FILE = 'BYODS';
11
+ const BYODS_SDK_VERSION = exports.BYODS_SDK_VERSION = '0.0.1';
12
+ const BYODS_PACKAGE_NAME = exports.BYODS_PACKAGE_NAME = 'BYoDS NodeJS SDK';
13
+ const USER_AGENT = exports.USER_AGENT = `${BYODS_PACKAGE_NAME}/(${_os.default.type()}; ${_os.default.platform()}; ${_os.default.arch()}; Node.js/${process.version})`;
14
+ const PRODUCTION_BASE_URL = exports.PRODUCTION_BASE_URL = 'https://webexapis.com/v1';
15
+ const INTEGRATION_BASE_URL = exports.INTEGRATION_BASE_URL = 'https://integration.webexapis.com/v1';
16
+ const PRODUCTION_JWKS_URL = exports.PRODUCTION_JWKS_URL = 'https://idbroker.webex.com/idb/oauth2/v2/keys/verificationjwk';
17
+ const INTEGRATION_JWKS_URL = exports.INTEGRATION_JWKS_URL = 'https://idbrokerbts.webex.com/idb/oauth2/v2/keys/verificationjwk';
18
+ const APPLICATION_ID_PREFIX = exports.APPLICATION_ID_PREFIX = 'ciscospark://us/APPLICATION/';
19
+ const BYODS_BASE_CLIENT_MODULE = exports.BYODS_BASE_CLIENT_MODULE = 'base-client';
20
+ const BYODS_MODULE = exports.BYODS_MODULE = 'byods';
21
+ const BYODS_TOKEN_MANAGER_MODULE = exports.BYODS_TOKEN_MANAGER_MODULE = 'token-manager';
22
+ const BYODS_DATA_SOURCE_CLIENT_MODULE = exports.BYODS_DATA_SOURCE_CLIENT_MODULE = 'data-source-client';
23
+ const DEFAULT_LOGGER_CONFIG = exports.DEFAULT_LOGGER_CONFIG = {
24
+ level: _types.LOGGER.ERROR
25
+ };