@macula-io/ts 0.13.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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,343 @@
1
+ # macula-ts
2
+
3
+ [![CI](https://img.shields.io/github/actions/workflow/status/macula-io/macula-ts/ci.yml?branch=main&label=CI)](https://github.com/macula-io/macula-ts/actions/workflows/ci.yml)
4
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](#license)
5
+ [![Node](https://img.shields.io/badge/node-24.18%2B-339933?logo=node.js)](https://nodejs.org)
6
+ [![zero install scripts](https://img.shields.io/badge/install--scripts-zero-success.svg)](#packaging-genuinely-zero-install-time-scripts)
7
+ [![GitHub Sponsors](https://img.shields.io/badge/GitHub%20Sponsors-support-ea4aaa.svg?logo=githubsponsors&logoColor=white)](https://github.com/sponsors/rgfaber)
8
+
9
+ <p align="center">
10
+ <picture>
11
+ <source media="(prefers-color-scheme: dark)" srcset="assets/macula-ts-full-dark.svg">
12
+ <img src="assets/macula-ts-full-light.svg" alt="Macula" width="320">
13
+ </picture>
14
+ </p>
15
+
16
+ <p align="center">
17
+ <strong>TypeScript SDK for the Macula mesh, via FFI over macula-go</strong>
18
+ </p>
19
+
20
+ ---
21
+
22
+ > **Status, 2026-09-04:** identity generation, a real transport +
23
+ > CONNECT/HELLO handshake, unary RPC (both roles), DHT record
24
+ > lookups/publication, pubsub, content transfer, UCAN minting/inspection
25
+ > + UCAN-gated calling, and direct-dial (both roles) are all
26
+ > **live-verified against the real production fleet**
27
+ > (`station-de-frankfurt.macula.io`). Streaming RPC, streaming/content
28
+ > direct-dial, cert-chain-authorized direct-dial, and provider-side UCAN
29
+ > policy gating don't exist yet — see [What's explicitly not yet
30
+ > implemented](#whats-explicitly-not-yet-implemented). Published to npm
31
+ > as `@macula-io/ts` with zero install-time scripts — see
32
+ > [Packaging](#packaging-genuinely-zero-install-time-scripts). Full
33
+ > development history, including every bug found and fixed along the
34
+ > way, lives in [CHANGELOG.md](CHANGELOG.md), not here.
35
+
36
+ ## What is this?
37
+
38
+ A TypeScript SDK for the Macula mesh protocol — real QUIC-based mesh
39
+ connectivity from Node.js: identity, sessions, unary RPC, pub/sub,
40
+ content transfer, UCAN capability tokens, and direct-dial, all reaching
41
+ the real production fleet today. Built as an FFI binding over
42
+ [macula-go](https://github.com/macula-io/macula-go) rather than a native
43
+ reimplementation — see below for why.
44
+
45
+ ## Why FFI over macula-go, not a native TypeScript reimplementation
46
+
47
+ Macula's mesh protocol runs over raw QUIC with a custom ALPN string
48
+ (`"macula"`, not `"h3"`) and its own length-prefixed, deterministic-CBOR
49
+ frame format — not HTTP/3. Node.js has no mature first-party QUIC stack
50
+ that's actually usable for this today:
51
+
52
+ - `node:quic` (Node's own built-in, experimental module) **does** work at
53
+ the transport level — the QUIC+TLS 1.3 handshake with ALPN `"macula"`
54
+ completes and a bidirectional stream opens against the real production
55
+ stations. But it is absent from every currently-supportable official
56
+ Node binary — compile-time gated out of the Node 24 and 26 LTS lines —
57
+ and the one line that does ship it (Node 25.x) is already past its own
58
+ EOL and crashes the process about a second after a successful
59
+ handshake (a native assertion failure in `Endpoint::FindSession`). Not
60
+ viable to depend on today.
61
+ - No actively-maintained pure-JS or WASM QUIC implementation currently
62
+ exposes a public client API with custom-ALPN support (the most promising
63
+ one found, [quico](https://github.com/colocohen/quico), documents custom
64
+ ALPN only on its low-level *server* API — its client convenience API is
65
+ HTTP/3-specific).
66
+
67
+ macula-go, macula-rust, macula-dotnet, and macula-php have all already
68
+ proven this protocol works and are actively maintained. Rather than
69
+ reimplement QUIC + deterministic CBOR + Ed25519 framing a fifth time in a
70
+ language with no mature QUIC story of its own, macula-ts reuses macula-go's
71
+ already-proven implementation through FFI — the same tradeoff
72
+ [macula-php](https://github.com/macula-io/macula-php) already made
73
+ successfully (see its `cabi/` directory, which this package's own `cabi/`
74
+ is structurally modeled on, including its handle-based memory-ownership
75
+ convention).
76
+
77
+ ## Sibling SDKs
78
+
79
+ | Repo | Approach |
80
+ |---|---|
81
+ | [macula](https://github.com/macula-io/macula) | The reference SDK (Erlang/OTP) |
82
+ | [macula-go](https://github.com/macula-io/macula-go) | Go port — same protocol |
83
+ | [macula-rust](https://github.com/macula-io/macula-rust) | Native reimplementation (quinn, pure Rust) |
84
+ | [macula-dotnet](https://github.com/macula-io/macula-dotnet) | Native reimplementation (System.Net.Quic / msquic) |
85
+ | [macula-php](https://github.com/macula-io/macula-php) | FFI binding over macula-go (this package's structural precedent) |
86
+ | **macula-ts** | FFI binding over macula-go |
87
+ | [macula-station](https://github.com/macula-io/macula-station) | The station: DHT, SWIM, routing, peering |
88
+ | [macula-realm](https://github.com/macula-io/macula-realm) | Managed-realm identity + certificate authority |
89
+
90
+ ## Architecture
91
+
92
+ ```
93
+ src/*.ts --(node-gyp-build)--> addon/binding.cc (N-API) --(static link)--> cabi/ --(cgo)--> macula-go
94
+ ```
95
+
96
+ `cabi/` is a Go module that imports `macula-go` and builds with
97
+ `go build -buildmode=c-archive` into a C ABI static archive (`libmacula.a`
98
+ + `libmacula.h`) — not a shared library. `addon/binding.cc` is a small,
99
+ purpose-built [node-addon-api](https://github.com/nodejs/node-addon-api)
100
+ N-API addon (not a generic FFI bridge) that links `libmacula.a` in
101
+ statically, so the resulting `.node` file is self-contained: nothing to
102
+ locate or `dlopen` at runtime, no separate shared library to ship
103
+ alongside it. `src/binding.ts` loads that addon via
104
+ [`node-gyp-build`](https://github.com/prebuild/node-gyp-build) (a
105
+ zero-dependency runtime loader) and re-exports its typed functions;
106
+ `src/identity.ts` (and everything built on top of it) is the actual
107
+ public TypeScript API, never touching the addon directly.
108
+
109
+ **Memory ownership**, copied from macula-php's `cabi/` rather than
110
+ reinvented: every opaque Go value (an identity keypair, a session, or an
111
+ inbound "pending call" awaiting a `serve()` handler's reply) crosses the
112
+ boundary as a `uintptr_t` from `runtime/cgo.Handle`. Hold it, pass it
113
+ back for every operation on that value, and free it exactly once
114
+ (`Identity#dispose()` on the TS side; a pending-call handle is freed
115
+ automatically by whichever of `macula_pending_call_reply_result`/`_error`
116
+ answers it). Fixed-length fields (a 32-byte NodeID or seed) are written
117
+ directly into a caller-supplied output buffer. Every exported function
118
+ resolves handles through a `recover()`-guarded lookup, never a raw
119
+ `cgo.Handle(h)` — `cgo.Handle`'s own `.Value()`/`.Delete()` panic, not
120
+ return an error, on a handle this process never issued or already freed.
121
+
122
+ **RPC payloads cross this boundary as JSON text**, not another handle —
123
+ `cabi/wirevalue.go` converts to/from macula-go's `cbor.Value`, ported from
124
+ [macula-cli](https://github.com/macula-io/macula-cli)'s
125
+ `internal/wirevalue` package (already proven against the same no-bool,
126
+ bytes-as-hex-string rules) rather than reinvented. `Session.serve()`
127
+ cannot hand a Go closure across the FFI boundary the way `ServeOneCall`
128
+ expects, since the actual answer has to come from arbitrary, possibly-
129
+ async TypeScript — so `cabi/serve.go` splits that one blocking Go call
130
+ into three cgo exports instead (wait-for-call, read the pending call's
131
+ procedure/payload, reply), the same split
132
+ [macula-php](https://github.com/macula-io/macula-php)'s `cabi/serve.go`
133
+ already proved for the identical problem.
134
+
135
+ Development history (every bug found while building this, and how it was
136
+ fixed) is in [CHANGELOG.md](CHANGELOG.md).
137
+
138
+ ## What's implemented
139
+
140
+ - **Identity** — `Identity.generate()` (a fresh, S/Kademlia
141
+ puzzle-hardened Ed25519 identity), `Identity.fromSeedBytes()`
142
+ (deterministic reconstruction from a saved 32-byte seed),
143
+ `identity.nodeId`/`.privateSeedBytes`/`.dispose()`, and
144
+ `identity.sign(data)` — a generic Ed25519 primitive (no
145
+ application-specific message format baked in; `data` is signed exactly
146
+ as given). Using a disposed `Identity` throws instead of signing with a
147
+ freed handle.
148
+ - **Session** — `Session.connect(host, port, identity)` dials a real
149
+ macula-station and completes the CONNECT/HELLO handshake (WebPKI
150
+ trust). `session.remoteAddr`, `session.stationNodeId` (the
151
+ HELLO-verified station identity), `session.close(identity, reason?)`
152
+ (idempotent). Using a session's accessors after `close()` throws
153
+ cleanly rather than crashing.
154
+ - **RPC, caller role** — `session.call(procedure, payload, opts?)` sends
155
+ a signed CALL and waits for the matching RESULT/ERROR.
156
+ `payload`/the return value are `JsonValue` (string/number/null/array/
157
+ object — **no boolean**, since macula's wire CBOR has no bool type;
158
+ encode `true`/`false` as `1`/`0` yourself). A BOLT#4 ERROR frame (e.g.
159
+ `unknown_next_peer`) rejects with a `MaculaCallError` carrying the
160
+ numeric `code`, `bolt4Name`, `retryable`, and `detail`. `opts.realm` (a
161
+ 64-character hex string) scopes the call to a realm other than the
162
+ all-zero default; `callWithUcan()`/`publish()`/`subscribe()` take the
163
+ identical option.
164
+ - **RPC, provider role** — `session.serve(procedure, handler)` advertises
165
+ `procedure` and answers inbound CALLs against it forever, invoking
166
+ `handler(payload)` for each (sync or async). Resolves with an async
167
+ `stop()` that unadvertises and waits for the current poll tick to
168
+ finish. Only one `serve()` per `Session` at a time, and `call()`/
169
+ `serve()` refuse to run concurrently on the same `Session` — both read
170
+ frames off one shared control stream; open a second `Session` for the
171
+ other role.
172
+ - **DHT** — `session.findRecordsByType(recordType)`,
173
+ `session.findRecords(key)`, `session.findRecord(key)`, and
174
+ `session.putProcedureAdvertisement(procedure, servingStation, opts?)`/
175
+ `session.putContentAnnouncement(mcid, endpoint, ttlMs?)` — typed
176
+ builders wrapping macula-go's own `dht.NewProcedureAdvertisement`/
177
+ `NewContentAnnouncement` (signed via `dht.Sign`, stored via
178
+ `dht.PutRecord`). There is deliberately no generic
179
+ `putRecord(type, arbitraryPayload)` — a procedure_advertisement/
180
+ content_announcement payload carries raw pubkey/MCID fields that must
181
+ be actual CBOR byte strings, which only the typed builders guarantee.
182
+ - **Pubsub** — `session.publish(topic, payload, opts?)` (fire-and-forget,
183
+ no ack on the wire) and `session.subscribe(topic, handler, opts?)`.
184
+ `subscribe()` resolves with an async `stop()` that sends UNSUBSCRIBE
185
+ and does not resolve until the underlying reader goroutine has
186
+ genuinely exited. Only one `subscribe()` (and no active `serve()`) per
187
+ `Session` at a time — `publish()` itself is exempt, since it only ever
188
+ writes, so a `Session` can safely `publish()` on the same topic it's
189
+ `subscribe()`d to.
190
+ - **Content transfer** — `session.putContent(data, name?)` /
191
+ `session.getContent(mcid)`, sent on their own dedicated QUIC stream
192
+ (not the shared control stream, so they run safely alongside an active
193
+ `serve()`/`subscribe()`). Data above 256 KiB is chunked and reassembled
194
+ automatically. `mcid` crosses the boundary as a lowercase hex string.
195
+ **This is a one-time TRANSFER mechanism, not durable object storage** —
196
+ a station may forget content after serving it, and there is no
197
+ list/delete operation.
198
+ - **UCAN** — `Ucan.mint(issuer, audience, capabilities?, opts?)` (a
199
+ JWT-shaped, EdDSA-signed capability token, UCAN spec `"0.10.0"`) and
200
+ `Ucan.decode(token)` (parses claims WITHOUT verifying signature or
201
+ expiry — `Ucan#isExpired` mirrors macula-go's own semantics). Both are
202
+ pure local operations, no network I/O. `issuer`/`audience` DID strings
203
+ are `did:macula:<hex NodeID>`. `session.callWithUcan(procedure,
204
+ payload, ucanToken, opts?)` attaches a token to an outgoing CALL, for
205
+ invoking a procedure gated behind a provider-side `ucan.Policy.Required`
206
+ policy. **Deliberately places no restriction relating the calling
207
+ identity to the token's own `aud` claim** — macula's UCAN gate is a
208
+ BEARER-token check (verifies signature + expiry against the issuer
209
+ only, never the caller's identity against `aud`), so a client-side
210
+ "does my identity match this token's audience" guard would both reject
211
+ configurations the real wire-level gate accepts and misrepresent a
212
+ security property the mesh doesn't enforce. This SDK does **not**
213
+ expose `ucan.Verify` or `ucan.Policy` — only minting, inspecting, and
214
+ attaching a token are implemented; enforcing one is provider-side, out
215
+ of scope here.
216
+ - **Direct-dial** — `session.resolveDirect(procedure, opts?)`,
217
+ `session.callDirect(procedure, payload, opts?)`,
218
+ `session.callDirectWithUcan(procedure, payload, ucanToken, opts?)`
219
+ (caller side) and `session.advertiseDirect(procedure, opts?)` plus a
220
+ standalone `keepAdvertisedDirect(session, procedure, opts?)` helper
221
+ (provider side). Resolves a signed `procedure_advertisement` DHT record
222
+ to its serving station's own signed `station_endpoint`, then dials that
223
+ station directly in one hop instead of depending on advertise-gossip
224
+ having reached whichever station the caller happens to already be
225
+ connected to. Trust is enforced at the application layer: the freshly
226
+ connected peer's HELLO-proven identity is checked against the exact
227
+ pubkey the signed DHT chain resolved. `advertiseDirect()` issues both a
228
+ plain ADVERTISE and the signed DHT record on the same call — both are
229
+ required for `resolveDirect()`+`callDirect()` to actually reach a live
230
+ route. `resolveDirect`/`callDirect`/`callDirectWithUcan`/
231
+ `advertiseDirect` share the same same-Session exclusivity guard as
232
+ `call()`/the DHT methods; a long-lived provider that also serves the
233
+ same procedure needs a separate `Session` (and identity — this fleet
234
+ enforces one connection per identity) to keep re-advertising on, which
235
+ is why `keepAdvertisedDirect()` is a standalone function rather than a
236
+ `Session` method.
237
+
238
+ Every item above is live-verified against the real production fleet
239
+ (`station-de-frankfurt.macula.io`), including negative/error paths and,
240
+ where applicable, the actual packaged npm tarball rather than only the
241
+ dev build — see [CHANGELOG.md](CHANGELOG.md) for the specific
242
+ assertions, bugs found, and fixes for each.
243
+
244
+ ## What's explicitly not yet implemented
245
+
246
+ Streaming RPC, streaming/content direct-dial (`OpenStreamDirect`,
247
+ `PutDirect`/`GetDirect` — plain `Session.call`/`serve` direct-dial is
248
+ implemented, see above), cert-chain-authorized direct-dial
249
+ (`ResolveWithCertChain`/`CallWithCertChain`/`AdvertiseDirectWithCertChain`
250
+ — opt-in even in macula-go itself), provider-side UCAN policy gating
251
+ (`ucan.Policy`/`ServeOneCallGated` — this SDK can mint/attach a token but
252
+ not enforce one on a served procedure), per-realm `serve`/`advertise`
253
+ (these two still only ever use the all-zero realm — `call`/`callWithUcan`/
254
+ `publish`/`subscribe`, and DHT's `putProcedureAdvertisement`, all DO now
255
+ take an optional realm), a generic "put any DHT record type with an
256
+ arbitrary payload" function (see above for why), a `station_endpoint`
257
+ record builder (macula-go has none either — stations publish those
258
+ themselves, not clients), and `Pinned`/`Insecure` trust modes (`WebPKI`
259
+ only so far). Multiple concurrent `subscribe()` topics on one `Session`
260
+ also isn't supported yet — one `subscribe()` (like one `serve()`) per
261
+ `Session` at a time; open a second `Session` for a second topic. Each of
262
+ these is a separate, later slice of work built on top of a working
263
+ `Session`.
264
+
265
+ ## Testing
266
+
267
+ ```bash
268
+ npx vitest run # default suite, no network
269
+ npm run test:live # MACULA_TS_LIVE=1 vitest run src/session.live.test.ts src/rpc.live.test.ts src/dht.live.test.ts src/pubsub.live.test.ts src/content.live.test.ts src/ucan.live.test.ts src/directdial.live.test.ts
270
+ ```
271
+
272
+ `src/session.live.test.ts`, `src/rpc.live.test.ts`, `src/dht.live.test.ts`,
273
+ `src/pubsub.live.test.ts`, `src/content.live.test.ts`,
274
+ `src/ucan.live.test.ts`, and `src/directdial.live.test.ts` hit the real
275
+ production fleet and are **not** part of default `npm test`/CI — opt in
276
+ explicitly, gated behind `MACULA_TS_LIVE`. Same convention as macula-go's
277
+ `live` build tag, macula-rust's `#[ignore]`, and macula-dotnet's
278
+ `[Trait("Category","Live")]`: real-network tests are written and
279
+ runnable, just excluded from the default/CI run so a station outage doesn't
280
+ make ordinary CI flaky. `.github/workflows/ci.yml` exposes this as a
281
+ manually-triggered (`workflow_dispatch`) job, never run automatically on
282
+ push/PR.
283
+
284
+ ## Packaging: genuinely zero install-time scripts
285
+
286
+ An earlier version of this package used [koffi](https://koffi.dev) (a
287
+ generic dynamic FFI bridge) to load `libmacula.so` at runtime. That was
288
+ replaced — koffi has its own native `install` script and ships no
289
+ prebuilt binaries in its npm tarball, so it inherited the exact class of
290
+ npm-install-script friction that
291
+ [macula-mcp's better-sqlite3 dependency caused](https://github.com/macula-io/macula-mcp/blob/main/CHANGELOG.md)
292
+ before that project moved to `node:sqlite`. No actively-maintained
293
+ generic Node FFI library was found that avoids this.
294
+
295
+ Instead, `addon/binding.cc` is a small addon purpose-built for exactly
296
+ macula-ts's own exported functions (not a generic bridge), packaged with
297
+ [`prebuildify`](https://github.com/prebuild/prebuildify) +
298
+ [`node-gyp-build`](https://github.com/prebuild/node-gyp-build) — the same
299
+ pattern used by `sharp`, `bcrypt`, and other native modules that need zero
300
+ consumer-side compilation. The compiled `.node` binary for each supported
301
+ platform is baked into `prebuilds/` and published as part of the npm
302
+ package itself (**not** gitignored — there is nothing to build or fetch
303
+ at a consumer's `npm install` time). `package.json` has no `install`,
304
+ `postinstall`, or `preinstall` script at all.
305
+
306
+ Five platforms are covered: `linux-x64`, `linux-arm64`, `darwin-arm64`,
307
+ `darwin-x64`, and `win32-x64`. `.github/workflows/prebuilds.yml` builds
308
+ each on a real GitHub-hosted runner for that platform (`CGO_ENABLED=1`
309
+ needs a matching native C toolchain per target, so cross-compiling
310
+ `cabi/`'s Go archive from Linux isn't the right approach here — the same
311
+ reason `sharp`/`bcrypt`/etc. use real per-OS runners) and commits the
312
+ results back to `main`. `.github/workflows/ci.yml`'s "Confirm the
313
+ committed prebuild is not stale" step re-verifies, on every push, that
314
+ `linux-x64`'s committed binary still matches a fresh rebuild of current
315
+ source, byte for byte. Getting that check — and the Windows build — to
316
+ actually hold surfaced three real build-toolchain bugs; see
317
+ [CHANGELOG.md](CHANGELOG.md) for the specifics.
318
+
319
+ ## Development
320
+
321
+ ```bash
322
+ npm run build:go # builds cabi/build/libmacula.a -- must run BEFORE
323
+ # npm install, since binding.gyp's mere presence in
324
+ # this repo (not in the published package) makes npm
325
+ # implicitly run `node-gyp rebuild` as part of
326
+ # install, and that rebuild links against this archive
327
+ npm install # builds the native addon (via the implicit node-gyp
328
+ # rebuild above) and installs JS deps
329
+ npm run typecheck
330
+ npm test
331
+ npm run build:prebuilds # regenerate prebuilds/ after touching addon/ or cabi/ -- commit the result
332
+ npm run build # local dev build: addon + tsc
333
+ ```
334
+
335
+ Requires Go >=1.27 (for `cabi/`), a C++ toolchain (for `addon/`), and Node
336
+ >=24.18.1 (see `engines` in `package.json` — matches the same floor
337
+ macula-mcp landed on for `node:sqlite`; earlier Node lines don't ship it).
338
+ None of this is required to *consume* the published package — only to
339
+ work on macula-ts itself.
340
+
341
+ ## License
342
+
343
+ Apache-2.0
@@ -0,0 +1,47 @@
1
+ export type Handle = number | bigint;
2
+ export declare const native: {
3
+ identityGenerate(): bigint;
4
+ identityFromSeedBytes(seed32: Uint8Array): bigint;
5
+ identityNodeId(handle: Handle): Uint8Array;
6
+ identityPrivateBytes(handle: Handle): Uint8Array;
7
+ identityFree(handle: Handle): void;
8
+ identitySign(handle: Handle, data: Uint8Array): Uint8Array;
9
+ sessionConnect(host: string, port: number, identityHandle: Handle): Promise<bigint>;
10
+ sessionRemoteAddr(handle: Handle): string;
11
+ sessionStationNodeId(handle: Handle): Uint8Array;
12
+ sessionClose(handle: Handle, identityHandle: Handle, reason: string): Promise<void>;
13
+ sessionCall(sessionHandle: Handle, identityHandle: Handle, procedure: string, realm: Uint8Array | undefined, payloadJson: string, timeoutMs: number): Promise<string>;
14
+ ucanMint(identityHandle: Handle, issuer: string, audience: string, capabilitiesJson: string, expiresAt: number | undefined, notBefore: number | undefined, nonce: string, factsJson: string | undefined, proofsJson: string | undefined): string;
15
+ ucanDecode(token: string): string;
16
+ sessionCallWithUcan(sessionHandle: Handle, identityHandle: Handle, procedure: string, realm: Uint8Array | undefined, payloadJson: string, timeoutMs: number, ucanToken: string): Promise<string>;
17
+ sessionAdvertise(sessionHandle: Handle, identityHandle: Handle, realm: Uint8Array | undefined, procedure: string): Promise<void>;
18
+ sessionUnadvertise(sessionHandle: Handle, identityHandle: Handle, realm: Uint8Array | undefined, procedure: string): Promise<void>;
19
+ serveWaitForCall(sessionHandle: Handle, identityHandle: Handle, realm: Uint8Array | undefined, procedure: string, timeoutMs: number): Promise<Handle | null>;
20
+ pendingCallProcedure(pendingHandle: Handle): string;
21
+ pendingCallPayloadJson(pendingHandle: Handle): string;
22
+ pendingCallReplyResult(pendingHandle: Handle, resultJson: string): Promise<void>;
23
+ pendingCallReplyError(pendingHandle: Handle, detail: string): Promise<void>;
24
+ dhtFindRecordsByType(sessionHandle: Handle, identityHandle: Handle, recordType: number): Promise<string>;
25
+ dhtFindRecords(sessionHandle: Handle, identityHandle: Handle, key32: Uint8Array): Promise<string>;
26
+ dhtFindRecord(sessionHandle: Handle, identityHandle: Handle, key32: Uint8Array): Promise<string | null>;
27
+ dhtPutProcedureAdvertisement(sessionHandle: Handle, identityHandle: Handle, realm: Uint8Array | undefined, procedure: string, servingStation32: Uint8Array, ttlMs: number): Promise<string>;
28
+ dhtPutContentAnnouncement(sessionHandle: Handle, identityHandle: Handle, mcid34: Uint8Array, endpoint: string, ttlMs: number): Promise<string>;
29
+ sessionPublish(sessionHandle: Handle, identityHandle: Handle, realm: Uint8Array | undefined, topic: string, payloadJson: string, ttlMs: number): Promise<void>;
30
+ sessionSubscribeStart(sessionHandle: Handle, identityHandle: Handle, realm: Uint8Array | undefined, topic: string, onEvent: (msg: {
31
+ kind: "event";
32
+ topic: string;
33
+ publisher: Uint8Array;
34
+ seq: number;
35
+ payloadJson: string;
36
+ } | {
37
+ kind: "closed";
38
+ error: string;
39
+ }) => void): Promise<bigint>;
40
+ sessionSubscribeStop(subscriptionHandle: Handle): Promise<void>;
41
+ contentPut(sessionHandle: Handle, identityHandle: Handle, data: Uint8Array, name: string): Promise<string>;
42
+ contentGet(sessionHandle: Handle, identityHandle: Handle, mcidHex: string): Promise<Uint8Array | null>;
43
+ directdialResolve(sessionHandle: Handle, identityHandle: Handle, realm: Uint8Array | undefined, procedure: string): Promise<string>;
44
+ directdialCall(sessionHandle: Handle, identityHandle: Handle, procedure: string, realm: Uint8Array | undefined, payloadJson: string, timeoutMs: number): Promise<string>;
45
+ directdialCallWithUcan(sessionHandle: Handle, identityHandle: Handle, procedure: string, realm: Uint8Array | undefined, payloadJson: string, timeoutMs: number, ucanToken: string): Promise<string>;
46
+ directdialAdvertise(sessionHandle: Handle, identityHandle: Handle, realm: Uint8Array | undefined, procedure: string, ttlMs: number): Promise<void>;
47
+ };