Skip to content
Myr

immer.js

This file

Path

src/immer.js

262 lines · 8.8 KiB · JavaScript

Last changed by

Some additional comments, improvement in error handlingMichel Weststratebefore adoptioned6dfcc

History of this file

Take it

The walk stopped after 200 commits: lines older than d87d637 point at it.

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 1–2why, one step back
1import * as legacyProxy from "./es5"
2import * as modernProxy from "./proxy"

fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77

line 3why, one step back
3import {applyPatches, generatePatches} from "./patches"

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 4–6why, one step back
4import {
5 assign,6 each,

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

line 7why, one step back
7 has,

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 8–10why, one step back
8 is,
9 isDraft,10 isDraftable,

nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419

line 11why, one step back
11 isEnumerable,

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 12–13why, one step back
12 shallowCopy,
13 DRAFT_STATE,

nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419

line 14why, one step back
14 NOTHING

Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417

line 15why, one step back
15} from "./common"

feat: support async recipesaleclarsonbefore adoption5fee518

line 16why, one step back
16import {ImmerScope} from "./scope"

Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637

line 17why, one step back
17

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 18why, one step back
18function verifyMinified() {}

Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637

line 19why, one step back
19

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 20–24why, one step back
20const 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 back
25 : verifyMinified.name === "verifyMinified",
26 onAssign: null,27 onDelete: null,28 onCopy: null

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 29why, one step back
29}

Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637

line 30why, one step back
30

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 31–41why, one step back
31export 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 = base

Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637

line 42why, one step back
42

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 43–45why, one step back
43 // prettier-ignore
44 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 back
46 }
47

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 48–52why, one step back
48 // prettier-ignore
49 {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 back
53

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 54why, one step back
54 let result

feat: support async recipesaleclarsonbefore adoption5fee518

lines 55–58why, one step back
55
56 // Only plain objects, arrays, and "immerable classes" are drafted.57 if (isDraftable(base)) {58 const scope = ImmerScope.enter()

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 59why, one step back
59 const baseDraft = this.createDraft(base)

Some additional comments, improvement in error handlingMichel Weststratebefore adoptioned6dfcc

line 60why, one step back
60 let hasError = true

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 61–62why, one step back
61 try {
62 result = recipe.call(baseDraft, baseDraft)

Some additional comments, improvement in error handlingMichel Weststratebefore adoptioned6dfcc

lines 63–67why, one step back
63 hasError = false
64 } 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 back
68 }
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 error

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 78why, one step back
78 }

feat: support async recipesaleclarsonbefore adoption5fee518

line 79why, one step back
79 )

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 80why, one step back
80 }

feat: support async recipesaleclarsonbefore adoption5fee518

lines 81–86why, one step back
81 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 : undefined

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 87–94why, one step back
87 }
88 }89 setAutoFreeze(value) {90 this.autoFreeze = value91 }92 setUseProxies(value) {93 this.useProxies = value94 assign(this, value ? modernProxy : legacyProxy)

fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77

lines 95–102why, one step back
95 }
96 applyPatches(base, patches) {97 // Mutate the base state when a draft is passed.98 if (isDraft(base)) {99 return applyPatches(base, patches)100 }101 // Otherwise, produce a copy of the base state.102 return this.produce(base, draft => applyPatches(draft, patches))

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 103why, one step back
103 }

feat: support async recipesaleclarsonbefore adoption5fee518

lines 104–139why, one step back
104 /** @internal */
105 processResult(result, scope) {106 const baseDraft = scope.drafts[0]107 const isReplaced = result !== undefined && result !== baseDraft108 this.willFinalize(scope, result, isReplaced)109 if (isReplaced) {110 if (baseDraft[DRAFT_STATE].modified) {111 scope.revoke()112 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore113 }114 if (isDraftable(result)) {115 // Finalize the result in case it contains (or is) a subset of the draft.116 result = this.finalize(result, null, scope)117 }118 if (scope.patches) {119 scope.patches.push({120 op: "replace",121 path: [],122 value: result123 })124 scope.inversePatches.push({125 op: "replace",126 path: [],127 value: baseDraft[DRAFT_STATE].base128 })129 }130 } else {131 // Finalize the base draft.132 result = this.finalize(baseDraft, [], scope)133 }134 scope.revoke()135 if (scope.patches) {136 scope.patchListener(scope.patches, scope.inversePatches)137 }138 return result !== NOTHING ? result : undefined139 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 140–144why, one step back
140 /**
141 * @internal142 * Finalize a draft, returning either the unmodified base state or a modified143 * copy of the base state.144 */

feat: support async recipesaleclarsonbefore adoption5fee518

line 145why, one step back
145 finalize(draft, path, scope) {

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 146–148why, one step back
146 const state = draft[DRAFT_STATE]
147 if (!state) {148 if (Object.isFrozen(draft)) return draft

feat: support async recipesaleclarsonbefore adoption5fee518

line 149why, one step back
149 return this.finalizeTree(draft, null, scope)

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 150why, one step back
150 }

feat: support async recipesaleclarsonbefore adoption5fee518

lines 151–152why, one step back
151 // Never finalize drafts owned by another scope.
152 if (state.scope !== scope) {

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 153–154why, one step back
153 return draft
154 }

feat: support async recipesaleclarsonbefore adoption5fee518

lines 155–157why, one step back
155 if (!state.modified) {
156 return state.base157 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 158–159why, one step back
158 if (!state.finalized) {
159 state.finalized = true

feat: support async recipesaleclarsonbefore adoption5fee518

lines 160–161why, one step back
160 this.finalizeTree(state.draft, path, scope)
161

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 162why, one step back
162 if (this.onDelete) {

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

lines 163–170why, one step back
163 // The `assigned` object is unreliable with ES5 drafts.
164 if (this.useProxies) {165 const {assigned} = state166 for (const prop in assigned) {167 if (!assigned[prop]) this.onDelete(state, prop)168 }169 } else {170 const {base, copy} = state

nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419

line 171why, one step back
171 each(base, prop => {

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

lines 172–174why, one step back
172 if (!has(copy, prop)) this.onDelete(state, prop)
173 })174 }

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 175why, one step back
175 }

feat: support async recipesaleclarsonbefore adoption5fee518

lines 176–178why, one step back
176 if (this.onCopy) {
177 this.onCopy(state)178 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 179why, one step back
179

fix: recursive produce call in async recipealeclarsonbefore adoption327d659

lines 180–182why, one step back
180 // At this point, all descendants of `state.copy` have been finalized,
181 // so we can be sure that `scope.canAutoFreeze` is accurate.182 if (this.autoFreeze && scope.canAutoFreeze) {

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 183–185why, one step back
183 Object.freeze(state.copy)
184 }185

feat: support async recipesaleclarsonbefore adoption5fee518

lines 186–193why, one step back
186 if (path && scope.patches) {
187 generatePatches(188 state,189 path,190 scope.patches,191 scope.inversePatches192 )193 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 194–200why, one step back
194 }
195 return state.copy196 }197 /**198 * @internal199 * Finalize all drafts in the given state tree.200 */

fix: recursive produce call in async recipealeclarsonbefore adoption327d659

line 201why, one step back
201 finalizeTree(root, rootPath, scope) {

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 202–203why, one step back
202 const state = root[DRAFT_STATE]
203 if (state) {

feat: limited class supportaleclarsonbefore adoption9877d64

lines 204–209why, one step back
204 if (!this.useProxies) {
205 state.finalizing = true206 state.copy = shallowCopy(state.draft, true)207 state.finalizing = false208 }209 root = state.copy

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 210why, one step back
210 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 211why, one step back
211

fix: recursive produce call in async recipealeclarsonbefore adoption327d659

line 212why, one step back
212 const needPatches = !!rootPath && !!scope.patches

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 213why, one step back
213 const finalizeProperty = (prop, value, parent) => {

fix: throw on circular referencesaleclarsonbefore adoption9c6603e

lines 214–217why, one step back
214 if (value === parent) {
215 throw Error("Immer forbids circular references")216 }217

fix: recursive produce call in async recipealeclarsonbefore adoption327d659

lines 218–219why, one step back
218 // In the `finalizeTree` method, only the `root` object may be a draft.
219 const isDraftProp = !!state && parent === root

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 220why, one step back
220

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 221why, one step back
221 if (isDraft(value)) {

fix: recursive produce call in async recipealeclarsonbefore adoption327d659

lines 222–225why, one step back
222 const path =
223 isDraftProp && needPatches && !state.assigned[prop]224 ? rootPath.concat(prop)225 : null

feat: support async recipesaleclarsonbefore adoption5fee518

line 226why, one step back
226

fix: recursive produce call in async recipealeclarsonbefore adoption327d659

lines 227–228why, one step back
227 // Drafts owned by `scope` are finalized here.
228 value = this.finalize(value, path, scope)

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 229why, one step back
229

fix: recursive produce call in async recipealeclarsonbefore adoption327d659

lines 230–234why, one step back
230 // Drafts from another scope must prevent auto-freezing.
231 if (isDraft(value)) {232 scope.canAutoFreeze = false233 }234

feat: limited class supportaleclarsonbefore adoption9877d64

lines 235–242why, one step back
235 // Preserve non-enumerable properties.
236 if (Array.isArray(parent) || isEnumerable(parent, prop)) {237 parent[prop] = value238 } else {239 Object.defineProperty(parent, prop, {value})240 }241242 // Unchanged drafts are never passed to the `onAssign` hook.

fix: recursive produce call in async recipealeclarsonbefore adoption327d659

line 243why, one step back
243 if (isDraftProp && value === state.base[prop]) return

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 244why, one step back
244 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 245why, one step back
245 // Unchanged draft properties are ignored.

fix: recursive produce call in async recipealeclarsonbefore adoption327d659

line 246why, one step back
246 else if (isDraftProp && is(value, state.base[prop])) {

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 247why, one step back
247 return

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 248why, one step back
248 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

lines 249–250why, one step back
249 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.
250 else if (isDraftable(value) && !Object.isFrozen(value)) {

nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419

line 251why, one step back
251 each(value, finalizeProperty)

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

lines 252–253why, one step back
252 }
253

fix: recursive produce call in async recipealeclarsonbefore adoption327d659

lines 254–255why, one step back
254 if (isDraftProp && this.onAssign) {
255 this.onAssign(state, prop, value)

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 256why, one step back
256 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 257why, one step back
257 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 258why, one step back
258

nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419

line 259why, one step back
259 each(root, finalizeProperty)

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 260–262why, one step back
260 return root
261 }262}