const STATE = 0, LEN = 1, TOTAL = 2; const IDLE = 0, REQ = 1, REQ_ACK = 2, REPLY = 3, REPLY_ACK = 4, QUIT = 9;
const DATA_OFF = 16;
let I = null, B = null, CAP = 0; let wasm = null;
const utf8enc = new TextEncoder();
const utf8dec = new TextDecoder();
const wmem = () => new Uint8Array(wasm.memory.buffer);
const wstr = (p, n) => utf8dec.decode(new Uint8Array(wasm.memory.buffer, p, n));
const POOL_SIZE = 64;
let dir = null; let mapHandle = null; const slots = [];
function readMap() {
try {
const size = mapHandle.getSize();
if (size === 0) return {};
const buf = new Uint8Array(size);
mapHandle.read(buf, { at: 0 });
return JSON.parse(utf8dec.decode(buf)) || {};
} catch { return {}; }
}
function persistMap() {
const names = {};
slots.forEach((s, i) => { if (s.name !== null) names[s.name] = i; });
const bytes = utf8enc.encode(JSON.stringify(names));
mapHandle.truncate(0);
mapHandle.write(bytes, { at: 0 });
mapHandle.flush();
}
function warm(h) {
if (h.getSize() === 0) {
h.write(new Uint8Array(1), { at: 0 });
h.truncate(0);
} else {
const b = new Uint8Array(1);
h.read(b, { at: 0 });
h.write(b, { at: 0 });
}
h.flush();
}
async function acquireHandle(fileHandle) {
const deadline = Date.now() + 10000;
for (;;) {
try {
return await fileHandle.createSyncAccessHandle();
} catch (e) {
if (Date.now() > deadline) throw e;
await new Promise((r) => setTimeout(r, 100));
}
}
}
async function bootPool() {
const root = await navigator.storage.getDirectory();
dir = await root.getDirectoryHandle('.day-sql', { create: true });
const mapFh = await dir.getFileHandle('map.json', { create: true });
mapHandle = await acquireHandle(mapFh);
warm(mapHandle);
const names = readMap();
const top = Math.max(POOL_SIZE, ...Object.values(names).map((i) => i + 1));
for (let i = 0; i < top; i++) {
const fh = await dir.getFileHandle(`pool-${i}`, { create: true });
const handle = await acquireHandle(fh);
warm(handle);
slots.push({ handle, name: null, refs: 0 });
}
for (const [name, i] of Object.entries(names)) if (slots[i]) slots[i].name = name;
}
const fsEnv = {
day_sql_fs_open(p, n, create) {
const name = n ? wstr(p, n) : '';
if (name) {
const i = slots.findIndex((s) => s.name === name);
if (i >= 0) { slots[i].refs += 1; return i; }
if (!create) return -1;
}
const i = slots.findIndex((s) => s.name === null && s.refs === 0);
if (i < 0) return -1; slots[i].handle.truncate(0);
slots[i].refs = 1;
if (name) { slots[i].name = name; persistMap(); }
return i;
},
day_sql_fs_read(slot, off, p, n) {
const s = slots[slot]; if (!s) return -1;
try { return s.handle.read(new Uint8Array(wasm.memory.buffer, p, n), { at: off }); }
catch { return -1; }
},
day_sql_fs_write(slot, off, p, n) {
const s = slots[slot]; if (!s) return -1;
try { return s.handle.write(new Uint8Array(wasm.memory.buffer, p, n), { at: off }) === n ? 0 : -1; }
catch { return -1; }
},
day_sql_fs_truncate(slot, size) {
const s = slots[slot]; if (!s) return -1;
try { s.handle.truncate(size); return 0; } catch { return -1; }
},
day_sql_fs_size(slot) {
const s = slots[slot]; if (!s) return -1;
try { return s.handle.getSize(); } catch { return -1; }
},
day_sql_fs_flush(slot) {
const s = slots[slot]; if (!s) return -1;
try { s.handle.flush(); return 0; } catch { return -1; }
},
day_sql_fs_close(slot, del) {
const s = slots[slot]; if (!s) return;
s.refs = Math.max(0, s.refs - 1);
if (del && s.refs === 0) {
try { s.handle.truncate(0); } catch { }
if (s.name !== null) { s.name = null; persistMap(); }
}
},
day_sql_fs_delete(p, n) {
const name = wstr(p, n);
const i = slots.findIndex((s) => s.name === name);
if (i < 0) return -1;
try { slots[i].handle.truncate(0); } catch { }
slots[i].name = null;
persistMap();
return 0;
},
day_sql_fs_exists(p, n) {
const name = wstr(p, n);
return slots.some((s) => s.name === name) ? 1 : 0;
},
day_sql_log(p, n) {
console.debug('[day-sql]', wstr(p, n));
},
day_sql_fs_list(p, cap) {
const joined = slots.filter((s) => s.name !== null).map((s) => s.name).join('\u001f');
const bytes = utf8enc.encode(joined);
if (cap === 0) return bytes.length;
if (bytes.length > cap) return -1;
wmem().set(bytes, p);
return bytes.length;
},
};
function waitFor(...vs) {
for (;;) {
const cur = Atomics.load(I, STATE);
if (vs.includes(cur)) return cur;
Atomics.wait(I, STATE, cur);
}
}
function callWasm(req) {
const p = wasm.day_sql_alloc(req.length);
wmem().set(req, p);
const out = wasm.day_sql_exec(p, req.length);
const head = new DataView(wasm.memory.buffer, out, 4);
const len = head.getUint32(0, true);
return new Uint8Array(wasm.memory.buffer, out + 4, len).slice();
}
function serve() {
for (;;) {
if (waitFor(REQ, QUIT) === QUIT) {
for (const s of slots) { try { s.handle.close(); } catch { } }
try { mapHandle.close(); } catch { }
return;
}
const total = I[TOTAL];
const req = new Uint8Array(total);
let got = 0;
for (;;) {
const n = I[LEN];
req.set(B.subarray(0, n), got);
got += n;
if (got >= total) break;
Atomics.store(I, STATE, REQ_ACK);
Atomics.notify(I, STATE);
waitFor(REQ);
}
let reply;
try {
reply = callWasm(req);
} catch (e) {
const msg = utf8enc.encode(`sql worker crashed: ${e}`);
reply = new Uint8Array(5 + msg.length);
reply[0] = 255;
new DataView(reply.buffer).setUint32(1, msg.length, true);
reply.set(msg, 5);
}
I[TOTAL] = reply.length;
let off = 0;
for (;;) {
const n = Math.min(CAP, reply.length - off);
B.set(reply.subarray(off, off + n));
I[LEN] = n;
off += n;
Atomics.store(I, STATE, REPLY);
Atomics.notify(I, STATE);
if (off >= reply.length) break;
waitFor(REPLY_ACK);
}
waitFor(IDLE, REQ);
}
}
onmessage = async (e) => {
const { sab, module } = e.data;
try {
I = new Int32Array(sab);
B = new Uint8Array(sab, DATA_OFF);
CAP = B.length;
const now = () => Date.now();
const entropy = (p, n) => crypto.getRandomValues(new Uint8Array(wasm.memory.buffer, p, n));
const host = { day_sql_now_ms: now, day_sql_entropy: entropy, day_dom_now_ms: now, day_dom_entropy: entropy };
const env = new Proxy(fsEnv, {
get: (t, k) => t[k] ?? host[k] ?? (() => 0),
});
const imports = { env };
for (const im of WebAssembly.Module.imports(module)) {
if (im.module === 'env') continue;
const mod = (imports[im.module] ||= {});
if (im.name in mod) continue;
if (im.kind === 'function') {
mod[im.name] = () => {
throw new Error(`day-sql worker: ${im.module}.${im.name} called — no wasm-bindgen runtime here`);
};
} else if (im.kind === 'global') {
mod[im.name] = new WebAssembly.Global({ value: 'i32', mutable: false }, 0);
} else if (im.kind === 'table') {
mod[im.name] = new WebAssembly.Table({ element: 'anyfunc', initial: 0 });
} else if (im.kind === 'memory') {
mod[im.name] = new WebAssembly.Memory({ initial: 1 });
}
}
const instantiated = WebAssembly.instantiate(module, imports);
await bootPool();
wasm = (await instantiated).exports;
postMessage('ready');
serve();
} catch (err) {
postMessage(`dead: ${err}`);
}
};