Skip to content

Commit a2e7829

Browse files
committed
Initial commit
0 parents  commit a2e7829

21 files changed

Lines changed: 1779 additions & 0 deletions

File tree

.github/workflows/deno.yml

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# This workflow uses actions that are not certified by GitHub.
2+
# They are provided by a third-party and are governed by
3+
# separate terms of service, privacy policy, and support
4+
# documentation.
5+
6+
# This workflow will install Deno then run `deno lint` and `deno test`.
7+
# For more information see: https://github.com/denoland/setup-deno
8+
9+
name: Deno
10+
11+
on:
12+
push:
13+
branches: ["main"]
14+
pull_request:
15+
branches: ["main"]
16+
17+
permissions:
18+
contents: read
19+
20+
jobs:
21+
test:
22+
runs-on: ubuntu-latest
23+
24+
steps:
25+
- name: Setup repo
26+
uses: actions/checkout@v5
27+
28+
- name: Setup Deno
29+
uses: denoland/setup-deno@v2
30+
with:
31+
deno-version: v2.5.x
32+
33+
# - name: Verify formatting
34+
# run: deno fmt --check
35+
36+
# - name: Run linter
37+
# run: deno lint
38+
39+
- name: Run tests
40+
run: deno task test

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
node_modules/
2+
dist/
3+
.workers/

CODE_OF_CONDUCT.md

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
# Contributor Covenant Code of Conduct
2+
3+
## Our Pledge
4+
5+
We as members, contributors, and leaders pledge to make participation in our
6+
community a harassment-free experience for everyone, regardless of age, body
7+
size, visible or invisible disability, ethnicity, sex characteristics, gender
8+
identity and expression, level of experience, education, socio-economic status,
9+
nationality, personal appearance, race, religion, or sexual identity
10+
and orientation.
11+
12+
We pledge to act and interact in ways that contribute to an open, welcoming,
13+
diverse, inclusive, and healthy community.
14+
15+
## Our Standards
16+
17+
Examples of behavior that contributes to a positive environment for our
18+
community include:
19+
20+
* Demonstrating empathy and kindness toward other people
21+
* Being respectful of differing opinions, viewpoints, and experiences
22+
* Giving and gracefully accepting constructive feedback
23+
* Accepting responsibility and apologizing to those affected by our mistakes,
24+
and learning from the experience
25+
* Focusing on what is best not just for us as individuals, but for the
26+
overall community
27+
28+
Examples of unacceptable behavior include:
29+
30+
* The use of sexualized language or imagery, and sexual attention or
31+
advances of any kind
32+
* Trolling, insulting or derogatory comments, and personal or political attacks
33+
* Public or private harassment
34+
* Publishing others' private information, such as a physical or email
35+
address, without their explicit permission
36+
* Other conduct which could reasonably be considered inappropriate in a
37+
professional setting
38+
39+
## Enforcement Responsibilities
40+
41+
Community leaders are responsible for clarifying and enforcing our standards of
42+
acceptable behavior and will take appropriate and fair corrective action in
43+
response to any behavior that they deem inappropriate, threatening, offensive,
44+
or harmful.
45+
46+
Community leaders have the right and responsibility to remove, edit, or reject
47+
comments, commits, code, wiki edits, issues, and other contributions that are
48+
not aligned to this Code of Conduct, and will communicate reasons for moderation
49+
decisions when appropriate.
50+
51+
## Scope
52+
53+
This Code of Conduct applies within all community spaces, and also applies when
54+
an individual is officially representing the community in public spaces.
55+
Examples of representing our community include using an official e-mail address,
56+
posting via an official social media account, or acting as an appointed
57+
representative at an online or offline event.
58+
59+
## Enforcement
60+
61+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
62+
reported to the community leaders responsible for enforcement at
63+
waltervdgiessen@gmail.com.
64+
All complaints will be reviewed and investigated promptly and fairly.
65+
66+
All community leaders are obligated to respect the privacy and security of the
67+
reporter of any incident.
68+
69+
## Enforcement Guidelines
70+
71+
Community leaders will follow these Community Impact Guidelines in determining
72+
the consequences for any action they deem in violation of this Code of Conduct:
73+
74+
### 1. Correction
75+
76+
**Community Impact**: Use of inappropriate language or other behavior deemed
77+
unprofessional or unwelcome in the community.
78+
79+
**Consequence**: A private, written warning from community leaders, providing
80+
clarity around the nature of the violation and an explanation of why the
81+
behavior was inappropriate. A public apology may be requested.
82+
83+
### 2. Warning
84+
85+
**Community Impact**: A violation through a single incident or series
86+
of actions.
87+
88+
**Consequence**: A warning with consequences for continued behavior. No
89+
interaction with the people involved, including unsolicited interaction with
90+
those enforcing the Code of Conduct, for a specified period of time. This
91+
includes avoiding interactions in community spaces as well as external channels
92+
like social media. Violating these terms may lead to a temporary or
93+
permanent ban.
94+
95+
### 3. Temporary Ban
96+
97+
**Community Impact**: A serious violation of community standards, including
98+
sustained inappropriate behavior.
99+
100+
**Consequence**: A temporary ban from any sort of interaction or public
101+
communication with the community for a specified period of time. No public or
102+
private interaction with the people involved, including unsolicited interaction
103+
with those enforcing the Code of Conduct, is allowed during this period.
104+
Violating these terms may lead to a permanent ban.
105+
106+
### 4. Permanent Ban
107+
108+
**Community Impact**: Demonstrating a pattern of violation of community
109+
standards, including sustained inappropriate behavior, harassment of an
110+
individual, or aggression toward or disparagement of classes of individuals.
111+
112+
**Consequence**: A permanent ban from any sort of public interaction within
113+
the community.
114+
115+
## Attribution
116+
117+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118+
version 2.0, available at
119+
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120+
121+
Community Impact Guidelines were inspired by [Mozilla's code of conduct
122+
enforcement ladder](https://github.com/mozilla/diversity).
123+
124+
[homepage]: https://www.contributor-covenant.org
125+
126+
For answers to common questions about this code of conduct, see the FAQ at
127+
https://www.contributor-covenant.org/faq. Translations are available at
128+
https://www.contributor-covenant.org/translations.

LICENSE.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
MIT License
2+
3+
Copyright (c) 2026 Walter van der Giessen
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6+
7+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8+
9+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

README.md

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
<div align="center">
2+
3+
<h1>experimental-threads</h1>
4+
5+
<p>
6+
<strong>JIT-compiled multithreading using lexical scope analysis and shared memory rehydration.</strong>
7+
</p>
8+
9+
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
10+
[![Status](https://img.shields.io/badge/status-experimental-orange.svg)]()
11+
[![TypeScript](https://img.shields.io/badge/language-TypeScript-3178C6.svg)]()
12+
13+
</div>
14+
15+
<br />
16+
17+
**experimental-threads** is a highly experimental concurrency library for server-side JavaScript that bridges the gap between the single-threaded Event Loop and true parallelism. It introduces a novel runtime architecture that combines **Abstract Syntax Tree (AST) analysis**, **source-code injection**, and **deterministic memory hydration** to emulate the ergonomics of Go routines or Rust threads.
18+
19+
Unlike traditional Web Workers which require separate entry files and manual message passing, this library allows for the execution of **lexical closures** in isolated threads. It automatically handles the serialization of captured variables and ensures referential integrity of shared memory resources (`SharedArrayBuffer`) across execution contexts.
20+
21+
## Installation
22+
23+
```bash
24+
npm install experimental-threads
25+
```
26+
27+
## Architecture
28+
29+
### 1. Runtime Scope Analysis & AST Traversal
30+
31+
Standard JavaScript closures cannot be serialized to Workers because they are bound to the parent execution context. **experimental-threads** bypasses this limitation by performing **Just-In-Time (JIT) Static Analysis** on the calling code.
32+
33+
When `spawn(fn)` is invoked:
34+
35+
1. **Call Site Resolution:** The library inspects the V8 stack trace to identify the exact file, line, and column of the invocation.
36+
2. **AST Generation:** It reads the source file from the disk and feeds it into the **TypeScript Compiler API** to generate a synthetic AST.
37+
3. **Symbol Resolution:** It traverses the AST to locate the specific arrow function expression passed to `spawn`.
38+
4. **Identifier Resolution:** It walks the scope chain of the function body, distinguishing between *bound identifiers* (parameters, local variables) and *free variables* (captured from the outer scope).
39+
5. **Transpilation:** It generates a standalone worker entry script that imports necessary modules and injects the captured free variables as structured-cloned properties.
40+
41+
### 2. Deterministic Memory Hydration (`Global<T>`)
42+
43+
In a multi-process or multi-isolate architecture (like Web Workers), module singletons are not shared. They are instantiated once per thread. This breaks the identity of shared locks or buffers.
44+
45+
This library introduces **Location-Dependent Reference Integrity**.
46+
47+
* **Identity Generation:** Every `Global` instance is assigned a deterministic ID based on its definition site.
48+
* **Memory Registry:** The main thread maintains a global memory registry, mapping these IDs to their underlying `SharedArrayBuffer` pointers.
49+
* **Hydration:** When a Worker boots and imports a module containing a `Global`, the constructor intercepts the instantiation. Instead of allocating new memory, it queries the registry transmitted during the handshake phase and **hydrates** the instance with the existing buffer from the main/parent thread.
50+
51+
This guarantees that `const lock = new Global(new Mutex())` refers to the exact same memory address (access cost) in every thread, enabling atomic synchronization.
52+
53+
## Usage
54+
55+
```typescript
56+
import { spawn } from "experimental-threads";
57+
58+
const data = { hello: 'world' };
59+
60+
const result = await eval(spawn(async () => {
61+
// Will be automatically captured
62+
console.log(data.hello); // "world"
63+
64+
return Math.random();
65+
}));
66+
67+
console.log(result); // 0.6378467071314606
68+
```
69+
70+
## Synchronization Primitives
71+
72+
### `Mutex`
73+
74+
A mutual exclusion primitive preventing race conditions. Uses a futex-like mechanism with `Atomics.wait` and `Atomics.notify`. Supports the `using` keyword (Explicit Resource Management) for RAII-style scope-based unlocking.
75+
76+
### `Semaphore`
77+
78+
A signaling mechanism to control access to a common resource by multiple processes. Supports the `using` keyword (Explicit Resource Management).
79+
80+
---
81+
82+
## License
83+
84+
MIT

SECURITY.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Reporting a Vulnerability
2+
3+
To report a vulnerability, please open a private vulnerability report at https://github.com/W4G1/experimental-threads/security.

deno.jsonc

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
{
2+
"tasks": {
3+
"dev": "deno run -A --watch ./main.ts",
4+
"update": "deno outdated --update --latest",
5+
"build": "deno run -A scripts/build.ts",
6+
"test": "deno test -A --v8-flags=\"--expose-gc\"",
7+
"bench": "deno bench -A --no-check --cached-only",
8+
},
9+
"imports": {
10+
"@std/assert": "jsr:@std/assert@^1.0.18",
11+
"@std/async": "jsr:@std/async@^1.1.1",
12+
"@std/fs": "jsr:@std/fs@^1.0.22",
13+
"@std/path": "jsr:@std/path@^1.1.4",
14+
"typescript": "npm:typescript@^5.9.3",
15+
"experimental-threads": "./src/deno/lib.ts",
16+
},
17+
"compilerOptions": {
18+
// From @tsconfig/strictest
19+
"strict": true,
20+
"allowUnusedLabels": false,
21+
"allowUnreachableCode": false,
22+
"exactOptionalPropertyTypes": true,
23+
"noFallthroughCasesInSwitch": true,
24+
"noImplicitOverride": true,
25+
"noImplicitReturns": true,
26+
"noPropertyAccessFromIndexSignature": true,
27+
"noUncheckedIndexedAccess": true,
28+
// "noUnusedLocals": true,
29+
// "noUnusedParameters": true,
30+
"checkJs": true,
31+
"lib": ["deno.window", "deno.worker" /*, "deno.unstable"*/],
32+
},
33+
"lint": {
34+
"rules": {
35+
"include": [],
36+
"exclude": ["no-explicit-any", "no-unused-vars"],
37+
},
38+
},
39+
// "unstable": ["raw-imports", "worker-options", "cron"]
40+
}

deno.lock

Lines changed: 54 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)