@basis-theory/basis-theory-js 1.17.0 → 1.21.0

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/BasisTheory.d.ts CHANGED
@@ -1,13 +1,12 @@
1
- import type { AtomicBanks as ElementsAtomicBanks, AtomicCards as ElementsAtomicCards, BasisTheoryElements, CardElement, CustomizableElementOptions, ElementType, TextElement, Tokenize as ElementsTokenize, Tokens as ElementsTokens } from '@basis-theory/basis-theory-elements-interfaces/elements';
2
- import type { Applications, AtomicBanks, AtomicCards, BasisTheory as IBasisTheory, BasisTheoryInit, Logs, Permissions, ReactorFormulas, Reactors, Tenants, Tokenize, Tokens } from '@basis-theory/basis-theory-elements-interfaces/sdk';
3
- import { BasisTheoryEncryptionAdapters } from './encryption/BasisTheoryEncryptionAdapters';
1
+ import type { AtomicBanks as ElementsAtomicBanks, AtomicCards as ElementsAtomicCards, BasisTheoryElements, CardElement, CustomizableElementOptions, ElementType, TextElement, TokenizeData as ElementsTokenizeData, Tokens as ElementsTokens } from '@basis-theory/basis-theory-elements-interfaces/elements';
2
+ import type { TokenizeData } from '@basis-theory/basis-theory-elements-interfaces/models';
3
+ import type { Applications, AtomicBanks, AtomicCards, BasisTheory as IBasisTheory, BasisTheoryInit, Logs, Permissions, ReactorFormulas, Reactors, RequestOptions, Tenants, Tokens } from '@basis-theory/basis-theory-elements-interfaces/sdk';
4
4
  import type { BasisTheoryInitOptions, BasisTheoryInitOptionsWithElements, BasisTheoryInitOptionsWithoutElements } from './types';
5
5
  export declare class BasisTheory implements BasisTheoryInit, IBasisTheory, BasisTheoryElements {
6
6
  private _initStatus;
7
7
  private _initOptions?;
8
8
  private _tokens?;
9
9
  private _tokenize?;
10
- private _encryption?;
11
10
  private _elements?;
12
11
  private _applications?;
13
12
  private _tenants?;
@@ -20,14 +19,10 @@ export declare class BasisTheory implements BasisTheoryInit, IBasisTheory, Basis
20
19
  init(apiKey: string, options?: BasisTheoryInitOptionsWithoutElements): Promise<IBasisTheory>;
21
20
  init(apiKey: string, options: BasisTheoryInitOptionsWithElements): Promise<IBasisTheory & BasisTheoryElements>;
22
21
  createElement(type: ElementType, options: CustomizableElementOptions): CardElement | TextElement;
22
+ tokenize(tokens: TokenizeData & ElementsTokenizeData, options?: RequestOptions): Promise<TokenizeData>;
23
23
  private loadElements;
24
24
  get initOptions(): Required<BasisTheoryInitOptions>;
25
25
  get tokens(): Tokens & ElementsTokens;
26
- get tokenize(): Tokenize & ElementsTokenize;
27
- /**
28
- * @deprecated
29
- */
30
- get encryption(): BasisTheoryEncryptionAdapters;
31
26
  get applications(): Applications;
32
27
  get tenants(): Tenants;
33
28
  get logs(): Logs;
package/BasisTheory.js CHANGED
@@ -9,13 +9,9 @@ var _applications = require("./applications");
9
9
 
10
10
  var _common = require("./common");
11
11
 
12
- var _constants = require("./common/constants");
13
-
14
12
  var _elements = require("./elements");
15
13
 
16
- var _constants2 = require("./elements/constants");
17
-
18
- var _BasisTheoryEncryptionAdapters = require("./encryption/BasisTheoryEncryptionAdapters");
14
+ var _constants = require("./elements/constants");
19
15
 
20
16
  var _logs = require("./logs");
21
17
 
@@ -30,8 +26,9 @@ var _tenants = require("./tenants");
30
26
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
31
27
 
32
28
  const defaultInitOptions = {
33
- apiBaseUrl: _constants.DEFAULT_BASE_URL,
34
- elements: false
29
+ apiBaseUrl: _common.DEFAULT_BASE_URL,
30
+ elements: false,
31
+ appInfo: {}
35
32
  };
36
33
 
37
34
  class BasisTheory {
@@ -66,51 +63,62 @@ class BasisTheory {
66
63
  throw new Error('Invalid format for the given API base url.');
67
64
  }
68
65
 
66
+ const appInfo = this._initOptions.appInfo;
67
+
69
68
  if (this._initOptions.elements) {
70
69
  await this.loadElements(apiKey);
71
70
  }
72
71
 
73
72
  this._tokens = new ((0, _elements.delegateTokens)(this._elements))({
74
73
  apiKey,
75
- baseURL: new URL(_constants.CLIENT_BASE_PATHS.tokens, baseUrl).toString()
74
+ baseURL: new URL(_common.CLIENT_BASE_PATHS.tokens, baseUrl).toString(),
75
+ appInfo
76
76
  });
77
77
  this._tokenize = new ((0, _elements.delegateTokenize)(this._elements))({
78
78
  apiKey,
79
- baseURL: new URL(_constants.CLIENT_BASE_PATHS.tokenize, baseUrl).toString()
79
+ baseURL: new URL(_common.CLIENT_BASE_PATHS.tokenize, baseUrl).toString(),
80
+ appInfo
80
81
  });
81
82
  this._applications = new _applications.BasisTheoryApplications({
82
83
  apiKey,
83
- baseURL: new URL(_constants.CLIENT_BASE_PATHS.applications, baseUrl).toString()
84
+ baseURL: new URL(_common.CLIENT_BASE_PATHS.applications, baseUrl).toString(),
85
+ appInfo
84
86
  });
85
87
  this._tenants = new _tenants.BasisTheoryTenants({
86
88
  apiKey,
87
- baseURL: new URL(_constants.CLIENT_BASE_PATHS.tenants, baseUrl).toString()
89
+ baseURL: new URL(_common.CLIENT_BASE_PATHS.tenants, baseUrl).toString(),
90
+ appInfo
88
91
  });
89
92
  this._logs = new _logs.BasisTheoryLogs({
90
93
  apiKey,
91
- baseURL: new URL(_constants.CLIENT_BASE_PATHS.logs, baseUrl).toString()
94
+ baseURL: new URL(_common.CLIENT_BASE_PATHS.logs, baseUrl).toString(),
95
+ appInfo
92
96
  });
93
97
  this._reactorFormulas = new _reactorFormulas.BasisTheoryReactorFormulas({
94
98
  apiKey,
95
- baseURL: new URL(_constants.CLIENT_BASE_PATHS.reactorFormulas, baseUrl).toString()
99
+ baseURL: new URL(_common.CLIENT_BASE_PATHS.reactorFormulas, baseUrl).toString(),
100
+ appInfo
96
101
  });
97
102
  this._reactors = new _reactors.BasisTheoryReactors({
98
103
  apiKey,
99
- baseURL: new URL(_constants.CLIENT_BASE_PATHS.reactors, baseUrl).toString()
104
+ baseURL: new URL(_common.CLIENT_BASE_PATHS.reactors, baseUrl).toString(),
105
+ appInfo
100
106
  });
101
107
  this._atomicBanks = new ((0, _elements.delegateAtomicBanks)(this._elements))({
102
108
  apiKey,
103
- baseURL: new URL(_constants.CLIENT_BASE_PATHS.atomicBanks, baseUrl).toString()
109
+ baseURL: new URL(_common.CLIENT_BASE_PATHS.atomicBanks, baseUrl).toString(),
110
+ appInfo
104
111
  });
105
112
  this._atomicCards = new ((0, _elements.delegateAtomicCards)(this._elements))({
106
113
  apiKey,
107
- baseURL: new URL(_constants.CLIENT_BASE_PATHS.atomicCards, baseUrl).toString()
114
+ baseURL: new URL(_common.CLIENT_BASE_PATHS.atomicCards, baseUrl).toString(),
115
+ appInfo
108
116
  });
109
117
  this._permissions = new _permissions.BasisTheoryPermissions({
110
118
  apiKey,
111
- baseURL: new URL(_constants.CLIENT_BASE_PATHS.permissions, baseUrl).toString()
119
+ baseURL: new URL(_common.CLIENT_BASE_PATHS.permissions, baseUrl).toString(),
120
+ appInfo
112
121
  });
113
- this._encryption = new _BasisTheoryEncryptionAdapters.BasisTheoryEncryptionAdapters();
114
122
  this._initStatus = 'done';
115
123
  } catch (error) {
116
124
  this._initStatus = 'error';
@@ -122,7 +130,7 @@ class BasisTheory {
122
130
 
123
131
  createElement(type, options) {
124
132
  if (!this._elements) {
125
- throw new Error(_constants2.ELEMENTS_INIT_ERROR_MESSAGE);
133
+ throw new Error(_constants.ELEMENTS_INIT_ERROR_MESSAGE);
126
134
  } // the cast below is to avoid unnecessary conditional calls to elements
127
135
  // the underlying elements function called will be the same, no matter the
128
136
  // element type
@@ -131,11 +139,15 @@ class BasisTheory {
131
139
  return this._elements.createElement(type, options);
132
140
  }
133
141
 
142
+ tokenize(tokens, options) {
143
+ return (0, _common.assertInit)(this._tokenize).tokenize(tokens, options);
144
+ }
145
+
134
146
  async loadElements(apiKey) {
135
147
  let elementsBaseUrl;
136
148
 
137
149
  try {
138
- elementsBaseUrl = new URL(this.initOptions.elementsBaseUrl || _constants.DEFAULT_ELEMENTS_BASE_URL);
150
+ elementsBaseUrl = new URL(this.initOptions.elementsBaseUrl || _common.DEFAULT_ELEMENTS_BASE_URL);
139
151
  } catch {
140
152
  throw new Error('Invalid format for the given Elements base url.');
141
153
  }
@@ -156,18 +168,6 @@ class BasisTheory {
156
168
  return (0, _common.assertInit)(this._tokens);
157
169
  }
158
170
 
159
- get tokenize() {
160
- return (0, _common.assertInit)(this._tokenize);
161
- }
162
- /**
163
- * @deprecated
164
- */
165
-
166
-
167
- get encryption() {
168
- return (0, _common.assertInit)(this._encryption);
169
- }
170
-
171
171
  get applications() {
172
172
  return (0, _common.assertInit)(this._applications);
173
173
  }
@@ -1,7 +1,14 @@
1
1
  import type { ClientsBasePathMap } from '../types';
2
2
  declare const API_KEY_HEADER = "BT-API-KEY";
3
3
  declare const BT_TRACE_ID_HEADER = "bt-trace-id";
4
+ declare const USER_AGENT_HEADER = "User-Agent";
5
+ declare const CLIENT_USER_AGENT_HEADER = "BT-CLIENT-USER-AGENT";
6
+ declare const USER_AGENT_CLIENT = "BasisTheoryJS";
4
7
  declare const DEFAULT_BASE_URL: string;
5
8
  declare const DEFAULT_ELEMENTS_BASE_URL: string;
6
9
  declare const CLIENT_BASE_PATHS: ClientsBasePathMap;
7
- export { API_KEY_HEADER, BT_TRACE_ID_HEADER, DEFAULT_BASE_URL, DEFAULT_ELEMENTS_BASE_URL, CLIENT_BASE_PATHS, };
10
+ declare const BROWSER_LIST: {
11
+ browserName: string;
12
+ browserUA: string;
13
+ }[];
14
+ export { API_KEY_HEADER, BT_TRACE_ID_HEADER, USER_AGENT_HEADER, CLIENT_USER_AGENT_HEADER, USER_AGENT_CLIENT, DEFAULT_BASE_URL, DEFAULT_ELEMENTS_BASE_URL, CLIENT_BASE_PATHS, BROWSER_LIST, };
@@ -3,11 +3,17 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.DEFAULT_ELEMENTS_BASE_URL = exports.DEFAULT_BASE_URL = exports.CLIENT_BASE_PATHS = exports.BT_TRACE_ID_HEADER = exports.API_KEY_HEADER = void 0;
6
+ exports.USER_AGENT_HEADER = exports.USER_AGENT_CLIENT = exports.DEFAULT_ELEMENTS_BASE_URL = exports.DEFAULT_BASE_URL = exports.CLIENT_USER_AGENT_HEADER = exports.CLIENT_BASE_PATHS = exports.BT_TRACE_ID_HEADER = exports.BROWSER_LIST = exports.API_KEY_HEADER = void 0;
7
7
  const API_KEY_HEADER = 'BT-API-KEY';
8
8
  exports.API_KEY_HEADER = API_KEY_HEADER;
9
9
  const BT_TRACE_ID_HEADER = 'bt-trace-id';
10
10
  exports.BT_TRACE_ID_HEADER = BT_TRACE_ID_HEADER;
11
+ const USER_AGENT_HEADER = 'User-Agent';
12
+ exports.USER_AGENT_HEADER = USER_AGENT_HEADER;
13
+ const CLIENT_USER_AGENT_HEADER = 'BT-CLIENT-USER-AGENT';
14
+ exports.CLIENT_USER_AGENT_HEADER = CLIENT_USER_AGENT_HEADER;
15
+ const USER_AGENT_CLIENT = 'BasisTheoryJS';
16
+ exports.USER_AGENT_CLIENT = USER_AGENT_CLIENT;
11
17
  const DEFAULT_BASE_URL = `https://${"api.basistheory.com"}`;
12
18
  exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
13
19
  const DEFAULT_ELEMENTS_BASE_URL = `https://${"elements.basistheory.com"}`;
@@ -24,4 +30,33 @@ const CLIENT_BASE_PATHS = {
24
30
  atomicCards: 'atomic/cards',
25
31
  permissions: 'permissions'
26
32
  };
27
- exports.CLIENT_BASE_PATHS = CLIENT_BASE_PATHS;
33
+ exports.CLIENT_BASE_PATHS = CLIENT_BASE_PATHS;
34
+ const BROWSER_LIST = [{
35
+ browserName: 'Firefox',
36
+ browserUA: 'Firefox'
37
+ }, {
38
+ browserName: 'SamsungBrowser',
39
+ browserUA: 'SamsungBrowser'
40
+ }, {
41
+ browserName: 'Opera',
42
+ browserUA: 'Opera'
43
+ }, {
44
+ browserName: 'Opera',
45
+ browserUA: 'OPR'
46
+ }, {
47
+ browserName: 'Microsoft Internet Explorer',
48
+ browserUA: 'Trident'
49
+ }, {
50
+ browserName: 'Microsoft Edge (Legacy)',
51
+ browserUA: 'Edge'
52
+ }, {
53
+ browserName: 'Microsoft Edge (Chromium)',
54
+ browserUA: 'Edg'
55
+ }, {
56
+ browserName: 'Google Chrome/Chromium',
57
+ browserUA: 'Chrome'
58
+ }, {
59
+ browserName: 'Safari',
60
+ browserUA: 'Safari'
61
+ }];
62
+ exports.BROWSER_LIST = BROWSER_LIST;
package/common/utils.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { RequestOptions } from '@basis-theory/basis-theory-elements-interfaces/sdk/services';
2
2
  import type { AxiosRequestConfig, AxiosResponse, AxiosTransformer } from 'axios';
3
+ import type { ApplicationInfo } from '../types';
3
4
  declare const assertInit: <T>(prop: T) => NonNullable<T>;
4
5
  declare const transformRequestSnakeCase: AxiosTransformer;
5
6
  declare const proxyRaw: AxiosTransformer;
@@ -17,4 +18,9 @@ declare const concatResponseTransformermWithDefault: (responseTransformer: Axios
17
18
  declare const createRequestConfig: (options?: RequestOptions | undefined, transformers?: Pick<AxiosRequestConfig, "transformRequest" | "transformResponse"> | undefined) => AxiosRequestConfig | undefined;
18
19
  declare const errorInterceptor: (error: any) => void;
19
20
  declare const getQueryParams: <Q>(query: Q) => string;
20
- export { assertInit, transformRequestSnakeCase, proxyRaw, transformReactorRequestSnakeCase, transformAtomicRequestSnakeCase, transformTokenRequestSnakeCase, transformAtomicReactionRequestSnakeCase, transformTokenResponseCamelCase, transformReactorResponseCamelCase, transformResponseCamelCase, transformAtomicResponseCamelCase, dataExtractor, createRequestConfig, concatRequestTransformerWithDefault, concatResponseTransformermWithDefault, errorInterceptor, getQueryParams, };
21
+ declare const buildUserAgentString: (appInfo?: ApplicationInfo | undefined) => string;
22
+ declare const getBrowser: () => string;
23
+ declare const getOSVersion: () => string;
24
+ declare const getRuntime: () => string;
25
+ declare const buildClientUserAgentString: (appInfo?: ApplicationInfo | undefined) => string;
26
+ export { assertInit, transformRequestSnakeCase, proxyRaw, transformReactorRequestSnakeCase, transformAtomicRequestSnakeCase, transformTokenRequestSnakeCase, transformAtomicReactionRequestSnakeCase, transformTokenResponseCamelCase, transformReactorResponseCamelCase, transformResponseCamelCase, transformAtomicResponseCamelCase, dataExtractor, createRequestConfig, concatRequestTransformerWithDefault, concatResponseTransformermWithDefault, errorInterceptor, getQueryParams, buildUserAgentString, buildClientUserAgentString, getOSVersion, getRuntime, getBrowser, };
package/common/utils.js CHANGED
@@ -3,12 +3,14 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.transformTokenResponseCamelCase = exports.transformTokenRequestSnakeCase = exports.transformResponseCamelCase = exports.transformRequestSnakeCase = exports.transformReactorResponseCamelCase = exports.transformReactorRequestSnakeCase = exports.transformAtomicResponseCamelCase = exports.transformAtomicRequestSnakeCase = exports.transformAtomicReactionRequestSnakeCase = exports.proxyRaw = exports.getQueryParams = exports.errorInterceptor = exports.dataExtractor = exports.createRequestConfig = exports.concatResponseTransformermWithDefault = exports.concatRequestTransformerWithDefault = exports.assertInit = void 0;
6
+ exports.transformTokenResponseCamelCase = exports.transformTokenRequestSnakeCase = exports.transformResponseCamelCase = exports.transformRequestSnakeCase = exports.transformReactorResponseCamelCase = exports.transformReactorRequestSnakeCase = exports.transformAtomicResponseCamelCase = exports.transformAtomicRequestSnakeCase = exports.transformAtomicReactionRequestSnakeCase = exports.proxyRaw = exports.getRuntime = exports.getQueryParams = exports.getOSVersion = exports.getBrowser = exports.errorInterceptor = exports.dataExtractor = exports.createRequestConfig = exports.concatResponseTransformermWithDefault = exports.concatRequestTransformerWithDefault = exports.buildUserAgentString = exports.buildClientUserAgentString = exports.assertInit = void 0;
7
7
 
8
8
  var _axios = _interopRequireDefault(require("axios"));
9
9
 
10
10
  var _camelcaseKeys = _interopRequireDefault(require("camelcase-keys"));
11
11
 
12
+ var _os = _interopRequireDefault(require("os"));
13
+
12
14
  var _snakeCase = require("snake-case");
13
15
 
14
16
  var _snakecaseKeys = _interopRequireDefault(require("snakecase-keys"));
@@ -246,11 +248,12 @@ const getQueryParams = query => {
246
248
  if (keys.length) {
247
249
  const params = new URLSearchParams();
248
250
 
249
- const appendSafe = (key, value) => {
250
- const type = typeof value; // eslint-disable-next-line unicorn/no-null
251
+ const appendSafe = (key, value, isNested = false) => {
252
+ const type = typeof value;
253
+ const formattedKey = isNested ? key : (0, _snakeCase.snakeCase)(key); // eslint-disable-next-line unicorn/no-null
251
254
 
252
255
  if (value === null || ['boolean', 'number', 'string'].includes(type)) {
253
- params.append((0, _snakeCase.snakeCase)(key), value);
256
+ params.append(formattedKey, value);
254
257
  }
255
258
  };
256
259
 
@@ -261,6 +264,11 @@ const getQueryParams = query => {
261
264
  value.forEach(aValue => {
262
265
  appendSafe(String(key), aValue);
263
266
  });
267
+ } else if (value && typeof value === 'object') {
268
+ const objectKeys = Object.keys(value);
269
+ objectKeys.forEach(objectKey => {
270
+ appendSafe(`${key}.${objectKey}`, value[objectKey], true);
271
+ });
264
272
  } else {
265
273
  appendSafe(String(key), value);
266
274
  }
@@ -271,4 +279,96 @@ const getQueryParams = query => {
271
279
  return '';
272
280
  };
273
281
 
274
- exports.getQueryParams = getQueryParams;
282
+ exports.getQueryParams = getQueryParams;
283
+
284
+ const appInfoToUserAgentString = appInfo => `(${appInfo.name || ''}; ${appInfo.version || ''}; ${appInfo.url || ''})`;
285
+
286
+ const buildUserAgentString = appInfo => {
287
+ let userAgent = `${_constants.USER_AGENT_CLIENT}/${undefined || 'unknown'}`;
288
+
289
+ if (appInfo && Object.keys(appInfo || {}).length) {
290
+ userAgent += ` ${appInfoToUserAgentString(appInfo)}`;
291
+ }
292
+
293
+ return userAgent;
294
+ };
295
+
296
+ exports.buildUserAgentString = buildUserAgentString;
297
+
298
+ const getBrowser = () => {
299
+ const {
300
+ userAgent
301
+ } = window.navigator;
302
+ let version = 'unknown';
303
+
304
+ const browser = _constants.BROWSER_LIST.find(b => userAgent.includes(b.browserUA));
305
+
306
+ if (browser) {
307
+ try {
308
+ version = userAgent.split(`${browser.browserUA}/`)[1];
309
+ } catch {
310
+ version = 'unknown';
311
+ }
312
+ }
313
+
314
+ return `${(browser === null || browser === void 0 ? void 0 : browser.browserName) || 'unknown'}/${version}`;
315
+ };
316
+
317
+ exports.getBrowser = getBrowser;
318
+
319
+ const getOSVersion = () => {
320
+ // node
321
+ if (typeof window === 'undefined') {
322
+ try {
323
+ return `${_os.default.type()}/${_os.default.version()}`;
324
+ } catch {
325
+ return 'unknown';
326
+ }
327
+ } // browser
328
+
329
+
330
+ try {
331
+ const appVersionString = window.navigator.appVersion;
332
+ const osMatch = appVersionString.match(/\(([^)]+)\)/u);
333
+
334
+ if (osMatch && osMatch.length > 1) {
335
+ return osMatch[1];
336
+ }
337
+
338
+ return 'unknown';
339
+ } catch {
340
+ return 'unknown';
341
+ }
342
+ };
343
+
344
+ exports.getOSVersion = getOSVersion;
345
+
346
+ const getRuntime = () => {
347
+ // node
348
+ if (typeof window === 'undefined') {
349
+ return `NodeJS/${process.version}`;
350
+ } // browser
351
+
352
+
353
+ return getBrowser();
354
+ };
355
+
356
+ exports.getRuntime = getRuntime;
357
+
358
+ const buildClientUserAgentString = appInfo => {
359
+ const clientUserAgent = {
360
+ client: _constants.USER_AGENT_CLIENT,
361
+ clientVersion: undefined || 'unknown',
362
+ osVersion: getOSVersion(),
363
+ runtimeVersion: getRuntime(),
364
+ application: {}
365
+ };
366
+
367
+ if (appInfo) {
368
+ clientUserAgent.application = appInfo;
369
+ }
370
+
371
+ return JSON.stringify((0, _snakecaseKeys.default)(clientUserAgent));
372
+ };
373
+
374
+ exports.buildClientUserAgentString = buildClientUserAgentString;
@@ -10,7 +10,7 @@ var _tokenize = require("../../tokenize");
10
10
  const delegateTokenize = elements => class BasisTheoryTokenizesElementsDelegate extends _tokenize.BasisTheoryTokenize {
11
11
  tokenize(payload, requestOptions) {
12
12
  if (elements !== null && elements !== void 0 && elements.hasElement(payload)) {
13
- return elements.tokenize.tokenize(payload, requestOptions);
13
+ return elements.tokenize(payload, requestOptions);
14
14
  }
15
15
 
16
16
  return super.tokenize(payload, requestOptions);
package/index.d.ts CHANGED
@@ -5,6 +5,5 @@ import type { BasisTheoryInit } from '@basis-theory/basis-theory-elements-interf
5
5
  */
6
6
  export declare const _instance: BasisTheoryInit;
7
7
  export * from './BasisTheory';
8
- export * from './encryption';
9
8
  export * from './applications';
10
9
  export * from './tokens';
package/index.js CHANGED
@@ -22,20 +22,6 @@ Object.keys(_BasisTheory).forEach(function (key) {
22
22
  });
23
23
  });
24
24
 
25
- var _encryption = require("./encryption");
26
-
27
- Object.keys(_encryption).forEach(function (key) {
28
- if (key === "default" || key === "__esModule") return;
29
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
30
- if (key in exports && exports[key] === _encryption[key]) return;
31
- Object.defineProperty(exports, key, {
32
- enumerable: true,
33
- get: function () {
34
- return _encryption[key];
35
- }
36
- });
37
- });
38
-
39
25
  var _applications = require("./applications");
40
26
 
41
27
  Object.keys(_applications).forEach(function (key) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basis-theory/basis-theory-js",
3
- "version": "1.17.0",
3
+ "version": "1.21.0",
4
4
  "repository": "https://github.com/Basis-Theory/basis-theory-js",
5
5
  "license": "Apache-2.0",
6
6
  "author": {
@@ -15,7 +15,7 @@
15
15
  "!*.bundle.js"
16
16
  ],
17
17
  "dependencies": {
18
- "@basis-theory/basis-theory-elements-interfaces": "^2.2.0",
18
+ "@basis-theory/basis-theory-elements-interfaces": "^3.2.0",
19
19
  "axios": "^0.21.2",
20
20
  "camelcase-keys": "^6.2.2",
21
21
  "snake-case": "^3.0.4",
@@ -17,12 +17,15 @@ class BasisTheoryService {
17
17
  apiKey,
18
18
  baseURL,
19
19
  transformRequest,
20
- transformResponse
20
+ transformResponse,
21
+ appInfo
21
22
  } = options;
22
23
  this.client = _axios.default.create({
23
24
  baseURL,
24
25
  headers: {
25
- [_common.API_KEY_HEADER]: apiKey
26
+ [_common.API_KEY_HEADER]: apiKey,
27
+ [_common.USER_AGENT_HEADER]: (0, _common.buildUserAgentString)(appInfo),
28
+ [_common.CLIENT_USER_AGENT_HEADER]: (0, _common.buildClientUserAgentString)(appInfo)
26
29
  },
27
30
 
28
31
  /* eslint-disable unicorn/prefer-spread */
@@ -1,7 +1,9 @@
1
1
  import type { AxiosRequestConfig } from 'axios';
2
+ import type { ApplicationInfo } from '../types';
2
3
  interface BasisTheoryServiceOptions extends Pick<AxiosRequestConfig, 'transformRequest' | 'transformResponse'> {
3
4
  apiKey: string;
4
5
  baseURL: string;
6
+ appInfo?: ApplicationInfo;
5
7
  }
6
8
  declare type RequestTransformers = Pick<AxiosRequestConfig, 'transformRequest' | 'transformResponse'>;
7
9
  export type { BasisTheoryServiceOptions, RequestTransformers };
@@ -7,16 +7,14 @@ exports.BasisTheoryTokenize = void 0;
7
7
 
8
8
  var _common = require("../common");
9
9
 
10
- var _utils = require("../common/utils");
11
-
12
10
  var _service = require("../service");
13
11
 
14
12
  class BasisTheoryTokenize extends _service.BasisTheoryService {
15
13
  tokenize(tokens, options = {}) {
16
14
  return this.client.post('/', tokens, (0, _common.createRequestConfig)(options, {
17
- transformRequest: _utils.proxyRaw,
18
- transformResponse: _utils.proxyRaw
19
- })).then(_utils.dataExtractor);
15
+ transformRequest: _common.proxyRaw,
16
+ transformResponse: _common.proxyRaw
17
+ })).then(_common.dataExtractor);
20
18
  }
21
19
 
22
20
  }
package/types.d.ts CHANGED
@@ -7,16 +7,9 @@ declare type ClientsBasePathMap = {
7
7
  declare type Providers = 'BROWSER' | 'NODE';
8
8
  declare const algorithm: readonly ["RSA", "AES"];
9
9
  declare type Algorithm = typeof algorithm[number];
10
- interface EncryptionProviderOptions {
11
- defaultKeySize: number;
12
- keyExpirationInDays: number;
13
- }
14
- interface EncryptionOptions {
15
- algorithm: Algorithm;
16
- options?: EncryptionProviderOptions;
17
- }
18
10
  interface BasisTheoryInitOptions {
19
11
  apiBaseUrl?: string;
12
+ appInfo?: ApplicationInfo;
20
13
  }
21
14
  interface BasisTheoryInitOptionsWithoutElements extends BasisTheoryInitOptions {
22
15
  elements?: false;
@@ -25,10 +18,22 @@ interface BasisTheoryInitOptionsWithElements extends BasisTheoryInitOptions {
25
18
  elements: true;
26
19
  elementsBaseUrl?: string;
27
20
  }
21
+ interface ApplicationInfo {
22
+ name?: string;
23
+ version?: string;
24
+ url?: string;
25
+ }
26
+ interface ClientUserAgent {
27
+ client: string;
28
+ clientVersion: string;
29
+ osVersion: string;
30
+ runtimeVersion: string;
31
+ application?: ApplicationInfo;
32
+ }
28
33
  declare global {
29
34
  interface Window {
30
35
  BasisTheoryElements?: BasisTheoryElementsInternal;
31
36
  }
32
37
  }
33
38
  export { algorithm };
34
- export type { InitStatus, Clients, ClientsBasePathMap, Providers, Algorithm, EncryptionProviderOptions, EncryptionOptions, BasisTheoryInitOptions, BasisTheoryInitOptionsWithoutElements, BasisTheoryInitOptionsWithElements, };
39
+ export type { InitStatus, Clients, ClientsBasePathMap, Providers, Algorithm, BasisTheoryInitOptions, BasisTheoryInitOptionsWithoutElements, BasisTheoryInitOptionsWithElements, ApplicationInfo, ClientUserAgent, };
@@ -1,12 +0,0 @@
1
- import type { Providers } from '../types';
2
- import { EncryptionOptions } from '../types';
3
- import type { EncryptionAdapter, KeyPair } from './types';
4
- export declare class BasisTheoryEncryption implements EncryptionAdapter {
5
- private readonly adapter;
6
- constructor(encryptionProvider: Providers);
7
- init(encryptionOptions: EncryptionOptions): void;
8
- get name(): string;
9
- generateKeys(): Promise<KeyPair | string | unknown>;
10
- encrypt(encryptionKey: string, plainTextData: string): Promise<string>;
11
- decrypt(decryptionKey: string, cipherTextData: string): Promise<string>;
12
- }
@@ -1,51 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.BasisTheoryEncryption = void 0;
7
-
8
- var _browser = require("./providers/browser");
9
-
10
- var _node = require("./providers/node");
11
-
12
- class BasisTheoryEncryption {
13
- constructor(encryptionProvider) {
14
- switch (encryptionProvider) {
15
- case 'BROWSER':
16
- this.adapter = _browser.browserAdapter;
17
- break;
18
-
19
- case 'NODE':
20
- this.adapter = _node.nodeAdapter;
21
- break;
22
-
23
- default:
24
- throw new Error(`No adapter found for provider name "${encryptionProvider}"`);
25
- }
26
- }
27
-
28
- init(encryptionOptions) {
29
- return this.adapter.init(encryptionOptions);
30
- } // eslint-disable-next-line accessor-pairs
31
-
32
-
33
- get name() {
34
- return this.adapter.name;
35
- }
36
-
37
- generateKeys() {
38
- return this.adapter.generateKeys();
39
- }
40
-
41
- encrypt(encryptionKey, plainTextData) {
42
- return this.adapter.encrypt(encryptionKey, plainTextData);
43
- }
44
-
45
- decrypt(decryptionKey, cipherTextData) {
46
- return this.adapter.decrypt(decryptionKey, cipherTextData);
47
- }
48
-
49
- }
50
-
51
- exports.BasisTheoryEncryption = BasisTheoryEncryption;
@@ -1,8 +0,0 @@
1
- import { BasisTheoryEncryption } from './BasisTheoryEncryption';
2
- export declare class BasisTheoryEncryptionAdapters {
3
- private _nodeEncryption?;
4
- private _browserEncryption?;
5
- constructor();
6
- get browserEncryption(): BasisTheoryEncryption;
7
- get nodeEncryption(): BasisTheoryEncryption;
8
- }
@@ -1,33 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.BasisTheoryEncryptionAdapters = void 0;
7
-
8
- var _common = require("../common");
9
-
10
- var _BasisTheoryEncryption = require("./BasisTheoryEncryption");
11
-
12
- class BasisTheoryEncryptionAdapters {
13
- constructor() {
14
- if (typeof window === 'undefined') {
15
- this._nodeEncryption = new _BasisTheoryEncryption.BasisTheoryEncryption('NODE');
16
- } else {
17
- this._browserEncryption = new _BasisTheoryEncryption.BasisTheoryEncryption('BROWSER');
18
- }
19
- } // eslint-disable-next-line accessor-pairs
20
-
21
-
22
- get browserEncryption() {
23
- return (0, _common.assertInit)(this._browserEncryption);
24
- } // eslint-disable-next-line accessor-pairs
25
-
26
-
27
- get nodeEncryption() {
28
- return (0, _common.assertInit)(this._nodeEncryption);
29
- }
30
-
31
- }
32
-
33
- exports.BasisTheoryEncryptionAdapters = BasisTheoryEncryptionAdapters;
@@ -1,2 +0,0 @@
1
- export * from './BasisTheoryEncryption';
2
- export * from './types';
@@ -1,31 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
-
7
- var _BasisTheoryEncryption = require("./BasisTheoryEncryption");
8
-
9
- Object.keys(_BasisTheoryEncryption).forEach(function (key) {
10
- if (key === "default" || key === "__esModule") return;
11
- if (key in exports && exports[key] === _BasisTheoryEncryption[key]) return;
12
- Object.defineProperty(exports, key, {
13
- enumerable: true,
14
- get: function () {
15
- return _BasisTheoryEncryption[key];
16
- }
17
- });
18
- });
19
-
20
- var _types = require("./types");
21
-
22
- Object.keys(_types).forEach(function (key) {
23
- if (key === "default" || key === "__esModule") return;
24
- if (key in exports && exports[key] === _types[key]) return;
25
- Object.defineProperty(exports, key, {
26
- enumerable: true,
27
- get: function () {
28
- return _types[key];
29
- }
30
- });
31
- });
@@ -1,2 +0,0 @@
1
- import type { EncryptionAdapter } from '../types';
2
- export declare const browserAdapter: EncryptionAdapter;
@@ -1,98 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.browserAdapter = void 0;
7
-
8
- var _utils = require("./utils");
9
-
10
- let signAlgorithm;
11
- let algorithm;
12
-
13
- const init = browserEncryption => {
14
- var _browserEncryption$op, _browserEncryption$op2, _browserEncryption$al;
15
-
16
- signAlgorithm = {
17
- name: 'RSA-OAEP',
18
- modulusLength: (_browserEncryption$op = browserEncryption === null || browserEncryption === void 0 ? void 0 : (_browserEncryption$op2 = browserEncryption.options) === null || _browserEncryption$op2 === void 0 ? void 0 : _browserEncryption$op2.defaultKeySize) !== null && _browserEncryption$op !== void 0 ? _browserEncryption$op : 4096,
19
- publicExponent: new Uint8Array([1, 0, 1]),
20
- hash: 'SHA-256'
21
- };
22
- algorithm = (_browserEncryption$al = browserEncryption === null || browserEncryption === void 0 ? void 0 : browserEncryption.algorithm) !== null && _browserEncryption$al !== void 0 ? _browserEncryption$al : 'RSA';
23
- };
24
-
25
- const convertBinaryToPem = (binaryData, label) => {
26
- const base64Cert = (0, _utils.arrayBufferToBase64String)(binaryData);
27
- let pemCert = `-----BEGIN ${label} KEY-----\r\n`;
28
- let nextIndex = 0;
29
-
30
- while (nextIndex < base64Cert.length) {
31
- pemCert += nextIndex + 64 <= base64Cert.length ? `${base64Cert.slice(nextIndex, nextIndex + 64)}\r\n` : `${base64Cert.slice(nextIndex)}\r\n`;
32
- nextIndex += 64;
33
- }
34
-
35
- pemCert += `-----END ${label} KEY-----\r\n`;
36
- return pemCert;
37
- };
38
-
39
- const convertPemToBinary = (pem, label) => {
40
- const lines = pem.split('\n');
41
- let encoded = '';
42
-
43
- for (const line of lines) {
44
- if (line.trim().length > 0 && !line.includes(`-BEGIN ${label} KEY-`) && !line.includes(`-END ${label} KEY-`)) {
45
- encoded = encoded + line.trim();
46
- }
47
- }
48
-
49
- return (0, _utils.base64StringToArrayBuffer)(encoded);
50
- };
51
-
52
- const generateRSAKeys = async () => {
53
- const keyPair = await window.crypto.subtle.generateKey(signAlgorithm, true, ['encrypt', 'decrypt']);
54
- const exportedPublic = await window.crypto.subtle.exportKey('spki', keyPair.publicKey);
55
- const exportedPrivate = await window.crypto.subtle.exportKey('pkcs8', keyPair.privateKey);
56
- return {
57
- publicKey: convertBinaryToPem(exportedPublic, 'PUBLIC'),
58
- privateKey: convertBinaryToPem(exportedPrivate, 'PRIVATE')
59
- };
60
- };
61
-
62
- const generateKeyMap = {
63
- RSA: generateRSAKeys,
64
- AES: () => Promise.reject()
65
- };
66
-
67
- const generateKeys = () => generateKeyMap[algorithm]();
68
-
69
- const loadPublicKey = pem => window.crypto.subtle.importKey('spki', convertPemToBinary(pem, 'PUBLIC'), signAlgorithm, true, ['encrypt']);
70
-
71
- const loadPrivateKey = pem => window.crypto.subtle.importKey('pkcs8', convertPemToBinary(pem, 'PRIVATE'), signAlgorithm, true, ['decrypt']);
72
-
73
- const encrypt = async (publicKey, data) => {
74
- const key = await loadPublicKey(publicKey);
75
- const encrypted = await window.crypto.subtle.encrypt({
76
- name: signAlgorithm.name
77
- }, key, // eslint-disable-next-line node/no-unsupported-features/node-builtins
78
- new TextEncoder().encode(data).buffer);
79
- return (0, _utils.arrayBufferToBase64String)(encrypted);
80
- };
81
-
82
- const decrypt = async (privateKey, data) => {
83
- const key = await loadPrivateKey(privateKey);
84
- const decrypted = await window.crypto.subtle.decrypt({
85
- name: signAlgorithm.name
86
- }, key, (0, _utils.base64StringToArrayBuffer)(data)); // eslint-disable-next-line node/no-unsupported-features/node-builtins
87
-
88
- return new TextDecoder().decode(decrypted);
89
- };
90
-
91
- const browserAdapter = {
92
- name: 'browser',
93
- generateKeys,
94
- init,
95
- encrypt,
96
- decrypt
97
- };
98
- exports.browserAdapter = browserAdapter;
@@ -1,2 +0,0 @@
1
- import { EncryptionAdapter } from '../types';
2
- export declare const nodeAdapter: EncryptionAdapter;
@@ -1,73 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.nodeAdapter = void 0;
7
-
8
- var _crypto = require("crypto");
9
-
10
- let keySize;
11
- let algorithm;
12
-
13
- const init = nodeEncryption => {
14
- var _nodeEncryption$optio, _nodeEncryption$optio2, _nodeEncryption$algor;
15
-
16
- keySize = (_nodeEncryption$optio = nodeEncryption === null || nodeEncryption === void 0 ? void 0 : (_nodeEncryption$optio2 = nodeEncryption.options) === null || _nodeEncryption$optio2 === void 0 ? void 0 : _nodeEncryption$optio2.defaultKeySize) !== null && _nodeEncryption$optio !== void 0 ? _nodeEncryption$optio : 4096;
17
- algorithm = (_nodeEncryption$algor = nodeEncryption === null || nodeEncryption === void 0 ? void 0 : nodeEncryption.algorithm) !== null && _nodeEncryption$algor !== void 0 ? _nodeEncryption$algor : 'RSA';
18
- };
19
-
20
- const generateRSAKeys = () => {
21
- const {
22
- publicKey,
23
- privateKey
24
- } = (0, _crypto.generateKeyPairSync)('rsa', {
25
- modulusLength: keySize,
26
- publicKeyEncoding: {
27
- type: 'spki',
28
- format: 'pem'
29
- },
30
- privateKeyEncoding: {
31
- type: 'pkcs8',
32
- format: 'pem'
33
- }
34
- });
35
- return Promise.resolve({
36
- publicKey,
37
- privateKey
38
- });
39
- };
40
-
41
- const generateKeyMap = {
42
- RSA: generateRSAKeys,
43
- AES: () => Promise.reject()
44
- };
45
-
46
- const generateKeys = () => generateKeyMap[algorithm]();
47
-
48
- const encrypt = (publicKey, data) => {
49
- const encrypted = (0, _crypto.publicEncrypt)({
50
- key: publicKey,
51
- padding: _crypto.constants.RSA_PKCS1_OAEP_PADDING,
52
- oaepHash: 'sha256'
53
- }, Buffer.from(data));
54
- return Promise.resolve(encrypted.toString('base64'));
55
- };
56
-
57
- const decrypt = (privateKey, data) => {
58
- const decrypted = (0, _crypto.privateDecrypt)({
59
- key: privateKey,
60
- padding: _crypto.constants.RSA_PKCS1_OAEP_PADDING,
61
- oaepHash: 'sha256'
62
- }, Buffer.from(data, 'base64'));
63
- return Promise.resolve(decrypted.toString());
64
- };
65
-
66
- const nodeAdapter = {
67
- name: 'node',
68
- generateKeys,
69
- init,
70
- encrypt,
71
- decrypt
72
- };
73
- exports.nodeAdapter = nodeAdapter;
@@ -1,3 +0,0 @@
1
- declare const arrayBufferToBase64String: (arrayBuffer: ArrayBuffer) => string;
2
- declare const base64StringToArrayBuffer: (b64str: string) => ArrayBuffer;
3
- export { arrayBufferToBase64String, base64StringToArrayBuffer };
@@ -1,24 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.base64StringToArrayBuffer = exports.arrayBufferToBase64String = void 0;
7
-
8
- const arrayBufferToBase64String = arrayBuffer => window.btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));
9
-
10
- exports.arrayBufferToBase64String = arrayBufferToBase64String;
11
-
12
- const base64StringToArrayBuffer = b64str => {
13
- const binary = window.atob(b64str);
14
- const len = binary.length;
15
- const bytes = new Uint8Array(len);
16
-
17
- for (let i = 0; i < len; i++) {
18
- bytes[i] = binary.charCodeAt(i);
19
- }
20
-
21
- return bytes.buffer;
22
- };
23
-
24
- exports.base64StringToArrayBuffer = base64StringToArrayBuffer;
@@ -1,13 +0,0 @@
1
- import { EncryptionOptions } from '../types';
2
- interface KeyPair {
3
- publicKey: string;
4
- privateKey: string;
5
- }
6
- interface EncryptionAdapter {
7
- name: string;
8
- generateKeys(): Promise<KeyPair | string | unknown>;
9
- init(encryptionOptions: EncryptionOptions): void;
10
- encrypt(encryptionKey: unknown, plainTextData: string): Promise<string>;
11
- decrypt(decryptionKey: unknown, cipherTextData: string): Promise<string>;
12
- }
13
- export { KeyPair, EncryptionAdapter };
@@ -1 +0,0 @@
1
- "use strict";