serializr
Version:
Serialize and deserialize complex object graphs to JSON
4 lines (3 loc) • 16.1 kB
JavaScript
/** serializr - (c) Michel Weststrate 2016 - MIT Licensed */
function e(e){return{factory:function(){return{}},props:e}}var n={j:function(e){try{return JSON.stringify(e)}catch(n){return"[UnexpectedJSONParseError]: ".concat(n.message)}},l:function(e){return e.toString()}};function t(e,t){for(var r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];if(!e){var o=[],u=0,f=t.replace(/%([a-zA-Z%])/g,(function(e,t){if("%%"===e)return e;var i=n[t];if("function"==typeof i){var f=r[u++];return o.push(f),i(f)}return e}));throw console&&o.length>0&&console.log.apply(console,o),Error("[serializr] "+(f||"Illegal State"))}}function r(e){if(e)throw Error(e)}function i(e,n,t){if(0!==e.length){var r=e.filter((function(e){return!0})).length,i=[],o=!1;e.forEach((function(e,u){n(e,(function(e,n){e?o||(o=!0,t(e)):(i[u]=n,0==--r&&t(null,i))}),u)}))}else t(null,[])}function o(e){return null===e||"object"!=typeof e&&"function"!=typeof e}function u(e){return e&&e.factory&&e.props}function f(e){return e&&e.serializer&&e.deserializer}function a(e){return"object"==typeof e&&"string"==typeof e.jsonname}function c(e){return"object"==typeof e&&!0===e.identifier}function s(e,n){for(var t=e;t;){if(t===n)return!0;t=t["extends"]}return!1}function l(e){return e&&"function"==typeof e.keys&&"function"==typeof e.clear&&"function"==typeof e.forEach&&"function"==typeof e.set}function d(e,n){return n&&(t(f(e),"expected a propSchema"),Object.assign(e,n)),e}function p(e){return e?u(e)?e:u(e.serializeInfo)?e.serializeInfo:e.constructor&&e.constructor.serializeInfo?e.constructor.serializeInfo:void 0:undefined}function v(e,n){return t(u(n),"expected modelSchema, got ".concat(n)),e.serializeInfo=n,n}function h(e,n,r){t(e!==Object,"one cannot simply put define a model schema for Object"),t("function"==typeof e,"expected constructor function");var i={targetClass:e,factory:r||function(){return new e},props:n};if(e.prototype.constructor!==Object){var o=p(e.prototype.constructor);o&&o.targetClass!==e&&(i["extends"]=o)}return v(e,i),i}function m(e){return d({serializer:function(e){return t(o(e),"this value is not primitive: ".concat(e)),e},deserializer:function(e,n){o(e)?n(null,e):n("[serializr] this value is not primitive: ".concat(e))}},e)}"function"==typeof SuppressedError&&SuppressedError;var y="undefined"!=typeof Symbol?Symbol("SKIP"):{SKIP:!0},b="_type",j=m(),z=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,g=/([^\s,]+)/g;function x(e,n,r,i){var o,u,c;if(t(arguments.length>=2,"too few arguments. Please use @serializable as property decorator"),r===undefined&&"function"==typeof n&&n.prototype&&i!==undefined&&"number"==typeof i){t(f(e),"Constructor params must use alias(name)"),t(a(e),"Constructor params must use alias(name)");var s=null!==(u=(c=n.toString().replace(z,"")).slice(c.indexOf("(")+1,c.indexOf(")")).match(g))&&void 0!==u?u:[];s.length>=i&&(r=s[i],e.paramNumber=i,i=undefined,n=n.prototype,o=function(e){for(var t,r=[],i=function(n){Object.keys(e.modelSchema.props).forEach((function(t){var i=e.modelSchema.props[t];i.paramNumber===n&&(r[n]=e.json[i.jsonname])}))},o=0;o<n.constructor.length;o++)i(o);return(t=n.constructor).bind.apply(t,function(e,n,t){if(t||2===arguments.length)for(var r,i=0,o=n.length;i<o;i++)!r&&i in n||(r||(r=Array.prototype.slice.call(n,0,i)),r[i]=n[i]);return e.concat(r||Array.prototype.slice.call(n))}([undefined],r,!1))})}t("string"==typeof r,"incorrect usage of @serializable decorator");var l=p(n);return l&&Object.prototype.hasOwnProperty.call(n.constructor,"serializeInfo")||(l=h(n.constructor,{},o)),l&&l.targetClass!==n.constructor&&(l=h(n.constructor,{},o)),l.props[r]=e,!i||i.get||i.set||(i.writable=!0),i}function S(e,n,r){if(!n){var i=!0===e?j:e;return t(f(i),"@serializable expects prop schema"),x.bind(null,i)}x(m(),e,n,r)}function O(){for(var e,n,r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];return t(1===r.length||2===r.length,"serialize expects one or 2 arguments"),1===r.length?(e=undefined,n=r[0]):(e=r[0],n=r[1]),Array.isArray(n)?n.map((function(n){return e?O(e,n):O(n)})):(e?"object"!=typeof e&&(e=p(e)):e=p(n),e||t(e,"Failed to find default schema for ".concat(n)),w(e,n))}function w(e,n){var r,i;return t(e&&"object"==typeof e&&e.props,"Expected schema"),t(n&&"object"==typeof n,"Expected object"),i=e["extends"]?w(e["extends"],n):{},Object.keys(e.props).forEach((function(t){var r=e.props[t];if(r)if("*"!==t){!0===r&&(r=j);var u=r.serializer(n[t],t,n);u!==y&&(i[r.jsonname||t]=u)}else!function(e,n,t,r){for(var i=0,u=Object.keys(t);i<u.length;i++){var f=u[i];if(!(f in e.props)&&(!0===n||n&&(!n.pattern||n.pattern.test(f)))){var a=t[f];if(!0===n)o(a)&&(r[f]=a);else{var c=n.serializer(a,f,t);if(c===y)return;r[f]=c}}}}(e,r,n,i)})),(null===(r=e.discriminator)||void 0===r?void 0:r.storeDiscriminator)&&e.discriminator.storeDiscriminator(i),i}var A=function(){function e(e,n,t,r,i){this.parentContext=e,this.modelSchema=n,this.json=t,this.onReadyCb=r,this.isRoot=!e,this.pendingCallbacks=0,this.pendingRefsCount=0,this.target=undefined,this.hasError=!1,e?(this.rootContext=e.rootContext,this.args=e.args):(this.rootContext=this,this.args=i,this.pendingRefs={},this.resolvedRefs={})}return e.prototype.createCallback=function(n){var r=this;return this.pendingCallbacks++,function(e){var n=!1;return function(){for(var r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];if(!n)return n=!0,e.apply(void 0,r);t(!1,"callback was invoked twice")}}((function(t,i){t?r.hasError||(r.hasError=!0,r.onReadyCb(t),e.rootContextCache["delete"](r)):r.hasError||(n(i),--r.pendingCallbacks===r.pendingRefsCount&&(r.pendingRefsCount>0?(r.onReadyCb(Error('Unresolvable references in json: "'.concat(Object.keys(r.pendingRefs).filter((function(e){return r.pendingRefs[e].length>0})).join('", "'),'"'))),e.rootContextCache["delete"](r)):(r.onReadyCb(null,r.target),e.rootContextCache["delete"](r))))}))},e.prototype.await=function(e,n,r){if(t(this.isRoot,"await can only be called on the root context"),n in this.resolvedRefs){var i=this.resolvedRefs[n].filter((function(n){return s(n.modelSchema,e)}))[0];if(i)return void r(null,i.value)}this.pendingRefsCount++,this.pendingRefs[n]||(this.pendingRefs[n]=[]),this.pendingRefs[n].push({modelSchema:e,uuid:n,callback:r})},e.prototype.resolve=function(e,n,r){if(t(this.isRoot,"resolve can only called on the root context"),this.resolvedRefs[n]||(this.resolvedRefs[n]=[]),this.resolvedRefs[n].push({modelSchema:e,value:r}),n in this.pendingRefs)for(var i=this.pendingRefs[n].length-1;i>=0;i--){var o=this.pendingRefs[n][i];s(e,o.modelSchema)&&(this.pendingRefs[n].splice(i,1),this.pendingRefsCount--,o.callback(null,r))}},e.prototype.setTarget=function(n){this.isRoot&&this.target&&e.rootContextCache["delete"](this.target),this.target=n,e.rootContextCache.set(this.target,this)},e.prototype.cancelAwaits=function(){var e=this;t(this.isRoot,"cancelAwaits can only be called on the root context"),Object.keys(this.pendingRefs).forEach((function(n){e.pendingRefs[n].forEach((function(t){e.pendingRefsCount--,t.callback(Error("Reference resolution canceled for "+n))}))})),this.pendingRefs={},this.pendingRefsCount=0},e.getTargetContext=function(n){return e.rootContextCache.get(n)},e.rootContextCache=new WeakMap,e}();function E(e,n){var t;if(null===(t=n.subSchemas)||void 0===t?void 0:t.length)for(var r=0,i=n.subSchemas;r<i.length;r++){var o=i[r];if(o.discriminator){if(o.discriminator.isActualType(e))return o;var u=E(e,o);if(u!==o)return u}}return n}function k(e,n,o,f){void 0===o&&(o=r),t(arguments.length>=2,"deserialize expects at least 2 arguments");var a=p(e);if(t(u(a),"first argument should be model schema"),Array.isArray(n)){var c=[];return i(n,(function(e,n){var t=D(undefined,a,e,n,f);c.push(t)}),o),c}return D(undefined,a,n,o,f)}function D(e,n,i,o,u){if(null!==i&&i!==undefined&&"object"==typeof i){var f=E(i,n),a=new A(e,f,i,o,u),c=f.factory(a);t(!!c,"No object returned from factory"),a.setTarget(c);var s=a.createCallback(r);return C(a,f,i,c),s(),c}o(null,null)}var N=function(e,n,t,r,i,o){o&&"function"==typeof o.beforeDeserialize?o.beforeDeserialize(e,n,t,r,i,o):e(null,n)},I=function(e,n,t,r,i,o,u,f){f&&"function"==typeof f.afterDeserialize?f.afterDeserialize(e,n,t,r,i,o,u,f):e(n,t)};function C(e,n,r,i){var u;n["extends"]&&C(e,n["extends"],r,i);for(var f=function(f){var a=n.props[f];if(!a)return{value:void 0};if("*"===f)return function(e,n,r,i,u){var f=function(f){if(!(f in n.props)&&!function(e,n){for(var t in e.props){var r=e.props[t];if("object"==typeof r&&r.jsonname===n)return!0}return!1}(n,f)){var a=u[f];!0===r?(t(o(a),"encountered non primitive value while deserializing '*' properties in property '".concat(f,"': ").concat(a)),i[f]=a):!r||r.pattern&&!r.pattern.test(f)||r.deserializer(a,e.rootContext.createCallback((function(e){return e!==y&&(i[f]=e)})),e)}};for(var a in u)f(a)}(e,n,a,i,r),{value:void 0};!0===a&&(a=j);var c=null!==(u=a.jsonname)&&void 0!==u?u:f;t("symbol"!=typeof c,"You must alias symbol properties. prop = %l",f);var s=r[c],l=a;N((function(n,t){n||t===undefined||function(n,t,o){var u=e.rootContext.createCallback((function(e){return e!==y&&(i[o]=e)}));n.deserializer(t,(function(i,f){return I(u,i,f,t,r,o,e,n)}),e,i[o])}(l,t,f)}),s,r,c,e,a)},a=0,c=Object.keys(n.props);a<c.length;a++){var s=f(c[a]);if("object"==typeof s)return s.value}}function J(e,n){return t("object"==typeof e||"function"==typeof e,"No modelschema provided. If you are importing it from another file be aware of circular dependencies."),d({serializer:function(n){var r=p(n)||p(e);return t(u(r),"expected modelSchema, got ".concat(r)),null===n||n===undefined?n:O(r,n)},deserializer:function(n,r,i){t(u(e=p(e)),"expected modelSchema, got ".concat(e)),null!==n&&n!==undefined?D(i,e,n,r,undefined):r(null,n)}},n)}function M(e,n){var r,i;if(1===arguments.length)return r=!0,o(e);function o(e){t("function"==typeof e,"@serializeAll can only be used as class decorator");var n=p(e);return n||v(e,n=h(e,{})),n.props["*"]=r,e}return t("object"==typeof(i=e)&&i.test,"@serializeAll pattern doesn't have test"),"function"==typeof n&&(n=J(n)),!0===n&&(n=j),t(f(n),"couldn't resolve schema"),r=Object.assign({},n,{pattern:e}),o}var P=function(e){if(u(e))return e;var n=p(e);return n||(n=h(e,{})),n};function K(e,n){return function(r){var i,o=P(r);t(null==o?void 0:o["extends"],"Can not apply subSchema on a schema not extending another one.");var u=P(n||o["extends"]);return u.subSchemas=null!==(i=u.subSchemas)&&void 0!==i?i:[],u.subSchemas.push(o),o.discriminator="object"==typeof e?e:{isActualType:function(n){return n[b]===e},storeDiscriminator:function(n){n[b]=e}},r}}function U(e){t("object"==typeof e&&e&&!Array.isArray(e),"cancelDeserialize needs an object");var n,r=(n=e,A.getTargetContext(n));r&&r.cancelAwaits()}function q(){for(var e,n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];"function"==typeof n[0]||u(n[0])?(e=p(n[0]),n.shift()):e=p(n[0]);var o=n[0],f=n[1],a=n[2],c=n[3];t(u(e),"update failed to determine schema"),t("object"==typeof o&&o&&!Array.isArray(o),"update needs an object");var s=new A(undefined,e,f,a||r,c);s.setTarget(o);var l=s.createCallback(r),d=C(s,e,f,o);return l(),d}function F(e,n){var r,i;return"function"==typeof e?(r=e,i=n):i=e,t(!i||"object"==typeof i,"Additional property arguments should be an object, register function should be omitted or a funtion"),d({identifier:!0,serializer:j.serializer,deserializer:function(e,n,t){j.deserializer(e,(function(e,i){!function(e,n,t){t.rootContext.resolve(t.modelSchema,e,t.target)}(i,t.target,t),r&&r(i,t.target,t),n(e,i)}),t)}},i)}function R(e){return d({serializer:function(e){return null===e||e===undefined?e:(t(e instanceof Date,"Expected Date object"),e.getTime())},deserializer:function(e,n){null!==e&&e!==undefined?n(null,new Date(e)):n(null,e)}},e)}function T(e,n){return t(e&&"string"==typeof e,"expected prop name as first argument"),t(f(n=n&&!0!==n?n:j),"expected prop schema as second argument"),t(!a(n),"provided prop is already aliased"),{jsonname:e,serializer:n.serializer,deserializer:n.deserializer,identifier:c(n)||undefined,beforeDeserialize:n.beforeDeserialize,afterDeserialize:n.afterDeserialize}}function W(e,n,r){return t("function"==typeof e,"first argument should be function"),t("function"==typeof n,"second argument should be a function or promise"),d({serializer:e,deserializer:function(e,t,r,i){var o=n(e,r,i,t);4!==n.length&&t(null,o)}},r)}function Y(e){t(f(e=e&&!0!==e?e:j),"expected prop schema as second argument");var n=e.serializer;return t("function"==typeof n,"expected prop schema to have a callable serializer"),Object.assign({},e,{serializer:function(e,t,r){var i=n(e,t,r);return i===undefined?y:i}})}function Z(e,n,r){t(!!e,"No modelSchema provided. If you are importing it from another file be aware of circular dependencies.");var i="function"==typeof n?n:undefined;r=r||(i?undefined:n);var o,f=!1;function a(){if(f=!0,t("string"!=typeof e||"function"==typeof i,"if the reference target is specified by attribute name, a lookup function is required"),t(!i||"function"==typeof i,"second argument should be a lookup function or additional arguments object"),"string"==typeof e)o=e;else{var n=p(e);t(u(n),"expected model schema or string as first argument for 'ref', got ".concat(n)),i=i||function(e){return function(n,t,r){r.rootContext.await(e,n,t)}}(n),o=function(e){t(u(e),"modelSchema must be a ModelSchema");for(var n=e;n;){for(var r in n.props)if(c(n.props[r]))return r;n=n["extends"]}return undefined}(n),t(!!o,"provided model schema doesn't define an identifier() property and cannot be used by 'ref'.")}}return d({serializer:function(e){return f||a(),e?e[o]:null},deserializer:function(e,n,t){f||a(),null===e||e===undefined?n(null,e):i(e,n,t)}},r)}function $(e,n){return t(f(e=e||j),"expected prop schema as first argument"),t(!a(e),"provided prop is aliased, please put aliases first"),d({serializer:function(n){return n===undefined?y:null===n?null:(t(n&&"length"in n&&"map"in n,"expected array (like) object"),n.map(e.serializer))},deserializer:function(n,t,r){null!==n?Array.isArray(n)?i(n,(function(t,i,o){function u(u,f){"function"==typeof e.afterDeserialize?I(i,u,f,t,n,o,r,e):i(u,f)}N((function(n,t){n?i(n):e.deserializer(t,u,r)}),t,n,o,r,e)}),(function(e,n){e?t(e):t(undefined,n.filter((function(e){return y!==e})))})):t("[serializr] expected JSON array"):t(null,n)}},n)}function _(e,n){return t(f(e=e||j),"expected prop schema as first argument"),t(!a(e),"provided prop is aliased, please put aliases first"),d({serializer:function(n){t(n&&"object"==typeof n,"expected object or Map");var r={};if(l(n))n.forEach((function(t,i){return r[i]=e.serializer(t,i,n)}));else for(var i in n)r[i]=e.serializer(n[i],i,n);return r},deserializer:function(t,r,i,o){if(t&&"object"==typeof t){var u=Object.keys(t);$(e,n).deserializer(u.map((function(e){return t[e]})),(function(e,n){if(e)r(e);else{var t,i=l(o);i?(o.clear(),t=o):t={};for(var f=0,a=u.length;f<a;f++)i?t.set(u[f],n[f]):t[u[f]]=n[f];r(null,t)}}),i)}else r("[serializr] expected JSON object")}},n)}function B(e,n,r){return t(f(e=e||j),"expected prop schema as first argument"),t(!!n,"expected key property name as second argument"),d({serializer:function(n){t(n&&"object"==typeof n,"expected object or Map");var r=[];if(l(n))n.forEach((function(t,i){return r.push(e.serializer(t,i,n))}));else for(var i in n)r.push(e.serializer(n[i],i,n));return r},deserializer:function(t,i,o,u){$(e,r).deserializer(t,(function(e,r){if(e)i(e);else{var o,f=l(u);f?(u.clear(),o=u):o={};for(var a=0,c=t.length;a<c;a++)f?o.set(r[a][n],r[a]):o[r[a][n].toString()]=r[a];i(null,o)}}),o,undefined)}},r)}function G(e){return d({serializer:function(e){return e},deserializer:function(e,n){n(null,e)}},e)}export{b as DEFAULT_DISCRIMINATOR_ATTR,y as SKIP,T as alias,U as cancelDeserialize,h as createModelSchema,e as createSimpleSchema,W as custom,R as date,k as deserialize,p as getDefaultModelSchema,F as identifier,$ as list,_ as map,B as mapAsArray,J as object,Y as optional,m as primitive,G as raw,Z as reference,S as serializable,O as serialize,M as serializeAll,v as setDefaultModelSchema,K as subSchema,q as update};
//# sourceMappingURL=serializr.es.min.js.map