immer.js
This file
Path
src/immer.js
350 lines · 9.5 KiB · JavaScript
Last changed by
More tests, also fixed binding of produceWithPatchesMichel Weststratebefore adoption7d32b7c
History of this fileTake it
The walk stopped after 200 commits: lines older than 53e9ce8 point at it.
feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 1–2why, one step back1import * as legacyProxy from "./es5"2import * as modernProxy from "./proxy"fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77
line 3why, one step back3import {applyPatches, generatePatches} from "./patches"feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 4why, one step back4import {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 5–9why, one step back5 assign,6 each,7 has,8 is,9 isDraft,Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 10–12why, one step back10 isSet,11 get,12 isMap,run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 13–17why, one step back13 isDraftable,14 isEnumerable,15 shallowCopy,16 DRAFT_STATE,17 NOTHING,Merge branch 'master' into v4Michel Weststratebefore adoption741e941
line 18why, one step back18 deepFreezeperf: proxy assignaleclarsonbefore adoption53e9ce8
line 19why, one step back19} from "./common"Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 20why, one step back20import {ImmerScope} from "./scope"perf: proxy assignaleclarsonbefore adoption53e9ce8
line 21why, one step back21feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 22why, one step back22function verifyMinified() {}perf: proxy assignaleclarsonbefore adoption53e9ce8
line 23why, one step back23feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 24why, one step back24const configDefaults = {Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 25–28why, one step back25 useProxies:26 typeof Proxy !== "undefined" &&27 typeof Proxy.revocable !== "undefined" &&28 typeof Reflect !== "undefined",run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 29–35why, one step back29 autoFreeze:30 typeof process !== "undefined"31 ? process.env.NODE_ENV !== "production"32 : verifyMinified.name === "verifyMinified",33 onAssign: null,34 onDelete: null,35 onCopy: nullfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 36why, one step back36}perf: proxy assignaleclarsonbefore adoption53e9ce8
line 37why, one step back37feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 38why, one step back38export class Immer {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 39–42why, one step back39 constructor(config) {40 assign(this, configDefaults, config)41 this.setUseProxies(this.useProxies)42 this.produce = this.produce.bind(this)More tests, also fixed binding of produceWithPatchesMichel Weststratebefore adoption7d32b7c
line 43why, one step back43 this.produceWithPatches = this.produceWithPatches.bind(this)run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 44–49why, one step back44 }45 produce(base, recipe, patchListener) {46 // curried invocation47 if (typeof base === "function" && typeof recipe !== "function") {48 const defaultBase = recipe49 recipe = baseperf: proxy assignaleclarsonbefore adoption53e9ce8
line 50why, one step back50run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 51–55why, one step back51 const self = this52 return function curriedProduce(base = defaultBase, ...args) {53 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore54 }55 }perf: proxy assignaleclarsonbefore adoption53e9ce8
line 56why, one step back56run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 57–58why, one step back57 // prettier-ignore58 {Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 59–65why, one step back59 if (typeof recipe !== "function") {60 throw new Error("The first or second argument to `produce` must be a function")61 }62 if (patchListener !== undefined && typeof patchListener !== "function") {63 throw new Error("The third argument to `produce` must be a function or undefined")64 }65 }perf: proxy assignaleclarsonbefore adoption53e9ce8
line 66why, one step back66run prettier with master config before mergingMichel Weststratebefore adoptionae80361
line 67why, one step back67 let resultperf: proxy assignaleclarsonbefore adoption53e9ce8
line 68why, one step back68run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 69–81why, one step back69 // Only plain objects, arrays, and "immerable classes" are drafted.70 if (isDraftable(base)) {71 const scope = ImmerScope.enter()72 const proxy = this.createProxy(base)73 let hasError = true74 try {75 result = recipe(proxy)76 hasError = false77 } finally {78 // finally instead of catch + rethrow better preserves original stack79 if (hasError) scope.revoke()80 else scope.leave()81 }fix ie11Andrey Boldyrevbefore adoptionffd8769
line 82why, one step back82 if (typeof Promise !== "undefined" && result instanceof Promise) {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 83–97why, one step back83 return result.then(84 result => {85 scope.usePatches(patchListener)86 return this.processResult(result, scope)87 },88 error => {89 scope.revoke()90 throw error91 }92 )93 }94 scope.usePatches(patchListener)95 return this.processResult(result, scope)96 } else {97 result = recipe(base)Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 98–101why, one step back98 if (result === NOTHING) return undefined99 if (result === undefined) result = base100 this.maybeFreeze(result, true)101 return resultrun prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 102–103why, one step back102 }103 }Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 104–119why, one step back104 produceWithPatches(arg1, arg2, arg3) {105 if (typeof arg1 === "function") {106 const self = this107 return (state, ...args) =>108 this.produceWithPatches(state, draft => arg1(draft, ...args))109 }110 // non-curried form111 if (arg3)112 throw new Error("A patch listener cannot be passed to produceWithPatches")113 let patches, inversePatches114 const nextState = this.produce(arg1, arg2, (p, ip) => {115 patches = p116 inversePatches = ip117 })118 return [nextState, patches, inversePatches]119 }run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 120–149why, one step back120 createDraft(base) {121 if (!isDraftable(base)) {122 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore123 }124 const scope = ImmerScope.enter()125 const proxy = this.createProxy(base)126 proxy[DRAFT_STATE].isManual = true127 scope.leave()128 return proxy129 }130 finishDraft(draft, patchListener) {131 const state = draft && draft[DRAFT_STATE]132 if (!state || !state.isManual) {133 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore134 }135 if (state.finalized) {136 throw new Error("The given draft is already finalized") // prettier-ignore137 }138 const {scope} = state139 scope.usePatches(patchListener)140 return this.processResult(undefined, scope)141 }142 setAutoFreeze(value) {143 this.autoFreeze = value144 }145 setUseProxies(value) {146 this.useProxies = value147 assign(this, value ? modernProxy : legacyProxy)148 }149 applyPatches(base, patches) {Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 150–160why, one step back150 // If a patch replaces the entire state, take that replacement as base151 // before applying patches152 let i153 for (i = patches.length - 1; i >= 0; i--) {154 const patch = patches[i]155 if (patch.path.length === 0 && patch.op === "replace") {156 base = patch.value157 break158 }159 }160run prettier with master config before mergingMichel Weststratebefore adoptionae80361
line 161why, one step back161 if (isDraft(base)) {Merge branch 'master' into v4Michel Weststratebefore adoption741e941
line 162why, one step back162 // N.B: never hits if some patch a replacement, patches are never draftsrun prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 163–165why, one step back163 return applyPatches(base, patches)164 }165 // Otherwise, produce a copy of the base state.Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 166–168why, one step back166 return this.produce(base, draft =>167 applyPatches(draft, patches.slice(i + 1))168 )run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 169–182why, one step back169 }170 /** @internal */171 processResult(result, scope) {172 const baseDraft = scope.drafts[0]173 const isReplaced = result !== undefined && result !== baseDraft174 this.willFinalize(scope, result, isReplaced)175 if (isReplaced) {176 if (baseDraft[DRAFT_STATE].modified) {177 scope.revoke()178 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore179 }180 if (isDraftable(result)) {181 // Finalize the result in case it contains (or is) a subset of the draft.182 result = this.finalize(result, null, scope)Merge branch 'master' into v4Michel Weststratebefore adoption741e941
line 183why, one step back183 this.maybeFreeze(result)run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 184–222why, one step back184 }185 if (scope.patches) {186 scope.patches.push({187 op: "replace",188 path: [],189 value: result190 })191 scope.inversePatches.push({192 op: "replace",193 path: [],194 value: baseDraft[DRAFT_STATE].base195 })196 }197 } else {198 // Finalize the base draft.199 result = this.finalize(baseDraft, [], scope)200 }201 scope.revoke()202 if (scope.patches) {203 scope.patchListener(scope.patches, scope.inversePatches)204 }205 return result !== NOTHING ? result : undefined206 }207 /**208 * @internal209 * Finalize a draft, returning either the unmodified base state or a modified210 * copy of the base state.211 */212 finalize(draft, path, scope) {213 const state = draft[DRAFT_STATE]214 if (!state) {215 if (Object.isFrozen(draft)) return draft216 return this.finalizeTree(draft, null, scope)217 }218 // Never finalize drafts owned by another scope.219 if (state.scope !== scope) {220 return draft221 }222 if (!state.modified) {Merge branch 'master' into v4Michel Weststratebefore adoption741e941
line 223why, one step back223 this.maybeFreeze(state.base, true)run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 224–228why, one step back224 return state.base225 }226 if (!state.finalized) {227 state.finalized = true228 this.finalizeTree(state.draft, path, scope)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 229why, one step back229run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 230–248why, one step back230 // We cannot really delete anything inside of a Set. We can only replace the whole Set.231 if (this.onDelete && !isSet(state.base)) {232 // The `assigned` object is unreliable with ES5 drafts.233 if (this.useProxies) {234 const {assigned} = state235 each(assigned, (prop, exists) => {236 if (!exists) this.onDelete(state, prop)237 })238 } else {239 // TODO: Figure it out for Maps and Sets if we need to support ES5240 const {base, copy} = state241 each(base, prop => {242 if (!has(copy, prop)) this.onDelete(state, prop)243 })244 }245 }246 if (this.onCopy) {247 this.onCopy(state)248 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 249why, one step back249run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 250–254why, one step back250 // At this point, all descendants of `state.copy` have been finalized,251 // so we can be sure that `scope.canAutoFreeze` is accurate.252 if (this.autoFreeze && scope.canAutoFreeze) {253 Object.freeze(state.copy)254 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 255why, one step back255run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 256–274why, one step back256 if (path && scope.patches) {257 generatePatches(state, path, scope.patches, scope.inversePatches)258 }259 }260 return state.copy261 }262 /**263 * @internal264 * Finalize all drafts in the given state tree.265 */266 finalizeTree(root, rootPath, scope) {267 const state = root[DRAFT_STATE]268 if (state) {269 if (!this.useProxies) {270 // Create the final copy, with added keys and without deleted keys.271 state.copy = shallowCopy(state.draft, true)272 }273 root = state.copy274 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 275why, one step back275run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 276–280why, one step back276 const needPatches = !!rootPath && !!scope.patches277 const finalizeProperty = (prop, value, parent) => {278 if (value === parent) {279 throw Error("Immer forbids circular references")280 }fix: throw on circular referencesaleclarsonbefore adoption9c6603e
line 281why, one step back281run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 282–284why, one step back282 // In the `finalizeTree` method, only the `root` object may be a draft.283 const isDraftProp = !!state && parent === root284 const isSetMember = isSet(parent)feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 285why, one step back285run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 286–293why, one step back286 if (isDraft(value)) {287 const path =288 isDraftProp &&289 needPatches &&290 !isSetMember && // Set objects are atomic since they have no keys.291 !has(state.assigned, prop) // Skip deep patches for assigned keys.292 ? rootPath.concat(prop)293 : nullfeat: passing drafts to producealeclarsonbefore adoption9c53415
line 294why, one step back294run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 295–297why, one step back295 // Drafts owned by `scope` are finalized here.296 value = this.finalize(value, path, scope)297 replace(parent, prop, value)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 298why, one step back298run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 299–302why, one step back299 // Drafts from another scope must prevent auto-freezing.300 if (isDraft(value)) {301 scope.canAutoFreeze = false302 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 303why, one step back303run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 304–313why, one step back304 // Unchanged drafts are never passed to the `onAssign` hook.305 if (isDraftProp && value === get(state.base, prop)) return306 }307 // Unchanged draft properties are ignored.308 else if (isDraftProp && is(value, get(state.base, prop))) {309 return310 }311 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.312 else if (isDraftable(value) && !Object.isFrozen(value)) {313 each(value, finalizeProperty)Merge branch 'master' into v4Michel Weststratebefore adoption741e941
line 314why, one step back314 this.maybeFreeze(value)run prettier with master config before mergingMichel Weststratebefore adoptionae80361
line 315why, one step back315 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 316why, one step back316run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 317–320why, one step back317 if (isDraftProp && this.onAssign && !isSetMember) {318 this.onAssign(state, prop, value)319 }320 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 321why, one step back321run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 322–323why, one step back322 each(root, finalizeProperty)323 return rootMerge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 324–329why, one step back324 }325 maybeFreeze(value, deep = false) {326 if (this.autoFreeze && !isDraft(value)) {327 if (deep) deepFreeze(value)328 else Object.freeze(value)329 }run prettier with master config before mergingMichel Weststratebefore adoptionae80361
line 330why, one step back330 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 331why, one step back331}feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 332why, one step back332nit: minor refactoringAlec Larsonbefore adoptiona2c4754
line 333why, one step back333function replace(parent, prop, value) {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 334–349why, one step back334 if (isMap(parent)) {335 parent.set(prop, value)336 } else if (isSet(parent)) {337 // In this case, the `prop` is actually a draft.338 parent.delete(prop)339 parent.add(value)340 } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {341 // Preserve non-enumerable properties.342 parent[prop] = value343 } else {344 Object.defineProperty(parent, prop, {345 value,346 writable: true,347 configurable: true348 })349 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 350why, one step back350}