Skip to content
Myr

immer.ts

This file

Path

src/immer.ts

273 lines · 7.6 KiB · TypeScript

Last changed by

Several refactoringsMichel Weststratebefore adoptionc7f8f5b

History of this file

Take it

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

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

basic map tests succeedingMichel Weststratebefore adoption735c402

line 3why, one step back
3

TS type improvementsMichel Weststratebefore adoptiondd1808e

line 4why, one step back
4import {applyPatches} from "./patches"

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Several refactoringsMichel Weststratebefore adoptionc7f8f5b

line 12why, one step back
12 NOTHING

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

lines 15–21why, one step back
15import {
16 ImmerState,17 IProduce,18 IProduceWithPatches,19 Objectish,20 PatchListener,21 Draft,

clean up create proxyMichel Weststratebefore adoptionc182c1e

lines 22–23why, one step back
22 Patch,
23 Drafted

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

line 24why, one step back
24} from "./types"

clean up create proxyMichel Weststratebefore adoptionc182c1e

line 25why, one step back
25import {proxyMap} from "./map"

TS type improvementsMichel Weststratebefore adoptiondd1808e

line 26why, one step back
26import {proxySet} from "./set"

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

line 27why, one step back
27import {processResult, maybeFreeze} from "./finalize"

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 28–42why, one step back
28
29function verifyMinified() {}3031const configDefaults = {32 useProxies:33 typeof Proxy !== "undefined" &&34 typeof Proxy.revocable !== "undefined" &&35 typeof Reflect !== "undefined",36 autoFreeze:37 typeof process !== "undefined"38 ? process.env.NODE_ENV !== "production"39 : verifyMinified.name === "verifyMinified",40 onAssign: null,41 onDelete: null,42 onCopy: null

TS type improvementsMichel Weststratebefore adoptiondd1808e

line 43why, one step back
43} as const

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 44–52why, one step back
44
45interface ProducersFns {46 produce: IProduce47 produceWithPatches: IProduceWithPatches48}4950export class Immer implements ProducersFns {51 useProxies: boolean = false52 autoFreeze: boolean = false

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 54–67why, one step back
54 onDelete?: (state: ImmerState, prop: string | number) => void
55 onCopy?: (state: ImmerState) => void5657 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 }) {

Dropped Object.assignMichel Weststratebefore adoption79a1d2c

line 68why, one step back
68 each(configDefaults, (key, value) => {

TS type improvementsMichel Weststratebefore adoptiondd1808e

lines 69–70why, one step back
69 // @ts-ignore
70 this[key] = config?.[key] ?? value

Dropped Object.assignMichel Weststratebefore adoption79a1d2c

line 71why, one step back
71 })

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 72–95why, one step back
72 this.setUseProxies(this.useProxies)
73 this.produce = this.produce.bind(this)74 this.produceWithPatches = this.produceWithPatches.bind(this)75 }7677 /**78 * The `produce` function takes a value and a "recipe function" (whose79 * return value often depends on the base state). The recipe function is80 * free to mutate its first argument however it wants. All mutations are81 * only ever applied to a __copy__ of the base state.82 *83 * Pass only a function to create a "curried producer" which relieves you84 * from passing the recipe function every time.85 *86 * Only plain objects and arrays are made mutable. All other objects are87 * considered uncopyable.88 *89 * Note: This function is __bound__ to its `Immer` instance.90 *91 * @param {any} base - the initial state92 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified93 * @param {Function} patchListener - optional function that will be called with all the patches produced here94 * @returns {any} a new state, or the initial state if nothing was modified95 */

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 97–102why, one step back
97 // curried invocation
98 if (typeof base === "function" && typeof recipe !== "function") {99 const defaultBase = recipe100 recipe = base101102 const self = this

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 109–125why, one step back
109 }
110 }111112 // prettier-ignore113 {114 if (typeof recipe !== "function") {115 throw new Error("The first or second argument to `produce` must be a function")116 }117 if (patchListener !== undefined && typeof patchListener !== "function") {118 throw new Error("The third argument to `produce` must be a function or undefined")119 }120 }121122 let result123124 // Only plain objects, arrays, and "immerable classes" are drafted.125 if (isDraftable(base)) {

map unification WIPMichel Weststratebefore adoption9bcefb6

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 128–140why, one step back
128 let hasError = true
129 try {130 result = recipe(proxy)131 hasError = false132 } finally {133 // finally instead of catch + rethrow better preserves original stack134 if (hasError) scope.revoke()135 else scope.leave()136 }137 if (typeof Promise !== "undefined" && result instanceof Promise) {138 return result.then(139 result => {140 scope.usePatches(patchListener)

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 142–149why, one step back
142 },
143 error => {144 scope.revoke()145 throw error146 }147 )148 }149 scope.usePatches(patchListener)

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 151–154why, one step back
151 } else {
152 result = recipe(base)153 if (result === NOTHING) return undefined154 if (result === undefined) result = base

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 156–159why, one step back
156 return result
157 }158 }159

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 164–167why, one step back
164 }
165 // non-curried form166 if (arg3)167 throw new Error("A patch listener cannot be passed to produceWithPatches")

TS type improvementsMichel Weststratebefore adoptiondd1808e

lines 168–169why, one step back
168 let patches: Patch[], inversePatches: Patch[]
169 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 170–172why, one step back
170 patches = p
171 inversePatches = ip172 })

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 174–175why, one step back
174 }
175

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

map unification WIPMichel Weststratebefore adoption9bcefb6

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

line 184why, one step back
184 return proxy

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 185–186why, one step back
185 }
186

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

lines 187–190why, one step back
187 finishDraft<D extends Draft<any>>(
188 draft: D,189 patchListener: PatchListener190 ): D extends Draft<infer T> ? T : never {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 191–199why, one step back
191 const state = draft && draft[DRAFT_STATE]
192 if (!state || !state.isManual) {193 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore194 }195 if (state.finalized) {196 throw new Error("The given draft is already finalized") // prettier-ignore197 }198 const {scope} = state199 scope.usePatches(patchListener)

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 201–224why, one step back
201 }
202203 /**204 * Pass true to automatically freeze all copies created by Immer.205 *206 * By default, auto-freezing is disabled in production.207 */208 setAutoFreeze(value: boolean) {209 this.autoFreeze = value210 }211212 /**213 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is214 * always faster than using ES5 proxies.215 *216 * By default, feature detection is used, so calling this is rarely necessary.217 */218 setUseProxies(value: boolean) {219 this.useProxies = value220 }221222 applyPatches(base: Objectish, patches: Patch[]) {223 // If a patch replaces the entire state, take that replacement as base224 // before applying patches

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 226–238why, one step back
226 for (i = patches.length - 1; i >= 0; i--) {
227 const patch = patches[i]228 if (patch.path.length === 0 && patch.op === "replace") {229 base = patch.value230 break231 }232 }233234 if (isDraft(base)) {235 // N.B: never hits if some patch a replacement, patches are never drafts236 return applyPatches(base, patches)237 }238 // Otherwise, produce a copy of the base state.

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 240–243why, one step back
240 applyPatches(draft, patches.slice(i + 1))
241 )242 }243

TS type improvementsMichel Weststratebefore adoptiondd1808e

lines 244–247why, one step back
244 createProxy<T extends Objectish>(
245 value: T,246 parent?: ImmerState247 ): Drafted<T, ImmerState> {

Several refactoringsMichel Weststratebefore adoptionc7f8f5b

lines 248–255why, one step back
248 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft
249 const draft: Drafted = isMap(value)250 ? proxyMap(value, parent)251 : isSet(value)252 ? proxySet(value, parent)253 : this.useProxies254 ? createProxy(value, parent)255 : createES5Proxy(value, parent)

clean up create proxyMichel Weststratebefore adoptionc182c1e

lines 256–259why, one step back
256
257 const scope = parent ? parent.scope : ImmerScope.current!258 scope.drafts.push(draft)259 return draft

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

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

TS type improvementsMichel Weststratebefore adoptiondd1808e

line 266why, one step back
266 markChanged(state: ImmerState) {

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

lines 267–271why, one step back
267 if (this.useProxies) {
268 markChanged(state)269 } else {270 markChangedES5(state)271 }

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 272–273why, one step back
272 }
273}