@fractal-solutions/qflow 1.0.0

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/README.md ADDED
@@ -0,0 +1,498 @@
1
+ # qflow
2
+
3
+ A lightweight and flexible JavaScript library for creating and managing workflows. Adopted Pocket Flow design.
4
+
5
+ ## Core Concepts
6
+
7
+ qflow allows you to define complex workflows as a series of connected nodes. Each node represents a step in the process, and you can control the flow of execution based on the outcome of each step.
8
+
9
+ * **`Node`**: The fundamental building block of a qflow. A `Node` is a single step in your workflow. It has three main lifecycle methods:
10
+ * `prep(shared)`: Prepare data for the `exec` method. The `shared` object is passed through the entire flow.
11
+ * `exec(prepRes)`: The main logic of the node. It receives the result from the `prep` method.
12
+ * `post(shared, prepRes, execRes)`: Clean up or process the results after the `exec` method. **The return value of this method determines the next action in the flow.**
13
+
14
+ * **`Flow`**: A `Flow` manages the execution of a series of connected `Node`s. You define the starting node and the transitions between nodes.
15
+
16
+ ## Features
17
+
18
+ * **Synchronous and Asynchronous Execution**: qflow provides both synchronous and asynchronous versions of `Node`s and `Flow`s, allowing you to handle both CPU-bound and I/O-bound tasks efficiently.
19
+ * **Batch Processing**: The `BatchFlow` and `AsyncBatchFlow` classes allow you to process arrays of items in a single workflow.
20
+ * **Parallel Execution**: The `AsyncParallelBatchNode` and `AsyncParallelBatchFlow` classes enable you to execute asynchronous operations in parallel for maximum efficiency.
21
+ * **Retries and Error Handling**: The `Node` class has built-in support for retries with a configurable delay. You can also define a `execFallback` method to handle cases where all retries fail.
22
+ * **Conditional Transitions**: You can define multiple successors for a node and choose which one to transition to based on the return value of the `exec` or `post` method.
23
+
24
+ ## Understanding Nodes, Flows, and Data Management
25
+
26
+ ### Nodes: The Building Blocks
27
+
28
+ Each `Node` in qflow represents a distinct step in your workflow. Nodes are designed with a clear lifecycle to manage their execution:
29
+
30
+ * **`prep(shared)`**: This method is called before `exec`. It's ideal for preparing any data or resources needed for the node's main logic. The `shared` object, which is a mutable object passed throughout the entire flow, can be used here to access or store global state. The return value of `prep` is passed as `prepRes` to the `exec` method.
31
+ * **`exec(prepRes)`**: This is the core logic of your node. It receives the result from the `prep` method (`prepRes`). The `exec` method should perform the primary task of the node. **The return value of `exec` is crucial for controlling the flow's path.** It can be a string representing an "action" (e.g., "success", "failure", "long", "short") that the `Flow` uses to determine the next node.
32
+ * **`post(shared, prepRes, execRes)`**: This method is called after `exec` completes. It's suitable for cleanup, logging, or further processing of the `exec` result. It receives the `shared` object, the `prepRes`, and the `execRes`. **The return value of `post` also dictates the flow's path, similar to `exec`.** If both `exec` and `post` return a value, the `post` method's return value takes precedence for determining the next transition.
33
+
34
+ ### Flows: Orchestrating Execution
35
+
36
+ A `Flow` acts as the orchestrator for your nodes. It defines the sequence of execution and manages transitions between nodes.
37
+
38
+ * **Starting a Flow**: You initialize a `Flow` with a `startNode`. This is the first node that will be executed when the flow runs.
39
+ * **Transitions**: Nodes are connected using the `node.next(nextNode, action)` method. When a node's `exec` or `post` method returns an `action` string, the `Flow` looks for a successor node registered with that specific action. If no action is specified (or the method returns `undefined`), the "default" action is used. This allows for powerful conditional branching in your workflows.
40
+
41
+ ### Data Transfer and State Management
42
+
43
+ qflow provides two primary mechanisms for data management within a flow:
44
+
45
+ 1. **Node-Specific Parameters (`this.params`)**: Each node instance has a `this.params` object. This object is populated by the `Flow` when it calls `node.setParams(params)`. This is the recommended way to pass data *into* a specific node for its execution. For `BatchFlow` and `AsyncBatchFlow`, the `prep` (or `prepAsync`) method should return an array of objects, where each object contains the `params` for a single batch item.
46
+ ```javascript
47
+ // Example of setting params for a node
48
+ class MyNode extends Node {
49
+ exec() {
50
+ console.log(this.params.myValue);
51
+ }
52
+ }
53
+ const myNode = new MyNode();
54
+ // When running a flow, the flow will call myNode.setParams({ myValue: 'hello' });
55
+ ```
56
+
57
+ 2. **Shared State (`shared` object)**: The `shared` object is a mutable object that is passed to the `prep`, `exec`, and `post` methods of every node in the flow. This object is ideal for maintaining global state or data that needs to be accessible and modifiable across multiple nodes in the workflow. Any changes made to the `shared` object by one node will be visible to subsequent nodes.
58
+
59
+ ### Nuances
60
+
61
+ * **Return Values for Transitions**: The string returned by a node's `exec` or `post` method is critical for defining the flow's path. If a node returns "success", the flow will look for a successor registered with the "success" action. If no action is returned, the "default" action is assumed.
62
+ * **Error Handling**: Nodes can throw errors. The `Node` class provides `maxRetries` and `wait` parameters for automatic retries. If all retries fail, the `execFallback` method is called.
63
+ * **Asynchronous Operations**: For asynchronous operations, use `AsyncNode` and `AsyncFlow`. Their lifecycle methods (`prepAsync`, `execAsync`, `postAsync`) are `async` functions, allowing you to use `await` for non-blocking operations.
64
+
65
+ ## API Reference
66
+
67
+ ### `BaseNode`
68
+
69
+ The base class for all nodes.
70
+
71
+ * `constructor()`
72
+ * `setParams(params)`: Sets the parameters for the node.
73
+ * `next(node, action = "default")`: Defines the next node in the flow.
74
+ * `prep(shared)`: Pre-execution logic.
75
+ * `exec(prepRes)`: Execution logic.
76
+ * `post(shared, prepRes, execRes)`: Post-execution logic. The return value of this method is used to determine the next node in the flow.
77
+ * `run(shared)`: Runs the node.
78
+
79
+ ### `Node`
80
+
81
+ Extends `BaseNode` with retry logic.
82
+
83
+ * `constructor(maxRetries = 1, wait = 0)`: `maxRetries` is the number of times to retry on failure, and `wait` is the delay in seconds between retries.
84
+ * `execFallback(prepRes, error)`: Logic to execute if all retries fail.
85
+
86
+ ### `Flow`
87
+
88
+ Manages a workflow of nodes.
89
+
90
+ * `constructor(start = null)`: `start` is the starting node of the flow.
91
+ * `start(startNode)`: Sets the starting node.
92
+ * `run(shared)`: Runs the entire flow.
93
+
94
+ ### `BatchFlow`
95
+
96
+ Extends `Flow` for batch processing. The `prep` method should return an array of objects, where each object contains the parameters for a single execution of the flow.
97
+
98
+ ### Asynchronous Classes
99
+
100
+ qflow provides asynchronous versions of the core classes:
101
+
102
+ * `AsyncNode`
103
+ * `AsyncFlow`
104
+ * `AsyncBatchFlow`
105
+ * `AsyncParallelBatchFlow`
106
+
107
+ These classes have `...Async` versions of the lifecycle methods (e.g., `prepAsync`, `execAsync`, `postAsync`) and support `async/await`. The `AsyncFlow` class has a `runAsync` method to execute the flow.
108
+
109
+ ## Usage Examples
110
+
111
+ ### Basic Flow
112
+
113
+ ```javascript
114
+ import { Node, Flow } from './qflow.js';
115
+
116
+ // A node that prints a message
117
+ class MessageNode extends Node {
118
+ exec() {
119
+ console.log("Hello from MessageNode!");
120
+ return 'default'; // Transition to the default successor
121
+ }
122
+ }
123
+
124
+ // A node that prints the current time
125
+ class TimeNode extends Node {
126
+ exec() {
127
+ console.log(`Current time: ${Date.now()}`);
128
+ return 'default';
129
+ }
130
+ }
131
+
132
+ // Create the nodes
133
+ const messageNode = new MessageNode();
134
+ const timeNode = new TimeNode();
135
+
136
+ // Define the workflow
137
+ messageNode.next(timeNode); // After messageNode, go to timeNode
138
+
139
+ // Create and run the flow
140
+ const flow = new Flow(messageNode);
141
+ flow.run({});
142
+ ```
143
+
144
+ ### Batch Flow
145
+
146
+ ```javascript
147
+ import { Node, BatchFlow } from './qflow.js';
148
+
149
+ class MyBatchNode extends Node {
150
+ exec() {
151
+ console.log(`BatchNode: Processing item ${this.params.item}`);
152
+ return 'default';
153
+ }
154
+ }
155
+
156
+ const batchNode = new MyBatchNode();
157
+ const batchFlow = new BatchFlow(batchNode);
158
+
159
+ // The prep method returns an array of parameter objects for the batch.
160
+ batchFlow.prep = () => [ { item: 1 }, { item: 2 }, { item: 3 } ];
161
+
162
+ batchFlow.run({});
163
+ ```
164
+
165
+ ### Async Parallel Batch Flow
166
+
167
+ ```javascript
168
+ import { AsyncNode, AsyncParallelBatchFlow } from './qflow.js';
169
+
170
+ class MyAsyncParallelBatchNode extends AsyncNode {
171
+ async execAsync() {
172
+ console.log(`AsyncParallelBatchNode: Starting item ${this.params.item}`);
173
+ await new Promise(resolve => setTimeout(resolve, Math.random() * 100));
174
+ console.log(`AsyncParallelBatchNode: Finished item ${this.params.item}`);
175
+ return 'default';
176
+ }
177
+ }
178
+
179
+ const asyncParallelBatchNode = new MyAsyncParallelBatchNode();
180
+ const asyncParallelBatchFlow = new AsyncParallelBatchFlow(asyncParallelBatchNode);
181
+
182
+ // The prepAsync method returns an array of parameter objects for the batch.
183
+ asyncParallelBatchFlow.prepAsync = async () => [ { item: 1 }, { item: 2 }, { item: 3 }, { item: 4 }, { item: 5 } ];
184
+
185
+ await asyncParallelBatchFlow.runAsync({});
186
+ ```
187
+
188
+ ## Extending qflow with LLM Nodes
189
+
190
+ qflow's flexible node structure makes it straightforward to integrate with external APIs, including Large Language Models (LLMs). By creating custom `AsyncNode` implementations, you can easily add capabilities like text generation, summarization, and more to your workflows.
191
+
192
+ Below are examples of how you might create nodes for popular LLM providers. Remember to handle API keys securely (e.g., using environment variables) and to include necessary `fetch` polyfills or libraries if running in environments that don't natively support `fetch` (like Node.js without a recent version or a polyfill).
193
+
194
+ ### OpenAI GPT-3.5 Turbo Node
195
+
196
+ This example demonstrates an `AsyncNode` that interacts with the OpenAI Chat Completions API.
197
+
198
+ ```javascript
199
+ import { AsyncNode } from './qflow.js';
200
+
201
+ class OpenAILLMNode extends AsyncNode {
202
+ async execAsync() {
203
+ const { prompt, apiKey } = this.params; // prompt and apiKey passed via node params
204
+
205
+ if (!prompt) {
206
+ throw new Error('Prompt is required for OpenAILLMNode.');
207
+ }
208
+ if (!apiKey) {
209
+ throw new Error('OpenAI API Key is required.');
210
+ }
211
+
212
+ console.log(`OpenAILLMNode: Sending prompt to OpenAI: "${prompt.substring(0, 50)}..."`);
213
+
214
+ try {
215
+ const response = await fetch('https://api.openai.com/v1/chat/completions', {
216
+ method: 'POST',
217
+ headers: {
218
+ 'Content-Type': 'application/json',
219
+ 'Authorization': `Bearer ${apiKey}`
220
+ },
221
+ body: JSON.stringify({
222
+ model: 'gpt-3.5-turbo',
223
+ messages: [{ role: 'user', content: prompt }],
224
+ max_tokens: 150
225
+ })
226
+ });
227
+
228
+ if (!response.ok) {
229
+ const errorData = await response.json();
230
+ throw new Error(`OpenAI API error: ${response.status} - ${errorData.error.message}`);
231
+ }
232
+
233
+ const data = await response.json();
234
+ const llmResponse = data.choices[0].message.content.trim();
235
+ console.log(`OpenAILLMNode: Received response: "${llmResponse.substring(0, 50)}..."`);
236
+ return llmResponse; // Return the LLM's response
237
+ } catch (error) {
238
+ console.error('OpenAILLMNode: Error during API call:', error);
239
+ throw error; // Re-throw to trigger qflow's retry/fallback
240
+ }
241
+ }
242
+ }
243
+
244
+ // Example Usage in a Flow:
245
+ import { AsyncFlow } from './qflow.js';
246
+
247
+ const openAILLMNode = new OpenAILLMNode();
248
+ // Pass prompt and API key via params
249
+ openAILLMNode.setParams({
250
+ prompt: 'Write a short, creative slogan for a new coffee shop.',
251
+ apiKey: process.env.OPENAI_API_KEY // Load from environment variable
252
+ });
253
+
254
+ const llmFlow = new AsyncFlow(openAILLMNode);
255
+ const llmResult = await llmFlow.runAsync({});
256
+ console.log('LLM Flow Result:', llmResult);
257
+
258
+ ```
259
+
260
+ ### Google Gemini Node
261
+
262
+ This example demonstrates an `AsyncNode` that interacts with the Google Gemini API.
263
+
264
+ ```javascript
265
+ import { AsyncNode } from './qflow.js';
266
+
267
+ class GeminiLLMNode extends AsyncNode {
268
+ async execAsync() {
269
+ const { prompt, apiKey } = this.params; // prompt and apiKey passed via node params
270
+
271
+ if (!prompt) {
272
+ throw new Error('Prompt is required for GeminiLLMNode.');
273
+ }
274
+ if (!apiKey) {
275
+ throw new Error('Google Gemini API Key is required.');
276
+ }
277
+
278
+ console.log(`GeminiLLMNode: Sending prompt to Gemini: "${prompt.substring(0, 50)}..."`);
279
+
280
+ try {
281
+ const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=${apiKey}`, {
282
+ method: 'POST',
283
+ headers: {
284
+ 'Content-Type': 'application/json'
285
+ },
286
+ body: JSON.stringify({
287
+ contents: [{ parts: [{ text: prompt }] }]
288
+ })
289
+ });
290
+
291
+ if (!response.ok) {
292
+ const errorData = await response.json();
293
+ throw new Error(`Gemini API error: ${response.status} - ${errorData.error.message}`);
294
+ }
295
+
296
+ const data = await response.json();
297
+ const llmResponse = data.candidates[0].content.parts[0].text.trim();
298
+ console.log(`GeminiLLMNode: Received response: "${llmResponse.substring(0, 50)}..."`);
299
+ return llmResponse; // Return the LLM's response
300
+ } catch (error) {
301
+ console.error('GeminiLLMNode: Error during API call:', error);
302
+ throw error; // Re-throw to trigger qflow's retry/fallback
303
+ }
304
+ }
305
+ }
306
+
307
+ // Example Usage in a Flow:
308
+ import { AsyncFlow } from './qflow.js';
309
+
310
+ const geminiLLMNode = new GeminiLLMNode();
311
+ // Pass prompt and API key via params
312
+ geminiLLMNode.setParams({
313
+ prompt: 'Generate a short, catchy headline for a tech blog post about AI in healthcare.',
314
+ apiKey: process.env.GEMINI_API_KEY // Load from environment variable
315
+ });
316
+
317
+ const llmFlow = new AsyncFlow(geminiLLMNode);
318
+ const llmResult = await llmFlow.runAsync({});
319
+ console.log('LLM Flow Result:', llmResult);
320
+
321
+ ```
322
+
323
+ ### Chaining Nodes and Passing Data
324
+
325
+ One of the powerful features of qflow is the ability to chain nodes, allowing the output of one node to become the input for the next. This is particularly useful for multi-step workflows where the output of one operation is required for the next.
326
+
327
+ The recommended way to pass data between asynchronous nodes is to use the `shared` object. The first node should place its result into the `shared` object in its `postAsync` method, and the second node can then access that data in its `prepAsync` method.
328
+
329
+ This example demonstrates a flow where a GitHub issue is created, and then the created issue is retrieved:
330
+
331
+ ```javascript
332
+ import { AsyncFlow } from 'qflow';
333
+ import { CreateIssueNode, GetIssueNode } from 'qflow/nodes';
334
+
335
+ // 1. Create instances of the nodes
336
+ const createIssue = new CreateIssueNode();
337
+ createIssue.setParams({
338
+ token: process.env.GITHUB_TOKEN,
339
+ owner: 'your-username',
340
+ repo: 'your-repo',
341
+ title: '[qflow] Test Issue'
342
+ });
343
+
344
+ const getIssue = new GetIssueNode();
345
+ getIssue.setParams({
346
+ token: process.env.GITHUB_TOKEN,
347
+ owner: 'your-username',
348
+ repo: 'your-repo'
349
+ });
350
+
351
+ // 2. Define the workflow
352
+ createIssue.next(getIssue);
353
+
354
+ // 3. Create and run the flow
355
+ const githubFlow = new AsyncFlow(createIssue);
356
+ const result = await githubFlow.runAsync({});
357
+ ```
358
+
359
+ ### Web Scraping Example
360
+
361
+ This example demonstrates how to use the `ScrapeURLNode` to fetch content from multiple URLs in parallel and then process them with another node.
362
+
363
+ ```javascript
364
+ import { AsyncFlow, AsyncNode, AsyncParallelBatchFlow } from 'qflow';
365
+ import { ScrapeURLNode } from 'qflow/nodes';
366
+
367
+ /**
368
+ * A node to display the scraped content.
369
+ */
370
+ class DisplayScrapedContentNode extends AsyncNode {
371
+ async prepAsync(shared) {
372
+ this.params.html = shared.scrapedHTML;
373
+ this.params.url = shared.scrapedURL;
374
+ }
375
+
376
+ async execAsync() {
377
+ const { html, url } = this.params;
378
+ if (!html) {
379
+ console.log(`[DisplayContent] No HTML content found for ${url || 'unknown URL'}.`);
380
+ return 'error';
381
+ }
382
+
383
+ console.log(`\n--- Scraped Content for: ${url} ---\n`);
384
+ console.log(html.substring(0, 500) + '...'); // Log first 500 characters
385
+ console.log(`\n--- End Content for: ${url} ---\n`);
386
+ return html.length; // Return character count as the result
387
+ }
388
+ }
389
+
390
+ // 1. Create instances of the nodes
391
+ const scrapeNode = new ScrapeURLNode();
392
+ // Override postAsync to pass data to the shared object for the next node
393
+ scrapeNode.postAsync = async (shared, prepRes, execRes) => {
394
+ shared.scrapedHTML = execRes; // execRes is the returned HTML
395
+ // We also need to store the URL that was just scraped for context in the next node
396
+ shared.scrapedURL = scrapeNode.params.url;
397
+ return 'default'; // Return a static action for the flow to transition
398
+ };
399
+
400
+ const displayNode = new DisplayScrapedContentNode();
401
+
402
+ // 2. Define the workflow
403
+ scrapeNode.next(displayNode);
404
+
405
+ // 3. Create the batch flow
406
+ const scraperBatchFlow = new AsyncParallelBatchFlow(scrapeNode);
407
+
408
+ // Define the URLs to scrape in the prepAsync of the flow
409
+ scraperBatchFlow.prepAsync = async () => [
410
+ { url: 'https://example.com' },
411
+ { url: 'https://www.iana.org/domains/example' },
412
+ { url: 'https://www.w3.org/' }
413
+ ];
414
+
415
+ // 4. Run the flow
416
+ const results = await scraperBatchFlow.runAsync({});
417
+ console.log('Final Results (character counts):', results);
418
+ ```
419
+
420
+ ## More Examples
421
+
422
+ For more detailed usage examples and advanced workflows, refer to the `examples/` directory.
423
+
424
+ * `examples/test.js` - Basic flow and node usage.
425
+ * `examples/test2.js` - Demonstrates async flows, conditional transitions, retries, and batch processing.
426
+ * `examples/test3.js` - Advanced workflow integrating with a public API.
427
+ * `examples/hackernews_test.js` - Demonstrates the Hacker News integration.
428
+ * `examples/github_test.js` - Demonstrates the GitHub integration.
429
+ * `examples/stripe_test.js` - Demonstrates the Stripe integration.
430
+
431
+ ### Running the Examples
432
+
433
+ To run the examples, you can use `bun run`:
434
+
435
+ ```bash
436
+ bun run examples/test.js
437
+ ```
438
+
439
+ **Note:** Some examples require API keys or other credentials. These can be set as environment variables or by replacing the placeholder values in the example files.
440
+
441
+ ## Installation
442
+
443
+ Install `qflow` using your favorite package manager:
444
+
445
+ **NPM**
446
+ ```bash
447
+ npm install qflow
448
+ ```
449
+
450
+ **Yarn**
451
+ ```bash
452
+ yarn add qflow
453
+ ```
454
+
455
+ **Bun**
456
+ ```bash
457
+ bun add qflow
458
+ ```
459
+
460
+ ## Usage
461
+
462
+ ### Core Concepts
463
+
464
+ Import the core `qflow` classes from the main entry point:
465
+
466
+ ```javascript
467
+ import { Node, Flow, AsyncNode, AsyncFlow } from 'qflow';
468
+ ```
469
+
470
+ ### Integrated Nodes
471
+
472
+ `qflow` also includes a variety of pre-built nodes for common integrations, such as LLMs. You can import these nodes from the `qflow/nodes` entry point:
473
+
474
+ ```javascript
475
+ import { OpenAILLMNode, GeminiLLMNode, DeepSeekLLMNode } from 'qflow/nodes';
476
+ ```
477
+
478
+ ### Runtime Compatibility
479
+
480
+ `qflow` is designed to be compatible with modern JavaScript runtimes.
481
+
482
+ **Node.js**
483
+
484
+ When using `qflow` in a Node.js environment, you may need to use the `--experimental-modules` flag if you are using ES modules.
485
+
486
+ **Deno**
487
+
488
+ `qflow` can be used in Deno by importing it from a CDN that serves NPM packages, such as esm.sh:
489
+
490
+ ```javascript
491
+ import { Node, Flow } from 'https://esm.sh/qflow';
492
+ import { OpenAILLMNode } from 'https://esm.sh/qflow/nodes';
493
+ ```
494
+
495
+
496
+ ## Contributing
497
+
498
+ Contributions are welcome! Please feel free to submit a pull request.
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Creates a new issue in a GitHub repository.
3
+ * @param {object} params - The parameters for the node.
4
+ * @param {string} params.token - The GitHub personal access token.
5
+ * @param {string} params.owner - The owner of the repository.
6
+ * @param {string} params.repo - The name of the repository.
7
+ * @param {string} params.title - The title of the issue.
8
+ * @param {string} [params.body] - The body of the issue.
9
+ * @returns {Promise<object>} A promise that resolves to the created issue object.
10
+ */
11
+ export class CreateIssueNode extends AsyncNode {
12
+ execAsync(): Promise<unknown>;
13
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
14
+ }
15
+ /**
16
+ * Retrieves an issue from a GitHub repository.
17
+ * @param {object} params - The parameters for the node.
18
+ * @param {string} params.token - The GitHub personal access token.
19
+ * @param {string} params.owner - The owner of the repository.
20
+ * @param {string} params.repo - The name of the repository.
21
+ * @param {number} params.issue_number - The number of the issue to retrieve.
22
+ * @returns {Promise<object>} A promise that resolves to the issue object.
23
+ */
24
+ export class GetIssueNode extends AsyncNode {
25
+ execAsync(): Promise<unknown>;
26
+ }
27
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,74 @@
1
+ import { AsyncNode } from '../qflow.js';
2
+ const API_BASE = 'https://api.github.com';
3
+ /**
4
+ * Creates a new issue in a GitHub repository.
5
+ * @param {object} params - The parameters for the node.
6
+ * @param {string} params.token - The GitHub personal access token.
7
+ * @param {string} params.owner - The owner of the repository.
8
+ * @param {string} params.repo - The name of the repository.
9
+ * @param {string} params.title - The title of the issue.
10
+ * @param {string} [params.body] - The body of the issue.
11
+ * @returns {Promise<object>} A promise that resolves to the created issue object.
12
+ */
13
+ export class CreateIssueNode extends AsyncNode {
14
+ async execAsync() {
15
+ const { token, owner, repo, title, body } = this.params;
16
+ if (!token || !owner || !repo || !title) {
17
+ throw new Error('Missing required parameters: token, owner, repo, title');
18
+ }
19
+ console.log(`[GitHub] Creating issue "${title}" in ${owner}/${repo}...`);
20
+ const response = await fetch(`${API_BASE}/repos/${owner}/${repo}/issues`, {
21
+ method: 'POST',
22
+ headers: {
23
+ 'Authorization': `token ${token}`,
24
+ 'Content-Type': 'application/json'
25
+ },
26
+ body: JSON.stringify({ title, body })
27
+ });
28
+ if (!response.ok) {
29
+ const errorData = await response.json();
30
+ throw new Error(`GitHub API error: ${response.status} - ${errorData.message}`);
31
+ }
32
+ const issue = await response.json();
33
+ console.log(`[GitHub] Successfully created issue #${issue.number}`);
34
+ return issue;
35
+ }
36
+ async postAsync(shared, prepRes, execRes) {
37
+ shared.createdIssue = execRes; // Put the result in the shared object
38
+ return 'default'; // Return an action to transition
39
+ }
40
+ }
41
+ /**
42
+ * Retrieves an issue from a GitHub repository.
43
+ * @param {object} params - The parameters for the node.
44
+ * @param {string} params.token - The GitHub personal access token.
45
+ * @param {string} params.owner - The owner of the repository.
46
+ * @param {string} params.repo - The name of the repository.
47
+ * @param {number} params.issue_number - The number of the issue to retrieve.
48
+ * @returns {Promise<object>} A promise that resolves to the issue object.
49
+ */
50
+ export class GetIssueNode extends AsyncNode {
51
+ async prepAsync(shared) {
52
+ // Retrieve the issue number from the shared object
53
+ this.params.issue_number = shared.createdIssue?.number;
54
+ }
55
+ async execAsync() {
56
+ const { token, owner, repo, issue_number } = this.params;
57
+ if (!token || !owner || !repo || !issue_number) {
58
+ throw new Error('Missing required parameters: token, owner, repo, issue_number');
59
+ }
60
+ console.log(`[GitHub] Getting issue #${issue_number} from ${owner}/${repo}...`);
61
+ const response = await fetch(`${API_BASE}/repos/${owner}/${repo}/issues/${issue_number}`, {
62
+ headers: {
63
+ 'Authorization': `token ${token}`
64
+ }
65
+ });
66
+ if (!response.ok) {
67
+ const errorData = await response.json();
68
+ throw new Error(`GitHub API error: ${response.status} - ${errorData.message}`);
69
+ }
70
+ const issue = await response.json();
71
+ console.log(`[GitHub] Successfully retrieved issue #${issue.number}`);
72
+ return issue;
73
+ }
74
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Fetches the top story IDs from the Hacker News API.
3
+ * @param {object} params - The parameters for the node.
4
+ * @param {number} [params.limit=10] - The maximum number of story IDs to return.
5
+ * @returns {Promise<number[]>} A promise that resolves to an array of story IDs.
6
+ */
7
+ export class GetTopStoriesNode extends AsyncNode {
8
+ execAsync(prepRes: any, shared: any): Promise<string>;
9
+ }
10
+ /**
11
+ * Fetches the details of a specific item from the Hacker News API.
12
+ * @param {object} params - The parameters for the node.
13
+ * @param {number} params.id - The ID of the item to fetch.
14
+ * @returns {Promise<object>} A promise that resolves to the item details.
15
+ */
16
+ export class GetItemNode extends AsyncNode {
17
+ execAsync(): Promise<unknown>;
18
+ }
19
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,46 @@
1
+ import { AsyncNode } from '../qflow.js';
2
+ const API_BASE = 'https://hacker-news.firebaseio.com/v0';
3
+ /**
4
+ * Fetches the top story IDs from the Hacker News API.
5
+ * @param {object} params - The parameters for the node.
6
+ * @param {number} [params.limit=10] - The maximum number of story IDs to return.
7
+ * @returns {Promise<number[]>} A promise that resolves to an array of story IDs.
8
+ */
9
+ export class GetTopStoriesNode extends AsyncNode {
10
+ async execAsync(prepRes, shared) {
11
+ const { limit = 10 } = this.params;
12
+ console.log(`[HackerNews] Fetching top ${limit} stories...`);
13
+ const response = await fetch(`${API_BASE}/topstories.json`);
14
+ if (!response.ok) {
15
+ throw new Error(`Hacker News API error: ${response.status}`);
16
+ }
17
+ const storyIds = await response.json();
18
+ const limitedIds = storyIds.slice(0, limit);
19
+ console.log(`[HackerNews] Found ${limitedIds.length} stories.`);
20
+ shared.storyIds = limitedIds;
21
+ return 'default';
22
+ }
23
+ }
24
+ /**
25
+ * Fetches the details of a specific item from the Hacker News API.
26
+ * @param {object} params - The parameters for the node.
27
+ * @param {number} params.id - The ID of the item to fetch.
28
+ * @returns {Promise<object>} A promise that resolves to the item details.
29
+ */
30
+ export class GetItemNode extends AsyncNode {
31
+ async execAsync() {
32
+ const { id } = this.params;
33
+ if (!id) {
34
+ throw new Error('Item ID is required for GetItemNode.');
35
+ }
36
+ console.log(`[HackerNews] Fetching item ${id}...`);
37
+ const response = await fetch(`${API_BASE}/item/${id}.json`);
38
+ if (!response.ok) {
39
+ throw new Error(`Hacker News API error: ${response.status}`);
40
+ }
41
+ const item = await response.json();
42
+ console.log(`[HackerNews] Fetched item title: ${item.title}`);
43
+ console.log(`[HackerNews] Fetched item: ${item.url}`);
44
+ return item;
45
+ }
46
+ }
@@ -0,0 +1,5 @@
1
+ export * from "./llm.js";
2
+ export * from "./hackernews.js";
3
+ export * from "./github.js";
4
+ export * from "./stripe.js";
5
+ export * from "./webscraper.js";
@@ -0,0 +1,5 @@
1
+ export * from './llm.js';
2
+ export * from './hackernews.js';
3
+ export * from './github.js';
4
+ export * from './stripe.js';
5
+ export * from './webscraper.js';
@@ -0,0 +1,11 @@
1
+ export class DeepSeekLLMNode extends AsyncNode {
2
+ preparePrompt(): void;
3
+ execAsync(): Promise<any>;
4
+ }
5
+ export class OpenAILLMNode extends AsyncNode {
6
+ execAsync(): Promise<any>;
7
+ }
8
+ export class GeminiLLMNode extends AsyncNode {
9
+ execAsync(): Promise<any>;
10
+ }
11
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,119 @@
1
+ import { AsyncNode } from '../qflow.js';
2
+ // --- Reusable LLM Node for DeepSeek ---
3
+ export class DeepSeekLLMNode extends AsyncNode {
4
+ constructor(maxRetries = 3, wait = 2) {
5
+ super(maxRetries, wait);
6
+ }
7
+ // This will be implemented by subclasses
8
+ preparePrompt() {
9
+ throw new Error("preparePrompt must be implemented by subclasses");
10
+ }
11
+ async execAsync() {
12
+ this.preparePrompt(); // Set the prompt
13
+ const { prompt, keyword, apiKey } = this.params;
14
+ if (!prompt) {
15
+ throw new Error("Prompt was not generated.");
16
+ }
17
+ if (!apiKey) {
18
+ throw new Error("DeepSeek API Key is not configured.");
19
+ }
20
+ console.log(`[DeepSeek] Sending prompt for \"${keyword}\"...`);
21
+ const response = await fetch('https://api.deepseek.com/chat/completions', {
22
+ method: 'POST',
23
+ headers: {
24
+ 'Content-Type': 'application/json',
25
+ 'Authorization': `Bearer ${apiKey}`
26
+ },
27
+ body: JSON.stringify({
28
+ model: 'deepseek-chat',
29
+ messages: [{ role: 'user', content: prompt }],
30
+ max_tokens: 2048,
31
+ temperature: 0.7,
32
+ })
33
+ });
34
+ if (!response.ok) {
35
+ const errorData = await response.json();
36
+ throw new Error(`DeepSeek API error: ${response.status} - ${errorData.error.message}`);
37
+ }
38
+ const data = await response.json();
39
+ if (!data.choices || data.choices.length === 0 || !data.choices[0].message || typeof data.choices[0].message.content !== 'string') {
40
+ throw new Error('Invalid response structure from DeepSeek API.');
41
+ }
42
+ const llmResponse = data.choices[0].message.content.trim();
43
+ console.log(`[DeepSeek] Received response for \"${keyword}\".`);
44
+ return llmResponse; // Return the actual content
45
+ }
46
+ }
47
+ export class OpenAILLMNode extends AsyncNode {
48
+ async execAsync() {
49
+ const { prompt, apiKey } = this.params; // prompt and apiKey passed via node params
50
+ if (!prompt) {
51
+ throw new Error('Prompt is required for OpenAILLMNode.');
52
+ }
53
+ if (!apiKey) {
54
+ throw new Error('OpenAI API Key is required.');
55
+ }
56
+ console.log(`OpenAILLMNode: Sending prompt to OpenAI: \"${prompt.substring(0, 50)}\"...`);
57
+ try {
58
+ const response = await fetch('https://api.openai.com/v1/chat/completions', {
59
+ method: 'POST',
60
+ headers: {
61
+ 'Content-Type': 'application/json',
62
+ 'Authorization': `Bearer ${apiKey}`
63
+ },
64
+ body: JSON.stringify({
65
+ model: 'gpt-3.5-turbo',
66
+ messages: [{ role: 'user', content: prompt }],
67
+ max_tokens: 150
68
+ })
69
+ });
70
+ if (!response.ok) {
71
+ const errorData = await response.json();
72
+ throw new Error(`OpenAI API error: ${response.status} - ${errorData.error.message}`);
73
+ }
74
+ const data = await response.json();
75
+ const llmResponse = data.choices[0].message.content.trim();
76
+ console.log(`OpenAILLMNode: Received response: \"${llmResponse.substring(0, 50)}\"...`);
77
+ return llmResponse; // Return the LLM's response
78
+ }
79
+ catch (error) {
80
+ console.error('OpenAILLMNode: Error during API call:', error);
81
+ throw error; // Re-throw to trigger qflow's retry/fallback
82
+ }
83
+ }
84
+ }
85
+ export class GeminiLLMNode extends AsyncNode {
86
+ async execAsync() {
87
+ const { prompt, apiKey } = this.params; // prompt and apiKey passed via node params
88
+ if (!prompt) {
89
+ throw new Error('Prompt is required for GeminiLLMNode.');
90
+ }
91
+ if (!apiKey) {
92
+ throw new Error('Google Gemini API Key is required.');
93
+ }
94
+ console.log(`GeminiLLMNode: Sending prompt to Gemini: \"${prompt.substring(0, 50)}\"...`);
95
+ try {
96
+ const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=${apiKey}`, {
97
+ method: 'POST',
98
+ headers: {
99
+ 'Content-Type': 'application/json'
100
+ },
101
+ body: JSON.stringify({
102
+ contents: [{ parts: [{ text: prompt }] }]
103
+ })
104
+ });
105
+ if (!response.ok) {
106
+ const errorData = await response.json();
107
+ throw new Error(`Gemini API error: ${response.status} - ${errorData.error.message}`);
108
+ }
109
+ const data = await response.json();
110
+ const llmResponse = data.candidates[0].content.parts[0].text.trim();
111
+ console.log(`GeminiLLMNode: Received response: \"${llmResponse.substring(0, 50)}\"...`);
112
+ return llmResponse; // Return the LLM's response
113
+ }
114
+ catch (error) {
115
+ console.error('GeminiLLMNode: Error during API call:', error);
116
+ throw error; // Re-throw to trigger qflow's retry/fallback
117
+ }
118
+ }
119
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Creates a new charge in Stripe.
3
+ * @param {object} params - The parameters for the node.
4
+ * @param {string} params.apiKey - The Stripe secret key.
5
+ * @param {number} params.amount - The amount to charge, in cents.
6
+ * @param {string} params.currency - The currency of the charge.
7
+ * @param {string} params.source - The source of the charge (e.g., a token).
8
+ * @param {string} [params.description] - The description of the charge.
9
+ * @returns {Promise<object>} A promise that resolves to the created charge object.
10
+ */
11
+ export class CreateChargeNode extends AsyncNode {
12
+ execAsync(): Promise<unknown>;
13
+ }
14
+ /**
15
+ * Retrieves the current account balance from Stripe.
16
+ * @param {object} params - The parameters for the node.
17
+ * @param {string} params.apiKey - The Stripe secret key.
18
+ * @returns {Promise<object>} A promise that resolves to the balance object.
19
+ */
20
+ export class GetBalanceNode extends AsyncNode {
21
+ execAsync(): Promise<unknown>;
22
+ }
23
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,68 @@
1
+ import { AsyncNode } from '../qflow.js';
2
+ const API_BASE = 'https://api.stripe.com/v1';
3
+ /**
4
+ * Creates a new charge in Stripe.
5
+ * @param {object} params - The parameters for the node.
6
+ * @param {string} params.apiKey - The Stripe secret key.
7
+ * @param {number} params.amount - The amount to charge, in cents.
8
+ * @param {string} params.currency - The currency of the charge.
9
+ * @param {string} params.source - The source of the charge (e.g., a token).
10
+ * @param {string} [params.description] - The description of the charge.
11
+ * @returns {Promise<object>} A promise that resolves to the created charge object.
12
+ */
13
+ export class CreateChargeNode extends AsyncNode {
14
+ async execAsync() {
15
+ const { apiKey, amount, currency, source, description } = this.params;
16
+ if (!apiKey || !amount || !currency || !source) {
17
+ throw new Error('Missing required parameters: apiKey, amount, currency, source');
18
+ }
19
+ console.log(`[Stripe] Creating charge for ${amount} ${currency}...`);
20
+ const response = await fetch(`${API_BASE}/charges`, {
21
+ method: 'POST',
22
+ headers: {
23
+ 'Authorization': `Bearer ${apiKey}`,
24
+ 'Content-Type': 'application/x-www-form-urlencoded'
25
+ },
26
+ body: new URLSearchParams({
27
+ amount,
28
+ currency,
29
+ source,
30
+ description
31
+ })
32
+ });
33
+ if (!response.ok) {
34
+ const errorData = await response.json();
35
+ throw new Error(`Stripe API error: ${response.status} - ${errorData.error.message}`);
36
+ }
37
+ const charge = await response.json();
38
+ console.log(`[Stripe] Successfully created charge ${charge.id}`);
39
+ return charge;
40
+ }
41
+ }
42
+ /**
43
+ * Retrieves the current account balance from Stripe.
44
+ * @param {object} params - The parameters for the node.
45
+ * @param {string} params.apiKey - The Stripe secret key.
46
+ * @returns {Promise<object>} A promise that resolves to the balance object.
47
+ */
48
+ export class GetBalanceNode extends AsyncNode {
49
+ async execAsync() {
50
+ const { apiKey } = this.params;
51
+ if (!apiKey) {
52
+ throw new Error('Missing required parameter: apiKey');
53
+ }
54
+ console.log('[Stripe] Getting account balance...');
55
+ const response = await fetch(`${API_BASE}/balance`, {
56
+ headers: {
57
+ 'Authorization': `Bearer ${apiKey}`
58
+ }
59
+ });
60
+ if (!response.ok) {
61
+ const errorData = await response.json();
62
+ throw new Error(`Stripe API error: ${response.status} - ${errorData.error.message}`);
63
+ }
64
+ const balance = await response.json();
65
+ console.log('[Stripe] Successfully retrieved account balance.');
66
+ return balance;
67
+ }
68
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Fetches the HTML content of a given URL.
3
+ * @param {object} params - The parameters for the node.
4
+ * @param {string} params.url - The URL to scrape.
5
+ * @returns {Promise<string>} A promise that resolves to the HTML content of the page.
6
+ */
7
+ export class ScrapeURLNode extends AsyncNode {
8
+ execAsync(): Promise<string>;
9
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
10
+ }
11
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,28 @@
1
+ import { AsyncNode } from '../qflow.js';
2
+ /**
3
+ * Fetches the HTML content of a given URL.
4
+ * @param {object} params - The parameters for the node.
5
+ * @param {string} params.url - The URL to scrape.
6
+ * @returns {Promise<string>} A promise that resolves to the HTML content of the page.
7
+ */
8
+ export class ScrapeURLNode extends AsyncNode {
9
+ async execAsync() {
10
+ const { url } = this.params;
11
+ if (!url) {
12
+ throw new Error('URL is required for ScrapeURLNode.');
13
+ }
14
+ console.log(`[WebScraper] Scraping URL: ${url}...`);
15
+ const response = await fetch(url);
16
+ if (!response.ok) {
17
+ throw new Error(`Failed to fetch URL: ${response.status} - ${response.statusText}`);
18
+ }
19
+ const html = await response.text();
20
+ console.log(`[WebScraper] Successfully scraped URL: ${url}`);
21
+ return html;
22
+ }
23
+ async postAsync(shared, prepRes, execRes) {
24
+ // The scraped HTML (execRes) will be passed as prepRes to the next node.
25
+ // We don't need to store it in shared for this specific flow.
26
+ return 'default';
27
+ }
28
+ }
@@ -0,0 +1,66 @@
1
+ export class BaseNode {
2
+ params: {};
3
+ successors: {};
4
+ setParams(params: any): void;
5
+ next(node: any, action?: string): any;
6
+ prep(shared: any): void;
7
+ exec(prepRes: any): void;
8
+ post(shared: any, prepRes: any, execRes: any): any;
9
+ _exec(prepRes: any): void;
10
+ _run(shared: any): any;
11
+ run(shared: any): any;
12
+ transition(action: any): ConditionalTransition;
13
+ }
14
+ export class Node extends BaseNode {
15
+ constructor(maxRetries?: number, wait?: number);
16
+ maxRetries: number;
17
+ wait: number;
18
+ execFallback(prepRes: any, error: any): void;
19
+ _exec(prepRes: any, shared: any): void;
20
+ }
21
+ export class BatchNode extends Node {
22
+ _exec(items: any): any;
23
+ }
24
+ export class Flow extends BaseNode {
25
+ constructor(start?: null);
26
+ startNode: any;
27
+ start(startNode: any): any;
28
+ getNextNode(curr: any, action: any): any;
29
+ _orch(shared: any, params?: {}): any;
30
+ }
31
+ export class BatchFlow extends Flow {
32
+ }
33
+ export class AsyncNode extends Node {
34
+ prepAsync(shared: any): Promise<void>;
35
+ execAsync(prepRes: any): Promise<void>;
36
+ execFallbackAsync(prepRes: any, error: any): Promise<void>;
37
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<void>;
38
+ _exec(prepRes: any, shared: any): Promise<void>;
39
+ runAsync(shared: any): Promise<void>;
40
+ _runAsync(shared: any): Promise<void>;
41
+ _run(): void;
42
+ }
43
+ export class AsyncBatchNode extends AsyncNode {
44
+ _exec(items: any): Promise<void[]>;
45
+ }
46
+ export class AsyncParallelBatchNode extends AsyncNode {
47
+ _exec(items: any): Promise<any[]>;
48
+ }
49
+ export class AsyncFlow extends Flow {
50
+ prepAsync(shared: any): Promise<void>;
51
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
52
+ _orchAsync(shared: any, params?: {}, initialNode?: any): Promise<any>;
53
+ _runAsync(shared: any): Promise<any>;
54
+ run(): void;
55
+ runAsync(shared: any): Promise<any>;
56
+ }
57
+ export class AsyncBatchFlow extends AsyncFlow {
58
+ }
59
+ export class AsyncParallelBatchFlow extends AsyncFlow {
60
+ }
61
+ export class ConditionalTransition {
62
+ constructor(src: any, action: any);
63
+ src: any;
64
+ action: any;
65
+ to(tgt: any): any;
66
+ }
package/dist/qflow.js ADDED
@@ -0,0 +1,235 @@
1
+ class BaseNode {
2
+ constructor() {
3
+ this.params = {};
4
+ this.successors = {};
5
+ }
6
+ setParams(params) {
7
+ this.params = params;
8
+ }
9
+ next(node, action = "default") {
10
+ if (this.successors[action]) {
11
+ console.warn(`Overwriting successor for action '${action}'`);
12
+ }
13
+ this.successors[action] = node;
14
+ return node;
15
+ }
16
+ prep(shared) { }
17
+ exec(prepRes) { }
18
+ post(shared, prepRes, execRes) {
19
+ return execRes;
20
+ }
21
+ _exec(prepRes) {
22
+ return this.exec(prepRes);
23
+ }
24
+ _run(shared) {
25
+ const prepRes = this.prep(shared);
26
+ const execRes = this._exec(prepRes, shared);
27
+ return this.post(shared, prepRes, execRes);
28
+ }
29
+ run(shared) {
30
+ if (Object.keys(this.successors).length) {
31
+ console.warn("Node won't run successors. Use Flow.");
32
+ }
33
+ return this._run(shared);
34
+ }
35
+ transition(action) {
36
+ return new ConditionalTransition(this, action);
37
+ }
38
+ }
39
+ class ConditionalTransition {
40
+ constructor(src, action) {
41
+ this.src = src;
42
+ this.action = action;
43
+ }
44
+ to(tgt) {
45
+ return this.src.next(tgt, this.action);
46
+ }
47
+ }
48
+ class Node extends BaseNode {
49
+ constructor(maxRetries = 1, wait = 0) {
50
+ super();
51
+ this.maxRetries = maxRetries;
52
+ this.wait = wait;
53
+ }
54
+ execFallback(prepRes, error) {
55
+ throw error;
56
+ }
57
+ _exec(prepRes, shared) {
58
+ for (let i = 0; i < this.maxRetries; i++) {
59
+ try {
60
+ return this.exec(prepRes, shared);
61
+ }
62
+ catch (e) {
63
+ if (i === this.maxRetries - 1)
64
+ return this.execFallback(prepRes, e);
65
+ if (this.wait > 0)
66
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, this.wait * 1000);
67
+ }
68
+ }
69
+ }
70
+ }
71
+ class BatchNode extends Node {
72
+ _exec(items) {
73
+ return (items || []).map(item => super._exec(item));
74
+ }
75
+ }
76
+ class Flow extends BaseNode {
77
+ constructor(start = null) {
78
+ super();
79
+ this.startNode = start;
80
+ }
81
+ start(startNode) {
82
+ this.startNode = startNode;
83
+ return startNode;
84
+ }
85
+ getNextNode(curr, action) {
86
+ const nxt = curr.successors[action || "default"];
87
+ if (!nxt && Object.keys(curr.successors).length) {
88
+ console.warn(`Flow ends: '${action}' not found in [${Object.keys(curr.successors)}]`);
89
+ }
90
+ return nxt;
91
+ }
92
+ _orch(shared, params = {}) {
93
+ let curr = this.startNode;
94
+ let lastAction = null;
95
+ let p = { ...this.params, ...params };
96
+ while (curr) {
97
+ curr.setParams(p);
98
+ lastAction = curr._run(shared);
99
+ curr = this.getNextNode(curr, lastAction);
100
+ }
101
+ return lastAction;
102
+ }
103
+ _run(shared) {
104
+ const prepRes = this.prep(shared);
105
+ const out = this._orch(shared);
106
+ return this.post(shared, prepRes, out);
107
+ }
108
+ post(shared, prepRes, execRes) {
109
+ return execRes;
110
+ }
111
+ }
112
+ class BatchFlow extends Flow {
113
+ _run(shared) {
114
+ const prepResults = this.prep(shared) || [];
115
+ const results = [];
116
+ for (const bp of prepResults) {
117
+ results.push(this._orch(shared, { ...this.params, ...bp }));
118
+ }
119
+ return this.post(shared, prepResults, results);
120
+ }
121
+ }
122
+ // ----------- ASYNC VERSIONS ------------
123
+ class AsyncNode extends Node {
124
+ async prepAsync(shared) { }
125
+ async execAsync(prepRes) { }
126
+ async execFallbackAsync(prepRes, error) {
127
+ throw error;
128
+ }
129
+ async postAsync(shared, prepRes, execRes) { }
130
+ async _exec(prepRes, shared) {
131
+ for (let i = 0; i < this.maxRetries; i++) {
132
+ try {
133
+ return await this.execAsync(prepRes, shared);
134
+ }
135
+ catch (e) {
136
+ if (i === this.maxRetries - 1)
137
+ return await this.execFallbackAsync(prepRes, e);
138
+ if (this.wait > 0)
139
+ await new Promise(resolve => setTimeout(resolve, this.wait * 1000));
140
+ }
141
+ }
142
+ }
143
+ async runAsync(shared) {
144
+ if (Object.keys(this.successors).length) {
145
+ console.warn("Node won't run successors. Use AsyncFlow.");
146
+ }
147
+ return await this._runAsync(shared);
148
+ }
149
+ async _runAsync(shared) {
150
+ const prepRes = await this.prepAsync(shared);
151
+ const execRes = await this._exec(prepRes, shared);
152
+ return await this.postAsync(shared, prepRes, execRes);
153
+ }
154
+ _run() {
155
+ throw new Error("Use runAsync instead.");
156
+ }
157
+ }
158
+ class AsyncBatchNode extends AsyncNode {
159
+ async _exec(items) {
160
+ const results = [];
161
+ for (const item of items) {
162
+ results.push(await super._exec(item));
163
+ }
164
+ return results;
165
+ }
166
+ }
167
+ class AsyncParallelBatchNode extends AsyncNode {
168
+ async _exec(items) {
169
+ return await Promise.all(items.map(item => super._exec(item)));
170
+ }
171
+ }
172
+ class AsyncFlow extends Flow {
173
+ async prepAsync(shared) { }
174
+ async postAsync(shared, prepRes, execRes) {
175
+ return execRes;
176
+ }
177
+ async _orchAsync(shared, params = {}, initialNode = this.startNode) {
178
+ let curr = initialNode;
179
+ let lastAction = null;
180
+ let lastExecRes = null;
181
+ let p = { ...this.params, ...params };
182
+ let currentPrepRes = undefined; // This will hold the prepRes for the current node
183
+ while (curr) {
184
+ curr.setParams(p);
185
+ // If there was a previous execution result, that becomes the prepRes for the current node.
186
+ // Otherwise, use the current node's own prepAsync/prep method.
187
+ if (lastExecRes !== null) {
188
+ currentPrepRes = lastExecRes;
189
+ }
190
+ else {
191
+ currentPrepRes = curr instanceof AsyncNode ? await curr.prepAsync(shared) : curr.prep(shared);
192
+ }
193
+ const execRes = curr instanceof AsyncNode ? await curr._exec(currentPrepRes, shared) : curr._exec(currentPrepRes, shared);
194
+ lastAction = curr instanceof AsyncNode ? await curr.postAsync(shared, currentPrepRes, execRes) : curr.post(shared, currentPrepRes, execRes);
195
+ lastExecRes = execRes; // Store execRes for the next iteration
196
+ curr = this.getNextNode(curr, lastAction);
197
+ }
198
+ return lastExecRes;
199
+ }
200
+ async _runAsync(shared) {
201
+ const prepRes = await this.prepAsync(shared);
202
+ const result = await this._orchAsync(shared);
203
+ return await this.postAsync(shared, prepRes, result);
204
+ }
205
+ run() {
206
+ throw new Error("Use runAsync instead.");
207
+ }
208
+ async runAsync(shared) {
209
+ return await this._runAsync(shared);
210
+ }
211
+ }
212
+ class AsyncBatchFlow extends AsyncFlow {
213
+ async _runAsync(shared) {
214
+ const prepResults = await this.prepAsync(shared) || [];
215
+ const results = [];
216
+ for (const bp of prepResults) {
217
+ results.push(await this._orchAsync(shared, { ...this.params, ...bp }));
218
+ }
219
+ return await this.postAsync(shared, prepResults, results);
220
+ }
221
+ }
222
+ class AsyncParallelBatchFlow extends AsyncFlow {
223
+ async _runAsync(shared) {
224
+ const prepResults = await this.prepAsync(shared) || [];
225
+ const results = await Promise.all(prepResults.map(bp => {
226
+ // Create a new instance of the startNode for each batch item
227
+ const newStartNode = new this.startNode.constructor();
228
+ // Copy successors from the original startNode to the new instance
229
+ Object.assign(newStartNode.successors, this.startNode.successors);
230
+ return this._orchAsync(shared, { ...this.params, ...bp }, newStartNode);
231
+ }));
232
+ return await this.postAsync(shared, prepResults, results);
233
+ }
234
+ }
235
+ export { BaseNode, Node, BatchNode, Flow, BatchFlow, AsyncNode, AsyncBatchNode, AsyncParallelBatchNode, AsyncFlow, AsyncBatchFlow, AsyncParallelBatchFlow, ConditionalTransition };
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@fractal-solutions/qflow",
3
+ "version": "1.0.0",
4
+ "description": "A lightweight and flexible JavaScript library for creating and managing workflows and agents.",
5
+ "main": "dist/qflow.js",
6
+ "types": "dist/qflow.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/qflow.d.ts",
10
+ "default": "./dist/qflow.js"
11
+ },
12
+ "./nodes": {
13
+ "types": "./dist/nodes/index.d.ts",
14
+ "default": "./dist/nodes/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist/",
19
+ "README.md"
20
+ ],
21
+ "scripts": {
22
+ "test": "bun test",
23
+ "build": "tsc --project tsconfig.build.json"
24
+ },
25
+ "keywords": [
26
+ "workflow",
27
+ "agents",
28
+ "pipeline",
29
+ "automation",
30
+ "flow",
31
+ "async",
32
+ "batch"
33
+ ],
34
+ "author": "Fractal Solutions",
35
+ "license": "MIT",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "https://github.com/fractal-solutions/qflow.git"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/fractal-solutions/qflow/issues"
42
+ },
43
+ "homepage": "https://github.com/fractal-solutions/qflow#readme",
44
+ "devDependencies": {
45
+ "@types/bun": "latest"
46
+ },
47
+ "peerDependencies": {
48
+ "typescript": "^5"
49
+ }
50
+ }