Skip to content
Myr

immer.js

This file

Path

src/immer.js

324 lines · 8.7 KiB · JavaScript

Last changed by

BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581

History of this file

Take it

The walk stopped after 200 commits: lines older than 7d2f308 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

line 4why, one step back
4import {

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 5–13why, one step back
5 assign,
6 each,7 has,8 is,9 isDraft,10 isDraftable,11 isEnumerable,12 shallowCopy,13 DRAFT_STATE,

BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581

lines 14–15why, one step back
14 NOTHING,
15 deepFreeze

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

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 18why, one step back
18

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 20why, one step back
20

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 21why, one step back
21const configDefaults = {

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 22–29why, one step back
22 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",
23 autoFreeze:24 typeof process !== "undefined"25 ? process.env.NODE_ENV !== "production"26 : verifyMinified.name === "verifyMinified",27 onAssign: null,28 onDelete: null,29 onCopy: null

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 30why, one step back
30}

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 31why, one step back
31

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 32why, one step back
32export class Immer {

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 33–42why, one step back
33 constructor(config) {
34 assign(this, configDefaults, config)35 this.setUseProxies(this.useProxies)36 this.produce = this.produce.bind(this)37 }38 produce(base, recipe, patchListener) {39 // curried invocation40 if (typeof base === "function" && typeof recipe !== "function") {41 const defaultBase = recipe42 recipe = base

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 43why, one step back
43

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 44–48why, one step back
44 const self = this
45 return function curriedProduce(base = defaultBase, ...args) {46 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore47 }48 }

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 49why, one step back
49

style: use tabsuse-tabsbefore adoptiona9c0fd0

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

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 59why, one step back
59

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 60why, one step back
60 let result

nit: dedupe some codealeclarsonbefore adoptionc9e1d98

line 61why, one step back
61

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 62–90why, one step back
62 // Only plain objects, arrays, and "immerable classes" are drafted.
63 if (isDraftable(base)) {64 const scope = ImmerScope.enter()65 const proxy = this.createProxy(base)66 let hasError = true67 try {68 result = recipe(proxy)69 hasError = false70 } finally {71 // finally instead of catch + rethrow better preserves original stack72 if (hasError) scope.revoke()73 else scope.leave()74 }75 if (result instanceof Promise) {76 return result.then(77 result => {78 scope.usePatches(patchListener)79 return this.processResult(result, scope)80 },81 error => {82 scope.revoke()83 throw error84 }85 )86 }87 scope.usePatches(patchListener)88 return this.processResult(result, scope)89 } else {90 result = recipe(base)

BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581

lines 91–94why, one step back
91 if (result === NOTHING) return undefined
92 if (result === undefined) result = base93 this.maybeFreeze(result, true)94 return result

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 95–96why, one step back
95 }
96 }

Merge pull request #402 from immerjs/produce-with-patchesMichel Weststratebefore adoptiona16deda

lines 97–112why, one step back
97 produceWithPatches(arg1, arg2, arg3) {
98 if (typeof arg1 === "function") {99 const self = this100 return (state, ...args) =>101 this.produceWithPatches(state, draft => arg1(draft, ...args))102 }103 // non-curried form104 if (arg3)105 throw new Error("A patch listener cannot be passed to produceWithPatches")106 let patches, inversePatches107 const nextState = this.produce(arg1, arg2, (p, ip) => {108 patches = p109 inversePatches = ip110 })111 return [nextState, patches, inversePatches]112 }

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 113–142why, one step back
113 createDraft(base) {
114 if (!isDraftable(base)) {115 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore116 }117 const scope = ImmerScope.enter()118 const proxy = this.createProxy(base)119 proxy[DRAFT_STATE].isManual = true120 scope.leave()121 return proxy122 }123 finishDraft(draft, patchListener) {124 const state = draft && draft[DRAFT_STATE]125 if (!state || !state.isManual) {126 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore127 }128 if (state.finalized) {129 throw new Error("The given draft is already finalized") // prettier-ignore130 }131 const {scope} = state132 scope.usePatches(patchListener)133 return this.processResult(undefined, scope)134 }135 setAutoFreeze(value) {136 this.autoFreeze = value137 }138 setUseProxies(value) {139 this.useProxies = value140 assign(this, value ? modernProxy : legacyProxy)141 }142 applyPatches(base, patches) {

fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e

lines 143–153why, one step back
143 // If a patch replaces the entire state, take that replacement as base
144 // before applying patches145 let i146 for (i = patches.length - 1; i >= 0; i--) {147 const patch = patches[i]148 if (patch.path.length === 0 && patch.op === "replace") {149 base = patch.value150 break151 }152 }153

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 154why, one step back
154 if (isDraft(base)) {

fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e

line 155why, one step back
155 // N.B: never hits if some patch a replacement, patches are never drafts

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 156–158why, one step back
156 return applyPatches(base, patches)
157 }158 // Otherwise, produce a copy of the base state.

fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e

lines 159–161why, one step back
159 return this.produce(base, draft =>
160 applyPatches(draft, patches.slice(i + 1))161 )

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 162–175why, one step back
162 }
163 /** @internal */164 processResult(result, scope) {165 const baseDraft = scope.drafts[0]166 const isReplaced = result !== undefined && result !== baseDraft167 this.willFinalize(scope, result, isReplaced)168 if (isReplaced) {169 if (baseDraft[DRAFT_STATE].modified) {170 scope.revoke()171 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore172 }173 if (isDraftable(result)) {174 // Finalize the result in case it contains (or is) a subset of the draft.175 result = this.finalize(result, null, scope)

BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581

line 176why, one step back
176 this.maybeFreeze(result)

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 177–215why, one step back
177 }
178 if (scope.patches) {179 scope.patches.push({180 op: "replace",181 path: [],182 value: result183 })184 scope.inversePatches.push({185 op: "replace",186 path: [],187 value: baseDraft[DRAFT_STATE].base188 })189 }190 } else {191 // Finalize the base draft.192 result = this.finalize(baseDraft, [], scope)193 }194 scope.revoke()195 if (scope.patches) {196 scope.patchListener(scope.patches, scope.inversePatches)197 }198 return result !== NOTHING ? result : undefined199 }200 /**201 * @internal202 * Finalize a draft, returning either the unmodified base state or a modified203 * copy of the base state.204 */205 finalize(draft, path, scope) {206 const state = draft[DRAFT_STATE]207 if (!state) {208 if (Object.isFrozen(draft)) return draft209 return this.finalizeTree(draft, null, scope)210 }211 // Never finalize drafts owned by another scope.212 if (state.scope !== scope) {213 return draft214 }215 if (!state.modified) {

BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581

line 216why, one step back
216 this.maybeFreeze(state.base, true)

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 217–221why, one step back
217 return state.base
218 }219 if (!state.finalized) {220 state.finalized = true221 this.finalizeTree(state.draft, path, scope)

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 222why, one step back
222

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 223–239why, one step back
223 if (this.onDelete) {
224 // The `assigned` object is unreliable with ES5 drafts.225 if (this.useProxies) {226 const {assigned} = state227 for (const prop in assigned) {228 if (!assigned[prop]) this.onDelete(state, prop)229 }230 } else {231 const {base, copy} = state232 each(base, prop => {233 if (!has(copy, prop)) this.onDelete(state, prop)234 })235 }236 }237 if (this.onCopy) {238 this.onCopy(state)239 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 240why, one step back
240

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 241–245why, one step back
241 // At this point, all descendants of `state.copy` have been finalized,
242 // so we can be sure that `scope.canAutoFreeze` is accurate.243 if (this.autoFreeze && scope.canAutoFreeze) {244 Object.freeze(state.copy)245 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 246why, one step back
246

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 247–265why, one step back
247 if (path && scope.patches) {
248 generatePatches(state, path, scope.patches, scope.inversePatches)249 }250 }251 return state.copy252 }253 /**254 * @internal255 * Finalize all drafts in the given state tree.256 */257 finalizeTree(root, rootPath, scope) {258 const state = root[DRAFT_STATE]259 if (state) {260 if (!this.useProxies) {261 // Create the final copy, with added keys and without deleted keys.262 state.copy = shallowCopy(state.draft, true)263 }264 root = state.copy265 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 266why, one step back
266

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 267–271why, one step back
267 const needPatches = !!rootPath && !!scope.patches
268 const finalizeProperty = (prop, value, parent) => {269 if (value === parent) {270 throw Error("Immer forbids circular references")271 }

fix: throw on circular referencesaleclarsonbefore adoption9c6603e

line 272why, one step back
272

style: use tabsuse-tabsbefore adoptiona9c0fd0

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

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 275why, one step back
275

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 276–280why, one step back
276 if (isDraft(value)) {
277 const path =278 isDraftProp && needPatches && !state.assigned[prop]279 ? rootPath.concat(prop)280 : null

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 281why, one step back
281

style: use tabsuse-tabsbefore adoptiona9c0fd0

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 284why, one step back
284

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 285–288why, one step back
285 // Drafts from another scope must prevent auto-freezing.
286 if (isDraft(value)) {287 scope.canAutoFreeze = false288 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 289why, one step back
289

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 290–295why, one step back
290 // Preserve non-enumerable properties.
291 if (Array.isArray(parent) || isEnumerable(parent, prop)) {292 parent[prop] = value293 } else {294 Object.defineProperty(parent, prop, {value})295 }

feat: limited class supportaleclarsonbefore adoption9877d64

line 296why, one step back
296

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 297–306why, one step back
297 // Unchanged drafts are never passed to the `onAssign` hook.
298 if (isDraftProp && value === state.base[prop]) return299 }300 // Unchanged draft properties are ignored.301 else if (isDraftProp && is(value, state.base[prop])) {302 return303 }304 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.305 else if (isDraftable(value) && !Object.isFrozen(value)) {306 each(value, finalizeProperty)

BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581

line 307why, one step back
307 this.maybeFreeze(value)

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 308why, one step back
308 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 309why, one step back
309

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 310–313why, one step back
310 if (isDraftProp && this.onAssign) {
311 this.onAssign(state, prop, value)312 }313 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 314why, one step back
314

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 315–316why, one step back
315 each(root, finalizeProperty)
316 return root

BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581

lines 317–322why, one step back
317 }
318 maybeFreeze(value, deep = false) {319 if (this.autoFreeze && !isDraft(value)) {320 if (deep) deepFreeze(value)321 else Object.freeze(value)322 }

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 323why, one step back
323 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 324why, one step back
324}