@venizia/ardor-kernel 0.5.0-12 → 0.5.0-13
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/README.md +1 -1
- package/dist/base/applications/abstract.d.ts +12 -24
- package/dist/base/applications/abstract.js +4 -6
- package/dist/base/decorators/api.d.ts +0 -3
- package/dist/base/decorators/api.js +0 -3
- package/dist/base/providers/base.d.ts +0 -3
- package/dist/base/providers/base.js +0 -3
- package/dist/base/providers/role-permission.d.ts +1 -8
- package/dist/base/providers/role-permission.js +0 -3
- package/dist/base/services/auth.d.ts +6 -12
- package/dist/base/services/auth.js +5 -8
- package/dist/base/services/base.d.ts +0 -3
- package/dist/base/services/base.js +0 -3
- package/dist/base/services/network-request-base.d.ts +133 -0
- package/dist/base/services/network-request-base.js +302 -0
- package/dist/base/services/network-request.d.ts +28 -131
- package/dist/base/services/network-request.js +13 -252
- package/dist/common/constants.d.ts +0 -23
- package/dist/common/constants.js +0 -23
- package/dist/common/keys.d.ts +17 -20
- package/dist/common/keys.js +5 -9
- package/dist/common/types.d.ts +45 -45
- package/dist/helpers/networks/auth-recovery.d.ts +0 -3
- package/dist/helpers/networks/auth-recovery.js +0 -3
- package/dist/{testing.d.ts → testing/index.d.ts} +2 -17
- package/dist/{testing.js → testing/index.js} +1 -16
- package/dist/utilities/auth-token-store.d.ts +2 -8
- package/dist/utilities/auth-token-store.js +1 -4
- package/dist/utilities/browser-clipboard.d.ts +1 -3
- package/dist/utilities/browser-clipboard.js +5 -5
- package/dist/utilities/browser-storage.d.ts +16 -10
- package/dist/utilities/browser-storage.js +36 -20
- package/dist/utilities/browser.d.ts +0 -3
- package/dist/utilities/browser.js +0 -3
- package/dist/utilities/file.d.ts +5 -5
- package/dist/utilities/file.js +5 -5
- package/dist/utilities/network-response-reader.d.ts +61 -17
- package/dist/utilities/network-response-reader.js +157 -22
- package/dist/utilities/request-body-encoder.d.ts +35 -15
- package/dist/utilities/request-body-encoder.js +67 -10
- package/dist/utilities/runtime-config.d.ts +8 -9
- package/dist/utilities/runtime-config.js +0 -9
- package/dist/utilities/storage-codecs.d.ts +0 -3
- package/dist/utilities/storage-codecs.js +0 -3
- package/dist/utilities/value.d.ts +0 -3
- package/dist/utilities/value.js +0 -3
- package/package.json +13 -13
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import { getError } from '@venizia/ignis-inversion';
|
|
2
|
+
import { HTTP } from '@venizia/ignis-helpers/common';
|
|
3
|
+
import { HttpHeaders } from '@venizia/ignis-helpers/core';
|
|
4
|
+
import { UuidV4Generator } from '@venizia/ignis-helpers/uuid';
|
|
5
|
+
import { HttpExtraRequest } from '@venizia/ignis-kernel/repository';
|
|
6
|
+
import { App, LocalStorageKeys, RequestChannel, RequestCountData, } from '../../common/index.js';
|
|
7
|
+
import { AuthTokenStore, NetworkResponseReader, RequestBodyEncoder, } from '../../utilities/index.js';
|
|
8
|
+
import { BaseService } from './base.js';
|
|
9
|
+
/**
|
|
10
|
+
* What `DefaultNetworkRequestService` is built on: which requests go without a token, the token, the
|
|
11
|
+
* headers and body of a request, and the hooks that read data. It holds nothing about a request in
|
|
12
|
+
* flight.
|
|
13
|
+
*/
|
|
14
|
+
export class AbstractNetworkRequestService extends BaseService {
|
|
15
|
+
/**
|
|
16
|
+
* The token under the unscoped session key (`AuthTokenStore.read`), `undefined` outside a browser, for an
|
|
17
|
+
* application with no `id`. With an application `id` the session is under other keys: use
|
|
18
|
+
* `createAuthTokenReader({ id })`, the `HttpDataSource` `getDataSourceAuth()` of the data provider, or `authService.getAuth`.
|
|
19
|
+
*/
|
|
20
|
+
static readAuthTokenFromStorage() {
|
|
21
|
+
return AuthTokenStore.read();
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A reader of the stored token of the application with this `id` (`IApplicationInfo.id`): the same
|
|
25
|
+
* key `DefaultAuthService.getAuth` reads (`LocalStorageKeys.scoped({ id }).token`). Without an `id` it
|
|
26
|
+
* is `readAuthTokenFromStorage`. Throws for an invalid `id`, when it is created.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```ts
|
|
30
|
+
* super({ baseUrl: '/api', authTokenResolver: DefaultNetworkRequestService.createAuthTokenReader({ id: 'shop' }) });
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
static createAuthTokenReader(opts = {}) {
|
|
34
|
+
const { token: key } = LocalStorageKeys.scoped({ id: opts.id });
|
|
35
|
+
return () => AuthTokenStore.read({ key });
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Throws for options that carry `noAuthPaths` or `noAuthPathRegex`, which `noAuth` replaced, and for
|
|
39
|
+
* a `noAuth` that is not `{ paths, regex }`: an ignored one would send the token to a path that is
|
|
40
|
+
* meant to go without it.
|
|
41
|
+
*/
|
|
42
|
+
static assertNoAuthOptions(opts) {
|
|
43
|
+
const removed = ['noAuthPaths', 'noAuthPathRegex'].filter((key) => key in opts.options);
|
|
44
|
+
if (removed.length) {
|
|
45
|
+
const verb = removed.length > 1 ? 'were' : 'was';
|
|
46
|
+
throw getError({
|
|
47
|
+
message: `[${opts.owner}] ${removed.join(' and ')} ${verb} replaced by noAuth: { paths, regex }; run "bun run ardor codemod no-auth"`,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
const noAuth = 'noAuth' in opts.options ? opts.options.noAuth : undefined;
|
|
51
|
+
const invalid = AbstractNetworkRequestService.findInvalidNoAuth({ noAuth });
|
|
52
|
+
if (invalid) {
|
|
53
|
+
throw getError({
|
|
54
|
+
message: `[${opts.owner}] noAuth takes { paths, regex }: invalid ${invalid}`,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** What is wrong with a `noAuth` value: its shape, `paths` or `regex`; `undefined` when nothing is. */
|
|
59
|
+
static findInvalidNoAuth(opts) {
|
|
60
|
+
const { noAuth } = opts;
|
|
61
|
+
if (noAuth === undefined) {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
if (Array.isArray(noAuth)) {
|
|
65
|
+
return 'shape (got an array)';
|
|
66
|
+
}
|
|
67
|
+
if (noAuth instanceof RegExp) {
|
|
68
|
+
return 'shape (got a RegExp)';
|
|
69
|
+
}
|
|
70
|
+
if (noAuth === null) {
|
|
71
|
+
return 'shape (got null)';
|
|
72
|
+
}
|
|
73
|
+
if (typeof noAuth !== 'object') {
|
|
74
|
+
return `shape (got a ${typeof noAuth})`;
|
|
75
|
+
}
|
|
76
|
+
const { paths, regex, ...rest } = noAuth;
|
|
77
|
+
const unknownKeys = Object.keys(rest);
|
|
78
|
+
if (unknownKeys.length) {
|
|
79
|
+
return `shape (unknown key ${unknownKeys.join(', ')})`;
|
|
80
|
+
}
|
|
81
|
+
const isPattern = (value) => typeof value === 'string' || value instanceof RegExp;
|
|
82
|
+
// A text in place of the list would match by substring, and leave more requests without a token.
|
|
83
|
+
if (paths !== undefined &&
|
|
84
|
+
!(Array.isArray(paths) && paths.every((p) => typeof p === 'string'))) {
|
|
85
|
+
return 'paths';
|
|
86
|
+
}
|
|
87
|
+
const isRegex = Array.isArray(regex) ? regex.every(isPattern) : isPattern(regex);
|
|
88
|
+
return regex === undefined || isRegex ? undefined : 'regex';
|
|
89
|
+
}
|
|
90
|
+
/** Throws unless a timeout that is on has a positive integer `milliseconds`. */
|
|
91
|
+
static assertTimeout(opts) {
|
|
92
|
+
const { timeout } = opts;
|
|
93
|
+
if (!timeout?.use) {
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const { milliseconds } = timeout;
|
|
97
|
+
if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) {
|
|
98
|
+
throw getError({
|
|
99
|
+
message: `[DefaultNetworkRequestService] timeout.milliseconds must be a positive integer, got ${milliseconds}`,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The token this service sends. The one way to supply a token: override it to read another
|
|
105
|
+
* store, or to hold the token in memory.
|
|
106
|
+
*/
|
|
107
|
+
resolveAuthToken() {
|
|
108
|
+
// The auth service knows where this application's session is kept (its `id` scopes the keys).
|
|
109
|
+
return this.authService
|
|
110
|
+
? (this.authService.getAuth() ?? undefined)
|
|
111
|
+
: AbstractNetworkRequestService.readAuthTokenFromStorage();
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Whether a request goes without a token: its `resource` is in `noAuth.paths`, or the resource, or
|
|
115
|
+
* the joined `paths`, matches `noAuth.regex`. To send no token at all (an API with no sign-in),
|
|
116
|
+
* set `noAuth: { regex: /./ }`.
|
|
117
|
+
*/
|
|
118
|
+
isNoAuthPath(opts) {
|
|
119
|
+
const { resource, paths } = opts;
|
|
120
|
+
if (resource && this.noAuthPaths?.includes(resource)) {
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
if (!this.noAuthPathRegexes.length) {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
const candidates = [resource, paths?.join('/')].filter((item) => !!item);
|
|
127
|
+
if (!candidates.length) {
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
return this.noAuthPathRegexes.some((regex) => {
|
|
131
|
+
return candidates.some((candidate) => {
|
|
132
|
+
regex.lastIndex = 0;
|
|
133
|
+
return regex.test(candidate);
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* The new token of a refresh response: `{ token: { value, type } }` or `{ token: '<jwt>' }`. A
|
|
139
|
+
* refresh keeps the same user, so nothing else is read. Override it for another shape. No token is
|
|
140
|
+
* a throw.
|
|
141
|
+
*/
|
|
142
|
+
readRefreshedToken(opts) {
|
|
143
|
+
const body = typeof opts.data === 'object' && opts.data !== null ? opts.data : {};
|
|
144
|
+
const { token } = body;
|
|
145
|
+
let record = {};
|
|
146
|
+
if (typeof token === 'string') {
|
|
147
|
+
record = { value: token };
|
|
148
|
+
}
|
|
149
|
+
else if (typeof token === 'object' && token !== null) {
|
|
150
|
+
record = token;
|
|
151
|
+
}
|
|
152
|
+
const value = 'value' in record ? record.value : undefined;
|
|
153
|
+
const type = 'type' in record ? record.type : undefined;
|
|
154
|
+
if (typeof value !== 'string' || !value) {
|
|
155
|
+
throw getError({ message: '[refreshToken] The refresh response carries no token' });
|
|
156
|
+
}
|
|
157
|
+
return { value, type: typeof type === 'string' ? type : App.TOKEN_TYPE };
|
|
158
|
+
}
|
|
159
|
+
/** Runs once when `refreshToken` threw. The place to send the user back to sign-in. */
|
|
160
|
+
onAuthFailure() {
|
|
161
|
+
return Promise.resolve();
|
|
162
|
+
}
|
|
163
|
+
/** The tracing id of a request, sent in `x-request-id`. Default `<application name>_<uuid>`. */
|
|
164
|
+
buildRequestTracingId(opts) {
|
|
165
|
+
return `${opts.applicationInfo.name}_${UuidV4Generator.generate()}`;
|
|
166
|
+
}
|
|
167
|
+
/** `noAuth.regex` as `RegExp`s; a string is compiled, and an invalid one is logged and dropped. */
|
|
168
|
+
compileNoAuthPathRegex(opts) {
|
|
169
|
+
const { input } = opts;
|
|
170
|
+
if (!input) {
|
|
171
|
+
return [];
|
|
172
|
+
}
|
|
173
|
+
const patterns = Array.isArray(input) ? input : [input];
|
|
174
|
+
const compiled = [];
|
|
175
|
+
for (const pattern of patterns) {
|
|
176
|
+
if (!pattern) {
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (pattern instanceof RegExp) {
|
|
180
|
+
compiled.push(pattern);
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
try {
|
|
184
|
+
compiled.push(new RegExp(pattern));
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
this.logger.error('[compileNoAuthPathRegex] Invalid noAuth.regex pattern: %s | error: %o', pattern, error);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return compiled;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* The `token` (`<type> <value>`, `Bearer` when the type is empty) and `provider` of the stored
|
|
194
|
+
* token. Throws an error with status 401 when there is no token.
|
|
195
|
+
*/
|
|
196
|
+
getRequestAuthorizationHeader() {
|
|
197
|
+
const authToken = this.resolveAuthToken();
|
|
198
|
+
if (!authToken?.value) {
|
|
199
|
+
throw getError({
|
|
200
|
+
message: '[dataProvider][getAuthHeader] Invalid auth token to fetch!',
|
|
201
|
+
statusCode: 401,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
return {
|
|
205
|
+
provider: authToken?.provider,
|
|
206
|
+
token: `${authToken?.type?.length ? authToken.type : App.TOKEN_TYPE} ${authToken.value}`,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
/** Adds headers to every request this service sends; a name already set is replaced, in any case. */
|
|
210
|
+
setHeaders(opts) {
|
|
211
|
+
this.headers = HttpHeaders.merge({ layers: [this.headers, opts.headers] });
|
|
212
|
+
}
|
|
213
|
+
/** Removes the headers set by name, in any case. */
|
|
214
|
+
removeHeaders(opts) {
|
|
215
|
+
if (!opts.keys?.length) {
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
for (const key of opts.keys) {
|
|
219
|
+
this.headers.delete(key);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
/** The timezone, then whatever `setHeaders` holds now. Both transports send these. */
|
|
223
|
+
getSessionHeaders() {
|
|
224
|
+
return Object.fromEntries(HttpHeaders.merge({
|
|
225
|
+
layers: [
|
|
226
|
+
{
|
|
227
|
+
[HTTP.Headers.TIMEZONE]: App.TIMEZONE,
|
|
228
|
+
[HTTP.Headers.TIMEZONE_OFFSET]: `${App.TIMEZONE_OFFSET}`,
|
|
229
|
+
},
|
|
230
|
+
this.headers,
|
|
231
|
+
],
|
|
232
|
+
}));
|
|
233
|
+
}
|
|
234
|
+
/** The request channel (`RequestChannel.WEB` unless configured) and a fresh tracing id. */
|
|
235
|
+
getTracingHeaders(opts) {
|
|
236
|
+
const { restDataProviderOptions, applicationInfo } = opts;
|
|
237
|
+
const channel = restDataProviderOptions.requestTracingChannel?.length
|
|
238
|
+
? restDataProviderOptions.requestTracingChannel
|
|
239
|
+
: RequestChannel.WEB;
|
|
240
|
+
return {
|
|
241
|
+
[HTTP.Headers.REQUEST_CHANNEL]: channel,
|
|
242
|
+
[HTTP.Headers.REQUEST_TRACING_ID]: this.buildRequestTracingId({ applicationInfo }),
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* The session headers, plus `authorization` and `x-auth-provider` unless `resource` is a no-auth
|
|
247
|
+
* path. Throws a 401 error for any other resource when there is no token.
|
|
248
|
+
*/
|
|
249
|
+
getRequestHeader(opts) {
|
|
250
|
+
const { resource } = opts;
|
|
251
|
+
const defaultHeaders = this.getSessionHeaders();
|
|
252
|
+
if (this.isNoAuthPath({ resource })) {
|
|
253
|
+
return defaultHeaders;
|
|
254
|
+
}
|
|
255
|
+
const authHeader = this.getRequestAuthorizationHeader();
|
|
256
|
+
return {
|
|
257
|
+
...defaultHeaders,
|
|
258
|
+
// A token need not name a provider; never send the string `undefined`.
|
|
259
|
+
...(authHeader.provider ? { [HTTP.Headers.AUTH_PROVIDER]: authHeader.provider } : {}),
|
|
260
|
+
[HTTP.Headers.AUTHORIZATION]: authHeader.token,
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* The body as it is sent and the content type to send it under. Override to encode another way. It
|
|
265
|
+
* takes `body` and `bodyType`, not a `payload`: an override written for these names would otherwise
|
|
266
|
+
* receive the wrapper and send it.
|
|
267
|
+
*/
|
|
268
|
+
encodeBody(opts) {
|
|
269
|
+
return RequestBodyEncoder.encode({ payload: { data: opts.body, type: opts.bodyType } });
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* The headers (session, auth, tracing, `x-request-count`, the `extra` header, and the content type
|
|
273
|
+
* of the encoded body) and the encoded body of a request. Throws as `getRequestHeader` does.
|
|
274
|
+
*/
|
|
275
|
+
getRequestProps(params) {
|
|
276
|
+
RequestBodyEncoder.assertPayload({ options: params, owner: this.constructor.name });
|
|
277
|
+
const { payload, resource, restDataProviderOptions, applicationInfo, requestCountData = RequestCountData.DATA_ONLY, extra, } = params;
|
|
278
|
+
const extraHeader = HttpExtraRequest.toHeader({ extra });
|
|
279
|
+
// Merged, not spread, so a per-request value replaces a static header in any case.
|
|
280
|
+
const headers = Object.fromEntries(HttpHeaders.merge({
|
|
281
|
+
layers: [
|
|
282
|
+
this.getRequestHeader({ resource }),
|
|
283
|
+
this.getTracingHeaders({ restDataProviderOptions, applicationInfo }),
|
|
284
|
+
{ [HTTP.Headers.REQUEST_COUNT_DATA]: requestCountData },
|
|
285
|
+
extraHeader ? { [HttpExtraRequest.HEADER]: extraHeader } : undefined,
|
|
286
|
+
],
|
|
287
|
+
}));
|
|
288
|
+
const encoded = this.encodeBody({ bodyType: payload?.type, body: payload?.data });
|
|
289
|
+
const props = {
|
|
290
|
+
headers: encoded.contentType
|
|
291
|
+
? { ...headers, [HTTP.Headers.CONTENT_TYPE]: encoded.contentType }
|
|
292
|
+
: headers,
|
|
293
|
+
body: encoded.body,
|
|
294
|
+
};
|
|
295
|
+
return props;
|
|
296
|
+
}
|
|
297
|
+
/** Reads a response by the request type. See `NetworkResponseReader.convert`. */
|
|
298
|
+
convertResponse(opts) {
|
|
299
|
+
return NetworkResponseReader.convert(opts);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
//# sourceMappingURL=network-request-base.js.map
|
|
@@ -1,20 +1,27 @@
|
|
|
1
1
|
import { NativeFetchNetworkRequest } from '@venizia/ignis-helpers/core';
|
|
2
|
-
import { type
|
|
3
|
-
import { type IEncodedBody, NetworkResponseReader } from '../../utilities/index.js';
|
|
2
|
+
import { type IAuthRecoveryOptions, type IDataSourceAuth, type IGetRequestPropsParams, type IGetRequestPropsResult, type INetworkResponse, type IResponseSchema, type INoAuthOptions, type RequestCountData, type TConstValue, type TRequestMethod, type TRequestTimeoutOptions, type TRequestType } from '../../common/index.js';
|
|
4
3
|
import type { DefaultAuthService } from './auth.js';
|
|
5
|
-
import {
|
|
4
|
+
import { AbstractNetworkRequestService } from './network-request-base.js';
|
|
6
5
|
/**
|
|
7
6
|
* The `normalized.code` of the 401 that answers a request whose session is gone: the user who sent it signed out or another user signed in while it was in flight.
|
|
8
|
-
*
|
|
9
|
-
* @useWhen you tell a request that failed because the session changed from any other 401
|
|
10
7
|
*/
|
|
11
8
|
export declare const SESSION_CHANGED_CODE = "ardor.network.session_changed";
|
|
12
9
|
/**
|
|
13
10
|
* The `normalized.code` of the 504 a request rejects with when it outlives the configured `timeout`.
|
|
14
|
-
*
|
|
15
|
-
* @useWhen you tell a request that timed out from any other failure
|
|
16
11
|
*/
|
|
17
12
|
export declare const NETWORK_TIMEOUT_CODE = "ardor.network.timeout";
|
|
13
|
+
/** What `doRequest` takes besides a schema. */
|
|
14
|
+
type TDoRequestOptions = IGetRequestPropsResult & {
|
|
15
|
+
/** @default this.baseUrl */
|
|
16
|
+
baseUrl?: string;
|
|
17
|
+
query?: Record<string, unknown>;
|
|
18
|
+
type: TRequestType;
|
|
19
|
+
method: TRequestMethod;
|
|
20
|
+
paths: string[];
|
|
21
|
+
requestCountData?: TConstValue<typeof RequestCountData>;
|
|
22
|
+
/** Aborts this request only: a refresh its 401 started runs on for the other requests. */
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
};
|
|
18
25
|
/**
|
|
19
26
|
* Sends the requests of the data provider with its own sender. The repositories of
|
|
20
27
|
* `@venizia/ardor/repository` send through IGNIS's `HttpDataSource`, from the optional peer
|
|
@@ -24,28 +31,20 @@ export declare const NETWORK_TIMEOUT_CODE = "ardor.network.timeout";
|
|
|
24
31
|
*
|
|
25
32
|
* The options hold data (the base URL, headers, the no-auth lists, the refresh path); behaviour is
|
|
26
33
|
* in the protected hooks, each taking one `opts` object, which a subclass overrides.
|
|
27
|
-
*
|
|
28
|
-
* @useWhen the data provider needs to send requests with timeout, auth recovery and normalized errors
|
|
29
|
-
* @insteadOf a hand-written `fetch` wrapper
|
|
30
34
|
*/
|
|
31
|
-
export declare class DefaultNetworkRequestService extends
|
|
32
|
-
/** Resources sent without a token, matched exactly. */
|
|
33
|
-
protected noAuthPaths?: string[];
|
|
34
|
-
/** `noAuthPathRegex` compiled; a resource matching any is sent without a token. */
|
|
35
|
-
protected noAuthPathRegexes: RegExp[];
|
|
36
|
-
/** Headers added to every request. */
|
|
37
|
-
protected headers: Headers;
|
|
35
|
+
export declare class DefaultNetworkRequestService extends AbstractNetworkRequestService {
|
|
38
36
|
protected networkRequest: NativeFetchNetworkRequest;
|
|
39
37
|
/** The origin and base path requests are sent to; an empty one makes `doRequest` throw. */
|
|
40
38
|
protected baseUrl: string;
|
|
41
39
|
protected authRecovery?: IAuthRecoveryOptions;
|
|
42
|
-
protected authService?: DefaultAuthService;
|
|
43
40
|
/** How long a request may take; see `IRestDataProviderOptions.timeout`. */
|
|
44
41
|
protected timeout: TRequestTimeoutOptions;
|
|
45
42
|
private readonly recovery;
|
|
46
43
|
/** The session each data source request was sent under, keyed by the context object IGNIS hands to both hooks. */
|
|
47
44
|
private readonly sentSessions;
|
|
48
|
-
constructor(opts:
|
|
45
|
+
constructor(opts: {
|
|
46
|
+
/** Which requests go without a token. */
|
|
47
|
+
noAuth?: INoAuthOptions;
|
|
49
48
|
/** The name of the underlying network request helper. */
|
|
50
49
|
name: string;
|
|
51
50
|
/**
|
|
@@ -74,43 +73,6 @@ export declare class DefaultNetworkRequestService extends BaseService {
|
|
|
74
73
|
* and so does a raw body (`FormData`, `Blob`, `URLSearchParams`, bytes, a stream) with none, so `fetch` writes it.
|
|
75
74
|
*/
|
|
76
75
|
private toSendHeaders;
|
|
77
|
-
/**
|
|
78
|
-
* The token under the unscoped session key (`AuthTokenStore.read`), `undefined` outside a browser, for an
|
|
79
|
-
* application with no `id`. With an application `id` the session is under other keys: use
|
|
80
|
-
* `createAuthTokenReader({ id })`, the `HttpDataSource` `getDataSourceAuth()` of the data provider, or `authService.getAuth`.
|
|
81
|
-
*/
|
|
82
|
-
static readAuthTokenFromStorage(): IAuthTokenRecord | undefined;
|
|
83
|
-
/**
|
|
84
|
-
* A reader of the stored token of the application with this `id` (`IApplicationInfo.id`): the same
|
|
85
|
-
* key `DefaultAuthService.getAuth` reads (`LocalStorageKeys.scoped({ id }).token`). Without an `id` it
|
|
86
|
-
* is `readAuthTokenFromStorage`. Throws for an invalid `id`, when it is created.
|
|
87
|
-
*
|
|
88
|
-
* @example
|
|
89
|
-
* ```ts
|
|
90
|
-
* super({ baseUrl: '/api', authTokenResolver: DefaultNetworkRequestService.createAuthTokenReader({ id: 'shop' }) });
|
|
91
|
-
* ```
|
|
92
|
-
*/
|
|
93
|
-
static createAuthTokenReader(opts?: {
|
|
94
|
-
id?: string;
|
|
95
|
-
}): () => IAuthTokenRecord | undefined;
|
|
96
|
-
/** Throws unless a timeout that is on has a positive integer `milliseconds`. */
|
|
97
|
-
static assertTimeout(opts: {
|
|
98
|
-
timeout?: TRequestTimeoutOptions;
|
|
99
|
-
}): void;
|
|
100
|
-
/**
|
|
101
|
-
* The token this service sends. The one way to supply a token: override it to read another
|
|
102
|
-
* store, or to hold the token in memory.
|
|
103
|
-
*/
|
|
104
|
-
protected resolveAuthToken(): IAuthTokenRecord | undefined;
|
|
105
|
-
/**
|
|
106
|
-
* Whether a request goes without a token: its `resource` is in `noAuthPaths`, or the resource, or
|
|
107
|
-
* the joined `paths`, matches `noAuthPathRegex`. To send no token at all (an API with no sign-in),
|
|
108
|
-
* set `noAuthPathRegex: /./`.
|
|
109
|
-
*/
|
|
110
|
-
protected isNoAuthPath(opts: {
|
|
111
|
-
resource?: string;
|
|
112
|
-
paths?: string[];
|
|
113
|
-
}): boolean;
|
|
114
76
|
/**
|
|
115
77
|
* Refreshes the session after a 401. `true`: refreshed, the request is retried; `false`: this
|
|
116
78
|
* service has no refresh, or the session changed while the request was in flight (another user
|
|
@@ -121,27 +83,6 @@ export declare class DefaultNetworkRequestService extends BaseService {
|
|
|
121
83
|
* with no path or no `authService` it answers `false`.
|
|
122
84
|
*/
|
|
123
85
|
protected refreshToken(): Promise<boolean>;
|
|
124
|
-
/**
|
|
125
|
-
* The new token of a refresh response: `{ token: { value, type } }` or `{ token: '<jwt>' }`. A
|
|
126
|
-
* refresh keeps the same user, so nothing else is read. Override it for another shape. No token is
|
|
127
|
-
* a throw.
|
|
128
|
-
*/
|
|
129
|
-
protected readRefreshedToken(opts: {
|
|
130
|
-
data: unknown;
|
|
131
|
-
}): {
|
|
132
|
-
value: string;
|
|
133
|
-
type: string;
|
|
134
|
-
};
|
|
135
|
-
/** Runs once when `refreshToken` threw. The place to send the user back to sign-in. */
|
|
136
|
-
protected onAuthFailure(): Promise<void>;
|
|
137
|
-
/** The tracing id of a request, sent in `x-request-id`. Default `<application name>_<uuid>`. */
|
|
138
|
-
protected buildRequestTracingId(opts: {
|
|
139
|
-
applicationInfo: IApplicationInfo;
|
|
140
|
-
}): string;
|
|
141
|
-
/** `noAuthPathRegex` as `RegExp`s; a string is compiled, and an invalid one is logged and dropped. */
|
|
142
|
-
protected compileNoAuthPathRegex(opts: {
|
|
143
|
-
input?: TNoAuthPathRegex;
|
|
144
|
-
}): RegExp[];
|
|
145
86
|
/**
|
|
146
87
|
* Refreshes the session, once for every 401 in flight on either transport (see `AuthRecoveryHelper`).
|
|
147
88
|
* Also what `DefaultAuthProvider.refreshToken` calls, so a refresh is made in one place.
|
|
@@ -171,68 +112,24 @@ export declare class DefaultNetworkRequestService extends BaseService {
|
|
|
171
112
|
* options), and a 401 joins this service's shared `refresh`. A no-auth path gets no token.
|
|
172
113
|
*/
|
|
173
114
|
getDataSourceAuth(opts?: Pick<IGetRequestPropsParams, 'restDataProviderOptions' | 'applicationInfo'>): IDataSourceAuth;
|
|
174
|
-
/**
|
|
175
|
-
* The `token` (`<type> <value>`, `Bearer` when the type is empty) and `provider` of the stored
|
|
176
|
-
* token. Throws an error with status 401 when there is no token.
|
|
177
|
-
*/
|
|
178
|
-
getRequestAuthorizationHeader(): {
|
|
179
|
-
provider: string | undefined;
|
|
180
|
-
token: string;
|
|
181
|
-
};
|
|
182
|
-
/** Adds headers to every request this service sends; a name already set is replaced, in any case. */
|
|
183
|
-
setHeaders(opts: {
|
|
184
|
-
headers: HeadersInit;
|
|
185
|
-
}): void;
|
|
186
|
-
/** Removes the headers set by name, in any case. */
|
|
187
|
-
removeHeaders(opts: {
|
|
188
|
-
keys: string[];
|
|
189
|
-
}): void;
|
|
190
|
-
/** The timezone, then whatever `setHeaders` holds now. Both transports send these. */
|
|
191
|
-
protected getSessionHeaders(): Record<string, string>;
|
|
192
|
-
/** The request channel (`RequestChannel.WEB` unless configured) and a fresh tracing id. */
|
|
193
|
-
protected getTracingHeaders(opts: Pick<IGetRequestPropsParams, 'restDataProviderOptions' | 'applicationInfo'>): Record<string, string>;
|
|
194
|
-
/**
|
|
195
|
-
* The session headers, plus `authorization` and `x-auth-provider` unless `resource` is a no-auth
|
|
196
|
-
* path. Throws a 401 error for any other resource when there is no token.
|
|
197
|
-
*/
|
|
198
|
-
getRequestHeader(opts: {
|
|
199
|
-
resource: string;
|
|
200
|
-
}): Record<string, string>;
|
|
201
|
-
/** The body as it is sent and the content type to send it under. Override to encode another way. */
|
|
202
|
-
protected encodeBody(opts: {
|
|
203
|
-
bodyType?: string;
|
|
204
|
-
body: unknown;
|
|
205
|
-
}): IEncodedBody;
|
|
206
|
-
/**
|
|
207
|
-
* The headers (session, auth, tracing, `x-request-count`, the `extra` header, and the content type
|
|
208
|
-
* of the encoded body) and the encoded body of a request. Throws as `getRequestHeader` does.
|
|
209
|
-
*/
|
|
210
|
-
getRequestProps(params: IGetRequestPropsParams): IGetRequestPropsResult;
|
|
211
|
-
/** Reads a response by the request type. See `NetworkResponseReader.convert`. */
|
|
212
|
-
convertResponse<TData = unknown>(opts: Parameters<typeof NetworkResponseReader.convert<TData>>[0]): {
|
|
213
|
-
data: TData;
|
|
214
|
-
count?: number;
|
|
215
|
-
total?: number;
|
|
216
|
-
};
|
|
217
115
|
/**
|
|
218
116
|
* Sends the request and reads the response by `type`. Throws when `baseUrl` (the option, else the
|
|
219
117
|
* service's) is empty. A 401 on a path that can recover triggers `refresh` and, if it refreshed,
|
|
220
118
|
* one retry with the new token. Any other non-2xx response, or a retry that still fails, throws
|
|
221
119
|
* the error read from the response. An aborted `signal` rejects with its reason, and a request
|
|
222
|
-
* that outlives the service's `timeout` rejects with a 504 coded `NETWORK_TIMEOUT_CODE`.
|
|
120
|
+
* that outlives the service's `timeout` rejects with a 504 coded `NETWORK_TIMEOUT_CODE`. With a
|
|
121
|
+
* `schema`, `data` is what it checked and typed; what it refuses, an empty answer included, throws a
|
|
122
|
+
* `FetchSchemaError` (502).
|
|
223
123
|
*/
|
|
224
|
-
doRequest<TResult
|
|
225
|
-
|
|
226
|
-
baseUrl?: string;
|
|
227
|
-
query?: Record<string, unknown>;
|
|
228
|
-
type: TRequestType;
|
|
229
|
-
method: TRequestMethod;
|
|
230
|
-
paths: string[];
|
|
231
|
-
requestCountData?: TConstValue<typeof RequestCountData>;
|
|
232
|
-
/** Aborts this request only: a refresh its 401 started runs on for the other requests. */
|
|
233
|
-
signal?: AbortSignal;
|
|
124
|
+
doRequest<TResult>(opts: TDoRequestOptions & {
|
|
125
|
+
schema: IResponseSchema<TResult>;
|
|
234
126
|
}): Promise<INetworkResponse<TResult>>;
|
|
127
|
+
/** As above with no schema: the `data` of the response is `unknown`. */
|
|
128
|
+
doRequest(opts: TDoRequestOptions & {
|
|
129
|
+
schema?: IResponseSchema;
|
|
130
|
+
}): Promise<INetworkResponse>;
|
|
235
131
|
/** `doRequest` once the URL is checked: the send, the refresh and retry after a 401, then the read. */
|
|
236
132
|
private sendAndRead;
|
|
237
133
|
}
|
|
134
|
+
export {};
|
|
238
135
|
//# sourceMappingURL=network-request.d.ts.map
|