UNPKG

@cloudflare/redux-grim

Version:

Generator for asynchronous Redux endpoint actions and reducers

3 lines (2 loc) 19.4 kB
function addHooks(e,t){e.on=function(r,n){if(!r in t)throw"invalid hook "+r;var o=t[r];return t[r]=o?function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),a=1;a<t;a++)r[a-1]=arguments[a];return n.apply(void 0,[o.apply(void 0,[e].concat(r))].concat(r))}:n,e}}var _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},asyncToGenerator=function(e){return function(){var t=e.apply(this,arguments);return new Promise(function(e,r){return function n(o,a){try{var i=t[o](a),s=i.value}catch(e){return void r(e)}if(!i.done)return Promise.resolve(s).then(function(e){n("next",e)},function(e){n("throw",e)});e(s)}("next")})}},defineProperty=function(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},slicedToArray=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],n=!0,o=!1,a=void 0;try{for(var i,s=e[Symbol.iterator]();!(n=(i=s.next()).done)&&(r.push(i.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{!n&&s.return&&s.return()}finally{if(o)throw a}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),toArray=function(e){return Array.isArray(e)?e:Array.from(e)},toConsumableArray=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)},bodyMethods=["put","patch","post"],parensReg=/\(([^)]+)\)/g,squareParensReg=/\[([^)]+)\]/g,defaultHooks={start:function(e,t,r,n){return e},success:function(e,t,r,n){return e},error:function(e,t,r,n){return e},all:function(e,t,r,n){return e}},defaultFunctions={apiFetch:function(e,t,r){return fetch(t,{method:e.toUpperCase(),body:JSON.stringify(r)})}};function hasBodyParam(e,t){return bodyMethods.includes(e)||"delete"===e&&t.includes("[")}function getNamedParameters(e,t){for(var r=new Set,n=void 0;n=parensReg.exec(t);){var o=n[1],a=o.indexOf(".");r.add(-1===a?o:o.substr(0,o.indexOf(".")))}return hasBodyParam(e,t)&&r.add("body"),r.size?[].concat(toConsumableArray(r)):[]}function makeUrlEvaluator(e){var t=e.replace(parensReg,"$${params.$1}").replace("[]","").replace(squareParensReg,"$${params.body.$1}");return new Function("params","return `"+t+"`;")}function makeGetApiData(e,t){var r=makeUrlEvaluator(e);return function(){for(var e=arguments.length,n=Array(e),o=0;o<e;o++)n[o]=arguments[o];var a=t.reduce(function(e,t,r){return e[t]=n[r],e},{});return{url:r(a),params:a,restArgs:n.slice(t.length)}}}function makeActionCreator(e,t,r){var n=this,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},a=getNamedParameters(t,r);o.debug&&logActionCreation(e,t,r,a);var i=_extends({},defaultHooks),s=_extends({},defaultFunctions),u=makeGetApiData(r,a),c=function(){for(var c=arguments.length,l=Array(c),f=0;f<c;f++)l[f]=arguments[f];return p=asyncToGenerator(regeneratorRuntime.mark(function c(f){var p,d,y,m,h,v,b,g,w;return regeneratorRuntime.wrap(function(n){for(;;)switch(n.prev=n.next){case 0:return o.debug&&validateActionParameters(e,t,r,l,a),p=u.apply(void 0,l),d=p.url,y=p.params,m=p.restArgs,h={type:e+".start",meta:{entityType:e,method:t}},h=i.start(h,y,m,o),h=i.all(h,y,m,o),f(h),n.prev=6,n.next=9,s.apiFetch.apply(s,[t,d,y.body].concat(toConsumableArray(m)));case 9:return v=n.sent,b={type:e+".success",payload:v,meta:{entityType:e,method:t}},b=i.success(b,y,m,o,v),b=i.all(b,y,m,o,v),g=b.payload,f(b),n.abrupt("return",g);case 18:throw n.prev=18,n.t0=n.catch(6),w={type:e+".error",payload:n.t0,error:!0,meta:{entityType:e,method:t}},w=i.error(w,y,m,o,n.t0),w=i.all(w,y,m,o,n.t0),f(w),n.t0;case 25:case"end":return n.stop()}},c,n,[[6,18]])})),function(e){return p.apply(this,arguments)};var p};return addHooks(c,i),c.apiFetch=function(e){return s.apiFetch=e,c},c}function logActionCreation(e,t,r,n){console.log("Created action "+e+", "+r+", "+t+"("+n.join(", ")+")")}function validateActionParameters(e,t,r,n,o){var a=r.indexOf("[")>-1||["post","put","patch"].includes(t);n.length<o.length&&console.warn("For api call "+e+", "+t+", "+r+",\n Expected parameters: "+o.join(", ")+"\n Actual parameters: "+n.join(", ")+"\n "),o.forEach(function(i,s){var u=_typeof(n[s]);a&&s===o.length-1?"object"!==u&&console.warn(e+", "+t+", "+r+": Expected parameter "+i+" to be an object. Actual value: "+n[s]+" "+u):"string"!==u&&"number"!==u&&console.warn(e+", "+t+", "+r+": Expected parameter "+i+" to be a string or number. Actual value: "+n[s])})}function createCommonjsModule(e,t){return e(t={exports:{}},t.exports),t.exports}var seamlessImmutable_development=createCommonjsModule(function(e,t){!function(){var t=function e(t){var r,n="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element"),o=60103,a={use_static:!1};function i(e){var t=Object.getPrototypeOf(e);return t?Object.create(t):{}}function s(e,t,r){Object.defineProperty(e,t,{enumerable:!1,configurable:!1,writable:!1,value:r})}function u(e,t){s(e,t,function(){throw new v("The "+t+" method cannot be invoked on an Immutable data structure.")})}"object"!=typeof(r=t)||Array.isArray(r)||null===r||void 0!==t.use_static&&(a.use_static=Boolean(t.use_static));var c="__immutable_invariants_hold";function l(e){return"object"!=typeof e||null===e||Boolean(Object.getOwnPropertyDescriptor(e,c))}function f(e,t){return e===t||e!=e&&t!=t}function p(e){return!(null===e||"object"!=typeof e||Array.isArray(e)||e instanceof Date)}var d=["setPrototypeOf"],y=d.concat(["push","pop","sort","splice","shift","unshift","reverse"]),m=["keys"].concat(["map","filter","slice","concat","reduce","reduceRight"]),h=d.concat(["setDate","setFullYear","setHours","setMilliseconds","setMinutes","setMonth","setSeconds","setTime","setUTCDate","setUTCFullYear","setUTCHours","setUTCMilliseconds","setUTCMinutes","setUTCMonth","setUTCSeconds","setYear"]);function v(e){this.name="MyError",this.message=e,this.stack=(new Error).stack}function b(e,t){for(var r in s(e,c,!0),t)t.hasOwnProperty(r)&&u(e,t[r]);return Object.freeze(e),e}function g(e,t){var r=e[t];s(e,t,function(){return J(r.apply(e,arguments))})}function w(e,t,r){var n=r&&r.deep;if(e in this&&(n&&this[e]!==t&&p(t)&&p(this[e])&&(t=J.merge(this[e],t,{deep:!0,mode:"replace"})),f(this[e],t)))return this;var o=T.call(this);return o[e]=J(t),P(o)}v.prototype=new Error,v.prototype.constructor=Error;var A=J([]);function _(e,t,r){var n=e[0];if(1===e.length)return w.call(this,n,t,r);var o,a=e.slice(1),i=this[n];if("object"==typeof i&&null!==i)o=J.setIn(i,a,t);else{var s=a[0];o=""!==s&&isFinite(s)?_.call(A,a,t):F.call(D,a,t)}if(n in this&&i===o)return this;var u=T.call(this);return u[n]=o,P(u)}function P(e){for(var t in m)m.hasOwnProperty(t)&&g(e,m[t]);a.use_static||(s(e,"flatMap",j),s(e,"asObject",S),s(e,"asMutable",T),s(e,"set",w),s(e,"setIn",_),s(e,"update",$),s(e,"updateIn",H),s(e,"getIn",N));for(var r=0,n=e.length;r<n;r++)e[r]=J(e[r]);return b(e,y)}function O(){return new Date(this.getTime())}function j(e){if(0===arguments.length)return this;var t,r=[],n=this.length;for(t=0;t<n;t++){var o=e(this[t],t,this);Array.isArray(o)?r.push.apply(r,o):r.push(o)}return P(r)}function I(e){if(void 0===e&&0===arguments.length)return this;if("function"!=typeof e){var t=Array.isArray(e)?e.slice():Array.prototype.slice.call(arguments);t.forEach(function(e,t,r){"number"==typeof e&&(r[t]=e.toString())}),e=function(e,r){return-1!==t.indexOf(r)}}var r=i(this);for(var n in this)this.hasOwnProperty(n)&&!1===e(this[n],n)&&(r[n]=this[n]);return G(r)}function T(e){var t,r,n=[];if(e&&e.deep)for(t=0,r=this.length;t<r;t++)n.push(x(this[t]));else for(t=0,r=this.length;t<r;t++)n.push(this[t]);return n}function S(e){"function"!=typeof e&&(e=function(e){return e});var t,r={},n=this.length;for(t=0;t<n;t++){var o=e(this[t],t,this),a=o[0],i=o[1];r[a]=i}return G(r)}function x(e){return!e||"object"!=typeof e||!Object.getOwnPropertyDescriptor(e,c)||e instanceof Date?e:J.asMutable(e,{deep:!0})}function R(e,t){for(var r in e)Object.getOwnPropertyDescriptor(e,r)&&(t[r]=e[r]);return t}function E(e,t){if(0===arguments.length)return this;if(null===e||"object"!=typeof e)throw new TypeError("Immutable#merge can only be invoked with objects or arrays, not "+JSON.stringify(e));var r,n,o=Array.isArray(e),a=t&&t.deep,s=t&&t.mode||"merge",u=t&&t.merger;function c(e,n,o){var s,c=J(n[o]),l=u&&u(e[o],c,t),d=e[o];void 0===r&&void 0===l&&e.hasOwnProperty(o)&&f(c,d)||f(d,s=l||(a&&p(d)&&p(c)?J.merge(d,c,t):c))&&e.hasOwnProperty(o)||(void 0===r&&(r=R(e,i(e))),r[o]=s)}if(o)for(var l=0,d=e.length;l<d;l++){var y=e[l];for(n in y)y.hasOwnProperty(n)&&c(void 0!==r?r:this,y,n)}else{for(n in e)Object.getOwnPropertyDescriptor(e,n)&&c(this,e,n);"replace"===s&&function(e,t){for(var n in e)t.hasOwnProperty(n)||(void 0===r&&(r=R(e,i(e))),delete r[n])}(this,e)}return void 0===r?this:G(r)}function k(e,t){var r=t&&t.deep;if(0===arguments.length)return this;if(null===e||"object"!=typeof e)throw new TypeError("Immutable#replace can only be invoked with objects or arrays, not "+JSON.stringify(e));return J.merge(this,e,{deep:r,mode:"replace"})}var C,M,z,D=J({});function F(e,t,r){if(!Array.isArray(e)||0===e.length)throw new TypeError('The first argument to Immutable#setIn must be an array containing at least one "key" string.');var n=e[0];if(1===e.length)return U.call(this,n,t,r);var o,a=e.slice(1),s=this[n];if(o=this.hasOwnProperty(n)&&"object"==typeof s&&null!==s?J.setIn(s,a,t):F.call(D,a,t),this.hasOwnProperty(n)&&s===o)return this;var u=R(this,i(this));return u[n]=o,G(u)}function U(e,t,r){var n=r&&r.deep;if(this.hasOwnProperty(e)&&(n&&this[e]!==t&&p(t)&&p(this[e])&&(t=J.merge(this[e],t,{deep:!0,mode:"replace"})),f(this[e],t)))return this;var o=R(this,i(this));return o[e]=J(t),G(o)}function $(e,t){var r=Array.prototype.slice.call(arguments,2),n=this[e];return J.set(this,e,t.apply(n,[n].concat(r)))}function q(e,t){for(var r=0,n=t.length;null!=e&&r<n;r++)e=e[t[r]];return r&&r==n?e:void 0}function H(e,t){var r=Array.prototype.slice.call(arguments,2),n=q(this,e);return J.setIn(this,e,t.apply(n,[n].concat(r)))}function N(e,t){var r=q(this,e);return void 0===r?t:r}function B(e){var t,r=i(this);if(e&&e.deep)for(t in this)this.hasOwnProperty(t)&&(r[t]=x(this[t]));else for(t in this)this.hasOwnProperty(t)&&(r[t]=this[t]);return r}function K(){return{}}function G(e){return a.use_static||(s(e,"merge",E),s(e,"replace",k),s(e,"without",I),s(e,"asMutable",B),s(e,"set",U),s(e,"setIn",F),s(e,"update",$),s(e,"updateIn",H),s(e,"getIn",N)),b(e,d)}function J(e,t,r){if(l(e)||function(e){return"object"==typeof e&&null!==e&&(e.$$typeof===o||e.$$typeof===n)}(e)||function(e){return"undefined"!=typeof File&&e instanceof File}(e)||function(e){return"undefined"!=typeof Blob&&e instanceof Blob}(e)||function(e){return e instanceof Error}(e))return e;if(function(e){return"object"==typeof e&&"function"==typeof e.then}(e))return e.then(J);if(Array.isArray(e))return P(e.slice());if(e instanceof Date)return i=new Date(e.getTime()),a.use_static||s(i,"asMutable",O),b(i,h);var i,u=t&&t.prototype,c=(u&&u!==Object.prototype?function(){return Object.create(u)}:K)();if(null==r&&(r=64),r<=0)throw new v("Attempt to construct Immutable from a deeply nested object was detected. Have you tried to wrap an object with circular references (e.g. React element)? See https://github.com/rtfeldman/seamless-immutable/wiki/Deeply-nested-object-was-detected for details.");for(var f in r-=1,e)Object.getOwnPropertyDescriptor(e,f)&&(c[f]=J(e[f],void 0,r));return G(c)}function L(e){return function(){var t=[].slice.call(arguments),r=t.shift();return e.apply(r,t)}}function Y(e,t){return function(){var r=[].slice.call(arguments),n=r.shift();return Array.isArray(n)?t.apply(n,r):e.apply(n,r)}}return J.from=J,J.isImmutable=l,J.ImmutableError=v,J.merge=L(E),J.replace=L(k),J.without=L(I),J.asMutable=(C=B,M=T,z=O,function(){var e=[].slice.call(arguments),t=e.shift();return Array.isArray(t)?M.apply(t,e):t instanceof Date?z.apply(t,e):C.apply(t,e)}),J.set=Y(U,w),J.setIn=Y(F,_),J.update=L($),J.updateIn=L(H),J.getIn=L(N),J.flatMap=L(j),J.asObject=L(S),a.use_static||(J.static=e({use_static:!0})),Object.freeze(J),J}();e.exports=t}()}),seamlessImmutable_development_1=seamlessImmutable_development.static,seamlessImmutable_development_2=seamlessImmutable_development.Immutable,defaultState=seamlessImmutable_development_1.from({data:void 0,error:null,isRequesting:!1,isErrored:!1}),defaultErrorKey="error";function makeReducer(e,t){var r={start:function(e,t,r,n){return e},success:function(e,t,r,n){return e},error:function(e,t,r,n){return e},all:function(e,t,r,n){return e},default:function(e,t,r){return e}},n=t&&t.errorKey||defaultErrorKey,o=n===defaultErrorKey?defaultState:o=seamlessImmutable_development_1.from(_extends({},seamlessImmutable_development_1.without(defaultState,"error"),defineProperty({},n,null))),a=function(){var a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:o,i=arguments[1],s=void 0;switch(i.type){case e+".start":return s=_extends({},a,defineProperty({isRequesting:!0,isErrored:!1},n,null)),s=r.start(s,a,i,t),s=r.all(s,a,i,t),seamlessImmutable_development_1.from(s);case e+".success":return s=_extends({},a,{data:i.payload,isRequesting:!1,isErrored:!1}),s=r.success(s,a,i,t),s=r.all(s,a,i,t),seamlessImmutable_development_1.from(s);case e+".error":return s=_extends({},a,defineProperty({isRequesting:!1,isErrored:!0},n,i.payload)),s=r.error(s,a,i,t),s=r.all(s,a,i,t),seamlessImmutable_development_1.from(s);case e+".set":var u=["data"];return i.meta.path&&(u=u.concat(i.meta.path)),seamlessImmutable_development_1.setIn(a,u,i.payload);case"grim.reset":var c=i.payload,l=c.includes,f=c.excludes;if(l){if(l.includes(e))return o}else if(!f||!f.includes(e))return o;default:return s=r.default?r.default(a,i,t):s,seamlessImmutable_development_1.from(s)}};return addHooks(a,r),a.modifyInitialState=function(e){return o=e(o),a},a}function setAction(e,t,r){return{type:e+".set",payload:t,meta:{entityType:e,path:r}}}function resetAction(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.includes;return{type:"grim.reset",payload:{excludes:e.excludes,includes:t}}}var _configSchema,defaultId="id",idProp="idProp",targetProp="to",propertiesProp="nestedProps";function resolveRule(e,t){for(var r=e[t],n=r&&t;r&&r[targetProp];){if(r[idProp]||r[propertiesProp])throw"'"+targetProp+"' aliases cannot be used with '"+idProp+"' and '"+propertiesProp+"' properties";n=r[targetProp],r=e[r[targetProp]]}return{entityType:n,rule:r}}function denormalize(e,t,r,n){if(!r)return r;var o=resolveRule(e,t),a=o.rule,i=o.entityType;if(Array.isArray(r))return r.map(function(t){return denormalize(e,i,t,n)});if("object"===(void 0===r?"undefined":_typeof(r)))return Object.entries(r).reduce(function(t,r){var o=slicedToArray(r,2),a=o[0],s=o[1];return t[a]=denormalize(e,i,s,n),t},{});var s=n[i]&&n[i][r];if(!s)return r;var u=_extends({},s);if(a[propertiesProp]){var c=!0,l=!1,f=void 0;try{for(var p,d=Object.entries(a[propertiesProp])[Symbol.iterator]();!(c=(p=d.next()).done);c=!0){var y=p.value,m=slicedToArray(y,2),h=m[0],v=m[1];u[h]=denormalize(e,v,u[h],n)}}catch(e){l=!0,f=e}finally{try{!c&&d.return&&d.return()}finally{if(l)throw f}}}return u}var configSchema=(defineProperty(_configSchema={entityType:"string"},idProp,"string?"),defineProperty(_configSchema,targetProp,"string?"),defineProperty(_configSchema,propertiesProp,"string{}?"),_configSchema),schemaRE=/(\{\})?(\??)$/,verifySchema=function(e,t){return e.every(function(e){var r=new Set([].concat(toConsumableArray(Object.keys(configSchema)),toConsumableArray(Object.keys(e))));return Array.from(r).every(function(r){var n=t[r];if(void 0!==n){var o=n.split(schemaRE),a=toArray(o),i=a[0],s=a.slice(1),u=s.indexOf("?")>-1,c=s.indexOf("{}")>-1,l=e[r],f=void 0===l?"undefined":_typeof(l);return!(!u||void 0!==l)||(c?"object"===f&&Object.values(l).every(function(e){return(void 0===e?"undefined":_typeof(e))===i}):void 0!==l&&(void 0===f?"undefined":_typeof(f))===i)}})})},cachedRules=void 0,previousRules=void 0,previousLength=void 0;function processRules(e){if(cachedRules&&e===previousRules&&e.length===previousLength)return cachedRules;if(!verifySchema(e,configSchema))throw"Error: rules do not match schema";return cachedRules=e.reduce(function(e,t){return e[t.entityType]=t,e},{}),previousRules=e,previousLength=e.length,cachedRules}function arrayEquals(e,t){return e===t||e&&t&&e.length===t.length&&e.every(function(e,r){return e===t[r]})}function getEntityTypes(e,t){var r=resolveRule(e,t),n=r.rule,o=r.entityType,a=o&&[o];if(n&&n[propertiesProp]){var i=!0,s=!1,u=void 0;try{for(var c,l=Object.values(n[propertiesProp])[Symbol.iterator]();!(i=(c=l.next()).done);i=!0){var f=c.value;a=[].concat(toConsumableArray(a),toConsumableArray(getEntityTypes(e,f)))}}catch(e){s=!0,u=e}finally{try{!i&&l.return&&l.return()}finally{if(s)throw u}}}return a}function createSelector(e,t,r,n){var o=processRules(e);if(!o[r])throw"Key not found "+r;var a=[].concat(toConsumableArray(new Set(getEntityTypes(o,r)))),i=[function(e){var t=n(e);return t&&"object"===(void 0===t?"undefined":_typeof(t))&&"data"in t?t.data:t}].concat(toConsumableArray(a.map(function(e){return function(r){return t(r)[e]}}))),s=void 0,u=void 0;return function(e){var n=i.map(function(t){return t(e)});return arrayEquals(n,s)||(s=n,u=seamlessImmutable_development_1.from(denormalize(o,r,n[0],t(e)))),u}}function normalizationReducer(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1].meta;if(t&&"delete"===t.method&&t.id)return seamlessImmutable_development_1.set(e,t.entityType,seamlessImmutable_development_1.without(e[t.entityType],t.id));if(t&&t.entities&&"object"===_typeof(t.entities)){var r=e;return Object.keys(t.entities).forEach(function(n){return r=seamlessImmutable_development_1.set(r,n,seamlessImmutable_development_1.merge({},[e[n],t.entities[n]]))}),r}return e}function normalize(e,t,r,n){if(!e[t])throw"Unrecognised entityType: "+t;var o=resolveRule(e,t),a=o.rule,i=o.entityType;if(Array.isArray(r))return r.map(function(t){return normalize(e,i,t,n)});if(!r||"object"!==(void 0===r?"undefined":_typeof(r)))return r;var s=r[a[idProp]||defaultId];if(!s)return Object.entries(r).reduce(function(t,r){var o=slicedToArray(r,2),a=o[0],s=o[1];return t[a]=normalize(e,i,s,n),t},{});var u=_extends({},r);if(n[i]=n[i]||{},n[i][s]=u,a[propertiesProp]){var c=!0,l=!1,f=void 0;try{for(var p,d=Object.entries(a[propertiesProp])[Symbol.iterator]();!(c=(p=d.next()).done);c=!0){var y=p.value,m=slicedToArray(y,2),h=m[0],v=m[1];u[h]=normalize(e,v,r[h],n)}}catch(e){l=!0,f=e}finally{try{!c&&d.return&&d.return()}finally{if(l)throw f}}}return s}function getNormalizerMiddleware(e,t){var r=processRules(e);return function(){return function(e){return function(n){var o=n.payload,a=n.meta,i=a&&a.entityType;return i&&o&&r[i]&&(a.entities={},n.payload=normalize(r,i,o,a.entities),t&&t(i,o)),e(n)}}}}export{makeActionCreator,makeReducer,setAction,resetAction,createSelector,normalizationReducer,getNormalizerMiddleware,processRules}; //# sourceMappingURL=redux-grim.es.min.js.map