immer.js
This file
Path
src/immer.js
307 lines · 8.4 KiB · JavaScript
Last changed by
run prettier with master config before mergingMichel Weststratebefore adoptionae80361
History of this fileTake it
The walk stopped after 200 commits: lines older than 53e9ce8 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
line 4why, one step back4import {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 5–18why, one step back5 assign,6 each,7 get,8 has,9 is,10 isDraft,11 isDraftable,12 isEnumerable,13 isMap,14 shallowCopy,15 DRAFT_STATE,16 NOTHING,17 isSet,18 originalperf: proxy assignaleclarsonbefore adoption53e9ce8
line 19why, one step back19} from "./common"Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 20why, one step back20import {ImmerScope} from "./scope"perf: proxy assignaleclarsonbefore adoption53e9ce8
line 21why, one step back21feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 22why, one step back22function verifyMinified() {}perf: proxy assignaleclarsonbefore adoption53e9ce8
line 23why, one step back23feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 24why, one step back24const configDefaults = {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 25–32why, one step back25 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",26 autoFreeze:27 typeof process !== "undefined"28 ? process.env.NODE_ENV !== "production"29 : verifyMinified.name === "verifyMinified",30 onAssign: null,31 onDelete: null,32 onCopy: nullfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 33why, one step back33}perf: proxy assignaleclarsonbefore adoption53e9ce8
line 34why, one step back34feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 35why, one step back35export class Immer {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 36–45why, one step back36 constructor(config) {37 assign(this, configDefaults, config)38 this.setUseProxies(this.useProxies)39 this.produce = this.produce.bind(this)40 }41 produce(base, recipe, patchListener) {42 // curried invocation43 if (typeof base === "function" && typeof recipe !== "function") {44 const defaultBase = recipe45 recipe = baseperf: proxy assignaleclarsonbefore adoption53e9ce8
line 46why, one step back46run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 47–51why, one step back47 const self = this48 return function curriedProduce(base = defaultBase, ...args) {49 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore50 }51 }perf: proxy assignaleclarsonbefore adoption53e9ce8
line 52why, one step back52run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 53–54why, one step back53 // prettier-ignore54 {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 55–60why, one step back55 if (typeof recipe !== "function") {56 throw new Error("The first or second argument to `produce` must be a function")57 }58 if (patchListener !== undefined && typeof patchListener !== "function") {59 throw new Error("The third argument to `produce` must be a function or undefined")60 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 61why, one step back61 }perf: proxy assignaleclarsonbefore adoption53e9ce8
line 62why, one step back62run prettier with master config before mergingMichel Weststratebefore adoptionae80361
line 63why, one step back63 let resultperf: proxy assignaleclarsonbefore adoption53e9ce8
line 64why, one step back64run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 65–191why, one step back65 // Only plain objects, arrays, and "immerable classes" are drafted.66 if (isDraftable(base)) {67 const scope = ImmerScope.enter()68 const proxy = this.createProxy(base)69 let hasError = true70 try {71 result = recipe(proxy)72 hasError = false73 } finally {74 // finally instead of catch + rethrow better preserves original stack75 if (hasError) scope.revoke()76 else scope.leave()77 }78 if (result instanceof Promise) {79 return result.then(80 result => {81 scope.usePatches(patchListener)82 return this.processResult(result, scope)83 },84 error => {85 scope.revoke()86 throw error87 }88 )89 }90 scope.usePatches(patchListener)91 return this.processResult(result, scope)92 } else {93 result = recipe(base)94 if (result === undefined) return base95 return result !== NOTHING ? result : undefined96 }97 }98 createDraft(base) {99 if (!isDraftable(base)) {100 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore101 }102 const scope = ImmerScope.enter()103 const proxy = this.createProxy(base)104 proxy[DRAFT_STATE].isManual = true105 scope.leave()106 return proxy107 }108 finishDraft(draft, patchListener) {109 const state = draft && draft[DRAFT_STATE]110 if (!state || !state.isManual) {111 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore112 }113 if (state.finalized) {114 throw new Error("The given draft is already finalized") // prettier-ignore115 }116 const {scope} = state117 scope.usePatches(patchListener)118 return this.processResult(undefined, scope)119 }120 setAutoFreeze(value) {121 this.autoFreeze = value122 }123 setUseProxies(value) {124 this.useProxies = value125 assign(this, value ? modernProxy : legacyProxy)126 }127 applyPatches(base, patches) {128 // Mutate the base state when a draft is passed.129 if (isDraft(base)) {130 return applyPatches(base, patches)131 }132 // Otherwise, produce a copy of the base state.133 return this.produce(base, draft => applyPatches(draft, patches))134 }135 /** @internal */136 processResult(result, scope) {137 const baseDraft = scope.drafts[0]138 const isReplaced = result !== undefined && result !== baseDraft139 this.willFinalize(scope, result, isReplaced)140 if (isReplaced) {141 if (baseDraft[DRAFT_STATE].modified) {142 scope.revoke()143 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore144 }145 if (isDraftable(result)) {146 // Finalize the result in case it contains (or is) a subset of the draft.147 result = this.finalize(result, null, scope)148 }149 if (scope.patches) {150 scope.patches.push({151 op: "replace",152 path: [],153 value: result154 })155 scope.inversePatches.push({156 op: "replace",157 path: [],158 value: baseDraft[DRAFT_STATE].base159 })160 }161 } else {162 // Finalize the base draft.163 result = this.finalize(baseDraft, [], scope)164 }165 scope.revoke()166 if (scope.patches) {167 scope.patchListener(scope.patches, scope.inversePatches)168 }169 return result !== NOTHING ? result : undefined170 }171 /**172 * @internal173 * Finalize a draft, returning either the unmodified base state or a modified174 * copy of the base state.175 */176 finalize(draft, path, scope) {177 const state = draft[DRAFT_STATE]178 if (!state) {179 if (Object.isFrozen(draft)) return draft180 return this.finalizeTree(draft, null, scope)181 }182 // Never finalize drafts owned by another scope.183 if (state.scope !== scope) {184 return draft185 }186 if (!state.modified) {187 return state.base188 }189 if (!state.finalized) {190 state.finalized = true191 this.finalizeTree(state.draft, path, scope)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 192why, one step back192run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 193–211why, one step back193 // We cannot really delete anything inside of a Set. We can only replace the whole Set.194 if (this.onDelete && !isSet(state.base)) {195 // The `assigned` object is unreliable with ES5 drafts.196 if (this.useProxies) {197 const {assigned} = state198 each(assigned, (prop, exists) => {199 if (!exists) this.onDelete(state, prop)200 })201 } else {202 // TODO: Figure it out for Maps and Sets if we need to support ES5203 const {base, copy} = state204 each(base, prop => {205 if (!has(copy, prop)) this.onDelete(state, prop)206 })207 }208 }209 if (this.onCopy) {210 this.onCopy(state)211 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 212why, one step back212run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 213–217why, one step back213 // At this point, all descendants of `state.copy` have been finalized,214 // so we can be sure that `scope.canAutoFreeze` is accurate.215 if (this.autoFreeze && scope.canAutoFreeze) {216 Object.freeze(state.copy)217 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 218why, one step back218run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 219–237why, one step back219 if (path && scope.patches) {220 generatePatches(state, path, scope.patches, scope.inversePatches)221 }222 }223 return state.copy224 }225 /**226 * @internal227 * Finalize all drafts in the given state tree.228 */229 finalizeTree(root, rootPath, scope) {230 const state = root[DRAFT_STATE]231 if (state) {232 if (!this.useProxies) {233 // Create the final copy, with added keys and without deleted keys.234 state.copy = shallowCopy(state.draft, true)235 }236 root = state.copy237 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 238why, one step back238run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 239–243why, one step back239 const needPatches = !!rootPath && !!scope.patches240 const finalizeProperty = (prop, value, parent) => {241 if (value === parent) {242 throw Error("Immer forbids circular references")243 }fix: throw on circular referencesaleclarsonbefore adoption9c6603e
line 244why, one step back244run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 245–247why, one step back245 // In the `finalizeTree` method, only the `root` object may be a draft.246 const isDraftProp = !!state && parent === root247 const isSetMember = isSet(parent)feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 248why, one step back248run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 249–256why, one step back249 if (isDraft(value)) {250 const path =251 isDraftProp &&252 needPatches &&253 !isSetMember && // Set objects are atomic since they have no keys.254 !has(state.assigned, prop) // Skip deep patches for assigned keys.255 ? rootPath.concat(prop)256 : nullfeat: passing drafts to producealeclarsonbefore adoption9c53415
line 257why, one step back257run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 258–260why, one step back258 // Drafts owned by `scope` are finalized here.259 value = this.finalize(value, path, scope)260 replace(parent, prop, value)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 261why, one step back261run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 262–265why, one step back262 // Drafts from another scope must prevent auto-freezing.263 if (isDraft(value)) {264 scope.canAutoFreeze = false265 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 266why, one step back266run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 267–277why, one step back267 // Unchanged drafts are never passed to the `onAssign` hook.268 if (isDraftProp && value === get(state.base, prop)) return269 }270 // Unchanged draft properties are ignored.271 else if (isDraftProp && is(value, get(state.base, prop))) {272 return273 }274 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.275 else if (isDraftable(value) && !Object.isFrozen(value)) {276 each(value, finalizeProperty)277 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 278why, one step back278run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 279–283why, one step back279 // We cannot really assign anything inside of a Set. We can only replace the whole Set.280 if (isDraftProp && this.onAssign && !isSetMember) {281 this.onAssign(state, prop, value)282 }283 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 284why, one step back284run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 285–287why, one step back285 each(root, finalizeProperty)286 return root287 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 288why, one step back288}feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 289why, one step back289nit: minor refactoringAlec Larsonbefore adoptiona2c4754
line 290why, one step back290function replace(parent, prop, value) {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 291–306why, one step back291 if (isMap(parent)) {292 parent.set(prop, value)293 } else if (isSet(parent)) {294 // In this case, the `prop` is actually a draft.295 parent.delete(prop)296 parent.add(value)297 } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {298 // Preserve non-enumerable properties.299 parent[prop] = value300 } else {301 Object.defineProperty(parent, prop, {302 value,303 writable: true,304 configurable: true305 })306 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 307why, one step back307}