Comparing version 5.13.0 to 5.14.0
# typeson CHANGES | ||
## 5.14.0 | ||
- Fix: Ensure `this` is defined with old-style function-based type specs | ||
- Fix: Ensure `Undefined` and `TypesonPromise` revivers are correctly | ||
detected (independent of minification or Babelification). | ||
- Linting (ESLint): Switch to more rigorous config (ash-nazg); jsdoc, etc. | ||
- Linting (ESLint): add any html to linting | ||
- Maintenance: Add `.editorconfig` | ||
- Testing: Add coverage | ||
- npm: Update devDeps/peerDeps | ||
## 5.13.0 | ||
@@ -4,0 +15,0 @@ |
@@ -1,1 +0,1 @@ | ||
"use strict";function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function asyncGeneratorStep(e,t,n,r,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(r,o)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(r,o){var i=e.apply(t,n);function _next(e){asyncGeneratorStep(i,r,o,_next,_throw,"next",e)}function _throw(e){asyncGeneratorStep(i,r,o,_next,_throw,"throw",e)}_next(void 0)})}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _objectSpread(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){_defineProperty(e,t,n[t])})}return e}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_nonIterableRest()}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_nonIterableSpread()}function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}function _iterableToArrayLimit(e,t){var n=[],r=!0,o=!1,i=void 0;try{for(var a,s=e[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{r||null==s.return||s.return()}finally{if(o)throw i}}return n}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}var TypesonPromise=function TypesonPromise(e){_classCallCheck(this,TypesonPromise),this.p=new Promise(e)};"undefined"!=typeof Symbol&&(TypesonPromise.prototype[Symbol.toStringTag]="TypesonPromise"),TypesonPromise.prototype.then=function(e,t){var n=this;return new TypesonPromise(function(r,o){n.p.then(function(t){r(e?e(t):t)},function(e){n.p.catch(function(e){return t?t(e):Promise.reject(e)}).then(r,o)})})},TypesonPromise.prototype.catch=function(e){return this.then(null,e)},TypesonPromise.resolve=function(e){return new TypesonPromise(function(t){t(e)})},TypesonPromise.reject=function(e){return new TypesonPromise(function(t,n){n(e)})},["all","race"].map(function(e){TypesonPromise[e]=function(t){return new TypesonPromise(function(n,r){Promise[e](t.map(function(e){return e.p})).then(n,r)})}});var _ref={},toString=_ref.toString,hasOwn={}.hasOwnProperty,getProto=Object.getPrototypeOf,fnToString=hasOwn.toString;function isThenable(e,t){return isObject(e)&&"function"==typeof e.then&&(!t||"function"==typeof e.catch)}function toStringTag(e){return toString.call(e).slice(8,-1)}function hasConstructorOf(e,t){if(!e||"object"!==_typeof(e))return!1;var n=getProto(e);if(!n)return!1;var r=hasOwn.call(n,"constructor")&&n.constructor;return"function"!=typeof r?null===t:"function"==typeof r&&null!==t&&fnToString.call(r)===fnToString.call(t)}function isPlainObject(e){return!(!e||"Object"!==toStringTag(e))&&(!getProto(e)||hasConstructorOf(e,Object))}function isUserObject(e){if(!e||"Object"!==toStringTag(e))return!1;var t=getProto(e);return!t||(hasConstructorOf(e,Object)||isUserObject(t))}function isObject(e){return e&&"object"===_typeof(e)}function escapeKeyPathComponent(e){return e.replace(/~/g,"~0").replace(/\./g,"~1")}function unescapeKeyPathComponent(e){return e.replace(/~1/g,".").replace(/~0/g,"~")}function getByKeyPath(e,t){if(""===t)return e;var n=t.indexOf(".");if(n>-1){var r=e[unescapeKeyPathComponent(t.substr(0,n))];return void 0===r?void 0:getByKeyPath(r,t.substr(n+1))}return e[unescapeKeyPathComponent(t)]}function setAtKeyPath(e,t,n){if(""===t)return n;var r=t.indexOf(".");return r>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.substr(0,r))],t.substr(r+1),n):(e[unescapeKeyPathComponent(t)]=n,e)}function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)}var keys=Object.keys,isArray=Array.isArray,hasOwn$1={}.hasOwnProperty,internalStateObjPropsToIgnore=["type","replaced","iterateIn","iterateUnsetNumeric"];function nestedPathsFirst(e,t){var n=e.keypath.match(/\./g),r=e.keypath.match(/\./g);return n&&(n=n.length),r&&(r=r.length),n>r?-1:n<r?1:e.keypath<t.keypath?-1:e.keypath>t.keypath}var Typeson=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={}}return _createClass(Typeson,[{key:"stringify",value:function stringify(e,t,n,r){r=_objectSpread({},this.options,r,{stringification:!0});var o=this.encapsulate(e,null,r);return isArray(o)?JSON.stringify(o[0],t,n):o.then(function(e){return JSON.stringify(e,t,n)})}},{key:"stringifySync",value:function stringifySync(e,t,n,r){return this.stringify(e,t,n,_objectSpread({throwOnBadSyncType:!0},r,{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,n,r){return this.stringify(e,t,n,_objectSpread({throwOnBadSyncType:!0},r,{sync:!1}))}},{key:"parse",value:function parse(e,t,n){return n=_objectSpread({},this.options,n,{parse:!0}),this.revive(JSON.parse(e,t),n)}},{key:"parseSync",value:function parseSync(e,t,n){return this.parse(e,t,_objectSpread({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,n){return this.parse(e,t,_objectSpread({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.returnTypeNames=!0,this.encapsulate(e,t,n)}},{key:"rootTypeName",value:function rootTypeName(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.iterateNone=!0,this.encapsulate(e,t,n)}},{key:"encapsulate",value:function encapsulate(e,t,n){var r=(n=_objectSpread({sync:!0},this.options,n)).sync,o=this,i={},a=[],s=[],c=[],u=!("cyclic"in n)||n.cyclic,y=n.encapsulateObserver,p=_encapsulate("",e,u,t||{},c);function finish(e){var t=Object.values(i);if(n.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(n.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!hasOwn$1.call(e,"$types")?e.$types=i:e={$:e,$types:{$:i}}}else isObject(e)&&hasOwn$1.call(e,"$types")&&(e={$:e,$types:!0});return!n.returnTypeNames&&e}function checkPromises(e,t){return _checkPromises.apply(this,arguments)}function _checkPromises(){return(_checkPromises=_asyncToGenerator(regeneratorRuntime.mark(function _callee2(e,t){var n;return regeneratorRuntime.wrap(function _callee2$(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,Promise.all(t.map(function(e){return e[1].p}));case 2:return n=r.sent,r.next=5,Promise.all(n.map(function(){var n=_asyncToGenerator(regeneratorRuntime.mark(function _callee(n){var r,o,i,a,s,c,u,y,p,l,f,h,v,d;return regeneratorRuntime.wrap(function _callee$(b){for(;;)switch(b.prev=b.next){case 0:if(r=[],o=t.splice(0,1),i=_slicedToArray(o,1),a=i[0],s=_slicedToArray(a,7),c=s[0],u=s[2],y=s[3],p=s[4],l=s[5],f=s[6],h=_encapsulate(c,n,u,y,r,!0,f),v=hasConstructorOf(h,TypesonPromise),!c||!v){b.next=11;break}return b.next=8,h.p;case 8:return d=b.sent,p[l]=d,b.abrupt("return",checkPromises(e,r));case 11:return c?p[l]=h:e=v?h.p:h,b.abrupt("return",checkPromises(e,r));case 13:case"end":return b.stop()}},_callee)}));return function(e){return n.apply(this,arguments)}}()));case 5:return r.abrupt("return",e);case 6:case"end":return r.stop()}},_callee2)}))).apply(this,arguments)}function _adaptBuiltinStateObjectProperties(e,t,n){Object.assign(e,t);var r=internalStateObjPropsToIgnore.map(function(t){var n=e[t];return delete e[t],n});n(),internalStateObjPropsToIgnore.forEach(function(t,n){e[t]=r[n]})}function _encapsulate(e,t,r,c,u,p,l){var f,h={},v=_typeof(t),d=y?function(n){var o=l||c.type||Typeson.getJSONType(t);y(Object.assign(n||h,{keypath:e,value:t,cyclic:r,stateObj:c,promisesData:u,resolvingTypesonPromise:p,awaitingTypesonPromise:hasConstructorOf(t,TypesonPromise)},void 0!==o?{type:o}:{}))}:null;if(["string","boolean","number","undefined"].includes(v))return void 0===t||"number"===v&&(isNaN(t)||t===-1/0||t===1/0)?(f=replace(e,t,c,u,!1,p,d))!==t&&(h={replaced:f}):f=t,d&&d(),f;if(null===t)return d&&d(),t;if(r&&!c.iterateIn&&!c.iterateUnsetNumeric){var b=a.indexOf(t);if(!(b<0))return i[e]="#",d&&d({cyclicKeypath:s[b]}),"#"+s[b];!0===r&&(a.push(t),s.push(e))}var m,O=isPlainObject(t),T=isArray(t),P=(O||T)&&(!o.plainObjectReplacers.length||c.replaced)||c.iterateIn?t:replace(e,t,c,u,O||T,null,d);if(P!==t?(f=P,h={replaced:P}):T&&"object"!==c.iterateIn||"array"===c.iterateIn?(m=new Array(t.length),h={clone:m}):O||"object"===c.iterateIn?(m={},c.addLength&&(m.length=t.length),h={clone:m}):""===e&&hasConstructorOf(t,TypesonPromise)?(u.push([e,t,r,c,void 0,void 0,c.type]),f=t):f=t,d&&d(),n.iterateNone)return m||f;if(!m)return f;if(c.iterateIn){var g=function _loop(n){var o={ownKeys:hasOwn$1.call(t,n)};_adaptBuiltinStateObjectProperties(c,o,function(){var o=e+(e?".":"")+escapeKeyPathComponent(n),i=_encapsulate(o,t[n],!!r,c,u,p);hasConstructorOf(i,TypesonPromise)?u.push([o,i,!!r,c,m,n,c.type]):void 0!==i&&(m[n]=i)})};for(var _ in t)g(_);d&&d({endIterateIn:!0,end:!0})}else keys(t).forEach(function(n){var o=e+(e?".":"")+escapeKeyPathComponent(n);_adaptBuiltinStateObjectProperties(c,{ownKeys:!0},function(){var e=_encapsulate(o,t[n],!!r,c,u,p);hasConstructorOf(e,TypesonPromise)?u.push([o,e,!!r,c,m,n,c.type]):void 0!==e&&(m[n]=e)})}),d&&d({endIterateOwn:!0,end:!0});if(c.iterateUnsetNumeric){for(var S=t.length,j=function _loop2(n){if(!(n in t)){var o=e+(e?".":"")+n;_adaptBuiltinStateObjectProperties(c,{ownKeys:!1},function(){var e=_encapsulate(o,void 0,!!r,c,u,p);hasConstructorOf(e,TypesonPromise)?u.push([o,e,!!r,c,m,n,c.type]):void 0!==e&&(m[n]=e)})}},w=0;w<S;w++)j(w);d&&d({endIterateUnsetNumeric:!0,end:!0})}return m}function replace(e,t,n,a,s,c,y){for(var p=s?o.plainObjectReplacers:o.nonplainObjectReplacers,l=p.length;l--;){var f=p[l];if(f.test(t,n)){var h=f.type;if(o.revivers[h]){var v=i[e];i[e]=v?[h].concat(v):h}return Object.assign(n,{type:h,replaced:!0}),!r&&f.replaceAsync||f.replace?(y&&y({replacing:!0}),_encapsulate(e,f[r||!f.replaceAsync?"replace":"replaceAsync"](t,n),u&&"readonly",n,a,c,h)):(y&&y({typeDetected:!0}),_encapsulate(e,t,u&&"readonly",n,a,c,h))}}return t}return c.length?r&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(checkPromises(p,c)).then(finish):!r&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():n.stringification&&r?[finish(p)]:r?finish(p):Promise.resolve(finish(p))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,n){return this.encapsulate(e,t,_objectSpread({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,n){return this.encapsulate(e,t,_objectSpread({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"revive",value:function revive(e,t){var n=e&&e.$types;if(!n)return e;if(!0===n)return e.$;var r=(t=_objectSpread({sync:!0},this.options,t)).sync,o=[],i={},a=!0;n.$&&isPlainObject(n.$)&&(e=e.$,n=n.$,a=!1);var s=this;function _revive(e,t,c,u,y){if(!a||"$types"!==e){var p=n[e];if(isArray(t)||isPlainObject(t)){var l=isArray(t)?new Array(t.length):{};for(keys(t).forEach(function(n){var r=_revive(e+(e?".":"")+escapeKeyPathComponent(n),t[n],c||l,l,n);hasConstructorOf(r,Undefined)?l[n]=void 0:void 0!==r&&(l[n]=r)}),t=l;o.length;){var f=_slicedToArray(o[0],4),h=f[0],v=f[1],d=f[2],b=f[3],m=getByKeyPath(h,v);if(hasConstructorOf(m,Undefined))d[b]=void 0;else{if(void 0===m)break;d[b]=m}o.splice(0,1)}}if(!p)return t;if("#"===p){var O=getByKeyPath(c,t.slice(1));return void 0===O&&o.push([c,t.slice(1),u,y]),O}return[].concat(p).reduce(function reducer(e,t){if(hasConstructorOf(e,TypesonPromise))return e.then(function(e){return reducer(e,t)});var n=_slicedToArray(s.revivers[t],1)[0];if(!n)throw new Error("Unregistered type: "+t);return n[r&&n.revive?"revive":!r&&n.reviveAsync?"reviveAsync":"revive"](e,i)},t)}}function checkUndefined(e){return hasConstructorOf(e,Undefined)?void 0:e}var c,u=function revivePlainObjects(){var t=[];if(Object.entries(n).forEach(function(e){var r=_slicedToArray(e,2),o=r[0],i=r[1];"#"!==i&&[].concat(i).forEach(function(e){_slicedToArray(s.revivers[e],2)[1].plain&&(t.push({keypath:o,type:e}),delete n[o])})}),t.length)return t.sort(nestedPathsFirst).reduce(function reducer(t,n){var o=n.keypath,a=n.type;if(hasConstructorOf(t,TypesonPromise))return t.then(function(e){return reducer(e,a)});var c=getByKeyPath(e,o);if(hasConstructorOf(c,TypesonPromise))return c.then(function(e){return reducer(e,a)});var u=_slicedToArray(s.revivers[a],1)[0];if(!u)throw new Error("Unregistered type: "+a);void 0!==(c=u[r&&u.revive?"revive":!r&&u.reviveAsync?"reviveAsync":"revive"](c,i))&&(hasConstructorOf(c,Undefined)&&(c=void 0),setAtKeyPath(e,o,c)===c&&(e=c))},void 0)}();return isThenable(c=hasConstructorOf(u,TypesonPromise)?u.then(function(){return _revive("",e,null)}):_revive("",e,null))?r&&t.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(c,TypesonPromise)?c.p.then(checkUndefined):c:!r&&t.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():r?checkUndefined(c):Promise.resolve(checkUndefined(c))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread({throwOnBadSyncType:!0},t,{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread({throwOnBadSyncType:!0},t,{sync:!1}))}},{key:"register",value:function register(e,t){return t=t||{},[].concat(e).forEach(function R(e){if(isArray(e))return e.map(R,this);e&&keys(e).forEach(function(n){if("#"===n)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(Typeson.JSON_TYPES.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var r=e[n],o=r.testPlainObjects?this.plainObjectReplacers:this.nonplainObjectReplacers,i=o.filter(function(e){return e.type===n});if(i.length&&(o.splice(o.indexOf(i[0]),1),delete this.revivers[n],delete this.types[n]),r){if("function"==typeof r){var a=r;r={test:function test(e){return e&&e.constructor===a},replace:function replace(e){return Object.assign({},e)},revive:function revive(e){return Object.assign(Object.create(a.prototype),e)}}}else if(isArray(r)){var s=_slicedToArray(r,3);r={test:s[0],replace:s[1],revive:s[2]}}var c={type:n,test:r.test.bind(r)};r.replace&&(c.replace=r.replace.bind(r)),r.replaceAsync&&(c.replaceAsync=r.replaceAsync.bind(r));var u="number"==typeof t.fallback?t.fallback:t.fallback?0:1/0;if(r.testPlainObjects?this.plainObjectReplacers.splice(u,0,c):this.nonplainObjectReplacers.splice(u,0,c),r.revive||r.reviveAsync){var y={};r.revive&&(y.revive=r.revive.bind(r)),r.reviveAsync&&(y.reviveAsync=r.reviveAsync.bind(r)),this.revivers[n]=[y,{plain:r.testPlainObjects}]}this.types[n]=r}},this)},this),this}}]),Typeson}(),Undefined=function Undefined(){_classCallCheck(this,Undefined)};Typeson.Undefined=Undefined,Typeson.Promise=TypesonPromise,Typeson.isThenable=isThenable,Typeson.toStringTag=toStringTag,Typeson.hasConstructorOf=hasConstructorOf,Typeson.isObject=isObject,Typeson.isPlainObject=isPlainObject,Typeson.isUserObject=isUserObject,Typeson.escapeKeyPathComponent=escapeKeyPathComponent,Typeson.unescapeKeyPathComponent=unescapeKeyPathComponent,Typeson.getByKeyPath=getByKeyPath,Typeson.getJSONType=getJSONType,Typeson.JSON_TYPES=["null","boolean","number","string","array","object"],module.exports=Typeson; | ||
"use strict";function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(n),!0).forEach((function(t){_defineProperty(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ownKeys(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_nonIterableRest()}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_nonIterableSpread()}function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}function _iterableToArrayLimit(e,t){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)){var n=[],r=!0,o=!1,i=void 0;try{for(var a,s=e[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{r||null==s.return||s.return()}finally{if(o)throw i}}return n}}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}var TypesonPromise=function TypesonPromise(e){_classCallCheck(this,TypesonPromise),this.p=new Promise(e)};TypesonPromise.__typeson__type__="TypesonPromise","undefined"!=typeof Symbol&&(TypesonPromise.prototype[Symbol.toStringTag]="TypesonPromise"),TypesonPromise.prototype.then=function(e,t){var n=this;return new TypesonPromise((function(r,o){n.p.then((function(t){r(e?e(t):t)})).catch((function(e){return t?t(e):Promise.reject(e)})).then(r,o)}))},TypesonPromise.prototype.catch=function(e){return this.then(null,e)},TypesonPromise.resolve=function(e){return new TypesonPromise((function(t){t(e)}))},TypesonPromise.reject=function(e){return new TypesonPromise((function(t,n){n(e)}))},["all","race"].forEach((function(e){TypesonPromise[e]=function(t){return new TypesonPromise((function(n,r){Promise[e](t.map((function(e){return e.p}))).then(n,r)}))}}));var _ref={},toStr=_ref.toString,hasOwn={}.hasOwnProperty,getProto=Object.getPrototypeOf,fnToString=hasOwn.toString;function isThenable(e,t){return isObject(e)&&"function"==typeof e.then&&(!t||"function"==typeof e.catch)}function toStringTag(e){return toStr.call(e).slice(8,-1)}function hasConstructorOf(e,t){if(!e||"object"!==_typeof(e))return!1;var n=getProto(e);if(!n)return!1;var r=hasOwn.call(n,"constructor")&&n.constructor;return"function"!=typeof r?null===t:t===r||(null!==t&&fnToString.call(r)===fnToString.call(t)||"function"==typeof t&&"string"==typeof r.__typeson__type__&&r.__typeson__type__===t.__typeson__type__)}function isPlainObject(e){return!(!e||"Object"!==toStringTag(e))&&(!getProto(e)||hasConstructorOf(e,Object))}function isUserObject(e){if(!e||"Object"!==toStringTag(e))return!1;var t=getProto(e);return!t||(hasConstructorOf(e,Object)||isUserObject(t))}function isObject(e){return e&&"object"===_typeof(e)}function escapeKeyPathComponent(e){return e.replace(/~/g,"~0").replace(/\./g,"~1")}function unescapeKeyPathComponent(e){return e.replace(/~1/g,".").replace(/~0/g,"~")}function getByKeyPath(e,t){if(""===t)return e;var n=t.indexOf(".");if(n>-1){var r=e[unescapeKeyPathComponent(t.slice(0,n))];return void 0===r?void 0:getByKeyPath(r,t.slice(n+1))}return e[unescapeKeyPathComponent(t)]}function setAtKeyPath(e,t,n){if(""===t)return n;var r=t.indexOf(".");return r>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,r))],t.slice(r+1),n):(e[unescapeKeyPathComponent(t)]=n,e)}function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)}var keys=Object.keys,isArray=Array.isArray,hasOwn$1={}.hasOwnProperty,internalStateObjPropsToIgnore=["type","replaced","iterateIn","iterateUnsetNumeric"];function nestedPathsFirst(e,t){var n=e.keypath.match(/\./g),r=e.keypath.match(/\./g);return n&&(n=n.length),r&&(r=r.length),n>r?-1:n<r?1:e.keypath<t.keypath?-1:e.keypath>t.keypath}var Typeson=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={}}return _createClass(Typeson,[{key:"stringify",value:function stringify(e,t,n,r){r=_objectSpread2({},this.options,{},r,{stringification:!0});var o=this.encapsulate(e,null,r);return isArray(o)?JSON.stringify(o[0],t,n):o.then((function(e){return JSON.stringify(e,t,n)}))}},{key:"stringifySync",value:function stringifySync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!1}))}},{key:"parse",value:function parse(e,t,n){return n=_objectSpread2({},this.options,{},n,{parse:!0}),this.revive(JSON.parse(e,t),n)}},{key:"parseSync",value:function parseSync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.returnTypeNames=!0,this.encapsulate(e,t,n)}},{key:"rootTypeName",value:function rootTypeName(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.iterateNone=!0,this.encapsulate(e,t,n)}},{key:"encapsulate",value:function encapsulate(e,t,n){var r=(n=_objectSpread2({sync:!0},this.options,{},n)).sync,o=this,i={},a=[],s=[],c=[],u=!("cyclic"in n)||n.cyclic,p=n.encapsulateObserver,y=_encapsulate("",e,u,t||{},c);function finish(e){var t=Object.values(i);if(n.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(n.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!hasOwn$1.call(e,"$types")?e.$types=i:e={$:e,$types:{$:i}}}else isObject(e)&&hasOwn$1.call(e,"$types")&&(e={$:e,$types:!0});return!n.returnTypeNames&&e}function _adaptBuiltinStateObjectProperties(e,t,n){Object.assign(e,t);var r=internalStateObjPropsToIgnore.map((function(t){var n=e[t];return delete e[t],n}));n(),internalStateObjPropsToIgnore.forEach((function(t,n){e[t]=r[n]}))}function _encapsulate(e,t,r,c,u,y,l){var f,h={},v=_typeof(t),d=p?function(n){var o=l||c.type||Typeson.getJSONType(t);p(Object.assign(n||h,{keypath:e,value:t,cyclic:r,stateObj:c,promisesData:u,resolvingTypesonPromise:y,awaitingTypesonPromise:hasConstructorOf(t,TypesonPromise)},void 0!==o?{type:o}:{}))}:null;if(["string","boolean","number","undefined"].includes(v))return void 0===t||"number"===v&&(isNaN(t)||t===-1/0||t===1/0)?(f=replace(e,t,c,u,!1,y,d))!==t&&(h={replaced:f}):f=t,d&&d(),f;if(null===t)return d&&d(),t;if(r&&!c.iterateIn&&!c.iterateUnsetNumeric){var b=a.indexOf(t);if(!(b<0))return i[e]="#",d&&d({cyclicKeypath:s[b]}),"#"+s[b];!0===r&&(a.push(t),s.push(e))}var O,m=isPlainObject(t),T=isArray(t),P=(m||T)&&(!o.plainObjectReplacers.length||c.replaced)||c.iterateIn?t:replace(e,t,c,u,m||T,null,d);if(P!==t?(f=P,h={replaced:P}):T&&"object"!==c.iterateIn||"array"===c.iterateIn?(O=new Array(t.length),h={clone:O}):m||"object"===c.iterateIn?(O={},c.addLength&&(O.length=t.length),h={clone:O}):""===e&&hasConstructorOf(t,TypesonPromise)?(u.push([e,t,r,c,void 0,void 0,c.type]),f=t):f=t,d&&d(),n.iterateNone)return O||f;if(!O)return f;if(c.iterateIn){var g=function _loop(n){var o={ownKeys:hasOwn$1.call(t,n)};_adaptBuiltinStateObjectProperties(c,o,(function(){var o=e+(e?".":"")+escapeKeyPathComponent(n),i=_encapsulate(o,t[n],Boolean(r),c,u,y);hasConstructorOf(i,TypesonPromise)?u.push([o,i,Boolean(r),c,O,n,c.type]):void 0!==i&&(O[n]=i)}))};for(var _ in t)g(_);d&&d({endIterateIn:!0,end:!0})}else keys(t).forEach((function(n){var o=e+(e?".":"")+escapeKeyPathComponent(n);_adaptBuiltinStateObjectProperties(c,{ownKeys:!0},(function(){var e=_encapsulate(o,t[n],Boolean(r),c,u,y);hasConstructorOf(e,TypesonPromise)?u.push([o,e,Boolean(r),c,O,n,c.type]):void 0!==e&&(O[n]=e)}))})),d&&d({endIterateOwn:!0,end:!0});if(c.iterateUnsetNumeric){for(var j=t.length,S=function _loop2(n){if(!(n in t)){var o=e+(e?".":"")+n;_adaptBuiltinStateObjectProperties(c,{ownKeys:!1},(function(){var e=_encapsulate(o,void 0,Boolean(r),c,u,y);hasConstructorOf(e,TypesonPromise)?u.push([o,e,Boolean(r),c,O,n,c.type]):void 0!==e&&(O[n]=e)}))}},w=0;w<j;w++)S(w);d&&d({endIterateUnsetNumeric:!0,end:!0})}return O}function replace(e,t,n,a,s,c,p){for(var y=s?o.plainObjectReplacers:o.nonplainObjectReplacers,l=y.length;l--;){var f=y[l];if(f.test(t,n)){var h=f.type;if(o.revivers[h]){var v=i[e];i[e]=v?[h].concat(v):h}return Object.assign(n,{type:h,replaced:!0}),!r&&f.replaceAsync||f.replace?(p&&p({replacing:!0}),_encapsulate(e,f[r||!f.replaceAsync?"replace":"replaceAsync"](t,n),u&&"readonly",n,a,c,h)):(p&&p({typeDetected:!0}),_encapsulate(e,t,u&&"readonly",n,a,c,h))}}return t}return c.length?r&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(function checkPromises(e,t){var n;return regeneratorRuntime.async((function checkPromises$(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,regeneratorRuntime.awrap(Promise.all(t.map((function(e){return e[1].p}))));case 2:return n=r.sent,r.next=5,regeneratorRuntime.awrap(Promise.all(n.map((function _callee(n){var r,o,i,a,s,c,u,p,y,l,f,h,v,d;return regeneratorRuntime.async((function _callee$(b){for(;;)switch(b.prev=b.next){case 0:if(r=[],o=t.splice(0,1),i=_slicedToArray(o,1),a=i[0],s=_slicedToArray(a,7),c=s[0],u=s[2],p=s[3],y=s[4],l=s[5],f=s[6],h=_encapsulate(c,n,u,p,r,!0,f),v=hasConstructorOf(h,TypesonPromise),!c||!v){b.next=11;break}return b.next=8,regeneratorRuntime.awrap(h.p);case 8:return d=b.sent,y[l]=d,b.abrupt("return",checkPromises(e,r));case 11:return c?y[l]=h:e=v?h.p:h,b.abrupt("return",checkPromises(e,r));case 13:case"end":return b.stop()}}))}))));case 5:return r.abrupt("return",e);case 6:case"end":return r.stop()}}))}(y,c)).then(finish):!r&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():n.stringification&&r?[finish(y)]:r?finish(y):Promise.resolve(finish(y))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"revive",value:function revive(e,t){var n=e&&e.$types;if(!n)return e;if(!0===n)return e.$;var r=(t=_objectSpread2({sync:!0},this.options,{},t)).sync,o=[],i={},a=!0;n.$&&isPlainObject(n.$)&&(e=e.$,n=n.$,a=!1);var s=this;function _revive(e,t,c,u,p){if(!a||"$types"!==e){var y=n[e];if(isArray(t)||isPlainObject(t)){var l=isArray(t)?new Array(t.length):{};for(keys(t).forEach((function(n){var r=_revive(e+(e?".":"")+escapeKeyPathComponent(n),t[n],c||l,l,n);hasConstructorOf(r,Undefined)?l[n]=void 0:void 0!==r&&(l[n]=r)})),t=l;o.length;){var f=_slicedToArray(o[0],4),h=f[0],v=f[1],d=f[2],b=f[3],O=getByKeyPath(h,v);if(hasConstructorOf(O,Undefined))d[b]=void 0;else{if(void 0===O)break;d[b]=O}o.splice(0,1)}}if(!y)return t;if("#"===y){var m=getByKeyPath(c,t.slice(1));return void 0===m&&o.push([c,t.slice(1),u,p]),m}return[].concat(y).reduce((function reducer(e,t){if(hasConstructorOf(e,TypesonPromise))return e.then((function(e){return reducer(e,t)}));var n=_slicedToArray(s.revivers[t],1)[0];if(!n)throw new Error("Unregistered type: "+t);return n[r&&n.revive?"revive":!r&&n.reviveAsync?"reviveAsync":"revive"](e,i)}),t)}}function checkUndefined(e){return hasConstructorOf(e,Undefined)?void 0:e}var c,u=function revivePlainObjects(){var t=[];if(Object.entries(n).forEach((function(e){var r=_slicedToArray(e,2),o=r[0],i=r[1];"#"!==i&&[].concat(i).forEach((function(e){_slicedToArray(s.revivers[e],2)[1].plain&&(t.push({keypath:o,type:e}),delete n[o])}))})),t.length)return t.sort(nestedPathsFirst).reduce((function reducer(t,n){var o=n.keypath,a=n.type;if(hasConstructorOf(t,TypesonPromise))return t.then((function(e){return reducer(e,a)}));var c=getByKeyPath(e,o);if(hasConstructorOf(c,TypesonPromise))return c.then((function(e){return reducer(e,a)}));var u=_slicedToArray(s.revivers[a],1)[0];if(!u)throw new Error("Unregistered type: "+a);void 0!==(c=u[r&&u.revive?"revive":!r&&u.reviveAsync?"reviveAsync":"revive"](c,i))&&(hasConstructorOf(c,Undefined)&&(c=void 0),setAtKeyPath(e,o,c)===c&&(e=c))}),void 0)}();return isThenable(c=hasConstructorOf(u,TypesonPromise)?u.then((function(){return _revive("",e,null)})):_revive("",e,null))?r&&t.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(c,TypesonPromise)?c.p.then(checkUndefined):c:!r&&t.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():r?checkUndefined(c):Promise.resolve(checkUndefined(c))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!1}))}},{key:"register",value:function register(e,t){return t=t||{},[].concat(e).forEach((function R(e){var n=this;if(isArray(e))return e.map((function(e){return R.call(n,e)}));e&&keys(e).forEach((function(n){if("#"===n)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(Typeson.JSON_TYPES.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var r=e[n],o=r.testPlainObjects?this.plainObjectReplacers:this.nonplainObjectReplacers,i=o.filter((function(e){return e.type===n}));if(i.length&&(o.splice(o.indexOf(i[0]),1),delete this.revivers[n],delete this.types[n]),r){if("function"==typeof r){var a=r;r={test:function test(e){return e&&e.constructor===a},replace:function replace(e){return _objectSpread2({},e)},revive:function revive(e){return Object.assign(Object.create(a.prototype),e)}}}else if(isArray(r)){var s=_slicedToArray(r,3);r={test:s[0],replace:s[1],revive:s[2]}}var c={type:n,test:r.test.bind(r)};r.replace&&(c.replace=r.replace.bind(r)),r.replaceAsync&&(c.replaceAsync=r.replaceAsync.bind(r));var u="number"==typeof t.fallback?t.fallback:t.fallback?0:1/0;if(r.testPlainObjects?this.plainObjectReplacers.splice(u,0,c):this.nonplainObjectReplacers.splice(u,0,c),r.revive||r.reviveAsync){var p={};r.revive&&(p.revive=r.revive.bind(r)),r.reviveAsync&&(p.reviveAsync=r.reviveAsync.bind(r)),this.revivers[n]=[p,{plain:r.testPlainObjects}]}this.types[n]=r}}),this)}),this),this}}]),Typeson}(),Undefined=function Undefined(){_classCallCheck(this,Undefined)};Undefined.__typeson__type__="TypesonUndefined",Typeson.Undefined=Undefined,Typeson.Promise=TypesonPromise,Typeson.isThenable=isThenable,Typeson.toStringTag=toStringTag,Typeson.hasConstructorOf=hasConstructorOf,Typeson.isObject=isObject,Typeson.isPlainObject=isPlainObject,Typeson.isUserObject=isUserObject,Typeson.escapeKeyPathComponent=escapeKeyPathComponent,Typeson.unescapeKeyPathComponent=unescapeKeyPathComponent,Typeson.getByKeyPath=getByKeyPath,Typeson.getJSONType=getJSONType,Typeson.JSON_TYPES=["null","boolean","number","string","array","object"],module.exports=Typeson; |
@@ -15,38 +15,2 @@ function _typeof(obj) { | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { | ||
try { | ||
var info = gen[key](arg); | ||
var value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
Promise.resolve(value).then(_next, _throw); | ||
} | ||
} | ||
function _asyncToGenerator(fn) { | ||
return function () { | ||
var self = this, | ||
args = arguments; | ||
return new Promise(function (resolve, reject) { | ||
var gen = fn.apply(self, args); | ||
function _next(value) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); | ||
} | ||
function _throw(err) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); | ||
} | ||
_next(undefined); | ||
}); | ||
}; | ||
} | ||
function _classCallCheck(instance, Constructor) { | ||
@@ -89,16 +53,31 @@ if (!(instance instanceof Constructor)) { | ||
function _objectSpread(target) { | ||
function ownKeys(object, enumerableOnly) { | ||
var keys = Object.keys(object); | ||
if (Object.getOwnPropertySymbols) { | ||
var symbols = Object.getOwnPropertySymbols(object); | ||
if (enumerableOnly) symbols = symbols.filter(function (sym) { | ||
return Object.getOwnPropertyDescriptor(object, sym).enumerable; | ||
}); | ||
keys.push.apply(keys, symbols); | ||
} | ||
return keys; | ||
} | ||
function _objectSpread2(target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i] != null ? arguments[i] : {}; | ||
var ownKeys = Object.keys(source); | ||
if (typeof Object.getOwnPropertySymbols === 'function') { | ||
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { | ||
return Object.getOwnPropertyDescriptor(source, sym).enumerable; | ||
})); | ||
if (i % 2) { | ||
ownKeys(Object(source), true).forEach(function (key) { | ||
_defineProperty(target, key, source[key]); | ||
}); | ||
} else if (Object.getOwnPropertyDescriptors) { | ||
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); | ||
} else { | ||
ownKeys(Object(source)).forEach(function (key) { | ||
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); | ||
}); | ||
} | ||
ownKeys.forEach(function (key) { | ||
_defineProperty(target, key, source[key]); | ||
}); | ||
} | ||
@@ -134,2 +113,6 @@ | ||
function _iterableToArrayLimit(arr, i) { | ||
if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { | ||
return; | ||
} | ||
var _arr = []; | ||
@@ -176,2 +159,4 @@ var _n = true; | ||
*/ | ||
// eslint-disable-next-line max-len | ||
// eslint-disable-next-line block-spacing, space-before-function-paren, space-before-blocks, space-infix-ops, semi, promise/avoid-new | ||
var TypesonPromise = function TypesonPromise(f) { | ||
@@ -181,7 +166,8 @@ _classCallCheck(this, TypesonPromise); | ||
this.p = new Promise(f); | ||
}; // eslint-disable-line block-spacing, space-before-function-paren, space-before-blocks, space-infix-ops, semi | ||
}; // eslint-disable-next-line max-len | ||
// class TypesonPromise extends Promise {get[Symbol.toStringTag](){return 'TypesonPromise'};} // eslint-disable-line keyword-spacing, space-before-function-paren, space-before-blocks, block-spacing, semi | ||
// Note: core-js-bundle provides a `Symbol` polyfill | ||
TypesonPromise.__typeson__type__ = 'TypesonPromise'; // Note: core-js-bundle provides a `Symbol` polyfill | ||
if (typeof Symbol !== 'undefined') { | ||
@@ -203,9 +189,9 @@ // Ensure `isUserObject` will return `false` for `TypesonPromise` | ||
return new TypesonPromise(function (typesonResolve, typesonReject) { | ||
// eslint-disable-next-line promise/catch-or-return | ||
_this.p.then(function (res) { | ||
// eslint-disable-next-line promise/always-return | ||
typesonResolve(onFulfilled ? onFulfilled(res) : res); | ||
}, function (r) { | ||
_this.p['catch'](function (res) { | ||
return onRejected ? onRejected(res) : Promise.reject(res); | ||
}).then(typesonResolve, typesonReject); | ||
}); | ||
})["catch"](function (res) { | ||
return onRejected ? onRejected(res) : Promise.reject(res); | ||
}).then(typesonResolve, typesonReject); | ||
}); | ||
@@ -225,3 +211,3 @@ }; | ||
* | ||
* @param {} v | ||
* @param {Any} v | ||
* @returns {TypesonPromise} | ||
@@ -238,3 +224,3 @@ */ | ||
* | ||
* @param {} v | ||
* @param {Any} v | ||
* @returns {TypesonPromise} | ||
@@ -250,3 +236,3 @@ */ | ||
['all', 'race'].map(function (meth) { | ||
['all', 'race'].forEach(function (meth) { | ||
/** | ||
@@ -259,2 +245,3 @@ * | ||
return new TypesonPromise(function (typesonResolve, typesonReject) { | ||
// eslint-disable-next-line promise/catch-or-return | ||
Promise[meth](promArr.map(function (prom) { | ||
@@ -268,3 +255,3 @@ return prom.p; | ||
var _ref = {}, | ||
toString = _ref.toString, | ||
toStr = _ref.toString, | ||
hasOwn = {}.hasOwnProperty, | ||
@@ -275,3 +262,3 @@ getProto = Object.getPrototypeOf, | ||
* | ||
* @param {*} v | ||
* @param {Any} v | ||
* @param {boolean} catchCheck | ||
@@ -286,3 +273,3 @@ * @returns {boolean} | ||
* | ||
* @param {*} val | ||
* @param {Any} val | ||
* @returns {string} | ||
@@ -293,3 +280,3 @@ */ | ||
function toStringTag(val) { | ||
return toString.call(val).slice(8, -1); | ||
return toStr.call(val).slice(8, -1); | ||
} | ||
@@ -299,3 +286,3 @@ /** | ||
* being identical so any minimization is expected of both. | ||
* @param {*} a | ||
* @param {Any} a | ||
* @param {function} b | ||
@@ -323,7 +310,19 @@ * @returns {boolean} | ||
return typeof Ctor === 'function' && b !== null && fnToString.call(Ctor) === fnToString.call(b); | ||
if (b === Ctor) { | ||
return true; | ||
} | ||
if (b !== null && fnToString.call(Ctor) === fnToString.call(b)) { | ||
return true; | ||
} | ||
if (typeof b === 'function' && typeof Ctor.__typeson__type__ === 'string' && Ctor.__typeson__type__ === b.__typeson__type__) { | ||
return true; | ||
} | ||
return false; | ||
} | ||
/** | ||
* | ||
* @param {*} val | ||
* @param {Any} val | ||
* @returns {boolean} | ||
@@ -350,3 +349,3 @@ */ | ||
* | ||
* @param {*} val | ||
* @param {Any} val | ||
* @returns {boolean} | ||
@@ -372,3 +371,3 @@ */ | ||
* | ||
* @param {*} v | ||
* @param {Any} v | ||
* @returns {boolean} | ||
@@ -402,5 +401,5 @@ */ | ||
/** | ||
* @param {object|array} obj | ||
* @param {PlainObject|GenericArray} obj | ||
* @param {string} keyPath | ||
* @returns {*} | ||
* @returns {Any} | ||
*/ | ||
@@ -417,4 +416,4 @@ | ||
if (period > -1) { | ||
var innerObj = obj[unescapeKeyPathComponent(keyPath.substr(0, period))]; | ||
return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1)); | ||
var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))]; | ||
return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.slice(period + 1)); | ||
} | ||
@@ -424,3 +423,11 @@ | ||
} | ||
/** | ||
* | ||
* @param {PlainObject} obj | ||
* @param {string} keyPath | ||
* @param {Any} value | ||
* @returns {Any} | ||
*/ | ||
function setAtKeyPath(obj, keyPath, value) { | ||
@@ -434,4 +441,4 @@ if (keyPath === '') { | ||
if (period > -1) { | ||
var innerObj = obj[unescapeKeyPathComponent(keyPath.substr(0, period))]; | ||
return setAtKeyPath(innerObj, keyPath.substr(period + 1), value); | ||
var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))]; | ||
return setAtKeyPath(innerObj, keyPath.slice(period + 1), value); | ||
} | ||
@@ -445,3 +452,4 @@ | ||
* @param {external:JSON} value | ||
* @returns {"null"|"array"|"undefined"|"boolean"|"number"|"string"|"object"|"symbol"} | ||
* @returns {"null"|"array"|"undefined"|"boolean"|"number"|"string"| | ||
* "object"|"symbol"} | ||
*/ | ||
@@ -458,2 +466,8 @@ | ||
internalStateObjPropsToIgnore = ['type', 'replaced', 'iterateIn', 'iterateUnsetNumeric']; | ||
/** | ||
* | ||
* @param {PlainObjectType} a | ||
* @param {PlainObjectType} b | ||
* @returns {1|-1|boolean} | ||
*/ | ||
@@ -479,3 +493,3 @@ function nestedPathsFirst(a, b) { | ||
* | ||
* @constructor | ||
* @class | ||
* @param {{cyclic: boolean}} [options] - if cyclic (default true), | ||
@@ -505,7 +519,19 @@ * cyclic references will be handled gracefully. | ||
/** | ||
* @typedef {null|boolean|number|string|GenericArray|PlainObject} JSON | ||
*/ | ||
/** | ||
* @callback JSONReplacer | ||
* @param {""|string} key | ||
* @param {JSON} value | ||
* @returns {number|string|boolean|null|PlainObject|undefined} | ||
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20replacer%20parameter | ||
*/ | ||
/** | ||
* Serialize given object to Typeson. | ||
* Initial arguments work identical to those of `JSON.stringify`. | ||
* The `replacer` argument has nothing to do with our replacers. | ||
* @param {*} obj | ||
* @param {function|string[]} replacer | ||
* @param {Any} obj | ||
* @param {JSONReplacer|string[]} replacer | ||
* @param {number|string} space | ||
@@ -520,3 +546,3 @@ * @param {object} opts | ||
value: function stringify(obj, replacer, space, opts) { | ||
opts = _objectSpread({}, this.options, opts, { | ||
opts = _objectSpread2({}, this.options, {}, opts, { | ||
stringification: true | ||
@@ -535,5 +561,5 @@ }); | ||
/** | ||
* Also sync but throws on non-sync result | ||
* @param {*} obj | ||
* @param {function|string[]} replacer | ||
* Also sync but throws on non-sync result. | ||
* @param {Any} obj | ||
* @param {JSONReplacer|string[]} replacer | ||
* @param {number|string} space | ||
@@ -547,3 +573,3 @@ * @param {object} opts | ||
value: function stringifySync(obj, replacer, space, opts) { | ||
return this.stringify(obj, replacer, space, _objectSpread({ | ||
return this.stringify(obj, replacer, space, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -556,7 +582,7 @@ }, opts, { | ||
* | ||
* @param {*} obj | ||
* @param {function|string[]} replacer | ||
* @param {Any} obj | ||
* @param {JSONReplacer|string[]} replacer | ||
* @param {number|string} space | ||
* @param {object} opts | ||
* @returns {Promise} Resolves to string | ||
* @returns {Promise<string>} | ||
*/ | ||
@@ -567,3 +593,3 @@ | ||
value: function stringifyAsync(obj, replacer, space, opts) { | ||
return this.stringify(obj, replacer, space, _objectSpread({ | ||
return this.stringify(obj, replacer, space, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -587,3 +613,3 @@ }, opts, { | ||
value: function parse(text, reviver, opts) { | ||
opts = _objectSpread({}, this.options, opts, { | ||
opts = _objectSpread2({}, this.options, {}, opts, { | ||
parse: true | ||
@@ -594,3 +620,3 @@ }); | ||
/** | ||
* Also sync but throws on non-sync result | ||
* Also sync but throws on non-sync result. | ||
* @param {string} text | ||
@@ -606,3 +632,3 @@ * @param {function} reviver This JSON reviver has nothing to do with | ||
value: function parseSync(text, reviver, opts) { | ||
return this.parse(text, reviver, _objectSpread({ | ||
return this.parse(text, reviver, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -624,3 +650,3 @@ }, opts, { | ||
value: function parseAsync(text, reviver, opts) { | ||
return this.parse(text, reviver, _objectSpread({ | ||
return this.parse(text, reviver, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -633,3 +659,3 @@ }, opts, { | ||
* | ||
* @param {*} obj | ||
* @param {Any} obj | ||
* @param {object} stateObj | ||
@@ -649,6 +675,6 @@ * @param {object} [opts={}] | ||
* | ||
* @param {*} obj | ||
* @param {object} stateObj | ||
* @param {object} [opts={}] | ||
* @returns {Promise|Array|object|string|false} | ||
* @param {Any} obj | ||
* @param {PlainObject} stateObj | ||
* @param {PlainObject} [opts={}] | ||
* @returns {Promise|GenericArray|PlainObject|string|false} | ||
*/ | ||
@@ -667,7 +693,7 @@ | ||
* | ||
* This method is used internally by T`ypeson.stringify()`. | ||
* @param {Object} obj - Object to encapsulate. | ||
* @param {object} stateObj | ||
* @param {object} opts | ||
* @returns {Promise|Array|object|string|false} | ||
* This method is used internally by `Typeson.stringify()`. | ||
* @param {Any} obj - Object to encapsulate. | ||
* @param {PlainObject} stateObj | ||
* @param {PlainObject} opts | ||
* @returns {Promise|GenericArray|PlainObject|string|false} | ||
*/ | ||
@@ -678,5 +704,5 @@ | ||
value: function encapsulate(obj, stateObj, opts) { | ||
opts = _objectSpread({ | ||
opts = _objectSpread2({ | ||
sync: true | ||
}, this.options, opts); | ||
}, this.options, {}, opts); | ||
var _opts = opts, | ||
@@ -700,4 +726,4 @@ sync = _opts.sync; | ||
* | ||
* @param {*} ret | ||
* @returns {Array|object|string|false} | ||
* @param {Any} ret | ||
* @returns {GenericArray|PlainObject|string|false} | ||
*/ | ||
@@ -754,113 +780,94 @@ | ||
* | ||
* @param {*} ret | ||
* @param {array} promisesData | ||
* @returns {Promise} Resolves to ... | ||
* @param {Any} ret | ||
* @param {GenericArray} promisesData | ||
* @returns {Promise<Any>} | ||
*/ | ||
function checkPromises(_x, _x2) { | ||
return _checkPromises.apply(this, arguments); | ||
} | ||
/** | ||
* | ||
* @param {object} stateObj | ||
* @param {object} ownKeysObj | ||
* @param {function} cb | ||
* @returns {undefined} | ||
*/ | ||
function checkPromises(ret, promisesData) { | ||
var promResults; | ||
return regeneratorRuntime.async(function checkPromises$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
_context2.next = 2; | ||
return regeneratorRuntime.awrap(Promise.all(promisesData.map(function (pd) { | ||
return pd[1].p; | ||
}))); | ||
case 2: | ||
promResults = _context2.sent; | ||
_context2.next = 5; | ||
return regeneratorRuntime.awrap(Promise.all(promResults.map(function _callee(promResult) { | ||
var newPromisesData, _promisesData$splice, _promisesData$splice2, prData, _prData, keyPath, cyclic, stateObj, parentObj, key, detectedType, encaps, isTypesonPromise, encaps2; | ||
function _checkPromises() { | ||
_checkPromises = _asyncToGenerator( | ||
/*#__PURE__*/ | ||
regeneratorRuntime.mark(function _callee2(ret, promisesData) { | ||
var promResults; | ||
return regeneratorRuntime.wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
_context2.next = 2; | ||
return Promise.all(promisesData.map(function (pd) { | ||
return pd[1].p; | ||
})); | ||
return regeneratorRuntime.async(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
newPromisesData = []; | ||
_promisesData$splice = promisesData.splice(0, 1), _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1), prData = _promisesData$splice2[0]; | ||
_prData = _slicedToArray(prData, 7), keyPath = _prData[0], cyclic = _prData[2], stateObj = _prData[3], parentObj = _prData[4], key = _prData[5], detectedType = _prData[6]; | ||
encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType); | ||
isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself | ||
// returns a `Typeson.Promise` | ||
case 2: | ||
promResults = _context2.sent; | ||
_context2.next = 5; | ||
return Promise.all(promResults.map( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref = _asyncToGenerator( | ||
/*#__PURE__*/ | ||
regeneratorRuntime.mark(function _callee(promResult) { | ||
var newPromisesData, _promisesData$splice, _promisesData$splice2, prData, _prData, keyPath, cyclic, stateObj, parentObj, key, detectedType, encaps, isTypesonPromise, encaps2; | ||
if (!(keyPath && isTypesonPromise)) { | ||
_context.next = 11; | ||
break; | ||
} | ||
return regeneratorRuntime.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
newPromisesData = []; | ||
_promisesData$splice = promisesData.splice(0, 1), _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1), prData = _promisesData$splice2[0]; | ||
_prData = _slicedToArray(prData, 7), keyPath = _prData[0], cyclic = _prData[2], stateObj = _prData[3], parentObj = _prData[4], key = _prData[5], detectedType = _prData[6]; | ||
encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType); | ||
isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself | ||
// returns a `Typeson.Promise` | ||
_context.next = 8; | ||
return regeneratorRuntime.awrap(encaps.p); | ||
if (!(keyPath && isTypesonPromise)) { | ||
_context.next = 11; | ||
break; | ||
} | ||
case 8: | ||
encaps2 = _context.sent; | ||
parentObj[key] = encaps2; | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
_context.next = 8; | ||
return encaps.p; | ||
case 11: | ||
if (keyPath) { | ||
parentObj[key] = encaps; | ||
} else if (isTypesonPromise) { | ||
ret = encaps.p; | ||
} else { | ||
// If this is itself a `Typeson.Promise` (because the | ||
// original value supplied was a `Promise` or | ||
// because the supplied custom type value resolved | ||
// to one), returning it below will be fine since | ||
// a `Promise` is expected anyways given current | ||
// config (and if not a `Promise`, it will be ready | ||
// as the resolve value) | ||
ret = encaps; | ||
} | ||
case 8: | ||
encaps2 = _context.sent; | ||
parentObj[key] = encaps2; | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
case 11: | ||
if (keyPath) { | ||
parentObj[key] = encaps; | ||
} else if (isTypesonPromise) { | ||
ret = encaps.p; | ||
} else { | ||
// If this is itself a `Typeson.Promise` (because the | ||
// original value supplied was a `Promise` or | ||
// because the supplied custom type value resolved | ||
// to one), returning it below will be fine since | ||
// a `Promise` is expected anyways given current | ||
// config (and if not a `Promise`, it will be ready | ||
// as the resolve value) | ||
ret = encaps; | ||
} | ||
case 13: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}); | ||
}))); | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
case 5: | ||
return _context2.abrupt("return", ret); | ||
case 13: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee); | ||
})); | ||
return function (_x3) { | ||
return _ref.apply(this, arguments); | ||
}; | ||
}())); | ||
case 5: | ||
return _context2.abrupt("return", ret); | ||
case 6: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
case 6: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
}, _callee2); | ||
})); | ||
return _checkPromises.apply(this, arguments); | ||
} | ||
}); | ||
} | ||
/** | ||
* | ||
* @param {object} stateObj | ||
* @param {object} ownKeysObj | ||
* @param {function} cb | ||
* @returns {undefined} | ||
*/ | ||
function _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, cb) { | ||
@@ -872,3 +879,4 @@ Object.assign(stateObj, ownKeysObj); | ||
return tmp; | ||
}); | ||
}); // eslint-disable-next-line callback-return | ||
cb(); | ||
@@ -882,9 +890,9 @@ internalStateObjPropsToIgnore.forEach(function (prop, i) { | ||
* @param {string} keypath | ||
* @param {*} value | ||
* @param {Any} value | ||
* @param {boolean} cyclic | ||
* @param {object} stateObj | ||
* @param {PlainObject} stateObj | ||
* @param {boolean} promisesData | ||
* @param {boolean} resolvingTypesonPromise | ||
* @param {string} detectedType | ||
* @returns {*} | ||
* @returns {Any} | ||
*/ | ||
@@ -980,2 +988,3 @@ | ||
} else { | ||
// eslint-disable-next-line no-lonely-if | ||
if (isArr && stateObj.iterateIn !== 'object' || stateObj.iterateIn === 'array') { | ||
@@ -1026,6 +1035,6 @@ clone = new Array(value.length); | ||
var val = _encapsulate(kp, value[key], !!cyclic, stateObj, promisesData, resolvingTypesonPromise); | ||
var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); | ||
if (hasConstructorOf(val, TypesonPromise)) { | ||
promisesData.push([kp, val, !!cyclic, stateObj, clone, key, stateObj.type]); | ||
promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]); | ||
} else if (val !== undefined) { | ||
@@ -1037,2 +1046,3 @@ clone[key] = val; | ||
// eslint-disable-next-line guard-for-in | ||
for (var key in value) { | ||
@@ -1060,6 +1070,6 @@ _loop(key); | ||
_adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () { | ||
var val = _encapsulate(kp, value[key], !!cyclic, stateObj, promisesData, resolvingTypesonPromise); | ||
var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); | ||
if (hasConstructorOf(val, TypesonPromise)) { | ||
promisesData.push([kp, val, !!cyclic, stateObj, clone, key, stateObj.type]); | ||
promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]); | ||
} else if (val !== undefined) { | ||
@@ -1094,6 +1104,6 @@ clone[key] = val; | ||
_adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () { | ||
var val = _encapsulate(kp, undefined, !!cyclic, stateObj, promisesData, resolvingTypesonPromise); | ||
var val = _encapsulate(kp, undefined, Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); | ||
if (hasConstructorOf(val, TypesonPromise)) { | ||
promisesData.push([kp, val, !!cyclic, stateObj, clone, i, stateObj.type]); | ||
promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, i, stateObj.type]); | ||
} else if (val !== undefined) { | ||
@@ -1123,5 +1133,5 @@ clone[i] = val; | ||
* @param {string} keypath | ||
* @param {*} value | ||
* @param {object} stateObj | ||
* @param {array} promisesData | ||
* @param {Any} value | ||
* @param {PlainObject} stateObj | ||
* @param {GenericArray} promisesData | ||
* @param {boolean} plainObject | ||
@@ -1200,3 +1210,3 @@ * @param {boolean} resolvingTypesonPromise | ||
/** | ||
* Also sync but throws on non-sync result | ||
* Also sync but throws on non-sync result. | ||
* @param {*} obj | ||
@@ -1211,3 +1221,3 @@ * @param {object} stateObj | ||
value: function encapsulateSync(obj, stateObj, opts) { | ||
return this.encapsulate(obj, stateObj, _objectSpread({ | ||
return this.encapsulate(obj, stateObj, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -1228,3 +1238,3 @@ }, opts, { | ||
value: function encapsulateAsync(obj, stateObj, opts) { | ||
return this.encapsulate(obj, stateObj, _objectSpread({ | ||
return this.encapsulate(obj, stateObj, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -1261,5 +1271,5 @@ }, opts, { | ||
opts = _objectSpread({ | ||
opts = _objectSpread2({ | ||
sync: true | ||
}, this.options, opts); | ||
}, this.options, {}, opts); | ||
var _opts3 = opts, | ||
@@ -1280,2 +1290,6 @@ sync = _opts3.sync; | ||
var that = this; | ||
/** | ||
* | ||
* @returns {void|TypesonPromise<void>} | ||
*/ | ||
@@ -1286,6 +1300,6 @@ function revivePlainObjects() { | ||
var plainObjectTypes = []; | ||
Object.entries(types).forEach(function (_ref2) { | ||
var _ref3 = _slicedToArray(_ref2, 2), | ||
keypath = _ref3[0], | ||
type = _ref3[1]; | ||
Object.entries(types).forEach(function (_ref) { | ||
var _ref2 = _slicedToArray(_ref, 2), | ||
keypath = _ref2[0], | ||
type = _ref2[1]; | ||
@@ -1320,4 +1334,10 @@ if (type === '#') { | ||
if (!plainObjectTypes.length) { | ||
return; | ||
} // Handle plain object revivers first so reference | ||
return undefined; | ||
} | ||
/** | ||
* @typedef {PlainObject} PlainObjectType | ||
* @property {string} keypath | ||
* @property {string} type | ||
*/ | ||
// Handle plain object revivers first so reference | ||
// setting can use revived type (e.g., array instead | ||
@@ -1328,5 +1348,5 @@ // of object); assumes revived has same structure | ||
return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref4) { | ||
var keypath = _ref4.keypath, | ||
type = _ref4.type; | ||
return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref3) { | ||
var keypath = _ref3.keypath, | ||
type = _ref3.type; | ||
@@ -1380,7 +1400,7 @@ if (hasConstructorOf(possibleTypesonPromise, TypesonPromise)) { | ||
* @param {string} keypath | ||
* @param {*} value | ||
* @param {Any} value | ||
* @param {?(Array|object)} target | ||
* @param {Array|object} [clone] | ||
* @param {string} [key] | ||
* @returns {*} | ||
* @returns {Any} | ||
*/ | ||
@@ -1465,3 +1485,9 @@ | ||
} | ||
/** | ||
* | ||
* @param {Any} retrn | ||
* @returns {undefined|Any} | ||
*/ | ||
function checkUndefined(retrn) { | ||
@@ -1489,6 +1515,6 @@ return hasConstructorOf(retrn, Undefined) ? undefined : retrn; | ||
/** | ||
* Also sync but throws on non-sync result | ||
* @param {*} obj | ||
* Also sync but throws on non-sync result. | ||
* @param {Any} obj | ||
* @param {object} opts | ||
* @returns {*} | ||
* @returns {Any} | ||
*/ | ||
@@ -1499,3 +1525,3 @@ | ||
value: function reviveSync(obj, opts) { | ||
return this.revive(obj, _objectSpread({ | ||
return this.revive(obj, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -1507,3 +1533,3 @@ }, opts, { | ||
/** | ||
* @param {*} obj | ||
* @param {Any} obj | ||
* @param {object} opts | ||
@@ -1516,3 +1542,3 @@ * @returns {Promise} Resolves to `*` | ||
value: function reviveAsync(obj, opts) { | ||
return this.revive(obj, _objectSpread({ | ||
return this.revive(obj, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -1526,4 +1552,4 @@ }, opts, { | ||
* For examples on how to use this method, see | ||
* {@link https://github.com/dfahlander/typeson-registry/tree/master/types} | ||
* @param {Array.<Object.<string,Function[]>>} typeSpecSets - Types and | ||
* {@link https://github.com/dfahlander/typeson-registry/tree/master/types}. | ||
* @param {object.<string,Function[]>[]} typeSpecSets - Types and | ||
* their functions [test, encapsulate, revive]; | ||
@@ -1539,5 +1565,9 @@ * @param {object} opts | ||
[].concat(typeSpecSets).forEach(function R(typeSpec) { | ||
var _this = this; | ||
// Allow arrays of arrays of arrays... | ||
if (isArray(typeSpec)) { | ||
return typeSpec.map(R, this); | ||
return typeSpec.map(function (typSpec) { | ||
return R.call(_this, typSpec); | ||
}); | ||
} | ||
@@ -1577,3 +1607,3 @@ | ||
replace: function replace(x) { | ||
return Object.assign({}, x); | ||
return _objectSpread2({}, x); | ||
}, | ||
@@ -1650,3 +1680,3 @@ revive: function revive(x) { | ||
* with `hasConstructorOf`. | ||
* @constructor | ||
* @class | ||
*/ | ||
@@ -1658,6 +1688,7 @@ | ||
}; // eslint-disable-line space-before-blocks | ||
// The following provide classes meant to avoid clashes with other values | ||
Undefined.__typeson__type__ = 'TypesonUndefined'; // The following provide classes meant to avoid clashes with other values | ||
// To insist `undefined` should be added | ||
Typeson.Undefined = Undefined; // To support async encapsulation/stringification | ||
@@ -1664,0 +1695,0 @@ |
@@ -1,1 +0,1 @@ | ||
function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function asyncGeneratorStep(e,t,n,r,i,a,c){try{var o=e[a](c),s=o.value}catch(e){return void n(e)}o.done?t(s):Promise.resolve(s).then(r,i)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var a=e.apply(t,n);function _next(e){asyncGeneratorStep(a,r,i,_next,_throw,"next",e)}function _throw(e){asyncGeneratorStep(a,r,i,_next,_throw,"throw",e)}_next(void 0)})}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _objectSpread(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){_defineProperty(e,t,n[t])})}return e}function _slicedToArray(e,t){return function _arrayWithHoles(e){if(Array.isArray(e))return e}(e)||function _iterableToArrayLimit(e,t){var n=[],r=!0,i=!1,a=void 0;try{for(var c,o=e[Symbol.iterator]();!(r=(c=o.next()).done)&&(n.push(c.value),!t||n.length!==t);r=!0);}catch(e){i=!0,a=e}finally{try{r||null==o.return||o.return()}finally{if(i)throw a}}return n}(e,t)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function _toConsumableArray(e){return function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}(e)||function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var e=function TypesonPromise(e){_classCallCheck(this,TypesonPromise),this.p=new Promise(e)};"undefined"!=typeof Symbol&&(e.prototype[Symbol.toStringTag]="TypesonPromise"),e.prototype.then=function(t,n){var r=this;return new e(function(e,i){r.p.then(function(n){e(t?t(n):n)},function(t){r.p.catch(function(e){return n?n(e):Promise.reject(e)}).then(e,i)})})},e.prototype.catch=function(e){return this.then(null,e)},e.resolve=function(t){return new e(function(e){e(t)})},e.reject=function(t){return new e(function(e,n){n(t)})},["all","race"].map(function(t){e[t]=function(n){return new e(function(e,r){Promise[t](n.map(function(e){return e.p})).then(e,r)})}});var t={}.toString,n={}.hasOwnProperty,r=Object.getPrototypeOf,i=n.toString;function isThenable(e,t){return isObject(e)&&"function"==typeof e.then&&(!t||"function"==typeof e.catch)}function toStringTag(e){return t.call(e).slice(8,-1)}function hasConstructorOf(e,t){if(!e||"object"!==_typeof(e))return!1;var a=r(e);if(!a)return!1;var c=n.call(a,"constructor")&&a.constructor;return"function"!=typeof c?null===t:"function"==typeof c&&null!==t&&i.call(c)===i.call(t)}function isPlainObject(e){return!(!e||"Object"!==toStringTag(e))&&(!r(e)||hasConstructorOf(e,Object))}function isObject(e){return e&&"object"===_typeof(e)}function escapeKeyPathComponent(e){return e.replace(/~/g,"~0").replace(/\./g,"~1")}function unescapeKeyPathComponent(e){return e.replace(/~1/g,".").replace(/~0/g,"~")}function getByKeyPath(e,t){if(""===t)return e;var n=t.indexOf(".");if(n>-1){var r=e[unescapeKeyPathComponent(t.substr(0,n))];return void 0===r?void 0:getByKeyPath(r,t.substr(n+1))}return e[unescapeKeyPathComponent(t)]}var a=Object.keys,c=Array.isArray,o={}.hasOwnProperty,s=["type","replaced","iterateIn","iterateUnsetNumeric"];function nestedPathsFirst(e,t){var n=e.keypath.match(/\./g),r=e.keypath.match(/\./g);return n&&(n=n.length),r&&(r=r.length),n>r?-1:n<r?1:e.keypath<t.keypath?-1:e.keypath>t.keypath}var u=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={}}return function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}(Typeson,[{key:"stringify",value:function stringify(e,t,n,r){r=_objectSpread({},this.options,r,{stringification:!0});var i=this.encapsulate(e,null,r);return c(i)?JSON.stringify(i[0],t,n):i.then(function(e){return JSON.stringify(e,t,n)})}},{key:"stringifySync",value:function stringifySync(e,t,n,r){return this.stringify(e,t,n,_objectSpread({throwOnBadSyncType:!0},r,{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,n,r){return this.stringify(e,t,n,_objectSpread({throwOnBadSyncType:!0},r,{sync:!1}))}},{key:"parse",value:function parse(e,t,n){return n=_objectSpread({},this.options,n,{parse:!0}),this.revive(JSON.parse(e,t),n)}},{key:"parseSync",value:function parseSync(e,t,n){return this.parse(e,t,_objectSpread({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,n){return this.parse(e,t,_objectSpread({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.returnTypeNames=!0,this.encapsulate(e,t,n)}},{key:"rootTypeName",value:function rootTypeName(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.iterateNone=!0,this.encapsulate(e,t,n)}},{key:"encapsulate",value:function encapsulate(t,n,r){var i=(r=_objectSpread({sync:!0},this.options,r)).sync,u=this,p={},l=[],y=[],f=[],h=!("cyclic"in r)||r.cyclic,v=r.encapsulateObserver,d=_encapsulate("",t,h,n||{},f);function finish(e){var t=Object.values(p);if(r.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(r.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!o.call(e,"$types")?e.$types=p:e={$:e,$types:{$:p}}}else isObject(e)&&o.call(e,"$types")&&(e={$:e,$types:!0});return!r.returnTypeNames&&e}function checkPromises(e,t){return _checkPromises.apply(this,arguments)}function _checkPromises(){return(_checkPromises=_asyncToGenerator(regeneratorRuntime.mark(function _callee2(t,n){var r;return regeneratorRuntime.wrap(function _callee2$(i){for(;;)switch(i.prev=i.next){case 0:return i.next=2,Promise.all(n.map(function(e){return e[1].p}));case 2:return r=i.sent,i.next=5,Promise.all(r.map(function(){var r=_asyncToGenerator(regeneratorRuntime.mark(function _callee(r){var i,a,c,o,s,u,p,l,y,f,h,v,d,b;return regeneratorRuntime.wrap(function _callee$(O){for(;;)switch(O.prev=O.next){case 0:if(i=[],a=n.splice(0,1),c=_slicedToArray(a,1),o=c[0],s=_slicedToArray(o,7),u=s[0],p=s[2],l=s[3],y=s[4],f=s[5],h=s[6],v=_encapsulate(u,r,p,l,i,!0,h),d=hasConstructorOf(v,e),!u||!d){O.next=11;break}return O.next=8,v.p;case 8:return b=O.sent,y[f]=b,O.abrupt("return",checkPromises(t,i));case 11:return u?y[f]=v:t=d?v.p:v,O.abrupt("return",checkPromises(t,i));case 13:case"end":return O.stop()}},_callee)}));return function(e){return r.apply(this,arguments)}}()));case 5:return i.abrupt("return",t);case 6:case"end":return i.stop()}},_callee2)}))).apply(this,arguments)}function _adaptBuiltinStateObjectProperties(e,t,n){Object.assign(e,t);var r=s.map(function(t){var n=e[t];return delete e[t],n});n(),s.forEach(function(t,n){e[t]=r[n]})}function _encapsulate(t,n,i,s,f,h,d){var b,O={},m=_typeof(n),g=v?function(r){var a=d||s.type||Typeson.getJSONType(n);v(Object.assign(r||O,{keypath:t,value:n,cyclic:i,stateObj:s,promisesData:f,resolvingTypesonPromise:h,awaitingTypesonPromise:hasConstructorOf(n,e)},void 0!==a?{type:a}:{}))}:null;if(["string","boolean","number","undefined"].includes(m))return void 0===n||"number"===m&&(isNaN(n)||n===-1/0||n===1/0)?(b=replace(t,n,s,f,!1,h,g))!==n&&(O={replaced:b}):b=n,g&&g(),b;if(null===n)return g&&g(),n;if(i&&!s.iterateIn&&!s.iterateUnsetNumeric){var _=l.indexOf(n);if(!(_<0))return p[t]="#",g&&g({cyclicKeypath:y[_]}),"#"+y[_];!0===i&&(l.push(n),y.push(t))}var j,P=isPlainObject(n),S=c(n),T=(P||S)&&(!u.plainObjectReplacers.length||s.replaced)||s.iterateIn?n:replace(t,n,s,f,P||S,null,g);if(T!==n?(b=T,O={replaced:T}):S&&"object"!==s.iterateIn||"array"===s.iterateIn?(j=new Array(n.length),O={clone:j}):P||"object"===s.iterateIn?(j={},s.addLength&&(j.length=n.length),O={clone:j}):""===t&&hasConstructorOf(n,e)?(f.push([t,n,i,s,void 0,void 0,s.type]),b=n):b=n,g&&g(),r.iterateNone)return j||b;if(!j)return b;if(s.iterateIn){var w=function _loop(r){var a={ownKeys:o.call(n,r)};_adaptBuiltinStateObjectProperties(s,a,function(){var a=t+(t?".":"")+escapeKeyPathComponent(r),c=_encapsulate(a,n[r],!!i,s,f,h);hasConstructorOf(c,e)?f.push([a,c,!!i,s,j,r,s.type]):void 0!==c&&(j[r]=c)})};for(var A in n)w(A);g&&g({endIterateIn:!0,end:!0})}else a(n).forEach(function(r){var a=t+(t?".":"")+escapeKeyPathComponent(r);_adaptBuiltinStateObjectProperties(s,{ownKeys:!0},function(){var t=_encapsulate(a,n[r],!!i,s,f,h);hasConstructorOf(t,e)?f.push([a,t,!!i,s,j,r,s.type]):void 0!==t&&(j[r]=t)})}),g&&g({endIterateOwn:!0,end:!0});if(s.iterateUnsetNumeric){for(var k=n.length,C=function _loop2(r){if(!(r in n)){var a=t+(t?".":"")+r;_adaptBuiltinStateObjectProperties(s,{ownKeys:!1},function(){var t=_encapsulate(a,void 0,!!i,s,f,h);hasConstructorOf(t,e)?f.push([a,t,!!i,s,j,r,s.type]):void 0!==t&&(j[r]=t)})}},K=0;K<k;K++)C(K);g&&g({endIterateUnsetNumeric:!0,end:!0})}return j}function replace(e,t,n,r,a,c,o){for(var s=a?u.plainObjectReplacers:u.nonplainObjectReplacers,l=s.length;l--;){var y=s[l];if(y.test(t,n)){var f=y.type;if(u.revivers[f]){var v=p[e];p[e]=v?[f].concat(v):f}return Object.assign(n,{type:f,replaced:!0}),!i&&y.replaceAsync||y.replace?(o&&o({replacing:!0}),_encapsulate(e,y[i||!y.replaceAsync?"replace":"replaceAsync"](t,n),h&&"readonly",n,r,c,f)):(o&&o({typeDetected:!0}),_encapsulate(e,t,h&&"readonly",n,r,c,f))}}return t}return f.length?i&&r.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(checkPromises(d,f)).then(finish):!i&&r.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():r.stringification&&i?[finish(d)]:i?finish(d):Promise.resolve(finish(d))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,n){return this.encapsulate(e,t,_objectSpread({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,n){return this.encapsulate(e,t,_objectSpread({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"revive",value:function revive(t,n){var r=t&&t.$types;if(!r)return t;if(!0===r)return t.$;var i=(n=_objectSpread({sync:!0},this.options,n)).sync,o=[],s={},u=!0;r.$&&isPlainObject(r.$)&&(t=t.$,r=r.$,u=!1);var l=this;function _revive(t,n,y,f,h){if(!u||"$types"!==t){var v=r[t];if(c(n)||isPlainObject(n)){var d=c(n)?new Array(n.length):{};for(a(n).forEach(function(e){var r=_revive(t+(t?".":"")+escapeKeyPathComponent(e),n[e],y||d,d,e);hasConstructorOf(r,p)?d[e]=void 0:void 0!==r&&(d[e]=r)}),n=d;o.length;){var b=_slicedToArray(o[0],4),O=b[0],m=b[1],g=b[2],_=b[3],j=getByKeyPath(O,m);if(hasConstructorOf(j,p))g[_]=void 0;else{if(void 0===j)break;g[_]=j}o.splice(0,1)}}if(!v)return n;if("#"===v){var P=getByKeyPath(y,n.slice(1));return void 0===P&&o.push([y,n.slice(1),f,h]),P}return[].concat(v).reduce(function reducer(t,n){if(hasConstructorOf(t,e))return t.then(function(e){return reducer(e,n)});var r=_slicedToArray(l.revivers[n],1)[0];if(!r)throw new Error("Unregistered type: "+n);return r[i&&r.revive?"revive":!i&&r.reviveAsync?"reviveAsync":"revive"](t,s)},n)}}function checkUndefined(e){return hasConstructorOf(e,p)?void 0:e}var y,f=function revivePlainObjects(){var n=[];if(Object.entries(r).forEach(function(e){var t=_slicedToArray(e,2),i=t[0],a=t[1];"#"!==a&&[].concat(a).forEach(function(e){_slicedToArray(l.revivers[e],2)[1].plain&&(n.push({keypath:i,type:e}),delete r[i])})}),n.length)return n.sort(nestedPathsFirst).reduce(function reducer(n,r){var a=r.keypath,c=r.type;if(hasConstructorOf(n,e))return n.then(function(e){return reducer(e,c)});var o=getByKeyPath(t,a);if(hasConstructorOf(o,e))return o.then(function(e){return reducer(e,c)});var u=_slicedToArray(l.revivers[c],1)[0];if(!u)throw new Error("Unregistered type: "+c);void 0!==(o=u[i&&u.revive?"revive":!i&&u.reviveAsync?"reviveAsync":"revive"](o,s))&&(hasConstructorOf(o,p)&&(o=void 0),function setAtKeyPath(e,t,n){if(""===t)return n;var r=t.indexOf(".");return r>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.substr(0,r))],t.substr(r+1),n):(e[unescapeKeyPathComponent(t)]=n,e)}(t,a,o)===o&&(t=o))},void 0)}();return isThenable(y=hasConstructorOf(f,e)?f.then(function(){return _revive("",t,null)}):_revive("",t,null))?i&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(y,e)?y.p.then(checkUndefined):y:!i&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():i?checkUndefined(y):Promise.resolve(checkUndefined(y))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread({throwOnBadSyncType:!0},t,{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread({throwOnBadSyncType:!0},t,{sync:!1}))}},{key:"register",value:function register(e,t){return t=t||{},[].concat(e).forEach(function R(e){if(c(e))return e.map(R,this);e&&a(e).forEach(function(n){if("#"===n)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(Typeson.JSON_TYPES.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var r=e[n],i=r.testPlainObjects?this.plainObjectReplacers:this.nonplainObjectReplacers,a=i.filter(function(e){return e.type===n});if(a.length&&(i.splice(i.indexOf(a[0]),1),delete this.revivers[n],delete this.types[n]),r){if("function"==typeof r){var o=r;r={test:function test(e){return e&&e.constructor===o},replace:function replace(e){return Object.assign({},e)},revive:function revive(e){return Object.assign(Object.create(o.prototype),e)}}}else if(c(r)){var s=_slicedToArray(r,3);r={test:s[0],replace:s[1],revive:s[2]}}var u={type:n,test:r.test.bind(r)};r.replace&&(u.replace=r.replace.bind(r)),r.replaceAsync&&(u.replaceAsync=r.replaceAsync.bind(r));var p="number"==typeof t.fallback?t.fallback:t.fallback?0:1/0;if(r.testPlainObjects?this.plainObjectReplacers.splice(p,0,u):this.nonplainObjectReplacers.splice(p,0,u),r.revive||r.reviveAsync){var l={};r.revive&&(l.revive=r.revive.bind(r)),r.reviveAsync&&(l.reviveAsync=r.reviveAsync.bind(r)),this.revivers[n]=[l,{plain:r.testPlainObjects}]}this.types[n]=r}},this)},this),this}}]),Typeson}(),p=function Undefined(){_classCallCheck(this,Undefined)};u.Undefined=p,u.Promise=e,u.isThenable=isThenable,u.toStringTag=toStringTag,u.hasConstructorOf=hasConstructorOf,u.isObject=isObject,u.isPlainObject=isPlainObject,u.isUserObject=function isUserObject(e){if(!e||"Object"!==toStringTag(e))return!1;var t=r(e);return!t||hasConstructorOf(e,Object)||isUserObject(t)},u.escapeKeyPathComponent=escapeKeyPathComponent,u.unescapeKeyPathComponent=unescapeKeyPathComponent,u.getByKeyPath=getByKeyPath,u.getJSONType=function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)},u.JSON_TYPES=["null","boolean","number","string","array","object"];export default u; | ||
function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(n),!0).forEach((function(t){_defineProperty(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ownKeys(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function _slicedToArray(e,t){return function _arrayWithHoles(e){if(Array.isArray(e))return e}(e)||function _iterableToArrayLimit(e,t){if(!(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)))return;var n=[],r=!0,i=!1,a=void 0;try{for(var o,c=e[Symbol.iterator]();!(r=(o=c.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,a=e}finally{try{r||null==c.return||c.return()}finally{if(i)throw a}}return n}(e,t)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function _toConsumableArray(e){return function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}(e)||function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var e=function TypesonPromise(e){_classCallCheck(this,TypesonPromise),this.p=new Promise(e)};e.__typeson__type__="TypesonPromise","undefined"!=typeof Symbol&&(e.prototype[Symbol.toStringTag]="TypesonPromise"),e.prototype.then=function(t,n){var r=this;return new e((function(e,i){r.p.then((function(n){e(t?t(n):n)})).catch((function(e){return n?n(e):Promise.reject(e)})).then(e,i)}))},e.prototype.catch=function(e){return this.then(null,e)},e.resolve=function(t){return new e((function(e){e(t)}))},e.reject=function(t){return new e((function(e,n){n(t)}))},["all","race"].forEach((function(t){e[t]=function(n){return new e((function(e,r){Promise[t](n.map((function(e){return e.p}))).then(e,r)}))}}));var t={}.toString,n={}.hasOwnProperty,r=Object.getPrototypeOf,i=n.toString;function isThenable(e,t){return isObject(e)&&"function"==typeof e.then&&(!t||"function"==typeof e.catch)}function toStringTag(e){return t.call(e).slice(8,-1)}function hasConstructorOf(e,t){if(!e||"object"!==_typeof(e))return!1;var a=r(e);if(!a)return!1;var o=n.call(a,"constructor")&&a.constructor;return"function"!=typeof o?null===t:t===o||(null!==t&&i.call(o)===i.call(t)||"function"==typeof t&&"string"==typeof o.__typeson__type__&&o.__typeson__type__===t.__typeson__type__)}function isPlainObject(e){return!(!e||"Object"!==toStringTag(e))&&(!r(e)||hasConstructorOf(e,Object))}function isObject(e){return e&&"object"===_typeof(e)}function escapeKeyPathComponent(e){return e.replace(/~/g,"~0").replace(/\./g,"~1")}function unescapeKeyPathComponent(e){return e.replace(/~1/g,".").replace(/~0/g,"~")}function getByKeyPath(e,t){if(""===t)return e;var n=t.indexOf(".");if(n>-1){var r=e[unescapeKeyPathComponent(t.slice(0,n))];return void 0===r?void 0:getByKeyPath(r,t.slice(n+1))}return e[unescapeKeyPathComponent(t)]}var a=Object.keys,o=Array.isArray,c={}.hasOwnProperty,s=["type","replaced","iterateIn","iterateUnsetNumeric"];function nestedPathsFirst(e,t){var n=e.keypath.match(/\./g),r=e.keypath.match(/\./g);return n&&(n=n.length),r&&(r=r.length),n>r?-1:n<r?1:e.keypath<t.keypath?-1:e.keypath>t.keypath}var u=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={}}return function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}(Typeson,[{key:"stringify",value:function stringify(e,t,n,r){r=_objectSpread2({},this.options,{},r,{stringification:!0});var i=this.encapsulate(e,null,r);return o(i)?JSON.stringify(i[0],t,n):i.then((function(e){return JSON.stringify(e,t,n)}))}},{key:"stringifySync",value:function stringifySync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!1}))}},{key:"parse",value:function parse(e,t,n){return n=_objectSpread2({},this.options,{},n,{parse:!0}),this.revive(JSON.parse(e,t),n)}},{key:"parseSync",value:function parseSync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.returnTypeNames=!0,this.encapsulate(e,t,n)}},{key:"rootTypeName",value:function rootTypeName(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.iterateNone=!0,this.encapsulate(e,t,n)}},{key:"encapsulate",value:function encapsulate(t,n,r){var i=(r=_objectSpread2({sync:!0},this.options,{},r)).sync,u=this,p={},y=[],l=[],f=[],h=!("cyclic"in r)||r.cyclic,v=r.encapsulateObserver,d=_encapsulate("",t,h,n||{},f);function finish(e){var t=Object.values(p);if(r.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(r.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!c.call(e,"$types")?e.$types=p:e={$:e,$types:{$:p}}}else isObject(e)&&c.call(e,"$types")&&(e={$:e,$types:!0});return!r.returnTypeNames&&e}function _adaptBuiltinStateObjectProperties(e,t,n){Object.assign(e,t);var r=s.map((function(t){var n=e[t];return delete e[t],n}));n(),s.forEach((function(t,n){e[t]=r[n]}))}function _encapsulate(t,n,i,s,f,h,d){var b,O={},_=_typeof(n),g=v?function(r){var a=d||s.type||Typeson.getJSONType(n);v(Object.assign(r||O,{keypath:t,value:n,cyclic:i,stateObj:s,promisesData:f,resolvingTypesonPromise:h,awaitingTypesonPromise:hasConstructorOf(n,e)},void 0!==a?{type:a}:{}))}:null;if(["string","boolean","number","undefined"].includes(_))return void 0===n||"number"===_&&(isNaN(n)||n===-1/0||n===1/0)?(b=replace(t,n,s,f,!1,h,g))!==n&&(O={replaced:b}):b=n,g&&g(),b;if(null===n)return g&&g(),n;if(i&&!s.iterateIn&&!s.iterateUnsetNumeric){var m=y.indexOf(n);if(!(m<0))return p[t]="#",g&&g({cyclicKeypath:l[m]}),"#"+l[m];!0===i&&(y.push(n),l.push(t))}var j,P=isPlainObject(n),S=o(n),T=(P||S)&&(!u.plainObjectReplacers.length||s.replaced)||s.iterateIn?n:replace(t,n,s,f,P||S,null,g);if(T!==n?(b=T,O={replaced:T}):S&&"object"!==s.iterateIn||"array"===s.iterateIn?(j=new Array(n.length),O={clone:j}):P||"object"===s.iterateIn?(j={},s.addLength&&(j.length=n.length),O={clone:j}):""===t&&hasConstructorOf(n,e)?(f.push([t,n,i,s,void 0,void 0,s.type]),b=n):b=n,g&&g(),r.iterateNone)return j||b;if(!j)return b;if(s.iterateIn){var w=function _loop(r){var a={ownKeys:c.call(n,r)};_adaptBuiltinStateObjectProperties(s,a,(function(){var a=t+(t?".":"")+escapeKeyPathComponent(r),o=_encapsulate(a,n[r],Boolean(i),s,f,h);hasConstructorOf(o,e)?f.push([a,o,Boolean(i),s,j,r,s.type]):void 0!==o&&(j[r]=o)}))};for(var A in n)w(A);g&&g({endIterateIn:!0,end:!0})}else a(n).forEach((function(r){var a=t+(t?".":"")+escapeKeyPathComponent(r);_adaptBuiltinStateObjectProperties(s,{ownKeys:!0},(function(){var t=_encapsulate(a,n[r],Boolean(i),s,f,h);hasConstructorOf(t,e)?f.push([a,t,Boolean(i),s,j,r,s.type]):void 0!==t&&(j[r]=t)}))})),g&&g({endIterateOwn:!0,end:!0});if(s.iterateUnsetNumeric){for(var C=n.length,k=function _loop2(r){if(!(r in n)){var a=t+(t?".":"")+r;_adaptBuiltinStateObjectProperties(s,{ownKeys:!1},(function(){var t=_encapsulate(a,void 0,Boolean(i),s,f,h);hasConstructorOf(t,e)?f.push([a,t,Boolean(i),s,j,r,s.type]):void 0!==t&&(j[r]=t)}))}},B=0;B<C;B++)k(B);g&&g({endIterateUnsetNumeric:!0,end:!0})}return j}function replace(e,t,n,r,a,o,c){for(var s=a?u.plainObjectReplacers:u.nonplainObjectReplacers,y=s.length;y--;){var l=s[y];if(l.test(t,n)){var f=l.type;if(u.revivers[f]){var v=p[e];p[e]=v?[f].concat(v):f}return Object.assign(n,{type:f,replaced:!0}),!i&&l.replaceAsync||l.replace?(c&&c({replacing:!0}),_encapsulate(e,l[i||!l.replaceAsync?"replace":"replaceAsync"](t,n),h&&"readonly",n,r,o,f)):(c&&c({typeDetected:!0}),_encapsulate(e,t,h&&"readonly",n,r,o,f))}}return t}return f.length?i&&r.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(function checkPromises(t,n){var r;return regeneratorRuntime.async((function checkPromises$(i){for(;;)switch(i.prev=i.next){case 0:return i.next=2,regeneratorRuntime.awrap(Promise.all(n.map((function(e){return e[1].p}))));case 2:return r=i.sent,i.next=5,regeneratorRuntime.awrap(Promise.all(r.map((function _callee(r){var i,a,o,c,s,u,p,y,l,f,h,v,d,b;return regeneratorRuntime.async((function _callee$(O){for(;;)switch(O.prev=O.next){case 0:if(i=[],a=n.splice(0,1),o=_slicedToArray(a,1),c=o[0],s=_slicedToArray(c,7),u=s[0],p=s[2],y=s[3],l=s[4],f=s[5],h=s[6],v=_encapsulate(u,r,p,y,i,!0,h),d=hasConstructorOf(v,e),!u||!d){O.next=11;break}return O.next=8,regeneratorRuntime.awrap(v.p);case 8:return b=O.sent,l[f]=b,O.abrupt("return",checkPromises(t,i));case 11:return u?l[f]=v:t=d?v.p:v,O.abrupt("return",checkPromises(t,i));case 13:case"end":return O.stop()}}))}))));case 5:return i.abrupt("return",t);case 6:case"end":return i.stop()}}))}(d,f)).then(finish):!i&&r.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():r.stringification&&i?[finish(d)]:i?finish(d):Promise.resolve(finish(d))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"revive",value:function revive(t,n){var r=t&&t.$types;if(!r)return t;if(!0===r)return t.$;var i=(n=_objectSpread2({sync:!0},this.options,{},n)).sync,c=[],s={},u=!0;r.$&&isPlainObject(r.$)&&(t=t.$,r=r.$,u=!1);var y=this;function _revive(t,n,l,f,h){if(!u||"$types"!==t){var v=r[t];if(o(n)||isPlainObject(n)){var d=o(n)?new Array(n.length):{};for(a(n).forEach((function(e){var r=_revive(t+(t?".":"")+escapeKeyPathComponent(e),n[e],l||d,d,e);hasConstructorOf(r,p)?d[e]=void 0:void 0!==r&&(d[e]=r)})),n=d;c.length;){var b=_slicedToArray(c[0],4),O=b[0],_=b[1],g=b[2],m=b[3],j=getByKeyPath(O,_);if(hasConstructorOf(j,p))g[m]=void 0;else{if(void 0===j)break;g[m]=j}c.splice(0,1)}}if(!v)return n;if("#"===v){var P=getByKeyPath(l,n.slice(1));return void 0===P&&c.push([l,n.slice(1),f,h]),P}return[].concat(v).reduce((function reducer(t,n){if(hasConstructorOf(t,e))return t.then((function(e){return reducer(e,n)}));var r=_slicedToArray(y.revivers[n],1)[0];if(!r)throw new Error("Unregistered type: "+n);return r[i&&r.revive?"revive":!i&&r.reviveAsync?"reviveAsync":"revive"](t,s)}),n)}}function checkUndefined(e){return hasConstructorOf(e,p)?void 0:e}var l,f=function revivePlainObjects(){var n=[];if(Object.entries(r).forEach((function(e){var t=_slicedToArray(e,2),i=t[0],a=t[1];"#"!==a&&[].concat(a).forEach((function(e){_slicedToArray(y.revivers[e],2)[1].plain&&(n.push({keypath:i,type:e}),delete r[i])}))})),n.length)return n.sort(nestedPathsFirst).reduce((function reducer(n,r){var a=r.keypath,o=r.type;if(hasConstructorOf(n,e))return n.then((function(e){return reducer(e,o)}));var c=getByKeyPath(t,a);if(hasConstructorOf(c,e))return c.then((function(e){return reducer(e,o)}));var u=_slicedToArray(y.revivers[o],1)[0];if(!u)throw new Error("Unregistered type: "+o);void 0!==(c=u[i&&u.revive?"revive":!i&&u.reviveAsync?"reviveAsync":"revive"](c,s))&&(hasConstructorOf(c,p)&&(c=void 0),function setAtKeyPath(e,t,n){if(""===t)return n;var r=t.indexOf(".");return r>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,r))],t.slice(r+1),n):(e[unescapeKeyPathComponent(t)]=n,e)}(t,a,c)===c&&(t=c))}),void 0)}();return isThenable(l=hasConstructorOf(f,e)?f.then((function(){return _revive("",t,null)})):_revive("",t,null))?i&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(l,e)?l.p.then(checkUndefined):l:!i&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():i?checkUndefined(l):Promise.resolve(checkUndefined(l))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!1}))}},{key:"register",value:function register(e,t){return t=t||{},[].concat(e).forEach((function R(e){var n=this;if(o(e))return e.map((function(e){return R.call(n,e)}));e&&a(e).forEach((function(n){if("#"===n)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(Typeson.JSON_TYPES.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var r=e[n],i=r.testPlainObjects?this.plainObjectReplacers:this.nonplainObjectReplacers,a=i.filter((function(e){return e.type===n}));if(a.length&&(i.splice(i.indexOf(a[0]),1),delete this.revivers[n],delete this.types[n]),r){if("function"==typeof r){var c=r;r={test:function test(e){return e&&e.constructor===c},replace:function replace(e){return _objectSpread2({},e)},revive:function revive(e){return Object.assign(Object.create(c.prototype),e)}}}else if(o(r)){var s=_slicedToArray(r,3);r={test:s[0],replace:s[1],revive:s[2]}}var u={type:n,test:r.test.bind(r)};r.replace&&(u.replace=r.replace.bind(r)),r.replaceAsync&&(u.replaceAsync=r.replaceAsync.bind(r));var p="number"==typeof t.fallback?t.fallback:t.fallback?0:1/0;if(r.testPlainObjects?this.plainObjectReplacers.splice(p,0,u):this.nonplainObjectReplacers.splice(p,0,u),r.revive||r.reviveAsync){var y={};r.revive&&(y.revive=r.revive.bind(r)),r.reviveAsync&&(y.reviveAsync=r.reviveAsync.bind(r)),this.revivers[n]=[y,{plain:r.testPlainObjects}]}this.types[n]=r}}),this)}),this),this}}]),Typeson}(),p=function Undefined(){_classCallCheck(this,Undefined)};p.__typeson__type__="TypesonUndefined",u.Undefined=p,u.Promise=e,u.isThenable=isThenable,u.toStringTag=toStringTag,u.hasConstructorOf=hasConstructorOf,u.isObject=isObject,u.isPlainObject=isPlainObject,u.isUserObject=function isUserObject(e){if(!e||"Object"!==toStringTag(e))return!1;var t=r(e);return!t||(hasConstructorOf(e,Object)||isUserObject(t))},u.escapeKeyPathComponent=escapeKeyPathComponent,u.unescapeKeyPathComponent=unescapeKeyPathComponent,u.getByKeyPath=getByKeyPath,u.getJSONType=function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)},u.JSON_TYPES=["null","boolean","number","string","array","object"];export default u; |
@@ -5,3 +5,3 @@ (function (global, factory) { | ||
(global = global || self, global.Typeson = factory()); | ||
}(this, function () { 'use strict'; | ||
}(this, (function () { 'use strict'; | ||
@@ -22,38 +22,2 @@ function _typeof(obj) { | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { | ||
try { | ||
var info = gen[key](arg); | ||
var value = info.value; | ||
} catch (error) { | ||
reject(error); | ||
return; | ||
} | ||
if (info.done) { | ||
resolve(value); | ||
} else { | ||
Promise.resolve(value).then(_next, _throw); | ||
} | ||
} | ||
function _asyncToGenerator(fn) { | ||
return function () { | ||
var self = this, | ||
args = arguments; | ||
return new Promise(function (resolve, reject) { | ||
var gen = fn.apply(self, args); | ||
function _next(value) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); | ||
} | ||
function _throw(err) { | ||
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); | ||
} | ||
_next(undefined); | ||
}); | ||
}; | ||
} | ||
function _classCallCheck(instance, Constructor) { | ||
@@ -96,16 +60,31 @@ if (!(instance instanceof Constructor)) { | ||
function _objectSpread(target) { | ||
function ownKeys(object, enumerableOnly) { | ||
var keys = Object.keys(object); | ||
if (Object.getOwnPropertySymbols) { | ||
var symbols = Object.getOwnPropertySymbols(object); | ||
if (enumerableOnly) symbols = symbols.filter(function (sym) { | ||
return Object.getOwnPropertyDescriptor(object, sym).enumerable; | ||
}); | ||
keys.push.apply(keys, symbols); | ||
} | ||
return keys; | ||
} | ||
function _objectSpread2(target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i] != null ? arguments[i] : {}; | ||
var ownKeys = Object.keys(source); | ||
if (typeof Object.getOwnPropertySymbols === 'function') { | ||
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { | ||
return Object.getOwnPropertyDescriptor(source, sym).enumerable; | ||
})); | ||
if (i % 2) { | ||
ownKeys(Object(source), true).forEach(function (key) { | ||
_defineProperty(target, key, source[key]); | ||
}); | ||
} else if (Object.getOwnPropertyDescriptors) { | ||
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); | ||
} else { | ||
ownKeys(Object(source)).forEach(function (key) { | ||
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); | ||
}); | ||
} | ||
ownKeys.forEach(function (key) { | ||
_defineProperty(target, key, source[key]); | ||
}); | ||
} | ||
@@ -141,2 +120,6 @@ | ||
function _iterableToArrayLimit(arr, i) { | ||
if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { | ||
return; | ||
} | ||
var _arr = []; | ||
@@ -183,2 +166,4 @@ var _n = true; | ||
*/ | ||
// eslint-disable-next-line max-len | ||
// eslint-disable-next-line block-spacing, space-before-function-paren, space-before-blocks, space-infix-ops, semi, promise/avoid-new | ||
var TypesonPromise = function TypesonPromise(f) { | ||
@@ -188,7 +173,8 @@ _classCallCheck(this, TypesonPromise); | ||
this.p = new Promise(f); | ||
}; // eslint-disable-line block-spacing, space-before-function-paren, space-before-blocks, space-infix-ops, semi | ||
}; // eslint-disable-next-line max-len | ||
// class TypesonPromise extends Promise {get[Symbol.toStringTag](){return 'TypesonPromise'};} // eslint-disable-line keyword-spacing, space-before-function-paren, space-before-blocks, block-spacing, semi | ||
// Note: core-js-bundle provides a `Symbol` polyfill | ||
TypesonPromise.__typeson__type__ = 'TypesonPromise'; // Note: core-js-bundle provides a `Symbol` polyfill | ||
if (typeof Symbol !== 'undefined') { | ||
@@ -210,9 +196,9 @@ // Ensure `isUserObject` will return `false` for `TypesonPromise` | ||
return new TypesonPromise(function (typesonResolve, typesonReject) { | ||
// eslint-disable-next-line promise/catch-or-return | ||
_this.p.then(function (res) { | ||
// eslint-disable-next-line promise/always-return | ||
typesonResolve(onFulfilled ? onFulfilled(res) : res); | ||
}, function (r) { | ||
_this.p['catch'](function (res) { | ||
return onRejected ? onRejected(res) : Promise.reject(res); | ||
}).then(typesonResolve, typesonReject); | ||
}); | ||
})["catch"](function (res) { | ||
return onRejected ? onRejected(res) : Promise.reject(res); | ||
}).then(typesonResolve, typesonReject); | ||
}); | ||
@@ -232,3 +218,3 @@ }; | ||
* | ||
* @param {} v | ||
* @param {Any} v | ||
* @returns {TypesonPromise} | ||
@@ -245,3 +231,3 @@ */ | ||
* | ||
* @param {} v | ||
* @param {Any} v | ||
* @returns {TypesonPromise} | ||
@@ -257,3 +243,3 @@ */ | ||
['all', 'race'].map(function (meth) { | ||
['all', 'race'].forEach(function (meth) { | ||
/** | ||
@@ -266,2 +252,3 @@ * | ||
return new TypesonPromise(function (typesonResolve, typesonReject) { | ||
// eslint-disable-next-line promise/catch-or-return | ||
Promise[meth](promArr.map(function (prom) { | ||
@@ -275,3 +262,3 @@ return prom.p; | ||
var _ref = {}, | ||
toString = _ref.toString, | ||
toStr = _ref.toString, | ||
hasOwn = {}.hasOwnProperty, | ||
@@ -282,3 +269,3 @@ getProto = Object.getPrototypeOf, | ||
* | ||
* @param {*} v | ||
* @param {Any} v | ||
* @param {boolean} catchCheck | ||
@@ -293,3 +280,3 @@ * @returns {boolean} | ||
* | ||
* @param {*} val | ||
* @param {Any} val | ||
* @returns {string} | ||
@@ -300,3 +287,3 @@ */ | ||
function toStringTag(val) { | ||
return toString.call(val).slice(8, -1); | ||
return toStr.call(val).slice(8, -1); | ||
} | ||
@@ -306,3 +293,3 @@ /** | ||
* being identical so any minimization is expected of both. | ||
* @param {*} a | ||
* @param {Any} a | ||
* @param {function} b | ||
@@ -330,7 +317,19 @@ * @returns {boolean} | ||
return typeof Ctor === 'function' && b !== null && fnToString.call(Ctor) === fnToString.call(b); | ||
if (b === Ctor) { | ||
return true; | ||
} | ||
if (b !== null && fnToString.call(Ctor) === fnToString.call(b)) { | ||
return true; | ||
} | ||
if (typeof b === 'function' && typeof Ctor.__typeson__type__ === 'string' && Ctor.__typeson__type__ === b.__typeson__type__) { | ||
return true; | ||
} | ||
return false; | ||
} | ||
/** | ||
* | ||
* @param {*} val | ||
* @param {Any} val | ||
* @returns {boolean} | ||
@@ -357,3 +356,3 @@ */ | ||
* | ||
* @param {*} val | ||
* @param {Any} val | ||
* @returns {boolean} | ||
@@ -379,3 +378,3 @@ */ | ||
* | ||
* @param {*} v | ||
* @param {Any} v | ||
* @returns {boolean} | ||
@@ -409,5 +408,5 @@ */ | ||
/** | ||
* @param {object|array} obj | ||
* @param {PlainObject|GenericArray} obj | ||
* @param {string} keyPath | ||
* @returns {*} | ||
* @returns {Any} | ||
*/ | ||
@@ -424,4 +423,4 @@ | ||
if (period > -1) { | ||
var innerObj = obj[unescapeKeyPathComponent(keyPath.substr(0, period))]; | ||
return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1)); | ||
var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))]; | ||
return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.slice(period + 1)); | ||
} | ||
@@ -431,3 +430,11 @@ | ||
} | ||
/** | ||
* | ||
* @param {PlainObject} obj | ||
* @param {string} keyPath | ||
* @param {Any} value | ||
* @returns {Any} | ||
*/ | ||
function setAtKeyPath(obj, keyPath, value) { | ||
@@ -441,4 +448,4 @@ if (keyPath === '') { | ||
if (period > -1) { | ||
var innerObj = obj[unescapeKeyPathComponent(keyPath.substr(0, period))]; | ||
return setAtKeyPath(innerObj, keyPath.substr(period + 1), value); | ||
var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))]; | ||
return setAtKeyPath(innerObj, keyPath.slice(period + 1), value); | ||
} | ||
@@ -452,3 +459,4 @@ | ||
* @param {external:JSON} value | ||
* @returns {"null"|"array"|"undefined"|"boolean"|"number"|"string"|"object"|"symbol"} | ||
* @returns {"null"|"array"|"undefined"|"boolean"|"number"|"string"| | ||
* "object"|"symbol"} | ||
*/ | ||
@@ -465,2 +473,8 @@ | ||
internalStateObjPropsToIgnore = ['type', 'replaced', 'iterateIn', 'iterateUnsetNumeric']; | ||
/** | ||
* | ||
* @param {PlainObjectType} a | ||
* @param {PlainObjectType} b | ||
* @returns {1|-1|boolean} | ||
*/ | ||
@@ -486,3 +500,3 @@ function nestedPathsFirst(a, b) { | ||
* | ||
* @constructor | ||
* @class | ||
* @param {{cyclic: boolean}} [options] - if cyclic (default true), | ||
@@ -512,7 +526,19 @@ * cyclic references will be handled gracefully. | ||
/** | ||
* @typedef {null|boolean|number|string|GenericArray|PlainObject} JSON | ||
*/ | ||
/** | ||
* @callback JSONReplacer | ||
* @param {""|string} key | ||
* @param {JSON} value | ||
* @returns {number|string|boolean|null|PlainObject|undefined} | ||
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20replacer%20parameter | ||
*/ | ||
/** | ||
* Serialize given object to Typeson. | ||
* Initial arguments work identical to those of `JSON.stringify`. | ||
* The `replacer` argument has nothing to do with our replacers. | ||
* @param {*} obj | ||
* @param {function|string[]} replacer | ||
* @param {Any} obj | ||
* @param {JSONReplacer|string[]} replacer | ||
* @param {number|string} space | ||
@@ -527,3 +553,3 @@ * @param {object} opts | ||
value: function stringify(obj, replacer, space, opts) { | ||
opts = _objectSpread({}, this.options, opts, { | ||
opts = _objectSpread2({}, this.options, {}, opts, { | ||
stringification: true | ||
@@ -542,5 +568,5 @@ }); | ||
/** | ||
* Also sync but throws on non-sync result | ||
* @param {*} obj | ||
* @param {function|string[]} replacer | ||
* Also sync but throws on non-sync result. | ||
* @param {Any} obj | ||
* @param {JSONReplacer|string[]} replacer | ||
* @param {number|string} space | ||
@@ -554,3 +580,3 @@ * @param {object} opts | ||
value: function stringifySync(obj, replacer, space, opts) { | ||
return this.stringify(obj, replacer, space, _objectSpread({ | ||
return this.stringify(obj, replacer, space, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -563,7 +589,7 @@ }, opts, { | ||
* | ||
* @param {*} obj | ||
* @param {function|string[]} replacer | ||
* @param {Any} obj | ||
* @param {JSONReplacer|string[]} replacer | ||
* @param {number|string} space | ||
* @param {object} opts | ||
* @returns {Promise} Resolves to string | ||
* @returns {Promise<string>} | ||
*/ | ||
@@ -574,3 +600,3 @@ | ||
value: function stringifyAsync(obj, replacer, space, opts) { | ||
return this.stringify(obj, replacer, space, _objectSpread({ | ||
return this.stringify(obj, replacer, space, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -594,3 +620,3 @@ }, opts, { | ||
value: function parse(text, reviver, opts) { | ||
opts = _objectSpread({}, this.options, opts, { | ||
opts = _objectSpread2({}, this.options, {}, opts, { | ||
parse: true | ||
@@ -601,3 +627,3 @@ }); | ||
/** | ||
* Also sync but throws on non-sync result | ||
* Also sync but throws on non-sync result. | ||
* @param {string} text | ||
@@ -613,3 +639,3 @@ * @param {function} reviver This JSON reviver has nothing to do with | ||
value: function parseSync(text, reviver, opts) { | ||
return this.parse(text, reviver, _objectSpread({ | ||
return this.parse(text, reviver, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -631,3 +657,3 @@ }, opts, { | ||
value: function parseAsync(text, reviver, opts) { | ||
return this.parse(text, reviver, _objectSpread({ | ||
return this.parse(text, reviver, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -640,3 +666,3 @@ }, opts, { | ||
* | ||
* @param {*} obj | ||
* @param {Any} obj | ||
* @param {object} stateObj | ||
@@ -656,6 +682,6 @@ * @param {object} [opts={}] | ||
* | ||
* @param {*} obj | ||
* @param {object} stateObj | ||
* @param {object} [opts={}] | ||
* @returns {Promise|Array|object|string|false} | ||
* @param {Any} obj | ||
* @param {PlainObject} stateObj | ||
* @param {PlainObject} [opts={}] | ||
* @returns {Promise|GenericArray|PlainObject|string|false} | ||
*/ | ||
@@ -674,7 +700,7 @@ | ||
* | ||
* This method is used internally by T`ypeson.stringify()`. | ||
* @param {Object} obj - Object to encapsulate. | ||
* @param {object} stateObj | ||
* @param {object} opts | ||
* @returns {Promise|Array|object|string|false} | ||
* This method is used internally by `Typeson.stringify()`. | ||
* @param {Any} obj - Object to encapsulate. | ||
* @param {PlainObject} stateObj | ||
* @param {PlainObject} opts | ||
* @returns {Promise|GenericArray|PlainObject|string|false} | ||
*/ | ||
@@ -685,5 +711,5 @@ | ||
value: function encapsulate(obj, stateObj, opts) { | ||
opts = _objectSpread({ | ||
opts = _objectSpread2({ | ||
sync: true | ||
}, this.options, opts); | ||
}, this.options, {}, opts); | ||
var _opts = opts, | ||
@@ -707,4 +733,4 @@ sync = _opts.sync; | ||
* | ||
* @param {*} ret | ||
* @returns {Array|object|string|false} | ||
* @param {Any} ret | ||
* @returns {GenericArray|PlainObject|string|false} | ||
*/ | ||
@@ -761,113 +787,94 @@ | ||
* | ||
* @param {*} ret | ||
* @param {array} promisesData | ||
* @returns {Promise} Resolves to ... | ||
* @param {Any} ret | ||
* @param {GenericArray} promisesData | ||
* @returns {Promise<Any>} | ||
*/ | ||
function checkPromises(_x, _x2) { | ||
return _checkPromises.apply(this, arguments); | ||
} | ||
/** | ||
* | ||
* @param {object} stateObj | ||
* @param {object} ownKeysObj | ||
* @param {function} cb | ||
* @returns {undefined} | ||
*/ | ||
function checkPromises(ret, promisesData) { | ||
var promResults; | ||
return regeneratorRuntime.async(function checkPromises$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
_context2.next = 2; | ||
return regeneratorRuntime.awrap(Promise.all(promisesData.map(function (pd) { | ||
return pd[1].p; | ||
}))); | ||
case 2: | ||
promResults = _context2.sent; | ||
_context2.next = 5; | ||
return regeneratorRuntime.awrap(Promise.all(promResults.map(function _callee(promResult) { | ||
var newPromisesData, _promisesData$splice, _promisesData$splice2, prData, _prData, keyPath, cyclic, stateObj, parentObj, key, detectedType, encaps, isTypesonPromise, encaps2; | ||
function _checkPromises() { | ||
_checkPromises = _asyncToGenerator( | ||
/*#__PURE__*/ | ||
regeneratorRuntime.mark(function _callee2(ret, promisesData) { | ||
var promResults; | ||
return regeneratorRuntime.wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
_context2.next = 2; | ||
return Promise.all(promisesData.map(function (pd) { | ||
return pd[1].p; | ||
})); | ||
return regeneratorRuntime.async(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
newPromisesData = []; | ||
_promisesData$splice = promisesData.splice(0, 1), _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1), prData = _promisesData$splice2[0]; | ||
_prData = _slicedToArray(prData, 7), keyPath = _prData[0], cyclic = _prData[2], stateObj = _prData[3], parentObj = _prData[4], key = _prData[5], detectedType = _prData[6]; | ||
encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType); | ||
isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself | ||
// returns a `Typeson.Promise` | ||
case 2: | ||
promResults = _context2.sent; | ||
_context2.next = 5; | ||
return Promise.all(promResults.map( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref = _asyncToGenerator( | ||
/*#__PURE__*/ | ||
regeneratorRuntime.mark(function _callee(promResult) { | ||
var newPromisesData, _promisesData$splice, _promisesData$splice2, prData, _prData, keyPath, cyclic, stateObj, parentObj, key, detectedType, encaps, isTypesonPromise, encaps2; | ||
if (!(keyPath && isTypesonPromise)) { | ||
_context.next = 11; | ||
break; | ||
} | ||
return regeneratorRuntime.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
newPromisesData = []; | ||
_promisesData$splice = promisesData.splice(0, 1), _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1), prData = _promisesData$splice2[0]; | ||
_prData = _slicedToArray(prData, 7), keyPath = _prData[0], cyclic = _prData[2], stateObj = _prData[3], parentObj = _prData[4], key = _prData[5], detectedType = _prData[6]; | ||
encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType); | ||
isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself | ||
// returns a `Typeson.Promise` | ||
_context.next = 8; | ||
return regeneratorRuntime.awrap(encaps.p); | ||
if (!(keyPath && isTypesonPromise)) { | ||
_context.next = 11; | ||
break; | ||
} | ||
case 8: | ||
encaps2 = _context.sent; | ||
parentObj[key] = encaps2; | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
_context.next = 8; | ||
return encaps.p; | ||
case 11: | ||
if (keyPath) { | ||
parentObj[key] = encaps; | ||
} else if (isTypesonPromise) { | ||
ret = encaps.p; | ||
} else { | ||
// If this is itself a `Typeson.Promise` (because the | ||
// original value supplied was a `Promise` or | ||
// because the supplied custom type value resolved | ||
// to one), returning it below will be fine since | ||
// a `Promise` is expected anyways given current | ||
// config (and if not a `Promise`, it will be ready | ||
// as the resolve value) | ||
ret = encaps; | ||
} | ||
case 8: | ||
encaps2 = _context.sent; | ||
parentObj[key] = encaps2; | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
case 11: | ||
if (keyPath) { | ||
parentObj[key] = encaps; | ||
} else if (isTypesonPromise) { | ||
ret = encaps.p; | ||
} else { | ||
// If this is itself a `Typeson.Promise` (because the | ||
// original value supplied was a `Promise` or | ||
// because the supplied custom type value resolved | ||
// to one), returning it below will be fine since | ||
// a `Promise` is expected anyways given current | ||
// config (and if not a `Promise`, it will be ready | ||
// as the resolve value) | ||
ret = encaps; | ||
} | ||
case 13: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}); | ||
}))); | ||
return _context.abrupt("return", checkPromises(ret, newPromisesData)); | ||
case 5: | ||
return _context2.abrupt("return", ret); | ||
case 13: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee); | ||
})); | ||
return function (_x3) { | ||
return _ref.apply(this, arguments); | ||
}; | ||
}())); | ||
case 5: | ||
return _context2.abrupt("return", ret); | ||
case 6: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
case 6: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
}, _callee2); | ||
})); | ||
return _checkPromises.apply(this, arguments); | ||
} | ||
}); | ||
} | ||
/** | ||
* | ||
* @param {object} stateObj | ||
* @param {object} ownKeysObj | ||
* @param {function} cb | ||
* @returns {undefined} | ||
*/ | ||
function _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, cb) { | ||
@@ -879,3 +886,4 @@ Object.assign(stateObj, ownKeysObj); | ||
return tmp; | ||
}); | ||
}); // eslint-disable-next-line callback-return | ||
cb(); | ||
@@ -889,9 +897,9 @@ internalStateObjPropsToIgnore.forEach(function (prop, i) { | ||
* @param {string} keypath | ||
* @param {*} value | ||
* @param {Any} value | ||
* @param {boolean} cyclic | ||
* @param {object} stateObj | ||
* @param {PlainObject} stateObj | ||
* @param {boolean} promisesData | ||
* @param {boolean} resolvingTypesonPromise | ||
* @param {string} detectedType | ||
* @returns {*} | ||
* @returns {Any} | ||
*/ | ||
@@ -987,2 +995,3 @@ | ||
} else { | ||
// eslint-disable-next-line no-lonely-if | ||
if (isArr && stateObj.iterateIn !== 'object' || stateObj.iterateIn === 'array') { | ||
@@ -1033,6 +1042,6 @@ clone = new Array(value.length); | ||
var val = _encapsulate(kp, value[key], !!cyclic, stateObj, promisesData, resolvingTypesonPromise); | ||
var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); | ||
if (hasConstructorOf(val, TypesonPromise)) { | ||
promisesData.push([kp, val, !!cyclic, stateObj, clone, key, stateObj.type]); | ||
promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]); | ||
} else if (val !== undefined) { | ||
@@ -1044,2 +1053,3 @@ clone[key] = val; | ||
// eslint-disable-next-line guard-for-in | ||
for (var key in value) { | ||
@@ -1067,6 +1077,6 @@ _loop(key); | ||
_adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () { | ||
var val = _encapsulate(kp, value[key], !!cyclic, stateObj, promisesData, resolvingTypesonPromise); | ||
var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); | ||
if (hasConstructorOf(val, TypesonPromise)) { | ||
promisesData.push([kp, val, !!cyclic, stateObj, clone, key, stateObj.type]); | ||
promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]); | ||
} else if (val !== undefined) { | ||
@@ -1101,6 +1111,6 @@ clone[key] = val; | ||
_adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () { | ||
var val = _encapsulate(kp, undefined, !!cyclic, stateObj, promisesData, resolvingTypesonPromise); | ||
var val = _encapsulate(kp, undefined, Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); | ||
if (hasConstructorOf(val, TypesonPromise)) { | ||
promisesData.push([kp, val, !!cyclic, stateObj, clone, i, stateObj.type]); | ||
promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, i, stateObj.type]); | ||
} else if (val !== undefined) { | ||
@@ -1130,5 +1140,5 @@ clone[i] = val; | ||
* @param {string} keypath | ||
* @param {*} value | ||
* @param {object} stateObj | ||
* @param {array} promisesData | ||
* @param {Any} value | ||
* @param {PlainObject} stateObj | ||
* @param {GenericArray} promisesData | ||
* @param {boolean} plainObject | ||
@@ -1207,3 +1217,3 @@ * @param {boolean} resolvingTypesonPromise | ||
/** | ||
* Also sync but throws on non-sync result | ||
* Also sync but throws on non-sync result. | ||
* @param {*} obj | ||
@@ -1218,3 +1228,3 @@ * @param {object} stateObj | ||
value: function encapsulateSync(obj, stateObj, opts) { | ||
return this.encapsulate(obj, stateObj, _objectSpread({ | ||
return this.encapsulate(obj, stateObj, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -1235,3 +1245,3 @@ }, opts, { | ||
value: function encapsulateAsync(obj, stateObj, opts) { | ||
return this.encapsulate(obj, stateObj, _objectSpread({ | ||
return this.encapsulate(obj, stateObj, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -1268,5 +1278,5 @@ }, opts, { | ||
opts = _objectSpread({ | ||
opts = _objectSpread2({ | ||
sync: true | ||
}, this.options, opts); | ||
}, this.options, {}, opts); | ||
var _opts3 = opts, | ||
@@ -1287,2 +1297,6 @@ sync = _opts3.sync; | ||
var that = this; | ||
/** | ||
* | ||
* @returns {void|TypesonPromise<void>} | ||
*/ | ||
@@ -1293,6 +1307,6 @@ function revivePlainObjects() { | ||
var plainObjectTypes = []; | ||
Object.entries(types).forEach(function (_ref2) { | ||
var _ref3 = _slicedToArray(_ref2, 2), | ||
keypath = _ref3[0], | ||
type = _ref3[1]; | ||
Object.entries(types).forEach(function (_ref) { | ||
var _ref2 = _slicedToArray(_ref, 2), | ||
keypath = _ref2[0], | ||
type = _ref2[1]; | ||
@@ -1327,4 +1341,10 @@ if (type === '#') { | ||
if (!plainObjectTypes.length) { | ||
return; | ||
} // Handle plain object revivers first so reference | ||
return undefined; | ||
} | ||
/** | ||
* @typedef {PlainObject} PlainObjectType | ||
* @property {string} keypath | ||
* @property {string} type | ||
*/ | ||
// Handle plain object revivers first so reference | ||
// setting can use revived type (e.g., array instead | ||
@@ -1335,5 +1355,5 @@ // of object); assumes revived has same structure | ||
return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref4) { | ||
var keypath = _ref4.keypath, | ||
type = _ref4.type; | ||
return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref3) { | ||
var keypath = _ref3.keypath, | ||
type = _ref3.type; | ||
@@ -1387,7 +1407,7 @@ if (hasConstructorOf(possibleTypesonPromise, TypesonPromise)) { | ||
* @param {string} keypath | ||
* @param {*} value | ||
* @param {Any} value | ||
* @param {?(Array|object)} target | ||
* @param {Array|object} [clone] | ||
* @param {string} [key] | ||
* @returns {*} | ||
* @returns {Any} | ||
*/ | ||
@@ -1472,3 +1492,9 @@ | ||
} | ||
/** | ||
* | ||
* @param {Any} retrn | ||
* @returns {undefined|Any} | ||
*/ | ||
function checkUndefined(retrn) { | ||
@@ -1496,6 +1522,6 @@ return hasConstructorOf(retrn, Undefined) ? undefined : retrn; | ||
/** | ||
* Also sync but throws on non-sync result | ||
* @param {*} obj | ||
* Also sync but throws on non-sync result. | ||
* @param {Any} obj | ||
* @param {object} opts | ||
* @returns {*} | ||
* @returns {Any} | ||
*/ | ||
@@ -1506,3 +1532,3 @@ | ||
value: function reviveSync(obj, opts) { | ||
return this.revive(obj, _objectSpread({ | ||
return this.revive(obj, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -1514,3 +1540,3 @@ }, opts, { | ||
/** | ||
* @param {*} obj | ||
* @param {Any} obj | ||
* @param {object} opts | ||
@@ -1523,3 +1549,3 @@ * @returns {Promise} Resolves to `*` | ||
value: function reviveAsync(obj, opts) { | ||
return this.revive(obj, _objectSpread({ | ||
return this.revive(obj, _objectSpread2({ | ||
throwOnBadSyncType: true | ||
@@ -1533,4 +1559,4 @@ }, opts, { | ||
* For examples on how to use this method, see | ||
* {@link https://github.com/dfahlander/typeson-registry/tree/master/types} | ||
* @param {Array.<Object.<string,Function[]>>} typeSpecSets - Types and | ||
* {@link https://github.com/dfahlander/typeson-registry/tree/master/types}. | ||
* @param {object.<string,Function[]>[]} typeSpecSets - Types and | ||
* their functions [test, encapsulate, revive]; | ||
@@ -1546,5 +1572,9 @@ * @param {object} opts | ||
[].concat(typeSpecSets).forEach(function R(typeSpec) { | ||
var _this = this; | ||
// Allow arrays of arrays of arrays... | ||
if (isArray(typeSpec)) { | ||
return typeSpec.map(R, this); | ||
return typeSpec.map(function (typSpec) { | ||
return R.call(_this, typSpec); | ||
}); | ||
} | ||
@@ -1584,3 +1614,3 @@ | ||
replace: function replace(x) { | ||
return Object.assign({}, x); | ||
return _objectSpread2({}, x); | ||
}, | ||
@@ -1657,3 +1687,3 @@ revive: function revive(x) { | ||
* with `hasConstructorOf`. | ||
* @constructor | ||
* @class | ||
*/ | ||
@@ -1665,6 +1695,7 @@ | ||
}; // eslint-disable-line space-before-blocks | ||
// The following provide classes meant to avoid clashes with other values | ||
Undefined.__typeson__type__ = 'TypesonUndefined'; // The following provide classes meant to avoid clashes with other values | ||
// To insist `undefined` should be added | ||
Typeson.Undefined = Undefined; // To support async encapsulation/stringification | ||
@@ -1688,2 +1719,2 @@ | ||
})); | ||
}))); |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).Typeson=t()}(this,function(){"use strict";function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function asyncGeneratorStep(e,t,n,r,i,a,o){try{var c=e[a](o),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(r,i)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var a=e.apply(t,n);function _next(e){asyncGeneratorStep(a,r,i,_next,_throw,"next",e)}function _throw(e){asyncGeneratorStep(a,r,i,_next,_throw,"throw",e)}_next(void 0)})}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _objectSpread(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){_defineProperty(e,t,n[t])})}return e}function _slicedToArray(e,t){return function _arrayWithHoles(e){if(Array.isArray(e))return e}(e)||function _iterableToArrayLimit(e,t){var n=[],r=!0,i=!1,a=void 0;try{for(var o,c=e[Symbol.iterator]();!(r=(o=c.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,a=e}finally{try{r||null==c.return||c.return()}finally{if(i)throw a}}return n}(e,t)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function _toConsumableArray(e){return function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}(e)||function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var e=function TypesonPromise(e){_classCallCheck(this,TypesonPromise),this.p=new Promise(e)};"undefined"!=typeof Symbol&&(e.prototype[Symbol.toStringTag]="TypesonPromise"),e.prototype.then=function(t,n){var r=this;return new e(function(e,i){r.p.then(function(n){e(t?t(n):n)},function(t){r.p.catch(function(e){return n?n(e):Promise.reject(e)}).then(e,i)})})},e.prototype.catch=function(e){return this.then(null,e)},e.resolve=function(t){return new e(function(e){e(t)})},e.reject=function(t){return new e(function(e,n){n(t)})},["all","race"].map(function(t){e[t]=function(n){return new e(function(e,r){Promise[t](n.map(function(e){return e.p})).then(e,r)})}});var t={}.toString,n={}.hasOwnProperty,r=Object.getPrototypeOf,i=n.toString;function isThenable(e,t){return isObject(e)&&"function"==typeof e.then&&(!t||"function"==typeof e.catch)}function toStringTag(e){return t.call(e).slice(8,-1)}function hasConstructorOf(e,t){if(!e||"object"!==_typeof(e))return!1;var a=r(e);if(!a)return!1;var o=n.call(a,"constructor")&&a.constructor;return"function"!=typeof o?null===t:"function"==typeof o&&null!==t&&i.call(o)===i.call(t)}function isPlainObject(e){return!(!e||"Object"!==toStringTag(e))&&(!r(e)||hasConstructorOf(e,Object))}function isObject(e){return e&&"object"===_typeof(e)}function escapeKeyPathComponent(e){return e.replace(/~/g,"~0").replace(/\./g,"~1")}function unescapeKeyPathComponent(e){return e.replace(/~1/g,".").replace(/~0/g,"~")}function getByKeyPath(e,t){if(""===t)return e;var n=t.indexOf(".");if(n>-1){var r=e[unescapeKeyPathComponent(t.substr(0,n))];return void 0===r?void 0:getByKeyPath(r,t.substr(n+1))}return e[unescapeKeyPathComponent(t)]}var a=Object.keys,o=Array.isArray,c={}.hasOwnProperty,s=["type","replaced","iterateIn","iterateUnsetNumeric"];function nestedPathsFirst(e,t){var n=e.keypath.match(/\./g),r=e.keypath.match(/\./g);return n&&(n=n.length),r&&(r=r.length),n>r?-1:n<r?1:e.keypath<t.keypath?-1:e.keypath>t.keypath}var u=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={}}return function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}(Typeson,[{key:"stringify",value:function stringify(e,t,n,r){r=_objectSpread({},this.options,r,{stringification:!0});var i=this.encapsulate(e,null,r);return o(i)?JSON.stringify(i[0],t,n):i.then(function(e){return JSON.stringify(e,t,n)})}},{key:"stringifySync",value:function stringifySync(e,t,n,r){return this.stringify(e,t,n,_objectSpread({throwOnBadSyncType:!0},r,{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,n,r){return this.stringify(e,t,n,_objectSpread({throwOnBadSyncType:!0},r,{sync:!1}))}},{key:"parse",value:function parse(e,t,n){return n=_objectSpread({},this.options,n,{parse:!0}),this.revive(JSON.parse(e,t),n)}},{key:"parseSync",value:function parseSync(e,t,n){return this.parse(e,t,_objectSpread({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,n){return this.parse(e,t,_objectSpread({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.returnTypeNames=!0,this.encapsulate(e,t,n)}},{key:"rootTypeName",value:function rootTypeName(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.iterateNone=!0,this.encapsulate(e,t,n)}},{key:"encapsulate",value:function encapsulate(t,n,r){var i=(r=_objectSpread({sync:!0},this.options,r)).sync,u=this,p={},l=[],y=[],f=[],h=!("cyclic"in r)||r.cyclic,v=r.encapsulateObserver,d=_encapsulate("",t,h,n||{},f);function finish(e){var t=Object.values(p);if(r.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(r.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!c.call(e,"$types")?e.$types=p:e={$:e,$types:{$:p}}}else isObject(e)&&c.call(e,"$types")&&(e={$:e,$types:!0});return!r.returnTypeNames&&e}function checkPromises(e,t){return _checkPromises.apply(this,arguments)}function _checkPromises(){return(_checkPromises=_asyncToGenerator(regeneratorRuntime.mark(function _callee2(t,n){var r;return regeneratorRuntime.wrap(function _callee2$(i){for(;;)switch(i.prev=i.next){case 0:return i.next=2,Promise.all(n.map(function(e){return e[1].p}));case 2:return r=i.sent,i.next=5,Promise.all(r.map(function(){var r=_asyncToGenerator(regeneratorRuntime.mark(function _callee(r){var i,a,o,c,s,u,p,l,y,f,h,v,d,b;return regeneratorRuntime.wrap(function _callee$(O){for(;;)switch(O.prev=O.next){case 0:if(i=[],a=n.splice(0,1),o=_slicedToArray(a,1),c=o[0],s=_slicedToArray(c,7),u=s[0],p=s[2],l=s[3],y=s[4],f=s[5],h=s[6],v=_encapsulate(u,r,p,l,i,!0,h),d=hasConstructorOf(v,e),!u||!d){O.next=11;break}return O.next=8,v.p;case 8:return b=O.sent,y[f]=b,O.abrupt("return",checkPromises(t,i));case 11:return u?y[f]=v:t=d?v.p:v,O.abrupt("return",checkPromises(t,i));case 13:case"end":return O.stop()}},_callee)}));return function(e){return r.apply(this,arguments)}}()));case 5:return i.abrupt("return",t);case 6:case"end":return i.stop()}},_callee2)}))).apply(this,arguments)}function _adaptBuiltinStateObjectProperties(e,t,n){Object.assign(e,t);var r=s.map(function(t){var n=e[t];return delete e[t],n});n(),s.forEach(function(t,n){e[t]=r[n]})}function _encapsulate(t,n,i,s,f,h,d){var b,O={},m=_typeof(n),g=v?function(r){var a=d||s.type||Typeson.getJSONType(n);v(Object.assign(r||O,{keypath:t,value:n,cyclic:i,stateObj:s,promisesData:f,resolvingTypesonPromise:h,awaitingTypesonPromise:hasConstructorOf(n,e)},void 0!==a?{type:a}:{}))}:null;if(["string","boolean","number","undefined"].includes(m))return void 0===n||"number"===m&&(isNaN(n)||n===-1/0||n===1/0)?(b=replace(t,n,s,f,!1,h,g))!==n&&(O={replaced:b}):b=n,g&&g(),b;if(null===n)return g&&g(),n;if(i&&!s.iterateIn&&!s.iterateUnsetNumeric){var _=l.indexOf(n);if(!(_<0))return p[t]="#",g&&g({cyclicKeypath:y[_]}),"#"+y[_];!0===i&&(l.push(n),y.push(t))}var j,P=isPlainObject(n),S=o(n),T=(P||S)&&(!u.plainObjectReplacers.length||s.replaced)||s.iterateIn?n:replace(t,n,s,f,P||S,null,g);if(T!==n?(b=T,O={replaced:T}):S&&"object"!==s.iterateIn||"array"===s.iterateIn?(j=new Array(n.length),O={clone:j}):P||"object"===s.iterateIn?(j={},s.addLength&&(j.length=n.length),O={clone:j}):""===t&&hasConstructorOf(n,e)?(f.push([t,n,i,s,void 0,void 0,s.type]),b=n):b=n,g&&g(),r.iterateNone)return j||b;if(!j)return b;if(s.iterateIn){var w=function _loop(r){var a={ownKeys:c.call(n,r)};_adaptBuiltinStateObjectProperties(s,a,function(){var a=t+(t?".":"")+escapeKeyPathComponent(r),o=_encapsulate(a,n[r],!!i,s,f,h);hasConstructorOf(o,e)?f.push([a,o,!!i,s,j,r,s.type]):void 0!==o&&(j[r]=o)})};for(var A in n)w(A);g&&g({endIterateIn:!0,end:!0})}else a(n).forEach(function(r){var a=t+(t?".":"")+escapeKeyPathComponent(r);_adaptBuiltinStateObjectProperties(s,{ownKeys:!0},function(){var t=_encapsulate(a,n[r],!!i,s,f,h);hasConstructorOf(t,e)?f.push([a,t,!!i,s,j,r,s.type]):void 0!==t&&(j[r]=t)})}),g&&g({endIterateOwn:!0,end:!0});if(s.iterateUnsetNumeric){for(var k=n.length,C=function _loop2(r){if(!(r in n)){var a=t+(t?".":"")+r;_adaptBuiltinStateObjectProperties(s,{ownKeys:!1},function(){var t=_encapsulate(a,void 0,!!i,s,f,h);hasConstructorOf(t,e)?f.push([a,t,!!i,s,j,r,s.type]):void 0!==t&&(j[r]=t)})}},K=0;K<k;K++)C(K);g&&g({endIterateUnsetNumeric:!0,end:!0})}return j}function replace(e,t,n,r,a,o,c){for(var s=a?u.plainObjectReplacers:u.nonplainObjectReplacers,l=s.length;l--;){var y=s[l];if(y.test(t,n)){var f=y.type;if(u.revivers[f]){var v=p[e];p[e]=v?[f].concat(v):f}return Object.assign(n,{type:f,replaced:!0}),!i&&y.replaceAsync||y.replace?(c&&c({replacing:!0}),_encapsulate(e,y[i||!y.replaceAsync?"replace":"replaceAsync"](t,n),h&&"readonly",n,r,o,f)):(c&&c({typeDetected:!0}),_encapsulate(e,t,h&&"readonly",n,r,o,f))}}return t}return f.length?i&&r.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(checkPromises(d,f)).then(finish):!i&&r.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():r.stringification&&i?[finish(d)]:i?finish(d):Promise.resolve(finish(d))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,n){return this.encapsulate(e,t,_objectSpread({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,n){return this.encapsulate(e,t,_objectSpread({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"revive",value:function revive(t,n){var r=t&&t.$types;if(!r)return t;if(!0===r)return t.$;var i=(n=_objectSpread({sync:!0},this.options,n)).sync,c=[],s={},u=!0;r.$&&isPlainObject(r.$)&&(t=t.$,r=r.$,u=!1);var l=this;function _revive(t,n,y,f,h){if(!u||"$types"!==t){var v=r[t];if(o(n)||isPlainObject(n)){var d=o(n)?new Array(n.length):{};for(a(n).forEach(function(e){var r=_revive(t+(t?".":"")+escapeKeyPathComponent(e),n[e],y||d,d,e);hasConstructorOf(r,p)?d[e]=void 0:void 0!==r&&(d[e]=r)}),n=d;c.length;){var b=_slicedToArray(c[0],4),O=b[0],m=b[1],g=b[2],_=b[3],j=getByKeyPath(O,m);if(hasConstructorOf(j,p))g[_]=void 0;else{if(void 0===j)break;g[_]=j}c.splice(0,1)}}if(!v)return n;if("#"===v){var P=getByKeyPath(y,n.slice(1));return void 0===P&&c.push([y,n.slice(1),f,h]),P}return[].concat(v).reduce(function reducer(t,n){if(hasConstructorOf(t,e))return t.then(function(e){return reducer(e,n)});var r=_slicedToArray(l.revivers[n],1)[0];if(!r)throw new Error("Unregistered type: "+n);return r[i&&r.revive?"revive":!i&&r.reviveAsync?"reviveAsync":"revive"](t,s)},n)}}function checkUndefined(e){return hasConstructorOf(e,p)?void 0:e}var y,f=function revivePlainObjects(){var n=[];if(Object.entries(r).forEach(function(e){var t=_slicedToArray(e,2),i=t[0],a=t[1];"#"!==a&&[].concat(a).forEach(function(e){_slicedToArray(l.revivers[e],2)[1].plain&&(n.push({keypath:i,type:e}),delete r[i])})}),n.length)return n.sort(nestedPathsFirst).reduce(function reducer(n,r){var a=r.keypath,o=r.type;if(hasConstructorOf(n,e))return n.then(function(e){return reducer(e,o)});var c=getByKeyPath(t,a);if(hasConstructorOf(c,e))return c.then(function(e){return reducer(e,o)});var u=_slicedToArray(l.revivers[o],1)[0];if(!u)throw new Error("Unregistered type: "+o);void 0!==(c=u[i&&u.revive?"revive":!i&&u.reviveAsync?"reviveAsync":"revive"](c,s))&&(hasConstructorOf(c,p)&&(c=void 0),function setAtKeyPath(e,t,n){if(""===t)return n;var r=t.indexOf(".");return r>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.substr(0,r))],t.substr(r+1),n):(e[unescapeKeyPathComponent(t)]=n,e)}(t,a,c)===c&&(t=c))},void 0)}();return isThenable(y=hasConstructorOf(f,e)?f.then(function(){return _revive("",t,null)}):_revive("",t,null))?i&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(y,e)?y.p.then(checkUndefined):y:!i&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():i?checkUndefined(y):Promise.resolve(checkUndefined(y))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread({throwOnBadSyncType:!0},t,{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread({throwOnBadSyncType:!0},t,{sync:!1}))}},{key:"register",value:function register(e,t){return t=t||{},[].concat(e).forEach(function R(e){if(o(e))return e.map(R,this);e&&a(e).forEach(function(n){if("#"===n)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(Typeson.JSON_TYPES.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var r=e[n],i=r.testPlainObjects?this.plainObjectReplacers:this.nonplainObjectReplacers,a=i.filter(function(e){return e.type===n});if(a.length&&(i.splice(i.indexOf(a[0]),1),delete this.revivers[n],delete this.types[n]),r){if("function"==typeof r){var c=r;r={test:function test(e){return e&&e.constructor===c},replace:function replace(e){return Object.assign({},e)},revive:function revive(e){return Object.assign(Object.create(c.prototype),e)}}}else if(o(r)){var s=_slicedToArray(r,3);r={test:s[0],replace:s[1],revive:s[2]}}var u={type:n,test:r.test.bind(r)};r.replace&&(u.replace=r.replace.bind(r)),r.replaceAsync&&(u.replaceAsync=r.replaceAsync.bind(r));var p="number"==typeof t.fallback?t.fallback:t.fallback?0:1/0;if(r.testPlainObjects?this.plainObjectReplacers.splice(p,0,u):this.nonplainObjectReplacers.splice(p,0,u),r.revive||r.reviveAsync){var l={};r.revive&&(l.revive=r.revive.bind(r)),r.reviveAsync&&(l.reviveAsync=r.reviveAsync.bind(r)),this.revivers[n]=[l,{plain:r.testPlainObjects}]}this.types[n]=r}},this)},this),this}}]),Typeson}(),p=function Undefined(){_classCallCheck(this,Undefined)};return u.Undefined=p,u.Promise=e,u.isThenable=isThenable,u.toStringTag=toStringTag,u.hasConstructorOf=hasConstructorOf,u.isObject=isObject,u.isPlainObject=isPlainObject,u.isUserObject=function isUserObject(e){if(!e||"Object"!==toStringTag(e))return!1;var t=r(e);return!t||hasConstructorOf(e,Object)||isUserObject(t)},u.escapeKeyPathComponent=escapeKeyPathComponent,u.unescapeKeyPathComponent=unescapeKeyPathComponent,u.getByKeyPath=getByKeyPath,u.getJSONType=function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)},u.JSON_TYPES=["null","boolean","number","string","array","object"],u}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).Typeson=t()}(this,(function(){"use strict";function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(n),!0).forEach((function(t){_defineProperty(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ownKeys(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function _slicedToArray(e,t){return function _arrayWithHoles(e){if(Array.isArray(e))return e}(e)||function _iterableToArrayLimit(e,t){if(!(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)))return;var n=[],r=!0,i=!1,o=void 0;try{for(var a,c=e[Symbol.iterator]();!(r=(a=c.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){i=!0,o=e}finally{try{r||null==c.return||c.return()}finally{if(i)throw o}}return n}(e,t)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function _toConsumableArray(e){return function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}(e)||function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var e=function TypesonPromise(e){_classCallCheck(this,TypesonPromise),this.p=new Promise(e)};e.__typeson__type__="TypesonPromise","undefined"!=typeof Symbol&&(e.prototype[Symbol.toStringTag]="TypesonPromise"),e.prototype.then=function(t,n){var r=this;return new e((function(e,i){r.p.then((function(n){e(t?t(n):n)})).catch((function(e){return n?n(e):Promise.reject(e)})).then(e,i)}))},e.prototype.catch=function(e){return this.then(null,e)},e.resolve=function(t){return new e((function(e){e(t)}))},e.reject=function(t){return new e((function(e,n){n(t)}))},["all","race"].forEach((function(t){e[t]=function(n){return new e((function(e,r){Promise[t](n.map((function(e){return e.p}))).then(e,r)}))}}));var t={}.toString,n={}.hasOwnProperty,r=Object.getPrototypeOf,i=n.toString;function isThenable(e,t){return isObject(e)&&"function"==typeof e.then&&(!t||"function"==typeof e.catch)}function toStringTag(e){return t.call(e).slice(8,-1)}function hasConstructorOf(e,t){if(!e||"object"!==_typeof(e))return!1;var o=r(e);if(!o)return!1;var a=n.call(o,"constructor")&&o.constructor;return"function"!=typeof a?null===t:t===a||(null!==t&&i.call(a)===i.call(t)||"function"==typeof t&&"string"==typeof a.__typeson__type__&&a.__typeson__type__===t.__typeson__type__)}function isPlainObject(e){return!(!e||"Object"!==toStringTag(e))&&(!r(e)||hasConstructorOf(e,Object))}function isObject(e){return e&&"object"===_typeof(e)}function escapeKeyPathComponent(e){return e.replace(/~/g,"~0").replace(/\./g,"~1")}function unescapeKeyPathComponent(e){return e.replace(/~1/g,".").replace(/~0/g,"~")}function getByKeyPath(e,t){if(""===t)return e;var n=t.indexOf(".");if(n>-1){var r=e[unescapeKeyPathComponent(t.slice(0,n))];return void 0===r?void 0:getByKeyPath(r,t.slice(n+1))}return e[unescapeKeyPathComponent(t)]}var o=Object.keys,a=Array.isArray,c={}.hasOwnProperty,s=["type","replaced","iterateIn","iterateUnsetNumeric"];function nestedPathsFirst(e,t){var n=e.keypath.match(/\./g),r=e.keypath.match(/\./g);return n&&(n=n.length),r&&(r=r.length),n>r?-1:n<r?1:e.keypath<t.keypath?-1:e.keypath>t.keypath}var u=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={}}return function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}(Typeson,[{key:"stringify",value:function stringify(e,t,n,r){r=_objectSpread2({},this.options,{},r,{stringification:!0});var i=this.encapsulate(e,null,r);return a(i)?JSON.stringify(i[0],t,n):i.then((function(e){return JSON.stringify(e,t,n)}))}},{key:"stringifySync",value:function stringifySync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,n,r){return this.stringify(e,t,n,_objectSpread2({throwOnBadSyncType:!0},r,{sync:!1}))}},{key:"parse",value:function parse(e,t,n){return n=_objectSpread2({},this.options,{},n,{parse:!0}),this.revive(JSON.parse(e,t),n)}},{key:"parseSync",value:function parseSync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,n){return this.parse(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.returnTypeNames=!0,this.encapsulate(e,t,n)}},{key:"rootTypeName",value:function rootTypeName(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.iterateNone=!0,this.encapsulate(e,t,n)}},{key:"encapsulate",value:function encapsulate(t,n,r){var i=(r=_objectSpread2({sync:!0},this.options,{},r)).sync,u=this,p={},y=[],l=[],f=[],h=!("cyclic"in r)||r.cyclic,v=r.encapsulateObserver,d=_encapsulate("",t,h,n||{},f);function finish(e){var t=Object.values(p);if(r.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(r.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!c.call(e,"$types")?e.$types=p:e={$:e,$types:{$:p}}}else isObject(e)&&c.call(e,"$types")&&(e={$:e,$types:!0});return!r.returnTypeNames&&e}function _adaptBuiltinStateObjectProperties(e,t,n){Object.assign(e,t);var r=s.map((function(t){var n=e[t];return delete e[t],n}));n(),s.forEach((function(t,n){e[t]=r[n]}))}function _encapsulate(t,n,i,s,f,h,d){var b,O={},_=_typeof(n),g=v?function(r){var o=d||s.type||Typeson.getJSONType(n);v(Object.assign(r||O,{keypath:t,value:n,cyclic:i,stateObj:s,promisesData:f,resolvingTypesonPromise:h,awaitingTypesonPromise:hasConstructorOf(n,e)},void 0!==o?{type:o}:{}))}:null;if(["string","boolean","number","undefined"].includes(_))return void 0===n||"number"===_&&(isNaN(n)||n===-1/0||n===1/0)?(b=replace(t,n,s,f,!1,h,g))!==n&&(O={replaced:b}):b=n,g&&g(),b;if(null===n)return g&&g(),n;if(i&&!s.iterateIn&&!s.iterateUnsetNumeric){var m=y.indexOf(n);if(!(m<0))return p[t]="#",g&&g({cyclicKeypath:l[m]}),"#"+l[m];!0===i&&(y.push(n),l.push(t))}var j,P=isPlainObject(n),S=a(n),T=(P||S)&&(!u.plainObjectReplacers.length||s.replaced)||s.iterateIn?n:replace(t,n,s,f,P||S,null,g);if(T!==n?(b=T,O={replaced:T}):S&&"object"!==s.iterateIn||"array"===s.iterateIn?(j=new Array(n.length),O={clone:j}):P||"object"===s.iterateIn?(j={},s.addLength&&(j.length=n.length),O={clone:j}):""===t&&hasConstructorOf(n,e)?(f.push([t,n,i,s,void 0,void 0,s.type]),b=n):b=n,g&&g(),r.iterateNone)return j||b;if(!j)return b;if(s.iterateIn){var w=function _loop(r){var o={ownKeys:c.call(n,r)};_adaptBuiltinStateObjectProperties(s,o,(function(){var o=t+(t?".":"")+escapeKeyPathComponent(r),a=_encapsulate(o,n[r],Boolean(i),s,f,h);hasConstructorOf(a,e)?f.push([o,a,Boolean(i),s,j,r,s.type]):void 0!==a&&(j[r]=a)}))};for(var A in n)w(A);g&&g({endIterateIn:!0,end:!0})}else o(n).forEach((function(r){var o=t+(t?".":"")+escapeKeyPathComponent(r);_adaptBuiltinStateObjectProperties(s,{ownKeys:!0},(function(){var t=_encapsulate(o,n[r],Boolean(i),s,f,h);hasConstructorOf(t,e)?f.push([o,t,Boolean(i),s,j,r,s.type]):void 0!==t&&(j[r]=t)}))})),g&&g({endIterateOwn:!0,end:!0});if(s.iterateUnsetNumeric){for(var C=n.length,k=function _loop2(r){if(!(r in n)){var o=t+(t?".":"")+r;_adaptBuiltinStateObjectProperties(s,{ownKeys:!1},(function(){var t=_encapsulate(o,void 0,Boolean(i),s,f,h);hasConstructorOf(t,e)?f.push([o,t,Boolean(i),s,j,r,s.type]):void 0!==t&&(j[r]=t)}))}},B=0;B<C;B++)k(B);g&&g({endIterateUnsetNumeric:!0,end:!0})}return j}function replace(e,t,n,r,o,a,c){for(var s=o?u.plainObjectReplacers:u.nonplainObjectReplacers,y=s.length;y--;){var l=s[y];if(l.test(t,n)){var f=l.type;if(u.revivers[f]){var v=p[e];p[e]=v?[f].concat(v):f}return Object.assign(n,{type:f,replaced:!0}),!i&&l.replaceAsync||l.replace?(c&&c({replacing:!0}),_encapsulate(e,l[i||!l.replaceAsync?"replace":"replaceAsync"](t,n),h&&"readonly",n,r,a,f)):(c&&c({typeDetected:!0}),_encapsulate(e,t,h&&"readonly",n,r,a,f))}}return t}return f.length?i&&r.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(function checkPromises(t,n){var r;return regeneratorRuntime.async((function checkPromises$(i){for(;;)switch(i.prev=i.next){case 0:return i.next=2,regeneratorRuntime.awrap(Promise.all(n.map((function(e){return e[1].p}))));case 2:return r=i.sent,i.next=5,regeneratorRuntime.awrap(Promise.all(r.map((function _callee(r){var i,o,a,c,s,u,p,y,l,f,h,v,d,b;return regeneratorRuntime.async((function _callee$(O){for(;;)switch(O.prev=O.next){case 0:if(i=[],o=n.splice(0,1),a=_slicedToArray(o,1),c=a[0],s=_slicedToArray(c,7),u=s[0],p=s[2],y=s[3],l=s[4],f=s[5],h=s[6],v=_encapsulate(u,r,p,y,i,!0,h),d=hasConstructorOf(v,e),!u||!d){O.next=11;break}return O.next=8,regeneratorRuntime.awrap(v.p);case 8:return b=O.sent,l[f]=b,O.abrupt("return",checkPromises(t,i));case 11:return u?l[f]=v:t=d?v.p:v,O.abrupt("return",checkPromises(t,i));case 13:case"end":return O.stop()}}))}))));case 5:return i.abrupt("return",t);case 6:case"end":return i.stop()}}))}(d,f)).then(finish):!i&&r.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():r.stringification&&i?[finish(d)]:i?finish(d):Promise.resolve(finish(d))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,n){return this.encapsulate(e,t,_objectSpread2({throwOnBadSyncType:!0},n,{sync:!1}))}},{key:"revive",value:function revive(t,n){var r=t&&t.$types;if(!r)return t;if(!0===r)return t.$;var i=(n=_objectSpread2({sync:!0},this.options,{},n)).sync,c=[],s={},u=!0;r.$&&isPlainObject(r.$)&&(t=t.$,r=r.$,u=!1);var y=this;function _revive(t,n,l,f,h){if(!u||"$types"!==t){var v=r[t];if(a(n)||isPlainObject(n)){var d=a(n)?new Array(n.length):{};for(o(n).forEach((function(e){var r=_revive(t+(t?".":"")+escapeKeyPathComponent(e),n[e],l||d,d,e);hasConstructorOf(r,p)?d[e]=void 0:void 0!==r&&(d[e]=r)})),n=d;c.length;){var b=_slicedToArray(c[0],4),O=b[0],_=b[1],g=b[2],m=b[3],j=getByKeyPath(O,_);if(hasConstructorOf(j,p))g[m]=void 0;else{if(void 0===j)break;g[m]=j}c.splice(0,1)}}if(!v)return n;if("#"===v){var P=getByKeyPath(l,n.slice(1));return void 0===P&&c.push([l,n.slice(1),f,h]),P}return[].concat(v).reduce((function reducer(t,n){if(hasConstructorOf(t,e))return t.then((function(e){return reducer(e,n)}));var r=_slicedToArray(y.revivers[n],1)[0];if(!r)throw new Error("Unregistered type: "+n);return r[i&&r.revive?"revive":!i&&r.reviveAsync?"reviveAsync":"revive"](t,s)}),n)}}function checkUndefined(e){return hasConstructorOf(e,p)?void 0:e}var l,f=function revivePlainObjects(){var n=[];if(Object.entries(r).forEach((function(e){var t=_slicedToArray(e,2),i=t[0],o=t[1];"#"!==o&&[].concat(o).forEach((function(e){_slicedToArray(y.revivers[e],2)[1].plain&&(n.push({keypath:i,type:e}),delete r[i])}))})),n.length)return n.sort(nestedPathsFirst).reduce((function reducer(n,r){var o=r.keypath,a=r.type;if(hasConstructorOf(n,e))return n.then((function(e){return reducer(e,a)}));var c=getByKeyPath(t,o);if(hasConstructorOf(c,e))return c.then((function(e){return reducer(e,a)}));var u=_slicedToArray(y.revivers[a],1)[0];if(!u)throw new Error("Unregistered type: "+a);void 0!==(c=u[i&&u.revive?"revive":!i&&u.reviveAsync?"reviveAsync":"revive"](c,s))&&(hasConstructorOf(c,p)&&(c=void 0),function setAtKeyPath(e,t,n){if(""===t)return n;var r=t.indexOf(".");return r>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,r))],t.slice(r+1),n):(e[unescapeKeyPathComponent(t)]=n,e)}(t,o,c)===c&&(t=c))}),void 0)}();return isThenable(l=hasConstructorOf(f,e)?f.then((function(){return _revive("",t,null)})):_revive("",t,null))?i&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(l,e)?l.p.then(checkUndefined):l:!i&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():i?checkUndefined(l):Promise.resolve(checkUndefined(l))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread2({throwOnBadSyncType:!0},t,{sync:!1}))}},{key:"register",value:function register(e,t){return t=t||{},[].concat(e).forEach((function R(e){var n=this;if(a(e))return e.map((function(e){return R.call(n,e)}));e&&o(e).forEach((function(n){if("#"===n)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(Typeson.JSON_TYPES.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var r=e[n],i=r.testPlainObjects?this.plainObjectReplacers:this.nonplainObjectReplacers,o=i.filter((function(e){return e.type===n}));if(o.length&&(i.splice(i.indexOf(o[0]),1),delete this.revivers[n],delete this.types[n]),r){if("function"==typeof r){var c=r;r={test:function test(e){return e&&e.constructor===c},replace:function replace(e){return _objectSpread2({},e)},revive:function revive(e){return Object.assign(Object.create(c.prototype),e)}}}else if(a(r)){var s=_slicedToArray(r,3);r={test:s[0],replace:s[1],revive:s[2]}}var u={type:n,test:r.test.bind(r)};r.replace&&(u.replace=r.replace.bind(r)),r.replaceAsync&&(u.replaceAsync=r.replaceAsync.bind(r));var p="number"==typeof t.fallback?t.fallback:t.fallback?0:1/0;if(r.testPlainObjects?this.plainObjectReplacers.splice(p,0,u):this.nonplainObjectReplacers.splice(p,0,u),r.revive||r.reviveAsync){var y={};r.revive&&(y.revive=r.revive.bind(r)),r.reviveAsync&&(y.reviveAsync=r.reviveAsync.bind(r)),this.revivers[n]=[y,{plain:r.testPlainObjects}]}this.types[n]=r}}),this)}),this),this}}]),Typeson}(),p=function Undefined(){_classCallCheck(this,Undefined)};return p.__typeson__type__="TypesonUndefined",u.Undefined=p,u.Promise=e,u.isThenable=isThenable,u.toStringTag=toStringTag,u.hasConstructorOf=hasConstructorOf,u.isObject=isObject,u.isPlainObject=isPlainObject,u.isUserObject=function isUserObject(e){if(!e||"Object"!==toStringTag(e))return!1;var t=r(e);return!t||(hasConstructorOf(e,Object)||isUserObject(t))},u.escapeKeyPathComponent=escapeKeyPathComponent,u.unescapeKeyPathComponent=unescapeKeyPathComponent,u.getByKeyPath=getByKeyPath,u.getJSONType=function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)},u.JSON_TYPES=["null","boolean","number","string","array","object"],u})); |
{ | ||
"name": "typeson", | ||
"version": "5.13.0", | ||
"version": "5.14.0", | ||
"description": "Preserves types over JSON, BSON or socket.io", | ||
@@ -10,9 +10,15 @@ "main": "./dist/typeson-commonjs2.js", | ||
"prepublishOnly": "yarn", | ||
"eslint": "eslint --report-unused-disable-directives .", | ||
"eslint": "eslint --ext js,md,html .", | ||
"start": "static -p 8092", | ||
"rollup": "rollup -c", | ||
"browser-test": "npm run eslint && npm run rollup && open-cli http://localhost:8092/test/ && npm start", | ||
"browser-test": "npm run rollup && npm run eslint && open-cli http://localhost:8092/test/ && npm start", | ||
"open-coverage": "open-cli http://localhost:8092/coverage/ && npm start", | ||
"node-test": "node -r esm test/test.js", | ||
"test": "npm run eslint && npm run rollup && npm run node-test" | ||
"node-test-cov": "rm -Rf node_modules/.cache/esm && nyc --reporter=html --reporter=text node -r esm test/test.js", | ||
"test-cov": "npm run rollup && npm run eslint && npm run node-test-cov", | ||
"test": "npm run rollup && npm run eslint && npm run node-test" | ||
}, | ||
"nyc": { | ||
"exclude": ["instrumented/**", "test/**"] | ||
}, | ||
"repository": { | ||
@@ -42,27 +48,42 @@ "type": "git", | ||
"peerDependencies": { | ||
"core-js-bundle": "^3.1.3", | ||
"regenerator-runtime": "^0.13.2" | ||
"core-js-bundle": "^3.4.5", | ||
"regenerator-runtime": "^0.13.3" | ||
}, | ||
"dependencies": {}, | ||
"devDependencies": { | ||
"@babel/core": "^7.4.5", | ||
"@babel/preset-env": "^7.4.5", | ||
"@babel/core": "^7.7.4", | ||
"@babel/preset-env": "^7.7.4", | ||
"@mysticatea/eslint-plugin": "^13.0.0", | ||
"@rollup/plugin-replace": "^2.2.1", | ||
"base64-arraybuffer-es6": "^0.5.0", | ||
"core-js-bundle": "^3.1.3", | ||
"eslint": "5.16.0", | ||
"eslint-config-standard": "12.0.0", | ||
"eslint-plugin-compat": "3.1.1", | ||
"eslint-plugin-import": "2.17.3", | ||
"eslint-plugin-node": "9.1.0", | ||
"eslint-plugin-promise": "4.1.1", | ||
"eslint-plugin-standard": "4.0.0", | ||
"core-js-bundle": "^3.4.5", | ||
"eslint": "^6.7.2", | ||
"eslint-config-ash-nazg": "^13.1.0", | ||
"eslint-config-standard": "^14.1.0", | ||
"eslint-plugin-array-func": "^3.1.3", | ||
"eslint-plugin-compat": "^3.3.0", | ||
"eslint-plugin-eslint-comments": "^3.1.2", | ||
"eslint-plugin-html": "^6.0.0", | ||
"eslint-plugin-import": "^2.18.2", | ||
"eslint-plugin-jsdoc": "^18.4.1", | ||
"eslint-plugin-markdown": "^1.0.1", | ||
"eslint-plugin-no-use-extend-native": "^0.4.1", | ||
"eslint-plugin-node": "^10.0.0", | ||
"eslint-plugin-promise": "^4.2.1", | ||
"eslint-plugin-sonarjs": "^0.5.0", | ||
"eslint-plugin-standard": "^4.0.1", | ||
"eslint-plugin-unicorn": "^14.0.1", | ||
"esm": "^3.2.25", | ||
"node-static": "0.7.11", | ||
"nyc": "^14.1.1", | ||
"open-cli": "^5.0.0", | ||
"regenerator-runtime": "^0.13.2", | ||
"rollup": "1.13.1", | ||
"rollup-plugin-babel": "^4.3.2", | ||
"rollup-plugin-terser": "^5.0.0" | ||
"regenerator-runtime": "^0.13.3", | ||
"rollup": "1.27.8", | ||
"rollup-plugin-babel": "^4.3.3", | ||
"rollup-plugin-istanbul": "^2.0.1", | ||
"rollup-plugin-re": "^1.0.7", | ||
"rollup-plugin-terser": "^5.1.2", | ||
"typescript": "^3.7.2" | ||
}, | ||
"tonicExample": "var Typeson = require('typeson');\nvar TSON = new Typeson().register(require('typeson-registry/presets/builtin'));\n\nTSON.stringify({foo: new Date()}, null, 2);" | ||
} |
123
README.md
@@ -10,8 +10,16 @@ # typeson.js | ||
```js | ||
{foo: "bar"} // {"foo":"bar"} (simple types gives plain JSON) | ||
{foo: new Date()} // {"foo":1464049031538, "$types":{"foo":"Date"}} | ||
{foo: new Set([new Date()])} // {"foo":[1464127925971], "$types":{"foo":"Set","foo.0":"Date"}} | ||
{foo: {sub: /bar/i}} // {"foo":{"sub":{"source":"bar","flags":"i"}}, "$types":{"foo.sub":"RegExp"}} | ||
{foo: new Int8Array(3)} // {"foo":"AAAA", "$types":{"foo":"Int8Array"}} | ||
new Date() // {"$":1464128478593, "$types":{"$":{"":"Date"}}} (special format at root) | ||
const objs = [ | ||
{foo: 'bar'}, | ||
// {"foo":"bar"} (simple types gives plain JSON) | ||
{foo: new Date()}, | ||
// {"foo":1464049031538, "$types":{"foo":"Date"}} | ||
{foo: new Set([new Date()])}, | ||
// {"foo":[1464127925971], "$types":{"foo":"Set","foo.0":"Date"}} | ||
{foo: {sub: /bar/iu}}, | ||
// {"foo":{"sub":{"source":"bar","flags":"i"}}, "$types":{"foo.sub":"RegExp"}} | ||
{foo: new Int8Array(3)}, | ||
// {"foo":"AAAA", "$types":{"foo":"Int8Array"}} | ||
new Date() | ||
// {"$":1464128478593, "$types":{"$":{"":"Date"}}} (special format at root) | ||
]; | ||
``` | ||
@@ -35,3 +43,3 @@ | ||
``` | ||
or if you want support for all built-in javascript classes: | ||
or if you want support for all built-in JavaScript classes: | ||
```js | ||
@@ -42,3 +50,3 @@ const typeson = new Typeson().register([ | ||
``` | ||
The module `typeson-registry/presets/builtin` is 1.6 kb minizied and gzipped and adds support 32 builtin JavaScript types: *Date, RegExp, NaN, Infinity, -Infinity, Set, Map, ArrayBuffer, DataView, Uint8Array, Int8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, Error, SyntaxError, TypeError, RangeError, ReferenceError, EvalError, URIError, InternalError, Intl.Collator, Intl.DateTimeFormat, Intl.NumberFormat, Object String, Object Number and Object Boolean*. | ||
The module `typeson-registry/presets/builtin` is 1.6 kb minified and gzipped and adds support 32 builtin JavaScript types: *Date, RegExp, NaN, Infinity, -Infinity, Set, Map, ArrayBuffer, DataView, Uint8Array, Int8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, Error, SyntaxError, TypeError, RangeError, ReferenceError, EvalError, URIError, InternalError, Intl.Collator, Intl.DateTimeFormat, Intl.NumberFormat, Object String, Object Number and Object Boolean*. | ||
@@ -72,3 +80,4 @@ ## Compatibility | ||
```js | ||
// Require typeson. It's an UMD module so you could also use requirejs or plain script tags. | ||
// Require typeson. It's an UMD module so you could also use requirejs | ||
// or plain script tags. | ||
const Typeson = require('typeson'); | ||
@@ -78,12 +87,12 @@ | ||
Date: [ | ||
x => x instanceof Date, // test function | ||
d => d.getTime(), // encapsulator function | ||
number => new Date(number) // reviver function | ||
(x) => x instanceof Date, // test function | ||
(d) => d.getTime(), // encapsulator function | ||
(number) => new Date(number) // reviver function | ||
], | ||
Error: [ | ||
x => x instanceof Error, // tester | ||
e => ({name: e.name, message: e.message}), // encapsulator | ||
data => { | ||
(x) => x instanceof Error, // tester | ||
(e) => ({name: e.name, message: e.message}), // encapsulator | ||
(data) => { | ||
// reviver | ||
const e = new Error (data.message); | ||
const e = new Error(data.message); | ||
e.name = data.name; | ||
@@ -93,3 +102,3 @@ return e; | ||
], | ||
SimpleClass: SimpleClass // Default rules apply. See "register (typeSpec)" | ||
SimpleClass // Default rules apply. See "register (typeSpec)" | ||
}); | ||
@@ -104,4 +113,4 @@ | ||
date: new Date(), | ||
e: new Error("Oops"), | ||
c: new SimpleClass("bar") | ||
e: new Error('Oops'), | ||
c: new SimpleClass('bar') | ||
}); | ||
@@ -158,5 +167,5 @@ // Stringify using good old JSON.stringify() | ||
CustomClass: [ | ||
x => x instanceof CustomClass, | ||
c => {foo: c.foo, bar: c.bar}, | ||
o => new CustomClass(o.foo, o.bar) | ||
(x) => x instanceof CustomClass, | ||
(c) => ({foo: c.foo, bar: c.bar}), | ||
(o) => new CustomClass(o.foo, o.bar) | ||
] | ||
@@ -170,5 +179,5 @@ }); | ||
date: new Date(), | ||
error: new SyntaxError("Ooops!"), | ||
array: array, | ||
custom: new CustomClass("foo", "bar") | ||
error: new SyntaxError('Ooops!'), | ||
array, | ||
custom: new CustomClass('foo', 'bar') | ||
}; | ||
@@ -186,3 +195,4 @@ | ||
const revived = TSON.revive(data); | ||
// Here we have a true Date, SyntaxError, Float64Array and Custom to play with. | ||
// Here we have a true `Date`, `SyntaxError`, `Float64Array` | ||
// and `Custom` to play with. | ||
}); | ||
@@ -205,3 +215,3 @@ ``` | ||
```js | ||
new Typeson([options]); | ||
const typeson = new Typeson([options]); | ||
``` | ||
@@ -286,3 +296,3 @@ | ||
const typeson = new Typeson() | ||
.register (require('typeson-registry/presets/builtin')); | ||
.register(require('typeson-registry/presets/builtin')); | ||
@@ -337,6 +347,7 @@ const tson = typeson.stringify(complexObject); | ||
const TSON = new Typeson().register(require('typeson-registry/types/date')); | ||
TSON.stringify ({date: new Date()}); | ||
TSON.stringify({date: new Date()}); | ||
``` | ||
Output: | ||
```js | ||
```json | ||
{"date": 1463667643065, "$types": {"date": "Date"}} | ||
@@ -367,4 +378,6 @@ ``` | ||
```js | ||
const TSON = new Typeson().register(require('typeson-registry/types/date')); | ||
TSON.parse ('{"date": 1463667643065, "$types": {"date": "Date"}}'); | ||
const date = require('typeson-registry/types/date'); | ||
const TSON = new Typeson().register(date); | ||
TSON.parse('{"date": 1463667643065, "$types": {"date": "Date"}}'); | ||
``` | ||
@@ -402,3 +415,3 @@ | ||
const revived = typeson.revive(encapsulated); | ||
assert (revived instanceof Date); | ||
assert(revived instanceof Date); | ||
``` | ||
@@ -419,3 +432,3 @@ | ||
`{TypeName => constructor-function | [tester, encapsulator, reviver] | specObject = {test: function, replace: function, revive: function, testPlainObjects: boolean=false}}` or an array of such structures. | ||
`{TypeName => constructor-function | [tester, encapsulator, reviver] | specObject = {test: function, replace: function, replaceAsync: function, revive: function, reviveAsync: function, testPlainObjects: boolean=false}}` or an array of such structures. | ||
@@ -501,3 +514,3 @@ Please note that if an array is supplied, the tester (and upon matching, the encapsulator) | ||
function CustomType(foo) { | ||
function CustomType (foo) { | ||
this.foo = foo; | ||
@@ -509,3 +522,3 @@ } | ||
// This style works for any trivial js class without hidden closures. | ||
CustomType: CustomType, | ||
CustomType, | ||
@@ -515,11 +528,11 @@ // Date is native and hides it's internal state. | ||
Date: [ | ||
x => x instanceof Date, // tester | ||
date => date.getTime(), // encapsulator | ||
obj => new Date(obj) // reviver | ||
(x) => x instanceof Date, // tester | ||
(date) => date.getTime(), // encapsulator | ||
(obj) => new Date(obj) // reviver | ||
], | ||
RegExp: [ | ||
x = x instanceof RegExp, | ||
re => [re.source, re.flags], | ||
a => new RegExp (a[0], a[1]) | ||
(x) = x instanceof RegExp, | ||
(re) => [re.source, re.flags], | ||
([source, flags]) => new RegExp(source, flags) | ||
] | ||
@@ -529,7 +542,8 @@ }); | ||
console.log(typeson.stringify({ | ||
ct: new CustomType("hello"), | ||
ct: new CustomType('hello'), | ||
d: new Date(), | ||
r:/foo/gi | ||
r: /foo/giu | ||
})); | ||
// {"ct":{"foo":"hello"},"d":1464049031538,"r":["foo","gi"],$types:{"ct":"CustomType","d":"Date","r":"RegExp"}} | ||
// {"ct":{"foo":"hello"},"d":1464049031538,"r":["foo","gi"], | ||
// $types:{"ct":"CustomType","d":"Date","r":"RegExp"}} | ||
``` | ||
@@ -591,6 +605,11 @@ | ||
myAsyncType: [ | ||
function (x) { return x instanceof MyAsync;}, | ||
function (x) { return x instanceof MyAsync; }, | ||
function (o) { | ||
return new Typeson.Promise(function (resolve, reject) { | ||
setTimeout(function () { // Do something more useful in real code | ||
setTimeout(function () { | ||
// Do something more useful in real code | ||
if (new Date().getTime() % 2) { | ||
reject(new Error('Better luck next time')); | ||
return; | ||
} | ||
resolve(o.prop); | ||
@@ -607,6 +626,8 @@ }, 800); | ||
const mya = new MyAsync(500); | ||
return typeson.stringify(mya).then(function (result) { | ||
const back = typeson.parse(result, null, {sync: true}); | ||
console.log(back.prop); // 500 | ||
}); | ||
(async () => { | ||
const result = await typeson.stringify(mya); | ||
const back = typeson.parse(result, null, {sync: true}); | ||
console.log(back.prop); // 500 | ||
})(); | ||
``` | ||
@@ -613,0 +634,0 @@ |
142
typeson.js
@@ -0,1 +1,2 @@ | ||
/* eslint-disable node/no-unsupported-features/es-syntax, no-shadow */ | ||
/** | ||
@@ -22,5 +23,11 @@ * Typeson - JSON with types | ||
/** | ||
* | ||
* @param {PlainObjectType} a | ||
* @param {PlainObjectType} b | ||
* @returns {1|-1|boolean} | ||
*/ | ||
function nestedPathsFirst (a, b) { | ||
let as = a.keypath.match(/\./g); | ||
let bs = a.keypath.match(/\./g); | ||
let as = a.keypath.match(/\./gu); | ||
let bs = a.keypath.match(/\./gu); | ||
if (as) { | ||
@@ -46,3 +53,3 @@ as = as.length; | ||
* | ||
* @constructor | ||
* @class | ||
* @param {{cyclic: boolean}} [options] - if cyclic (default true), | ||
@@ -69,7 +76,19 @@ * cyclic references will be handled gracefully. | ||
/** | ||
* @typedef {null|boolean|number|string|GenericArray|PlainObject} JSON | ||
*/ | ||
/** | ||
* @callback JSONReplacer | ||
* @param {""|string} key | ||
* @param {JSON} value | ||
* @returns {number|string|boolean|null|PlainObject|undefined} | ||
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20replacer%20parameter | ||
*/ | ||
/** | ||
* Serialize given object to Typeson. | ||
* Initial arguments work identical to those of `JSON.stringify`. | ||
* The `replacer` argument has nothing to do with our replacers. | ||
* @param {*} obj | ||
* @param {function|string[]} replacer | ||
* @param {Any} obj | ||
* @param {JSONReplacer|string[]} replacer | ||
* @param {number|string} space | ||
@@ -91,5 +110,5 @@ * @param {object} opts | ||
/** | ||
* Also sync but throws on non-sync result | ||
* @param {*} obj | ||
* @param {function|string[]} replacer | ||
* Also sync but throws on non-sync result. | ||
* @param {Any} obj | ||
* @param {JSONReplacer|string[]} replacer | ||
* @param {number|string} space | ||
@@ -107,7 +126,7 @@ * @param {object} opts | ||
* | ||
* @param {*} obj | ||
* @param {function|string[]} replacer | ||
* @param {Any} obj | ||
* @param {JSONReplacer|string[]} replacer | ||
* @param {number|string} space | ||
* @param {object} opts | ||
* @returns {Promise} Resolves to string | ||
* @returns {Promise<string>} | ||
*/ | ||
@@ -135,3 +154,3 @@ stringifyAsync (obj, replacer, space, opts) { | ||
/** | ||
* Also sync but throws on non-sync result | ||
* Also sync but throws on non-sync result. | ||
* @param {string} text | ||
@@ -167,3 +186,3 @@ * @param {function} reviver This JSON reviver has nothing to do with | ||
* | ||
* @param {*} obj | ||
* @param {Any} obj | ||
* @param {object} stateObj | ||
@@ -180,6 +199,6 @@ * @param {object} [opts={}] | ||
* | ||
* @param {*} obj | ||
* @param {object} stateObj | ||
* @param {object} [opts={}] | ||
* @returns {Promise|Array|object|string|false} | ||
* @param {Any} obj | ||
* @param {PlainObject} stateObj | ||
* @param {PlainObject} [opts={}] | ||
* @returns {Promise|GenericArray|PlainObject|string|false} | ||
*/ | ||
@@ -195,7 +214,7 @@ rootTypeName (obj, stateObj, opts = {}) { | ||
* | ||
* This method is used internally by T`ypeson.stringify()`. | ||
* @param {Object} obj - Object to encapsulate. | ||
* @param {object} stateObj | ||
* @param {object} opts | ||
* @returns {Promise|Array|object|string|false} | ||
* This method is used internally by `Typeson.stringify()`. | ||
* @param {Any} obj - Object to encapsulate. | ||
* @param {PlainObject} stateObj | ||
* @param {PlainObject} opts | ||
* @returns {Promise|GenericArray|PlainObject|string|false} | ||
*/ | ||
@@ -223,4 +242,4 @@ encapsulate (obj, stateObj, opts) { | ||
* | ||
* @param {*} ret | ||
* @returns {Array|object|string|false} | ||
* @param {Any} ret | ||
* @returns {GenericArray|PlainObject|string|false} | ||
*/ | ||
@@ -264,5 +283,5 @@ function finish (ret) { | ||
* | ||
* @param {*} ret | ||
* @param {array} promisesData | ||
* @returns {Promise} Resolves to ... | ||
* @param {Any} ret | ||
* @param {GenericArray} promisesData | ||
* @returns {Promise<Any>} | ||
*/ | ||
@@ -333,2 +352,3 @@ async function checkPromises (ret, promisesData) { | ||
}); | ||
// eslint-disable-next-line callback-return | ||
cb(); | ||
@@ -343,9 +363,9 @@ internalStateObjPropsToIgnore.forEach((prop, i) => { | ||
* @param {string} keypath | ||
* @param {*} value | ||
* @param {Any} value | ||
* @param {boolean} cyclic | ||
* @param {object} stateObj | ||
* @param {PlainObject} stateObj | ||
* @param {boolean} promisesData | ||
* @param {boolean} resolvingTypesonPromise | ||
* @param {string} detectedType | ||
* @returns {*} | ||
* @returns {Any} | ||
*/ | ||
@@ -451,2 +471,3 @@ function _encapsulate ( | ||
} else { | ||
// eslint-disable-next-line no-lonely-if | ||
if ((isArr && stateObj.iterateIn !== 'object') || | ||
@@ -489,2 +510,3 @@ stateObj.iterateIn === 'array' | ||
if (stateObj.iterateIn) { | ||
// eslint-disable-next-line guard-for-in | ||
for (const key in value) { | ||
@@ -499,3 +521,3 @@ const ownKeysObj = {ownKeys: hasOwn.call(value, key)}; | ||
const val = _encapsulate( | ||
kp, value[key], !!cyclic, stateObj, | ||
kp, value[key], Boolean(cyclic), stateObj, | ||
promisesData, resolvingTypesonPromise | ||
@@ -505,3 +527,3 @@ ); | ||
promisesData.push([ | ||
kp, val, !!cyclic, stateObj, | ||
kp, val, Boolean(cyclic), stateObj, | ||
clone, key, stateObj.type | ||
@@ -532,3 +554,3 @@ ]); | ||
const val = _encapsulate( | ||
kp, value[key], !!cyclic, stateObj, | ||
kp, value[key], Boolean(cyclic), stateObj, | ||
promisesData, resolvingTypesonPromise | ||
@@ -538,3 +560,3 @@ ); | ||
promisesData.push([ | ||
kp, val, !!cyclic, stateObj, | ||
kp, val, Boolean(cyclic), stateObj, | ||
clone, key, stateObj.type | ||
@@ -568,3 +590,3 @@ ]); | ||
const val = _encapsulate( | ||
kp, undefined, !!cyclic, stateObj, | ||
kp, undefined, Boolean(cyclic), stateObj, | ||
promisesData, resolvingTypesonPromise | ||
@@ -574,3 +596,3 @@ ); | ||
promisesData.push([ | ||
kp, val, !!cyclic, stateObj, | ||
kp, val, Boolean(cyclic), stateObj, | ||
clone, i, stateObj.type | ||
@@ -595,5 +617,5 @@ ]); | ||
* @param {string} keypath | ||
* @param {*} value | ||
* @param {object} stateObj | ||
* @param {array} promisesData | ||
* @param {Any} value | ||
* @param {PlainObject} stateObj | ||
* @param {GenericArray} promisesData | ||
* @param {boolean} plainObject | ||
@@ -691,3 +713,3 @@ * @param {boolean} resolvingTypesonPromise | ||
/** | ||
* Also sync but throws on non-sync result | ||
* Also sync but throws on non-sync result. | ||
* @param {*} obj | ||
@@ -756,2 +778,6 @@ * @param {object} stateObj | ||
const that = this; | ||
/** | ||
* | ||
* @returns {void|TypesonPromise<void>} | ||
*/ | ||
function revivePlainObjects () { | ||
@@ -784,4 +810,9 @@ // const references = []; | ||
if (!plainObjectTypes.length) { | ||
return; | ||
return undefined; | ||
} | ||
/** | ||
* @typedef {PlainObject} PlainObjectType | ||
* @property {string} keypath | ||
* @property {string} type | ||
*/ | ||
// Handle plain object revivers first so reference | ||
@@ -842,7 +873,7 @@ // setting can use revived type (e.g., array instead | ||
* @param {string} keypath | ||
* @param {*} value | ||
* @param {Any} value | ||
* @param {?(Array|object)} target | ||
* @param {Array|object} [clone] | ||
* @param {string} [key] | ||
* @returns {*} | ||
* @returns {Any} | ||
*/ | ||
@@ -918,2 +949,7 @@ function _revive (keypath, value, target, clone, key) { | ||
/** | ||
* | ||
* @param {Any} retrn | ||
* @returns {undefined|Any} | ||
*/ | ||
function checkUndefined (retrn) { | ||
@@ -955,6 +991,6 @@ return hasConstructorOf(retrn, Undefined) ? undefined : retrn; | ||
/** | ||
* Also sync but throws on non-sync result | ||
* @param {*} obj | ||
* Also sync but throws on non-sync result. | ||
* @param {Any} obj | ||
* @param {object} opts | ||
* @returns {*} | ||
* @returns {Any} | ||
*/ | ||
@@ -968,3 +1004,3 @@ reviveSync (obj, opts) { | ||
/** | ||
* @param {*} obj | ||
* @param {Any} obj | ||
* @param {object} opts | ||
@@ -982,4 +1018,4 @@ * @returns {Promise} Resolves to `*` | ||
* For examples on how to use this method, see | ||
* {@link https://github.com/dfahlander/typeson-registry/tree/master/types} | ||
* @param {Array.<Object.<string,Function[]>>} typeSpecSets - Types and | ||
* {@link https://github.com/dfahlander/typeson-registry/tree/master/types}. | ||
* @param {object.<string,Function[]>[]} typeSpecSets - Types and | ||
* their functions [test, encapsulate, revive]; | ||
@@ -994,3 +1030,3 @@ * @param {object} opts | ||
if (isArray(typeSpec)) { | ||
return typeSpec.map(R, this); | ||
return typeSpec.map((typSpec) => R.call(this, typSpec)); | ||
} | ||
@@ -1029,3 +1065,3 @@ typeSpec && keys(typeSpec).forEach(function (typeId) { | ||
test: (x) => x && x.constructor === Class, | ||
replace: (x) => Object.assign({}, x), | ||
replace: (x) => ({...x}), | ||
revive: (x) => Object.assign( | ||
@@ -1083,6 +1119,8 @@ Object.create(Class.prototype), x | ||
* with `hasConstructorOf`. | ||
* @constructor | ||
* @class | ||
*/ | ||
class Undefined{} // eslint-disable-line space-before-blocks | ||
Undefined.__typeson__type__ = 'TypesonUndefined'; | ||
// The following provide classes meant to avoid clashes with other values | ||
@@ -1089,0 +1127,0 @@ |
@@ -1,2 +0,2 @@ | ||
const {toString} = {}, | ||
const {toString: toStr} = {}, | ||
hasOwn = ({}.hasOwnProperty), | ||
@@ -8,3 +8,3 @@ getProto = Object.getPrototypeOf, | ||
* | ||
* @param {*} v | ||
* @param {Any} v | ||
* @param {boolean} catchCheck | ||
@@ -21,7 +21,7 @@ * @returns {boolean} | ||
* | ||
* @param {*} val | ||
* @param {Any} val | ||
* @returns {string} | ||
*/ | ||
function toStringTag (val) { | ||
return toString.call(val).slice(8, -1); | ||
return toStr.call(val).slice(8, -1); | ||
} | ||
@@ -32,3 +32,3 @@ | ||
* being identical so any minimization is expected of both. | ||
* @param {*} a | ||
* @param {Any} a | ||
* @param {function} b | ||
@@ -49,4 +49,15 @@ * @returns {boolean} | ||
} | ||
return typeof Ctor === 'function' && b !== null && | ||
fnToString.call(Ctor) === fnToString.call(b); | ||
if (b === Ctor) { | ||
return true; | ||
} | ||
if (b !== null && fnToString.call(Ctor) === fnToString.call(b)) { | ||
return true; | ||
} | ||
if (typeof b === 'function' && | ||
typeof Ctor.__typeson__type__ === 'string' && | ||
Ctor.__typeson__type__ === b.__typeson__type__ | ||
) { | ||
return true; | ||
} | ||
return false; | ||
} | ||
@@ -56,3 +67,3 @@ | ||
* | ||
* @param {*} val | ||
* @param {Any} val | ||
* @returns {boolean} | ||
@@ -75,3 +86,3 @@ */ | ||
* | ||
* @param {*} val | ||
* @param {Any} val | ||
* @returns {boolean} | ||
@@ -93,3 +104,3 @@ */ | ||
* | ||
* @param {*} v | ||
* @param {Any} v | ||
* @returns {boolean} | ||
@@ -107,3 +118,3 @@ */ | ||
function escapeKeyPathComponent (keyPathComponent) { | ||
return keyPathComponent.replace(/~/g, '~0').replace(/\./g, '~1'); | ||
return keyPathComponent.replace(/~/gu, '~0').replace(/\./gu, '~1'); | ||
} | ||
@@ -117,9 +128,9 @@ | ||
function unescapeKeyPathComponent (keyPathComponent) { | ||
return keyPathComponent.replace(/~1/g, '.').replace(/~0/g, '~'); | ||
return keyPathComponent.replace(/~1/gu, '.').replace(/~0/gu, '~'); | ||
} | ||
/** | ||
* @param {object|array} obj | ||
* @param {PlainObject|GenericArray} obj | ||
* @param {string} keyPath | ||
* @returns {*} | ||
* @returns {Any} | ||
*/ | ||
@@ -133,7 +144,7 @@ function getByKeyPath (obj, keyPath) { | ||
const innerObj = obj[ | ||
unescapeKeyPathComponent(keyPath.substr(0, period)) | ||
unescapeKeyPathComponent(keyPath.slice(0, period)) | ||
]; | ||
return innerObj === undefined | ||
? undefined | ||
: getByKeyPath(innerObj, keyPath.substr(period + 1)); | ||
: getByKeyPath(innerObj, keyPath.slice(period + 1)); | ||
} | ||
@@ -143,2 +154,9 @@ return obj[unescapeKeyPathComponent(keyPath)]; | ||
/** | ||
* | ||
* @param {PlainObject} obj | ||
* @param {string} keyPath | ||
* @param {Any} value | ||
* @returns {Any} | ||
*/ | ||
function setAtKeyPath (obj, keyPath, value) { | ||
@@ -151,5 +169,5 @@ if (keyPath === '') { | ||
const innerObj = obj[ | ||
unescapeKeyPathComponent(keyPath.substr(0, period)) | ||
unescapeKeyPathComponent(keyPath.slice(0, period)) | ||
]; | ||
return setAtKeyPath(innerObj, keyPath.substr(period + 1), value); | ||
return setAtKeyPath(innerObj, keyPath.slice(period + 1), value); | ||
} | ||
@@ -163,9 +181,12 @@ obj[unescapeKeyPathComponent(keyPath)] = value; | ||
* @param {external:JSON} value | ||
* @returns {"null"|"array"|"undefined"|"boolean"|"number"|"string"|"object"|"symbol"} | ||
* @returns {"null"|"array"|"undefined"|"boolean"|"number"|"string"| | ||
* "object"|"symbol"} | ||
*/ | ||
function getJSONType (value) { | ||
return value === null ? 'null' : ( | ||
Array.isArray(value) | ||
? 'array' | ||
: typeof value); | ||
return value === null | ||
? 'null' | ||
: ( | ||
Array.isArray(value) | ||
? 'array' | ||
: typeof value); | ||
} | ||
@@ -172,0 +193,0 @@ |
@@ -9,5 +9,10 @@ /** | ||
*/ | ||
class TypesonPromise{constructor(f){this.p=new Promise(f)}} // eslint-disable-line block-spacing, space-before-function-paren, space-before-blocks, space-infix-ops, semi | ||
// eslint-disable-next-line max-len | ||
// eslint-disable-next-line block-spacing, space-before-function-paren, space-before-blocks, space-infix-ops, semi, promise/avoid-new | ||
class TypesonPromise{constructor(f){this.p=new Promise(f)}} | ||
// eslint-disable-next-line max-len | ||
// class TypesonPromise extends Promise {get[Symbol.toStringTag](){return 'TypesonPromise'};} // eslint-disable-line keyword-spacing, space-before-function-paren, space-before-blocks, block-spacing, semi | ||
TypesonPromise.__typeson__type__ = 'TypesonPromise'; | ||
// Note: core-js-bundle provides a `Symbol` polyfill | ||
@@ -27,9 +32,9 @@ if (typeof Symbol !== 'undefined') { | ||
return new TypesonPromise((typesonResolve, typesonReject) => { | ||
// eslint-disable-next-line promise/catch-or-return | ||
this.p.then(function (res) { | ||
// eslint-disable-next-line promise/always-return | ||
typesonResolve(onFulfilled ? onFulfilled(res) : res); | ||
}, (r) => { | ||
this.p['catch'](function (res) { | ||
return onRejected ? onRejected(res) : Promise.reject(res); | ||
}).then(typesonResolve, typesonReject); | ||
}); | ||
}).catch(function (res) { | ||
return onRejected ? onRejected(res) : Promise.reject(res); | ||
}).then(typesonResolve, typesonReject); | ||
}); | ||
@@ -48,3 +53,3 @@ }; | ||
* | ||
* @param {} v | ||
* @param {Any} v | ||
* @returns {TypesonPromise} | ||
@@ -59,3 +64,3 @@ */ | ||
* | ||
* @param {} v | ||
* @param {Any} v | ||
* @returns {TypesonPromise} | ||
@@ -68,3 +73,3 @@ */ | ||
}; | ||
['all', 'race'].map(function (meth) { | ||
['all', 'race'].forEach(function (meth) { | ||
/** | ||
@@ -77,2 +82,3 @@ * | ||
return new TypesonPromise(function (typesonResolve, typesonReject) { | ||
// eslint-disable-next-line promise/catch-or-return | ||
Promise[meth](promArr.map((prom) => { | ||
@@ -79,0 +85,0 @@ return prom.p; |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
698
0
243335
33
12
4248