@common-stack/server-core 7.2.1-alpha.45 → 7.2.1-alpha.47

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 (81) hide show
  1. package/package.json +2 -2
  2. package/lib/__tests__/connector-inngest-arrays.test.d.ts +0 -1
  3. package/lib/connector/__tests__/container-connector.test.d.ts +0 -2
  4. package/lib/connector/__tests__/context-connector.test.d.ts +0 -1
  5. package/lib/connector/__tests__/fixtures/preferenfces/sample-settings.d.ts +0 -98
  6. package/lib/connector/__tests__/fixtures/sample-roles-permissions/account-api/permission-contribution.d.ts +0 -90
  7. package/lib/connector/__tests__/graphql-middleware.test.d.ts +0 -1
  8. package/lib/connector/__tests__/permissions.test.d.ts +0 -1
  9. package/lib/connector/__tests__/policies.test.d.ts +0 -1
  10. package/lib/connector/__tests__/preferences.test.d.ts +0 -1
  11. package/lib/connector/__tests__/roles-update-connector.test.d.ts +0 -1
  12. package/lib/connector/__tests__/rules-connector.test.d.ts +0 -1
  13. package/lib/connector/__tests__/samples/graphql/types/person_entity_type.d.ts +0 -2
  14. package/lib/connector/__tests__/samples/graphql/types/person_search_type.d.ts +0 -2
  15. package/lib/connector/__tests__/samples/graphql/types/vendor_type.d.ts +0 -2
  16. package/lib/connector/__tests__/schema-connector.test.d.ts +0 -1
  17. package/lib/connector/__tests__/service-connector.test.d.ts +0 -2
  18. package/lib/connector/__tests__/websocket-connector.test.d.ts +0 -1
  19. package/lib/connector/connector.d.ts +0 -619
  20. package/lib/connector/connector.js +0 -470
  21. package/lib/connector/connector.js.map +0 -1
  22. package/lib/connector/index.d.ts +0 -1
  23. package/lib/constants/directives.d.ts +0 -1
  24. package/lib/constants/directives.js +0 -1
  25. package/lib/constants/directives.js.map +0 -1
  26. package/lib/constants/index.d.ts +0 -2
  27. package/lib/constants/types.d.ts +0 -8
  28. package/lib/constants/types.js +0 -8
  29. package/lib/constants/types.js.map +0 -1
  30. package/lib/index.d.ts +0 -6
  31. package/lib/index.js +0 -1
  32. package/lib/index.js.map +0 -1
  33. package/lib/interfaces/connector.d.ts +0 -36
  34. package/lib/interfaces/datasource.d.ts +0 -14
  35. package/lib/interfaces/index.d.ts +0 -7
  36. package/lib/interfaces/mongo-migration.d.ts +0 -17
  37. package/lib/interfaces/permissions.d.ts +0 -5
  38. package/lib/interfaces/policies.d.ts +0 -5
  39. package/lib/interfaces/roles.d.ts +0 -8
  40. package/lib/interfaces/rules.d.ts +0 -12
  41. package/lib/interfaces/rules.js +0 -6
  42. package/lib/interfaces/rules.js.map +0 -1
  43. package/lib/interfaces/store.d.ts +0 -3
  44. package/lib/logger/index.d.ts +0 -1
  45. package/lib/logger/logger.d.ts +0 -2
  46. package/lib/logger/logger.js +0 -5
  47. package/lib/logger/logger.js.map +0 -1
  48. package/lib/moleculer-generation/__tests__/moleculerEventHandler.test.d.ts +0 -5
  49. package/lib/moleculer-generation/__tests__/serviceGenerationUtils.test.d.ts +0 -5
  50. package/lib/moleculer-generation/__tests__/typedMoleculerService.test.d.ts +0 -5
  51. package/lib/moleculer-generation/__tests__/typedProxyService.test.d.ts +0 -5
  52. package/lib/moleculer-generation/generateAllServiceSchemas.cjs +0 -628
  53. package/lib/moleculer-generation/index.d.ts +0 -16
  54. package/lib/moleculer-generation/moleculerEventHandler.d.ts +0 -73
  55. package/lib/moleculer-generation/moleculerEventHandler.js +0 -91
  56. package/lib/moleculer-generation/moleculerEventHandler.js.map +0 -1
  57. package/lib/moleculer-generation/serviceGenerationUtils.d.ts +0 -100
  58. package/lib/moleculer-generation/serviceGenerationUtils.js +0 -156
  59. package/lib/moleculer-generation/serviceGenerationUtils.js.map +0 -1
  60. package/lib/moleculer-generation/typedMoleculerService.d.ts +0 -502
  61. package/lib/moleculer-generation/typedMoleculerService.js +0 -670
  62. package/lib/moleculer-generation/typedMoleculerService.js.map +0 -1
  63. package/lib/moleculer-generation/typedProxyService.d.ts +0 -119
  64. package/lib/moleculer-generation/typedProxyService.js +0 -231
  65. package/lib/moleculer-generation/typedProxyService.js.map +0 -1
  66. package/lib/moleculer-generation/zodToMoleculer.d.ts +0 -45
  67. package/lib/moleculer-generation/zodToMoleculer.js +0 -120
  68. package/lib/moleculer-generation/zodToMoleculer.js.map +0 -1
  69. package/lib/utils/extract-tenant-id.d.ts +0 -1
  70. package/lib/utils/extract-tenant-id.js +0 -4
  71. package/lib/utils/extract-tenant-id.js.map +0 -1
  72. package/lib/utils/generate-query-cache-key.d.ts +0 -11
  73. package/lib/utils/generate-query-cache-key.js +0 -13
  74. package/lib/utils/generate-query-cache-key.js.map +0 -1
  75. package/lib/utils/get-directive-args-from-schema.d.ts +0 -13
  76. package/lib/utils/get-directive-args-from-schema.js +0 -25
  77. package/lib/utils/get-directive-args-from-schema.js.map +0 -1
  78. package/lib/utils/index.d.ts +0 -4
  79. package/lib/utils/preferences.d.ts +0 -87
  80. package/lib/utils/preferences.js +0 -40
  81. package/lib/utils/preferences.js.map +0 -1
@@ -1,670 +0,0 @@
1
- import {Moleculer}from'./moleculerEventHandler.js';import {getAllMethodNames}from'./serviceGenerationUtils.js';// from package: store-mongo
2
- /**
3
- * @file typed-moleculer-service.ts
4
- * @description Provides type-safe base class for Moleculer services with ENFORCED
5
- * compile-time verification AND automatic action generation from service methods.
6
- */
7
- /**
8
- * Split parameters by comma, respecting nested structures
9
- */
10
- function splitParams(paramsStr) {
11
- const params = [];
12
- let current = '';
13
- let depth = 0;
14
- for (let i = 0; i < paramsStr.length; i++) {
15
- const char = paramsStr[i];
16
- if (char === '<' || char === '{' || char === '[' || char === '(') {
17
- depth++;
18
- current += char;
19
- }
20
- else if (char === '>' || char === '}' || char === ']' || char === ')') {
21
- depth--;
22
- current += char;
23
- }
24
- else if (char === ',' && depth === 0) {
25
- params.push(current);
26
- current = '';
27
- }
28
- else {
29
- current += char;
30
- }
31
- }
32
- if (current) {
33
- params.push(current);
34
- }
35
- return params;
36
- }
37
- /**
38
- * Infer Moleculer validator type from TypeScript type annotation
39
- */
40
- function inferMoleculerType(typeAnnotation) {
41
- const type = typeAnnotation.trim();
42
- // Check for array types
43
- if (type.endsWith('[]') || type.startsWith('Array<') || type.startsWith('ReadonlyArray<')) {
44
- return 'array';
45
- }
46
- // Check for primitive types
47
- if (type === 'string' || type === 'String')
48
- return 'string';
49
- if (type === 'number' || type === 'Number')
50
- return 'number';
51
- if (type === 'boolean' || type === 'Boolean')
52
- return 'boolean';
53
- // Check for common built-in types
54
- if (type === 'Date')
55
- return 'date';
56
- if (type === 'RegExp')
57
- return 'object';
58
- // Check for union types with primitive
59
- if (type.includes('|')) {
60
- const types = type.split('|').map((t) => t.trim());
61
- // If all types are same primitive, return that
62
- const nonNullTypes = types.filter((t) => t !== 'null' && t !== 'undefined');
63
- if (nonNullTypes.length === 1) {
64
- return inferMoleculerType(nonNullTypes[0]);
65
- }
66
- // If contains string, number, or boolean, try to infer
67
- if (nonNullTypes.some((t) => t === 'string'))
68
- return 'string';
69
- if (nonNullTypes.some((t) => t === 'number'))
70
- return 'number';
71
- if (nonNullTypes.some((t) => t === 'boolean'))
72
- return 'boolean';
73
- }
74
- // Check for enum types (assume string enum)
75
- if (type.includes('Enum') || type.includes('Type')) {
76
- return 'string';
77
- }
78
- // Default to object for interfaces, types, classes, etc.
79
- return 'object';
80
- }
81
- /**
82
- * Infer type from default value
83
- */
84
- function inferTypeFromDefault(defaultValue) {
85
- // String defaults
86
- if (defaultValue.startsWith("'") || defaultValue.startsWith('"') || defaultValue.startsWith('`')) {
87
- return 'string';
88
- }
89
- // Number defaults
90
- if (/^-?\d+(\.\d+)?$/.test(defaultValue)) {
91
- return 'number';
92
- }
93
- // Boolean defaults
94
- if (defaultValue === 'true' || defaultValue === 'false') {
95
- return 'boolean';
96
- }
97
- // Array defaults
98
- if (defaultValue.startsWith('[')) {
99
- return 'array';
100
- }
101
- // Object defaults
102
- if (defaultValue.startsWith('{')) {
103
- return 'object';
104
- }
105
- return 'object';
106
- }
107
- /**
108
- * Extract parameter names and infer types from a function's string representation
109
- * Returns array of { name, type } where type is the inferred Moleculer validator
110
- */
111
- function extractParamsWithTypes(funcStr) {
112
- // Match function parameters: function(a, b) or (a, b) => or async (a, b) =>
113
- const match = funcStr.match(/(?:function\s*)?(?:\w+\s*)?\(([^)]*)\)/);
114
- if (!match || !match[1])
115
- return [];
116
- const paramsStr = match[1].trim();
117
- if (!paramsStr)
118
- return [];
119
- const params = [];
120
- // Split by comma, but handle nested objects/arrays
121
- const paramParts = splitParams(paramsStr);
122
- paramParts.forEach((param) => {
123
- const trimmed = param.trim();
124
- if (!trimmed)
125
- return;
126
- // Check if optional (has ?)
127
- const optional = trimmed.includes('?');
128
- // Extract parameter name and type annotation
129
- // Patterns: "name", "name?", "name: Type", "name?: Type", "name = default"
130
- const paramMatch = trimmed.match(/^(\w+)\??(?:\s*:\s*([^=]+))?(?:\s*=\s*(.+))?/);
131
- if (!paramMatch)
132
- return;
133
- const name = paramMatch[1];
134
- const typeAnnotation = paramMatch[2]?.trim();
135
- const defaultValue = paramMatch[3]?.trim();
136
- // Infer Moleculer type from TypeScript annotation or default value
137
- let moleculerType = 'object'; // Safe default
138
- if (typeAnnotation) {
139
- moleculerType = inferMoleculerType(typeAnnotation);
140
- }
141
- else if (defaultValue) {
142
- moleculerType = inferTypeFromDefault(defaultValue);
143
- }
144
- params.push({
145
- name,
146
- type: moleculerType,
147
- optional: optional || !!defaultValue,
148
- });
149
- });
150
- return params;
151
- }
152
- // getAllMethodNames is now imported from serviceGenerationUtils.ts for consistency
153
- /**
154
- * ADVANCED AUTO-GENERATED: Generate actions with full control over inclusion, exclusion, and overrides.
155
- * Params are inferred from TypeScript function signatures with optional fine-grained control.
156
- *
157
- * @param service - The service instance to wrap
158
- * @param config - Advanced configuration for fine-grained control
159
- * @returns Actions object with handlers for selected service methods
160
- *
161
- * @example
162
- * ```typescript
163
- * // Basic: Auto-generate all methods
164
- * const actions = generateAutoInferredServiceActions<IAccountService>(accountService);
165
- *
166
- * // Advanced: Include only specific methods
167
- * const actions = generateAutoInferredServiceActions<IAccountService>(accountService, {
168
- * include: ['findAccountById', 'createAccount', 'updateAccount']
169
- * });
170
- *
171
- * // Advanced: Exclude specific methods
172
- * const actions = generateAutoInferredServiceActions<IAccountService>(accountService, {
173
- * exclude: ['deleteAccount', 'internalMethod']
174
- * });
175
- *
176
- * // Advanced: Override param schemas for specific methods
177
- * const actions = generateAutoInferredServiceActions<IAccountService>(accountService, {
178
- * paramOverrides: {
179
- * findAccountById: { id: 'string' },
180
- * getUsers: { where: { type: 'object', optional: true } }
181
- * }
182
- * });
183
- *
184
- * // Advanced: Add custom action configuration
185
- * const actions = generateAutoInferredServiceActions<IAccountService>(accountService, {
186
- * actionConfig: {
187
- * findAccountById: { cache: true, visibility: 'public' },
188
- * deleteAccount: { visibility: 'protected' }
189
- * }
190
- * });
191
- *
192
- * // Advanced: Combine multiple options
193
- * const actions = generateAutoInferredServiceActions<IAccountService>(accountService, {
194
- * include: ['findAccountById', 'createAccount'],
195
- * paramOverrides: {
196
- * findAccountById: { id: 'string' }
197
- * },
198
- * actionConfig: {
199
- * findAccountById: { cache: true }
200
- * }
201
- * });
202
- * ```
203
- */
204
- function generateAutoInferredServiceActions(service, config = {}) {
205
- const { paramOverrides = {}, include, exclude = [], actionToMethodMap = {}, actionConfig = {} } = config;
206
- const actions = {};
207
- // Get all methods from the service, including inherited methods from parent classes
208
- const allKeys = getAllMethodNames(service);
209
- allKeys.forEach((key) => {
210
- // Skip constructor and private methods
211
- if (key === 'constructor' || key.startsWith('_')) {
212
- return;
213
- }
214
- // Skip utility methods that should never be exposed as actions
215
- if (['dispose', 'broker', 'logger', 'topic', 'callAction'].includes(key)) {
216
- return;
217
- }
218
- // Apply include filter (whitelist) - takes precedence
219
- if (include && include.length > 0) {
220
- if (!include.includes(key)) {
221
- return;
222
- }
223
- }
224
- // Apply exclude filter (blacklist) - only if include is not specified
225
- else if (exclude.includes(key)) {
226
- return;
227
- }
228
- const method = service[key];
229
- if (typeof method !== 'function') {
230
- return;
231
- }
232
- const methodName = actionToMethodMap[key] || key;
233
- const serviceMethod = service[methodName];
234
- if (typeof serviceMethod !== 'function') {
235
- return;
236
- }
237
- // Use runtime reflection to infer params and types from function signature
238
- const funcStr = serviceMethod.toString();
239
- const paramsWithTypes = extractParamsWithTypes(funcStr);
240
- // Build param schema
241
- let paramSchema;
242
- // Use override if provided
243
- if (paramOverrides[key]) {
244
- paramSchema = paramOverrides[key];
245
- }
246
- else if (paramsWithTypes.length > 0) {
247
- // Auto-generate schema from inferred types
248
- paramSchema = paramsWithTypes.reduce((acc, param) => {
249
- if (param.optional) {
250
- acc[param.name] = { type: param.type, optional: true };
251
- }
252
- else {
253
- acc[param.name] = param.type;
254
- }
255
- return acc;
256
- }, {});
257
- }
258
- // Get custom action configuration if provided
259
- const customActionConfig = actionConfig[key];
260
- // Build the action object
261
- // Build the action object
262
- const action = {
263
- ...(paramSchema ? { params: paramSchema } : {}),
264
- handler: (ctx) => {
265
- const method = service[methodName];
266
- const paramsObj = ctx.params || {};
267
- // Extract parameters in the correct order based on method signature
268
- // Use paramsWithTypes to maintain parameter order
269
- const args = paramsWithTypes.length > 0
270
- ? paramsWithTypes.map((param) => {
271
- const value = paramsObj[param.name];
272
- // For optional parameters, provide empty object if undefined
273
- if (param.optional && value === undefined) {
274
- return {};
275
- }
276
- return value;
277
- })
278
- : [paramsObj]; // Fallback: pass entire params object if no signature info
279
- return method.apply(service, args);
280
- },
281
- };
282
- // Merge custom action config if provided (cache, visibility, etc.)
283
- if (customActionConfig) {
284
- Object.assign(action, customActionConfig);
285
- }
286
- actions[key] = action;
287
- });
288
- return actions;
289
- }
290
- /**
291
- * Generate both actions AND events from a service instance
292
- * - Actions: Generated from regular service methods
293
- * - Events: Generated from methods marked with @MoleculerEventHandler decorator
294
- *
295
- * @param service - The service instance to wrap
296
- * @param config - Configuration for actions and events
297
- * @returns Object with both actions and events
298
- *
299
- * @example
300
- * ```typescript
301
- * // Service with decorator
302
- * class OrganizationService {
303
- * // Regular method becomes action
304
- * async createOrganization(org: Org): Promise<Org> { }
305
- *
306
- * // Decorated method becomes event handler
307
- * @MoleculerEventHandler(UserBroadcasterAction.OnUserCreated)
308
- * async onUserCreated(event: UserEvent): Promise<void> { }
309
- * }
310
- *
311
- * // Generate both
312
- * const { actions, events } = generateServiceActionsAndEvents(service);
313
- * ```
314
- */
315
- function generateServiceActionsAndEvents(service, config = {}) {
316
- // Get event handlers from decorator metadata
317
- const eventHandlers = Moleculer.getEventHandlers(service);
318
- const eventHandlerMethods = new Set(eventHandlers.map((h) => h.methodName));
319
- // Generate actions (excluding event handler methods)
320
- const actionsConfig = {
321
- ...config,
322
- exclude: [...(config.exclude || []), ...Array.from(eventHandlerMethods)],
323
- };
324
- const actions = generateAutoInferredServiceActions(service, actionsConfig);
325
- // Generate events from decorated methods
326
- const events = {};
327
- eventHandlers.forEach((metadata) => {
328
- const method = service[metadata.methodName];
329
- if (typeof method === 'function') {
330
- events[metadata.eventName] = {
331
- handler: async (ctx) => {
332
- // Event payload is typically wrapped in ctx.params.event
333
- const eventData = ctx.params.event || ctx.params;
334
- await method.call(service, eventData);
335
- // Explicitly return void for Moleculer event handler signature
336
- },
337
- ...(metadata.group ? { group: metadata.group } : {}),
338
- };
339
- }
340
- });
341
- return { actions, events };
342
- }
343
- /**
344
- * Automatically generate Moleculer actions from a service instance.
345
- *
346
- * This eliminates the need to write repetitive action handlers - just pass your service
347
- * and it will create handlers that forward all calls automatically.
348
- *
349
- * @param service - The service instance to wrap
350
- * @param config - Optional configuration for customizing actions
351
- * @returns Actions object with handlers for all service methods
352
- *
353
- * @example
354
- * ```typescript
355
- * const actions = generateServiceActions(accountService, {
356
- * params: {
357
- * findAccountById: { id: 'string' },
358
- * createAccount: { account: 'object' }
359
- * },
360
- * exclude: ['get', 'getAll'] // Handle these manually
361
- * });
362
- * ```
363
- */
364
- function generateServiceActions(service, config = {}) {
365
- const { params = {}, exclude = [], actionToMethodMap = {} } = config;
366
- const actions = {};
367
- // Get all methods from the service
368
- const allKeys = Object.getOwnPropertyNames(Object.getPrototypeOf(service));
369
- const generatedMethods = [];
370
- allKeys.forEach((key) => {
371
- // Skip excluded methods, constructors, and private methods
372
- if (exclude.includes(key) || key === 'constructor' || key.startsWith('_')) {
373
- return;
374
- }
375
- const method = service[key];
376
- // Only process functions
377
- if (typeof method !== 'function') {
378
- return;
379
- }
380
- // Determine the method name to call (in case of mapping)
381
- const methodName = actionToMethodMap[key] || key;
382
- const serviceMethod = service[methodName];
383
- if (typeof serviceMethod !== 'function') {
384
- return;
385
- }
386
- generatedMethods.push(key);
387
- // Create the action handler
388
- actions[key] = {
389
- ...(params[key] ? { params: params[key] } : {}),
390
- handler: (ctx) => {
391
- // Call the service method with ctx.params spread as arguments
392
- const method = service[methodName];
393
- // If params is an object with known keys, extract them in order
394
- // Otherwise, pass the whole params object
395
- const paramsObj = ctx.params || {};
396
- const values = Object.values(paramsObj);
397
- return method.apply(service, values.length > 0 ? values : [paramsObj]);
398
- },
399
- };
400
- });
401
- // In development, log methods that don't have param validation
402
- if (process.env.NODE_ENV !== 'production') {
403
- const methodsWithoutParams = generatedMethods.filter((method) => !params[method]);
404
- if (methodsWithoutParams.length > 0) {
405
- console.warn(`⚠️ [generateServiceActions] The following methods don't have param validation defined:`, methodsWithoutParams);
406
- }
407
- }
408
- return actions;
409
- }
410
- /**
411
- * TYPE-SAFE version: Generate Moleculer actions with COMPILE-TIME verification.
412
- * TypeScript will error if any service method is missing from params.
413
- *
414
- * @param service - The service instance to wrap
415
- * @param config - Type-safe configuration requiring ALL methods to have params
416
- * @returns Actions object with handlers for all service methods
417
- *
418
- * @example
419
- * ```typescript
420
- * const actions = generateTypeSafeServiceActions<IAccountService>(accountService, {
421
- * params: {
422
- * // TypeScript enforces ALL IAccountService methods are here!
423
- * findAccountById: { id: 'string' },
424
- * createAccount: { account: 'object' },
425
- * // ... if you forget any method, TypeScript will error
426
- * }
427
- * });
428
- * ```
429
- */
430
- function generateTypeSafeServiceActions(service, config) {
431
- // Delegate to the regular function - type checking happens at compile time
432
- return generateServiceActions(service, config);
433
- }
434
- /**
435
- * Verify that all service methods have param validation defined.
436
- * Throws an error if any methods are missing params.
437
- *
438
- * Use this in development to ensure you haven't forgotten any param schemas.
439
- *
440
- * @param service - The service instance
441
- * @param config - The config used for generateServiceActions
442
- * @throws Error if any methods are missing param validation
443
- *
444
- * @example
445
- * ```typescript
446
- * const config = { params: { ... }, exclude: [...] };
447
- * verifyAllParamsDefined(accountService, config); // Throws if params missing
448
- * const actions = generateServiceActions(accountService, config);
449
- * ```
450
- */
451
- function verifyAllParamsDefined(service, config = {}) {
452
- const { params = {}, exclude = [] } = config;
453
- const allKeys = Object.getOwnPropertyNames(Object.getPrototypeOf(service));
454
- const missingParams = [];
455
- allKeys.forEach((key) => {
456
- // Skip excluded methods, constructors, and private methods
457
- if (exclude.includes(key) || key === 'constructor' || key.startsWith('_')) {
458
- return;
459
- }
460
- const method = service[key];
461
- // Only check functions
462
- if (typeof method !== 'function') {
463
- return;
464
- }
465
- // Check if params defined
466
- if (!params[key]) {
467
- missingParams.push(key);
468
- }
469
- });
470
- if (missingParams.length > 0) {
471
- const errorMessage = [
472
- `Missing param validation for methods: ${missingParams.join(', ')}`,
473
- '',
474
- 'Add these to your params config:',
475
- ...missingParams.map((method) => ` ${method}: { /* your params */ },`),
476
- ].join('\n');
477
- throw new Error(errorMessage);
478
- }
479
- }
480
- /**
481
- * Helper to create a typed action handler
482
- */
483
- function createTypedAction(action) {
484
- return action;
485
- }
486
- /**
487
- * DEBUG UTILITY: Dumps parameter information for all service methods
488
- *
489
- * This function extracts and logs parameter names, types, and inferred schemas
490
- * for debugging auto-generation issues. Use during development to understand
491
- * what the auto-generation sees and optimize paramOverrides.
492
- *
493
- * @param service - The service instance to analyze
494
- * @param config - Optional configuration to see what would be generated
495
- * @returns Object with detailed parameter information for each method
496
- *
497
- * @example
498
- * ```typescript
499
- * // In development/debug mode
500
- * const paramInfo = Moleculer.debugServiceParams(accountService);
501
- * console.log(JSON.stringify(paramInfo, null, 2));
502
- *
503
- * // With config to see filtered results
504
- * const paramInfo = Moleculer.debugServiceParams(accountService, {
505
- * exclude: ['dispose', 'createUserToken']
506
- * });
507
- * ```
508
- */
509
- function debugServiceParams(service, config = {}) {
510
- const { paramOverrides = {}, include, exclude = [] } = config;
511
- const result = {};
512
- // Get all methods from the service, including inherited methods
513
- const allKeys = getAllMethodNames(service);
514
- // Get event handler methods
515
- const eventHandlers = Moleculer.getEventHandlers(service);
516
- const eventHandlerMethods = new Set(eventHandlers.map((h) => h.methodName));
517
- allKeys.forEach((key) => {
518
- // Skip constructor and private methods
519
- if (key === 'constructor' || key.startsWith('_')) {
520
- return;
521
- }
522
- const method = service[key];
523
- if (typeof method !== 'function') {
524
- return;
525
- }
526
- // Determine if this method would be excluded
527
- const isEventHandler = eventHandlerMethods.has(key);
528
- let isExcluded = false;
529
- if (include && include.length > 0) {
530
- isExcluded = !include.includes(key);
531
- }
532
- else {
533
- isExcluded = exclude.includes(key) || isEventHandler;
534
- }
535
- // Get function signature
536
- const funcStr = method.toString();
537
- const paramsWithTypes = extractParamsWithTypes(funcStr);
538
- // Extract just the function signature (first line with params)
539
- const signatureMatch = funcStr.match(/^(?:async\s+)?(?:function\s+)?(?:\w+\s*)?\(([^)]*)\)/);
540
- const signature = signatureMatch ? signatureMatch[0] : funcStr.split('{')[0].trim();
541
- // Build inferred schema using new type inference
542
- let inferredSchema;
543
- if (paramsWithTypes.length > 0) {
544
- inferredSchema = paramsWithTypes.reduce((acc, param) => {
545
- if (param.optional) {
546
- acc[param.name] = { type: param.type, optional: true };
547
- }
548
- else {
549
- acc[param.name] = param.type;
550
- }
551
- return acc;
552
- }, {});
553
- }
554
- // Get override schema if provided
555
- const overrideSchema = paramOverrides[key];
556
- result[key] = {
557
- methodName: key,
558
- paramNames: paramsWithTypes.map((p) => p.name),
559
- functionSignature: signature,
560
- inferredSchema,
561
- overrideSchema,
562
- isExcluded,
563
- isEventHandler,
564
- };
565
- });
566
- return result;
567
- }
568
- /**
569
- * DEBUG UTILITY: Pretty prints service parameter information to console
570
- *
571
- * Formats and logs the output of debugServiceParams() in a readable way.
572
- * Shows which methods need paramOverrides and what types are inferred.
573
- *
574
- * @param service - The service instance to analyze
575
- * @param config - Optional configuration
576
- * @param options - Display options
577
- *
578
- * @example
579
- * ```typescript
580
- * // Print all methods
581
- * Moleculer.printServiceParams(accountService);
582
- *
583
- * // Print only methods without overrides
584
- * Moleculer.printServiceParams(accountService, config, { onlyMissingOverrides: true });
585
- *
586
- * // Print only included methods
587
- * Moleculer.printServiceParams(accountService, config, { onlyIncluded: true });
588
- * ```
589
- */
590
- function printServiceParams(service, config = {}, options = {}) {
591
- const paramInfo = debugServiceParams(service, config);
592
- const methods = Object.values(paramInfo);
593
- const separator = '='.repeat(80);
594
- const dashedLine = '-'.repeat(80);
595
- console.log(`\n${separator}`);
596
- console.log('SERVICE PARAMETER DEBUG INFORMATION');
597
- console.log(`${separator}\n`);
598
- // Summary statistics
599
- const totalMethods = methods.length;
600
- const includedMethods = methods.filter((m) => !m.isExcluded);
601
- const eventHandlers = methods.filter((m) => m.isEventHandler);
602
- const withOverrides = methods.filter((m) => m.overrideSchema);
603
- const withoutOverrides = includedMethods.filter((m) => !m.overrideSchema && !m.isExcluded);
604
- console.log('📊 SUMMARY:');
605
- console.log(` Total methods found: ${totalMethods}`);
606
- console.log(` Included in actions: ${includedMethods.length}`);
607
- console.log(` Event handlers (excluded from actions): ${eventHandlers.length}`);
608
- console.log(` With param overrides: ${withOverrides.length}`);
609
- console.log(` Without param overrides: ${withoutOverrides.length}`);
610
- console.log(`\n${dashedLine}\n`);
611
- // Filter methods based on options
612
- let displayMethods = methods;
613
- if (options.onlyMissingOverrides) {
614
- displayMethods = displayMethods.filter((m) => !m.overrideSchema && !m.isExcluded);
615
- }
616
- if (options.onlyIncluded) {
617
- displayMethods = displayMethods.filter((m) => !m.isExcluded);
618
- }
619
- if (!options.showExcluded) {
620
- displayMethods = displayMethods.filter((m) => !m.isExcluded);
621
- }
622
- // Print each method
623
- displayMethods.forEach((info, index) => {
624
- let status;
625
- if (info.isExcluded) {
626
- status = '❌ EXCLUDED';
627
- }
628
- else if (info.isEventHandler) {
629
- status = '📡 EVENT HANDLER';
630
- }
631
- else if (info.overrideSchema) {
632
- status = '✅ HAS OVERRIDE';
633
- }
634
- else {
635
- status = '⚠️ NEEDS OVERRIDE';
636
- }
637
- console.log(`${index + 1}. ${info.methodName} ${status}`);
638
- console.log(` Signature: ${info.functionSignature}`);
639
- console.log(` Parameters: [${info.paramNames.join(', ')}]`);
640
- if (info.inferredSchema) {
641
- console.log(` Inferred: ${JSON.stringify(info.inferredSchema)}`);
642
- }
643
- if (info.overrideSchema) {
644
- console.log(` Override: ${JSON.stringify(info.overrideSchema)}`);
645
- }
646
- console.log('');
647
- });
648
- // Suggestions
649
- if (withoutOverrides.length > 0 && !options.onlyMissingOverrides) {
650
- console.log(`\n${separator}`);
651
- console.log('💡 SUGGESTIONS:');
652
- console.log(`${separator}\n`);
653
- console.log('The following methods use default "object" validation:');
654
- console.log('Consider adding paramOverrides for better type safety:\n');
655
- const suggestions = [];
656
- withoutOverrides.forEach((info) => {
657
- const params = info.paramNames.map((p) => `${p}: 'string'`).join(', ');
658
- suggestions.push(` ${info.methodName}: { ${params} },`);
659
- });
660
- console.log('paramOverrides: {');
661
- console.log(suggestions.join('\n'));
662
- console.log('}');
663
- }
664
- console.log(`\n${separator}\n`);
665
- }
666
- // Implement the namespace extensions
667
- Moleculer.generateAutoInferredActions = generateAutoInferredServiceActions;
668
- Moleculer.generateActionsAndEvents = generateServiceActionsAndEvents;
669
- Moleculer.debugServiceParams = debugServiceParams;
670
- Moleculer.printServiceParams = printServiceParams;export{createTypedAction,debugServiceParams,generateAutoInferredServiceActions,generateServiceActions,generateServiceActionsAndEvents,generateTypeSafeServiceActions,printServiceParams,verifyAllParamsDefined};//# sourceMappingURL=typedMoleculerService.js.map