immer.ts
This file
Path
src/immer.ts
283 lines · 7.6 KiB · TypeScript
Last changed by
Small code cleanupMichel Weststratebefore adoption9217809
History of this fileTake it
feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 1why, one step back1import {fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a
lines 2–7why, one step back2 createES5Proxy,3 willFinalizeES5,4 markChangedES5,5 IProduceWithPatches,6 IProduce,7 ImmerState,feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 8why, one step back8 each,fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a
line 9why, one step back9 Drafted,feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 10why, one step back10 isDraftable,fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a
lines 11–12why, one step back11 ImmerScope,12 processResult,feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 13why, one step back13 NOTHING,fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a
lines 14–16why, one step back14 maybeFreeze,15 die,16 Patch,feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 17why, one step back17 Objectish,fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a
line 18why, one step back18 DRAFT_STATE,feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 19why, one step back19 Draft,fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a
lines 20–26why, one step back20 PatchListener,21 isDraft,22 applyPatches,23 isMap,24 proxyMap,25 isSet,26 proxySet,Small code cleanupMichel Weststratebefore adoption9217809
lines 27–28why, one step back27 markChangedProxy,28 createProxyProxyfix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a
line 29why, one step back29} from "./internal"feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 30why, one step back30feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 31why, one step back31/* istanbul ignore next */feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 32–41why, one step back32function verifyMinified() {}3334const configDefaults = {35 useProxies:36 typeof Proxy !== "undefined" &&37 typeof Proxy.revocable !== "undefined" &&38 typeof Reflect !== "undefined",39 autoFreeze:40 typeof process !== "undefined"41 ? process.env.NODE_ENV !== "production"feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 42–43why, one step back42 : /* istanbul ignore next */43 verifyMinified.name === "verifyMinified",feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 44–46why, one step back44 onAssign: null,45 onDelete: null,46 onCopy: nullfeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 47why, one step back47} as constfeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 48–56why, one step back4849interface ProducersFns {50 produce: IProduce51 produceWithPatches: IProduceWithPatches52}5354export class Immer implements ProducersFns {55 useProxies: boolean = false56 autoFreeze: boolean = falsefeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 57why, one step back57 onAssign?: (state: ImmerState, prop: string | number, value: unknown) => voidfeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 58–71why, one step back58 onDelete?: (state: ImmerState, prop: string | number) => void59 onCopy?: (state: ImmerState) => void6061 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 }) {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 72–75why, one step back72 each(configDefaults, (key, value) => {73 // @ts-ignore74 this[key] = config?.[key] ?? value75 })feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 76–99why, one step back76 this.setUseProxies(this.useProxies)77 this.produce = this.produce.bind(this)78 this.produceWithPatches = this.produceWithPatches.bind(this)79 }8081 /**82 * The `produce` function takes a value and a "recipe function" (whose83 * return value often depends on the base state). The recipe function is84 * free to mutate its first argument however it wants. All mutations are85 * only ever applied to a __copy__ of the base state.86 *87 * Pass only a function to create a "curried producer" which relieves you88 * from passing the recipe function every time.89 *90 * Only plain objects and arrays are made mutable. All other objects are91 * considered uncopyable.92 *93 * Note: This function is __bound__ to its `Immer` instance.94 *95 * @param {any} base - the initial state96 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified97 * @param {Function} patchListener - optional function that will be called with all the patches produced here98 * @returns {any} a new state, or the initial state if nothing was modified99 */feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 100why, one step back100 produce(base: any, recipe?: any, patchListener?: any) {feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 101–106why, one step back101 // curried invocation102 if (typeof base === "function" && typeof recipe !== "function") {103 const defaultBase = recipe104 recipe = base105106 const self = thisfeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 107–112why, one step back107 return function curriedProduce(108 this: any,109 base = defaultBase,110 ...args: any[]111 ) {112 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignorefeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 113–129why, one step back113 }114 }115116 // prettier-ignore117 {118 if (typeof recipe !== "function") {119 throw new Error("The first or second argument to `produce` must be a function")120 }121 if (patchListener !== undefined && typeof patchListener !== "function") {122 throw new Error("The third argument to `produce` must be a function or undefined")123 }124 }125126 let result127128 // Only plain objects, arrays, and "immerable classes" are drafted.129 if (isDraftable(base)) {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 130why, one step back130 const scope = ImmerScope.enter(this)Small code cleanupMichel Weststratebefore adoption9217809
line 131why, one step back131 const proxy = createProxy(this, base, undefined)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 132–144why, one step back132 let hasError = true133 try {134 result = recipe(proxy)135 hasError = false136 } finally {137 // finally instead of catch + rethrow better preserves original stack138 if (hasError) scope.revoke()139 else scope.leave()140 }141 if (typeof Promise !== "undefined" && result instanceof Promise) {142 return result.then(143 result => {144 scope.usePatches(patchListener)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 145why, one step back145 return processResult(this, result, scope)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 146–153why, one step back146 },147 error => {148 scope.revoke()149 throw error150 }151 )152 }153 scope.usePatches(patchListener)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 154why, one step back154 return processResult(this, result, scope)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 155–158why, one step back155 } else {156 result = recipe(base)157 if (result === NOTHING) return undefined158 if (result === undefined) result = basefeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 159why, one step back159 maybeFreeze(this, result, true)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 160–163why, one step back160 return result161 }162 }163feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 164why, one step back164 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 165why, one step back165 if (typeof arg1 === "function") {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 166–167why, one step back166 return (state: any, ...args: any[]) =>167 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 168–169why, one step back168 }169 // non-curried formfeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 170–173why, one step back170 /* istanbul ignore next */171 if (arg3) die()172 let patches: Patch[], inversePatches: Patch[]173 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 174–176why, one step back174 patches = p175 inversePatches = ip176 })feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 177why, one step back177 return [nextState, patches!, inversePatches!]feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 178–179why, one step back178 }179fix: createDraft should return `Draft` instead of `Drafted`. Fixes #512Michel Weststratebefore adoption3f15d49
line 180why, one step back180 createDraft<T extends Objectish>(base: T): Draft<T> {feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 181–183why, one step back181 if (!isDraftable(base)) {182 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore183 }feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 184why, one step back184 const scope = ImmerScope.enter(this)Small code cleanupMichel Weststratebefore adoption9217809
line 185why, one step back185 const proxy = createProxy(this, base, undefined)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 186–187why, one step back186 proxy[DRAFT_STATE].isManual = true187 scope.leave()fix: createDraft should return `Draft` instead of `Drafted`. Fixes #512Michel Weststratebefore adoption3f15d49
line 188why, one step back188 return proxy as anyfeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 189–190why, one step back189 }190feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 191–195why, one step back191 finishDraft<D extends Draft<any>>(192 draft: D,193 patchListener?: PatchListener194 ): D extends Draft<infer T> ? T : never {195 const state: ImmerState = draft && draft[DRAFT_STATE]feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 196–203why, one step back196 if (!state || !state.isManual) {197 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore198 }199 if (state.finalized) {200 throw new Error("The given draft is already finalized") // prettier-ignore201 }202 const {scope} = state203 scope.usePatches(patchListener)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 204why, one step back204 return processResult(this, undefined, scope)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 205–228why, one step back205 }206207 /**208 * Pass true to automatically freeze all copies created by Immer.209 *210 * By default, auto-freezing is disabled in production.211 */212 setAutoFreeze(value: boolean) {213 this.autoFreeze = value214 }215216 /**217 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is218 * always faster than using ES5 proxies.219 *220 * By default, feature detection is used, so calling this is rarely necessary.221 */222 setUseProxies(value: boolean) {223 this.useProxies = value224 }225226 applyPatches(base: Objectish, patches: Patch[]) {227 // If a patch replaces the entire state, take that replacement as base228 // before applying patchesfeat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 229why, one step back229 let i: numberfeat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 230–242why, one step back230 for (i = patches.length - 1; i >= 0; i--) {231 const patch = patches[i]232 if (patch.path.length === 0 && patch.op === "replace") {233 base = patch.value234 break235 }236 }237238 if (isDraft(base)) {239 // N.B: never hits if some patch a replacement, patches are never drafts240 return applyPatches(base, patches)241 }242 // Otherwise, produce a copy of the base state.feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 243why, one step back243 return this.produce(base, (draft: Drafted) =>feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 244–246why, one step back244 applyPatches(draft, patches.slice(i + 1))245 )246 }Small code cleanupMichel Weststratebefore adoption9217809
line 247why, one step back247}feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 248why, one step back248Small code cleanupMichel Weststratebefore adoption9217809
lines 249–261why, one step back249export function createProxy<T extends Objectish>(250 immer: Immer,251 value: T,252 parent?: ImmerState253): Drafted<T, ImmerState> {254 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft255 const draft: Drafted = isMap(value)256 ? proxyMap(value, parent)257 : isSet(value)258 ? proxySet(value, parent)259 : immer.useProxies260 ? createProxyProxy(value, parent)261 : createES5Proxy(value, parent)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 262why, one step back262Small code cleanupMichel Weststratebefore adoption9217809
lines 263–266why, one step back263 const scope = parent ? parent.scope : ImmerScope.current!264 scope.drafts.push(draft)265 return draft266}feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 267why, one step back267Small code cleanupMichel Weststratebefore adoption9217809
lines 268–275why, one step back268export function willFinalize(269 immer: Immer,270 scope: ImmerScope,271 thing: any,272 isReplaced: boolean273) {274 if (!immer.useProxies) willFinalizeES5(scope, thing, isReplaced)275}feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
line 276why, one step back276Small code cleanupMichel Weststratebefore adoption9217809
lines 277–281why, one step back277export function markChanged(immer: Immer, state: ImmerState) {278 if (immer.useProxies) {279 markChangedProxy(state)280 } else {281 markChangedES5(state)feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914
lines 282–283why, one step back282 }283}