Socket
Socket
Sign inDemoInstall

immer

Package Overview
Dependencies
Maintainers
2
Versions
173
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

immer - npm Package Compare versions

Comparing version 1.7.2 to 1.7.3

6

changelog.md
# Changelog
### 1.7.3
* fix: Only use proxies if both `Proxy` and `Reflect` global APIs exist, fixes [#226](https://github.com/mweststrate/immer/issues/226)
### 1.7.2
* Disabled `sideEffects` module flag, it somehow blows breaks the Angular build, fixes [#198](https://github.com/mweststrate/immer/issues/198)
* Disabled `sideEffects` module flag, it somehow breaks the Angular build, fixes [#198](https://github.com/mweststrate/immer/issues/198)

@@ -7,0 +11,0 @@ ### 1.7.1

54

dist/immer.d.ts
// Mapped type to remove readonly modifiers from state
// Based on https://github.com/Microsoft/TypeScript/blob/d4dc67aab233f5a8834dff16531baf99b16fea78/tests/cases/conformance/types/conditional/conditionalTypes1.ts#L120-L129
export type DraftObject<T> = {
-readonly [P in keyof T]: Draft<T[P]>;
};
export interface DraftArray<T> extends Array<Draft<T>> { }
export type Draft<T> =
T extends any[] ? DraftArray<T[number]> :
T extends ReadonlyArray<any> ? DraftArray<T[number]> :
T extends object ? DraftObject<T> :
T;
export type DraftObject<T> = {-readonly [P in keyof T]: Draft<T[P]>}
export interface DraftArray<T> extends Array<Draft<T>> {}
export type Draft<T> = T extends any[]
? DraftArray<T[number]>
: T extends ReadonlyArray<any>
? DraftArray<T[number]>
: T extends object ? DraftObject<T> : T
export interface Patch {
op: "replace" | "remove" | "add",
path: (string|number)[]
op: "replace" | "remove" | "add"
path: (string | number)[]
value?: any

@@ -59,3 +57,9 @@ }

<S = any, A = any, B = any, C = any>(
recipe: (this: Draft<S>, draftState: Draft<S>, a: A, b: B, c: C) => void | S,
recipe: (
this: Draft<S>,
draftState: Draft<S>,
a: A,
b: B,
c: C
) => void | S,
initialState: S

@@ -67,3 +71,7 @@ ): (currentState: S | undefined, a: A, b: B, c: C) => S

<S = any>(
recipe: (this: Draft<S>, draftState: Draft<S>, ...extraArgs: any[]) => void | S,
recipe: (
this: Draft<S>,
draftState: Draft<S>,
...extraArgs: any[]
) => void | S,
initialState: S

@@ -74,5 +82,5 @@ ): (currentState: S | undefined, ...extraArgs: any[]) => S

// 0 additional arguments
<S = any>(
recipe: (this: Draft<S>, draftState: Draft<S>) => void | S
): (currentState: S) => S
<S = any>(recipe: (this: Draft<S>, draftState: Draft<S>) => void | S): (
currentState: S
) => S
// 1 additional argument of type A

@@ -88,3 +96,9 @@ <S = any, A = any>(

<S = any, A = any, B = any, C = any>(
recipe: (this: Draft<S>, draftState: Draft<S>, a: A, b: B, c: C) => void | S
recipe: (
this: Draft<S>,
draftState: Draft<S>,
a: A,
b: B,
c: C
) => void | S
): (currentState: S, a: A, b: B, c: C) => S

@@ -95,3 +109,7 @@ // any number of additional arguments, but with loss of type safety

<S = any>(
recipe: (this: Draft<S>, draftState: Draft<S>, ...extraArgs: any[]) => void | S
recipe: (
this: Draft<S>,
draftState: Draft<S>,
...extraArgs: any[]
) => void | S
): (currentState: S, ...extraArgs: any[]) => S

@@ -98,0 +116,0 @@ }

@@ -141,3 +141,3 @@ 'use strict';

var autoFreeze = !inProduction;
var useProxies = typeof Proxy !== "undefined";
var useProxies = typeof Proxy !== "undefined" && typeof Reflect !== "undefined";

@@ -388,5 +388,5 @@ /**

// creates a proxy for plain objects / arrays
function createProxy(parentState, base, key) {
function createProxy(parentState, base) {
if (isProxy(base)) throw new Error("Immer bug. Plz report.");
var state = createState(parentState, base, key);
var state = createState(parentState, base);
var proxy = Array.isArray(base) ? Proxy.revocable([state], arrayTraps) : Proxy.revocable(state, objectTraps);

@@ -393,0 +393,0 @@ proxies.push(proxy);

@@ -137,3 +137,3 @@ function generatePatches(state, basepath, patches, inversePatches, baseValue, resultValue) {

var autoFreeze = !inProduction;
var useProxies = typeof Proxy !== "undefined";
var useProxies = typeof Proxy !== "undefined" && typeof Reflect !== "undefined";

@@ -384,5 +384,5 @@ /**

// creates a proxy for plain objects / arrays
function createProxy(parentState, base, key) {
function createProxy(parentState, base) {
if (isProxy(base)) throw new Error("Immer bug. Plz report.");
var state = createState(parentState, base, key);
var state = createState(parentState, base);
var proxy = Array.isArray(base) ? Proxy.revocable([state], arrayTraps) : Proxy.revocable(state, objectTraps);

@@ -389,0 +389,0 @@ proxies.push(proxy);

@@ -1,2 +0,2 @@

var e,r;e=this,r=function(e){"use strict";function r(e,r,n,t,o,i){var a,f,u,c,p;n&&(Array.isArray(o)?function(e,r,n,t,o,i){for(var a=Math.min(o.length,i.length),f=0;f<a;f++)if(e.assigned[f]&&o[f]!==i[f]){var u=r.concat(f);n.push({op:"replace",path:u,value:i[f]}),t.push({op:"replace",path:u,value:o[f]})}if(a<i.length){for(var c=a;c<i.length;c++){var p=r.concat(c);n.push({op:"add",path:p,value:i[c]})}t.push({op:"replace",path:r.concat("length"),value:o.length})}else if(a<o.length){n.push({op:"replace",path:r.concat("length"),value:i.length});for(var s=a;s<o.length;s++){var d=r.concat(s);t.push({op:"add",path:d,value:o[s]})}}}(e,r,n,t,o,i):(a=r,f=n,u=t,c=o,p=i,v(e.assigned,function(e,r){var n=c[e],t=p[e],o=r?e in c?"replace":"add":"remove";if(n!==c||"replace"!==o){var i=a.concat(e);f.push("remove"===o?{op:o,path:i}:{op:o,path:i,value:t}),u.push("add"===o?{op:"remove",path:i}:"remove"===o?{op:"add",path:i,value:n}:{op:"replace",path:i,value:n})}})))}var n,t,o,i="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},a="undefined"!=typeof Symbol?Symbol("immer-nothing"):(o=!0,(t="immer-nothing")in(n={})?Object.defineProperty(n,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):n[t]=o,n),f="undefined"!=typeof Symbol?Symbol("immer-proxy-state"):"__$immer_state",u="An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.";var c=!("undefined"!=typeof process&&"production"===process.env.NODE_ENV||"verifyMinified"!==function(){}.name),p="undefined"!=typeof Proxy;function s(e){return!!e&&!!e[f]}function d(e){if(!e)return!1;if("object"!==(void 0===e?"undefined":i(e)))return!1;if(Array.isArray(e))return!0;var r=Object.getPrototypeOf(e);return null===r||r===Object.prototype}function l(e){return c&&Object.freeze(e),e}var h=Object.assign||function(e,r){for(var n in r)g(r,n)&&(e[n]=r[n]);return e};function y(e){if(Array.isArray(e))return e.slice();var r=void 0===e.__proto__?Object.create(null):{};return h(r,e)}function v(e,r){if(Array.isArray(e))for(var n=0;n<e.length;n++)r(n,e[n]);else for(var t in e)r(t,e[t])}function g(e,r){return Object.prototype.hasOwnProperty.call(e,r)}function m(e,n,t,o){if(s(e)){var i=e[f];if(!0===i.modified){if(!0===i.finalized)return i.copy;i.finalized=!0;var a=(u=p?i.copy:i.copy=y(e),h=n,b=t,w=o,O=(c=i).base,v(u,function(e,r){if(r!==O[e]){var n=b&&!g(c.assigned,e);u[e]=m(r,n&&h.concat(e),n&&b,w)}}),l(u));return r(i,n,t,o,i.base,a),a}return i.base}var u,c,h,b,w,O;return function e(r){if(!d(r))return;if(Object.isFrozen(r))return;v(r,function(n,t){s(t)?r[n]=m(t):e(t)});l(r)}(e),e}function b(e,r){return e===r?0!==e||1/e==1/r:e!=e&&r!=r}var w=null,O={get:function(e,r){if(r===f)return e;if(e.modified){var n=e.copy[r];return n===e.base[r]&&d(n)?e.copy[r]=A(e,n):n}if(g(e.proxies,r))return e.proxies[r];var t=e.base[r];return!s(t)&&d(t)?e.proxies[r]=A(e,t):t},has:function(e,r){return r in x(e)},ownKeys:function(e){return Reflect.ownKeys(x(e))},set:function(e,r,n){if(e.assigned[r]=!0,!e.modified){if(r in e.base&&b(e.base[r],n)||g(e.proxies,r)&&e.proxies[r]===n)return!0;P(e)}return e.copy[r]=n,!0},deleteProperty:function(e,r){return e.assigned[r]=!1,P(e),delete e.copy[r],!0},getOwnPropertyDescriptor:function(e,r){var n=e.modified?e.copy:g(e.proxies,r)?e.proxies:e.base,t=Reflect.getOwnPropertyDescriptor(n,r);!t||Array.isArray(n)&&"length"===r||(t.configurable=!0);return t},defineProperty:function(){throw new Error("Immer does not support defining properties on draft objects.")},setPrototypeOf:function(){throw new Error("Immer does not support `setPrototypeOf()`.")}},j={};function x(e){return!0===e.modified?e.copy:e.base}function P(e){e.modified||(e.modified=!0,e.copy=y(e.base),Object.assign(e.copy,e.proxies),e.parent&&P(e.parent))}function A(e,r,n){if(s(r))throw new Error("Immer bug. Plz report.");var t={modified:!1,assigned:{},finalized:!1,parent:e,base:r,copy:void 0,proxies:{}},o=Array.isArray(r)?Proxy.revocable([t],j):Proxy.revocable(t,O);return w.push(o),o.proxy}v(O,function(e,r){j[e]=function(){return arguments[0]=arguments[0][0],r.apply(this,arguments)}}),j.deleteProperty=function(e,r){if(isNaN(parseInt(r)))throw new Error("Immer does not support deleting properties from arrays: "+r);return O.deleteProperty.call(this,e[0],r)},j.set=function(e,r,n){if("length"!==r&&isNaN(parseInt(r)))throw new Error("Immer does not support setting non-numeric properties on arrays: "+r);return O.set.call(this,e[0],r,n)};var E={},k=null;function z(e){return e.hasCopy?e.copy:e.base}function S(e){e.modified||(e.modified=!0,e.parent&&S(e.parent))}function _(e){e.hasCopy||(e.hasCopy=!0,e.copy=y(e.base))}function C(e,r){var n=y(r);v(r,function(e){var r;Object.defineProperty(n,""+e,E[r=""+e]||(E[r]={configurable:!0,enumerable:!0,get:function(){return function(e,r){I(e);var n=z(e)[r];return!e.finalizing&&n===e.base[r]&&d(n)?(_(e),e.copy[r]=C(e,n)):n}(this[f],r)},set:function(e){!function(e,r,n){if(I(e),e.assigned[r]=!0,!e.modified){if(b(z(e)[r],n))return;S(e),_(e)}e.copy[r]=n}(this[f],r,e)}}))});var t,o,i,a={modified:!1,assigned:{},hasCopy:!1,parent:e,base:r,proxy:n,copy:void 0,finished:!1,finalizing:!1,finalized:!1};return t=n,o=f,i=a,Object.defineProperty(t,o,{value:i,enumerable:!1,writable:!0}),k.push(a),n}function I(e){if(!0===e.finished)throw new Error("Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+JSON.stringify(e.copy||e.base))}function N(e){if(e&&"object"===(void 0===e?"undefined":i(e))){var r=e[f];if(r){var n,t,o,a,u=r.proxy,c=r.base;if(Array.isArray(e)){if(D(r)){if(S(r),r.assigned.length=!0,u.length<c.length)for(var p=u.length;p<c.length;p++)r.assigned[p]=!1;else for(var s=c.length;s<u.length;s++)r.assigned[s]=!0;v(u,function(e,n){r.assigned[e]||N(n)})}}else{var d=(n=c,t=u,o=Object.keys(n),{added:(a=Object.keys(t)).filter(function(e){return-1===o.indexOf(e)}),removed:o.filter(function(e){return-1===a.indexOf(e)})}),l=d.added,h=d.removed;(l.length>0||h.length>0)&&S(r),v(l,function(e,n){r.assigned[n]=!0}),v(h,function(e,n){r.assigned[n]=!1}),v(u,function(e,n){r.assigned[e]||N(n)})}}}}function D(e){var r=e.proxy;if(r.length!==e.base.length)return!0;var n=Object.getOwnPropertyDescriptor(r,r.length-1);return!(!n||n.get)}function M(e,r,n){if(s(e)){var t=r.call(e,e);return void 0===t?e:t}var o=k;k=[];var a=n&&[],c=n&&[];try{var p=C(void 0,e),d=r.call(p,p);v(k,function(e,r){r.finalizing=!0});var l=void 0;if(void 0!==d&&d!==p){if(p[f].modified)throw new Error(u);l=m(d),a&&(a.push({op:"replace",path:[],value:l}),c.push({op:"replace",path:[],value:e}))}else n&&N(p),function(){for(var e=k.length-1;e>=0;e--){var r=k[e];!1===r.modified&&(Array.isArray(r.base)?D(r)&&S(r):(n=r,t=Object.keys(n.base),o=Object.keys(n.proxy),function(e,r){if(b(e,r))return!0;if("object"!==(void 0===e?"undefined":i(e))||null===e||"object"!==(void 0===r?"undefined":i(r))||null===r)return!1;var n=Object.keys(e),t=Object.keys(r);if(n.length!==t.length)return!1;for(var o=0;o<n.length;o++)if(!hasOwnProperty.call(r,n[o])||!b(e[n[o]],r[n[o]]))return!1;return!0}(t,o)||S(r)))}var n,t,o}(),l=m(p,[],a,c);return v(k,function(e,r){r.finished=!0}),n&&n(a,c),l}finally{k=o}}function R(e,r,n){if(arguments.length<1||arguments.length>3)throw new Error("produce expects 1 to 3 arguments, got "+arguments.length);if("function"==typeof e){if("function"==typeof r)throw new Error("if first argument is a function (curried invocation), the second argument to produce cannot be a function");var t=r,o=e;return function(){var e=arguments;return R(void 0===e[0]&&void 0!==t?t:e[0],function(r){return e[0]=r,o.apply(r,e)})}}if("function"!=typeof r)throw new Error("if first argument is not a function, the second argument to produce should be a function");if(void 0!==n&&"function"!=typeof n)throw new Error("the third argument of a producer should not be set or a function");if("object"!==(void 0===e?"undefined":i(e))||null===e){var a=r(e);return void 0===a?e:F(a)}if(!d(e))throw new Error("the first argument to an immer producer should be a primitive, plain object or array, got "+(void 0===e?"undefined":i(e))+': "'+e+'"');return F(p?function(e,r,n){if(s(e)){var t=r.call(e,e);return void 0===t?e:t}var o=w;w=[];var i=n&&[],a=n&&[];try{var c=A(void 0,e),p=r.call(c,c),d=void 0;if(void 0!==p&&p!==c){if(c[f].modified)throw new Error(u);d=m(p),i&&(i.push({op:"replace",path:[],value:d}),a.push({op:"replace",path:[],value:e}))}else d=m(c,[],i,a);return v(w,function(e,r){return r.revoke()}),n&&n(i,a),d}finally{w=o}}(e,r,n):M(e,r,n))}function F(e){return e===a?void 0:e}var K=R(function(e,r){for(var n=function(n){var t=r[n];if(0===t.path.length&&"replace"===t.op)e=t.value;else{var o=t.path.slice(),i=o.pop(),a=o.reduce(function(e,r){if(!e)throw new Error("Cannot apply patch, path doesn't resolve: "+t.path.join("/"));return e[r]},e);if(!a)throw new Error("Cannot apply patch, path doesn't resolve: "+t.path.join("/"));switch(t.op){case"replace":case"add":a[i]=t.value;break;case"remove":if(Array.isArray(a)){if(i!==a.length-1)throw new Error("Remove can only remove the last key of an array, index: "+i+", length: "+a.length);a.length-=1}else delete a[i];break;default:throw new Error("Unsupported patch operation: "+t.op)}}},t=0;t<r.length;t++)n(t);return e}),U=a;e.produce=R,e.default=R,e.applyPatches=K,e.nothing=U,e.setAutoFreeze=function(e){c=e},e.setUseProxies=function(e){p=e},e.original=function(e){if(e&&e[f])return e[f].base},Object.defineProperty(e,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r(e.immer={});
var e,r;e=this,r=function(e){"use strict";function r(e,r,n,t,o,i){n&&(Array.isArray(o)?function(e,r,n,t,o,i){for(var a=Math.min(o.length,i.length),f=0;f<a;f++)if(e.assigned[f]&&o[f]!==i[f]){var u=r.concat(f);n.push({op:"replace",path:u,value:i[f]}),t.push({op:"replace",path:u,value:o[f]})}if(a<i.length){for(var c=a;c<i.length;c++){var p=r.concat(c);n.push({op:"add",path:p,value:i[c]})}t.push({op:"replace",path:r.concat("length"),value:o.length})}else if(a<o.length){n.push({op:"replace",path:r.concat("length"),value:i.length});for(var s=a;s<o.length;s++){var d=r.concat(s);t.push({op:"add",path:d,value:o[s]})}}}(e,r,n,t,o,i):function(e,r,n,t,o,i){v(e.assigned,function(e,a){var f=o[e],u=i[e],c=a?e in o?"replace":"add":"remove";if(f!==o||"replace"!==c){var p=r.concat(e);n.push("remove"===c?{op:c,path:p}:{op:c,path:p,value:u}),t.push("add"===c?{op:"remove",path:p}:"remove"===c?{op:"add",path:p,value:f}:{op:"replace",path:p,value:f})}})}(e,r,n,t,o,i))}var n,t,o,i="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},a="undefined"!=typeof Symbol?Symbol("immer-nothing"):(o=!0,(t="immer-nothing")in(n={})?Object.defineProperty(n,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):n[t]=o,n),f="undefined"!=typeof Symbol?Symbol("immer-proxy-state"):"__$immer_state",u="An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.";var c=!("undefined"!=typeof process&&"production"===process.env.NODE_ENV||"verifyMinified"!==function(){}.name),p="undefined"!=typeof Proxy&&"undefined"!=typeof Reflect;function s(e){return!!e&&!!e[f]}function d(e){if(!e)return!1;if("object"!==(void 0===e?"undefined":i(e)))return!1;if(Array.isArray(e))return!0;var r=Object.getPrototypeOf(e);return null===r||r===Object.prototype}function l(e){return c&&Object.freeze(e),e}var h=Object.assign||function(e,r){for(var n in r)g(r,n)&&(e[n]=r[n]);return e};function y(e){if(Array.isArray(e))return e.slice();var r=void 0===e.__proto__?Object.create(null):{};return h(r,e)}function v(e,r){if(Array.isArray(e))for(var n=0;n<e.length;n++)r(n,e[n]);else for(var t in e)r(t,e[t])}function g(e,r){return Object.prototype.hasOwnProperty.call(e,r)}function m(e,n,t,o){if(s(e)){var i=e[f];if(!0===i.modified){if(!0===i.finalized)return i.copy;i.finalized=!0;var a=function(e,r,n,t,o){var i=r.base;return v(e,function(a,f){if(f!==i[a]){var u=t&&!g(r.assigned,a);e[a]=m(f,u&&n.concat(a),u&&t,o)}}),l(e)}(p?i.copy:i.copy=y(e),i,n,t,o);return r(i,n,t,o,i.base,a),a}return i.base}return function e(r){if(!d(r))return;if(Object.isFrozen(r))return;v(r,function(n,t){s(t)?r[n]=m(t):e(t)});l(r)}(e),e}function b(e,r){return e===r?0!==e||1/e==1/r:e!=e&&r!=r}var w=null,O={get:function(e,r){if(r===f)return e;if(e.modified){var n=e.copy[r];return n===e.base[r]&&d(n)?e.copy[r]=A(e,n):n}if(g(e.proxies,r))return e.proxies[r];var t=e.base[r];return!s(t)&&d(t)?e.proxies[r]=A(e,t):t},has:function(e,r){return r in x(e)},ownKeys:function(e){return Reflect.ownKeys(x(e))},set:function(e,r,n){if(e.assigned[r]=!0,!e.modified){if(r in e.base&&b(e.base[r],n)||g(e.proxies,r)&&e.proxies[r]===n)return!0;P(e)}return e.copy[r]=n,!0},deleteProperty:function(e,r){return e.assigned[r]=!1,P(e),delete e.copy[r],!0},getOwnPropertyDescriptor:function(e,r){var n=e.modified?e.copy:g(e.proxies,r)?e.proxies:e.base,t=Reflect.getOwnPropertyDescriptor(n,r);!t||Array.isArray(n)&&"length"===r||(t.configurable=!0);return t},defineProperty:function(){throw new Error("Immer does not support defining properties on draft objects.")},setPrototypeOf:function(){throw new Error("Immer does not support `setPrototypeOf()`.")}},j={};function x(e){return!0===e.modified?e.copy:e.base}function P(e){e.modified||(e.modified=!0,e.copy=y(e.base),Object.assign(e.copy,e.proxies),e.parent&&P(e.parent))}function A(e,r){if(s(r))throw new Error("Immer bug. Plz report.");var n=function(e,r){return{modified:!1,assigned:{},finalized:!1,parent:e,base:r,copy:void 0,proxies:{}}}(e,r),t=Array.isArray(r)?Proxy.revocable([n],j):Proxy.revocable(n,O);return w.push(t),t.proxy}v(O,function(e,r){j[e]=function(){return arguments[0]=arguments[0][0],r.apply(this,arguments)}}),j.deleteProperty=function(e,r){if(isNaN(parseInt(r)))throw new Error("Immer does not support deleting properties from arrays: "+r);return O.deleteProperty.call(this,e[0],r)},j.set=function(e,r,n){if("length"!==r&&isNaN(parseInt(r)))throw new Error("Immer does not support setting non-numeric properties on arrays: "+r);return O.set.call(this,e[0],r,n)};var E={},k=null;function z(e){return e.hasCopy?e.copy:e.base}function S(e){e.modified||(e.modified=!0,e.parent&&S(e.parent))}function _(e){e.hasCopy||(e.hasCopy=!0,e.copy=y(e.base))}function C(e,r){var n=y(r);v(r,function(e){var r;Object.defineProperty(n,""+e,E[r=""+e]||(E[r]={configurable:!0,enumerable:!0,get:function(){return function(e,r){I(e);var n=z(e)[r];return!e.finalizing&&n===e.base[r]&&d(n)?(_(e),e.copy[r]=C(e,n)):n}(this[f],r)},set:function(e){!function(e,r,n){if(I(e),e.assigned[r]=!0,!e.modified){if(b(z(e)[r],n))return;S(e),_(e)}e.copy[r]=n}(this[f],r,e)}}))});var t,o,i,a=function(e,r,n){return{modified:!1,assigned:{},hasCopy:!1,parent:e,base:n,proxy:r,copy:void 0,finished:!1,finalizing:!1,finalized:!1}}(e,n,r);return t=n,o=f,i=a,Object.defineProperty(t,o,{value:i,enumerable:!1,writable:!0}),k.push(a),n}function I(e){if(!0===e.finished)throw new Error("Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+JSON.stringify(e.copy||e.base))}function N(e){if(e&&"object"===(void 0===e?"undefined":i(e))){var r=e[f];if(r){var n,t,o,a,u=r.proxy,c=r.base;if(Array.isArray(e)){if(R(r)){if(S(r),r.assigned.length=!0,u.length<c.length)for(var p=u.length;p<c.length;p++)r.assigned[p]=!1;else for(var s=c.length;s<u.length;s++)r.assigned[s]=!0;v(u,function(e,n){r.assigned[e]||N(n)})}}else{var d=(n=c,t=u,o=Object.keys(n),{added:(a=Object.keys(t)).filter(function(e){return-1===o.indexOf(e)}),removed:o.filter(function(e){return-1===a.indexOf(e)})}),l=d.added,h=d.removed;(l.length>0||h.length>0)&&S(r),v(l,function(e,n){r.assigned[n]=!0}),v(h,function(e,n){r.assigned[n]=!1}),v(u,function(e,n){r.assigned[e]||N(n)})}}}}function D(e){return!function(e,r){if(b(e,r))return!0;if("object"!==(void 0===e?"undefined":i(e))||null===e||"object"!==(void 0===r?"undefined":i(r))||null===r)return!1;var n=Object.keys(e),t=Object.keys(r);if(n.length!==t.length)return!1;for(var o=0;o<n.length;o++)if(!hasOwnProperty.call(r,n[o])||!b(e[n[o]],r[n[o]]))return!1;return!0}(Object.keys(e.base),Object.keys(e.proxy))}function R(e){var r=e.proxy;if(r.length!==e.base.length)return!0;var n=Object.getOwnPropertyDescriptor(r,r.length-1);return!(!n||n.get)}function M(e,r,n){if(s(e)){var t=r.call(e,e);return void 0===t?e:t}var o=k;k=[];var i=n&&[],a=n&&[];try{var c=C(void 0,e),p=r.call(c,c);v(k,function(e,r){r.finalizing=!0});var d=void 0;if(void 0!==p&&p!==c){if(c[f].modified)throw new Error(u);d=m(p),i&&(i.push({op:"replace",path:[],value:d}),a.push({op:"replace",path:[],value:e}))}else n&&N(c),function(){for(var e=k.length-1;e>=0;e--){var r=k[e];!1===r.modified&&(Array.isArray(r.base)?R(r)&&S(r):D(r)&&S(r))}}(),d=m(c,[],i,a);return v(k,function(e,r){r.finished=!0}),n&&n(i,a),d}finally{k=o}}function F(e,r,n){if(arguments.length<1||arguments.length>3)throw new Error("produce expects 1 to 3 arguments, got "+arguments.length);if("function"==typeof e){if("function"==typeof r)throw new Error("if first argument is a function (curried invocation), the second argument to produce cannot be a function");var t=r,o=e;return function(){var e=arguments;return F(void 0===e[0]&&void 0!==t?t:e[0],function(r){return e[0]=r,o.apply(r,e)})}}if("function"!=typeof r)throw new Error("if first argument is not a function, the second argument to produce should be a function");if(void 0!==n&&"function"!=typeof n)throw new Error("the third argument of a producer should not be set or a function");if("object"!==(void 0===e?"undefined":i(e))||null===e){var a=r(e);return void 0===a?e:K(a)}if(!d(e))throw new Error("the first argument to an immer producer should be a primitive, plain object or array, got "+(void 0===e?"undefined":i(e))+': "'+e+'"');return K(p?function(e,r,n){if(s(e)){var t=r.call(e,e);return void 0===t?e:t}var o=w;w=[];var i=n&&[],a=n&&[];try{var c=A(void 0,e),p=r.call(c,c),d=void 0;if(void 0!==p&&p!==c){if(c[f].modified)throw new Error(u);d=m(p),i&&(i.push({op:"replace",path:[],value:d}),a.push({op:"replace",path:[],value:e}))}else d=m(c,[],i,a);return v(w,function(e,r){return r.revoke()}),n&&n(i,a),d}finally{w=o}}(e,r,n):M(e,r,n))}function K(e){return e===a?void 0:e}var U=F(function(e,r){for(var n=function(n){var t=r[n];if(0===t.path.length&&"replace"===t.op)e=t.value;else{var o=t.path.slice(),i=o.pop(),a=o.reduce(function(e,r){if(!e)throw new Error("Cannot apply patch, path doesn't resolve: "+t.path.join("/"));return e[r]},e);if(!a)throw new Error("Cannot apply patch, path doesn't resolve: "+t.path.join("/"));switch(t.op){case"replace":case"add":a[i]=t.value;break;case"remove":if(Array.isArray(a)){if(i!==a.length-1)throw new Error("Remove can only remove the last key of an array, index: "+i+", length: "+a.length);a.length-=1}else delete a[i];break;default:throw new Error("Unsupported patch operation: "+t.op)}}},t=0;t<r.length;t++)n(t);return e}),J=a;e.produce=F,e.default=F,e.applyPatches=U,e.nothing=J,e.setAutoFreeze=function(e){c=e},e.setUseProxies=function(e){p=e},e.original=function(e){if(e&&e[f])return e[f].base},Object.defineProperty(e,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r(e.immer={});
//# sourceMappingURL=immer.umd.js.map
{
"name": "immer",
"version": "1.7.2",
"version": "1.7.3",
"description": "Create your next immutable state by mutating the current one",

@@ -18,3 +18,3 @@ "main": "dist/immer.js",

"build": "rimraf dist/ && cross-env NODE_ENV=production rollup -c && cpx \"src/immer.{d.ts,js.flow}\" dist",
"prettier": "prettier \"*/**/*.js\" --ignore-path ./.prettierignore --write",
"prettier": "prettier \"*/**/*.js\" \"*/**/*.ts\" --ignore-path ./.prettierignore --write",
"precommit": "lint-staged",

@@ -82,2 +82,6 @@ "prepublish": "yarn-or-npm run build",

"git add"
],
"*.ts": [
"prettier --write",
"git add"
]

@@ -84,0 +88,0 @@ },

@@ -23,17 +23,21 @@ <img src="images/immer-logo.png" height="200px" align="right"/>

* Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)
* [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate
* Blog: by Workday Prism on why they picked Immer to manage immutable state [The Search for a Strongly-Typed, Immutable State](https://medium.com/workday-engineering/workday-prism-analytics-the-search-for-a-strongly-typed-immutable-state-a09f6768b2b5)
* Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)
* Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)
Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way. It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.
The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_. Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state. This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.
The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_. Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state. This means that you can interact with your data by simply modifying it while keeping all the benefits of immutable data.
![immer-hd.png](images/hd/immer.png)
Using Immer is like having a personal assistant; he takes a letter (the current state), and gives you a copy (draft) to jot changes onto. Once you are done, the assistant will take your draft and produce the real immutable, final letter for you (the next state).
Using Immer is like having a personal assistant; he takes a letter (the current state) and gives you a copy (draft) to jot changes onto. Once you are done, the assistant will take your draft and produce the real immutable, final letter for you (the next state).
A mindful reader might notice that this is quite similar to `withMutations` of ImmutableJS. It is indeed, but generalized and applied to plain, native JavaScript data structures (arrays and objects) without further needing any library.
## External resources
* Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)
* Blog: by Workday Prism on why they picked Immer to manage immutable state [The Search for a Strongly-Typed, Immutable State](https://medium.com/workday-engineering/workday-prism-analytics-the-search-for-a-strongly-typed-immutable-state-a09f6768b2b5)
* Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)
* Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)
* [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate
## API

@@ -176,3 +180,3 @@

Passing a function as the first argument to `produce` is intended to be used for currying. This means that you get a pre-bound producer that only needs a state to produce the value from. The producer function gets passed in the draft, and any further arguments that were passed to the curried function.
Passing a function as the first argument to `produce` is intended to be used for currying. This means that you get a pre-bound producer that only needs a state to produce the value from. The producer function gets passed in the draft and any further arguments that were passed to the curried function.

@@ -232,6 +236,23 @@ For example:

##### Fun with currying
A random fun example just for inspiration:
a neat trick is to turn `Object.assign` into a producer to create a "spread" function that is smarter than the normal spread operator, as it doesn't produce a new state if the result doesn't actually change ([details & explanation](https://twitter.com/mweststrate/status/1045059430256119809)).
Quick example:
```javascript
import produce from "immer"
const spread = produce(Object.assign)
const base = {x: 1, y: 1}
console.log({...base, y: 1} === base) // false
console.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was produced
console.log(spread(base, {y: 2}) === base) // false, produced a new object as it should
```
## Patches
During the run of a producer, Immer can record all the patches that would replay the changes made by the reducer.
This is a very powerful tool if you want to fork your state temporarily, and replay the changes to the original.
This is a very powerful tool if you want to fork your state temporarily and replay the changes to the original.

@@ -241,3 +262,3 @@ Patches are useful in few scenarios:

* For debugging / traces, to see precisely how state is changed over time
* As basis for undo/redo or as approach to replay changes on a slightly different state tree
* As basis for undo/redo or as an approach to replay changes on a slightly different state tree

@@ -256,3 +277,3 @@ To help with replaying patches, `applyPatches` comes in handy. Here is an example how patches could be used

// Let's assume the user is in a wizard, and we don't know whether
// his changes should be end up in the base state ultimately or not...
// his changes should end up in the base state ultimately or not...
let fork = state

@@ -276,3 +297,3 @@ // all the changes the user made in the wizard

// In the mean time, our original state is replaced, as, for example,
// In the meantime, our original state is replaced, as, for example,
// some changes were received from the server

@@ -317,5 +338,9 @@ state = produce(state, draft => {

For a more in-depth study, see [Distributing patches and rebasing actions using Immer](https://medium.com/@mweststrate/distributing-state-changes-using-snapshots-patches-and-actions-part-2-2f50d8363988)
Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.
## Auto freezing
Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. It is by default enabled. By default it is turned on during local development, and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.
Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. It is by default enabled. By default, it is turned on during local development and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.

@@ -367,3 +392,3 @@ ## Returning data from producers

So, in general one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft.
So, in general, one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft.
There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`:

@@ -386,3 +411,3 @@

The problem is that in JavaScript a function that doesn't return anything, also returns `undefined`!
The problem is that in JavaScript a function that doesn't return anything also returns `undefined`!
So immer cannot differentiate between those different cases.

@@ -446,3 +471,3 @@ So, by default, Immer will assume that any producer that returns `undefined` just tried to modify the draft.

In such cases you can use javascripts [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) operator, which evaluates expressions and returns `undefined`.
In such cases, you can use javascripts [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) operator, which evaluates expressions and returns `undefined`.

@@ -489,7 +514,7 @@ ```javascript

By default `produce` tries to use proxies for optimal performance. However, on older JavaScript engines `Proxy` is not available. For example, when running Microsoft Internet Explorer or React Native on Android. In such cases Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.
By default `produce` tries to use proxies for optimal performance. However, on older JavaScript engines `Proxy` is not available. For example, when running Microsoft Internet Explorer or React Native on Android. In such cases, Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.
## Importing immer
`produce` is exposed as the default export, but optionally it can be used as name import as well, as this benefits some older project setups. So the following imports are all correct, where the first is recommend:
`produce` is exposed as the default export, but optionally it can be used as name import as well, as this benefits some older project setups. So the following imports are all correct, where the first is recommended:

@@ -522,9 +547,9 @@ ```javascript

1. Immer assumes your state to be a unidirectional tree. That is, no object should appear twice in the tree, and there should be no circular references.
1. Class instances are not, and will not supported first-class supported. Read [here](https://github.com/mweststrate/immer/issues/155#issuecomment-407725592) why classes are a conceptual mismatch (and technically extremely challenging)
1. Class instances are not, and will not have first-class support. Read [here](https://github.com/mweststrate/immer/issues/155#issuecomment-407725592) why classes are a conceptual mismatch (and technically extremely challenging)
1. For example, working with `Date` objects is no problem, just make sure you never modify them (by using methods like `setYear` on an existing instance). Instead, always create fresh `Date` instances. Which is probably what you were unconsciously doing already.
1. Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`. Also realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Also note that `original` can be used to get the original state of an object, which is cheaper to read.
1. Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`. Also, realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Also note that `original` can be used to get the original state of an object, which is cheaper to read.
1. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.
1. Always try to pull `produce` 'up', for example `for (let x of y) produce(base, d => d.push(x))` is exponentially slower than `produce(base, d => { for (let x of y) d.push(x)})`
1. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistiguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.
1. Immer does not support built in data-structures like `Map` and `Set`. However, it is fine to just immutably "update" them yourself but still leverage immer wherever possible:
1. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistinguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.
1. Immer does not support built-in data-structures like `Map` and `Set`. However, it is fine to just immutably "update" them yourself but still leverage immer wherever possible:

@@ -551,3 +576,3 @@ ```javascript

Or a deep update in maps (well, don't use maps for this use case, but as example):
Or a deep update in maps (well, don't use maps for this use case, but as an example):

@@ -580,3 +605,3 @@ ```javascript

* [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_
* [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate
* [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_
* ... and [many more](https://www.npmjs.com/browse/depended/immer)

@@ -642,3 +667,3 @@

Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer. This test takes 50,000 todo items, and updates 5,000 of them. _Freeze_ indicates that the state tree has been frozen after producing it. This is a _development_ best practice, as it prevents developers from accidentally modifying the state tree.
Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer. This test takes 50,000 todo items and updates 5,000 of them. _Freeze_ indicates that the state tree has been frozen after producing it. This is a _development_ best practice, as it prevents developers from accidentally modifying the state tree.

@@ -651,3 +676,3 @@ These tests were executed on Node 9.3.0. Use `yarn test:perf` to reproduce them locally.

* Immer with proxies is roughly speaking twice to three times slower as a hand written reducer (the above test case is worst case, see `yarn test:perf` for more tests). This is in practice negligible.
* Immer with proxies is roughly speaking twice to three times slower as a handwritten reducer (the above test case is worst case, see `yarn test:perf` for more tests). This is in practice negligible.
* Immer is roughly as fast as ImmutableJS. However, the _immutableJS + toJS_ makes clear the cost that often needs to be paid later; converting the immutableJS objects back to plain objects, to be able to pass them to components, over the network etc... (And there is also the upfront cost of converting data received from e.g. the server to immutable JS)

@@ -691,3 +716,3 @@ * Generating patches doesn't significantly slow immer down

Special thanks goes to @Mendix, which supports it's employees to experiment completely freely two full days a month, which formed the kick-start for this project.
Special thanks to @Mendix, which supports its employees to experiment completely freely two full days a month, which formed the kick-start for this project.

@@ -694,0 +719,0 @@ ## Donations

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc