Skip to content
Myr

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 file

Take it

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

line 1why, one step back
1import {

fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a

lines 2–7why, one step back
2 createES5Proxy,
3 willFinalizeES5,4 markChangedES5,5 IProduceWithPatches,6 IProduce,7 ImmerState,

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

line 8why, one step back
8 each,

fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a

line 9why, one step back
9 Drafted,

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

line 10why, one step back
10 isDraftable,

fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a

lines 11–12why, one step back
11 ImmerScope,
12 processResult,

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

line 13why, one step back
13 NOTHING,

fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a

lines 14–16why, one step back
14 maybeFreeze,
15 die,16 Patch,

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

line 17why, one step back
17 Objectish,

fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a

line 18why, one step back
18 DRAFT_STATE,

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

line 19why, one step back
19 Draft,

fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a

lines 20–26why, one step back
20 PatchListener,
21 isDraft,22 applyPatches,23 isMap,24 proxyMap,25 isSet,26 proxySet,

Small code cleanupMichel Weststratebefore adoption9217809

lines 27–28why, one step back
27 markChangedProxy,
28 createProxyProxy

fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a

line 29why, one step back
29} from "./internal"

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

line 30why, one step back
30

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

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

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 32–41why, one step back
32function 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 back
42 : /* istanbul ignore next */
43 verifyMinified.name === "verifyMinified",

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

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

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

line 47why, one step back
47} as const

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 48–56why, one step back
48
49interface ProducersFns {50 produce: IProduce51 produceWithPatches: IProduceWithPatches52}5354export class Immer implements ProducersFns {55 useProxies: boolean = false56 autoFreeze: boolean = false

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

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

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 58–71why, one step back
58 onDelete?: (state: ImmerState, prop: string | number) => void
59 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 back
72 each(configDefaults, (key, value) => {
73 // @ts-ignore74 this[key] = config?.[key] ?? value75 })

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 76–99why, one step back
76 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 back
100 produce(base: any, recipe?: any, patchListener?: any) {

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 101–106why, one step back
101 // curried invocation
102 if (typeof base === "function" && typeof recipe !== "function") {103 const defaultBase = recipe104 recipe = base105106 const self = this

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

lines 107–112why, one step back
107 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-ignore

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 113–129why, one step back
113 }
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 back
130 const scope = ImmerScope.enter(this)

Small code cleanupMichel Weststratebefore adoption9217809

line 131why, one step back
131 const proxy = createProxy(this, base, undefined)

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 132–144why, one step back
132 let hasError = true
133 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 back
145 return processResult(this, result, scope)

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 146–153why, one step back
146 },
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 back
154 return processResult(this, result, scope)

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

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

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

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

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

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

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

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

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

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

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

lines 166–167why, one step back
166 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 back
168 }
169 // non-curried form

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

lines 170–173why, one step back
170 /* 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 back
174 patches = p
175 inversePatches = ip176 })

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

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

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

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

fix: createDraft should return `Draft` instead of `Drafted`. Fixes #512Michel Weststratebefore adoption3f15d49

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

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 181–183why, one step back
181 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 back
184 const scope = ImmerScope.enter(this)

Small code cleanupMichel Weststratebefore adoption9217809

line 185why, one step back
185 const proxy = createProxy(this, base, undefined)

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

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

fix: createDraft should return `Draft` instead of `Drafted`. Fixes #512Michel Weststratebefore adoption3f15d49

line 188why, one step back
188 return proxy as any

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

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

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

lines 191–195why, one step back
191 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 back
196 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 back
204 return processResult(this, undefined, scope)

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 205–228why, one step back
205 }
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 patches

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

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

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

lines 230–242why, one step back
230 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 back
243 return this.produce(base, (draft: Drafted) =>

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

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

Small code cleanupMichel Weststratebefore adoption9217809

line 247why, one step back
247}

feat: convert Immer to TypeScriptMichel Weststratebefore adoption52c9914

line 248why, one step back
248

Small code cleanupMichel Weststratebefore adoption9217809

lines 249–261why, one step back
249export 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 back
262

Small code cleanupMichel Weststratebefore adoption9217809

lines 263–266why, one step back
263 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 back
267

Small code cleanupMichel Weststratebefore adoption9217809

lines 268–275why, one step back
268export 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 back
276

Small code cleanupMichel Weststratebefore adoption9217809

lines 277–281why, one step back
277export 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 back
282 }
283}