@motiadev/core 0.0.6 → 0.0.7-build.20250529212805

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 (124) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +142 -0
  3. package/dist/index.d.ts +13 -8
  4. package/dist/index.js +28 -8
  5. package/dist/src/call-step-file.d.ts +17 -2
  6. package/dist/src/call-step-file.js +88 -47
  7. package/dist/src/cron-handler.d.ts +13 -0
  8. package/dist/src/cron-handler.js +98 -0
  9. package/dist/src/event-manager.js +10 -5
  10. package/dist/src/flows-config-endpoint.d.ts +2 -0
  11. package/dist/src/flows-config-endpoint.js +51 -0
  12. package/dist/src/flows-endpoint.d.ts +11 -7
  13. package/dist/src/flows-endpoint.js +53 -22
  14. package/dist/src/generate-trace-id.d.ts +2 -0
  15. package/dist/src/generate-trace-id.js +14 -0
  16. package/dist/src/get-step-config.d.ts +4 -0
  17. package/dist/src/get-step-config.js +88 -0
  18. package/dist/src/guards.d.ts +3 -2
  19. package/dist/src/guards.js +3 -1
  20. package/dist/src/locked-data.d.ts +60 -0
  21. package/dist/src/locked-data.js +278 -0
  22. package/dist/src/logger-factory.d.ts +15 -0
  23. package/dist/src/logger-factory.js +14 -0
  24. package/dist/src/logger.d.ts +21 -15
  25. package/dist/src/logger.js +49 -29
  26. package/dist/src/mermaid-generator.d.ts +4 -0
  27. package/dist/src/mermaid-generator.js +203 -0
  28. package/dist/src/node/get-config.d.ts +1 -2
  29. package/dist/src/node/get-config.js +51 -8
  30. package/dist/src/node/logger.d.ts +10 -6
  31. package/dist/src/node/logger.js +27 -16
  32. package/dist/src/node/middleware-compose.d.ts +1 -0
  33. package/dist/src/node/middleware-compose.js +12 -0
  34. package/dist/src/node/node-runner.js +28 -9
  35. package/dist/src/node/rpc-state-manager.d.ts +3 -2
  36. package/dist/src/node/rpc-state-manager.js +5 -2
  37. package/dist/src/node/rpc.d.ts +3 -1
  38. package/dist/src/node/rpc.js +21 -3
  39. package/dist/src/pretty-print.d.ts +1 -0
  40. package/dist/src/pretty-print.js +66 -0
  41. package/dist/src/printer.d.ts +45 -0
  42. package/dist/src/printer.js +121 -0
  43. package/dist/src/process-communication/communication-config.d.ts +7 -0
  44. package/dist/src/process-communication/communication-config.js +12 -0
  45. package/dist/src/process-communication/process-manager.d.ts +30 -0
  46. package/dist/src/process-communication/process-manager.js +88 -0
  47. package/dist/src/process-communication/rpc-processor-interface.d.ts +9 -0
  48. package/dist/src/process-communication/rpc-processor-interface.js +2 -0
  49. package/dist/src/python/communication_factory.py +35 -0
  50. package/dist/src/python/context.py +21 -0
  51. package/dist/src/python/get-config.py +31 -13
  52. package/dist/src/python/ipc_communication.py +145 -0
  53. package/dist/src/python/logger.py +4 -6
  54. package/dist/src/python/middleware.py +17 -0
  55. package/dist/src/python/python-runner.py +105 -39
  56. package/dist/src/python/rpc.py +33 -68
  57. package/dist/src/python/rpc_communication.py +125 -0
  58. package/dist/src/python/rpc_state_manager.py +49 -11
  59. package/dist/src/python/type_definitions.py +34 -0
  60. package/dist/src/python/validation.py +56 -0
  61. package/dist/src/ruby/get-config.rb +61 -0
  62. package/dist/src/ruby/logger.rb +21 -16
  63. package/dist/src/ruby/rpc.rb +118 -0
  64. package/dist/src/ruby/rpc_state_manager.rb +41 -0
  65. package/dist/src/ruby/ruby-runner.rb +94 -0
  66. package/dist/src/server.d.ts +14 -12
  67. package/dist/src/server.js +149 -28
  68. package/dist/src/socket-server.d.ts +39 -0
  69. package/dist/src/socket-server.js +76 -0
  70. package/dist/src/state/adapters/default-state-adapter.d.ts +7 -3
  71. package/dist/src/state/adapters/default-state-adapter.js +37 -14
  72. package/dist/src/state/adapters/memory-state-adapter.d.ts +14 -0
  73. package/dist/src/state/adapters/memory-state-adapter.js +58 -0
  74. package/dist/src/state/create-state-adapter.d.ts +5 -6
  75. package/dist/src/state/create-state-adapter.js +2 -10
  76. package/dist/src/state/state-adapter.d.ts +4 -4
  77. package/dist/src/state-stream.d.ts +19 -0
  78. package/dist/src/state-stream.js +28 -0
  79. package/dist/src/step-handler-rpc-processor.d.ts +13 -4
  80. package/dist/src/step-handler-rpc-processor.js +33 -3
  81. package/dist/src/step-handler-rpc-stdin-processor.d.ts +22 -0
  82. package/dist/src/step-handler-rpc-stdin-processor.js +84 -0
  83. package/dist/src/step-handlers.d.ts +7 -2
  84. package/dist/src/step-handlers.js +47 -19
  85. package/dist/src/step-validator.d.ts +14 -0
  86. package/dist/src/step-validator.js +138 -0
  87. package/dist/src/steps/emit.step.d.ts +11 -0
  88. package/dist/src/steps/emit.step.js +27 -0
  89. package/dist/src/steps/emit.step.ts +34 -0
  90. package/dist/src/steps/index.d.ts +2 -0
  91. package/dist/src/steps/index.js +16 -0
  92. package/dist/src/streams/api-endpoints.d.ts +2 -0
  93. package/dist/src/streams/api-endpoints.js +71 -0
  94. package/dist/src/streams/flows-stream.d.ts +14 -0
  95. package/dist/src/streams/flows-stream.js +29 -0
  96. package/dist/src/streams/logs-stream.d.ts +16 -0
  97. package/dist/src/streams/logs-stream.js +22 -0
  98. package/dist/src/types/generate-type-from-schema.d.ts +2 -0
  99. package/dist/src/types/generate-type-from-schema.js +28 -0
  100. package/dist/src/types/generate-types-from-response.d.ts +2 -0
  101. package/dist/src/types/generate-types-from-response.js +13 -0
  102. package/dist/src/types/generate-types.d.ts +12 -0
  103. package/dist/src/types/generate-types.js +108 -0
  104. package/dist/src/types/merge-schemas.d.ts +3 -0
  105. package/dist/src/types/merge-schemas.js +59 -0
  106. package/dist/src/types/schema.types.d.ts +20 -0
  107. package/dist/src/types/schema.types.js +10 -0
  108. package/dist/src/types-stream.d.ts +34 -0
  109. package/dist/src/types-stream.js +2 -0
  110. package/dist/src/types.d.ts +93 -47
  111. package/dist/src/utils.d.ts +2 -0
  112. package/dist/src/utils.js +12 -0
  113. package/package.json +20 -9
  114. package/requirements.txt +1 -0
  115. package/dist/src/node/get-module-export.d.ts +0 -1
  116. package/dist/src/node/get-module-export.js +0 -63
  117. package/dist/src/python/get-python-config.d.ts +0 -2
  118. package/dist/src/python/get-python-config.js +0 -34
  119. package/dist/src/ruby/get_config.rb +0 -78
  120. package/dist/src/ruby/ruby_runner.rb +0 -80
  121. package/dist/src/ruby/state_adapter.rb +0 -62
  122. package/dist/src/state/adapters/redis-state-adapter.d.ts +0 -19
  123. package/dist/src/state/adapters/redis-state-adapter.js +0 -44
  124. package/tsconfig.json +0 -20
@@ -1,23 +1,29 @@
1
- import { Server } from 'socket.io';
2
- declare class BaseLogger {
3
- private logger;
4
- constructor(meta?: any);
5
- info(message: string, args?: any): void;
6
- error(message: string, args?: any): void;
7
- debug(message: string, args?: any): void;
8
- warn(message: string, args?: any): void;
1
+ import { Log } from './streams/logs-stream';
2
+ import { StateStream } from './state-stream';
3
+ export declare class BaseLogger {
4
+ readonly isVerbose: boolean;
5
+ private readonly meta;
6
+ constructor(isVerbose?: boolean, meta?: Record<string, unknown>);
7
+ child(meta?: Record<string, unknown>): this;
8
+ private _log;
9
+ info(message: string, args?: unknown): void;
10
+ error(message: string, args?: unknown): void;
11
+ debug(message: string, args?: unknown): void;
12
+ warn(message: string, args?: unknown): void;
13
+ log(args: any): void;
9
14
  }
10
15
  export declare class Logger extends BaseLogger {
11
16
  private readonly traceId;
12
17
  private readonly flows;
13
- private readonly file;
18
+ private readonly step;
19
+ private readonly logStream?;
14
20
  private emitLog;
15
- constructor(traceId: string, flows: string[], file: string, socketServer?: Server);
21
+ constructor(traceId: string, flows: string[] | undefined, step: string, isVerbose: boolean, logStream?: StateStream<Log> | undefined);
22
+ child(meta?: Record<string, unknown>): this;
16
23
  log(message: any): void;
17
- info: (message: string, args?: any) => void;
18
- error: (message: string, args?: any) => void;
19
- debug: (message: string, args?: any) => void;
20
- warn: (message: string, args?: any) => void;
24
+ info: (message: string, args?: unknown) => void;
25
+ error: (message: string, args?: unknown) => void;
26
+ debug: (message: string, args?: unknown) => void;
27
+ warn: (message: string, args?: unknown) => void;
21
28
  }
22
29
  export declare const globalLogger: BaseLogger;
23
- export {};
@@ -1,39 +1,56 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.globalLogger = exports.Logger = void 0;
7
- const pino_1 = __importDefault(require("pino"));
8
- const isDebugEnabled = () => process.env.LOG_LEVEL === 'debug';
3
+ exports.globalLogger = exports.Logger = exports.BaseLogger = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const pretty_print_1 = require("./pretty-print");
6
+ const logLevel = process.env.LOG_LEVEL ?? 'info';
7
+ const isDebugEnabled = logLevel === 'debug';
8
+ const isInfoEnabled = ['info', 'debug'].includes(logLevel);
9
+ const isWarnEnabled = ['warn', 'info', 'debug', 'trace'].includes(logLevel);
9
10
  class BaseLogger {
10
- constructor(meta = {}) {
11
- this.logger = (0, pino_1.default)({
12
- level: process.env.LOG_LEVEL || 'info',
13
- formatters: { level: (level) => ({ level }) },
14
- base: null,
15
- mixin: () => meta,
16
- });
11
+ constructor(isVerbose = false, meta = {}) {
12
+ this.isVerbose = isVerbose;
13
+ this.meta = meta;
14
+ }
15
+ child(meta = {}) {
16
+ return new BaseLogger(this.isVerbose, { ...this.meta, ...meta });
17
+ }
18
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
19
+ _log(level, msg, args) {
20
+ const time = Date.now();
21
+ (0, pretty_print_1.prettyPrint)({ level, time, msg, ...this.meta, ...(args ?? {}) }, !this.isVerbose);
17
22
  }
18
23
  info(message, args) {
19
- this.logger.info(args, message);
24
+ if (isInfoEnabled) {
25
+ this._log('info', message, args);
26
+ }
20
27
  }
21
28
  error(message, args) {
22
- this.logger.error(args, message);
29
+ this._log('error', message, args);
23
30
  }
24
31
  debug(message, args) {
25
- this.logger.debug(args, message);
32
+ if (isDebugEnabled) {
33
+ this._log('debug', message, args);
34
+ }
26
35
  }
27
36
  warn(message, args) {
28
- this.logger.warn(args, message);
37
+ if (isWarnEnabled) {
38
+ this._log('warn', message, args);
39
+ }
40
+ }
41
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
42
+ log(args) {
43
+ this._log('info', args.msg, args);
29
44
  }
30
45
  }
46
+ exports.BaseLogger = BaseLogger;
31
47
  class Logger extends BaseLogger {
32
- constructor(traceId, flows, file, socketServer) {
33
- super({ traceId, flows, file });
48
+ constructor(traceId, flows, step, isVerbose, logStream) {
49
+ super(isVerbose, { traceId, flows, step });
34
50
  this.traceId = traceId;
35
51
  this.flows = flows;
36
- this.file = file;
52
+ this.step = step;
53
+ this.logStream = logStream;
37
54
  this.info = (message, args) => {
38
55
  super.info(message, args);
39
56
  this.emitLog('info', message, args);
@@ -43,8 +60,8 @@ class Logger extends BaseLogger {
43
60
  this.emitLog('error', message, args);
44
61
  };
45
62
  this.debug = (message, args) => {
46
- super.debug(message, args);
47
- if (isDebugEnabled()) {
63
+ if (isDebugEnabled) {
64
+ super.debug(message, args);
48
65
  this.emitLog('debug', message, args);
49
66
  }
50
67
  };
@@ -53,22 +70,25 @@ class Logger extends BaseLogger {
53
70
  this.emitLog('warn', message, args);
54
71
  };
55
72
  this.emitLog = (level, msg, args) => {
56
- if (!socketServer) {
57
- return;
58
- }
59
- socketServer.emit('log', {
60
- file: this.file,
73
+ const id = (0, crypto_1.randomUUID)();
74
+ this.logStream?.set('default', id, {
75
+ id,
76
+ step: this.step,
61
77
  ...(args ?? {}),
62
78
  level,
63
79
  time: Date.now(),
64
80
  msg,
65
81
  traceId: this.traceId,
66
- flows: this.flows,
82
+ flows: this.flows ?? [],
67
83
  });
68
84
  };
69
85
  }
86
+ child(meta = {}) {
87
+ return new Logger(this.traceId, this.flows, meta.step, this.isVerbose, this.logStream);
88
+ }
89
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
70
90
  log(message) {
71
- console.log(JSON.stringify(message));
91
+ super.log(message);
72
92
  this.emitLog(message.level, message.msg, message);
73
93
  }
74
94
  }
@@ -0,0 +1,4 @@
1
+ import { LockedData } from './locked-data';
2
+ export declare const createMermaidGenerator: (baseDir: string) => {
3
+ initialize: (lockedData: LockedData) => void;
4
+ };
@@ -0,0 +1,203 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createMermaidGenerator = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const guards_1 = require("./guards");
10
+ // Pure function to ensure diagrams directory exists
11
+ const ensureDiagramsDirectory = (diagramsDir) => {
12
+ if (!fs_1.default.existsSync(diagramsDir)) {
13
+ fs_1.default.mkdirSync(diagramsDir, { recursive: true });
14
+ }
15
+ };
16
+ // Pure function to get node ID
17
+ const getNodeId = (step, baseDir) => {
18
+ // Get relative path from the base directory
19
+ const relativePath = path_1.default.relative(baseDir, step.filePath);
20
+ // Remove common file extensions
21
+ const pathWithoutExtension = relativePath.replace(/\.(ts|js|tsx|jsx)$/, '');
22
+ // Replace slashes with underscores and dots with underscores
23
+ // Only keep alphanumeric characters and underscores
24
+ return pathWithoutExtension.replace(/[^a-zA-Z0-9]/g, '_');
25
+ };
26
+ // Pure function to get node label
27
+ const getNodeLabel = (step) => {
28
+ // Get display name for node
29
+ const displayName = step.config.name || path_1.default.basename(step.filePath, path_1.default.extname(step.filePath));
30
+ // Add node type prefix to help distinguish types
31
+ let prefix = '';
32
+ if ((0, guards_1.isApiStep)(step))
33
+ prefix = '🌐 ';
34
+ else if ((0, guards_1.isEventStep)(step))
35
+ prefix = '⚡ ';
36
+ else if ((0, guards_1.isCronStep)(step))
37
+ prefix = '⏰ ';
38
+ else if ((0, guards_1.isNoopStep)(step))
39
+ prefix = '⚙️ ';
40
+ // Create a node label with the step name
41
+ return `["${prefix}${displayName}"]`;
42
+ };
43
+ // Pure function to get node style
44
+ const getNodeStyle = (step) => {
45
+ // Apply style class based on step type
46
+ if ((0, guards_1.isApiStep)(step))
47
+ return ':::apiStyle';
48
+ if ((0, guards_1.isEventStep)(step))
49
+ return ':::eventStyle';
50
+ if ((0, guards_1.isCronStep)(step))
51
+ return ':::cronStyle';
52
+ if ((0, guards_1.isNoopStep)(step))
53
+ return ':::noopStyle';
54
+ return '';
55
+ };
56
+ // Pure function to generate connections
57
+ const generateConnections = (emits, sourceStep, steps, sourceId, baseDir) => {
58
+ const connections = [];
59
+ if (!emits || !Array.isArray(emits) || emits.length === 0) {
60
+ return '';
61
+ }
62
+ // Helper function to check if a step subscribes to a topic
63
+ const stepSubscribesToTopic = (step, topic) => {
64
+ // Event steps use regular subscribes
65
+ if ((0, guards_1.isEventStep)(step) &&
66
+ step.config.subscribes &&
67
+ Array.isArray(step.config.subscribes) &&
68
+ step.config.subscribes.includes(topic)) {
69
+ return true;
70
+ }
71
+ // Noop and API steps use virtualSubscribes
72
+ if (((0, guards_1.isNoopStep)(step) || (0, guards_1.isApiStep)(step)) &&
73
+ step.config.virtualSubscribes &&
74
+ Array.isArray(step.config.virtualSubscribes) &&
75
+ step.config.virtualSubscribes.includes(topic)) {
76
+ return true;
77
+ }
78
+ return false;
79
+ };
80
+ emits.forEach((emit) => {
81
+ const topic = typeof emit === 'string' ? emit : emit.topic;
82
+ const label = typeof emit === 'string' ? topic : emit.label || topic;
83
+ steps.forEach((targetStep) => {
84
+ if (stepSubscribesToTopic(targetStep, topic)) {
85
+ const targetId = getNodeId(targetStep, baseDir);
86
+ connections.push(` ${sourceId} -->|${label}| ${targetId}`);
87
+ }
88
+ });
89
+ });
90
+ return connections.join('\n');
91
+ };
92
+ // Pure function to generate flow diagram
93
+ const generateFlowDiagram = (flowName, steps, baseDir) => {
94
+ // Start mermaid flowchart with top-down direction
95
+ let diagram = `flowchart TD\n`;
96
+ // Add class definitions for styling with explicit text color
97
+ const classDefinitions = [
98
+ ` classDef apiStyle fill:#f96,stroke:#333,stroke-width:2px,color:#fff`,
99
+ ` classDef eventStyle fill:#69f,stroke:#333,stroke-width:2px,color:#fff`,
100
+ ` classDef cronStyle fill:#9c6,stroke:#333,stroke-width:2px,color:#fff`,
101
+ ` classDef noopStyle fill:#3f3a50,stroke:#333,stroke-width:2px,color:#fff`,
102
+ ];
103
+ diagram += classDefinitions.join('\n') + '\n';
104
+ // Check if we have any steps
105
+ if (!steps || steps.length === 0) {
106
+ return diagram + ' empty[No steps in this flow]';
107
+ }
108
+ // Create node definitions with proper format
109
+ steps.forEach((step) => {
110
+ const nodeId = getNodeId(step, baseDir);
111
+ const nodeLabel = getNodeLabel(step);
112
+ const nodeStyle = getNodeStyle(step);
113
+ diagram += ` ${nodeId}${nodeLabel}${nodeStyle}\n`;
114
+ });
115
+ // Create connections between nodes
116
+ let connectionsStr = '';
117
+ steps.forEach((sourceStep) => {
118
+ const sourceId = getNodeId(sourceStep, baseDir);
119
+ // Helper function to process emissions if they exist
120
+ function processEmissions(emissionsArray, stepSource, stepsCollection, sourceIdentifier) {
121
+ if (emissionsArray && Array.isArray(emissionsArray)) {
122
+ return generateConnections(emissionsArray, stepSource, stepsCollection, sourceIdentifier, baseDir);
123
+ }
124
+ return '';
125
+ }
126
+ // Semantic variables to clarify which step types support which emission types
127
+ const supportsEmits = (0, guards_1.isApiStep)(sourceStep) || (0, guards_1.isEventStep)(sourceStep) || (0, guards_1.isCronStep)(sourceStep);
128
+ const supportsVirtualEmits = supportsEmits || (0, guards_1.isNoopStep)(sourceStep);
129
+ // Process regular emissions if supported
130
+ if (supportsEmits) {
131
+ const emitConnections = processEmissions(sourceStep.config.emits, sourceStep, steps, sourceId);
132
+ if (emitConnections) {
133
+ connectionsStr += emitConnections + '\n';
134
+ }
135
+ }
136
+ // Process virtual emissions if supported
137
+ if (supportsVirtualEmits) {
138
+ const virtualEmitConnections = processEmissions(sourceStep.config.virtualEmits, sourceStep, steps, sourceId);
139
+ if (virtualEmitConnections) {
140
+ connectionsStr += virtualEmitConnections + '\n';
141
+ }
142
+ }
143
+ });
144
+ // Add connections to the diagram
145
+ diagram += connectionsStr;
146
+ return diagram;
147
+ };
148
+ // Function to save a diagram to a file
149
+ const saveDiagram = (diagramsDir, flowName, diagram) => {
150
+ const filePath = path_1.default.join(diagramsDir, `${flowName}.mmd`);
151
+ fs_1.default.writeFileSync(filePath, diagram);
152
+ };
153
+ // Function to remove a diagram file
154
+ const removeDiagram = (diagramsDir, flowName) => {
155
+ const filePath = path_1.default.join(diagramsDir, `${flowName}.mmd`);
156
+ if (fs_1.default.existsSync(filePath)) {
157
+ fs_1.default.unlinkSync(filePath);
158
+ }
159
+ };
160
+ // Function to generate and save a diagram
161
+ const generateAndSaveDiagram = (diagramsDir, flowName, flow, baseDir) => {
162
+ const diagram = generateFlowDiagram(flowName, flow.steps, baseDir);
163
+ saveDiagram(diagramsDir, flowName, diagram);
164
+ };
165
+ // Main exported function that creates the mermaid generator
166
+ const createMermaidGenerator = (baseDir) => {
167
+ const diagramsDir = path_1.default.join(baseDir, '.mermaid');
168
+ ensureDiagramsDirectory(diagramsDir);
169
+ // Event handlers
170
+ const handleFlowCreated = (flowName, flow) => {
171
+ generateAndSaveDiagram(diagramsDir, flowName, flow, baseDir);
172
+ };
173
+ const handleFlowUpdated = (flowName, flow) => {
174
+ generateAndSaveDiagram(diagramsDir, flowName, flow, baseDir);
175
+ };
176
+ const handleFlowRemoved = (flowName) => {
177
+ removeDiagram(diagramsDir, flowName);
178
+ };
179
+ // Initialize function to hook into LockedData events
180
+ const initialize = (lockedData) => {
181
+ // Hook into flow events
182
+ lockedData.on('flow-created', (flowName) => {
183
+ handleFlowCreated(flowName, lockedData.flows[flowName]);
184
+ });
185
+ lockedData.on('flow-updated', (flowName) => {
186
+ handleFlowUpdated(flowName, lockedData.flows[flowName]);
187
+ });
188
+ lockedData.on('flow-removed', (flowName) => {
189
+ handleFlowRemoved(flowName);
190
+ });
191
+ // Generate diagrams for all existing flows
192
+ if (lockedData.flows && typeof lockedData.flows === 'object') {
193
+ Object.entries(lockedData.flows).forEach(([flowName, flow]) => {
194
+ generateAndSaveDiagram(diagramsDir, flowName, flow, baseDir);
195
+ });
196
+ }
197
+ };
198
+ // Return the public API
199
+ return {
200
+ initialize,
201
+ };
202
+ };
203
+ exports.createMermaidGenerator = createMermaidGenerator;
@@ -1,2 +1 @@
1
- import { StepConfig } from "../types";
2
- export declare const getNodeFileConfig: (filePath: string) => Promise<StepConfig>;
1
+ export {};
@@ -1,14 +1,57 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getNodeFileConfig = void 0;
4
- const get_module_export_1 = require("./get-module-export");
5
- const getNodeFileConfig = async (filePath) => {
6
+ const path_1 = __importDefault(require("path"));
7
+ const zod_to_json_schema_1 = __importDefault(require("zod-to-json-schema"));
8
+ // Add ts-node registration before dynamic imports
9
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
10
+ require('ts-node').register({
11
+ transpileOnly: true,
12
+ compilerOptions: { module: 'commonjs' },
13
+ });
14
+ function isZodSchema(value) {
15
+ return Boolean(value && typeof value.safeParse === 'function' && value._def);
16
+ }
17
+ async function getConfig(filePath) {
6
18
  try {
7
- return await (0, get_module_export_1.getModuleExport)(filePath, 'config');
19
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
20
+ const module = require(path_1.default.resolve(filePath));
21
+ // Check if the specified function exists in the module
22
+ if (!module.config) {
23
+ throw new Error(`Config not found in module ${filePath}`);
24
+ }
25
+ if (isZodSchema(module.config.input)) {
26
+ module.config.input = (0, zod_to_json_schema_1.default)(module.config.input);
27
+ }
28
+ else if (isZodSchema(module.config.bodySchema)) {
29
+ module.config.bodySchema = (0, zod_to_json_schema_1.default)(module.config.bodySchema);
30
+ }
31
+ if (module.config.responseSchema) {
32
+ for (const [status, schema] of Object.entries(module.config.responseSchema)) {
33
+ if (isZodSchema(schema)) {
34
+ module.config.responseSchema[status] = (0, zod_to_json_schema_1.default)(schema);
35
+ }
36
+ }
37
+ }
38
+ if (isZodSchema(module.config.schema)) {
39
+ module.config.schema = (0, zod_to_json_schema_1.default)(module.config.schema);
40
+ }
41
+ process.send?.(module.config);
42
+ process.exit(0);
8
43
  }
9
44
  catch (error) {
10
- console.error(`Failed to extract config from ${filePath}:`, error);
11
- throw new Error(`No config found in step ${filePath}`);
45
+ console.error('Error running TypeScript module:', error);
46
+ process.exit(1);
12
47
  }
13
- };
14
- exports.getNodeFileConfig = getNodeFileConfig;
48
+ }
49
+ const [, , filePath] = process.argv;
50
+ if (!filePath) {
51
+ console.error('Usage: node get-config.js <file-path>');
52
+ process.exit(1);
53
+ }
54
+ getConfig(filePath).catch((err) => {
55
+ console.error('Error:', err);
56
+ process.exit(1);
57
+ });
@@ -1,8 +1,12 @@
1
+ import { RpcSender } from './rpc';
1
2
  export declare class Logger {
2
- private logger;
3
- constructor(traceId: string, flows: string[], file?: string);
4
- info: (message: string, args: Record<string, unknown>) => void;
5
- error: (message: string, args: Record<string, unknown>) => void;
6
- debug: (message: string, args: Record<string, unknown>) => void;
7
- warn: (message: string, args: Record<string, unknown>) => void;
3
+ private readonly traceId;
4
+ private readonly flows;
5
+ private readonly sender;
6
+ constructor(traceId: string, flows: string[], sender: RpcSender);
7
+ private _log;
8
+ info(message: string, args?: Record<string, unknown>): void;
9
+ error(message: string, args?: Record<string, unknown>): void;
10
+ debug(message: string, args?: Record<string, unknown>): void;
11
+ warn(message: string, args?: Record<string, unknown>): void;
8
12
  }
@@ -1,23 +1,34 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.Logger = void 0;
7
- const pino_1 = __importDefault(require("pino"));
8
4
  class Logger {
9
- constructor(traceId, flows, file) {
10
- this.info = (message, args) => this.logger.info(args, message);
11
- this.error = (message, args) => this.logger.error(args, message);
12
- this.debug = (message, args) => this.logger.debug(args, message);
13
- this.warn = (message, args) => this.logger.warn(args, message);
14
- this.logger = (0, pino_1.default)({
15
- level: 'info',
16
- formatters: { level: (level) => ({ level }) },
17
- errorKey: 'error',
18
- base: null,
19
- mixin: () => ({ traceId, flows, file }),
20
- });
5
+ constructor(traceId, flows, sender) {
6
+ this.traceId = traceId;
7
+ this.flows = flows;
8
+ this.sender = sender;
9
+ }
10
+ _log(level, message, args) {
11
+ const logEntry = {
12
+ ...(args || {}),
13
+ level,
14
+ time: Date.now(),
15
+ traceId: this.traceId,
16
+ flows: this.flows,
17
+ msg: message,
18
+ };
19
+ this.sender.sendNoWait('log', logEntry);
20
+ }
21
+ info(message, args) {
22
+ this._log('info', message, args);
23
+ }
24
+ error(message, args) {
25
+ this._log('error', message, args);
26
+ }
27
+ debug(message, args) {
28
+ this._log('debug', message, args);
29
+ }
30
+ warn(message, args) {
31
+ this._log('warn', message, args);
21
32
  }
22
33
  }
23
34
  exports.Logger = Logger;
@@ -0,0 +1 @@
1
+ export declare const composeMiddleware: (...middlewares: any[]) => (req: any, ctx: any, handler: () => Promise<any>) => Promise<any>;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.composeMiddleware = void 0;
4
+ /* eslint-disable @typescript-eslint/no-explicit-any */
5
+ const composeMiddleware = (...middlewares) => {
6
+ return async (req, ctx, handler) => {
7
+ const composedHandler = middlewares.reduceRight((nextHandler, middleware) => () => middleware(req, ctx, nextHandler), handler);
8
+ return composedHandler();
9
+ };
10
+ };
11
+ exports.composeMiddleware = composeMiddleware;
12
+ /* eslint-enable @typescript-eslint/no-explicit-any */
@@ -5,9 +5,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const path_1 = __importDefault(require("path"));
7
7
  const logger_1 = require("./logger");
8
- const rpc_state_manager_1 = require("./rpc-state-manager");
8
+ const middleware_compose_1 = require("./middleware-compose");
9
9
  const rpc_1 = require("./rpc");
10
+ const rpc_state_manager_1 = require("./rpc-state-manager");
11
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
12
+ require('dotenv').config();
10
13
  // Add ts-node registration before dynamic imports
14
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
11
15
  require('ts-node').register({
12
16
  transpileOnly: true,
13
17
  compilerOptions: { module: 'commonjs' },
@@ -20,24 +24,39 @@ function parseArgs(arg) {
20
24
  return arg;
21
25
  }
22
26
  }
23
- async function runTypescriptModule(filePath, args) {
27
+ async function runTypescriptModule(filePath, event) {
24
28
  try {
25
- // Remove pathToFileURL since we'll use require
29
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
26
30
  const module = require(path_1.default.resolve(filePath));
27
31
  // Check if the specified function exists in the module
28
32
  if (typeof module.handler !== 'function') {
29
33
  throw new Error(`Function handler not found in module ${filePath}`);
30
34
  }
31
- const { stateConfig, ...event } = args;
32
- const { traceId, flows } = event;
33
- const logger = new logger_1.Logger(traceId, flows, filePath.split('/').pop());
35
+ const { traceId, flows, contextInFirstArg } = event;
34
36
  const sender = new rpc_1.RpcSender(process);
37
+ const logger = new logger_1.Logger(traceId, flows, sender);
35
38
  const state = new rpc_state_manager_1.RpcStateManager(sender);
36
39
  const emit = async (data) => sender.send('emit', data);
37
- const context = { traceId, flows, logger, state, emit };
40
+ const streamsConfig = event.streams;
41
+ const streams = (streamsConfig ?? []).reduce((acc, streams) => {
42
+ acc[streams.name] = {
43
+ get: (groupId, id) => sender.send(`streams.${streams.name}.get`, { groupId, id }),
44
+ set: (groupId, id, data) => sender.send(`streams.${streams.name}.set`, { groupId, id, data }),
45
+ delete: (groupId, id) => sender.send(`streams.${streams.name}.delete`, { groupId, id }),
46
+ getGroup: (groupId) => sender.send(`streams.${streams.name}.getGroup`, { groupId }),
47
+ };
48
+ return acc;
49
+ }, {});
50
+ const context = { traceId, flows, logger, state, emit, streams };
38
51
  sender.init();
39
- // Call the function with provided arguments
40
- await module.handler(event.data, context);
52
+ const middlewares = Array.isArray(module.config.middleware) ? module.config.middleware : [];
53
+ const composedMiddleware = (0, middleware_compose_1.composeMiddleware)(...middlewares);
54
+ const handlerFn = () => {
55
+ return contextInFirstArg ? module.handler(context) : module.handler(event.data, context);
56
+ };
57
+ const result = await composedMiddleware(event.data, context, handlerFn);
58
+ await sender.send('result', result);
59
+ await sender.close();
41
60
  process.exit(0);
42
61
  }
43
62
  catch (error) {
@@ -4,7 +4,8 @@ export declare class RpcStateManager implements InternalStateManager {
4
4
  private readonly sender;
5
5
  constructor(sender: RpcSender);
6
6
  get<T>(traceId: string, key: string): Promise<T>;
7
- set<T>(traceId: string, key: string, value: T): Promise<void>;
8
- delete(traceId: string, key: string): Promise<void>;
7
+ set<T>(traceId: string, key: string, value: T): Promise<T>;
8
+ delete<T>(traceId: string, key: string): Promise<T | null>;
9
9
  clear(traceId: string): Promise<void>;
10
+ getGroup<T>(groupId: string): Promise<T[]>;
10
11
  }
@@ -9,13 +9,16 @@ class RpcStateManager {
9
9
  return this.sender.send('state.get', { traceId, key });
10
10
  }
11
11
  async set(traceId, key, value) {
12
- await this.sender.send('state.set', { traceId, key, value });
12
+ return this.sender.send('state.set', { traceId, key, value });
13
13
  }
14
14
  async delete(traceId, key) {
15
- await this.sender.send('state.delete', { traceId, key });
15
+ return this.sender.send('state.delete', { traceId, key });
16
16
  }
17
17
  async clear(traceId) {
18
18
  await this.sender.send('state.clear', { traceId });
19
19
  }
20
+ async getGroup(groupId) {
21
+ return this.sender.send('state.getGroup', { groupId });
22
+ }
20
23
  }
21
24
  exports.RpcStateManager = RpcStateManager;
@@ -2,6 +2,8 @@ export declare class RpcSender {
2
2
  private readonly process;
3
3
  private readonly pendingRequests;
4
4
  constructor(process: NodeJS.Process);
5
- send<T>(method: string, args: any): Promise<T>;
5
+ close(): Promise<void>;
6
+ send<T>(method: string, args: unknown): Promise<T>;
7
+ sendNoWait(method: string, args: unknown): void;
6
8
  init(): void;
7
9
  }