immer.js
This file
Path
src/immer.js
288 lines · 9.8 KiB · JavaScript
Last changed by
refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04
History of this fileTake it
The walk stopped after 200 commits: lines older than 0d262e1 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"Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 16why, one step back16import {ImmerScope} from "./scope"Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1
line 17why, one step back17feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 18why, one step back18function verifyMinified() {}Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1
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}Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1
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 = baseFixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1
line 42why, one step back42refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04
line 43why, one step back43 const self = thisfeat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298
line 44why, one step back44 return function curriedProduce(base = defaultBase, ...args) {refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04
line 45why, one step back45 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 46why, one step back46 }Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1
lines 47–48why, one step back47 }48feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 49–50why, one step back49 // prettier-ignore50 {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 51–56why, one step back51 if (typeof recipe !== "function") {52 throw new Error("The first or second argument to `produce` must be a function")53 }54 if (patchListener !== undefined && typeof patchListener !== "function") {55 throw new Error("The third argument to `produce` must be a function or undefined")56 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 57why, one step back57 }Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1
line 58why, one step back58feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 59why, one step back59 let resultnit: dedupe some codealeclarsonbefore adoptionc9e1d98
line 60why, one step back60Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 61–66why, one step back61 // Only plain objects, arrays, and "immerable classes" are drafted.62 if (isDraftable(base)) {63 const scope = ImmerScope.enter()64 const proxy = this.createProxy(base)65 let hasError = true66 try {feat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298
line 67why, one step back67 result = recipe(proxy)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 68why, one step back68 hasError = falsefeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 69why, one step back69 } finally {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 70–72why, one step back70 // finally instead of catch + rethrow better preserves original stack71 if (hasError) scope.revoke()72 else scope.leave()feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 73why, one step back73 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 74–91why, one step back74 if (result instanceof Promise) {75 return result.then(76 result => {77 scope.usePatches(patchListener)78 return this.processResult(result, scope)79 },80 error => {81 scope.revoke()82 throw error83 }84 )85 }86 scope.usePatches(patchListener)87 return this.processResult(result, scope)88 } else {89 result = recipe(base)90 if (result === undefined) return base91 return result !== NOTHING ? result : undefinedfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 92–93why, one step back92 }93 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 94why, one step back94 createDraft(base) {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 95–97why, one step back95 if (!isDraftable(base)) {96 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore97 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 98–99why, one step back98 const scope = ImmerScope.enter()99 const proxy = this.createProxy(base)nit: improved error messagesAlec Larsonbefore adoptiona951f40
line 100why, one step back100 proxy[DRAFT_STATE].isManual = trueMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 101–104why, one step back101 scope.leave()102 return proxy103 }104 finishDraft(draft, patchListener) {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 105–111why, one step back105 const state = draft && draft[DRAFT_STATE]106 if (!state || !state.isManual) {107 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore108 }109 if (state.finalized) {110 throw new Error("The given draft is already finalized") // prettier-ignore111 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 112–115why, one step back112 const {scope} = state113 scope.usePatches(patchListener)114 return this.processResult(undefined, scope)115 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 116–121why, one step back116 setAutoFreeze(value) {117 this.autoFreeze = value118 }119 setUseProxies(value) {120 this.useProxies = value121 assign(this, value ? modernProxy : legacyProxy)fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77
lines 122–129why, one step back122 }123 applyPatches(base, patches) {124 // Mutate the base state when a draft is passed.125 if (isDraft(base)) {126 return applyPatches(base, patches)127 }128 // Otherwise, produce a copy of the base state.129 return this.produce(base, draft => applyPatches(draft, patches))feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 130why, one step back130 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 131–166why, one step back131 /** @internal */132 processResult(result, scope) {133 const baseDraft = scope.drafts[0]134 const isReplaced = result !== undefined && result !== baseDraft135 this.willFinalize(scope, result, isReplaced)136 if (isReplaced) {137 if (baseDraft[DRAFT_STATE].modified) {138 scope.revoke()139 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore140 }141 if (isDraftable(result)) {142 // Finalize the result in case it contains (or is) a subset of the draft.143 result = this.finalize(result, null, scope)144 }145 if (scope.patches) {146 scope.patches.push({147 op: "replace",148 path: [],149 value: result150 })151 scope.inversePatches.push({152 op: "replace",153 path: [],154 value: baseDraft[DRAFT_STATE].base155 })156 }157 } else {158 // Finalize the base draft.159 result = this.finalize(baseDraft, [], scope)160 }161 scope.revoke()162 if (scope.patches) {163 scope.patchListener(scope.patches, scope.inversePatches)164 }165 return result !== NOTHING ? result : undefined166 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 167–171why, one step back167 /**168 * @internal169 * Finalize a draft, returning either the unmodified base state or a modified170 * copy of the base state.171 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 172why, one step back172 finalize(draft, path, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 173–175why, one step back173 const state = draft[DRAFT_STATE]174 if (!state) {175 if (Object.isFrozen(draft)) return draftMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 176why, one step back176 return this.finalizeTree(draft, null, scope)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 177why, one step back177 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 178–179why, one step back178 // Never finalize drafts owned by another scope.179 if (state.scope !== scope) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 180–181why, one step back180 return draft181 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 182–184why, one step back182 if (!state.modified) {183 return state.base184 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 185–186why, one step back185 if (!state.finalized) {186 state.finalized = trueMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 187–188why, one step back187 this.finalizeTree(state.draft, path, scope)188feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 189why, one step back189 if (this.onDelete) {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 190–197why, one step back190 // The `assigned` object is unreliable with ES5 drafts.191 if (this.useProxies) {192 const {assigned} = state193 for (const prop in assigned) {194 if (!assigned[prop]) this.onDelete(state, prop)195 }196 } else {197 const {base, copy} = statenit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 198why, one step back198 each(base, prop => {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 199–201why, one step back199 if (!has(copy, prop)) this.onDelete(state, prop)200 })201 }feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 202why, one step back202 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 203–205why, one step back203 if (this.onCopy) {204 this.onCopy(state)205 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 206why, one step back206Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 207–209why, one step back207 // At this point, all descendants of `state.copy` have been finalized,208 // so we can be sure that `scope.canAutoFreeze` is accurate.209 if (this.autoFreeze && scope.canAutoFreeze) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 210–212why, one step back210 Object.freeze(state.copy)211 }212Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 213–220why, one step back213 if (path && scope.patches) {214 generatePatches(215 state,216 path,217 scope.patches,218 scope.inversePatches219 )220 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 221–227why, one step back221 }222 return state.copy223 }224 /**225 * @internal226 * Finalize all drafts in the given state tree.227 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 228why, one step back228 finalizeTree(root, rootPath, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 229–230why, one step back229 const state = root[DRAFT_STATE]230 if (state) {feat: limited class supportaleclarsonbefore adoption9877d64
line 231why, one step back231 if (!this.useProxies) {chore: comments and formattingAlec Larsonbefore adoptionff96173
line 232why, one step back232 // Create the final copy, with added keys and without deleted keys.feat: limited class supportaleclarsonbefore adoption9877d64
lines 233–235why, one step back233 state.copy = shallowCopy(state.draft, true)234 }235 root = state.copyfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 236why, one step back236 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 237why, one step back237Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 238why, one step back238 const needPatches = !!rootPath && !!scope.patchesfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 239why, one step back239 const finalizeProperty = (prop, value, parent) => {fix: throw on circular referencesaleclarsonbefore adoption9c6603e
lines 240–243why, one step back240 if (value === parent) {241 throw Error("Immer forbids circular references")242 }243Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 244–245why, one step back244 // In the `finalizeTree` method, only the `root` object may be a draft.245 const isDraftProp = !!state && parent === rootfeat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 246why, one step back246refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 247why, one step back247 if (isDraft(value)) {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 248–251why, one step back248 const path =249 isDraftProp && needPatches && !state.assigned[prop]250 ? rootPath.concat(prop)251 : nullfeat: passing drafts to producealeclarsonbefore adoption9c53415
line 252why, one step back252Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 253–260why, one step back253 // Drafts owned by `scope` are finalized here.254 value = this.finalize(value, path, scope)255256 // Drafts from another scope must prevent auto-freezing.257 if (isDraft(value)) {258 scope.canAutoFreeze = false259 }260feat: limited class supportaleclarsonbefore adoption9877d64
lines 261–268why, one step back261 // Preserve non-enumerable properties.262 if (Array.isArray(parent) || isEnumerable(parent, prop)) {263 parent[prop] = value264 } else {265 Object.defineProperty(parent, prop, {value})266 }267268 // Unchanged drafts are never passed to the `onAssign` hook.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 269why, one step back269 if (isDraftProp && value === state.base[prop]) returnrefactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 270why, one step back270 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 271why, one step back271 // Unchanged draft properties are ignored.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 272why, one step back272 else if (isDraftProp && is(value, state.base[prop])) {feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 273why, one step back273 returnfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 274why, one step back274 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 275–276why, one step back275 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.276 else if (isDraftable(value) && !Object.isFrozen(value)) {nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 277why, one step back277 each(value, finalizeProperty)refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 278–279why, one step back278 }279Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 280–281why, one step back280 if (isDraftProp && this.onAssign) {281 this.onAssign(state, prop, value)feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 282why, one step back282 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 283why, one step back283 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 284why, one step back284nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 285why, one step back285 each(root, finalizeProperty)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 286–288why, one step back286 return root287 }288}