immer.ts
This file
Path
src/immer.ts
417 lines · 11.8 KiB · TypeScript
Last changed by
Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
History of this fileTake it
Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 1–417why, one step back1import * as legacyProxy from "./es5"2import * as modernProxy from "./proxy"3import {applyPatches, generatePatches} from "./patches"4import {5 assign,6 each,7 has,8 is,9 isDraft,10 isSet,11 get,12 isMap,13 isDraftable,14 isEnumerable,15 shallowCopy,16 DRAFT_STATE,17 NOTHING,18 freeze19} from "./common"20import {ImmerScope} from "./scope"21import {ImmerState, IProduce, IProduceWithPatches, Objectish, PatchListener, Draft, Patch} from "./types"2223function verifyMinified() {}2425const configDefaults = {26 useProxies:27 typeof Proxy !== "undefined" &&28 typeof Proxy.revocable !== "undefined" &&29 typeof Reflect !== "undefined",30 autoFreeze:31 typeof process !== "undefined"32 ? process.env.NODE_ENV !== "production"33 : verifyMinified.name === "verifyMinified",34 onAssign: null,35 onDelete: null,36 onCopy: null37}3839interface ProducersFns {40 produce: IProduce41 produceWithPatches: IProduceWithPatches42}4344export class Immer implements ProducersFns {45 useProxies: boolean = false46 autoFreeze: boolean = false47 onAssign?: (48 state: ImmerState,49 prop: string | number,50 value: unknown51 ) => void52 onDelete?: (state: ImmerState, prop: string | number) => void53 onCopy?: (state: ImmerState) => void54 createProxy!:<T>(value: T) => T;55 willFinalize!: (scope: ImmerScope, thing: any, isReplaced: boolean) => void;5657 constructor(config?: {58 useProxies?: boolean59 autoFreeze?: boolean60 onAssign?: (61 state: ImmerState,62 prop: string | number,63 value: unknown64 ) => void65 onDelete?: (state: ImmerState, prop: string | number) => void66 onCopy?: (state: ImmerState) => void67 }) {68 assign(this, configDefaults, config)69 this.setUseProxies(this.useProxies)70 this.produce = this.produce.bind(this)71 this.produceWithPatches = this.produceWithPatches.bind(this)72 }7374 /**75 * The `produce` function takes a value and a "recipe function" (whose76 * return value often depends on the base state). The recipe function is77 * free to mutate its first argument however it wants. All mutations are78 * only ever applied to a __copy__ of the base state.79 *80 * Pass only a function to create a "curried producer" which relieves you81 * from passing the recipe function every time.82 *83 * Only plain objects and arrays are made mutable. All other objects are84 * considered uncopyable.85 *86 * Note: This function is __bound__ to its `Immer` instance.87 *88 * @param {any} base - the initial state89 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified90 * @param {Function} patchListener - optional function that will be called with all the patches produced here91 * @returns {any} a new state, or the initial state if nothing was modified92 */93 produce(base, recipe?, patchListener?) {94 // curried invocation95 if (typeof base === "function" && typeof recipe !== "function") {96 const defaultBase = recipe97 recipe = base9899 const self = this100 return function curriedProduce(this: any, base = defaultBase, ...args) {101 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore102 }103 }104105 // prettier-ignore106 {107 if (typeof recipe !== "function") {108 throw new Error("The first or second argument to `produce` must be a function")109 }110 if (patchListener !== undefined && typeof patchListener !== "function") {111 throw new Error("The third argument to `produce` must be a function or undefined")112 }113 }114115 let result116117 // Only plain objects, arrays, and "immerable classes" are drafted.118 if (isDraftable(base)) {119 const scope = ImmerScope.enter()120 const proxy = this.createProxy(base)121 let hasError = true122 try {123 result = recipe(proxy)124 hasError = false125 } finally {126 // finally instead of catch + rethrow better preserves original stack127 if (hasError) scope.revoke()128 else scope.leave()129 }130 if (typeof Promise !== "undefined" && result instanceof Promise) {131 return result.then(132 result => {133 scope.usePatches(patchListener)134 return this.processResult(result, scope)135 },136 error => {137 scope.revoke()138 throw error139 }140 )141 }142 scope.usePatches(patchListener)143 return this.processResult(result, scope)144 } else {145 result = recipe(base)146 if (result === NOTHING) return undefined147 if (result === undefined) result = base148 this.maybeFreeze(result, true)149 return result150 }151 }152153 produceWithPatches(arg1, arg2?, arg3?): any {154 if (typeof arg1 === "function") {155 const self = this156 return (state, ...args) =>157 this.produceWithPatches(state, draft => arg1(draft, ...args))158 }159 // non-curried form160 if (arg3)161 throw new Error("A patch listener cannot be passed to produceWithPatches")162 let patches, inversePatches163 const nextState = this.produce(arg1, arg2, (p, ip) => {164 patches = p165 inversePatches = ip166 })167 return [nextState, patches, inversePatches]168 }169170 createDraft<T extends Objectish>(base: T): Draft<T> {171 if (!isDraftable(base)) {172 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore173 }174 const scope = ImmerScope.enter()175 const proxy = this.createProxy(base)176 proxy[DRAFT_STATE].isManual = true177 scope.leave()178 return proxy as any179 }180181 finishDraft<D extends Draft<any>>(draft: D, patchListener: PatchListener): D extends Draft<infer T> ? T : never {182 const state = draft && draft[DRAFT_STATE]183 if (!state || !state.isManual) {184 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore185 }186 if (state.finalized) {187 throw new Error("The given draft is already finalized") // prettier-ignore188 }189 const {scope} = state190 scope.usePatches(patchListener)191 return this.processResult(undefined, scope)192 }193194 /**195 * Pass true to automatically freeze all copies created by Immer.196 *197 * By default, auto-freezing is disabled in production.198 */199 setAutoFreeze(value: boolean) {200 this.autoFreeze = value201 }202203 /**204 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is205 * always faster than using ES5 proxies.206 *207 * By default, feature detection is used, so calling this is rarely necessary.208 */209 setUseProxies(value: boolean) {210 this.useProxies = value211 assign(this, value ? modernProxy : legacyProxy)212 }213214 applyPatches(base: Objectish, patches: Patch[]) {215 // If a patch replaces the entire state, take that replacement as base216 // before applying patches217 let i218 for (i = patches.length - 1; i >= 0; i--) {219 const patch = patches[i]220 if (patch.path.length === 0 && patch.op === "replace") {221 base = patch.value222 break223 }224 }225226 if (isDraft(base)) {227 // N.B: never hits if some patch a replacement, patches are never drafts228 return applyPatches(base, patches)229 }230 // Otherwise, produce a copy of the base state.231 return this.produce(base, draft =>232 applyPatches(draft, patches.slice(i + 1))233 )234 }235236 /** @internal */237 processResult(result: any, scope: ImmerScope) {238 const baseDraft = scope.drafts![0]239 const isReplaced = result !== undefined && result !== baseDraft240 this.willFinalize(scope, result, isReplaced)241 if (isReplaced) {242 if (baseDraft[DRAFT_STATE].modified) {243 scope.revoke()244 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore245 }246 if (isDraftable(result)) {247 // Finalize the result in case it contains (or is) a subset of the draft.248 result = this.finalize(result, null, scope)249 this.maybeFreeze(result)250 }251 if (scope.patches) {252 scope.patches.push({253 op: "replace",254 path: [],255 value: result256 })257 scope.inversePatches!.push({258 op: "replace",259 path: [],260 value: baseDraft[DRAFT_STATE].base261 })262 }263 } else {264 // Finalize the base draft.265 result = this.finalize(baseDraft, [], scope)266 }267 scope.revoke()268 if (scope.patches) {269 scope.patchListener!(scope.patches, scope.inversePatches!)270 }271 return result !== NOTHING ? result : undefined272 }273274 /**275 * @internal276 * Finalize a draft, returning either the unmodified base state or a modified277 * copy of the base state.278 */279 finalize(draft: any, path: string[] | null, scope: ImmerScope) {280 const state = draft[DRAFT_STATE]281 if (!state) {282 if (Object.isFrozen(draft)) return draft283 return this.finalizeTree(draft, null, scope)284 }285 // Never finalize drafts owned by another scope.286 if (state.scope !== scope) {287 return draft288 }289 if (!state.modified) {290 this.maybeFreeze(state.base, true)291 return state.base292 }293 if (!state.finalized) {294 state.finalized = true295 this.finalizeTree(state.draft, path, scope)296297 // We cannot really delete anything inside of a Set. We can only replace the whole Set.298 if (this.onDelete && !isSet(state.base)) {299 // The `assigned` object is unreliable with ES5 drafts.300 if (this.useProxies) {301 const {assigned} = state302 each(assigned, (prop, exists) => {303 if (!exists) this.onDelete?.(state, prop as any)304 })305 } else {306 // TODO: Figure it out for Maps and Sets if we need to support ES5307 const {base, copy} = state308 each(base, prop => {309 if (!has(copy, prop)) this.onDelete?.(state, prop as any)310 })311 }312 }313 if (this.onCopy) {314 this.onCopy(state)315 }316317 // At this point, all descendants of `state.copy` have been finalized,318 // so we can be sure that `scope.canAutoFreeze` is accurate.319 if (this.autoFreeze && scope.canAutoFreeze) {320 freeze(state.copy, false)321 }322323 if (path && scope.patches) {324 generatePatches(state, path, scope.patches, scope.inversePatches!)325 }326 }327 return state.copy328 }329330 /**331 * @internal332 * Finalize all drafts in the given state tree.333 */334 finalizeTree(root: any, rootPath: string[] | null, scope: ImmerScope) {335 const state = root[DRAFT_STATE]336 if (state) {337 if (!this.useProxies) {338 // Create the final copy, with added keys and without deleted keys.339 state.copy = shallowCopy(state.draft, true)340 }341 root = state.copy342 }343344 const needPatches = !!rootPath && !!scope.patches345 const finalizeProperty = (prop, value, parent) => {346 if (value === parent) {347 throw Error("Immer forbids circular references")348 }349350 // In the `finalizeTree` method, only the `root` object may be a draft.351 const isDraftProp = !!state && parent === root352 const isSetMember = isSet(parent)353354 if (isDraft(value)) {355 const path =356 isDraftProp &&357 needPatches &&358 !isSetMember && // Set objects are atomic since they have no keys.359 !has(state.assigned, prop) // Skip deep patches for assigned keys.360 ? rootPath!.concat(prop)361 : null362363 // Drafts owned by `scope` are finalized here.364 value = this.finalize(value, path, scope)365 replace(parent, prop, value)366367 // Drafts from another scope must prevent auto-freezing.368 if (isDraft(value)) {369 scope.canAutoFreeze = false370 }371372 // Unchanged drafts are never passed to the `onAssign` hook.373 if (isDraftProp && value === get(state.base, prop)) return374 }375 // Unchanged draft properties are ignored.376 else if (isDraftProp && is(value, get(state.base, prop))) {377 return378 }379 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.380 else if (isDraftable(value) && !Object.isFrozen(value)) {381 each(value, finalizeProperty)382 this.maybeFreeze(value)383 }384385 if (isDraftProp && this.onAssign && !isSetMember) {386 this.onAssign(state, prop, value)387 }388 }389390 each(root, finalizeProperty)391 return root392 }393 maybeFreeze(value, deep = false) {394 if (this.autoFreeze && !isDraft(value)) {395 freeze(value, deep)396 }397 }398}399400function replace(parent, prop, value) {401 if (isMap(parent)) {402 parent.set(prop, value)403 } else if (isSet(parent)) {404 // In this case, the `prop` is actually a draft.405 parent.delete(prop)406 parent.add(value)407 } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {408 // Preserve non-enumerable properties.409 parent[prop] = value410 } else {411 Object.defineProperty(parent, prop, {412 value,413 writable: true,414 configurable: true415 })416 }417}