@beetlebug/ztcl 0.0.0-stage → 1.0.0-beta.1

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.
@@ -0,0 +1,20 @@
1
+ simdjson
2
+
3
+ The JSON parser of ztcl (src/json/) implements the simdjson algorithm
4
+ in Zig. simdjson is at https://github.com/simdjson/simdjson. Its license
5
+ is the Apache License 2.0 or the MIT license, at the choice of the user.
6
+
7
+ ztcl copies no code, no lookup table, and no constant set from
8
+ simdjson. The Zig code is new, written from the descriptions of the
9
+ method in these papers:
10
+
11
+ - Geoff Langdale and Daniel Lemire, "Parsing Gigabytes of JSON per
12
+ Second", The VLDB Journal 28 (2019).
13
+ - John Keiser and Daniel Lemire, "Validating UTF-8 In Less Than One
14
+ Instruction Per Byte", Software: Practice and Experience 51 (2021).
15
+ - Daniel Lemire, "Number Parsing at a Gigabyte per Second", Software:
16
+ Practice and Experience 51 (2021). ztcl uses the Eisel-Lemire method
17
+ through std.fmt.parseFloat of the Zig standard library.
18
+
19
+ docs/references/stdlib.md says what each part of src/json/ takes from
20
+ each source.
@@ -0,0 +1,40 @@
1
+ This software is copyrighted by the Regents of the University of
2
+ California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
3
+ Corporation and other parties. The following terms apply to all files
4
+ associated with the software unless explicitly disclaimed in
5
+ individual files.
6
+
7
+ The authors hereby grant permission to use, copy, modify, distribute,
8
+ and license this software and its documentation for any purpose, provided
9
+ that existing copyright notices are retained in all copies and that this
10
+ notice is included verbatim in any distributions. No written agreement,
11
+ license, or royalty fee is required for any of the authorized uses.
12
+ Modifications to this software may be copyrighted by their authors
13
+ and need not follow the licensing terms described here, provided that
14
+ the new terms are clearly indicated on the first page of each file where
15
+ they apply.
16
+
17
+ IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
18
+ FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
19
+ ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
20
+ DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
21
+ POSSIBILITY OF SUCH DAMAGE.
22
+
23
+ THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
24
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
26
+ IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
27
+ NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
28
+ MODIFICATIONS.
29
+
30
+ GOVERNMENT USE: If you are acquiring this software on behalf of the
31
+ U.S. government, the Government shall have only "Restricted Rights"
32
+ in the software and related documentation as defined in the Federal
33
+ Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
34
+ are acquiring the software on behalf of the Department of Defense, the
35
+ software shall be classified as "Commercial Computer Software" and the
36
+ Government shall have only "Restricted Rights" as defined in Clause
37
+ 252.227-7014 (b) (3) of DFARs. Notwithstanding the foregoing, the
38
+ authors grant the U.S. Government and others acting in its behalf
39
+ permission to use and distribute the software in accordance with the
40
+ terms specified in this license.
@@ -0,0 +1,39 @@
1
+ UNICODE LICENSE V3
2
+
3
+ COPYRIGHT AND PERMISSION NOTICE
4
+
5
+ Copyright © 1991-2026 Unicode, Inc.
6
+
7
+ NOTICE TO USER: Carefully read the following legal agreement. BY
8
+ DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
9
+ SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
10
+ TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
11
+ DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a
14
+ copy of data files and any associated documentation (the "Data Files") or
15
+ software and any associated documentation (the "Software") to deal in the
16
+ Data Files or Software without restriction, including without limitation
17
+ the rights to use, copy, modify, merge, publish, distribute, and/or sell
18
+ copies of the Data Files or Software, and to permit persons to whom the
19
+ Data Files or Software are furnished to do so, provided that either (a)
20
+ this copyright and permission notice appear with all copies of the Data
21
+ Files or Software, or (b) this copyright and permission notice appear in
22
+ associated Documentation.
23
+
24
+ THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
25
+ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
27
+ THIRD PARTY RIGHTS.
28
+
29
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
30
+ BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
31
+ OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
32
+ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
33
+ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
34
+ FILES OR SOFTWARE.
35
+
36
+ Except as contained in this notice, the name of a copyright holder shall
37
+ not be used in advertising or otherwise to promote the sale, use or other
38
+ dealings in these Data Files or Software without prior written
39
+ authorization of the copyright holder.
@@ -0,0 +1,30 @@
1
+ # uucode license
2
+
3
+ MIT License
4
+
5
+ Copyright (c) 2026 Jacob Sandlund
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
8
+ this software and associated documentation files (the "Software"), to deal in
9
+ the Software without restriction, including without limitation the rights to
10
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
11
+ of the Software, and to permit persons to whom the Software is furnished to do
12
+ so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
24
+
25
+ ## Other licenses
26
+
27
+ See [./licenses](./licenses) for licenses of code being used in the repo:
28
+
29
+ * [LICENSE_Bjoern_Hoehrmann](./licenses/LICENSE_Bjoern_Hoehrmann)
30
+ * [LICENSE_unicode](./licenses/LICENSE_unicode)
@@ -0,0 +1,8 @@
1
+ Copyright © 2019-2024 the Contributors to the WASI Specification, published
2
+ by the [WebAssembly Community Group][cg] under the
3
+ [W3C Community Contributor License Agreement (CLA)][cla]. A human-readable
4
+ [summary][summary] is available.
5
+
6
+ [cg]: https://www.w3.org/community/webassembly/
7
+ [cla]: https://www.w3.org/community/about/agreements/cla/
8
+ [summary]: https://www.w3.org/community/about/agreements/cla-deed/
@@ -0,0 +1,21 @@
1
+ The MIT License (Expat)
2
+
3
+ Copyright (c) Zig 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
13
+ all 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
21
+ THE SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@beetlebug/ztcl",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0-beta.1",
4
+ "description": "A Tcl interpreter in WebAssembly, with a compute limit and a memory limit for untrusted scripts",
5
+ "license": "BSD-2-Clause",
6
+ "author": "The ztcl authors <opensource@beetlebug.org>",
7
+ "homepage": "https://beetlebug.org/ztcl/",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/beetlebugorg/ztcl.git"
11
+ },
12
+ "bugs": "https://github.com/beetlebugorg/ztcl/issues",
13
+ "keywords": [
14
+ "tcl",
15
+ "interpreter",
16
+ "webassembly",
17
+ "wasm",
18
+ "sandbox",
19
+ "scripting"
20
+ ],
21
+ "type": "module",
22
+ "main": "./ztcl.mjs",
23
+ "types": "./ztcl.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./ztcl.d.ts",
27
+ "default": "./ztcl.mjs"
28
+ },
29
+ "./worker": {
30
+ "types": "./ztcl-worker.d.ts",
31
+ "default": "./ztcl-worker.mjs"
32
+ },
33
+ "./threads": {
34
+ "types": "./ztcl-threads.d.ts",
35
+ "default": "./ztcl-threads.mjs"
36
+ },
37
+ "./ztcl.wasm": "./ztcl.wasm",
38
+ "./ztcl-threads.wasm": "./ztcl-threads.wasm",
39
+ "./ztcl-async.wasm": "./ztcl-async.wasm",
40
+ "./package.json": "./package.json"
41
+ },
42
+ "files": [
43
+ "ztcl.mjs",
44
+ "ztcl-worker.mjs",
45
+ "ztcl.wasm",
46
+ "ztcl.d.ts",
47
+ "ztcl-worker.d.ts",
48
+ "ztcl-threads.mjs",
49
+ "ztcl-thread-worker.mjs",
50
+ "ztcl-threads.wasm",
51
+ "ztcl-async.wasm",
52
+ "ztcl-threads.d.ts",
53
+ "NOTICE",
54
+ "licenses/"
55
+ ],
56
+ "sideEffects": [
57
+ "./ztcl-worker.mjs",
58
+ "./ztcl-thread-worker.mjs"
59
+ ],
60
+ "engines": {
61
+ "node": ">=22.3"
62
+ }
63
+ }
Binary file
@@ -0,0 +1,204 @@
1
+ // The worker of web/ztcl-threads.mjs. One worker runs one ztcl thread:
2
+ // the main interpreter or a thread of a script.
3
+ //
4
+ // The build with one shared memory (ztcl-threads.wasm): each worker
5
+ // makes an instance of the module on the shared memory of the host. A
6
+ // thread worker calls ztcl_thread_start, which runs the whole thread.
7
+ // The waits of the thread are Atomics waits on the shared memory.
8
+ //
9
+ // The build with a memory in each worker (ztcl-async.wasm): each worker
10
+ // has its own memory. A message is a script, and a reply is the result
11
+ // as bytes. The host routes them with postMessage. The worker runs one
12
+ // message at a time, between the turns of its event loop.
13
+ // SPDX-License-Identifier: BSD-2-Clause
14
+
15
+ const node = typeof WorkerGlobalScope === "undefined";
16
+ const port = node ? (await import("node:worker_threads")).parentPort : self;
17
+ const post = (m) => port.postMessage(m);
18
+ const listen = (f) => (node ? port.on("message", f) : (port.onmessage = ({ data }) => f(data)));
19
+
20
+ const encoder = new TextEncoder();
21
+ const decoder = new TextDecoder();
22
+ const NO_LIMIT = 0xffffffffffffffffn;
23
+ const now = () => performance.timeOrigin + performance.now();
24
+
25
+ let x = null; // the exports of the instance
26
+ let h = 0; // the interpreter of a main worker or of an async thread
27
+ let shared = false;
28
+
29
+ function bytesIn(bytes) {
30
+ const p = x.ztcl_alloc(bytes.length || 1);
31
+ if (!p) throw new Error("ztcl_alloc: out of memory");
32
+ new Uint8Array(x.memory.buffer, p, bytes.length).set(bytes);
33
+ return p;
34
+ }
35
+
36
+ function bytesOut(ptr, len) {
37
+ // A copy: TextDecoder does not read a SharedArrayBuffer. An empty
38
+ // slice can have an address outside the memory.
39
+ if (len === 0) return new Uint8Array(0);
40
+ return new Uint8Array(x.memory.buffer, ptr, len).slice();
41
+ }
42
+
43
+ function output() {
44
+ if (x.ztcl_output_take) x.ztcl_output_take(h);
45
+ const text = decoder.decode(bytesOut(x.ztcl_output_ptr(h), x.ztcl_output_len(h)));
46
+ x.ztcl_output_clear(h);
47
+ return text;
48
+ }
49
+
50
+ function evalScript(script, computeLimit) {
51
+ x.ztcl_set_compute_limit(h, computeLimit == null ? NO_LIMIT : BigInt(computeLimit));
52
+ const bytes = encoder.encode(script);
53
+ const p = bytesIn(bytes);
54
+ const rc = x.ztcl_eval(h, p, bytes.length);
55
+ x.ztcl_free(p, bytes.length || 1);
56
+ const result = decoder.decode(bytesOut(x.ztcl_result_ptr(h), x.ztcl_result_len(h)));
57
+ return { ok: rc === 0, result, output: output() };
58
+ }
59
+
60
+ // Sends the output of the threads while the main interpreter waits for
61
+ // an eval.
62
+ let poll = null;
63
+ function startPoll() {
64
+ poll = setInterval(() => {
65
+ const text = output();
66
+ if (text) post({ output: text });
67
+ }, 50);
68
+ }
69
+
70
+ function setup(init) {
71
+ const limits = init.limits ?? {};
72
+ const n = (v) => (v == null ? 0 : v);
73
+ const big = (v) => (v == null ? 0n : BigInt(v));
74
+ x.ztcl_set_thread_limits(h, n(limits.maxThreads), big(limits.computeLimit), n(limits.memLimit), big(limits.totalCompute), n(limits.totalMem), n(limits.maxQueue));
75
+ if (init.memLimit != null) x.ztcl_set_mem_limit(h, init.memLimit);
76
+ const rc = x.ztcl_allow(h, init.caps);
77
+ if (rc !== 0) throw new Error(rc === 2 ? "the build does not have one of these capabilities" : "ztcl_allow: out of memory");
78
+ }
79
+
80
+ // ---- The build with one shared memory ----
81
+
82
+ async function startShared(init) {
83
+ shared = true;
84
+ const imports = {
85
+ env: { memory: init.memory },
86
+ ztcl: {
87
+ now_ms: now,
88
+ thread_spawn: (arg) => {
89
+ post({ spawn: arg });
90
+ return 0;
91
+ },
92
+ },
93
+ };
94
+ const instance = await WebAssembly.instantiate(init.module, imports);
95
+ x = { ...instance.exports, memory: init.memory };
96
+ if (init.role === "thread") return runThread(init.arg);
97
+ h = x.ztcl_new();
98
+ setup(init);
99
+ startPoll();
100
+ }
101
+
102
+ // Runs one thread on the instance of this worker. After the return the
103
+ // host can give the worker the next thread, so a new thread needs no
104
+ // new worker and no new instance.
105
+ function runThread(arg) {
106
+ try {
107
+ x.ztcl_thread_start(arg);
108
+ } finally {
109
+ // The thread returned: its stack is free for `join`.
110
+ const done = new Int32Array(x.memory.buffer);
111
+ const i = x.ztcl_thread_done(arg) >> 2;
112
+ Atomics.store(done, i, 1);
113
+ Atomics.notify(done, i);
114
+ post({ idle: true });
115
+ }
116
+ }
117
+
118
+ // ---- The build with a memory in each worker ----
119
+
120
+ let self_id = 0;
121
+ let ending = false;
122
+
123
+ function asyncImports() {
124
+ const text = (p, len) => decoder.decode(bytesOut(p, len));
125
+ return {
126
+ ztcl: {
127
+ now_ms: now,
128
+ thread_create: (id, p, len) => post({ create: { id, script: text(p, len) } }),
129
+ thread_send: (id, p, len, token) => post({ send: { to: id, token, script: text(p, len) } }),
130
+ thread_end: () => {
131
+ ending = true;
132
+ },
133
+ },
134
+ };
135
+ }
136
+
137
+ async function startAsync(init) {
138
+ const instance = await WebAssembly.instantiate(init.module, asyncImports());
139
+ x = instance.exports;
140
+ h = x.ztcl_new();
141
+ self_id = init.id;
142
+ x.ztcl_web_init(h, init.id, init.role === "main" ? 1 : 0);
143
+ setup(init);
144
+ if (init.role === "thread") {
145
+ const r = evalScript(init.script, init.computeLimit);
146
+ if (r.output) post({ output: r.output });
147
+ if (!r.ok) post({ output: `Error from thread tid0x${init.id.toString(16)}\n${r.result}\n` });
148
+ if (ending || !x.ztcl_web_waiting(h)) end();
149
+ }
150
+ }
151
+
152
+ function end() {
153
+ post({ exit: true });
154
+ ending = true;
155
+ }
156
+
157
+ // A script from another thread. A token asks for a reply.
158
+ function deliver({ from, token, script }) {
159
+ const bytes = encoder.encode(script);
160
+ const p = bytesIn(bytes);
161
+ const code = x.ztcl_web_recv(h, from, token, p, bytes.length);
162
+ x.ztcl_free(p, bytes.length || 1);
163
+ const out = output();
164
+ if (out) post({ output: out });
165
+ if (token) post({ reply: { to: from, token, code, bytes: bytesOut(x.ztcl_web_msg_ptr(h), x.ztcl_web_msg_len(h)) } });
166
+ if (ending) end();
167
+ }
168
+
169
+ function reply({ token, code, bytes }) {
170
+ const p = bytesIn(bytes);
171
+ x.ztcl_web_reply(h, token, code, p, bytes.length);
172
+ x.ztcl_free(p, bytes.length || 1);
173
+ const out = output();
174
+ if (out) post({ output: out });
175
+ }
176
+
177
+ // ---- Messages of the host ----
178
+
179
+ let queue = Promise.resolve();
180
+ listen((data) => {
181
+ queue = queue.then(() => handle(data)).catch((e) => post({ fatal: String(e?.message ?? e) }));
182
+ });
183
+
184
+ async function handle(data) {
185
+ if (data.init) {
186
+ if (data.init.memory) await startShared(data.init);
187
+ else await startAsync(data.init);
188
+ post({ ready: true });
189
+ return;
190
+ }
191
+ if (data.run != null) return runThread(data.run);
192
+ if (ending) return;
193
+ if (data.deliver) return deliver(data.deliver);
194
+ if (data.reply) return reply(data.reply);
195
+ if (data.gone) return x.ztcl_web_gone(h, data.gone);
196
+ if (data.eval != null) {
197
+ try {
198
+ const r = evalScript(data.script, data.computeLimit);
199
+ post({ id: data.eval, ...r });
200
+ } catch (e) {
201
+ post({ id: data.eval, error: String(e?.message ?? e) });
202
+ }
203
+ }
204
+ }
@@ -0,0 +1,55 @@
1
+ // Types of ztcl-threads.mjs: ztcl with the capability `thread`.
2
+ // SPDX-License-Identifier: BSD-2-Clause
3
+
4
+ /** The capabilities that a thread interpreter can turn on. */
5
+ export type ThreadCapability = "thread" | "event" | "clock" | "package" | "interp";
6
+
7
+ /** The limits of the threads. A missing field keeps its default. */
8
+ export interface ThreadLimits {
9
+ maxThreads?: number;
10
+ computeLimit?: number;
11
+ memLimit?: number;
12
+ totalCompute?: number;
13
+ totalMem?: number;
14
+ maxQueue?: number;
15
+ }
16
+
17
+ export interface ThreadInterpOptions {
18
+ /** "shared" needs Node.js or a cross-origin isolated page. "auto" picks "shared" when it can. */
19
+ mode?: "auto" | "shared" | "async";
20
+ /** The URL or path of ztcl-threads.wasm. */
21
+ wasm?: string | URL;
22
+ /** The URL or path of ztcl-async.wasm. */
23
+ asyncWasm?: string | URL;
24
+ /** The default is ["thread"]. "event" works only in the shared mode. */
25
+ allow?: ThreadCapability[];
26
+ limits?: ThreadLimits;
27
+ /** The compute units of each eval of the main interpreter. */
28
+ computeLimit?: number | null;
29
+ memLimit?: number | null;
30
+ /** The text of `puts` of each thread. */
31
+ onOutput?: ((text: string) => void) | null;
32
+ }
33
+
34
+ export interface ThreadEvalResult {
35
+ ok: boolean;
36
+ result: string;
37
+ output: string;
38
+ }
39
+
40
+ /** True in Node.js and on a cross-origin isolated page. */
41
+ export function isolated(): boolean;
42
+ export function threadsURL(): URL;
43
+ export function asyncURL(): URL;
44
+
45
+ /** A main interpreter in a worker, with one worker for each thread. */
46
+ export class ThreadInterp {
47
+ static create(options?: ThreadInterpOptions): Promise<ThreadInterp>;
48
+ readonly mode: "shared" | "async";
49
+ computeLimit: number | null;
50
+ onOutput: ((text: string) => void) | null;
51
+ /** Runs a script in the main interpreter. */
52
+ eval(script: string): Promise<ThreadEvalResult>;
53
+ /** Stops each worker. */
54
+ close(): void;
55
+ }