Skip to content
Myr

immer.ts

This file

Path

src/immer.ts

279 lines · 7.8 KiB · TypeScript

Last changed by

Processed bunch of todosMichel Weststratebefore adoption00425e1

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–12why, one step back
5import {
6 each,7 isDraft,8 isSet,9 isMap,10 isDraftable,11 DRAFT_STATE,12 NOTHING,

clean up create proxyMichel Weststratebefore adoptionc182c1e

line 13why, one step back
13 isPlainObject,

TS type improvementsMichel Weststratebefore adoptiondd1808e

lines 14–15why, one step back
14 DRAFTABLE,
15 die

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

lines 18–24why, one step back
18import {
19 ImmerState,20 IProduce,21 IProduceWithPatches,22 Objectish,23 PatchListener,24 Draft,

clean up create proxyMichel Weststratebefore adoptionc182c1e

lines 25–26why, one step back
25 Patch,
26 Drafted

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

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

clean up create proxyMichel Weststratebefore adoptionc182c1e

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

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 31–45why, one step back
31
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"42 : verifyMinified.name === "verifyMinified",43 onAssign: null,44 onDelete: null,45 onCopy: null

TS type improvementsMichel Weststratebefore adoptiondd1808e

line 46why, one step back
46} as const

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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 }) {

Dropped Object.assignMichel Weststratebefore adoption79a1d2c

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

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Dropped Object.assignMichel Weststratebefore adoption79a1d2c

line 74why, one step back
74 })

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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 */

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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)) {

map unification WIPMichel Weststratebefore adoption9bcefb6

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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)

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 164–165why, one step back
164 if (typeof arg1 === "function") {
165 const self = this

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 168–171why, one step back
168 }
169 // non-curried form170 if (arg3)171 throw new Error("A patch listener cannot be passed to produceWithPatches")

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 174–176why, one step back
174 patches = p
175 inversePatches = ip176 })

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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 }

map unification WIPMichel Weststratebefore adoption9bcefb6

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

line 188why, one step back
188 return proxy

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

lines 191–194why, one step back
191 finishDraft<D extends Draft<any>>(
192 draft: D,193 patchListener: PatchListener194 ): D extends Draft<infer T> ? T : never {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 195–203why, one step back
195 const state = draft && draft[DRAFT_STATE]
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)

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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.

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

TS type improvementsMichel Weststratebefore adoptiondd1808e

lines 248–251why, one step back
248 createProxy<T extends Objectish>(
249 value: T,250 parent?: ImmerState251 ): Drafted<T, ImmerState> {

clean up create proxyMichel Weststratebefore adoptionc182c1e

line 252why, one step back
252 let draft: Drafted

TS type improvementsMichel Weststratebefore adoptiondd1808e

lines 253–257why, one step back
253 // TODO: use switch + type discovery>
254 if (isMap(value)) draft = proxyMap(value, parent)255 else if (isSet(value)) draft = proxySet(value, parent)256 else {257 // createProxy should be guarded by isDraftable, so we know we can safely draft

clean up create proxyMichel Weststratebefore adoptionc182c1e

lines 258–260why, one step back
258 draft = this.useProxies
259 ? createProxy(value, parent)260 : createES5Proxy(value, parent)

TS type improvementsMichel Weststratebefore adoptiondd1808e

line 261why, one step back
261 }

clean up create proxyMichel Weststratebefore adoptionc182c1e

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

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

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

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

lines 273–277why, one step back
273 if (this.useProxies) {
274 markChanged(state)275 } else {276 markChangedES5(state)277 }

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 278–279why, one step back
278 }
279}