@common-stack/server-core 7.2.1-alpha.47 → 7.2.1-alpha.49
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/lib/__tests__/connector-inngest-arrays.test.d.ts +1 -0
- package/lib/connector/__tests__/container-connector.test.d.ts +2 -0
- package/lib/connector/__tests__/context-connector.test.d.ts +1 -0
- package/lib/connector/__tests__/fixtures/preferenfces/sample-settings.d.ts +98 -0
- package/lib/connector/__tests__/fixtures/sample-roles-permissions/account-api/permission-contribution.d.ts +90 -0
- package/lib/connector/__tests__/graphql-middleware.test.d.ts +1 -0
- package/lib/connector/__tests__/permissions.test.d.ts +1 -0
- package/lib/connector/__tests__/policies.test.d.ts +1 -0
- package/lib/connector/__tests__/preferences.test.d.ts +1 -0
- package/lib/connector/__tests__/roles-update-connector.test.d.ts +1 -0
- package/lib/connector/__tests__/rules-connector.test.d.ts +1 -0
- package/lib/connector/__tests__/samples/graphql/types/person_entity_type.d.ts +2 -0
- package/lib/connector/__tests__/samples/graphql/types/person_search_type.d.ts +2 -0
- package/lib/connector/__tests__/samples/graphql/types/vendor_type.d.ts +2 -0
- package/lib/connector/__tests__/schema-connector.test.d.ts +1 -0
- package/lib/connector/__tests__/service-connector.test.d.ts +2 -0
- package/lib/connector/__tests__/websocket-connector.test.d.ts +1 -0
- package/lib/connector/connector.d.ts +619 -0
- package/lib/connector/connector.js +470 -0
- package/lib/connector/connector.js.map +1 -0
- package/lib/connector/index.d.ts +1 -0
- package/lib/constants/directives.d.ts +1 -0
- package/lib/constants/directives.js +1 -0
- package/lib/constants/directives.js.map +1 -0
- package/lib/constants/index.d.ts +2 -0
- package/lib/constants/types.d.ts +8 -0
- package/lib/constants/types.js +8 -0
- package/lib/constants/types.js.map +1 -0
- package/lib/index.d.ts +6 -0
- package/lib/index.js +1 -0
- package/lib/index.js.map +1 -0
- package/lib/interfaces/connector.d.ts +36 -0
- package/lib/interfaces/datasource.d.ts +14 -0
- package/lib/interfaces/index.d.ts +7 -0
- package/lib/interfaces/mongo-migration.d.ts +17 -0
- package/lib/interfaces/permissions.d.ts +5 -0
- package/lib/interfaces/policies.d.ts +5 -0
- package/lib/interfaces/roles.d.ts +8 -0
- package/lib/interfaces/rules.d.ts +12 -0
- package/lib/interfaces/rules.js +6 -0
- package/lib/interfaces/rules.js.map +1 -0
- package/lib/interfaces/store.d.ts +3 -0
- package/lib/logger/index.d.ts +1 -0
- package/lib/logger/logger.d.ts +2 -0
- package/lib/logger/logger.js +5 -0
- package/lib/logger/logger.js.map +1 -0
- package/lib/moleculer-generation/__tests__/integration-proxy-moleculer.test.d.ts +6 -0
- package/lib/moleculer-generation/__tests__/moleculerEventHandler.test.d.ts +5 -0
- package/lib/moleculer-generation/__tests__/serviceGenerationUtils.test.d.ts +5 -0
- package/lib/moleculer-generation/__tests__/typedMoleculerService.test.d.ts +5 -0
- package/lib/moleculer-generation/__tests__/typedProxyService.test.d.ts +5 -0
- package/lib/moleculer-generation/generateAllServiceSchemas.cjs +628 -0
- package/lib/moleculer-generation/index.d.ts +16 -0
- package/lib/moleculer-generation/moleculerEventHandler.d.ts +73 -0
- package/lib/moleculer-generation/moleculerEventHandler.js +91 -0
- package/lib/moleculer-generation/moleculerEventHandler.js.map +1 -0
- package/lib/moleculer-generation/serviceGenerationUtils.d.ts +100 -0
- package/lib/moleculer-generation/serviceGenerationUtils.js +156 -0
- package/lib/moleculer-generation/serviceGenerationUtils.js.map +1 -0
- package/lib/moleculer-generation/typedMoleculerService.d.ts +502 -0
- package/lib/moleculer-generation/typedMoleculerService.js +685 -0
- package/lib/moleculer-generation/typedMoleculerService.js.map +1 -0
- package/lib/moleculer-generation/typedProxyService.d.ts +119 -0
- package/lib/moleculer-generation/typedProxyService.js +226 -0
- package/lib/moleculer-generation/typedProxyService.js.map +1 -0
- package/lib/moleculer-generation/zodToMoleculer.d.ts +45 -0
- package/lib/moleculer-generation/zodToMoleculer.js +120 -0
- package/lib/moleculer-generation/zodToMoleculer.js.map +1 -0
- package/lib/utils/extract-tenant-id.d.ts +1 -0
- package/lib/utils/extract-tenant-id.js +4 -0
- package/lib/utils/extract-tenant-id.js.map +1 -0
- package/lib/utils/generate-query-cache-key.d.ts +11 -0
- package/lib/utils/generate-query-cache-key.js +13 -0
- package/lib/utils/generate-query-cache-key.js.map +1 -0
- package/lib/utils/get-directive-args-from-schema.d.ts +13 -0
- package/lib/utils/get-directive-args-from-schema.js +25 -0
- package/lib/utils/get-directive-args-from-schema.js.map +1 -0
- package/lib/utils/index.d.ts +4 -0
- package/lib/utils/preferences.d.ts +87 -0
- package/lib/utils/preferences.js +40 -0
- package/lib/utils/preferences.js.map +1 -0
- package/package.json +3 -3
|
@@ -0,0 +1,685 @@
|
|
|
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
|
+
let value = paramsObj[param.name];
|
|
272
|
+
// If parameter not found by name and this is a single parameter method,
|
|
273
|
+
// treat the entire paramsObj as the parameter value
|
|
274
|
+
if (value === undefined && paramsWithTypes.length === 1) {
|
|
275
|
+
value = paramsObj;
|
|
276
|
+
// TODO: SECURITY - Add parameter validation and sanitization
|
|
277
|
+
// - Validate against Zod schema before passing to method
|
|
278
|
+
// - Sanitize MongoDB operators (strip $ prefixed fields)
|
|
279
|
+
// - Prevent prototype pollution (__proto__, constructor, prototype)
|
|
280
|
+
// - Whitelist allowed parameter fields
|
|
281
|
+
// See: Parameter injection, NoSQL injection, type confusion risks
|
|
282
|
+
console.warn('[MoleculerService] SECURITY WARNING: Passing entire params object as single parameter for method:', methodName, '- Implement validation before production use');
|
|
283
|
+
}
|
|
284
|
+
// For optional parameters, provide empty object if still undefined
|
|
285
|
+
if (param.optional && value === undefined) {
|
|
286
|
+
return {};
|
|
287
|
+
}
|
|
288
|
+
return value;
|
|
289
|
+
})
|
|
290
|
+
: [paramsObj]; // Fallback: pass entire params object if no signature info
|
|
291
|
+
if (methodName === 'getAll') {
|
|
292
|
+
console.log('[MoleculerService] getAll args to be passed:', JSON.stringify(args, null, 2));
|
|
293
|
+
}
|
|
294
|
+
return method.apply(service, args);
|
|
295
|
+
},
|
|
296
|
+
};
|
|
297
|
+
// Merge custom action config if provided (cache, visibility, etc.)
|
|
298
|
+
if (customActionConfig) {
|
|
299
|
+
Object.assign(action, customActionConfig);
|
|
300
|
+
}
|
|
301
|
+
actions[key] = action;
|
|
302
|
+
});
|
|
303
|
+
return actions;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Generate both actions AND events from a service instance
|
|
307
|
+
* - Actions: Generated from regular service methods
|
|
308
|
+
* - Events: Generated from methods marked with @MoleculerEventHandler decorator
|
|
309
|
+
*
|
|
310
|
+
* @param service - The service instance to wrap
|
|
311
|
+
* @param config - Configuration for actions and events
|
|
312
|
+
* @returns Object with both actions and events
|
|
313
|
+
*
|
|
314
|
+
* @example
|
|
315
|
+
* ```typescript
|
|
316
|
+
* // Service with decorator
|
|
317
|
+
* class OrganizationService {
|
|
318
|
+
* // Regular method becomes action
|
|
319
|
+
* async createOrganization(org: Org): Promise<Org> { }
|
|
320
|
+
*
|
|
321
|
+
* // Decorated method becomes event handler
|
|
322
|
+
* @MoleculerEventHandler(UserBroadcasterAction.OnUserCreated)
|
|
323
|
+
* async onUserCreated(event: UserEvent): Promise<void> { }
|
|
324
|
+
* }
|
|
325
|
+
*
|
|
326
|
+
* // Generate both
|
|
327
|
+
* const { actions, events } = generateServiceActionsAndEvents(service);
|
|
328
|
+
* ```
|
|
329
|
+
*/
|
|
330
|
+
function generateServiceActionsAndEvents(service, config = {}) {
|
|
331
|
+
// Get event handlers from decorator metadata
|
|
332
|
+
const eventHandlers = Moleculer.getEventHandlers(service);
|
|
333
|
+
const eventHandlerMethods = new Set(eventHandlers.map((h) => h.methodName));
|
|
334
|
+
// Generate actions (excluding event handler methods)
|
|
335
|
+
const actionsConfig = {
|
|
336
|
+
...config,
|
|
337
|
+
exclude: [...(config.exclude || []), ...Array.from(eventHandlerMethods)],
|
|
338
|
+
};
|
|
339
|
+
const actions = generateAutoInferredServiceActions(service, actionsConfig);
|
|
340
|
+
// Generate events from decorated methods
|
|
341
|
+
const events = {};
|
|
342
|
+
eventHandlers.forEach((metadata) => {
|
|
343
|
+
const method = service[metadata.methodName];
|
|
344
|
+
if (typeof method === 'function') {
|
|
345
|
+
events[metadata.eventName] = {
|
|
346
|
+
handler: async (ctx) => {
|
|
347
|
+
// Event payload is typically wrapped in ctx.params.event
|
|
348
|
+
const eventData = ctx.params.event || ctx.params;
|
|
349
|
+
await method.call(service, eventData);
|
|
350
|
+
// Explicitly return void for Moleculer event handler signature
|
|
351
|
+
},
|
|
352
|
+
...(metadata.group ? { group: metadata.group } : {}),
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
});
|
|
356
|
+
return { actions, events };
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Automatically generate Moleculer actions from a service instance.
|
|
360
|
+
*
|
|
361
|
+
* This eliminates the need to write repetitive action handlers - just pass your service
|
|
362
|
+
* and it will create handlers that forward all calls automatically.
|
|
363
|
+
*
|
|
364
|
+
* @param service - The service instance to wrap
|
|
365
|
+
* @param config - Optional configuration for customizing actions
|
|
366
|
+
* @returns Actions object with handlers for all service methods
|
|
367
|
+
*
|
|
368
|
+
* @example
|
|
369
|
+
* ```typescript
|
|
370
|
+
* const actions = generateServiceActions(accountService, {
|
|
371
|
+
* params: {
|
|
372
|
+
* findAccountById: { id: 'string' },
|
|
373
|
+
* createAccount: { account: 'object' }
|
|
374
|
+
* },
|
|
375
|
+
* exclude: ['get', 'getAll'] // Handle these manually
|
|
376
|
+
* });
|
|
377
|
+
* ```
|
|
378
|
+
*/
|
|
379
|
+
function generateServiceActions(service, config = {}) {
|
|
380
|
+
const { params = {}, exclude = [], actionToMethodMap = {} } = config;
|
|
381
|
+
const actions = {};
|
|
382
|
+
// Get all methods from the service
|
|
383
|
+
const allKeys = Object.getOwnPropertyNames(Object.getPrototypeOf(service));
|
|
384
|
+
const generatedMethods = [];
|
|
385
|
+
allKeys.forEach((key) => {
|
|
386
|
+
// Skip excluded methods, constructors, and private methods
|
|
387
|
+
if (exclude.includes(key) || key === 'constructor' || key.startsWith('_')) {
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
const method = service[key];
|
|
391
|
+
// Only process functions
|
|
392
|
+
if (typeof method !== 'function') {
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
// Determine the method name to call (in case of mapping)
|
|
396
|
+
const methodName = actionToMethodMap[key] || key;
|
|
397
|
+
const serviceMethod = service[methodName];
|
|
398
|
+
if (typeof serviceMethod !== 'function') {
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
generatedMethods.push(key);
|
|
402
|
+
// Create the action handler
|
|
403
|
+
actions[key] = {
|
|
404
|
+
...(params[key] ? { params: params[key] } : {}),
|
|
405
|
+
handler: (ctx) => {
|
|
406
|
+
// Call the service method with ctx.params spread as arguments
|
|
407
|
+
const method = service[methodName];
|
|
408
|
+
// If params is an object with known keys, extract them in order
|
|
409
|
+
// Otherwise, pass the whole params object
|
|
410
|
+
const paramsObj = ctx.params || {};
|
|
411
|
+
const values = Object.values(paramsObj);
|
|
412
|
+
return method.apply(service, values.length > 0 ? values : [paramsObj]);
|
|
413
|
+
},
|
|
414
|
+
};
|
|
415
|
+
});
|
|
416
|
+
// In development, log methods that don't have param validation
|
|
417
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
418
|
+
const methodsWithoutParams = generatedMethods.filter((method) => !params[method]);
|
|
419
|
+
if (methodsWithoutParams.length > 0) {
|
|
420
|
+
console.warn(`⚠️ [generateServiceActions] The following methods don't have param validation defined:`, methodsWithoutParams);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
return actions;
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* TYPE-SAFE version: Generate Moleculer actions with COMPILE-TIME verification.
|
|
427
|
+
* TypeScript will error if any service method is missing from params.
|
|
428
|
+
*
|
|
429
|
+
* @param service - The service instance to wrap
|
|
430
|
+
* @param config - Type-safe configuration requiring ALL methods to have params
|
|
431
|
+
* @returns Actions object with handlers for all service methods
|
|
432
|
+
*
|
|
433
|
+
* @example
|
|
434
|
+
* ```typescript
|
|
435
|
+
* const actions = generateTypeSafeServiceActions<IAccountService>(accountService, {
|
|
436
|
+
* params: {
|
|
437
|
+
* // TypeScript enforces ALL IAccountService methods are here!
|
|
438
|
+
* findAccountById: { id: 'string' },
|
|
439
|
+
* createAccount: { account: 'object' },
|
|
440
|
+
* // ... if you forget any method, TypeScript will error
|
|
441
|
+
* }
|
|
442
|
+
* });
|
|
443
|
+
* ```
|
|
444
|
+
*/
|
|
445
|
+
function generateTypeSafeServiceActions(service, config) {
|
|
446
|
+
// Delegate to the regular function - type checking happens at compile time
|
|
447
|
+
return generateServiceActions(service, config);
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Verify that all service methods have param validation defined.
|
|
451
|
+
* Throws an error if any methods are missing params.
|
|
452
|
+
*
|
|
453
|
+
* Use this in development to ensure you haven't forgotten any param schemas.
|
|
454
|
+
*
|
|
455
|
+
* @param service - The service instance
|
|
456
|
+
* @param config - The config used for generateServiceActions
|
|
457
|
+
* @throws Error if any methods are missing param validation
|
|
458
|
+
*
|
|
459
|
+
* @example
|
|
460
|
+
* ```typescript
|
|
461
|
+
* const config = { params: { ... }, exclude: [...] };
|
|
462
|
+
* verifyAllParamsDefined(accountService, config); // Throws if params missing
|
|
463
|
+
* const actions = generateServiceActions(accountService, config);
|
|
464
|
+
* ```
|
|
465
|
+
*/
|
|
466
|
+
function verifyAllParamsDefined(service, config = {}) {
|
|
467
|
+
const { params = {}, exclude = [] } = config;
|
|
468
|
+
const allKeys = Object.getOwnPropertyNames(Object.getPrototypeOf(service));
|
|
469
|
+
const missingParams = [];
|
|
470
|
+
allKeys.forEach((key) => {
|
|
471
|
+
// Skip excluded methods, constructors, and private methods
|
|
472
|
+
if (exclude.includes(key) || key === 'constructor' || key.startsWith('_')) {
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
const method = service[key];
|
|
476
|
+
// Only check functions
|
|
477
|
+
if (typeof method !== 'function') {
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
// Check if params defined
|
|
481
|
+
if (!params[key]) {
|
|
482
|
+
missingParams.push(key);
|
|
483
|
+
}
|
|
484
|
+
});
|
|
485
|
+
if (missingParams.length > 0) {
|
|
486
|
+
const errorMessage = [
|
|
487
|
+
`Missing param validation for methods: ${missingParams.join(', ')}`,
|
|
488
|
+
'',
|
|
489
|
+
'Add these to your params config:',
|
|
490
|
+
...missingParams.map((method) => ` ${method}: { /* your params */ },`),
|
|
491
|
+
].join('\n');
|
|
492
|
+
throw new Error(errorMessage);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Helper to create a typed action handler
|
|
497
|
+
*/
|
|
498
|
+
function createTypedAction(action) {
|
|
499
|
+
return action;
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* DEBUG UTILITY: Dumps parameter information for all service methods
|
|
503
|
+
*
|
|
504
|
+
* This function extracts and logs parameter names, types, and inferred schemas
|
|
505
|
+
* for debugging auto-generation issues. Use during development to understand
|
|
506
|
+
* what the auto-generation sees and optimize paramOverrides.
|
|
507
|
+
*
|
|
508
|
+
* @param service - The service instance to analyze
|
|
509
|
+
* @param config - Optional configuration to see what would be generated
|
|
510
|
+
* @returns Object with detailed parameter information for each method
|
|
511
|
+
*
|
|
512
|
+
* @example
|
|
513
|
+
* ```typescript
|
|
514
|
+
* // In development/debug mode
|
|
515
|
+
* const paramInfo = Moleculer.debugServiceParams(accountService);
|
|
516
|
+
* console.log(JSON.stringify(paramInfo, null, 2));
|
|
517
|
+
*
|
|
518
|
+
* // With config to see filtered results
|
|
519
|
+
* const paramInfo = Moleculer.debugServiceParams(accountService, {
|
|
520
|
+
* exclude: ['dispose', 'createUserToken']
|
|
521
|
+
* });
|
|
522
|
+
* ```
|
|
523
|
+
*/
|
|
524
|
+
function debugServiceParams(service, config = {}) {
|
|
525
|
+
const { paramOverrides = {}, include, exclude = [] } = config;
|
|
526
|
+
const result = {};
|
|
527
|
+
// Get all methods from the service, including inherited methods
|
|
528
|
+
const allKeys = getAllMethodNames(service);
|
|
529
|
+
// Get event handler methods
|
|
530
|
+
const eventHandlers = Moleculer.getEventHandlers(service);
|
|
531
|
+
const eventHandlerMethods = new Set(eventHandlers.map((h) => h.methodName));
|
|
532
|
+
allKeys.forEach((key) => {
|
|
533
|
+
// Skip constructor and private methods
|
|
534
|
+
if (key === 'constructor' || key.startsWith('_')) {
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
const method = service[key];
|
|
538
|
+
if (typeof method !== 'function') {
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
// Determine if this method would be excluded
|
|
542
|
+
const isEventHandler = eventHandlerMethods.has(key);
|
|
543
|
+
let isExcluded = false;
|
|
544
|
+
if (include && include.length > 0) {
|
|
545
|
+
isExcluded = !include.includes(key);
|
|
546
|
+
}
|
|
547
|
+
else {
|
|
548
|
+
isExcluded = exclude.includes(key) || isEventHandler;
|
|
549
|
+
}
|
|
550
|
+
// Get function signature
|
|
551
|
+
const funcStr = method.toString();
|
|
552
|
+
const paramsWithTypes = extractParamsWithTypes(funcStr);
|
|
553
|
+
// Extract just the function signature (first line with params)
|
|
554
|
+
const signatureMatch = funcStr.match(/^(?:async\s+)?(?:function\s+)?(?:\w+\s*)?\(([^)]*)\)/);
|
|
555
|
+
const signature = signatureMatch ? signatureMatch[0] : funcStr.split('{')[0].trim();
|
|
556
|
+
// Build inferred schema using new type inference
|
|
557
|
+
let inferredSchema;
|
|
558
|
+
if (paramsWithTypes.length > 0) {
|
|
559
|
+
inferredSchema = paramsWithTypes.reduce((acc, param) => {
|
|
560
|
+
if (param.optional) {
|
|
561
|
+
acc[param.name] = { type: param.type, optional: true };
|
|
562
|
+
}
|
|
563
|
+
else {
|
|
564
|
+
acc[param.name] = param.type;
|
|
565
|
+
}
|
|
566
|
+
return acc;
|
|
567
|
+
}, {});
|
|
568
|
+
}
|
|
569
|
+
// Get override schema if provided
|
|
570
|
+
const overrideSchema = paramOverrides[key];
|
|
571
|
+
result[key] = {
|
|
572
|
+
methodName: key,
|
|
573
|
+
paramNames: paramsWithTypes.map((p) => p.name),
|
|
574
|
+
functionSignature: signature,
|
|
575
|
+
inferredSchema,
|
|
576
|
+
overrideSchema,
|
|
577
|
+
isExcluded,
|
|
578
|
+
isEventHandler,
|
|
579
|
+
};
|
|
580
|
+
});
|
|
581
|
+
return result;
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* DEBUG UTILITY: Pretty prints service parameter information to console
|
|
585
|
+
*
|
|
586
|
+
* Formats and logs the output of debugServiceParams() in a readable way.
|
|
587
|
+
* Shows which methods need paramOverrides and what types are inferred.
|
|
588
|
+
*
|
|
589
|
+
* @param service - The service instance to analyze
|
|
590
|
+
* @param config - Optional configuration
|
|
591
|
+
* @param options - Display options
|
|
592
|
+
*
|
|
593
|
+
* @example
|
|
594
|
+
* ```typescript
|
|
595
|
+
* // Print all methods
|
|
596
|
+
* Moleculer.printServiceParams(accountService);
|
|
597
|
+
*
|
|
598
|
+
* // Print only methods without overrides
|
|
599
|
+
* Moleculer.printServiceParams(accountService, config, { onlyMissingOverrides: true });
|
|
600
|
+
*
|
|
601
|
+
* // Print only included methods
|
|
602
|
+
* Moleculer.printServiceParams(accountService, config, { onlyIncluded: true });
|
|
603
|
+
* ```
|
|
604
|
+
*/
|
|
605
|
+
function printServiceParams(service, config = {}, options = {}) {
|
|
606
|
+
const paramInfo = debugServiceParams(service, config);
|
|
607
|
+
const methods = Object.values(paramInfo);
|
|
608
|
+
const separator = '='.repeat(80);
|
|
609
|
+
const dashedLine = '-'.repeat(80);
|
|
610
|
+
console.log(`\n${separator}`);
|
|
611
|
+
console.log('SERVICE PARAMETER DEBUG INFORMATION');
|
|
612
|
+
console.log(`${separator}\n`);
|
|
613
|
+
// Summary statistics
|
|
614
|
+
const totalMethods = methods.length;
|
|
615
|
+
const includedMethods = methods.filter((m) => !m.isExcluded);
|
|
616
|
+
const eventHandlers = methods.filter((m) => m.isEventHandler);
|
|
617
|
+
const withOverrides = methods.filter((m) => m.overrideSchema);
|
|
618
|
+
const withoutOverrides = includedMethods.filter((m) => !m.overrideSchema && !m.isExcluded);
|
|
619
|
+
console.log('📊 SUMMARY:');
|
|
620
|
+
console.log(` Total methods found: ${totalMethods}`);
|
|
621
|
+
console.log(` Included in actions: ${includedMethods.length}`);
|
|
622
|
+
console.log(` Event handlers (excluded from actions): ${eventHandlers.length}`);
|
|
623
|
+
console.log(` With param overrides: ${withOverrides.length}`);
|
|
624
|
+
console.log(` Without param overrides: ${withoutOverrides.length}`);
|
|
625
|
+
console.log(`\n${dashedLine}\n`);
|
|
626
|
+
// Filter methods based on options
|
|
627
|
+
let displayMethods = methods;
|
|
628
|
+
if (options.onlyMissingOverrides) {
|
|
629
|
+
displayMethods = displayMethods.filter((m) => !m.overrideSchema && !m.isExcluded);
|
|
630
|
+
}
|
|
631
|
+
if (options.onlyIncluded) {
|
|
632
|
+
displayMethods = displayMethods.filter((m) => !m.isExcluded);
|
|
633
|
+
}
|
|
634
|
+
if (!options.showExcluded) {
|
|
635
|
+
displayMethods = displayMethods.filter((m) => !m.isExcluded);
|
|
636
|
+
}
|
|
637
|
+
// Print each method
|
|
638
|
+
displayMethods.forEach((info, index) => {
|
|
639
|
+
let status;
|
|
640
|
+
if (info.isExcluded) {
|
|
641
|
+
status = '❌ EXCLUDED';
|
|
642
|
+
}
|
|
643
|
+
else if (info.isEventHandler) {
|
|
644
|
+
status = '📡 EVENT HANDLER';
|
|
645
|
+
}
|
|
646
|
+
else if (info.overrideSchema) {
|
|
647
|
+
status = '✅ HAS OVERRIDE';
|
|
648
|
+
}
|
|
649
|
+
else {
|
|
650
|
+
status = '⚠️ NEEDS OVERRIDE';
|
|
651
|
+
}
|
|
652
|
+
console.log(`${index + 1}. ${info.methodName} ${status}`);
|
|
653
|
+
console.log(` Signature: ${info.functionSignature}`);
|
|
654
|
+
console.log(` Parameters: [${info.paramNames.join(', ')}]`);
|
|
655
|
+
if (info.inferredSchema) {
|
|
656
|
+
console.log(` Inferred: ${JSON.stringify(info.inferredSchema)}`);
|
|
657
|
+
}
|
|
658
|
+
if (info.overrideSchema) {
|
|
659
|
+
console.log(` Override: ${JSON.stringify(info.overrideSchema)}`);
|
|
660
|
+
}
|
|
661
|
+
console.log('');
|
|
662
|
+
});
|
|
663
|
+
// Suggestions
|
|
664
|
+
if (withoutOverrides.length > 0 && !options.onlyMissingOverrides) {
|
|
665
|
+
console.log(`\n${separator}`);
|
|
666
|
+
console.log('💡 SUGGESTIONS:');
|
|
667
|
+
console.log(`${separator}\n`);
|
|
668
|
+
console.log('The following methods use default "object" validation:');
|
|
669
|
+
console.log('Consider adding paramOverrides for better type safety:\n');
|
|
670
|
+
const suggestions = [];
|
|
671
|
+
withoutOverrides.forEach((info) => {
|
|
672
|
+
const params = info.paramNames.map((p) => `${p}: 'string'`).join(', ');
|
|
673
|
+
suggestions.push(` ${info.methodName}: { ${params} },`);
|
|
674
|
+
});
|
|
675
|
+
console.log('paramOverrides: {');
|
|
676
|
+
console.log(suggestions.join('\n'));
|
|
677
|
+
console.log('}');
|
|
678
|
+
}
|
|
679
|
+
console.log(`\n${separator}\n`);
|
|
680
|
+
}
|
|
681
|
+
// Implement the namespace extensions
|
|
682
|
+
Moleculer.generateAutoInferredActions = generateAutoInferredServiceActions;
|
|
683
|
+
Moleculer.generateActionsAndEvents = generateServiceActionsAndEvents;
|
|
684
|
+
Moleculer.debugServiceParams = debugServiceParams;
|
|
685
|
+
Moleculer.printServiceParams = printServiceParams;export{createTypedAction,debugServiceParams,generateAutoInferredServiceActions,generateServiceActions,generateServiceActionsAndEvents,generateTypeSafeServiceActions,printServiceParams,verifyAllParamsDefined};//# sourceMappingURL=typedMoleculerService.js.map
|