Skip to content
Myr

immer.ts

This file

Path

src/immer.ts

427 lines · 12.3 KiB · TypeScript

Last changed by

fixed most testsMichel Weststratebefore adoption385c0a4

History of this file

Take it

1// TODO: destructure these, as the * as import makes it unclear which methods get installed on the Immer class2import * as legacyProxy from "./es5"3import * as modernProxy from "./proxy"45import {applyPatches, generatePatches} from "./patches"6import {7	assign,8	each,9	has,10	is,11	isDraft,12	isSet,13	get,14	isMap,15	isDraftable,16	isEnumerable,17	shallowCopy,18	DRAFT_STATE,19	NOTHING,20	freeze,21	latest22} from "./common"23import {ImmerScope} from "./scope"24import {ImmerState, IProduce, IProduceWithPatches, Objectish, PatchListener, Draft, Patch} from "./types"2526function verifyMinified() {}2728const configDefaults = {29	useProxies:30		typeof Proxy !== "undefined" &&31		typeof Proxy.revocable !== "undefined" &&32		typeof Reflect !== "undefined",33	autoFreeze:34		typeof process !== "undefined"35			? process.env.NODE_ENV !== "production"36			: verifyMinified.name === "verifyMinified",37	onAssign: null,38	onDelete: null,39	onCopy: null40}4142interface ProducersFns {43	produce: IProduce44	produceWithPatches: IProduceWithPatches45}4647export class Immer implements ProducersFns {48	useProxies: boolean = false49	autoFreeze: boolean = false50	onAssign?: (51		state: ImmerState,52		prop: string | number,53		value: unknown54	) => void55	onDelete?: (state: ImmerState, prop: string | number) => void56	onCopy?: (state: ImmerState) => void57	createProxy!:<T>(value: T, parent: any) => T;58	willFinalize!: (scope: ImmerScope, thing: any, isReplaced: boolean) => void;59	markChanged!:(state: any) => void; // TODO: immerState?6061	constructor(config?: {62		useProxies?: boolean63		autoFreeze?: boolean64		onAssign?: (65			state: ImmerState,66			prop: string | number,67			value: unknown68		) => void69		onDelete?: (state: ImmerState, prop: string | number) => void70		onCopy?: (state: ImmerState) => void71	}) {72		assign(this, configDefaults, config)73		this.setUseProxies(this.useProxies)74		this.produce = this.produce.bind(this)75		this.produceWithPatches = this.produceWithPatches.bind(this)76	}7778	/**79	 * The `produce` function takes a value and a "recipe function" (whose80	 * return value often depends on the base state). The recipe function is81	 * free to mutate its first argument however it wants. All mutations are82	 * only ever applied to a __copy__ of the base state.83	 *84	 * Pass only a function to create a "curried producer" which relieves you85	 * from passing the recipe function every time.86	 *87	 * Only plain objects and arrays are made mutable. All other objects are88	 * considered uncopyable.89	 *90	 * Note: This function is __bound__ to its `Immer` instance.91	 *92	 * @param {any} base - the initial state93	 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified94	 * @param {Function} patchListener - optional function that will be called with all the patches produced here95	 * @returns {any} a new state, or the initial state if nothing was modified96	 */97	produce(base, recipe?, patchListener?) {98		// curried invocation99		if (typeof base === "function" && typeof recipe !== "function") {100			const defaultBase = recipe101			recipe = base102103			const self = this104			return function curriedProduce(this: any, base = defaultBase, ...args) {105				return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore106			}107		}108109		// prettier-ignore110		{111			if (typeof recipe !== "function") {112				throw new Error("The first or second argument to `produce` must be a function")113			}114			if (patchListener !== undefined && typeof patchListener !== "function") {115				throw new Error("The third argument to `produce` must be a function or undefined")116			}117		}118119		let result120121		// Only plain objects, arrays, and "immerable classes" are drafted.122		if (isDraftable(base)) {123			const scope = ImmerScope.enter(this)124			const proxy = this.createProxy(base, undefined)125			let hasError = true126			try {127				result = recipe(proxy)128				hasError = false129			} finally {130				// finally instead of catch + rethrow better preserves original stack131				if (hasError) scope.revoke()132				else scope.leave()133			}134			if (typeof Promise !== "undefined" && result instanceof Promise) {135				return result.then(136					result => {137						scope.usePatches(patchListener)138						return this.processResult(result, scope)139					},140					error => {141						scope.revoke()142						throw error143					}144				)145			}146			scope.usePatches(patchListener)147			return this.processResult(result, scope)148		} else {149			result = recipe(base)150			if (result === NOTHING) return undefined151			if (result === undefined) result = base152			this.maybeFreeze(result, true)153			return result154		}155	}156157	produceWithPatches(arg1, arg2?, arg3?): any {158		if (typeof arg1 === "function") {159			const self = this160			return (state, ...args) =>161				this.produceWithPatches(state, draft => arg1(draft, ...args))162		}163		// non-curried form164		if (arg3)165			throw new Error("A patch listener cannot be passed to produceWithPatches")166		let patches, inversePatches167		const nextState = this.produce(arg1, arg2, (p, ip) => {168			patches = p169			inversePatches = ip170		})171		return [nextState, patches, inversePatches]172	}173174	createDraft<T extends Objectish>(base: T): Draft<T> {175		if (!isDraftable(base)) {176			throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore177		}178		const scope = ImmerScope.enter(this)179		const proxy = this.createProxy(base, undefined)180		proxy[DRAFT_STATE].isManual = true181		scope.leave()182		return proxy as any183	}184185	finishDraft<D extends Draft<any>>(draft: D, patchListener: PatchListener): D extends Draft<infer T> ? T : never {186		const state = draft && draft[DRAFT_STATE]187		if (!state || !state.isManual) {188			throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore189		}190		if (state.finalized) {191			throw new Error("The given draft is already finalized") // prettier-ignore192		}193		const {scope} = state194		scope.usePatches(patchListener)195		return this.processResult(undefined, scope)196	}197198	/**199	 * Pass true to automatically freeze all copies created by Immer.200	 *201	 * By default, auto-freezing is disabled in production.202	 */203	setAutoFreeze(value: boolean) {204		this.autoFreeze = value205	}206207	/**208	 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is209	 * always faster than using ES5 proxies.210	 *211	 * By default, feature detection is used, so calling this is rarely necessary.212	 */213	setUseProxies(value: boolean) {214		this.useProxies = value215		assign(this, value ? modernProxy : legacyProxy)216	}217218	applyPatches(base: Objectish, patches: Patch[]) {219		// If a patch replaces the entire state, take that replacement as base220		// before applying patches221		let i222		for (i = patches.length - 1; i >= 0; i--) {223			const patch = patches[i]224			if (patch.path.length === 0 && patch.op === "replace") {225				base = patch.value226				break227			}228		}229230		if (isDraft(base)) {231			// N.B: never hits if some patch a replacement, patches are never drafts232			return applyPatches(base, patches)233		}234		// Otherwise, produce a copy of the base state.235		return this.produce(base, draft =>236			applyPatches(draft, patches.slice(i + 1))237		)238	}239240	/** @internal */241	processResult(result: any, scope: ImmerScope) {242		const baseDraft = scope.drafts![0]243		const isReplaced = result !== undefined && result !== baseDraft244		this.willFinalize(scope, result, isReplaced)245		if (isReplaced) {246			if (baseDraft[DRAFT_STATE].modified) {247				scope.revoke()248				throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore249			}250			if (isDraftable(result)) {251				// Finalize the result in case it contains (or is) a subset of the draft.252				result = this.finalize(result, null, scope)253				this.maybeFreeze(result)254			}255			if (scope.patches) {256				scope.patches.push({257					op: "replace",258					path: [],259					value: result260				})261				scope.inversePatches!.push({262					op: "replace",263					path: [],264					value: baseDraft[DRAFT_STATE].base265				})266			}267		} else {268			// Finalize the base draft.269			result = this.finalize(baseDraft, [], scope)270		}271		scope.revoke()272		if (scope.patches) {273			scope.patchListener!(scope.patches, scope.inversePatches!)274		}275		return result !== NOTHING ? result : undefined276	}277278	/**279	 * @internal280	 * Finalize a draft, returning either the unmodified base state or a modified281	 * copy of the base state.282	 */283	finalize(draft: any, path: string[] | null, scope: ImmerScope) {284		const state = draft[DRAFT_STATE]285		if (!state) {286			if (Object.isFrozen(draft)) return draft287			return this.finalizeTree(draft, null, scope)288		}289		// Never finalize drafts owned by another scope.290		if (state.scope !== scope) {291			return draft292		}293		if (!state.modified) {294			this.maybeFreeze(state.base, true)295			return state.base296		}297		if (!state.finalized) {298			state.finalized = true299			this.finalizeTree(state.draft, path, scope)300301			// We cannot really delete anything inside of a Set. We can only replace the whole Set.302			if (this.onDelete && !isSet(state.base)) {303				// The `assigned` object is unreliable with ES5 drafts.304				if (this.useProxies) {305					const {assigned} = state306					each(assigned, (prop, exists) => {307						if (!exists) this.onDelete?.(state, prop as any)308					})309				} else {310					// TODO: Figure it out for Maps and Sets if we need to support ES5311					const {base, copy} = state312					each(base, prop => {313						if (!has(copy, prop)) this.onDelete?.(state, prop as any)314					})315				}316			}317			if (this.onCopy) {318				this.onCopy(state)319			}320321			// At this point, all descendants of `state.copy` have been finalized,322			// so we can be sure that `scope.canAutoFreeze` is accurate.323			if (this.autoFreeze && scope.canAutoFreeze) {324				freeze(state.copy, false)325			}326327			if (path && scope.patches) {328				generatePatches(state, path, scope.patches, scope.inversePatches!)329			}330		}331		return state.copy332	}333334	/**335	 * @internal336	 * Finalize all drafts in the given state tree.337	 */338	finalizeTree(root: any, rootPath: string[] | null, scope: ImmerScope) {339		const state = root[DRAFT_STATE]340		if (state) {341			// TODO: remove crap342			// if (state.modified && !state.copy) {343			// 	state.copy = shallowCopy(state.base, false)344			// }345			// else346			 if (!this.useProxies && !isMap(root) && !isSet(root)) {347				// Create the final copy, with added keys and without deleted keys.348				state.copy = shallowCopy(state.draft, true) // TODO: optimization, can we get rid of this and just use state.copy?349			}350351			root = state.copy352		}353354		const needPatches = !!rootPath && !!scope.patches355		const finalizeProperty = (prop, value, parent) => {356			if (value === parent) {357				throw Error("Immer forbids circular references")358			}359360			// In the `finalizeTree` method, only the `root` object may be a draft.361			const isDraftProp = !!state && parent === root362			const isSetMember = isSet(parent)363364			if (isDraft(value)) {365				const path =366					isDraftProp &&367					needPatches &&368					!isSetMember && // Set objects are atomic since they have no keys.369					!has(state.assigned, prop) // Skip deep patches for assigned keys.370						? rootPath!.concat(prop)371						: null372373				// Drafts owned by `scope` are finalized here.374				value = this.finalize(value, path, scope)375				replace(parent, prop, value)376377				// Drafts from another scope must prevent auto-freezing.378				if (isDraft(value)) {379					scope.canAutoFreeze = false380				}381382				// Unchanged drafts are never passed to the `onAssign` hook.383				if (isDraftProp && !isSetMember && value === get(state.base, prop)) return384			}385			// Unchanged draft properties are ignored.386			else if (isDraftProp && is(value, get(state.base, prop))) {387				return388			}389			// Search new objects for unfinalized drafts. Frozen objects should never contain drafts.390			else if (isDraftable(value) && !Object.isFrozen(value)) {391				each(value, finalizeProperty)392				this.maybeFreeze(value)393			}394395			if (isDraftProp && this.onAssign && !isSetMember) {396				this.onAssign(state, prop, value)397			}398		}399400		each(root, finalizeProperty)401		return root402	}403	maybeFreeze(value, deep = false) {404		if (this.autoFreeze && !isDraft(value)) {405			freeze(value, deep)406		}407	}408}409410function replace(parent, prop, value) {411	if (isMap(parent)) {412		parent.set(prop, value)413	} else if (isSet(parent)) {414		// In this case, the `prop` is actually a draft.415		parent.delete(prop)416		parent.add(value)417	} else if (Array.isArray(parent) || isEnumerable(parent, prop)) {418		// Preserve non-enumerable properties.419		parent[prop] = value420	} else {421		Object.defineProperty(parent, prop, {422			value,423			writable: true,424			configurable: true425		})426	}427}