webspresso 0.0.106 → 0.0.107

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 (49) hide show
  1. package/bin/webspresso.js +17 -7
  2. package/core/app.js +38 -6
  3. package/core/auth/index.js +4 -1
  4. package/core/auth/jwt.js +85 -13
  5. package/core/auth/magic-link.js +23 -5
  6. package/core/auth/manager.js +7 -1
  7. package/core/auth/redis-session.js +62 -25
  8. package/core/auth/session-manager.js +28 -2
  9. package/core/auth/sessions.js +182 -52
  10. package/core/console/eval.js +4 -1
  11. package/core/content/service.js +1 -0
  12. package/core/errors/domain.js +20 -2
  13. package/core/errors/http.js +1 -0
  14. package/core/http/hono-adapter.js +1 -1
  15. package/core/http/pipeline.js +36 -2
  16. package/core/index.js +12 -1
  17. package/core/mail/mailer.js +1 -1
  18. package/core/orm/eager-loader.js +81 -1
  19. package/core/orm/index.js +27 -13
  20. package/core/orm/json-fields.js +44 -13
  21. package/core/orm/model.js +12 -0
  22. package/core/orm/query-builder.js +33 -15
  23. package/core/orm/repository.js +59 -12
  24. package/core/orm/scopes.js +54 -4
  25. package/core/services/index.js +9 -0
  26. package/core/shutdown/shutdown-manager.js +57 -38
  27. package/core/studio/inspector.js +9 -1
  28. package/core/studio/server.js +24 -8
  29. package/core/utils/string.js +77 -16
  30. package/core/validation/index.js +18 -0
  31. package/index.d.ts +172 -8
  32. package/index.js +4 -0
  33. package/package.json +18 -8
  34. package/plugins/admin-panel/client/parts/07-model-list.js +5 -2
  35. package/plugins/admin-panel/index.js +24 -11
  36. package/plugins/admin-panel/modules/user-management.js +3 -2
  37. package/plugins/csrf/index.js +2 -1
  38. package/plugins/dashboard/index.js +27 -7
  39. package/src/app-context.js +9 -1
  40. package/src/file-router.js +12 -3
  41. package/src/plugin-manager.js +273 -48
  42. package/src/server.js +26 -33
  43. package/src/services/discovery.js +9 -1
  44. package/src/services/executor.js +271 -58
  45. package/src/services/index.js +52 -3
  46. package/src/services/loader.js +120 -0
  47. package/src/services/memoize.js +223 -49
  48. package/src/services/registry.js +492 -94
  49. package/src/services/validator.js +164 -13
@@ -1,14 +1,23 @@
1
1
  /**
2
2
  * Webspresso Service Registry
3
- * Central registry holding discovered and programmatically registered services
3
+ * Central registry holding discovered and programmatically registered services.
4
+ * Supports CommonJS and ESM native dynamic import, on-demand lazy loading,
5
+ * and dev-mode hot reloading.
4
6
  * @module src/services/registry
5
7
  */
6
8
 
9
+ 'use strict';
10
+
7
11
  const path = require('path');
8
12
  const { ConfigurationError, WebspressoError } = require('../../core/errors');
9
13
  const { discoverServices } = require('./discovery');
10
14
  const { executeService } = require('./executor');
11
15
  const { memoize } = require('./memoize');
16
+ const {
17
+ loadModuleSync,
18
+ loadModuleAsync,
19
+ extractModuleExport,
20
+ } = require('./loader');
12
21
 
13
22
  class ServiceRegistry {
14
23
  /**
@@ -16,6 +25,9 @@ class ServiceRegistry {
16
25
  * @param {string} [options.servicesDir] - Path to services directory
17
26
  * @param {boolean} [options.isDev=false] - Whether in development mode
18
27
  * @param {Object} [options.logger] - Logger instance
28
+ * @param {Object} [options.timeouts] - Global timeouts configuration
29
+ * @param {number|string} [options.timeout] - Default execution timeout
30
+ * @param {boolean} [options.lazy=false] - Whether to defer module loading until invocation
19
31
  */
20
32
  constructor(options = {}) {
21
33
  this.servicesDir = options.servicesDir ? path.resolve(options.servicesDir) : null;
@@ -23,16 +35,124 @@ class ServiceRegistry {
23
35
  this.logger = options.logger || null;
24
36
  this.timeouts = options.timeouts || null;
25
37
  this.timeout = options.timeout !== undefined ? options.timeout : null;
38
+ this.lazy = Boolean(options.lazy);
39
+ this.cacheProvider = options.cacheProvider || (options.cache && typeof options.cache === 'object' && options.cache.provider ? options.cache.provider : null);
26
40
 
27
- /** @type {Map<string, Object>} */
41
+ /** @type {Map<string, Object>} Materialized service definitions */
28
42
  this.services = new Map();
29
43
 
30
- /** @type {Map<string, string>} */
44
+ /** @type {Map<string, string>} Aliases mapping to primary service names */
31
45
  this.aliases = new Map();
46
+
47
+ /** @type {Map<string, Object>} Deferred lazy service registrations */
48
+ this.lazyServices = new Map();
49
+
50
+ /** @type {Function[]} Global middlewares executed in onion order */
51
+ this.middlewares = [];
52
+ if (Array.isArray(options.middlewares)) {
53
+ this.middlewares.push(...options.middlewares);
54
+ } else if (typeof options.middleware === 'function') {
55
+ this.middlewares.push(options.middleware);
56
+ }
57
+
58
+ /** @type {Function[]} Global before-hooks */
59
+ this.beforeHooks = [];
60
+ if (Array.isArray(options.before)) {
61
+ this.beforeHooks.push(...options.before);
62
+ } else if (typeof options.before === 'function') {
63
+ this.beforeHooks.push(options.before);
64
+ }
65
+
66
+ /** @type {Function[]} Global after-hooks */
67
+ this.afterHooks = [];
68
+ if (Array.isArray(options.after)) {
69
+ this.afterHooks.push(...options.after);
70
+ } else if (typeof options.after === 'function') {
71
+ this.afterHooks.push(options.after);
72
+ }
73
+
74
+ /** @type {Function[]} Global onError-hooks */
75
+ this.onErrorHooks = [];
76
+ if (Array.isArray(options.onError)) {
77
+ this.onErrorHooks.push(...options.onError);
78
+ } else if (typeof options.onError === 'function') {
79
+ this.onErrorHooks.push(options.onError);
80
+ }
81
+
82
+ /** @type {Object|null} Optional event dispatcher */
83
+ this.events = options.events || null;
84
+ }
85
+
86
+ /**
87
+ * Normalize raw module export or definition into a standardized ServiceDefinition
88
+ * @param {string} name - Service name
89
+ * @param {any} raw - Raw module or object
90
+ * @param {string|null} [filePath=null] - Origin file path if discovered from disk
91
+ * @returns {Object} Standardized service definition
92
+ * @private
93
+ */
94
+ _normalizeDefinition(name, raw, filePath = null) {
95
+ const extracted = extractModuleExport(raw);
96
+ const definition = typeof extracted === 'function' ? { handler: extracted } : extracted;
97
+
98
+ if (!definition || typeof definition !== 'object') {
99
+ const target = filePath ? `Service file '${filePath}'` : `Service '${name}'`;
100
+ throw new ConfigurationError(`${target} must export an object or handler function`);
101
+ }
102
+
103
+ if (typeof definition.handler !== 'function') {
104
+ const target = filePath ? `Service '${name}' in '${filePath}'` : `Service '${name}'`;
105
+ throw new ConfigurationError(`${target} must provide a handler function`);
106
+ }
107
+
108
+ let handler = definition.handler;
109
+ let memoizeFn = null;
110
+
111
+ if (definition.cache) {
112
+ const memoizeOpts = typeof definition.cache === 'object' && definition.cache !== null
113
+ ? { ...definition.cache }
114
+ : { ttl: definition.cache };
115
+ if (!memoizeOpts.provider && this.cacheProvider) {
116
+ memoizeOpts.provider = this.cacheProvider;
117
+ }
118
+ memoizeFn = memoize(definition.handler, memoizeOpts);
119
+ handler = memoizeFn;
120
+ }
121
+
122
+ return {
123
+ name,
124
+ filePath: filePath || definition.filePath || null,
125
+ schema: definition.schema || null,
126
+ handler,
127
+ rawHandler: definition.handler,
128
+ memoize: memoizeFn,
129
+ metadata: definition.metadata || {},
130
+ description: definition.description || definition.metadata?.description || '',
131
+ auth: definition.auth,
132
+ cache: definition.cache,
133
+ timeout: definition.timeout,
134
+ transaction: definition.transaction,
135
+ circuitBreaker: definition.circuitBreaker,
136
+ retry: definition.retry,
137
+ before: Array.isArray(definition.before)
138
+ ? definition.before
139
+ : (typeof definition.before === 'function' ? [definition.before] : []),
140
+ after: Array.isArray(definition.after)
141
+ ? definition.after
142
+ : (typeof definition.after === 'function' ? [definition.after] : []),
143
+ onError: Array.isArray(definition.onError)
144
+ ? definition.onError
145
+ : (typeof definition.onError === 'function' ? [definition.onError] : []),
146
+ middleware: Array.isArray(definition.middleware)
147
+ ? definition.middleware
148
+ : (typeof definition.middleware === 'function' ? [definition.middleware] : (Array.isArray(definition.middlewares) ? definition.middlewares : [])),
149
+ };
32
150
  }
33
151
 
34
152
  /**
35
- * Discover and load all services from servicesDir
153
+ * Discover and synchronously load all services from servicesDir.
154
+ * If a file is an ES Module (or options.lazy is true), it is automatically
155
+ * registered as lazy to be resolved asynchronously on invocation.
36
156
  * @returns {ServiceRegistry}
37
157
  */
38
158
  load() {
@@ -46,77 +166,97 @@ class ServiceRegistry {
46
166
  const { name, aliases, filePath } = item;
47
167
 
48
168
  // Duplicate check
49
- if (this.services.has(name)) {
50
- const existing = this.services.get(name);
169
+ if (this.services.has(name) || this.lazyServices.has(name)) {
170
+ const existing = this.services.get(name) || this.lazyServices.get(name);
51
171
  throw new ConfigurationError(
52
172
  `Duplicate service registered: ${name} (files: ${existing.filePath} and ${filePath})`
53
173
  );
54
174
  }
55
175
 
56
- // In dev mode, ensure fresh require
57
- if (this.isDev) {
58
- try {
59
- const resolved = require.resolve(filePath);
60
- delete require.cache[resolved];
61
- } catch (e) {}
176
+ for (const alias of aliases) {
177
+ this.aliases.set(alias, name);
178
+ }
179
+
180
+ const isMjs = filePath.endsWith('.mjs');
181
+
182
+ // If lazy mode or .mjs file, register lazily
183
+ if (this.lazy || isMjs) {
184
+ this.lazyServices.set(name, {
185
+ name,
186
+ aliases,
187
+ filePath,
188
+ isMjs,
189
+ });
190
+ continue;
62
191
  }
63
192
 
64
- let mod;
65
193
  try {
66
- mod = require(filePath);
194
+ const mod = loadModuleSync(filePath, { isDev: this.isDev });
195
+ const serviceDef = this._normalizeDefinition(name, mod, filePath);
196
+ this.services.set(name, serviceDef);
67
197
  } catch (err) {
68
- throw new ConfigurationError(`Failed to load service file '${filePath}': ${err.message}`, {
69
- cause: err,
70
- });
198
+ // If file is an ES Module (ERR_REQUIRE_ESM), fall back to lazy async evaluation
199
+ if (err.code === 'ERR_REQUIRE_ESM' || err.message?.includes('ERR_REQUIRE_ESM')) {
200
+ this.lazyServices.set(name, {
201
+ name,
202
+ aliases,
203
+ filePath,
204
+ isMjs: true,
205
+ });
206
+ } else {
207
+ throw new ConfigurationError(`Failed to load service file '${filePath}': ${err.message}`, {
208
+ cause: err,
209
+ });
210
+ }
71
211
  }
212
+ }
72
213
 
73
- const raw = mod && mod.__esModule && mod.default ? mod.default : (mod && mod.default ? mod.default : mod);
74
- const definition = typeof raw === 'function' ? { handler: raw } : raw;
214
+ return this;
215
+ }
75
216
 
76
- if (!definition || typeof definition !== 'object') {
77
- throw new ConfigurationError(
78
- `Service file '${filePath}' must export an object or handler function`
79
- );
80
- }
217
+ /**
218
+ * Discover and asynchronously load all services from servicesDir, supporting both CJS and native ESM.
219
+ * @returns {Promise<ServiceRegistry>}
220
+ */
221
+ async loadAsync() {
222
+ if (!this.servicesDir) {
223
+ return this;
224
+ }
225
+
226
+ const discovered = discoverServices(this.servicesDir);
81
227
 
82
- if (typeof definition.handler !== 'function') {
228
+ for (const item of discovered) {
229
+ const { name, aliases, filePath } = item;
230
+
231
+ if (this.services.has(name) || this.lazyServices.has(name)) {
232
+ const existing = this.services.get(name) || this.lazyServices.get(name);
83
233
  throw new ConfigurationError(
84
- `Service '${name}' in '${filePath}' must provide a handler function`
234
+ `Duplicate service registered: ${name} (files: ${existing.filePath} and ${filePath})`
85
235
  );
86
236
  }
87
237
 
88
- let handler = definition.handler;
89
- let memoizeFn = null;
90
-
91
- if (definition.cache) {
92
- const memoizeOpts = typeof definition.cache === 'object' && definition.cache !== null
93
- ? definition.cache
94
- : { ttl: definition.cache };
95
- memoizeFn = memoize(definition.handler, memoizeOpts);
96
- handler = memoizeFn;
238
+ for (const alias of aliases) {
239
+ this.aliases.set(alias, name);
97
240
  }
98
241
 
99
- const serviceDef = {
100
- name,
101
- filePath,
102
- schema: definition.schema || null,
103
- handler,
104
- rawHandler: definition.handler,
105
- memoize: memoizeFn,
106
- metadata: definition.metadata || {},
107
- description: definition.description || definition.metadata?.description || '',
108
- auth: definition.auth,
109
- cache: definition.cache,
110
- timeout: definition.timeout,
111
- transaction: definition.transaction,
112
- circuitBreaker: definition.circuitBreaker,
113
- retry: definition.retry,
114
- };
115
-
116
- this.services.set(name, serviceDef);
242
+ if (this.lazy) {
243
+ this.lazyServices.set(name, {
244
+ name,
245
+ aliases,
246
+ filePath,
247
+ isMjs: filePath.endsWith('.mjs'),
248
+ });
249
+ continue;
250
+ }
117
251
 
118
- for (const alias of aliases) {
119
- this.aliases.set(alias, name);
252
+ try {
253
+ const mod = await loadModuleAsync(filePath, { isDev: this.isDev });
254
+ const serviceDef = this._normalizeDefinition(name, mod, filePath);
255
+ this.services.set(name, serviceDef);
256
+ } catch (err) {
257
+ throw new ConfigurationError(`Failed to load service file '${filePath}': ${err.message}`, {
258
+ cause: err,
259
+ });
120
260
  }
121
261
  }
122
262
 
@@ -125,8 +265,9 @@ class ServiceRegistry {
125
265
 
126
266
  /**
127
267
  * Programmatically register a service
128
- * @param {string} name - Service name (e.g. 'user.get')
129
- * @param {Object|Function} definition - Service definition or handler function
268
+ * @param {string|Object} nameOrDef - Service name or definition object
269
+ * @param {Object|Function} [maybeDef] - Service definition or handler function
270
+ * @param {Object} [options={}] - Options (e.g. { overwrite: true, aliases: [] })
130
271
  * @returns {ServiceRegistry}
131
272
  */
132
273
  register(nameOrDef, maybeDef, options = {}) {
@@ -142,45 +283,58 @@ class ServiceRegistry {
142
283
  throw new WebspressoError('Service name must be a non-empty string');
143
284
  }
144
285
 
145
- if (this.services.has(name) && !options.overwrite) {
286
+ if ((this.services.has(name) || this.lazyServices.has(name)) && !options.overwrite) {
146
287
  throw new ConfigurationError(`Duplicate service registered: ${name}`);
147
288
  }
148
289
 
149
- const def = typeof definition === 'function' ? { handler: definition } : definition;
290
+ const serviceDef = this._normalizeDefinition(name, definition, definition?.filePath || null);
291
+ this.services.set(name, serviceDef);
292
+ this.lazyServices.delete(name);
150
293
 
151
- if (!def || typeof def !== 'object' || typeof def.handler !== 'function') {
152
- throw new ConfigurationError(`Service '${name}' must provide a handler function`);
294
+ if (Array.isArray(options.aliases)) {
295
+ for (const alias of options.aliases) {
296
+ this.aliases.set(alias, name);
297
+ }
153
298
  }
154
299
 
155
- let handler = def.handler;
156
- let memoizeFn = null;
300
+ return this;
301
+ }
157
302
 
158
- if (def.cache) {
159
- const memoizeOpts = typeof def.cache === 'object' && def.cache !== null
160
- ? def.cache
161
- : { ttl: def.cache };
162
- memoizeFn = memoize(def.handler, memoizeOpts);
163
- handler = memoizeFn;
303
+ /**
304
+ * Programmatically register a lazy service with a custom loader function or file path
305
+ * @param {string} name - Service name
306
+ * @param {Function|string} loader - Async loader function or file path
307
+ * @param {Object} [options={}] - Registration options
308
+ * @returns {ServiceRegistry}
309
+ */
310
+ registerLazy(name, loader, options = {}) {
311
+ if (!name || typeof name !== 'string') {
312
+ throw new WebspressoError('Service name must be a non-empty string');
164
313
  }
165
314
 
166
- const serviceDef = {
315
+ if (typeof loader !== 'function' && typeof loader !== 'string') {
316
+ throw new ConfigurationError(
317
+ `Lazy service loader for '${name}' must be an async loader function or file path string`
318
+ );
319
+ }
320
+
321
+ if ((this.services.has(name) || this.lazyServices.has(name)) && !options.overwrite) {
322
+ throw new ConfigurationError(`Duplicate service registered: ${name}`);
323
+ }
324
+
325
+ this.lazyServices.set(name, {
167
326
  name,
168
- filePath: def.filePath || null,
169
- schema: def.schema || null,
170
- handler,
171
- rawHandler: def.handler,
172
- memoize: memoizeFn,
173
- metadata: def.metadata || {},
174
- description: def.description || def.metadata?.description || '',
175
- auth: def.auth,
176
- cache: def.cache,
177
- timeout: def.timeout,
178
- transaction: def.transaction,
179
- circuitBreaker: def.circuitBreaker,
180
- retry: def.retry,
181
- };
327
+ loader: typeof loader === 'function' ? loader : null,
328
+ filePath: typeof loader === 'string' ? loader : (options.filePath || null),
329
+ options,
330
+ });
331
+
332
+ if (Array.isArray(options.aliases)) {
333
+ for (const alias of options.aliases) {
334
+ this.aliases.set(alias, name);
335
+ }
336
+ }
182
337
 
183
- this.services.set(name, serviceDef);
184
338
  return this;
185
339
  }
186
340
 
@@ -191,11 +345,15 @@ class ServiceRegistry {
191
345
  */
192
346
  unregister(name) {
193
347
  if (!name || typeof name !== 'string') return false;
194
- return this.services.delete(name);
348
+ const removedService = this.services.delete(name);
349
+ const removedLazy = this.lazyServices.delete(name);
350
+ return removedService || removedLazy;
195
351
  }
196
352
 
197
353
  /**
198
- * Get a service definition by name or alias
354
+ * Get a service definition by name or alias (synchronous).
355
+ * If the service is registered as lazy CommonJS, it will be loaded and cached synchronously.
356
+ * If the service is an ES Module, call getAsync() or execute() instead.
199
357
  * @param {string} name - Service name
200
358
  * @returns {Object|undefined}
201
359
  */
@@ -209,28 +367,102 @@ class ServiceRegistry {
209
367
  }
210
368
 
211
369
  const aliasedName = this.aliases.get(name);
212
- if (aliasedName && this.services.has(aliasedName)) {
213
- return this.services.get(aliasedName);
370
+ const targetName = (aliasedName && (this.services.has(aliasedName) || this.lazyServices.has(aliasedName)))
371
+ ? aliasedName
372
+ : name;
373
+
374
+ if (this.services.has(targetName)) {
375
+ return this.services.get(targetName);
376
+ }
377
+
378
+ if (this.lazyServices.has(targetName)) {
379
+ const lazyItem = this.lazyServices.get(targetName);
380
+ // Attempt synchronous require if it is a CJS file path
381
+ if (lazyItem.filePath && !lazyItem.isMjs) {
382
+ try {
383
+ const mod = loadModuleSync(lazyItem.filePath, { isDev: this.isDev });
384
+ const serviceDef = this._normalizeDefinition(targetName, mod, lazyItem.filePath);
385
+ this.services.set(targetName, serviceDef);
386
+ this.lazyServices.delete(targetName);
387
+ return serviceDef;
388
+ } catch (err) {
389
+ if (err.code !== 'ERR_REQUIRE_ESM' && !err.message?.includes('ERR_REQUIRE_ESM')) {
390
+ throw err;
391
+ }
392
+ }
393
+ }
394
+ }
395
+
396
+ return undefined;
397
+ }
398
+
399
+ /**
400
+ * Asynchronously get or load a service definition by name or alias.
401
+ * Seamlessly resolves lazy CJS, ESM dynamic imports, and custom loader functions.
402
+ * @param {string} name - Service name
403
+ * @returns {Promise<Object|undefined>}
404
+ */
405
+ async getAsync(name) {
406
+ if (!name || typeof name !== 'string') {
407
+ return undefined;
408
+ }
409
+
410
+ if (this.services.has(name)) {
411
+ return this.services.get(name);
412
+ }
413
+
414
+ const aliasedName = this.aliases.get(name);
415
+ const targetName = (aliasedName && (this.services.has(aliasedName) || this.lazyServices.has(aliasedName)))
416
+ ? aliasedName
417
+ : name;
418
+
419
+ if (this.services.has(targetName)) {
420
+ return this.services.get(targetName);
421
+ }
422
+
423
+ if (this.lazyServices.has(targetName)) {
424
+ const lazyItem = this.lazyServices.get(targetName);
425
+ let mod;
426
+ if (typeof lazyItem.loader === 'function') {
427
+ mod = await lazyItem.loader();
428
+ } else if (lazyItem.filePath) {
429
+ mod = await loadModuleAsync(lazyItem.filePath, { isDev: this.isDev });
430
+ }
431
+
432
+ const serviceDef = this._normalizeDefinition(targetName, mod, lazyItem.filePath);
433
+ this.services.set(targetName, serviceDef);
434
+ this.lazyServices.delete(targetName);
435
+ return serviceDef;
214
436
  }
215
437
 
216
438
  return undefined;
217
439
  }
218
440
 
219
441
  /**
220
- * Check if a service exists
442
+ * Check if a service exists (either materialized or registered lazily)
221
443
  * @param {string} name - Service name
222
444
  * @returns {boolean}
223
445
  */
224
446
  has(name) {
225
- return this.get(name) !== undefined;
447
+ if (!name || typeof name !== 'string') return false;
448
+ if (this.services.has(name) || this.lazyServices.has(name)) return true;
449
+ const aliasedName = this.aliases.get(name);
450
+ if (aliasedName) {
451
+ return this.services.has(aliasedName) || this.lazyServices.has(aliasedName);
452
+ }
453
+ return false;
226
454
  }
227
455
 
228
456
  /**
229
- * List all registered service names
457
+ * List all registered service names (including lazy services)
230
458
  * @returns {string[]}
231
459
  */
232
460
  list() {
233
- return Array.from(this.services.keys());
461
+ const names = new Set(this.services.keys());
462
+ for (const name of this.lazyServices.keys()) {
463
+ names.add(name);
464
+ }
465
+ return Array.from(names);
234
466
  }
235
467
 
236
468
  /**
@@ -279,6 +511,98 @@ class ServiceRegistry {
279
511
  return this.clearCache();
280
512
  }
281
513
 
514
+ /**
515
+ * Invalidate cached service entries matching a specific tag across all registered services
516
+ * or within a single named service.
517
+ * @param {string} tag - Tag to invalidate (e.g. 'users', 'user:123')
518
+ * @param {string} [serviceName] - Optional specific service name
519
+ * @returns {number|Promise<number>} Count of invalidated entries
520
+ */
521
+ invalidateByTag(tag, serviceName) {
522
+ if (serviceName) {
523
+ const serviceDef = this.get(serviceName);
524
+ if (serviceDef && serviceDef.memoize && typeof serviceDef.memoize.invalidateByTag === 'function') {
525
+ return serviceDef.memoize.invalidateByTag(tag);
526
+ }
527
+ return 0;
528
+ }
529
+
530
+ const promises = [];
531
+ let total = 0;
532
+
533
+ for (const serviceDef of this.services.values()) {
534
+ if (serviceDef.memoize && typeof serviceDef.memoize.invalidateByTag === 'function') {
535
+ const res = serviceDef.memoize.invalidateByTag(tag);
536
+ if (res && typeof res.then === 'function') {
537
+ promises.push(res);
538
+ } else if (typeof res === 'number') {
539
+ total += res;
540
+ }
541
+ }
542
+ }
543
+
544
+ if (promises.length > 0) {
545
+ return Promise.all(promises).then((results) => {
546
+ return total + results.reduce((acc, c) => acc + (typeof c === 'number' ? c : 0), 0);
547
+ });
548
+ }
549
+
550
+ return total;
551
+ }
552
+
553
+ /**
554
+ * Invalidate cached service entries matching any of the specified tags
555
+ * across all registered services or within a single named service.
556
+ * @param {string[]|string} tags - Tags to invalidate
557
+ * @param {string} [serviceName] - Optional specific service name
558
+ * @returns {number|Promise<number>} Total count of invalidated entries
559
+ */
560
+ invalidateByTags(tags, serviceName) {
561
+ if (serviceName) {
562
+ const serviceDef = this.get(serviceName);
563
+ if (serviceDef && serviceDef.memoize && typeof serviceDef.memoize.invalidateByTags === 'function') {
564
+ return serviceDef.memoize.invalidateByTags(tags);
565
+ }
566
+ return 0;
567
+ }
568
+
569
+ const promises = [];
570
+ let total = 0;
571
+
572
+ for (const serviceDef of this.services.values()) {
573
+ if (serviceDef.memoize && typeof serviceDef.memoize.invalidateByTags === 'function') {
574
+ const res = serviceDef.memoize.invalidateByTags(tags);
575
+ if (res && typeof res.then === 'function') {
576
+ promises.push(res);
577
+ } else if (typeof res === 'number') {
578
+ total += res;
579
+ }
580
+ }
581
+ }
582
+
583
+ if (promises.length > 0) {
584
+ return Promise.all(promises).then((results) => {
585
+ return total + results.reduce((acc, c) => acc + (typeof c === 'number' ? c : 0), 0);
586
+ });
587
+ }
588
+
589
+ return total;
590
+ }
591
+
592
+ /**
593
+ * Alias for invalidateByTag
594
+ */
595
+ invalidateTag(tag, serviceName) {
596
+ return this.invalidateByTag(tag, serviceName);
597
+ }
598
+
599
+ /**
600
+ * Alias for invalidateByTags
601
+ */
602
+ invalidateTags(tags, serviceName) {
603
+ return this.invalidateByTags(tags, serviceName);
604
+ }
605
+
282
606
  /**
283
607
  * Execute a service by name
284
608
  * @param {string} name - Service name
@@ -299,14 +623,88 @@ class ServiceRegistry {
299
623
  }
300
624
 
301
625
  /**
302
- * Reload services from disk (useful in development)
626
+ * Register a global service middleware following the async onion model
627
+ * @param {Function} middleware - ({ name, input, ctx, serviceDef, options, registry }, next) => Promise<any>
628
+ * @returns {ServiceRegistry}
629
+ */
630
+ use(middleware) {
631
+ if (typeof middleware !== 'function') {
632
+ throw new WebspressoError('Service middleware must be a function');
633
+ }
634
+ this.middlewares.push(middleware);
635
+ return this;
636
+ }
637
+
638
+ /**
639
+ * Register a global pre-execution hook
640
+ * @param {Function} hook - ({ name, input, ctx, serviceDef, options }) => Promise<any>|void
641
+ * @returns {ServiceRegistry}
642
+ */
643
+ before(hook) {
644
+ if (typeof hook !== 'function') {
645
+ throw new WebspressoError('Service before hook must be a function');
646
+ }
647
+ this.beforeHooks.push(hook);
648
+ return this;
649
+ }
650
+
651
+ /**
652
+ * Register a global post-execution hook
653
+ * @param {Function} hook - ({ name, result, input, ctx, serviceDef, duration, options }) => Promise<any>|void
654
+ * @returns {ServiceRegistry}
655
+ */
656
+ after(hook) {
657
+ if (typeof hook !== 'function') {
658
+ throw new WebspressoError('Service after hook must be a function');
659
+ }
660
+ this.afterHooks.push(hook);
661
+ return this;
662
+ }
663
+
664
+ /**
665
+ * Register a global error interception hook
666
+ * @param {Function} hook - ({ name, error, input, ctx, serviceDef, duration, options }) => Promise<any>|void
667
+ * @returns {ServiceRegistry}
668
+ */
669
+ onError(hook) {
670
+ if (typeof hook !== 'function') {
671
+ throw new WebspressoError('Service onError hook must be a function');
672
+ }
673
+ this.onErrorHooks.push(hook);
674
+ return this;
675
+ }
676
+
677
+ /**
678
+ * Attach an EventDispatcher instance to emit service lifecycle events
679
+ * @param {Object} events - EventDispatcher instance
680
+ * @returns {ServiceRegistry}
681
+ */
682
+ setEventDispatcher(events) {
683
+ this.events = events;
684
+ return this;
685
+ }
686
+
687
+ /**
688
+ * Reload services from disk synchronously (useful in development)
303
689
  * @returns {ServiceRegistry}
304
690
  */
305
691
  reload() {
306
692
  this.services.clear();
693
+ this.lazyServices.clear();
307
694
  this.aliases.clear();
308
695
  return this.load();
309
696
  }
697
+
698
+ /**
699
+ * Reload services from disk asynchronously (useful in development for ESM)
700
+ * @returns {Promise<ServiceRegistry>}
701
+ */
702
+ async reloadAsync() {
703
+ this.services.clear();
704
+ this.lazyServices.clear();
705
+ this.aliases.clear();
706
+ return this.loadAsync();
707
+ }
310
708
  }
311
709
 
312
710
  module.exports = {