@kargjonas/sabus 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 +177 -0
- package/README.md +87 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/runtime-peer.d.ts +13 -0
- package/dist/runtime-peer.d.ts.map +1 -0
- package/dist/runtime-peer.js +93 -0
- package/dist/schema.d.ts +108 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +172 -0
- package/dist/shared-object.d.ts +55 -0
- package/dist/shared-object.d.ts.map +1 -0
- package/dist/shared-object.js +159 -0
- package/dist/shared-runtime.d.ts +31 -0
- package/dist/shared-runtime.d.ts.map +1 -0
- package/dist/shared-runtime.js +119 -0
- package/package.json +55 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# sabus
|
|
2
|
+
|
|
3
|
+
Minimal SharedArrayBuffer worker bus for low-overhead cross-worker data sharing.
|
|
4
|
+
|
|
5
|
+
> [!NOTE]
|
|
6
|
+
> Check the `examples/` directory. Each example has a focused `README` with context and usage notes.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
Install from command line:
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install @kargjonas/sabus@0.1.0
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Install via `package.json`:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
"@kargjonas/sabus": "0.1.0"
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Quick start
|
|
23
|
+
|
|
24
|
+
Host:
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { SharedRuntime, Type } from "sabus";
|
|
28
|
+
|
|
29
|
+
const schema = {
|
|
30
|
+
count: Type.Int32,
|
|
31
|
+
} as const;
|
|
32
|
+
|
|
33
|
+
const host = SharedRuntime.host();
|
|
34
|
+
const counter = host.createSharedObject("counter", schema);
|
|
35
|
+
const worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
|
|
36
|
+
|
|
37
|
+
await host.attachWorker("reader", worker);
|
|
38
|
+
|
|
39
|
+
await counter.write({ count: 1 });
|
|
40
|
+
console.log(counter.read()?.count); // 1
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Worker (`worker.ts`):
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import { SharedRuntime, Type } from "sabus";
|
|
47
|
+
|
|
48
|
+
const schema = {
|
|
49
|
+
count: Type.Int32,
|
|
50
|
+
} as const;
|
|
51
|
+
|
|
52
|
+
const runtime = await SharedRuntime.worker();
|
|
53
|
+
const counter = runtime.openSharedObject("counter", schema);
|
|
54
|
+
|
|
55
|
+
counter.subscribe(() => {
|
|
56
|
+
const latest = counter.read();
|
|
57
|
+
if (latest) console.log("count:", latest.count, "seq:", latest.seq);
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
For worker-side usage and more complete patterns, check `examples/`.
|
|
62
|
+
|
|
63
|
+
## What it provides
|
|
64
|
+
|
|
65
|
+
- `SharedRuntime` to coordinate shared objects across host and workers.
|
|
66
|
+
- `SharedObject` with FIFO write lock and atomic latest-read behavior.
|
|
67
|
+
- `TypedSharedObject` for schema-based typed reads and writes.
|
|
68
|
+
- `schema` helpers (`Type`, `computeLayout`, `readSnapshot`, `writeFields`).
|
|
69
|
+
|
|
70
|
+
## Requirements
|
|
71
|
+
|
|
72
|
+
- Environment with `SharedArrayBuffer` support.
|
|
73
|
+
- Browser usage needs cross-origin isolation headers (`COOP`/`COEP`).
|
|
74
|
+
|
|
75
|
+
## Development
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
npm run typecheck
|
|
79
|
+
npm test
|
|
80
|
+
npm run build
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Example app:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
npm run dev
|
|
87
|
+
```
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { default as SharedRuntime } from "./shared-runtime.js";
|
|
2
|
+
export { SharedObject, TypedSharedObject, type SharedObjectConfig, type SharedObjectDescriptor, type SharedObjectReadSnapshot, type SharedObjectWriteCallback, type SharedObjectWriteContext, } from "./shared-object.js";
|
|
3
|
+
export { Type, computeLayout, readSnapshot, writeFields, type Layout, type SchemaDefinition, type SchemaValues, type SchemaWriteValues, } from "./schema.js";
|
|
4
|
+
export { createRuntimePeer, detectCurrentWorkerPeer, type RuntimePeer, } from "./runtime-peer.js";
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAE/D,OAAO,EACL,YAAY,EACZ,iBAAiB,EACjB,KAAK,kBAAkB,EACvB,KAAK,sBAAsB,EAC3B,KAAK,wBAAwB,EAC7B,KAAK,yBAAyB,EAC9B,KAAK,wBAAwB,GAC9B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,IAAI,EACJ,aAAa,EACb,YAAY,EACZ,WAAW,EACX,KAAK,MAAM,EACX,KAAK,gBAAgB,EACrB,KAAK,YAAY,EACjB,KAAK,iBAAiB,GACvB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,iBAAiB,EACjB,uBAAuB,EACvB,KAAK,WAAW,GACjB,MAAM,mBAAmB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { default as SharedRuntime } from "./shared-runtime.js";
|
|
2
|
+
export { SharedObject, TypedSharedObject, } from "./shared-object.js";
|
|
3
|
+
export { Type, computeLayout, readSnapshot, writeFields, } from "./schema.js";
|
|
4
|
+
export { createRuntimePeer, detectCurrentWorkerPeer, } from "./runtime-peer.js";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime message peer adapters.
|
|
3
|
+
*
|
|
4
|
+
* Converts browser- and Node-style worker endpoints into a uniform RuntimePeer.
|
|
5
|
+
* Also provides worker-side auto-detection for SharedRuntime.worker().
|
|
6
|
+
*/
|
|
7
|
+
export interface RuntimePeer {
|
|
8
|
+
postMessage(message: unknown): void;
|
|
9
|
+
addMessageListener(listener: (message: unknown) => void): () => void;
|
|
10
|
+
}
|
|
11
|
+
export declare function createRuntimePeer(endpoint: unknown): RuntimePeer;
|
|
12
|
+
export declare function detectCurrentWorkerPeer(): Promise<RuntimePeer>;
|
|
13
|
+
//# sourceMappingURL=runtime-peer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime-peer.d.ts","sourceRoot":"","sources":["../runtime-peer.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,WAAW,WAAW;IAC1B,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;IACpC,kBAAkB,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CACtE;AAoCD,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,OAAO,GAAG,WAAW,CAwChE;AAuCD,wBAAsB,uBAAuB,IAAI,OAAO,CAAC,WAAW,CAAC,CAMpE"}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime message peer adapters.
|
|
3
|
+
*
|
|
4
|
+
* Converts browser- and Node-style worker endpoints into a uniform RuntimePeer.
|
|
5
|
+
* Also provides worker-side auto-detection for SharedRuntime.worker().
|
|
6
|
+
*/
|
|
7
|
+
function isObject(value) {
|
|
8
|
+
return typeof value === "object" && value !== null;
|
|
9
|
+
}
|
|
10
|
+
function isBrowserPeerEndpoint(value) {
|
|
11
|
+
return (isObject(value) &&
|
|
12
|
+
typeof value.postMessage === "function" &&
|
|
13
|
+
typeof value.addEventListener === "function" &&
|
|
14
|
+
typeof value.removeEventListener === "function");
|
|
15
|
+
}
|
|
16
|
+
function isNodePeerEndpoint(value) {
|
|
17
|
+
return (isObject(value) &&
|
|
18
|
+
typeof value.postMessage === "function" &&
|
|
19
|
+
typeof value.on === "function");
|
|
20
|
+
}
|
|
21
|
+
export function createRuntimePeer(endpoint) {
|
|
22
|
+
if (isBrowserPeerEndpoint(endpoint)) {
|
|
23
|
+
return {
|
|
24
|
+
postMessage(message) {
|
|
25
|
+
endpoint.postMessage(message);
|
|
26
|
+
},
|
|
27
|
+
addMessageListener(listener) {
|
|
28
|
+
const onMessage = (event) => {
|
|
29
|
+
listener(event.data);
|
|
30
|
+
};
|
|
31
|
+
endpoint.addEventListener("message", onMessage);
|
|
32
|
+
return () => endpoint.removeEventListener("message", onMessage);
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
if (isNodePeerEndpoint(endpoint)) {
|
|
37
|
+
return {
|
|
38
|
+
postMessage(message) {
|
|
39
|
+
endpoint.postMessage(message);
|
|
40
|
+
},
|
|
41
|
+
addMessageListener(listener) {
|
|
42
|
+
const onMessage = (message) => {
|
|
43
|
+
listener(message);
|
|
44
|
+
};
|
|
45
|
+
endpoint.on("message", onMessage);
|
|
46
|
+
return () => {
|
|
47
|
+
if (typeof endpoint.off === "function") {
|
|
48
|
+
endpoint.off("message", onMessage);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
endpoint.removeListener?.("message", onMessage);
|
|
52
|
+
};
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
throw new Error("Unsupported worker endpoint: expected browser Worker/worker scope or Node worker endpoint");
|
|
57
|
+
}
|
|
58
|
+
function detectBrowserWorkerEndpoint() {
|
|
59
|
+
const g = globalThis;
|
|
60
|
+
if (typeof g.document === "undefined" &&
|
|
61
|
+
typeof g.postMessage === "function" &&
|
|
62
|
+
typeof g.addEventListener === "function" &&
|
|
63
|
+
typeof g.removeEventListener === "function")
|
|
64
|
+
return g;
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
function isNodeLikeRuntime() {
|
|
68
|
+
const processLike = globalThis.process;
|
|
69
|
+
return typeof processLike?.versions?.node === "string";
|
|
70
|
+
}
|
|
71
|
+
async function detectNodeParentPortEndpoint() {
|
|
72
|
+
if (!isNodeLikeRuntime())
|
|
73
|
+
return null;
|
|
74
|
+
try {
|
|
75
|
+
const dynamicImport = Function("specifier", "return import(specifier)");
|
|
76
|
+
const mod = await dynamicImport("node:worker_threads");
|
|
77
|
+
if (!isObject(mod))
|
|
78
|
+
return null;
|
|
79
|
+
return mod.parentPort ?? null;
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
export async function detectCurrentWorkerPeer() {
|
|
86
|
+
const browserEndpoint = detectBrowserWorkerEndpoint();
|
|
87
|
+
if (browserEndpoint)
|
|
88
|
+
return createRuntimePeer(browserEndpoint);
|
|
89
|
+
const nodeEndpoint = await detectNodeParentPortEndpoint();
|
|
90
|
+
if (nodeEndpoint)
|
|
91
|
+
return createRuntimePeer(nodeEndpoint);
|
|
92
|
+
throw new Error("No worker message endpoint available in this environment");
|
|
93
|
+
}
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema-driven type system for SharedObjects.
|
|
3
|
+
*
|
|
4
|
+
* A schema is a plain object mapping field names to types. Each field is either
|
|
5
|
+
* a scalar (Type.Float32) or a fixed-length array ([Type.Float32, 3]).
|
|
6
|
+
*
|
|
7
|
+
* From a schema definition, this module derives:
|
|
8
|
+
* - A memory layout (byte offsets and total size), computed once at creation
|
|
9
|
+
* - TypeScript types for reading (SchemaValues) and writing (SchemaWriteValues)
|
|
10
|
+
* - Functions to read/write fields directly via DataView, with no serialization
|
|
11
|
+
*/
|
|
12
|
+
export declare enum Type {
|
|
13
|
+
Int8 = 1,
|
|
14
|
+
Uint8 = 2,
|
|
15
|
+
Int16 = 3,
|
|
16
|
+
Uint16 = 4,
|
|
17
|
+
Int32 = 5,
|
|
18
|
+
Uint32 = 6,
|
|
19
|
+
Float32 = 7,
|
|
20
|
+
Float64 = 8
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Maps each Type enum value to its corresponding TypedArray class.
|
|
24
|
+
* Used as an indexed lookup by TypedArrayFor<T> to resolve types at compile time.
|
|
25
|
+
*/
|
|
26
|
+
interface TypedArrayMap {
|
|
27
|
+
[Type.Int8]: Int8Array;
|
|
28
|
+
[Type.Uint8]: Uint8Array;
|
|
29
|
+
[Type.Int16]: Int16Array;
|
|
30
|
+
[Type.Uint16]: Uint16Array;
|
|
31
|
+
[Type.Int32]: Int32Array;
|
|
32
|
+
[Type.Uint32]: Uint32Array;
|
|
33
|
+
[Type.Float32]: Float32Array;
|
|
34
|
+
[Type.Float64]: Float64Array;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Resolves a Type enum value to its TypedArray type via indexed access into
|
|
38
|
+
* TypedArrayMap. e.g. TypedArrayFor<Type.Float32> = Float32Array
|
|
39
|
+
*/
|
|
40
|
+
type TypedArrayFor<T extends Type> = TypedArrayMap[T];
|
|
41
|
+
/**
|
|
42
|
+
* A schema definition is a plain object mapping field names to field types.
|
|
43
|
+
* Must be declared `as const` to preserve literal types for type inference.
|
|
44
|
+
* Uses an interface to allow recursive (nested) schemas without circular alias errors.
|
|
45
|
+
* e.g. { health: Type.Int32, position: [Type.Float32, 3], transform: { x: Type.Float32 } }
|
|
46
|
+
*/
|
|
47
|
+
export interface SchemaDefinition {
|
|
48
|
+
readonly [key: string]: Type | readonly [Type, number] | SchemaDefinition;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Derives the JS read types from a schema. Scalar fields become `number`,
|
|
52
|
+
* array fields become the corresponding TypedArray (e.g. Float32Array),
|
|
53
|
+
* and nested schema fields become a nested SchemaValues object.
|
|
54
|
+
*/
|
|
55
|
+
export type SchemaValues<S extends SchemaDefinition> = {
|
|
56
|
+
[K in keyof S]: S[K] extends readonly [infer T extends Type, number] ? TypedArrayFor<T> : S[K] extends SchemaDefinition ? SchemaValues<S[K]> : number;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Derives the JS write types from a schema. Same as SchemaValues, except
|
|
60
|
+
* array fields also accept ArrayLike<number> for ergonomics (e.g. plain [1, 2, 3]),
|
|
61
|
+
* and nested schema fields accept partial values at every level.
|
|
62
|
+
*/
|
|
63
|
+
export type SchemaWriteValues<S extends SchemaDefinition> = {
|
|
64
|
+
[K in keyof S]: S[K] extends readonly [infer T extends Type, number] ? TypedArrayFor<T> | ArrayLike<number> : S[K] extends SchemaDefinition ? Partial<SchemaWriteValues<S[K]>> : number;
|
|
65
|
+
};
|
|
66
|
+
interface ScalarFieldLayout {
|
|
67
|
+
kind: "scalar";
|
|
68
|
+
type: Type;
|
|
69
|
+
offset: number;
|
|
70
|
+
}
|
|
71
|
+
interface ArrayFieldLayout {
|
|
72
|
+
kind: "array";
|
|
73
|
+
type: Type;
|
|
74
|
+
offset: number;
|
|
75
|
+
count: number;
|
|
76
|
+
}
|
|
77
|
+
interface NestedFieldLayout {
|
|
78
|
+
kind: "nested";
|
|
79
|
+
offset: number;
|
|
80
|
+
layout: Layout<SchemaDefinition>;
|
|
81
|
+
}
|
|
82
|
+
type FieldLayout = ScalarFieldLayout | ArrayFieldLayout | NestedFieldLayout;
|
|
83
|
+
export interface Layout<S extends SchemaDefinition> {
|
|
84
|
+
fields: {
|
|
85
|
+
[K in keyof S]: FieldLayout;
|
|
86
|
+
};
|
|
87
|
+
byteLength: number;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Walks a schema and computes the byte offset of each field, respecting natural
|
|
91
|
+
* alignment (each field aligned to its element size). Recurses into nested schemas.
|
|
92
|
+
* Called once at creation time.
|
|
93
|
+
*/
|
|
94
|
+
export declare function computeLayout<S extends SchemaDefinition>(schema: S): Layout<S>;
|
|
95
|
+
/**
|
|
96
|
+
* Reads all fields from a DataView into a plain object according to the layout.
|
|
97
|
+
* Scalar fields use a single DataView getter call. Array fields return a TypedArray
|
|
98
|
+
* view directly into the underlying buffer (no copy). Nested fields recurse.
|
|
99
|
+
*/
|
|
100
|
+
export declare function readSnapshot<S extends SchemaDefinition>(layout: Layout<S>, dataView: DataView, baseOffset?: number): SchemaValues<S>;
|
|
101
|
+
/**
|
|
102
|
+
* Writes a partial set of fields into a DataView according to the layout.
|
|
103
|
+
* Scalar fields use a single DataView setter call. Array fields iterate
|
|
104
|
+
* and write each element individually. Nested fields recurse.
|
|
105
|
+
*/
|
|
106
|
+
export declare function writeFields<S extends SchemaDefinition>(layout: Layout<S>, dataView: DataView, values: Partial<SchemaWriteValues<S>>, baseOffset?: number): void;
|
|
107
|
+
export {};
|
|
108
|
+
//# sourceMappingURL=schema.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../schema.ts"],"names":[],"mappings":"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"}
|
package/dist/schema.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema-driven type system for SharedObjects.
|
|
3
|
+
*
|
|
4
|
+
* A schema is a plain object mapping field names to types. Each field is either
|
|
5
|
+
* a scalar (Type.Float32) or a fixed-length array ([Type.Float32, 3]).
|
|
6
|
+
*
|
|
7
|
+
* From a schema definition, this module derives:
|
|
8
|
+
* - A memory layout (byte offsets and total size), computed once at creation
|
|
9
|
+
* - TypeScript types for reading (SchemaValues) and writing (SchemaWriteValues)
|
|
10
|
+
* - Functions to read/write fields directly via DataView, with no serialization
|
|
11
|
+
*/
|
|
12
|
+
export var Type;
|
|
13
|
+
(function (Type) {
|
|
14
|
+
Type[Type["Int8"] = 1] = "Int8";
|
|
15
|
+
Type[Type["Uint8"] = 2] = "Uint8";
|
|
16
|
+
Type[Type["Int16"] = 3] = "Int16";
|
|
17
|
+
Type[Type["Uint16"] = 4] = "Uint16";
|
|
18
|
+
Type[Type["Int32"] = 5] = "Int32";
|
|
19
|
+
Type[Type["Uint32"] = 6] = "Uint32";
|
|
20
|
+
Type[Type["Float32"] = 7] = "Float32";
|
|
21
|
+
Type[Type["Float64"] = 8] = "Float64";
|
|
22
|
+
})(Type || (Type = {}));
|
|
23
|
+
const TYPE_SIZE = {
|
|
24
|
+
[Type.Int8]: 1,
|
|
25
|
+
[Type.Uint8]: 1,
|
|
26
|
+
[Type.Int16]: 2,
|
|
27
|
+
[Type.Uint16]: 2,
|
|
28
|
+
[Type.Int32]: 4,
|
|
29
|
+
[Type.Uint32]: 4,
|
|
30
|
+
[Type.Float32]: 4,
|
|
31
|
+
[Type.Float64]: 8,
|
|
32
|
+
};
|
|
33
|
+
const TYPE_GETTER = {
|
|
34
|
+
[Type.Int8]: "getInt8",
|
|
35
|
+
[Type.Uint8]: "getUint8",
|
|
36
|
+
[Type.Int16]: "getInt16",
|
|
37
|
+
[Type.Uint16]: "getUint16",
|
|
38
|
+
[Type.Int32]: "getInt32",
|
|
39
|
+
[Type.Uint32]: "getUint32",
|
|
40
|
+
[Type.Float32]: "getFloat32",
|
|
41
|
+
[Type.Float64]: "getFloat64",
|
|
42
|
+
};
|
|
43
|
+
const TYPE_SETTER = {
|
|
44
|
+
[Type.Int8]: "setInt8",
|
|
45
|
+
[Type.Uint8]: "setUint8",
|
|
46
|
+
[Type.Int16]: "setInt16",
|
|
47
|
+
[Type.Uint16]: "setUint16",
|
|
48
|
+
[Type.Int32]: "setInt32",
|
|
49
|
+
[Type.Uint32]: "setUint32",
|
|
50
|
+
[Type.Float32]: "setFloat32",
|
|
51
|
+
[Type.Float64]: "setFloat64",
|
|
52
|
+
};
|
|
53
|
+
const TYPE_ARRAY_CTOR = {
|
|
54
|
+
[Type.Int8]: Int8Array,
|
|
55
|
+
[Type.Uint8]: Uint8Array,
|
|
56
|
+
[Type.Int16]: Int16Array,
|
|
57
|
+
[Type.Uint16]: Uint16Array,
|
|
58
|
+
[Type.Int32]: Int32Array,
|
|
59
|
+
[Type.Uint32]: Uint32Array,
|
|
60
|
+
[Type.Float32]: Float32Array,
|
|
61
|
+
[Type.Float64]: Float64Array,
|
|
62
|
+
};
|
|
63
|
+
function isNestedSchema(raw) {
|
|
64
|
+
return typeof raw === "object" && !Array.isArray(raw);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Returns the maximum element alignment required by any field in a schema.
|
|
68
|
+
*/
|
|
69
|
+
function maxAlignment(schema) {
|
|
70
|
+
let align = 1;
|
|
71
|
+
for (const raw of Object.values(schema)) {
|
|
72
|
+
if (isNestedSchema(raw))
|
|
73
|
+
align = Math.max(align, maxAlignment(raw));
|
|
74
|
+
else {
|
|
75
|
+
const type = typeof raw === "number" ? raw : raw[0];
|
|
76
|
+
align = Math.max(align, TYPE_SIZE[type]);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return align;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Walks a schema and computes the byte offset of each field, respecting natural
|
|
83
|
+
* alignment (each field aligned to its element size). Recurses into nested schemas.
|
|
84
|
+
* Called once at creation time.
|
|
85
|
+
*/
|
|
86
|
+
export function computeLayout(schema) {
|
|
87
|
+
let offset = 0;
|
|
88
|
+
const fields = {};
|
|
89
|
+
for (const key of Object.keys(schema)) {
|
|
90
|
+
const raw = schema[key];
|
|
91
|
+
if (isNestedSchema(raw)) {
|
|
92
|
+
const nested = computeLayout(raw);
|
|
93
|
+
const align = maxAlignment(raw);
|
|
94
|
+
offset = Math.ceil(offset / align) * align;
|
|
95
|
+
fields[key] = { kind: "nested", offset, layout: nested };
|
|
96
|
+
offset += nested.byteLength;
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
const type = typeof raw === "number" ? raw : raw[0];
|
|
100
|
+
const count = typeof raw === "number" ? 1 : raw[1];
|
|
101
|
+
const elemSize = TYPE_SIZE[type];
|
|
102
|
+
offset = Math.ceil(offset / elemSize) * elemSize;
|
|
103
|
+
if (count === 1)
|
|
104
|
+
fields[key] = { kind: "scalar", type, offset };
|
|
105
|
+
else
|
|
106
|
+
fields[key] = { kind: "array", type, offset, count };
|
|
107
|
+
offset += elemSize * count;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return { fields, byteLength: offset };
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Reads all fields from a DataView into a plain object according to the layout.
|
|
114
|
+
* Scalar fields use a single DataView getter call. Array fields return a TypedArray
|
|
115
|
+
* view directly into the underlying buffer (no copy). Nested fields recurse.
|
|
116
|
+
*/
|
|
117
|
+
export function readSnapshot(layout, dataView, baseOffset = 0) {
|
|
118
|
+
const out = {};
|
|
119
|
+
for (const key of Object.keys(layout.fields)) {
|
|
120
|
+
const field = layout.fields[key];
|
|
121
|
+
const abs = baseOffset + field.offset;
|
|
122
|
+
switch (field.kind) {
|
|
123
|
+
case "scalar": {
|
|
124
|
+
const getter = TYPE_GETTER[field.type];
|
|
125
|
+
out[key] = dataView[getter].call(dataView, abs, true);
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
case "array": {
|
|
129
|
+
const Ctor = TYPE_ARRAY_CTOR[field.type];
|
|
130
|
+
out[key] = new Ctor(dataView.buffer, dataView.byteOffset + abs, field.count);
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
case "nested": {
|
|
134
|
+
out[key] = readSnapshot(field.layout, dataView, abs);
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Writes a partial set of fields into a DataView according to the layout.
|
|
143
|
+
* Scalar fields use a single DataView setter call. Array fields iterate
|
|
144
|
+
* and write each element individually. Nested fields recurse.
|
|
145
|
+
*/
|
|
146
|
+
export function writeFields(layout, dataView, values, baseOffset = 0) {
|
|
147
|
+
for (const key of Object.keys(values)) {
|
|
148
|
+
const field = layout.fields[key];
|
|
149
|
+
const val = values[key];
|
|
150
|
+
const abs = baseOffset + field.offset;
|
|
151
|
+
switch (field.kind) {
|
|
152
|
+
case "scalar": {
|
|
153
|
+
const setter = TYPE_SETTER[field.type];
|
|
154
|
+
dataView[setter].call(dataView, abs, val, true);
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
case "array": {
|
|
158
|
+
const src = val;
|
|
159
|
+
const setter = TYPE_SETTER[field.type];
|
|
160
|
+
const elemSize = TYPE_SIZE[field.type];
|
|
161
|
+
for (let i = 0; i < field.count; i++) {
|
|
162
|
+
dataView[setter].call(dataView, abs + i * elemSize, src[i], true);
|
|
163
|
+
}
|
|
164
|
+
break;
|
|
165
|
+
}
|
|
166
|
+
case "nested": {
|
|
167
|
+
writeFields(field.layout, dataView, val, abs);
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SharedObject: synchronized access to a SharedArrayBuffer across threads.
|
|
3
|
+
*
|
|
4
|
+
* Provides a triple-buffered ring of data slots with a sequence lock for lock-free
|
|
5
|
+
* reads and a ticket-lock for serialized writes. TypedSharedObject wraps a
|
|
6
|
+
* SharedObject with a schema to provide typed read/write access.
|
|
7
|
+
*/
|
|
8
|
+
import { type Layout, type SchemaDefinition, type SchemaValues, type SchemaWriteValues } from "./schema.js";
|
|
9
|
+
export interface SharedObjectConfig {
|
|
10
|
+
byteLength: number;
|
|
11
|
+
}
|
|
12
|
+
export interface SharedObjectDescriptor {
|
|
13
|
+
id: string;
|
|
14
|
+
byteLength: number;
|
|
15
|
+
slotCount: number;
|
|
16
|
+
dataSab: SharedArrayBuffer;
|
|
17
|
+
controlSab: SharedArrayBuffer;
|
|
18
|
+
}
|
|
19
|
+
export interface SharedObjectWriteContext {
|
|
20
|
+
bytes: Uint8Array;
|
|
21
|
+
dataView: DataView;
|
|
22
|
+
seq: number;
|
|
23
|
+
}
|
|
24
|
+
export type SharedObjectReadSnapshot = SharedObjectWriteContext;
|
|
25
|
+
export type SharedObjectWriteCallback<TReturn = void> = (ctx: SharedObjectWriteContext) => TReturn | Promise<TReturn>;
|
|
26
|
+
export declare class SharedObject {
|
|
27
|
+
readonly id: string;
|
|
28
|
+
readonly byteLength: number;
|
|
29
|
+
readonly slotCount: number;
|
|
30
|
+
readonly dataSab: SharedArrayBuffer;
|
|
31
|
+
readonly controlSab: SharedArrayBuffer;
|
|
32
|
+
private readonly control;
|
|
33
|
+
private readonly notifyChannel;
|
|
34
|
+
constructor(descriptor: SharedObjectDescriptor);
|
|
35
|
+
static create(id: string, config: SharedObjectConfig): SharedObject;
|
|
36
|
+
static fromDescriptor(descriptor: SharedObjectDescriptor): SharedObject;
|
|
37
|
+
descriptor(): SharedObjectDescriptor;
|
|
38
|
+
requestWrite<TReturn>(cb: SharedObjectWriteCallback<TReturn>): Promise<TReturn>;
|
|
39
|
+
private writeUnlocked;
|
|
40
|
+
subscribe(callback: () => void): () => void;
|
|
41
|
+
readLatest(): SharedObjectReadSnapshot | null;
|
|
42
|
+
private waitForTurn;
|
|
43
|
+
private releaseWriteLock;
|
|
44
|
+
}
|
|
45
|
+
export declare class TypedSharedObject<S extends SchemaDefinition> {
|
|
46
|
+
readonly inner: SharedObject;
|
|
47
|
+
readonly layout: Layout<S>;
|
|
48
|
+
constructor(inner: SharedObject, schema: S);
|
|
49
|
+
write(values: Partial<SchemaWriteValues<S>>): Promise<void>;
|
|
50
|
+
read(): (SchemaValues<S> & {
|
|
51
|
+
seq: number;
|
|
52
|
+
}) | null;
|
|
53
|
+
subscribe(callback: () => void): () => void;
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=shared-object.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shared-object.d.ts","sourceRoot":"","sources":["../shared-object.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAIL,KAAK,MAAM,EACX,KAAK,gBAAgB,EACrB,KAAK,YAAY,EACjB,KAAK,iBAAiB,EACvB,MAAM,aAAa,CAAC;AAarB,MAAM,WAAW,kBAAkB;IACjC,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,sBAAsB;IACrC,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,iBAAiB,CAAC;IAC3B,UAAU,EAAE,iBAAiB,CAAC;CAC/B;AAED,MAAM,WAAW,wBAAwB;IACvC,KAAK,EAAE,UAAU,CAAC;IAClB,QAAQ,EAAE,QAAQ,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,MAAM,wBAAwB,GAAG,wBAAwB,CAAC;AAChE,MAAM,MAAM,yBAAyB,CAAC,OAAO,GAAG,IAAI,IAAI,CACtD,GAAG,EAAE,wBAAwB,KAC1B,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AAkBhC,qBAAa,YAAY;IACvB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,OAAO,EAAE,iBAAiB,CAAC;IACpC,QAAQ,CAAC,UAAU,EAAE,iBAAiB,CAAC;IACvC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAa;IACrC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAmB;gBAErC,UAAU,EAAE,sBAAsB;IAU9C,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,kBAAkB,GAAG,YAAY;IAuBnE,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,sBAAsB,GAAG,YAAY;IAIvE,UAAU,IAAI,sBAAsB;IAU9B,YAAY,CAAC,OAAO,EAAE,EAAE,EAAE,yBAAyB,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;YAavE,aAAa;IAiB3B,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI;IAM3C,UAAU,IAAI,wBAAwB,GAAG,IAAI;YAe/B,WAAW;IAiBzB,OAAO,CAAC,gBAAgB;CAUzB;AAED,qBAAa,iBAAiB,CAAC,CAAC,SAAS,gBAAgB;IACvD,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;gBAEf,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC;IAKpC,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAIjE,IAAI,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,GAAG;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC,GAAG,IAAI;IAMlD,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI;CAG5C"}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SharedObject: synchronized access to a SharedArrayBuffer across threads.
|
|
3
|
+
*
|
|
4
|
+
* Provides a triple-buffered ring of data slots with a sequence lock for lock-free
|
|
5
|
+
* reads and a ticket-lock for serialized writes. TypedSharedObject wraps a
|
|
6
|
+
* SharedObject with a schema to provide typed read/write access.
|
|
7
|
+
*/
|
|
8
|
+
import { computeLayout, readSnapshot, writeFields, } from "./schema.js";
|
|
9
|
+
const localThreadId = (crypto.getRandomValues(new Uint32Array(1))[0] & 0x7fffffff) || 1;
|
|
10
|
+
const CTRL_PUBLISHED_SLOT = 0;
|
|
11
|
+
const CTRL_SEQ = 1;
|
|
12
|
+
const CTRL_NEXT_TICKET = 2;
|
|
13
|
+
const CTRL_SERVING_TICKET = 3;
|
|
14
|
+
const CTRL_WRITE_OWNER_THREAD_ID = 4;
|
|
15
|
+
const CTRL_WORDS = 5;
|
|
16
|
+
const NO_OWNER_THREAD_ID = -1;
|
|
17
|
+
const atomicsWithWaitAsync = Atomics;
|
|
18
|
+
export class SharedObject {
|
|
19
|
+
id;
|
|
20
|
+
byteLength;
|
|
21
|
+
slotCount;
|
|
22
|
+
dataSab;
|
|
23
|
+
controlSab;
|
|
24
|
+
control;
|
|
25
|
+
notifyChannel;
|
|
26
|
+
constructor(descriptor) {
|
|
27
|
+
this.id = descriptor.id;
|
|
28
|
+
this.byteLength = descriptor.byteLength;
|
|
29
|
+
this.slotCount = descriptor.slotCount;
|
|
30
|
+
this.dataSab = descriptor.dataSab;
|
|
31
|
+
this.controlSab = descriptor.controlSab;
|
|
32
|
+
this.control = new Int32Array(this.controlSab);
|
|
33
|
+
this.notifyChannel = new BroadcastChannel(`shared-object:${this.id}`);
|
|
34
|
+
}
|
|
35
|
+
static create(id, config) {
|
|
36
|
+
const byteLength = config.byteLength;
|
|
37
|
+
const slotCount = 3;
|
|
38
|
+
if (!Number.isInteger(byteLength) || byteLength <= 0) {
|
|
39
|
+
throw new Error(`byteLength must be a positive integer, got ${byteLength}`);
|
|
40
|
+
}
|
|
41
|
+
const descriptor = {
|
|
42
|
+
id,
|
|
43
|
+
byteLength,
|
|
44
|
+
slotCount,
|
|
45
|
+
dataSab: new SharedArrayBuffer(slotCount * byteLength),
|
|
46
|
+
controlSab: new SharedArrayBuffer(CTRL_WORDS * Int32Array.BYTES_PER_ELEMENT),
|
|
47
|
+
};
|
|
48
|
+
const obj = new SharedObject(descriptor);
|
|
49
|
+
Atomics.store(obj.control, CTRL_PUBLISHED_SLOT, -1);
|
|
50
|
+
Atomics.store(obj.control, CTRL_SEQ, 0);
|
|
51
|
+
Atomics.store(obj.control, CTRL_NEXT_TICKET, 0);
|
|
52
|
+
Atomics.store(obj.control, CTRL_SERVING_TICKET, 0);
|
|
53
|
+
Atomics.store(obj.control, CTRL_WRITE_OWNER_THREAD_ID, NO_OWNER_THREAD_ID);
|
|
54
|
+
return obj;
|
|
55
|
+
}
|
|
56
|
+
static fromDescriptor(descriptor) {
|
|
57
|
+
return new SharedObject(descriptor);
|
|
58
|
+
}
|
|
59
|
+
descriptor() {
|
|
60
|
+
return {
|
|
61
|
+
id: this.id,
|
|
62
|
+
byteLength: this.byteLength,
|
|
63
|
+
slotCount: this.slotCount,
|
|
64
|
+
dataSab: this.dataSab,
|
|
65
|
+
controlSab: this.controlSab,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
async requestWrite(cb) {
|
|
69
|
+
if (Atomics.load(this.control, CTRL_WRITE_OWNER_THREAD_ID) === localThreadId) {
|
|
70
|
+
throw new Error(`Reentrant writes are not supported for shared object "${this.id}"`);
|
|
71
|
+
}
|
|
72
|
+
const ticket = Atomics.add(this.control, CTRL_NEXT_TICKET, 1);
|
|
73
|
+
await this.waitForTurn(ticket);
|
|
74
|
+
Atomics.store(this.control, CTRL_WRITE_OWNER_THREAD_ID, localThreadId);
|
|
75
|
+
try {
|
|
76
|
+
return await this.writeUnlocked(cb);
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
this.releaseWriteLock();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async writeUnlocked(cb) {
|
|
83
|
+
const nextSeq = (Atomics.load(this.control, CTRL_SEQ) + 1) >>> 0;
|
|
84
|
+
const slotIndex = nextSeq % this.slotCount;
|
|
85
|
+
const offset = slotIndex * this.byteLength;
|
|
86
|
+
const bytes = new Uint8Array(this.dataSab, offset, this.byteLength);
|
|
87
|
+
const dataView = new DataView(this.dataSab, offset, this.byteLength);
|
|
88
|
+
const result = await cb({ bytes, dataView, seq: nextSeq });
|
|
89
|
+
Atomics.store(this.control, CTRL_PUBLISHED_SLOT, slotIndex);
|
|
90
|
+
Atomics.store(this.control, CTRL_SEQ, nextSeq);
|
|
91
|
+
this.notifyChannel.postMessage(null);
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
subscribe(callback) {
|
|
95
|
+
const channel = new BroadcastChannel(`shared-object:${this.id}`);
|
|
96
|
+
channel.onmessage = callback;
|
|
97
|
+
return () => channel.close();
|
|
98
|
+
}
|
|
99
|
+
readLatest() {
|
|
100
|
+
for (let attempts = 0; attempts < 4; attempts += 1) {
|
|
101
|
+
const seq1 = Atomics.load(this.control, CTRL_SEQ);
|
|
102
|
+
const slotIndex = Atomics.load(this.control, CTRL_PUBLISHED_SLOT);
|
|
103
|
+
if (slotIndex < 0)
|
|
104
|
+
return null;
|
|
105
|
+
const offset = slotIndex * this.byteLength;
|
|
106
|
+
const bytes = new Uint8Array(this.dataSab, offset, this.byteLength);
|
|
107
|
+
const dataView = new DataView(this.dataSab, offset, this.byteLength);
|
|
108
|
+
const seq2 = Atomics.load(this.control, CTRL_SEQ);
|
|
109
|
+
if (seq1 === seq2)
|
|
110
|
+
return { seq: seq1 >>> 0, bytes, dataView };
|
|
111
|
+
}
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
async waitForTurn(ticket) {
|
|
115
|
+
for (;;) {
|
|
116
|
+
const servingTicket = Atomics.load(this.control, CTRL_SERVING_TICKET);
|
|
117
|
+
if (servingTicket === ticket)
|
|
118
|
+
return;
|
|
119
|
+
const waitAsync = atomicsWithWaitAsync.waitAsync;
|
|
120
|
+
if (typeof waitAsync === "function") {
|
|
121
|
+
const waitResult = waitAsync(this.control, CTRL_SERVING_TICKET, servingTicket);
|
|
122
|
+
if (typeof waitResult.value !== "string")
|
|
123
|
+
await waitResult.value;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
// Fallback path for runtimes without Atomics.waitAsync.
|
|
127
|
+
await new Promise((resolve) => setTimeout(resolve, 1));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
releaseWriteLock() {
|
|
131
|
+
const ownerThreadId = Atomics.load(this.control, CTRL_WRITE_OWNER_THREAD_ID);
|
|
132
|
+
if (ownerThreadId !== localThreadId) {
|
|
133
|
+
throw new Error(`Thread ${localThreadId} attempted to release write lock owned by ${ownerThreadId}`);
|
|
134
|
+
}
|
|
135
|
+
Atomics.store(this.control, CTRL_WRITE_OWNER_THREAD_ID, NO_OWNER_THREAD_ID);
|
|
136
|
+
Atomics.add(this.control, CTRL_SERVING_TICKET, 1);
|
|
137
|
+
Atomics.notify(this.control, CTRL_SERVING_TICKET, 1);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
export class TypedSharedObject {
|
|
141
|
+
inner;
|
|
142
|
+
layout;
|
|
143
|
+
constructor(inner, schema) {
|
|
144
|
+
this.inner = inner;
|
|
145
|
+
this.layout = computeLayout(schema);
|
|
146
|
+
}
|
|
147
|
+
async write(values) {
|
|
148
|
+
await this.inner.requestWrite(({ dataView }) => writeFields(this.layout, dataView, values));
|
|
149
|
+
}
|
|
150
|
+
read() {
|
|
151
|
+
const snap = this.inner.readLatest();
|
|
152
|
+
if (!snap)
|
|
153
|
+
return null;
|
|
154
|
+
return { ...readSnapshot(this.layout, snap.dataView), seq: snap.seq };
|
|
155
|
+
}
|
|
156
|
+
subscribe(callback) {
|
|
157
|
+
return this.inner.subscribe(callback);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SharedRuntime: orchestrates shared memory communication between host and workers.
|
|
3
|
+
*
|
|
4
|
+
* In host mode, callers attach worker endpoints and manage SharedObject creation/distribution.
|
|
5
|
+
* In worker mode, runtime receives SharedObject descriptors from the host and provides
|
|
6
|
+
* access to them.
|
|
7
|
+
*/
|
|
8
|
+
import { SharedObject, TypedSharedObject } from "./shared-object.js";
|
|
9
|
+
import type { SharedObjectConfig } from "./shared-object.js";
|
|
10
|
+
import { type SchemaDefinition } from "./schema.js";
|
|
11
|
+
import { type RuntimePeer } from "./runtime-peer.js";
|
|
12
|
+
type RuntimeMode = "host" | "worker";
|
|
13
|
+
export default class SharedRuntime {
|
|
14
|
+
private readonly mode;
|
|
15
|
+
private readonly port;
|
|
16
|
+
private readonly sharedObjects;
|
|
17
|
+
private readonly workers;
|
|
18
|
+
private workerSetupData;
|
|
19
|
+
constructor(mode: RuntimeMode, port?: RuntimePeer | null);
|
|
20
|
+
static host(): SharedRuntime;
|
|
21
|
+
static worker(endpoint?: unknown): Promise<SharedRuntime>;
|
|
22
|
+
attachWorker(name: string, endpoint: unknown, setupData?: unknown): Promise<void>;
|
|
23
|
+
createSharedObject(id: string, config: SharedObjectConfig): SharedObject;
|
|
24
|
+
createSharedObject<S extends SchemaDefinition>(id: string, schema: S): TypedSharedObject<S>;
|
|
25
|
+
openSharedObject(id: string): SharedObject;
|
|
26
|
+
openSharedObject<S extends SchemaDefinition>(id: string, schema: S): TypedSharedObject<S>;
|
|
27
|
+
getWorkerSetupData<TSetup = unknown>(): TSetup | undefined;
|
|
28
|
+
private waitForInit;
|
|
29
|
+
}
|
|
30
|
+
export {};
|
|
31
|
+
//# sourceMappingURL=shared-runtime.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shared-runtime.d.ts","sourceRoot":"","sources":["../shared-runtime.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,KAAK,EAAE,kBAAkB,EAA0B,MAAM,oBAAoB,CAAC;AACrF,OAAO,EAAiB,KAAK,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAA8C,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEjG,KAAK,WAAW,GAAG,MAAM,GAAG,QAAQ,CAAC;AA2CrC,MAAM,CAAC,OAAO,OAAO,aAAa;IAChC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAc;IACnC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAqB;IAC1C,OAAO,CAAC,QAAQ,CAAC,aAAa,CAA4B;IAC1D,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA2B;IACnD,OAAO,CAAC,eAAe,CAAU;gBAErB,IAAI,EAAE,WAAW,EAAE,IAAI,GAAE,WAAW,GAAG,IAAW;IAQ9D,MAAM,CAAC,IAAI,IAAI,aAAa;WAIf,MAAM,CAAC,QAAQ,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,aAAa,CAAC;IAOzD,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAuBvF,kBAAkB,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,kBAAkB,GAAG,YAAY;IACxE,kBAAkB,CAAC,CAAC,SAAS,gBAAgB,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC;IAsB3F,gBAAgB,CAAC,EAAE,EAAE,MAAM,GAAG,YAAY;IAC1C,gBAAgB,CAAC,CAAC,SAAS,gBAAgB,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC;IAUzF,kBAAkB,CAAC,MAAM,GAAG,OAAO,KAAK,MAAM,GAAG,SAAS;YAI5C,WAAW;CAyB1B"}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SharedRuntime: orchestrates shared memory communication between host and workers.
|
|
3
|
+
*
|
|
4
|
+
* In host mode, callers attach worker endpoints and manage SharedObject creation/distribution.
|
|
5
|
+
* In worker mode, runtime receives SharedObject descriptors from the host and provides
|
|
6
|
+
* access to them.
|
|
7
|
+
*/
|
|
8
|
+
import { SharedObject, TypedSharedObject } from "./shared-object.js";
|
|
9
|
+
import { computeLayout } from "./schema.js";
|
|
10
|
+
import { createRuntimePeer, detectCurrentWorkerPeer } from "./runtime-peer.js";
|
|
11
|
+
function isObject(value) {
|
|
12
|
+
return typeof value === "object" && value !== null;
|
|
13
|
+
}
|
|
14
|
+
function isReadyMessage(msg) {
|
|
15
|
+
return isObject(msg) && msg.type === "ready";
|
|
16
|
+
}
|
|
17
|
+
function isInitMessage(msg) {
|
|
18
|
+
return isObject(msg) && msg.type === "init" && Array.isArray(msg.sharedObjects);
|
|
19
|
+
}
|
|
20
|
+
function isSharedObjectCreatedMessage(msg) {
|
|
21
|
+
return isObject(msg) && msg.type === "shared-object-created" && isObject(msg.sharedObject);
|
|
22
|
+
}
|
|
23
|
+
function send(port, msg) {
|
|
24
|
+
port.postMessage(msg);
|
|
25
|
+
}
|
|
26
|
+
export default class SharedRuntime {
|
|
27
|
+
mode;
|
|
28
|
+
port;
|
|
29
|
+
sharedObjects;
|
|
30
|
+
workers;
|
|
31
|
+
workerSetupData;
|
|
32
|
+
constructor(mode, port = null) {
|
|
33
|
+
this.mode = mode;
|
|
34
|
+
this.port = port;
|
|
35
|
+
this.sharedObjects = new Map();
|
|
36
|
+
this.workers = new Map();
|
|
37
|
+
this.workerSetupData = undefined;
|
|
38
|
+
}
|
|
39
|
+
static host() {
|
|
40
|
+
return new SharedRuntime("host");
|
|
41
|
+
}
|
|
42
|
+
static async worker(endpoint) {
|
|
43
|
+
const port = endpoint ? createRuntimePeer(endpoint) : await detectCurrentWorkerPeer();
|
|
44
|
+
const runtime = new SharedRuntime("worker", port);
|
|
45
|
+
await runtime.waitForInit();
|
|
46
|
+
return runtime;
|
|
47
|
+
}
|
|
48
|
+
async attachWorker(name, endpoint, setupData) {
|
|
49
|
+
if (this.mode !== "host")
|
|
50
|
+
throw new Error("attachWorker is only available on host runtime");
|
|
51
|
+
if (this.workers.has(name))
|
|
52
|
+
throw new Error(`Worker "${name}" already attached`);
|
|
53
|
+
const peer = createRuntimePeer(endpoint);
|
|
54
|
+
const ready = new Promise((resolve) => {
|
|
55
|
+
const stop = peer.addMessageListener((msg) => {
|
|
56
|
+
if (!isReadyMessage(msg))
|
|
57
|
+
return;
|
|
58
|
+
stop();
|
|
59
|
+
resolve();
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
this.workers.set(name, peer);
|
|
63
|
+
send(peer, {
|
|
64
|
+
type: "init",
|
|
65
|
+
sharedObjects: [...this.sharedObjects.values()].map((obj) => obj.descriptor()),
|
|
66
|
+
setupData,
|
|
67
|
+
});
|
|
68
|
+
await ready;
|
|
69
|
+
}
|
|
70
|
+
createSharedObject(id, configOrSchema) {
|
|
71
|
+
if (this.sharedObjects.has(id)) {
|
|
72
|
+
throw new Error(`Shared object "${id}" already exists`);
|
|
73
|
+
}
|
|
74
|
+
const isConfig = "byteLength" in configOrSchema && typeof configOrSchema.byteLength === "number";
|
|
75
|
+
const config = isConfig
|
|
76
|
+
? configOrSchema
|
|
77
|
+
: { byteLength: computeLayout(configOrSchema).byteLength };
|
|
78
|
+
const obj = SharedObject.create(id, config);
|
|
79
|
+
this.sharedObjects.set(id, obj);
|
|
80
|
+
const descriptor = obj.descriptor();
|
|
81
|
+
for (const peer of this.workers.values()) {
|
|
82
|
+
send(peer, { type: "shared-object-created", sharedObject: descriptor });
|
|
83
|
+
}
|
|
84
|
+
return isConfig ? obj : new TypedSharedObject(obj, configOrSchema);
|
|
85
|
+
}
|
|
86
|
+
openSharedObject(id, schema) {
|
|
87
|
+
const obj = this.sharedObjects.get(id);
|
|
88
|
+
if (!obj)
|
|
89
|
+
throw new Error(`Shared object "${id}" not found`);
|
|
90
|
+
return schema ? new TypedSharedObject(obj, schema) : obj;
|
|
91
|
+
}
|
|
92
|
+
getWorkerSetupData() {
|
|
93
|
+
return this.workerSetupData;
|
|
94
|
+
}
|
|
95
|
+
async waitForInit() {
|
|
96
|
+
const port = this.port;
|
|
97
|
+
if (!port)
|
|
98
|
+
throw new Error("Worker runtime has no message port");
|
|
99
|
+
await new Promise((resolve) => {
|
|
100
|
+
const stop = port.addMessageListener((msg) => {
|
|
101
|
+
if (!isInitMessage(msg))
|
|
102
|
+
return;
|
|
103
|
+
for (const descriptor of msg.sharedObjects) {
|
|
104
|
+
this.sharedObjects.set(descriptor.id, SharedObject.fromDescriptor(descriptor));
|
|
105
|
+
}
|
|
106
|
+
this.workerSetupData = msg.setupData;
|
|
107
|
+
send(port, { type: "ready" });
|
|
108
|
+
stop();
|
|
109
|
+
resolve();
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
port.addMessageListener((msg) => {
|
|
113
|
+
if (!isSharedObjectCreatedMessage(msg))
|
|
114
|
+
return;
|
|
115
|
+
const descriptor = msg.sharedObject;
|
|
116
|
+
this.sharedObjects.set(descriptor.id, SharedObject.fromDescriptor(descriptor));
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@kargjonas/sabus",
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"access": "public"
|
|
6
|
+
},
|
|
7
|
+
"description": "Minimal SharedArrayBuffer worker bus for low-overhead cross-worker data sharing.",
|
|
8
|
+
"license": "Apache-2.0",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/KargJonas/sabus.git"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/KargJonas/sabus/issues"
|
|
15
|
+
},
|
|
16
|
+
"homepage": "https://github.com/KargJonas/sabus#readme",
|
|
17
|
+
"type": "module",
|
|
18
|
+
"main": "./dist/index.js",
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"import": "./dist/index.js"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"dist",
|
|
28
|
+
"README.md",
|
|
29
|
+
"LICENSE"
|
|
30
|
+
],
|
|
31
|
+
"keywords": [
|
|
32
|
+
"sharedarraybuffer",
|
|
33
|
+
"worker",
|
|
34
|
+
"atomics",
|
|
35
|
+
"shared-memory"
|
|
36
|
+
],
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=18"
|
|
39
|
+
},
|
|
40
|
+
"sideEffects": false,
|
|
41
|
+
"scripts": {
|
|
42
|
+
"clean": "rm -rf dist test-dist",
|
|
43
|
+
"build": "npm run clean && tsc -p tsconfig.json",
|
|
44
|
+
"build:examples": "vite build",
|
|
45
|
+
"dev": "vite --host 0.0.0.0 --port 3000 --strictPort",
|
|
46
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
47
|
+
"test:build": "tsc -p tsconfig.test.json",
|
|
48
|
+
"test": "npm run test:build && node --test test/*.test.mjs",
|
|
49
|
+
"prepack": "npm run typecheck && npm test && npm run build"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"typescript": "^5.4.5",
|
|
53
|
+
"vite": "^7.1.5"
|
|
54
|
+
}
|
|
55
|
+
}
|