@forgehive/runner 0.1.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 ForgeHive
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,34 @@
1
+ import { TaskInstanceType, BaseFunction } from '@forgehive/task';
2
+ type TaskRecord<T extends TaskInstanceType = TaskInstanceType> = {
3
+ task: T;
4
+ };
5
+ type Tasks = Record<string, TaskRecord>;
6
+ export interface RunnerParsedArguments {
7
+ taskName: string;
8
+ args: unknown;
9
+ }
10
+ export declare class Runner<InputType = unknown, ParseResult extends RunnerParsedArguments = RunnerParsedArguments> {
11
+ _tasks: Tasks;
12
+ parseArguments: (data: InputType) => ParseResult;
13
+ handler: (data: InputType) => Promise<unknown>;
14
+ constructor(parseArgumentsFn?: (data: InputType) => ParseResult);
15
+ /**
16
+ * Set a custom handler function
17
+ * @param handlerFn The custom handler function
18
+ */
19
+ setHandler(handlerFn: (data: InputType) => Promise<unknown>): void;
20
+ /**
21
+ * Default handler implementation
22
+ * @param data Input data
23
+ * @returns Output data
24
+ */
25
+ private defaultHandler;
26
+ describe(): void;
27
+ load<T extends BaseFunction>(name: string, task: TaskInstanceType<T>): void;
28
+ getTask<T extends BaseFunction = BaseFunction>(name: string): TaskInstanceType<T> | undefined;
29
+ getTasks(): Tasks;
30
+ getTaskList(): string[];
31
+ run<T extends BaseFunction, P extends Parameters<T>[0], R = ReturnType<T>>(name: string, args: P): Promise<Awaited<R>>;
32
+ }
33
+ export default Runner;
34
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAEhE,KAAK,UAAU,CAAC,CAAC,SAAS,gBAAgB,GAAG,gBAAgB,IAAI;IAC/D,IAAI,EAAE,CAAC,CAAA;CACR,CAAA;AAED,KAAK,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAA;AAGvC,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,OAAO,CAAC;CACf;AAED,qBAAa,MAAM,CAAC,SAAS,GAAG,OAAO,EAAE,WAAW,SAAS,qBAAqB,GAAG,qBAAqB;IACjG,MAAM,EAAE,KAAK,CAAA;IACb,cAAc,EAAE,CAAC,IAAI,EAAE,SAAS,KAAK,WAAW,CAAA;IAChD,OAAO,EAAE,CAAC,IAAI,EAAE,SAAS,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;gBAEzC,gBAAgB,CAAC,EAAE,CAAC,IAAI,EAAE,SAAS,KAAK,WAAW;IAsB/D;;;OAGG;IACH,UAAU,CAAC,SAAS,EAAE,CAAC,IAAI,EAAE,SAAS,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI;IAIlE;;;;OAIG;YACW,cAAc;IAM5B,QAAQ,IAAI,IAAI;IAQhB,IAAI,CAAC,CAAC,SAAS,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,IAAI;IAI3E,OAAO,CAAC,CAAC,SAAS,YAAY,GAAG,YAAY,EAAE,IAAI,EAAE,MAAM,GAAG,gBAAgB,CAAC,CAAC,CAAC,GAAG,SAAS;IAU7F,QAAQ,IAAI,KAAK;IAIjB,WAAW,IAAI,MAAM,EAAE;IAIjB,GAAG,CAAC,CAAC,SAAS,YAAY,EAAE,CAAC,SAAS,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,EAC7E,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,CAAC,GACN,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;CAgBvB;AAED,eAAe,MAAM,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Runner = void 0;
4
+ class Runner {
5
+ constructor(parseArgumentsFn) {
6
+ this._tasks = {};
7
+ // Use provided parseArguments function or default implementation
8
+ this.parseArguments = parseArgumentsFn || ((data) => {
9
+ // Check if data is an object and has the expected properties
10
+ if (data && typeof data === 'object' && 'task' in data && 'args' in data) {
11
+ return {
12
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
13
+ taskName: String(data.task),
14
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
+ args: data.args
16
+ };
17
+ }
18
+ // If data doesn't have the expected structure, throw an error
19
+ throw new Error('Invalid task data: expected object with task and args properties');
20
+ });
21
+ // Set default handler
22
+ this.handler = this.defaultHandler.bind(this);
23
+ }
24
+ /**
25
+ * Set a custom handler function
26
+ * @param handlerFn The custom handler function
27
+ */
28
+ setHandler(handlerFn) {
29
+ this.handler = handlerFn;
30
+ }
31
+ /**
32
+ * Default handler implementation
33
+ * @param data Input data
34
+ * @returns Output data
35
+ */
36
+ async defaultHandler(data) {
37
+ const { taskName, args } = this.parseArguments(data);
38
+ const res = await this.run(taskName, args);
39
+ return res;
40
+ }
41
+ describe() {
42
+ const listItems = this.getTaskList();
43
+ console.log('Available tasks:');
44
+ listItems.forEach(taskName => {
45
+ console.log(`- ${taskName}`);
46
+ });
47
+ }
48
+ load(name, task) {
49
+ this._tasks[name] = { task };
50
+ }
51
+ getTask(name) {
52
+ if (this._tasks[name] === undefined) {
53
+ return undefined;
54
+ }
55
+ const { task } = this._tasks[name];
56
+ return task;
57
+ }
58
+ getTasks() {
59
+ return this._tasks;
60
+ }
61
+ getTaskList() {
62
+ return Object.keys(this._tasks);
63
+ }
64
+ async run(name, args) {
65
+ const exists = this._tasks[name];
66
+ if (exists === undefined) {
67
+ throw new Error(`Task ${name} not found`);
68
+ }
69
+ const { task } = exists;
70
+ if (task === undefined) {
71
+ throw new Error(`Task ${name} not found`);
72
+ }
73
+ const results = await task.run(args);
74
+ return results;
75
+ }
76
+ }
77
+ exports.Runner = Runner;
78
+ exports.default = Runner;
79
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAeA,MAAa,MAAM;IAKjB,YAAY,gBAAmD;QAC7D,IAAI,CAAC,MAAM,GAAG,EAAE,CAAA;QAChB,iEAAiE;QACjE,IAAI,CAAC,cAAc,GAAG,gBAAgB,IAAI,CAAC,CAAC,IAAe,EAAe,EAAE;YAC1E,6DAA6D;YAC7D,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;gBACzE,OAAO;oBACL,8DAA8D;oBAC9D,QAAQ,EAAE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IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;QAElC,OAAO,IAA2B,CAAA;IACpC,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;IAED,WAAW;QACT,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IACjC,CAAC;IAED,KAAK,CAAC,GAAG,CACP,IAAY,EACZ,IAAO;QAEP,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;QAEhC,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,QAAQ,IAAI,YAAY,CAAC,CAAA;QAC3C,CAAC;QAED,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAA;QAEvB,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,MAAM,IAAI,KAAK,CAAC,QAAQ,IAAI,YAAY,CAAC,CAAA;QAC3C,CAAC;QAED,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QACpC,OAAO,OAAqB,CAAA;IAC9B,CAAC;CACF;AA/FD,wBA+FC;AAED,kBAAe,MAAM,CAAA"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=runner.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner.test.d.ts","sourceRoot":"","sources":["../../src/test/runner.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /* eslint-disable @typescript-eslint/no-unused-vars */
4
+ const index_1 = require("../index");
5
+ const task_1 = require("@forgehive/task");
6
+ describe('Runner', () => {
7
+ it('should create a new Runner instance', () => {
8
+ const runner = new index_1.Runner();
9
+ expect(runner).toBeInstanceOf(index_1.Runner);
10
+ expect(runner._tasks).toEqual({});
11
+ });
12
+ it('should throw error when running non-existent task', async () => {
13
+ const runner = new index_1.Runner();
14
+ await expect(runner.run('nonExistentTask', {}))
15
+ .rejects.toThrow('Task nonExistentTask not found');
16
+ });
17
+ it('should handle arguments correctly', () => {
18
+ const runner = new index_1.Runner();
19
+ const data = {
20
+ task: 'testTask',
21
+ args: { value: 'test' }
22
+ };
23
+ const parsed = runner.parseArguments(data);
24
+ expect(parsed).toEqual({
25
+ taskName: 'testTask',
26
+ args: { value: 'test' }
27
+ });
28
+ });
29
+ it('should run a task', async () => {
30
+ const task = new task_1.Task(() => {
31
+ return 'hi five!!!';
32
+ });
33
+ const runner = new index_1.Runner();
34
+ runner.load('sample', task);
35
+ const result = await runner.run('sample', {});
36
+ expect(result).toBe('hi five!!!');
37
+ });
38
+ it('should run a task with params', async () => {
39
+ const taskInt = new task_1.Task(({ int }) => {
40
+ return int + 5;
41
+ });
42
+ const runner = new index_1.Runner();
43
+ runner.load('sample', taskInt);
44
+ const result = await runner.run('sample', { int: 6 });
45
+ expect(result).toBe(11);
46
+ });
47
+ it('should run multiple tasks with different params', async () => {
48
+ const taskInt = new task_1.Task(({ int }) => {
49
+ return int + 5;
50
+ });
51
+ const taskString = new task_1.Task(({ str }) => {
52
+ return str + ' world';
53
+ });
54
+ const runner = new index_1.Runner();
55
+ runner.load('int', taskInt);
56
+ runner.load('string', taskString);
57
+ const int = await runner.run('int', { int: 6 });
58
+ const str = await runner.run('string', { str: 'hello' });
59
+ expect(int).toBe(11);
60
+ expect(str).toBe('hello world');
61
+ });
62
+ it('should get task back and be able to run it', async () => {
63
+ const taskInt = new task_1.Task(async ({ int }) => {
64
+ return int + 5;
65
+ });
66
+ const indentity = new task_1.Task(async function ({ int }) {
67
+ return int + 5;
68
+ });
69
+ const runner = new index_1.Runner();
70
+ runner.load('int', taskInt);
71
+ const task = runner.getTask('int');
72
+ let int = 0;
73
+ if (task !== undefined) {
74
+ int = await task.run({ int: 6 });
75
+ }
76
+ const int2 = await taskInt.run({ int: 6 });
77
+ const int3 = await indentity.run({ int: 6 });
78
+ expect(int).toBe(11);
79
+ expect(int2).toBe(11);
80
+ expect(int3).toBe(11);
81
+ });
82
+ it('should return undefined if task does not exist', async () => {
83
+ const runner = new index_1.Runner();
84
+ const task = runner.getTask('int');
85
+ expect(task).toBeUndefined();
86
+ });
87
+ });
88
+ //# sourceMappingURL=runner.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner.test.js","sourceRoot":"","sources":["../../src/test/runner.test.ts"],"names":[],"mappings":";;AAAA,sDAAsD;AACtD,oCAAiC;AACjC,0CAAsC;AAEtC,QAAQ,CAAC,QAAQ,EAAE,GAAG,EAAE;IACtB,EAAE,CAAC,qCAAqC,EAAE,GAAG,EAAE;QAC7C,MAAM,MAAM,GAAG,IAAI,cAAM,EAAE,CAAA;QAC3B,MAAM,CAAC,MAAM,CAAC,CAAC,cAAc,CAAC,cAAM,CAAC,CAAA;QACrC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;IACnC,CAAC,CAAC,CAAA;IAGF,EAAE,CAAC,mDAAmD,EAAE,KAAK,IAAI,EAAE;QACjE,MAAM,MAAM,GAAG,IAAI,cAAM,EAAE,CAAA;QAC3B,MAAM,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC;aAC5C,OAAO,CAAC,OAAO,CAAC,gCAAgC,CAAC,CAAA;IACtD,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,mCAAmC,EAAE,GAAG,EAAE;QAC3C,MAAM,MAAM,GAAG,IAAI,cAAM,EAAE,CAAA;QAC3B,MAAM,IAAI,GAAG;YACX,IAAI,EAAE,UAAU;YAChB,IAAI,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE;SACxB,CAAA;QAED,MAAM,MAAM,GAAG,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAA;QAE1C,MAAM,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC;YACrB,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GAAG,GAAG,CAAC,CAAA;QACX,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,GAAG,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,CAAA;QAClC,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,CAAA;QAC1C,MAAM,IAAI,GAAG,MAAM,SAAS,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,CAAA;QAE5C,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;QACpB,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;QACrB,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;IACvB,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,gDAAgD,EAAE,KAAK,IAAI,EAAE;QAC9D,MAAM,MAAM,GAAG,IAAI,cAAM,EAAE,CAAA;QAC3B,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;QAElC,MAAM,CAAC,IAAI,CAAC,CAAC,aAAa,EAAE,CAAA;IAC9B,CAAC,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA"}
package/jest.config.js ADDED
@@ -0,0 +1,7 @@
1
+ /** @type {import('ts-jest').JestConfigWithTsJest} */
2
+ module.exports = {
3
+ preset: 'ts-jest',
4
+ testEnvironment: 'node',
5
+ testMatch: ['**/*.test.ts'],
6
+ collectCoverageFrom: ['src/**/*.ts']
7
+ };
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@forgehive/runner",
3
+ "version": "0.1.2",
4
+ "license": "MIT",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "publishConfig": {
9
+ "access": "public",
10
+ "dependencies": {
11
+ "@forgehive/schema": "^0.1.0",
12
+ "@forgehive/task": "^0.1.1"
13
+ }
14
+ },
15
+ "scripts": {
16
+ "build": "tsc",
17
+ "dev": "tsc --watch",
18
+ "clean": "rm -rf dist",
19
+ "test": "jest"
20
+ },
21
+ "dependencies": {
22
+ "@forgehive/schema": "0.1.0",
23
+ "@forgehive/task": "0.1.1"
24
+ },
25
+ "devDependencies": {
26
+ "@types/jest": "^29.5.12",
27
+ "@types/node": "^20.11.19",
28
+ "jest": "^29.7.0",
29
+ "ts-jest": "^29.1.2",
30
+ "typescript": "^5.3.3"
31
+ },
32
+ "gitHead": "0e8d2be05c08abeb14c5ac0c48d5ed367a7caafd"
33
+ }
package/src/index.ts ADDED
@@ -0,0 +1,113 @@
1
+ /* eslint-disable no-console */
2
+ import { TaskInstanceType, BaseFunction } from '@forgehive/task'
3
+
4
+ type TaskRecord<T extends TaskInstanceType = TaskInstanceType> = {
5
+ task: T
6
+ }
7
+
8
+ type Tasks = Record<string, TaskRecord>
9
+
10
+ // Define the base parsed arguments interface
11
+ export interface RunnerParsedArguments {
12
+ taskName: string;
13
+ args: unknown;
14
+ }
15
+
16
+ export class Runner<InputType = unknown, ParseResult extends RunnerParsedArguments = RunnerParsedArguments> {
17
+ public _tasks: Tasks
18
+ public parseArguments: (data: InputType) => ParseResult
19
+ public handler: (data: InputType) => Promise<unknown>
20
+
21
+ constructor(parseArgumentsFn?: (data: InputType) => ParseResult) {
22
+ this._tasks = {}
23
+ // Use provided parseArguments function or default implementation
24
+ this.parseArguments = parseArgumentsFn || ((data: InputType): ParseResult => {
25
+ // Check if data is an object and has the expected properties
26
+ if (data && typeof data === 'object' && 'task' in data && 'args' in data) {
27
+ return {
28
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
29
+ taskName: String((data as any).task),
30
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
31
+ args: (data as any).args
32
+ } as unknown as ParseResult
33
+ }
34
+
35
+ // If data doesn't have the expected structure, throw an error
36
+ throw new Error('Invalid task data: expected object with task and args properties')
37
+ })
38
+
39
+ // Set default handler
40
+ this.handler = this.defaultHandler.bind(this)
41
+ }
42
+
43
+ /**
44
+ * Set a custom handler function
45
+ * @param handlerFn The custom handler function
46
+ */
47
+ setHandler(handlerFn: (data: InputType) => Promise<unknown>): void {
48
+ this.handler = handlerFn
49
+ }
50
+
51
+ /**
52
+ * Default handler implementation
53
+ * @param data Input data
54
+ * @returns Output data
55
+ */
56
+ private async defaultHandler(data: InputType): Promise<unknown> {
57
+ const { taskName, args } = this.parseArguments(data)
58
+ const res = await this.run(taskName, args)
59
+ return res
60
+ }
61
+
62
+ describe(): void {
63
+ const listItems: string[] = this.getTaskList()
64
+ console.log('Available tasks:')
65
+ listItems.forEach(taskName => {
66
+ console.log(`- ${taskName}`)
67
+ })
68
+ }
69
+
70
+ load<T extends BaseFunction>(name: string, task: TaskInstanceType<T>): void {
71
+ this._tasks[name] = { task }
72
+ }
73
+
74
+ getTask<T extends BaseFunction = BaseFunction>(name: string): TaskInstanceType<T> | undefined {
75
+ if (this._tasks[name] === undefined) {
76
+ return undefined
77
+ }
78
+
79
+ const { task } = this._tasks[name]
80
+
81
+ return task as TaskInstanceType<T>
82
+ }
83
+
84
+ getTasks(): Tasks {
85
+ return this._tasks
86
+ }
87
+
88
+ getTaskList(): string[] {
89
+ return Object.keys(this._tasks)
90
+ }
91
+
92
+ async run<T extends BaseFunction, P extends Parameters<T>[0], R = ReturnType<T>>(
93
+ name: string,
94
+ args: P
95
+ ): Promise<Awaited<R>> {
96
+ const exists = this._tasks[name]
97
+
98
+ if (exists === undefined) {
99
+ throw new Error(`Task ${name} not found`)
100
+ }
101
+
102
+ const { task } = exists
103
+
104
+ if (task === undefined) {
105
+ throw new Error(`Task ${name} not found`)
106
+ }
107
+
108
+ const results = await task.run(args)
109
+ return results as Awaited<R>
110
+ }
111
+ }
112
+
113
+ export default Runner
@@ -0,0 +1,112 @@
1
+ /* eslint-disable @typescript-eslint/no-unused-vars */
2
+ import { Runner } from '../index'
3
+ import { Task } from '@forgehive/task'
4
+
5
+ describe('Runner', () => {
6
+ it('should create a new Runner instance', () => {
7
+ const runner = new Runner()
8
+ expect(runner).toBeInstanceOf(Runner)
9
+ expect(runner._tasks).toEqual({})
10
+ })
11
+
12
+
13
+ it('should throw error when running non-existent task', async () => {
14
+ const runner = new Runner()
15
+ await expect(runner.run('nonExistentTask', {}))
16
+ .rejects.toThrow('Task nonExistentTask not found')
17
+ })
18
+
19
+ it('should handle arguments correctly', () => {
20
+ const runner = new Runner()
21
+ const data = {
22
+ task: 'testTask',
23
+ args: { value: 'test' }
24
+ }
25
+
26
+ const parsed = runner.parseArguments(data)
27
+
28
+ expect(parsed).toEqual({
29
+ taskName: 'testTask',
30
+ args: { value: 'test' }
31
+ })
32
+ })
33
+
34
+ it('should run a task', async () => {
35
+ const task = new Task(() => {
36
+ return 'hi five!!!'
37
+ })
38
+
39
+ const runner = new Runner()
40
+ runner.load('sample', task)
41
+
42
+ const result = await runner.run('sample', {})
43
+
44
+ expect(result).toBe('hi five!!!')
45
+ })
46
+
47
+ it('should run a task with params', async () => {
48
+ const taskInt = new Task(({ int }: { int: number }) => {
49
+ return int + 5
50
+ })
51
+
52
+ const runner = new Runner()
53
+ runner.load('sample', taskInt)
54
+
55
+ const result = await runner.run<typeof taskInt['_fn'], { int: number }, number>('sample', { int: 6 })
56
+
57
+ expect(result).toBe(11)
58
+ })
59
+
60
+ it('should run multiple tasks with different params', async () => {
61
+ const taskInt = new Task(({ int }: { int: number }) => {
62
+ return int + 5
63
+ })
64
+
65
+ const taskString = new Task(({ str }: { str: string }) => {
66
+ return str + ' world'
67
+ })
68
+
69
+ const runner = new Runner()
70
+ runner.load('int', taskInt)
71
+ runner.load('string', taskString)
72
+
73
+ const int = await runner.run<typeof taskInt['_fn'], { int: number }, number>('int', { int: 6 })
74
+ const str = await runner.run<typeof taskString['_fn'], { str: string }, string>('string', { str: 'hello' })
75
+
76
+ expect(int).toBe(11)
77
+ expect(str).toBe('hello world')
78
+ })
79
+
80
+ it('should get task back and be able to run it', async () => {
81
+ const taskInt = new Task(async ({ int }: { int: number }): Promise<number> => {
82
+ return int + 5
83
+ })
84
+
85
+ const indentity = new Task(async function ({ int }: { int: number }): Promise<number> {
86
+ return int + 5
87
+ })
88
+
89
+ const runner = new Runner()
90
+ runner.load('int', taskInt)
91
+
92
+ const task = runner.getTask<typeof taskInt['_fn']>('int')
93
+
94
+ let int = 0
95
+ if (task !== undefined) {
96
+ int = await task.run({ int: 6 })
97
+ }
98
+ const int2 = await taskInt.run({ int: 6 })
99
+ const int3 = await indentity.run({ int: 6 })
100
+
101
+ expect(int).toBe(11)
102
+ expect(int2).toBe(11)
103
+ expect(int3).toBe(11)
104
+ })
105
+
106
+ it('should return undefined if task does not exist', async () => {
107
+ const runner = new Runner()
108
+ const task = runner.getTask('int')
109
+
110
+ expect(task).toBeUndefined()
111
+ })
112
+ })
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist",
5
+ "rootDir": "./src",
6
+ "composite": false,
7
+ "incremental": false,
8
+ "declaration": true,
9
+ "declarationMap": true,
10
+ "sourceMap": true
11
+ },
12
+ "include": [
13
+ "src/**/*"
14
+ ],
15
+ "exclude": [
16
+ "node_modules",
17
+ "dist"
18
+ ]
19
+ }