immer.ts
This file
Path
src/immer.ts
473 lines · 13.0 KiB · TypeScript
Last changed by
Dropped Object.assignMichel Weststratebefore adoption79a1d2c
History of this fileTake it
Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 1–2why, one step back1import {createES5Proxy, willFinalizeES5, markChangedES5} from "./es5"2import {createProxy, markChanged} from "./proxy"basic map tests succeedingMichel Weststratebefore adoption735c402
line 3why, one step back3Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 4–17why, one step back4import {applyPatches, generatePatches} from "./patches"5import {6 each,7 has,8 is,9 isDraft,10 isSet,11 get,12 isMap,13 isDraftable,14 isEnumerable,15 shallowCopy,16 DRAFT_STATE,17 NOTHING,basic map tests succeedingMichel Weststratebefore adoption735c402
line 18why, one step back18 freeze,clean up create proxyMichel Weststratebefore adoptionc182c1e
lines 19–20why, one step back19 isPlainObject,20 DRAFTABLEMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 21–22why, one step back21} from "./common"22import {ImmerScope} from "./scope"Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 23–29why, one step back23import {24 ImmerState,25 IProduce,26 IProduceWithPatches,27 Objectish,28 PatchListener,29 Draft,clean up create proxyMichel Weststratebefore adoptionc182c1e
lines 30–31why, one step back30 Patch,31 DraftedStop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
line 32why, one step back32} from "./types"clean up create proxyMichel Weststratebefore adoptionc182c1e
lines 33–34why, one step back33import {proxyMap} from "./map"34import {proxySet} from "./set"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 35–59why, one step back3536function verifyMinified() {}3738const configDefaults = {39 useProxies:40 typeof Proxy !== "undefined" &&41 typeof Proxy.revocable !== "undefined" &&42 typeof Reflect !== "undefined",43 autoFreeze:44 typeof process !== "undefined"45 ? process.env.NODE_ENV !== "production"46 : verifyMinified.name === "verifyMinified",47 onAssign: null,48 onDelete: null,49 onCopy: null50}5152interface ProducersFns {53 produce: IProduce54 produceWithPatches: IProduceWithPatches55}5657export class Immer implements ProducersFns {58 useProxies: boolean = false59 autoFreeze: boolean = falseStop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
line 60why, one step back60 onAssign?: (state: ImmerState, prop: string | number, value: unknown) => voidMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 61–74why, one step back61 onDelete?: (state: ImmerState, prop: string | number) => void62 onCopy?: (state: ImmerState) => void6364 constructor(config?: {65 useProxies?: boolean66 autoFreeze?: boolean67 onAssign?: (68 state: ImmerState,69 prop: string | number,70 value: unknown71 ) => void72 onDelete?: (state: ImmerState, prop: string | number) => void73 onCopy?: (state: ImmerState) => void74 }) {Dropped Object.assignMichel Weststratebefore adoption79a1d2c
lines 75–81why, one step back75 each(configDefaults, (key, value) => {76 this[key] = value77 })78 config &&79 each(config, (key, value) => {80 this[key] = value81 })Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 82–131why, one step back82 this.setUseProxies(this.useProxies)83 this.produce = this.produce.bind(this)84 this.produceWithPatches = this.produceWithPatches.bind(this)85 }8687 /**88 * The `produce` function takes a value and a "recipe function" (whose89 * return value often depends on the base state). The recipe function is90 * free to mutate its first argument however it wants. All mutations are91 * only ever applied to a __copy__ of the base state.92 *93 * Pass only a function to create a "curried producer" which relieves you94 * from passing the recipe function every time.95 *96 * Only plain objects and arrays are made mutable. All other objects are97 * considered uncopyable.98 *99 * Note: This function is __bound__ to its `Immer` instance.100 *101 * @param {any} base - the initial state102 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified103 * @param {Function} patchListener - optional function that will be called with all the patches produced here104 * @returns {any} a new state, or the initial state if nothing was modified105 */106 produce(base, recipe?, patchListener?) {107 // curried invocation108 if (typeof base === "function" && typeof recipe !== "function") {109 const defaultBase = recipe110 recipe = base111112 const self = this113 return function curriedProduce(this: any, base = defaultBase, ...args) {114 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore115 }116 }117118 // prettier-ignore119 {120 if (typeof recipe !== "function") {121 throw new Error("The first or second argument to `produce` must be a function")122 }123 if (patchListener !== undefined && typeof patchListener !== "function") {124 throw new Error("The third argument to `produce` must be a function or undefined")125 }126 }127128 let result129130 // Only plain objects, arrays, and "immerable classes" are drafted.131 if (isDraftable(base)) {map unification WIPMichel Weststratebefore adoption9bcefb6
lines 132–133why, one step back132 const scope = ImmerScope.enter(this)133 const proxy = this.createProxy(base, undefined)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 134–186why, one step back134 let hasError = true135 try {136 result = recipe(proxy)137 hasError = false138 } finally {139 // finally instead of catch + rethrow better preserves original stack140 if (hasError) scope.revoke()141 else scope.leave()142 }143 if (typeof Promise !== "undefined" && result instanceof Promise) {144 return result.then(145 result => {146 scope.usePatches(patchListener)147 return this.processResult(result, scope)148 },149 error => {150 scope.revoke()151 throw error152 }153 )154 }155 scope.usePatches(patchListener)156 return this.processResult(result, scope)157 } else {158 result = recipe(base)159 if (result === NOTHING) return undefined160 if (result === undefined) result = base161 this.maybeFreeze(result, true)162 return result163 }164 }165166 produceWithPatches(arg1, arg2?, arg3?): any {167 if (typeof arg1 === "function") {168 const self = this169 return (state, ...args) =>170 this.produceWithPatches(state, draft => arg1(draft, ...args))171 }172 // non-curried form173 if (arg3)174 throw new Error("A patch listener cannot be passed to produceWithPatches")175 let patches, inversePatches176 const nextState = this.produce(arg1, arg2, (p, ip) => {177 patches = p178 inversePatches = ip179 })180 return [nextState, patches, inversePatches]181 }182183 createDraft<T extends Objectish>(base: T): Draft<T> {184 if (!isDraftable(base)) {185 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore186 }map unification WIPMichel Weststratebefore adoption9bcefb6
lines 187–188why, one step back187 const scope = ImmerScope.enter(this)188 const proxy = this.createProxy(base, undefined)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 189–193why, one step back189 proxy[DRAFT_STATE].isManual = true190 scope.leave()191 return proxy as any192 }193Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 194–197why, one step back194 finishDraft<D extends Draft<any>>(195 draft: D,196 patchListener: PatchListener197 ): D extends Draft<infer T> ? T : never {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 198–288why, one step back198 const state = draft && draft[DRAFT_STATE]199 if (!state || !state.isManual) {200 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore201 }202 if (state.finalized) {203 throw new Error("The given draft is already finalized") // prettier-ignore204 }205 const {scope} = state206 scope.usePatches(patchListener)207 return this.processResult(undefined, scope)208 }209210 /**211 * Pass true to automatically freeze all copies created by Immer.212 *213 * By default, auto-freezing is disabled in production.214 */215 setAutoFreeze(value: boolean) {216 this.autoFreeze = value217 }218219 /**220 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is221 * always faster than using ES5 proxies.222 *223 * By default, feature detection is used, so calling this is rarely necessary.224 */225 setUseProxies(value: boolean) {226 this.useProxies = value227 }228229 applyPatches(base: Objectish, patches: Patch[]) {230 // If a patch replaces the entire state, take that replacement as base231 // before applying patches232 let i233 for (i = patches.length - 1; i >= 0; i--) {234 const patch = patches[i]235 if (patch.path.length === 0 && patch.op === "replace") {236 base = patch.value237 break238 }239 }240241 if (isDraft(base)) {242 // N.B: never hits if some patch a replacement, patches are never drafts243 return applyPatches(base, patches)244 }245 // Otherwise, produce a copy of the base state.246 return this.produce(base, draft =>247 applyPatches(draft, patches.slice(i + 1))248 )249 }250251 /** @internal */252 processResult(result: any, scope: ImmerScope) {253 const baseDraft = scope.drafts![0]254 const isReplaced = result !== undefined && result !== baseDraft255 this.willFinalize(scope, result, isReplaced)256 if (isReplaced) {257 if (baseDraft[DRAFT_STATE].modified) {258 scope.revoke()259 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore260 }261 if (isDraftable(result)) {262 // Finalize the result in case it contains (or is) a subset of the draft.263 result = this.finalize(result, null, scope)264 this.maybeFreeze(result)265 }266 if (scope.patches) {267 scope.patches.push({268 op: "replace",269 path: [],270 value: result271 })272 scope.inversePatches!.push({273 op: "replace",274 path: [],275 value: baseDraft[DRAFT_STATE].base276 })277 }278 } else {279 // Finalize the base draft.280 result = this.finalize(baseDraft, [], scope)281 }282 scope.revoke()283 if (scope.patches) {284 scope.patchListener!(scope.patches, scope.inversePatches!)285 }286 return result !== NOTHING ? result : undefined287 }288clean up create proxyMichel Weststratebefore adoptionc182c1e
lines 289–309why, one step back289 createProxy<T>(value: any, parent?: ImmerState) {290 if (!value || typeof value !== "object") return value291292 let draft: Drafted293294 if (295 isPlainObject(value) ||296 Array.isArray(value) ||297 value[DRAFTABLE] ||298 value?.constructor?.[DRAFTABLE]299 ) {300 draft = this.useProxies301 ? createProxy(value, parent)302 : createES5Proxy(value, parent)303 } else if (isMap(value)) draft = proxyMap(value, parent)304 else if (isSet(value)) draft = proxySet(value, parent)305 else return value306307 const scope = parent ? parent.scope : ImmerScope.current!308 scope.drafts.push(draft)309 return draftStop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 310–323why, one step back310 }311312 willFinalize(scope: ImmerScope, thing: any, isReplaced: boolean) {313 if (!this.useProxies) willFinalizeES5(scope, thing, isReplaced)314 }315316 markChanged(state: any) {317 if (this.useProxies) {318 markChanged(state)319 } else {320 markChangedES5(state)321 }322 }323Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 324–386why, one step back324 /**325 * @internal326 * Finalize a draft, returning either the unmodified base state or a modified327 * copy of the base state.328 */329 finalize(draft: any, path: string[] | null, scope: ImmerScope) {330 const state = draft[DRAFT_STATE]331 if (!state) {332 if (Object.isFrozen(draft)) return draft333 return this.finalizeTree(draft, null, scope)334 }335 // Never finalize drafts owned by another scope.336 if (state.scope !== scope) {337 return draft338 }339 if (!state.modified) {340 this.maybeFreeze(state.base, true)341 return state.base342 }343 if (!state.finalized) {344 state.finalized = true345 this.finalizeTree(state.draft, path, scope)346347 // We cannot really delete anything inside of a Set. We can only replace the whole Set.348 if (this.onDelete && !isSet(state.base)) {349 // The `assigned` object is unreliable with ES5 drafts.350 if (this.useProxies) {351 const {assigned} = state352 each(assigned, (prop, exists) => {353 if (!exists) this.onDelete?.(state, prop as any)354 })355 } else {356 // TODO: Figure it out for Maps and Sets if we need to support ES5357 const {base, copy} = state358 each(base, prop => {359 if (!has(copy, prop)) this.onDelete?.(state, prop as any)360 })361 }362 }363 if (this.onCopy) {364 this.onCopy(state)365 }366367 // At this point, all descendants of `state.copy` have been finalized,368 // so we can be sure that `scope.canAutoFreeze` is accurate.369 if (this.autoFreeze && scope.canAutoFreeze) {370 freeze(state.copy, false)371 }372373 if (path && scope.patches) {374 generatePatches(state, path, scope.patches, scope.inversePatches!)375 }376 }377 return state.copy378 }379380 /**381 * @internal382 * Finalize all drafts in the given state tree.383 */384 finalizeTree(root: any, rootPath: string[] | null, scope: ImmerScope) {385 const state = root[DRAFT_STATE]386 if (state) {basic map tests succeedingMichel Weststratebefore adoption735c402
lines 387–391why, one step back387 // TODO: remove crap388 // if (state.modified && !state.copy) {389 // state.copy = shallowCopy(state.base, false)390 // }391 // elseStop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
line 392why, one step back392 if (!this.useProxies && !isMap(root) && !isSet(root)) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 393why, one step back393 // Create the final copy, with added keys and without deleted keys.basic map tests succeedingMichel Weststratebefore adoption735c402
line 394why, one step back394 state.copy = shallowCopy(state.draft, true) // TODO: optimization, can we get rid of this and just use state.copy?Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 395why, one step back395 }fixed most testsMichel Weststratebefore adoption385c0a4
line 396why, one step back396Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 397–428why, one step back397 root = state.copy398 }399400 const needPatches = !!rootPath && !!scope.patches401 const finalizeProperty = (prop, value, parent) => {402 if (value === parent) {403 throw Error("Immer forbids circular references")404 }405406 // In the `finalizeTree` method, only the `root` object may be a draft.407 const isDraftProp = !!state && parent === root408 const isSetMember = isSet(parent)409410 if (isDraft(value)) {411 const path =412 isDraftProp &&413 needPatches &&414 !isSetMember && // Set objects are atomic since they have no keys.415 !has(state.assigned, prop) // Skip deep patches for assigned keys.416 ? rootPath!.concat(prop)417 : null418419 // Drafts owned by `scope` are finalized here.420 value = this.finalize(value, path, scope)421 replace(parent, prop, value)422423 // Drafts from another scope must prevent auto-freezing.424 if (isDraft(value)) {425 scope.canAutoFreeze = false426 }427428 // Unchanged drafts are never passed to the `onAssign` hook.🎵...killing me softly, with your fingers... 🎶Michel Weststratebefore adoption19a6b66
line 429why, one step back429 // if (isDraftProp && !isSet && value === get(state.base, prop)) returnMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 430–473why, one step back430 }431 // Unchanged draft properties are ignored.432 else if (isDraftProp && is(value, get(state.base, prop))) {433 return434 }435 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.436 else if (isDraftable(value) && !Object.isFrozen(value)) {437 each(value, finalizeProperty)438 this.maybeFreeze(value)439 }440441 if (isDraftProp && this.onAssign && !isSetMember) {442 this.onAssign(state, prop, value)443 }444 }445446 each(root, finalizeProperty)447 return root448 }449 maybeFreeze(value, deep = false) {450 if (this.autoFreeze && !isDraft(value)) {451 freeze(value, deep)452 }453 }454}455456function replace(parent, prop, value) {457 if (isMap(parent)) {458 parent.set(prop, value)459 } else if (isSet(parent)) {460 // In this case, the `prop` is actually a draft.461 parent.delete(prop)462 parent.add(value)463 } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {464 // Preserve non-enumerable properties.465 parent[prop] = value466 } else {467 Object.defineProperty(parent, prop, {468 value,469 writable: true,470 configurable: true471 })472 }473}