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.
2 lines (1 loc) • 1.51 kB
JavaScript
;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function h(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 f(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"),g=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 S(e,e,[],0),e}function S(e,t,o,s){for(const[r,c]of Object.entries(t)){const n=c;d(n)?(p(n,o,s),n.get=a=>h(a,n),n.set=(a,x)=>f(a,n,x)):S(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?(b(t,e),t):{[i]:[e],[g]:void 0,[u]:!0}}function d(e){return Object.hasOwn(e,u)}function b(e,t){for(const[o,s]of Object.entries(e)){const r=s;d(r)?r[i].push(t):b(r,t)}}function v(e,t){const o={};for(const[s,r]of Object.entries(t)){const c=r;let n;d(c)?n=h(e,c):n=v(e,c),o[s]=n}return o}function O(e,t){const o=[];return I(o,e,t),o}function I(e,t,o){for(const[s,r]of Object.entries(o)){const c=r,n=t[s];d(c)?f(e,c,n):I(e,n,c)}}exports.InvalidSchemaError=l;exports.buildSchema=m;exports.get=h;exports.set=f;exports.toIndexedKeysMessage=O;exports.toPlainObject=v;exports.withIndex=y;