tinyc-web 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/vfs-store.mjs ADDED
@@ -0,0 +1,180 @@
1
+ // Persistent storage layer for the virtual filesystem (index.mjs).
2
+ //
3
+ // A store persists file records { bytes, size, mtime } keyed by path
4
+ // and, once opened, exposes the persisted index (path -> { size,
5
+ // mtime }) without file contents. VirtualFS keeps only that index
6
+ // (plus a small content cache) in memory; the bytes live here.
7
+ //
8
+ // Two backends with identical semantics:
9
+ // IndexedDbFsStore one IndexedDB database per target, named
10
+ // "tinyc-web-fs-<target>", with a single object
11
+ // store "files" (key = path, value = the record).
12
+ // Used whenever the environment has IndexedDB
13
+ // (browsers and Web Workers both do).
14
+ // MemoryFsStore a plain Map. Used where IndexedDB does not
15
+ // exist (Node, tests) and as the fallback when an
16
+ // IndexedDB open fails (e.g. blocked in private
17
+ // browsing). Volatile: contents last as long as
18
+ // the store object.
19
+ //
20
+ // A custom store — or a factory producing one — can be injected per
21
+ // loadTinyc call (options.fsStore / options.storeFactory), which is
22
+ // how the test suite simulates IndexedDB semantics, including its
23
+ // asynchronous write queue, without a browser.
24
+
25
+ /** In-memory store: the no-IndexedDB fallback backend. */
26
+ export class MemoryFsStore {
27
+ constructor() {
28
+ this.kind = 'memory';
29
+ this._records = new Map();
30
+ this.index = new Map();
31
+ }
32
+
33
+ async open() {
34
+ this.index = new Map();
35
+ for (const [path, rec] of this._records) {
36
+ this.index.set(path, { size: rec.size, mtime: rec.mtime });
37
+ }
38
+ return this.index;
39
+ }
40
+
41
+ async get(path) {
42
+ const rec = this._records.get(path);
43
+ return rec ? { bytes: rec.bytes, size: rec.size, mtime: rec.mtime } : null;
44
+ }
45
+
46
+ async put(path, record) {
47
+ this._records.set(path, {
48
+ bytes: record.bytes,
49
+ size: record.size,
50
+ mtime: record.mtime,
51
+ });
52
+ }
53
+
54
+ async delete(path) {
55
+ this._records.delete(path);
56
+ }
57
+
58
+ async close() {}
59
+ }
60
+
61
+ /** IndexedDB store: one database per target, one "files" table. */
62
+ export class IndexedDbFsStore {
63
+ constructor(dbName) {
64
+ this.kind = 'indexeddb';
65
+ this.dbName = dbName;
66
+ this.index = new Map();
67
+ this._db = null;
68
+ }
69
+
70
+ _openDatabase() {
71
+ return new Promise((resolve, reject) => {
72
+ const req = globalThis.indexedDB.open(this.dbName, 1);
73
+ req.onupgradeneeded = () => {
74
+ const db = req.result;
75
+ if (!db.objectStoreNames.contains('files')) db.createObjectStore('files');
76
+ };
77
+ req.onsuccess = () => resolve(req.result);
78
+ req.onerror = () => reject(req.error);
79
+ });
80
+ }
81
+
82
+ async open() {
83
+ this._db = await this._openDatabase();
84
+ this.index = new Map();
85
+ // Walk the table once with a cursor, keeping only each record's
86
+ // metadata for the index; the bytes stay in the database.
87
+ await new Promise((resolve, reject) => {
88
+ const tx = this._db.transaction('files', 'readonly');
89
+ const req = tx.objectStore('files').openCursor();
90
+ req.onsuccess = () => {
91
+ const cursor = req.result;
92
+ if (!cursor) {
93
+ resolve();
94
+ return;
95
+ }
96
+ const value = cursor.value;
97
+ this.index.set(cursor.key, { size: value.size, mtime: value.mtime });
98
+ cursor.continue();
99
+ };
100
+ req.onerror = () => reject(req.error);
101
+ tx.onerror = () => reject(tx.error);
102
+ });
103
+ return this.index;
104
+ }
105
+
106
+ _request(request) {
107
+ return new Promise((resolve, reject) => {
108
+ request.onsuccess = () => resolve(request.result);
109
+ request.onerror = () => reject(request.error);
110
+ });
111
+ }
112
+
113
+ _transactionDone(tx) {
114
+ return new Promise((resolve, reject) => {
115
+ tx.oncomplete = () => resolve();
116
+ tx.onerror = () => reject(tx.error);
117
+ tx.onabort = () => reject(tx.error);
118
+ });
119
+ }
120
+
121
+ async get(path) {
122
+ const tx = this._db.transaction('files', 'readonly');
123
+ const rec = await this._request(tx.objectStore('files').get(path));
124
+ return rec ?? null;
125
+ }
126
+
127
+ async put(path, record) {
128
+ const tx = this._db.transaction('files', 'readwrite');
129
+ tx.objectStore('files').put(
130
+ { bytes: record.bytes, size: record.size, mtime: record.mtime },
131
+ path
132
+ );
133
+ await this._transactionDone(tx);
134
+ }
135
+
136
+ async delete(path) {
137
+ const tx = this._db.transaction('files', 'readwrite');
138
+ tx.objectStore('files').delete(path);
139
+ await this._transactionDone(tx);
140
+ }
141
+
142
+ async close() {
143
+ if (this._db) {
144
+ this._db.close();
145
+ this._db = null;
146
+ }
147
+ }
148
+ }
149
+
150
+ /** Pick the store for one loadTinyc call: an injected store
151
+ * (options.fsStore) wins, then an injected factory
152
+ * (options.storeFactory, called with the target), then IndexedDB
153
+ * when the environment has it, then the in-memory backend. */
154
+ export function createFsStore(target, options = {}) {
155
+ if (options.fsStore) return options.fsStore;
156
+ if (typeof options.storeFactory === 'function') {
157
+ return options.storeFactory(target);
158
+ }
159
+ if (typeof globalThis.indexedDB !== 'undefined' && globalThis.indexedDB) {
160
+ return new IndexedDbFsStore(`tinyc-web-fs-${target}`);
161
+ }
162
+ return new MemoryFsStore();
163
+ }
164
+
165
+ /** Create the store for a target and open it (loading its index).
166
+ * When the default IndexedDB backend fails to open, this falls
167
+ * back to the in-memory backend rather than failing the load;
168
+ * errors from an injected store or factory propagate. */
169
+ export async function openFsStore(target, options = {}) {
170
+ const injected = Boolean(options.fsStore) || typeof options.storeFactory === 'function';
171
+ let store = await createFsStore(target, options);
172
+ try {
173
+ await store.open();
174
+ } catch (err) {
175
+ if (injected || store.kind !== 'indexeddb') throw err;
176
+ store = new MemoryFsStore();
177
+ await store.open();
178
+ }
179
+ return store;
180
+ }
package/worker.mjs ADDED
@@ -0,0 +1,260 @@
1
+ // tinyc-web worker interface.
2
+ //
3
+ // Two halves in one file:
4
+ // - Main thread: the TinycWorker class spawns this file as a module
5
+ // Worker and exposes promise-based compile / runCli methods.
6
+ // Compilation blocks the WASM module for its whole duration, so
7
+ // anything longer than a snippet belongs here, not on the UI
8
+ // thread.
9
+ // - Worker thread: when this file runs inside a
10
+ // DedicatedWorkerGlobalScope it installs the message handler and
11
+ // never touches the class.
12
+ //
13
+ // Protocol: request { id, type, payload }
14
+ // response { id, ok: true, result } | { id, ok: false, error }
15
+ // io push { type: 'io', stream: 'out'|'err', text }
16
+ // IO callbacks are functions and cannot cross postMessage, so native
17
+ // output produced inside the worker is pushed to the main thread as
18
+ // 'io' messages and re-dispatched to the io option given to
19
+ // TinycWorker (default: console, line-buffered by index.mjs wiring
20
+ // on the worker side is raw chunk forwarding).
21
+
22
+ import { loadTinyc, normalizeIO, flushIO } from './index.mjs';
23
+
24
+ function shimBoundaryError(method) {
25
+ return new Error(
26
+ `tinyc: TinycWorker.${method} cannot work: JS functions cannot cross ` +
27
+ `postMessage, so a shim function cannot be sent to the worker. Pass ` +
28
+ `shimModules: [url, ...] to the TinycWorker constructor instead — each ` +
29
+ `module's default export must be a shim map object ({ name: fn }), which ` +
30
+ `the worker imports and registers on its instance.`
31
+ );
32
+ }
33
+
34
+ export class TinycWorker {
35
+ constructor({ workerUrl, wasmUrl, sysroot, glueUrl, target, io, shimModules } = {}) {
36
+ if (typeof Worker === 'undefined') {
37
+ throw new Error('tinyc: TinycWorker needs the Worker API (browser main thread)');
38
+ }
39
+ this._worker = new Worker(
40
+ workerUrl ?? new URL('./worker.mjs', import.meta.url),
41
+ { type: 'module' }
42
+ );
43
+ // target selects the per-target WASM module inside the worker
44
+ // (default: wasm32-wasi). runCli with "-run" is rejected inside
45
+ // the worker for every non-wasm32 target, by the same glue-layer
46
+ // guard as on the main thread.
47
+ // shimModules: URLs of JS modules whose default export is a
48
+ // shim map; the worker imports them and registers the maps on
49
+ // its instance (functions themselves cannot cross postMessage —
50
+ // see registerShim below).
51
+ this._initPayload = { wasmUrl, sysroot, glueUrl, target, shimModules };
52
+ this._io = normalizeIO(io);
53
+ this._pending = new Map();
54
+ this._nextId = 1;
55
+ this._initPromise = null;
56
+ this._worker.addEventListener('message', (ev) => this._onMessage(ev.data));
57
+ this._worker.addEventListener('error', (ev) => this._onError(ev));
58
+ }
59
+
60
+ _onMessage(msg) {
61
+ if (!msg || typeof msg !== 'object') return;
62
+ if (msg.type === 'io') {
63
+ const fn = msg.stream === 'err' ? this._io.err : this._io.out;
64
+ fn(msg.text);
65
+ return;
66
+ }
67
+ const entry = this._pending.get(msg.id);
68
+ if (!entry) return;
69
+ this._pending.delete(msg.id);
70
+ if (msg.ok) entry.resolve(msg.result);
71
+ else {
72
+ const err = new Error(msg.error?.message ?? 'tinyc worker error');
73
+ err.name = msg.error?.name ?? 'TinycWorkerError';
74
+ entry.reject(err);
75
+ }
76
+ }
77
+
78
+ _onError(ev) {
79
+ const err = new Error(ev.message ?? 'tinyc worker failed');
80
+ for (const entry of this._pending.values()) entry.reject(err);
81
+ this._pending.clear();
82
+ }
83
+
84
+ _request(type, payload) {
85
+ const id = this._nextId++;
86
+ return new Promise((resolve, reject) => {
87
+ this._pending.set(id, { resolve, reject });
88
+ this._worker.postMessage({ id, type, payload });
89
+ });
90
+ }
91
+
92
+ /** Load the WASM module inside the worker. Idempotent. */
93
+ init() {
94
+ if (!this._initPromise) {
95
+ this._initPromise = this._request('init', this._initPayload);
96
+ }
97
+ return this._initPromise;
98
+ }
99
+
100
+ async compileString(source, opts) {
101
+ await this.init();
102
+ return this._request('compileString', { source: String(source), opts });
103
+ }
104
+
105
+ /** content: string (sent as-is) or Uint8Array (sent as ArrayBuffer). */
106
+ async compileFile(path, content) {
107
+ await this.init();
108
+ return this._request('compileFile', { path, content });
109
+ }
110
+
111
+ async addFile(path, content) {
112
+ await this.init();
113
+ return this._request('addFile', { path, content });
114
+ }
115
+
116
+ async registerIncludeDir(path) {
117
+ await this.init();
118
+ return this._request('registerIncludeDir', { path });
119
+ }
120
+
121
+ /** Command-line mode inside the worker; resolves to the exit code. */
122
+ async runCli(args = []) {
123
+ await this.init();
124
+ return this._request('callMain', { args: args.map(String) });
125
+ }
126
+
127
+ /** Shims cannot be registered from the main thread on a
128
+ * TinycWorker: the function would have to cross postMessage.
129
+ * Use the constructor's shimModules option instead. */
130
+ registerShim() {
131
+ throw shimBoundaryError('registerShim');
132
+ }
133
+
134
+ registerShims() {
135
+ throw shimBoundaryError('registerShims');
136
+ }
137
+
138
+ terminate() {
139
+ this._worker.terminate();
140
+ for (const entry of this._pending.values()) {
141
+ entry.reject(new Error('tinyc: worker terminated'));
142
+ }
143
+ this._pending.clear();
144
+ }
145
+ }
146
+
147
+ // ---------------------------------------------------------------------
148
+ // Worker side
149
+ // ---------------------------------------------------------------------
150
+
151
+ const isDedicatedWorker =
152
+ typeof DedicatedWorkerGlobalScope !== 'undefined' &&
153
+ typeof self !== 'undefined' &&
154
+ self instanceof DedicatedWorkerGlobalScope;
155
+
156
+ if (isDedicatedWorker) {
157
+ let instancePromise = null;
158
+
159
+ const workerIO = {
160
+ out: (text) => self.postMessage({ type: 'io', stream: 'out', text }),
161
+ err: (text) => self.postMessage({ type: 'io', stream: 'err', text }),
162
+ in: () => null,
163
+ };
164
+
165
+ async function getInstance(payload) {
166
+ if (!instancePromise) {
167
+ instancePromise = (async () => {
168
+ const opts = { io: workerIO, sysroot: payload?.sysroot, target: payload?.target };
169
+ if (payload?.glueUrl) {
170
+ const factory = (await import(/* @vite-ignore */ payload.glueUrl)).default;
171
+ opts.createModule = factory;
172
+ }
173
+ if (payload?.wasmUrl) opts.wasmUrl = payload.wasmUrl;
174
+ const instance = await loadTinyc(opts);
175
+ // Shim modules arrive as URLs (functions cannot cross
176
+ // postMessage): import each one and register its default
177
+ // export — a shim map object — on this instance.
178
+ if (Array.isArray(payload?.shimModules)) {
179
+ for (const url of payload.shimModules) {
180
+ const mod = await import(/* @vite-ignore */ url);
181
+ if (mod?.default && typeof mod.default === 'object') {
182
+ instance.registerShims(mod.default);
183
+ }
184
+ }
185
+ }
186
+ return instance;
187
+ })();
188
+ }
189
+ return instancePromise;
190
+ }
191
+
192
+ const handlers = {
193
+ async init(payload) {
194
+ await getInstance(payload);
195
+ return { ready: true };
196
+ },
197
+ async addFile(payload, payloadInit) {
198
+ const instance = await getInstance(payloadInit);
199
+ if (typeof payload.content === 'string') {
200
+ return instance.addFileSync(payload.path, payload.content);
201
+ }
202
+ return instance.addFileSync(payload.path, new Uint8Array(payload.content));
203
+ },
204
+ async registerIncludeDir(payload, payloadInit) {
205
+ const instance = await getInstance(payloadInit);
206
+ return instance.registerIncludeDir(payload.path);
207
+ },
208
+ async compileString(payload, payloadInit) {
209
+ const instance = await getInstance(payloadInit);
210
+ return instance.compileString(payload.source, payload.opts ?? {});
211
+ },
212
+ async compileFile(payload, payloadInit) {
213
+ const instance = await getInstance(payloadInit);
214
+ if (payload.content !== undefined) {
215
+ if (typeof payload.content === 'string') {
216
+ instance.addFileSync(payload.path, payload.content);
217
+ } else {
218
+ instance.addFileSync(payload.path, new Uint8Array(payload.content));
219
+ }
220
+ }
221
+ const state = instance.createState();
222
+ try {
223
+ return state.compileFile(payload.path);
224
+ } finally {
225
+ state.delete();
226
+ }
227
+ },
228
+ async callMain(payload, payloadInit) {
229
+ const instance = await getInstance(payloadInit);
230
+ return instance.callMain(payload.args ?? []);
231
+ },
232
+ };
233
+
234
+ let initPayload = null;
235
+
236
+ self.addEventListener('message', async (ev) => {
237
+ const { id, type, payload } = ev.data ?? {};
238
+ if (type === 'init') initPayload = payload;
239
+ const handler = handlers[type];
240
+ if (!handler) {
241
+ self.postMessage({
242
+ id, ok: false,
243
+ error: { name: 'TinycWorkerError', message: `unknown message type: ${type}` },
244
+ });
245
+ return;
246
+ }
247
+ try {
248
+ const result = await handler(payload, initPayload);
249
+ flushIO(workerIO);
250
+ self.postMessage({ id, ok: true, result });
251
+ } catch (err) {
252
+ self.postMessage({
253
+ id, ok: false,
254
+ error: { name: err?.name ?? 'Error', message: err?.message ?? String(err) },
255
+ });
256
+ }
257
+ });
258
+ }
259
+
260
+ export default TinycWorker;
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.