// Redis's Lua JSON/MessagePack runtime libraries. Values only; no state or vendor names. // https://redis.io/docs/latest/develop/programmability/lua-api/ (cjson, cmsgpack, bit) import { LuaTable, LuaError, LUA_NULL, luaPattern, numberToLuaString, luaTypeName, type LuaValue, type LuaHost } from './lua.ts'; const bytes = (s: string) => Uint8Array.from(s, (c) => c.charCodeAt(0)); const text = (b: Uint8Array) => Array.from(b, (v) => String.fromCharCode(v)).join(''); const objectTable = (v: any): LuaTable => { const t = new LuaTable(); for (const [k, x] of Object.entries(v)) t.set(k, from(x)); return t; }; const from = (v: any): LuaValue => v === null ? LUA_NULL : Array.isArray(v) ? LuaTable.fromArray(v.map(from)) : typeof v === 'object' ? objectTable(v) : v; const to = (v: LuaValue): any => v === LUA_NULL || v === null ? null : v instanceof LuaTable ? v.length > 0 ? v.toArray().map(to) : Object.fromEntries([...v.map.entries()].map(([k, x]) => [String(k), to(x)])) : v; export function unpackMessage(s: string): LuaValue { const b = bytes(s), d = new DataView(b.buffer); let i = 0; const n = (width: number, signed = false): number => { let v: number; if (i + width > b.length) throw new LuaError('Bad data format in input.'); if (width === 1) v = signed ? d.getInt8(i) : d.getUint8(i); else if (width === 2) v = signed ? d.getInt16(i) : d.getUint16(i); else if (width === 4) v = signed ? d.getInt32(i) : d.getUint32(i); else v = Number(signed ? d.getBigInt64(i) : d.getBigUint64(i)); i += width; return v; }; const string = (len: number) => { const out = text(b.subarray(i, i + len)); i += len; if (i > b.length) throw new LuaError('Bad data format in input.'); return out; }; const array = (len: number) => LuaTable.fromArray(Array.from({ length: len }, read)); const map = (len: number) => { const t = new LuaTable(); for (let j = 0; j < len; j++) t.set(read(), read()); return t; }; function read(): LuaValue { const c = n(1); if (c < 128) return c; if (c >= 224) return c - 256; if ((c & 0xe0) === 0xa0) return string(c & 31); if ((c & 0xf0) === 0x90) return array(c & 15); if ((c & 0xf0) === 0x80) return map(c & 15); switch (c) { case 0xc0: return null; case 0xc2: return false; case 0xc3: return true; case 0xc4: case 0xd9: return string(n(1)); case 0xc5: case 0xda: return string(n(2)); case 0xc6: case 0xdb: return string(n(4)); case 0xcc: return n(1); case 0xcd: return n(2); case 0xce: return n(4); case 0xcf: return n(8); case 0xd0: return n(1, true); case 0xd1: return n(2, true); case 0xd2: return n(4, true); case 0xd3: return n(8, true); case 0xca: { const v = d.getFloat32(i); i += 4; return v; } case 0xcb: { const v = d.getFloat64(i); i += 8; return v; } case 0xdc: return array(n(2)); case 0xdd: return array(n(4)); case 0xde: return map(n(2)); case 0xdf: return map(n(4)); default: throw new LuaError('Bad data format in input.'); } } const value = read(); if (i !== b.length) throw new LuaError('Extra bytes in input.'); return value; } export function packMessage(value: LuaValue): string { const out: number[] = []; const len = (tag: number, size: number, n: number) => { out.push(tag); for (let j = size - 1; j >= 0; j--) out.push(Math.floor(n / 2 ** (j * 8)) & 255); }; const put = (v: LuaValue): void => { if (v === null || v === LUA_NULL) { out.push(0xc0); return; } if (typeof v === 'boolean') { out.push(v ? 0xc3 : 0xc2); return; } if (typeof v === 'number') { if (Number.isInteger(v) && v >= 0 && v < 128 || v >= -32 && v < 0 && Number.isInteger(v)) out.push(v & 255); else { const b = new Uint8Array(8); new DataView(b.buffer).setFloat64(0, v); out.push(0xcb, ...b); } return; } if (typeof v === 'string') { if (v.length < 32) out.push(0xa0 | v.length); else len(v.length < 256 ? 0xd9 : 0xda, v.length < 256 ? 1 : 2, v.length); out.push(...bytes(v)); return; } if (!(v instanceof LuaTable)) throw new LuaError('Unsupported type'); if (v.length > 0) { const a = v.toArray(); if (a.length < 16) out.push(0x90 | a.length); else len(0xdc, 2, a.length); a.forEach(put); } else { if (v.map.size < 16) out.push(0x80 | v.map.size); else len(0xde, 2, v.map.size); for (const [k, x] of v.map) { put(k as LuaValue); put(x); } } }; put(value); return text(Uint8Array.from(out)); } export const standardLuaLibraries: NonNullable = ({ get, set, commandApi }) => { // Lua 5.1 string.match is a selected script runtime capability, not a base-library change. // source: https://www.lua.org/manual/5.1/manual.html "Returns the captures from the pattern" const string = get('string') as LuaTable; string.set('match', (a) => { const str = (i: number): string => { const v = a[i] ?? null; if (typeof v === 'string') return v; if (typeof v === 'number') return numberToLuaString(v); throw new LuaError(`bad argument #${i + 1} to 'string.match' (string expected, got ${luaTypeName(v)})`); }; const value = str(0), pattern = str(1); const start = a[2] === undefined ? 0 : Math.max(0, Number(a[2]) - 1); const match = new RegExp(luaPattern(pattern)).exec(value.slice(start)); return match ? match.length > 1 ? match.slice(1) : [match[0]] : [null]; }); set('redis', commandApi); set('server', commandApi); const json = new LuaTable(); json.set('null', LUA_NULL); json.set('encode', (a) => [text(new TextEncoder().encode(JSON.stringify(to(a[0] ?? null))))]); json.set('decode', (a) => { try { return [from(JSON.parse(new TextDecoder().decode(bytes(String(a[0])))))]; } catch { throw new LuaError('Expected value but found invalid token'); } }); set('cjson', json); const msg = new LuaTable(); msg.set('unpack', (a) => [unpackMessage(String(a[0]))]); msg.set('pack', (a) => [packMessage(a[0] ?? null)]); set('cmsgpack', msg); const bit = new LuaTable(); const ns = (a: LuaValue[]) => a.map(Number); bit.set('band', (a) => [ns(a).reduce((x, y) => x & y, -1)]); bit.set('bor', (a) => [ns(a).reduce((x, y) => x | y, 0)]); bit.set('bxor', (a) => [ns(a).reduce((x, y) => x ^ y, 0)]); bit.set('bnot', (a) => [~Number(a[0])]); bit.set('lshift', (a) => [Number(a[0]) << Number(a[1])]); bit.set('rshift', (a) => [Number(a[0]) >>> Number(a[1])]); bit.set('arshift', (a) => [Number(a[0]) >> Number(a[1])]); set('bit', bit); };