Skip to content
Myr

immer.js

This file

Path

src/immer.js

287 lines · 9.7 KiB · JavaScript

Last changed by

fix: remove pointless assignmentsAlec Larsonbefore adoption366943c

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"

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

nit: improved error messagesAlec Larsonbefore adoptiona951f40

lines 50–55why, one step back
50 if (typeof recipe !== "function") {
51 throw new Error("The first or second argument to `produce` must be a function")52 }53 if (patchListener !== undefined && typeof patchListener !== "function") {54 throw new Error("The third argument to `produce` must be a function or undefined")55 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 56why, one step back
56 }

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

line 57why, one step back
57

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 58why, one step back
58 let result

nit: dedupe some codealeclarsonbefore adoptionc9e1d98

line 59why, one step back
59

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 60–67why, one step back
60 // Only plain objects, arrays, and "immerable classes" are drafted.
61 if (isDraftable(base)) {62 const scope = ImmerScope.enter()63 const proxy = this.createProxy(base)64 let hasError = true65 try {66 result = recipe.call(proxy, proxy)67 hasError = false

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 68why, one step back
68 } finally {

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 69–71why, one step back
69 // finally instead of catch + rethrow better preserves original stack
70 if (hasError) scope.revoke()71 else scope.leave()

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 72why, one step back
72 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 73–90why, one step back
73 if (result instanceof Promise) {
74 return result.then(75 result => {76 scope.usePatches(patchListener)77 return this.processResult(result, scope)78 },79 error => {80 scope.revoke()81 throw error82 }83 )84 }85 scope.usePatches(patchListener)86 return this.processResult(result, scope)87 } else {88 result = recipe(base)89 if (result === undefined) return base90 return result !== NOTHING ? result : undefined

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 91–92why, one step back
91 }
92 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 93why, one step back
93 createDraft(base) {

nit: improved error messagesAlec Larsonbefore adoptiona951f40

lines 94–96why, one step back
94 if (!isDraftable(base)) {
95 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore96 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 97–98why, one step back
97 const scope = ImmerScope.enter()
98 const proxy = this.createProxy(base)

nit: improved error messagesAlec Larsonbefore adoptiona951f40

line 99why, one step back
99 proxy[DRAFT_STATE].isManual = true

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 100–103why, one step back
100 scope.leave()
101 return proxy102 }103 finishDraft(draft, patchListener) {

nit: improved error messagesAlec Larsonbefore adoptiona951f40

lines 104–110why, one step back
104 const state = draft && draft[DRAFT_STATE]
105 if (!state || !state.isManual) {106 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore107 }108 if (state.finalized) {109 throw new Error("The given draft is already finalized") // prettier-ignore110 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 111–114why, one step back
111 const {scope} = state
112 scope.usePatches(patchListener)113 return this.processResult(undefined, scope)114 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 115–120why, one step back
115 setAutoFreeze(value) {
116 this.autoFreeze = value117 }118 setUseProxies(value) {119 this.useProxies = value120 assign(this, value ? modernProxy : legacyProxy)

fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77

lines 121–128why, one step back
121 }
122 applyPatches(base, patches) {123 // Mutate the base state when a draft is passed.124 if (isDraft(base)) {125 return applyPatches(base, patches)126 }127 // Otherwise, produce a copy of the base state.128 return this.produce(base, draft => applyPatches(draft, patches))

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 129why, one step back
129 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 130–165why, one step back
130 /** @internal */
131 processResult(result, scope) {132 const baseDraft = scope.drafts[0]133 const isReplaced = result !== undefined && result !== baseDraft134 this.willFinalize(scope, result, isReplaced)135 if (isReplaced) {136 if (baseDraft[DRAFT_STATE].modified) {137 scope.revoke()138 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore139 }140 if (isDraftable(result)) {141 // Finalize the result in case it contains (or is) a subset of the draft.142 result = this.finalize(result, null, scope)143 }144 if (scope.patches) {145 scope.patches.push({146 op: "replace",147 path: [],148 value: result149 })150 scope.inversePatches.push({151 op: "replace",152 path: [],153 value: baseDraft[DRAFT_STATE].base154 })155 }156 } else {157 // Finalize the base draft.158 result = this.finalize(baseDraft, [], scope)159 }160 scope.revoke()161 if (scope.patches) {162 scope.patchListener(scope.patches, scope.inversePatches)163 }164 return result !== NOTHING ? result : undefined165 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 166–170why, one step back
166 /**
167 * @internal168 * Finalize a draft, returning either the unmodified base state or a modified169 * copy of the base state.170 */

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 172–174why, one step back
172 const state = draft[DRAFT_STATE]
173 if (!state) {174 if (Object.isFrozen(draft)) return draft

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 176why, one step back
176 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 179–180why, one step back
179 return draft
180 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 181–183why, one step back
181 if (!state.modified) {
182 return state.base183 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

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

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

lines 189–196why, one step back
189 // The `assigned` object is unreliable with ES5 drafts.
190 if (this.useProxies) {191 const {assigned} = state192 for (const prop in assigned) {193 if (!assigned[prop]) this.onDelete(state, prop)194 }195 } else {196 const {base, copy} = state

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

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

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

lines 198–200why, one step back
198 if (!has(copy, prop)) this.onDelete(state, prop)
199 })200 }

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 201why, one step back
201 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 202–204why, one step back
202 if (this.onCopy) {
203 this.onCopy(state)204 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 205why, one step back
205

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 209–211why, one step back
209 Object.freeze(state.copy)
210 }211

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 212–219why, one step back
212 if (path && scope.patches) {
213 generatePatches(214 state,215 path,216 scope.patches,217 scope.inversePatches218 )219 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 220–226why, one step back
220 }
221 return state.copy222 }223 /**224 * @internal225 * Finalize all drafts in the given state tree.226 */

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

feat: limited class supportaleclarsonbefore adoption9877d64

line 230why, one step back
230 if (!this.useProxies) {

chore: comments and formattingAlec Larsonbefore adoptionff96173

line 231why, one step back
231 // Create the final copy, with added keys and without deleted keys.

feat: limited class supportaleclarsonbefore adoption9877d64

lines 232–234why, one step back
232 state.copy = shallowCopy(state.draft, true)
233 }234 root = state.copy

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 235why, one step back
235 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 236why, one step back
236

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

fix: throw on circular referencesaleclarsonbefore adoption9c6603e

lines 239–242why, one step back
239 if (value === parent) {
240 throw Error("Immer forbids circular references")241 }242

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 245why, one step back
245

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 247–250why, one step back
247 const path =
248 isDraftProp && needPatches && !state.assigned[prop]249 ? rootPath.concat(prop)250 : null

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 251why, one step back
251

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 252–259why, one step back
252 // Drafts owned by `scope` are finalized here.
253 value = this.finalize(value, path, scope)254255 // Drafts from another scope must prevent auto-freezing.256 if (isDraft(value)) {257 scope.canAutoFreeze = false258 }259

feat: limited class supportaleclarsonbefore adoption9877d64

lines 260–267why, one step back
260 // Preserve non-enumerable properties.
261 if (Array.isArray(parent) || isEnumerable(parent, prop)) {262 parent[prop] = value263 } else {264 Object.defineProperty(parent, prop, {value})265 }266267 // Unchanged drafts are never passed to the `onAssign` hook.

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 269why, one step back
269 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 272why, one step back
272 return

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 273why, one step back
273 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

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

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

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

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

lines 277–278why, one step back
277 }
278

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 281why, one step back
281 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 282why, one step back
282 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 283why, one step back
283

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

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 285–287why, one step back
285 return root
286 }287}