@vulog/aima-client 1.0.5 → 1.0.6

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/.eslintrc.js ADDED
@@ -0,0 +1,112 @@
1
+ module.exports = {
2
+ parser: '@typescript-eslint/parser',
3
+ parserOptions: {
4
+ // Indicates the location of the TypeScript configuration file
5
+ project: 'tsconfig.json',
6
+ // Sets the root directory for the TypeScript configuration
7
+ tsconfigRootDir: __dirname,
8
+ // Specifies the version of ECMAScript syntax to be used
9
+ ecmaVersion: 'latest',
10
+ // Indicates the type of source code (script or module)
11
+ sourceType: 'module',
12
+ },
13
+ plugins: ['@typescript-eslint', 'prettier', 'import'],
14
+ extends: [
15
+ 'airbnb-base',
16
+ 'airbnb-typescript/base',
17
+ 'plugin:@typescript-eslint/recommended',
18
+ 'prettier',
19
+ 'plugin:prettier/recommended',
20
+ ],
21
+ root: true,
22
+ env: {
23
+ es6: true,
24
+ node: true,
25
+ },
26
+ ignorePatterns: [
27
+ '/dist/**/*', // Ignore built files.
28
+ '.eslintrc.js',
29
+ '**/*.test.ts',
30
+ ],
31
+ rules: {
32
+ // Configures the Prettier integration with ESLint
33
+ 'prettier/prettier': ['error', { endOfLine: 'auto' }],
34
+ // Disables the rule requiring an 'I' prefix for interfaces
35
+ '@typescript-eslint/interface-name-prefix': 'off',
36
+ // Configures the naming conventions for various code constructs
37
+ '@typescript-eslint/naming-convention': [
38
+ // ... various naming convention configurations ...
39
+ 'error',
40
+ // Allows any naming format for destructured variables
41
+ {
42
+ selector: 'variable',
43
+ modifiers: ['destructured'],
44
+ format: null,
45
+ },
46
+ // Requires strict camelCase for function names
47
+ {
48
+ selector: 'function',
49
+ format: ['strictCamelCase'],
50
+ },
51
+ // Requires boolean variables to have one of the specified prefixes
52
+ {
53
+ selector: 'variable',
54
+ format: null,
55
+ types: ['boolean'],
56
+ prefix: ['is', 'should', 'has', 'can', 'did', 'will'],
57
+ },
58
+ // Requires enum names to have a strict PascalCase format
59
+ {
60
+ selector: 'enum',
61
+ format: ['StrictPascalCase'],
62
+ },
63
+ ],
64
+ 'import/extensions': 'off',
65
+ // Disables the rule requiring explicit return types for functions
66
+ '@typescript-eslint/explicit-function-return-type': 'off',
67
+ // Disables the rule requiring explicit boundary types for modules
68
+ '@typescript-eslint/explicit-module-boundary-types': 'off',
69
+ // Disables the rule prohibiting the use of 'any' type
70
+ '@typescript-eslint/no-explicit-any': 'off',
71
+ // Disables the rule detecting unused variables
72
+ 'no-unused-vars': 0,
73
+ // Disables the rule disallowing named exports used as a default export
74
+ 'import/no-named-as-default': 0,
75
+ // Configures the order and formatting of import statements
76
+ 'import/order': [
77
+ // ... import order configuration ...
78
+ 'error',
79
+ {
80
+ // Configure the alphabetization settings
81
+ alphabetize: {
82
+ // Enforce ascending alphabetical order
83
+ order: 'asc',
84
+ // Do not ignore the case while sorting
85
+ caseInsensitive: false,
86
+ },
87
+ // Enforce newlines between different groups and inside groups of imports
88
+ 'newlines-between': 'always-and-inside-groups',
89
+ // Warn when there is an import statement that is not part of any group
90
+ warnOnUnassignedImports: true,
91
+ },
92
+ ],
93
+ // Configures the rule detecting extraneous dependencies
94
+ 'import/no-extraneous-dependencies': [
95
+ // ... extraneous dependencies configuration ...
96
+ 'error',
97
+ {
98
+ // Specify the file patterns where devDependencies imports are allowed
99
+ devDependencies: [
100
+ // Allow devDependencies imports in test and spec files
101
+ '**/*.test.{ts,js}',
102
+ '**/*.spec.{ts,js}',
103
+ // Allow devDependencies imports in the 'test' folder
104
+ './test/**.{ts,js}',
105
+ // Allow devDependencies imports in the 'scripts' folder
106
+ './scripts/**/*.{ts,js}',
107
+ ],
108
+ },
109
+ ],
110
+ 'import/prefer-default-export': 'off',
111
+ },
112
+ };
package/dist/index.js CHANGED
@@ -46,7 +46,7 @@ var formatError = (error) => {
46
46
  status,
47
47
  data
48
48
  },
49
- originalError: error
49
+ originalError: error.toJSON ? error.toJSON() : error
50
50
  };
51
51
  };
52
52
  var getClient = (options) => {
package/dist/index.mjs CHANGED
@@ -10,7 +10,7 @@ var formatError = (error) => {
10
10
  status,
11
11
  data
12
12
  },
13
- originalError: error
13
+ originalError: error.toJSON ? error.toJSON() : error
14
14
  };
15
15
  };
16
16
  var getClient = (options) => {
package/package.json CHANGED
@@ -1,13 +1,10 @@
1
1
  {
2
2
  "name": "@vulog/aima-client",
3
- "version": "1.0.5",
3
+ "version": "1.0.6",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.mjs",
6
6
  "types": "dist/index.d.ts",
7
- "files": [
8
- "dist",
9
- "README.md"
10
- ],
7
+
11
8
  "scripts": {
12
9
  "build": "tsup",
13
10
  "dev": "tsup --watch",
@@ -0,0 +1,21 @@
1
+ import { describe, test, vi, beforeEach, expect } from 'vitest';
2
+ import getClient from './getClient';
3
+ import { ClientOptions } from './types';
4
+
5
+ describe('getClient', () => {
6
+ beforeEach(() => {
7
+ vi.resetAllMocks();
8
+ });
9
+
10
+ test('create client', () => {
11
+ const options: ClientOptions = {
12
+ fleetId: 'fleetId',
13
+ baseUrl: 'baseUrl',
14
+ clientId: 'clientId',
15
+ clientSecret: 'clientSecret',
16
+ apiKey: 'apiKey',
17
+ };
18
+ const client = getClient(options);
19
+ expect(client.defaults.baseURL).toEqual(options.baseUrl);
20
+ });
21
+ });
@@ -0,0 +1,156 @@
1
+ import axios from 'axios';
2
+ import _ from 'lodash';
3
+ import { LRUCache } from 'lru-cache';
4
+
5
+ import { Client, ClientError, ClientOptions } from './types';
6
+
7
+ const clientCache = new LRUCache<
8
+ string,
9
+ {
10
+ options: ClientOptions;
11
+ client: Client;
12
+ }
13
+ >({ max: 100 });
14
+
15
+ const formatError = (error: any): ClientError => {
16
+ const { response: { status, data } = { status: 500 } } = error ?? {};
17
+
18
+ return {
19
+ formattedError: {
20
+ status,
21
+ data,
22
+ },
23
+ originalError: error.toJSON ? error.toJSON() : error,
24
+ };
25
+ };
26
+
27
+ const getClient = (options: ClientOptions): Client => {
28
+ if (clientCache.has(options.name ?? options.fleetId)) {
29
+ const { options: cachedOptions, client } = clientCache.get(options.fleetId)!;
30
+ if (_.isEqual(cachedOptions, options)) {
31
+ return client;
32
+ }
33
+ }
34
+
35
+ const client = axios.create({
36
+ baseURL: _.trimEnd(options.baseUrl, '/'),
37
+ timeout: 30000,
38
+ headers: {
39
+ 'Cache-Control': 'no-cache',
40
+ 'Content-Type': 'application/json',
41
+ 'X-Api-Key': options.apiKey,
42
+ },
43
+ withCredentials: false,
44
+ }) as Client;
45
+
46
+ const clientCredentialsAuthentification = async (): Promise<string> => {
47
+ const params = new URLSearchParams();
48
+ params.append('client_id', options.clientId);
49
+ params.append('client_secret', options.clientSecret);
50
+ params.append('securityOptions', 'SSL_OP_NO_SSLv3');
51
+ params.append('grant_type', 'client_credentials');
52
+
53
+ const { data: token } = await axios.post(
54
+ `${_.trimEnd(options.baseUrl, '/')}/auth/realms/${options.fleetMaster ?? options.fleetId}/protocol/openid-connect/token`,
55
+ params,
56
+ {
57
+ timeout: 30000,
58
+ headers: {
59
+ 'Content-Type': 'application/x-www-form-urlencoded',
60
+ },
61
+ withCredentials: false,
62
+ }
63
+ );
64
+ client.defaults.headers.Authorization = `Bearer ${token.access_token}`;
65
+ return token.access_token;
66
+ };
67
+
68
+ const refreshTokenAuthentification = async (): Promise<string> => {
69
+ if (!client.refreshToken) {
70
+ throw new Error('No refresh token available');
71
+ }
72
+ const params = new URLSearchParams();
73
+ params.append('client_id', options.clientId);
74
+ params.append('client_secret', options.clientSecret);
75
+ params.append('securityOptions', 'SSL_OP_NO_SSLv3');
76
+ params.append('grant_type', 'refresh_token');
77
+ params.append('refresh_token', client.refreshToken);
78
+
79
+ const { data: token } = await axios.post(
80
+ `${_.trimEnd(options.baseUrl, '/')}/auth/realms/${options.fleetMaster ?? options.fleetId}/protocol/openid-connect/token`,
81
+ params,
82
+ {
83
+ timeout: 30000,
84
+ headers: {
85
+ 'Content-Type': 'application/x-www-form-urlencoded',
86
+ },
87
+ withCredentials: false,
88
+ }
89
+ );
90
+ client.defaults.headers.Authorization = `Bearer ${token.access_token}`;
91
+ client.refreshToken = token.refresh_token;
92
+ return token.access_token;
93
+ };
94
+
95
+ client.signInWithPassword = async (username: string, password: string): Promise<void> => {
96
+ if (!options.secure) {
97
+ throw new Error('Not secure');
98
+ }
99
+ const params = new URLSearchParams();
100
+ params.append('client_id', options.clientId);
101
+ params.append('client_secret', options.clientSecret);
102
+ params.append('securityOptions', 'SSL_OP_NO_SSLv3');
103
+ params.append('grant_type', 'password');
104
+ params.append('username', username);
105
+ params.append('password', password);
106
+
107
+ const { data: token } = await axios.post(
108
+ `${_.trimEnd(options.baseUrl, '/')}/auth/realms/${options.fleetMaster ?? options.fleetId}/protocol/openid-connect/token`,
109
+ params,
110
+ {
111
+ timeout: 30000,
112
+ headers: {
113
+ 'Content-Type': 'application/x-www-form-urlencoded',
114
+ },
115
+ withCredentials: false,
116
+ }
117
+ );
118
+ client.defaults.headers.Authorization = `Bearer ${token.access_token}`;
119
+ client.refreshToken = token.refresh_token;
120
+ };
121
+
122
+ client.interceptors.response.use(
123
+ (response) => response,
124
+ (error) => {
125
+ const { config, response: { status } = { status: 500 } } = error;
126
+ const originalRequest = config;
127
+
128
+ if (originalRequest.attemptCount === undefined) {
129
+ originalRequest.attemptCount = 0;
130
+ }
131
+
132
+ if (originalRequest.attemptCount === 5) {
133
+ return Promise.reject(formatError(error));
134
+ }
135
+
136
+ if (status === 401) {
137
+ return new Promise((resolve, reject) => {
138
+ (options.secure ? refreshTokenAuthentification() : clientCredentialsAuthentification())
139
+ .then((token) => {
140
+ originalRequest.headers.Authorization = `Bearer ${token}`;
141
+ resolve(client.request(originalRequest));
142
+ })
143
+ .catch(() => reject(formatError(error)));
144
+ });
145
+ }
146
+
147
+ return Promise.reject(formatError(error));
148
+ }
149
+ );
150
+
151
+ clientCache.set(options.name ?? options.fleetId, { options, client });
152
+
153
+ return client;
154
+ };
155
+
156
+ export default getClient;
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ import getClient from './getClient';
2
+ import { ClientOptions } from './types';
3
+
4
+ export { ClientOptions, getClient };
package/src/types.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { AxiosInstance } from 'axios';
2
+
3
+ export type ClientOptions = {
4
+ fleetId: string;
5
+ name?: string;
6
+ fleetMaster?: string;
7
+ baseUrl: string;
8
+ clientId: string;
9
+ clientSecret: string;
10
+ apiKey: string;
11
+ secure?: boolean;
12
+ };
13
+
14
+ export type ClientError = {
15
+ formattedError: {
16
+ status: number;
17
+ data: any;
18
+ };
19
+ originalError: any;
20
+ };
21
+
22
+ export type Client = AxiosInstance & {
23
+ refreshToken?: string;
24
+ signInWithPassword: (username: string, password: string) => Promise<void>;
25
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "include": ["src"],
3
+ "exclude": ["**/*.test.ts"],
4
+ "compilerOptions": {
5
+ "module": "esnext",
6
+ "target": "esnext",
7
+ "lib": ["esnext"],
8
+ "declaration": true,
9
+ "strict": true,
10
+ "moduleResolution": "node",
11
+ "skipLibCheck": true,
12
+ "esModuleInterop": true,
13
+ "outDir": "dist",
14
+ "rootDir": "src"
15
+ }
16
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from 'tsup';
2
+
3
+ export default defineConfig({
4
+ entry: ['src/index.ts'],
5
+ clean: true,
6
+ format: ['cjs', 'esm'],
7
+ dts: true,
8
+ });
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ globals: true,
6
+ environment: 'node',
7
+ },
8
+ });