@heojeongbo/wasmgen 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +342 -2
- package/dist/adapters/compiler.d.ts +13 -0
- package/dist/adapters/compiler.js +1 -0
- package/dist/adapters/cpp/bridge.d.ts +2 -0
- package/dist/adapters/cpp/bridge.js +59 -0
- package/dist/adapters/cpp/compiler.d.ts +2 -0
- package/dist/adapters/cpp/compiler.js +32 -0
- package/dist/adapters/cpp/worker.d.ts +1 -0
- package/dist/adapters/cpp/worker.js +7 -0
- package/dist/adapters/go/bridge.d.ts +2 -0
- package/dist/adapters/go/bridge.js +93 -0
- package/dist/adapters/go/compiler.d.ts +2 -0
- package/dist/adapters/go/compiler.js +64 -0
- package/dist/adapters/go/worker.d.ts +1 -0
- package/dist/adapters/go/worker.js +18 -0
- package/dist/application/generate.d.ts +9 -0
- package/dist/application/generate.js +28 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +40 -0
- package/dist/codegen/web.d.ts +5 -0
- package/dist/codegen/web.js +48 -0
- package/dist/config.d.ts +3 -0
- package/dist/config.js +76 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +6 -0
- package/dist/licenses/COMPILER-RT-LICENSE +311 -0
- package/dist/licenses/EMSCRIPTEN-LICENSE +102 -0
- package/dist/licenses/GO-LICENSE +27 -0
- package/dist/licenses/LIBCXX-LICENSE +311 -0
- package/dist/licenses/LIBCXXABI-LICENSE +311 -0
- package/dist/licenses/MUSL-COPYRIGHT +193 -0
- package/dist/licenses/README.md +23 -0
- package/dist/model/config.d.ts +142 -0
- package/dist/model/config.js +18 -0
- package/dist/model/value-types.d.ts +3 -0
- package/dist/model/value-types.js +1 -0
- package/dist/process.d.ts +7 -0
- package/dist/process.js +23 -0
- package/dist/runtime/client.d.ts +17 -0
- package/dist/runtime/client.js +95 -0
- package/dist/runtime/protocol.d.ts +34 -0
- package/dist/runtime/protocol.js +14 -0
- package/dist/runtime/worker.d.ts +6 -0
- package/dist/runtime/worker.js +86 -0
- package/dist/shared/errors.d.ts +2 -0
- package/dist/shared/errors.js +2 -0
- package/dist/storage/output.d.ts +2 -0
- package/dist/storage/output.js +96 -0
- package/package.json +53 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 wasmgen contributors
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,343 @@
|
|
|
1
|
-
#
|
|
1
|
+
# wasmgen
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Generate browser WebAssembly modules and typed clients from Go and C++ sources.
|
|
4
|
+
Declare native inputs, exported function signatures, and an output directory;
|
|
5
|
+
then import the generated code from your TypeScript application.
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
Go files / package ── Go compiler ───────┐
|
|
9
|
+
├── .wasm + Worker + JS + .d.ts
|
|
10
|
+
C++ sources / headers ── Emscripten ─────┘ ↓
|
|
11
|
+
TypeScript imports
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
wasmgen orchestrates existing compilers and generates the bindings. Each client
|
|
15
|
+
runs in its own Web Worker and exposes Promise-returning functions. Generated
|
|
16
|
+
code has no runtime npm dependency on wasmgen and contacts no build service.
|
|
17
|
+
|
|
18
|
+
The project and CLI are named **wasmgen**. The npm package is
|
|
19
|
+
`@heojeongbo/wasmgen`. Rust support is not implemented in this version.
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
Build prerequisites: Node.js 22.12+, pnpm 10.11.0, Go 1.22+, and Emscripten's `em++` on
|
|
24
|
+
`PATH`. C++ uses C++17. The [test container](test/Dockerfile) supplies the tested
|
|
25
|
+
toolchains and browser engines if you do not want to install them locally.
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
pnpm add -D @heojeongbo/wasmgen
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Create a `wasmgen.yaml` using the configuration below, then generate the browser
|
|
32
|
+
modules:
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
pnpm exec wasmgen gen --config wasmgen.yaml
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Run the repository example
|
|
39
|
+
|
|
40
|
+
Clone this repository and run:
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
pnpm install --frozen-lockfile
|
|
44
|
+
pnpm run build
|
|
45
|
+
node dist/cli.js gen --config examples/wasmgen.yaml
|
|
46
|
+
pnpm exec vite examples/web
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Open the URL printed by Vite. The example calls C++ to clamp a number and Go to
|
|
50
|
+
uppercase the result label. To build deployable static assets:
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
pnpm exec vite build examples/web --base=/demo/
|
|
54
|
+
pnpm exec vite preview examples/web --base=/demo/
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
To test a local build of the generator in another project, run `pnpm pack` here,
|
|
58
|
+
then `pnpm add -D /absolute/path/to/heojeongbo-wasmgen-0.1.0.tgz`
|
|
59
|
+
there. This does not publish anything. Its runtime npm dependencies are the
|
|
60
|
+
public `yaml` and `zod` packages. Installation has no install/postinstall scripts
|
|
61
|
+
or native builds; `prepack` compiles TypeScript when packaging the generator.
|
|
62
|
+
|
|
63
|
+
## Configure inputs and output
|
|
64
|
+
|
|
65
|
+
`wasmgen.yaml` (JSON is also accepted):
|
|
66
|
+
|
|
67
|
+
```yaml
|
|
68
|
+
version: 1
|
|
69
|
+
output: ./web/generated
|
|
70
|
+
input:
|
|
71
|
+
- name: geometry
|
|
72
|
+
language: cpp
|
|
73
|
+
files: [./cpp/geometry.cc]
|
|
74
|
+
headers: [./cpp/geometry.h]
|
|
75
|
+
exports:
|
|
76
|
+
clamp:
|
|
77
|
+
symbol: geometry::Clamp
|
|
78
|
+
params:
|
|
79
|
+
- { name: value, type: f64 }
|
|
80
|
+
- { name: low, type: f64 }
|
|
81
|
+
- { name: high, type: f64 }
|
|
82
|
+
result: f64
|
|
83
|
+
- name: policy
|
|
84
|
+
language: go
|
|
85
|
+
files: [./go/logic.go]
|
|
86
|
+
exports:
|
|
87
|
+
upper:
|
|
88
|
+
symbol: Upper
|
|
89
|
+
params:
|
|
90
|
+
- { name: value, type: string }
|
|
91
|
+
result: string
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
The matching source files are in [examples](examples/wasmgen.yaml).
|
|
95
|
+
|
|
96
|
+
```sh
|
|
97
|
+
pnpm exec wasmgen check --config wasmgen.yaml
|
|
98
|
+
pnpm exec wasmgen gen --config wasmgen.yaml
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
`check` validates the configuration and input paths; `gen` also compiles and
|
|
102
|
+
checks native calls. All source/output paths resolve relative to the config.
|
|
103
|
+
The output is exclusively owned by wasmgen: use a dedicated generated directory.
|
|
104
|
+
Failed builds preserve the previous output. Unknown files and symlinks in the
|
|
105
|
+
output prevent replacement. Do not hand-edit generated files. A sibling lock
|
|
106
|
+
prevents concurrent generation into the same output; after a hard process kill,
|
|
107
|
+
remove that lock only after verifying no generator is still running.
|
|
108
|
+
|
|
109
|
+
## Import from TypeScript
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
import { geometry, policy } from './generated/index.js';
|
|
113
|
+
|
|
114
|
+
const cpp = await geometry();
|
|
115
|
+
try {
|
|
116
|
+
const go = await policy();
|
|
117
|
+
try {
|
|
118
|
+
const clamped: number = await cpp.clamp(23, 0, 10);
|
|
119
|
+
const label: string = await go.upper(`value: ${clamped}`);
|
|
120
|
+
console.log(label); // VALUE: 10
|
|
121
|
+
} finally {
|
|
122
|
+
go.dispose();
|
|
123
|
+
}
|
|
124
|
+
} finally {
|
|
125
|
+
cpp.dispose();
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Each factory starts a separate Worker and native runtime. Calls within an
|
|
130
|
+
instance execute serially; separate instances can run independently. Strings
|
|
131
|
+
and arrays are copied across boundaries. Array parameters and results use plain
|
|
132
|
+
JavaScript arrays, not typed arrays or shared memory.
|
|
133
|
+
|
|
134
|
+
Factories accept `{ signal?: AbortSignal, timeoutMs?: number }`. The default
|
|
135
|
+
30-second timeout applies to initialization and each call, including queue time.
|
|
136
|
+
Abort, timeout, disposal, and fatal Wasm traps terminate the whole instance and
|
|
137
|
+
reject every outstanding call. Create a new instance to resume. Ordinary Go
|
|
138
|
+
errors, Go panics within the exported call, and C++ exceptions reject just that call. Go
|
|
139
|
+
panics in independently running goroutines are outside the exported-call boundary.
|
|
140
|
+
|
|
141
|
+
## Native interface
|
|
142
|
+
|
|
143
|
+
| Config type | TypeScript | Go parameter | C++ parameter |
|
|
144
|
+
| --- | --- | --- | --- |
|
|
145
|
+
| `i32` | `number` | `int32` | `std::int32_t` |
|
|
146
|
+
| `u32` | `number` | `uint32` | `std::uint32_t` |
|
|
147
|
+
| `f64` | `number` | `float64` | `double` |
|
|
148
|
+
| `bool` | `boolean` | `bool` | `bool` |
|
|
149
|
+
| `string` | `string` | `string` | `std::string` |
|
|
150
|
+
| `i32[]`, `u32[]`, `f64[]` | `number[]` | slice of the corresponding type | `std::vector<T>` |
|
|
151
|
+
| `void` (result only) | `void` | no result | `void` |
|
|
152
|
+
|
|
153
|
+
Numeric arguments/results are validated at runtime; `f64` requires finite values.
|
|
154
|
+
`i32` and `u32` enforce their integer ranges. Nil Go slices become empty arrays.
|
|
155
|
+
For Go functions returning `(T, error)`, add `error: true` to the export; use
|
|
156
|
+
`result: void` for functions returning only `error`.
|
|
157
|
+
|
|
158
|
+
Exports use ordinary native function signatures. Go functions may wait on
|
|
159
|
+
goroutines, channels, and timers; the generated bridge returns a JavaScript
|
|
160
|
+
Promise and invokes native work in a goroutine so the JS event loop can resume.
|
|
161
|
+
The Go runtime is compiled into the Wasm binary; wasmgen copies `wasm_exec.js`
|
|
162
|
+
from the same selected toolchain as `go-runtime.js`. This supports concurrency
|
|
163
|
+
within a Worker, not Go CPU parallelism across OS threads. Exported calls on
|
|
164
|
+
one client still execute in order. Abort/timeout terminates the Worker rather
|
|
165
|
+
than invoking Go defers or performing a graceful `context.Context` cancellation.
|
|
166
|
+
User-created goroutines must have their own exit path while the instance lives.
|
|
167
|
+
|
|
168
|
+
See `DelayedDouble` in [the Go example](examples/go/logic.go) for a channel/timer
|
|
169
|
+
example tested in real browsers. C++ exports remain synchronous inside their Worker.
|
|
170
|
+
Signatures are explicit in the config;
|
|
171
|
+
wasmgen does not infer a whole native API. Use small native adapters for methods,
|
|
172
|
+
custom parameter types, or APIs that differ from this table. C++ const-reference
|
|
173
|
+
parameters and templates work when callable with the generated argument types.
|
|
174
|
+
`dispose` and `then` cannot be exported as function names; `then` also cannot
|
|
175
|
+
be a module name because dynamic imports would treat it as a Promise callback.
|
|
176
|
+
|
|
177
|
+
Go has two input modes:
|
|
178
|
+
|
|
179
|
+
- `files`: selected `.go` files from one non-main package, with standard-library
|
|
180
|
+
imports only. Files are compiled in an isolated temporary module with `GOWORK=off`.
|
|
181
|
+
- `package`: an importable package directory in an existing Go module. This
|
|
182
|
+
preserves module dependencies, `replace`, workspace resolution, and `internal`
|
|
183
|
+
visibility. The package directory must be writable: a temporary wrapper directory
|
|
184
|
+
is created there and removed afterward. Go may resolve/download dependencies or a
|
|
185
|
+
selected toolchain according to the original module's settings.
|
|
186
|
+
|
|
187
|
+
```yaml
|
|
188
|
+
version: 1
|
|
189
|
+
output: ./web/generated
|
|
190
|
+
input:
|
|
191
|
+
- name: calculation
|
|
192
|
+
language: go
|
|
193
|
+
package: ./native/internal/calc
|
|
194
|
+
exports:
|
|
195
|
+
add:
|
|
196
|
+
symbol: Add
|
|
197
|
+
params: [{ name: value, type: f64 }]
|
|
198
|
+
result: f64
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
C++ requires `headers`; `files` is optional for header-only functions. `include`
|
|
202
|
+
adds include directories. All supplied sources are compiled and linked into a
|
|
203
|
+
single module, with `-O3`, LTO, and warnings treated as errors. This version does
|
|
204
|
+
not drive CMake or expose arbitrary linker flags.
|
|
205
|
+
|
|
206
|
+
Use `tools: { go: /path/to/go, cpp: /path/to/em++ }` to override executables.
|
|
207
|
+
Executable names resolve through `PATH`; use absolute paths for overrides outside
|
|
208
|
+
`PATH`. Compiler arguments are passed directly, without a shell.
|
|
209
|
+
|
|
210
|
+
The source and its dependencies must support the browser target. Native OS,
|
|
211
|
+
hardware devices, raw sockets, filesystem access, cgo, pthreads, and arbitrary
|
|
212
|
+
native libraries are not made browser-compatible automatically. This version
|
|
213
|
+
targets portable computation; structs, pointers, callbacks, int64, streaming,
|
|
214
|
+
Rust, and WASI are outside its supported interface.
|
|
215
|
+
|
|
216
|
+
## Build and deploy in a monorepo
|
|
217
|
+
|
|
218
|
+
Install the public generator as a dev dependency, generate from your local native
|
|
219
|
+
sources, and build the web application.
|
|
220
|
+
Native application code and generated artifacts do not need a pnpm package or
|
|
221
|
+
an internal package registry. Generation happens explicitly during development
|
|
222
|
+
or CI, not during `pnpm install`.
|
|
223
|
+
|
|
224
|
+
The generated directory contains module factories, `.d.ts` declarations,
|
|
225
|
+
Workers, `.wasm` binaries, and runtime/license files. Vite is tested in both
|
|
226
|
+
development and production, including a `/demo/` base path. Its normal
|
|
227
|
+
`new Worker(new URL(..., import.meta.url))` and asset handling bundle the files.
|
|
228
|
+
Other bundlers are not yet tested. Native ESM serving requires preserving the
|
|
229
|
+
relative generated directory structure and serving JavaScript/Wasm over HTTP(S).
|
|
230
|
+
|
|
231
|
+
Deploy the entire bundler output. Serve `.wasm` as `application/wasm` and keep
|
|
232
|
+
Worker scripts/assets accessible from the application. The current implementation
|
|
233
|
+
does not use SharedArrayBuffer or require cross-origin isolation. A restrictive
|
|
234
|
+
CSP must allow the application's Workers and WebAssembly compilation.
|
|
235
|
+
|
|
236
|
+
Preserve generated license notices in your application's distribution: bundlers
|
|
237
|
+
do not copy standalone license text files automatically. See
|
|
238
|
+
[runtime notices](src/licenses/README.md) for compiler provenance; also include
|
|
239
|
+
notices belonging to your own native dependencies.
|
|
240
|
+
|
|
241
|
+
## Library API
|
|
242
|
+
|
|
243
|
+
```ts
|
|
244
|
+
import { generate, readConfig } from '@heojeongbo/wasmgen';
|
|
245
|
+
|
|
246
|
+
await readConfig('wasmgen.yaml');
|
|
247
|
+
await generate('wasmgen.yaml', {
|
|
248
|
+
onProgress: console.log,
|
|
249
|
+
signal: new AbortController().signal,
|
|
250
|
+
});
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
## Architecture
|
|
254
|
+
|
|
255
|
+
Sources, tests, and build/check scripts are TypeScript. `pnpm run build` emits
|
|
256
|
+
the distributable JavaScript and declarations into `dist/`; browser codegen
|
|
257
|
+
emits executable JS plus `.d.ts`. There are no separately maintained public
|
|
258
|
+
type declarations. Configuration types are inferred from the Zod schema.
|
|
259
|
+
|
|
260
|
+
The structure follows the strict typing, downward dependencies, public module
|
|
261
|
+
entry points, and injection principles in
|
|
262
|
+
[ui-app-template](https://github.com/heojeongbo/ui-app-template/blob/c852869c2342c92b4a196cd6b0fe3691799eb724/docs/architecture.md).
|
|
263
|
+
The generator is infrastructure, so its modules follow their responsibilities;
|
|
264
|
+
the browser example uses the FSD subset it needs.
|
|
265
|
+
|
|
266
|
+
| Module | Responsibility |
|
|
267
|
+
| --- | --- |
|
|
268
|
+
| `src/model/` | Configuration schema and value contracts |
|
|
269
|
+
| `src/config.ts` | Parse, validate, and resolve input paths |
|
|
270
|
+
| `src/application/` | Generation workflow using injected compiler adapters |
|
|
271
|
+
| `src/adapters/go/`, `src/adapters/cpp/` | Native bridge generation, compiler invocation, language-specific Worker initialization |
|
|
272
|
+
| `src/storage/` | Output ownership, lock, staging, replacement, rollback |
|
|
273
|
+
| `src/codegen/` | Shared browser client and declaration emission |
|
|
274
|
+
| `src/runtime/` | Typed Worker protocol, call ordering, deadlines, lifetime |
|
|
275
|
+
| `src/index.ts` | Compose the concrete Go/C++ adapters into the public API |
|
|
276
|
+
| `examples/web/src/` | `app → pages → features → shared`; generated native clients enter through `shared/api` |
|
|
277
|
+
|
|
278
|
+
The Go/C++ implementations adapt distinct toolchains to a single
|
|
279
|
+
`CompilerAdapter` contract. The browser adapter presents generated native APIs
|
|
280
|
+
as a small `NativeOperations` contract; the calculation feature receives it
|
|
281
|
+
as a dependency. The page owns DOM interaction while the feature owns the
|
|
282
|
+
calculation sequence. Empty FSD layers, React, and template-specific application
|
|
283
|
+
dependencies are not needed for this example.
|
|
284
|
+
|
|
285
|
+
`pnpm run check` runs strict TypeScript checking and an import-boundary check:
|
|
286
|
+
application/codegen cannot import concrete compilers, runtime code cannot import
|
|
287
|
+
build-time services, and FSD imports must flow downward through public entry points.
|
|
288
|
+
It also rejects explicit TypeScript `any` and disabled type-checking directives.
|
|
289
|
+
`pnpm run typecheck:generated` validates the generated declarations and browser
|
|
290
|
+
example after generation; test compilation checks all test code too.
|
|
291
|
+
|
|
292
|
+
## Validation
|
|
293
|
+
|
|
294
|
+
The container uses Emscripten 4.0.10, Ubuntu's Go 1.22 toolchain, and Playwright
|
|
295
|
+
1.60.0. Run from the wasmgen checkout with Docker available:
|
|
296
|
+
|
|
297
|
+
```sh
|
|
298
|
+
docker build -t wasmgen-test:local -f test/Dockerfile .
|
|
299
|
+
docker run --rm -it --ipc=host \
|
|
300
|
+
--mount type=bind,source="$PWD",target=/work \
|
|
301
|
+
--mount type=volume,source=wasmgen-test-node-modules,target=/work/node_modules \
|
|
302
|
+
wasmgen-test:local bash
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
Inside the container:
|
|
306
|
+
|
|
307
|
+
```sh
|
|
308
|
+
pnpm install --frozen-lockfile
|
|
309
|
+
pnpm run check
|
|
310
|
+
pnpm test
|
|
311
|
+
pnpm run test:e2e
|
|
312
|
+
pnpm run test:package
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
`test:e2e` compiles real Go/C++, checks TypeScript declarations, and runs
|
|
316
|
+
Chromium, Firefox, and WebKit against Vite development and production output.
|
|
317
|
+
It checks Unicode, numeric boundaries, arrays and memory growth, errors/panics,
|
|
318
|
+
concurrency, goroutine/channel/timer completion, call ordering, responsiveness,
|
|
319
|
+
cancellation, timeout, and Worker cleanup.
|
|
320
|
+
|
|
321
|
+
`test:package` packs and installs a local tarball into a separate
|
|
322
|
+
consumer, invokes the installed CLI/library, compiles a Go `internal` package
|
|
323
|
+
with a local `replace` dependency and a C++ module, typechecks imports, and runs
|
|
324
|
+
the same browser/build matrix. Only public generator files enter the package.
|
|
325
|
+
|
|
326
|
+
All checked-in fixtures are independent, general-purpose examples. No external
|
|
327
|
+
application checkout is required. Reports, screenshots, and the local tarball are written to
|
|
328
|
+
`.artifacts/`; temporary consumers go under `.test-output/`. Both are gitignored.
|
|
329
|
+
|
|
330
|
+
## Maintainer credentials
|
|
331
|
+
|
|
332
|
+
The project `.npmrc` uses the public npm registry and reads authentication from
|
|
333
|
+
`NPM_TOKEN`. Never put a token directly in `.npmrc`. For local storage, copy
|
|
334
|
+
`.env.example` to `.env.local`, restrict its permissions with `chmod 600 .env.local`,
|
|
335
|
+
and fill in the value. `.env.local` is gitignored; pnpm does not load it
|
|
336
|
+
automatically, so explicitly load it into the publishing process when needed.
|
|
337
|
+
Public dependency installation requires no token. With `NPM_TOKEN` unset,
|
|
338
|
+
pnpm 10 may print an environment-substitution warning but still installs public
|
|
339
|
+
dependencies. Do not share token values in chat or commit them to the repository.
|
|
340
|
+
|
|
341
|
+
## License
|
|
342
|
+
|
|
343
|
+
MIT. Native inputs remain under their original licenses.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Language, ResolvedInput, Tools } from '../model/config.js';
|
|
2
|
+
export interface BuildContext {
|
|
3
|
+
directory: string;
|
|
4
|
+
scratch: string;
|
|
5
|
+
tools: Tools;
|
|
6
|
+
signal?: AbortSignal;
|
|
7
|
+
}
|
|
8
|
+
export interface CompilerAdapter {
|
|
9
|
+
readonly language: Language;
|
|
10
|
+
build(mod: ResolvedInput, context: BuildContext): Promise<void>;
|
|
11
|
+
workerSource(): string;
|
|
12
|
+
}
|
|
13
|
+
export type CompilerAdapters = Readonly<Record<Language, CompilerAdapter>>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
function cppType(type) {
|
|
2
|
+
if (type.endsWith('[]'))
|
|
3
|
+
return `std::vector<${cppType(type.slice(0, -2))}>`;
|
|
4
|
+
return { i32: 'std::int32_t', u32: 'std::uint32_t', f64: 'double', bool: 'bool', string: 'std::string', void: 'void' }[type];
|
|
5
|
+
}
|
|
6
|
+
export function cppBridge(mod) {
|
|
7
|
+
const functions = mod.exports.map((fn, index) => {
|
|
8
|
+
const args = fn.params.map((param, i) => {
|
|
9
|
+
if (!param.type.endsWith('[]'))
|
|
10
|
+
return ` auto arg${i} = args[${i}].as<${cppType(param.type)}>();`;
|
|
11
|
+
const scalar = cppType(param.type.slice(0, -2));
|
|
12
|
+
return ` ${cppType(param.type)} arg${i};
|
|
13
|
+
const auto size${i} = args[${i}]["length"].as<std::uint32_t>();
|
|
14
|
+
arg${i}.reserve(size${i});
|
|
15
|
+
for (std::uint32_t j = 0; j < size${i}; ++j) arg${i}.push_back(args[${i}][j].as<${scalar}>());`;
|
|
16
|
+
}).join('\n');
|
|
17
|
+
const call = `${fn.symbol}(${fn.params.map((_, i) => `arg${i}`).join(', ')})`;
|
|
18
|
+
let invoke;
|
|
19
|
+
if (fn.result === 'void')
|
|
20
|
+
invoke = ` ${call};\n result.set("value", val::undefined());`;
|
|
21
|
+
else if (fn.result.endsWith('[]'))
|
|
22
|
+
invoke = ` const auto value = ${call};
|
|
23
|
+
auto array = val::array();
|
|
24
|
+
for (std::size_t i = 0; i < value.size(); ++i) array.set(static_cast<unsigned>(i), value[i]);
|
|
25
|
+
result.set("value", array);`;
|
|
26
|
+
else
|
|
27
|
+
invoke = ` result.set("value", ${call});`;
|
|
28
|
+
return `val call_${index}(val args) {
|
|
29
|
+
auto result = val::object();
|
|
30
|
+
try {
|
|
31
|
+
${args}
|
|
32
|
+
${invoke}
|
|
33
|
+
result.set("ok", true);
|
|
34
|
+
} catch (const std::exception& error) {
|
|
35
|
+
result.set("ok", false);
|
|
36
|
+
result.set("error", std::string(error.what()));
|
|
37
|
+
} catch (...) {
|
|
38
|
+
result.set("ok", false);
|
|
39
|
+
result.set("error", std::string("unknown C++ exception"));
|
|
40
|
+
}
|
|
41
|
+
return result;
|
|
42
|
+
}`;
|
|
43
|
+
}).join('\n\n');
|
|
44
|
+
return `// Code generated by wasmgen. DO NOT EDIT.
|
|
45
|
+
#include <cstdint>
|
|
46
|
+
#include <exception>
|
|
47
|
+
#include <string>
|
|
48
|
+
#include <vector>
|
|
49
|
+
#include <emscripten/bind.h>
|
|
50
|
+
${mod.headers.map((header) => `#include ${JSON.stringify(header)}`).join('\n')}
|
|
51
|
+
namespace {
|
|
52
|
+
using emscripten::val;
|
|
53
|
+
${functions}
|
|
54
|
+
}
|
|
55
|
+
EMSCRIPTEN_BINDINGS(wasmgen_module) {
|
|
56
|
+
${mod.exports.map((fn, index) => ` emscripten::function(${JSON.stringify(fn.name)}, &call_${index});`).join('\n')}
|
|
57
|
+
}
|
|
58
|
+
`;
|
|
59
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { cppBridge } from './bridge.js';
|
|
2
|
+
import { workerSource } from './worker.js';
|
|
3
|
+
import { copyFile, mkdir, writeFile } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { run } from '../../process.js';
|
|
6
|
+
async function build(mod, { directory, scratch, tools, signal }) {
|
|
7
|
+
const bridge = path.join(scratch, 'bridge.cc');
|
|
8
|
+
await writeFile(bridge, cppBridge(mod));
|
|
9
|
+
const compiler = tools.cpp ?? 'em++';
|
|
10
|
+
const objects = [];
|
|
11
|
+
for (const [index, source] of [...mod.files, bridge].entries()) {
|
|
12
|
+
const object = path.join(scratch, `unit-${index}.o`);
|
|
13
|
+
await run(compiler, [
|
|
14
|
+
'-c', source, '-o', object, '-std=c++17', '-O3', '-flto', '-fexceptions', '-Wall', '-Werror', '-sSTRICT',
|
|
15
|
+
...mod.include.flatMap((directory) => ['-I', directory]),
|
|
16
|
+
], { signal });
|
|
17
|
+
objects.push(object);
|
|
18
|
+
}
|
|
19
|
+
await run(compiler, [
|
|
20
|
+
...objects, '-O3', '-flto', '-fexceptions', '-lembind', '--no-entry',
|
|
21
|
+
'-sSTRICT', '-sEXPORT_ES6', '-sENVIRONMENT=worker',
|
|
22
|
+
'-sINCOMING_MODULE_JS_API=locateFile',
|
|
23
|
+
'-sALLOW_MEMORY_GROWTH', '-sFILESYSTEM=0',
|
|
24
|
+
'-o', path.join(directory, 'native.js'),
|
|
25
|
+
], { signal });
|
|
26
|
+
const licenses = path.join(directory, 'licenses');
|
|
27
|
+
await mkdir(licenses);
|
|
28
|
+
for (const name of ['EMSCRIPTEN-LICENSE', 'MUSL-COPYRIGHT', 'LIBCXX-LICENSE', 'LIBCXXABI-LICENSE', 'COMPILER-RT-LICENSE']) {
|
|
29
|
+
await copyFile(new URL(`../../licenses/${name}`, import.meta.url), path.join(licenses, name));
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export const cppAdapter = { language: 'cpp', build, workerSource };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function workerSource(): string;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export function workerSource() {
|
|
2
|
+
return `import initialize from './native.js';
|
|
3
|
+
serve(async () => {
|
|
4
|
+
const native = await initialize({ locateFile: () => new URL('./native.wasm', import.meta.url).href });
|
|
5
|
+
return (method, args) => native[method](args);
|
|
6
|
+
}, schema);`;
|
|
7
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
function goType(type) {
|
|
2
|
+
if (type.endsWith('[]'))
|
|
3
|
+
return `[]${goType(type.slice(0, -2))}`;
|
|
4
|
+
return { i32: 'int32', u32: 'uint32', f64: 'float64', bool: 'bool', string: 'string', void: 'void' }[type];
|
|
5
|
+
}
|
|
6
|
+
export function goBridge(mod, importPath) {
|
|
7
|
+
const quote = String.fromCharCode(96);
|
|
8
|
+
const bindings = mod.exports.map((fn) => {
|
|
9
|
+
const params = fn.params.map((param, i) => ` var arg${i} ${goType(param.type)}
|
|
10
|
+
if err := json.Unmarshal(args[${i}], &arg${i}); err != nil {
|
|
11
|
+
return nil, fmt.Errorf("decode ${param.name}: %w", err)
|
|
12
|
+
}`).join('\n');
|
|
13
|
+
const call = `native.${fn.symbol}(${fn.params.map((_, i) => `arg${i}`).join(', ')})`;
|
|
14
|
+
const invoke = fn.result === 'void' ? (fn.error ? `return nil, ${call}` : `${call}\n return nil, nil`) : (fn.error ? `return ${call}` : `return ${call}, nil`);
|
|
15
|
+
return ` ${JSON.stringify(fn.name)}: bind(${fn.params.length}, func(args []json.RawMessage) (any, error) {
|
|
16
|
+
${params}
|
|
17
|
+
${invoke}
|
|
18
|
+
}),`;
|
|
19
|
+
}).join('\n');
|
|
20
|
+
return `// Code generated by wasmgen. DO NOT EDIT.
|
|
21
|
+
package main
|
|
22
|
+
|
|
23
|
+
import (
|
|
24
|
+
"encoding/json"
|
|
25
|
+
"fmt"
|
|
26
|
+
"syscall/js"
|
|
27
|
+
native ${JSON.stringify(importPath)}
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
type response struct {
|
|
31
|
+
OK bool ${quote}json:"ok"${quote}
|
|
32
|
+
Value any ${quote}json:"value,omitempty"${quote}
|
|
33
|
+
Error string ${quote}json:"error,omitempty"${quote}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
func encode(value any, err error) string {
|
|
37
|
+
out := response{OK: err == nil, Value: value}
|
|
38
|
+
if err != nil { out.Value = nil; out.Error = err.Error() }
|
|
39
|
+
data, marshalErr := json.Marshal(out)
|
|
40
|
+
if marshalErr != nil {
|
|
41
|
+
// The error string itself is always JSON encodable.
|
|
42
|
+
escaped, escapeErr := json.Marshal(marshalErr.Error())
|
|
43
|
+
if escapeErr != nil { return ${quote}{"ok":false,"error":"cannot encode result"}${quote} }
|
|
44
|
+
return ${quote}{"ok":false,"error":${quote} + string(escaped) + ${quote}}${quote}
|
|
45
|
+
}
|
|
46
|
+
return string(data)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
func invoke(arity int, encoded string, call func([]json.RawMessage) (any, error)) (result string) {
|
|
50
|
+
defer func() {
|
|
51
|
+
if recovered := recover(); recovered != nil { result = encode(nil, fmt.Errorf("Go panic: %v", recovered)) }
|
|
52
|
+
}()
|
|
53
|
+
var args []json.RawMessage
|
|
54
|
+
if err := json.Unmarshal([]byte(encoded), &args); err != nil { return encode(nil, fmt.Errorf("decode arguments: %w", err)) }
|
|
55
|
+
if len(args) != arity { return encode(nil, fmt.Errorf("expected %d arguments", arity)) }
|
|
56
|
+
value, err := call(args)
|
|
57
|
+
return encode(value, err)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
func bind(arity int, call func([]json.RawMessage) (any, error)) js.Func {
|
|
61
|
+
return js.FuncOf(func(_ js.Value, values []js.Value) any {
|
|
62
|
+
if len(values) != 1 || values[0].Type() != js.TypeString { return encode(nil, fmt.Errorf("expected encoded arguments")) }
|
|
63
|
+
encoded := values[0].String()
|
|
64
|
+
executor := js.FuncOf(func(_ js.Value, callbacks []js.Value) any {
|
|
65
|
+
resolve := callbacks[0]
|
|
66
|
+
// Return to JS before waiting for timers/channels: blocking a js.FuncOf
|
|
67
|
+
// callback would prevent the event loop from resuming the Go scheduler.
|
|
68
|
+
// The owning Worker bounds this goroutine's lifetime on abort/timeout.
|
|
69
|
+
go func() { resolve.Invoke(invoke(arity, encoded, call)) }()
|
|
70
|
+
return nil
|
|
71
|
+
})
|
|
72
|
+
promise := js.Global().Get("Promise").New(executor)
|
|
73
|
+
// Promise constructors invoke their executor synchronously; keeping the
|
|
74
|
+
// temporary js.Func beyond construction would leak one callback per call.
|
|
75
|
+
executor.Release()
|
|
76
|
+
return promise
|
|
77
|
+
})
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
func main() {
|
|
81
|
+
functions := map[string]js.Func{
|
|
82
|
+
${bindings}
|
|
83
|
+
}
|
|
84
|
+
api := js.Global().Get("Object").New()
|
|
85
|
+
for name, fn := range functions { api.Set(name, fn) }
|
|
86
|
+
js.Global().Set("__wasmgen_api", api)
|
|
87
|
+
js.Global().Call("__wasmgen_ready")
|
|
88
|
+
// The owning Web Worker keeps callbacks alive; dispose/abort terminates it
|
|
89
|
+
// and releases its entire Go runtime, memory, and registered callbacks.
|
|
90
|
+
select {}
|
|
91
|
+
}
|
|
92
|
+
`;
|
|
93
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { goBridge } from './bridge.js';
|
|
2
|
+
import { workerSource } from './worker.js';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { hasCode } from '../../shared/errors.js';
|
|
5
|
+
import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { run } from '../../process.js';
|
|
8
|
+
async function build(mod, { directory, scratch, tools, signal }) {
|
|
9
|
+
const go = tools.go ?? 'go';
|
|
10
|
+
const env = { ...process.env, GOOS: 'js', GOARCH: 'wasm', CGO_ENABLED: '0', ...(mod.package ? {} : { GOWORK: 'off' }) };
|
|
11
|
+
let buildRoot = scratch;
|
|
12
|
+
let externalBuild;
|
|
13
|
+
let importPath = 'wasmgen.local/generated/native';
|
|
14
|
+
try {
|
|
15
|
+
if (mod.package) {
|
|
16
|
+
const metadata = z.object({ Name: z.string(), Dir: z.string(), ImportPath: z.string(), Module: z.object({ Dir: z.string() }).optional() }).parse(JSON.parse(await run(go, ['list', '-json', '.'], { cwd: mod.package, env, signal })));
|
|
17
|
+
if (metadata.Name === 'main' || !metadata.Module?.Dir)
|
|
18
|
+
throw new Error(`${mod.name}: package must be an importable Go module package`);
|
|
19
|
+
importPath = metadata.ImportPath;
|
|
20
|
+
// Keep the wrapper beneath the target package so the original module
|
|
21
|
+
// settings and even nested internal-package visibility are preserved.
|
|
22
|
+
externalBuild = await mkdtemp(path.join(metadata.Dir, '.wasmgen-'));
|
|
23
|
+
buildRoot = externalBuild;
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
await mkdir(path.join(scratch, 'native'));
|
|
27
|
+
await writeFile(path.join(scratch, 'go.mod'), 'module wasmgen.local/generated\n\ngo 1.22\n');
|
|
28
|
+
for (const file of mod.files)
|
|
29
|
+
await copyFile(file, path.join(scratch, 'native', path.basename(file)));
|
|
30
|
+
}
|
|
31
|
+
await writeFile(path.join(buildRoot, 'main.go'), goBridge(mod, importPath));
|
|
32
|
+
await run(go, ['build', '-trimpath', '-ldflags=-s -w', '-o', path.join(directory, 'native.wasm'), '.'], { cwd: buildRoot, env, signal });
|
|
33
|
+
// Resolve GOROOT in the same module: Go's auto-selected toolchain may differ.
|
|
34
|
+
const goroot = await run(go, ['env', 'GOROOT'], { cwd: buildRoot, env, signal });
|
|
35
|
+
let runtime;
|
|
36
|
+
for (const relative of ['lib/wasm/wasm_exec.js', 'misc/wasm/wasm_exec.js']) {
|
|
37
|
+
try {
|
|
38
|
+
runtime = await readFile(path.join(goroot, relative));
|
|
39
|
+
break;
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (!hasCode(error, 'ENOENT'))
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (!runtime)
|
|
47
|
+
throw new Error(`Go JavaScript runtime not found in ${goroot}`);
|
|
48
|
+
await writeFile(path.join(directory, 'go-runtime.js'), runtime);
|
|
49
|
+
try {
|
|
50
|
+
await copyFile(path.join(goroot, 'LICENSE'), path.join(directory, 'GO-LICENSE'));
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (!hasCode(error, 'ENOENT'))
|
|
54
|
+
throw error;
|
|
55
|
+
// Some OS distributions move GOROOT/LICENSE into their package documentation.
|
|
56
|
+
await copyFile(new URL('../../licenses/GO-LICENSE', import.meta.url), path.join(directory, 'GO-LICENSE'));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
if (externalBuild)
|
|
61
|
+
await rm(externalBuild, { recursive: true, force: true });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export const goAdapter = { language: 'go', build, workerSource };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function workerSource(): string;
|