Skip to content
Myr

finalize.ts

This file

Path

src/finalize.ts

243 lines · 5.9 KiB · TypeScript

Last changed by

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

History of this file

Take it

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

lines 1–243why, one step back
1import {Immer} from "./immer"
2import {ImmerState, Drafted} from "./types"3import {ImmerScope} from "./scope"4import {5 isSet,6 has,7 is,8 get,9 each,10 isMap,11 isEnumerable,12 DRAFT_STATE,13 NOTHING,14 freeze,15 shallowCopy16} from "./common"17import {isDraft, isDraftable} from "./index"18import {SetState} from "./set"19import {generatePatches} from "./patches"2021type PatchPath = Array<string | number> | null2223export function processResult(immer: Immer, result: any, scope: ImmerScope) {24 const baseDraft = scope.drafts![0]25 const isReplaced = result !== undefined && result !== baseDraft26 immer.willFinalize(scope, result, isReplaced)27 if (isReplaced) {28 if (baseDraft[DRAFT_STATE].modified) {29 scope.revoke()30 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore31 }32 if (isDraftable(result)) {33 // Finalize the result in case it contains (or is) a subset of the draft.34 result = finalize(immer, result, null, scope)35 maybeFreeze(immer, result)36 }37 if (scope.patches) {38 scope.patches.push({39 op: "replace",40 path: [],41 value: result42 })43 scope.inversePatches!.push({44 op: "replace",45 path: [],46 value: baseDraft[DRAFT_STATE].base47 })48 }49 } else {50 // Finalize the base draft.51 result = finalize(immer, baseDraft, [], scope)52 }53 scope.revoke()54 if (scope.patches) {55 scope.patchListener!(scope.patches, scope.inversePatches!)56 }57 return result !== NOTHING ? result : undefined58}5960function finalize(61 immer: Immer,62 draft: Drafted,63 path: PatchPath,64 scope: ImmerScope65) {66 const state = draft[DRAFT_STATE]67 if (!state) {68 if (Object.isFrozen(draft)) return draft69 return finalizeTree(immer, draft, null, scope)70 }71 // Never finalize drafts owned by another scope.72 if (state.scope !== scope) {73 return draft74 }75 if (!state.modified) {76 maybeFreeze(immer, state.base, true)77 return state.base78 }79 if (!state.finalized) {80 state.finalized = true81 finalizeTree(immer, state.draft, path, scope)8283 // We cannot really delete anything inside of a Set. We can only replace the whole Set.84 if (immer.onDelete && !isSet(state.base)) {85 // The `assigned` object is unreliable with ES5 drafts.86 if (immer.useProxies) {87 const {assigned} = state88 each(assigned, (prop, exists) => {89 if (!exists) immer.onDelete?.(state, prop as any)90 })91 } else {92 // TODO: Figure it out for Maps and Sets if we need to support ES593 const {base, copy} = state94 each(base, prop => {95 if (!has(copy, prop)) immer.onDelete?.(state, prop as any)96 })97 }98 }99 if (immer.onCopy) {100 immer.onCopy(state)101 }102103 // At this point, all descendants of `state.copy` have been finalized,104 // so we can be sure that `scope.canAutoFreeze` is accurate.105 if (immer.autoFreeze && scope.canAutoFreeze) {106 freeze(state.copy, false)107 }108109 if (path && scope.patches) {110 generatePatches(state, path, scope.patches, scope.inversePatches!)111 }112 }113 return state.copy114}115116function finalizeTree(117 immer: Immer,118 root: Drafted,119 rootPath: PatchPath,120 scope: ImmerScope121) {122 const state = root[DRAFT_STATE]123 if (state) {124 // TODO: kill isMap / isSet here125 if (!immer.useProxies && !isMap(root) && !isSet(root)) {126 // Create the final copy, with added keys and without deleted keys.127 state.copy = shallowCopy(state.draft, true) // TODO: optimization, can we get rid of this and just use state.copy?128 }129130 root = state.copy131 }132133 const needPatches = !!rootPath && !!scope.patches134135 each(root, (key, value) =>136 finalizeProperty(137 immer,138 root,139 state,140 key,141 value,142 root,143 needPatches,144 scope,145 rootPath146 )147 )148 return root149}150151function finalizeProperty(152 // TODO: can do with less args?153 immer: Immer,154 root: ImmerState,155 state: ImmerState,156 prop: string | number,157 value: any,158 parent: ImmerState,159 needPatches: boolean,160 scope: ImmerScope,161 rootPath: PatchPath162) {163 if (value === parent) {164 throw Error("Immer forbids circular references")165 }166167 // In the `finalizeTree` method, only the `root` object may be a draft.168 const isDraftProp = !!state && parent === root169 const isSetMember = isSet(parent)170171 if (isDraft(value)) {172 const path =173 isDraftProp &&174 needPatches &&175 !isSetMember && // Set objects are atomic since they have no keys.176 !has((state as Exclude<ImmerState, SetState>).assigned!, prop) // Skip deep patches for assigned keys.177 ? rootPath!.concat(prop)178 : null179180 // Drafts owned by `scope` are finalized here.181 value = finalize(immer, value, path, scope)182 replace(parent, prop, value)183184 // Drafts from another scope must prevent auto-freezing.185 if (isDraft(value)) {186 scope.canAutoFreeze = false187 }188189 // Unchanged drafts are never passed to the `onAssign` hook.190 // if (isDraftProp && !isSet && value === get(state.base, prop)) return191 }192 // Unchanged draft properties are ignored.193 else if (isDraftProp && is(value, get(state.base, prop))) {194 return195 }196 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.197 else if (isDraftable(value) && !Object.isFrozen(value)) {198 each(value, (key, v) =>199 finalizeProperty(200 immer,201 root,202 state,203 key,204 v,205 value,206 needPatches,207 scope,208 rootPath209 )210 )211 maybeFreeze(immer, value)212 }213214 if (isDraftProp && immer.onAssign && !isSetMember) {215 immer.onAssign(state, prop, value)216 }217}218219function replace(parent: Drafted, prop: PropertyKey, value: any) {220 // TODO: kill isMap clal here221 if (isMap(parent)) {222 parent.set(prop, value)223 } else if (isSet(parent)) {224 // In this case, the `prop` is actually a draft.225 parent.delete(prop)226 parent.add(value)227 } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {228 // Preserve non-enumerable properties.229 parent[prop] = value230 } else {231 Object.defineProperty(parent, prop, {232 value,233 writable: true,234 configurable: true235 })236 }237}238239export function maybeFreeze(immer: Immer, value: any, deep = false) {240 if (immer.autoFreeze && !isDraft(value)) {241 freeze(value, deep)242 }243}