navi-hey 1.5.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -100,6 +100,8 @@ resources:
100
100
  - pages: parsedBody.pagination.pages
101
101
  - page_key: page
102
102
  - zero_indexed: false
103
+ parameters:
104
+ per_page: headers['x-per-page']
103
105
  - url: /categories
104
106
  status: 302
105
107
  - url: /#/categories
@@ -147,6 +149,7 @@ When the web server is enabled, the following screens are available:
147
149
  | `paginated_actions[].pagination[].pages` | Path expression (e.g. `parsedBody.pagination.pages`) resolving to the total page count. |
148
150
  | `paginated_actions[].pagination[].page_key` | Parameter name injected as the current page number into each downstream request. |
149
151
  | `paginated_actions[].pagination[].zero_indexed` | Boolean. Pages start at `0` when `true`, at `1` when `false` (default). |
152
+ | `paginated_actions[].parameters` | Optional. Path expressions (same syntax as `actions[].parameters`) resolved against the response and merged into each page's request parameters. `page_key`'s value always takes precedence on key collision. |
150
153
  | `assets` | Optional list of asset extraction rules. When present on an HTML resource, Navi parses the response body and enqueues a download job for each matched URL. |
151
154
  | `assets[].selector` | CSS selector used to find asset elements in the HTML response (e.g. `script[src]`, `link[rel="stylesheet"]`). |
152
155
  | `assets[].attribute` | Attribute on the matched element that holds the asset URL (e.g. `src`, `href`). |
@@ -165,7 +168,7 @@ For example, requesting `/categories.json` might return `[{ "id": 1 }, { "id": 2
165
168
 
166
169
  ## Paginated Actions
167
170
 
168
- `paginated_actions` complement `actions` when the response indicates multiple pages. Instead of iterating over array items, Navi evaluates a `pages` expression against the whole response, then enqueues one `ResourceRequestJob` per page, injecting the page number under the configured `page_key`.
171
+ `paginated_actions` complement `actions` when the response indicates multiple pages. Instead of iterating over array items, Navi evaluates a `pages` expression against the whole response, then enqueues one `ResourceRequestJob` per page, injecting the page number under the configured `page_key`. An optional `parameters` map (same syntax as `actions[].parameters`) is resolved against that same response and merged into every page's request parameters, overriding same-named inherited parameters — though `page_key`'s value always wins on collision.
169
172
 
170
173
  ```yaml
171
174
  resources:
@@ -178,6 +181,8 @@ resources:
178
181
  - pages: parsedBody.pagination.pages
179
182
  - page_key: page
180
183
  - zero_indexed: false
184
+ parameters:
185
+ per_page: headers['x-per-page']
181
186
  products_page:
182
187
  - url: /products/{:page}.json
183
188
  status: 200
@@ -1,5 +1,4 @@
1
1
  import { LogConfig } from './LogConfig.js';
2
- import { ClientRegistry } from '../../registry/ClientRegistry.js';
3
2
  import { NamespaceMap } from '../../registry/NamespaceMap.js';
4
3
  import { ResourceRegistry } from '../../registry/ResourceRegistry.js';
5
4
  import { ConfigLoader } from '../../services/ConfigLoader.js';
@@ -25,8 +24,7 @@ class Config {
25
24
  this.namespaceMap = NamespaceMap.build(namespaceMap);
26
25
 
27
26
  const defaultNamespace = namespaceMap[DEFAULT_NAMESPACE];
28
- this.resourceRegistry = ResourceRegistry.build(defaultNamespace ? defaultNamespace.resourceRegistry.items : {});
29
- this.clientRegistry = ClientRegistry.build(defaultNamespace ? defaultNamespace.clientRegistry.items : {});
27
+ this.resourceRegistry = defaultNamespace ? defaultNamespace.resourceRegistry : new ResourceRegistry({});
30
28
 
31
29
  this.workersConfig = workersConfig;
32
30
  this.webConfig = webConfig ?? null;
@@ -13,14 +13,16 @@ class WebConfig {
13
13
  * @param {boolean} [config.autostart=true] - Whether the engine starts processing immediately at boot.
14
14
  * @param {number} [config.idle_timeout=0] - Seconds of inactivity (no busy workers, no queued jobs) before the application auto-shuts-down. `0` disables auto-shutdown.
15
15
  * @param {Array<string|object>} [config.links=[]] - Links shown in the web UI.
16
+ * @param {object} [config.api={}] - Configuration for the token-secured `/api` namespace (`{ token }`).
16
17
  */
17
- constructor({ port, logs_page_size: logsPageSize = 20, enable_shutdown: enableShutdown = true, autostart = true, idle_timeout: idleTimeout = 0, links = [] }) {
18
+ constructor({ port, logs_page_size: logsPageSize = 20, enable_shutdown: enableShutdown = true, autostart = true, idle_timeout: idleTimeout = 0, links = [], api = {} }) {
18
19
  this.port = port;
19
20
  this.logsPageSize = logsPageSize;
20
21
  this.enableShutdown = enableShutdown;
21
22
  this.autostart = autostart;
22
23
  this.idleTimeout = idleTimeout;
23
24
  this.links = links.map((link) => Link.fromObject(link));
25
+ this.apiToken = api?.token ?? null;
24
26
  }
25
27
  }
26
28
 
@@ -14,6 +14,7 @@ class ResourceRequest {
14
14
  #clientName;
15
15
  #clientNamespace;
16
16
  #namespace;
17
+ #disabled;
17
18
 
18
19
  /**
19
20
  * @param {object} attributes ResourceRequest attributes
@@ -25,11 +26,26 @@ class ResourceRequest {
25
26
  * @param {Array} [attributes.actions=[]] List of raw action config objects.
26
27
  * @param {Array} [attributes.assets=[]] List of raw asset extraction rule objects.
27
28
  * @param {Array} [attributes.paginated_actions=[]] List of raw paginated action config objects.
29
+ * @param {boolean} [attributes.enabled] Whether this request is enabled. Defaults to enabled
30
+ * when omitted. Ignored when `disabled` is `true`.
31
+ * @param {boolean} [attributes.disabled] Whether this request is disabled. Takes precedence
32
+ * over `enabled` when `true`.
28
33
  */
29
- constructor({ url, status, clientName, namespace = 'default', actions = [], assets = [], paginated_actions = [] }) {
34
+ constructor({
35
+ url,
36
+ status,
37
+ clientName,
38
+ namespace = 'default',
39
+ actions = [],
40
+ assets = [],
41
+ paginated_actions = [],
42
+ enabled,
43
+ disabled,
44
+ }) {
30
45
  this.url = url;
31
46
  this.status = status;
32
47
  this.#namespace = namespace;
48
+ this.#disabled = disabled === true || enabled === false;
33
49
 
34
50
  const parsedClient = ResourceRequest.#parseClient(clientName);
35
51
  this.#clientName = parsedClient.name;
@@ -66,6 +82,17 @@ class ResourceRequest {
66
82
  return this.#namespace;
67
83
  }
68
84
 
85
+ /**
86
+ * Returns whether this resource request is disabled, i.e. it must not be enqueued
87
+ * through any path (startup, manual trigger, or chained actions). A request is
88
+ * disabled when `disabled: true` was given (regardless of `enabled`), or when
89
+ * `enabled: false` was given. Otherwise it is enabled (the default).
90
+ * @returns {boolean} True if the request is disabled.
91
+ */
92
+ get disabled() {
93
+ return this.#disabled;
94
+ }
95
+
69
96
  /**
70
97
  * Enqueues one ActionProcessingJob per action associated with the resource request.
71
98
  * Returns immediately if there are no actions.
@@ -65,6 +65,8 @@ class ResourceRequestAction {
65
65
  const resource = this.#namespaceMap.getResource(this.originNamespace, this.resource, this.namespace);
66
66
 
67
67
  for (const resourceRequest of resource.resourceRequests) {
68
+ if (resourceRequest.disabled) continue;
69
+
68
70
  this.#jobRegistry.enqueue('ResourceRequestJob', { resourceRequest, parameters: vars });
69
71
  }
70
72
  }
@@ -4,6 +4,7 @@ import { LogRegistry } from '../../registry/LogRegistry.js';
4
4
  import { NamespaceMap as DefaultNamespaceMap } from '../../registry/NamespaceMap.js';
5
5
  import { Application } from '../../services/Application.js';
6
6
  import { PaginationConfig } from '../configs/PaginationConfig.js';
7
+ import { ParametersMapper } from '../response/ParametersMapper.js';
7
8
 
8
9
  /**
9
10
  * Represents a single paginated action to execute after a successful resource request response.
@@ -17,6 +18,7 @@ class ResourceRequestPaginatedAction {
17
18
  #namespace;
18
19
  #originNamespace;
19
20
  #pagination;
21
+ #mapper;
20
22
  #jobRegistry;
21
23
  #namespaceMap;
22
24
 
@@ -28,6 +30,10 @@ class ResourceRequestPaginatedAction {
28
30
  * @param {string} [attributes.originNamespace='default'] The namespace of the resource that owns
29
31
  * this paginated action. Threaded in at construction time, not read from YAML.
30
32
  * @param {Array<object>} attributes.pagination Pagination config list.
33
+ * @param {object} [attributes.parameters={}] Key-value map where keys are destination
34
+ * variable names and values are path expressions (e.g. `parsedBody.id`, `headers['page']`),
35
+ * resolved against the same response used to compute `pages` and merged into each page's
36
+ * parameters (overriding same-named inherited parameters, but always losing to `page_key`).
31
37
  * @param {object} [attributes.jobRegistry=JobRegistry] The job registry to enqueue jobs to.
32
38
  * @param {object} [attributes.namespaceMap=NamespaceMap] The namespace map used to look up resources.
33
39
  * @throws {MissingActionResource} If resource is absent or falsy.
@@ -37,6 +43,7 @@ class ResourceRequestPaginatedAction {
37
43
  namespace = null,
38
44
  originNamespace = 'default',
39
45
  pagination,
46
+ parameters = {},
40
47
  jobRegistry = DefaultJobRegistry,
41
48
  namespaceMap = DefaultNamespaceMap,
42
49
  }) {
@@ -45,6 +52,7 @@ class ResourceRequestPaginatedAction {
45
52
  this.#namespace = namespace;
46
53
  this.#originNamespace = originNamespace;
47
54
  this.#pagination = PaginationConfig.fromList(pagination);
55
+ this.#mapper = new ParametersMapper(parameters);
48
56
  this.#jobRegistry = jobRegistry;
49
57
  this.#namespaceMap = namespaceMap;
50
58
  }
@@ -86,10 +94,17 @@ class ResourceRequestPaginatedAction {
86
94
  const count = this.#pagination.resolvePages(responseWrapper);
87
95
  const pages = this.#pagination.pageNumbers(count);
88
96
  const resource = this.#namespaceMap.getResource(this.#originNamespace, this.#resource, this.#namespace);
97
+ const mappedParameters = this.#mapper.map(responseWrapper);
89
98
 
90
99
  for (const page of pages) {
91
- const pageParameters = { ...parameters, [this.#pagination.pageKey]: page };
100
+ const pageParameters = {
101
+ ...parameters,
102
+ ...mappedParameters,
103
+ [this.#pagination.pageKey]: page,
104
+ };
92
105
  for (const resourceRequest of resource.resourceRequests) {
106
+ if (resourceRequest.disabled) continue;
107
+
93
108
  this.#jobRegistry.enqueue('ResourceRequestJob', { resourceRequest, parameters: pageParameters });
94
109
  }
95
110
  }
@@ -2,10 +2,10 @@ import { NamedRegistry } from './NamedRegistry.js';
2
2
  import { ClientNotFound } from '../exceptions/registry/ClientNotFound.js';
3
3
 
4
4
  /**
5
- * ClientRegistry manages client retrieval logic and exposes a static singleton facade.
5
+ * ClientRegistry manages client retrieval logic.
6
6
  *
7
- * Call `ClientRegistry.build(clients)` once during application bootstrap.
8
- * Use `ClientRegistry.reset()` in tests to restore a clean state between examples.
7
+ * A plain `NamedRegistry` subclass, used as a per-namespace instance inside
8
+ * `Namespace`. Resolution across namespaces is done via `NamespaceMap`.
9
9
  *
10
10
  * @example
11
11
  * const clientRegistry = new ClientRegistry({
@@ -40,62 +40,6 @@ class ClientRegistry extends NamedRegistry {
40
40
  */
41
41
  static notFoundException = ClientNotFound;
42
42
 
43
- static #instance = null;
44
-
45
- /**
46
- * Creates and stores the singleton instance.
47
- * @param {object} clients - An object mapping client names to Client instances.
48
- * @returns {ClientRegistry} The created instance.
49
- * @throws {Error} If `build()` has already been called without a preceding `reset()`.
50
- */
51
- static build(clients) {
52
- if (ClientRegistry.#instance) {
53
- throw new Error('ClientRegistry.build() has already been called. Call reset() first.');
54
- }
55
- ClientRegistry.#instance = new ClientRegistry(clients);
56
- return ClientRegistry.#instance;
57
- }
58
-
59
- /**
60
- * Destroys the singleton instance. Intended for test teardown.
61
- * @returns {void}
62
- */
63
- static reset() {
64
- ClientRegistry.#instance = null;
65
- }
66
-
67
- /**
68
- * Retrieves a client by name from the singleton instance.
69
- * @param {string} [name] - The name of the client to retrieve.
70
- * @returns {Client} The requested client instance.
71
- * @throws {ClientNotFound} If the client with the specified name does not exist.
72
- * @throws {Error} If `build()` has not been called.
73
- */
74
- static getClient(name) {
75
- return ClientRegistry.#getInstance().getClient(name);
76
- }
77
-
78
- /**
79
- * Returns all registered client instances from the singleton.
80
- * @returns {Client[]} Array of all registered Client instances.
81
- * @throws {Error} If `build()` has not been called.
82
- */
83
- static all() {
84
- return Object.values(ClientRegistry.#getInstance().items);
85
- }
86
-
87
- /**
88
- * Returns the singleton instance, throwing if not yet built.
89
- * @returns {ClientRegistry} The singleton instance.
90
- * @throws {Error} If `build()` has not been called.
91
- */
92
- static #getInstance() {
93
- if (!ClientRegistry.#instance) {
94
- throw new Error('ClientRegistry has not been built. Call ClientRegistry.build() first.');
95
- }
96
- return ClientRegistry.#instance;
97
- }
98
-
99
43
  /**
100
44
  * Retrieves a client by name or the default client if no name is provided.
101
45
  *
@@ -22,7 +22,18 @@ class NamedRegistry {
22
22
  * @param {object} items An object mapping item names to their corresponding instances.
23
23
  */
24
24
  constructor(items) {
25
+ this.replaceItems(items);
26
+ }
27
+
28
+ /**
29
+ * Replaces the registry's items, invalidating any memoized {@link #size} so it
30
+ * reflects the new item count on the next call.
31
+ * @param {object} items An object mapping item names to their corresponding instances.
32
+ * @returns {void}
33
+ */
34
+ replaceItems(items) {
25
35
  this.items = items;
36
+ this.#size = undefined;
26
37
  }
27
38
 
28
39
  /**
@@ -2,6 +2,7 @@ import { NamedRegistry } from './NamedRegistry.js';
2
2
  import { ClientNotFound } from '../exceptions/registry/ClientNotFound.js';
3
3
  import { NamespaceNotFound } from '../exceptions/registry/NamespaceNotFound.js';
4
4
  import { ResourceNotFound } from '../exceptions/registry/ResourceNotFound.js';
5
+ import { NamespaceMapBuilder } from '../services/NamespaceMapBuilder.js';
5
6
 
6
7
  const DEFAULT_NAMESPACE = 'default';
7
8
 
@@ -10,8 +11,12 @@ const DEFAULT_NAMESPACE = 'default';
10
11
  *
11
12
  * Implements a static singleton facade: call `NamespaceMap.build(namespaces)` once
12
13
  * during application bootstrap, then use static delegation methods (`getResource`,
13
- * `getClient`) to access it. Use `NamespaceMap.reset()` in tests to restore a clean
14
- * state between examples.
14
+ * `getClient`, `getNamespace`, `include`) to access it. Use `NamespaceMap.reset()` in
15
+ * tests to restore a clean state between examples.
16
+ *
17
+ * `include(files)` (instance and static) reuses `NamespaceMapBuilder`'s merge/validation
18
+ * logic to add or update a namespace's resources/clients into the running map, after
19
+ * boot, with the same fail-fast guarantees boot-time loading already has.
15
20
  *
16
21
  * Resolution rules:
17
22
  * - When an explicit target namespace is given and it (or the item within it) cannot
@@ -79,6 +84,31 @@ class NamespaceMap extends NamedRegistry {
79
84
  return NamespaceMap.#getInstance().getClient(originNamespace, name, namespace);
80
85
  }
81
86
 
87
+ /**
88
+ * Returns a namespace, by name, from the singleton instance.
89
+ * @param {string} name The namespace name.
90
+ * @returns {Namespace} The resolved namespace.
91
+ * @throws {NamespaceNotFound} When the namespace cannot be found.
92
+ * @throws {Error} If `build()` has not been called.
93
+ */
94
+ static getNamespace(name) {
95
+ return NamespaceMap.#getInstance().getItem(name);
96
+ }
97
+
98
+ /**
99
+ * Merges the given files' resources/clients into the singleton instance, reusing
100
+ * `NamespaceMapBuilder`'s merge and cross-reference validation logic.
101
+ * @param {Array<{namespace: string, resources: object, clients: object, filePath: string}>} files
102
+ * The flat list of files (see `ConfigIncluder`).
103
+ * @returns {NamespaceMap} The singleton instance.
104
+ * @throws {NamespaceNotFound|ResourceNotFound|ClientNotFound} When a resource/client
105
+ * reference cannot be resolved.
106
+ * @throws {Error} If `build()` has not been called.
107
+ */
108
+ static include(files) {
109
+ return NamespaceMap.#getInstance().include(files);
110
+ }
111
+
82
112
  /**
83
113
  * Returns the singleton instance, throwing if not yet built.
84
114
  * @returns {NamespaceMap} The singleton instance.
@@ -129,6 +159,22 @@ class NamespaceMap extends NamedRegistry {
129
159
  });
130
160
  }
131
161
 
162
+ /**
163
+ * Merges the given files' resources/clients into this namespace map, creating
164
+ * new namespaces and/or extending or replacing items in already-existing ones,
165
+ * reusing the same merge/validation logic used at boot.
166
+ * @param {Array<{namespace: string, resources: object, clients: object, filePath: string}>} files
167
+ * The flat list of files (see `ConfigIncluder`).
168
+ * @returns {NamespaceMap} this, for chaining.
169
+ * @throws {NamespaceNotFound|ResourceNotFound|ClientNotFound} When a resource/client
170
+ * reference cannot be resolved.
171
+ */
172
+ include(files) {
173
+ const namespaces = NamespaceMapBuilder.build(files, this.items);
174
+ this.replaceItems(namespaces);
175
+ return this;
176
+ }
177
+
132
178
  /**
133
179
  * Resolves an item (resource or client) using the namespace resolution rules.
134
180
  * @param {string} originNamespace The namespace of the requester.
@@ -4,10 +4,8 @@ import { ResourceNotFound } from '../exceptions/registry/ResourceNotFound.js';
4
4
  /**
5
5
  * Registry of named Resource instances.
6
6
  *
7
- * Implements a static singleton facade: call `ResourceRegistry.build(items)` once
8
- * during application bootstrap, then use static delegation methods (`getItem`,
9
- * `filter`, `size`) to access the registry. Use `ResourceRegistry.reset()` in
10
- * tests to restore a clean state between examples.
7
+ * A plain `NamedRegistry` subclass, used as a per-namespace instance inside
8
+ * `Namespace`. Resolution across namespaces is done via `NamespaceMap`.
11
9
  * @author darthjee
12
10
  * @augments NamedRegistry
13
11
  */
@@ -20,82 +18,6 @@ class ResourceRegistry extends NamedRegistry {
20
18
  * @see NamedRegistry#notFoundException
21
19
  */
22
20
  static notFoundException = ResourceNotFound;
23
-
24
- static #instance = null;
25
-
26
- /**
27
- * Creates and stores the singleton instance.
28
- * @param {object} items - An object mapping resource names to Resource instances.
29
- * @returns {ResourceRegistry} The created instance.
30
- * @throws {Error} If `build()` has already been called without a preceding `reset()`.
31
- */
32
- static build(items) {
33
- if (ResourceRegistry.#instance) {
34
- throw new Error('ResourceRegistry.build() has already been called. Call reset() first.');
35
- }
36
- ResourceRegistry.#instance = new ResourceRegistry(items);
37
- return ResourceRegistry.#instance;
38
- }
39
-
40
- /**
41
- * Destroys the singleton instance. Intended for test teardown.
42
- * @returns {void}
43
- */
44
- static reset() {
45
- ResourceRegistry.#instance = null;
46
- }
47
-
48
- /**
49
- * Retrieves a resource by name from the singleton instance.
50
- * @param {string} name - The name of the resource to retrieve.
51
- * @returns {*} The resource associated with the given name.
52
- * @throws {ResourceNotFound} If the resource with the specified name does not exist.
53
- * @throws {Error} If `build()` has not been called.
54
- */
55
- static getItem(name) {
56
- return ResourceRegistry.#getInstance().getItem(name);
57
- }
58
-
59
- /**
60
- * Checks whether a resource with the given name exists in the singleton instance.
61
- * @param {string} name - The name of the resource to check.
62
- * @returns {boolean} True if a resource with the given name exists.
63
- * @throws {Error} If `build()` has not been called.
64
- */
65
- static has(name) {
66
- return ResourceRegistry.#getInstance().has(name);
67
- }
68
-
69
- /**
70
- * Filters the resources in the singleton instance based on a predicate function.
71
- * @param {function} predicate - The predicate function to test each resource.
72
- * @returns {Array} An array of resources that match the predicate.
73
- * @throws {Error} If `build()` has not been called.
74
- */
75
- static filter(predicate) {
76
- return ResourceRegistry.#getInstance().filter(predicate);
77
- }
78
-
79
- /**
80
- * Returns the number of resources in the singleton instance.
81
- * @returns {number} The number of resources in the registry.
82
- * @throws {Error} If `build()` has not been called.
83
- */
84
- static size() {
85
- return ResourceRegistry.#getInstance().size();
86
- }
87
-
88
- /**
89
- * Returns the singleton instance, throwing if not yet built.
90
- * @returns {ResourceRegistry} The singleton instance.
91
- * @throws {Error} If `build()` has not been called.
92
- */
93
- static #getInstance() {
94
- if (!ResourceRegistry.#instance) {
95
- throw new Error('ResourceRegistry has not been built. Call ResourceRegistry.build() first.');
96
- }
97
- return ResourceRegistry.#instance;
98
- }
99
21
  }
100
22
 
101
- export { ResourceRegistry };
23
+ export { ResourceRegistry };
@@ -55,6 +55,25 @@ class RouteRegister {
55
55
  });
56
56
  }
57
57
 
58
+ /**
59
+ * Registers a POST route on the router.
60
+ * Catches ForbiddenError → 403, NotFoundError → 404, and any other error → 500.
61
+ * @param {object} params - Options for registering a route.
62
+ * @param {string} params.route - The route path (e.g. '/api/config').
63
+ * @param {object} params.handler - The handler whose handle method is called.
64
+ * @returns {void}
65
+ */
66
+ registerPost({ route, handler }) {
67
+ this.#router.post(route, async (req, res) => {
68
+ try {
69
+ await handler.handle(req, res);
70
+ Logger.debug(`${req.method} ${req.path} ${res.statusCode}`);
71
+ } catch (e) {
72
+ this.#handleError(e, req, res);
73
+ }
74
+ });
75
+ }
76
+
58
77
  /**
59
78
  * Maps a caught exception to an HTTP error response and logs the access entry.
60
79
  * @param {Error} e - The caught exception.
@@ -3,6 +3,9 @@ import { fileURLToPath } from 'url';
3
3
  import express from 'express';
4
4
  import { AssetsHandler } from './handlers/AssetsHandler.js';
5
5
  import { HandlerConfig } from '../common/server/HandlerConfig.js';
6
+ import { ApiConfigHandler } from './handlers/api/ApiConfigHandler.js';
7
+ import { ApiEngineStartHandler } from './handlers/api/ApiEngineStartHandler.js';
8
+ import { ApiEngineStopHandler } from './handlers/api/ApiEngineStopHandler.js';
6
9
  import { EngineContinueHandler } from './handlers/engine/EngineContinueHandler.js';
7
10
  import { EnginePauseHandler } from './handlers/engine/EnginePauseHandler.js';
8
11
  import { EngineRestartHandler } from './handlers/engine/EngineRestartHandler.js';
@@ -77,6 +80,12 @@ class Router {
77
80
  '/engine/shutdown': new HandlerConfig(EngineShutdownHandler),
78
81
  };
79
82
 
83
+ const POST_ROUTES = {
84
+ '/api/config': new HandlerConfig(ApiConfigHandler, this.#webConfig.apiToken),
85
+ '/api/engine/start': new HandlerConfig(ApiEngineStartHandler, this.#webConfig.apiToken),
86
+ '/api/engine/stop': new HandlerConfig(ApiEngineStopHandler, this.#webConfig.apiToken),
87
+ };
88
+
80
89
  Object.entries(GET_ROUTES).forEach(([route, handler]) => {
81
90
  register.register({ route, handler });
82
91
  });
@@ -85,6 +94,10 @@ class Router {
85
94
  register.registerPatch({ route, handler });
86
95
  });
87
96
 
97
+ Object.entries(POST_ROUTES).forEach(([route, handler]) => {
98
+ register.registerPost({ route, handler });
99
+ });
100
+
88
101
  router.use(express.static(staticDir));
89
102
 
90
103
  router.use((_req, res) => {
@@ -0,0 +1,90 @@
1
+ import { RequestHandler } from '../common/server/RequestHandler.js';
2
+ import { ForbiddenError } from '../exceptions/http/ForbiddenError.js';
3
+
4
+ /**
5
+ * Base class for token-secured request handlers (the `/api/*` namespace).
6
+ *
7
+ * Concrete subclasses implement {@link SecuredRequestHandler#process} instead of
8
+ * `handle()`; `handle()` itself always checks the request's bearer token against
9
+ * the configured token first, throwing `ForbiddenError` on any mismatch (including
10
+ * when no token is configured at all, which rejects every request by design).
11
+ * @author darthjee
12
+ */
13
+ class SecuredRequestHandler extends RequestHandler {
14
+ #request;
15
+ #response;
16
+ #token;
17
+
18
+ /**
19
+ * @param {object} request - The Express request object.
20
+ * @param {object} response - The Express response object.
21
+ * @param {string|null} token - The configured token to check the request against.
22
+ */
23
+ constructor(request, response, token) {
24
+ super();
25
+ this.#request = request;
26
+ this.#response = response;
27
+ this.#token = token;
28
+ }
29
+
30
+ /**
31
+ * Checks the bearer token, then delegates to {@link SecuredRequestHandler#process}.
32
+ * @returns {Promise<void>}
33
+ * @throws {ForbiddenError} When the provided token is missing/invalid, or no token is configured.
34
+ */
35
+ async handle() {
36
+ this.#authorize();
37
+ return this.process();
38
+ }
39
+
40
+ /**
41
+ * Template method: concrete subclasses implement the actual request handling here.
42
+ * @returns {void|Promise<void>} Nothing, or a promise resolving once handling completes.
43
+ */
44
+ process() {}
45
+
46
+ /**
47
+ * The Express request object.
48
+ * @returns {object} The request.
49
+ */
50
+ get request() {
51
+ return this.#request;
52
+ }
53
+
54
+ /**
55
+ * The Express response object.
56
+ * @returns {object} The response.
57
+ */
58
+ get response() {
59
+ return this.#response;
60
+ }
61
+
62
+ /**
63
+ * Validates the request's bearer token against the configured token.
64
+ * @returns {void}
65
+ * @throws {ForbiddenError} When the provided token is missing/invalid, or no token is configured.
66
+ * @private
67
+ */
68
+ #authorize() {
69
+ if (!this.#token || this.#bearerToken() !== this.#token) {
70
+ throw new ForbiddenError();
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Extracts the bearer token from the request's `Authorization` header.
76
+ * @returns {string|null} The extracted token, or null when absent/malformed.
77
+ * @private
78
+ */
79
+ #bearerToken() {
80
+ const header = this.#request?.headers?.authorization;
81
+ if (!header) return null;
82
+
83
+ const [scheme, token] = header.split(' ');
84
+ if (scheme !== 'Bearer' || !token) return null;
85
+
86
+ return token;
87
+ }
88
+ }
89
+
90
+ export { SecuredRequestHandler };
@@ -1,8 +1,10 @@
1
1
  import { RequestHandler } from '../../common/server/RequestHandler.js';
2
2
  import { Link } from '../../models/configs/Link.js';
3
- import { ClientRegistry } from '../../registry/ClientRegistry.js';
3
+ import { NamespaceMap } from '../../registry/NamespaceMap.js';
4
4
  import { LinksSerializer } from '../../serializers/LinksSerializer.js';
5
5
 
6
+ const DEFAULT_NAMESPACE = 'default';
7
+
6
8
  /**
7
9
  * Executes request-handling behaviour for GET /links.json.
8
10
  * @author darthjee
@@ -38,10 +40,13 @@ class LinksHandler extends RequestHandler {
38
40
  }
39
41
 
40
42
  /**
43
+ * Returns links derived from the `default` namespace's clients only, so a
44
+ * namespace added later (e.g. via a future config-addition endpoint) does not
45
+ * silently leak its clients into the public `/links.json` response.
41
46
  * @returns {Array<Link>}
42
47
  */
43
48
  #clientLinks() {
44
- return ClientRegistry.all().map((client) => (
49
+ return NamespaceMap.getNamespace(DEFAULT_NAMESPACE).clientRegistry.filter(() => true).map((client) => (
45
50
  new Link({ url: client.baseUrl, text: client.linkText ?? client.name })
46
51
  ));
47
52
  }
@@ -0,0 +1,102 @@
1
+ import { AppError } from '../../../exceptions/AppError.js';
2
+ import { NamespaceMap } from '../../../registry/NamespaceMap.js';
3
+ import { Application } from '../../../services/Application.js';
4
+ import { ResourceEnqueuer } from '../../../utils/ResourceEnqueuer.js';
5
+ import { SecuredRequestHandler } from '../../SecuredRequestHandler.js';
6
+
7
+ /**
8
+ * Executes request-handling behaviour for POST /api/config.
9
+ *
10
+ * Merges a single namespace's `resources`/`clients` into the running `NamespaceMap`
11
+ * (creating the namespace when it doesn't yet exist, replacing on name clash), reusing
12
+ * the same merge/validation machinery boot-time config loading already relies on.
13
+ * Only when the engine is currently running, the param-free resources among those
14
+ * just added/updated are additionally enqueued.
15
+ * @author darthjee
16
+ */
17
+ class ApiConfigHandler extends SecuredRequestHandler {
18
+ /**
19
+ * Validates the payload, merges it into the target namespace, optionally enqueues
20
+ * the newly added/updated param-free resources, then responds.
21
+ * @returns {void}
22
+ */
23
+ process() {
24
+ const body = this.request.body ?? {};
25
+ const { namespace } = body;
26
+
27
+ if (!this.#validNamespace(namespace)) {
28
+ this.#badRequest('"namespace" is required and must be a non-empty string.');
29
+ return;
30
+ }
31
+
32
+ const resources = body.resources ?? {};
33
+ const clients = body.clients ?? {};
34
+
35
+ if (!this.#isPlainObject(resources) || !this.#isPlainObject(clients)) {
36
+ this.#badRequest('"resources" and "clients" must be objects when present.');
37
+ return;
38
+ }
39
+
40
+ if (!this.#merge(namespace, resources, clients)) return;
41
+
42
+ if (Application.isRunning()) {
43
+ new ResourceEnqueuer(namespace).enqueue(Object.keys(resources));
44
+ }
45
+
46
+ this.response.json({ status: 'accepted' });
47
+ }
48
+
49
+ /**
50
+ * Merges the payload into the target namespace, responding with 400 when the
51
+ * merge raises a known config/registry validation error.
52
+ * @param {string} namespace - The target namespace name.
53
+ * @param {object} resources - The namespace's incoming resources.
54
+ * @param {object} clients - The namespace's incoming clients.
55
+ * @returns {boolean} True when the merge succeeded.
56
+ * @private
57
+ */
58
+ #merge(namespace, resources, clients) {
59
+ try {
60
+ NamespaceMap.include([{ namespace, resources, clients }]);
61
+ return true;
62
+ } catch (error) {
63
+ if (error instanceof AppError) {
64
+ this.#badRequest(error.message);
65
+ return false;
66
+ }
67
+ throw error;
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Validates that the given namespace is a non-empty string.
73
+ * @param {*} namespace - The candidate namespace value.
74
+ * @returns {boolean} True when valid.
75
+ * @private
76
+ */
77
+ #validNamespace(namespace) {
78
+ return typeof namespace === 'string' && namespace.trim().length > 0;
79
+ }
80
+
81
+ /**
82
+ * Validates that the given value is a plain (non-array, non-null) object.
83
+ * @param {*} value - The candidate value.
84
+ * @returns {boolean} True when it is a plain object.
85
+ * @private
86
+ */
87
+ #isPlainObject(value) {
88
+ return !!value && typeof value === 'object' && !Array.isArray(value);
89
+ }
90
+
91
+ /**
92
+ * Responds with a 400 error body.
93
+ * @param {string} message - The error message.
94
+ * @returns {void}
95
+ * @private
96
+ */
97
+ #badRequest(message) {
98
+ this.response.status(400).json({ error: message });
99
+ }
100
+ }
101
+
102
+ export { ApiConfigHandler };
@@ -0,0 +1,154 @@
1
+ import { ConflictError } from '../../../exceptions/http/ConflictError.js';
2
+ import { Application } from '../../../services/Application.js';
3
+ import { ResourceEnqueuer } from '../../../utils/ResourceEnqueuer.js';
4
+ import { SecuredRequestHandler } from '../../SecuredRequestHandler.js';
5
+
6
+ /**
7
+ * Executes request-handling behaviour for POST /api/engine/start.
8
+ *
9
+ * Mirrors `PATCH /engine/start`'s state logic (starts the engine if stopped, or
10
+ * enqueues additional jobs if already running; `ConflictError` otherwise), but
11
+ * resolves what to enqueue from `req.body.targets` — an array of
12
+ * `{ namespace, resources? }` entries, each scoped to its own namespace via the
13
+ * namespace-aware `ResourceEnqueuer` — falling back to today's top-level
14
+ * `resources` / default-namespace behavior when `targets` is omitted entirely.
15
+ * @author darthjee
16
+ */
17
+ class ApiEngineStartHandler extends SecuredRequestHandler {
18
+ /**
19
+ * Starts engine processing from a stopped state, or pushes resources into an
20
+ * already-running engine, scoped per namespace via `targets`.
21
+ * @returns {Promise<void>}
22
+ * @throws {ConflictError} When the engine is paused/pausing/stopping.
23
+ */
24
+ async process() {
25
+ const targets = this.#targets();
26
+
27
+ if (targets === false) {
28
+ this.#badRequest('"targets" must be an array of { namespace, resources? } objects.');
29
+ return;
30
+ }
31
+
32
+ if (Application.isStopped()) {
33
+ await this.#start(targets);
34
+ return;
35
+ }
36
+
37
+ if (Application.isRunning()) {
38
+ this.#enqueue(targets);
39
+ return;
40
+ }
41
+
42
+ throw new ConflictError();
43
+ }
44
+
45
+ /**
46
+ * Handles the stopped → running transition, enqueueing either the top-level
47
+ * `resources` (no `targets` given) or every named target's resources.
48
+ * @param {Array<object>|null} targets - Parsed `targets`, or null when omitted.
49
+ * @returns {Promise<void>}
50
+ * @private
51
+ */
52
+ async #start(targets) {
53
+ if (!targets) {
54
+ const result = await Application.start(this.#topLevelResources());
55
+ this.response.json({ status: 'running', ...result });
56
+ return;
57
+ }
58
+
59
+ await Application.start([], { enqueue: false });
60
+ this.response.json({ status: 'running', ...this.#aggregate(targets) });
61
+ }
62
+
63
+ /**
64
+ * Handles enqueueing additional jobs into an already-running engine.
65
+ * @param {Array<object>|null} targets - Parsed `targets`, or null when omitted.
66
+ * @returns {void}
67
+ * @private
68
+ */
69
+ #enqueue(targets) {
70
+ if (!targets) {
71
+ const result = Application.enqueueResources(this.#topLevelResources());
72
+ this.response.json({ status: 'running', ...result });
73
+ return;
74
+ }
75
+
76
+ this.response.json({ status: 'running', ...this.#aggregate(targets) });
77
+ }
78
+
79
+ /**
80
+ * Reads the top-level `resources` array, used when `targets` is omitted.
81
+ * @returns {Array<string>} The named resources, or an empty array.
82
+ * @private
83
+ */
84
+ #topLevelResources() {
85
+ return Array.isArray(this.request.body?.resources) ? this.request.body.resources : [];
86
+ }
87
+
88
+ /**
89
+ * Parses and validates `req.body.targets`.
90
+ * @returns {Array<object>|null|false} The parsed targets array, `null` when omitted,
91
+ * or `false` when present but malformed.
92
+ * @private
93
+ */
94
+ #targets() {
95
+ const { targets } = this.request.body ?? {};
96
+ if (targets === undefined) return null;
97
+ if (!this.#validTargets(targets)) return false;
98
+ return targets;
99
+ }
100
+
101
+ /**
102
+ * Validates every entry of the `targets` array.
103
+ * @param {*} targets - The candidate targets value.
104
+ * @returns {boolean} True when every entry is well-formed.
105
+ * @private
106
+ */
107
+ #validTargets(targets) {
108
+ return Array.isArray(targets) && targets.every((target) => this.#validTarget(target));
109
+ }
110
+
111
+ /**
112
+ * Validates a single `targets` entry.
113
+ * @param {*} target - The candidate target entry.
114
+ * @returns {boolean} True when the entry is well-formed.
115
+ * @private
116
+ */
117
+ #validTarget(target) {
118
+ if (!target || typeof target.namespace !== 'string' || !target.namespace.trim()) return false;
119
+ if (target.resources === undefined) return true;
120
+
121
+ return Array.isArray(target.resources) && target.resources.every((name) => typeof name === 'string');
122
+ }
123
+
124
+ /**
125
+ * Aggregates the per-target enqueue results into one flat `{ enqueued, skippedResources }`.
126
+ * @param {Array<{namespace: string, resources: Array<string>|undefined}>} targets - The targets to enqueue.
127
+ * @param {{enqueued: Array<string>, skippedResources: Array<object>}} [seed] - Initial accumulator.
128
+ * @returns {{enqueued: Array<string>, skippedResources: Array<object>}} The aggregated result.
129
+ * @private
130
+ */
131
+ #aggregate(targets, seed = { enqueued: [], skippedResources: [] }) {
132
+ return targets.reduce((acc, { namespace, resources }) => {
133
+ const enqueuer = new ResourceEnqueuer(namespace);
134
+ const result = resources === undefined ? enqueuer.enqueueAll() : enqueuer.enqueue(resources);
135
+
136
+ return {
137
+ enqueued: [...acc.enqueued, ...result.enqueued],
138
+ skippedResources: [...acc.skippedResources, ...result.skippedResources],
139
+ };
140
+ }, seed);
141
+ }
142
+
143
+ /**
144
+ * Responds with a 400 error body.
145
+ * @param {string} message - The error message.
146
+ * @returns {void}
147
+ * @private
148
+ */
149
+ #badRequest(message) {
150
+ this.response.status(400).json({ error: message });
151
+ }
152
+ }
153
+
154
+ export { ApiEngineStartHandler };
@@ -0,0 +1,20 @@
1
+ import { EngineStopService } from '../../../services/EngineStopService.js';
2
+ import { SecuredRequestHandler } from '../../SecuredRequestHandler.js';
3
+
4
+ /**
5
+ * Executes request-handling behaviour for POST /api/engine/stop.
6
+ * Identical to `PATCH /engine/stop` (no body), reusing the same shared logic.
7
+ * @author darthjee
8
+ */
9
+ class ApiEngineStopHandler extends SecuredRequestHandler {
10
+ /**
11
+ * Initiates engine stop. Responds immediately with the transitional status.
12
+ * @returns {void}
13
+ * @throws {ConflictError} When the engine is not currently running.
14
+ */
15
+ process() {
16
+ this.response.json(EngineStopService.stop());
17
+ }
18
+ }
19
+
20
+ export { ApiEngineStopHandler };
@@ -1,6 +1,5 @@
1
1
  import { RequestHandler } from '../../../common/server/RequestHandler.js';
2
- import { ConflictError } from '../../../exceptions/http/ConflictError.js';
3
- import { Application } from '../../../services/Application.js';
2
+ import { EngineStopService } from '../../../services/EngineStopService.js';
4
3
 
5
4
  /**
6
5
  * Executes request-handling behaviour for PATCH /engine/stop.
@@ -23,9 +22,7 @@ class EngineStopHandler extends RequestHandler {
23
22
  * @returns {Promise<void>}
24
23
  */
25
24
  async handle() {
26
- if (!Application.isRunning()) throw new ConflictError();
27
- Application.stop();
28
- this.#response.json({ status: 'stopping' });
25
+ this.#response.json(EngineStopService.stop());
29
26
  }
30
27
  }
31
28
 
@@ -156,10 +156,11 @@ class Application {
156
156
  /**
157
157
  * Starts processing from a stopped state.
158
158
  * @param {Array<string>} [names] - Resource names to enqueue; omit/empty for the default set.
159
+ * @param {object} [options] - Extra options, forwarded to `ApplicationInstance#start`.
159
160
  * @returns {Promise<{enqueued: Array<string>, skippedResources: Array<object>}|undefined>} The enqueue result, or undefined when not stopped.
160
161
  */
161
- static async start(names) {
162
- return Application.#getInstance().start(names);
162
+ static async start(names, options) {
163
+ return Application.#getInstance().start(names, options);
163
164
  }
164
165
 
165
166
  /**
@@ -228,15 +228,19 @@ class ApplicationInstance {
228
228
  * No new engine is created; the existing loop continues.
229
229
  * Only valid when status is 'stopped'.
230
230
  * @param {Array<string>} [names=[]] - Resource names to enqueue; omit/empty for the default set.
231
+ * @param {object} [options={}] - Extra options.
232
+ * @param {boolean} [options.enqueue=true] - When false, only transitions the engine to
233
+ * `running` without enqueueing anything — used by callers (namespace-scoped `/api`
234
+ * flows) that manage their own enqueueing afterwards.
231
235
  * @returns {Promise<{enqueued: Array<string>, skippedResources: Array<object>}|undefined>} The enqueue result, or undefined when not stopped.
232
236
  */
233
- async start(names = []) {
237
+ async start(names = [], { enqueue = true } = {}) {
234
238
  if (this.#engineStatus !== 'stopped') return undefined;
235
239
  this.engine.resume();
236
- const result = this.enqueueResources(names);
237
240
  this.#engineStatus = 'running';
238
241
  EngineEvents.emit('start');
239
- return result;
242
+ if (!enqueue) return { enqueued: [], skippedResources: [] };
243
+ return this.enqueueResources(names);
240
244
  }
241
245
 
242
246
  /**
@@ -0,0 +1,22 @@
1
+ import { Application } from './Application.js';
2
+ import { ConflictError } from '../exceptions/http/ConflictError.js';
3
+
4
+ /**
5
+ * Shared engine-stop logic used by both `PATCH /engine/stop` and
6
+ * `POST /api/engine/stop`, which are otherwise identical.
7
+ * @author darthjee
8
+ */
9
+ class EngineStopService {
10
+ /**
11
+ * Initiates engine stop.
12
+ * @returns {{status: string}} The transitional status response body.
13
+ * @throws {ConflictError} When the engine is not currently running.
14
+ */
15
+ static stop() {
16
+ if (!Application.isRunning()) throw new ConflictError();
17
+ Application.stop();
18
+ return { status: 'stopping' };
19
+ }
20
+ }
21
+
22
+ export { EngineStopService };
@@ -1,5 +1,4 @@
1
1
  import { ConfigParser } from './ConfigParser.js';
2
- import { DuplicateNamespaceItem } from '../exceptions/registry/DuplicateNamespaceItem.js';
3
2
  import { Namespace } from '../registry/Namespace.js';
4
3
  import { NamespaceMap } from '../registry/NamespaceMap.js';
5
4
 
@@ -9,37 +8,46 @@ import { NamespaceMap } from '../registry/NamespaceMap.js';
9
8
  * eagerly validates every resource/client reference collected while parsing (actions,
10
9
  * paginated_actions, and resource-level client references), so unresolvable
11
10
  * references fail fast at load time rather than at request time.
11
+ *
12
+ * When an `existingNamespaces` map is given, its namespaces' current resources/clients
13
+ * are merged with the new `files`, so this same builder serves both boot-time loading
14
+ * (no existing namespaces) and later additions into an already-running `NamespaceMap`.
12
15
  * @author darthjee
13
16
  */
14
17
  class NamespaceMapBuilder {
15
18
  #files;
19
+ #existingNamespaces;
16
20
  #strict;
17
21
 
18
22
  /**
19
23
  * @param {Array<{namespace: string, resources: object, clients: object, filePath: string}>} files
20
24
  * The flat list of files returned by `ConfigIncluder`.
25
+ * @param {Record<string, Namespace>} [existingNamespaces={}] An already-built namespace
26
+ * map to merge `files` into, replacing on name collision.
21
27
  */
22
- constructor(files) {
28
+ constructor(files, existingNamespaces = {}) {
23
29
  this.#files = files;
30
+ this.#existingNamespaces = existingNamespaces;
24
31
  this.#strict = files.length === 1;
25
32
  }
26
33
 
27
34
  /**
28
- * Builds a namespace map from the given list of files.
35
+ * Builds a namespace map from the given list of files, optionally merged into an
36
+ * already-built namespace map.
29
37
  * @param {Array<{namespace: string, resources: object, clients: object, filePath: string}>} files
30
38
  * The flat list of files returned by `ConfigIncluder`.
39
+ * @param {Record<string, Namespace>} [existingNamespaces={}] An already-built namespace
40
+ * map to merge `files` into, replacing on name collision.
31
41
  * @returns {Record<string, Namespace>} A map of namespace name to Namespace instance.
32
42
  */
33
- static build(files) {
34
- return new NamespaceMapBuilder(files).build();
43
+ static build(files, existingNamespaces = {}) {
44
+ return new NamespaceMapBuilder(files, existingNamespaces).build();
35
45
  }
36
46
 
37
47
  /**
38
48
  * Groups files by namespace, builds one Namespace per group, and eagerly
39
49
  * validates every cross-reference before returning.
40
50
  * @returns {Record<string, Namespace>} A map of namespace name to Namespace instance.
41
- * @throws {DuplicateNamespaceItem} When two files sharing a namespace declare the
42
- * same resource or client name.
43
51
  * @throws {NamespaceNotFound|ResourceNotFound|ClientNotFound} When a resource/client
44
52
  * reference cannot be resolved.
45
53
  */
@@ -50,13 +58,14 @@ class NamespaceMapBuilder {
50
58
  }
51
59
 
52
60
  /**
53
- * Groups every file's parsed resources/clients by namespace name, raising on
54
- * duplicate names within a namespace group, then builds one Namespace per group.
61
+ * Groups every file's parsed resources/clients by namespace name (seeded from any
62
+ * already-existing namespace's current items, replacing on name collision), then
63
+ * builds one fresh Namespace per group.
55
64
  * @returns {Record<string, Namespace>} A map of namespace name to Namespace instance.
56
65
  * @private
57
66
  */
58
67
  #buildNamespaces() {
59
- const groups = {};
68
+ const groups = this.#seedGroups();
60
69
 
61
70
  this.#files.forEach((file) => {
62
71
  const parsed = ConfigParser.fromObject(
@@ -65,8 +74,8 @@ class NamespaceMapBuilder {
65
74
  );
66
75
 
67
76
  const group = groups[file.namespace] ??= { resources: {}, clients: {} };
68
- this.#mergeInto(group.resources, parsed.resources, file.namespace, 'resource');
69
- this.#mergeInto(group.clients, parsed.clients, file.namespace, 'client');
77
+ this.#mergeInto(group.resources, parsed.resources);
78
+ this.#mergeInto(group.clients, parsed.clients);
70
79
  });
71
80
 
72
81
  return Object.fromEntries(
@@ -76,6 +85,26 @@ class NamespaceMapBuilder {
76
85
  );
77
86
  }
78
87
 
88
+ /**
89
+ * Seeds the groups accumulator from each already-existing namespace's current
90
+ * resources/clients, so untouched namespaces are preserved and touched ones are
91
+ * merged into rather than replaced wholesale.
92
+ * @returns {Record<string, {resources: object, clients: object}>} The seeded groups accumulator.
93
+ * @private
94
+ */
95
+ #seedGroups() {
96
+ const groups = {};
97
+
98
+ Object.entries(this.#existingNamespaces).forEach(([name, namespace]) => {
99
+ groups[name] = {
100
+ resources: { ...namespace.resourceRegistry.items },
101
+ clients: { ...namespace.clientRegistry.items },
102
+ };
103
+ });
104
+
105
+ return groups;
106
+ }
107
+
79
108
  /**
80
109
  * Builds the plain config object handed to `ConfigParser`, omitting the
81
110
  * `resources`/`clients` keys entirely when the file did not declare them
@@ -93,21 +122,16 @@ class NamespaceMapBuilder {
93
122
  }
94
123
 
95
124
  /**
96
- * Merges a file's parsed items into the namespace group's accumulator, raising
97
- * when an item name is already present.
125
+ * Merges a file's parsed items into the namespace group's accumulator, replacing
126
+ * (rather than raising) when an item name is already present — the last item
127
+ * registered under a given name wins.
98
128
  * @param {object} target The namespace group's accumulator map.
99
129
  * @param {object} source The current file's parsed items.
100
- * @param {string} namespace The namespace name being merged into.
101
- * @param {string} itemType Either 'resource' or 'client' (used for the error message).
102
130
  * @returns {void}
103
- * @throws {DuplicateNamespaceItem} When an item name is already present in the group.
104
131
  * @private
105
132
  */
106
- #mergeInto(target, source, namespace, itemType) {
133
+ #mergeInto(target, source) {
107
134
  Object.entries(source).forEach(([name, item]) => {
108
- if (name in target) {
109
- throw new DuplicateNamespaceItem(name, { namespace, itemType });
110
- }
111
135
  target[name] = item;
112
136
  });
113
137
  }
@@ -1,13 +1,28 @@
1
+ import { ResourceRequestCollector } from './ResourceRequestCollector.js';
1
2
  import { JobRegistry } from '../background/JobRegistry.js';
2
- import { ResourceRegistry } from '../registry/ResourceRegistry.js';
3
+ import { NamespaceNotFound } from '../exceptions/registry/NamespaceNotFound.js';
4
+ import { ResourceNotFound } from '../exceptions/registry/ResourceNotFound.js';
5
+ import { NamespaceMap } from '../registry/NamespaceMap.js';
6
+
7
+ const DEFAULT_NAMESPACE = 'default';
3
8
 
4
9
  /**
5
- * Resolves resource names against the ResourceRegistry and enqueues the
6
- * ResourceRequestJobs for each, skipping (rather than partially enqueueing)
7
- * any resource that is unknown or has a request needing parameters.
10
+ * Resolves resource names against a given namespace (`default` unless otherwise
11
+ * specified) via `NamespaceMap` and enqueues the ResourceRequestJobs for each,
12
+ * skipping (rather than partially enqueueing) any resource that is unknown, disabled,
13
+ * or has a request needing parameters.
8
14
  * @author darthjee
9
15
  */
10
16
  class ResourceEnqueuer {
17
+ #namespace;
18
+
19
+ /**
20
+ * @param {string} [namespace='default'] - The namespace to resolve resources against.
21
+ */
22
+ constructor(namespace = DEFAULT_NAMESPACE) {
23
+ this.#namespace = namespace;
24
+ }
25
+
11
26
  /**
12
27
  * Enqueues the given resource names.
13
28
  * @param {Array<string>} names - Resource names to enqueue.
@@ -18,12 +33,18 @@ class ResourceEnqueuer {
18
33
  const skippedResources = [];
19
34
 
20
35
  names.forEach((name) => {
21
- if (!ResourceRegistry.has(name)) {
36
+ const resource = this.#findResource(name);
37
+
38
+ if (!resource) {
22
39
  skippedResources.push({ name, reason: 'not_found' });
23
40
  return;
24
41
  }
25
42
 
26
- const resource = ResourceRegistry.getItem(name);
43
+ if (resource.resourceRequests.some((request) => request.disabled)) {
44
+ skippedResources.push({ name, reason: 'disabled' });
45
+ return;
46
+ }
47
+
27
48
  if (resource.resourceRequests.some((request) => request.needsParams())) {
28
49
  skippedResources.push({ name, reason: 'needs_params' });
29
50
  return;
@@ -37,6 +58,60 @@ class ResourceEnqueuer {
37
58
 
38
59
  return { enqueued, skippedResources };
39
60
  }
61
+
62
+ /**
63
+ * Enqueues every parameter-free (and enabled) resource request declared within
64
+ * the target namespace. Mirrors the boot-time `ApplicationInstance#enqueueFirstJobs`
65
+ * strategy, scoped to an arbitrary namespace instead of the boot-time default.
66
+ * @returns {{enqueued: Array<string>, skippedResources: Array<object>}} Always
67
+ * `{ enqueued: [], skippedResources: [] }` — matching the existing bulk-enqueue
68
+ * convention of not tracking individual resource names.
69
+ */
70
+ enqueueAll() {
71
+ const namespace = this.#findNamespace();
72
+
73
+ if (namespace) {
74
+ new ResourceRequestCollector(namespace.resourceRegistry).requestsNeedingNoParams().forEach((resourceRequest) => {
75
+ JobRegistry.enqueue('ResourceRequestJob', { resourceRequest, parameters: {} });
76
+ });
77
+ }
78
+
79
+ return { enqueued: [], skippedResources: [] };
80
+ }
81
+
82
+ /**
83
+ * Looks up a resource, by name, in the target namespace, returning `null`
84
+ * instead of raising when the resource (or the namespace itself) cannot be found.
85
+ * @param {string} name - The resource name to look up.
86
+ * @returns {Resource|null} The resolved resource, or null if not found.
87
+ * @private
88
+ */
89
+ #findResource(name) {
90
+ const namespace = this.#findNamespace();
91
+ if (!namespace) return null;
92
+
93
+ try {
94
+ return namespace.resourceRegistry.getItem(name);
95
+ } catch (error) {
96
+ if (error instanceof ResourceNotFound) return null;
97
+ throw error;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Looks up the target namespace, returning `null` instead of raising when it
103
+ * cannot be found.
104
+ * @returns {Namespace|null} The resolved namespace, or null if not found.
105
+ * @private
106
+ */
107
+ #findNamespace() {
108
+ try {
109
+ return NamespaceMap.getNamespace(this.#namespace);
110
+ } catch (error) {
111
+ if (error instanceof NamespaceNotFound) return null;
112
+ throw error;
113
+ }
114
+ }
40
115
  }
41
116
 
42
117
  export { ResourceEnqueuer };
@@ -23,12 +23,12 @@ class ResourceRequestCollector {
23
23
 
24
24
  /**
25
25
  * Returns only the ResourceRequest instances that do not require parameter substitution,
26
- * i.e. those whose URL templates contain no {:placeholder} tokens.
26
+ * i.e. those whose URL templates contain no {:placeholder} tokens, and that are not disabled.
27
27
  * These are safe to enqueue at startup without any additional context.
28
- * @returns {Array<ResourceRequest>} Resource requests that need no parameters.
28
+ * @returns {Array<ResourceRequest>} Resource requests that need no parameters and are enabled.
29
29
  */
30
30
  requestsNeedingNoParams() {
31
- return this.allRequests().filter((request) => !request.needsParams());
31
+ return this.allRequests().filter((request) => !request.needsParams() && !request.disabled);
32
32
  }
33
33
  }
34
34
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "navi-hey",
3
3
  "type": "module",
4
- "version": "1.5.0",
4
+ "version": "1.5.1",
5
5
  "description": "Navi cache warmer CLI",
6
6
  "readme": "README.md",
7
7
  "main": "index.js",
@@ -1,23 +0,0 @@
1
- import { AppError } from '../AppError.js';
2
-
3
- /**
4
- * DuplicateNamespaceItem is thrown when two files contributing to the same
5
- * namespace declare a resource or client under the same name.
6
- * @author darthjee
7
- */
8
- class DuplicateNamespaceItem extends AppError {
9
- /**
10
- * @param {string} itemName - The duplicated resource/client name.
11
- * @param {object} attributes - Additional attributes describing the duplication.
12
- * @param {string} attributes.namespace - The namespace where the duplication happened.
13
- * @param {string} [attributes.itemType='Item'] - Either "resource" or "client".
14
- */
15
- constructor(itemName, { namespace, itemType = 'Item' } = {}) {
16
- super(`${itemType} "${itemName}" is already declared in namespace "${namespace}".`);
17
- this.itemName = itemName;
18
- this.namespace = namespace;
19
- this.itemType = itemType;
20
- }
21
- }
22
-
23
- export { DuplicateNamespaceItem };