Skip to content
Myr

finalize.ts

This file

Path

src/finalize.ts

193 lines · 5.2 KiB · TypeScript

Last changed by

fix: #502Michel Weststratebefore adoption8d4f723

History of this file

Take it

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

lines 1–3why, one step back
1import {Immer} from "./immer"
2import {ImmerState, Drafted, ProxyType} from "./types"3import {ImmerScope} from "./scope"

fix: #502Michel Weststratebefore adoption8d4f723

line 4why, one step back
4import {isSet, has, is, get, each, freeze, shallowCopy, set} from "./common"

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

lines 5–7why, one step back
5import {isDraft, isDraftable} from "./index"
6import {SetState} from "./set"7import {generatePatches, PatchPath} from "./patches"

fix: #502Michel Weststratebefore adoption8d4f723

line 8why, one step back
8import {DRAFT_STATE, NOTHING} from "./env"

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

lines 9–193why, one step back
9
10export function processResult(immer: Immer, result: any, scope: ImmerScope) {11 const baseDraft = scope.drafts![0]12 const isReplaced = result !== undefined && result !== baseDraft13 immer.willFinalize(scope, result, isReplaced)14 if (isReplaced) {15 if (baseDraft[DRAFT_STATE].modified) {16 scope.revoke()17 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore18 }19 if (isDraftable(result)) {20 // Finalize the result in case it contains (or is) a subset of the draft.21 result = finalize(immer, result, scope)22 maybeFreeze(immer, result)23 }24 if (scope.patches) {25 scope.patches.push({26 op: "replace",27 path: [],28 value: result29 })30 scope.inversePatches!.push({31 op: "replace",32 path: [],33 value: baseDraft[DRAFT_STATE].base34 })35 }36 } else {37 // Finalize the base draft.38 result = finalize(immer, baseDraft, scope, [])39 }40 scope.revoke()41 if (scope.patches) {42 scope.patchListener!(scope.patches, scope.inversePatches!)43 }44 return result !== NOTHING ? result : undefined45}4647function finalize(48 immer: Immer,49 draft: Drafted,50 scope: ImmerScope,51 path?: PatchPath52) {53 const state = draft[DRAFT_STATE]54 if (!state) {55 if (Object.isFrozen(draft)) return draft56 return finalizeTree(immer, draft, scope)57 }58 // Never finalize drafts owned by another scope.59 if (state.scope !== scope) {60 return draft61 }62 if (!state.modified) {63 maybeFreeze(immer, state.base, true)64 return state.base65 }66 if (!state.finalized) {67 state.finalized = true68 finalizeTree(immer, state.draft, scope, path)6970 // We cannot really delete anything inside of a Set. We can only replace the whole Set.71 if (immer.onDelete && state.type !== ProxyType.Set) {72 // The `assigned` object is unreliable with ES5 drafts.73 if (immer.useProxies) {74 const {assigned} = state75 each(assigned, (prop, exists) => {76 if (!exists) immer.onDelete!(state, prop as any)77 })78 } else {79 const {base, copy} = state80 each(base, prop => {81 if (!has(copy, prop)) immer.onDelete!(state, prop as any)82 })83 }84 }85 if (immer.onCopy) {86 immer.onCopy(state)87 }8889 // At this point, all descendants of `state.copy` have been finalized,90 // so we can be sure that `scope.canAutoFreeze` is accurate.91 if (immer.autoFreeze && scope.canAutoFreeze) {92 freeze(state.copy, false)93 }9495 if (path && scope.patches) {96 generatePatches(state, path, scope.patches, scope.inversePatches!)97 }98 }99 return state.copy100}101102function finalizeTree(103 immer: Immer,104 root: Drafted,105 scope: ImmerScope,106 rootPath?: PatchPath107) {108 const state = root[DRAFT_STATE]109 if (state) {110 if (111 state.type === ProxyType.ES5Object ||112 state.type === ProxyType.ES5Array113 ) {114 // Create the final copy, with added keys and without deleted keys.115 state.copy = shallowCopy(state.draft, true)116 }117 root = state.copy118 }119 each(root, (key, value) =>120 finalizeProperty(immer, scope, root, state, root, key, value, rootPath)121 )122 return root123}124125function finalizeProperty(126 immer: Immer,127 scope: ImmerScope,128 root: Drafted,129 rootState: ImmerState,130 parentValue: Drafted,131 prop: string | number,132 childValue: any,133 rootPath?: PatchPath134) {135 if (childValue === parentValue) {136 throw Error("Immer forbids circular references")137 }138139 // In the `finalizeTree` method, only the `root` object may be a draft.140 const isDraftProp = !!rootState && parentValue === root141 const isSetMember = isSet(parentValue)142143 if (isDraft(childValue)) {144 const path =145 rootPath &&146 isDraftProp &&147 !isSetMember && // Set objects are atomic since they have no keys.148 !has((rootState as Exclude<ImmerState, SetState>).assigned!, prop) // Skip deep patches for assigned keys.149 ? rootPath!.concat(prop)150 : undefined151152 // Drafts owned by `scope` are finalized here.153 childValue = finalize(immer, childValue, scope, path)154 set(parentValue, prop, childValue)155156 // Drafts from another scope must prevent auto-freezing.157 if (isDraft(childValue)) {158 scope.canAutoFreeze = false159 }160 }161 // Unchanged draft properties are ignored.162 else if (isDraftProp && is(childValue, get(rootState.base, prop))) {163 return164 }165 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.166 // TODO: the recursion over here looks weird, shouldn't non-draft stuff have it's own recursion?167 // especially the passing on of root and rootState doesn't make sense...168 else if (isDraftable(childValue) && !Object.isFrozen(childValue)) {169 each(childValue, (key, grandChild) =>170 finalizeProperty(171 immer,172 scope,173 root,174 rootState,175 childValue,176 key,177 grandChild,178 rootPath179 )180 )181 maybeFreeze(immer, childValue)182 }183184 if (isDraftProp && immer.onAssign && !isSetMember) {185 immer.onAssign(rootState, prop, childValue)186 }187}188189export function maybeFreeze(immer: Immer, value: any, deep = false) {190 if (immer.autoFreeze && !isDraft(value)) {191 freeze(value, deep)192 }193}