immer.js
This file
Path
src/immer.js
349 lines · 9.4 KiB · JavaScript
Last changed by
fix ie11Andrey Boldyrevbefore adoptionffd8769
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–9why, one step back5 assign,6 each,7 has,8 is,9 isDraft,Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 10–12why, one step back10 isSet,11 get,12 isMap,run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 13–17why, one step back13 isDraftable,14 isEnumerable,15 shallowCopy,16 DRAFT_STATE,17 NOTHING,Merge branch 'master' into v4Michel Weststratebefore adoption741e941
line 18why, one step back18 deepFreezeperf: 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 = {Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 25–28why, one step back25 useProxies:26 typeof Proxy !== "undefined" &&27 typeof Proxy.revocable !== "undefined" &&28 typeof Reflect !== "undefined",run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 29–35why, one step back29 autoFreeze:30 typeof process !== "undefined"31 ? process.env.NODE_ENV !== "production"32 : verifyMinified.name === "verifyMinified",33 onAssign: null,34 onDelete: null,35 onCopy: nullfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 36why, one step back36}perf: proxy assignaleclarsonbefore adoption53e9ce8
line 37why, one step back37feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 38why, one step back38export class Immer {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 39–48why, one step back39 constructor(config) {40 assign(this, configDefaults, config)41 this.setUseProxies(this.useProxies)42 this.produce = this.produce.bind(this)43 }44 produce(base, recipe, patchListener) {45 // curried invocation46 if (typeof base === "function" && typeof recipe !== "function") {47 const defaultBase = recipe48 recipe = baseperf: proxy assignaleclarsonbefore adoption53e9ce8
line 49why, one step back49run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 50–54why, one step back50 const self = this51 return function curriedProduce(base = defaultBase, ...args) {52 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore53 }54 }perf: proxy assignaleclarsonbefore adoption53e9ce8
line 55why, one step back55run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 56–57why, one step back56 // prettier-ignore57 {Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 58–64why, one step back58 if (typeof recipe !== "function") {59 throw new Error("The first or second argument to `produce` must be a function")60 }61 if (patchListener !== undefined && typeof patchListener !== "function") {62 throw new Error("The third argument to `produce` must be a function or undefined")63 }64 }perf: proxy assignaleclarsonbefore adoption53e9ce8
line 65why, one step back65run prettier with master config before mergingMichel Weststratebefore adoptionae80361
line 66why, one step back66 let resultperf: proxy assignaleclarsonbefore adoption53e9ce8
line 67why, one step back67run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 68–80why, one step back68 // Only plain objects, arrays, and "immerable classes" are drafted.69 if (isDraftable(base)) {70 const scope = ImmerScope.enter()71 const proxy = this.createProxy(base)72 let hasError = true73 try {74 result = recipe(proxy)75 hasError = false76 } finally {77 // finally instead of catch + rethrow better preserves original stack78 if (hasError) scope.revoke()79 else scope.leave()80 }fix ie11Andrey Boldyrevbefore adoptionffd8769
line 81why, one step back81 if (typeof Promise !== "undefined" && result instanceof Promise) {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 82–96why, one step back82 return result.then(83 result => {84 scope.usePatches(patchListener)85 return this.processResult(result, scope)86 },87 error => {88 scope.revoke()89 throw error90 }91 )92 }93 scope.usePatches(patchListener)94 return this.processResult(result, scope)95 } else {96 result = recipe(base)Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 97–100why, one step back97 if (result === NOTHING) return undefined98 if (result === undefined) result = base99 this.maybeFreeze(result, true)100 return resultrun prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 101–102why, one step back101 }102 }Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 103–118why, one step back103 produceWithPatches(arg1, arg2, arg3) {104 if (typeof arg1 === "function") {105 const self = this106 return (state, ...args) =>107 this.produceWithPatches(state, draft => arg1(draft, ...args))108 }109 // non-curried form110 if (arg3)111 throw new Error("A patch listener cannot be passed to produceWithPatches")112 let patches, inversePatches113 const nextState = this.produce(arg1, arg2, (p, ip) => {114 patches = p115 inversePatches = ip116 })117 return [nextState, patches, inversePatches]118 }run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 119–148why, one step back119 createDraft(base) {120 if (!isDraftable(base)) {121 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore122 }123 const scope = ImmerScope.enter()124 const proxy = this.createProxy(base)125 proxy[DRAFT_STATE].isManual = true126 scope.leave()127 return proxy128 }129 finishDraft(draft, patchListener) {130 const state = draft && draft[DRAFT_STATE]131 if (!state || !state.isManual) {132 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore133 }134 if (state.finalized) {135 throw new Error("The given draft is already finalized") // prettier-ignore136 }137 const {scope} = state138 scope.usePatches(patchListener)139 return this.processResult(undefined, scope)140 }141 setAutoFreeze(value) {142 this.autoFreeze = value143 }144 setUseProxies(value) {145 this.useProxies = value146 assign(this, value ? modernProxy : legacyProxy)147 }148 applyPatches(base, patches) {Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 149–159why, one step back149 // If a patch replaces the entire state, take that replacement as base150 // before applying patches151 let i152 for (i = patches.length - 1; i >= 0; i--) {153 const patch = patches[i]154 if (patch.path.length === 0 && patch.op === "replace") {155 base = patch.value156 break157 }158 }159run prettier with master config before mergingMichel Weststratebefore adoptionae80361
line 160why, one step back160 if (isDraft(base)) {Merge branch 'master' into v4Michel Weststratebefore adoption741e941
line 161why, one step back161 // N.B: never hits if some patch a replacement, patches are never draftsrun prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 162–164why, one step back162 return applyPatches(base, patches)163 }164 // Otherwise, produce a copy of the base state.Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 165–167why, one step back165 return this.produce(base, draft =>166 applyPatches(draft, patches.slice(i + 1))167 )run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 168–181why, one step back168 }169 /** @internal */170 processResult(result, scope) {171 const baseDraft = scope.drafts[0]172 const isReplaced = result !== undefined && result !== baseDraft173 this.willFinalize(scope, result, isReplaced)174 if (isReplaced) {175 if (baseDraft[DRAFT_STATE].modified) {176 scope.revoke()177 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore178 }179 if (isDraftable(result)) {180 // Finalize the result in case it contains (or is) a subset of the draft.181 result = this.finalize(result, null, scope)Merge branch 'master' into v4Michel Weststratebefore adoption741e941
line 182why, one step back182 this.maybeFreeze(result)run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 183–221why, one step back183 }184 if (scope.patches) {185 scope.patches.push({186 op: "replace",187 path: [],188 value: result189 })190 scope.inversePatches.push({191 op: "replace",192 path: [],193 value: baseDraft[DRAFT_STATE].base194 })195 }196 } else {197 // Finalize the base draft.198 result = this.finalize(baseDraft, [], scope)199 }200 scope.revoke()201 if (scope.patches) {202 scope.patchListener(scope.patches, scope.inversePatches)203 }204 return result !== NOTHING ? result : undefined205 }206 /**207 * @internal208 * Finalize a draft, returning either the unmodified base state or a modified209 * copy of the base state.210 */211 finalize(draft, path, scope) {212 const state = draft[DRAFT_STATE]213 if (!state) {214 if (Object.isFrozen(draft)) return draft215 return this.finalizeTree(draft, null, scope)216 }217 // Never finalize drafts owned by another scope.218 if (state.scope !== scope) {219 return draft220 }221 if (!state.modified) {Merge branch 'master' into v4Michel Weststratebefore adoption741e941
line 222why, one step back222 this.maybeFreeze(state.base, true)run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 223–227why, one step back223 return state.base224 }225 if (!state.finalized) {226 state.finalized = true227 this.finalizeTree(state.draft, path, scope)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 228why, one step back228run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 229–247why, one step back229 // We cannot really delete anything inside of a Set. We can only replace the whole Set.230 if (this.onDelete && !isSet(state.base)) {231 // The `assigned` object is unreliable with ES5 drafts.232 if (this.useProxies) {233 const {assigned} = state234 each(assigned, (prop, exists) => {235 if (!exists) this.onDelete(state, prop)236 })237 } else {238 // TODO: Figure it out for Maps and Sets if we need to support ES5239 const {base, copy} = state240 each(base, prop => {241 if (!has(copy, prop)) this.onDelete(state, prop)242 })243 }244 }245 if (this.onCopy) {246 this.onCopy(state)247 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 248why, one step back248run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 249–253why, one step back249 // At this point, all descendants of `state.copy` have been finalized,250 // so we can be sure that `scope.canAutoFreeze` is accurate.251 if (this.autoFreeze && scope.canAutoFreeze) {252 Object.freeze(state.copy)253 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 254why, one step back254run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 255–273why, one step back255 if (path && scope.patches) {256 generatePatches(state, path, scope.patches, scope.inversePatches)257 }258 }259 return state.copy260 }261 /**262 * @internal263 * Finalize all drafts in the given state tree.264 */265 finalizeTree(root, rootPath, scope) {266 const state = root[DRAFT_STATE]267 if (state) {268 if (!this.useProxies) {269 // Create the final copy, with added keys and without deleted keys.270 state.copy = shallowCopy(state.draft, true)271 }272 root = state.copy273 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 274why, one step back274run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 275–279why, one step back275 const needPatches = !!rootPath && !!scope.patches276 const finalizeProperty = (prop, value, parent) => {277 if (value === parent) {278 throw Error("Immer forbids circular references")279 }fix: throw on circular referencesaleclarsonbefore adoption9c6603e
line 280why, one step back280run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 281–283why, one step back281 // In the `finalizeTree` method, only the `root` object may be a draft.282 const isDraftProp = !!state && parent === root283 const isSetMember = isSet(parent)feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 284why, one step back284run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 285–292why, one step back285 if (isDraft(value)) {286 const path =287 isDraftProp &&288 needPatches &&289 !isSetMember && // Set objects are atomic since they have no keys.290 !has(state.assigned, prop) // Skip deep patches for assigned keys.291 ? rootPath.concat(prop)292 : nullfeat: passing drafts to producealeclarsonbefore adoption9c53415
line 293why, one step back293run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 294–296why, one step back294 // Drafts owned by `scope` are finalized here.295 value = this.finalize(value, path, scope)296 replace(parent, prop, value)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 297why, one step back297run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 298–301why, one step back298 // Drafts from another scope must prevent auto-freezing.299 if (isDraft(value)) {300 scope.canAutoFreeze = false301 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 302why, one step back302run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 303–312why, one step back303 // Unchanged drafts are never passed to the `onAssign` hook.304 if (isDraftProp && value === get(state.base, prop)) return305 }306 // Unchanged draft properties are ignored.307 else if (isDraftProp && is(value, get(state.base, prop))) {308 return309 }310 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.311 else if (isDraftable(value) && !Object.isFrozen(value)) {312 each(value, finalizeProperty)Merge branch 'master' into v4Michel Weststratebefore adoption741e941
line 313why, one step back313 this.maybeFreeze(value)run prettier with master config before mergingMichel Weststratebefore adoptionae80361
line 314why, one step back314 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 315why, one step back315run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 316–319why, one step back316 if (isDraftProp && this.onAssign && !isSetMember) {317 this.onAssign(state, prop, value)318 }319 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 320why, one step back320run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 321–322why, one step back321 each(root, finalizeProperty)322 return rootMerge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 323–328why, one step back323 }324 maybeFreeze(value, deep = false) {325 if (this.autoFreeze && !isDraft(value)) {326 if (deep) deepFreeze(value)327 else Object.freeze(value)328 }run prettier with master config before mergingMichel Weststratebefore adoptionae80361
line 329why, one step back329 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 330why, one step back330}feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 331why, one step back331nit: minor refactoringAlec Larsonbefore adoptiona2c4754
line 332why, one step back332function replace(parent, prop, value) {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 333–348why, one step back333 if (isMap(parent)) {334 parent.set(prop, value)335 } else if (isSet(parent)) {336 // In this case, the `prop` is actually a draft.337 parent.delete(prop)338 parent.add(value)339 } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {340 // Preserve non-enumerable properties.341 parent[prop] = value342 } else {343 Object.defineProperty(parent, prop, {344 value,345 writable: true,346 configurable: true347 })348 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 349why, one step back349}