@venizia/ardor-kernel 0.4.8-0 → 0.4.8-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 (104) hide show
  1. package/README.md +10 -6
  2. package/dist/base/applications/abstract.d.ts +17 -1
  3. package/dist/base/applications/abstract.js +7 -0
  4. package/dist/base/providers/base.d.ts +2 -0
  5. package/dist/base/providers/base.js +1 -0
  6. package/dist/base/services/auth.d.ts +23 -2
  7. package/dist/base/services/auth.js +48 -13
  8. package/dist/base/services/base.d.ts +1 -0
  9. package/dist/base/services/base.js +1 -0
  10. package/dist/base/services/network-request.d.ts +78 -4
  11. package/dist/base/services/network-request.js +161 -10
  12. package/dist/common/constants.d.ts +47 -0
  13. package/dist/common/constants.js +47 -0
  14. package/dist/common/keys.d.ts +37 -1
  15. package/dist/common/keys.js +41 -1
  16. package/dist/common/types.d.ts +99 -8
  17. package/dist/helpers/auth-token-store.d.ts +6 -2
  18. package/dist/helpers/auth-token-store.js +5 -4
  19. package/dist/helpers/networks/auth-recovery.d.ts +1 -0
  20. package/dist/helpers/networks/request-body-encoder.d.ts +1 -0
  21. package/dist/helpers/networks/request-body-encoder.js +1 -0
  22. package/dist/helpers/networks/response-reader.d.ts +8 -0
  23. package/dist/helpers/networks/response-reader.js +8 -0
  24. package/dist/testing.d.ts +137 -0
  25. package/dist/testing.js +367 -0
  26. package/dist/utilities/browser-clipboard.d.ts +17 -0
  27. package/dist/utilities/browser-clipboard.js +37 -0
  28. package/dist/utilities/browser-storage.d.ts +42 -2
  29. package/dist/utilities/browser-storage.js +49 -5
  30. package/dist/utilities/browser.d.ts +2 -0
  31. package/dist/utilities/browser.js +2 -0
  32. package/dist/utilities/file.d.ts +1 -0
  33. package/dist/utilities/file.js +1 -0
  34. package/dist/utilities/index.d.ts +2 -0
  35. package/dist/utilities/index.js +2 -0
  36. package/dist/utilities/runtime-config.d.ts +4 -0
  37. package/dist/utilities/runtime-config.js +1 -0
  38. package/dist/utilities/storage-codecs.d.ts +9 -0
  39. package/dist/utilities/storage-codecs.js +19 -0
  40. package/dist/utilities/value.d.ts +3 -0
  41. package/dist/utilities/value.js +3 -0
  42. package/package.json +24 -14
  43. package/dist/base/applications/abstract.d.ts.map +0 -1
  44. package/dist/base/applications/abstract.js.map +0 -1
  45. package/dist/base/applications/index.d.ts.map +0 -1
  46. package/dist/base/applications/index.js.map +0 -1
  47. package/dist/base/decorators/api.d.ts.map +0 -1
  48. package/dist/base/decorators/api.js.map +0 -1
  49. package/dist/base/decorators/index.d.ts.map +0 -1
  50. package/dist/base/decorators/index.js.map +0 -1
  51. package/dist/base/index.d.ts.map +0 -1
  52. package/dist/base/index.js.map +0 -1
  53. package/dist/base/metadata/index.d.ts.map +0 -1
  54. package/dist/base/metadata/index.js.map +0 -1
  55. package/dist/base/providers/base.d.ts.map +0 -1
  56. package/dist/base/providers/base.js.map +0 -1
  57. package/dist/base/providers/index.d.ts.map +0 -1
  58. package/dist/base/providers/index.js.map +0 -1
  59. package/dist/base/repositories/index.d.ts.map +0 -1
  60. package/dist/base/repositories/index.js.map +0 -1
  61. package/dist/base/services/auth.d.ts.map +0 -1
  62. package/dist/base/services/auth.js.map +0 -1
  63. package/dist/base/services/base.d.ts.map +0 -1
  64. package/dist/base/services/base.js.map +0 -1
  65. package/dist/base/services/index.d.ts.map +0 -1
  66. package/dist/base/services/index.js.map +0 -1
  67. package/dist/base/services/network-request.d.ts.map +0 -1
  68. package/dist/base/services/network-request.js.map +0 -1
  69. package/dist/common/constants.d.ts.map +0 -1
  70. package/dist/common/constants.js.map +0 -1
  71. package/dist/common/index.d.ts.map +0 -1
  72. package/dist/common/index.js.map +0 -1
  73. package/dist/common/keys.d.ts.map +0 -1
  74. package/dist/common/keys.js.map +0 -1
  75. package/dist/common/types.d.ts.map +0 -1
  76. package/dist/common/types.js.map +0 -1
  77. package/dist/helpers/auth-token-store.d.ts.map +0 -1
  78. package/dist/helpers/auth-token-store.js.map +0 -1
  79. package/dist/helpers/index.d.ts.map +0 -1
  80. package/dist/helpers/index.js.map +0 -1
  81. package/dist/helpers/networks/auth-recovery.d.ts.map +0 -1
  82. package/dist/helpers/networks/auth-recovery.js.map +0 -1
  83. package/dist/helpers/networks/headers.d.ts.map +0 -1
  84. package/dist/helpers/networks/headers.js.map +0 -1
  85. package/dist/helpers/networks/index.d.ts.map +0 -1
  86. package/dist/helpers/networks/index.js.map +0 -1
  87. package/dist/helpers/networks/request-body-encoder.d.ts.map +0 -1
  88. package/dist/helpers/networks/request-body-encoder.js.map +0 -1
  89. package/dist/helpers/networks/response-reader.d.ts.map +0 -1
  90. package/dist/helpers/networks/response-reader.js.map +0 -1
  91. package/dist/index.d.ts.map +0 -1
  92. package/dist/index.js.map +0 -1
  93. package/dist/utilities/browser-storage.d.ts.map +0 -1
  94. package/dist/utilities/browser-storage.js.map +0 -1
  95. package/dist/utilities/browser.d.ts.map +0 -1
  96. package/dist/utilities/browser.js.map +0 -1
  97. package/dist/utilities/file.d.ts.map +0 -1
  98. package/dist/utilities/file.js.map +0 -1
  99. package/dist/utilities/index.d.ts.map +0 -1
  100. package/dist/utilities/index.js.map +0 -1
  101. package/dist/utilities/runtime-config.d.ts.map +0 -1
  102. package/dist/utilities/runtime-config.js.map +0 -1
  103. package/dist/utilities/value.d.ts.map +0 -1
  104. package/dist/utilities/value.js.map +0 -1
package/README.md CHANGED
@@ -4,9 +4,13 @@ The isomorphic core of [ARDOR](https://github.com/VENIZIA-AI/ardor). No React, n
4
4
  layer a browser data client and a plain TypeScript consumer can both use.
5
5
 
6
6
  ```bash
7
- bun add @venizia/ardor-kernel @venizia/ignis-inversion @venizia/ignis-filter reflect-metadata
7
+ bun add @venizia/ardor-kernel @venizia/ignis-inversion @venizia/ignis-filter @venizia/ignis-helpers @venizia/ignis-kernel reflect-metadata
8
8
  ```
9
9
 
10
+ `@venizia/ignis-connectors` is an optional peer, needed only for `./repository`.
11
+
12
+ `@venizia/ardor-kernel/testing` holds fakes of `ResizeObserver`, `IntersectionObserver`, `matchMedia`, `Storage` and `navigator.clipboard` for your tests; the main entry does not include them.
13
+
10
14
  Most applications install [`@venizia/ardor`](https://www.npmjs.com/package/@venizia/ardor) instead,
11
15
  which re-exports this package.
12
16
 
@@ -14,14 +18,14 @@ which re-exports this package.
14
18
 
15
19
  | Area | Exports |
16
20
  |---|---|
17
- | Application | `AbstractArdorApplication`, `BaseArdorApplication` - an IGNIS inversion `Container` with `injectable()` and `service()` helpers |
21
+ | Application | `AbstractArdorApplication`, `BaseArdorApplication` - an IGNIS inversion `Container` with `injectable()`, `service()`, `repository()`, `dataSource()` and `component()` helpers |
18
22
  | Services | `BaseService`, `DefaultAuthService`, `DefaultNetworkRequestService` |
19
23
  | Providers | `BaseProvider` |
20
- | Decorators | `api()` - logs and rethrows a failing API method |
21
- | Bindings | `CoreBindings`, `LocalStorageKeys` |
22
- | Constants | `RequestMethods`, `RequestTypes`, `RequestBodyTypes`, `RequestCountData`, `HeaderConstants`, `Environments`, `App` |
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
+ | Bindings | `CoreBindings`, `LocalStorageKeys`, `BindingKeys`, `BindingNamespaces` |
26
+ | Constants | `RequestMethods`, `RequestTypes`, `RequestBodyTypes`, `RequestCountData`, `HeaderConstants`, `Environments`, `App`, `Authentication`, `StorageAreas`, `RequestChannel` |
23
27
  | Network | `NetworkHeaders`, `RequestBodyEncoder`, `ResponseReader`, `AuthRecovery`, `AuthTokenStore` (the fetch transport is IGNIS's `NodeFetchNetworkRequest`) |
24
- | Utilities | `ValueUtility` (`isDefined`, `isString`, `isNumber`, `isObject`, `isValidDate`), `BrowserUtility.isBrowser`, `FileUtility.toDataUrl`, `RuntimeConfig.get`; the earlier bare names are removed (`bun run ardor codemod namespace` moves your code) |
28
+ | Utilities | `ValueUtility` (`isDefined`, `isString`, `isNumber`, `isObject`, `isValidDate`), `BrowserUtility.isBrowser`, `FileUtility.toDataUrl`, `RuntimeConfig.get` (with `RUNTIME_CONFIG_GLOBAL` and `RUNTIME_CONFIG_REQUIRED_CODE`), `BrowserStorage`, `BrowserClipboard`, `StorageCodecs`; the earlier bare names are removed (`bun run ardor codemod namespace` moves your code) |
25
29
  | Types | `IdType`, `AnyType`, `AnyObject`, `ValueOrPromise`, `ValueOf`, `TConstValue`, `TPaths`, `TFullPaths`, `ISendParams`, `IRestDataProviderOptions`, `IApplicationInfo`, ... |
26
30
 
27
31
  ## License
@@ -7,8 +7,15 @@ export interface IArtifactRegistration {
7
7
  namespace: string;
8
8
  key: string;
9
9
  };
10
+ /**
11
+ * The scope of the binding.
12
+ * @default The scope declared on the class, else `BindingScopes.SINGLETON`
13
+ */
10
14
  scope?: TBindingScope;
11
- /** `false` refuses to replace a binding already under the key. */
15
+ /**
16
+ * `false` refuses to replace a binding already under the key.
17
+ * @default true
18
+ */
12
19
  allowOverride?: boolean;
13
20
  }
14
21
  /**
@@ -17,7 +24,9 @@ export interface IArtifactRegistration {
17
24
  * SINGLETON (IGNIS's server uses transient): a hook resolves on every render.
18
25
  */
19
26
  export declare abstract class AbstractArdorApplication extends Container implements IArdorApplication {
27
+ /** The application's own bindings; `preConfigure` runs it last, so they win over discovered and feature bindings. */
20
28
  abstract bindContext(): ValueOrPromise<void>;
29
+ /** The `IApplicationInfo` that `preConfigure` binds under `CoreBindings.APPLICATION_INFO`. */
21
30
  abstract getAppInfo(): ValueOrPromise<IApplicationInfo>;
22
31
  /** What `start()` resolved from `artifacts()`; unset when `preConfigure()` runs without it. */
23
32
  private resolvedIndexes;
@@ -57,17 +66,24 @@ export declare abstract class AbstractArdorApplication extends Container impleme
57
66
  * been discovered: one that was not means the feature's bindings were silently never made.
58
67
  */
59
68
  private registerFeatures;
69
+ /** Runs after `preConfigure` in `start()`; empty by default, for a subclass to override. */
60
70
  postConfigure(): ValueOrPromise<void>;
71
+ /** Binds `target` in the service namespace; returns the binding. */
61
72
  service<T>(target: TClass<T>, opts?: IArtifactRegistration): Binding<T>;
73
+ /** Binds `target` in the repository namespace; returns the binding. */
62
74
  repository<T>(target: TClass<T>, opts?: IArtifactRegistration): Binding<T>;
75
+ /** Binds `target` in the data source namespace; returns the binding. */
63
76
  dataSource<T>(target: TClass<T>, opts?: IArtifactRegistration): Binding<T>;
77
+ /** Binds `target` in the component namespace; returns the binding. */
64
78
  component<T>(target: TClass<T>, opts?: IArtifactRegistration): Binding<T>;
65
79
  /** `<scope>.<ClassName>`, singleton, with tags. Prefer the per-kind methods above. */
66
80
  injectable<T>(scope: string, value: TClass<T>, tags?: Array<string>): void;
81
+ /** Resolves the artifact indexes, then runs `preConfigure`, then `postConfigure`, in that order. */
67
82
  start(): Promise<void>;
68
83
  /** Key: explicit `binding` > the class's stereotype > `<namespace>.<ClassName>`. Same for scope. */
69
84
  private registerArtifact;
70
85
  }
86
+ /** The base to extend for an application: implement `bindContext` and `getAppInfo`. */
71
87
  export declare abstract class BaseArdorApplication extends AbstractArdorApplication {
72
88
  }
73
89
  //# sourceMappingURL=abstract.d.ts.map
@@ -176,7 +176,9 @@ export class AbstractArdorApplication extends Container {
176
176
  }
177
177
  this.bind({ key: CoreBindings.FEATURES }).toValue(features);
178
178
  }
179
+ /** Runs after `preConfigure` in `start()`; empty by default, for a subclass to override. */
179
180
  postConfigure() { }
181
+ /** Binds `target` in the service namespace; returns the binding. */
180
182
  service(target, opts) {
181
183
  return this.registerArtifact({
182
184
  target,
@@ -185,6 +187,7 @@ export class AbstractArdorApplication extends Container {
185
187
  opts,
186
188
  });
187
189
  }
190
+ /** Binds `target` in the repository namespace; returns the binding. */
188
191
  repository(target, opts) {
189
192
  return this.registerArtifact({
190
193
  target,
@@ -193,6 +196,7 @@ export class AbstractArdorApplication extends Container {
193
196
  opts,
194
197
  });
195
198
  }
199
+ /** Binds `target` in the data source namespace; returns the binding. */
196
200
  dataSource(target, opts) {
197
201
  return this.registerArtifact({
198
202
  target,
@@ -201,6 +205,7 @@ export class AbstractArdorApplication extends Container {
201
205
  opts,
202
206
  });
203
207
  }
208
+ /** Binds `target` in the component namespace; returns the binding. */
204
209
  component(target, opts) {
205
210
  return this.registerArtifact({
206
211
  target,
@@ -218,6 +223,7 @@ export class AbstractArdorApplication extends Container {
218
223
  .setScope(BindingScopes.SINGLETON)
219
224
  .setTags(...(tags ?? []));
220
225
  }
226
+ /** Resolves the artifact indexes, then runs `preConfigure`, then `postConfigure`, in that order. */
221
227
  async start() {
222
228
  const result = await this.resolveArtifactIndexes();
223
229
  this.resolvedIndexes = result;
@@ -245,6 +251,7 @@ export class AbstractArdorApplication extends Container {
245
251
  .setScope(opts.opts?.scope ?? declared?.scope ?? BindingScopes.SINGLETON);
246
252
  }
247
253
  }
254
+ /** The base to extend for an application: implement `bindContext` and `getAppInfo`. */
248
255
  export class BaseArdorApplication extends AbstractArdorApplication {
249
256
  }
250
257
  //# sourceMappingURL=abstract.js.map
@@ -1,6 +1,8 @@
1
1
  import { BaseHelper } from '@venizia/ignis-helpers/core';
2
2
  import type { Container, IProvider } from '@venizia/ignis-inversion';
3
+ /** Base of a provider: `value` yields what the provider supplies, resolved through the container. */
3
4
  export declare abstract class BaseProvider<T> extends BaseHelper implements IProvider<T> {
5
+ /** Produces the provided value. */
4
6
  abstract value(container: Container): T;
5
7
  }
6
8
  //# sourceMappingURL=base.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import { BaseHelper } from '@venizia/ignis-helpers/core';
2
+ /** Base of a provider: `value` yields what the provider supplies, resolved through the container. */
2
3
  export class BaseProvider extends BaseHelper {
3
4
  }
4
5
  //# sourceMappingURL=base.js.map
@@ -1,8 +1,15 @@
1
- import { type AnyType, type IAuthTokenRecord, type IdType } from '../../common/index.js';
1
+ import { type AnyType, type IApplicationInfo, type IAuthTokenRecord, type IdType, type IScopedKeys } from '../../common/index.js';
2
2
  import { BaseService } from './base.js';
3
+ /**
4
+ * Keeps the signed-in session (token, identity, roles) in `localStorage`, everything under
5
+ * `keys.authPrefix`: `LocalStorageKeys.PREFIX_AUTH`, or `@app/auth/<id>/` when the application has an `id`.
6
+ */
3
7
  export declare class DefaultAuthService extends BaseService {
4
8
  private readonly listeners;
5
- constructor();
9
+ /** The keys of this application's session and store: the application's `id` scopes them. */
10
+ readonly keys: IScopedKeys;
11
+ /** A subclass with its own constructor passes `info` on to `super(info)`; otherwise its keys are the unscoped ones. */
12
+ constructor(info?: IApplicationInfo);
6
13
  /** `listener` runs after every `saveAuth` and `cleanUp`, so after any change of the session this service makes. */
7
14
  subscribe(opts: {
8
15
  listener: () => void;
@@ -15,14 +22,27 @@ export declare class DefaultAuthService extends BaseService {
15
22
  * logged: the message of a JSON parse error quotes the text it could not parse, which can be a token.
16
23
  */
17
24
  private parseStored;
25
+ /** The stored identity; `{}` when nothing usable is stored, also outside a browser. */
18
26
  getUser(): AnyType;
27
+ /**
28
+ * The stored roles; empty when nothing usable is stored, also outside a browser. They are data in
29
+ * the browser, so whoever controls the browser can change them: use them to show or hide interface,
30
+ * never to decide what a user may do. The backend must check every permission on every request.
31
+ */
19
32
  getRoles(): Set<string>;
20
33
  /** The stored token, `null` for every visitor who has not signed in. */
21
34
  getAuth(): IAuthTokenRecord | null;
35
+ /**
36
+ * Stores the token and identity, then notifies the subscribers. Throws when `localStorage` is
37
+ * not available. Roles are stored only when `roles` is given.
38
+ */
22
39
  saveAuth(opts: {
23
40
  userId: number | string;
41
+ /** @default '' */
24
42
  username?: string;
43
+ /** @default '' */
25
44
  provider?: string;
45
+ /** @default '' */
26
46
  referenceId?: IdType;
27
47
  token: {
28
48
  value: string;
@@ -34,6 +54,7 @@ export declare class DefaultAuthService extends BaseService {
34
54
  */
35
55
  roles?: ReadonlyArray<string>;
36
56
  }): void;
57
+ /** Removes every key under `keys.authPrefix`, then notifies the subscribers; does nothing outside a browser. */
37
58
  cleanUp(): void;
38
59
  }
39
60
  //# sourceMappingURL=auth.d.ts.map
@@ -1,11 +1,30 @@
1
- import { getError } from '@venizia/ignis-inversion';
2
- import { LocalStorageKeys } from '../../common/index.js';
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ var DefaultAuthService_1;
14
+ import { getError, inject } from '@venizia/ignis-inversion';
15
+ import { CoreBindings, LocalStorageKeys, } from '../../common/index.js';
3
16
  import { AuthTokenStore } from '../../helpers/index.js';
4
17
  import { BaseService } from './base.js';
5
- export class DefaultAuthService extends BaseService {
6
- constructor() {
7
- super({ scope: DefaultAuthService.name });
18
+ /**
19
+ * Keeps the signed-in session (token, identity, roles) in `localStorage`, everything under
20
+ * `keys.authPrefix`: `LocalStorageKeys.PREFIX_AUTH`, or `@app/auth/<id>/` when the application has an `id`.
21
+ */
22
+ let DefaultAuthService = DefaultAuthService_1 = class DefaultAuthService extends BaseService {
23
+ /** A subclass with its own constructor passes `info` on to `super(info)`; otherwise its keys are the unscoped ones. */
24
+ constructor(info) {
25
+ super({ scope: DefaultAuthService_1.name });
8
26
  this.listeners = new Set();
27
+ this.keys = LocalStorageKeys.scoped({ id: info?.id });
9
28
  }
10
29
  /** `listener` runs after every `saveAuth` and `cleanUp`, so after any change of the session this service makes. */
11
30
  subscribe(opts) {
@@ -45,17 +64,23 @@ export class DefaultAuthService extends BaseService {
45
64
  return undefined;
46
65
  }
47
66
  }
67
+ /** The stored identity; `{}` when nothing usable is stored, also outside a browser. */
48
68
  getUser() {
49
69
  const identity = this.parseStored({
50
- key: LocalStorageKeys.KEY_AUTH_IDENTITY,
70
+ key: this.keys.identity,
51
71
  method: 'getUser',
52
72
  });
53
73
  const isRecord = typeof identity === 'object' && identity !== null && !Array.isArray(identity);
54
74
  return isRecord ? identity : {};
55
75
  }
76
+ /**
77
+ * The stored roles; empty when nothing usable is stored, also outside a browser. They are data in
78
+ * the browser, so whoever controls the browser can change them: use them to show or hide interface,
79
+ * never to decide what a user may do. The backend must check every permission on every request.
80
+ */
56
81
  getRoles() {
57
82
  const stored = this.parseStored({
58
- key: LocalStorageKeys.KEY_AUTH_PERMISSION,
83
+ key: this.keys.permission,
59
84
  method: 'getRoles',
60
85
  });
61
86
  const roles = Array.isArray(stored) ? stored.filter((role) => typeof role === 'string') : [];
@@ -63,8 +88,12 @@ export class DefaultAuthService extends BaseService {
63
88
  }
64
89
  /** The stored token, `null` for every visitor who has not signed in. */
65
90
  getAuth() {
66
- return AuthTokenStore.read() ?? null;
91
+ return AuthTokenStore.read({ key: this.keys.token }) ?? null;
67
92
  }
93
+ /**
94
+ * Stores the token and identity, then notifies the subscribers. Throws when `localStorage` is
95
+ * not available. Roles are stored only when `roles` is given.
96
+ */
68
97
  saveAuth(opts) {
69
98
  // Not a silent skip: a sign-in that is not kept would look like it worked.
70
99
  if (typeof localStorage === 'undefined') {
@@ -73,24 +102,30 @@ export class DefaultAuthService extends BaseService {
73
102
  });
74
103
  }
75
104
  const { token, userId, username = '', provider = '', referenceId = '', roles } = opts;
76
- AuthTokenStore.write({ token, provider });
77
- localStorage.setItem(LocalStorageKeys.KEY_AUTH_IDENTITY, JSON.stringify({ userId, username, referenceId, provider }));
105
+ AuthTokenStore.write({ token, provider, key: this.keys.token });
106
+ localStorage.setItem(this.keys.identity, JSON.stringify({ userId, username, referenceId, provider }));
78
107
  if (roles) {
79
- localStorage.setItem(LocalStorageKeys.KEY_AUTH_PERMISSION, JSON.stringify(roles));
108
+ localStorage.setItem(this.keys.permission, JSON.stringify(roles));
80
109
  }
81
110
  this.notify();
82
111
  }
112
+ /** Removes every key under `keys.authPrefix`, then notifies the subscribers; does nothing outside a browser. */
83
113
  cleanUp() {
84
114
  if (typeof localStorage === 'undefined') {
85
115
  return;
86
116
  }
87
117
  Object.keys(localStorage).forEach((key) => {
88
- if (!key.startsWith(LocalStorageKeys.PREFIX_AUTH)) {
118
+ if (!key.startsWith(this.keys.authPrefix)) {
89
119
  return;
90
120
  }
91
121
  localStorage.removeItem(key);
92
122
  });
93
123
  this.notify();
94
124
  }
95
- }
125
+ };
126
+ DefaultAuthService = DefaultAuthService_1 = __decorate([
127
+ __param(0, inject({ key: CoreBindings.APPLICATION_INFO, isOptional: true })),
128
+ __metadata("design:paramtypes", [Object])
129
+ ], DefaultAuthService);
130
+ export { DefaultAuthService };
96
131
  //# sourceMappingURL=auth.js.map
@@ -1,4 +1,5 @@
1
1
  import { BaseHelper } from '@venizia/ignis-helpers/core';
2
+ /** Base of the services of an application; a `BaseHelper` with a scoped logger. */
2
3
  export declare class BaseService extends BaseHelper {
3
4
  }
4
5
  //# sourceMappingURL=base.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import { BaseHelper } from '@venizia/ignis-helpers/core';
2
+ /** Base of the services of an application; a `BaseHelper` with a scoped logger. */
2
3
  export class BaseService extends BaseHelper {
3
4
  }
4
5
  //# sourceMappingURL=base.js.map
@@ -1,30 +1,62 @@
1
1
  import { NodeFetchNetworkRequest } 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 TRequestType } from '../../common/index.js';
3
3
  import { type IEncodedBody, ResponseReader } from '../../helpers/index.js';
4
+ import type { DefaultAuthService } from './auth.js';
4
5
  import { BaseService } from './base.js';
5
6
  /**
6
7
  * The options hold data (the base URL, headers, the no-auth lists, the refresh path); behaviour is
7
8
  * in the protected hooks, each taking one `opts` object, which a subclass overrides.
8
9
  */
9
10
  export declare class DefaultNetworkRequestService extends BaseService {
11
+ /** Resources sent without a token, matched exactly. */
10
12
  protected noAuthPaths?: string[];
13
+ /** `noAuthPathRegex` compiled; a resource matching any is sent without a token. */
11
14
  protected noAuthPathRegexes: RegExp[];
15
+ /** Headers added to every request, keyed by lowercase name. */
12
16
  protected headers: Record<string, string>;
13
17
  protected networkRequest: NodeFetchNetworkRequest;
18
+ /** The origin and base path requests are sent to; an empty one makes `doRequest` throw. */
14
19
  protected baseUrl: string;
15
20
  protected authRecovery?: IAuthRecoveryOptions;
21
+ protected authService?: DefaultAuthService;
16
22
  private readonly recovery;
17
23
  constructor(opts: INoAuthOptions & {
24
+ /** The name of the underlying network request helper. */
18
25
  name: string;
26
+ /**
27
+ * An empty one makes `doRequest` refuse, unless it is given its own `baseUrl`.
28
+ * @default ''
29
+ */
19
30
  baseUrl?: string;
31
+ /**
32
+ * Sent with every request; a name set later with `setHeaders` replaces it.
33
+ * @default {}
34
+ */
20
35
  headers?: HeadersInit;
36
+ /** Enables the refresh-and-retry after a 401. */
21
37
  authRecovery?: IAuthRecoveryOptions;
38
+ /** What the default `refreshToken` saves the new token through. */
39
+ authService?: DefaultAuthService;
22
40
  });
23
41
  /**
24
- * The stored token (`AuthTokenStore.read`), `undefined` outside a browser. The default of
25
- * `resolveAuthToken`, and what to hand an `HttpDataSource` as its `authTokenResolver`.
42
+ * The token under the unscoped session key (`AuthTokenStore.read`), `undefined` outside a browser, for an
43
+ * application with no `id`. With an application `id` the session is under other keys: use
44
+ * `createAuthTokenReader({ id })`, the `HttpDataSource` `getDataSourceAuth()` of the data provider, or `authService.getAuth`.
26
45
  */
27
46
  static readAuthTokenFromStorage(): IAuthTokenRecord | undefined;
47
+ /**
48
+ * A reader of the stored token of the application with this `id` (`IApplicationInfo.id`): the same
49
+ * key `DefaultAuthService.getAuth` reads (`LocalStorageKeys.scoped({ id }).token`). Without an `id` it
50
+ * is `readAuthTokenFromStorage`. Throws for an invalid `id`, when it is created.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * super({ baseUrl: '/api', authTokenResolver: DefaultNetworkRequestService.createAuthTokenReader({ id: 'shop' }) });
55
+ * ```
56
+ */
57
+ static createAuthTokenReader(opts?: {
58
+ id?: string;
59
+ }): () => IAuthTokenRecord | undefined;
28
60
  /**
29
61
  * The token this service sends. The one way to supply a token: override it to read another
30
62
  * store, or to hold the token in memory.
@@ -41,12 +73,28 @@ export declare class DefaultNetworkRequestService extends BaseService {
41
73
  }): boolean;
42
74
  /**
43
75
  * Refreshes the session after a 401. `true`: refreshed, the request is retried; `false`: this
44
- * service has no refresh (the default); a throw: the refresh failed and `onAuthFailure` runs.
76
+ * service has no refresh, or the session changed while the request was in flight (another user
77
+ * signed in, the user signed out, or another tab refreshed): the new token is not saved, and the
78
+ * failure of a refresh made for a session that is gone is not reported; a throw: the refresh
79
+ * failed and `onAuthFailure` runs. The default posts to `authRecovery.refreshTokenPath` with no
80
+ * body and saves the new token through `authService`, keeping the stored identity and roles;
81
+ * with no path or no `authService` it answers `false`.
45
82
  */
46
83
  protected refreshToken(): Promise<boolean>;
84
+ /**
85
+ * The new token of a refresh response: `{ token: { value, type } }` or `{ token: '<jwt>' }`. A
86
+ * refresh keeps the same user, so nothing else is read. Override it for another shape. No token is
87
+ * a throw.
88
+ */
89
+ protected readRefreshedToken(opts: {
90
+ data: unknown;
91
+ }): {
92
+ value: string;
93
+ type: string;
94
+ };
47
95
  /** Runs once when `refreshToken` threw. The place to send the user back to sign-in. */
48
96
  protected onAuthFailure(): Promise<void>;
49
- /** The tracing id of a request, sent in `x-request-tracing-id`. Default `<application name>_<uuid>`. */
97
+ /** The tracing id of a request, sent in `x-request-id`. Default `<application name>_<uuid>`. */
50
98
  protected buildRequestTracingId(opts: {
51
99
  applicationInfo: IApplicationInfo;
52
100
  }): string;
@@ -65,6 +113,10 @@ export declare class DefaultNetworkRequestService extends BaseService {
65
113
  * options), and a 401 joins this service's shared `refresh`. A no-auth path gets no token.
66
114
  */
67
115
  getDataSourceAuth(opts?: Pick<IGetRequestPropsParams, 'restDataProviderOptions' | 'applicationInfo'>): IDataSourceAuth;
116
+ /**
117
+ * The `token` (`<type> <value>`, `Bearer` when the type is empty) and `provider` of the stored
118
+ * token. Throws an error with status 401 when there is no token.
119
+ */
68
120
  getRequestAuthorizationHeader(): {
69
121
  provider: string | undefined;
70
122
  token: string;
@@ -73,6 +125,7 @@ export declare class DefaultNetworkRequestService extends BaseService {
73
125
  setHeaders(opts: {
74
126
  headers: HeadersInit;
75
127
  }): void;
128
+ /** Removes the headers set by name, in any case. */
76
129
  removeHeaders(opts: {
77
130
  keys: string[];
78
131
  }): void;
@@ -80,14 +133,28 @@ export declare class DefaultNetworkRequestService extends BaseService {
80
133
  protected getSessionHeaders(): Record<string, string>;
81
134
  /** The request channel (`RequestChannel.WEB` unless configured) and a fresh tracing id. */
82
135
  protected getTracingHeaders(opts: Pick<IGetRequestPropsParams, 'restDataProviderOptions' | 'applicationInfo'>): Record<string, string>;
136
+ /**
137
+ * The session headers, plus `authorization` and `x-auth-provider` unless `resource` is a no-auth
138
+ * path. Throws a 401 error for any other resource when there is no token.
139
+ */
83
140
  getRequestHeader(opts: {
84
141
  resource: string;
85
142
  }): Record<string, string>;
143
+ /**
144
+ * Whether the request stays where `baseUrl` points: no entry of `paths` carries a tab, a line break,
145
+ * a backslash or a dot segment (also written `%2E`), and the URL built from
146
+ * them, resolved the way a browser does, has the origin of the base and a path under it.
147
+ */
148
+ private static isUnderBase;
86
149
  /** The body as it is sent and the content type to send it under. Override to encode another way. */
87
150
  protected encodeBody(opts: {
88
151
  bodyType?: string;
89
152
  body: unknown;
90
153
  }): IEncodedBody;
154
+ /**
155
+ * The headers (session, auth, tracing, `x-request-count`, the `extra` header, and the content type
156
+ * of the encoded body) and the encoded body of a request. Throws as `getRequestHeader` does.
157
+ */
91
158
  getRequestProps(params: IGetRequestPropsParams): IGetRequestPropsResult;
92
159
  /** Reads a response by the request type. See `ResponseReader.convert`. */
93
160
  convertResponse<TData = unknown>(opts: Parameters<typeof ResponseReader.convert<TData>>[0]): {
@@ -95,7 +162,14 @@ export declare class DefaultNetworkRequestService extends BaseService {
95
162
  count?: number;
96
163
  total?: number;
97
164
  };
165
+ /**
166
+ * Sends the request and reads the response by `type`. Throws when `baseUrl` (the option, else the
167
+ * service's) is empty. A 401 on a path that can recover triggers `refresh` and, if it refreshed,
168
+ * one retry with the new token. Any other non-2xx response, or a retry that still fails, throws
169
+ * the error read from the response.
170
+ */
98
171
  doRequest<TResult = unknown>(opts: IGetRequestPropsResult & {
172
+ /** @default this.baseUrl */
99
173
  baseUrl?: string;
100
174
  query?: any;
101
175
  type: TRequestType;