@venizia/ardor-kernel 0.5.0-0 → 0.5.0-10

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 (30) hide show
  1. package/README.md +3 -3
  2. package/dist/base/applications/abstract.d.ts +5 -3
  3. package/dist/base/applications/abstract.js +44 -35
  4. package/dist/base/services/auth.js +3 -3
  5. package/dist/base/services/network-request.d.ts +6 -8
  6. package/dist/base/services/network-request.js +58 -60
  7. package/dist/common/constants.d.ts +9 -78
  8. package/dist/common/constants.js +9 -123
  9. package/dist/common/types.d.ts +2 -0
  10. package/dist/helpers/index.d.ts +0 -1
  11. package/dist/helpers/index.js +0 -1
  12. package/dist/helpers/networks/auth-recovery.d.ts +2 -3
  13. package/dist/helpers/networks/auth-recovery.js +6 -4
  14. package/dist/helpers/networks/index.d.ts +0 -3
  15. package/dist/helpers/networks/index.js +0 -3
  16. package/dist/utilities/file.d.ts +16 -0
  17. package/dist/utilities/file.js +30 -0
  18. package/dist/utilities/index.d.ts +3 -0
  19. package/dist/utilities/index.js +3 -0
  20. package/dist/{helpers/networks → utilities}/network-response-reader.d.ts +3 -11
  21. package/dist/{helpers/networks → utilities}/network-response-reader.js +18 -67
  22. package/dist/{helpers/networks → utilities}/request-body-encoder.d.ts +1 -1
  23. package/dist/{helpers/networks → utilities}/request-body-encoder.js +2 -2
  24. package/dist/utilities/value.d.ts +0 -8
  25. package/dist/utilities/value.js +0 -10
  26. package/package.json +14 -14
  27. package/dist/helpers/networks/headers.d.ts +0 -16
  28. package/dist/helpers/networks/headers.js +0 -32
  29. /package/dist/{helpers → utilities}/auth-token-store.d.ts +0 -0
  30. /package/dist/{helpers → utilities}/auth-token-store.js +0 -0
package/README.md CHANGED
@@ -23,9 +23,9 @@ which re-exports this package.
23
23
  | Providers | `BaseProvider` |
24
24
  | Decorators | `api()` - logs and rethrows a failing API method; the IGNIS stereotypes it re-exports (`component`, `configuration`, `datasource`, `inject`, `injectable`, `model`, `provide`, `repository`, `service`) |
25
25
  | Bindings | `CoreBindings`, `LocalStorageKeys`, `BindingKeys`, `BindingNamespaces` |
26
- | Constants | `RequestMethods`, `RequestTypes`, `RequestBodyTypes`, `RequestCountData`, `HeaderConstants`, `Environments`, `App`, `Authentication`, `StorageAreas`, `RequestChannel` |
27
- | Network | `NetworkHeaders`, `RequestBodyEncoder`, `NetworkResponseReader`, `AuthRecovery`, `AuthTokenStore` (the fetch transport is IGNIS's `NativeFetchNetworkRequest`) |
28
- | Utilities | `ValueUtility` (`isDefined`, `isString`, `isNumber`, `isObject`, `isValidDate`), `BrowserUtility.isBrowser`, `FileUtility.toDataUrl`, `RuntimeConfig.get` and `RuntimeConfig.getRequired` (with `RUNTIME_CONFIG_GLOBAL`, `RUNTIME_CONFIG_REQUIRED_CODE` and `RUNTIME_CONFIG_INVALID_CODE`), `BrowserStorage`, `BrowserClipboard`, `StorageCodecs`; the earlier bare names are removed (`bun run ardor codemod namespace` moves your code) |
26
+ | Constants | `RequestMethods`, `RequestTypes`, `RequestBodyTypes`, `RequestCountData`, `Environments`, `App`, `StorageAreas`, `RequestChannel` |
27
+ | Network | `RequestBodyEncoder`, `NetworkResponseReader`, `AuthRecoveryHelper`, `AuthTokenStore` (the fetch transport is IGNIS's `NativeFetchNetworkRequest`) |
28
+ | Utilities | `ValueUtility` (`isDefined`, `isString`, `isNumber`), `BrowserUtility.isBrowser`, `FileUtility.toDataUrl` and `FileUtility.save`, `RuntimeConfig.get` and `RuntimeConfig.getRequired` (with `RUNTIME_CONFIG_GLOBAL`, `RUNTIME_CONFIG_REQUIRED_CODE` and `RUNTIME_CONFIG_INVALID_CODE`), `BrowserStorage`, `BrowserClipboard`, `StorageCodecs`; the earlier bare names are removed (`bun run ardor codemod namespace` moves your code) |
29
29
  | Types | `IdType`, `IAuthUser`, `ValueOrPromise`, `ValueOf`, `TConstValue`, `TPaths`, `TFullPaths`, `ISendParams`, `IRestDataProviderOptions`, `IApplicationInfo`, ... |
30
30
 
31
31
  ## License
@@ -74,9 +74,8 @@ export declare abstract class AbstractArdorApplication extends Container {
74
74
  /** The feature packages this application mounts, bound under `CoreBindings.FEATURES`. */
75
75
  features(): Array<IFeatureBase>;
76
76
  /**
77
- * `artifacts()` with each group without `content` replaced by the index its `resolve()` returns.
78
- * Resolving imports the modules, which decorates their classes: it must finish before
79
- * `registerArtifacts()` reads the discovery list.
77
+ * `artifacts()` with each group replaced by its index. Resolving imports the modules, which
78
+ * decorates their classes: it must finish before `registerArtifacts()` reads the discovery list.
80
79
  */
81
80
  private resolveArtifactIndexes;
82
81
  /**
@@ -85,6 +84,9 @@ export declare abstract class AbstractArdorApplication extends Container {
85
84
  * its inlined `content` is checked.
86
85
  */
87
86
  private assertIndexed;
87
+ /** Every class list of an index: the six built-in fields, then `custom.<type>` for each defined type. */
88
+ private static listsOf;
89
+ private assertListed;
88
90
  /**
89
91
  * Binds the features after the stereotypes, so `bindingList()` and `bindContext()` still override
90
92
  * what a feature provides. A name is unique, and every configuration and artifact a feature lists
@@ -1,4 +1,4 @@
1
- import { ArtifactBindingKeys, ArtifactNamespaces, BindingNamespaces, MetadataRegistry, } from '@venizia/ignis-kernel/metadata';
1
+ import { ArtifactBindingKeys, ArtifactGroup, ArtifactNamespaces, ArtifactTypes, BindingNamespaces, MetadataRegistry, } from '@venizia/ignis-kernel/metadata';
2
2
  import { BindingKeys, BindingScopes, Container, getError, } from '@venizia/ignis-inversion';
3
3
  import { CoreBindings, } from '../../common/index.js';
4
4
  import { ApplicationInfoGuard } from './app-info.js';
@@ -96,9 +96,10 @@ export class AbstractArdorApplication extends Container {
96
96
  if (metadata?.allowOverride === false) {
97
97
  this.lockedKeys.set(key, target);
98
98
  }
99
+ const definition = metadata ? ArtifactTypes.definitionOf({ type: metadata.type }) : undefined;
99
100
  this.bind({ key })
100
101
  .toClass(target)
101
- .setScope(metadata?.scope ?? BindingScopes.SINGLETON);
102
+ .setScope(metadata?.scope ?? definition?.scope ?? BindingScopes.SINGLETON);
102
103
  for (const entry of registry.getProvideMetadata({ target })) {
103
104
  this.bind({ key: entry.key })
104
105
  .toProvider((container) => {
@@ -191,27 +192,18 @@ export class AbstractArdorApplication extends Container {
191
192
  return [];
192
193
  }
193
194
  /**
194
- * `artifacts()` with each group without `content` replaced by the index its `resolve()` returns.
195
- * Resolving imports the modules, which decorates their classes: it must finish before
196
- * `registerArtifacts()` reads the discovery list.
195
+ * `artifacts()` with each group replaced by its index. Resolving imports the modules, which
196
+ * decorates their classes: it must finish before `registerArtifacts()` reads the discovery list.
197
197
  */
198
198
  async resolveArtifactIndexes() {
199
199
  const resolved = [];
200
200
  for (const entry of this.artifacts()) {
201
- const group = entry;
202
- if (group.isArtifactGroup !== true || group.content !== undefined) {
201
+ if (!ArtifactGroup.isGroup(entry)) {
203
202
  resolved.push(entry);
204
203
  continue;
205
204
  }
206
- // Such a group (`ArtifactGroup.define()`, `application()`) resolves only through a resolver in
207
- // IGNIS's realm, which this package cannot reach; skipping it would bind none of its classes.
208
- if (typeof group.resolve !== 'function') {
209
- throw getError({
210
- message: '[artifacts] A group has neither content nor resolve | Return AutoArtifacts from @venizia/ignis-boot/auto, or build with IgnisArtifactsPlugin so the group arrives with its content',
211
- });
212
- }
213
- const result = await group.resolve();
214
- resolved.push(result);
205
+ const index = await ArtifactGroup.resolveContent({ group: entry });
206
+ resolved.push(index);
215
207
  }
216
208
  return resolved;
217
209
  }
@@ -228,21 +220,36 @@ export class AbstractArdorApplication extends Container {
228
220
  if (!index) {
229
221
  continue;
230
222
  }
231
- for (const kind of ArtifactIndexKinds) {
232
- for (const [position, target] of (index[kind] ?? []).entries()) {
233
- // A cycle leaves `undefined` here: a bundler's eager class list is built while the module of
234
- // the class is still evaluating. Say so, rather than fail on `.name` below.
235
- if (typeof target !== 'function') {
236
- throw getError({
237
- message: `[artifacts] '${kind}' lists an entry that is not a class (position ${position}) | Usually an import cycle: the module that imports the index (or @venizia/ignis-boot/auto) must not define decorated classes or be imported by them`,
238
- });
239
- }
240
- if (!discovered.has(target)) {
241
- throw getError({
242
- message: `[artifacts] '${kind}' lists ${target.name}, which was never discovered | Decorate it with its stereotype and regenerate the index`,
243
- });
244
- }
245
- }
223
+ for (const { field, targets } of AbstractArdorApplication.listsOf({ index })) {
224
+ this.assertListed({ field, targets, discovered });
225
+ }
226
+ }
227
+ }
228
+ /** Every class list of an index: the six built-in fields, then `custom.<type>` for each defined type. */
229
+ static listsOf(opts) {
230
+ const { index } = opts;
231
+ return [
232
+ ...ArtifactIndexKinds.map((field) => ({ field, targets: index[field] ?? [] })),
233
+ ...Object.entries(index.custom ?? {}).map(([type, targets]) => ({
234
+ field: `custom.${type}`,
235
+ targets,
236
+ })),
237
+ ];
238
+ }
239
+ assertListed(opts) {
240
+ const { field, targets, discovered } = opts;
241
+ for (const [position, target] of targets.entries()) {
242
+ // A cycle leaves `undefined` here: a bundler's eager class list is built while the module of
243
+ // the class is still evaluating. Say so, rather than fail on `.name` below.
244
+ if (typeof target !== 'function') {
245
+ throw getError({
246
+ message: `[artifacts] '${field}' lists an entry that is not a class (position ${position}) | Usually an import cycle: the module that imports the index (or @venizia/ignis-boot/auto) must not define decorated classes or be imported by them`,
247
+ });
248
+ }
249
+ if (!discovered.has(target)) {
250
+ throw getError({
251
+ message: `[artifacts] '${field}' lists ${target.name}, which was never discovered | Decorate it with its stereotype and regenerate the index`,
252
+ });
246
253
  }
247
254
  }
248
255
  }
@@ -269,16 +276,18 @@ export class AbstractArdorApplication extends Container {
269
276
  });
270
277
  }
271
278
  }
272
- for (const group of ArtifactIndexKinds) {
273
- for (const [position, target] of (feature.artifacts?.[group] ?? []).entries()) {
279
+ for (const { field, targets } of AbstractArdorApplication.listsOf({
280
+ index: feature.artifacts ?? {},
281
+ })) {
282
+ for (const [position, target] of targets.entries()) {
274
283
  if (typeof target !== 'function') {
275
284
  throw getError({
276
- message: `[features] '${feature.name}' lists an entry in artifacts.${group} that is not a class (position ${position}) | Usually an import cycle: the feature module must not be imported by the classes it lists`,
285
+ message: `[features] '${feature.name}' lists an entry in artifacts.${field} that is not a class (position ${position}) | Usually an import cycle: the feature module must not be imported by the classes it lists`,
277
286
  });
278
287
  }
279
288
  if (!discovered.has(target)) {
280
289
  throw getError({
281
- message: `[features] '${feature.name}' lists ${target.name} in artifacts.${group}, which was never discovered | Decorate it with its stereotype and import its module before start()`,
290
+ message: `[features] '${feature.name}' lists ${target.name} in artifacts.${field}, which was never discovered | Decorate it with its stereotype and import its module before start()`,
282
291
  });
283
292
  }
284
293
  }
@@ -11,10 +11,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
11
  return function (target, key) { decorator(target, key, paramIndex); }
12
12
  };
13
13
  var DefaultAuthService_1;
14
+ import { RecordUtility } from '@venizia/ignis-helpers/core';
14
15
  import { getError, inject } from '@venizia/ignis-inversion';
15
16
  import { CoreBindings, LocalStorageKeys, StorageAreas, } from '../../common/index.js';
16
- import { AuthTokenStore } from '../../helpers/index.js';
17
- import { BrowserStorage, StorageCodecs } from '../../utilities/index.js';
17
+ import { AuthTokenStore, BrowserStorage, StorageCodecs } from '../../utilities/index.js';
18
18
  import { BaseService } from './base.js';
19
19
  /**
20
20
  * Keeps the signed-in session (token, identity, roles) in `localStorage`, everything under
@@ -179,7 +179,7 @@ let DefaultAuthService = DefaultAuthService_1 = class DefaultAuthService extends
179
179
  }
180
180
  /** A stored identity is data from the browser: an object whose known fields, when present, have their type. */
181
181
  isAuthUser(value) {
182
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
182
+ if (!RecordUtility.isPlainRecord(value)) {
183
183
  return false;
184
184
  }
185
185
  const userId = 'userId' in value ? value.userId : undefined;
@@ -1,6 +1,6 @@
1
1
  import { NativeFetchNetworkRequest } from '@venizia/ignis-helpers/core';
2
2
  import { type IApplicationInfo, type IAuthTokenRecord, type IAuthRecoveryOptions, type IDataSourceAuth, type IGetRequestPropsParams, type IGetRequestPropsResult, type INetworkResponse, type INoAuthOptions, RequestCountData, type TConstValue, type TNoAuthPathRegex, type TRequestMethod, type TRequestTimeoutOptions, type TRequestType } from '../../common/index.js';
3
- import { type IEncodedBody, NetworkResponseReader } from '../../helpers/index.js';
3
+ import { type IEncodedBody, NetworkResponseReader } from '../../utilities/index.js';
4
4
  import type { DefaultAuthService } from './auth.js';
5
5
  import { BaseService } from './base.js';
6
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. */
@@ -22,8 +22,8 @@ export declare class DefaultNetworkRequestService extends BaseService {
22
22
  protected noAuthPaths?: string[];
23
23
  /** `noAuthPathRegex` compiled; a resource matching any is sent without a token. */
24
24
  protected noAuthPathRegexes: RegExp[];
25
- /** Headers added to every request, keyed by lowercase name. */
26
- protected headers: Record<string, string>;
25
+ /** Headers added to every request. */
26
+ protected headers: Headers;
27
27
  protected networkRequest: NativeFetchNetworkRequest;
28
28
  /** The origin and base path requests are sent to; an empty one makes `doRequest` throw. */
29
29
  protected baseUrl: string;
@@ -59,12 +59,10 @@ export declare class DefaultNetworkRequestService extends BaseService {
59
59
  });
60
60
  /**
61
61
  * The headers of one call: its own alone, or the ones `setHeaders` holds now. The transport keeps no
62
- * default of ours, so a removed header is gone; a call that names no `content-type` sends none (`null`)
63
- * when its body is one `fetch` types itself (`FormData`, `Blob`, bytes, a stream), so a multipart boundary is written.
62
+ * default of ours, so a removed header is gone. A call with headers but no `content-type` sends none (`null`),
63
+ * and so does a raw body (`FormData`, `Blob`, `URLSearchParams`, bytes, a stream) with none, so `fetch` writes it.
64
64
  */
65
65
  private toSendHeaders;
66
- /** A body the platform `fetch` gives a content type of its own, or none: it is sent as it is. */
67
- private static isRawBody;
68
66
  /**
69
67
  * The token under the unscoped session key (`AuthTokenStore.read`), `undefined` outside a browser, for an
70
68
  * application with no `id`. With an application `id` the session is under other keys: use
@@ -134,7 +132,7 @@ export declare class DefaultNetworkRequestService extends BaseService {
134
132
  input?: TNoAuthPathRegex;
135
133
  }): RegExp[];
136
134
  /**
137
- * Refreshes the session, once for every 401 in flight on either transport (see `AuthRecovery`).
135
+ * Refreshes the session, once for every 401 in flight on either transport (see `AuthRecoveryHelper`).
138
136
  * Also what `DefaultAuthProvider.refreshToken` calls, so a refresh is made in one place.
139
137
  */
140
138
  refresh(): Promise<boolean>;
@@ -1,10 +1,11 @@
1
1
  import { getError } from '@venizia/ignis-inversion';
2
2
  import { HTTP } from '@venizia/ignis-helpers/common';
3
- import { NativeFetchNetworkRequest } from '@venizia/ignis-helpers/core';
3
+ import { HttpHeaders, HttpResponseReader, NativeFetcher, NativeFetchNetworkRequest, } from '@venizia/ignis-helpers/core';
4
4
  import { UuidV4Generator } from '@venizia/ignis-helpers/uuid';
5
5
  import { HttpExtraRequest } from '@venizia/ignis-kernel/repository';
6
- import { App, HeaderConstants, LocalStorageKeys, RequestChannel, RequestCountData, RequestMethods, RequestTypes, } from '../../common/index.js';
7
- import { AuthRecovery, AuthTokenStore, NetworkHeaders, RequestBodyEncoder, NetworkResponseReader, } from '../../helpers/index.js';
6
+ import { App, LocalStorageKeys, RequestChannel, RequestCountData, RequestMethods, RequestTypes, } from '../../common/index.js';
7
+ import { AuthRecoveryHelper } from '../../helpers/index.js';
8
+ import { AuthTokenStore, NetworkResponseReader, RequestBodyEncoder, } from '../../utilities/index.js';
8
9
  import { BaseService } from './base.js';
9
10
  /** 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. */
10
11
  export const SESSION_CHANGED_CODE = 'ardor.network.session_changed';
@@ -28,14 +29,13 @@ export class DefaultNetworkRequestService extends BaseService {
28
29
  const { name, baseUrl = '', headers = {}, noAuthPaths, noAuthPathRegex, authRecovery, authService, timeout = { use: false }, } = opts;
29
30
  DefaultNetworkRequestService.assertTimeout({ timeout });
30
31
  this.timeout = timeout;
31
- this.headers = NetworkHeaders.toRecord({ headers });
32
+ this.headers = HttpHeaders.merge({ layers: [headers] });
32
33
  this.noAuthPaths = noAuthPaths;
33
34
  this.noAuthPathRegexes = this.compileNoAuthPathRegex({ input: noAuthPathRegex });
34
35
  this.baseUrl = baseUrl;
35
36
  this.authRecovery = authRecovery;
36
37
  this.authService = authService;
37
- this.recovery = new AuthRecovery({
38
- logger: this.logger,
38
+ this.recovery = new AuthRecoveryHelper({
39
39
  getRefreshTokenPath: () => this.authRecovery?.refreshTokenPath,
40
40
  refresh: () => this.refreshToken(),
41
41
  onFailure: () => this.onAuthFailure(),
@@ -49,30 +49,24 @@ export class DefaultNetworkRequestService extends BaseService {
49
49
  }
50
50
  /**
51
51
  * The headers of one call: its own alone, or the ones `setHeaders` holds now. The transport keeps no
52
- * default of ours, so a removed header is gone; a call that names no `content-type` sends none (`null`)
53
- * when its body is one `fetch` types itself (`FormData`, `Blob`, bytes, a stream), so a multipart boundary is written.
52
+ * default of ours, so a removed header is gone. A call with headers but no `content-type` sends none (`null`),
53
+ * and so does a raw body (`FormData`, `Blob`, `URLSearchParams`, bytes, a stream) with none, so `fetch` writes it.
54
54
  */
55
55
  toSendHeaders(opts) {
56
- const sent = Object.fromEntries(new Headers(opts.headers ?? this.headers));
57
- if (opts.headers && !(HeaderConstants.CONTENT_TYPE in sent)) {
58
- sent[HeaderConstants.CONTENT_TYPE] = null;
56
+ const sent = {
57
+ ...Object.fromEntries(new Headers(opts.headers ?? this.headers)),
58
+ ...opts.extra,
59
+ };
60
+ if (opts.headers && !(HTTP.Headers.CONTENT_TYPE in sent)) {
61
+ sent[HTTP.Headers.CONTENT_TYPE] = null;
59
62
  }
60
- if (DefaultNetworkRequestService.isRawBody({ body: opts.body }) &&
61
- !sent[HeaderConstants.CONTENT_TYPE]) {
62
- sent[HeaderConstants.CONTENT_TYPE] = null;
63
+ if (typeof opts.body !== 'string' &&
64
+ NativeFetcher.isRawBody(opts.body) &&
65
+ !sent[HTTP.Headers.CONTENT_TYPE]) {
66
+ sent[HTTP.Headers.CONTENT_TYPE] = null;
63
67
  }
64
68
  return sent;
65
69
  }
66
- /** A body the platform `fetch` gives a content type of its own, or none: it is sent as it is. */
67
- static isRawBody(opts) {
68
- const { body } = opts;
69
- return (body instanceof FormData ||
70
- body instanceof Blob ||
71
- body instanceof URLSearchParams ||
72
- body instanceof ArrayBuffer ||
73
- ArrayBuffer.isView(body) ||
74
- body instanceof ReadableStream);
75
- }
76
70
  /**
77
71
  * The token under the unscoped session key (`AuthTokenStore.read`), `undefined` outside a browser, for an
78
72
  * application with no `id`. With an application `id` the session is under other keys: use
@@ -230,7 +224,7 @@ export class DefaultNetworkRequestService extends BaseService {
230
224
  if (typeof value !== 'string' || !value) {
231
225
  throw getError({ message: '[refreshToken] The refresh response carries no token' });
232
226
  }
233
- return { value, type: typeof type === 'string' ? type : 'Bearer' };
227
+ return { value, type: typeof type === 'string' ? type : App.TOKEN_TYPE };
234
228
  }
235
229
  /** Runs once when `refreshToken` threw. The place to send the user back to sign-in. */
236
230
  onAuthFailure() {
@@ -267,7 +261,7 @@ export class DefaultNetworkRequestService extends BaseService {
267
261
  return compiled;
268
262
  }
269
263
  /**
270
- * Refreshes the session, once for every 401 in flight on either transport (see `AuthRecovery`).
264
+ * Refreshes the session, once for every 401 in flight on either transport (see `AuthRecoveryHelper`).
271
265
  * Also what `DefaultAuthProvider.refreshToken` calls, so a refresh is made in one place.
272
266
  */
273
267
  refresh() {
@@ -368,9 +362,9 @@ export class DefaultNetworkRequestService extends BaseService {
368
362
  return token;
369
363
  },
370
364
  headersResolver: () => {
371
- return NetworkHeaders.merge({
372
- sources: [this.getSessionHeaders(), opts ? this.getTracingHeaders(opts) : {}],
373
- });
365
+ return Object.fromEntries(HttpHeaders.merge({
366
+ layers: [this.getSessionHeaders(), opts ? this.getTracingHeaders(opts) : {}],
367
+ }));
374
368
  },
375
369
  onUnauthorized: (context, info) => {
376
370
  if (!this.recovery.canRecover({ paths: context.paths })) {
@@ -415,34 +409,33 @@ export class DefaultNetworkRequestService extends BaseService {
415
409
  }
416
410
  return {
417
411
  provider: authToken?.provider,
418
- token: `${authToken?.type?.length ? authToken.type : 'Bearer'} ${authToken.value}`,
412
+ token: `${authToken?.type?.length ? authToken.type : App.TOKEN_TYPE} ${authToken.value}`,
419
413
  };
420
414
  }
421
415
  /** Adds headers to every request this service sends; a name already set is replaced, in any case. */
422
416
  setHeaders(opts) {
423
- this.headers = NetworkHeaders.merge({ sources: [this.headers, opts.headers] });
417
+ this.headers = HttpHeaders.merge({ layers: [this.headers, opts.headers] });
424
418
  }
425
419
  /** Removes the headers set by name, in any case. */
426
420
  removeHeaders(opts) {
427
421
  if (!opts.keys?.length) {
428
422
  return;
429
423
  }
430
- // The record is keyed by lowercase name.
431
424
  for (const key of opts.keys) {
432
- delete this.headers[key.toLowerCase()];
425
+ this.headers.delete(key);
433
426
  }
434
427
  }
435
428
  /** The timezone, then whatever `setHeaders` holds now. Both transports send these. */
436
429
  getSessionHeaders() {
437
- return NetworkHeaders.merge({
438
- sources: [
430
+ return Object.fromEntries(HttpHeaders.merge({
431
+ layers: [
439
432
  {
440
- [HeaderConstants.TIMEZONE]: App.TIMEZONE,
441
- [HeaderConstants.TIMEZONE_OFFSET]: `${App.TIMEZONE_OFFSET}`,
433
+ [HTTP.Headers.TIMEZONE]: App.TIMEZONE,
434
+ [HTTP.Headers.TIMEZONE_OFFSET]: `${App.TIMEZONE_OFFSET}`,
442
435
  },
443
436
  this.headers,
444
437
  ],
445
- });
438
+ }));
446
439
  }
447
440
  /** The request channel (`RequestChannel.WEB` unless configured) and a fresh tracing id. */
448
441
  getTracingHeaders(opts) {
@@ -451,8 +444,8 @@ export class DefaultNetworkRequestService extends BaseService {
451
444
  ? restDataProviderOptions.requestTracingChannel
452
445
  : RequestChannel.WEB;
453
446
  return {
454
- [HeaderConstants.REQUEST_CHANNEL]: channel,
455
- [HeaderConstants.REQUEST_TRACING_ID]: this.buildRequestTracingId({ applicationInfo }),
447
+ [HTTP.Headers.REQUEST_CHANNEL]: channel,
448
+ [HTTP.Headers.REQUEST_TRACING_ID]: this.buildRequestTracingId({ applicationInfo }),
456
449
  };
457
450
  }
458
451
  /**
@@ -469,8 +462,8 @@ export class DefaultNetworkRequestService extends BaseService {
469
462
  return {
470
463
  ...defaultHeaders,
471
464
  // A token need not name a provider; never send the string `undefined`.
472
- ...(authHeader.provider ? { [HeaderConstants.X_AUTH_PROVIDER]: authHeader.provider } : {}),
473
- [HeaderConstants.AUTHORIZATION]: authHeader.token,
465
+ ...(authHeader.provider ? { [HTTP.Headers.AUTH_PROVIDER]: authHeader.provider } : {}),
466
+ [HTTP.Headers.AUTHORIZATION]: authHeader.token,
474
467
  };
475
468
  }
476
469
  /** The body as it is sent and the content type to send it under. Override to encode another way. */
@@ -485,18 +478,18 @@ export class DefaultNetworkRequestService extends BaseService {
485
478
  const { bodyType, body, resource, restDataProviderOptions, applicationInfo, requestCountData = RequestCountData.DATA_ONLY, extra, } = params;
486
479
  const extraHeader = HttpExtraRequest.toHeader({ extra });
487
480
  // Merged, not spread, so a per-request value replaces a static header in any case.
488
- const headers = NetworkHeaders.merge({
489
- sources: [
481
+ const headers = Object.fromEntries(HttpHeaders.merge({
482
+ layers: [
490
483
  this.getRequestHeader({ resource }),
491
484
  this.getTracingHeaders({ restDataProviderOptions, applicationInfo }),
492
- { [HeaderConstants.REQUEST_COUNT_DATA]: requestCountData },
485
+ { [HTTP.Headers.REQUEST_COUNT_DATA]: requestCountData },
493
486
  extraHeader ? { [HttpExtraRequest.HEADER]: extraHeader } : undefined,
494
487
  ],
495
- });
488
+ }));
496
489
  const encoded = this.encodeBody({ bodyType, body });
497
490
  const props = {
498
491
  headers: encoded.contentType
499
- ? { ...headers, [HeaderConstants.CONTENT_TYPE]: encoded.contentType }
492
+ ? { ...headers, [HTTP.Headers.CONTENT_TYPE]: encoded.contentType }
500
493
  : headers,
501
494
  body: encoded.body,
502
495
  };
@@ -548,14 +541,15 @@ export class DefaultNetworkRequestService extends BaseService {
548
541
  /** `doRequest` once the URL is checked: the send, the refresh and retry after a 401, then the read. */
549
542
  async sendAndRead(opts) {
550
543
  const { url, type, method, paths, body, headers, query, requestCountData, signal } = opts;
551
- const sendOnce = (sendHeaders) => {
544
+ const sendOnce = (retryHeaders) => {
552
545
  return this.networkRequest.getNetworkService().send({
553
546
  url,
554
547
  method,
555
548
  params: query,
556
549
  body: method === RequestMethods.GET ? undefined : body,
557
550
  headers: this.toSendHeaders({
558
- headers: sendHeaders,
551
+ headers,
552
+ extra: retryHeaders,
559
553
  body: method === RequestMethods.GET ? undefined : body,
560
554
  }),
561
555
  signal,
@@ -564,7 +558,7 @@ export class DefaultNetworkRequestService extends BaseService {
564
558
  };
565
559
  const sent = this.readSession();
566
560
  let isRetried = false;
567
- let fetched = await sendOnce(headers);
561
+ let fetched = await sendOnce();
568
562
  if (fetched.status === 401 && this.recovery.canRecover({ paths })) {
569
563
  // A 401 that arrives after the session changed is not the new session's to refresh or to end.
570
564
  const change = this.readSessionChange({ sent });
@@ -587,16 +581,17 @@ export class DefaultNetworkRequestService extends BaseService {
587
581
  // The shared refresh is never aborted for one request: this request stops when it returns.
588
582
  signal?.throwIfAborted();
589
583
  if (isRefreshed) {
584
+ if (method !== RequestMethods.GET && body instanceof ReadableStream) {
585
+ throw getError({
586
+ message: '[doRequest] The session was refreshed, but a ReadableStream body cannot be sent a second time | Send the request again from your code, or send a body that can be read again (FormData, Blob, a string)',
587
+ });
588
+ }
590
589
  const authHeader = this.getRequestAuthorizationHeader();
591
- const retryHeaders = NetworkHeaders.merge({
592
- sources: [
593
- headers,
594
- { [HeaderConstants.AUTHORIZATION]: authHeader.token },
595
- authHeader.provider
596
- ? { [HeaderConstants.X_AUTH_PROVIDER]: authHeader.provider }
597
- : undefined,
598
- ],
599
- });
590
+ // The token's provider wins, and a token with none removes the one the call carried.
591
+ const retryHeaders = {
592
+ [HTTP.Headers.AUTHORIZATION]: authHeader.token,
593
+ [HTTP.Headers.AUTH_PROVIDER]: authHeader.provider ?? null,
594
+ };
600
595
  const result = await sendOnce(retryHeaders);
601
596
  fetched = result;
602
597
  isRetried = true;
@@ -610,7 +605,10 @@ export class DefaultNetworkRequestService extends BaseService {
610
605
  throw this.sessionChangedError();
611
606
  }
612
607
  if (status < 200 || status >= 300) {
613
- const result2 = await NetworkResponseReader.toError({ response: fetched });
608
+ const result2 = await HttpResponseReader.toApplicationError({
609
+ response: fetched,
610
+ rootKey: NetworkResponseReader.ERROR_ROOT_KEY,
611
+ });
614
612
  throw result2;
615
613
  }
616
614
  const response = await NetworkResponseReader.read({
@@ -1,3 +1,4 @@
1
+ import { ConstClass } from '@venizia/ignis-helpers/common';
1
2
  /** Values of the running environment, read once when the module loads. */
2
3
  export declare class App {
3
4
  /** The IANA name of the timezone of the runtime. */
@@ -6,22 +7,11 @@ export declare class App {
6
7
  static readonly TIMEZONE_OFFSET: number;
7
8
  /** In milliseconds. */
8
9
  static readonly DEFAULT_DEBOUNCE_TIME = 500;
9
- }
10
- /** Authorization schemes (`Basic`, `Bearer`) and strategies (`basic`, `jwt`). */
11
- export declare class Authentication {
12
- /** The scheme in the `authorization` header. */
13
- static readonly TYPE_BASIC = "Basic";
14
- static readonly TYPE_BEARER = "Bearer";
15
- /** The name of the auth strategy. */
16
- static readonly STRATEGY_BASIC = "basic";
17
- static readonly STRATEGY_JWT = "jwt";
18
- /** Every value of this class that `isValid` accepts. */
19
- static readonly SCHEME_SET: Set<string>;
20
- /** Whether `value` is in `SCHEME_SET`. */
21
- static isValid(value: string): boolean;
10
+ /** The authorization scheme of a token that names none. */
11
+ static readonly TOKEN_TYPE = "Bearer";
22
12
  }
23
13
  /** HTTP methods. */
24
- export declare class RequestMethods {
14
+ export declare class RequestMethods extends ConstClass {
25
15
  static readonly HEAD = "HEAD";
26
16
  static readonly OPTIONS = "OPTIONS";
27
17
  static readonly GET = "GET";
@@ -29,13 +19,9 @@ export declare class RequestMethods {
29
19
  static readonly PUT = "PUT";
30
20
  static readonly PATCH = "PATCH";
31
21
  static readonly DELETE = "DELETE";
32
- /** Every value of this class that `isValid` accepts. */
33
- static readonly SCHEME_SET: Set<string>;
34
- /** Whether `value` is in `SCHEME_SET`. */
35
- static isValid(value: string): boolean;
36
22
  }
37
23
  /** What a request is for, which decides how its response is read: `SEND`, and react-admin's data provider calls. */
38
- export declare class RequestTypes {
24
+ export declare class RequestTypes extends ConstClass {
39
25
  /** A request that is not a react-admin call. */
40
26
  static readonly SEND = "SEND";
41
27
  static readonly GET_LIST = "GET_LIST";
@@ -47,10 +33,6 @@ export declare class RequestTypes {
47
33
  static readonly UPDATE_MANY = "UPDATE_MANY";
48
34
  static readonly DELETE = "DELETE";
49
35
  static readonly DELETE_MANY = "DELETE_MANY";
50
- /** Every value of this class that `isValid` accepts. */
51
- static readonly SCHEME_SET: Set<string>;
52
- /** Whether `value` is in `SCHEME_SET`. */
53
- static isValid(value: string): boolean;
54
36
  }
55
37
  /** The Web Storage areas `BrowserStorage` reads and writes. */
56
38
  export declare class StorageAreas {
@@ -60,73 +42,26 @@ export declare class StorageAreas {
60
42
  static readonly SESSION = "session";
61
43
  }
62
44
  /** How a request body is encoded; see `RequestBodyEncoder`. */
63
- export declare class RequestBodyTypes {
45
+ export declare class RequestBodyTypes extends ConstClass {
64
46
  /** The body goes through as it is. */
65
47
  static readonly NONE = "none";
66
48
  static readonly FORM_DATA = "form-data";
67
49
  static readonly FORM_URL_ENCODED = "x-www-form-urlencoded";
68
50
  static readonly JSON = "json";
69
51
  static readonly BINARY = "binary";
70
- /** Every value of this class that `isValid` accepts. */
71
- static readonly SCHEME_SET: Set<string>;
72
- /** Whether `value` is in `SCHEME_SET`. */
73
- static isValid(value: string): boolean;
74
52
  }
75
53
  /** Names of the build environments. */
76
- export declare class Environments {
54
+ export declare class Environments extends ConstClass {
77
55
  static readonly DEVELOPMENT = "development";
78
56
  static readonly PRODUCTION = "production";
79
- /** Every value of this class that `isValid` accepts. */
80
- static readonly SCHEME_SET: Set<string>;
81
- /** Whether `value` is in `SCHEME_SET`. */
82
- static isValid(value: string): boolean;
83
- }
84
- /** Header names, lowercase, and patterns on header values. */
85
- export declare class HeaderConstants {
86
- /** The header on a request body and on a response. */
87
- static readonly CONTENT_TYPE = "content-type";
88
- /**
89
- * content-range: <unit> <range-start>-<range-end>/<size>
90
- * @format unit start-end/total
91
- * The positions are zero-indexed, the end inclusive; the total is `*` if unknown.
92
- */
93
- static readonly CONTENT_RANGE = "content-range";
94
- /** Names the file of a file response. */
95
- static readonly CONTENT_DISPOSITION = "content-disposition";
96
- /** Carries `<type> <token>`. */
97
- static readonly AUTHORIZATION = "authorization";
98
- /** Names the provider of the token; sent only when the token names one. */
99
- static readonly X_AUTH_PROVIDER = "x-auth-provider";
100
- /** The locale of the request, the header `useRequestHeaderLocale` sets by default. */
101
- static readonly X_LOCALE = "x-locale";
102
- /** Carries `App.TIMEZONE`. */
103
- static readonly TIMEZONE = "timezone";
104
- /** Carries `App.TIMEZONE_OFFSET`, in hours. */
105
- static readonly TIMEZONE_OFFSET = "timezone-offset";
106
- /** Carries the tracing id of a request. */
107
- static readonly REQUEST_TRACING_ID = "x-request-id";
108
- /** Carries a `RequestChannel` value. */
109
- static readonly REQUEST_CHANNEL = "x-request-channel";
110
- /** Carries a `RequestCountData` value: what the request asks the server to return. */
111
- static readonly REQUEST_COUNT_DATA = "x-request-count";
112
- /** Carries the count a server sends with a response that is not a list. */
113
- static readonly RESPONSE_COUNT_DATA = "x-response-count";
114
- /** Content types read as text. */
115
- static readonly TEXTUAL_CONTENT_TYPE_RE: RegExp;
116
- /** A `content-disposition` that marks a file download. */
117
- static readonly ATTACHMENT_CONTENT_DISPOSITION_RE: RegExp;
118
57
  }
119
58
  /** The channels a request says it comes from, sent in `x-request-channel`. */
120
- export declare class RequestChannel {
59
+ export declare class RequestChannel extends ConstClass {
121
60
  /** A browser application; what a request says unless `requestTracingChannel` is set. */
122
61
  static readonly WEB = "100_WEB";
123
- /** Every value of this class that `isValid` accepts. */
124
- static readonly SCHEME_SET: Set<string>;
125
- /** Whether `value` is in `SCHEME_SET`. */
126
- static isValid(value: string): boolean;
127
62
  }
128
63
  /** Whether a response carries a count, sent in `x-request-count`. */
129
- export declare class RequestCountData {
64
+ export declare class RequestCountData extends ConstClass {
130
65
  /**
131
66
  * @description Only the data is returned in the response body
132
67
  */
@@ -135,9 +70,5 @@ export declare class RequestCountData {
135
70
  * @description Both data and count are returned in the response body
136
71
  */
137
72
  static readonly DATA_WITH_COUNT = "1";
138
- /** Every value of this class that `isValid` accepts. */
139
- static readonly SCHEME_SET: Set<string>;
140
- /** Whether `value` is in `SCHEME_SET`. */
141
- static isValid(value: string): boolean;
142
73
  }
143
74
  //# sourceMappingURL=constants.d.ts.map