Skip to content

Commit 13fc8db

Browse files
committed
Add an integration test for worker thread TS compilation
1 parent 3f9333d commit 13fc8db

File tree

5 files changed

+83
-0
lines changed

5 files changed

+83
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"jsc": {
3+
"parser": {
4+
"syntax": "typescript",
5+
"tsx": true,
6+
"decorators": true,
7+
"dynamicImport": true
8+
},
9+
"target": "esnext"
10+
},
11+
"module": {
12+
"type": "commonjs",
13+
"lazy": true
14+
}
15+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { parentPort, threadId } from "worker_threads";
2+
3+
function fibonacci(n: number): number {
4+
if (n <= 1) return n;
5+
return fibonacci(n - 1) + fibonacci(n - 2);
6+
}
7+
8+
parentPort?.on("message", (message: number) => {
9+
const result = fibonacci(message);
10+
parentPort?.postMessage({
11+
input: message,
12+
result: result,
13+
threadId: threadId,
14+
});
15+
});
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"name": "app-worker-thread",
3+
"version": "1.0.0",
4+
"description": "",
5+
"main": "index.js",
6+
"type": "commonjs",
7+
"scripts": {
8+
"test": "echo \"Error: no test specified\" && exit 1"
9+
},
10+
"license": "ISC"
11+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import path from "path";
2+
import { Worker } from "worker_threads";
3+
4+
async function runWorkerThread(n: number): Promise<{ input: number; result: number; threadId: number }> {
5+
return new Promise((resolve, reject) => {
6+
const worker = new Worker(path.join(__dirname, "app-thread.js"));
7+
8+
worker.on("message", (result) => {
9+
console.log(`Fibonacci(${result.input}) = ${result.result} (calculated in thread ${result.threadId})`);
10+
resolve(result);
11+
});
12+
13+
worker.on("error", reject);
14+
worker.on("exit", (code) => {
15+
if (code !== 0) {
16+
reject(new Error(`Worker stopped with exit code ${code}`));
17+
}
18+
});
19+
20+
worker.postMessage(n);
21+
});
22+
}
23+
24+
async function main() {
25+
console.log("Starting worker thread test...");
26+
try {
27+
const result = await runWorkerThread(10);
28+
if (result.result !== 55) {
29+
throw new Error("Result is incorrect");
30+
}
31+
console.log("IT WORKED");
32+
} catch (error) {
33+
console.error("Worker thread test failed:", error);
34+
}
35+
}
36+
37+
main();
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#!/usr/bin/env bash
2+
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
3+
set -ex
4+
5+
$DIR/../../pkg/wds.bin.js $@ $DIR/run.ts | grep "IT WORKED"

0 commit comments

Comments
 (0)