Skip to content
Myr

immer.ts

This file

Path

src/immer.ts

276 lines · 7.7 KiB · TypeScript

Last changed by

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

History of this file

Take it

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 1–4why, one step back
1import {createES5Proxy, willFinalizeES5, markChangedES5} from "./es5"
2import {createProxy, markChanged} from "./proxy"34import {applyPatches} from "./patches"

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 5–12why, one step back
5import {
6 each,7 isDraft,8 isSet,9 isMap,10 isDraftable,11 DRAFT_STATE,12 NOTHING,

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 13why, one step back
13 die

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 14–15why, one step back
14} from "./common"
15import {ImmerScope} from "./scope"

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 16–28why, one step back
16import {
17 ImmerState,18 IProduce,19 IProduceWithPatches,20 Objectish,21 PatchListener,22 Draft,23 Patch,24 Drafted25} from "./types"26import {proxyMap} from "./map"27import {proxySet} from "./set"28import {processResult, maybeFreeze} from "./finalize"

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

line 29why, one step back
29

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 30why, one step back
30/* istanbul ignore next */

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 31–40why, one step back
31function verifyMinified() {}
3233const configDefaults = {34 useProxies:35 typeof Proxy !== "undefined" &&36 typeof Proxy.revocable !== "undefined" &&37 typeof Reflect !== "undefined",38 autoFreeze:39 typeof process !== "undefined"40 ? process.env.NODE_ENV !== "production"

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 41–42why, one step back
41 : /* istanbul ignore next */
42 verifyMinified.name === "verifyMinified",

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 43–45why, one step back
43 onAssign: null,
44 onDelete: null,45 onCopy: null

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 46why, one step back
46} as const

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 47–55why, one step back
47
48interface ProducersFns {49 produce: IProduce50 produceWithPatches: IProduceWithPatches51}5253export class Immer implements ProducersFns {54 useProxies: boolean = false55 autoFreeze: boolean = false

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 56why, one step back
56 onAssign?: (state: ImmerState, prop: string | number, value: unknown) => void

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 57–70why, one step back
57 onDelete?: (state: ImmerState, prop: string | number) => void
58 onCopy?: (state: ImmerState) => void5960 constructor(config?: {61 useProxies?: boolean62 autoFreeze?: boolean63 onAssign?: (64 state: ImmerState,65 prop: string | number,66 value: unknown67 ) => void68 onDelete?: (state: ImmerState, prop: string | number) => void69 onCopy?: (state: ImmerState) => void70 }) {

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 71–74why, one step back
71 each(configDefaults, (key, value) => {
72 // @ts-ignore73 this[key] = config?.[key] ?? value74 })

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 75–98why, one step back
75 this.setUseProxies(this.useProxies)
76 this.produce = this.produce.bind(this)77 this.produceWithPatches = this.produceWithPatches.bind(this)78 }7980 /**81 * The `produce` function takes a value and a "recipe function" (whose82 * return value often depends on the base state). The recipe function is83 * free to mutate its first argument however it wants. All mutations are84 * only ever applied to a __copy__ of the base state.85 *86 * Pass only a function to create a "curried producer" which relieves you87 * from passing the recipe function every time.88 *89 * Only plain objects and arrays are made mutable. All other objects are90 * considered uncopyable.91 *92 * Note: This function is __bound__ to its `Immer` instance.93 *94 * @param {any} base - the initial state95 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified96 * @param {Function} patchListener - optional function that will be called with all the patches produced here97 * @returns {any} a new state, or the initial state if nothing was modified98 */

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 99why, one step back
99 produce(base: any, recipe?: any, patchListener?: any) {

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 100–105why, one step back
100 // curried invocation
101 if (typeof base === "function" && typeof recipe !== "function") {102 const defaultBase = recipe103 recipe = base104105 const self = this

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 106–111why, one step back
106 return function curriedProduce(
107 this: any,108 base = defaultBase,109 ...args: any[]110 ) {111 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 112–128why, one step back
112 }
113 }114115 // prettier-ignore116 {117 if (typeof recipe !== "function") {118 throw new Error("The first or second argument to `produce` must be a function")119 }120 if (patchListener !== undefined && typeof patchListener !== "function") {121 throw new Error("The third argument to `produce` must be a function or undefined")122 }123 }124125 let result126127 // Only plain objects, arrays, and "immerable classes" are drafted.128 if (isDraftable(base)) {

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 129–130why, one step back
129 const scope = ImmerScope.enter(this)
130 const proxy = this.createProxy(base, undefined)

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 131–143why, one step back
131 let hasError = true
132 try {133 result = recipe(proxy)134 hasError = false135 } finally {136 // finally instead of catch + rethrow better preserves original stack137 if (hasError) scope.revoke()138 else scope.leave()139 }140 if (typeof Promise !== "undefined" && result instanceof Promise) {141 return result.then(142 result => {143 scope.usePatches(patchListener)

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 144why, one step back
144 return processResult(this, result, scope)

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 145–152why, one step back
145 },
146 error => {147 scope.revoke()148 throw error149 }150 )151 }152 scope.usePatches(patchListener)

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 153why, one step back
153 return processResult(this, result, scope)

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 154–157why, one step back
154 } else {
155 result = recipe(base)156 if (result === NOTHING) return undefined157 if (result === undefined) result = base

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 158why, one step back
158 maybeFreeze(this, result, true)

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 159–162why, one step back
159 return result
160 }161 }162

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 163why, one step back
163 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

line 164why, one step back
164 if (typeof arg1 === "function") {

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 165–166why, one step back
165 return (state: any, ...args: any[]) =>
166 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 167–168why, one step back
167 }
168 // non-curried form

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 169–172why, one step back
169 /* istanbul ignore next */
170 if (arg3) die()171 let patches: Patch[], inversePatches: Patch[]172 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 173–175why, one step back
173 patches = p
174 inversePatches = ip175 })

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 176why, one step back
176 return [nextState, patches!, inversePatches!]

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 177–178why, one step back
177 }
178

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 179why, one step back
179 createDraft<T extends Objectish>(base: T): Drafted<T> {

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 180–182why, one step back
180 if (!isDraftable(base)) {
181 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore182 }

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 183–184why, one step back
183 const scope = ImmerScope.enter(this)
184 const proxy = this.createProxy(base, undefined)

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 185–186why, one step back
185 proxy[DRAFT_STATE].isManual = true
186 scope.leave()

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 187why, one step back
187 return proxy

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 188–189why, one step back
188 }
189

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 190–194why, one step back
190 finishDraft<D extends Draft<any>>(
191 draft: D,192 patchListener?: PatchListener193 ): D extends Draft<infer T> ? T : never {194 const state: ImmerState = draft && draft[DRAFT_STATE]

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 195–202why, one step back
195 if (!state || !state.isManual) {
196 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore197 }198 if (state.finalized) {199 throw new Error("The given draft is already finalized") // prettier-ignore200 }201 const {scope} = state202 scope.usePatches(patchListener)

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 203why, one step back
203 return processResult(this, undefined, scope)

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 204–227why, one step back
204 }
205206 /**207 * Pass true to automatically freeze all copies created by Immer.208 *209 * By default, auto-freezing is disabled in production.210 */211 setAutoFreeze(value: boolean) {212 this.autoFreeze = value213 }214215 /**216 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is217 * always faster than using ES5 proxies.218 *219 * By default, feature detection is used, so calling this is rarely necessary.220 */221 setUseProxies(value: boolean) {222 this.useProxies = value223 }224225 applyPatches(base: Objectish, patches: Patch[]) {226 // If a patch replaces the entire state, take that replacement as base227 // before applying patches

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 228why, one step back
228 let i: number

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 229–241why, one step back
229 for (i = patches.length - 1; i >= 0; i--) {
230 const patch = patches[i]231 if (patch.path.length === 0 && patch.op === "replace") {232 base = patch.value233 break234 }235 }236237 if (isDraft(base)) {238 // N.B: never hits if some patch a replacement, patches are never drafts239 return applyPatches(base, patches)240 }241 // Otherwise, produce a copy of the base state.

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 242why, one step back
242 return this.produce(base, (draft: Drafted) =>

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 243–246why, one step back
243 applyPatches(draft, patches.slice(i + 1))
244 )245 }246

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 247–258why, one step back
247 createProxy<T extends Objectish>(
248 value: T,249 parent?: ImmerState250 ): Drafted<T, ImmerState> {251 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft252 const draft: Drafted = isMap(value)253 ? proxyMap(value, parent)254 : isSet(value)255 ? proxySet(value, parent)256 : this.useProxies257 ? createProxy(value, parent)258 : createES5Proxy(value, parent)

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

line 259why, one step back
259

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 260–262why, one step back
260 const scope = parent ? parent.scope : ImmerScope.current!
261 scope.drafts.push(draft)262 return draft

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 263–264why, one step back
263 }
264

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 265–266why, one step back
265 willFinalize(scope: ImmerScope, thing: any, isReplaced: boolean) {
266 if (!this.useProxies) willFinalizeES5(scope, thing, isReplaced)

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 267–268why, one step back
267 }
268

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 269–274why, one step back
269 markChanged(state: ImmerState) {
270 if (this.useProxies) {271 markChanged(state)272 } else {273 markChangedES5(state)274 }

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 275–276why, one step back
275 }
276}