schemind
Version:
Read and write to messages serialized as arrays (indexed keys) by defining a schema, enabling smaller message size when using protocols such as msgpack or JSON.
82 lines (81 loc) • 1.85 kB
JavaScript
function f(e, t) {
const o = t[i];
let s = e;
for (let c = t[i].length - 1; c >= 1; c--)
s = s[o[c]];
const r = o[0];
return s[r];
}
function h(e, t, o) {
const s = t[i];
let r = e;
for (let n = t[i].length - 1; n >= 1; n--)
r[s[n]] === void 0 && (r[s[n]] = []), r = r[s[n]];
const c = s[0];
r[c] = o;
}
const i = Symbol("indexesPathReversed"), b = Symbol("fieldType"), u = Symbol("isSchemaLeaf");
class l extends Error {
constructor() {
super("Invalid schema. Make sure there are no duplicate indexes, and that nested objects are also wrapped with withIndex."), this.name = "InvalidSchemaError";
}
}
function m(e) {
return v(e, e, [], 0), e;
}
function v(e, t, o, s) {
for (const [r, c] of Object.entries(t)) {
const n = c;
d(n) ? (p(n, o, s), n.get = (a) => f(a, n), n.set = (a, I) => h(a, n, I)) : v(e, n, o, s + 1);
}
}
function p(e, t, o) {
if (t.some((c) => c.length === e[i].length && c.every((n, a) => n === e[i][a])))
throw new l();
if (t.push(e[i]), e[i].length !== o + 1)
throw new l();
}
function y(e) {
return (t) => t ? (S(t, e), t) : {
[i]: [e],
[b]: void 0,
[u]: !0
};
}
function d(e) {
return Object.hasOwn(e, u);
}
function S(e, t) {
for (const [o, s] of Object.entries(e)) {
const r = s;
d(r) ? r[i].push(t) : S(r, t);
}
}
function g(e, t) {
const o = {};
for (const [s, r] of Object.entries(t)) {
const c = r;
let n;
d(c) ? n = f(e, c) : n = g(e, c), o[s] = n;
}
return o;
}
function O(e, t) {
const o = [];
return x(o, e, t), o;
}
function x(e, t, o) {
for (const [s, r] of Object.entries(o)) {
const c = r, n = t[s];
d(c) ? h(e, c, n) : x(e, n, c);
}
}
export {
l as InvalidSchemaError,
m as buildSchema,
f as get,
h as set,
O as toIndexedKeysMessage,
g as toPlainObject,
y as withIndex
};