@venizia/ardor-kernel 0.4.8-9 → 0.5.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,12 @@
1
- import type { AnyObject, AnyType, TConstValue, TNumberConstValue, TPrettify, TStringConstValue, ValueOf, ValueOptional, ValueOptionalExcept, ValueOrPromise } from '@venizia/ignis-helpers/common';
1
+ import type { TConstValue, TNumberConstValue, TPrettify, TStringConstValue, ValueOf, ValueOptional, ValueOptionalExcept, ValueOrPromise } from '@venizia/ignis-helpers/common';
2
2
  import type { TBuildInfoRecord } from '@venizia/ignis-helpers/core';
3
3
  import type { TClass } from '@venizia/ignis-inversion';
4
4
  import type { TExtraRequest } from '@venizia/ignis-kernel/repository';
5
+ import type { AbstractArdorApplication } from '../base/applications/abstract.js';
5
6
  import type { Environments, RequestBodyTypes, RequestCountData, RequestMethods, RequestTypes, StorageAreas } from './constants.js';
6
7
  /** A record id: a string or a number. */
7
8
  export type IdType = string | number;
8
- export type { AnyObject, AnyType, TConstValue, TNumberConstValue, TPrettify, TStringConstValue, ValueOf, ValueOptional, ValueOptionalExcept, ValueOrPromise, };
9
+ export type { TConstValue, TNumberConstValue, TPrettify, TStringConstValue, ValueOf, ValueOptional, ValueOptionalExcept, ValueOrPromise, };
9
10
  /** One of the `RequestMethods` values. */
10
11
  export type TRequestMethod = TStringConstValue<typeof RequestMethods>;
11
12
  /** One of the `Environments` values. */
@@ -30,7 +31,19 @@ export interface ISendParams {
30
31
  requestCountData?: TConstValue<typeof RequestCountData>;
31
32
  /** The list extras to ask the route for, sent in `x-request-extra`. */
32
33
  extra?: TExtraRequest;
34
+ /** Aborts the request; it then rejects with the signal's reason. */
35
+ signal?: AbortSignal;
33
36
  }
37
+ /**
38
+ * How long a request may take before it is aborted and rejects with `NETWORK_TIMEOUT_CODE`.
39
+ * `milliseconds` is a positive integer.
40
+ */
41
+ export type TRequestTimeoutOptions = {
42
+ use: false;
43
+ } | {
44
+ use: true;
45
+ milliseconds: number;
46
+ };
34
47
  /** One of the `RequestBodyTypes` values. */
35
48
  export type TRequestBodyType = TStringConstValue<typeof RequestBodyTypes>;
36
49
  /** One of the `StorageAreas` values. */
@@ -66,10 +79,23 @@ export interface IGetRequestPropsResult {
66
79
  headers?: HeadersInit;
67
80
  body?: unknown;
68
81
  }
69
- /** Keys react-admin does not know ride on its params and become filter keys; `any`, so ra-core's param interfaces stay assignable. */
82
+ /**
83
+ * Keys react-admin does not know ride on its params and become filter keys. A react-admin param type
84
+ * is an interface, which has no index signature: spread it (`{ ...params }`) where this is expected.
85
+ */
70
86
  export interface ICustomParams {
71
- params?: Record<string, AnyType>;
72
- [key: string]: AnyType;
87
+ params?: Record<string, unknown>;
88
+ [key: string]: unknown;
89
+ }
90
+ /**
91
+ * The identity `saveAuth` stores and `getUser` reads back: every field is absent when nothing is
92
+ * stored. It has no index signature, so an interface of your own that has these fields fits it.
93
+ */
94
+ export interface IAuthUser {
95
+ userId?: IdType;
96
+ username?: string;
97
+ referenceId?: IdType;
98
+ provider?: string;
73
99
  }
74
100
  /** What `login` read from the sign-in response. `roles` are names. */
75
101
  export interface ISignInSession {
@@ -80,7 +106,10 @@ export interface ISignInSession {
80
106
  };
81
107
  roles: Array<string>;
82
108
  }
83
- /** Data only: where the auth provider talks to. Behaviour is in `DefaultAuthProvider`'s protected hooks. */
109
+ /**
110
+ * Data only: where the auth provider talks to, the `use: true` half of `TAuthProviderOptions`.
111
+ * Behaviour is in `DefaultAuthProvider`'s protected hooks.
112
+ */
84
113
  export interface IAuthProviderOptions {
85
114
  paths?: {
86
115
  /**
@@ -98,6 +127,16 @@ export interface IAuthProviderOptions {
98
127
  afterLogin?: string | false;
99
128
  };
100
129
  }
130
+ /**
131
+ * What `CoreBindings.AUTH_PROVIDER_OPTIONS` holds: sign-in on with its `paths`, or off. Unbound means
132
+ * `{ use: false }`: `ApplicationProviders.resolve` then hands react-admin no auth provider, and
133
+ * every page is public.
134
+ */
135
+ export type TAuthProviderOptions = {
136
+ use: false;
137
+ } | ({
138
+ use: true;
139
+ } & IAuthProviderOptions);
101
140
  /** How a request recovers from a 401. */
102
141
  export interface IAuthRecoveryOptions {
103
142
  /**
@@ -154,6 +193,12 @@ export interface IRestDataProviderOptions extends INoAuthOptions {
154
193
  headers?: HeadersInit;
155
194
  /** Enables the refresh-and-retry after a 401. */
156
195
  authRecovery?: IAuthRecoveryOptions;
196
+ /**
197
+ * Aborts a request that has not answered within `milliseconds`; it rejects with a 504 whose
198
+ * `normalized.code` is `NETWORK_TIMEOUT_CODE`. An invalid `milliseconds` throws when the provider is built.
199
+ * @default { use: false }
200
+ */
201
+ timeout?: TRequestTimeoutOptions;
157
202
  }
158
203
  /** The token an application is signed in with. */
159
204
  export interface IAuthTokenRecord {
@@ -161,11 +206,17 @@ export interface IAuthTokenRecord {
161
206
  type?: string;
162
207
  value: string;
163
208
  provider?: string;
209
+ /** The user the token was issued to, stored by `saveAuth`; absent on a token stored without it. */
210
+ userId?: IdType;
164
211
  }
165
212
  /** What an `HttpDataSource` hook reads from the request it is asked about. */
166
213
  export interface IDataSourceRequestContext {
167
214
  paths: Array<string>;
168
215
  }
216
+ /** What `onUnauthorized` is told besides the request: `attempt` is 1 for the first 401 and 2 for the retry's own. */
217
+ export interface IDataSourceUnauthorizedInfo {
218
+ attempt: number;
219
+ }
169
220
  /**
170
221
  * The settings an `HttpDataSource` takes, bound to one `DefaultNetworkRequestService`, so a
171
222
  * repository sends what the data provider sends: the same headers, the same token on the same
@@ -174,7 +225,7 @@ export interface IDataSourceRequestContext {
174
225
  export interface IDataSourceAuth {
175
226
  authTokenResolver: (context: IDataSourceRequestContext) => IAuthTokenRecord | undefined;
176
227
  headersResolver: (context: IDataSourceRequestContext) => Record<string, string>;
177
- onUnauthorized: (context: IDataSourceRequestContext) => Promise<boolean>;
228
+ onUnauthorized: (context: IDataSourceRequestContext, info: IDataSourceUnauthorizedInfo) => Promise<boolean>;
178
229
  errorRootKey: string;
179
230
  }
180
231
  /** What `DefaultNetworkRequestService.doRequest` answers. */
@@ -204,7 +255,18 @@ export interface IFeatureBase {
204
255
  * @default []
205
256
  */
206
257
  configurations?: Array<TClass<unknown>>;
207
- /** What the feature checks, in the application's vocabulary. Declared for a role editor; ARDOR enforces nothing. */
258
+ /**
259
+ * The feature's own stereotyped classes, by value, in the shape of the application's
260
+ * `artifacts()` index. Importing the feature module imports them, so discovery binds them, and
261
+ * `start()` checks each was discovered.
262
+ * @default {}
263
+ */
264
+ artifacts?: IArtifactIndex;
265
+ /**
266
+ * The permission names the feature's pages use, in the application's vocabulary: metadata for a
267
+ * role editor to list. Descriptive only, it enforces nothing; `access` on a route or a menu entry
268
+ * is what asks `canAccess`.
269
+ */
208
270
  permissions?: Array<string>;
209
271
  }
210
272
  /**
@@ -232,47 +294,35 @@ export interface IPermissionProvider {
232
294
  record?: unknown;
233
295
  }): Promise<boolean>;
234
296
  }
235
- /** The contract of an application: lifecycle hooks, registration of artifacts, and `start`. */
236
- export interface IArdorApplication {
237
- /** Binds the application instance and info, then the discovered, feature and listed classes. */
238
- preConfigure(): ValueOrPromise<void>;
239
- /** Runs after `preConfigure` in `start`. */
240
- postConfigure(): ValueOrPromise<void>;
241
- /** The application's own bindings, bound last in `preConfigure`. */
242
- bindContext(): ValueOrPromise<void>;
243
- /** Classes bound by key as singletons. */
244
- bindingList(): Record<string, TClass<unknown>>;
245
- /** The features this application mounts. */
246
- features(): Array<IFeatureBase>;
247
- /** The artifact indexes `start` checks every stereotyped class against. */
248
- artifacts(): Array<IArtifactIndex>;
249
- /** Binds `value` under `<scope>.<ClassName>` as a singleton. */
250
- injectable<T>(scope: string, value: TClass<T>, tags?: Array<string>): void;
251
- /** Binds `value` in the service namespace. */
252
- service<T>(value: TClass<T>): unknown;
253
- /** Binds `value` in the repository namespace. */
254
- repository<T>(value: TClass<T>): unknown;
255
- /** Binds `value` in the data source namespace. */
256
- dataSource<T>(value: TClass<T>): unknown;
257
- /** Binds `value` in the component namespace. */
258
- component<T>(value: TClass<T>): unknown;
259
- /** Runs the whole startup: resolves the indexes, then `preConfigure`, then `postConfigure`. */
260
- start(): ValueOrPromise<void>;
297
+ /** The options of `RolePermissionProvider`, bound under `CoreBindings.PERMISSION_PROVIDER_OPTIONS`. */
298
+ export interface IRolePermissionProviderOptions {
299
+ /**
300
+ * Role name to grant patterns. A pattern is `'<resource>.<action>'`, `'<resource>.*'`, `'*.<action>'`
301
+ * or `'*'`; anything else throws when the provider is built. A pattern has one `.`, so a resource whose
302
+ * name contains a `.` cannot be named exactly: grant it with `'*.<action>'` or `'*'`, or give it a name without one.
303
+ */
304
+ grants: Record<string, ReadonlyArray<string>>;
305
+ }
306
+ /**
307
+ * The contract of an application: lifecycle hooks, registration of artifacts, and `start`. Picked
308
+ * from `AbstractArdorApplication`, so its signatures are the class's own.
309
+ */
310
+ export interface IArdorApplication extends Pick<AbstractArdorApplication, 'preConfigure' | 'postConfigure' | 'bindContext' | 'bindingList' | 'features' | 'artifacts' | 'service' | 'repository' | 'dataSource' | 'component' | 'start'> {
261
311
  }
262
312
  type TDeepPath = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
263
313
  /** Values a path stops at: their members are not state. */
264
- type TPathLeaf = Date | RegExp | ReadonlySet<AnyType> | ReadonlyMap<AnyType, AnyType> | Promise<AnyType> | ((...args: Array<AnyType>) => AnyType);
314
+ type TPathLeaf = Date | RegExp | ReadonlySet<unknown> | ReadonlyMap<unknown, unknown> | Promise<unknown> | ((...args: never[]) => unknown);
265
315
  type TIsAny<TValue> = 0 extends 1 & TValue ? true : false;
266
316
  /**
267
317
  * The dotted paths of an object type, to `DeepLevel` levels (10 by default). An array, a `Date`, a
268
318
  * `Set`, a `Map`, a `Promise`, a function and an `any` field are leaves: the path stops at them.
269
319
  */
270
- export type TPaths<T, DeepLevel extends number = 10> = DeepLevel extends 0 ? never : T extends Array<AnyType> | TPathLeaf ? never : T extends object ? {
271
- [K in keyof T]-?: K extends string | number ? TIsAny<T[K]> extends true ? `${K}` : NonNullable<T[K]> extends Array<AnyType> | TPathLeaf ? `${K}` : NonNullable<T[K]> extends object ? `${K}` | `${K}.${TPaths<NonNullable<T[K]>, TDeepPath[DeepLevel]>}` : `${K}` : never;
320
+ export type TPaths<T, DeepLevel extends number = 10> = DeepLevel extends 0 ? never : T extends Array<unknown> | TPathLeaf ? never : T extends object ? {
321
+ [K in keyof T]-?: K extends string | number ? TIsAny<T[K]> extends true ? `${K}` : NonNullable<T[K]> extends Array<unknown> | TPathLeaf ? `${K}` : NonNullable<T[K]> extends object ? `${K}` | `${K}.${TPaths<NonNullable<T[K]>, TDeepPath[DeepLevel]>}` : `${K}` : never;
272
322
  }[keyof T] : never;
273
323
  /** The dotted paths of an object type, to `DeepLevel` levels (10 by default); unlike `TPaths`, only the paths down to a leaf value. */
274
324
  export type TFullPaths<T, DeepLevel extends number = 10> = DeepLevel extends never ? never : T extends Array<infer U> ? TFullPaths<U> : T extends object ? {
275
- [K in keyof T]-?: K extends string | number ? T[K] extends Array<any> | object ? `${K}.${TFullPaths<T[K], TDeepPath[DeepLevel]>}` : `${K}` : never;
325
+ [K in keyof T]-?: K extends string | number ? T[K] extends object ? `${K}.${TFullPaths<T[K], TDeepPath[DeepLevel]>}` : `${K}` : never;
276
326
  }[keyof T] : never;
277
327
  /** What an application is: bound under `CoreBindings.APPLICATION_INFO`, and the name a tracing id starts with. */
278
328
  export interface IApplicationInfo {
@@ -1,4 +1,4 @@
1
- import { type IAuthTokenRecord } from '../common/index.js';
1
+ import { type IAuthTokenRecord, type IdType } from '../common/index.js';
2
2
  /** The one place that reads and writes the stored auth token, with the browser guard. */
3
3
  export declare class AuthTokenStore {
4
4
  private static readonly logger;
@@ -6,13 +6,17 @@ export declare class AuthTokenStore {
6
6
  static read(opts?: {
7
7
  key?: string;
8
8
  }): IAuthTokenRecord | undefined;
9
- /** Stores the token with its `provider` under `key` (`LocalStorageKeys.KEY_AUTH_TOKEN` by default). Throws when `localStorage` is not available. */
9
+ /**
10
+ * Stores the token with its `provider`, and the `userId` it was issued to when given, under `key`
11
+ * (`LocalStorageKeys.KEY_AUTH_TOKEN` by default). Throws when `localStorage` is not available.
12
+ */
10
13
  static write(opts: {
11
14
  token: {
12
15
  value: string;
13
16
  type: string;
14
17
  };
15
18
  provider: string;
19
+ userId?: IdType;
16
20
  key?: string;
17
21
  }): void;
18
22
  }
@@ -23,14 +23,17 @@ export class AuthTokenStore {
23
23
  return undefined;
24
24
  }
25
25
  }
26
- /** Stores the token with its `provider` under `key` (`LocalStorageKeys.KEY_AUTH_TOKEN` by default). Throws when `localStorage` is not available. */
26
+ /**
27
+ * Stores the token with its `provider`, and the `userId` it was issued to when given, under `key`
28
+ * (`LocalStorageKeys.KEY_AUTH_TOKEN` by default). Throws when `localStorage` is not available.
29
+ */
27
30
  static write(opts) {
28
31
  // Not a silent skip: a sign-in that is not kept would look like it worked.
29
32
  if (typeof localStorage === 'undefined') {
30
33
  throw getError({ message: '[write] localStorage is not available' });
31
34
  }
32
- const { token, provider } = opts;
33
- localStorage.setItem(opts.key ?? LocalStorageKeys.KEY_AUTH_TOKEN, JSON.stringify(Object.assign({}, token, { provider })));
35
+ const { token, provider, userId } = opts;
36
+ localStorage.setItem(opts.key ?? LocalStorageKeys.KEY_AUTH_TOKEN, JSON.stringify(Object.assign({}, token, { provider }, userId === undefined ? {} : { userId })));
34
37
  }
35
38
  }
36
39
  //# sourceMappingURL=auth-token-store.js.map
@@ -6,7 +6,8 @@ import type { ILogger } from '@venizia/ignis-helpers/core';
6
6
  */
7
7
  export declare class AuthRecovery {
8
8
  private readonly opts;
9
- private refreshing;
9
+ /** The refresh in flight for each session (`key`): a request of another session never joins it. */
10
+ private readonly refreshing;
10
11
  constructor(opts: {
11
12
  logger: ILogger;
12
13
  /** Read per request: the service lets its `authRecovery` be set after construction. */
@@ -18,8 +19,14 @@ export declare class AuthRecovery {
18
19
  /** Whether the request, given by its paths, goes without a token; such a request never recovers. */
19
20
  isNoAuthPath: (paths: string[]) => boolean;
20
21
  });
21
- /** Once for every 401 in flight: the callers share one `refresh`. `true` when the token was refreshed. */
22
- refresh(): Promise<boolean>;
22
+ /**
23
+ * Once for every 401 in flight of one session (`key`): those callers share one `refresh`. A 401 of
24
+ * another session starts its own, so it never waits for an answer that belongs to someone else.
25
+ * `true` when the token was refreshed.
26
+ */
27
+ refresh(opts?: {
28
+ key?: string;
29
+ }): Promise<boolean>;
23
30
  /** Not for a no-auth path, nor for the refresh path itself, which would wait on itself. */
24
31
  canRecover(opts: {
25
32
  paths: string[];
@@ -6,13 +6,23 @@
6
6
  export class AuthRecovery {
7
7
  constructor(opts) {
8
8
  this.opts = opts;
9
- this.refreshing = null;
9
+ /** The refresh in flight for each session (`key`): a request of another session never joins it. */
10
+ this.refreshing = new Map();
10
11
  }
11
- /** Once for every 401 in flight: the callers share one `refresh`. `true` when the token was refreshed. */
12
- refresh() {
12
+ /**
13
+ * Once for every 401 in flight of one session (`key`): those callers share one `refresh`. A 401 of
14
+ * another session starts its own, so it never waits for an answer that belongs to someone else.
15
+ * `true` when the token was refreshed.
16
+ */
17
+ refresh(opts = {}) {
13
18
  const { logger, refresh, onFailure } = this.opts;
19
+ const { key = '' } = opts;
20
+ const inFlight = this.refreshing.get(key);
21
+ if (inFlight) {
22
+ return inFlight;
23
+ }
14
24
  // A refresh that throws synchronously is still a failed refresh, not a stray exception.
15
- this.refreshing ??= Promise.resolve()
25
+ const started = Promise.resolve()
16
26
  .then(() => refresh())
17
27
  .catch(async (error) => {
18
28
  logger.error('[refresh] refreshToken failed | error: %o', error);
@@ -25,9 +35,10 @@ export class AuthRecovery {
25
35
  return false;
26
36
  })
27
37
  .finally(() => {
28
- this.refreshing = null;
38
+ this.refreshing.delete(key);
29
39
  });
30
- return this.refreshing;
40
+ this.refreshing.set(key, started);
41
+ return started;
31
42
  }
32
43
  /** Not for a no-auth path, nor for the refresh path itself, which would wait on itself. */
33
44
  canRecover(opts) {
@@ -1,5 +1,5 @@
1
1
  export * from './headers.js';
2
2
  export * from './request-body-encoder.js';
3
- export * from './response-reader.js';
3
+ export * from './network-response-reader.js';
4
4
  export * from './auth-recovery.js';
5
5
  //# sourceMappingURL=index.d.ts.map
@@ -1,5 +1,5 @@
1
1
  export * from './headers.js';
2
2
  export * from './request-body-encoder.js';
3
- export * from './response-reader.js';
3
+ export * from './network-response-reader.js';
4
4
  export * from './auth-recovery.js';
5
5
  //# sourceMappingURL=index.js.map
@@ -1,6 +1,6 @@
1
1
  import { type INetworkResponse, RequestCountData, type TConstValue, type TRequestType } from '../../common/index.js';
2
2
  /** Reads a `Response` into an `INetworkResponse`, and an error response into an error. */
3
- export declare class ResponseReader {
3
+ export declare class NetworkResponseReader {
4
4
  /** The server wraps an error body under this key; both transports unwrap it. */
5
5
  static readonly ERROR_ROOT_KEY = "error";
6
6
  /** A response as `INetworkResponse`: JSON read by the request type, a file as a `Blob`. */
@@ -31,6 +31,8 @@ export declare class ResponseReader {
31
31
  count?: number;
32
32
  total?: number;
33
33
  };
34
+ /** The rows of a list answer: an array as it is, no body at all (an empty answer) as no row, any other value as the one row. */
35
+ private static toRows;
34
36
  /**
35
37
  * A failed response as an `ApplicationError`, mapped like IGNIS `HttpDataSource`: the HTTP status,
36
38
  * the server's code and args, its `extra` with the `requestId` added, and `details.cause`.
@@ -52,4 +54,4 @@ export declare class ResponseReader {
52
54
  /** The file name a `Content-Disposition` header names, `filename*` before `filename`. */
53
55
  private static parseFilename;
54
56
  }
55
- //# sourceMappingURL=response-reader.d.ts.map
57
+ //# sourceMappingURL=network-response-reader.d.ts.map
@@ -6,7 +6,7 @@ const isCountedBody = (value) => {
6
6
  return typeof value === 'object' && value !== null && 'data' in value && 'count' in value;
7
7
  };
8
8
  /** Reads a `Response` into an `INetworkResponse`, and an error response into an error. */
9
- export class ResponseReader {
9
+ export class NetworkResponseReader {
10
10
  /** The server wraps an error body under this key; both transports unwrap it. */
11
11
  static { this.ERROR_ROOT_KEY = 'error'; }
12
12
  /** A response as `INetworkResponse`: JSON read by the request type, a file as a `Blob`. */
@@ -21,21 +21,24 @@ export class ResponseReader {
21
21
  const isTextual = contentType !== '' && HeaderConstants.TEXTUAL_CONTENT_TYPE_RE.test(contentType);
22
22
  if (isAttachment || !isTextual) {
23
23
  const blob = await response.blob();
24
- const filename = ResponseReader.parseFilename({ header: contentDisposition });
24
+ const filename = NetworkResponseReader.parseFilename({ header: contentDisposition });
25
25
  return {
26
26
  data: blob,
27
27
  ...(filename ? { filename } : {}),
28
28
  ...(contentDisposition ? { contentDisposition } : {}),
29
29
  };
30
30
  }
31
- const parsedBody = await response.json();
31
+ const parsedBody = await HttpResponseReader.readBody({
32
+ response,
33
+ context: `[NetworkResponseReader] ${response.status}`,
34
+ });
32
35
  // A route with extras answers `{ data, extra }`; `readExtra` strips only `extra`, so a
33
36
  // count-in-body request still reads `{ count, data }`.
34
37
  const { body, extra } = HttpResponseReader.readExtra({
35
38
  body: parsedBody,
36
39
  headers: response.headers,
37
40
  });
38
- const converted = ResponseReader.convert({
41
+ const converted = NetworkResponseReader.convert({
39
42
  type,
40
43
  requestCountData,
41
44
  response: { headers: response.headers, data: body },
@@ -61,18 +64,22 @@ export class ResponseReader {
61
64
  });
62
65
  }
63
66
  const dataFormatted = data;
64
- const normalizedData = !Array.isArray(dataFormatted.data)
65
- ? [dataFormatted.data]
66
- : dataFormatted.data;
67
- const total = ResponseReader.resolveTotal({ headers, rowCount: normalizedData.length });
67
+ const normalizedData = NetworkResponseReader.toRows({ data: dataFormatted.data });
68
+ const total = NetworkResponseReader.resolveTotal({
69
+ headers,
70
+ rowCount: normalizedData.length,
71
+ });
68
72
  return {
69
73
  data: normalizedData,
70
74
  count: dataFormatted?.count ?? normalizedData.length,
71
75
  total,
72
76
  };
73
77
  }
74
- const normalizedData = !Array.isArray(data) ? [data] : data;
75
- const total = ResponseReader.resolveTotal({ headers, rowCount: normalizedData.length });
78
+ const normalizedData = NetworkResponseReader.toRows({ data });
79
+ const total = NetworkResponseReader.resolveTotal({
80
+ headers,
81
+ rowCount: normalizedData.length,
82
+ });
76
83
  return {
77
84
  data: normalizedData,
78
85
  total,
@@ -91,6 +98,14 @@ export class ResponseReader {
91
98
  }
92
99
  }
93
100
  }
101
+ /** The rows of a list answer: an array as it is, no body at all (an empty answer) as no row, any other value as the one row. */
102
+ static toRows(opts) {
103
+ const { data } = opts;
104
+ if (Array.isArray(data)) {
105
+ return data;
106
+ }
107
+ return data === null || data === undefined ? [] : [data];
108
+ }
94
109
  /**
95
110
  * A failed response as an `ApplicationError`, mapped like IGNIS `HttpDataSource`: the HTTP status,
96
111
  * the server's code and args, its `extra` with the `requestId` added, and `details.cause`.
@@ -100,7 +115,7 @@ export class ResponseReader {
100
115
  const { response } = opts;
101
116
  const server = await HttpResponseReader.readError({
102
117
  response,
103
- rootKey: ResponseReader.ERROR_ROOT_KEY,
118
+ rootKey: NetworkResponseReader.ERROR_ROOT_KEY,
104
119
  });
105
120
  // A relaying server's `extra.requestId` names the request it made upstream; keep it, nearest first.
106
121
  const extra = { ...server.extra };
@@ -135,7 +150,7 @@ export class ResponseReader {
135
150
  */
136
151
  static readFilename(opts) {
137
152
  const header = opts.headers?.get(HeaderConstants.CONTENT_DISPOSITION) ?? '';
138
- return ResponseReader.parseFilename({ header });
153
+ return NetworkResponseReader.parseFilename({ header });
139
154
  }
140
155
  /** The file name a `Content-Disposition` header names, `filename*` before `filename`. */
141
156
  static parseFilename(opts) {
@@ -163,4 +178,4 @@ export class ResponseReader {
163
178
  return undefined;
164
179
  }
165
180
  }
166
- //# sourceMappingURL=response-reader.js.map
181
+ //# sourceMappingURL=network-response-reader.js.map
@@ -3,34 +3,60 @@
3
3
  * The preset image writes it at container start, from the environment variables that start with `VITE_`.
4
4
  */
5
5
  export declare const RUNTIME_CONFIG_GLOBAL = "__APP_CONFIG__";
6
- /** The `normalized.code` of the error `RuntimeConfig.get` throws for a required value that is not set; the key is in its `extra.key`. */
6
+ /** The `normalized.code` of the error `RuntimeConfig.getRequired` throws for a value that is not set; the key is in its `extra.key`. */
7
7
  export declare const RUNTIME_CONFIG_REQUIRED_CODE = "ardor.runtime_config.required";
8
- interface IRuntimeConfigOptions {
8
+ /** The `normalized.code` of the error a `transform` of `RuntimeConfig` causes by throwing, or by answering `undefined` or `null` to `getRequired`; the key is in its `extra.key`, the value is never in the error. */
9
+ export declare const RUNTIME_CONFIG_INVALID_CODE = "ardor.runtime_config.invalid";
10
+ interface IRuntimeConfigReadOptions {
9
11
  /** The name looked up in `window.__APP_CONFIG__` and in `buildTimeEnv`. */
10
12
  key: string;
11
13
  /** The build-time source, normally `import.meta.env`. */
12
14
  buildTimeEnv?: Record<string, unknown>;
13
- /** Used when neither source has a non-empty string for `key`. */
14
- defaultValue?: string;
15
15
  }
16
16
  /** Reads configuration a deployment can change without a rebuild. */
17
17
  export declare class RuntimeConfig {
18
18
  /**
19
19
  * One config value: the runtime one (`window.__APP_CONFIG__`), else the build-time one
20
- * (`buildTimeEnv`, passed by the app as `import.meta.env`), else `defaultValue`. Only a non-empty
21
- * string counts, and a missing global is not an error.
20
+ * (`buildTimeEnv`, passed by the app as `import.meta.env`), else `defaultValue`. A value that is
21
+ * empty or only spaces counts as unset, in both sources, and a missing global is not an error.
22
22
  *
23
- * With `required: true` the result is a `string`: when all three are absent it throws, naming the
24
- * key and never a value. The error is an `ApplicationError` with `normalized.code` equal to
25
- * `RUNTIME_CONFIG_REQUIRED_CODE` and the key in `extra.key`, so a caller tells it from another error
26
- * without reading the message. Without `required`, the result is `string | undefined`.
23
+ * With `transform` the result is what it makes of the value (a number, a boolean). It is handed
24
+ * `undefined` when the value is unset, and `defaultValue` applies when it answers `undefined` or
25
+ * `null`. A `transform` that throws raises an `ApplicationError` with `normalized.code` equal to
26
+ * `RUNTIME_CONFIG_INVALID_CODE` and the key in `extra.key`, never the value.
27
27
  */
28
- static get(opts: IRuntimeConfigOptions & {
29
- required: true;
28
+ static get(opts: IRuntimeConfigReadOptions & {
29
+ defaultValue: string;
30
+ transform?: undefined;
30
31
  }): string;
31
- static get(opts: IRuntimeConfigOptions & {
32
- required?: boolean;
32
+ static get(opts: IRuntimeConfigReadOptions & {
33
+ defaultValue?: undefined;
34
+ transform?: undefined;
33
35
  }): string | undefined;
36
+ static get<TValue>(opts: IRuntimeConfigReadOptions & {
37
+ transform: (raw: string | undefined) => TValue | null | undefined;
38
+ defaultValue: TValue;
39
+ }): TValue;
40
+ static get<TValue>(opts: IRuntimeConfigReadOptions & {
41
+ transform: (raw: string | undefined) => TValue;
42
+ defaultValue?: TValue;
43
+ }): TValue;
44
+ /**
45
+ * One config value the app cannot run without, read as `get` reads it. When it is unset it throws,
46
+ * naming the key and never a value: an `ApplicationError` with `normalized.code` equal to
47
+ * `RUNTIME_CONFIG_REQUIRED_CODE` and the key in `extra.key`, so a caller tells it from another
48
+ * error without reading the message. It has no `defaultValue`.
49
+ *
50
+ * With `transform` the result is what it makes of the value, which it is handed as a `string`. A
51
+ * `transform` that throws, or answers `undefined` or `null`, raises the error of
52
+ * `RUNTIME_CONFIG_INVALID_CODE`, with the key in `extra.key` and never the value.
53
+ */
54
+ static getRequired(opts: IRuntimeConfigReadOptions & {
55
+ transform?: undefined;
56
+ }): string;
57
+ static getRequired<TValue>(opts: IRuntimeConfigReadOptions & {
58
+ transform: (raw: string) => TValue | null | undefined;
59
+ }): TValue;
34
60
  }
35
61
  export {};
36
62
  //# sourceMappingURL=runtime-config.d.ts.map
@@ -4,8 +4,10 @@ import { getError } from '@venizia/ignis-inversion';
4
4
  * The preset image writes it at container start, from the environment variables that start with `VITE_`.
5
5
  */
6
6
  export const RUNTIME_CONFIG_GLOBAL = '__APP_CONFIG__';
7
- /** The `normalized.code` of the error `RuntimeConfig.get` throws for a required value that is not set; the key is in its `extra.key`. */
7
+ /** The `normalized.code` of the error `RuntimeConfig.getRequired` throws for a value that is not set; the key is in its `extra.key`. */
8
8
  export const RUNTIME_CONFIG_REQUIRED_CODE = 'ardor.runtime_config.required';
9
+ /** The `normalized.code` of the error a `transform` of `RuntimeConfig` causes by throwing, or by answering `undefined` or `null` to `getRequired`; the key is in its `extra.key`, the value is never in the error. */
10
+ export const RUNTIME_CONFIG_INVALID_CODE = 'ardor.runtime_config.invalid';
9
11
  const readString = (opts) => {
10
12
  const { source, key } = opts;
11
13
  if (typeof source !== 'object' || source === null || Array.isArray(source)) {
@@ -16,20 +18,55 @@ const readString = (opts) => {
16
18
  return undefined;
17
19
  }
18
20
  const value = Reflect.get(source, key);
19
- return typeof value === 'string' && value !== '' ? value : undefined;
21
+ return typeof value === 'string' && value.trim() !== '' ? value : undefined;
22
+ };
23
+ const readValue = (opts) => {
24
+ const { key, buildTimeEnv } = opts;
25
+ return (readString({ source: Reflect.get(globalThis, RUNTIME_CONFIG_GLOBAL), key }) ??
26
+ readString({ source: buildTimeEnv, key }));
27
+ };
28
+ const applyTransform = (opts) => {
29
+ const { key, raw, transform } = opts;
30
+ try {
31
+ return transform(raw);
32
+ }
33
+ catch {
34
+ throw getError({
35
+ messageCode: RUNTIME_CONFIG_INVALID_CODE,
36
+ extra: { key },
37
+ message: `[RuntimeConfig] '${key}' is not valid | The transform threw on the value; fix the value in config.js or in the build-time env`,
38
+ });
39
+ }
20
40
  };
21
41
  /** Reads configuration a deployment can change without a rebuild. */
22
42
  export class RuntimeConfig {
23
43
  static get(opts) {
24
- const { key, buildTimeEnv, defaultValue, required } = opts;
25
- const value = readString({ source: Reflect.get(globalThis, RUNTIME_CONFIG_GLOBAL), key }) ??
26
- readString({ source: buildTimeEnv, key }) ??
27
- defaultValue;
28
- if (required && value === undefined) {
44
+ const { key, defaultValue, transform } = opts;
45
+ const raw = readValue(opts);
46
+ if (transform === undefined) {
47
+ return raw ?? defaultValue;
48
+ }
49
+ return applyTransform({ key, raw, transform }) ?? defaultValue;
50
+ }
51
+ static getRequired(opts) {
52
+ const { key, transform } = opts;
53
+ const raw = readValue(opts);
54
+ if (raw === undefined) {
29
55
  throw getError({
30
56
  messageCode: RUNTIME_CONFIG_REQUIRED_CODE,
31
57
  extra: { key },
32
- message: `[RuntimeConfig.get] '${key}' is required and not set | Write it to config.js (a VITE_ variable of the container, listed in APP_REQUIRED_ENV), or pass it in buildTimeEnv or defaultValue`,
58
+ message: `[RuntimeConfig.getRequired] '${key}' is required and not set | Write it to config.js (a VITE_ variable of the container, listed in APP_REQUIRED_ENV), or pass it in buildTimeEnv`,
59
+ });
60
+ }
61
+ if (transform === undefined) {
62
+ return raw;
63
+ }
64
+ const value = applyTransform({ key, raw, transform });
65
+ if (value === undefined || value === null) {
66
+ throw getError({
67
+ messageCode: RUNTIME_CONFIG_INVALID_CODE,
68
+ extra: { key },
69
+ message: `[RuntimeConfig.getRequired] '${key}' is not valid | The transform answered nothing for the value; fix the value in config.js or in the build-time env`,
33
70
  });
34
71
  }
35
72
  return value;