immer.js
This file
Path
src/immer.js
310 lines · 10.4 KiB · JavaScript
Last changed by
feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
History of this fileTake it
The walk stopped after 200 commits: lines older than 5360e6c 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
lines 4–6why, one step back4import {5 assign,6 each,fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
line 7why, one step back7 has,feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 8–10why, one step back8 is,9 isDraft,10 isDraftable,nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 11why, one step back11 isEnumerable,feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 12why, one step back12 isMap,feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 13–14why, one step back13 shallowCopy,14 DRAFT_STATE,feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 15–16why, one step back15 NOTHING,16 isSetMerge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
line 17why, one step back17} from "./common"Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 18why, one step back18import {ImmerScope} from "./scope"Merge pull request #249 from aleclarson/patch1Michel Weststratebefore adoption5360e6c
line 19why, one step back19feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 20why, one step back20function verifyMinified() {}Merge pull request #249 from aleclarson/patch1Michel Weststratebefore adoption5360e6c
line 21why, one step back21feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 22–26why, one step back22const configDefaults = {23 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",24 autoFreeze:25 typeof process !== "undefined"26 ? process.env.NODE_ENV !== "production"feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
lines 27–30why, one step back27 : verifyMinified.name === "verifyMinified",28 onAssign: null,29 onDelete: null,30 onCopy: nullfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 31why, one step back31}Merge pull request #249 from aleclarson/patch1Michel Weststratebefore adoption5360e6c
line 32why, one step back32feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 33–43why, one step back33export class Immer {34 constructor(config) {35 assign(this, configDefaults, config)36 this.setUseProxies(this.useProxies)37 this.produce = this.produce.bind(this)38 }39 produce(base, recipe, patchListener) {40 // curried invocation41 if (typeof base === "function" && typeof recipe !== "function") {42 const defaultBase = recipe43 recipe = baseMerge pull request #249 from aleclarson/patch1Michel Weststratebefore adoption5360e6c
line 44why, one step back44refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04
line 45why, one step back45 const self = thisfeat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298
line 46why, one step back46 return function curriedProduce(base = defaultBase, ...args) {refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04
line 47why, one step back47 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignorefeat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298
line 48why, one step back48 }Merge pull request #249 from aleclarson/patch1Michel Weststratebefore adoption5360e6c
lines 49–50why, one step back49 }50feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 51–52why, one step back51 // prettier-ignore52 {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 53–58why, one step back53 if (typeof recipe !== "function") {54 throw new Error("The first or second argument to `produce` must be a function")55 }56 if (patchListener !== undefined && typeof patchListener !== "function") {57 throw new Error("The third argument to `produce` must be a function or undefined")58 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 59why, one step back59 }Merge pull request #249 from aleclarson/patch1Michel Weststratebefore adoption5360e6c
line 60why, one step back60feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 61why, one step back61 let resultnit: dedupe some codealeclarsonbefore adoptionc9e1d98
line 62why, one step back62Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 63–68why, one step back63 // Only plain objects, arrays, and "immerable classes" are drafted.64 if (isDraftable(base)) {65 const scope = ImmerScope.enter()66 const proxy = this.createProxy(base)67 let hasError = true68 try {feat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298
line 69why, one step back69 result = recipe(proxy)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 70why, one step back70 hasError = falsefeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 71why, one step back71 } finally {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 72–74why, one step back72 // finally instead of catch + rethrow better preserves original stack73 if (hasError) scope.revoke()74 else scope.leave()feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 75why, one step back75 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 76–93why, one step back76 if (result instanceof Promise) {77 return result.then(78 result => {79 scope.usePatches(patchListener)80 return this.processResult(result, scope)81 },82 error => {83 scope.revoke()84 throw error85 }86 )87 }88 scope.usePatches(patchListener)89 return this.processResult(result, scope)90 } else {91 result = recipe(base)92 if (result === undefined) return base93 return result !== NOTHING ? result : undefinedfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 94–95why, one step back94 }95 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 96why, one step back96 createDraft(base) {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 97–99why, one step back97 if (!isDraftable(base)) {98 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore99 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 100–101why, one step back100 const scope = ImmerScope.enter()101 const proxy = this.createProxy(base)nit: improved error messagesAlec Larsonbefore adoptiona951f40
line 102why, one step back102 proxy[DRAFT_STATE].isManual = trueMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 103–106why, one step back103 scope.leave()104 return proxy105 }106 finishDraft(draft, patchListener) {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 107–113why, one step back107 const state = draft && draft[DRAFT_STATE]108 if (!state || !state.isManual) {109 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore110 }111 if (state.finalized) {112 throw new Error("The given draft is already finalized") // prettier-ignore113 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 114–117why, one step back114 const {scope} = state115 scope.usePatches(patchListener)116 return this.processResult(undefined, scope)117 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 118–123why, one step back118 setAutoFreeze(value) {119 this.autoFreeze = value120 }121 setUseProxies(value) {122 this.useProxies = value123 assign(this, value ? modernProxy : legacyProxy)fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77
lines 124–131why, one step back124 }125 applyPatches(base, patches) {126 // Mutate the base state when a draft is passed.127 if (isDraft(base)) {128 return applyPatches(base, patches)129 }130 // Otherwise, produce a copy of the base state.131 return this.produce(base, draft => applyPatches(draft, patches))feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 132why, one step back132 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 133–168why, one step back133 /** @internal */134 processResult(result, scope) {135 const baseDraft = scope.drafts[0]136 const isReplaced = result !== undefined && result !== baseDraft137 this.willFinalize(scope, result, isReplaced)138 if (isReplaced) {139 if (baseDraft[DRAFT_STATE].modified) {140 scope.revoke()141 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore142 }143 if (isDraftable(result)) {144 // Finalize the result in case it contains (or is) a subset of the draft.145 result = this.finalize(result, null, scope)146 }147 if (scope.patches) {148 scope.patches.push({149 op: "replace",150 path: [],151 value: result152 })153 scope.inversePatches.push({154 op: "replace",155 path: [],156 value: baseDraft[DRAFT_STATE].base157 })158 }159 } else {160 // Finalize the base draft.161 result = this.finalize(baseDraft, [], scope)162 }163 scope.revoke()164 if (scope.patches) {165 scope.patchListener(scope.patches, scope.inversePatches)166 }167 return result !== NOTHING ? result : undefined168 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 169–173why, one step back169 /**170 * @internal171 * Finalize a draft, returning either the unmodified base state or a modified172 * copy of the base state.173 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 174why, one step back174 finalize(draft, path, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 175–177why, one step back175 const state = draft[DRAFT_STATE]176 if (!state) {177 if (Object.isFrozen(draft)) return draftMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 178why, one step back178 return this.finalizeTree(draft, null, scope)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 179why, one step back179 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 180–181why, one step back180 // Never finalize drafts owned by another scope.181 if (state.scope !== scope) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 182–183why, one step back182 return draft183 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 184–186why, one step back184 if (!state.modified) {185 return state.base186 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 187–188why, one step back187 if (!state.finalized) {188 state.finalized = trueMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 189–190why, one step back189 this.finalizeTree(state.draft, path, scope)190feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
line 191why, one step back191 // TODO: It won't fire for Sets because they don't use `assigned`. Is it an issue?feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 192why, one step back192 if (this.onDelete) {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 193–199why, one step back193 // The `assigned` object is unreliable with ES5 drafts.194 if (this.useProxies) {195 const {assigned} = state196 for (const prop in assigned) {197 if (!assigned[prop]) this.onDelete(state, prop)198 }199 } else {feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
line 200why, one step back200 // TODO: Figure it out for Maps and Sets if we need to support ES5fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
line 201why, one step back201 const {base, copy} = statenit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 202why, one step back202 each(base, prop => {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 203–205why, one step back203 if (!has(copy, prop)) this.onDelete(state, prop)204 })205 }feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 206why, one step back206 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 207–209why, one step back207 if (this.onCopy) {208 this.onCopy(state)209 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 210why, one step back210Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 211–213why, one step back211 // At this point, all descendants of `state.copy` have been finalized,212 // so we can be sure that `scope.canAutoFreeze` is accurate.213 if (this.autoFreeze && scope.canAutoFreeze) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 214–216why, one step back214 Object.freeze(state.copy)215 }216Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 217–224why, one step back217 if (path && scope.patches) {218 generatePatches(219 state,220 path,221 scope.patches,222 scope.inversePatches223 )224 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 225–231why, one step back225 }226 return state.copy227 }228 /**229 * @internal230 * Finalize all drafts in the given state tree.231 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 232why, one step back232 finalizeTree(root, rootPath, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 233–234why, one step back233 const state = root[DRAFT_STATE]234 if (state) {feat: limited class supportaleclarsonbefore adoption9877d64
line 235why, one step back235 if (!this.useProxies) {chore: comments and formattingAlec Larsonbefore adoptionff96173
line 236why, one step back236 // Create the final copy, with added keys and without deleted keys.feat: limited class supportaleclarsonbefore adoption9877d64
lines 237–239why, one step back237 state.copy = shallowCopy(state.draft, true)238 }239 root = state.copyfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 240why, one step back240 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 241why, one step back241Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 242why, one step back242 const needPatches = !!rootPath && !!scope.patchesfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 243why, one step back243 const finalizeProperty = (prop, value, parent) => {fix: throw on circular referencesaleclarsonbefore adoption9c6603e
lines 244–247why, one step back244 if (value === parent) {245 throw Error("Immer forbids circular references")246 }247Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 248–249why, one step back248 // In the `finalizeTree` method, only the `root` object may be a draft.249 const isDraftProp = !!state && parent === rootfeat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 250why, one step back250refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 251why, one step back251 if (isDraft(value)) {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 252why, one step back252 const path =feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 253–256why, one step back253 isDraftProp &&254 needPatches &&255 !isSet(parent) &&256 !state.assigned[prop]Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 257–258why, one step back257 ? rootPath.concat(prop)258 : nullfeat: passing drafts to producealeclarsonbefore adoption9c53415
line 259why, one step back259Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 260–267why, one step back260 // Drafts owned by `scope` are finalized here.261 value = this.finalize(value, path, scope)262263 // Drafts from another scope must prevent auto-freezing.264 if (isDraft(value)) {265 scope.canAutoFreeze = false266 }267chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 268why, one step back268 setProperty(parent, prop, value)feat: limited class supportaleclarsonbefore adoption9877d64
lines 269–270why, one step back269270 // Unchanged drafts are never passed to the `onAssign` hook.feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
line 271why, one step back271 // TODO: Add tests and support for Maps and SetsMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 272why, one step back272 if (isDraftProp && value === state.base[prop]) returnrefactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 273why, one step back273 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 274why, one step back274 // Unchanged draft properties are ignored.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 275why, one step back275 else if (isDraftProp && is(value, state.base[prop])) {feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 276why, one step back276 returnfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 277why, one step back277 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 278–279why, one step back278 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.279 else if (isDraftable(value) && !Object.isFrozen(value)) {nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 280why, one step back280 each(value, finalizeProperty)refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 281–282why, one step back281 }282Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 283–284why, one step back283 if (isDraftProp && this.onAssign) {284 this.onAssign(state, prop, value)feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 285why, one step back285 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 286why, one step back286 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 287why, one step back287nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 288why, one step back288 each(root, finalizeProperty)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 289why, one step back289 return rootfeat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 290why, one step back290 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 291why, one step back291}feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 292why, one step back292chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 293–297why, one step back293function setProperty(parent, prop, value) {294 // Preserve non-enumerable properties.295 if (Array.isArray(parent) || isEnumerable(parent, prop)) {296 parent[prop] = value297 returnfeat: `Map` supportkeenondrumsbefore adoption8276a6c
line 298why, one step back298 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 299–300why, one step back299 if (isMap(parent)) {300 parent.set(prop, value)feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 301–306why, one step back301 return302 }303 if (isSet(parent)) {304 // Here prop is a proxied value305 parent.delete(prop)306 parent.add(value)chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 307–309why, one step back307 return308 }309 Object.defineProperty(parent, prop, {value})feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 310why, one step back310}