rest-client-sdk 7.2.0 → 7.2.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/dist/{index.js → index.cjs} +1 -1
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/{index.es.js → index.mjs} +1 -1
  4. package/dist/index.mjs.map +1 -0
  5. package/package.json +10 -14
  6. package/dist/index.es.js.map +0 -1
  7. package/dist/index.js.map +0 -1
  8. package/src/AsyncStorageInterface.ts +0 -7
  9. package/src/ErrorFactory.ts +0 -258
  10. package/src/Mapping/Attribute.ts +0 -33
  11. package/src/Mapping/ClassMetadata.ts +0 -125
  12. package/src/Mapping/Relation.ts +0 -68
  13. package/src/Mapping.ts +0 -120
  14. package/src/RestClientSdk.ts +0 -127
  15. package/src/RestClientSdkInterface.ts +0 -27
  16. package/src/TokenGenerator/AbstractTokenGenerator.ts +0 -86
  17. package/src/TokenGenerator/AuthorizationCodeFlowTokenGenerator.ts +0 -146
  18. package/src/TokenGenerator/ClientCredentialsGenerator.ts +0 -97
  19. package/src/TokenGenerator/PasswordGenerator.ts +0 -140
  20. package/src/TokenGenerator/ProvidedTokenGenerator.ts +0 -44
  21. package/src/TokenGenerator/TokenGeneratorInterface.ts +0 -27
  22. package/src/TokenGenerator/types.ts +0 -33
  23. package/src/TokenStorage.ts +0 -256
  24. package/src/TokenStorageInterface.ts +0 -14
  25. package/src/UnitOfWork.ts +0 -354
  26. package/src/client/AbstractClient.ts +0 -545
  27. package/src/client/headerUtils.ts +0 -53
  28. package/src/decorator.ts +0 -53
  29. package/src/index.ts +0 -86
  30. package/src/isImmutable.ts +0 -52
  31. package/src/serializer/JsSerializer.ts +0 -30
  32. package/src/serializer/Serializer.ts +0 -138
  33. package/src/serializer/SerializerInterface.ts +0 -89
  34. package/src/utils/levenshtein.ts +0 -53
  35. package/src/utils/logging.ts +0 -96
  36. package/src/utils/repositoryGenerator.ts +0 -16
@@ -1,97 +0,0 @@
1
- /* eslint-disable camelcase */
2
- import { memoizePromise } from '../decorator';
3
- import AbstractTokenGenerator from './AbstractTokenGenerator';
4
- import { Token, TokenResponse } from './types';
5
-
6
- const ERROR_CONFIG_EMPTY = 'TokenGenerator config must be set';
7
- const ERROR_CONFIG_PATH_SCHEME =
8
- 'TokenGenerator config is not valid, it should contain a "path", a "scheme" parameter';
9
- const ERROR_CONFIG_CLIENT_INFORMATIONS =
10
- 'TokenGenerator config is not valid, it should contain a "clientId", a "clientSecret" parameter';
11
-
12
- type Config = {
13
- clientId: string;
14
- clientSecret: string;
15
- path: string;
16
- scheme: string;
17
- port?: string;
18
- scope?: string;
19
- };
20
-
21
- type BaseParameters = {
22
- scope?: string;
23
- };
24
-
25
- interface ClientCredentialToken extends Token {
26
- access_token: string;
27
- token_type: string;
28
- refresh_token: never;
29
- expires_in?: number;
30
- scope?: string;
31
- }
32
-
33
- type ClientCredentialResponse = TokenResponse<ClientCredentialToken>;
34
-
35
- class ClientCredentialsGenerator extends AbstractTokenGenerator<
36
- ClientCredentialToken,
37
- Config
38
- > {
39
- constructor(tokenGeneratorConfig: Config) {
40
- super(tokenGeneratorConfig);
41
- this.generateToken = memoizePromise(this.generateToken);
42
- }
43
-
44
- generateToken(
45
- baseParameters: BaseParameters = {}
46
- ): Promise<ClientCredentialResponse> {
47
- const body = new URLSearchParams({
48
- grant_type: 'client_credentials',
49
- client_id: this.tokenGeneratorConfig.clientId,
50
- client_secret: this.tokenGeneratorConfig.clientSecret,
51
- });
52
- if (baseParameters.scope) {
53
- body.append('scope', baseParameters.scope);
54
- } else if (this.tokenGeneratorConfig.scope) {
55
- body.append('scope', this.tokenGeneratorConfig.scope);
56
- }
57
-
58
- const params = {
59
- method: 'POST',
60
- headers: {
61
- 'Content-Type': 'application/x-www-form-urlencoded',
62
- },
63
- body: body.toString(),
64
- };
65
-
66
- const url = this.generateUrlFromConfig(this.tokenGeneratorConfig);
67
-
68
- if (this.logger) {
69
- this.logger.logRequest({ url, ...params });
70
- }
71
-
72
- return fetch(url, params);
73
- }
74
-
75
- refreshToken(
76
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
77
- accessToken: null | ClientCredentialToken
78
- ): Promise<ClientCredentialResponse> {
79
- return this.generateToken({});
80
- }
81
-
82
- checkTokenGeneratorConfig(config: Config): void {
83
- if (!config || Object.keys(config).length === 0) {
84
- throw new RangeError(ERROR_CONFIG_EMPTY);
85
- }
86
-
87
- if (!(config.path && config.scheme)) {
88
- throw new RangeError(ERROR_CONFIG_PATH_SCHEME);
89
- }
90
-
91
- if (!(config.clientId && config.clientSecret)) {
92
- throw new RangeError(ERROR_CONFIG_CLIENT_INFORMATIONS);
93
- }
94
- }
95
- }
96
-
97
- export default ClientCredentialsGenerator;
@@ -1,140 +0,0 @@
1
- /* eslint-disable camelcase */
2
- import AbstractTokenGenerator from './AbstractTokenGenerator';
3
- import { Token, TokenResponse } from './types';
4
-
5
- const ERROR_CONFIG_EMPTY = 'TokenGenerator config must be set';
6
- const ERROR_CONFIG_PATH_SCHEME =
7
- 'TokenGenerator config is not valid, it should contain a "path", a "scheme" parameter';
8
- const ERROR_CONFIG_CLIENT_INFORMATIONS =
9
- 'TokenGenerator config is not valid, it should contain a "clientId", a "clientSecret" parameter';
10
-
11
- const ERROR_TOKEN_EMPTY = 'parameters must be set';
12
- const ERROR_TOKEN_USERNAME_PASSWORD =
13
- 'username and password must be passed as parameters';
14
-
15
- type Config = {
16
- clientId: string;
17
- clientSecret: string;
18
- path: string;
19
- scheme: string;
20
- port?: string;
21
- scope?: string;
22
- };
23
-
24
- type GenerateTokenParameters = {
25
- username: string;
26
- password: string;
27
- scope?: string;
28
- };
29
-
30
- interface PasswordToken extends Token {
31
- access_token: string;
32
- token_type: string;
33
- refresh_token?: string;
34
- expires_in?: number;
35
- scope?: string;
36
- }
37
-
38
- type PasswordTokenResponse = TokenResponse<PasswordToken>;
39
-
40
- class PasswordGenerator extends AbstractTokenGenerator<PasswordToken, Config> {
41
- generateToken(
42
- baseParameters: GenerateTokenParameters
43
- ): Promise<PasswordTokenResponse> {
44
- this._checkGenerateParameters(baseParameters);
45
-
46
- const body = new URLSearchParams({
47
- grant_type: 'password',
48
- username: baseParameters.username,
49
- password: baseParameters.password,
50
- client_id: this.tokenGeneratorConfig.clientId,
51
- client_secret: this.tokenGeneratorConfig.clientSecret,
52
- });
53
-
54
- if (baseParameters.scope) {
55
- body.append('scope', baseParameters.scope);
56
- } else if (this.tokenGeneratorConfig.scope) {
57
- body.append('scope', this.tokenGeneratorConfig.scope);
58
- }
59
-
60
- const url = this.generateUrlFromConfig(this.tokenGeneratorConfig);
61
-
62
- const params = {
63
- method: 'POST',
64
- headers: {
65
- 'Content-Type': 'application/x-www-form-urlencoded',
66
- },
67
- body: body.toString(),
68
- };
69
-
70
- if (this.logger) {
71
- this.logger.logRequest({ url, ...params });
72
- }
73
-
74
- return fetch(url, params);
75
- }
76
-
77
- refreshToken(
78
- accessToken: null | PasswordToken
79
- ): Promise<PasswordTokenResponse> {
80
- const refreshToken = accessToken?.refresh_token;
81
- if (!refreshToken) {
82
- throw new Error(
83
- 'refresh_token is not set. Did you called `generateToken` before ?'
84
- );
85
- }
86
-
87
- const body = new URLSearchParams({
88
- grant_type: 'refresh_token',
89
- client_id: this.tokenGeneratorConfig.clientId,
90
- client_secret: this.tokenGeneratorConfig.clientSecret,
91
- refresh_token: refreshToken,
92
- });
93
-
94
- if (this.tokenGeneratorConfig.scope) {
95
- body.append('scope', this.tokenGeneratorConfig.scope);
96
- }
97
-
98
- const url = this.generateUrlFromConfig(this.tokenGeneratorConfig);
99
-
100
- const params = {
101
- method: 'POST',
102
- headers: {
103
- 'Content-Type': 'application/x-www-form-urlencoded',
104
- },
105
- body: body.toString(),
106
- };
107
-
108
- if (this.logger) {
109
- this.logger.logRequest({ url, ...params });
110
- }
111
-
112
- return fetch(url, params);
113
- }
114
-
115
- checkTokenGeneratorConfig(config: Config): void {
116
- if (!config || Object.keys(config).length === 0) {
117
- throw new RangeError(ERROR_CONFIG_EMPTY);
118
- }
119
-
120
- if (!(config.path && config.scheme)) {
121
- throw new RangeError(ERROR_CONFIG_PATH_SCHEME);
122
- }
123
-
124
- if (!(config.clientId && config.clientSecret)) {
125
- throw new RangeError(ERROR_CONFIG_CLIENT_INFORMATIONS);
126
- }
127
- }
128
-
129
- _checkGenerateParameters(parameters: GenerateTokenParameters): void {
130
- if (!(parameters && Object.keys(parameters).length > 0)) {
131
- throw new RangeError(ERROR_TOKEN_EMPTY);
132
- }
133
-
134
- if (!(parameters.username && parameters.password)) {
135
- throw new RangeError(ERROR_TOKEN_USERNAME_PASSWORD);
136
- }
137
- }
138
- }
139
-
140
- export default PasswordGenerator;
@@ -1,44 +0,0 @@
1
- /* eslint-disable camelcase */
2
- import TokenGeneratorInterface from './TokenGeneratorInterface';
3
- import { Token } from './types';
4
-
5
- type RefreshTokenFunc = (oldAccessToken: null | Token) => Promise<Token>;
6
-
7
- /**
8
- * @deprecated ProvidedTokenGenerator is not an Oauth valid generator.
9
- * You should use one of the official generator or implement your own custom generator.
10
- */
11
- class ProvidedTokenGenerator implements TokenGeneratorInterface<Token> {
12
- #token: Token;
13
-
14
- #refreshTokenFunc: null | RefreshTokenFunc;
15
-
16
- constructor(token: Token, refreshTokenFunc: null | RefreshTokenFunc = null) {
17
- this.#token = token;
18
- this.#refreshTokenFunc = refreshTokenFunc;
19
- }
20
-
21
- set token(token: Token) {
22
- this.#token = token;
23
- }
24
-
25
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
26
- generateToken(): Promise<Token> {
27
- return Promise.resolve(this.#token);
28
- }
29
-
30
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
31
- refreshToken(accessToken: null | Token): Promise<Token> {
32
- if (typeof this.#refreshTokenFunc === 'function') {
33
- return this.#refreshTokenFunc(accessToken);
34
- }
35
-
36
- return this.generateToken();
37
- }
38
-
39
- autoGenerateToken(): Promise<Token> {
40
- return this.generateToken();
41
- }
42
- }
43
-
44
- export default ProvidedTokenGenerator;
@@ -1,27 +0,0 @@
1
- import { Token, TokenBody, TokenResponse } from './types';
2
-
3
- /** @deprecated */
4
- export type TokenBodyReturn<T> = TokenBody<T>;
5
-
6
- export default interface TokenGeneratorInterface<T extends Token> {
7
- /**
8
- * This function needs no generate an access token
9
- */
10
- generateToken(
11
- parameters: unknown
12
- ): Promise<TokenBodyReturn<T> | TokenResponse<T>>;
13
-
14
- /**
15
- * This function needs to refresh the current possibly expired access token
16
- * and return a Promise that will be resolved with a fresh access token
17
- */
18
- refreshToken(
19
- accessToken: null | T
20
- ): Promise<TokenBodyReturn<T> | TokenResponse<T>>;
21
-
22
- /**
23
- * If defined, this function will be called automatically if we try to get an access token object
24
- * even if we did not call `generateToken` before
25
- */
26
- autoGenerateToken?(): Promise<T>;
27
- }
@@ -1,33 +0,0 @@
1
- /* eslint-disable camelcase */
2
-
3
- /**
4
- * See {@link https://tools.ietf.org/html/rfc6749#section-5.1 Successful Response}
5
- */
6
- export type Token = {
7
- access_token: string;
8
- token_type: string;
9
- refresh_token?: string;
10
- expires_in?: number;
11
- scope?: string;
12
- };
13
-
14
- /**
15
- * see {@link https://tools.ietf.org/html/rfc6749#section-5.2 Error Response}
16
- */
17
- export type ErrorBody = {
18
- error:
19
- | 'invalid_request'
20
- | 'invalid_client'
21
- | 'invalid_grant'
22
- | 'unauthorized_client'
23
- | 'unsupported_grant_type'
24
- | 'invalid_scope';
25
- error_description?: string;
26
- error_uri?: string;
27
- };
28
-
29
- export type TokenBody<T> = T | ErrorBody;
30
-
31
- export interface TokenResponse<T extends Token> extends Response {
32
- json(): Promise<TokenBody<T>>;
33
- }
@@ -1,256 +0,0 @@
1
- /* eslint-disable camelcase */
2
- import AsyncStorageInterface from './AsyncStorageInterface';
3
- import {
4
- getHttpErrorFromResponse,
5
- InvalidGrantError,
6
- InvalidScopeError,
7
- isOauthError,
8
- OauthError,
9
- } from './ErrorFactory';
10
- import TokenGeneratorInterface, {
11
- TokenBodyReturn,
12
- } from './TokenGenerator/TokenGeneratorInterface';
13
- import { ErrorBody, Token, TokenResponse } from './TokenGenerator/types';
14
- // eslint-disable-next-line import/no-duplicates
15
- import type TokenStorageInterface from './TokenStorageInterface';
16
- // eslint-disable-next-line import/no-duplicates
17
- import type { HasExpiresAt } from './TokenStorageInterface';
18
- import { memoizePromise } from './decorator';
19
- import { Logger } from './utils/logging';
20
-
21
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
22
- function isResponse(response: any): response is Response {
23
- return typeof response?.json === 'function';
24
- }
25
-
26
- function manageOauthError(body: ErrorBody, response?: Response): never {
27
- let error;
28
- if (response) {
29
- error = getHttpErrorFromResponse(response);
30
- }
31
-
32
- if (body.error === 'invalid_grant') {
33
- throw new InvalidGrantError(body.error, error);
34
- }
35
- if (body.error === 'invalid_scope') {
36
- throw new InvalidScopeError(body.error, error);
37
- }
38
-
39
- throw new OauthError(body.error, error);
40
- }
41
-
42
- class TokenStorage<T extends Token> implements TokenStorageInterface<T> {
43
- #tokenGenerator: TokenGeneratorInterface<T>;
44
-
45
- #hasATokenBeenGenerated: boolean;
46
-
47
- accessTokenKey: string;
48
-
49
- #asyncStorage!: AsyncStorageInterface;
50
-
51
- #logger?: Logger;
52
-
53
- constructor(
54
- tokenGenerator: TokenGeneratorInterface<T>,
55
- asyncStorage: AsyncStorageInterface,
56
- accessTokenKey = 'rest_client_sdk.api.access_token',
57
- logger?: Logger
58
- ) {
59
- if (logger) {
60
- this.#logger = logger;
61
- }
62
- this.#tokenGenerator = tokenGenerator;
63
- this.#hasATokenBeenGenerated = false;
64
- this.setAsyncStorage(asyncStorage);
65
- this.accessTokenKey = accessTokenKey;
66
-
67
- this.handleTokenResponse = this.handleTokenResponse.bind(this);
68
-
69
- this.generateToken = memoizePromise(this.generateToken);
70
- this.refreshToken = memoizePromise(this.refreshToken);
71
- }
72
-
73
- setAsyncStorage(asyncStorage: AsyncStorageInterface): void {
74
- this.#asyncStorage = asyncStorage;
75
- }
76
-
77
- hasAccessToken(): Promise<boolean> {
78
- return this.#asyncStorage
79
- .getItem(this.accessTokenKey)
80
- .then((accessToken) => !!accessToken);
81
- }
82
-
83
- getAccessToken(): Promise<null | string> {
84
- return this.getAccessTokenObject().then(
85
- (token) => token && token.access_token
86
- );
87
- }
88
-
89
- getAccessTokenObject(): Promise<null | (T & HasExpiresAt)> {
90
- return this.#asyncStorage.getItem(this.accessTokenKey).then((token) => {
91
- if (token) {
92
- const tokenObject = JSON.parse(token);
93
-
94
- if (typeof tokenObject !== 'object') {
95
- return null;
96
- }
97
-
98
- return tokenObject;
99
- }
100
-
101
- if (this.#hasATokenBeenGenerated) {
102
- return null;
103
- }
104
-
105
- if (typeof this.#tokenGenerator.autoGenerateToken === 'function') {
106
- return this.#tokenGenerator.autoGenerateToken();
107
- }
108
-
109
- throw new Error('No token has been generated yet.');
110
- });
111
- }
112
-
113
- logout(): Promise<void> {
114
- return this.#asyncStorage.removeItem(this.accessTokenKey);
115
- }
116
-
117
- private _addExpiresAtToResponseData(
118
- responseData: T,
119
- callTimestamp: number
120
- ): T & HasExpiresAt {
121
- if (!responseData) {
122
- return responseData;
123
- }
124
-
125
- const updatedResponseData: T & HasExpiresAt = {
126
- ...responseData,
127
- expires_at: null,
128
- };
129
-
130
- if (
131
- typeof updatedResponseData.expires_in !== 'undefined' &&
132
- updatedResponseData.expires_in !== null
133
- // && updatedResponseData.expires_in >= 0
134
- ) {
135
- updatedResponseData.expires_at =
136
- Math.round(callTimestamp / 1000) + updatedResponseData.expires_in;
137
- }
138
-
139
- return updatedResponseData;
140
- }
141
-
142
- generateToken(parameters: unknown): Promise<T & HasExpiresAt> {
143
- const callTimestamp = Date.now();
144
-
145
- return this.#tokenGenerator
146
- .generateToken(parameters)
147
- .then(this.handleTokenResponse)
148
- .then((body) => {
149
- const updatedResponseData = this._addExpiresAtToResponseData(
150
- body,
151
- callTimestamp
152
- );
153
-
154
- return this._storeAccessToken(updatedResponseData).then(() => {
155
- this.#hasATokenBeenGenerated = true;
156
- return updatedResponseData;
157
- });
158
- });
159
- }
160
-
161
- refreshToken(): Promise<T & HasExpiresAt> {
162
- return this.#asyncStorage.getItem(this.accessTokenKey).then((token) => {
163
- const callTimestamp = Date.now();
164
- return this.#tokenGenerator
165
- .refreshToken(token ? JSON.parse(token) : null)
166
- .then(this.handleTokenResponse)
167
- .then((body) => {
168
- const updatedResponseData = this._addExpiresAtToResponseData(
169
- body,
170
- callTimestamp
171
- );
172
-
173
- return this._storeAccessToken(updatedResponseData).then(
174
- () => updatedResponseData
175
- );
176
- });
177
- });
178
- }
179
-
180
- private handleTokenResponse(
181
- responseOrBody: TokenBodyReturn<T> | TokenResponse<T>
182
- ): Promise<T> {
183
- if (isResponse(responseOrBody)) {
184
- const response = responseOrBody;
185
- const originalResponse = response.clone();
186
-
187
- if (this.#logger) {
188
- this.#logger.logResponse(response);
189
- }
190
-
191
- return response
192
- .json()
193
- .then((body) => {
194
- if (isOauthError(body)) {
195
- // throw error if response body is an oauth error
196
- manageOauthError(body, originalResponse);
197
- } else if (response.status >= 400) {
198
- // throw an error if response status code is an "error" status code
199
- throw getHttpErrorFromResponse(originalResponse);
200
- }
201
-
202
- return body;
203
- })
204
- .catch((err) => {
205
- if (!(err instanceof OauthError)) {
206
- throw new OauthError(
207
- err.type,
208
- getHttpErrorFromResponse(originalResponse)
209
- );
210
- }
211
-
212
- throw err;
213
- });
214
- }
215
-
216
- const body = responseOrBody;
217
-
218
- if (isOauthError(body)) {
219
- // throw error if response body is an oauth error
220
- manageOauthError(body);
221
- }
222
-
223
- return Promise.resolve(body);
224
- }
225
-
226
- /**
227
- * Return the number of second when the token will expire
228
- * return value can be negative if the token is already expired
229
- */
230
- getCurrentTokenExpiresIn(): Promise<number | null> {
231
- return this.getAccessTokenObject().then((accessTokenObject) => {
232
- if (accessTokenObject === null) {
233
- throw new Error('No token has been stored.');
234
- }
235
-
236
- if (
237
- typeof accessTokenObject.expires_at === 'undefined' ||
238
- accessTokenObject.expires_at === null
239
- ) {
240
- return null;
241
- }
242
-
243
- const now = Math.round(Date.now() / 1000);
244
- return accessTokenObject.expires_at - now;
245
- });
246
- }
247
-
248
- private _storeAccessToken(responseData: T): Promise<unknown> {
249
- return this.#asyncStorage.setItem(
250
- this.accessTokenKey,
251
- JSON.stringify(responseData)
252
- );
253
- }
254
- }
255
-
256
- export default TokenStorage;
@@ -1,14 +0,0 @@
1
- export interface HasExpiresAt {
2
- // eslint-disable-next-line camelcase
3
- expires_at: null | number;
4
- }
5
-
6
- export default interface TokenStorageInterface<T> {
7
- hasAccessToken(): Promise<boolean>;
8
- getAccessToken(): Promise<null | string>;
9
- getAccessTokenObject(): Promise<null | (T & HasExpiresAt)>;
10
- logout(): Promise<void>;
11
- generateToken(parameters: unknown): Promise<T & HasExpiresAt>;
12
- refreshToken(): Promise<T & HasExpiresAt>;
13
- getCurrentTokenExpiresIn(): Promise<number | null>;
14
- }