less builds is more?
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parent 03a2736 · Browse files · 10 files·+241 added−334 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+241 added−334 removed
- other:+241 added−334 removed
Provenance
- Commit
74a97b6- Tree
a70e106- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
03a2736
10 files changed+241 added−334 removed
deleted:src/immer.js-189 removed
1-"use strict"2-// @ts-check3-4-import {autoFreeze, isProxyable, isProxy, freeze, PROXY_STATE} from "./common"5-6-let revocableProxies = null7-8-const objectTraps = {9- get,10- has(target, prop) {11- return prop in source(target)12- },13- ownKeys(target) {14- return Reflect.ownKeys(source(target))15- },16- set,17- deleteProperty,18- getOwnPropertyDescriptor,19- defineProperty,20- setPrototypeOf() {21- throw new Error("Don't even try this...")22- }23-}24-25-const arrayTraps = {}26-for (let key in objectTraps) {27- arrayTraps[key] = function() {28- arguments[0] = arguments[0][0]29- return objectTraps[key].apply(this, arguments)30- }31-}32-33-function createState(parent, base) {34- return {35- modified: false,36- finalized: false,37- parent,38- base,39- copy: undefined,40- proxies: {}41- }42-}43-44-function source(state) {45- return state.modified === true ? state.copy : state.base46-}47-48-function get(state, prop) {49- if (prop === PROXY_STATE) return state50- if (state.modified) {51- const value = state.copy[prop]52- if (!isProxy(value) && isProxyable(value))53- return (state.copy[prop] = createProxy(state, value))54- return value55- } else {56- if (prop in state.proxies) return state.proxies[prop]57- const value = state.base[prop]58- if (!isProxy(value) && isProxyable(value))59- return (state.proxies[prop] = createProxy(state, value))60- return value61- }62-}63-64-function set(state, prop, value) {65- if (!state.modified) {66- if (67- (prop in state.base && Object.is(state.base[prop], value)) ||68- (prop in state.proxies && state.proxies[prop] === value)69- )70- return true71- markChanged(state)72- }73- state.copy[prop] = value74- return true75-}76-77-function deleteProperty(state, prop) {78- markChanged(state)79- delete state.copy[prop]80- return true81-}82-83-function getOwnPropertyDescriptor(state, prop) {84- const owner = state.modified85- ? state.copy86- : prop in state.proxies ? state.proxies : state.base87- const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)88- if (descriptor && !(Array.isArray(owner) && prop === "length"))89- descriptor.configurable = true90- return descriptor91-}92-93-function defineProperty() {94- throw new Error(95- "Immer does currently not support defining properties on draft objects"96- )97-}98-99-function markChanged(state) {100- if (!state.modified) {101- state.modified = true102- state.copy = Array.isArray(state.base)103- ? state.base.slice()104- : Object.assign({}, state.base) // TODO: eliminate those isArray checks?105- Object.assign(state.copy, state.proxies) // yup that works for arrays as well106- if (state.parent) markChanged(state.parent)107- }108-}109-110-// creates a proxy for plain objects / arrays111-function createProxy(parentState, base) {112- const state = createState(parentState, base)113- let proxy114- if (Array.isArray(base)) {115- proxy = Proxy.revocable([state], arrayTraps)116- } else {117- proxy = Proxy.revocable(state, objectTraps)118- }119- revocableProxies.push(proxy)120- return proxy.proxy121-}122-123-// given a base object, returns it if unmodified, or return the changed cloned if modified124-function finalize(base) {125- if (isProxy(base)) {126- const state = base[PROXY_STATE]127- if (state.modified === true) {128- if (state.finalized === true) return state.copy129- state.finalized = true130- if (Array.isArray(state.base)) return finalizeArray(state)131- return finalizeObject(state)132- } else return state.base133- } else if (base !== null && typeof base === "object") {134- // If finalize is called on an object that was not a proxy, it means that it is an object that was not there in the original135- // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as well136- // TODO: optimize this; walk the tree without writing to find proxies137- if (Array.isArray(base)) {138- for (let i = 0; i < base.length; i++) base[i] = finalize(base[i])139- return freeze(base)140- }141- const proto = Object.getPrototypeOf(base)142- if (proto === null || proto === Object.prototype) {143- for (let key in base) base[key] = finalize(base[key])144- return freeze(base)145- }146- }147- return base148-}149-150-function finalizeObject(state) {151- const copy = state.copy152- const base = state.base153- for (var prop in copy) {154- if (copy[prop] !== base[prop]) copy[prop] = finalize(copy[prop])155- }156- return freeze(copy)157-}158-159-function finalizeArray(state) {160- const copy = state.copy161- const base = state.base162- for (let i = 0; i < copy.length; i++) {163- if (copy[i] !== base[i]) copy[i] = finalize(copy[i])164- }165- return freeze(copy)166-}167-168-export function produceProxy(baseState, producer) {169- const previousProxies = revocableProxies170- revocableProxies = []171- try {172- // create proxy for root173- const rootClone = createProxy(undefined, baseState)174- // execute the thunk175- const maybeVoidReturn = producer(rootClone)176- //values either than undefined will trigger warning;177- !Object.is(maybeVoidReturn, undefined) &&178- console.warn(179- `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`180- )181- // and finalize the modified proxy182- const res = finalize(rootClone)183- // revoke all proxies184- revocableProxies.forEach(p => p.revoke())185- return res186- } finally {187- revocableProxies = previousProxies188- }189-}modified:src/index.js+2 added-1 removed
12334567840 unmodified linesexport {setAutoFreeze} from "./common"
import {isProxyable} from "./common"import {produceProxy} from "./immer"import {produceProxy} from "./proxy"import {produceEs5} from "./es5"
let useProxies = typeof Proxy !== "undefined"
40 unmodified linesadded:src/proxy.js+189 added
1+"use strict"2+// @ts-check3+4+import {autoFreeze, isProxyable, isProxy, freeze, PROXY_STATE} from "./common"5+6+let revocableProxies = null7+8+const objectTraps = {9+ get,10+ has(target, prop) {11+ return prop in source(target)12+ },13+ ownKeys(target) {14+ return Reflect.ownKeys(source(target))15+ },16+ set,17+ deleteProperty,18+ getOwnPropertyDescriptor,19+ defineProperty,20+ setPrototypeOf() {21+ throw new Error("Don't even try this...")22+ }23+}24+25+const arrayTraps = {}26+for (let key in objectTraps) {27+ arrayTraps[key] = function() {28+ arguments[0] = arguments[0][0]29+ return objectTraps[key].apply(this, arguments)30+ }31+}32+33+function createState(parent, base) {34+ return {35+ modified: false,36+ finalized: false,37+ parent,38+ base,39+ copy: undefined,40+ proxies: {}41+ }42+}43+44+function source(state) {45+ return state.modified === true ? state.copy : state.base46+}47+48+function get(state, prop) {49+ if (prop === PROXY_STATE) return state50+ if (state.modified) {51+ const value = state.copy[prop]52+ if (!isProxy(value) && isProxyable(value))53+ return (state.copy[prop] = createProxy(state, value))54+ return value55+ } else {56+ if (prop in state.proxies) return state.proxies[prop]57+ const value = state.base[prop]58+ if (!isProxy(value) && isProxyable(value))59+ return (state.proxies[prop] = createProxy(state, value))60+ return value61+ }62+}63+64+function set(state, prop, value) {65+ if (!state.modified) {66+ if (67+ (prop in state.base && Object.is(state.base[prop], value)) ||68+ (prop in state.proxies && state.proxies[prop] === value)69+ )70+ return true71+ markChanged(state)72+ }73+ state.copy[prop] = value74+ return true75+}76+77+function deleteProperty(state, prop) {78+ markChanged(state)79+ delete state.copy[prop]80+ return true81+}82+83+function getOwnPropertyDescriptor(state, prop) {84+ const owner = state.modified85+ ? state.copy86+ : prop in state.proxies ? state.proxies : state.base87+ const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)88+ if (descriptor && !(Array.isArray(owner) && prop === "length"))89+ descriptor.configurable = true90+ return descriptor91+}92+93+function defineProperty() {94+ throw new Error(95+ "Immer does currently not support defining properties on draft objects"96+ )97+}98+99+function markChanged(state) {100+ if (!state.modified) {101+ state.modified = true102+ state.copy = Array.isArray(state.base)103+ ? state.base.slice()104+ : Object.assign({}, state.base) // TODO: eliminate those isArray checks?105+ Object.assign(state.copy, state.proxies) // yup that works for arrays as well106+ if (state.parent) markChanged(state.parent)107+ }108+}109+110+// creates a proxy for plain objects / arrays111+function createProxy(parentState, base) {112+ const state = createState(parentState, base)113+ let proxy114+ if (Array.isArray(base)) {115+ proxy = Proxy.revocable([state], arrayTraps)116+ } else {117+ proxy = Proxy.revocable(state, objectTraps)118+ }119+ revocableProxies.push(proxy)120+ return proxy.proxy121+}122+123+// given a base object, returns it if unmodified, or return the changed cloned if modified124+function finalize(base) {125+ if (isProxy(base)) {126+ const state = base[PROXY_STATE]127+ if (state.modified === true) {128+ if (state.finalized === true) return state.copy129+ state.finalized = true130+ if (Array.isArray(state.base)) return finalizeArray(state)131+ return finalizeObject(state)132+ } else return state.base133+ } else if (base !== null && typeof base === "object") {134+ // If finalize is called on an object that was not a proxy, it means that it is an object that was not there in the original135+ // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as well136+ // TODO: optimize this; walk the tree without writing to find proxies137+ if (Array.isArray(base)) {138+ for (let i = 0; i < base.length; i++) base[i] = finalize(base[i])139+ return freeze(base)140+ }141+ const proto = Object.getPrototypeOf(base)142+ if (proto === null || proto === Object.prototype) {143+ for (let key in base) base[key] = finalize(base[key])144+ return freeze(base)145+ }146+ }147+ return base148+}149+150+function finalizeObject(state) {151+ const copy = state.copy152+ const base = state.base153+ for (var prop in copy) {154+ if (copy[prop] !== base[prop]) copy[prop] = finalize(copy[prop])155+ }156+ return freeze(copy)157+}158+159+function finalizeArray(state) {160+ const copy = state.copy161+ const base = state.base162+ for (let i = 0; i < copy.length; i++) {163+ if (copy[i] !== base[i]) copy[i] = finalize(copy[i])164+ }165+ return freeze(copy)166+}167+168+export function produceProxy(baseState, producer) {169+ const previousProxies = revocableProxies170+ revocableProxies = []171+ try {172+ // create proxy for root173+ const rootClone = createProxy(undefined, baseState)174+ // execute the thunk175+ const maybeVoidReturn = producer(rootClone)176+ //values either than undefined will trigger warning;177+ !Object.is(maybeVoidReturn, undefined) &&178+ console.warn(179+ `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`180+ )181+ // and finalize the modified proxy182+ const res = finalize(rootClone)183+ // revoke all proxies184+ revocableProxies.forEach(p => p.revoke())185+ return res186+ } finally {187+ revocableProxies = previousProxies188+ }189+}modified:.gitignore-1 removed
57 unmodified lines58 .env59 60 .idea61 dist/62-proxy.jsdeleted:changelog.md-75 removed
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475# Changelog
### 0.7.0
* Immer will now use `Object.is` instead of `===` for equality checks
### 0.6.1
* Fixed issue where proxies inside new objects where not cleaned up. Fixes Fixes [#53](https://github.com/mweststrate/immer/issues/53)
### 0.6.0
* The default import now bundles both the es5 and proxy implementation as a convenient default. For more optimal bundle sizes, import `immer/proxy` or `immer/es5`
### 0.5.0
* Make sure es5.js is transpiled
### 0.4.2
* Fixed generating a wrong property descriptor for the `length` property of arrays. Fixes [#50](https://github.com/mweststrate/immer/issues/50)* Defining custom properties on drafts is no longer supported
### 0.4.1
* Added UMD build
### 0.4.0
* Introduce support for [currying](https://github.com/mweststrate/immer#currying). [#37](https://github.com/mweststrate/immer/pull/37)* Added argument checking* The name of the immer import is now idiomatically `produce`. So the recommend import statement is: `import produce from "immer"`.
### 0.3.1
* Republished, somehow NPM still returned 0.2.2
### 0.3.0 (8-1-2018)
* Increased performance of the proxy-based implementation by a factor 2x - 3x. [#38](https://github.com/mweststrate/immer/pull/38)* Improved typescript typings [#40](https://github.com/mweststrate/immer/pull/40) by [Julien Cavaleiro](https://github.com/Julienng)* Added badges, coverage and typical project shizzle. [#25](https://github.com/mweststrate/immer/pull/25) by [Gregory Assasie](https://github.com/Gregjarvez) and [#39](https://github.com/mweststrate/immer/pull/39) by [Fadi Khadra](https://github.com/fkhadra)
### 0.2.2
* Fixed [#32](https://github.com/mweststrate/immer/issue/32): changes are not properly reflected in proxies when using for example `console.dir`
### 0.2.1
* Fixed: `immer/es5.js` was not packed into the package. PR [#28](https://github.com/mweststrate/immer/pull/28) by [Nicolas Lepage](https://github.com/nlepage)
### 0.2.0
* Immer now supports JavaScript engines without Proxies as well! Just require `immer` from `"immer/es5"`. See [#22](https://github.com/mweststrate/immer/pull/22)
### 0.1.2 (2-1-2018)
* Fixed issue where trailing commas could break consumers. Fixes [#21](https://github.com/mweststrate/immer/pull/21).
### 0.1.1 (2-1-2018)
* Fixed issue where TypeScript typings were not correctly exposed. Fixes [#18](https://github.com/mweststrate/immer/issue/18).
### 0.1.0 (1-1-2018)
* Fixed `immer` function export, it is now properly exposed as the `default` export. So `import immer from "immer"`. See [#15](https://github.com/mweststrate/immer/pull/15)* Immer now automatically freezes any state modifications made. Turn this is using `setAutoFreeze(false)` for more efficiency in production builds. See [#15](https://github.com/mweststrate/immer/pull/15)* Added support for frozen state trees in strict mode. See [#15](https://github.com/mweststrate/immer/pull/15)* `immer` will now warn if you accidentally return something from the _thunk_. Fixes [#] through [#16](https://github.com/mweststrate/immer/pull/16/). By [Gregory Assasie](https://github.com/Gregjarvez).* Proxies are now automatically cleaned up. This makes it impossible to read proxies after the `immer` function has finished. This prevents users from accidentally reading stale date. [#14](https://github.com/mweststrate/immer/pull/14) by [@benbraou](https://github.com/benbraou)
### 0.0.4 (31-12-2017)
* Added typescript typings [#11](https://github.com/mweststrate/immer/pull/11) by [@benbraou](https://github.com/benbraou)* Fixed bug when setting properties to `undefined`. Fixes [#12](https://github.com/mweststrate/immer/issues/12) through [#13](https://github.com/mweststrate/immer/pull/13) by [@benbraou](https://github.com/benbraou)deleted:es5.js-1 removed
1module.exports = require("./dist/es5.js")added:immer.d.ts+37 added
12345678910111213141516171819202122232425262728293031323334353637/** * Immer takes a state, and runs a function against it. * That function can freely mutate the state, as it will create copies-on-write. * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned * * If only one argument is passed, this is interpreted as the recipe, and will create a curried function that will execute the recipe * any time it is called with a base state * * @param currentState - the state to start with * @param thunk - function that receives a proxy of the current state as first argument and which can be freely modified * @returns The next state: a new state, or the current state if nothing was modified */export default function<S = any>( currentState: S, recipe: (draftState: S) => void): S// curried invocationsexport default function<S = any, A = any, B = any, C = any>( recipe: (draftState: S, a: A, b: B, c: C) => void): (currentState: S, a: A, b: B, c: C) => Sexport default function<S = any, A = any, B = any>( recipe: (draftState: S, a: A, b: B) => void): (currentState: S, a: A, b: B) => Sexport default function<S = any, A = any>( recipe: (draftState: S, a: A) => void): (currentState: S) => Sexport default function<S = any>( recipe: (draftState: S, ...extraArgs: any[]) => void): (currentState: S, ...extraArgs: any[]) => S
/** * Automatically freezes any state trees generated by immer. * This protects against accidental modifications of the state tree outside of an immer function. * This comes with a performance impact, so it is recommended to disable this option in production. * It is by default enabled. */export function setAutoFreeze(autoFreeze: boolean): voiddeleted:index.d.ts-37 removed
12345678910111213141516171819202122232425262728293031323334353637/** * Immer takes a state, and runs a function against it. * That function can freely mutate the state, as it will create copies-on-write. * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned * * If only one argument is passed, this is interpreted as the recipe, and will create a curried function that will execute the recipe * any time it is called with a base state * * @param currentState - the state to start with * @param thunk - function that receives a proxy of the current state as first argument and which can be freely modified * @returns The next state: a new state, or the current state if nothing was modified */export default function<S = any>( currentState: S, recipe: (draftState: S) => void): S// curried invocationsexport default function<S = any, A = any, B = any, C = any>( recipe: (draftState: S, a: A, b: B, c: C) => void): (currentState: S, a: A, b: B, c: C) => Sexport default function<S = any, A = any, B = any>( recipe: (draftState: S, a: A, b: B) => void): (currentState: S, a: A, b: B) => Sexport default function<S = any, A = any>( recipe: (draftState: S, a: A) => void): (currentState: S) => Sexport default function<S = any>( recipe: (draftState: S, ...extraArgs: any[]) => void): (currentState: S, ...extraArgs: any[]) => S
/** * Automatically freezes any state trees generated by immer. * This protects against accidental modifications of the state tree outside of an immer function. * This comes with a performance impact, so it is recommended to disable this option in production. * It is by default enabled. */export function setAutoFreeze(autoFreeze: boolean): voidmodified:package.json+2 added-4 removed
123456567891019 unmodified lines3031323334353435363732 unmodified lines{ "name": "immer", "version": "0.7.0", "description": "Create your next immutable state by mutating the current one", "main": "dist/index.js", "types": "./index.d.ts", "main": "dist/immer.js", "types": "./immer.d.ts", "scripts": { "test": "jest", "test:perf": "yarn build:babel && node --expose-gc node_modules/jest-cli/bin/jest.js --verbose --testRegex '__performance_tests__/.*'", "coveralls": "jest --coverage && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage",19 unmodified lines "url": "https://github.com/mweststrate/immer/issues" }, "homepage": "https://github.com/mweststrate/immer#readme", "files": [ "es5.js", "proxy.js", "index.d.ts", "dist/" ], "devDependencies": {32 unmodified linesmodified:rollup.config.js+11 added-26 removed
3 unmodified lines4 import filesize from "rollup-plugin-filesize"5 import resolve from "rollup-plugin-node-resolve"6 import uglify from "rollup-plugin-uglify"7 8-function getFileName(file, format) {9- if (format === "umd") {10- return `dist/${file}.umd.js`11- }12-13- return `dist/${file}.js`14-}15-16-function getConfig(input, file, format) {8+function getConfig(format) {9 const conf = {18- input,10+ input: "src/index.js",11 output: {12 exports: "named",21- file: getFileName(file, format),13+ file: `dist/immer${format === "umd" ? ".umd" : ""}.js`,14 format,15 name: "immer",16 sourcemap: true17 },2 unmodified lines20 jsnext: true21 }),22 commonjs(),23 buble(),32- uglify({}, minify),24+ uglify(25+ {26+ warnings: true,27+ toplevel: true28+ },29+ minify30+ ),31 filesize()32 ]33 }34 35 return conf36 }37 40-const config = [41- getConfig("src/es5.js", "es5", "cjs"),42- getConfig("src/es5.js", "es5", "umd"),43- getConfig("src/immer.js", "immer", "cjs"),44- getConfig("src/immer.js", "immer", "umd"),45- {46- input: "src/index.js",47- output: {48- file: "dist/index.js",49- format: "cjs"50- },51- plugins: [uglify({}, minify), filesize()]52- }53-]38+const config = [getConfig("cjs"), getConfig("umd")]39 40 export default config