immer.js
This file
Path
src/immer.js
275 lines · 9.4 KiB · JavaScript
Last changed by
refactor: rename createPublicDraft/finishPublicDraft for consistencyaleclarsonbefore adoption44ef0c8
History of this fileTake it
The walk stopped after 200 commits: lines older than d87d637 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: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 12–13why, one step back12 shallowCopy,13 DRAFT_STATE,nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 14why, one step back14 NOTHINGMerge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
line 15why, one step back15} from "./common"feat: support async recipesaleclarsonbefore adoption5fee518
line 16why, one step back16import {ImmerScope} from "./scope"Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637
line 17why, one step back17feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 18why, one step back18function verifyMinified() {}Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637
line 19why, one step back19feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 20–24why, one step back20const configDefaults = {21 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",22 autoFreeze:23 typeof process !== "undefined"24 ? process.env.NODE_ENV !== "production"feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
lines 25–28why, one step back25 : verifyMinified.name === "verifyMinified",26 onAssign: null,27 onDelete: null,28 onCopy: nullfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 29why, one step back29}Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637
line 30why, one step back30feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 31–41why, one step back31export class Immer {32 constructor(config) {33 assign(this, configDefaults, config)34 this.setUseProxies(this.useProxies)35 this.produce = this.produce.bind(this)36 }37 produce(base, recipe, patchListener) {38 // curried invocation39 if (typeof base === "function" && typeof recipe !== "function") {40 const defaultBase = recipe41 recipe = baseMerge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637
line 42why, one step back42feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 43–45why, one step back43 // prettier-ignore44 return (base = defaultBase, ...args) =>45 this.produce(base, draft => recipe.call(draft, draft, ...args))Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637
lines 46–47why, one step back46 }47feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 48–52why, one step back48 // prettier-ignore49 {50 if (typeof recipe !== "function") throw new Error("if first argument is not a function, the second argument to produce should be a function")51 if (patchListener !== undefined && typeof patchListener !== "function") throw new Error("the third argument of a producer should not be set or a function")52 }Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637
line 53why, one step back53feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 54why, one step back54 let resultfeat: support async recipesaleclarsonbefore adoption5fee518
lines 55–58why, one step back5556 // Only plain objects, arrays, and "immerable classes" are drafted.57 if (isDraftable(base)) {58 const scope = ImmerScope.enter()refactor: rename createPublicDraft/finishPublicDraft for consistencyaleclarsonbefore adoption44ef0c8
line 59why, one step back59 const proxy = this.createProxy(base)Some additional comments, improvement in error handlingMichel Weststratebefore adoptioned6dfcc
line 60why, one step back60 let hasError = truefeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 61why, one step back61 try {refactor: rename createPublicDraft/finishPublicDraft for consistencyaleclarsonbefore adoption44ef0c8
line 62why, one step back62 result = recipe.call(proxy, proxy)Some additional comments, improvement in error handlingMichel Weststratebefore adoptioned6dfcc
lines 63–67why, one step back63 hasError = false64 } finally {65 // finally instead of catch + rethrow better preserves original stack66 if (hasError) scope.revoke()67 else scope.leave()feat: support async recipesaleclarsonbefore adoption5fee518
lines 68–77why, one step back68 }69 if (result instanceof Promise) {70 return result.then(71 result => {72 scope.usePatches(patchListener)73 return this.processResult(result, scope)74 },75 error => {76 scope.revoke()77 throw errorfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 78why, one step back78 }feat: support async recipesaleclarsonbefore adoption5fee518
line 79why, one step back79 )feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 80why, one step back80 }feat: support async recipesaleclarsonbefore adoption5fee518
lines 81–86why, one step back81 scope.usePatches(patchListener)82 return this.processResult(result, scope)83 } else {84 result = recipe(base)85 if (result === undefined) return base86 return result !== NOTHING ? result : undefinedfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 87–88why, one step back87 }88 }refactor: rename createPublicDraft/finishPublicDraft for consistencyaleclarsonbefore adoption44ef0c8
lines 89–90why, one step back89 createDraft(base) {90 if (!isDraftable(base)) throw new Error("First argument to createDraft should be a plain object, an array, or an immerable object.") // prettier-ignorefeat: createDraft/finishDraft functionsMichel Weststratebefore adoptione2eb0a8
line 91why, one step back91 const scope = ImmerScope.enter()refactor: rename createPublicDraft/finishPublicDraft for consistencyaleclarsonbefore adoption44ef0c8
line 92why, one step back92 const proxy = this.createProxy(base)feat: createDraft/finishDraft functionsMichel Weststratebefore adoptione2eb0a8
line 93why, one step back93 scope.leave()refactor: rename createPublicDraft/finishPublicDraft for consistencyaleclarsonbefore adoption44ef0c8
line 94why, one step back94 return proxyfeat: createDraft/finishDraft functionsMichel Weststratebefore adoptione2eb0a8
line 95why, one step back95 }refactor: rename createPublicDraft/finishPublicDraft for consistencyaleclarsonbefore adoption44ef0c8
lines 96–97why, one step back96 finishDraft(draft, patchListener) {97 if (!isDraft(draft)) throw new Error("First argument to finishDraft should be an object from createDraft.") // prettier-ignorefeat: createDraft/finishDraft functionsMichel Weststratebefore adoptione2eb0a8
lines 98–101why, one step back98 const {scope} = draft[DRAFT_STATE]99 scope.usePatches(patchListener)100 return this.processResult(undefined, scope)101 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 102–107why, one step back102 setAutoFreeze(value) {103 this.autoFreeze = value104 }105 setUseProxies(value) {106 this.useProxies = value107 assign(this, value ? modernProxy : legacyProxy)fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77
lines 108–115why, one step back108 }109 applyPatches(base, patches) {110 // Mutate the base state when a draft is passed.111 if (isDraft(base)) {112 return applyPatches(base, patches)113 }114 // Otherwise, produce a copy of the base state.115 return this.produce(base, draft => applyPatches(draft, patches))feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 116why, one step back116 }feat: support async recipesaleclarsonbefore adoption5fee518
lines 117–152why, one step back117 /** @internal */118 processResult(result, scope) {119 const baseDraft = scope.drafts[0]120 const isReplaced = result !== undefined && result !== baseDraft121 this.willFinalize(scope, result, isReplaced)122 if (isReplaced) {123 if (baseDraft[DRAFT_STATE].modified) {124 scope.revoke()125 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore126 }127 if (isDraftable(result)) {128 // Finalize the result in case it contains (or is) a subset of the draft.129 result = this.finalize(result, null, scope)130 }131 if (scope.patches) {132 scope.patches.push({133 op: "replace",134 path: [],135 value: result136 })137 scope.inversePatches.push({138 op: "replace",139 path: [],140 value: baseDraft[DRAFT_STATE].base141 })142 }143 } else {144 // Finalize the base draft.145 result = this.finalize(baseDraft, [], scope)146 }147 scope.revoke()148 if (scope.patches) {149 scope.patchListener(scope.patches, scope.inversePatches)150 }151 return result !== NOTHING ? result : undefined152 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 153–157why, one step back153 /**154 * @internal155 * Finalize a draft, returning either the unmodified base state or a modified156 * copy of the base state.157 */feat: support async recipesaleclarsonbefore adoption5fee518
line 158why, one step back158 finalize(draft, path, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 159–161why, one step back159 const state = draft[DRAFT_STATE]160 if (!state) {161 if (Object.isFrozen(draft)) return draftfeat: support async recipesaleclarsonbefore adoption5fee518
line 162why, one step back162 return this.finalizeTree(draft, null, scope)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 163why, one step back163 }feat: support async recipesaleclarsonbefore adoption5fee518
lines 164–165why, one step back164 // Never finalize drafts owned by another scope.165 if (state.scope !== scope) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 166–167why, one step back166 return draft167 }feat: support async recipesaleclarsonbefore adoption5fee518
lines 168–170why, one step back168 if (!state.modified) {169 return state.base170 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 171–172why, one step back171 if (!state.finalized) {172 state.finalized = truefeat: support async recipesaleclarsonbefore adoption5fee518
lines 173–174why, one step back173 this.finalizeTree(state.draft, path, scope)174feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 175why, one step back175 if (this.onDelete) {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 176–183why, one step back176 // The `assigned` object is unreliable with ES5 drafts.177 if (this.useProxies) {178 const {assigned} = state179 for (const prop in assigned) {180 if (!assigned[prop]) this.onDelete(state, prop)181 }182 } else {183 const {base, copy} = statenit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 184why, one step back184 each(base, prop => {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 185–187why, one step back185 if (!has(copy, prop)) this.onDelete(state, prop)186 })187 }feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 188why, one step back188 }feat: support async recipesaleclarsonbefore adoption5fee518
lines 189–191why, one step back189 if (this.onCopy) {190 this.onCopy(state)191 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 192why, one step back192fix: recursive produce call in async recipealeclarsonbefore adoption327d659
lines 193–195why, one step back193 // At this point, all descendants of `state.copy` have been finalized,194 // so we can be sure that `scope.canAutoFreeze` is accurate.195 if (this.autoFreeze && scope.canAutoFreeze) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 196–198why, one step back196 Object.freeze(state.copy)197 }198feat: support async recipesaleclarsonbefore adoption5fee518
lines 199–206why, one step back199 if (path && scope.patches) {200 generatePatches(201 state,202 path,203 scope.patches,204 scope.inversePatches205 )206 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 207–213why, one step back207 }208 return state.copy209 }210 /**211 * @internal212 * Finalize all drafts in the given state tree.213 */fix: recursive produce call in async recipealeclarsonbefore adoption327d659
line 214why, one step back214 finalizeTree(root, rootPath, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 215–216why, one step back215 const state = root[DRAFT_STATE]216 if (state) {feat: limited class supportaleclarsonbefore adoption9877d64
lines 217–222why, one step back217 if (!this.useProxies) {218 state.finalizing = true219 state.copy = shallowCopy(state.draft, true)220 state.finalizing = false221 }222 root = state.copyfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 223why, one step back223 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 224why, one step back224fix: recursive produce call in async recipealeclarsonbefore adoption327d659
line 225why, one step back225 const needPatches = !!rootPath && !!scope.patchesfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 226why, one step back226 const finalizeProperty = (prop, value, parent) => {fix: throw on circular referencesaleclarsonbefore adoption9c6603e
lines 227–230why, one step back227 if (value === parent) {228 throw Error("Immer forbids circular references")229 }230fix: recursive produce call in async recipealeclarsonbefore adoption327d659
lines 231–232why, one step back231 // In the `finalizeTree` method, only the `root` object may be a draft.232 const isDraftProp = !!state && parent === rootfeat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 233why, one step back233refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 234why, one step back234 if (isDraft(value)) {fix: recursive produce call in async recipealeclarsonbefore adoption327d659
lines 235–238why, one step back235 const path =236 isDraftProp && needPatches && !state.assigned[prop]237 ? rootPath.concat(prop)238 : nullfeat: support async recipesaleclarsonbefore adoption5fee518
line 239why, one step back239fix: recursive produce call in async recipealeclarsonbefore adoption327d659
lines 240–241why, one step back240 // Drafts owned by `scope` are finalized here.241 value = this.finalize(value, path, scope)feat: passing drafts to producealeclarsonbefore adoption9c53415
line 242why, one step back242fix: recursive produce call in async recipealeclarsonbefore adoption327d659
lines 243–247why, one step back243 // Drafts from another scope must prevent auto-freezing.244 if (isDraft(value)) {245 scope.canAutoFreeze = false246 }247feat: limited class supportaleclarsonbefore adoption9877d64
lines 248–255why, one step back248 // Preserve non-enumerable properties.249 if (Array.isArray(parent) || isEnumerable(parent, prop)) {250 parent[prop] = value251 } else {252 Object.defineProperty(parent, prop, {value})253 }254255 // Unchanged drafts are never passed to the `onAssign` hook.fix: recursive produce call in async recipealeclarsonbefore adoption327d659
line 256why, one step back256 if (isDraftProp && value === state.base[prop]) returnrefactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 257why, one step back257 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 258why, one step back258 // Unchanged draft properties are ignored.fix: recursive produce call in async recipealeclarsonbefore adoption327d659
line 259why, one step back259 else if (isDraftProp && is(value, state.base[prop])) {feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 260why, one step back260 returnfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 261why, one step back261 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 262–263why, one step back262 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.263 else if (isDraftable(value) && !Object.isFrozen(value)) {nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 264why, one step back264 each(value, finalizeProperty)refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 265–266why, one step back265 }266fix: recursive produce call in async recipealeclarsonbefore adoption327d659
lines 267–268why, one step back267 if (isDraftProp && this.onAssign) {268 this.onAssign(state, prop, value)feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 269why, one step back269 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 270why, one step back270 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 271why, one step back271nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 272why, one step back272 each(root, finalizeProperty)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 273–275why, one step back273 return root274 }275}