@motiadev/core 0.0.6 → 0.0.7-build.20250529215343

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
@@ -4,26 +4,44 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.RpcSender = void 0;
7
+ /// <reference types="node" />
7
8
  const crypto_1 = __importDefault(require("crypto"));
8
9
  class RpcSender {
9
10
  constructor(process) {
10
11
  this.process = process;
11
12
  this.pendingRequests = {};
12
13
  }
14
+ async close() {
15
+ const outstandingRequests = Object.values(this.pendingRequests);
16
+ if (outstandingRequests.length > 0) {
17
+ console.error('Process ended while there are some promises outstanding');
18
+ this.process.exit(1);
19
+ }
20
+ }
13
21
  send(method, args) {
14
22
  return new Promise((resolve, reject) => {
15
23
  const id = crypto_1.default.randomUUID();
16
24
  this.pendingRequests[id] = { resolve, reject, method, args };
17
- process.send?.({ type: 'rpc_request', id, method, args });
25
+ this.process.send?.({ type: 'rpc_request', id, method, args });
18
26
  });
19
27
  }
28
+ sendNoWait(method, args) {
29
+ this.process.send?.({ type: 'rpc_request', method, args });
30
+ }
20
31
  init() {
21
32
  this.process.on('message', (msg) => {
22
33
  if (msg.type === 'rpc_response') {
23
34
  const { id, result, error } = msg;
24
35
  const callbacks = this.pendingRequests[id];
25
- const callback = error ? callbacks.reject : callbacks.resolve;
26
- callback(result);
36
+ if (!callbacks) {
37
+ return;
38
+ }
39
+ else if (error) {
40
+ callbacks.reject(error);
41
+ }
42
+ else {
43
+ callbacks.resolve(result);
44
+ }
27
45
  delete this.pendingRequests[id];
28
46
  }
29
47
  });
@@ -0,0 +1 @@
1
+ export declare const prettyPrint: (json: Record<string, any>, excludeDetails?: boolean) => void;
@@ -0,0 +1,66 @@
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.prettyPrint = void 0;
7
+ const colors_1 = __importDefault(require("colors"));
8
+ const stepTag = (step) => colors_1.default.bold(colors_1.default.cyan(step));
9
+ const timestampTag = (timestamp) => colors_1.default.gray(timestamp);
10
+ const traceIdTag = (traceId) => colors_1.default.gray(traceId);
11
+ const levelTags = {
12
+ error: colors_1.default.red('[ERROR]'),
13
+ info: colors_1.default.blue('[INFO]'),
14
+ warn: colors_1.default.yellow('[WARN]'),
15
+ debug: colors_1.default.gray('[DEBUG]'),
16
+ trace: colors_1.default.gray('[TRACE]'),
17
+ };
18
+ const numericTag = (value) => colors_1.default.green(value);
19
+ const stringTag = (value) => colors_1.default.cyan(value);
20
+ const booleanTag = (value) => colors_1.default.blue(value);
21
+ const arrayBrackets = ['[', ']'].map((s) => colors_1.default.gray(s));
22
+ const objectBrackets = ['{', '}'].map((s) => colors_1.default.gray(s));
23
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
24
+ const prettyPrintObject = (obj, depth = 0, parentIsLast = false, prefix = '') => {
25
+ const tab = prefix + (depth === 0 ? '' : parentIsLast ? '│ ' : '│ ');
26
+ if (depth > 2) {
27
+ return `${tab} └ ${colors_1.default.gray('[...]')}`;
28
+ }
29
+ const entries = Object.entries(obj);
30
+ return entries
31
+ .map(([key, value], index) => {
32
+ const isLast = index === entries.length - 1;
33
+ const isObject = typeof value === 'object' && value !== null;
34
+ const prefix = isLast && !isObject ? '└' : '├';
35
+ if (isObject) {
36
+ const subObject = prettyPrintObject(value, depth + 1, isLast, tab);
37
+ const [start, end] = Array.isArray(value) ? arrayBrackets : objectBrackets;
38
+ return `${tab}${prefix} ${key}: ${start}\n${subObject}\n${tab}${isLast ? '└' : '│'} ${end}`;
39
+ }
40
+ let printedValue = value;
41
+ if (typeof value === 'number') {
42
+ printedValue = numericTag(String(value));
43
+ }
44
+ else if (typeof value === 'boolean') {
45
+ printedValue = booleanTag(String(value));
46
+ }
47
+ else if (typeof value === 'string') {
48
+ printedValue = stringTag(value);
49
+ }
50
+ return `${tab}${prefix} ${key}: ${printedValue}`;
51
+ })
52
+ .join('\n');
53
+ };
54
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
55
+ const prettyPrint = (json, excludeDetails = false) => {
56
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
57
+ const { time, traceId, msg, flows, level, step, ...details } = json;
58
+ const levelTag = levelTags[level];
59
+ const timestamp = timestampTag(`[${new Date(time).toLocaleTimeString()}]`);
60
+ const objectHasKeys = Object.keys(details).length > 0;
61
+ console.log(`${timestamp} ${traceIdTag(traceId)} ${levelTag} ${stepTag(step)} ${msg}`);
62
+ if (objectHasKeys && !excludeDetails) {
63
+ console.log(prettyPrintObject(details));
64
+ }
65
+ };
66
+ exports.prettyPrint = prettyPrint;
@@ -0,0 +1,45 @@
1
+ import { ValidationError } from './step-validator';
2
+ import { Step } from './types';
3
+ import { Stream } from './types-stream';
4
+ export declare class Printer {
5
+ private readonly baseDir;
6
+ constructor(baseDir: string);
7
+ stepTag: string;
8
+ flowTag: string;
9
+ created: string;
10
+ building: string;
11
+ built: string;
12
+ updated: string;
13
+ removed: string;
14
+ printInvalidEmit(step: Step, emit: string): void;
15
+ printStepCreated(step: Step): void;
16
+ printStepUpdated(step: Step): void;
17
+ printStepRemoved(step: Step): void;
18
+ printFlowCreated(flowName: string): void;
19
+ printFlowUpdated(flowName: string): void;
20
+ printFlowRemoved(flowName: string): void;
21
+ printStreamCreated(stream: Stream): void;
22
+ printStreamUpdated(stream: Stream): void;
23
+ printStreamRemoved(stream: Stream): void;
24
+ printInvalidSchema(topic: string, step: Step[]): void;
25
+ printValidationError(stepPath: string, validationError: ValidationError): void;
26
+ getRelativePath(filePath: string): string;
27
+ getStepType(step: Step): string;
28
+ getStepPath(step: Step): string;
29
+ getStreamPath(stream: Stream): string;
30
+ }
31
+ export declare class NoPrinter extends Printer {
32
+ constructor(baseDir: string);
33
+ printInvalidEmit(): void;
34
+ printStepCreated(): void;
35
+ printStepUpdated(): void;
36
+ printStepRemoved(): void;
37
+ printFlowCreated(): void;
38
+ printFlowUpdated(): void;
39
+ printFlowRemoved(): void;
40
+ printStepType(): void;
41
+ printStepPath(): void;
42
+ printStreamCreated(): void;
43
+ printStreamUpdated(): void;
44
+ printStreamRemoved(): void;
45
+ }
@@ -0,0 +1,121 @@
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.NoPrinter = exports.Printer = void 0;
7
+ const colors_1 = __importDefault(require("colors"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const guards_1 = require("./guards");
10
+ const stepTag = colors_1.default.bold(colors_1.default.magenta('Step'));
11
+ const flowTag = colors_1.default.bold(colors_1.default.blue('Flow'));
12
+ const streamTag = colors_1.default.bold(colors_1.default.green('Stream'));
13
+ const created = colors_1.default.green('➜ [CREATED]');
14
+ const building = colors_1.default.yellow('⚡ [BUILDING]');
15
+ const built = colors_1.default.green('✓ [BUILT]');
16
+ const updated = colors_1.default.yellow('➜ [UPDATED]');
17
+ const removed = colors_1.default.red('➜ [REMOVED]');
18
+ const invalidEmit = colors_1.default.red('➜ [INVALID EMIT]');
19
+ const error = colors_1.default.red('[ERROR]');
20
+ class Printer {
21
+ constructor(baseDir) {
22
+ this.baseDir = baseDir;
23
+ this.stepTag = stepTag;
24
+ this.flowTag = flowTag;
25
+ this.created = created;
26
+ this.building = building;
27
+ this.built = built;
28
+ this.updated = updated;
29
+ this.removed = removed;
30
+ }
31
+ printInvalidEmit(step, emit) {
32
+ console.log(`${invalidEmit} ${stepTag} ${this.getStepType(step)} ${this.getStepPath(step)} tried to emit an event not defined in the step config: ${colors_1.default.yellow(emit)}`);
33
+ }
34
+ printStepCreated(step) {
35
+ console.log(`${created} ${stepTag} ${this.getStepType(step)} ${this.getStepPath(step)} created`);
36
+ }
37
+ printStepUpdated(step) {
38
+ console.log(`${updated} ${stepTag} ${this.getStepType(step)} ${this.getStepPath(step)} updated`);
39
+ }
40
+ printStepRemoved(step) {
41
+ console.log(`${removed} ${stepTag} ${this.getStepType(step)} ${this.getStepPath(step)} removed`);
42
+ }
43
+ printFlowCreated(flowName) {
44
+ console.log(`${created} ${flowTag} ${colors_1.default.bold(colors_1.default.cyan(flowName))} created`);
45
+ }
46
+ printFlowUpdated(flowName) {
47
+ console.log(`${updated} ${flowTag} ${colors_1.default.bold(colors_1.default.cyan(flowName))} updated`);
48
+ }
49
+ printFlowRemoved(flowName) {
50
+ console.log(`${removed} ${flowTag} ${colors_1.default.bold(colors_1.default.cyan(flowName))} removed`);
51
+ }
52
+ printStreamCreated(stream) {
53
+ console.log(`${created} ${streamTag} ${this.getStreamPath(stream)} created`);
54
+ }
55
+ printStreamUpdated(stream) {
56
+ console.log(`${updated} ${streamTag} ${this.getStreamPath(stream)} updated`);
57
+ }
58
+ printStreamRemoved(stream) {
59
+ console.log(`${removed} ${streamTag} ${this.getStreamPath(stream)} removed`);
60
+ }
61
+ printInvalidSchema(topic, step) {
62
+ console.log(`${error} Topic ${colors_1.default.bold(colors_1.default.blue(topic))} has incompatible schemas in the following steps:`);
63
+ step.forEach((step) => {
64
+ console.log(`${colors_1.default.red(' ✖')} ${this.getStepPath(step)}`);
65
+ });
66
+ }
67
+ printValidationError(stepPath, validationError) {
68
+ const relativePath = this.getRelativePath(stepPath);
69
+ console.log(`${error} ${colors_1.default.bold(colors_1.default.cyan(relativePath))}`);
70
+ validationError.errors?.forEach((error) => {
71
+ if (error.path) {
72
+ console.log(`${colors_1.default.red('│')} ${colors_1.default.yellow(`✖ ${error.path}`)}: ${error.message}`);
73
+ }
74
+ else {
75
+ console.log(`${colors_1.default.red('│')} ${colors_1.default.yellow('✖')} ${error.message}`);
76
+ }
77
+ });
78
+ console.log(`${colors_1.default.red('└─')} ${colors_1.default.red(validationError.error)} `);
79
+ }
80
+ getRelativePath(filePath) {
81
+ return path_1.default.relative(this.baseDir, filePath);
82
+ }
83
+ getStepType(step) {
84
+ if ((0, guards_1.isApiStep)(step))
85
+ return colors_1.default.gray('(API)');
86
+ if ((0, guards_1.isEventStep)(step))
87
+ return colors_1.default.gray('(Event)');
88
+ if ((0, guards_1.isCronStep)(step))
89
+ return colors_1.default.gray('(Cron)');
90
+ if ((0, guards_1.isNoopStep)(step))
91
+ return colors_1.default.gray('(Noop)');
92
+ return colors_1.default.gray('(Unknown)');
93
+ }
94
+ getStepPath(step) {
95
+ const stepPath = this.getRelativePath(step.filePath);
96
+ return colors_1.default.bold(colors_1.default.cyan(stepPath));
97
+ }
98
+ getStreamPath(stream) {
99
+ const streamPath = this.getRelativePath(stream.filePath);
100
+ return colors_1.default.bold(colors_1.default.magenta(streamPath));
101
+ }
102
+ }
103
+ exports.Printer = Printer;
104
+ class NoPrinter extends Printer {
105
+ constructor(baseDir) {
106
+ super(baseDir);
107
+ }
108
+ printInvalidEmit() { }
109
+ printStepCreated() { }
110
+ printStepUpdated() { }
111
+ printStepRemoved() { }
112
+ printFlowCreated() { }
113
+ printFlowUpdated() { }
114
+ printFlowRemoved() { }
115
+ printStepType() { }
116
+ printStepPath() { }
117
+ printStreamCreated() { }
118
+ printStreamUpdated() { }
119
+ printStreamRemoved() { }
120
+ }
121
+ exports.NoPrinter = NoPrinter;
@@ -0,0 +1,7 @@
1
+ import { SpawnOptions } from 'child_process';
2
+ export type CommunicationType = 'rpc' | 'ipc';
3
+ export interface CommunicationConfig {
4
+ type: CommunicationType;
5
+ spawnOptions: SpawnOptions;
6
+ }
7
+ export declare function createCommunicationConfig(command: string): CommunicationConfig;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createCommunicationConfig = createCommunicationConfig;
4
+ function createCommunicationConfig(command) {
5
+ const type = command === 'python' && process.platform === 'win32' ? 'rpc' : 'ipc';
6
+ const spawnOptions = {
7
+ stdio: type === 'rpc'
8
+ ? ['pipe', 'pipe', 'inherit'] // RPC: capture stdout
9
+ : ['inherit', 'inherit', 'inherit', 'ipc'], // IPC: include IPC channel
10
+ };
11
+ return { type, spawnOptions };
12
+ }
@@ -0,0 +1,30 @@
1
+ import { ChildProcess } from 'child_process';
2
+ import { CommunicationType } from './communication-config';
3
+ import { RpcHandler, MessageCallback } from './rpc-processor-interface';
4
+ import { BaseLogger } from '../logger';
5
+ export interface ProcessManagerOptions {
6
+ command: string;
7
+ args: string[];
8
+ logger: BaseLogger;
9
+ context?: string;
10
+ }
11
+ export declare class ProcessManager {
12
+ private options;
13
+ private child?;
14
+ private processor?;
15
+ private communicationType?;
16
+ constructor(options: ProcessManagerOptions);
17
+ spawn(): Promise<ChildProcess>;
18
+ handler<TInput, TOutput = unknown>(method: string, handler: RpcHandler<TInput, TOutput>): void;
19
+ onMessage<T = unknown>(callback: MessageCallback<T>): void;
20
+ onProcessClose(callback: (code: number | null) => void): void;
21
+ onProcessError(callback: (error: Error & {
22
+ code?: string;
23
+ }) => void): void;
24
+ onStderr(callback: (data: Buffer) => void): void;
25
+ onStdout(callback: (data: Buffer) => void): void;
26
+ kill(): void;
27
+ close(): void;
28
+ get process(): ChildProcess | undefined;
29
+ get commType(): CommunicationType | undefined;
30
+ }
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProcessManager = void 0;
4
+ const child_process_1 = require("child_process");
5
+ const communication_config_1 = require("./communication-config");
6
+ const step_handler_rpc_processor_1 = require("../step-handler-rpc-processor");
7
+ const step_handler_rpc_stdin_processor_1 = require("../step-handler-rpc-stdin-processor");
8
+ class ProcessManager {
9
+ constructor(options) {
10
+ this.options = options;
11
+ }
12
+ async spawn() {
13
+ const { command, args, logger, context = 'Process' } = this.options;
14
+ // Get communication configuration
15
+ const commConfig = (0, communication_config_1.createCommunicationConfig)(command);
16
+ this.communicationType = commConfig.type;
17
+ logger.debug(`[${context}] Spawning process`, {
18
+ command,
19
+ args,
20
+ communicationType: this.communicationType,
21
+ });
22
+ // Spawn the process
23
+ this.child = (0, child_process_1.spawn)(command, args, commConfig.spawnOptions);
24
+ // Create appropriate processor based on communication type
25
+ this.processor = this.communicationType === 'rpc' ? new step_handler_rpc_stdin_processor_1.RpcStdinProcessor(this.child) : new step_handler_rpc_processor_1.RpcProcessor(this.child);
26
+ // Initialize the processor
27
+ await this.processor.init();
28
+ return this.child;
29
+ }
30
+ handler(method, handler) {
31
+ if (!this.processor) {
32
+ throw new Error('Process not spawned yet. Call spawn() first.');
33
+ }
34
+ this.processor.handler(method, handler);
35
+ }
36
+ onMessage(callback) {
37
+ if (!this.processor) {
38
+ throw new Error('Process not spawned yet. Call spawn() first.');
39
+ }
40
+ this.processor.onMessage(callback);
41
+ }
42
+ onProcessClose(callback) {
43
+ if (!this.child) {
44
+ throw new Error('Process not spawned yet. Call spawn() first.');
45
+ }
46
+ this.child.on('close', callback);
47
+ }
48
+ onProcessError(callback) {
49
+ if (!this.child) {
50
+ throw new Error('Process not spawned yet. Call spawn() first.');
51
+ }
52
+ this.child.on('error', callback);
53
+ }
54
+ onStderr(callback) {
55
+ if (!this.child) {
56
+ throw new Error('Process not spawned yet. Call spawn() first.');
57
+ }
58
+ this.child.stderr?.on('data', callback);
59
+ }
60
+ onStdout(callback) {
61
+ if (!this.child) {
62
+ throw new Error('Process not spawned yet. Call spawn() first.');
63
+ }
64
+ // Only for non-RPC mode (in RPC mode, stdout is used for communication)
65
+ if (this.communicationType !== 'rpc') {
66
+ this.child.stdout?.on('data', callback);
67
+ }
68
+ }
69
+ kill() {
70
+ if (this.child) {
71
+ this.child.kill();
72
+ }
73
+ }
74
+ close() {
75
+ if (this.processor) {
76
+ this.processor.close();
77
+ }
78
+ this.processor = undefined;
79
+ this.child = undefined;
80
+ }
81
+ get process() {
82
+ return this.child;
83
+ }
84
+ get commType() {
85
+ return this.communicationType;
86
+ }
87
+ }
88
+ exports.ProcessManager = ProcessManager;
@@ -0,0 +1,9 @@
1
+ export type RpcHandler<TInput, TOutput> = (input: TInput) => Promise<TOutput>;
2
+ export type MessageCallback<T = unknown> = (message: T) => void;
3
+ export interface RpcProcessorInterface {
4
+ handler<TInput, TOutput = unknown>(method: string, handler: RpcHandler<TInput, TOutput>): void;
5
+ handle(method: string, input: unknown): Promise<unknown>;
6
+ onMessage<T = unknown>(callback: MessageCallback<T>): void;
7
+ init(): Promise<void>;
8
+ close(): void;
9
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,35 @@
1
+ import os
2
+ import platform
3
+ from typing import Union
4
+ from rpc_communication import RpcCommunication
5
+ from ipc_communication import IpcCommunication
6
+
7
+ def create_communication() -> Union[RpcCommunication, IpcCommunication]:
8
+ """
9
+ Create appropriate communication instance based on platform and environment.
10
+
11
+ Logic:
12
+ - Python + Windows = RPC (stdin/stdout)
13
+ - Other cases with NODE_CHANNEL_FD = IPC
14
+ - Fallback = RPC
15
+ """
16
+
17
+ # Check if we're on Windows
18
+ is_windows = platform.system() == 'Windows'
19
+
20
+ # Check if IPC file descriptor is available
21
+ has_ipc_fd = "NODE_CHANNEL_FD" in os.environ
22
+
23
+ if is_windows:
24
+ # On Windows, always use RPC
25
+ return RpcCommunication()
26
+ elif has_ipc_fd:
27
+ # On Unix with IPC FD available, use IPC
28
+ try:
29
+ return IpcCommunication()
30
+ except RuntimeError:
31
+ # Fallback to RPC if IPC fails to initialize
32
+ return RpcCommunication()
33
+ else:
34
+ # Fallback to RPC
35
+ return RpcCommunication()
@@ -0,0 +1,21 @@
1
+ from typing import Any, List, Optional
2
+ from type_definitions import HandlerResult
3
+ from rpc import RpcSender
4
+ from rpc_state_manager import RpcStateManager
5
+ from logger import Logger
6
+
7
+ class Context:
8
+ def __init__(
9
+ self,
10
+ trace_id: str,
11
+ flows: List[str],
12
+ rpc: RpcSender,
13
+ ):
14
+ self.trace_id = trace_id
15
+ self.flows = flows
16
+ self.rpc = rpc
17
+ self.state = RpcStateManager(rpc)
18
+ self.logger = Logger(self.trace_id, self.flows, rpc)
19
+
20
+ async def emit(self, event: Any) -> Optional[HandlerResult]:
21
+ return await self.rpc.send('emit', event)
@@ -2,31 +2,49 @@ import sys
2
2
  import json
3
3
  import importlib.util
4
4
  import os
5
- from typing import Any, Callable
6
-
7
- # get the FD from ENV
8
- NODEIPCFD = int(os.environ["NODE_CHANNEL_FD"])
5
+ import platform
9
6
 
10
7
  def sendMessage(text):
11
- 'sends a Node IPC message to parent proccess'
12
- # encode message as json string + newline in bytes
13
- bytesMessage = (json.dumps(text) + "\n").encode('utf-8')
14
- # send message
15
- os.write(NODEIPCFD, bytesMessage)
8
+ 'sends a Node IPC message to parent proccess'
9
+ # encode message as json string + newline in bytes
10
+ bytesMessage = (json.dumps(text) + "\n").encode('utf-8')
11
+
12
+ # Handle Windows differently
13
+ if platform.system() == 'Windows':
14
+ # On Windows, write to stdout
15
+ sys.stdout.buffer.write(bytesMessage)
16
+ sys.stdout.buffer.flush()
17
+ else:
18
+ # On Unix systems, use the file descriptor approach
19
+ NODEIPCFD = int(os.environ["NODE_CHANNEL_FD"])
20
+ os.write(NODEIPCFD, bytesMessage)
16
21
 
17
22
  async def run_python_module(file_path: str) -> None:
18
23
  try:
19
- # Load the module dynamically
24
+ module_dir = os.path.dirname(os.path.abspath(file_path))
25
+
26
+ if module_dir not in sys.path:
27
+ sys.path.insert(0, module_dir)
28
+
29
+ flows_dir = os.path.dirname(module_dir)
30
+ if flows_dir not in sys.path:
31
+ sys.path.insert(0, flows_dir)
32
+
20
33
  spec = importlib.util.spec_from_file_location("dynamic_module", file_path)
21
34
  if spec is None or spec.loader is None:
22
35
  raise ImportError(f"Could not load module from {file_path}")
23
36
 
24
37
  module = importlib.util.module_from_spec(spec)
38
+ module.__package__ = os.path.basename(module_dir)
25
39
  spec.loader.exec_module(module)
26
40
 
27
- # Print the config if it exists
28
- if hasattr(module, 'config'):
29
- sendMessage(module.config)
41
+ if not hasattr(module, 'config'):
42
+ raise AttributeError(f"No 'config' found in module {file_path}")
43
+
44
+ if 'middleware' in module.config:
45
+ del module.config['middleware']
46
+
47
+ sendMessage(module.config)
30
48
 
31
49
  except Exception as error:
32
50
  print('Error running Python module:', str(error), file=sys.stderr)