immer.js
This file
Path
src/immer.js
314 lines · 10.5 KiB · JavaScript
Last changed by
feat: `onAssign` for `Sets`keenondrumsbefore adoptionaa24f65
History of this fileTake it
The walk stopped after 200 commits: lines older than 3c7f374 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,feat: `onAssign` for `Maps`keenondrumsbefore adoptioneaea1b0
line 7why, one step back7 get,fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
line 8why, one step back8 has,feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 9–11why, one step back9 is,10 isDraft,11 isDraftable,nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 12why, one step back12 isEnumerable,feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 13why, one step back13 isMap,feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 14–15why, one step back14 shallowCopy,15 DRAFT_STATE,feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
line 16why, one step back16 NOTHING,feat: `onAssign` for `Sets`keenondrumsbefore adoptionaa24f65
lines 17–18why, one step back17 isSet,18 originalnit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
line 19why, one step back19} from "./common"Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 20why, one step back20import {ImmerScope} from "./scope"nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
line 21why, one step back21feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 22why, one step back22function verifyMinified() {}nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
line 23why, one step back23feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 24–28why, one step back24const configDefaults = {25 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",26 autoFreeze:27 typeof process !== "undefined"28 ? process.env.NODE_ENV !== "production"feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
lines 29–32why, one step back29 : verifyMinified.name === "verifyMinified",30 onAssign: null,31 onDelete: null,32 onCopy: nullfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 33why, one step back33}nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
line 34why, one step back34feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 35–45why, one step back35export class Immer {36 constructor(config) {37 assign(this, configDefaults, config)38 this.setUseProxies(this.useProxies)39 this.produce = this.produce.bind(this)40 }41 produce(base, recipe, patchListener) {42 // curried invocation43 if (typeof base === "function" && typeof recipe !== "function") {44 const defaultBase = recipe45 recipe = basenit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
line 46why, one step back46refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04
line 47why, one step back47 const self = thisfeat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298
line 48why, one step back48 return function curriedProduce(base = defaultBase, ...args) {refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04
line 49why, one step back49 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 50why, one step back50 }nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
lines 51–52why, one step back51 }52feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 53–54why, one step back53 // prettier-ignore54 {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 55–60why, one step back55 if (typeof recipe !== "function") {56 throw new Error("The first or second argument to `produce` must be a function")57 }58 if (patchListener !== undefined && typeof patchListener !== "function") {59 throw new Error("The third argument to `produce` must be a function or undefined")60 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 61why, one step back61 }nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
line 62why, one step back62feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 63why, one step back63 let resultnit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
line 64why, one step back64Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 65–70why, one step back65 // Only plain objects, arrays, and "immerable classes" are drafted.66 if (isDraftable(base)) {67 const scope = ImmerScope.enter()68 const proxy = this.createProxy(base)69 let hasError = true70 try {feat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298
line 71why, one step back71 result = recipe(proxy)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 72why, one step back72 hasError = falsefeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 73why, one step back73 } finally {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 74–76why, one step back74 // finally instead of catch + rethrow better preserves original stack75 if (hasError) scope.revoke()76 else scope.leave()feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 77why, one step back77 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 78–95why, one step back78 if (result instanceof Promise) {79 return result.then(80 result => {81 scope.usePatches(patchListener)82 return this.processResult(result, scope)83 },84 error => {85 scope.revoke()86 throw error87 }88 )89 }90 scope.usePatches(patchListener)91 return this.processResult(result, scope)92 } else {93 result = recipe(base)94 if (result === undefined) return base95 return result !== NOTHING ? result : undefinedfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 96–97why, one step back96 }97 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 98why, one step back98 createDraft(base) {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 99–101why, one step back99 if (!isDraftable(base)) {100 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore101 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 102–103why, one step back102 const scope = ImmerScope.enter()103 const proxy = this.createProxy(base)nit: improved error messagesAlec Larsonbefore adoptiona951f40
line 104why, one step back104 proxy[DRAFT_STATE].isManual = trueMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 105–108why, one step back105 scope.leave()106 return proxy107 }108 finishDraft(draft, patchListener) {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 109–115why, one step back109 const state = draft && draft[DRAFT_STATE]110 if (!state || !state.isManual) {111 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore112 }113 if (state.finalized) {114 throw new Error("The given draft is already finalized") // prettier-ignore115 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 116–119why, one step back116 const {scope} = state117 scope.usePatches(patchListener)118 return this.processResult(undefined, scope)119 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 120–125why, one step back120 setAutoFreeze(value) {121 this.autoFreeze = value122 }123 setUseProxies(value) {124 this.useProxies = value125 assign(this, value ? modernProxy : legacyProxy)fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77
lines 126–133why, one step back126 }127 applyPatches(base, patches) {128 // Mutate the base state when a draft is passed.129 if (isDraft(base)) {130 return applyPatches(base, patches)131 }132 // Otherwise, produce a copy of the base state.133 return this.produce(base, draft => applyPatches(draft, patches))feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 134why, one step back134 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 135–170why, one step back135 /** @internal */136 processResult(result, scope) {137 const baseDraft = scope.drafts[0]138 const isReplaced = result !== undefined && result !== baseDraft139 this.willFinalize(scope, result, isReplaced)140 if (isReplaced) {141 if (baseDraft[DRAFT_STATE].modified) {142 scope.revoke()143 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore144 }145 if (isDraftable(result)) {146 // Finalize the result in case it contains (or is) a subset of the draft.147 result = this.finalize(result, null, scope)148 }149 if (scope.patches) {150 scope.patches.push({151 op: "replace",152 path: [],153 value: result154 })155 scope.inversePatches.push({156 op: "replace",157 path: [],158 value: baseDraft[DRAFT_STATE].base159 })160 }161 } else {162 // Finalize the base draft.163 result = this.finalize(baseDraft, [], scope)164 }165 scope.revoke()166 if (scope.patches) {167 scope.patchListener(scope.patches, scope.inversePatches)168 }169 return result !== NOTHING ? result : undefined170 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 171–175why, one step back171 /**172 * @internal173 * Finalize a draft, returning either the unmodified base state or a modified174 * copy of the base state.175 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 176why, one step back176 finalize(draft, path, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 177–179why, one step back177 const state = draft[DRAFT_STATE]178 if (!state) {179 if (Object.isFrozen(draft)) return draftMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 180why, one step back180 return this.finalizeTree(draft, null, scope)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 181why, one step back181 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 182–183why, one step back182 // Never finalize drafts owned by another scope.183 if (state.scope !== scope) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 184–185why, one step back184 return draft185 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 186–188why, one step back186 if (!state.modified) {187 return state.base188 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 189–190why, one step back189 if (!state.finalized) {190 state.finalized = trueMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 191–192why, one step back191 this.finalizeTree(state.draft, path, scope)192feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
line 193why, one step back193 // 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 194why, one step back194 if (this.onDelete) {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 195–197why, one step back195 // The `assigned` object is unreliable with ES5 drafts.196 if (this.useProxies) {197 const {assigned} = statefeat: `onDelete` for `Maps`keenondrumsbefore adoption1ca49ef
lines 198–200why, one step back198 each(assigned, (prop, assignedValue) => {199 if (!assignedValue) this.onDelete(state, prop)200 })fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
line 201why, one step back201 } else {feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
line 202why, one step back202 // TODO: Figure it out for Maps and Sets if we need to support ES5fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
line 203why, one step back203 const {base, copy} = statenit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 204why, one step back204 each(base, prop => {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 205–207why, one step back205 if (!has(copy, prop)) this.onDelete(state, prop)206 })207 }feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 208why, one step back208 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 209–211why, one step back209 if (this.onCopy) {210 this.onCopy(state)211 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 212why, one step back212Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 213–215why, one step back213 // At this point, all descendants of `state.copy` have been finalized,214 // so we can be sure that `scope.canAutoFreeze` is accurate.215 if (this.autoFreeze && scope.canAutoFreeze) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 216–218why, one step back216 Object.freeze(state.copy)217 }218Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 219–226why, one step back219 if (path && scope.patches) {220 generatePatches(221 state,222 path,223 scope.patches,224 scope.inversePatches225 )226 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 227–233why, one step back227 }228 return state.copy229 }230 /**231 * @internal232 * Finalize all drafts in the given state tree.233 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 234why, one step back234 finalizeTree(root, rootPath, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 235–236why, one step back235 const state = root[DRAFT_STATE]236 if (state) {feat: limited class supportaleclarsonbefore adoption9877d64
line 237why, one step back237 if (!this.useProxies) {chore: comments and formattingAlec Larsonbefore adoptionff96173
line 238why, one step back238 // Create the final copy, with added keys and without deleted keys.feat: limited class supportaleclarsonbefore adoption9877d64
lines 239–241why, one step back239 state.copy = shallowCopy(state.draft, true)240 }241 root = state.copyfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 242why, one step back242 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 243why, one step back243Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 244why, one step back244 const needPatches = !!rootPath && !!scope.patchesfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 245why, one step back245 const finalizeProperty = (prop, value, parent) => {fix: throw on circular referencesaleclarsonbefore adoption9c6603e
lines 246–249why, one step back246 if (value === parent) {247 throw Error("Immer forbids circular references")248 }249Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 250–251why, one step back250 // In the `finalizeTree` method, only the `root` object may be a draft.251 const isDraftProp = !!state && parent === rootfeat: `onAssign` for `Sets`keenondrumsbefore adoptionaa24f65
line 252why, one step back252 const isSetMember = isSet(parent)feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 253why, one step back253refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 254why, one step back254 if (isDraft(value)) {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 255why, one step back255 const path =feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 256–257why, one step back256 isDraftProp &&257 needPatches &&feat: `onAssign` for `Sets`keenondrumsbefore adoptionaa24f65
line 258why, one step back258 !isSetMember &&feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5
line 259why, one step back259 !has(state.assigned, prop)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 260–261why, one step back260 ? rootPath.concat(prop)261 : nullfeat: passing drafts to producealeclarsonbefore adoption9c53415
line 262why, one step back262Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 263–270why, one step back263 // Drafts owned by `scope` are finalized here.264 value = this.finalize(value, path, scope)265266 // Drafts from another scope must prevent auto-freezing.267 if (isDraft(value)) {268 scope.canAutoFreeze = false269 }270chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 271why, one step back271 setProperty(parent, prop, value)feat: limited class supportaleclarsonbefore adoption9877d64
lines 272–273why, one step back272273 // Unchanged drafts are never passed to the `onAssign` hook.feat: `onDelete` for `Maps`keenondrumsbefore adoption1ca49ef
line 274why, one step back274 // TODO: Add tests and support for Setsfeat: `onAssign` for `Maps`keenondrumsbefore adoptioneaea1b0
line 275why, one step back275 if (isDraftProp && value === get(state.base, prop)) returnrefactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 276why, one step back276 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 277why, one step back277 // Unchanged draft properties are ignored.feat: `onAssign` for `Maps`keenondrumsbefore adoptioneaea1b0
line 278why, one step back278 else if (isDraftProp && is(value, get(state.base, prop))) {feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 279why, one step back279 returnfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 280why, one step back280 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 281–282why, one step back281 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.282 else if (isDraftable(value) && !Object.isFrozen(value)) {nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 283why, one step back283 each(value, finalizeProperty)refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 284–285why, one step back284 }285feat: `onAssign` for `Sets`keenondrumsbefore adoptionaa24f65
lines 286–287why, one step back286 // We cannot really assign anything inside of a Set. We can only replace the whole Set.287 if (isDraftProp && this.onAssign && !isSetMember) {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 288why, one step back288 this.onAssign(state, prop, value)feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 289why, one step back289 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 290why, one step back290 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 291why, one step back291nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 292why, one step back292 each(root, finalizeProperty)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 293why, one step back293 return rootfeat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 294why, one step back294 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 295why, one step back295}feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 296why, one step back296chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 297–301why, one step back297function setProperty(parent, prop, value) {298 // Preserve non-enumerable properties.299 if (Array.isArray(parent) || isEnumerable(parent, prop)) {300 parent[prop] = value301 returnfeat: `Map` supportkeenondrumsbefore adoption8276a6c
line 302why, one step back302 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 303–304why, one step back303 if (isMap(parent)) {304 parent.set(prop, value)feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 305–310why, one step back305 return306 }307 if (isSet(parent)) {308 // Here prop is a proxied value309 parent.delete(prop)310 parent.add(value)chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 311–313why, one step back311 return312 }313 Object.defineProperty(parent, prop, {value})feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 314why, one step back314}